From bce9fae8c263cf0ccb597a6c5a5bc66e86efb66a Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 28 Oct 2026 08:42:06 +0000 Subject: [PATCH 1/8] Fix typo --- Source.SoundEmitterSystem/SoundEmitterSystemBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source.SoundEmitterSystem/SoundEmitterSystemBase.cs b/Source.SoundEmitterSystem/SoundEmitterSystemBase.cs index 7608d4e8..830dd130 100644 --- a/Source.SoundEmitterSystem/SoundEmitterSystemBase.cs +++ b/Source.SoundEmitterSystem/SoundEmitterSystemBase.cs @@ -263,7 +263,7 @@ public int FindSoundScript(ReadOnlySpan name) { int i, c; FileNameHandle_t hFilename = filesystem.FindFileName(name); - if (hFilename == 0) { + if (hFilename != 0) { // First, make sure it's known c = SoundKeyValues.Count; for (i = 0; i < c; i++) From 98d3e7872620c4a244a75b5ee7660bfb33767e06 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 28 Oct 2026 10:41:11 +0000 Subject: [PATCH 2/8] Fixes --- Source.Common/Optimize.cs | 2 +- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 13 +++++++------ Source.ShaderAPI.Gl46/ShaderSystem.cs | 4 ++-- Source.VTF/VTFTexture.cs | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/Source.Common/Optimize.cs b/Source.Common/Optimize.cs index d1b20a5b..aed069e4 100644 --- a/Source.Common/Optimize.cs +++ b/Source.Common/Optimize.cs @@ -13,7 +13,7 @@ public static class OptimizedModel { public class MaterialReplacementHeader { - public const int SIZEOF = sizeof(short) + 2 + sizeof(int); + public const int SIZEOF = sizeof(short) + sizeof(int); Memory Data; int ThisOffset; diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index 75c9ea8b..b34406c2 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -2576,12 +2576,13 @@ public unsafe void TexSubImage2D(int mip, int face, int x, int y, int z, int wid glTextureSubImage2D(GetModifyTexture(), mip, x, y, Math.Max(width >> mip, 1), Math.Max(height >> mip, 1), ImageLoader.GetGLImageUploadFormat(srcFormat), ImageLoader.GetGLImageUploadType(srcFormat), data); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); var err = glGetError(); - // System.Diagnostics.Debug.Assert(err == 0); + // Assert(err == 0); if (err != 0) { InternalTextureInfo tex = GetTexture(ModifyTextureHandle); int levels = 0; glGetTextureParameteriv(GetModifyTexture(), GL_TEXTURE_IMMUTABLE_LEVELS, &levels); Warning($"glTextureSubImage2D error: {err} ('{tex.DebugName.String()}' {tex.Width}x{tex.Height} {tex.Format} levels {levels}, mip {mip} rect {x},{y} {width >> mip}x{height >> mip}, src {srcFormat} stride {srcStride})\n"); + // Console.WriteLine(Environment.StackTrace); } } @@ -3940,7 +3941,7 @@ public void PopDeformation() { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } - public void PushDeformation(in DeformationBase deformation ) { + public void PushDeformation(in DeformationBase deformation) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } @@ -3956,11 +3957,11 @@ public void ScaleXY(float x, float y) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } - public void SetBooleanPixelShaderConstant(int var, ReadOnlySpan vec, bool force = false ) { + public void SetBooleanPixelShaderConstant(int var, ReadOnlySpan vec, bool force = false) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } - public void SetBooleanVertexShaderConstant(int var, ReadOnlySpan vec, bool force = false ) { + public void SetBooleanVertexShaderConstant(int var, ReadOnlySpan vec, bool force = false) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } @@ -3982,11 +3983,11 @@ public void SetIntRenderingParameter(int parmNumber, int value) { IntRenderingParameters[parmNumber] = value; } - public void SetIntegerPixelShaderConstant(int var, ReadOnlySpan vec, bool force = false ) { + public void SetIntegerPixelShaderConstant(int var, ReadOnlySpan vec, bool force = false) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } - public void SetIntegerVertexShaderConstant(int var, ReadOnlySpan vec, bool force = false ) { + public void SetIntegerVertexShaderConstant(int var, ReadOnlySpan vec, bool force = false) { throw new NotImplementedException("Incomplete port of IShaderDynamicAPI"); } diff --git a/Source.ShaderAPI.Gl46/ShaderSystem.cs b/Source.ShaderAPI.Gl46/ShaderSystem.cs index ab1caa22..66c1ae25 100644 --- a/Source.ShaderAPI.Gl46/ShaderSystem.cs +++ b/Source.ShaderAPI.Gl46/ShaderSystem.cs @@ -576,7 +576,7 @@ private void ProcessSource(StringBuilder sb, ReadOnlySpan source, int file } private unsafe bool LoadCachedProgram(ShaderCompileJob job) { - using IFileHandle? handle = FileSystem.Open(job.CachePath, FileOpenOptions.Read | FileOpenOptions.Binary, "DEFAULT_WRITE_PATH"); + using IFileHandle? handle = FileSystem.Open(job.CachePath, FileOpenOptions.Read | FileOpenOptions.Binary, "MOD"); if (handle == null || handle.Stream.Length <= sizeof(int)) return false; @@ -718,7 +718,7 @@ private static void ApplyCompileJob(ShaderCompileJob job) { if (combos.IsEmpty) Msg($"Compiled shader: {shader.Name} ({shader.TypeName})\n"); else - Msg($"Compiled shader: {shader.Name} ({shader.TypeName}) [{combos}]\n"); + Msg($"Compiled shader: {shader.Name} ({shader.TypeName}) [{string.Join(';', combos.ToString().Split(';').Where(x => !x.EndsWith(" 0")))}]\n"); } } diff --git a/Source.VTF/VTFTexture.cs b/Source.VTF/VTFTexture.cs index c83b238e..3aa80abd 100644 --- a/Source.VTF/VTFTexture.cs +++ b/Source.VTF/VTFTexture.cs @@ -368,7 +368,7 @@ public bool Init(int width, int height, int depth, ImageFormat format, int flags } } - if (!IsMultipleOf4(width) || !IsMultipleOf4(height) || !IsMultipleOf4(depth)) { + if ((flags & (int)TextureFlags.Procedural) == 0 && (!IsMultipleOf4(width) || !IsMultipleOf4(height) || !IsMultipleOf4(depth))) { Warning("Image dimensions must be multiple of 4!\n"); return false; } From 9cc5443913ca2abd235037c61e01ad6fb5af6a39 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 28 Oct 2026 10:41:28 +0000 Subject: [PATCH 3/8] AvatarImage --- Game.Client/GarrysMod/AvatarImage.cs | 148 +++++++++++++++++++++++++++ Game.Client/GarrysMod/LuaGui.cs | 8 +- Game.Client/GarrysMod/LuaPanel.cs | 46 +++++++++ Game.Client/GarrysMod/LuaVGUI.cs | 2 +- 4 files changed, 199 insertions(+), 5 deletions(-) create mode 100644 Game.Client/GarrysMod/AvatarImage.cs diff --git a/Game.Client/GarrysMod/AvatarImage.cs b/Game.Client/GarrysMod/AvatarImage.cs new file mode 100644 index 00000000..d0c6efd3 --- /dev/null +++ b/Game.Client/GarrysMod/AvatarImage.cs @@ -0,0 +1,148 @@ +using Source; +using Source.Common.GUI; +using Source.GUI.Controls; + +using Steamworks; + +namespace Game.Client.GarrysMod; + +public class AvatarImage : Panel +{ + static readonly List[] FreeTextures = [[], [], []]; + + TextureID TextureID; + ulong SteamID; + int Size; + readonly IImage? DefaultImage; + + readonly Callback AvatarImageLoaded; + readonly Callback PersonaStateChange; + + public AvatarImage(Panel? parent, ReadOnlySpan name) : base(parent, name) { + SteamID = 0; + Size = 0; + AvatarImageLoaded = Callback.Create(OnAvatarImageLoaded); + PersonaStateChange = Callback.Create(OnPersonaStateChange); + TextureID = TextureID.INVALID; + DefaultImage = SchemeManager.GetImage("avatar_default", true); + } + + public override void Dispose() { + ClearTexture(); + PersonaStateChange.Dispose(); + AvatarImageLoaded.Dispose(); + base.Dispose(); + } + + void OnAvatarImageLoaded(AvatarImageLoaded_t info) { + if (info.m_steamID.m_SteamID == SteamID) + LoadAvatar(); + } + + void OnPersonaStateChange(PersonaStateChange_t info) { + if (info.m_ulSteamID == SteamID && (info.m_nChangeFlags & EPersonaChange.k_EPersonaChangeAvatar) != 0) + LoadAvatar(); + } + + void ClearTexture() { + SteamID = 0; + if (TextureID == TextureID.INVALID) { + TextureID = TextureID.INVALID; + return; + } + + FreeTextures[Size].Add(TextureID); + TextureID = TextureID.INVALID; + } + + void LoadAvatar() { + CSteamID steamID = new(SteamID); + if (SteamFriends.RequestUserInformation(steamID, false)) + return; + + int avatar; + if (Size == 0) + avatar = SteamFriends.GetSmallFriendAvatar(steamID); + else if (Size == 1) + avatar = SteamFriends.GetMediumFriendAvatar(steamID); + else if (Size == 2) + avatar = SteamFriends.GetLargeFriendAvatar(steamID); + else + return; + + if ((uint)(avatar + 1) <= 1) + return; + + if (!SteamUtils.GetImageSize(avatar, out uint wide, out uint tall)) + return; + + int size = (int)(wide * tall * 4); + byte[] rgba = new byte[size]; + if (!SteamUtils.GetImageRGBA(avatar, rgba, size)) + return; + + if (TextureID == TextureID.INVALID) { + List free = FreeTextures[Size]; + if (free.Count < 1) + TextureID = Surface.CreateNewTextureID(true); + else { + TextureID = free[^1]; + free.RemoveAt(free.Count - 1); + } + } + + Surface.DrawSetTextureRGBA(TextureID, rgba, (int)wide, (int)tall, 0, true); + } + + public void SetSteamID(ulong steamID, int size) { + if (size < 0) + size = 0; + else if (2 < size) + size = 2; + + if (SteamID != steamID || size != Size) { + if (size != Size) + ClearTexture(); + SteamID = steamID; + Size = size; + LoadAvatar(); + } + } + + public void SetPlayer(C_BasePlayer? player, int size) { + if (player == null || !player.GetSteamID(out CSteamID id)) { + ClearTexture(); + return; + } + + ulong steamID = id.m_SteamID; + int clamped = 0; + if (-1 < size) { + clamped = size; + if (2 < size) + clamped = 2; + } + + if (SteamID == steamID && clamped == Size) + return; + + if (clamped != Size) + ClearTexture(); + + SteamID = steamID; + Size = clamped; + LoadAvatar(); + } + + public override void Paint() { + if (TextureID == TextureID.INVALID) { + DefaultImage!.SetSize(GetWide(), GetTall()); + DefaultImage.Paint(); + return; + } + + Surface.DrawSetTexture(TextureID); + Surface.DrawSetColor(new Color(255, 255, 255, 255)); + Surface.DrawTexturedRect(0, 0, GetWide(), GetTall()); + } +} diff --git a/Game.Client/GarrysMod/LuaGui.cs b/Game.Client/GarrysMod/LuaGui.cs index 8122b800..a76c3697 100644 --- a/Game.Client/GarrysMod/LuaGui.cs +++ b/Game.Client/GarrysMod/LuaGui.cs @@ -20,16 +20,16 @@ public static partial class LuaGui [LuaFunction] static int EnableScreenClicker(ILuaInterface lua) { if (!g_Lua!.GetBool(1)) { - GModBase.GetMouseInput()!.SetKeyboardInputEnabled(false); + GModBase.GetMouseInput()!.SetMouseInputEnabled(false); GModBase.GetMouseInput()!.SetVisible(false); return 0; } - GModBase.GetGModBasePanel(true)!.SetKeyboardInputEnabled(true); + GModBase.GetGModBasePanel(true)!.SetMouseInputEnabled(true); GModBase.GetMouseInput()!.SetVisible(true); GModBase.GetMouseInput()!.MakePopup(true, false); - GModBase.GetMouseInput()!.SetKeyboardInputEnabled(true); - GModBase.GetMouseInput()!.SetMouseInputEnabled(false); + GModBase.GetMouseInput()!.SetMouseInputEnabled(true); + GModBase.GetMouseInput()!.SetKeyboardInputEnabled(false); return 0; } #endif diff --git a/Game.Client/GarrysMod/LuaPanel.cs b/Game.Client/GarrysMod/LuaPanel.cs index b575272e..881d4bad 100644 --- a/Game.Client/GarrysMod/LuaPanel.cs +++ b/Game.Client/GarrysMod/LuaPanel.cs @@ -81,6 +81,52 @@ static int Panel____index(ILuaInterface lua) { return 0; } +#if !MENU_DLL + [LuaMethod] + static int Panel__SetSteamID(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is AvatarImage avatar) { + _ = ulong.TryParse(lua.CheckString(2), out ulong steamID); + int size = 0; + if (lua.GetType(3) == LuaType.Number) { + int value = (int)lua.GetNumber(3); + size = 32 < value ? 1 : 0; + if (64 < value) + size = 2; + } + avatar.SetSteamID(steamID, size); + } + return 0; + } + + [LuaMethod] + static int Panel__SetPlayer(ILuaInterface lua) { + Panel? panel = Get_Panel(1); + if (panel == null) { + lua.Error("Tried to use a NULL Panel!"); + return 0; + } + + if (panel is not AvatarImage avatar) + return 0; + + int size = 0; + if (lua.GetType(3) == LuaType.Number) { + int value = (int)lua.GetNumber(3); + size = 32 < value ? 1 : 0; + if (64 < value) + size = 2; + } + avatar.SetPlayer(LuaPlayer.Get_Player(2, true), size); + return 0; + } +#endif + [LuaMethod] static int Panel__PaintManual(ILuaInterface lua) { Panel? panel = Get_Panel(1); diff --git a/Game.Client/GarrysMod/LuaVGUI.cs b/Game.Client/GarrysMod/LuaVGUI.cs index 2998d15b..0b581e35 100644 --- a/Game.Client/GarrysMod/LuaVGUI.cs +++ b/Game.Client/GarrysMod/LuaVGUI.cs @@ -196,7 +196,7 @@ public static bool IsValidPanel(Panel? panel) { return new SpawnIcon(null, "ModelImage"); if (stricmp(className, "AvatarImage") == 0) - return null; // AvatarImage + return new AvatarImage(null, "AvatarImage"); #endif if (stricmp(className, "HTML") == 0) From c1e9b1e8860d4a1e423ae4f8dfb328c9a17fa268 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 28 Oct 2026 10:44:30 +0000 Subject: [PATCH 4/8] More lua impl --- Game.Client/C_BaseEntity.cs | 1 + Game.Client/C_BasePlayer.cs | 8 +- Game.Client/C_PlayerResource.cs | 26 ++++ Game.Client/HL2/ClientModeHL2MPNormal.cs | 25 ++++ Game.Client/InMain.cs | 22 ++- Game.Lua/LuaInterfaceImpl.cs | 17 ++- Game.Server/GarrysMod/GMOD_Player.cs | 16 ++ Game.Server/Util.cs | 41 +++++ Game.Shared/GarrysMod/GarrysMod.cs | 2 +- Game.Shared/GarrysMod/LuaAngle.cs | 10 ++ Game.Shared/GarrysMod/LuaConVar.cs | 12 ++ Game.Shared/GarrysMod/LuaEntity.cs | 182 +++++++++++++++++++++++ Game.Shared/GarrysMod/LuaGame.cs | 7 +- Game.Shared/GarrysMod/LuaGameEvent.cs | 82 ++++++++++ Game.Shared/GarrysMod/LuaGameSystem.cs | 33 +++- Game.Shared/GarrysMod/LuaPlayer.cs | 168 +++++++++++++++++++++ Game.Shared/GarrysMod/LuaUtil.cs | 72 +++++++++ Game.Shared/GarrysMod/LuaVector.cs | 10 ++ Game.Shared/GarrysMod/LuaVideo.cs | 21 +++ Game.Shared/GarrysMod/LuaWeapon.cs | 8 + Source.Common/IGameEvents.cs | 6 + Source.DataCache/MDLCache.cs | 97 +++++++++++- Source.Engine/CdllEngineInterface.cs | 4 +- Source.Engine/Client/BaseClientState.cs | 21 +++ Source.Engine/Client/ClientState.cs | 5 +- Source.GUI.Controls/Button.cs | 2 + Source.GUI.Controls/RichText.cs | 2 + 27 files changed, 881 insertions(+), 19 deletions(-) create mode 100644 Game.Shared/GarrysMod/LuaGameEvent.cs create mode 100644 Game.Shared/GarrysMod/LuaVideo.cs diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index bc7b574f..74fc6047 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -876,6 +876,7 @@ public C_BaseEntity() { public int Health; [NetworkVar("m_iMaxHealth")] public int MaxHealth; + public virtual int GetMaxHealth() => MaxHealth; [NetworkVar("m_spawnflags")] public int SpawnFlags; [NetworkVar("m_iGModFlags")] diff --git a/Game.Client/C_BasePlayer.cs b/Game.Client/C_BasePlayer.cs index 12093654..814b7e05 100644 --- a/Game.Client/C_BasePlayer.cs +++ b/Game.Client/C_BasePlayer.cs @@ -106,6 +106,11 @@ public bool GetSteamID(out CSteamID id) { } return false; } + public int GetUserID() { + if (!engine.GetPlayerInfo(EntIndex(), out PlayerInfo pi)) + return -1; + return pi.UserID; + } PlayerInfo NetworkIDInfo; InlineArray33 NetworkIDString; public ReadOnlySpan GetNetworkIDString() { @@ -123,7 +128,7 @@ public ReadOnlySpan GetNetworkIDString() { return "NULL"; } public bool IsHLTV() => IsLocalPlayer() && engine.IsHLTV(); - public bool IsBot() => false; // TODO, gmod + public bool IsBot() => (GetFlags() & EntityFlags.FakeClient) != 0; public static bool ShouldDrawLocalPlayer() { return input.CAM_IsThirdPerson(); // todo } @@ -621,6 +626,7 @@ public void SetLocalViewAngles(in QAngle angles) { EHANDLE TonemapController = new(); [NetworkVar("m_hViewEntity")] EHANDLE ViewEntity = new(); + public virtual C_BaseEntity? GetViewEntity() => ViewEntity.Get(); [NetworkVar("m_hViewModel")] InlineArrayNewMaxViewmodels> ViewModel = new(); [NetworkVar("m_bDisableWorldClicking")] diff --git a/Game.Client/C_PlayerResource.cs b/Game.Client/C_PlayerResource.cs index 90ed8fc0..d6648f4a 100644 --- a/Game.Client/C_PlayerResource.cs +++ b/Game.Client/C_PlayerResource.cs @@ -71,6 +71,32 @@ public bool IsConnected(int index) { return Connected[index]; } + public int GetPlayerScore(int index) { + if (!IsConnected(index)) + return 0; + return Score[index]; + } + + public int GetPing(int index) { + if (!IsConnected(index)) + return 0; + return Ping[index]; + } + + public int GetDeaths(int index) { + if (!IsConnected(index)) + return 0; + return Deaths[index]; + } + + public int GetFrags(int index) => GetPlayerScore(index); + + public int GetArmor(int index) { + if (!IsConnected(index)) + return 0; + return Armor[index]; + } + public ReadOnlySpan GetPlayerName(int index) { if (index < 1 || index > Constants.MAX_PLAYERS) { Assert(false); diff --git a/Game.Client/HL2/ClientModeHL2MPNormal.cs b/Game.Client/HL2/ClientModeHL2MPNormal.cs index f362b104..c8a3c75b 100644 --- a/Game.Client/HL2/ClientModeHL2MPNormal.cs +++ b/Game.Client/HL2/ClientModeHL2MPNormal.cs @@ -1,10 +1,12 @@ global using static Game.Client.HL2.ClientModeHL2MPNormal; +using Game.Client.GarrysMod; using Game.Client.HUD; using Source.Common; using Source.Common.Commands; using Source.Common.GUI; +using Source.Common.Input; using Source.Engine; namespace Game.Client.HL2; @@ -29,4 +31,27 @@ public ClientModeHL2MPNormal() { Viewport = new HudViewport(); Viewport.Start(); } + +#if GMOD_DLL + public override int KeyInput(int down, ButtonCode keynum, ReadOnlySpan currentBinding) { + // todo + + if (engine.Con_IsVisible()) + return 1; + + if (currentBinding.IsEmpty || strcmp(currentBinding, "toggleconsole") != 0) { + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + if (player != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerBindPress)) { + LuaEntity.Push_Entity(player); + g_Lua!.PushString(currentBinding); + g_Lua.PushBool(down != 0); + g_Lua.PushNumber((int)keynum); + if (gGM.CallFinish(4)) + return 0; + } + } + + return base.KeyInput(down, keynum, currentBinding); + } +#endif } diff --git a/Game.Client/InMain.cs b/Game.Client/InMain.cs index c67db0b8..acb87932 100644 --- a/Game.Client/InMain.cs +++ b/Game.Client/InMain.cs @@ -190,7 +190,16 @@ void noclip() { [ConCommand(name: "+reload")] void IN_ReloadDown(in TokenizedCommand args) => KeyDown(ref in_reload, args[1]); [ConCommand(name: "+alt1")] void IN_Alt1Down(in TokenizedCommand args) => KeyDown(ref in_alt1, args[1]); [ConCommand(name: "+alt2")] void IN_Alt2Down(in TokenizedCommand args) => KeyDown(ref in_alt2, args[1]); - [ConCommand(name: "+score")] void IN_ScoreDown(in TokenizedCommand args) => KeyDown(ref in_score, args[1]); + [ConCommand(name: "+score")] + void IN_ScoreDown(in TokenizedCommand args) { + KeyDown(ref in_score, args[1]); +#if GMOD_DLL + gGM?.Call((int)LUA_POOLEDSTRING.ScoreboardShow); +#endif + } +#if GMOD_DLL + [ConCommand(name: "+showscores")] void IN_ShowScoresDown(in TokenizedCommand args) => IN_ScoreDown(in args); +#endif [ConCommand(name: "+graph")] void IN_GraphDown(in TokenizedCommand args) => KeyDown(ref in_graph, args[1]); [ConCommand(name: "+break")] void IN_BreakDown(in TokenizedCommand args) => KeyDown(ref in_break, args[1]); [ConCommand(name: "+zoom")] void IN_ZoomDown(in TokenizedCommand args) => KeyDown(ref in_zoom, args[1]); @@ -221,7 +230,16 @@ void noclip() { [ConCommand(name: "-reload")] void IN_ReloadUp(in TokenizedCommand args) => KeyUp(ref in_reload, args[1]); [ConCommand(name: "-alt1")] void IN_Alt1Up(in TokenizedCommand args) => KeyUp(ref in_alt1, args[1]); [ConCommand(name: "-alt2")] void IN_Alt2Up(in TokenizedCommand args) => KeyUp(ref in_alt2, args[1]); - [ConCommand(name: "-score")] void IN_ScoreUp(in TokenizedCommand args) => KeyUp(ref in_score, args[1]); + [ConCommand(name: "-score")] + void IN_ScoreUp(in TokenizedCommand args) { + KeyUp(ref in_score, args[1]); +#if GMOD_DLL + gGM?.Call((int)LUA_POOLEDSTRING.ScoreboardHide); +#endif + } +#if GMOD_DLL + [ConCommand(name: "-showscores")] void IN_ShowScoresUp(in TokenizedCommand args) => IN_ScoreUp(in args); +#endif [ConCommand(name: "-graph")] void IN_GraphUp(in TokenizedCommand args) => KeyUp(ref in_graph, args[1]); [ConCommand(name: "-break")] void IN_BreakUp(in TokenizedCommand args) => KeyUp(ref in_break, args[1]); [ConCommand(name: "-zoom")] void IN_ZoomUp(in TokenizedCommand args) => KeyUp(ref in_zoom, args[1]); diff --git a/Game.Lua/LuaInterfaceImpl.cs b/Game.Lua/LuaInterfaceImpl.cs index 10217580..4ee7b79d 100644 --- a/Game.Lua/LuaInterfaceImpl.cs +++ b/Game.Lua/LuaInterfaceImpl.cs @@ -129,6 +129,12 @@ public bool Init(ILuaGameCallback callbacks, bool isServer) { luaL_openlibs(state); DoStackCheck(); + // todo build lua with LUAJIT_DISABLE_VMEVENT + GetField(LuaIndex.Global, "jit"); + PushCFunction(JitAttachDisabled); + SetField(-2, "attach"); + lua_settop(state, -2); + GetField(LuaIndex.Global, "string"); GetField(-1, "gmatch"); SetField(-2, "gfind"); @@ -195,6 +201,11 @@ static void ReadStackIntoError(nint L) { } } + static int JitAttachDisabled(ILuaInterface lua) { + lua.ThrowError("vmevent API disabled"); + return 0; + } + static int AdvancedLuaErrorReporter(ILuaInterface lua) { nint L = ((LuaInterfaceImpl)lua).state; if (lua_isstring(L, 1) != 0) { @@ -1144,9 +1155,9 @@ public bool RunStringEx(ReadOnlySpan filename, ReadOnlySpan path, Re int status; using (Utf8 name = new(chunkName.SliceNullTerminatedString(), stackalloc byte[MAX_PATH * 3])) - fixed (byte* buf = code) - fixed (byte* mode = "t\0"u8) - status = luaL_loadbufferx(state, buf, (nuint)code.Length, name.Pointer, mode); + fixed (byte* buf = code) + fixed (byte* mode = "t\0"u8) + status = luaL_loadbufferx(state, buf, (nuint)code.Length, name.Pointer, mode); if (status != OK) { if (printErrors) { diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index c31e2386..a5cbd47f 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -5,6 +5,7 @@ using Source; using Source.Common; +using Source.Common.Commands; using Source.Common.Engine; using Source.Common.GarrysMod.Lua; @@ -38,6 +39,21 @@ public GMOD_Player() { Hands = new(); } +#if GMOD_DLL + static void CallShowHook(LUA_POOLEDSTRING hook) { + BasePlayer? player = Util.GetCommandClient(); + if (player == null || !player.IsPlayer() || gGM == null || !gGM.CallWithArgs((int)hook)) + return; + LuaEntity.Push_Entity(player); + gGM.CallFinish(1); + } + + [ConCommand("gm_showhelp")] static void CC_ShowHelp() => CallShowHook(LUA_POOLEDSTRING.ShowHelp); + [ConCommand("gm_showteam")] static void CC_ShowTeam() => CallShowHook(LUA_POOLEDSTRING.ShowTeam); + [ConCommand("gm_showspare1")] static void CC_ShowSpare1() => CallShowHook(LUA_POOLEDSTRING.ShowSpare1); + [ConCommand("gm_showspare2")] static void CC_ShowSpare2() => CallShowHook(LUA_POOLEDSTRING.ShowSpare2); +#endif + public static GMOD_Player? CreatePlayer(ReadOnlySpan classname, Edict ed) { s_PlayerEdict = ed; return (GMOD_Player?)CreateEntityByName(classname); diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index b19b4def..a4d12f7d 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -11,6 +11,7 @@ using Source.Common.Engine; using Source.Common.Formats.BSP; using Source.Common.Mathematics; +using Source.Common.Networking; using Source.Common.Physics; using Source.Engine.Server; @@ -593,6 +594,46 @@ public static void ClientPrint(BasePlayer? player, HudPrint dest, ReadOnlySpan cmdRateStr = engine.GetClientConVarValue(playerIndex, "cl_cmdrate"); + + int cmdRate = Math.Max(1, atoi(cmdRateStr)); + latency -= (0.5f / cmdRate) + TICKS_TO_TIME(1); + + latency -= TICK_INTERVAL * 0.5f; + + ping = (int)(latency * 1000.0f); + ping = Math.Clamp(ping, 5, 1000); + + packetloss = (int)(100.0f * nci.GetAverageLoss(NetFlow.FLOW_INCOMING)); + packetloss = Math.Clamp(packetloss, 0, 100); + } + else { + ping = 0; + packetloss = 0; + } + } + + public static BasePlayer? PlayerByUserId(int userID) { + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BasePlayer? player = PlayerByIndex(i); + if (player == null || !player.IsConnected()) + continue; + + if (engine.GetPlayerUserId(player.Edict()) == userID) + return player; + } + + return null; + } + public static BaseEntity? EntityByIndex(int entityIndex) { BaseEntity? entity = null; diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 420b0584..6bb3e095 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -334,7 +334,7 @@ public bool RunScript(ReadOnlySpan file, ReadOnlySpan pathId, bool r return g_Lua.FindAndRunScript(file, run, true, source, true); } - public bool ScriptExists(ReadOnlySpan file, ReadOnlySpan pathId) => get.LuaShared()!.LoadFile(file, pathId, false, true) != null; + public bool ScriptExists(ReadOnlySpan file, ReadOnlySpan pathId) => get.LuaShared()!.LoadFile(file, pathId, true, true) != null; #if CLIENT_DLL public C_BaseEntity? CreateEntity(ReadOnlySpan className) => LuaSENTManager.gSENTManager!.CreateEntity(className); diff --git a/Game.Shared/GarrysMod/LuaAngle.cs b/Game.Shared/GarrysMod/LuaAngle.cs index a962fd7c..21a28980 100644 --- a/Game.Shared/GarrysMod/LuaAngle.cs +++ b/Game.Shared/GarrysMod/LuaAngle.cs @@ -1,4 +1,5 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL +using Source; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -56,6 +57,15 @@ static int Angle____newindex(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Angle____tostring(ILuaInterface lua) { + ref QAngle ang = ref Get_Angle(1); + Span str = stackalloc char[64]; + sprintf(str, "%.3f %.3f %.3f").F(ang.X).F(ang.Y).F(ang.Z); + g_Lua!.PushString(((ReadOnlySpan)str).SliceNullTerminatedString()); + return 1; + } + [LuaMethod] static int Angle____index(ILuaInterface lua) { if (g_Lua!.FindOnObjectsMetaTable(1, 2)) diff --git a/Game.Shared/GarrysMod/LuaConVar.cs b/Game.Shared/GarrysMod/LuaConVar.cs index 066fd8d4..5d30edc7 100644 --- a/Game.Shared/GarrysMod/LuaConVar.cs +++ b/Game.Shared/GarrysMod/LuaConVar.cs @@ -91,6 +91,18 @@ public static string ConVar__GetString(ConVar convar) { return convar.GetString(); } + [LuaMethod] + static int ConVar____tostring(ILuaInterface lua) { + if (LC_ConVar.Get(1) is not ConVar convar) { + lua.PushString("ConVar [NULL]"); + return 1; + } + + string str = $"ConVar [{convar.GetName()}]"; + lua.PushString(str.Length > 0x1FF ? str[..0x1FF] : str); + return 1; + } + [LuaMethod] static float ConVar__GetFloat(ConVar convar) => convar.GetFloat(); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index c477cdeb..46e29537 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -174,6 +174,24 @@ public static void Push_Entity(BaseEntity? ent) { NULL.UnReference(); } +#if GAME_DLL + public static BaseEntity? GMEntityByIndex(int index) { + if (index == 0) + return GetWorldEntity(); + return Util.EntityByIndex(index); + } +#endif + + [LuaGlobal] + static int Entity(ILuaInterface lua) { +#if CLIENT_DLL + Push_Entity(cl_entitylist.GetBaseEntity((int)lua.CheckNumber(1))); +#else + Push_Entity(GMEntityByIndex((int)lua.CheckNumber(1))); +#endif + return 1; + } + public static ILuaObject FindEntityMetaTable(BaseEntity? ent) { if (ent == null) return LC_Entity.MetaTable; @@ -238,6 +256,19 @@ public static int __index_Entity(ILuaInterface lua) { [LuaMethod] static int Entity____index(ILuaInterface lua) => EntityBaseIndex(); + [LuaMethod] + static int Entity____tostring(ILuaInterface lua) { + BaseEntity? ent = Get_Entity(1, true); + if (ent == null) { + lua.PushString("[NULL Entity]"); + return 1; + } + + string str = $"Entity [{ent.EntIndex()}][{ent.GetClassname()}]"; + lua.PushString(str.Length > 0xFF ? str[..0xFF] : str); + return 1; + } + [LuaMethod] static int Entity__IsValid(ILuaInterface lua) { BaseEntity? ent = Get_Entity(1, true); @@ -301,6 +332,110 @@ static int Entity__DeleteOnRemove(ILuaInterface lua) { } #endif + [LuaMethod] + static int Entity__Health(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber(ent.Health); + return 1; + } + + [LuaMethod] + static int Entity__GetMaxHealth(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber(ent.GetMaxHealth()); + return 1; + } + + [LuaMethod] + static int Entity__GetFlags(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber((int)ent.GetFlags()); + return 1; + } + + [LuaMethod] + static int Entity__IsDormant(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushBool(ent.IsDormant()); + return 1; + } + + [LuaMethod] + static int Entity__GetCollisionGroup(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber((int)ent.GetCollisionGroup()); + return 1; + } + + [LuaMethod] + static int Entity__GetNoDraw(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushBool(ent.IsEffectActive(EntityEffects.NoDraw)); + return 1; + } + + [LuaMethod] + static int Entity__WorldSpaceCenter(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + LuaVector.Push_Vector(ent.WorldSpaceCenter()); + return 1; + } + + [LuaMethod] + static int Entity__OBBMins(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (ent.CollisionProp() == null) { + LuaVector.Push_Vector(vec3_origin); + return 1; + } + LuaVector.Push_Vector(ent.CollisionProp().OBBMins()); + return 1; + } + + [LuaMethod] + static int Entity__OBBMaxs(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (ent.CollisionProp() == null) { + LuaVector.Push_Vector(vec3_origin); + return 1; + } + LuaVector.Push_Vector(ent.CollisionProp().OBBMaxs()); + return 1; + } + + [LuaMethod] + static int Entity__GetMoveParent(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Push_Entity(ent.GetMoveParent()); + return 1; + } + + [LuaMethod] + static int Entity__GetRight(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.GetVectors(out _, out Vector3 right, out _); + LuaVector.Push_Vector(right); + return 1; + } + + [LuaMethod] + static int Entity__IsWeapon(ILuaInterface lua) { + lua.PushBool(false); + return 1; + } + + [LuaMethod] + static int Entity__IsVehicle(ILuaInterface lua) { + lua.PushBool(false); + return 1; + } + + [LuaMethod] + static int Entity__IsNextBot(ILuaInterface lua) { + lua.PushBool(false); + return 1; + } + [LuaMethod] static int Entity__AddEffects(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -1139,6 +1274,53 @@ static int Entity__SetSequence(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__ResetSequence(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + + int sequence; + if (lua.GetType(2) == LuaType.Number) + sequence = (int)lua.GetNumber(2); + else + sequence = animating.LookupSequence(lua.GetString(2)); + + animating.ResetSequence(sequence); + return 0; + } + + [LuaMethod] + static int Entity__GetSkin(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) { + lua.PushNumber(0); + return 1; + } + lua.PushNumber(animating.Skin); + return 1; + } + + [LuaMethod] + static int Entity__FrameAdvance(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || IsQueuedForRemoval(ent) || ent.IsMarkedForDeletion()) + return 0; + + animating.StudioFrameAdvance(); + return 0; + } + + [LuaMethod] + static int Entity__GetCreationID(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber(ent.CreationID); + return 1; + } + [LuaMethod] static int Entity__SetCycle(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index daee405a..aaae8c5a 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -87,7 +87,6 @@ static int GetMap(ILuaInterface lua) { // todo: GetTimeScale // todo: GetSkillLevel // todo: AddParticles - // todo: IsDedicated [LuaFunction] static int MountGMA(ILuaInterface lua) { @@ -133,5 +132,11 @@ static int SinglePlayer(ILuaInterface lua) { g_Lua!.PushBool(gpGlobals.MaxClients == 1); return 1; } + + [LuaFunction] + static int IsDedicated(ILuaInterface lua) { + g_Lua!.PushBool(engine.IsDedicatedServer()); + return 1; + } } #endif diff --git a/Game.Shared/GarrysMod/LuaGameEvent.cs b/Game.Shared/GarrysMod/LuaGameEvent.cs new file mode 100644 index 00000000..fc062280 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaGameEvent.cs @@ -0,0 +1,82 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common; +using Source.Common.Formats.Keyvalues; +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public class LuaGameEventListener : AutoGameSystemPerFrame, IGameEventListener2 +{ + public static readonly LuaGameEventListener g_LuaGameEventListener = new(); + + bool RegisteredForEvents; + + public void ListenForGameEvent(ReadOnlySpan name) { + RegisteredForEvents = true; +#if CLIENT_DLL + bool serverSide = false; +#else + bool serverSide = true; +#endif + gameeventmanager?.AddListener(this, name, serverSide); + } + + public void StopListeningForAllEvents() { + if (RegisteredForEvents) { + gameeventmanager?.RemoveListener(this); + RegisteredForEvents = false; + } + } + + public override ReadOnlySpan Name() => "LuaGameEventListener"; + + public override void LevelShutdownPostEntity() => StopListeningForAllEvents(); + + public void FireGameEvent(IGameEvent ev) { + if (g_Lua == null || gGM == null) + return; + + LuaTable data = new(); + for (KeyValues? key = ev.GetDataKeys()?.GetFirstValue(); key != null; key = key.GetNextValue()) { + switch (key.Type) { + case KeyValues.Types.String: + data.SetMember(key.Name, key.GetString()); + break; + case KeyValues.Types.Int: + data.SetMember(key.Name, key.GetInt()); + break; + case KeyValues.Types.Double: + data.SetMember(key.Name, key.GetFloat()); + break; + case KeyValues.Types.Uint64: + data.SetMember(key.Name, key.GetUint64(null).ToString()); + break; + } + } + + if (gGM.CallWithArgs(new string(ev.GetName()))) { + data.Push(); + gGM.CallFinish(1); + } + data.UnReference(); + } +} + +public static partial class LuaGameEventLib +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_gameevent = new("gameevent"); + + [LuaFunction] + static int Listen(ILuaInterface lua) { + LuaGameEventListener.g_LuaGameEventListener.ListenForGameEvent(g_Lua!.CheckString(1)); + return 0; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index f9b2679b..b489424f 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -132,15 +132,40 @@ public void FireGameEvent(IGameEvent ev) { #if CLIENT_DLL if (strcmp(ev.GetName(), "server_spawn") == 0) { Gamemode = new(ev.GetString("gamemode", "")); - // todo + filesystem.Gamemodes().SetActive(Gamemode); } - else #endif if (strcmp(ev.GetName(), "player_connect") == 0) { - // todo + if (g_Lua != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerConnect)) { + g_Lua.PushString(ev.GetString("name", "")); +#if CLIENT_DLL + gGM.CallFinish(1); +#else + g_Lua.PushString(ev.GetString("address", "")); + gGM.CallFinish(2); +#endif + } } else if (strcmp(ev.GetName(), "break_prop") == 0) { - // todo + if (g_Lua != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PropBreak)) { + BasePlayer? player = null; + if (ev.GetInt("userid", 0) > 0) +#if CLIENT_DLL + player = ClientModeShared.USERID2PLAYER(ev.GetInt("userid", 0)); +#else + player = Util.PlayerByUserId(ev.GetInt("userid", 0)); +#endif + LuaEntity.Push_Entity(player); + BaseEntity? entity = null; + if (ev.GetInt("entindex", 0) > 0) +#if CLIENT_DLL + entity = cl_entitylist.GetBaseEntity(ev.GetInt("entindex", 0)); +#else + entity = LuaEntity.GMEntityByIndex(ev.GetInt("entindex", 0)); +#endif + LuaEntity.Push_Entity(entity); + gGM.CallFinish(2); + } } #if CLIENT_DLL else if (strcmp(ev.GetName(), "user_data_downloaded") == 0 && !UserDataDownloaded) { diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index f17335a3..34960768 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -8,6 +8,8 @@ using Source.Common.Mathematics; using System.Numerics; +using Source.Common.Client; + #if CLIENT_DLL using GMOD_Player = Game.Client.GarrysMod.C_GMOD_Player; @@ -680,6 +682,172 @@ static int Player__GetViewModel(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__GetViewEntity(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + BaseEntity? viewEntity = player.GetViewEntity(); + if (viewEntity == null) + viewEntity = player; + LuaEntity.Push_Entity(viewEntity); + return 1; + } + + [LuaMethod] + static int Player____tostring(ILuaInterface lua) { + BasePlayer? player = Get_Player(1, true); + string str = player == null ? "Player [NULL]" : $"Player [{player.EntIndex()}][{player.GetPlayerName()}]"; + lua.PushString(str.Length > 0xFF ? str[..0xFF] : str); + return 1; + } + +#if CLIENT_DLL + [LuaMethod] + static int Player__GetFriendStatus(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + if (!Steamworks.SteamAPI.IsSteamRunning()) { + lua.PushString("error_steamworks"); + return 1; + } + + if (!engine.GetPlayerInfo(player.EntIndex(), out PlayerInfo info)) { + lua.PushString("error_noplayer"); + return 1; + } + + string status; + if (info.FriendsID == 0) + status = "error_nofriendid"; + else if (info.FakePlayer) + status = "error_bot"; + else { + Steamworks.CSteamID steamID = default; + steamID.InstancedSet(new Steamworks.AccountID_t(info.FriendsID), 1, Steamworks.SteamUtils.GetConnectedUniverse(), Steamworks.EAccountType.k_EAccountTypeIndividual); + status = Steamworks.SteamFriends.GetFriendRelationship(steamID) switch { + Steamworks.EFriendRelationship.k_EFriendRelationshipBlocked => "blocked", + Steamworks.EFriendRelationship.k_EFriendRelationshipRequestRecipient => "requestrecipient", + Steamworks.EFriendRelationship.k_EFriendRelationshipFriend => "friend", + Steamworks.EFriendRelationship.k_EFriendRelationshipRequestInitiator => "requested", + Steamworks.EFriendRelationship.k_EFriendRelationshipIgnored => "blocked", + _ => "none", + }; + } + lua.PushString(status); + return 1; + } +#endif + + [LuaMethod] + static int Player__Team(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushNumber(player.GetTeamNumber()); + return 1; + } + + [LuaMethod] + static int Player__Armor(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + if (g_pPlayerResource == null) + return 0; + lua.PushNumber(g_pPlayerResource.GetArmor(player.EntIndex())); +#else + lua.PushNumber(player.ArmorValue); +#endif + return 1; + } + + [LuaMethod] + static int Player__GetMaxArmor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + lua.PushNumber(player.MaxArmor); + return 1; + } + + [LuaMethod] + static int Player__Frags(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + if (g_pPlayerResource == null) + return 0; + lua.PushNumber(g_pPlayerResource.GetFrags(player.EntIndex())); +#else + lua.PushNumber(player.Frags); +#endif + return 1; + } + + [LuaMethod] + static int Player__Deaths(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + if (g_pPlayerResource == null) + return 0; + lua.PushNumber(g_pPlayerResource.GetDeaths(player.EntIndex())); +#else + lua.PushNumber(player.Deaths); +#endif + return 1; + } + + [LuaMethod] + static int Player__Ping(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; +#if CLIENT_DLL + if (g_pPlayerResource == null) + return 0; + lua.PushNumber(g_pPlayerResource.GetPing(player.EntIndex())); +#else + Util.GetPlayerConnectionInfo(player.EntIndex(), out int ping, out _); + lua.PushNumber(ping); +#endif + return 1; + } + + [LuaMethod] + static int Player__GetObserverMode(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushNumber((int)player.GetObserverMode()); + return 1; + } + + [LuaMethod] + static int Player__GetObserverTarget(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + LuaEntity.Push_Entity(player.GetObserverTarget()); + return 1; + } + + [LuaMethod] + static int Player__Crouching(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushBool((player.GetFlags() & EntityFlags.Ducking) != 0); + return 1; + } + + [LuaMethod] + static int Player__UserID(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushNumber(player.GetUserID()); + return 1; + } + + [LuaGlobal] + static int Player(ILuaInterface lua) { +#if CLIENT_DLL + LuaEntity.Push_Entity(ClientModeShared.USERID2PLAYER((int)lua.CheckNumber(1))); +#else + LuaEntity.Push_Entity(Util.PlayerByUserId((int)lua.CheckNumber(1))); +#endif + return 1; + } + + [LuaMethod] + static int Player__IsBot(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushBool(player.IsBot() || player.IsHLTV()); + return 1; + } + [LuaMethod] static int Player__GetHands(ILuaInterface lua) { GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 3a8fff00..f9bbf644 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -240,6 +240,78 @@ static int KeyValuesToTablePreserveOrder(ILuaInterface lua) { } #if !MENU_DLL + static bool ParseSteam2Number(ref ReadOnlySpan str, out uint value) { + value = 0; + int i = 0; + while (i < str.Length && char.IsAsciiDigit(str[i])) { + value = value * 10 + (uint)(str[i] - '0'); + i++; + } + if (i == 0) + return false; + str = str[i..]; + return true; + } + + static bool SetFromSteam2String(ReadOnlySpan str, Steamworks.EUniverse universe, out ulong steamID) { + steamID = 0; + str = str.SliceNullTerminatedString(); + if (strnicmp(str, "STEAM_", 6) == 0) + str = str[6..]; + + uint x = 0, y = 0, z = 0; + int count = 0; + if (ParseSteam2Number(ref str, out x)) { + count++; + if (str.Length > 0 && str[0] == ':') { + str = str[1..]; + if (ParseSteam2Number(ref str, out y)) { + count++; + if (str.Length > 0 && str[0] == ':') { + str = str[1..]; + if (ParseSteam2Number(ref str, out z)) { + count++; + if (str.Length > 0) + count++; + } + } + } + } + } + + if (count > 3 || count <= 1 || (count <= 2 && (ushort)x != 1)) + return false; + + Steamworks.CSteamID id = default; + id.InstancedSet(new Steamworks.AccountID_t(y + z * 2), 1, universe, Steamworks.EAccountType.k_EAccountTypeIndividual); + steamID = id.m_SteamID; + return true; + } + + [LuaFunction] + static int SteamIDTo64(ILuaInterface lua) { + string? str = lua.GetString(1); + if (str == null) + return 0; + + SetFromSteam2String(str, Steamworks.EUniverse.k_EUniversePublic, out ulong steamID); + lua.PushString(steamID.ToString()); + return 1; + } + + [LuaFunction] + static int SteamIDFrom64(ILuaInterface lua) { + string? str = lua.GetString(1); + if (str == null) + return 0; + + _ = ulong.TryParse(str, out ulong steamID); + Span buf = stackalloc char[1024]; + sprintf(buf, "STEAM_0:%u:%u").U((uint)steamID & 1).U((uint)(steamID >> 1) & 0x7fffffff); + lua.PushString(((ReadOnlySpan)buf).SliceNullTerminatedString()); + return 1; + } + [LuaFunction] static int SharedRandom(ILuaInterface lua) { int seed = 0; diff --git a/Game.Shared/GarrysMod/LuaVector.cs b/Game.Shared/GarrysMod/LuaVector.cs index 84ec36a5..b8794820 100644 --- a/Game.Shared/GarrysMod/LuaVector.cs +++ b/Game.Shared/GarrysMod/LuaVector.cs @@ -1,4 +1,5 @@ #if CLIENT_DLL || GAME_DLL || MENU_DLL +using Source; using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; @@ -29,6 +30,15 @@ static char FirstChar(int stackPos) { return str.IsEmpty ? '\0' : (char)str[0]; } + [LuaMethod] + static int Vector____tostring(ILuaInterface lua) { + ref Vector3 vec = ref Get_Vector(1); + Span str = stackalloc char[128]; + sprintf(str, "%f %f %f").F(vec.X).F(vec.Y).F(vec.Z); + g_Lua!.PushString(((ReadOnlySpan)str).SliceNullTerminatedString()); + return 1; + } + [LuaMethod] static int Vector____index(ILuaInterface lua) { if (g_Lua!.FindOnObjectsMetaTable(1, 2)) diff --git a/Game.Shared/GarrysMod/LuaVideo.cs b/Game.Shared/GarrysMod/LuaVideo.cs new file mode 100644 index 00000000..b1367d4f --- /dev/null +++ b/Game.Shared/GarrysMod/LuaVideo.cs @@ -0,0 +1,21 @@ +#if CLIENT_DLL || MENU_DLL +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.MenuSystem.GarrysMod; +#endif + +public static partial class LuaVideo +{ + [LuaLibrary] + static readonly LuaLibrary LL_Factory_video = new("video"); + + [LuaFunction] + static int Record(ILuaInterface lua) { + // todo!!! + return 0; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaWeapon.cs b/Game.Shared/GarrysMod/LuaWeapon.cs index a7e1157e..4979aa8d 100644 --- a/Game.Shared/GarrysMod/LuaWeapon.cs +++ b/Game.Shared/GarrysMod/LuaWeapon.cs @@ -14,6 +14,14 @@ public static partial class LuaWeapon [LuaClass] static readonly LuaEntityClass LC_Weapon = LuaEntity.LC_Weapon; + [LuaMethod] + static int Weapon____tostring(ILuaInterface lua) { + BaseCombatWeapon? weapon = LuaEntity.Get_Weapon(1, true); + string str = weapon == null ? "Weapon [NULL]" : $"Weapon [{weapon.EntIndex()}][{weapon.GetClassname()}]"; + lua.PushString(str.Length > 0xFF ? str[..0xFF] : str); + return 1; + } + [LuaMethod] static int Weapon__IsScripted(ILuaInterface lua) { BaseCombatWeapon weapon = LuaEntity.Get_Weapon(1, false)!; diff --git a/Source.Common/IGameEvents.cs b/Source.Common/IGameEvents.cs index 3bb9a763..b193a1dc 100644 --- a/Source.Common/IGameEvents.cs +++ b/Source.Common/IGameEvents.cs @@ -32,6 +32,9 @@ public interface IGameEvent void SetInt(ReadOnlySpan keyName, int value); void SetFloat(ReadOnlySpan keyName, float value); void SetString(ReadOnlySpan keyName, ReadOnlySpan value); +#if GMOD_DLL + KeyValues? GetDataKeys(); +#endif } public interface IGameEventListener2 @@ -111,6 +114,9 @@ public GameEvent(GameEventDescriptor descriptor) { public void SetInt(ReadOnlySpan keyName, int value) => DataKeys!.SetInt(keyName, value); public void SetFloat(ReadOnlySpan keyName, float value) => DataKeys!.SetFloat(keyName, value); public void SetString(ReadOnlySpan keyName, ReadOnlySpan value) => DataKeys!.SetString(keyName, value); +#if GMOD_DLL + public KeyValues? GetDataKeys() => DataKeys; +#endif public GameEventDescriptor? Descriptor; public KeyValues? DataKeys; diff --git a/Source.DataCache/MDLCache.cs b/Source.DataCache/MDLCache.cs index 0900528d..abd06c8b 100644 --- a/Source.DataCache/MDLCache.cs +++ b/Source.DataCache/MDLCache.cs @@ -148,7 +148,95 @@ public void Flush(MDLCacheFlush flushFlags = MDLCacheFlush.All) { } public void Flush(MDLHandle_t handle, MDLCacheFlush flushFlags = MDLCacheFlush.All) { - throw new NotImplementedException(); + StudioData studioData = HandleToMDLDict[handle]; + Assert(studioData != null); + + bool ignoreLock = (flushFlags & MDLCacheFlush.IgnoreLock) != 0; + + if ((flushFlags & MDLCacheFlush.StudioHWData) != 0) + UnloadHardwareData(handle, true, ignoreLock); + + if ((flushFlags & MDLCacheFlush.VCollide) != 0) + DestroyVCollide(handle); + + if ((flushFlags & MDLCacheFlush.VirtualModel) != 0) + FreeVirtualModel(handle); + + if ((flushFlags & MDLCacheFlush.AnimBlock) != 0) + FreeAnimBlocks(handle); + + if ((flushFlags & MDLCacheFlush.Autoplay) != 0) + FreeAutoplaySequences(studioData); + + if ((flushFlags & MDLCacheFlush.StudioHDR) != 0) { + MdlCacheMsg($"MDLCache: Free studiohdr {GetModelName(handle)}\n"); + + if ((studioData.Flags & StudioDataFlags.LockedMDL) != 0) + studioData.Flags &= ~StudioDataFlags.LockedMDL; + studioData.Header = null; + } + + if ((flushFlags & MDLCacheFlush.Vertexes) != 0) { + MdlCacheMsg($"MDLCache: Free VVD {GetModelName(handle)}\n"); + studioData.VertexCache = null; + } + + if (!IsDataLoaded(handle, MDLCacheDataType.StudioHDR)) + NotifyFileUnloaded(handle, ".mdl"); + + if (!IsDataLoaded(handle, MDLCacheDataType.StudioHWData)) + NotifyFileUnloaded(handle, GetVTXExtension()); + + if (!IsDataLoaded(handle, MDLCacheDataType.Vertexes)) + NotifyFileUnloaded(handle, ".vvd"); + + if (!IsDataLoaded(handle, MDLCacheDataType.VCollide)) + NotifyFileUnloaded(handle, ".phy"); + } + + private void UnloadHardwareData(MDLHandle_t handle, bool cacheRemove, bool lockedOk) { + // todo + } + + private void DestroyVCollide(MDLHandle_t handle) { + StudioData studioData = HandleToMDLDict[handle]; + + if ((studioData.Flags & StudioDataFlags.VCollisionShared) != 0) + return; + + if ((studioData.Flags & StudioDataFlags.VCollisionLoaded) != 0) { + studioData.Flags &= ~StudioDataFlags.VCollisionLoaded; + if (studioData.VCollisionData.SolidCount != 0) { + CacheNotify?.OnDataUnloaded(MDLCacheDataType.VCollide, handle); + + MdlCacheMsg($"MDLCache: Unload vcollide {GetModelName(handle)}\n"); + + physcollision.VCollideUnload(studioData.VCollisionData); + } + } + } + + private void FreeAnimBlocks(MDLHandle_t handle) { + StudioData studioData = HandleToMDLDict[handle]; + + if (studioData.AnimBlock != null) { + for (int i = 0; i < studioData.AnimBlockCount; ++i) { + MdlCacheMsg($"MDLCache: Free Anim block: {i}\n"); + studioData.AnimBlock[i] = null; + } + + studioData.AnimBlock = null; + } + + studioData.AnimBlockCount = 0; + } + + private void FreeAutoplaySequences(StudioData studioData) { + studioData.AutoplaySequenceList = []; + } + + private void NotifyFileUnloaded(MDLHandle_t handle, ReadOnlySpan extension) { + // todo } public Memory GetAnimBlock(MDLHandle_t handle, int block) { @@ -808,13 +896,18 @@ public int Release(MDLHandle_t handle) { if (nRefCount <= 0) { ShutdownStudioData(handle); HandleToMDLDict.Remove(handle, out _); + if (HandleToFileDict.Remove(handle, out UtlSymbol name)) + FileToMDLDict.Remove(name, out _); } return nRefCount; } private void ShutdownStudioData(MDLHandle_t handle) { - throw new NotImplementedException(); + Flush(handle); + + Assert(HandleToMDLDict.ContainsKey(handle)); + HandleToMDLDict[handle] = null!; } public void ResetErrorModelStatus(MDLHandle_t handle) { diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 3fc58375..fb9f2c0f 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -702,8 +702,6 @@ public bool NET_IsHostLocal(ReadOnlySpan hostName) { throw new NotImplementedException(); } - public bool IsDedicatedServer() { - throw new NotImplementedException(); - } + public bool IsDedicatedServer() => ClientState.IsDedicated; } #endif diff --git a/Source.Engine/Client/BaseClientState.cs b/Source.Engine/Client/BaseClientState.cs index 57176bab..56aada46 100644 --- a/Source.Engine/Client/BaseClientState.cs +++ b/Source.Engine/Client/BaseClientState.cs @@ -643,6 +643,27 @@ public virtual bool ProcessServerInfo(SVC_ServerInfo msg) { DeltaTick = -1; + IGameEvent? ev = g_GameEventManager.CreateEvent("server_spawn"); + if (ev != null) { +#if GMOD_DLL + ev.SetString("loadurl", msg.LoadingURL); + ev.SetString("gamemode", msg.Gamemode); +#endif + ev.SetString("hostname", msg.HostName); + ev.SetString("address", NetChannel!.GetRemoteAddress()!.ToString(true)); + ev.SetInt("ip", (int)NetChannel.GetRemoteAddress()!.GetIPNetworkByteOrder()); + ev.SetInt("port", NetChannel.GetRemoteAddress()!.GetPort()); + ev.SetString("game", msg.GameDirectory); + ev.SetString("mapname", msg.MapName); + ev.SetInt("maxplayers", msg.MaxClients); + ev.SetInt("password", 0); + ev.SetString("os", $"{char.ToUpperInvariant((char)msg.ServerOS)}"); + ev.SetInt("dedicated", msg.IsDedicated ? 1 : 0); + if (GameServerSteamID != 0) + ev.SetString("steamid", GameServerSteamID.ToString()); + g_GameEventManager.FireEventClientSide(ev); + } + Span levelFileName = stackalloc char[MAX_PATH]; Host.DefaultMapFileName(msg.MapName, levelFileName); strcpy(_LevelFileName, levelFileName); diff --git a/Source.Engine/Client/ClientState.cs b/Source.Engine/Client/ClientState.cs index 4554b7e9..60e42ba3 100644 --- a/Source.Engine/Client/ClientState.cs +++ b/Source.Engine/Client/ClientState.cs @@ -1261,6 +1261,8 @@ internal void CopyEntityBaseline(int from, int to) { } } + public static bool IsDedicated; + public override bool ProcessServerInfo(SVC_ServerInfo msg) { // Reset client state Clear(); @@ -1299,8 +1301,7 @@ public override bool ProcessServerInfo(SVC_ServerInfo msg) { host_state.IntervalPerTick = msg.TickInterval; } - // Gmod Specific - a global bool. Should we put this into the host state? - // g_bIsDedicated = msg->m_bIsDedicated; + IsDedicated = msg.IsDedicated; g_ClientDLL?.HudVidInit(); diff --git a/Source.GUI.Controls/Button.cs b/Source.GUI.Controls/Button.cs index b6c5fdda..bfc3c50e 100644 --- a/Source.GUI.Controls/Button.cs +++ b/Source.GUI.Controls/Button.cs @@ -318,11 +318,13 @@ public override void OnMouseReleased(ButtonCode code) { public override void OnCursorEntered() { if (IsEnabled() && !IsSelected()) SetArmed(true); + base.OnCursorEntered(); } public override void OnCursorExited() { if ((ButtonFlags & ButtonFlags.ButtonKeyDown) == 0 && !IsSelected()) SetArmed(false); + base.OnCursorExited(); } public virtual void SetSelected(bool state) { diff --git a/Source.GUI.Controls/RichText.cs b/Source.GUI.Controls/RichText.cs index f3bbce3e..dee89b47 100644 --- a/Source.GUI.Controls/RichText.cs +++ b/Source.GUI.Controls/RichText.cs @@ -185,10 +185,12 @@ public override void OnMouseFocusTicked() { public override void OnCursorEntered() { MouseDragSelection = false; + base.OnCursorEntered(); } public override void OnCursorExited() { if (MouseSelection) MouseDragSelection = true; + base.OnCursorExited(); } public override void OnCursorMoved(int x, int y) { From 753ac9a33180c559c6c9f87ab42c96e4bebf1438 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 28 Oct 2026 14:21:01 +0000 Subject: [PATCH 5/8] more lua --- Game.Client/C_BaseAnimating.cs | 10 +- Game.Client/C_BaseEntity.cs | 24 +++- Game.Client/GarrysMod/LuaRender.cs | 23 ++++ Game.Server/BaseAnimating.cs | 4 + Game.Server/BaseEntity.cs | 2 +- Game.Server/GarrysMod/GMOD_Player.cs | 1 + Game.Shared/Animation.cs | 39 ++++++ Game.Shared/BaseEntityShared.cs | 2 + Game.Shared/FuncLadder.cs | 1 + Game.Shared/GarrysMod/GarrysMod.cs | 4 + Game.Shared/GarrysMod/LuaEntity.cs | 145 +++++++++++++++++++++ Game.Shared/GarrysMod/LuaGameSystem.cs | 10 +- Game.Shared/GarrysMod/LuaPlayer.cs | 7 + Source.Common/Optimize.cs | 16 ++- Source.Engine/ModelInfo.cs | 10 +- Source.Engine/ModelLoader.cs | 28 ++++ Source.Engine/Server/BaseServer.cs | 4 + Source.GUI.Controls/Panel.cs | 1 + Source.MaterialSystem/Material.cs | 24 +++- Source.SDLSystem/SDL3_System.cs | 3 +- Source.ShaderAPI.Gl46/ShaderSystem.cs | 2 +- Source.StudioRender/StudioRenderContext.cs | 2 +- 22 files changed, 339 insertions(+), 23 deletions(-) diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs index dec04ba6..aed27258 100644 --- a/Game.Client/C_BaseAnimating.cs +++ b/Game.Client/C_BaseAnimating.cs @@ -82,6 +82,10 @@ public void SetBodygroup(int group, int value) { Animation.SetBodygroup(GetModelPtr(), ref Body, group, value); } + public int GetBodygroup(int group) => Animation.GetBodygroup(GetModelPtr(), Body, group); + public ReadOnlySpan GetBodygroupName(int group) => Animation.GetBodygroupName(GetModelPtr(), group); + public int GetBodygroupCount(int group) => Animation.GetBodygroupCount(GetModelPtr(), group); + float GroundSpeed; const TimeUnit_t MAX_ANIMTIME_INTERVAL = 0.2; public TimeUnit_t GetAnimTimeInterval() => Math.Min(gpGlobals.CurTime - AnimTime, MAX_ANIMTIME_INTERVAL); @@ -179,7 +183,7 @@ public void StudioFrameAdvance() { GroundSpeed = (float)GetSequenceGroundSpeed(hdr, GetSequence()) * GetModelScale(); } - public override int VPhysicsGetObjectList(Span list){ + public override int VPhysicsGetObjectList(Span list) { if (IsRagdoll()) { int i; for (i = 0; i < Ragdoll.RagdollBoneCount(); ++i) { @@ -845,7 +849,7 @@ public string GetSequenceName(int sequence) { return Animation.GetSequenceName(GetModelPtr(), sequence); } - public ClientRagdoll? Ragdoll = null; + public ClientRagdoll? Ragdoll = null; public override void OnDataChanged(DataUpdateType updateType) { if (Ragdoll != null && GetSequence() != PrevSequence) { @@ -1043,6 +1047,8 @@ public static class SequenceProxy for (i = 0; i < hdr.GetNumPoseParameters(); i++) { MStudioPoseParamDesc Pose = hdr.PoseParameter(i); iv_flPoseParameter.SetLooping(Pose.Loop != 0.0f, i); + if (!IsServerEntity()) + SetPoseParameter(hdr, i, 0.0f); } EyeAttachment = LookupAttachment("eyes"); diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index 74fc6047..2ecf73f3 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -1247,7 +1247,29 @@ public bool SetModel(ReadOnlySpan modelName) { public virtual ref readonly Vector3 GetRenderOrigin() => ref GetAbsOrigin(); public virtual ref readonly QAngle GetRenderAngles() => ref GetAbsAngles(); +#if GMOD_DLL + Vector3 RenderBoundsOverrideMins; + Vector3 RenderBoundsOverrideMaxs; + bool HasRenderBoundsOverride; + + public virtual void SetRenderBounds(in Vector3 mins, in Vector3 maxs) { + RenderBoundsOverrideMins = mins; + RenderBoundsOverrideMaxs = maxs; + HasRenderBoundsOverride = true; + } + + public virtual bool GetRenderBoundsOverride(out Vector3 mins, out Vector3 maxs) { + mins = RenderBoundsOverrideMins; + maxs = RenderBoundsOverrideMaxs; + return HasRenderBoundsOverride; + } +#endif + public void GetRenderBounds(out Vector3 mins, out Vector3 maxs) { +#if GMOD_DLL + if (GetRenderBoundsOverride(out mins, out maxs)) + return; +#endif ModelType nModelType = modelinfo.GetModelType(Model); if (nModelType == ModelType.Studio || nModelType == ModelType.Brush) modelinfo.GetModelRenderBounds(GetModel(), out mins, out maxs); @@ -2537,7 +2559,7 @@ public void MoveToAimEnt() { public bool IsDormant() => IsServerEntity() && Dormant; [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool IsServerEntity() => Index != -1; + public bool IsServerEntity() => Index != -1; public int EntIndex() { return Index; diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 1fbfdb5c..8f636a18 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -187,6 +187,29 @@ static int SuppressEngineLighting(ILuaInterface lua) { return 0; } + static readonly Vector3[] ModelLighting = new Vector3[6]; + + [LuaFunction] + static int ResetModelLighting(ILuaInterface lua) { + float b = (float)lua.GetNumber(3); + float g = (float)lua.GetNumber(2); + float r = (float)lua.GetNumber(1); + for (int i = 0; i < 6; i++) + ModelLighting[i] = new(r, g, b); + studiorender.SetAmbientLightColors(ModelLighting); + return 0; + } + + [LuaFunction] + static int SetModelLighting(ILuaInterface lua) { + int direction = (int)lua.GetNumber(1); + if ((uint)direction < 6) { + ModelLighting[direction] = new((float)lua.GetNumber(2), (float)lua.GetNumber(3), (float)lua.GetNumber(4)); + studiorender.SetAmbientLightColors(ModelLighting); + } + return 0; + } + [LuaFunction] static int UpdateScreenEffectTexture(ILuaInterface lua) { int textureIndex = 0; diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index dbf36296..6b68a62f 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -1316,6 +1316,10 @@ public void SetBodygroup(int group, int value) { Body = newBody; } + public int GetBodygroup(int group) => Animation.GetBodygroup(GetModelPtr(), Body, group); + public ReadOnlySpan GetBodygroupName(int group) => Animation.GetBodygroupName(GetModelPtr(), group); + public int GetBodygroupCount(int group) => Animation.GetBodygroupCount(GetModelPtr(), group); + public override BaseAnimating? GetBaseAnimating() => this; public bool IsUsingClientSideAnimation() { diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index d3fa2f68..821a29df 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -3042,7 +3042,7 @@ public static int PrecacheModel(ReadOnlySpan name, bool preload = true) { public static void PrecacheModelComponents(int modelIndex) { Model? model = (Model?)modelinfo.GetModel(modelIndex); - if (model != null || modelinfo.GetModelType(model) != ModelType.Studio) + if (model == null || modelinfo.GetModelType(model) != ModelType.Studio) return; // sounds diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index a5cbd47f..71dd150d 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -183,6 +183,7 @@ public override BaseEntity EntSelectSpawnPoint() { public partial Vector3 WeaponColor { get; set; } public virtual Vector3 GetPlayerColor() => PlayerColor; + public virtual Vector3 GetWeaponColor() => WeaponColor; public virtual void SetPlayerColor(in Vector3 color) { if (PlayerColor != color) { diff --git a/Game.Shared/Animation.cs b/Game.Shared/Animation.cs index 489dd46a..0b384b94 100644 --- a/Game.Shared/Animation.cs +++ b/Game.Shared/Animation.cs @@ -408,6 +408,45 @@ internal static void SetBodygroup(StudioHdr? studioHdr, ref int body, int group, body = (body - (iCurrent * bodypart.Base) + (value * bodypart.Base)); } + + internal static int GetBodygroup(StudioHdr? studioHdr, int body, int group) { + if (studioHdr == null) + return 0; + + if (group >= studioHdr.NumBodyParts()) + return 0; + + MStudioBodyParts bodypart = studioHdr.Bodypart(group); + + if (bodypart.NumModels <= 1) + return 0; + + int iCurrent = (body / bodypart.Base) % bodypart.NumModels; + + return iCurrent; + } + + internal static ReadOnlySpan GetBodygroupName(StudioHdr? studioHdr, int group) { + if (studioHdr == null) + return ""; + + if (group >= studioHdr.NumBodyParts()) + return ""; + + MStudioBodyParts bodypart = studioHdr.Bodypart(group); + return bodypart.Name(); + } + + internal static int GetBodygroupCount(StudioHdr? studioHdr, int group) { + if (studioHdr == null) + return 0; + + if (group >= studioHdr.NumBodyParts()) + return 0; + + MStudioBodyParts bodypart = studioHdr.Bodypart(group); + return bodypart.NumModels; + } } public static class ImplementStudioHdrFns { diff --git a/Game.Shared/BaseEntityShared.cs b/Game.Shared/BaseEntityShared.cs index 336ee6ee..c6489c09 100644 --- a/Game.Shared/BaseEntityShared.cs +++ b/Game.Shared/BaseEntityShared.cs @@ -65,6 +65,8 @@ public static class BaseEntityConstants #else public static readonly ConVar hl2_episodic = new("hl2_episodic", "0", FCvar.Replicated); #endif + public static readonly ConVar ai_shot_bias_min = new("ai_shot_bias_min", "-1.0", FCvar.Replicated); + public static readonly ConVar ai_shot_bias_max = new("ai_shot_bias_max", "1.0", FCvar.Replicated); public const int NUM_PARENTATTACHMENT_BITS = 8; // < gmod increased 6 . 8 public const int VPHYSICS_MAX_OBJECT_LIST_COUNT = 1024; diff --git a/Game.Shared/FuncLadder.cs b/Game.Shared/FuncLadder.cs index 3d45a001..54a4f34f 100644 --- a/Game.Shared/FuncLadder.cs +++ b/Game.Shared/FuncLadder.cs @@ -35,6 +35,7 @@ public FuncLadder() { public override void Term() { s_Ladders.Remove(this); + base.Term(); } public static int GetLadderCount() => s_Ladders.Count; diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 6bb3e095..dc09ee62 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -334,7 +334,11 @@ public bool RunScript(ReadOnlySpan file, ReadOnlySpan pathId, bool r return g_Lua.FindAndRunScript(file, run, true, source, true); } +#if CLIENT_DLL public bool ScriptExists(ReadOnlySpan file, ReadOnlySpan pathId) => get.LuaShared()!.LoadFile(file, pathId, true, true) != null; +#else + public bool ScriptExists(ReadOnlySpan file, ReadOnlySpan pathId) => get.LuaShared()!.LoadFile(file, pathId, false, true) != null; +#endif #if CLIENT_DLL public C_BaseEntity? CreateEntity(ReadOnlySpan className) => LuaSENTManager.gSENTManager!.CreateEntity(className); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 46e29537..3074e389 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -1,3 +1,4 @@ +using Source.Common.MaterialSystem; #if CLIENT_DLL || GAME_DLL using Game.Shared; @@ -851,6 +852,106 @@ static int Entity__GetNumBodyGroups(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__GetBodyGroups(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + StudioHdr? studioHdr = animating != null && !ent.IsMarkedForDeletion() ? animating.GetModelPtr() : null; + lua.CreateTable(); + if (studioHdr == null) + return 1; + + for (int i = 0; i < studioHdr.NumBodyParts(); i++) { + MStudioBodyParts bodypart = studioHdr.Bodypart(i); + lua.PushNumber(i + 1); + lua.CreateTable(); + lua.PushNumber(i); + lua.SetField(-2, "id"); + lua.PushString(bodypart.Name()); + lua.SetField(-2, "name"); + lua.PushNumber(bodypart.NumModels); + lua.SetField(-2, "num"); + lua.CreateTable(); + for (int j = 0; j < bodypart.NumModels; j++) { + lua.PushNumber(j); + lua.PushString(bodypart.Model(j).Name()); + lua.SetTable(-3); + } + lua.SetField(-2, "submodels"); + lua.SetTable(-3); + } + return 1; + } + + [LuaMethod] + static int Entity__GetBodygroup(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) + return 0; + lua.PushNumber(animating.GetBodygroup((int)lua.GetNumber(2))); + return 1; + } + + [LuaMethod] + static int Entity__GetBodygroupCount(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) { + lua.PushNumber(0); + return 1; + } + lua.PushNumber(animating.GetBodygroupCount((int)lua.GetNumber(2))); + return 1; + } + + [LuaMethod] + static int Entity__GetAttachment(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int attachment = (int)lua.GetNumber(2); + BaseAnimating? animating = ent.GetBaseAnimating(); + StudioHdr? studioHdr = animating?.GetModelPtr(); + if (animating == null || studioHdr == null || ent.IsMarkedForDeletion() || attachment <= 0) + return 0; + if (attachment > studioHdr.GetNumAttachments()) + return 0; + if (!animating.GetAttachment(attachment, out Vector3 origin, out QAngle angles)) + return 0; + + int bone = studioHdr.GetAttachmentBone(attachment - 1); + lua.CreateTable(); + LuaVector.Push_Vector(origin); + lua.SetField(-2, "Pos"); + LuaAngle.Push_Angle(angles); + lua.SetField(-2, "Ang"); + lua.PushNumber(bone); + lua.SetField(-2, "Bone"); + return 1; + } + + [LuaMethod] + static int Entity__GetBoneCount(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + StudioHdr? studioHdr = animating != null && !ent.IsMarkedForDeletion() ? animating.GetModelPtr() : null; + if (studioHdr == null) { + lua.PushNumber(0); + return 1; + } + lua.PushNumber(studioHdr.NumBones()); + return 1; + } + + [LuaMethod] + static int Entity__GetBodygroupName(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsMarkedForDeletion()) + return 0; + lua.PushString(animating.GetBodygroupName((int)lua.GetNumber(2))); + return 1; + } + [LuaMethod] static int Entity__SetBodygroup(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -942,8 +1043,52 @@ static int Entity__GetRenderBounds(ILuaInterface lua) { LuaVector.Push_Vector(maxs); return 2; } + + [LuaMethod] + static int Entity__SetRenderBounds(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Vector3 mins = Vector3.Min(LuaVector.Get_Vector(3), LuaVector.Get_Vector(2)); + Vector3 maxs = Vector3.Max(LuaVector.Get_Vector(3), LuaVector.Get_Vector(2)); + if (lua.GetType(4) == LuaType.Vector) { + mins -= LuaVector.Get_Vector(4); + maxs += LuaVector.Get_Vector(4); + } + ent.SetRenderBounds(mins, maxs); + UpdateRenderable(ent); + return 0; + } + + static void UpdateRenderable(BaseEntity ent) { + if (ent.RenderHandle() != INVALID_CLIENT_RENDER_HANDLE) + clientLeafSystem.RenderableChanged(ent.RenderHandle()); + } #endif + [LuaMethod] + static int Entity__GetMaterials(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + PushModelMaterials(ent.GetModel()); + return 1; + } + + static void PushModelMaterials(Model? model) { + if (model == null) { + g_Lua!.CreateTable(); + return; + } + int count = modelinfo.GetModelMaterialCount(model); + if (count <= 0) + count = 128; + Span mats = new IMaterial[count + 1]; + modelinfo.GetModelMaterials(model, mats[..count]); + g_Lua!.CreateTable(); + for (int i = 0; mats[i] != null; i++) { + g_Lua.PushNumber(i + 1); + g_Lua.PushString(mats[i].GetName()); + g_Lua.SetTable(-3); + } + } + [LuaMethod] static int Entity__NearestPoint(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index b489424f..e476d443 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -118,15 +118,7 @@ public override bool Init() { return true; } -// public override void LevelInitPreEntity() => throw new NotImplementedException(); -// public override void LevelInitPostEntity() => throw new NotImplementedException(); -// public override void LevelShutdownPreEntity() => throw new NotImplementedException(); -// public override void LevelShutdownPostEntity() => throw new NotImplementedException(); -#if CLIENT_DLL -// public override void Update(TimeUnit_t frametime) => throw new NotImplementedException(); -#else -// public override void FrameUpdatePreEntityThink() => throw new NotImplementedException(); -#endif + // todo LevelShutdownPostEntity public void FireGameEvent(IGameEvent ev) { #if CLIENT_DLL diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index 34960768..fefbab93 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -882,6 +882,13 @@ static int Player__SetPlayerColor(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Player__GetWeaponColor(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + LuaVector.Push_Vector(player.GetWeaponColor()); + return 1; + } + [LuaMethod] static int Player__SetWeaponColor(ILuaInterface lua) { GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; diff --git a/Source.Common/Optimize.cs b/Source.Common/Optimize.cs index aed069e4..1a4afbb5 100644 --- a/Source.Common/Optimize.cs +++ b/Source.Common/Optimize.cs @@ -126,6 +126,7 @@ void ReadData() { public ref BoneStateChangeHeader BoneStateChange(int i) => ref Data.Span[BoneStateChangeOffset..].Cast()[i]; public Span BoneStateChanges(int i) => Data.Span[BoneStateChangeOffset..].Cast()[i..NumBoneStateChanges]; public const int SIZEOF = 4 + 4 + 4 + 4 + 2 + 1 + 4 + 4; + public const int SIZEOF_V49 = SIZEOF + 4 + 4; } [StructLayout(LayoutKind.Sequential, Pack = 1)] @@ -151,8 +152,13 @@ public class StripGroupHeader byte flags; public StripGroupFlags Flags => (StripGroupFlags)flags; - public StripGroupHeader(Memory mem) { + public const int SIZEOF_V49 = SIZEOF + (sizeof(int) * 2); + + int StudioVersion; + + public StripGroupHeader(Memory mem, int studioVersion) { Data = mem; + StudioVersion = studioVersion; Span data = mem.Span; NumVerts = data[0..].Cast()[0]; VertOffset = data[4..].Cast()[0]; @@ -172,7 +178,8 @@ public StripHeader Strip(int i) { if (partCache == null) partCache = new StripHeader[NumStrips]; - return partCache[i] ?? (partCache[i] = new(Data[(StripOffset + (StripHeader.SIZEOF * i))..])); + int stride = StudioVersion < 49 ? StripHeader.SIZEOF : StripHeader.SIZEOF_V49; + return partCache[i] ?? (partCache[i] = new(Data[(StripOffset + (stride * i))..])); } } public class MeshHeader @@ -193,11 +200,12 @@ public MeshHeader(Memory mem) { } StripGroupHeader[]? partCache; - public StripGroupHeader StripGroup(int i) { + public StripGroupHeader StripGroup(int i, int studioVersion) { if (partCache == null) partCache = new StripGroupHeader[NumStripGroups]; - return partCache[i] ?? (partCache[i] = new(Data[(StripGroupHeaderOffset + (StripGroupHeader.SIZEOF * i))..])); + int stride = studioVersion < 49 ? StripGroupHeader.SIZEOF : StripGroupHeader.SIZEOF_V49; + return partCache[i] ?? (partCache[i] = new(Data[(StripGroupHeaderOffset + (stride * i))..], studioVersion)); } } public class ModelLODHeader diff --git a/Source.Engine/ModelInfo.cs b/Source.Engine/ModelInfo.cs index 464c9d5f..95aa66e9 100644 --- a/Source.Engine/ModelInfo.cs +++ b/Source.Engine/ModelInfo.cs @@ -6,6 +6,7 @@ using Source.Common.MaterialSystem; using Source.Common.Mathematics; using Source.Common.Physics; +using Source.Common.Utilities; using Source.Engine.Client; using System.Numerics; @@ -274,11 +275,16 @@ public void RecomputeTranslucency(Model? model, int skin, int nBody, object? cli } public int GetModelMaterialCount(Model? model) { - throw new NotImplementedException(); + if (model == null) + return 0; + return ((ModelLoader)modelloader).Mod_GetMaterialCount(model); } public void GetModelMaterials(Model? model, Span material) { - throw new NotImplementedException(); + if (model == null) + return; + SpanList materials = new(material); + ((ModelLoader)modelloader).Mod_GetModelMaterials(model, ref materials); } public bool IsModelVertexLit(Model? model) { diff --git a/Source.Engine/ModelLoader.cs b/Source.Engine/ModelLoader.cs index 5f5e4c40..f0e35b7b 100644 --- a/Source.Engine/ModelLoader.cs +++ b/Source.Engine/ModelLoader.cs @@ -602,6 +602,34 @@ static bool ContainsMaterial(ReadOnlySpan materials, IMaterial? mater return false; } + internal int Mod_GetMaterialCount(Model mod) { + switch (mod.Type) { + case ModelType.Brush: { + List uniqueMaterials = new(32); + for (int i = 0; i < mod.Brush.NumModelSurfaces; ++i) { + ref BSPMSurface2 surfID = ref SurfaceHandleFromIndex(mod.Brush.FirstModelSurface + i, mod.Brush.Shared); + if ((MSurf_Flags(ref surfID) & SurfDraw.NoDraw) != 0) + continue; + + IMaterial? material = MSurf_TexInfo(ref surfID, mod.Brush.Shared).Material; + if (!uniqueMaterials.Contains(material)) + uniqueMaterials.Add(material); + } + return uniqueMaterials.Count; + } + + case ModelType.Studio: + Assert(false); + break; + + default: + Assert(false); + break; + } + + return 0; + } + internal void Mod_GetModelMaterials(Model model, ref SpanList materials) { StudioHeader studioHdr; int i; diff --git a/Source.Engine/Server/BaseServer.cs b/Source.Engine/Server/BaseServer.cs index a8471510..153f0d99 100644 --- a/Source.Engine/Server/BaseServer.cs +++ b/Source.Engine/Server/BaseServer.cs @@ -823,6 +823,10 @@ public virtual void FillServerInfo(SVC_ServerInfo serverinfo) { serverinfo.SkyName = new(((ReadOnlySpan)Skyname).SliceNullTerminatedString()); serverinfo.HostName = new(GetName()); serverinfo.IsHLTV = IsHLTV(); +#if GMOD_DLL + // todo LoadingURL + serverinfo.Gamemode = new(g_pFileSystem.Gamemodes().Active().Name); +#endif } public virtual void UserInfoChanged(int nClientIndex) { diff --git a/Source.GUI.Controls/Panel.cs b/Source.GUI.Controls/Panel.cs index a1bb80d8..2ccb8094 100644 --- a/Source.GUI.Controls/Panel.cs +++ b/Source.GUI.Controls/Panel.cs @@ -2756,6 +2756,7 @@ public virtual void Dispose() { } #if GMOD_DLL + SetDrawOnTop(false); ClearLuaReferences(); #endif VGui.PanelDeleted(this); diff --git a/Source.MaterialSystem/Material.cs b/Source.MaterialSystem/Material.cs index eb486894..9502c2f8 100644 --- a/Source.MaterialSystem/Material.cs +++ b/Source.MaterialSystem/Material.cs @@ -181,7 +181,29 @@ private bool InitializeRenderState() { } private void SetupErrorShader() { - throw new NotImplementedException(); + int flags = 0; + if (ShaderParams != null && ShaderParams[(int)ShaderMaterialVars.Flags] != null) + flags = ShaderParams[(int)ShaderMaterialVars.Flags].GetIntValue() & (int)MaterialVarFlags.Model; + + CleanUpShaderParams(); + CleanUpMaterialProxy(); + + Shader = materials.ShaderSystem.FindShader(MissingShaderName()); + Assert(Shader); + + VarCount = Shader!.GetNumParams(); + ShaderParams = new IMaterialVar[VarCount]; + + for (int i = 0; i < VarCount; ++i) + ShaderParams[i] = new MaterialVar(this, Shader.GetParamName(i)); + + SetMaterialVarFlags((MaterialVarFlags)flags, true); + + materials.ShaderSystem.InitShaderParameters(Shader, ShaderParams, "Error", null); + + materials.ShaderSystem.InitShaderInstance(Shader, ShaderParams, "Error", GetTextureGroupName()); + + InitializeRenderState(); } static readonly ConVarRef mat_reduceparticles = new("mat_reduceparticles"); diff --git a/Source.SDLSystem/SDL3_System.cs b/Source.SDLSystem/SDL3_System.cs index cf364d52..9d6767e6 100644 --- a/Source.SDLSystem/SDL3_System.cs +++ b/Source.SDLSystem/SDL3_System.cs @@ -128,8 +128,9 @@ public unsafe void SetClipboardText(ReadOnlySpan text) { SDL3.SDL_SetClipboardText(""); nuint bytes = (nuint)Encoding.UTF8.GetByteCount(text); - byte* rawData = (byte*)NativeMemory.Alloc(bytes); + byte* rawData = (byte*)NativeMemory.Alloc(bytes + 1); Encoding.UTF8.GetBytes(text, new Span(rawData, (int)bytes)); + rawData[bytes] = 0; SDL3.SDL_SetClipboardText(rawData); NativeMemory.Free(rawData); } diff --git a/Source.ShaderAPI.Gl46/ShaderSystem.cs b/Source.ShaderAPI.Gl46/ShaderSystem.cs index 66c1ae25..3b75126a 100644 --- a/Source.ShaderAPI.Gl46/ShaderSystem.cs +++ b/Source.ShaderAPI.Gl46/ShaderSystem.cs @@ -576,7 +576,7 @@ private void ProcessSource(StringBuilder sb, ReadOnlySpan source, int file } private unsafe bool LoadCachedProgram(ShaderCompileJob job) { - using IFileHandle? handle = FileSystem.Open(job.CachePath, FileOpenOptions.Read | FileOpenOptions.Binary, "MOD"); + using IFileHandle? handle = FileSystem.Open(job.CachePath, FileOpenOptions.Read | FileOpenOptions.Binary, "DEFAULT_WRITE_PATH"); if (handle == null || handle.Stream.Length <= sizeof(int)) return false; diff --git a/Source.StudioRender/StudioRenderContext.cs b/Source.StudioRender/StudioRenderContext.cs index 0eeb865a..26bdcb7e 100644 --- a/Source.StudioRender/StudioRenderContext.cs +++ b/Source.StudioRender/StudioRenderContext.cs @@ -246,7 +246,7 @@ private void R_StudioCreateSingleMesh(StudioHeader studioHdr, StudioLODData stud meshData.MeshGroup = new StudioMeshGroup[vtxMesh.NumStripGroups]; for (int i = 0; i < vtxMesh.NumStripGroups; ++i) { - OptimizedModel.StripGroupHeader stripGroup = vtxMesh.StripGroup(i); + OptimizedModel.StripGroupHeader stripGroup = vtxMesh.StripGroup(i, studioHdr.Version); StudioMeshGroup meshGroup = meshData.MeshGroup[i] = new(); meshGroup.MeshNeedsRestore = false; From 6046ef2d7c495f2b82d77cee01db2c33205b2cfe Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 29 Oct 2026 10:31:39 +0000 Subject: [PATCH 6/8] More hooks/methods --- Game.Client/C_BaseEntity.cs | 6 +- Game.Client/GarrysMod/C_GMOD_Player.cs | 93 +++++++- Game.Client/GarrysMod/HudGMod.cs | 66 ++++++ Game.Client/HLClient.cs | 6 + Game.Client/HistoryResource.cs | 2 + Game.Server/BaseCombatCharacter.cs | 12 ++ Game.Server/BaseCombatWeapon.cs | 6 + Game.Server/BaseEntity.cs | 24 +++ Game.Server/Client.cs | 11 +- Game.Server/GarrysMod/GMOD_Player.cs | 15 +- Game.Server/HL2/HL2_Player.cs | 12 ++ Game.Server/Player.cs | 40 +++- Game.Shared/BasePlayerShared.cs | 18 ++ Game.Shared/GarrysMod/GMODGameRules.cs | 40 +++- Game.Shared/GarrysMod/GarrysMod.cs | 24 +++ Game.Shared/GarrysMod/LuaEntity.cs | 66 ++++++ Game.Shared/GarrysMod/LuaPlayer.cs | 44 ++++ Game.Shared/GarrysMod/LuaTakeDamageInfo.cs | 236 ++++++++++++++++++++ Game.Shared/GarrysMod/LuaUserCmd.cs | 240 +++++++++++++++++++++ Game.Shared/GarrysMod/SENT_Anim.cs | 153 +++++++++++++ Game.Shared/HL2MP/HL2MPGameRules.cs | 15 ++ Game.Shared/MultiplayRules.cs | 14 +- Game.Shared/SoundPatch.cs | 15 +- Source.GUI.Controls/Panel.cs | 57 ++++- Source.GUI.Controls/TextEntry.cs | 33 ++- 25 files changed, 1223 insertions(+), 25 deletions(-) create mode 100644 Game.Shared/GarrysMod/LuaTakeDamageInfo.cs create mode 100644 Game.Shared/GarrysMod/LuaUserCmd.cs diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs index 2ecf73f3..7b103024 100644 --- a/Game.Client/C_BaseEntity.cs +++ b/Game.Client/C_BaseEntity.cs @@ -1297,6 +1297,10 @@ public virtual bool IsTransparent() { } public virtual void UpdateOnRemove() { +#if GMOD_DLL + if (GetRefEHandle().Index != Constants.INVALID_EHANDLE_INDEX) + garrysmod.EntityRemoved(this, DestroyedOnRecreateEntities); +#endif VPhysicsDestroyObject(); Assert(GetMoveParent() == null); @@ -3561,7 +3565,7 @@ public bool GetShadowCastDistance(ref float dist, ShadowType shadowType) { EHANDLE ShadowDirUseOtherEntity = new(); - public bool GetShadowCastDirection(ref Vector3 direction, ShadowType shadowType) { + public virtual bool GetShadowCastDirection(ref Vector3 direction, ShadowType shadowType) { if (ShadowDirUseOtherEntity.Get() != null) return ShadowDirUseOtherEntity.Get()!.GetShadowCastDirection(ref direction, shadowType); return false; diff --git a/Game.Client/GarrysMod/C_GMOD_Player.cs b/Game.Client/GarrysMod/C_GMOD_Player.cs index e5497824..30741574 100644 --- a/Game.Client/GarrysMod/C_GMOD_Player.cs +++ b/Game.Client/GarrysMod/C_GMOD_Player.cs @@ -5,10 +5,13 @@ using Source.Common; using Source.Common.Commands; using Source.Common.GarrysMod.Lua; +using Source.Common.Hashing; using Source.Common.Mathematics; using System.Numerics; +using ClientModelRenderInfo = Source.Common.Engine.ModelRenderInfo; + namespace Game.Client.GarrysMod; [LinkEntityToClass("player")] @@ -24,7 +27,7 @@ public partial class C_GMOD_Player() : C_HL2MP_Player() nameof(PressedWidget), nameof(Driving), nameof(DrivingMode), - nameof(PlayerClass), + new(nameof(PlayerClass)) { Proxy = typeof(PlayerClassProxy) }, nameof(CanZoom), nameof(CanWalk), nameof(IsTyping), @@ -112,6 +115,94 @@ public virtual void SetWeaponColor(in Vector3 color) { return ent; } + private static void RecvProxy_PlayerClass(ref readonly RecvProxyData data, object instance, IFieldAccessor field) { + RecvProxy_Int32ToInt32(in data, instance, field); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerClassChanged)) { + C_GMOD_Player player = (C_GMOD_Player)instance; + LuaEntity.Push_Entity(player); + g_Lua!.PushNumber(player.PlayerClass); + gGM.CallNoReturns(2); + } + } + + public static class PlayerClassProxy + { + public static void Recv(ref readonly RecvProxyData data, object instance, IFieldAccessor field) => RecvProxy_PlayerClass(in data, instance, field); + } + + InlineArray128 UniqueID; + + static uint UniqueIDCRC(ReadOnlySpan str) { + Span bytes = stackalloc byte[str.Length]; + for (int i = 0; i < str.Length; i++) + bytes[i] = (byte)str[i]; + uint crc = 0; + CRC32.Init(ref crc); + CRC32.ProcessBuffer(ref crc, (ReadOnlySpan)bytes); + CRC32.Final(ref crc); + return crc; + } + + public ReadOnlySpan GetUniqueID() { + if (gpGlobals.MaxClients == 1) + return "1"; + + if ((GetFlags() & EntityFlags.FakeClient) != 0) { + ReadOnlySpan name = g_pPlayerResource == null ? "" : g_pPlayerResource.GetPlayerName(EntIndex()); + if (name.IsEmpty) + return "0"; + sprintf(UniqueID, "%u").U(UniqueIDCRC(name)); + return ((Span)UniqueID).SliceNullTerminatedString(); + } + + if (stricmp(GetNetworkIDString(), "STEAM_ID_LAN") == 0) { + if (engine.GetNetChannelInfo() == null) + return "PENDING"; + } + else if (stricmp(GetNetworkIDString(), "STEAMID_PENDING") == 0 || stricmp(GetNetworkIDString(), "STEAM_ID_PENDING") == 0) + return "PENDING"; + + Span gmID = stackalloc char[128]; + sprintf(gmID, "gm_%s_gm").S(GetNetworkIDString()); + sprintf(UniqueID, "%u").U(UniqueIDCRC(gmID.SliceNullTerminatedString())); + return ((Span)UniqueID).SliceNullTerminatedString(); + } + + sbyte PrePlayerDrawDepth; + sbyte PostPlayerDrawDepth; + + protected override bool OnInternalDrawModel(ref ClientModelRenderInfo info) { + if (PrePlayerDrawDepth < 11) { + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PrePlayerDraw)) { + LuaEntity.Push_Entity(this); + g_Lua!.PushNumber((int)info.Flags); + PrePlayerDrawDepth++; + bool ret = gGM.CallFinish(2); + PrePlayerDrawDepth--; + if (ret) + return false; + } + } + else + g_Lua!.ErrorNoHalt("PrePlayerDraw: We are 10 layers deep, runaway infinite loop?"); + return base.OnInternalDrawModel(ref info); + } + + protected override bool OnPostInternalDrawModel(ref ClientModelRenderInfo info) { + if (PostPlayerDrawDepth > 10) { + g_Lua!.ErrorNoHalt("PostPlayerDraw: We are 10 layers deep, runaway infinite loop?"); + return true; + } + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostPlayerDraw)) { + LuaEntity.Push_Entity(this); + g_Lua!.PushNumber((int)info.Flags); + PostPlayerDrawDepth++; + gGM.CallNoReturns(2); + PostPlayerDrawDepth--; + } + return true; + } + public override void UpdateClientSideAnimation() { if (Driving.Get() != null) { if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDriveAnimate)) { diff --git a/Game.Client/GarrysMod/HudGMod.cs b/Game.Client/GarrysMod/HudGMod.cs index 9cdace82..5ad08a47 100644 --- a/Game.Client/GarrysMod/HudGMod.cs +++ b/Game.Client/GarrysMod/HudGMod.cs @@ -1,6 +1,8 @@ using Game.Client.HUD; using Game.Shared; +using Source; +using Source.Common.Bitbuffers; using Source.Common.GUI; using Source.Engine; using Source.GUI.Controls; @@ -23,6 +25,70 @@ public HudGMod(string? elementName) : base(elementName, "GModHudHookAndUmsgRecei SetProportional(false); } + public override void Init() { + IHudElement.HookMessage("ItemPickup", MsgFunc_ItemPickup); + IHudElement.HookMessage("AmmoPickup", MsgFunc_AmmoPickup); + IHudElement.HookMessage("WeaponPickup", MsgFunc_WeaponPickup); + } + + struct PendingWeaponPickup + { + public uint Handle; + public TimeUnit_t Time; + } + + readonly List WeaponPickups = []; + + static void MsgFunc_WeaponPickup(bf_read msg) { + HudGMod? hud = (HudGMod?)gHUD.FindElement("CHudGMod"); + if (hud == null || g_Lua == null) + return; + uint handle = (uint)msg.ReadLong(); + hud.WeaponPickups.Add(new() { Handle = handle, Time = gpGlobals.CurTime }); + } + + public override void OnThink() { + for (int i = 0; i < WeaponPickups.Count; i++) { + C_BaseEntity? ent = cl_entitylist.GetBaseEntityFromHandle(new ClientEntityHandle(WeaponPickups[i].Handle)); + if (ent != null && ent.IsBaseCombatWeapon()) { + if (g_Lua != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.HUDWeaponPickedUp)) { + LuaEntity.Push_Entity(ent); + gGM.CallNoReturns(1); + } + WeaponPickups.RemoveAt(i); + return; + } + if (gpGlobals.CurTime - WeaponPickups[i].Time > 5.0) { + WeaponPickups.RemoveAt(i); + return; + } + } + } + + static void MsgFunc_ItemPickup(bf_read msg) { + if (gHUD.FindElement("CHudGMod") == null) + return; + Span name = stackalloc char[256]; + msg.ReadString(name); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.HUDItemPickedUp)) { + g_Lua!.PushString(name.SliceNullTerminatedString()); + gGM.CallNoReturns(1); + } + } + + static void MsgFunc_AmmoPickup(bf_read msg) { + if (gHUD.FindElement("CHudGMod") == null || g_Lua == null) + return; + Span name = stackalloc char[128]; + msg.ReadString(name); + short count = msg.ReadShort(); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.HUDAmmoPickedUp)) { + g_Lua.PushString(name.SliceNullTerminatedString()); + g_Lua.PushNumber(count); + gGM.CallNoReturns(2); + } + } + void IHudElement.VidInit() => ((IHudElement)this).Reset(); void IHudElement.Reset() => SetSize(ScreenWidth(), ScreenHeight()); diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index 22f2fa46..ef108e2a 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -283,6 +283,12 @@ public void View_Render(ViewRects rects) { ref ViewRect rect = ref rects[0]; if (rect.Width == 0 || rect.Height == 0) return; +#if GMOD_DLL + using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreRender) && gGM.CallFinish(0) && !enginevgui.IsGameUIVisible()) + return; +#endif view.Render(rects); } diff --git a/Game.Client/HistoryResource.cs b/Game.Client/HistoryResource.cs index 00a02826..6d4e62c1 100644 --- a/Game.Client/HistoryResource.cs +++ b/Game.Client/HistoryResource.cs @@ -66,7 +66,9 @@ public override void ApplySchemeSettings(IScheme scheme) { public override void Init() { IHudElement.HookMessage("SWEPCmd", MsgFunc_SWEPCmd); +#if !GMOD_DLL IHudElement.HookMessage("ItemPickup", MsgFunc_ItemPickup); +#endif IHudElement.HookMessage("AmmoDenied", MsgFunc_AmmoDenied); Reset(); } diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 16d38f89..5d6bc240 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -775,6 +775,18 @@ public int GiveAmmo(int count, ReadOnlySpan name, bool suppressSound = fal return GiveAmmo(count, ammoType, suppressSound); } + public void ClearActiveWeapon() => SetActiveWeapon(null); + + public void RemoveAllWeapons() { + ClearActiveWeapon(); + for (int i = 0; i < MAX_WEAPONS; i++) { + if (MyWeapons[i].Get() != null) { + MyWeapons[i].Get()!.Delete(); + MyWeaponsForModify()[i].Set(null); + } + } + } + public void SetActiveWeapon(BaseCombatWeapon? newWeapon) { BaseCombatWeapon? oldWeapon = ActiveWeapon.Get(); if (newWeapon != oldWeapon) { diff --git a/Game.Server/BaseCombatWeapon.cs b/Game.Server/BaseCombatWeapon.cs index 38a95028..020f6e37 100644 --- a/Game.Server/BaseCombatWeapon.cs +++ b/Game.Server/BaseCombatWeapon.cs @@ -186,6 +186,12 @@ public virtual SCOND_t WeaponRangeAttack1Condition(float dot, float dist) { public virtual SCOND_t WeaponMeleeAttack1Condition(float dot, float dist) => SCOND_t.COND_NONE; public virtual SCOND_t WeaponMeleeAttack2Condition(float dot, float dist) => SCOND_t.COND_NONE; + public virtual void Delete() { + SetTouch(null); + SetThink(SUB_Remove); + SetNextThink(gpGlobals.CurTime + 0.1f); + } + public BaseEntity? Respawn() { BaseEntity? newWeapon = Create(GetClassname(), g_pGameRules.VecWeaponRespawnSpot(this), GetLocalAngles(), GetOwnerEntity()); diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 821a29df..840e9d8d 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -5,6 +5,8 @@ using Source; using Source.Common; using Source.Common.GarrysMod; +using Source.Common.GarrysMod.Lua; +using Game.Server.GarrysMod; using Source.Common.Audio; using Source.Common.Commands; using Source.Common.Engine; @@ -935,6 +937,9 @@ public virtual void UpdateOnRemove() { Util.g_bReceivedChainedUpdateOnRemove = true; #if GMOD_DLL + if (GetRefEHandle().Index != Constants.INVALID_EHANDLE_INDEX) + garrysmod.EntityRemoved(this, false); + for (int i = 0; i < DeleteOnRemoveList.Count; i++) { BaseEntity? ent = DeleteOnRemoveList[i].Get(); if (ent == null) @@ -2110,6 +2115,24 @@ public int TakeDamage(in TakeDamageInfo inputInfo) { else { TakeDamageInfo info = inputInfo; +#if GMOD_DLL + TakeDamageInfoRef infoRef = new() { Info = info }; + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.EntityTakeDamage)) { + LuaEntity.Push_Entity(this); + LuaTakeDamageInfo.Push_TakeDamageInfo(infoRef); + if (gGM.CallFinish(2)) + return 0; + } + + int ret = OnTakeDamage(infoRef.Info); + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostEntityTakeDamage)) { + LuaEntity.Push_Entity(this); + LuaTakeDamageInfo.Push_TakeDamageInfo(infoRef); + g_Lua!.PushBool(ret != 0); + gGM.CallNoReturns(3); + } + return ret; +#else // Scale the damage by the attacker's modifier. if (info.GetAttacker() != null) info.ScaleDamage(info.GetAttacker()!.GetAttackDamageScale(this)); @@ -2120,6 +2143,7 @@ public int TakeDamage(in TakeDamageInfo inputInfo) { //Msg("%s took %.2f Damage, at %.2f\n", GetClassname(), info.GetDamage(), gpGlobals.curtime ); return OnTakeDamage(info); +#endif } return 0; } diff --git a/Game.Server/Client.cs b/Game.Server/Client.cs index 0e230b6d..c7308697 100644 --- a/Game.Server/Client.cs +++ b/Game.Server/Client.cs @@ -2,6 +2,7 @@ using Game.Server.GarrysMod; using Game.Shared; +using Game.Shared.GarrysMod; using Source; using Source.Common; @@ -134,8 +135,16 @@ static void kill_helper(in TokenizedCommand args, bool explode) { // TODO: } //else { BasePlayer? player = Util.GetCommandClient(); - if (player != null) + if (player != null) { +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.CanPlayerSuicide)) { + LuaEntity.Push_Entity(player); + if (!gGM.CallFinish(1)) + return; + } +#endif player.CommitSuicide(explode); + } //} } diff --git a/Game.Server/GarrysMod/GMOD_Player.cs b/Game.Server/GarrysMod/GMOD_Player.cs index 71dd150d..d4ba9e61 100644 --- a/Game.Server/GarrysMod/GMOD_Player.cs +++ b/Game.Server/GarrysMod/GMOD_Player.cs @@ -141,12 +141,17 @@ public override void Spawn() { } public override BaseEntity EntSelectSpawnPoint() { - BaseEntity? spot = null; - while ((spot = gEntList.FindEntityByClassname(spot, "info_player_start")) != null) { - if (spot.HasSpawnFlags(1)) - return spot; +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerSelectSpawn)) { + LuaEntity.Push_Entity(this); + g_Lua!.PushBool(Transition); + if (gGM.CallReturns(2, 1)) { + BaseEntity? spot = (BaseEntity?)g_Lua.GetReturn(0).GetEntity(); + if (spot != null) + return spot; + } } - +#endif return base.EntSelectSpawnPoint(); } diff --git a/Game.Server/HL2/HL2_Player.cs b/Game.Server/HL2/HL2_Player.cs index 1e7ea83e..5a8bd41e 100644 --- a/Game.Server/HL2/HL2_Player.cs +++ b/Game.Server/HL2/HL2_Player.cs @@ -5,6 +5,7 @@ using Source.Common; using Source.Common.Commands; using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; using Source.Common.Mathematics; using Source.Common.Physics; using Source; @@ -469,6 +470,17 @@ public override void PlayerUse() { // Found an object if (useEntity != null) { +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerUse)) { + Game.Server.GarrysMod.LuaEntity.Push_Entity(this); + Game.Server.GarrysMod.LuaEntity.Push_Entity(useEntity); + if (gGM.CallReturns(2, 1)) { + ILuaObject ret = g_Lua!.GetReturn(0); + if (ret.GetType() == LuaType.Bool && !ret.GetBool()) + return; + } + } +#endif //!!!UNDONE: traceline here to prevent +USEing buttons through walls EntityCapabilities caps = useEntity.ObjectCaps(); Variant_t emptyVariant = default; diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index 2a22162c..53203e2d 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -8,6 +8,7 @@ using Source.Common.Commands; using Source.Common.Engine; using Source.Common.Formats.BSP; +using Source.Common.GarrysMod.Lua; using Source.Common.Game.Server; using Source.Common.Hashing; using Source.Common.Mathematics; @@ -698,6 +699,22 @@ public virtual void EquipSuit(bool playEffects = false) { Local.WearingSuit = true; } + public void RemoveAllItems(bool removeSuit) { + if (GetActiveWeapon() != null) { + ResetAutoaim(); + GetActiveWeapon()!.Holster(); + } + + Weapon_SetLast(null); + RemoveAllWeapons(); + RemoveAllAmmo(); + + if (removeSuit) + RemoveSuit(); + + UpdateClientData(); + } + public virtual void RemoveSuit() { Local.WearingSuit = false; } @@ -962,7 +979,14 @@ public virtual void ImpulseCommands() { } if (tr.Fraction != 1.0) { // line hit something, so paint a decal - // todo +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerSpray)) { + Game.Server.GarrysMod.LuaEntity.Push_Entity(this); + if (gGM.CallFinish(1)) + break; + } +#endif + // todo } break; @@ -1119,6 +1143,20 @@ public virtual void CreateViewModel(int index = 0) { } } + public void DestroyViewModels() { + int i; + for (i = MAX_VIEWMODELS - 1; i >= 0; i--) { + BaseViewModel? vm = GetViewModel(i); + if (vm == null) + continue; + + Util.Remove(vm); + ViewModelForModify()[i].Set(null); + } + } + + public void SetConnected(PlayerConnectedState connected) => Connected = connected; + public TimeUnit_t GetDeathTime() => DeathTime; public virtual void SetAnimation(PlayerAnim playerAnim) { } // todo diff --git a/Game.Shared/BasePlayerShared.cs b/Game.Shared/BasePlayerShared.cs index 32433c15..0c8796fe 100644 --- a/Game.Shared/BasePlayerShared.cs +++ b/Game.Shared/BasePlayerShared.cs @@ -31,6 +31,14 @@ namespace Game.Server; using Source.Common.Audio; using Source.Common.Formats.BSP; using Source.Common.SoundEmitterSystem; +#if GMOD_DLL +using Source.Common.GarrysMod.Lua; +#if CLIENT_DLL +using Game.Client.GarrysMod; +#else +using Game.Server.GarrysMod; +#endif +#endif using System.Runtime.CompilerServices; @@ -416,6 +424,16 @@ public void SelectItem(ReadOnlySpan str, int subtype) { public override bool Weapon_Switch(BaseCombatWeapon? weapon, int viewmodelindex = 0) { BaseCombatWeapon? lastWeapon = GetActiveWeapon(); +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerSwitchWeapon)) { + LuaEntity.Push_Entity(this); + LuaEntity.Push_Entity(lastWeapon); + LuaEntity.Push_Entity(weapon); + if (gGM.CallFinish(3)) + return false; + } +#endif + if (base.Weapon_Switch(weapon, viewmodelindex)) { if (lastWeapon != null && Weapon_ShouldSetLast(lastWeapon, GetActiveWeapon())) Weapon_SetLast(lastWeapon.GetLastWeapon()); diff --git a/Game.Shared/GarrysMod/GMODGameRules.cs b/Game.Shared/GarrysMod/GMODGameRules.cs index 7cd7dd36..bcadcdee 100644 --- a/Game.Shared/GarrysMod/GMODGameRules.cs +++ b/Game.Shared/GarrysMod/GMODGameRules.cs @@ -16,9 +16,11 @@ namespace Game.Server.GarrysMod; using Source.Common; using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; using Source; using Game.Shared; +using Game.Shared.GarrysMod; using Source.GUI.Controls; public static class GMOD_GameRules_Globals @@ -95,7 +97,43 @@ public override bool FlPlayerFallDeathDoesScreenFade(BasePlayer player) { return base.FlPlayerFallDeathDoesScreenFade(player); } public override float FlPlayerFallDamage(BasePlayer player) { - return 10; // todo: lua hook + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.GetFallDamage)) { + LuaEntity.Push_Entity(player); + g_Lua!.PushNumber(player.Local.FallVelocity); + if (gGM.CallReturns(2, 1)) + return g_Lua.GetReturn(0).GetFloat(); + } + return 10; + } + + public override void ClientDisconnected(Edict client) { + BasePlayer? player = (BasePlayer?)BaseEntity.Instance(client); + if (player != null && player.IsPlayer()) { + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDisconnected)) { + LuaEntity.Push_Entity(player); + gGM.CallNoReturns(1); + } + base.ClientDisconnected(client); + } + } + + public override void DeathNotice(BasePlayer victim, in TakeDamageInfo info) { + if (gGM == null || !gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerDeath)) + return; + LuaEntity.Push_Entity(victim); + LuaEntity.Push_Entity(info.GetInflictor()); + LuaEntity.Push_Entity(info.GetAttacker()); + gGM.CallNoReturns(3); + } + + public override bool CanHaveItem(BasePlayer player, Item item) { + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerCanPickupItem)) { + LuaEntity.Push_Entity(player); + LuaEntity.Push_Entity(item); + if (!gGM.CallFinish(2)) + return false; + } + return true; } public override void InitDefaultAIRelationships() { diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index dc09ee62..2b33db07 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -618,6 +618,30 @@ public void EntityCreated(BaseEntity? ent) { gGM.CallNoReturns(1); } + public void EntityRemoved(BaseEntity ent, bool fullUpdate) { + SoundEnvelopeController.GetController().ShutdownSoundsForEntity(ent.EntIndex()); + if (g_Lua == null || gGM == null) + return; + + if (gGM.CallWithArgs((int)LUA_POOLEDSTRING.EntityRemoved)) { +#if CLIENT_DLL + LuaEntity.Push_Entity(ent); +#else + Game.Server.GarrysMod.LuaEntity.Push_Entity(ent); +#endif + g_Lua.PushBool(fullUpdate); + gGM.CallNoReturns(2); + } + ResetLuaIteratorEntityCache(ent); +#if !CLIENT_DLL + if (ent.IsPlayer()) { + ent.GetLuaTable()?.UnReference(); + ent.GetLuaEntity()?.UnReference(); + } + Game.Server.GarrysMod.LuaNetworkedVars.g_LuaNetworkedVars?.ClearEntity(ent.GetRefEHandle().Index); +#endif + } + public void Think() { if (g_Lua != null) { // CheckForFilesystemChanges(); diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 3074e389..2700c8e9 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -1312,6 +1312,57 @@ static int Entity__GetPos(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__LocalToWorld(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Vector3 local = LuaVector.Get_Vector(2); + Vector3 world; + if (ent.GetAbsAngles() == vec3_angle) + world = local + ent.GetAbsOrigin(); + else + MathLib.VectorTransform(local, ent.EntityToWorldTransform(), out world); + LuaVector.Push_Vector(world); + return 1; + } + + [LuaMethod] + static int Entity__WorldToLocal(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Vector3 world = LuaVector.Get_Vector(2); + Vector3 local; + if (ent.GetAbsAngles() == vec3_angle) + local = world - ent.GetAbsOrigin(); + else + MathLib.VectorITransform(world, ent.EntityToWorldTransform(), out local); + LuaVector.Push_Vector(local); + return 1; + } + + [LuaMethod] + static int Entity__LocalToWorldAngles(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + QAngle local = LuaAngle.Get_Angle(2); + LuaAngle.Push_Angle(MathLib.TransformAnglesToWorldSpace(local, ent.EntityToWorldTransform())); + return 1; + } + + [LuaMethod] + static int Entity__WorldToLocalAngles(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + QAngle world = LuaAngle.Get_Angle(2); + LuaAngle.Push_Angle(MathLib.TransformAnglesToLocalSpace(world, ent.EntityToWorldTransform())); + return 1; + } + +#if GAME_DLL + [LuaMethod] + static int Entity__IsInWorld(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushBool(engine.GetClusterForOrigin(ent.GetAbsOrigin()) != -1); + return 1; + } +#endif + [LuaMethod] static int Entity__GetMoveType(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -1436,6 +1487,21 @@ static int Entity__ResetSequence(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Entity__GetSpawnFlags(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + lua.PushNumber(ent.SpawnFlags); + return 1; + } + + [LuaMethod] + static int Entity__HasSpawnFlags(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + int flags = (int)lua.CheckNumber(2); + lua.PushBool((ent.SpawnFlags & flags) != 0); + return 1; + } + [LuaMethod] static int Entity__GetSkin(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index fefbab93..c3727ace 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -743,6 +743,50 @@ static int Player__Team(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__GetCurrentCommand(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + if (player.CurrentCommand.IsNull) { + lua.ErrorNoHalt("Player:GetCurrentCommand called outside of command/prediction\n"); + return 0; + } + LuaUserCmd.Push_CurrentCommand(player.CurrentCommand.Get()); + return 1; + } + +#if CLIENT_DLL + [LuaMethod] + static int Player__UniqueID(ILuaInterface lua) { + GMOD_Player player = (GMOD_Player)Get_Player(1, false)!; + lua.PushString(player.GetUniqueID()); + return 1; + } +#endif + +#if GAME_DLL + [LuaMethod] + static int Player__SetTeam(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + int team = (int)lua.CheckNumber(2); + if (gpGlobals.MaxClients > 1 && (team < short.MinValue || team > short.MaxValue)) + lua.ErrorNoHalt($"Out of bounds value {team} for networking in range {short.MinValue} to {short.MaxValue}\n"); + player.ChangeTeam(team); + return 0; + } + + [LuaMethod] + static int Player__SendLua(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + ReadOnlySpan code = lua.CheckString(2); + if (stristr(code, "while true do end").IsEmpty) { + Game.Server.RecipientFilter filter = new Game.Server.SingleUserRecipientFilter(player); + filter.MakeReliable(); + Game.Client.GarrysMod.GarrysMod.BroadcastLua(filter, code); + } + return 0; + } +#endif + [LuaMethod] static int Player__Armor(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaTakeDamageInfo.cs b/Game.Shared/GarrysMod/LuaTakeDamageInfo.cs new file mode 100644 index 00000000..1b3ed287 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaTakeDamageInfo.cs @@ -0,0 +1,236 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public class TakeDamageInfoRef +{ + public TakeDamageInfo Info; +} + +public static partial class LuaTakeDamageInfo +{ + [LuaClass(typeof(TakeDamageInfoRef), NullError = "Tried to use a NULL CTakeDamageInfo!")] + public static readonly LuaClass LC_TakeDamageInfo = new("CTakeDamageInfo", LuaType.DamageInfo, null, null); + + public static void Push_TakeDamageInfo(TakeDamageInfoRef? info) => LC_TakeDamageInfo.Push(info); + + public static ref TakeDamageInfo Get_TakeDamageInfo(int stackPos) { + TakeDamageInfoRef? info = LC_TakeDamageInfo.Get(stackPos) as TakeDamageInfoRef; + if (info == null) + g_Lua!.Error("Tried to use a NULL CTakeDamageInfo!"); + return ref info!.Info; + } + + [LuaGlobal] + static int DamageInfo(ILuaInterface lua) { + Push_TakeDamageInfo(new TakeDamageInfoRef { Info = new() }); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__AddDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).AddDamage((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__SubtractDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).SubtractDamage((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__ScaleDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).ScaleDamage((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetAmmoType(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetAmmoType()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetAmmoType(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetAmmoType((int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetAttacker(ILuaInterface lua) { + LuaEntity.Push_Entity(Get_TakeDamageInfo(1).GetAttacker()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetAttacker(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetAttacker(LuaEntity.Get_Entity(2, true)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetInflictor(ILuaInterface lua) { + LuaEntity.Push_Entity(Get_TakeDamageInfo(1).GetInflictor()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetInflictor(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetInflictor(LuaEntity.Get_Entity(2, true)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetWeapon(ILuaInterface lua) { + LuaEntity.Push_Entity(Get_TakeDamageInfo(1).GetWeapon()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetWeapon(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetWeapon(LuaEntity.Get_Entity(2, true)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetBaseDamage(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetBaseDamage()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetBaseDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).BaseDamage = (float)lua.GetNumber(2); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamage(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetDamage()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetDamage((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetMaxDamage(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetMaxDamage()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetMaxDamage(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetMaxDamage((float)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamageBonus(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetDamageBonus()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamageBonus(ILuaInterface lua) { + Get_TakeDamageInfo(1).DamageBonus = (float)lua.GetNumber(2); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamageCustom(ILuaInterface lua) { + lua.PushNumber(Get_TakeDamageInfo(1).GetDamageCustom()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamageCustom(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetDamageCustom((int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamageForce(ILuaInterface lua) { + LuaVector.Push_Vector(Get_TakeDamageInfo(1).GetDamageForce()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamageForce(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetDamageForce(LuaVector.Get_Vector(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamagePosition(ILuaInterface lua) { + LuaVector.Push_Vector(Get_TakeDamageInfo(1).GetDamagePosition()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamagePosition(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetDamagePosition(LuaVector.Get_Vector(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetReportedPosition(ILuaInterface lua) { + LuaVector.Push_Vector(Get_TakeDamageInfo(1).GetReportedPosition()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetReportedPosition(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetReportedPosition(LuaVector.Get_Vector(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__GetDamageType(ILuaInterface lua) { + lua.PushNumber((int)Get_TakeDamageInfo(1).GetDamageType()); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__SetDamageType(ILuaInterface lua) { + Get_TakeDamageInfo(1).SetDamageType((DamageType)(int)lua.GetNumber(2)); + return 0; + } + + [LuaMethod] + static int CTakeDamageInfo__IsDamageType(ILuaInterface lua) { + ref TakeDamageInfo info = ref Get_TakeDamageInfo(1); + lua.PushBool(((int)info.GetDamageType() & (int)lua.GetNumber(2)) != 0); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__IsBulletDamage(ILuaInterface lua) { + lua.PushBool((Get_TakeDamageInfo(1).GetDamageType() & DamageType.Bullet) != 0); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__IsExplosionDamage(ILuaInterface lua) { + lua.PushBool((Get_TakeDamageInfo(1).GetDamageType() & DamageType.Blast) != 0); + return 1; + } + + [LuaMethod] + static int CTakeDamageInfo__IsFallDamage(ILuaInterface lua) { + lua.PushBool((Get_TakeDamageInfo(1).GetDamageType() & DamageType.Fall) != 0); + return 1; + } +} +#endif diff --git a/Game.Shared/GarrysMod/LuaUserCmd.cs b/Game.Shared/GarrysMod/LuaUserCmd.cs new file mode 100644 index 00000000..28d0ae26 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaUserCmd.cs @@ -0,0 +1,240 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source; +using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaUserCmd +{ + [LuaClass(typeof(AnonymousSafeFieldPointer), NullError = "Tried to use a NULL CUserCmd!")] + public static readonly LuaClass LC_UserCmd = new("CUserCmd", LuaType.UserCmd, null, null); + + class UserCmdRef + { + public UserCmd Cmd; + public AnonymousSafeFieldPointer Ptr => new(this, static o => ref ((UserCmdRef)o).Cmd); + } + + static readonly UserCmdRef CurrentCommandCopy = new(); + + public static void Push_UserCmd(AnonymousSafeFieldPointer cmd) => LC_UserCmd.Push(cmd); + + public static ref UserCmd Get_UserCmd(int stackPos) { + if (LC_UserCmd.Get(stackPos) is not AnonymousSafeFieldPointer cmd || cmd.IsNull) { + g_Lua!.Error("Tried to use a NULL CUserCmd!"); + return ref UserCmd.NULL; + } + return ref cmd.Get(); + } + + public static void Push_CurrentCommand(in UserCmd cmd) { + CurrentCommandCopy.Cmd = cmd; + Push_UserCmd(CurrentCommandCopy.Ptr); + } + + [LuaMethod] + static int CUserCmd__AddKey(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.Buttons |= (InButtons)(int)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__RemoveKey(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.Buttons &= ~(InButtons)(int)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__KeyDown(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + lua.PushBool((cmd.Buttons & (InButtons)(int)lua.CheckNumber(2)) != 0); + return 1; + } + + [LuaMethod] + static int CUserCmd__ClearButtons(ILuaInterface lua) { + Get_UserCmd(1).Buttons = 0; + return 0; + } + + [LuaMethod] + static int CUserCmd__ClearMovement(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.ForwardMove = 0; + cmd.SideMove = 0; + cmd.UpMove = 0; + return 0; + } + + [LuaMethod] + static int CUserCmd__CommandNumber(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).CommandNumber); + return 1; + } + + [LuaMethod] + static int CUserCmd__TickCount(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).TickCount); + return 1; + } + + [LuaMethod] + static int CUserCmd__GetButtons(ILuaInterface lua) { + lua.PushNumber((int)Get_UserCmd(1).Buttons); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetButtons(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.Buttons = (InButtons)(int)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetForwardMove(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).ForwardMove); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetForwardMove(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.ForwardMove = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetSideMove(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).SideMove); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetSideMove(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.SideMove = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetUpMove(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).UpMove); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetUpMove(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.UpMove = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetImpulse(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).Impulse); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetImpulse(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.Impulse = (byte)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetMouseWheel(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).ScrollWheelSpeed); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetMouseWheel(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.ScrollWheelSpeed = (sbyte)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetMouseX(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).MouseDeltaX); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetMouseX(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.MouseDeltaX = (short)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetMouseY(ILuaInterface lua) { + lua.PushNumber(Get_UserCmd(1).MouseDeltaY); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetMouseY(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.MouseDeltaY = (short)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__GetViewAngles(ILuaInterface lua) { + LuaAngle.Push_Angle(Get_UserCmd(1).ViewAngles); + return 1; + } + + [LuaMethod] + static int CUserCmd__SetViewAngles(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + cmd.ViewAngles = LuaAngle.Get_Angle(2); + return 0; + } + + [LuaMethod] + static int CUserCmd__IsForced(ILuaInterface lua) { + lua.PushBool(Get_UserCmd(1).Forced); + return 1; + } + + [LuaMethod] + static int CUserCmd__SelectWeapon(ILuaInterface lua) { + ref UserCmd cmd = ref Get_UserCmd(1); + BaseCombatWeapon weapon = (BaseCombatWeapon)LuaEntity.Get_Entity(2, false)!; + cmd.WeaponSelect = weapon.EntIndex(); + cmd.WeaponSubtype = weapon.GetSubType(); + return 0; + } + + [LuaMethod] + static int CUserCmd__IsValid(ILuaInterface lua) { + lua.PushBool(LC_UserCmd.Get(1) is AnonymousSafeFieldPointer cmd && !cmd.IsNull); + return 1; + } + + [LuaMethod] + static int CUserCmd____tostring(ILuaInterface lua) { + if (LC_UserCmd.Get(1) is not AnonymousSafeFieldPointer cmd || cmd.IsNull) { + lua.PushString("CUserCmd [NULL]"); + return 1; + } + Span str = stackalloc char[256]; + sprintf(str, "CUserCmd [%i]").I(cmd.Get().CommandNumber); + lua.PushString(str.SliceNullTerminatedString()); + return 1; + } +} +#endif diff --git a/Game.Shared/GarrysMod/SENT_Anim.cs b/Game.Shared/GarrysMod/SENT_Anim.cs index c64a0714..ace1489a 100644 --- a/Game.Shared/GarrysMod/SENT_Anim.cs +++ b/Game.Shared/GarrysMod/SENT_Anim.cs @@ -1,5 +1,9 @@ #if (CLIENT_DLL || GAME_DLL) && GMOD_DLL +using System.Numerics; + using Source.Common; +using Source.Common.GarrysMod.Lua; +using Source.Common.Physics; using Game.Shared; using Source; @@ -47,6 +51,155 @@ public override void InitializeScriptedEntity(ReadOnlySpan name) { ScriptedEntity.StartLua(); } +#if GAME_DLL + public override void Use(BaseEntity? activator, BaseEntity? caller, UseType useType, float value) { + if (IsMarkedForDeletion() || !ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.Use)) + return; + LuaEntity.Push_Entity(activator); + LuaEntity.Push_Entity(caller); + g_Lua!.PushNumber((int)useType); + g_Lua.PushNumber(value); + ScriptedEntity.Call(4, 0); + } + + public override void Think() { + if (IsMarkedForDeletion()) + return; + if (!ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, true)) + SetNextThink(gpGlobals.CurTime + 0.2); + if (HasLuaTable() && GetLuaTable()!.GetMemberBool("AutomaticFrameAdvance", true)) { + StudioFrameAdvance(); + DispatchAnimEvents(this); + } + } + + public override void UpdateOnRemove() { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.OnRemove)) { + g_Lua!.PushBool(false); + ScriptedEntity.Call(1, 0); + } + base.UpdateOnRemove(); + } + + void CallEntityHook(LUA_POOLEDSTRING hook, BaseEntity? other) { + if (ScriptedEntity.StartFunction((int)hook)) { + LuaEntity.Push_Entity(other); + ScriptedEntity.Call(1, 0); + } + } + + public override int OnTakeDamage(in TakeDamageInfo info) { + if (IsMarkedForDeletion()) + return 0; + int ret = 0; + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.OnTakeDamage)) { + TakeDamageInfoRef infoRef = new() { Info = info }; + LuaTakeDamageInfo.Push_TakeDamageInfo(infoRef); + if (ScriptedEntity.Call(1, 1)) { + ILuaObject obj = g_Lua!.GetReturn(0); + if (obj.GetType() == LuaType.Number) + ret = obj.GetInt(); + } + } + return ret; + } + + public override void VPhysicsUpdate(IPhysicsObject physics) { + if (IsMarkedForDeletion()) + return; + base.VPhysicsUpdate(physics); + if (!physics.IsAsleep() && ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.PhysicsUpdate)) { + LuaPhysObj.Push_PhysObj(physics); + ScriptedEntity.Call(1, 0); + } + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.HandleAnimEvent)) { + g_Lua!.PushNumber(animEvent.Event); + g_Lua.PushNumber(animEvent.EventTime); + g_Lua.PushNumber(animEvent.Cycle); + g_Lua.PushNumber((int)animEvent.Type); + g_Lua.PushString(animEvent.Options ?? ""); + if (ScriptedEntity.Call(5, 1)) { + ILuaObject ret = g_Lua.GetReturn(0); + if (ret.GetType() == LuaType.Bool && ret.GetBool()) + return; + } + } + base.HandleAnimEvent(ref animEvent); + } + + public override void OnRestore() { + base.OnRestore(); + ScriptedEntity.StartLua(); + ScriptedEntity.CallFunction("OnRestore", true); + } + + public override void StartTouch(BaseEntity? other) => CallEntityHook(LUA_POOLEDSTRING.StartTouch, other); + public override void Touch(BaseEntity? other) => CallEntityHook(LUA_POOLEDSTRING.Touch, other); + public override void EndTouch(BaseEntity? other) => CallEntityHook(LUA_POOLEDSTRING.EndTouch, other); + public override void Blocked(BaseEntity? other) => CallEntityHook(LUA_POOLEDSTRING.Blocked, other); +#else + public override void UpdateOnRemove() { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.OnRemove)) { + g_Lua!.PushBool(DestroyedOnRecreateEntities); + ScriptedEntity.Call(1, 0); + } + base.UpdateOnRemove(); + } + + bool InDraw; + StudioFlags DrawFlags; + + public override int DrawModel(StudioFlags flags) { + if (!ShouldDraw()) + return 0; + if (InDraw) + return base.DrawModel(flags | DrawFlags); + + InDraw = true; + DrawFlags = flags & StudioFlags.ShadowDepthTexture; + if (ScriptedEntity.StartFunction((int)((flags & StudioFlags.Transparency) != 0 ? LUA_POOLEDSTRING.DrawTranslucent : LUA_POOLEDSTRING.Draw))) { + g_Lua!.PushNumber((int)flags); + ScriptedEntity.Call(1, 0); + } + DrawFlags = 0; + InDraw = false; + return 1; + } + + public override bool GetShadowCastDirection(ref Vector3 direction, ShadowType shadowType) { + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.GetShadowCastDirection)) { + g_Lua!.PushNumber((int)shadowType); + if (ScriptedEntity.Call(1, 1)) { + ILuaObject ret = g_Lua.GetReturn(0); + if (ret.GetType() == LuaType.Vector) { + direction = ret.GetVector(); + return true; + } + } + } + return base.GetShadowCastDirection(ref direction, shadowType); + } + + public override void ClientThink() { + if (!IsMarkedForDeletion() && !ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, true)) + SetNextClientThink(gpGlobals.CurTime + 0.2); + } +#endif + + public override bool KeyValue(ReadOnlySpan keyName, ReadOnlySpan value) { + if (stricmp(keyName, "ScriptName") == 0) + ScriptedEntity.SetScriptName(value); + if (ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.KeyValue)) { + g_Lua!.PushString(keyName); + g_Lua.PushString(value); + ScriptedEntity.Call(2, 0); + } + return base.KeyValue(keyName, value); + } + #if CLIENT_DLL public override RenderGroup GetRenderGroup() { RenderGroup group = RenderMode == (int)Source.RenderMode.None ? RenderGroup.OpaqueEntity : base.GetRenderGroup(); diff --git a/Game.Shared/HL2MP/HL2MPGameRules.cs b/Game.Shared/HL2MP/HL2MPGameRules.cs index e498b720..123f3921 100644 --- a/Game.Shared/HL2MP/HL2MPGameRules.cs +++ b/Game.Shared/HL2MP/HL2MPGameRules.cs @@ -18,7 +18,9 @@ namespace Game.Server.GarrysMod; using Source; using Game.Shared; +using Game.Shared.GarrysMod; using Source.Common.Engine; +using Source.Common.GarrysMod.Lua; [LinkEntityToClass("hl2mp_gamerules")] [NetworkName("CHL2MPGameRulesProxy")] @@ -104,7 +106,20 @@ public override bool ShouldCollide(CollisionGroup collisionGroup0, CollisionGrou public class VoiceGameMgrHelper : IVoiceGameMgrHelper { public bool CanPlayerHearPlayer(BasePlayer listener, BasePlayer talker, ref bool proximity) { +#if GMOD_DLL + if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PlayerCanHearPlayersVoice)) { + LuaEntity.Push_Entity(listener); + LuaEntity.Push_Entity(talker); + if (gGM.CallReturns(2, 2)) { + bool canHear = g_Lua!.GetReturn(1).GetBool(); + proximity = g_Lua.GetReturn(0).GetBool(); + return canHear; + } + } + return true; +#else return listener.GetTeamNumber() == talker.GetTeamNumber(); +#endif } } #endif diff --git a/Game.Shared/MultiplayRules.cs b/Game.Shared/MultiplayRules.cs index 00aab1ef..9e0d1831 100644 --- a/Game.Shared/MultiplayRules.cs +++ b/Game.Shared/MultiplayRules.cs @@ -242,7 +242,19 @@ public override void InitHUD(BasePlayer pl) { } public override void ClientDisconnected(Edict client) { - // todo + if (client != null) { + BasePlayer? player = (BasePlayer?)BaseEntity.Instance(client); + + if (player != null) { + FireTargets("game_playerleave", player, player, UseType.Toggle, 0); + + player.RemoveAllItems(true); + + player.DestroyViewModels(); + + player.SetConnected(PlayerConnectedState.Disconnected); + } + } } public override float FlPlayerFallDamage(BasePlayer player) { throw new NotImplementedException(); diff --git a/Game.Shared/SoundPatch.cs b/Game.Shared/SoundPatch.cs index 1750746c..ca7aad20 100644 --- a/Game.Shared/SoundPatch.cs +++ b/Game.Shared/SoundPatch.cs @@ -154,7 +154,7 @@ public class SoundPatch : IDisposable TimeUnit_t LastTime; string? SoundName; string? SoundScriptName; - EHANDLE Ent; + internal EHANDLE Ent; int EntityChannel; int Flags; int BaseFlags; @@ -536,6 +536,19 @@ public void CommandClear(SoundPatch sound) { } } +#if GMOD_DLL + public void ShutdownSoundsForEntity(int entIndex) { + if (entIndex <= 0) + return; + for (int i = SoundList.Count - 1; i >= 0; i--) { + SoundPatch sound = SoundList[i]; + BaseEntity? ent = sound.Ent.Get(); + if (ent != null && ent.EntIndex() == entIndex) + Shutdown(sound); + } + } +#endif + public void Shutdown(SoundPatch? sound) { if (sound == null) return; diff --git a/Source.GUI.Controls/Panel.cs b/Source.GUI.Controls/Panel.cs index 2ccb8094..dcbefce5 100644 --- a/Source.GUI.Controls/Panel.cs +++ b/Source.GUI.Controls/Panel.cs @@ -1288,6 +1288,21 @@ public bool IsVisible() { } public bool IsWithin(int x, int y) { +#if GMOD_DLL + if (PushLuaHook(LUA_POOLEDSTRING.TestHover)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber(x); + Lua.PushNumber(y); + if (Lua.CallInternal(3, 1)) { + if (Lua.GetType(-1) == LuaType.Bool) { + bool ret = Lua.GetBool(-1); + Lua.Pop(1); + return ret; + } + Lua.Pop(1); + } + } +#endif if (x < ClipRectX) return false; @@ -2593,15 +2608,24 @@ public virtual void OnCommand(ReadOnlySpan command) { public virtual void OnSetFocus() { Repaint(); #if GMOD_DLL - // todo: OnGetFocus hook + CallFocusChanged(true); #endif } public virtual void OnKillFocus(Panel? newPanel) { Repaint(); #if GMOD_DLL - // todo: OnLoseFocus hook + CallFocusChanged(false); #endif } +#if GMOD_DLL + void CallFocusChanged(bool gained) { + if (PushLuaHook(LUA_POOLEDSTRING.OnFocusChanged)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushBool(gained); + Lua.CallInternalNoReturns(2); + } + } +#endif public virtual void OnThink() { } public virtual void OnParentChanged(IPanel? oldParent, IPanel? newParent) { } public virtual void OnChildAdded(IPanel child) { @@ -2618,7 +2642,12 @@ public virtual void OnChildAdded(IPanel child) { } public virtual void OnSizeChanged(int newWide, int newTall) { #if GMOD_DLL - // todo: OnSizeChanged hook + if (PushLuaHook(LUA_POOLEDSTRING.OnSizeChanged)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber(newWide); + Lua.PushNumber(newTall); + Lua.CallInternalNoReturns(3); + } #endif InvalidateLayout(); } @@ -2775,7 +2804,12 @@ public virtual void OnKeyCodePressed(ButtonCode code) { if (!handled && !PassUnhandledInput) return; #if GMOD_DLL - // todo: OnKeyCodePressed hook + if (PushLuaHook(LUA_POOLEDSTRING.OnKeyCodePressed)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber((int)code); + if (Lua.CallInternalGetBool(2)) + return; + } #endif CallParentFunction(new KeyValues("KeyCodePressed").AddSubKey("code", (int)code)); } @@ -2817,7 +2851,12 @@ public void NavigateDown() { public virtual void OnKeyTyped(char unichar) { } public virtual void OnKeyCodeReleased(ButtonCode code) { #if GMOD_DLL - // todo: OnKeyCodeReleased hook + if (PushLuaHook(LUA_POOLEDSTRING.OnKeyCodeReleased)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber((int)code); + if (Lua.CallInternalGetBool(2)) + return; + } #endif CallParentFunction(new KeyValues("KeyCodeReleased", "code", (int)code)); } @@ -3002,7 +3041,13 @@ private void InternalCursorMoved([MessageParam("xpos")] int x, [MessageParam("yp ScreenToLocal(ref x, ref y); #if GMOD_DLL - // todo OnCursorMoved + if (PushLuaHook(LUA_POOLEDSTRING.OnCursorMoved)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushNumber(x); + Lua.PushNumber(y); + if (Lua.CallInternalGetBool(3)) + return; + } #endif OnCursorMoved(x, y); } diff --git a/Source.GUI.Controls/TextEntry.cs b/Source.GUI.Controls/TextEntry.cs index a466f35a..f75829ba 100644 --- a/Source.GUI.Controls/TextEntry.cs +++ b/Source.GUI.Controls/TextEntry.cs @@ -926,9 +926,6 @@ public override void OnKeyCodeTyped(ButtonCode code) { } public override void OnKeyTyped(char ch) { -#if GMOD_DLL - // todo: AllowInput hook -#endif CursorIsAtEnd = PutCursorAtEnd; PutCursorAtEnd = false; @@ -1106,6 +1103,15 @@ private void InsertChar(char ch) { if (!Multiline && ch == '\n') return; +#if GMOD_DLL + if (PushLuaHook(LUA_POOLEDSTRING.AllowInput)) { + PushLua(Lua!, LuaType.Panel); + Lua!.PushString([ch]); + if (Lua.CallInternalGetBool(2)) + return; + } +#endif + if (ch == '\t') return; @@ -1219,9 +1225,6 @@ private void SetCharAt(char ch, int index) { } public override void OnKillFocus(Panel? newPanel) { -#if GMOD_DLL - // todo: OnLoseFocus hook -#endif if (DataChanged) { FireActionSignal(); DataChanged = false; @@ -1243,7 +1246,20 @@ public override void OnKillFocus(Panel? newPanel) { SelectNone(); PostActionSignal(new KeyValues("TextKillFocus")); base.OnKillFocus(newPanel); +#if GMOD_DLL + if (!InLoseFocus) { + InLoseFocus = true; + if (PushLuaHook(LUA_POOLEDSTRING.OnLoseFocus)) { + PushLua(Lua!, LuaType.Panel); + Lua!.CallInternalNoReturns(1); + } + InLoseFocus = false; + } +#endif } +#if GMOD_DLL + bool InLoseFocus; +#endif private bool IsCursorOffRightSideOfWindow(int CursorPos) { int wx = GetWide() - 1; @@ -2065,7 +2081,10 @@ public void SelectAllOnFocusAlways(bool state) { } public override void OnSetFocus() { #if GMOD_DLL - // todo: OnGetFocus hook + if (PushLuaHook(LUA_POOLEDSTRING.OnGetFocus)) { + PushLua(Lua!, LuaType.Panel); + Lua!.CallInternalNoReturns(1); + } #endif if (ShouldSelectAllOnFirstFocus) { Select[1] = TextStream.Count; From 059f41997e220395e8591d810ac82d5c94e29fb0 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 29 Oct 2026 10:42:16 +0000 Subject: [PATCH 7/8] ModelSoundsCache impl --- Game.Server/BaseEntity.cs | 30 ++++++++-- Game.Shared/ModelSoundsCache.cs | 96 +++++++++++++++++++++++++++++- Source.Common/UtlCachedFileData.cs | 5 ++ 3 files changed, 123 insertions(+), 8 deletions(-) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 840e9d8d..e2259f9e 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -3071,13 +3071,13 @@ public static void PrecacheModelComponents(int modelIndex) { // sounds ReadOnlySpan name = modelinfo.GetModelName(model); - if (!g_ModelSoundsCache.TryGetValue(name.Hash(), out _)) { + if (!g_ModelSoundsCache.EntryExists(name)) { ReadOnlySpan extension = Path.GetExtension(name); if (!stristr(extension, "mdl").IsEmpty) DevMsg(2, $"Late precache of {name}, need to rebuild modelsounds.cache\n"); else { - if (extension[0] == '\0') + if (extension.IsEmpty) Warning($"Precache of {name} ambigious (no extension specified)\n"); else Warning($"Late precache of {name} (file missing?)\n"); @@ -3085,11 +3085,31 @@ public static void PrecacheModelComponents(int modelIndex) { } } - if (g_ModelSoundsCache.TryGetValue(name.Hash(), out ModelSoundsCache? entry)) - entry.PrecacheSoundList(); + ModelSoundsCache? entry = g_ModelSoundsCache.Get(name); + Assert(entry != null); + entry?.PrecacheSoundList(); } - static readonly Dictionary g_ModelSoundsCache = []; + public static StudioHdr? ModelSoundsCache_LoadModel(ReadOnlySpan filename) { + int idx = engine.PrecacheModel(filename, true); + if (idx != -1) { + Model? mdl = modelinfo.GetModel(idx); + if (mdl != null) { + StudioHdr studioHdr = new(); + studioHdr.Init(modelinfo.GetStudiomodel(mdl), mdlcache); + if (studioHdr.IsValid()) + return studioHdr; + } + } + return null; + } + + public static void ModelSoundsCache_FinishModel(StudioHdr hdr) => Assert(hdr != null); + + public static void ModelSoundsCache_PrecacheScriptSound(ReadOnlySpan soundname) => PrecacheScriptSound(soundname); + + const int MODELSOUNDSCACHE_VERSION = 5; + static readonly UtlCachedFileData g_ModelSoundsCache = new("modelsounds.cache", MODELSOUNDSCACHE_VERSION, null, UtlCachedFileDataType.UseFilesize, false); public bool HasSpawnFlags(int flags) => (SpawnFlags & flags) != 0; diff --git a/Game.Shared/ModelSoundsCache.cs b/Game.Shared/ModelSoundsCache.cs index b5ab69ae..9ec7b7ea 100644 --- a/Game.Shared/ModelSoundsCache.cs +++ b/Game.Shared/ModelSoundsCache.cs @@ -1,4 +1,5 @@ -using Source.Common; +using Source; +using Source.Common; using System; using System.Collections.Generic; @@ -8,12 +9,101 @@ namespace Game.Shared; public class ModelSoundsCache() : IBaseCacheInfo { - public void Rebuild(ReadOnlySpan filename) => throw new NotImplementedException(); + const int CL_EVENT_SOUND = 5004; + const int CL_EVENT_FOOTSTEP_LEFT = 6004; + const int CL_EVENT_FOOTSTEP_RIGHT = 6005; + const int CL_EVENT_MFOOTSTEP_LEFT = 6006; + const int CL_EVENT_MFOOTSTEP_RIGHT = 6007; + + public ReadOnlySpan GetSoundName(int index) => soundemitterbase.GetSoundName(sounds[index]); + + public void Rebuild(ReadOnlySpan filename) { +#if GAME_DLL + sounds.Clear(); + StudioHdr? hdr = BaseEntity.ModelSoundsCache_LoadModel(filename); + if (hdr != null) { + BuildAnimationEventSoundList(hdr, sounds); + BaseEntity.ModelSoundsCache_FinishModel(hdr); + } +#endif + } + public void Restore(Stream buf) => throw new NotImplementedException(); public void Save(Stream buf) => throw new NotImplementedException(); internal void PrecacheSoundList() { - throw new NotImplementedException(); +#if GAME_DLL + for (int i = 0; i < sounds.Count; ++i) + BaseEntity.ModelSoundsCache_PrecacheScriptSound(GetSoundName(i)); +#endif + } + + static void FindOrAddScriptSound(List sounds, ReadOnlySpan soundname) { + int soundindex = soundemitterbase.GetSoundIndex(soundname); + if (soundindex != -1) { + if (!sounds.Contains((ushort)soundindex)) + sounds.Add((ushort)soundindex); + } + } + + static void FindOrAddScriptSound(List sounds, MStudioEvent ev) => FindOrAddScriptSound(sounds, Encoding.ASCII.GetString(((ReadOnlySpan)ev.Options()).SliceNullTerminatedString())); + + public static void BuildAnimationEventSoundList(StudioHdr hdr, List sounds) { + Assert(hdr != null); + + Animation.VerifySequenceIndex(hdr); + + for (int iSeq = 0; iSeq < hdr.GetNumSeq(); iSeq++) { + MStudioSeqDesc seq = hdr.Seqdesc(iSeq); + + for (int iEvent = 0; iEvent < (int)seq.NumEvents; iEvent++) { + MStudioEvent? ev = seq.Event(iEvent); + if (ev == null) + continue; + + switch (ev.Event) { + default: + if (((AnimEventType)ev.Type & AnimEventType.NewEventSystem) != 0) { + if (ev.Event == (int)AnimEventId.AE_SV_PLAYSOUND) + FindOrAddScriptSound(sounds, ev); + } + break; + case CL_EVENT_SOUND: + FindOrAddScriptSound(sounds, ev); + break; + case CL_EVENT_FOOTSTEP_LEFT: + case CL_EVENT_FOOTSTEP_RIGHT: { + Span soundname = stackalloc char[256]; + ReadOnlySpan options = Encoding.ASCII.GetString(((ReadOnlySpan)ev.Options()).SliceNullTerminatedString()); + if (options.IsEmpty) + options = "NPC_CombineS"; + sprintf(soundname, "%s.RunFootstepLeft").S(options); + FindOrAddScriptSound(sounds, soundname.SliceNullTerminatedString()); + sprintf(soundname, "%s.RunFootstepRight").S(options); + FindOrAddScriptSound(sounds, soundname.SliceNullTerminatedString()); + sprintf(soundname, "%s.FootstepLeft").S(options); + FindOrAddScriptSound(sounds, soundname.SliceNullTerminatedString()); + sprintf(soundname, "%s.FootstepRight").S(options); + FindOrAddScriptSound(sounds, soundname.SliceNullTerminatedString()); + } + break; + case (int)AnimEventId.AE_CL_PLAYSOUND: + if (((AnimEventType)ev.Type & AnimEventType.Client) == 0) + break; + if (ev.Options()[0] != 0) + FindOrAddScriptSound(sounds, ev); + else + Warning($"-- Error --: empty soundname, .qc error on AE_CL_PLAYSOUND in model {hdr.Name()}, sequence {seq.Label()}, animevent # {iEvent + 1}\n"); + break; + case SCRIPT_EVENT_SOUND: + FindOrAddScriptSound(sounds, ev); + break; + case SCRIPT_EVENT_SOUND_VOICE: + FindOrAddScriptSound(sounds, ev); + break; + } + } + } } public readonly List sounds = []; diff --git a/Source.Common/UtlCachedFileData.cs b/Source.Common/UtlCachedFileData.cs index 928ee2ca..1093e218 100644 --- a/Source.Common/UtlCachedFileData.cs +++ b/Source.Common/UtlCachedFileData.cs @@ -78,6 +78,11 @@ public bool Init() { return true; } + public bool EntryExists(ReadOnlySpan filename) { + FileNameHandle_t handle = filesystem.FindOrAddFileName(filename); + return Elements.ContainsKey(handle); + } + public T? Get(ReadOnlySpan filename) { FileNameHandle_t idx = GetIndex(filename); ElementType e = Elements[idx]; From 436106dd6a77161e27cbe9f49bdcbeb24fef0a42 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 29 Oct 2026 11:05:27 +0000 Subject: [PATCH 8/8] Some render stuff/more methods --- Game.Client/GarrysMod/LuaCam.cs | 56 ++++++++++++++++ Game.Client/GarrysMod/LuaRender.cs | 4 +- Game.Client/HL2MP/C_HL2MP_Player.cs | 2 + Game.Client/HLClient.cs | 2 +- Game.Client/View.cs | 5 +- Game.Shared/GarrysMod/GarrysMod.cs | 57 +++++++++++++++++ Game.Shared/GarrysMod/LuaEntity.cs | 45 +++++++++++++ Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 71 +++++++++++---------- Game.Shared/GarrysMod/LuaPlayer.cs | 25 ++++++++ Game.Shared/GarrysMod/WeaponSWEP.cs | 2 + Source.MaterialSystem/MatRenderContext.cs | 8 +-- Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 49 +++++++++++++- 12 files changed, 282 insertions(+), 44 deletions(-) diff --git a/Game.Client/GarrysMod/LuaCam.cs b/Game.Client/GarrysMod/LuaCam.cs index eb22f1ff..cbb2aed1 100644 --- a/Game.Client/GarrysMod/LuaCam.cs +++ b/Game.Client/GarrysMod/LuaCam.cs @@ -20,6 +20,62 @@ public static partial class LuaCam static int Start3DCount; static int OrthoViewCount; + public static void CheckMissingEnds() { + if (Start2DCount > 0) { + do { + using MatRenderContextPtr renderContext = new(materials); + renderContext.OverrideAlphaWriteEnable(false, false); + ((ClientModeShared)clientMode).SetupGModSurface(false); + ClientModeShared.SetupVGuiMatrices(false, renderContext.Context); + Start2DCount--; + } while (Start2DCount > 0); + Warning("Warning! Detected missing cam.End2D call!\n"); + } + + if (Start3DCount > 0) { + do { + render.PopView(view.GetFrustum()); + Start3DCount--; + } while (Start3DCount > 0); + Warning("Warning! Detected missing cam.End3D call!\n"); + } + + if (Start3D2DCount > 0) { + do { + using MatRenderContextPtr renderContext = new(materials); + renderContext.MatrixMode(MaterialMatrixMode.Model); + renderContext.PopMatrix(); + renderContext.OverrideDepthEnable(false, true); + renderContext.GMOD_ForceFilterMode(true, 0); + renderContext.GMOD_ForceFilterMode(false, 0); + Start3D2DCount--; + } while (Start3D2DCount > 0); + Warning("Warning! Detected missing cam.End3D2D call!\n"); + } + + if (LuaRender.CustomClipPlaneCount > 0) { + do { + using MatRenderContextPtr renderContext = new(materials); + renderContext.PopCustomClipPlane(); + LuaRender.CustomClipPlaneCount--; + } while (LuaRender.CustomClipPlaneCount > 0); + Warning("Warning! Detected missing render.PopCustomClipPlane call!\n"); + } + + if (LuaRender.RenderTargetStack > 0) { + do { + using MatRenderContextPtr renderContext = new(materials); + renderContext.Flush(false); + renderContext.PopRenderTargetAndViewport(); + LuaRender.RenderTargetStack--; + } while (LuaRender.RenderTargetStack > 0); + Warning("Warning! Detected missing render.PopRenderTarget call!\n"); + } + + using MatRenderContextPtr context = new(materials); + context.BindLocalCubemap(null); + } + static ViewSetup StartView; public static bool InSurface3D; diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index 8f636a18..83ec1ad0 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -272,7 +272,7 @@ static int SetRenderTargetEx(ILuaInterface lua) { return 0; } #endif - static int RenderTargetStack; + internal static int RenderTargetStack; #if !MENU_DLL [LuaFunction] @@ -627,7 +627,7 @@ static int ClearDepth(ILuaInterface lua) { // todo: RenderView // todo: GetViewSetup // todo: RenderHUD - static int CustomClipPlaneCount; + internal static int CustomClipPlaneCount; [LuaFunction] static int PushCustomClipPlane(ILuaInterface lua) { diff --git a/Game.Client/HL2MP/C_HL2MP_Player.cs b/Game.Client/HL2MP/C_HL2MP_Player.cs index 5d526c59..2d673e48 100644 --- a/Game.Client/HL2MP/C_HL2MP_Player.cs +++ b/Game.Client/HL2MP/C_HL2MP_Player.cs @@ -103,6 +103,8 @@ public override void PostThink() { AngEyeAngles = EyeAngles(); } + public void DoAnimationEvent(PlayerAnimEvent evt, int data, bool predicted) => PlayerAnimState.DoAnimationEvent(evt, data); + #if GMOD_DLL public override void UpdateClientSideAnimation() { QAngle eyeAngles = EyeAngles(); diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs index ef108e2a..089660cc 100644 --- a/Game.Client/HLClient.cs +++ b/Game.Client/HLClient.cs @@ -285,7 +285,7 @@ public void View_Render(ViewRects rects) { return; #if GMOD_DLL using MatRenderContextPtr renderContext = new(materials); - renderContext.Flush(false); + renderContext.SetRenderTarget(null); if (gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreRender) && gGM.CallFinish(0) && !enginevgui.IsGameUIVisible()) return; #endif diff --git a/Game.Client/View.cs b/Game.Client/View.cs index d681296b..73764e12 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -356,7 +356,10 @@ public void Render(ViewRects rect) { if (drawViewModel) flags |= RenderViewInfo.DrawViewmodel; - RenderView(in viewEye, clearFlags, flags); +#if GMOD_DLL + if (!garrysmod.RenderScene(in viewEye)) +#endif + RenderView(in viewEye, clearFlags, flags); } View2D.X = rect[0].X; diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 2b33db07..2d1d820d 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -16,8 +16,11 @@ using Source.Common.Formats.Keyvalues; using Source.Common.GarrysMod; using Source.Common.MaterialSystem; +using Source.Common.Mathematics; using Source.Common.Networking; +using System.Numerics; + using Steamworks; using System; @@ -618,7 +621,61 @@ public void EntityCreated(BaseEntity? ent) { gGM.CallNoReturns(1); } +#if CLIENT_DLL + static readonly ConVarRef volume = new("volume"); + static readonly ConVarRef volume_sfx = new("volume_sfx"); + static readonly ConVarRef snd_mute_losefocus = new("snd_mute_losefocus"); + + public void UpdateAudioVolume() { + if (snd_mute_losefocus.GetBool() && !engine.IsActiveApp()) { + get.Audio()!.SetGlobalVolume(0); + return; + } + get.Audio()!.SetGlobalVolume(volume_sfx.GetFloat() * volume.GetFloat()); + } + + public bool RenderScene(in ViewSetup view) { + if (get.Audio() != null) { + Vector3 origin = view.Origin; + Vector3 velocity = default; + MathLib.AngleVectors(view.Angles, out Vector3 forward, out Vector3 right, out Vector3 up); + get.Audio()!.SetEar(ref origin, ref velocity, ref forward, ref up); + UpdateAudioVolume(); + } + + LuaCam.CheckMissingEnds(); + // todo: reset ShouldDrawLocalPlayer cache + + using (MatRenderContextPtr renderContext = new(materials)) { + renderContext.GMOD_ForceFilterMode(true, 0); + renderContext.GMOD_ForceFilterMode(false, 0); + renderContext.OverrideBlend(false, true, -1, -1, -1); + renderContext.OverrideBlendSeparateAlpha(false, true, -1, -1, -1); + } + + if (g_Lua == null || gGM == null) + return false; + + C_BasePlayer? player = C_BasePlayer.GetLocalPlayer(); + if (player != null && player.GetActiveWeapon() is C_WeaponSWEP swep) + swep.RenderScreen(); + + if (gGM.CallWithArgs((int)LUA_POOLEDSTRING.RenderScene)) { + LuaVector.Push_Vector(view.Origin); + LuaAngle.Push_Angle(view.Angles); + g_Lua.PushNumber(view.FOV); + return gGM.CallFinish(3); + } + return false; + } +#endif + public void EntityRemoved(BaseEntity ent, bool fullUpdate) { +#if CLIENT_DLL + LuaEntity.RemoveFromRemoveList(ent); +#else + Game.Server.GarrysMod.LuaEntity.RemoveFromRemoveList(ent); +#endif SoundEnvelopeController.GetController().ShutdownSoundsForEntity(ent.EntIndex()); if (g_Lua == null || gGM == null) return; diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 2700c8e9..34457b92 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -62,6 +62,17 @@ public static partial class LuaEntity static readonly List RemoveList = []; static bool ProcessingRemoveList; + public static void RemoveFromRemoveList(BaseEntity ent) { + if (ProcessingRemoveList) + return; + for (int i = 0; i < RemoveList.Count; i++) { + if (RemoveList[i].Get() == ent) { + RemoveList.RemoveAt(i); + return; + } + } + } + public static void RemoveQueuedEntities() { ProcessingRemoveList = true; for (int i = 0; i < RemoveList.Count; i++) { @@ -1502,6 +1513,40 @@ static int Entity__HasSpawnFlags(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__SetKeyValue(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + for (int i = 0; i < RemoveList.Count; i++) { + if (RemoveList[i].Get() == ent) + return 0; + } + if (ent.IsMarkedForDeletion()) + return 0; + + ReadOnlySpan key = lua.CheckString(2); + if (stricmp(key, "classname") == 0) + return 0; + + ReadOnlySpan value = lua.CheckString(3); + if (stricmp(key, "m_iEFlags") != 0 || (atoi(value) & 1) == 0) + ent.KeyValue(key, value); + return 0; + } + + [LuaMethod] + static int Entity__SetAnimation(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + if (!ent.IsPlayer()) + return 0; + int anim = (int)Math.Clamp((float)(int)lua.CheckNumber(2), 0, 9); + HL2MP_Player? player = ent as HL2MP_Player; + if (anim == (int)PlayerAnim.Attack1) + player!.DoAnimationEvent(PlayerAnimEvent.AttackPrimary, 0, true); + else if (anim == (int)PlayerAnim.Reload) + player!.DoAnimationEvent(PlayerAnimEvent.Reload, 0, true); + return 0; + } + [LuaMethod] static int Entity__GetSkin(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index ba9e01eb..40a5c711 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -727,49 +727,26 @@ static int DisableClipping(ILuaInterface lua) { } #endif - [LuaGlobal] - static int RunConsoleCommand(ILuaInterface lua) { - string command = g_Lua!.CheckString(1); - if (!LuaConVar.IsValidConsoleName(command)) { - g_Lua.ErrorFromLua($"RunConsoleCommand: Command has invalid characters! ({command})\n\tThe first parameter of this function should contain only the command, the second parameter should contain arguments."); - return 0; - } - - string? blocked = LuaConCommands.ConCommand_IsBlocked(command); - if (blocked != null) { -#if CLIENT_DLL - if (blocked == "connect") { - // todo menu system - return 0; - } -#endif - g_Lua.ErrorFromLua($"RunConsoleCommand: Command is blocked! ({blocked})"); - return 0; - } - - if (command.Length <= 1) { - g_Lua.ErrorFromLua($"RunConsoleCommand: Command is too short, bailing! ({command})"); - return 0; - } - + public static bool BuildConsoleCommand(ILuaInterface lua, int start, string command, out string result) { + result = ""; StringBuilder buffer = new(command); - for (int i = 2; i < 64; i++) { - LuaType type = g_Lua.GetType(i); + for (int i = start; i < 64; i++) { + LuaType type = lua.GetType(i); if (type == LuaType.Nil) break; - string? argument = g_Lua.GetString(i); + string? argument = lua.GetString(i); if (argument == null) break; string? blockedArg = LuaConCommands.ConCommand_IsBlockedArg(argument); if (blockedArg != null) { - g_Lua.ErrorFromLua($"RunConsoleCommand: Command argument is blocked! ({command} {blockedArg})"); - return 0; + lua.ErrorFromLua($"RunConsoleCommand: Command argument is blocked! ({command} {blockedArg})"); + return false; } if (type == LuaType.Number) - argument = g_Lua.GetNumber(i).ToString("F2", CultureInfo.InvariantCulture); + argument = lua.GetNumber(i).ToString("F2", CultureInfo.InvariantCulture); StringBuilder escaped = new(); for (int c = 0; c < argument.Length && c < 511; c++) @@ -783,9 +760,39 @@ static int RunConsoleCommand(ILuaInterface lua) { } buffer.Append(';'); - string result = buffer.ToString(); + result = buffer.ToString(); if (result.Length > 1023) result = result[..1023]; + return true; + } + + [LuaGlobal] + static int RunConsoleCommand(ILuaInterface lua) { + string command = g_Lua!.CheckString(1); + if (!LuaConVar.IsValidConsoleName(command)) { + g_Lua.ErrorFromLua($"RunConsoleCommand: Command has invalid characters! ({command})\n\tThe first parameter of this function should contain only the command, the second parameter should contain arguments."); + return 0; + } + + string? blocked = LuaConCommands.ConCommand_IsBlocked(command); + if (blocked != null) { +#if CLIENT_DLL + if (blocked == "connect") { + // todo menu system + return 0; + } +#endif + g_Lua.ErrorFromLua($"RunConsoleCommand: Command is blocked! ({blocked})"); + return 0; + } + + if (command.Length <= 1) { + g_Lua.ErrorFromLua($"RunConsoleCommand: Command is too short, bailing! ({command})"); + return 0; + } + + if (!BuildConsoleCommand(lua, 2, command, out string result)) + return 0; #if CLIENT_DLL || MENU_DLL engine.ClientCmd(result); #else diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index c3727ace..1aedb660 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -774,6 +774,31 @@ static int Player__SetTeam(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Player__RunConsoleCommand(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + string command = lua.CheckString(2); + if (!LuaConVar.IsValidConsoleName(command)) { + lua.ErrorFromLua($"RunConsoleCommand: Command has invalid characters! ({command})\n\tThe first parameter of this function should contain only the command, the second parameter should contain arguments."); + return 0; + } + + string? blocked = LuaConCommands.ConCommand_IsBlocked(command); + if (blocked != null) { + lua.ErrorFromLua($"RunConsoleCommand: Command is blocked! ({blocked})"); + return 0; + } + + if (command.Length < 2) { + lua.ErrorFromLua($"RunConsoleCommand: Command is too short, bailing! ({command})"); + return 0; + } + + if (LuaGlobalFunctions.BuildConsoleCommand(lua, 3, command, out string result)) + engine.ClientCommand(player.Edict(), result); + return 0; + } + [LuaMethod] static int Player__SendLua(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/WeaponSWEP.cs b/Game.Shared/GarrysMod/WeaponSWEP.cs index af436677..a437d7af 100644 --- a/Game.Shared/GarrysMod/WeaponSWEP.cs +++ b/Game.Shared/GarrysMod/WeaponSWEP.cs @@ -374,6 +374,8 @@ public override void Drop(in Vector3 velocity) { public override ReadOnlySpan GetName() => ScriptedEntity.ScriptNamePooled; #else public override ReadOnlySpan GetName() => ScriptedEntity.GetScriptName(); + + public void RenderScreen() => ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.RenderScreen, false); #endif public override int GetSlot() { diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index a7726fa2..2731bbe3 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -761,13 +761,9 @@ public void LockLookup(ColorCorrectionHandle_t handle) { public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) => shaderAPI.OverrideAlphaWriteEnable(enable, alphaWriteEnable); - public void OverrideBlend(bool unk1, bool unk2, int unk3, int unk4, int unk5) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void OverrideBlend(bool overrideEnable, bool useSeparateAlpha, int srcBlend, int destBlend, int blendFunc) => shaderAPI.OverrideBlend(overrideEnable, useSeparateAlpha, srcBlend, destBlend, blendFunc); - public void OverrideBlendSeparateAlpha(bool unk1, bool unk2, int unk3, int unk4, int unk5) { - throw new NotImplementedException("Incomplete port of IMatRenderContext"); - } + public void OverrideBlendSeparateAlpha(bool overrideEnable, bool useSeparateAlpha, int srcBlend, int destBlend, int blendFunc) => shaderAPI.OverrideBlendSeparateAlpha(overrideEnable, useSeparateAlpha, srcBlend, destBlend, blendFunc); public void OverrideColorWriteEnable(bool overrideEnable, bool colorWriteEnable) => shaderAPI.OverrideColorWriteEnable(overrideEnable, colorWriteEnable); diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index b34406c2..8a3721db 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -2678,6 +2678,27 @@ public void SetShaderUniform(IMaterialVar textureVar) { GraphicsBoardState lastBoardState; bool boardStateValid; public bool SetBoardState(in GraphicsBoardState state) { + if ((OverrideBlendEnabled && OverrideBlendColor) || (OverrideBlendAlphaEnabled && OverrideBlendAlpha)) { + GraphicsBoardState overridden = state; + if (OverrideBlendEnabled && OverrideBlendColor) { + overridden.Blending = true; + overridden.SourceBlend = OverriddenSrcBlend; + overridden.DestinationBlend = OverriddenDestBlend; + overridden.BlendOperation = OverriddenBlendOp; + } + if (OverrideBlendAlphaEnabled && OverrideBlendAlpha) { + overridden.Blending = true; + overridden.AlphaSeparateBlend = true; + overridden.AlphaSourceBlend = OverriddenSrcBlendAlpha; + overridden.AlphaDestinationBlend = OverriddenDestBlendAlpha; + overridden.AlphaBlendOperation = OverriddenBlendOpAlpha; + } + return SetBoardStateInternal(in overridden); + } + return SetBoardStateInternal(in state); + } + + bool SetBoardStateInternal(in GraphicsBoardState state) { ulong currHash = state.Hash(); if (currHash != lastBoardUploadHash) { ref GraphicsBoardState last = ref lastBoardState; @@ -3557,12 +3578,36 @@ public void OverrideAlphaWriteEnable(bool enable, bool alphaWriteEnable) { } } + bool OverrideBlendEnabled; + bool OverrideBlendColor; + ShaderBlendFactor OverriddenSrcBlend; + ShaderBlendFactor OverriddenDestBlend; + ShaderBlendOp OverriddenBlendOp; + + bool OverrideBlendAlphaEnabled; + bool OverrideBlendAlpha; + ShaderBlendFactor OverriddenSrcBlendAlpha; + ShaderBlendFactor OverriddenDestBlendAlpha; + ShaderBlendOp OverriddenBlendOpAlpha; + public void OverrideBlend(bool overrideEnable, bool useSeparateAlpha, int srcBlend, int destBlend, int blendFunc) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + FlushBufferedPrimitives(); + OverrideBlendEnabled = overrideEnable; + OverrideBlendColor = useSeparateAlpha; + OverriddenSrcBlend = (ShaderBlendFactor)srcBlend; + OverriddenDestBlend = (ShaderBlendFactor)destBlend; + OverriddenBlendOp = (ShaderBlendOp)blendFunc; + lastBoardUploadHash = 0; } public void OverrideBlendSeparateAlpha(bool overrideEnable, bool useSeparateAlpha, int srcBlend, int destBlend, int blendFunc) { - throw new NotImplementedException("Incomplete port of IShaderAPI"); + FlushBufferedPrimitives(); + OverrideBlendAlphaEnabled = overrideEnable; + OverrideBlendAlpha = useSeparateAlpha; + OverriddenSrcBlendAlpha = (ShaderBlendFactor)srcBlend; + OverriddenDestBlendAlpha = (ShaderBlendFactor)destBlend; + OverriddenBlendOpAlpha = (ShaderBlendOp)blendFunc; + lastBoardUploadHash = 0; } bool OverrideColorWrite;