From 097a4ec8a88eb5514cd89658dbb19974435a7a90 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 17 Nov 2026 06:40:26 +0000 Subject: [PATCH 01/12] ISteamHTTP --- Game.Shared/GarrysMod/GarrysMod.cs | 2 +- Game.Shared/GarrysMod/LuaHTTPRequest.cs | 57 ++++++++++++++----------- Source.Common/Steam/Steamworks.cs | 31 +++++++++++++- Source.Engine/Server/SteamAuth.cs | 2 +- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index 12e1f88b..d47b51bf 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -704,7 +704,7 @@ public void Think() { LuaTimer.Cycle(); LuaFileLibrary.AsyncCycle(); #endif - // HTTP.Cycle(); + LuaHTTP.Cycle(); // ErrorReporter.RunQueue(); } // AutoRefresh.Cycle(); diff --git a/Game.Shared/GarrysMod/LuaHTTPRequest.cs b/Game.Shared/GarrysMod/LuaHTTPRequest.cs index 8045a653..0e2c2bbc 100644 --- a/Game.Shared/GarrysMod/LuaHTTPRequest.cs +++ b/Game.Shared/GarrysMod/LuaHTTPRequest.cs @@ -5,10 +5,6 @@ using Steamworks; -#if GAME_DLL -using SteamHTTP = Steamworks.SteamGameServerHTTP; -#endif - #if CLIENT_DLL namespace Game.Client.GarrysMod; #elif MENU_DLL @@ -161,18 +157,18 @@ void ForEachStringPair(ReadOnlySpan member, Action action) void Send() { string method = (Table.GetMemberStr("method", "get") ?? "get").ToLowerInvariant(); - Request = SteamHTTP.CreateHTTPRequest(MethodFromName(method), Url); + Request = get.SteamHTTP()!.CreateHTTPRequest(MethodFromName(method), Url); if (Request == HTTPRequestHandle.Invalid) { Fail("invalid request"); return; } - ForEachStringPair("headers", (key, value) => SteamHTTP.SetHTTPRequestHeaderValue(Request, key, value)); - ForEachStringPair("parameters", (key, value) => SteamHTTP.SetHTTPRequestGetOrPostParameter(Request, key, value)); + ForEachStringPair("headers", (key, value) => get.SteamHTTP()!.SetHTTPRequestHeaderValue(Request, key, value)); + ForEachStringPair("parameters", (key, value) => get.SteamHTTP()!.SetHTTPRequestGetOrPostParameter(Request, key, value)); string type = Table.GetMemberStr("type", "text/plain; charset=utf-8") ?? ""; int timeout = Math.Clamp(Table.GetMemberInt("timeout", 60), 1, 3600); - SteamHTTP.SetHTTPRequestNetworkActivityTimeout(Request, (uint)timeout); + get.SteamHTTP()!.SetHTTPRequestNetworkActivityTimeout(Request, (uint)timeout); LuaObject body = new(); Table.GetMember("body", body); @@ -186,11 +182,11 @@ void Send() { body.Push(); byte[] bytes = g_Lua!.GetStringBytes(-1).ToArray(); g_Lua.Pop(1); - SteamHTTP.SetHTTPRequestRawPostBody(Request, type, bytes, (uint)bytes.Length); + get.SteamHTTP()!.SetHTTPRequestRawPostBody(Request, type, bytes, (uint)bytes.Length); } body.UnReference(); - if (!SteamHTTP.SendHTTPRequest(Request, out SteamAPICall_t call)) { + if (!get.SteamHTTP()!.SendHTTPRequest(Request, out SteamAPICall_t call)) { Fail("invalid request"); return; } @@ -213,26 +209,26 @@ void OnComplete(HTTPRequestCompleted_t result, bool ioFailure) { } if (!result.m_bRequestSuccessful) { - SteamHTTP.GetHTTPRequestWasTimedOut(result.m_hRequest, out bool timedOut); + get.SteamHTTP()!.GetHTTPRequestWasTimedOut(result.m_hRequest, out bool timedOut); Fail(timedOut ? "timeout" : "unsuccessful"); return; } LuaTable headers = new(); foreach (string name in ResponseHeaders) { - if (!SteamHTTP.GetHTTPResponseHeaderSize(Request, name, out uint size)) + if (!get.SteamHTTP()!.GetHTTPResponseHeaderSize(Request, name, out uint size)) continue; byte[] value = new byte[size]; - if (SteamHTTP.GetHTTPResponseHeaderValue(Request, name, value, size)) { + if (get.SteamHTTP()!.GetHTTPResponseHeaderValue(Request, name, value, size)) { int length = Array.IndexOf(value, (byte)0); headers.SetMember(name, length < 0 ? value : value.AsSpan(0, length)); } } - SteamHTTP.GetHTTPResponseBodySize(result.m_hRequest, out uint bodySize); + get.SteamHTTP()!.GetHTTPResponseBodySize(result.m_hRequest, out uint bodySize); byte[] responseBody = new byte[bodySize]; - SteamHTTP.GetHTTPResponseBodyData(result.m_hRequest, responseBody, bodySize); + get.SteamHTTP()!.GetHTTPResponseBodyData(result.m_hRequest, responseBody, bodySize); LuaObject success = new(); Table.GetMember("success", success); @@ -252,7 +248,7 @@ void OnComplete(HTTPRequestCompleted_t result, bool ioFailure) { void Delete() { RequestCompleted.Dispose(); if (Request != HTTPRequestHandle.Invalid) { - SteamHTTP.ReleaseHTTPRequest(Request); + get.SteamHTTP()!.ReleaseHTTPRequest(Request); Request = HTTPRequestHandle.Invalid; } Table.UnReference(); @@ -263,6 +259,20 @@ void Delete() { public static partial class LuaHTTP { + static readonly List PendingHTTPRequests = []; + + public static void Cycle() { + if (get.SteamHTTP() == null || PendingHTTPRequests.Count == 0) + return; + + foreach (LuaObject table in PendingHTTPRequests) { + if (!table.isNil()) + LuaHTTPRequest.Create(table); + table.UnReference(); + } + PendingHTTPRequests.Clear(); + } + static void CallFailed(ILuaObject table, string reason) { LuaObject failed = new(); table.GetMember("failed", failed); @@ -290,17 +300,14 @@ static int HTTP(ILuaInterface lua) { return 1; } -#if GAME_DLL - if (!SteamworksExts.HasSteamGameServer()) { -#else - if (!SteamworksExts.HasSteamHTTP()) { -#endif - lua.ErrorFromLua("HTTP failed - ISteamHTTP isn't available!\n"); - lua.PushBool(false); - return 1; + if (get.SteamHTTP() != null) + LuaHTTPRequest.Create(table); + else { + LuaObject pending = new(); + pending.Set(table); + PendingHTTPRequests.Add(pending); } - LuaHTTPRequest.Create(table); lua.PushBool(true); return 1; } diff --git a/Source.Common/Steam/Steamworks.cs b/Source.Common/Steam/Steamworks.cs index 6ecd722b..7522cc6d 100644 --- a/Source.Common/Steam/Steamworks.cs +++ b/Source.Common/Steam/Steamworks.cs @@ -128,7 +128,21 @@ public interface ISteamScreenshots public bool TagUser(ScreenshotHandle hScreenshot, CSteamID steamID) => SteamScreenshots.TagUser(hScreenshot, steamID); public bool SetLocation(ScreenshotHandle hScreenshot, ReadOnlySpan pchLocation) => SteamScreenshots.SetLocation(hScreenshot, new(pchLocation)); } -public interface ISteamHTTP; +public interface ISteamHTTP +{ + public HTTPRequestHandle CreateHTTPRequest(EHTTPMethod eHTTPRequestMethod, ReadOnlySpan pchAbsoluteURL) => SteamHTTP.CreateHTTPRequest(eHTTPRequestMethod, new(pchAbsoluteURL)); + public bool SetHTTPRequestNetworkActivityTimeout(HTTPRequestHandle hRequest, uint unTimeoutSeconds) => SteamHTTP.SetHTTPRequestNetworkActivityTimeout(hRequest, unTimeoutSeconds); + public bool SetHTTPRequestHeaderValue(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, ReadOnlySpan pchHeaderValue) => SteamHTTP.SetHTTPRequestHeaderValue(hRequest, new(pchHeaderName), new(pchHeaderValue)); + public bool SetHTTPRequestGetOrPostParameter(HTTPRequestHandle hRequest, ReadOnlySpan pchParamName, ReadOnlySpan pchParamValue) => SteamHTTP.SetHTTPRequestGetOrPostParameter(hRequest, new(pchParamName), new(pchParamValue)); + public bool SendHTTPRequest(HTTPRequestHandle hRequest, out SteamAPICall_t pCallHandle) => SteamHTTP.SendHTTPRequest(hRequest, out pCallHandle); + public bool GetHTTPResponseHeaderSize(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, out uint unResponseHeaderSize) => SteamHTTP.GetHTTPResponseHeaderSize(hRequest, new(pchHeaderName), out unResponseHeaderSize); + public bool GetHTTPResponseHeaderValue(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, byte[] pHeaderValueBuffer, uint unBufferSize) => SteamHTTP.GetHTTPResponseHeaderValue(hRequest, new(pchHeaderName), pHeaderValueBuffer, unBufferSize); + public bool GetHTTPResponseBodySize(HTTPRequestHandle hRequest, out uint unBodySize) => SteamHTTP.GetHTTPResponseBodySize(hRequest, out unBodySize); + public bool GetHTTPResponseBodyData(HTTPRequestHandle hRequest, byte[] pBodyDataBuffer, uint unBufferSize) => SteamHTTP.GetHTTPResponseBodyData(hRequest, pBodyDataBuffer, unBufferSize); + public bool ReleaseHTTPRequest(HTTPRequestHandle hRequest) => SteamHTTP.ReleaseHTTPRequest(hRequest); + public bool SetHTTPRequestRawPostBody(HTTPRequestHandle hRequest, ReadOnlySpan pchContentType, byte[] pubBody, uint unBodyLen) => SteamHTTP.SetHTTPRequestRawPostBody(hRequest, new(pchContentType), pubBody, unBodyLen); + public bool GetHTTPRequestWasTimedOut(HTTPRequestHandle hRequest, out bool pbWasTimedOut) => SteamHTTP.GetHTTPRequestWasTimedOut(hRequest, out pbWasTimedOut); +} public interface ISteamController; public interface ISteamUGC; public interface ISteamAppList; @@ -200,6 +214,21 @@ public class ImplSteamNetworking : ISteamNetworking; public class ImplSteamRemoteStorage : ISteamRemoteStorage; public class ImplSteamScreenshots : ISteamScreenshots; public class ImplSteamHTTP : ISteamHTTP; +public class ImplSteamGameServerHTTP : ISteamHTTP +{ + public HTTPRequestHandle CreateHTTPRequest(EHTTPMethod eHTTPRequestMethod, ReadOnlySpan pchAbsoluteURL) => SteamGameServerHTTP.CreateHTTPRequest(eHTTPRequestMethod, new(pchAbsoluteURL)); + public bool SetHTTPRequestNetworkActivityTimeout(HTTPRequestHandle hRequest, uint unTimeoutSeconds) => SteamGameServerHTTP.SetHTTPRequestNetworkActivityTimeout(hRequest, unTimeoutSeconds); + public bool SetHTTPRequestHeaderValue(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, ReadOnlySpan pchHeaderValue) => SteamGameServerHTTP.SetHTTPRequestHeaderValue(hRequest, new(pchHeaderName), new(pchHeaderValue)); + public bool SetHTTPRequestGetOrPostParameter(HTTPRequestHandle hRequest, ReadOnlySpan pchParamName, ReadOnlySpan pchParamValue) => SteamGameServerHTTP.SetHTTPRequestGetOrPostParameter(hRequest, new(pchParamName), new(pchParamValue)); + public bool SendHTTPRequest(HTTPRequestHandle hRequest, out SteamAPICall_t pCallHandle) => SteamGameServerHTTP.SendHTTPRequest(hRequest, out pCallHandle); + public bool GetHTTPResponseHeaderSize(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, out uint unResponseHeaderSize) => SteamGameServerHTTP.GetHTTPResponseHeaderSize(hRequest, new(pchHeaderName), out unResponseHeaderSize); + public bool GetHTTPResponseHeaderValue(HTTPRequestHandle hRequest, ReadOnlySpan pchHeaderName, byte[] pHeaderValueBuffer, uint unBufferSize) => SteamGameServerHTTP.GetHTTPResponseHeaderValue(hRequest, new(pchHeaderName), pHeaderValueBuffer, unBufferSize); + public bool GetHTTPResponseBodySize(HTTPRequestHandle hRequest, out uint unBodySize) => SteamGameServerHTTP.GetHTTPResponseBodySize(hRequest, out unBodySize); + public bool GetHTTPResponseBodyData(HTTPRequestHandle hRequest, byte[] pBodyDataBuffer, uint unBufferSize) => SteamGameServerHTTP.GetHTTPResponseBodyData(hRequest, pBodyDataBuffer, unBufferSize); + public bool ReleaseHTTPRequest(HTTPRequestHandle hRequest) => SteamGameServerHTTP.ReleaseHTTPRequest(hRequest); + public bool SetHTTPRequestRawPostBody(HTTPRequestHandle hRequest, ReadOnlySpan pchContentType, byte[] pubBody, uint unBodyLen) => SteamGameServerHTTP.SetHTTPRequestRawPostBody(hRequest, new(pchContentType), pubBody, unBodyLen); + public bool GetHTTPRequestWasTimedOut(HTTPRequestHandle hRequest, out bool pbWasTimedOut) => SteamGameServerHTTP.GetHTTPRequestWasTimedOut(hRequest, out pbWasTimedOut); +} public class ImplSteamController : ISteamController; public class ImplSteamUGC : ISteamUGC; public class ImplSteamAppList : ISteamAppList; diff --git a/Source.Engine/Server/SteamAuth.cs b/Source.Engine/Server/SteamAuth.cs index 0bba4165..7655114d 100644 --- a/Source.Engine/Server/SteamAuth.cs +++ b/Source.Engine/Server/SteamAuth.cs @@ -40,7 +40,7 @@ public class Steam3ServerImpl : IDisposable readonly ISteamUtils __SteamUtils = new ImplSteamUtils(); readonly ISteamNetworking __SteamNetworking = new ImplSteamNetworking(); readonly ISteamGameServerStats __SteamGameServerStats = new ImplSteamGameServerStats(); - readonly ISteamHTTP __SteamHTTP = new ImplSteamHTTP(); + readonly ISteamHTTP __SteamHTTP = new ImplSteamGameServerHTTP(); readonly ISteamInventory __SteamInventory = new ImplSteamInventory(); readonly ISteamUGC __SteamUGC = new ImplSteamUGC(); From e35de421852098e599c7c379601cce0c405f7c4c Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 17 Nov 2026 08:39:44 +0000 Subject: [PATCH 02/12] Fix FileBase no longer breaks without an extension, and now null terminates --- Source.Common/Exts.cs | 45 +++++++++++++++++++++++++++++-------------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/Source.Common/Exts.cs b/Source.Common/Exts.cs index 2dc95f00..7d40d43c 100644 --- a/Source.Common/Exts.cs +++ b/Source.Common/Exts.cs @@ -1051,20 +1051,37 @@ public static ulong Hash(this Span target) where T : unmanaged { } public static void FileBase(this ReadOnlySpan inSpan, Span outSpan) { - // Strip inSpan until we reach a . - while (inSpan.Length > 0 && inSpan[^1] != '.') - inSpan = inSpan[..^1]; - // Strip the period - inSpan = inSpan[..^1]; - - // Then repeat the same process, except for a slash - int lenPtr = inSpan.Length - 1; - while (lenPtr > 0 && (inSpan[lenPtr] != '/' && inSpan[lenPtr] != '\\')) - lenPtr--; - // This should be the final span - inSpan = inSpan[(lenPtr + 1)..]; - // Then copy - inSpan.ClampedCopyTo(outSpan); + inSpan = inSpan.SliceNullTerminatedString(); + if (inSpan.IsEmpty) { + if (!outSpan.IsEmpty) + outSpan[0] = '\0'; + return; + } + + int len = inSpan.Length; + + int end = len - 1; + while (end != 0 && inSpan[end] != '.' && !StrTools.IsPathSeparator(inSpan[end])) + end--; + + if (inSpan[end] != '.') + end = len - 1; + else + end--; + + int start = len - 1; + while (start >= 0 && !StrTools.IsPathSeparator(inSpan[start])) + start--; + + if (start < 0 || !StrTools.IsPathSeparator(inSpan[start])) + start = 0; + else + start++; + + len = end - start + 1; + + int maxcopy = Math.Min(len + 1, outSpan.Length); + strcpy(outSpan[..maxcopy], inSpan[start..(start + Math.Max(len, 0))]); } public static ReadOnlySpan UnqualifiedFileName(this ReadOnlySpan input) { From a961a2101c46373d2d2667d159aa06d4309c3f8f Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 17 Nov 2026 08:40:03 +0000 Subject: [PATCH 03/12] misc fixes --- Game.Client/HL2/HudWeaponSelection.cs | 2 ++ Game.Server/HL2MP/HL2MP_Player.cs | 6 ++++++ Source.Engine/CL.cs | 3 +++ Source.Engine/Client/ClientState.cs | 8 +++++++- Source.Engine/Host.cs | 6 ++++++ 5 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Game.Client/HL2/HudWeaponSelection.cs b/Game.Client/HL2/HudWeaponSelection.cs index 8058db26..b72d4932 100644 --- a/Game.Client/HL2/HudWeaponSelection.cs +++ b/Game.Client/HL2/HudWeaponSelection.cs @@ -92,8 +92,10 @@ public override void SetWeaponSelected() { #endif public override void OnWeaponPickup(BaseCombatWeapon weapon) { +#if !GMOD_DLL HudHistoryResource? hr = gHUD.FindElement("CHudHistoryResource") as HudHistoryResource; hr?.AddToHistory(weapon); +#endif } public override void OnThink() { diff --git a/Game.Server/HL2MP/HL2MP_Player.cs b/Game.Server/HL2MP/HL2MP_Player.cs index 69d035e6..2e04085d 100644 --- a/Game.Server/HL2MP/HL2MP_Player.cs +++ b/Game.Server/HL2MP/HL2MP_Player.cs @@ -190,7 +190,9 @@ public override void Spawn() { NextModelChangeTime = 0; NextTeamChangeTime = 0; +#if !GMOD_DLL PickDefaultSpawnTeam(); +#endif base.Spawn(); @@ -198,11 +200,15 @@ public override void Spawn() { pl.DeadFlag = false; // RemoveSolidFlags(SolidFlags.NotSolid); RemoveEffects(EntityEffects.NoDraw); +#if !GMOD_DLL GiveDefaultItems(); +#endif } +#if !GMOD_DLL SetNumAnimOverlays(3); ResetAnimation(); +#endif RenderFX = (byte)Source.RenderMode.Normal; diff --git a/Source.Engine/CL.cs b/Source.Engine/CL.cs index 053e3c3d..fb3afeed 100644 --- a/Source.Engine/CL.cs +++ b/Source.Engine/CL.cs @@ -270,6 +270,9 @@ public void FullyConnected() { if (!engineClient.IsLevelMainMenuBackground()) Host.AllowQueuedMaterialSystem(true); + + if (cl.MaxClients == 1 /* && !demoplayer.IsPlayingBack() */) + Scr.NextDrawTick = Host.TickCount + TIME_TO_TICKS(0.25f); } public void Connect(ReadOnlySpan address, string sourceTag) { diff --git a/Source.Engine/Client/ClientState.cs b/Source.Engine/Client/ClientState.cs index 06fb4fb3..7d01b8da 100644 --- a/Source.Engine/Client/ClientState.cs +++ b/Source.Engine/Client/ClientState.cs @@ -951,7 +951,13 @@ public double GetTime() { return tickTime + TickRemainder; } - public bool IsPaused() => Paused; + public bool IsPaused() { + return Paused || + // todo: (g_LostVideoMemory && Host.IsSinglePlayerGame()) || + !Host.Initialized || + // todo: demoplayer.IsPlaybackPaused() || + (EngineVGui != null && EngineVGui.ShouldPause()); + } public double GetPausedExpireTime() => PausedExpireTime; public double GetFrameTime() { if (!ClockDriftMgr.Enabled && InSimulation) { diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs index 2e4b02c3..7da812b1 100644 --- a/Source.Engine/Host.cs +++ b/Source.Engine/Host.cs @@ -118,6 +118,7 @@ public bool IsSinglePlayerGame() { } const TimeUnit_t MAX_FRAMETIME = 0.1; + const TimeUnit_t MIN_FRAMETIME = 0.001; void AccumulateTime(TimeUnit_t dt) { RealTime += dt; @@ -129,6 +130,11 @@ void AccumulateTime(TimeUnit_t dt) { FrameTimeUnbounded = FrameTime; FrameTime = Math.Min(FrameTime, MAX_FRAMETIME * fullscale); } + else { + FrameTimeUnbounded = FrameTime; + FrameTime = Math.Min(FrameTime, MAX_FRAMETIME); + FrameTime = Math.Max(FrameTime, MIN_FRAMETIME); + } soundServices.SetSoundFrametime(dt, FrameTime); } From a718e40255c108169bb65b013e117bda0932c1a5 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Tue, 17 Nov 2026 09:30:20 +0000 Subject: [PATCH 04/12] Some missing lua render funcs --- Game.Client/C_BaseAnimating.cs | 18 + Game.Client/C_BaseViewModel.cs | 4 +- Game.Client/GarrysMod/LuaRender.cs | 348 ++++++++++++++++-- Game.Client/SourceDllMain.cs | 1 + Game.Shared/BaseCombatWeaponShared.cs | 2 +- Game.Shared/GarrysMod/LuaEntity.cs | 80 ++++ Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 12 + Game.Shared/GarrysMod/LuaPlayer.cs | 7 + Game.Shared/GarrysMod/LuaUtil.cs | 31 ++ Game.Shared/GarrysMod/WeaponPhysCannon.cs | 4 +- Game.Shared/GarrysMod/WeaponSWEP.cs | 38 ++ Source.Common/Engine/IModelRender.cs | 1 + .../MaterialSystem/IMaterialSystem.cs | 3 + Source.Common/ShaderAPI/IShaderAPI.cs | 1 + Source.Engine/CdllEngineInterface.cs | 15 +- Source.Engine/GLRSurf.cs | 6 + Source.Engine/ImplStudio.cs | 12 + Source.Engine/Render.cs | 2 +- Source.Engine/RenderUtils.cs | 74 +++- .../MatQueuedRenderContext.cs | 1 + Source.MaterialSystem/MatRenderContext.cs | 1 + Source.MaterialSystem/MatStub.cs | 1 + Source.ShaderAPI.Gl46/ShaderAPIGl46.cs | 1 + 23 files changed, 613 insertions(+), 50 deletions(-) diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs index 0df4f952..e7c57f20 100644 --- a/Game.Client/C_BaseAnimating.cs +++ b/Game.Client/C_BaseAnimating.cs @@ -289,6 +289,24 @@ public void Dispose() { public TimeUnit_t GetPlaybackRate() => PlaybackRate; public void SetPlaybackRate(TimeUnit_t rate) => PlaybackRate = (float)rate; // todo: double? public ref readonly Matrix3x4 GetBone(int bone) => ref BoneAccessor.GetBone(bone); + + public void GetBonePosition(int bone, out Vector3 origin, out QAngle angles) { + GetBoneTransform(bone, out Matrix3x4 boneToWorld); + MathLib.MatrixAngles(boneToWorld, out angles, out origin); + } + + public void GetBoneTransform(int bone, out Matrix3x4 boneToWorld) { + Assert(GetModelPtr() != null && bone >= 0 && bone < GetModelPtr()!.NumBones()); + BoneCache cache = GetBoneCache(null); + + ref Matrix3x4 matrix = ref cache.GetCachedBone(bone); + if (Unsafe.IsNullRef(ref matrix)) { + boneToWorld = EntityToWorldTransform(); + return; + } + + boneToWorld = matrix; + } public ref Matrix3x4 GetBoneForWrite(int bone) => ref BoneAccessor.GetBoneForWrite(bone); BoneMergeCache? BoneMergeCache; diff --git a/Game.Client/C_BaseViewModel.cs b/Game.Client/C_BaseViewModel.cs index 43b00cf5..90e6330c 100644 --- a/Game.Client/C_BaseViewModel.cs +++ b/Game.Client/C_BaseViewModel.cs @@ -83,7 +83,7 @@ public override int DrawModel(StudioFlags flags) { drawnFlags = flags | StudioFlags.Transparency; if ((flags & (StudioFlags.ShadowDepthTexture | StudioFlags.SSAODepthTexture)) != 0) drawnFlags = flags & ~StudioFlags.Transparency; - weapon.ViewModelDrawn(this); + weapon.ViewModelDrawn(this, drawnFlags); } if ((drawnFlags & StudioFlags.Render) != 0 && weapon != null && player != null && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostDrawViewModel)) { @@ -133,7 +133,7 @@ public override int DrawModel(StudioFlags flags) { // Tell the weapon itself that we've rendered, in case it wants to do something if (weapon != null) - weapon.ViewModelDrawn(this); + weapon.ViewModelDrawn(this, flags); } return ret; diff --git a/Game.Client/GarrysMod/LuaRender.cs b/Game.Client/GarrysMod/LuaRender.cs index cd49d92a..7c786d7e 100644 --- a/Game.Client/GarrysMod/LuaRender.cs +++ b/Game.Client/GarrysMod/LuaRender.cs @@ -10,6 +10,7 @@ using TextureFlags = Source.Common.TextureFlags; using System.Numerics; +using Source.Common.Mathematics; #if MENU_DLL namespace Game.MenuSystem.GarrysMod; @@ -127,7 +128,36 @@ static int GetRenderTargetEx(ILuaInterface lua) { // todo: DrawQuad // todo: DrawScreenQuad // todo: DrawScreenQuadEx - // todo: DrawBeam +#if CLIENT_DLL + [LuaFunction] + static int DrawBeam(ILuaInterface lua) { + Vector3 start = LuaVector.Get_Vector(1); + Vector3 end = LuaVector.Get_Vector(2); + float width = (float)lua.CheckNumber(3); + float textureStart = (float)lua.CheckNumber(4); + float textureEnd = (float)lua.CheckNumber(5); + Color color = GetColor(lua.GetObject(6)); + + using MatRenderContextPtr renderContext = new(materials); + BeamSegDraw beamDraw = new(); + beamDraw.Start(renderContext.Context, 2, null); + + BeamSeg seg = default; + seg.Pos = start; + seg.Color = new(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f); + seg.Alpha = color.A / 255.0f; + seg.TexCoord = textureStart; + seg.Width = width; + beamDraw.NextSeg(ref seg); + + seg.Pos = end; + seg.TexCoord = textureEnd; + beamDraw.NextSeg(ref seg); + + beamDraw.End(); + return 0; + } +#endif // todo: StartBeam // todo: AddBeam // todo: EndBeam @@ -141,9 +171,34 @@ static int GetAmbientLightColor(ILuaInterface lua) { LuaVector.Push_Vector(color); return 1; } + + [LuaFunction] + static int GetLightColor(ILuaInterface lua) { + Vector3 position = LuaVector.Get_Vector(1); + LuaVector.Push_Vector(engine.GetLightForPoint(position, false)); + return 1; + } + + [LuaFunction] + static int ComputeDynamicLighting(ILuaInterface lua) { + Vector3 position = LuaVector.Get_Vector(1); + Vector3 normal = LuaVector.Get_Vector(2); + engine.ComputeDynamicLighting(position, normal, out Vector3 color); + LuaVector.Push_Vector(color); + return 1; + } + + [LuaFunction] + static int ComputeLighting(ILuaInterface lua) { + Vector3 position = LuaVector.Get_Vector(1); + Vector3? normal = null; + if (lua.GetType(2) != LuaType.Nil) + normal = LuaVector.Get_Vector(2); + engine.ComputeLighting(position, normal, false, out Vector3 color); + LuaVector.Push_Vector(color); + return 1; + } #endif - // todo: ComputeDynamicLighting - // todo: ComputeLighting // todo: GetSurfaceColor [LuaFunction] @@ -169,9 +224,25 @@ static int GetAmbientLightColor(ILuaInterface lua) { [LuaFunction] static int MaxTextureHeight() => HardwareConfig.MaxTextureHeight(); - // todo: UpdateFullScreenDepthTexture - // todo: GetFullScreenDepthTexture - // todo: GetResolvedFullFrameDepth +#if CLIENT_DLL + [LuaFunction] + static int UpdateFullScreenDepthTexture(ILuaInterface lua) { + ViewScene.UpdateFullScreenDepthTexture(); + return 0; + } + + [LuaFunction] + static int GetFullScreenDepthTexture(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetFullFrameDepthTexture()); + return 1; + } + + [LuaFunction] + static int GetResolvedFullFrameDepth(ILuaInterface lua) { + LuaTexture.Push(materials.FindTexture("_rt_ResolvedFullFrameDepth", MaterialDefines.TEXTURE_GROUP_RENDER_TARGET, true, 0)); + return 1; + } +#endif // todo: BindLocalCubemap static readonly Vector3[] SuppressedAmbientLight = [new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1), new(1, 1, 1)]; @@ -222,10 +293,32 @@ static int UpdateScreenEffectTexture(ILuaInterface lua) { return 0; } #endif - // todo: UpdateRefractTexture - // todo: GetRefractTexture - // todo: UpdatePowerOfTwoTexture - // todo: GetPowerOfTwoTexture +#if CLIENT_DLL + [LuaFunction] + static int UpdateRefractTexture(ILuaInterface lua) { + ViewScene.UpdateRefractTexture(false); + return 0; + } + + [LuaFunction] + static int GetRefractTexture(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetPowerOfTwoFrameBufferTexture()); + return 1; + } + + [LuaFunction] + static int UpdatePowerOfTwoTexture(ILuaInterface lua) { + ViewScene.UpdateRefractTexture(false); + LuaTexture.Push(RenderTexture.GetPowerOfTwoFrameBufferTexture()); + return 1; + } + + [LuaFunction] + static int GetPowerOfTwoTexture(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetPowerOfTwoFrameBufferTexture()); + return 1; + } +#endif #if !MENU_DLL [LuaFunction("GetRenderTarget")] static int GetCurrentRenderTarget(ILuaInterface lua) { @@ -345,10 +438,31 @@ static int GetMoBlurTex1(ILuaInterface lua) { return 1; } #endif - // todo: GetMorphTex0 - // todo: GetMorphTex1 - // todo: GetSmallTex0 - // todo: GetSmallTex1 +#if CLIENT_DLL + [LuaFunction] + static int GetMorphTex0(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetMorphTex0()); + return 1; + } + + [LuaFunction] + static int GetMorphTex1(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetMorphTex1()); + return 1; + } + + [LuaFunction] + static int GetSmallTex0(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetSmallBuffer0()); + return 1; + } + + [LuaFunction] + static int GetSmallTex1(ILuaInterface lua) { + LuaTexture.Push(RenderTexture.GetSmallBuffer1()); + return 1; + } +#endif #if !MENU_DLL [LuaFunction] static int GetSuperFPTex(ILuaInterface lua) { @@ -366,8 +480,17 @@ static int GetSuperFPTex2(ILuaInterface lua) { // todo: SetLocalModelLights // todo: ResetModelLighting // todo: SetModelLighting - // todo: SetAmbientLight #if !MENU_DLL + [LuaFunction] + static int SetAmbientLight(ILuaInterface lua) { + float r = (float)lua.CheckNumber(1); + float g = (float)lua.CheckNumber(2); + float b = (float)lua.CheckNumber(3); + using MatRenderContextPtr renderContext = new(materials); + renderContext.SetAmbientLight(r, g, b); + return 0; + } + [LuaFunction] static int SetLightingOrigin(ILuaInterface lua) { ref Vector3 origin = ref LuaVector.Get_Vector(1); @@ -912,8 +1035,22 @@ static int GetFogDistances(ILuaInterface lua) { } #endif - // todo: GetFogMaxDensity - // todo: FogMaxDensity +#if !MENU_DLL + [LuaFunction] + static int GetFogMaxDensity(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + lua.PushNumber(renderContext.GetFogMaxDensity()); + return 1; + } + + [LuaFunction] + static int FogMaxDensity(ILuaInterface lua) { + double maxDensity = lua.CheckNumber(1); + using MatRenderContextPtr renderContext = new(materials); + renderContext.FogMaxDensity((float)maxDensity); + return 0; + } +#endif [LuaFunction] static int CullMode(ILuaInterface lua) { @@ -967,8 +1104,53 @@ static int GetToneMappingScaleLinear(ILuaInterface lua) { } #endif - // todo: CapturePixels - // todo: ReadPixel +#if !MENU_DLL + static byte[]? CapturedPixels; + static int CapturedPixelsWidth; + static int CapturedPixelsHeight; + + [LuaFunction] + static int CapturePixels(ILuaInterface lua) { + using MatRenderContextPtr renderContext = new(materials); + ITexture? renderTarget = renderContext.GetRenderTarget(); + if (enginevgui.IsConsoleVisible() && !(renderTarget == null ? ViewRender.RenderingView : renderTarget.IsRenderTarget())) + return 0; + + renderContext.GetRenderTargetDimensions(out int width, out int height); + if ((uint)width > 65535 || (uint)height > 65535) + return 0; + + if (CapturedPixels == null || CapturedPixelsWidth != width || CapturedPixelsHeight != height) { + CapturedPixelsWidth = width; + CapturedPixelsHeight = height; + int size = width * height * 4; + if (CapturedPixels == null || CapturedPixels.Length < size) + CapturedPixels = new byte[size]; + } + + renderContext.ReadPixels(0, 0, CapturedPixelsWidth, CapturedPixelsHeight, CapturedPixels, ImageFormat.RGBA8888); + return 0; + } + + [LuaFunction] + static int ReadPixel(ILuaInterface lua) { + int x = (int)lua.CheckNumber(1); + int y = (int)lua.CheckNumber(2); + if ((uint)x < (uint)CapturedPixelsWidth && (uint)y < (uint)CapturedPixelsHeight && CapturedPixels != null) { + int offset = (CapturedPixelsWidth * y + x) * 4; + lua.PushNumber(CapturedPixels[offset]); + lua.PushNumber(CapturedPixels[offset + 1]); + lua.PushNumber(CapturedPixels[offset + 2]); + lua.PushNumber(CapturedPixels[offset + 3]); + return 4; + } + + lua.PushNumber(0); + lua.PushNumber(0); + lua.PushNumber(0); + return 3; + } +#endif [LuaFunction] static int OverrideDepthEnable(ILuaInterface lua) { @@ -1073,19 +1255,115 @@ static int DepthRange(ILuaInterface lua) { #endif // todo: MaterialOverride // todo: MaterialOverrideByIndex - // todo: DrawSphere - // todo: DrawWireframeSphere - // todo: DrawWireframeBox - // todo: DrawBox - // todo: DrawLine +#if CLIENT_DLL + [LuaFunction] + static int DrawSphere(ILuaInterface lua) { + float radius = (float)lua.CheckNumber(2); + int longitudeSteps = (int)lua.CheckNumber(3); + int latitudeSteps = (int)lua.CheckNumber(4); + if (longitudeSteps < 1 || latitudeSteps < 1) { + lua.ErrorFromLua("render.DrawSphere: Arguments #3 and/or #4 have invalid value! (must be 0 or above)"); + return 0; + } + + Color color = GetColor(lua.GetObject(5)); + Vector3 position = LuaVector.Get_Vector(1); + renderUtils.RenderSphere(position, radius, longitudeSteps + 1, latitudeSteps, color, CurrentMaterial.Get()); + return 0; + } + + [LuaFunction] + static int DrawWireframeSphere(ILuaInterface lua) { + float radius = (float)lua.CheckNumber(2); + int longitudeSteps = (int)lua.CheckNumber(3); + int latitudeSteps = (int)lua.CheckNumber(4); + if (longitudeSteps < 1 || latitudeSteps < 1) { + lua.ErrorFromLua("render.DrawSphere: Arguments #3 and/or #4 have invalid value! (must be 0 or above)"); + return 0; + } + + Color color = GetColor(lua.GetObject(5)); + bool writeZ = lua.GetBool(6); + Vector3 position = LuaVector.Get_Vector(1); + renderUtils.RenderWireframeSphere(position, radius, longitudeSteps, latitudeSteps, color, writeZ); + return 0; + } + + [LuaFunction] + static int DrawWireframeBox(ILuaInterface lua) { + Color color = GetColor(lua.GetObject(5)); + bool writeZ = lua.GetBool(6); + Vector3 maxs = LuaVector.Get_Vector(4); + Vector3 mins = LuaVector.Get_Vector(3); + QAngle angles = LuaAngle.Get_Angle(2); + Vector3 position = LuaVector.Get_Vector(1); + renderUtils.RenderWireframeBox(position, angles, mins, maxs, color, writeZ); + return 0; + } + + [LuaFunction] + static int DrawBox(ILuaInterface lua) { + Color color = GetColor(lua.GetObject(5)); + Vector3 maxs = LuaVector.Get_Vector(4); + Vector3 mins = LuaVector.Get_Vector(3); + QAngle angles = LuaAngle.Get_Angle(2); + Vector3 position = LuaVector.Get_Vector(1); + renderUtils.RenderBox(position, angles, mins, maxs, color, CurrentMaterial.Get(), false); + return 0; + } + + [LuaFunction] + static int DrawLine(ILuaInterface lua) { + Color color = GetColor(lua.GetObject(3)); + bool writeZ = lua.GetBool(4); + Vector3 end = LuaVector.Get_Vector(2); + Vector3 start = LuaVector.Get_Vector(1); + renderUtils.RenderLine(start, end, color, writeZ); + return 0; + } +#endif // todo: PushFlashlightMode // todo: PopFlashlightMode - // todo: SetShadowDirection - // todo: SetShadowColor - // todo: SetShadowDistance - // todo: SetShadowsDisabled +#if CLIENT_DLL + [LuaFunction] + static int SetShadowDirection(ILuaInterface lua) { + g_ClientShadowMgr.SetShadowDirection(LuaVector.Get_Vector(1)); + return 0; + } + + [LuaFunction] + static int SetShadowColor(ILuaInterface lua) { + double b = lua.CheckNumber(3); + double g = lua.CheckNumber(2); + double r = lua.CheckNumber(1); + g_ClientShadowMgr.SetShadowColor((byte)(int)r, (byte)(int)g, (byte)(int)b); + return 0; + } + + [LuaFunction] + static int SetShadowDistance(ILuaInterface lua) { + g_ClientShadowMgr.SetShadowDistance((float)lua.CheckNumber(1)); + return 0; + } + + [LuaFunction] + static int SetShadowsDisabled(ILuaInterface lua) { + g_ClientShadowMgr.SetShadowsDisabled(lua.GetBool(1)); + return 0; + } +#endif // todo: WorldMaterialOverride - // todo: BrushMaterialOverride +#if !MENU_DLL + [LuaFunction] + static int BrushMaterialOverride(ILuaInterface lua) { + IMaterial? material = null; + if (lua.IsType(1, LuaType.Material)) + material = (IMaterial?)LuaMaterial.LC_IMaterial.Get(1); + using MatRenderContextPtr renderContext = new(materials); + engine.GMOD_BrushMaterialOverride(material); + return 0; + } +#endif // todo: ModelMaterialOverride #if !MENU_DLL [LuaFunction] @@ -1173,7 +1451,17 @@ static int PopFilterMin(ILuaInterface lua) { renderContext.GMOD_ForceFilterMode(true, FilterMinStack[^1]); return 0; } - // todo: RedownloadAllLightmaps +#if !MENU_DLL + [LuaFunction] + static int RedownloadAllLightmaps(ILuaInterface lua) { + engine.GMOD_R_RedownloadAllLightmaps(lua.GetBool(1)); + if (lua.GetType(2) == LuaType.Bool && lua.GetBool(2)) { + engine.GMOD_R_StudioInitLightingCache(); + modelrender.RestoreAllStaticPropColorData(); + } + return 0; + } +#endif #if !MENU_DLL [LuaFunction] static int SetWriteDepthToDestAlpha(ILuaInterface lua) { diff --git a/Game.Client/SourceDllMain.cs b/Game.Client/SourceDllMain.cs index d53c6437..17d4eb2b 100644 --- a/Game.Client/SourceDllMain.cs +++ b/Game.Client/SourceDllMain.cs @@ -76,6 +76,7 @@ public static void Link(IServiceCollection services) { [Dependency] public static IInput input { get; private set; } = null!; [Dependency] public static IModelRender modelrender { get; private set; } = null!; [Dependency] public static IStudioRender studiorender { get; private set; } = null!; + [Dependency] public static RenderUtils renderUtils { get; private set; } = null!; [Dependency] public static IVEfx effects { get; private set; } = null!; [Dependency] public static IFileSystem filesystem { get; private set; } = null!; [Dependency] public static ISchemeManager vguiSchemeManager { get; private set; } = null!; diff --git a/Game.Shared/BaseCombatWeaponShared.cs b/Game.Shared/BaseCombatWeaponShared.cs index afebe6ff..50d44dfb 100644 --- a/Game.Shared/BaseCombatWeaponShared.cs +++ b/Game.Shared/BaseCombatWeaponShared.cs @@ -345,7 +345,7 @@ public struct PoseParamTable public virtual BaseCombatWeapon? GetLastWeapon() => this; public virtual bool IsOverridingViewmodel() => false; public virtual int DrawOverriddenViewmodel(BaseViewModel viewmodel, StudioFlags flags) => 0; - public virtual void ViewModelDrawn(BaseViewModel viewmodelflags) { } + public virtual void ViewModelDrawn(BaseViewModel viewmodel, StudioFlags flags) { } public virtual int UpdateClientData(BasePlayer player) { WeaponState iNewState = player.GetActiveWeapon() == this ? WeaponState.IsActive : WeaponState.IsCarriedByPlayer; diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index 733bef78..e3dfcef2 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -1180,6 +1180,27 @@ static int Entity__GetBodyGroups(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__GetAttachments(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + StudioHdr? studioHdr = animating != null && !ent.IsEFlagSet(EFL.KillMe) && !animating.IsDynamicModelLoading() ? animating.GetModelPtr() : null; + lua.CreateTable(); + if (studioHdr == null) + return 1; + + for (int i = 0; i < studioHdr.GetNumAttachments(); i++) { + lua.PushNumber(i + 1); + lua.CreateTable(); + lua.PushString(studioHdr.Attachment(i).Name()); + lua.SetField(-2, "name"); + lua.PushNumber(i + 1); + lua.SetField(-2, "id"); + lua.SetTable(-3); + } + return 1; + } + [LuaMethod] static int Entity__GetBodygroup(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -1514,6 +1535,19 @@ static int Entity__SetSkin(ILuaInterface lua) { return 0; } + [LuaMethod] + static int Entity__GetModelBounds(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + Model? model = ent.GetModel(); + if (model == null) + return 0; + + modelinfo.GetModelBounds(model, out Vector3 mins, out Vector3 maxs); + LuaVector.Push_Vector(mins); + LuaVector.Push_Vector(maxs); + return 2; + } + [LuaMethod] static int Entity__SetModel(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -2520,6 +2554,13 @@ static int Entity__GetGroundEntity(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Entity__SetGroundEntity(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + ent.SetGroundEntity(Get_Entity(2, true)); + return 1; + } + [LuaMethod] static int Entity__GetPoseParameterRange(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -3320,6 +3361,32 @@ static int Entity__InvalidateBoneCache(ILuaInterface lua) { ent.GetBaseAnimating()?.InvalidateBoneCache(); return 0; } +#endif + + [LuaMethod] + static int Entity__GetBonePosition(ILuaInterface lua) { + BaseEntity ent = Get_Entity(1, false)!; + BaseAnimating? animating = ent.GetBaseAnimating(); + if (animating == null || ent.IsEFlagSet(EFL.KillMe)) + return 0; + + int bone = (int)lua.CheckNumber(2); + if (bone < 0) + return 0; + +#if CLIENT_DLL + if (animating.IsDynamicModelLoading()) + return 0; +#endif + StudioHdr? hdr = animating.GetModelPtr(); + if (hdr == null || bone >= hdr.NumBones()) + return 0; + + animating.GetBonePosition(bone, out Vector3 origin, out QAngle angles); + LuaVector.Push_Vector(origin); + LuaAngle.Push_Angle(angles); + return 2; + } [LuaMethod] static int Entity__GetBoneMatrix(ILuaInterface lua) { @@ -3333,6 +3400,7 @@ static int Entity__GetBoneMatrix(ILuaInterface lua) { return 0; mdlcache.BeginLock(); +#if CLIENT_DLL if (!animating.IsDynamicModelLoading()) { StudioHdr? hdr = animating.GetModelPtr(); if (hdr != null && bone < hdr.NumBones() && (animating.AccumulatedBoneMask & hdr.BoneFlags(bone)) != 0) { @@ -3343,10 +3411,22 @@ static int Entity__GetBoneMatrix(ILuaInterface lua) { return 1; } } +#else + StudioHdr? hdr = animating.GetModelPtr(); + if (hdr != null && bone < hdr.NumBones()) { + animating.GetBoneTransform(bone, out Matrix3x4 boneToWorld); + Matrix4x4 matrix = default; + matrix.Init(boneToWorld); + LuaVMatrix.Push_VMatrix(matrix); + mdlcache.EndLock(); + return 1; + } +#endif mdlcache.EndLock(); return 0; } +#if CLIENT_DLL [LuaMethod] static int Entity__SetupBones(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs index 379b6d10..9bcd6120 100644 --- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs +++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs @@ -179,6 +179,18 @@ static int PrecacheParticleSystem(ILuaInterface lua) { return 0; } +#if CLIENT_DLL || GAME_DLL + [LuaGlobal] + static int ParticleEffectAttach(ILuaInterface lua) { + int attachment = (int)lua.GetNumber(4); + BaseEntity? ent = LuaEntity.Get_Entity(3, true); + int attachType = (int)lua.GetNumber(2); + ReadOnlySpan name = lua.GetString(1); + // todo: DispatchParticleEffect(name, attachType, ent, attachment, false); + return 0; + } +#endif + [LuaGlobal] static int CompileFile(ILuaInterface lua) { bool showErrors = true; diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index f018cf4b..e2e31df1 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -168,6 +168,13 @@ static int Player__KeyDown(ILuaInterface lua) { return 1; } + [LuaMethod] + static int Player__KeyPressed(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + lua.PushBool(((int)lua.CheckNumber(2) & (int)player.AfButtonPressed) != 0); + return 1; + } + [LuaMethod] static int Player__KeyDownLast(ILuaInterface lua) { BasePlayer player = Get_Player(1, false)!; diff --git a/Game.Shared/GarrysMod/LuaUtil.cs b/Game.Shared/GarrysMod/LuaUtil.cs index 4d4e315f..99718711 100644 --- a/Game.Shared/GarrysMod/LuaUtil.cs +++ b/Game.Shared/GarrysMod/LuaUtil.cs @@ -741,6 +741,37 @@ static int TraceHull(ILuaInterface lua) { return 1; } + [LuaFunction] + static int TraceEntity(ILuaInterface lua) { + if (g_PhysWorldObject == null) + return 0; + + LuaObject data = new(1, LuaType.None); + if (!data.isTable()) { + g_Lua!.TypeError("table", 1); + data.UnReference(); + return 0; + } + + Vector3 start = data.GetMemberVector("start", vec3_origin); + Vector3 end = data.GetMemberVector("endpos", vec3_origin); + Mask mask = (Mask)data.GetMemberUInt("mask", (uint)Mask.Solid); + + TraceFilterLua filter = TraceFilterFromTable(data); + + BaseEntity ent = LuaEntity.Get_Entity(2, false)!; + Util.TraceEntity(ent, start, end, mask, ref filter, out Trace tr); + + LuaObject output = new(); + data.GetMember("output", output); + PushTableFromTrace(ref tr, output); + output.UnReference(); + + filter.Function.UnReference(); + data.UnReference(); + return 1; + } + static TraceFilterLua TraceFilterFromTable(LuaObject data) { TraceFilterLua filter = new((CollisionGroup)data.GetMemberInt("collisiongroup", 0)); filter.SetIgnoreWorld(data.GetMemberBool("ignoreworld", false)); diff --git a/Game.Shared/GarrysMod/WeaponPhysCannon.cs b/Game.Shared/GarrysMod/WeaponPhysCannon.cs index 0aaf2190..64b247c2 100644 --- a/Game.Shared/GarrysMod/WeaponPhysCannon.cs +++ b/Game.Shared/GarrysMod/WeaponPhysCannon.cs @@ -777,9 +777,9 @@ public override int DrawModel(StudioFlags flags) { return base.DrawModel(flags); } - public override void ViewModelDrawn(BaseViewModel viewmodelflags) { + public override void ViewModelDrawn(BaseViewModel viewmodel, StudioFlags flags) { DrawEffects(); - base.ViewModelDrawn(viewmodelflags); + base.ViewModelDrawn(viewmodel, flags); } public void UpdateElementPosition() { BasePlayer? owner = ToBasePlayer(GetOwner()); diff --git a/Game.Shared/GarrysMod/WeaponSWEP.cs b/Game.Shared/GarrysMod/WeaponSWEP.cs index 3b97487b..9aef6941 100644 --- a/Game.Shared/GarrysMod/WeaponSWEP.cs +++ b/Game.Shared/GarrysMod/WeaponSWEP.cs @@ -297,6 +297,44 @@ public override bool Holster(BaseCombatWeapon? switchingTo) { } #if CLIENT_DLL + static StudioFlags DrawModelFlags; + static bool InDrawModel; + + public override int DrawModel(StudioFlags flags) { + if (!ShouldDrawInView()) + return 0; + + C_BasePlayer? localPlayer = C_BasePlayer.GetLocalPlayer(); + if (localPlayer != null && GetOwner() == localPlayer && !C_BasePlayer.ShouldDrawLocalPlayer()) + return 0; + + if (InDrawModel) + return base.DrawModel(DrawModelFlags); + + DrawModelFlags = flags; + UpdateLuaData(true); + InDrawModel = true; + + if (!ScriptedEntity.StartFunction((int)((int)flags < 0 ? LUA_POOLEDSTRING.DrawWorldModelTranslucent : LUA_POOLEDSTRING.DrawWorldModel))) { + InDrawModel = false; + return 1; + } + + g_Lua!.PushNumber((int)flags); + ScriptedEntity.Call(1, 0); + InDrawModel = false; + return 1; + } + + public override void ViewModelDrawn(BaseViewModel viewmodel, StudioFlags flags) { + if (!ScriptedEntity.StartFunction((int)LUA_POOLEDSTRING.ViewModelDrawn)) + return; + + LuaEntity.Push_Entity(viewmodel); + g_Lua!.PushNumber((int)flags); + ScriptedEntity.Call(2, 0); + } + public virtual void CreateMoveThink() { UpdateLuaData(true); ScriptedEntity.CallFunction((int)LUA_POOLEDSTRING.Think, false); diff --git a/Source.Common/Engine/IModelRender.cs b/Source.Common/Engine/IModelRender.cs index 376dfebb..acd3ad67 100644 --- a/Source.Common/Engine/IModelRender.cs +++ b/Source.Common/Engine/IModelRender.cs @@ -79,4 +79,5 @@ public interface IModelRender bool DrawModelShadowSetup(IClientRenderable renderable, int body, int skin, ref Source.Common.DrawModelInfo info, Span customBoneToWorld, out Span boneToWorldOut); void DrawModelShadow(IClientRenderable renderable, in Source.Common.DrawModelInfo info, Span boneToWorld); void SuppressEngineLighting(bool suppress); + void RestoreAllStaticPropColorData(); } diff --git a/Source.Common/MaterialSystem/IMaterialSystem.cs b/Source.Common/MaterialSystem/IMaterialSystem.cs index 33c83378..417a5462 100644 --- a/Source.Common/MaterialSystem/IMaterialSystem.cs +++ b/Source.Common/MaterialSystem/IMaterialSystem.cs @@ -1229,6 +1229,7 @@ void DrawScreenSpaceRectangle( IMesh? GetDynamicMeshEx(VertexFormat vertexFormat, bool buffered = true, IMesh? vertexOverride = null, IMesh? indexOverride = null, IMaterial? autoBind = null); void FogMaxDensity(float maxDensity); + float GetFogMaxDensity(); void FogRadial(bool radial); bool GetFogRadial(); @@ -1535,6 +1536,8 @@ public void FogMaxDensity(float maxDensity) { Context.FogMaxDensity(maxDensity); } + public float GetFogMaxDensity() => Context.GetFogMaxDensity(); + public void FogMode(MaterialFogMode fogMode) { Context.FogMode(fogMode); } diff --git a/Source.Common/ShaderAPI/IShaderAPI.cs b/Source.Common/ShaderAPI/IShaderAPI.cs index 180e213d..58a81e4c 100644 --- a/Source.Common/ShaderAPI/IShaderAPI.cs +++ b/Source.Common/ShaderAPI/IShaderAPI.cs @@ -276,6 +276,7 @@ void SetRenderTarget(ShaderAPITextureHandle_t colorTextureHandle = (ShaderAPITex void SceneFogMode(MaterialFogMode fogMode); void SceneFogRadial(bool radial); bool GetSceneFogRadial(); + float GetFogMaxDensity(); // Can we download textures? bool CanDownloadTextures(); diff --git a/Source.Engine/CdllEngineInterface.cs b/Source.Engine/CdllEngineInterface.cs index 5bc95ff2..89b4caa2 100644 --- a/Source.Engine/CdllEngineInterface.cs +++ b/Source.Engine/CdllEngineInterface.cs @@ -645,12 +645,13 @@ public void GMOD_SetViewEntity(ClientEntityHandle entity) { throw new NotImplementedException(); } - public void GMOD_BrushMaterialOverride(IMaterial? matOverride) { - throw new NotImplementedException(); - } + public void GMOD_BrushMaterialOverride(IMaterial? matOverride) => BrushBatchRender.BrushMaterialOverride.Init(matOverride); - public void GMOD_R_RedownloadAllLightmaps(bool unk) { - throw new NotImplementedException(); + public void GMOD_R_RedownloadAllLightmaps(bool deferred) { + if (!deferred) + Render.RedownloadAllLightmaps(); + else + Render.RebuildLightmaps(); } public void GMOD_RawClientCmd_Unrestricted(ReadOnlySpan command) { @@ -675,9 +676,7 @@ public ReadOnlySpan GMOD_TranslateAlias(ReadOnlySpan cmd) { throw new NotImplementedException(); } - public void GMOD_R_StudioInitLightingCache() { - throw new NotImplementedException(); - } + public void GMOD_R_StudioInitLightingCache() => Render.R_StudioInitLightingCache(); public int PrecacheSentenceFile(ReadOnlySpan fileName) { throw new NotImplementedException(); diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index c6b5918c..81f27cff 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -1690,6 +1690,8 @@ public void ClearRenderHandles() { return renderT; } + public static readonly MaterialReference BrushMaterialOverride = new(); + public void DrawOpaqueBrushModel(IClientEntity? baseEntity, Model? model, in Vector3 origin, RenderDepthMode depthMode) { SurfaceHandle_t firstSurfID = model!.Brush.FirstModelSurface; @@ -1740,6 +1742,8 @@ public void DrawOpaqueBrushModel(IClientEntity? baseEntity, Model? model, in Vec } else { material = batch.Material; + if (BrushMaterialOverride.IsNotNull) + material = BrushMaterialOverride.Get(); ModulateMaterial(material!, oldColor); if (!skipLight) @@ -1950,6 +1954,8 @@ private void DrawTransLists(ref TransRender renderT, object? proxyData) { MeshBuilder meshBuilder = new(); IMaterial material = batch.Material!; + if (BrushMaterialOverride.IsNotNull) + material = BrushMaterialOverride.Get()!; ModulateMaterial(material, oldColor); diff --git a/Source.Engine/ImplStudio.cs b/Source.Engine/ImplStudio.cs index 613abb3f..943958af 100644 --- a/Source.Engine/ImplStudio.cs +++ b/Source.Engine/ImplStudio.cs @@ -1403,6 +1403,18 @@ private void ComputeModelVertexLightingOld(StudioHeader studioHdr, MStudioModel } } + public void RestoreAllStaticPropColorData() { +#if !SWDS + if (host_state.WorldModel == null) + return; + + Render.InvalidateStaticLightingCache(); + + foreach (KeyValuePair instance in ModelInstances) + UpdateStaticPropColorData(instance.Value.Renderable!.GetIClientUnknown(), instance.Key); +#endif + } + private bool UpdateStaticPropColorData(IHandleEntity? pProp, ModelInstanceHandle_t handle) { #if !SWDS ColorMeshData? colorMeshData = FindOrCreateStaticPropColorData(handle); diff --git a/Source.Engine/Render.cs b/Source.Engine/Render.cs index 323b47ce..9ec18c11 100644 --- a/Source.Engine/Render.cs +++ b/Source.Engine/Render.cs @@ -821,7 +821,7 @@ public void CheckForLightingConfigChanges() { } } - private void RedownloadAllLightmaps() { + public void RedownloadAllLightmaps() { double st = Sys.Time; bool onlyUseLightStyles = false; diff --git a/Source.Engine/RenderUtils.cs b/Source.Engine/RenderUtils.cs index 5d6ac672..feb95eb6 100644 --- a/Source.Engine/RenderUtils.cs +++ b/Source.Engine/RenderUtils.cs @@ -141,7 +141,7 @@ float depth renderContext.PopMatrix(); } - internal void RenderLine(in Vector3 start, in Vector3 end, in Color color, bool zBuffer) { + public void RenderLine(in Vector3 start, in Vector3 end, in Color color, bool zBuffer) { InitializeStandardMaterials(); using MatRenderContextPtr renderContext = new(materials); @@ -215,7 +215,7 @@ internal void RenderTriangle(in Vector3 p1, in Vector3 p2, in Vector3 p3, in Col mesh.Draw(); } - internal void RenderBox(in Vector3 origin, in Vector3 angles, in Vector3 mins, in Vector3 maxs, in Color color, bool zBuffer, bool insideOut = false) { + public void RenderBox(in Vector3 origin, in Vector3 angles, in Vector3 mins, in Vector3 maxs, in Color color, bool zBuffer, bool insideOut = false) { IMaterial pMaterial = zBuffer ? VertexColor : VertexColorIgnoreZ; RenderBox(origin, angles, mins, maxs, color, pMaterial, insideOut); } @@ -245,7 +245,7 @@ internal void RenderBox(in Vector3 origin, in Vector3 angles, in Vector3 mins, i IMaterial VertexColor = null!; IMaterial VertexColorIgnoreZ = null!; - private void RenderBox(Vector3 origin, Vector3 angles, Vector3 mins, Vector3 maxs, Color color, IMaterial pMaterial, bool insideOut) { + public void RenderBox(Vector3 origin, Vector3 angles, Vector3 mins, Vector3 maxs, Color color, IMaterial pMaterial, bool insideOut) { InitializeStandardMaterials(); using MatRenderContextPtr pRenderContext = new(materials); @@ -342,7 +342,69 @@ private void InitializeStandardMaterials() { VertexColorIgnoreZ = materials.CreateMaterial("__utilVertexColorIgnoreZ", pVMTKeyValues); } - internal void RenderWireframeBox(in Vector3 origin, in Vector3 angles, in Vector3 mins, in Vector3 maxs, in Color color, bool zBuffer) { + public void RenderWireframeSphere(in Vector3 center, float radius, int theta, int phi, in Color c, bool zBuffer) { + InitializeStandardMaterials(); + + ++theta; + + int vertices = phi * theta; + int indices = (theta - 1) * 4 * (phi - 1); + + using MatRenderContextPtr renderContext = new(materials); + renderContext.Bind(zBuffer ? Wireframe : WireframeIgnoreZ); + + MeshBuilder meshBuilder = new(); + IMesh mesh = renderContext.GetDynamicMesh(); + + meshBuilder.Begin(mesh, MaterialPrimitiveType.Lines, vertices, indices); + + byte chRed = c.R; + byte chGreen = c.G; + byte chBlue = c.B; + byte chAlpha = c.A; + + int i, j; + for (i = 0; i < phi; ++i) { + for (j = 0; j < theta; ++j) { + float u = j / (float)(theta - 1); + float v = i / (float)(phi - 1); + float t = 2.0f * MathF.PI * u; + float p = MathF.PI * v; + + (float sinTheta, float cosTheta) = MathF.SinCos(t); + (float sinPhi, float cosPhi) = MathF.SinCos(p); + + meshBuilder.Position3f(center.X + (radius * sinPhi * cosTheta), + center.Y + (radius * sinPhi * sinTheta), + center.Z + (radius * cosPhi)); + meshBuilder.Color4ub(chRed, chGreen, chBlue, chAlpha); + meshBuilder.AdvanceVertex(); + } + } + + for (i = 0; i < phi - 1; ++i) { + for (j = 0; j < theta - 1; ++j) { + int idx = theta * i + j; + + meshBuilder.Index((ushort)idx); + meshBuilder.AdvanceIndex(); + + meshBuilder.Index((ushort)(idx + theta)); + meshBuilder.AdvanceIndex(); + + meshBuilder.Index((ushort)idx); + meshBuilder.AdvanceIndex(); + + meshBuilder.Index((ushort)(idx + 1)); + meshBuilder.AdvanceIndex(); + } + } + + meshBuilder.End(); + mesh.Draw(); + } + + public void RenderWireframeBox(in Vector3 origin, in Vector3 angles, in Vector3 mins, in Vector3 maxs, in Color color, bool zBuffer) { InitializeStandardMaterials(); using MatRenderContextPtr pRenderContext = new(materials); @@ -379,7 +441,7 @@ internal void RenderWireframeBox(in Vector3 origin, in Vector3 angles, in Vector pMesh.Draw(); } - internal void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, IMaterial material) { + public void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, IMaterial material) { InitializeStandardMaterials(); using MatRenderContextPtr renderContext = new(materials); @@ -457,7 +519,7 @@ internal void RenderSphere(in Vector3 center, float radius, int theta, int phi, mesh.Draw(); } - internal void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, bool zBuffer) { + public void RenderSphere(in Vector3 center, float radius, int theta, int phi, in Color c, bool zBuffer) { IMaterial material = zBuffer ? VertexColor : VertexColorIgnoreZ; Color actual = new(c.R, c.G, c.B, c.A); RenderSphere(center, radius, theta, phi, actual, material); diff --git a/Source.MaterialSystem/MatQueuedRenderContext.cs b/Source.MaterialSystem/MatQueuedRenderContext.cs index 74297c61..d51e56b6 100644 --- a/Source.MaterialSystem/MatQueuedRenderContext.cs +++ b/Source.MaterialSystem/MatQueuedRenderContext.cs @@ -398,6 +398,7 @@ public void FogRadial(bool radial) { } public bool GetFogRadial() => FogRadialValue; + public float GetFogMaxDensity() => FogMaxDensityValue; public MaterialFogMode GetFogMode() => FogModeValue; diff --git a/Source.MaterialSystem/MatRenderContext.cs b/Source.MaterialSystem/MatRenderContext.cs index ef49153f..4db66110 100644 --- a/Source.MaterialSystem/MatRenderContext.cs +++ b/Source.MaterialSystem/MatRenderContext.cs @@ -714,6 +714,7 @@ public void FogColor3fv(ReadOnlySpan rgb) { public void FogRadial(bool radial) => shaderAPI.SceneFogRadial(radial); public bool GetFogRadial() => shaderAPI.GetSceneFogRadial(); + public float GetFogMaxDensity() => shaderAPI.GetFogMaxDensity(); public void GMOD_FlushQueue() { throw new NotImplementedException("Incomplete port of IMatRenderContext"); diff --git a/Source.MaterialSystem/MatStub.cs b/Source.MaterialSystem/MatStub.cs index 1f147e7e..10264657 100644 --- a/Source.MaterialSystem/MatStub.cs +++ b/Source.MaterialSystem/MatStub.cs @@ -558,6 +558,7 @@ public void SetFogZ(float fogZ) { } public MaterialFogMode GetFogMode() => MaterialFogMode.None; public void FogRadial(bool radial) { } public bool GetFogRadial() => false; + public float GetFogMaxDensity() => 1.0f; public void FogColor3f(float r, float g, float b) { } public void FogColor3fv(ReadOnlySpan rgb) { } public void FogColor3ub(byte r, byte g, byte b) { } diff --git a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs index aebcec60..ab8ef9b3 100644 --- a/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs +++ b/Source.ShaderAPI.Gl46/ShaderAPIGl46.cs @@ -973,6 +973,7 @@ public void SceneFogRadial(bool radial) { } public bool GetSceneFogRadial() => SceneFogRadialValue; + public float GetFogMaxDensity() => FogMaxDensityValue; private void InitVertexAndPixelShaders() { // TODO; everything before this call From f4aa2e773411452a0cca076a3f29f2bd38f8e311 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 19 Nov 2026 07:52:12 +0000 Subject: [PATCH 05/12] Sun --- Game.Client/C_Sun.cs | 2 +- Game.Server/Sun.cs | 96 +++++++++++++++++++++++++++++- Game.Shared/GarrysMod/LuaEntity.cs | 20 +++++-- Game.Shared/GarrysMod/LuaPlayer.cs | 9 +++ Source.Common/MapUtils.cs | 41 +++++++++++++ 5 files changed, 162 insertions(+), 6 deletions(-) create mode 100644 Source.Common/MapUtils.cs diff --git a/Game.Client/C_Sun.cs b/Game.Client/C_Sun.cs index 302344d2..6fa20594 100644 --- a/Game.Client/C_Sun.cs +++ b/Game.Client/C_Sun.cs @@ -42,5 +42,5 @@ public partial class C_Sun : C_BaseEntity public int OverlayMaterial; // todo: RecvProxy_HDRColorScale [NetworkVar("HDRColorScale")] - public int HDRColorScale; + public float HDRColorScale; } \ No newline at end of file diff --git a/Game.Server/Sun.cs b/Game.Server/Sun.cs index 07ffac06..ef81b32b 100644 --- a/Game.Server/Sun.cs +++ b/Game.Server/Sun.cs @@ -2,6 +2,8 @@ using Source; using Source.Common; +using Source.Common.Engine; +using Source.Common.Mathematics; using System.Numerics; @@ -24,6 +26,98 @@ public partial class Sun : BaseEntity new(nameof(HDRColorScale)) { Encoding = NetEncoding.Float, Bits = 0, Flags = PropFlags.NoScale, Low = 0.0f, High = 100.0f }, ]; + public static readonly new DataMap DataDesc = new(typeof(Sun), BaseEntity.DataDesc, [ + DEFINE.FIELD(nameof(Direction), FieldType.Vector), + + DEFINE.KEYFIELD(nameof(UseAngles), FieldType.Integer, "use_angles"), + DEFINE.KEYFIELD(nameof(Pitch), FieldType.Float, "pitch"), + DEFINE.KEYFIELD(nameof(Yaw), FieldType.Float, "angle"), + DEFINE.KEYFIELD(nameof(Size), FieldType.Integer, "size"), + DEFINE.KEYFIELD(nameof(Overlay), FieldType.Color32, "overlaycolor"), + DEFINE.KEYFIELD(nameof(OverlaySize), FieldType.Integer, "overlaysize"), + DEFINE.KEYFIELD(nameof(StrMaterial), FieldType.String, "material"), + DEFINE.KEYFIELD(nameof(StrOverlayMaterial), FieldType.String, "overlaymaterial"), + + DEFINE.FIELD(nameof(On), FieldType.Boolean), + + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((Sun)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((Sun)self).InputTurnOff(data))), + DEFINE.INPUTFUNC(FieldType.Color32, "SetColor", nameof(InputSetColor), (INPUTFUNCPTR)((self, data) => ((Sun)self).InputSetColor(data))), + + DEFINE.KEYFIELD(nameof(HDRColorScale), FieldType.Float, "HDRColorScale"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public Sun() { + Direction = new(0, 0, 1); + + UseAngles = 0; + Pitch = 0; + Yaw = 0; + Size = 16; + + On = true; + AddEFlags(EFL.ForceCheckTransmit); + + StrMaterial = null; + StrOverlayMaterial = null; + OverlaySize = -1; + } + + public override void Activate() { + base.Activate(); + + if (UseAngles != 0) { + MapUtils.SetupLightNormalFromProps(GetAbsAngles(), Yaw, Pitch, out Vector3 direction); + Direction = -direction; + } + else { + BaseEntity? ent = gEntList.FindEntityByName(null, Target); + if (ent != null) { + Vector3 direction = GetAbsOrigin() - ent.GetAbsOrigin(); + MathLib.VectorNormalize(ref direction); + Direction = direction; + } + } + + if (OverlaySize == -1) + OverlaySize = Size; + + if (StrMaterial == null) + StrMaterial = "sprites/light_glow02_add_noz.vmt"; + else if (StrMaterial.AsSpan().GetFileExtension().IsEmpty) + StrMaterial += ".vmt"; + + if (StrOverlayMaterial == null) + StrOverlayMaterial = "sprites/light_glow02_add_noz.vmt"; + else if (StrOverlayMaterial.AsSpan().GetFileExtension().IsEmpty) + StrOverlayMaterial += ".vmt"; + + Material = PrecacheModel(StrMaterial); + OverlayMaterial = PrecacheModel(StrOverlayMaterial); + } + + void InputTurnOn(InputData inputdata) { + if (!On) + On = true; + } + + void InputTurnOff(InputData inputdata) { + if (On) + On = false; + } + + void InputSetColor(InputData inputdata) => Render = inputdata.Value.Color32(); + + public override EdictFlags UpdateTransmitState() => SetTransmitState(EdictFlags.Always); + + public string? StrMaterial; + public string? StrOverlayMaterial; + + public int UseAngles; + public float Pitch; + public float Yaw; + [NetworkVar("m_clrRender")] public partial Color Render { get; set; } [NetworkVar("m_clrOverlay")] @@ -41,5 +135,5 @@ public partial class Sun : BaseEntity [NetworkVar("m_nOverlayMaterial")] public partial int OverlayMaterial { get; set; } [NetworkVar("HDRColorScale")] - public partial int HDRColorScale { get; set; } + public partial float HDRColorScale { get; set; } } diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index e3dfcef2..d4efc4d3 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -2231,7 +2231,7 @@ static int Entity__SetSaveValue(ILuaInterface lua) { TypeDescription? td = null; for (DataMap? map = ent.GetDataDescMap(); map != null && td == null; map = map.BaseMap) { foreach (TypeDescription field in map.DataDesc) { - if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(ReallyUglyHack(name), field.FieldName) == 0))) { td = field; break; } @@ -2240,7 +2240,7 @@ static int Entity__SetSaveValue(ILuaInterface lua) { #if CLIENT_DLL for (DataMap? map = ent.GetPredDescMap(); map != null && td == null; map = map.BaseMap) { foreach (TypeDescription field in map.DataDesc) { - if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(ReallyUglyHack(name), field.FieldName) == 0))) { td = field; break; } @@ -2461,6 +2461,18 @@ static void PushInternalValue(TypeDescription td, object? value) { } } + // FIXME FIXME FIXME + // datadesc stores c# names rn.. + static ReadOnlySpan ReallyUglyHack(ReadOnlySpan name) { + if (name.Length < 3 || name[0] != 'm' || name[1] != '_') + return name; + name = name[2..]; + int i = 0; + while (i < name.Length && char.IsLower(name[i])) + i++; + return i == name.Length ? name : name[i..]; + } + [LuaMethod] static int Entity__GetInternalVariable(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; @@ -2469,7 +2481,7 @@ static int Entity__GetInternalVariable(ILuaInterface lua) { TypeDescription? td = null; for (DataMap? map = ent.GetDataDescMap(); map != null && td == null; map = map.BaseMap) { foreach (TypeDescription field in map.DataDesc) { - if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(ReallyUglyHack(name), field.FieldName) == 0))) { td = field; break; } @@ -2478,7 +2490,7 @@ static int Entity__GetInternalVariable(ILuaInterface lua) { #if CLIENT_DLL for (DataMap? map = ent.GetPredDescMap(); map != null && td == null; map = map.BaseMap) { foreach (TypeDescription field in map.DataDesc) { - if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(name, field.FieldName) == 0))) { + if (field.Flags != FieldTypeDescFlags.Input && (field.Flags & FieldTypeDescFlags.Output) == 0 && ((field.ExternalName.Length != 0 && stricmp(name, field.ExternalName) == 0) || (field.FieldName.Length != 0 && stricmp(ReallyUglyHack(name), field.FieldName) == 0))) { td = field; break; } diff --git a/Game.Shared/GarrysMod/LuaPlayer.cs b/Game.Shared/GarrysMod/LuaPlayer.cs index e2e31df1..bd772c5e 100644 --- a/Game.Shared/GarrysMod/LuaPlayer.cs +++ b/Game.Shared/GarrysMod/LuaPlayer.cs @@ -894,6 +894,15 @@ static int Player__SendLua(ILuaInterface lua) { } return 0; } + + [LuaMethod] + static int Player__PrintMessage(ILuaInterface lua) { + BasePlayer player = Get_Player(1, false)!; + ReadOnlySpan msg = lua.CheckString(3); + HudPrint type = (HudPrint)(int)lua.CheckNumber(2); + Util.ClientPrint(player, type, msg); + return 0; + } #endif [LuaMethod] diff --git a/Source.Common/MapUtils.cs b/Source.Common/MapUtils.cs new file mode 100644 index 00000000..17edc5c2 --- /dev/null +++ b/Source.Common/MapUtils.cs @@ -0,0 +1,41 @@ +using Source.Common.Mathematics; + +using System.Numerics; + +using static Source.Common.Formats.BSP.BSPFileCommon; +using static Source.Common.Mathematics.MathLib; +using static Source.Common.Mathematics.MathLibConsts; + +namespace Source.Common; + +public static class MapUtils +{ + public static void SetupLightNormalFromProps(in QAngle angles, float angle, float pitch, out Vector3 output) { + output = default; + if (angle == ANGLE_UP) { + output.X = output.Y = 0; + output.Z = 1; + } + else if (angle == ANGLE_DOWN) { + output.X = output.Y = 0; + output.Z = -1; + } + else { + if (angle == 0) + angle = angles[YAW]; + + output.Z = 0; + + SinCos(DEG2RAD(angle), out output.Y, out output.X); + } + + if (pitch == 0) + pitch = angles[PITCH]; + + SinCos(DEG2RAD(pitch), out float sin, out float cos); + + output.X *= cos; + output.Y *= cos; + output.Z = sin; + } +} From 32de7956cb1a8bc1996c42fffd67c7fe4348319f Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 25 Nov 2026 20:45:18 +0000 Subject: [PATCH 06/12] more map cleanup impl --- Game.Server/AI_DynamicLink.cs | 12 ++++++++++++ Game.Server/BaseEntity.cs | 4 ++++ Game.Server/Util.cs | 1 + Game.Shared/GarrysMod/GMODGameRules.cs | 21 ++++++++++++--------- Game.Shared/GarrysMod/LuaGame.cs | 26 ++++++++++++++++++++------ Game.Shared/GarrysMod/LuaGameSystem.cs | 8 ++++++++ 6 files changed, 57 insertions(+), 15 deletions(-) diff --git a/Game.Server/AI_DynamicLink.cs b/Game.Server/AI_DynamicLink.cs index 2a6b2386..53fdb710 100644 --- a/Game.Server/AI_DynamicLink.cs +++ b/Game.Server/AI_DynamicLink.cs @@ -273,6 +273,18 @@ public static void ResetDynamicLinks() { } } + public static void PurgeDynamicLinks() { + AI_DynamicLink? dynamicLink = AllDynamicLinks; + + while (dynamicLink != null) { + // todo: Editor_DeleteNodeLink + if (!dynamicLink.IsLinkValid()) + Util.Remove(dynamicLink); + + dynamicLink = dynamicLink.NextDynamicLink; + } + } + public bool IsLinkValid() { AI_Node node = g_pBigAINet!.GetNode(SrcID)!; return !Unsafe.IsNullRef(ref node.GetLink(DestID)); diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 8a007cf7..a9a071b8 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -934,6 +934,7 @@ public virtual bool IsViewable() { } public virtual void UpdateOnRemove() { + Util.g_bRemovingEntity++; Util.g_bReceivedChainedUpdateOnRemove = true; #if GMOD_DLL @@ -1013,6 +1014,7 @@ public virtual void UpdateOnRemove() { modelinfo.ReleaseDynamicModel(ModelIndex); // no-op if not dynamic ModelIndex = -1; } + Util.g_bRemovingEntity--; } public string GetDebugName() { @@ -3143,6 +3145,7 @@ public static void PrecacheModelComponents(int modelIndex) { /// see CBaseEntity::~CBaseEntity() etc /// public virtual void Term() { + Util.g_bRemovingEntity++; VPhysicsDestroyObject(); // Need to remove references to this entity before EHANDLES go null @@ -3163,6 +3166,7 @@ public virtual void Term() { LuaTableObject?.UnReference(); LuaTableObject = null; LuaCalcAbsolutePosition.UnReference(); + Util.g_bRemovingEntity--; CollisionProp().DestroyPartitionHandle(); diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 07102295..4d033fda 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -344,6 +344,7 @@ public static void EmitAmbientSound(int entindex, in Vector3 vecOrigin, ReadOnly } public static bool g_bDisableEhandleAccess = false; + public static int g_bRemovingEntity = 0; public static bool g_bReceivedChainedUpdateOnRemove = false; public static void LogPrintf(ReadOnlySpan text) { engine.LogPrint(text); diff --git a/Game.Shared/GarrysMod/GMODGameRules.cs b/Game.Shared/GarrysMod/GMODGameRules.cs index f99d77d2..bafdcf62 100644 --- a/Game.Shared/GarrysMod/GMODGameRules.cs +++ b/Game.Shared/GarrysMod/GMODGameRules.cs @@ -878,16 +878,19 @@ static bool CleanupFilterContains(ILuaObject? filters, ReadOnlySpan classN ILuaInterface lua = g_Lua!; filters.Push(); - lua.PushNil(); - while (lua.Next(-2)) { - if (lua.GetString(-1) is string value && className.SequenceEqual(value)) { - lua.Pop(3); + for (int i = 1; ; i++) { + lua.PushNumber(i); + lua.GetTable(-2); + if (lua.GetType(-1) != LuaType.String) { + lua.Pop(2); + return false; + } + if (strcmp(lua.GetString(-1), className) == 0) { + lua.Pop(2); return true; } lua.Pop(1); } - lua.Pop(1); - return false; } sealed class GMODMapEntityFilter(ILuaObject? filters) : IMapEntityFilter @@ -917,8 +920,8 @@ public bool ShouldCreateEntity(ReadOnlySpan className) { public void CleanUpMap(ILuaObject? filters) { BaseEntity? ent = gEntList.FirstEnt(); AI_DynamicLink.gm_bInitialized = false; - // todo: AI_DynamicLink.PurgeDynamicLinks(); - // todo: AI_DynamicLink.ResetStates(); + AI_DynamicLink.PurgeDynamicLinks(); + AI_DynamicLink.ResetDynamicLinks(); CleaningUpMap = true; while (ent != null) { @@ -943,7 +946,7 @@ public void CleanUpMap(ILuaObject? filters) { MapEntity_ParseAllEntities(engine.GetMapEntitiesString(), new GMODMapEntityFilter(filters), true); AI_DynamicLink.InitDynamicLinks(); - // todo: unidentified reset call that follows InitDynamicLinks + Game.Server.NavMesh.NavMesh.Instance?.Load(); } #endif } diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index 18987026..37afd7af 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -149,7 +149,11 @@ static int SetGlobalCounter(ILuaInterface lua) { [LuaFunction] static int CleanUpMap(ILuaInterface lua) { - // todo: refuse with "Cannot run game.CleanUpMap while deleting entities!\n" while entities are being deleted + if (Util.g_bRemovingEntity > 0 || Util.g_bDisableEhandleAccess) { + lua.ErrorFromLua("Cannot run game.CleanUpMap while deleting entities!\n"); + return 0; + } + if (MapCleanupRunning || MapCleanupPending) { lua.ErrorFromLua("Cannot run game.CleanUpMap while it is already running!\n"); return 0; @@ -198,13 +202,18 @@ static void DoCleanUpMap(bool dontSendToClients, ILuaObject filters) { GarrysMod.BroadcastLua(filter, "game.CleanUpMap()"); } - // todo: unidentified step between the client broadcast and AllowImmediateEdictReuse + // todo: s_RagdollLRU.RemoveAll() engine.AllowImmediateEdictReuse(); gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap); MapCleanupRunning = false; } + public static void ResetMapCleanupSchedule() { + MapCleanupPending = false; + MapCleanupDontSendToClients = false; + } + public static void RunMapCleanupIfNeeded() { if (!MapCleanupPending) return; @@ -259,12 +268,17 @@ static void DoCleanUpMap() { MapCleanupRunning = true; gGM?.Call((int)LUA_POOLEDSTRING.PreCleanupMap); - // todo: remove the Lua-created clientside entities + // todo: C_PhysPropClientside.RecreateAll() engine.ClientCmd("r_cleardecals\n"); enginesound.StopAllSounds(true); - // todo: unidentified call that follows StopAllSounds - // todo: release every C_Hairball in the client entity list - // todo: unidentified step before the PostCleanupMap hook + Soundscape_OnStopAllSounds(); + List hairballs = []; + for (C_BaseEntity? ent = cl_entitylist.FirstBaseEntity(); ent != null; ent = cl_entitylist.NextBaseEntity(ent)) + if (!ent.IsEFlagSet(EFL.KillMe) && strcmp(ent.GetClassname(), "class C_Hairball") == 0) + hairballs.Add(ent); + foreach (C_BaseEntity ent in hairballs) + ent.Release(); + // todo: s_RagdollLRU.RemoveAll() gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap); MapCleanupRunning = false; diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index 19b30959..f1a12bf1 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -128,7 +128,15 @@ public override bool Init() { return true; } +#if GAME_DLL + public override void LevelShutdownPostEntity() { + // todo: EmptyLoopingSounds(); + LuaGame.ResetMapCleanupSchedule(); + // todo: RemoveQueuedRecipientFilters(); + } +#else // todo LevelShutdownPostEntity +#endif public void FireGameEvent(IGameEvent ev) { #if CLIENT_DLL From 8f6d9f87b56eed19f81bf55f4bb6700f63c8a071 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 25 Nov 2026 23:26:09 +0000 Subject: [PATCH 07/12] gmod updates --- Game.Client/GarrysMod/LuaMesh.cs | 17 +++-- Game.Client/GarrysMod/SpawnIcon.cs | 2 +- Game.Client/View.cs | 3 + Game.Shared/GarrysMod/GarrysMod.cs | 6 +- Game.Shared/GarrysMod/LuaClass.cs | 17 ++++- Game.Shared/GarrysMod/LuaEntity.cs | 7 ++- Game.Shared/GarrysMod/LuaFileLibrary.cs | 21 ++++++- Game.Shared/GarrysMod/LuaGame.cs | 2 +- Game.Shared/GarrysMod/LuaGameCallback.cs | 36 +++++++++-- Source.Common/GUI/IInputInternal.cs | 3 + Source.Common/Registry.cs | 12 +++- Source.Engine/DownloadManager.cs | 7 +++ Source.Engine/FrameSnapshot.cs | 5 ++ Source.Engine/MatSysInterface.cs | 6 ++ Source.Engine/NetChannel.cs | 79 +++++++++++++++++++++++- Source.GUI.Controls/Frame.cs | 27 ++++---- Source.GUI.Controls/LuaEditablePanel.cs | 27 ++------ Source.GUI.Controls/MessageBox.cs | 7 +-- Source.GUI/VGuiInput.cs | 25 +++++++- 19 files changed, 239 insertions(+), 70 deletions(-) diff --git a/Game.Client/GarrysMod/LuaMesh.cs b/Game.Client/GarrysMod/LuaMesh.cs index 0c9706a1..31dd22c2 100644 --- a/Game.Client/GarrysMod/LuaMesh.cs +++ b/Game.Client/GarrysMod/LuaMesh.cs @@ -287,13 +287,20 @@ static int IMesh__DrawSkinned(ILuaInterface lua) { Matrix4x4 model = Matrix4x4.Identity; renderContext.GetMatrix(MaterialMatrixMode.Model, out model); - int bone = 1; - while (IsMatrixMember(table, bone)) { - Matrix4x4 bind = table.GetMemberMatrix(bone, default); + int bone = 0; + while (true) { + if (!IsMatrixMember(table, bone)) { + if (bone != 0) + break; + bone = 1; + if (!IsMatrixMember(table, bone)) + break; + } if (bone > 52) { lua.ErrorNoHalt($"Too many model transform matrices! ({53} max)\n"); break; } + Matrix4x4 bind = table.GetMemberMatrix(bone, default); if (transform) MathLib.MatrixMultiply(model, bind, out bind); renderContext.LoadBoneMatrix(bone, new ReadOnlySpan(in bind).Cast()[0]); @@ -456,11 +463,11 @@ static int BoneData(ILuaInterface lua) { uint index = (uint)lua.CheckNumber(1); uint bone = (uint)lua.CheckNumber(2); if (index >= 3) { - lua.Error($"Invalid bone matrix index. Must be integer [0,{index - 1}]\n"); + lua.Error($"Invalid bone matrix index. Must be integer [0,{2}]\n"); return 0; } if (bone >= 53) { - lua.Error($"Invalid bone matrix bone. Must be integer [1,{52}]\n"); + lua.Error($"Invalid bone matrix bone. Must be integer [0,{52}]\n"); return 0; } diff --git a/Game.Client/GarrysMod/SpawnIcon.cs b/Game.Client/GarrysMod/SpawnIcon.cs index 0cdb9348..9bf7e6c7 100644 --- a/Game.Client/GarrysMod/SpawnIcon.cs +++ b/Game.Client/GarrysMod/SpawnIcon.cs @@ -548,7 +548,7 @@ public override void OnThink() { string path = SpawnIconPath; Bootil.String.File.ExtractFilename(ref path); Bootil.String.File.StripExtension(ref path); - string cmd = "mat_reloadmaterial " + path + "\n"; + string cmd = "mat_reloadmaterial \"" + path + "\"\n"; if (!cmd.Contains(';')) engine.ClientCmd(cmd); } diff --git a/Game.Client/View.cs b/Game.Client/View.cs index 3f7202ff..7a6764f0 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -519,6 +519,9 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie renderContext.PopRenderTargetAndViewport(); renderContext.Flush(); } +#if GMOD_DLL + gGM?.Call((int)Source.Common.GarrysMod.Lua.LUA_POOLEDSTRING.PostRender); +#endif } RenderingView = false; diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs index d47b51bf..66d45e14 100644 --- a/Game.Shared/GarrysMod/GarrysMod.cs +++ b/Game.Shared/GarrysMod/GarrysMod.cs @@ -327,15 +327,15 @@ public static bool IsSacredEntity(ReadOnlySpan className) { static readonly string[] OverridableEntities = [ "point_servercommand", "point_teleport", "point_viewcontrol", "env_credits", "env_hudhint", "env_screenoverlay", "env_zoom", - "filter_activator_team", "filter_activator_context", "game_player_equip", "info_npc_spawn_destination", "logic_auto", + "env_message", "filter_activator_team", "filter_activator_context", "game_player_equip", "info_npc_spawn_destination", "logic_auto", "player_loadsaved", "player_speedmod", "npc_template_maker", "npc_maker", "prop_physics_respawnable", "trigger_auto", "trigger_changelevel", "trigger_hurt", "trigger_multiple", "trigger_once", "trigger_teleport", "trigger_transition", - "trigger_push", "ambient_generic", "func_pushable", "func_healthcharger", "func_recharge", "func_tankmortar", + "trigger_push", "trigger_portal_cleanser", "ambient_generic", "func_pushable", "func_healthcharger", "func_recharge", "func_tankmortar", "item_suitcharger", "item_healthcharger", "item_longjump", "item_suit", "item_healthkit", "item_battery", "weaponbox", "speaker", "monster_satchel", "monster_tripmine", "info_player_teamspawn", "info_vehicle_groundspawn", "ammo_crossbow", "ammo_egonclip", "ammo_gaussclip", "ammo_glockclip", "ammo_9mmclip", "ammo_mp5clip", "ammo_9mmar", "ammo_9mmbox", "ammo_mp5grenades", "ammo_argrenades", "ammo_357", "ammo_rpgclip", "ammo_buckshot", "bounce_bomb", "combine_bouncemine", - "combine_mine", "prop_car_alarm", "prop_car_glass", "prop_health_cabinet", "asw_door", "dod_control_point", + "combine_mine", "npc_portal_turret_floor", "npc_turret_floor", "npc_ichthyosaur", "prop_car_alarm", "prop_car_glass", "prop_health_cabinet", "asw_door", "dod_control_point", "team_control_point", "prop_portal_stats_display", "npc_personality_core", "prop_tractor_beam", "prop_under_floor_button", "prop_floor_ball_button", "prop_floor_cube_button", "prop_under_button", "prop_floor_button", "prop_button", "prop_indicator_panel", "prop_testchamber_door", "prop_wall_projector", "npc_wheatley_boss", "prop_laser_relay", diff --git a/Game.Shared/GarrysMod/LuaClass.cs b/Game.Shared/GarrysMod/LuaClass.cs index 741fba54..0abd5211 100644 --- a/Game.Shared/GarrysMod/LuaClass.cs +++ b/Game.Shared/GarrysMod/LuaClass.cs @@ -25,6 +25,7 @@ public class LuaClass public string Name; public string? DerivedFrom; public LuaType Type; + public int LuaID; public List? Functions; public LuaObject MetaTable; public Action? InitFn; @@ -32,6 +33,7 @@ public class LuaClass public LuaClass(string name, LuaType type, Action? initFn, string? derivedFrom) { MetaTable = new(); Functions = null; + LuaID = -1; Name = name; DerivedFrom = derivedFrom; Type = type; @@ -80,6 +82,8 @@ public unsafe LuaClassFunction Add(string name, delegate* unmanaged[Cdecl] MetaTable.UnReference(); + public void Shutdown() { + MetaTable.UnReference(); + LuaID = -1; + } public static void InitLuaClasses(ILuaInterface lua) { if (g_LuaClasses == null) @@ -143,8 +154,10 @@ public static void ShutdownLuaClasses(ILuaInterface lua) { if (g_LuaClasses == null) return; - for (int i = 0; i < g_LuaClasses.Count; i++) + for (int i = 0; i < g_LuaClasses.Count; i++) { g_LuaClasses[i].MetaTable.UnReference(); + g_LuaClasses[i].LuaID = -1; + } } } #endif diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs index d4efc4d3..d95a0366 100644 --- a/Game.Shared/GarrysMod/LuaEntity.cs +++ b/Game.Shared/GarrysMod/LuaEntity.cs @@ -1033,7 +1033,12 @@ static int Entity__GetDTString(ILuaInterface lua) { [LuaMethod] static int Entity__DrawModel(ILuaInterface lua) { BaseEntity ent = Get_Entity(1, false)!; - ent.DrawModel((StudioFlags)(int)lua.CheckNumberOpt(2, (int)StudioFlags.Render)); + double flags = lua.CheckNumberOpt(2, (int)StudioFlags.Render); + if (ent.EntIndex() == 0) { + lua.ErrorNoHalt("Trying to call DrawModel on the world entity, this will not work."); + return 0; + } + ent.DrawModel((StudioFlags)(int)flags); return 0; } #endif diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index ea086c32..cc809c51 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -792,12 +792,16 @@ static int AsyncRead(ILuaInterface lua) { Bootil.String.Lower(ref fileName); if (!IsFileAccessAllowed(fileName, path, false, false)) { - lua.PushNumber(-1); + AsyncReadEarlyReturn(lua, fileName, path); return 1; } long size = filesystem.Size(fileName, path); - int bytes = size < 0 ? 0 : (int)size; + if (size <= 0) { + AsyncReadEarlyReturn(lua, fileName, path); + return 1; + } + int bytes = (int)size; FileAsyncRequest request = new() { FileName = fileName, @@ -815,6 +819,19 @@ static int AsyncRead(ILuaInterface lua) { lua.PushNumber((double)filesystem.AsyncRead(request)); return 1; } + + static void AsyncReadEarlyReturn(ILuaInterface lua, string fileName, string path) { + using LuaObject callback = new(3, LuaType.None); + if (callback.isFunction()) { + callback.Push(); + lua.PushString(fileName); + lua.PushString(path); + lua.PushNumber(-1); + lua.PushString(""); + lua.CallInternalNoReturns(4); + } + lua.PushNumber(-1); + } #endif [LuaFunction] diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index 37afd7af..6a0352b4 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -274,7 +274,7 @@ static void DoCleanUpMap() { Soundscape_OnStopAllSounds(); List hairballs = []; for (C_BaseEntity? ent = cl_entitylist.FirstBaseEntity(); ent != null; ent = cl_entitylist.NextBaseEntity(ent)) - if (!ent.IsEFlagSet(EFL.KillMe) && strcmp(ent.GetClassname(), "class C_Hairball") == 0) + if (!ent.IsEFlagSet(EFL.KillMe) && stricmp(ent.GetClassname(), "class C_Hairball") == 0) hairballs.Add(ent); foreach (C_BaseEntity ent in hairballs) ent.Release(); diff --git a/Game.Shared/GarrysMod/LuaGameCallback.cs b/Game.Shared/GarrysMod/LuaGameCallback.cs index b22d8ab2..6db37c3b 100644 --- a/Game.Shared/GarrysMod/LuaGameCallback.cs +++ b/Game.Shared/GarrysMod/LuaGameCallback.cs @@ -45,6 +45,11 @@ public class LuaGameCallback : ILuaGameCallback static readonly ConVar lua_log = new("lua_log_sv", "0", 0, "Log serverside Lua errors to lua_errors_server.txt."); #endif static readonly ConVar lua_error_url = new("lua_error_url", "", FCvar.Replicated | FCvar.DontRecord); +#if CLIENT_DLL + static readonly ConVar lua_print_stack = new("lua_print_stack_cl", "0", 0, "Print the Lua stack when a message is printed to console from Lua. This is meant for debugging, to find out source of the messages, and is not supposed to be enabled at all times."); +#else + static readonly ConVar lua_print_stack = new("lua_print_stack_sv", "0", 0, "Print the Lua stack when a message is printed to console from Lua. This is meant for debugging, to find out source of the messages, and is not supposed to be enabled at all times."); +#endif static readonly Dictionary m_ReportedErrors = []; static readonly Queue LuaErrorQueue = []; @@ -133,20 +138,39 @@ public static void SendQueuedErrors() { public void Msg(ReadOnlySpan msg, bool useless) => MsgColour(msg, in cMsgColor); - public void MsgColour(ReadOnlySpan msg, in Color color) => Dbg._ColorSpewMessage(SpewType.Message, in color, msg.ToString()); + public void MsgColour(ReadOnlySpan msg, in Color color) { + Dbg._ColorSpewMessage(SpewType.Message, in color, msg.ToString()); - public void LuaError(in LuaError error) { - bool isAddon = LuaHelper.GetAddonFromError(in error, out IAddonSystem.Information addon, out bool overriding); + if (lua_print_stack.GetInt() == 0 || (msg.Length == 1 && (msg[0] == '\t' || msg[0] == '\n'))) + return; - string stack = ""; + LuaError error = new(); + LuaGlobalFunctions.ReadStackFrom(ref error, g_Lua!); + string stack = FormatLuaStack(error.Stack); + + if (msg.Length == 0 || msg[^1] != '\n') + Dbg._ColorSpewMessage(SpewType.Message, in color, $"\n{stack}\n"); + else + Dbg._ColorSpewMessage(SpewType.Message, in color, $"{stack}\n"); + } + + static string FormatLuaStack(List stack) { + string result = ""; string indent = ""; int i = 0; - foreach (LuaError.StackEntry entry in error.Stack) { + foreach (LuaError.StackEntry entry in stack) { indent += " "; string function = entry.Function.Length == 0 ? "unknown" : entry.Function; string source = entry.Source.Length == 0 ? "filename" : entry.Source; - stack += $"{indent}{++i}. {function} - {source}:{entry.Line}\n"; + result += $"{indent} {++i}. {function} - {source}:{entry.Line}\n"; } + return result; + } + + public void LuaError(in LuaError error) { + bool isAddon = LuaHelper.GetAddonFromError(in error, out IAddonSystem.Information addon, out bool overriding); + + string stack = FormatLuaStack(error.Stack); string message = error.Message; string tag = "ERROR"; diff --git a/Source.Common/GUI/IInputInternal.cs b/Source.Common/GUI/IInputInternal.cs index 79dcedd4..0b0d30cd 100644 --- a/Source.Common/GUI/IInputInternal.cs +++ b/Source.Common/GUI/IInputInternal.cs @@ -123,6 +123,9 @@ public unsafe struct SentenceModeItem IPanel? GetMouseCapture(); IPanel? GetMouseFocus(); + void PushAppModalSurface(IPanel? panel); + void PopAppModalSurface(IPanel? panel); + // InputInternal void RunFrame(); diff --git a/Source.Common/Registry.cs b/Source.Common/Registry.cs index 15f9f05f..215f8a2f 100644 --- a/Source.Common/Registry.cs +++ b/Source.Common/Registry.cs @@ -129,9 +129,15 @@ public bool DirectInit(ReadOnlySpan subDirectoryUnderValve) { Span modelKey = stackalloc char[1024]; int n = sprintf(modelKey, "Software\\Valve\\%s").S(subDirectoryUnderValve); - Key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( - modelKey[..n].ToString(), - RegistryKeyPermissionCheck.ReadWriteSubTree); + try { + Key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey( + modelKey[..n].ToString(), + RegistryKeyPermissionCheck.ReadWriteSubTree); + } + catch (Exception e) { + Error($"Failed to open registry key: {e.HResult & 0xFFFF} - {e.Message}"); + return false; + } if (Key == null) { Valid = false; diff --git a/Source.Engine/DownloadManager.cs b/Source.Engine/DownloadManager.cs index 41cb7d0b..28364d5c 100644 --- a/Source.Engine/DownloadManager.cs +++ b/Source.Engine/DownloadManager.cs @@ -801,6 +801,13 @@ static void ReadData(RequestContext rc, Stream stream) { while (!rc.ShouldStop) { int dwSize = stream.Read(data, 0, BufferSize); if (dwSize == 0) { + if (rc.BytesCurrent != rc.BytesTotal) { + rc.Status = HTTPStatus.Error; + rc.Error = HttpRequestError.ZeroLengthFile; + Warning($"FastDL: Received incomplete data! Got {rc.BytesCurrent} of {rc.BytesTotal} bytes\n"); + return; + } + // We're at the end of the file. If the file doesn't exist, write it out. WriteFileFromRequestContext(rc); diff --git a/Source.Engine/FrameSnapshot.cs b/Source.Engine/FrameSnapshot.cs index 4007d985..e09ece7b 100644 --- a/Source.Engine/FrameSnapshot.cs +++ b/Source.Engine/FrameSnapshot.cs @@ -88,6 +88,11 @@ PackedEntityHandle_t AllocHandle(PackedEntity entity) { public virtual void LevelChanged() { Assert(FrameSnapshots.Count == 0); + for (int i = 0; i < Constants.MAX_EDICTS; i++) { + if (PackedData[i] != INVALID_PACKED_ENTITY_HANDLE) + RemoveEntityReference(PackedData[i]); + } + PackedEntityCache.Clear(); HandleMap.Clear(); _nextHandle = 1; diff --git a/Source.Engine/MatSysInterface.cs b/Source.Engine/MatSysInterface.cs index 25b279db..db8e374e 100644 --- a/Source.Engine/MatSysInterface.cs +++ b/Source.Engine/MatSysInterface.cs @@ -987,7 +987,13 @@ private int FindOrAddMesh(IMaterial material, int vertexCount) { } public void WorldStaticMeshDestroy() { + using MatRenderContextPtr renderContext = new(materials); + Span meshes = Meshes.AsSpan(); + for (int i = 0; i < meshes.Length; i++) + renderContext.DestroyStaticMesh(meshes[i].Mesh); + WorldStaticMeshes.Clear(); + Meshes.Clear(); } public ConVar mat_loadtextures = new("1", 0); diff --git a/Source.Engine/NetChannel.cs b/Source.Engine/NetChannel.cs index 3f1b71bd..24bef9f5 100644 --- a/Source.Engine/NetChannel.cs +++ b/Source.Engine/NetChannel.cs @@ -1930,6 +1930,78 @@ public bool IsValidFileForTransfer(ReadOnlySpan filename) { if (filename.IsEmpty || filename[0] == '\0') return false; +#if GMOD_DLL + Span path = stackalloc char[MAX_PATH]; + ReadOnlySpan src = filename.SliceNullTerminatedString(); + int copyLen = Math.Min(src.Length, MAX_PATH - 1); + src[..copyLen].CopyTo(path); + path[copyLen] = '\0'; + StrTools.FixSlashes(path, '/'); + + int p = 0; + int componentLen = 0; + while (true) { + char c = path[p]; + if (c == '\\' || c == '/' || c == '\0') { + if (componentLen == 0) + return false; + if (path[p - 1] == ' ') + return false; + if (c == '\0') + break; + componentLen = 0; + p++; + continue; + } + + bool allowedChar = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_' || c == '-' || c == ' '; + if (!allowedChar) + return false; + + if (componentLen == 0) { + if (c == ' ' || c == '.') + return false; + } + else { + if (c == ' ' && path[p - 1] == ' ') + return false; + if (c == '.' && path[p - 1] == '.') + return false; + } + + componentLen++; + p++; + } + + if (p > 0) { + while (path[p] != '.' && path[p] != ' ') { + p--; + if (p <= 0) + break; + } + } + if (path[p] != '.') + return false; + + ReadOnlySpan ext = ((ReadOnlySpan)path[p..]).SliceNullTerminatedString(); + if (ext.Length == 1) + return false; + + ReadOnlySpan fullPath = path; + if ((HasPathPrefix(fullPath, "user_custom/") && stricmp(ext, ".dat") == 0) || + (HasPathPrefix(fullPath, "particles/") && stricmp(ext, ".pcf") == 0) || + (HasPathPrefix(fullPath, "resource/localization/") && stricmp(ext, ".properties") == 0) || + (HasPathPrefix(fullPath, "resource/fonts/") && (stricmp(ext, ".otf") == 0 || stricmp(ext, ".ttf") == 0)) || + (HasPathPrefix(fullPath, "maps/") && stricmp(ext, ".bsp") == 0) || + (HasPathPrefix(fullPath, "sound/") && (stricmp(ext, ".wav") == 0 || stricmp(ext, ".mp3") == 0 || stricmp(ext, ".ogg") == 0)) || + (HasPathPrefix(fullPath, "materials/") && (stricmp(ext, ".vmt") == 0 || stricmp(ext, ".vtf") == 0 || stricmp(ext, ".png") == 0 || stricmp(ext, ".jpg") == 0 || stricmp(ext, ".jpeg") == 0)) || + (HasPathPrefix(fullPath, "models/") && (stricmp(ext, ".mdl") == 0 || stricmp(ext, ".vvd") == 0 || stricmp(ext, ".vtx") == 0 || stricmp(ext, ".phy") == 0 || stricmp(ext, ".ani") == 0))) + return true; + + bool inDataFolder = HasPathPrefix(fullPath, "data_static/") || HasPathPrefix(fullPath, "data/"); + bool isDataExt = stricmp(ext, ".dat") == 0 || stricmp(ext, ".txt") == 0 || stricmp(ext, ".json") == 0 || stricmp(ext, ".xml") == 0 || stricmp(ext, ".csv") == 0 || stricmp(ext, ".bsp") == 0; + return inDataFolder && isDataExt; +#else if (!Source.Engine.Common.IsValidPath(filename) || Path.IsPathFullyQualified(filename)) return false; @@ -2018,8 +2090,13 @@ public bool IsValidFileForTransfer(ReadOnlySpan filename) { return false; return true; +#endif } +#if GMOD_DLL + static bool HasPathPrefix(ReadOnlySpan path, ReadOnlySpan prefix) => strnicmp(path, prefix, prefix.Length) == 0; +#endif + public bool SendFile(ReadOnlySpan filename, uint transferID) { // add file to waiting list if (RemoteAddress!.Type == NetAddressType.Null) @@ -2029,7 +2106,7 @@ public bool SendFile(ReadOnlySpan filename, uint transferID) { return false; ReadOnlySpan sendfile = filename; - while (sendfile[0] != '\0' && sendfile[0].IsPathSeparator()) + while (sendfile[0] != '\0' && (sendfile[0] == ' ' || sendfile[0].IsPathSeparator())) sendfile = sendfile[1..]; // Don't transfer exe, vbs, com, bat-type files. diff --git a/Source.GUI.Controls/Frame.cs b/Source.GUI.Controls/Frame.cs index eb2df3c3..d0d74077 100644 --- a/Source.GUI.Controls/Frame.cs +++ b/Source.GUI.Controls/Frame.cs @@ -526,8 +526,6 @@ public class Frame : EditablePanel public void SetDeleteSelfOnClose(bool state) => DeleteSelfOnClose = state; - IPanel? PreviousModal; - public virtual void Activate() { MoveToFront(); if (IsKeyboardInputEnabled()) @@ -543,11 +541,18 @@ public virtual void Activate() { } public override void DoModal() { + if (!Surface.IsCursorVisible()) + return; + MoveToCenterOfScreen(); InvalidateLayout(); Activate(); - PreviousModal = Input.GetAppModalSurface(); - Input.SetAppModalSurface(this); + Input.PushAppModalSurface(this); + } + + public override void Dispose() { + Input.PopAppModalSurface(this); + base.Dispose(); } public Frame(Panel? parent, ReadOnlySpan name, bool showTaskbarIcon = true, bool popup = true) : base(parent, name) { @@ -858,13 +863,7 @@ public override void LoadControlSettings(ReadOnlySpan resourceName, ReadOn GetFocusNavGroup().GetDefaultPanel()?.RequestFocus(); } public override void OnClose() { - if (Input.GetAppModalSurface() == this) { - Input.ReleaseAppModalSurface(); - if (PreviousModal != null) { - Input.SetAppModalSurface(PreviousModal); - PreviousModal = null; - } - } + Input.PopAppModalSurface(this); base.OnClose(); @@ -963,11 +962,7 @@ public virtual void Close() { [UiMessage("CloseModal")] [UiCommand("CloseModal")] private void CloseModal() { - Input.ReleaseAppModalSurface(); - if (PreviousModal != null) { - Input.SetAppModalSurface(PreviousModal); - PreviousModal = null; - } + Input.PopAppModalSurface(this); PostMessage(this, new("Close")); } diff --git a/Source.GUI.Controls/LuaEditablePanel.cs b/Source.GUI.Controls/LuaEditablePanel.cs index 0854fa95..4e857450 100644 --- a/Source.GUI.Controls/LuaEditablePanel.cs +++ b/Source.GUI.Controls/LuaEditablePanel.cs @@ -7,45 +7,26 @@ public class LuaEditablePanel : EditablePanel { static LuaEditablePanel() => ChainToAnimationMap(); - IPanel? PreviousModal; - public LuaEditablePanel(Panel? parent, ReadOnlySpan panelName) : base(parent, panelName) { - PreviousModal = null; SetBuildModeEditable(true); } // FIXME #37 public override void Dispose() { - if (Input.GetAppModalSurface() == this) { - Input.ReleaseAppModalSurface(); - if (PreviousModal != null) { - Input.SetAppModalSurface(PreviousModal); - PreviousModal = null; - } - } - + Input.PopAppModalSurface(this); base.Dispose(); } public override void OnChildAdded(IPanel child) => base.OnChildAdded(child); public override void MarkForDeletion() { - if (Input.GetAppModalSurface() == this) { - Input.ReleaseAppModalSurface(); - if (PreviousModal != null) { - Input.SetAppModalSurface(PreviousModal); - PreviousModal = null; - } - } - + Input.PopAppModalSurface(this); base.MarkForDeletion(); } public override void DoModal() { // TODO: Should this be an override? - if (Surface.IsCursorVisible()) { - PreviousModal = Input.GetAppModalSurface(); - Input.SetAppModalSurface(this); - } + if (Surface.IsCursorVisible()) + Input.PushAppModalSurface(this); } } #endif diff --git a/Source.GUI.Controls/MessageBox.cs b/Source.GUI.Controls/MessageBox.cs index 2fbdcedf..a23c3485 100644 --- a/Source.GUI.Controls/MessageBox.cs +++ b/Source.GUI.Controls/MessageBox.cs @@ -65,7 +65,7 @@ public void SetCancelButtonText(ReadOnlySpan buttonText) { public void SetCancelCommand(KeyValues? command) => CancelCommand = command; public virtual void DoModal(Frame? frameOver = null) { ShowWindow(frameOver); - Input.SetAppModalSurface(this); + Input.PushAppModalSurface(this); } [UiCommand("OnOk")] @@ -96,10 +96,7 @@ public override void OnCommand(ReadOnlySpan command) { AutoClose(); } - private void ReleaseModalSurface() { - if (Input.GetAppModalSurface() == this) - Input.ReleaseAppModalSurface(); - } + private void ReleaseModalSurface() => Input.PopAppModalSurface(this); private void AutoClose() { if (!NoAutoClose) diff --git a/Source.GUI/VGuiInput.cs b/Source.GUI/VGuiInput.cs index adb04f34..202a3d66 100644 --- a/Source.GUI/VGuiInput.cs +++ b/Source.GUI/VGuiInput.cs @@ -755,7 +755,7 @@ private bool IsChildOfModalPanel(IPanel? panel, bool checkModalSubTree = true) { ref InputContext context = ref GetInputContext(Context); - if (context.AppModalPanel != null) + if (context.AppModalPanel != null && context.AppModalPanel.IsVisible()) if (!panel.HasParent(context.AppModalPanel)) return false; @@ -786,6 +786,29 @@ public void SetAppModalSurface(IPanel? panel) { context.AppModalPanel = panel; } + static readonly List AppModalStack = []; + + public void PushAppModalSurface(IPanel? panel) { + IPanel? current = GetAppModalSurface(); + if (current != null && !AppModalStack.Contains(current)) + AppModalStack.Add(current); + SetAppModalSurface(panel); + } + + public void PopAppModalSurface(IPanel? panel) { + if (GetAppModalSurface() == panel) { + ReleaseAppModalSurface(); + if (AppModalStack.Count > 0) { + SetAppModalSurface(AppModalStack[^1]); + AppModalStack.RemoveAt(AppModalStack.Count - 1); + } + return; + } + + if (panel != null) + AppModalStack.Remove(panel); + } + public void SetCandidateListPageStart(int start) { throw new NotImplementedException(); } From e6c7f29246630f0333c0a03fcdf0bbbbc60ce3ac Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 26 Nov 2026 22:51:39 +0000 Subject: [PATCH 08/12] Fixes --- Game.Client/View.cs | 2 +- Game.Shared/GarrysMod/LuaFileLibrary.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Game.Client/View.cs b/Game.Client/View.cs index 7a6764f0..57432264 100644 --- a/Game.Client/View.cs +++ b/Game.Client/View.cs @@ -520,7 +520,7 @@ public void RenderView(in ViewSetup viewRender, ClearFlags clearFlags, RenderVie renderContext.Flush(); } #if GMOD_DLL - gGM?.Call((int)Source.Common.GarrysMod.Lua.LUA_POOLEDSTRING.PostRender); + gGM?.Call((int)LUA_POOLEDSTRING.PostRender); #endif } diff --git a/Game.Shared/GarrysMod/LuaFileLibrary.cs b/Game.Shared/GarrysMod/LuaFileLibrary.cs index cc809c51..3460dc05 100644 --- a/Game.Shared/GarrysMod/LuaFileLibrary.cs +++ b/Game.Shared/GarrysMod/LuaFileLibrary.cs @@ -821,7 +821,7 @@ static int AsyncRead(ILuaInterface lua) { } static void AsyncReadEarlyReturn(ILuaInterface lua, string fileName, string path) { - using LuaObject callback = new(3, LuaType.None); + LuaObject callback = new(3, LuaType.None); if (callback.isFunction()) { callback.Push(); lua.PushString(fileName); @@ -830,6 +830,7 @@ static void AsyncReadEarlyReturn(ILuaInterface lua, string fileName, string path lua.PushString(""); lua.CallInternalNoReturns(4); } + callback.UnReference(); lua.PushNumber(-1); } #endif From 6a06b6d99219bfa3c040da4934b0fd8f98719870 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 26 Nov 2026 22:57:03 +0000 Subject: [PATCH 09/12] Prevent drawing world --- Source.Common/Utilities/UtlSymbol.cs | 8 ++++++++ Source.Engine/GLRSurf.cs | 10 ++++++++++ Source.Filesystem/BaseFileSystem.cs | 6 +++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Source.Common/Utilities/UtlSymbol.cs b/Source.Common/Utilities/UtlSymbol.cs index f2a7fdf9..ea57f4a9 100644 --- a/Source.Common/Utilities/UtlSymbol.cs +++ b/Source.Common/Utilities/UtlSymbol.cs @@ -45,6 +45,14 @@ public UtlSymbol(in UtlSymbol symbol) { ValidId = id != UTL_INVAL_SYMBOL; } public readonly string? String() => CurrTable().String(id); + public readonly char this[int i] { + get { + string? str = String(); + if (str != null && i < str.Length) + return str[i]; + return '\0'; + } + } public readonly bool IsValid() => ValidId && id != UTL_INVAL_SYMBOL; public readonly UtlSymId_t Id => ValidId ? id : UTL_INVAL_SYMBOL; diff --git a/Source.Engine/GLRSurf.cs b/Source.Engine/GLRSurf.cs index 81f27cff..c08c28ad 100644 --- a/Source.Engine/GLRSurf.cs +++ b/Source.Engine/GLRSurf.cs @@ -1693,6 +1693,11 @@ public void ClearRenderHandles() { public static readonly MaterialReference BrushMaterialOverride = new(); public void DrawOpaqueBrushModel(IClientEntity? baseEntity, Model? model, in Vector3 origin, RenderDepthMode depthMode) { + if (model!.StrName[0] != '*') { + Warning("DrawOpaqueBrushModel: Refusing to render the map on an entity to prevent crashes!\n"); + return; + } + SurfaceHandle_t firstSurfID = model!.Brush.FirstModelSurface; BrushRender? render = FindOrCreateRenderBatch(model); @@ -1815,6 +1820,11 @@ public void DrawTranslucentBrushModel(IClientEntity? baseEntity, Model? model, i } private void DrawTranslucentBrushModel(Model? model, IClientEntity? baseEntity) { + if (model!.StrName[0] != '*') { + Warning("DrawTranslucentBrushModel: Refusing to render the map on an entity to prevent crashes!\n"); + return; + } + TransRender renderT = new() { LastBatch = -1, LastNode = -1, diff --git a/Source.Filesystem/BaseFileSystem.cs b/Source.Filesystem/BaseFileSystem.cs index e5a8fc13..8d3a5e77 100644 --- a/Source.Filesystem/BaseFileSystem.cs +++ b/Source.Filesystem/BaseFileSystem.cs @@ -929,7 +929,7 @@ readonly void FindInLooseAddonPaths(SearchPathCollection collection, ReadOnlySpa ISearchPath? searchPath = collection.AtSorted(i); if (searchPath == null) break; - if (searchPath is not DiskSearchPath) + if (searchPath is not DiskSearchPath { Workshop: true }) continue; ReadOnlySpan path = searchPath.GetPathString(); @@ -1026,6 +1026,10 @@ public ReadOnlySpan Next() { void PrepareFinds(ISearchPath path) { files!.Clear(); dirs!.Clear(); +#if GMOD_DLL + if (path is DiskSearchPath { Workshop: true }) + return; +#endif path.PrepareFinds(files, dirs, Wildcard.String()); for (int i = dirs.Count - 1; i >= 0; i--) if (!foundAlready!.Add(dirs[i].Hash())) From d86cc88c236d5a094748dab032303058a0a54501 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 26 Nov 2026 23:11:52 +0000 Subject: [PATCH 10/12] Prevent culture lookup per char + faster strlen/stricmp in cformatting --- Source.Common/CFormatting.cs | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/Source.Common/CFormatting.cs b/Source.Common/CFormatting.cs index afbac258..dfde18ae 100644 --- a/Source.Common/CFormatting.cs +++ b/Source.Common/CFormatting.cs @@ -6,10 +6,12 @@ This file is a bit of a mess. It was an attempt at implementing a C# version of for their arguments instead, along with not trying to reinvent the wheel and read actual C stdlib implementations. */ +using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; +using System.Text; namespace Source.Common; @@ -1128,13 +1130,17 @@ public static int atoi(ReadOnlySpan str) { public static void strlower(Span str) { - for (int i = 0; i < str.Length; i++) - str[i] = char.ToLower(str[i]); + if (Ascii.ToLowerInPlace(str, out int processed) == OperationStatus.Done) + return; + for (int i = processed; i < str.Length; i++) + str[i] = char.ToLowerInvariant(str[i]); } public static void strupper(Span str) { - for (int i = 0; i < str.Length; i++) - str[i] = char.ToUpper(str[i]); + if (Ascii.ToUpperInPlace(str, out int processed) == OperationStatus.Done) + return; + for (int i = processed; i < str.Length; i++) + str[i] = char.ToUpperInvariant(str[i]); } public static int strcmp(scoped ReadOnlySpan a, scoped ReadOnlySpan b) => a.SliceNullTerminatedString().CompareTo(b.SliceNullTerminatedString(), StringComparison.Ordinal); @@ -1143,14 +1149,14 @@ public static void strupper(Span str) { public static int stricmp(scoped ReadOnlySpan a, scoped ReadOnlySpan b) { a = a.SliceNullTerminatedString(); b = b.SliceNullTerminatedString(); for (int i = 0; i < a.Length && i < b.Length; i++) - if (char.ToLowerInvariant(a[i]) != char.ToLowerInvariant(b[i])) + if (a[i] != b[i] && char.ToLowerInvariant(a[i]) != char.ToLowerInvariant(b[i])) return char.ToLowerInvariant(a[i]) - char.ToLowerInvariant(b[i]); return a.Length - b.Length; } public static int stricmp(scoped ReadOnlySpan a, scoped ReadOnlySpan b) { a = a.SliceNullTerminatedString(); b = b.SliceNullTerminatedString(); for (int i = 0; i < a.Length && i < b.Length; i++) - if (char.ToLowerInvariant((char)a[i]) != char.ToLowerInvariant((char)b[i])) + if (a[i] != b[i] && char.ToLowerInvariant((char)a[i]) != char.ToLowerInvariant((char)b[i])) return char.ToLowerInvariant((char)a[i]) - char.ToLowerInvariant((char)b[i]); return a.Length - b.Length; } @@ -1161,21 +1167,13 @@ public static int stricmp(scoped ReadOnlySpan a, scoped ReadOnlySpan public static bool strieq(scoped ReadOnlySpan a, scoped ReadOnlySpan b) => a.SliceNullTerminatedString().Equals(b.SliceNullTerminatedString(), StringComparison.OrdinalIgnoreCase); public static nint strlen(scoped ReadOnlySpan str) { - int i = 0; - for (i = 0; i < str.Length; i++) { - if (str[i] == '\0') - return i; - } - return i; + int i = str.IndexOf('\0'); + return i == -1 ? str.Length : i; } public static nint strlen(scoped ReadOnlySpan str) { - int i = 0; - for (i = 0; i < str.Length; i++) { - if (str[i] == '\0') - return i; - } - return i; + int i = str.IndexOf((byte)0); + return i == -1 ? str.Length : i; } public static int strcpy(scoped Span target, scoped ReadOnlySpan str) { str = str.SliceNullTerminatedString(); From d8e36af60673a7aef82ab3ce98c6a25fc4b5cb00 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 26 Nov 2026 23:25:26 +0000 Subject: [PATCH 11/12] Span CheckString overload --- Game.Lua/LuaInterfaceImpl.cs | 10 +++++++++ Game.Shared/GarrysMod/LuaMaterial.cs | 30 +++++++++++++------------- Source.Common/GarrysMod/Lua/LuaBase.cs | 1 + Source.Common/GarrysMod/Lua/LuaNull.cs | 1 + 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/Game.Lua/LuaInterfaceImpl.cs b/Game.Lua/LuaInterfaceImpl.cs index 4ee7b79d..28a1a63f 100644 --- a/Game.Lua/LuaInterfaceImpl.cs +++ b/Game.Lua/LuaInterfaceImpl.cs @@ -542,6 +542,16 @@ public string CheckString(int stackPos = -1) { return GetString(stackPos)!; } + public ReadOnlySpan CheckString(int stackPos, Span buffer) { + int type = lua_type(state, stackPos); + if (type != TSTRING && type != TNUMBER) + TypeError("string", stackPos); + ReadOnlySpan bytes = GetStringBytes(stackPos); + if (Encoding.UTF8.GetMaxCharCount(bytes.Length) > buffer.Length) + return Encoding.UTF8.GetString(bytes); + return buffer[..Encoding.UTF8.GetChars(bytes, buffer)]; + } + public double CheckNumber(int stackPos = -1) { if (lua_isnumber(state, stackPos) == 0) TypeError("number", stackPos); diff --git a/Game.Shared/GarrysMod/LuaMaterial.cs b/Game.Shared/GarrysMod/LuaMaterial.cs index 765acf18..3343d292 100644 --- a/Game.Shared/GarrysMod/LuaMaterial.cs +++ b/Game.Shared/GarrysMod/LuaMaterial.cs @@ -45,7 +45,7 @@ static int IMaterial__GetString(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -159,7 +159,7 @@ static int IMaterial__SetTexture(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -186,7 +186,7 @@ static int IMaterial__GetMatrix(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -202,7 +202,7 @@ static int IMaterial__SetMatrix(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -219,7 +219,7 @@ static int IMaterial__GetInt(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -235,7 +235,7 @@ static int IMaterial__SetInt(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -255,7 +255,7 @@ static int IMaterial__GetFloat(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -271,7 +271,7 @@ static int IMaterial__SetFloat(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -287,7 +287,7 @@ static int IMaterial__SetUndefined(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -303,7 +303,7 @@ static int IMaterial__SetVector(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -320,7 +320,7 @@ static int IMaterial__GetVector(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -338,7 +338,7 @@ static int IMaterial__SetVector4D(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -358,7 +358,7 @@ static int IMaterial__GetVector4D(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -379,7 +379,7 @@ static int IMaterial__GetVectorLinear(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; @@ -397,7 +397,7 @@ static int IMaterial__SetString(ILuaInterface lua) { return 0; } - IMaterialVar var = material.FindVar(lua.CheckString(2), out bool found, false); + IMaterialVar var = material.FindVar(lua.CheckString(2, stackalloc char[256]), out bool found, false); if (var == null || !found) return 0; diff --git a/Source.Common/GarrysMod/Lua/LuaBase.cs b/Source.Common/GarrysMod/Lua/LuaBase.cs index e86b782d..1c4d2697 100644 --- a/Source.Common/GarrysMod/Lua/LuaBase.cs +++ b/Source.Common/GarrysMod/Lua/LuaBase.cs @@ -70,6 +70,7 @@ public interface ILuaBase string GetTypeName(LuaType type); void CreateMetaTableType(ReadOnlySpan name, int type); string CheckString(int stackPos = -1); + ReadOnlySpan CheckString(int stackPos, Span buffer); double CheckNumber(int stackPos = -1); int ObjLen(int stackPos = -1); QAngle GetAngle(int stackPos = -1); diff --git a/Source.Common/GarrysMod/Lua/LuaNull.cs b/Source.Common/GarrysMod/Lua/LuaNull.cs index a2766b6b..09695038 100644 --- a/Source.Common/GarrysMod/Lua/LuaNull.cs +++ b/Source.Common/GarrysMod/Lua/LuaNull.cs @@ -193,6 +193,7 @@ public void PushSpecial(Special type) { } public string GetTypeName(LuaType type) => "nil"; public void CreateMetaTableType(ReadOnlySpan name, int type) { } public string CheckString(int stackPos = -1) => ""; + public ReadOnlySpan CheckString(int stackPos, Span buffer) => []; public double CheckNumber(int stackPos = -1) => 0; public int ObjLen(int stackPos = -1) => 0; public QAngle GetAngle(int stackPos = -1) => default; From 15c0acdafb08d9556f4cb38d3ddd0a77b23a86ad Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Thu, 26 Nov 2026 23:27:34 +0000 Subject: [PATCH 12/12] Use StringBuilder for SingleplayerFiles --- Game.Shared/GarrysMod/GModDataPack.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Game.Shared/GarrysMod/GModDataPack.cs b/Game.Shared/GarrysMod/GModDataPack.cs index 4b4f01b4..ee11e4cd 100644 --- a/Game.Shared/GarrysMod/GModDataPack.cs +++ b/Game.Shared/GarrysMod/GModDataPack.cs @@ -341,9 +341,10 @@ public void AddOrUpdateFile(LuaFile file, bool refresh) { if (!SingleplayerFiles.Add(fileName)) return; - string files = ":"; + StringBuilder builder = new(":"); foreach (string name in SingleplayerFiles) - files += name + ":"; + builder.Append(name).Append(':'); + string files = builder.ToString(); for (int i = 0, offset = 0; i < 0x400; i++, offset += 0x19000) { string key = $"singleplayer_files{i}";