From 4d4a2853fc0b1172185a388314e70518192894d7 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:16:07 +0000 Subject: [PATCH 1/9] LuaPhysCollide --- Game.Shared/GarrysMod/LuaPhysCollide.cs | 159 ++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 Game.Shared/GarrysMod/LuaPhysCollide.cs diff --git a/Game.Shared/GarrysMod/LuaPhysCollide.cs b/Game.Shared/GarrysMod/LuaPhysCollide.cs new file mode 100644 index 00000000..e1a7ff31 --- /dev/null +++ b/Game.Shared/GarrysMod/LuaPhysCollide.cs @@ -0,0 +1,159 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common; +using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; +using Source.Common.Physics; + +using System.Numerics; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaPhysCollide +{ + [LuaClass(typeof(PhysCollide), NullError = "Tried to use a null PhysCollide!")] + public static readonly LuaClass LC_PhysCollide = new("PhysCollide", LuaType.PhysCollide, null, null); + + public static void Push_PhysCollide(PhysCollide? collide) => LC_PhysCollide.Push(collide); + + [LuaMethod] + static int PhysCollide__Destroy(ILuaInterface lua) { + PhysCollide? collide = (PhysCollide?)LC_PhysCollide.Get(1); + if (collide != null) { + lua.SetUserType(1, 0); + physcollision.DestroyCollide(collide); + } + return 0; + } + + [LuaMethod] + static int PhysCollide__IsValid(ILuaInterface lua) { + PhysCollide? collide = (PhysCollide?)LC_PhysCollide.Get(1); + lua.PushBool(collide != null); + return 1; + } + + [LuaMethod] + static int PhysCollide____tostring(ILuaInterface lua) { + PhysCollide? collide = (PhysCollide?)LC_PhysCollide.Get(1); + if (collide == null) { + lua.PushString("PhysCollide [NULL]"); + return 1; + } + lua.PushString("PhysCollide"); + return 1; + } + + [LuaMethod] + static int PhysCollide__TraceBox(ILuaInterface lua) { + PhysCollide? collide = (PhysCollide?)LC_PhysCollide.Get(1); + if (collide == null) + lua.Error("Tried to use a null PhysCollide!"); + + Vector3 origin = LuaVector.Get_Vector(2); + QAngle angles = LuaAngle.Get_Angle(3); + Vector3 start = LuaVector.Get_Vector(4); + Vector3 end = LuaVector.Get_Vector(5); + LuaVector.OrderVectors(LuaVector.Get_Vector(6), LuaVector.Get_Vector(7), out Vector3 mins, out Vector3 maxs); + + if (!origin.IsValid() || !angles.IsValid() || !start.IsValid() || !end.IsValid() || !mins.IsValid() || !maxs.IsValid()) { + lua.PushBool(false); + return 1; + } + + Ray ray = default; + ray.Init(start, end, mins, maxs); + physcollision.TraceBox(in ray, collide!, in origin, in angles, out Trace tr); + + if (tr.Fraction < 1.0f || tr.StartSolid || tr.AllSolid) { + LuaVector.Push_Vector(tr.EndPos); + LuaVector.Push_Vector(tr.Plane.Normal); + lua.PushNumber(tr.Fraction); + return 3; + } + + lua.PushBool(false); + return 1; + } + + [LuaGlobal] + static int CreatePhysCollideBox(ILuaInterface lua) { + LuaVector.OrderVectors(LuaVector.Get_Vector(1), LuaVector.Get_Vector(2), out Vector3 mins, out Vector3 maxs); + + PhysCollide? collide = null; + if (mins.IsValid() && maxs.IsValid() && maxs.X - mins.X >= 0.0001f && maxs.Y - mins.Y >= 0.0001f && maxs.Z - mins.Z >= 0.0001f) { + Span verts = [ + new(mins.X, mins.Y, mins.Z), + new(maxs.X, mins.Y, mins.Z), + new(mins.X, maxs.Y, mins.Z), + new(maxs.X, maxs.Y, mins.Z), + new(mins.X, mins.Y, maxs.Z), + new(maxs.X, mins.Y, maxs.Z), + new(mins.X, maxs.Y, maxs.Z), + new(maxs.X, maxs.Y, maxs.Z), + ]; + Span convex = [physcollision.ConvexFromVerts(verts)]; + collide = physcollision.ConvertConvexToCollide(convex); + } + + Push_PhysCollide(collide); + return 1; + } + + [LuaGlobal] + static int CreatePhysCollidesFromModel(ILuaInterface lua) { + string name = lua.CheckString(1); + if (name.Length <= 1 || name[0] == ' ') + return 0; + + int modelIndex = modelinfo.GetModelIndex(name); + if (modelIndex < 0) + return 0; + + VCollide? vcollide = modelinfo.GetVCollide(modelIndex); + if (vcollide == null) + return 0; + + PhysCollide?[] collides = new PhysCollide?[vcollide.SolidCount]; + for (int i = 0; i < vcollide.SolidCount; i++) { + PhysCollide? solid = vcollide.Solids![i]; + if (solid == null) + return 0; + + ICollisionQuery? query = physcollision.CreateQueryModel(solid); + if (query == null || query.ConvexCount() < 1) + return 0; + + int convexCount = query.ConvexCount(); + List convexes = new(convexCount); + for (int j = 0; j < convexCount; j++) { + int triCount = query.TriangleCount(j); + if (triCount <= 2) + continue; + + Vector3[] verts = new Vector3[triCount * 3]; + for (int k = 0; k < triCount; k++) + query.GetTriangleVerts(j, k, verts.AsSpan(k * 3, 3)); + + convexes.Add(physcollision.ConvexFromVerts(verts)); + } + + physcollision.DestroyQueryModel(query); + collides[i] = physcollision.ConvertConvexToCollide(System.Runtime.InteropServices.CollectionsMarshal.AsSpan(convexes)); + } + + lua.PreCreateTable(vcollide.SolidCount, 0); + for (int i = 0; i < vcollide.SolidCount; i++) { + lua.PushNumber(i + 1); + Push_PhysCollide(collides[i]); + lua.SetTable(-3); + } + return 1; + } +} +#endif From 42e4a6f9d45d9c818f84e54156890ea96ba357ad Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:17:06 +0000 Subject: [PATCH 2/9] LuaSoundPatch --- Game.Shared/GarrysMod/LuaSoundPatch.cs | 201 +++++++++++++++++++++++++ Game.Shared/SoundPatch.cs | 11 ++ 2 files changed, 212 insertions(+) create mode 100644 Game.Shared/GarrysMod/LuaSoundPatch.cs diff --git a/Game.Shared/GarrysMod/LuaSoundPatch.cs b/Game.Shared/GarrysMod/LuaSoundPatch.cs new file mode 100644 index 00000000..a117679b --- /dev/null +++ b/Game.Shared/GarrysMod/LuaSoundPatch.cs @@ -0,0 +1,201 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common.Audio; +using Source.Common.GarrysMod.Lua; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaSoundPatch +{ + [LuaClass(typeof(SoundPatch), NullError = "Tried to use a NULL CSoundPatch!")] + public static readonly LuaClass LC_CSoundPatch = new("CSoundPatch", LuaType.Sound, null, null); + + public static void Push_SoundPatch(SoundPatch? sound) => LC_CSoundPatch.Push(sound); + + static SoundPatch? Get_SoundPatch(ILuaInterface lua) { + SoundPatch? sound = (SoundPatch?)LC_CSoundPatch.Get(1); + if (sound == null) + lua.Error("Tried to use a NULL CSoundPatch!"); + return sound; + } + + [LuaGlobal] + static int CreateSound(ILuaInterface lua) { + BaseEntity ent = LuaEntity.Get_Entity(1, false)!; +#if CLIENT_DLL + PASAttenuationFilter filter = new(ent); + SoundPatch sound = SoundEnvelopeController.GetController().SoundCreate(filter, ent.EntIndex(), lua.CheckString(2)); + Push_SoundPatch(sound); + return 1; +#else + RecipientFilter filter = new(); + if (lua.GetType(3) == LuaType.RecipientFilter) + filter.CopyFrom(LuaRecipientFilter.Get_RecipientFilter(3)); + else + filter.CopyFrom(new PASAttenuationFilter(ent, ATTN_NORM)); + + SoundPatch sound = SoundEnvelopeController.GetController().SoundCreate(filter, ent.EntIndex(), lua.CheckString(2)); + Push_SoundPatch(sound); + return 1; +#endif + } + + [LuaMethod] + static int CSoundPatch____gc(ILuaInterface lua) { + SoundPatch? sound = (SoundPatch?)LC_CSoundPatch.Get(1); + if (sound != null) + SoundEnvelopeController.GetController().GMOD_OnLuaObjectDeleted(sound); + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int CSoundPatch____tostring(ILuaInterface lua) { + SoundPatch? sound = (SoundPatch?)LC_CSoundPatch.Get(1); + if (sound == null) { + lua.PushString("CSoundPatch [NULL]"); + return 1; + } + string name = SoundEnvelopeController.GetController().SoundGetName(sound) ?? ""; + lua.PushString($"CSoundPatch [{name}]"); + return 1; + } + + [LuaMethod] + static int CSoundPatch__ChangePitch(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + double deltaTime = lua.GetType(3) == LuaType.Number ? lua.GetNumber(3) : 0.0; + SoundEnvelopeController.GetController().SoundChangePitch(sound, (float)lua.CheckNumber(2), (float)deltaTime); + return 0; + } + + [LuaMethod] + static int CSoundPatch__ChangeVolume(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + double deltaTime = lua.GetType(3) == LuaType.Number ? lua.GetNumber(3) : 0.0; + SoundEnvelopeController.GetController().SoundChangeVolume(sound, (float)lua.CheckNumber(2), (float)deltaTime); + return 0; + } + + [LuaMethod] + static int CSoundPatch__FadeOut(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().SoundFadeOut(sound, (float)lua.CheckNumber(2), false); + return 0; + } + + [LuaMethod] + static int CSoundPatch__GetDSP(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushNumber(SoundEnvelopeController.GetController().GetDSP(sound)); + return 1; + } + + [LuaMethod] + static int CSoundPatch__GetPitch(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushNumber(SoundEnvelopeController.GetController().SoundGetPitch(sound)); + return 1; + } + + [LuaMethod] + static int CSoundPatch__GetSoundLevel(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushNumber((int)SoundEnvelopeController.GetController().GetSoundLevel(sound)); + return 1; + } + + [LuaMethod] + static int CSoundPatch__GetSoundName(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushString(SoundEnvelopeController.GetController().SoundGetName(sound) ?? ""); + return 1; + } + + [LuaMethod] + static int CSoundPatch__GetVolume(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushNumber(SoundEnvelopeController.GetController().SoundGetVolume(sound)); + return 1; + } + + [LuaMethod] + static int CSoundPatch__IsPlaying(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + lua.PushBool(SoundEnvelopeController.GetController().IsPlaying(sound)); + return 1; + } + + [LuaMethod] + static int CSoundPatch__Play(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().CommandClear(sound); + SoundEnvelopeController.GetController().Play(sound, 1.0f, 100.0f, 0); + return 0; + } + + [LuaMethod] + static int CSoundPatch__PlayEx(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().CommandClear(sound); + float pitch = (float)lua.CheckNumber(3); + float volume = (float)lua.CheckNumber(2); + SoundEnvelopeController.GetController().Play(sound, volume, pitch, 0); + return 0; + } + + [LuaMethod] + static int CSoundPatch__SetDSP(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().SetDSP(sound, (int)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int CSoundPatch__SetSoundLevel(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().SetSoundLevel(sound, (SoundLevel)(int)lua.CheckNumber(2)); + return 0; + } + + [LuaMethod] + static int CSoundPatch__Stop(ILuaInterface lua) { + SoundPatch? sound = Get_SoundPatch(lua); + if (sound == null) + return 0; + SoundEnvelopeController.GetController().Shutdown(sound); + return 0; + } +} +#endif diff --git a/Game.Shared/SoundPatch.cs b/Game.Shared/SoundPatch.cs index ca7aad20..c5875a4d 100644 --- a/Game.Shared/SoundPatch.cs +++ b/Game.Shared/SoundPatch.cs @@ -252,6 +252,10 @@ public void FadeOut(TimeUnit_t deltaTime, bool destroyOnFadeout) { #if GMOD_DLL public void SetSoundLevel(float volume) => SoundLevel = (SoundLevel)(int)volume; +#if GMOD_DLL + public SoundLevel GetSoundLevel() => SoundLevel; + public void SetSoundLevel(SoundLevel soundLevel) => SoundLevel = soundLevel; +#endif public void SetDSP(int dsp) => DSP = dsp; public int GetDSP() => DSP; #endif @@ -673,6 +677,13 @@ public void CheckLoopingSoundsForPlayer(BasePlayer player) { #if GMOD_DLL public int GetDSP(SoundPatch sound) => sound.GetDSP(); public void SetDSP(SoundPatch sound, int dsp) => sound.SetDSP(dsp); + public void SetSoundLevel(SoundPatch sound, SoundLevel soundLevel) => sound.SetSoundLevel(soundLevel); + public SoundLevel GetSoundLevel(SoundPatch sound) => sound.GetSoundLevel(); + + public void GMOD_OnLuaObjectDeleted(SoundPatch? sound) { + if (sound != null) + CommandAdd(sound, 0, SoundCommands.Destroy, 0, 0); + } #endif #if CLIENT_DLL From bf205081c068d701f90e3716cb6ae36b444a74c9 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:21:25 +0000 Subject: [PATCH 3/9] LuaSurfaceInfo --- Game.Shared/GarrysMod/LuaSurfaceInfo.cs | 101 ++++++++++++++++++++++++ Source.Common/Engine/IModelInfo.cs | 12 +++ Source.Engine/ModelInfo.cs | 72 +++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 Game.Shared/GarrysMod/LuaSurfaceInfo.cs diff --git a/Game.Shared/GarrysMod/LuaSurfaceInfo.cs b/Game.Shared/GarrysMod/LuaSurfaceInfo.cs new file mode 100644 index 00000000..af04532a --- /dev/null +++ b/Game.Shared/GarrysMod/LuaSurfaceInfo.cs @@ -0,0 +1,101 @@ +#if CLIENT_DLL || GAME_DLL +using Game.Shared; + +using Source.Common; +using Source.Common.Formats.BSP; +using Source.Common.GarrysMod.Lua; +using Source.Common.MaterialSystem; + +#if CLIENT_DLL +namespace Game.Client.GarrysMod; +#else +namespace Game.Server.GarrysMod; +#endif + +public static partial class LuaSurfaceInfo +{ + [LuaClass(typeof(int))] + public static readonly LuaClass LC_SurfaceInfo = new("SurfaceInfo", LuaType.SurfaceInfo, null, null); + + public static void Push_SurfaceInfo(int surfID) { + if (!LC_SurfaceInfo.MetaTable.isTable()) + Error("CLuaClass::Push - Not Table!"); + g_Lua!.PushValueUserType(surfID, LuaType.SurfaceInfo); + } + + [LuaMethod] + static int Entity__GetBrushSurfaces(ILuaInterface lua) { + BaseEntity ent = LuaEntity.Get_Entity(1, false)!; + if (ent.IsMarkedForDeletion()) + return 0; + + Model? model = ent.GetModel(); + if (model == null || modelinfo.GetModelType(model) != ModelType.Brush) + return 0; + + int count = modelinfo.GetBrushModelSurfaceCount(model); + lua.PreCreateTable(count, 0); + int[] surfaces = new int[count]; + if (modelinfo.GetBrushModelSurfaces(model, surfaces)) { + for (int i = 0; i < count; i++) { + lua.PushNumber(i + 1); + Push_SurfaceInfo(surfaces[i]); + lua.SetTable(-3); + } + } + return 1; + } + + [LuaMethod] + static int SurfaceInfo__GetMaterial(ILuaInterface lua) { + int surfID = LC_SurfaceInfo.GetValue(1); + IMaterial? material = modelinfo.GetBrushSurfaceMaterial(surfID); + if (material == null) { + lua.PushNil(); + return 1; + } + LuaMaterial.LC_IMaterial.Push(material); + return 1; + } + + [LuaMethod] + static int SurfaceInfo__GetVertices(ILuaInterface lua) { + int surfID = LC_SurfaceInfo.GetValue(1); + BSPDertex[]? vertices = modelinfo.GetBrushSurfaceVertices(surfID, out int count); + ReadOnlySpan indices = modelinfo.GetBrushSurfaceVertIndices(surfID); + lua.PreCreateTable(count, 0); + if (!indices.IsEmpty && vertices != null) { + for (int i = 0; i < count; i++) { + lua.PushNumber(i + 1); + LuaVector.Push_Vector(vertices[indices[i]].Position); + lua.SetTable(-3); + } + } + return 1; + } + + [LuaMethod] + static int SurfaceInfo__IsNoDraw(ILuaInterface lua) { + lua.PushBool(modelinfo.IsBrushSurfaceNoDraw(LC_SurfaceInfo.GetValue(1))); + return 1; + } + + [LuaMethod] + static int SurfaceInfo__IsSky(ILuaInterface lua) { + lua.PushBool(modelinfo.IsBrushSurfaceSky(LC_SurfaceInfo.GetValue(1))); + return 1; + } + + [LuaMethod] + static int SurfaceInfo__IsWater(ILuaInterface lua) { + lua.PushBool(modelinfo.IsBrushSurfaceWater(LC_SurfaceInfo.GetValue(1))); + return 1; + } + + [LuaMethod] + static int SurfaceInfo____tostring(ILuaInterface lua) { + lua.PushString($"SurfaceInfo [{LC_SurfaceInfo.GetValue(1)}]"); + return 1; + } +} +#endif diff --git a/Source.Common/Engine/IModelInfo.cs b/Source.Common/Engine/IModelInfo.cs index aafe256e..2cffb7ab 100644 --- a/Source.Common/Engine/IModelInfo.cs +++ b/Source.Common/Engine/IModelInfo.cs @@ -1,5 +1,6 @@ using Source.Common.Client; using Source.Common.Engine; +using Source.Common.Formats.BSP; using Source.Common.MaterialSystem; using Source.Common.Mathematics; using Source.Common.Physics; @@ -93,6 +94,17 @@ public interface IVModelInfo // Automatically adds reference, pair with ReleaseDynamicModel. bool RegisterModelLoadCallback(int modelindex, IModelLoadCallback callback, bool callImmediatelyIfLoaded = true); void UnregisterModelLoadCallback(int modelindex, IModelLoadCallback callback); + +#if GMOD_DLL + int GetBrushModelSurfaceCount(Model? model); + bool GetBrushModelSurfaces(Model? model, Span surfaces); + ReadOnlySpan GetBrushSurfaceVertIndices(int surfID); + BSPDertex[]? GetBrushSurfaceVertices(int surfID, out int count); + IMaterial? GetBrushSurfaceMaterial(int surfID); + bool IsBrushSurfaceWater(int surfID); + bool IsBrushSurfaceSky(int surfID); + bool IsBrushSurfaceNoDraw(int surfID); +#endif } public interface IVModelInfoClient : IVModelInfo diff --git a/Source.Engine/ModelInfo.cs b/Source.Engine/ModelInfo.cs index 95aa66e9..2d2400c2 100644 --- a/Source.Engine/ModelInfo.cs +++ b/Source.Engine/ModelInfo.cs @@ -403,6 +403,78 @@ public void UnregisterModelLoadCallback(int modelindex, IModelLoadCallback callb throw new NotImplementedException(); } +#if GMOD_DLL + public int GetBrushModelSurfaceCount(Model? model) { + if (model == null || model.Type != ModelType.Brush || model.Brush.Shared != SourceDllMain.host_state.WorldBrush) + return 0; + return model.Brush.NumModelSurfaces; + } + + public bool GetBrushModelSurfaces(Model? model, Span surfaces) { + if (model == null || model.Type != ModelType.Brush || model.Brush.Shared != SourceDllMain.host_state.WorldBrush || surfaces.Length != model.Brush.NumModelSurfaces) + return false; + for (int i = 0; i < model.Brush.NumModelSurfaces; i++) + surfaces[i] = model.Brush.FirstModelSurface + i; + return true; + } + + public ReadOnlySpan GetBrushSurfaceVertIndices(int surfID) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) + return default; + ref BSPMSurface2 surf = ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush); + if ((ModelLoader.MSurf_Flags(ref surf) & SurfDraw.HasDisp) != 0) + return default; + return worldBrush.VertIndices.AsSpan(ModelLoader.MSurf_FirstVertIndex(ref surf)); + } + + public BSPDertex[]? GetBrushSurfaceVertices(int surfID, out int count) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) { + count = 0; + return null; + } + ref BSPMSurface2 surf = ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush); + if ((ModelLoader.MSurf_Flags(ref surf) & SurfDraw.HasDisp) != 0) { + count = 0; + return null; + } + count = ModelLoader.MSurf_VertCount(ref surf); + return worldBrush.Vertexes; + } + + public IMaterial? GetBrushSurfaceMaterial(int surfID) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) + surfID = 0; + ref BSPMSurface2 surf = ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush); + if (surf.TexInfo >= worldBrush.NumTexInfo) + Error("MSurf_TexInfo OOB"); + return ModelLoader.MSurf_TexInfo(ref surf, worldBrush).Material; + } + + public bool IsBrushSurfaceWater(int surfID) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) + surfID = 0; + return (ModelLoader.MSurf_Flags(ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush)) & SurfDraw.WaterSurface) != 0; + } + + public bool IsBrushSurfaceSky(int surfID) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) + surfID = 0; + return (ModelLoader.MSurf_Flags(ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush)) & SurfDraw.Sky) != 0; + } + + public bool IsBrushSurfaceNoDraw(int surfID) { + WorldBrushData worldBrush = SourceDllMain.host_state.WorldBrush!; + if (surfID < 0 || surfID >= worldBrush.NumSurfaces) + surfID = 0; + return (ModelLoader.MSurf_Flags(ref ModelLoader.SurfaceHandleFromIndex(surfID, worldBrush)) & SurfDraw.NoDraw) != 0; + } +#endif + readonly List NetworkedDynamicModels = []; } From 5fa65d0466bd4a69b467531ffc6fef952b9122f7 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:25:26 +0000 Subject: [PATCH 4/9] Vector IsValid uses IsFinite --- Source.Common/Mathematics/MathLib.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index a75b6fb5..c9815db5 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -1619,26 +1619,26 @@ public static float CalcSqrDistanceToAABB(in Vector3 mins, in Vector3 maxs, in V return distSqr; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector2 v) => !Vector2.AnyWhereAllBitsSet(Vector2.IsNaN(v)); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector3 v) => !Vector3.AnyWhereAllBitsSet(Vector3.IsNaN(v)); - [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector4 v) => !Vector4.AnyWhereAllBitsSet(Vector4.IsNaN(v)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector2 v) => Vector2.AllWhereAllBitsSet(Vector2.IsFinite(v)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector3 v) => Vector3.AllWhereAllBitsSet(Vector3.IsFinite(v)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsValid(this ref Vector4 v) => Vector4.AllWhereAllBitsSet(Vector4.IsFinite(v)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsValid(this ref Quaternion q) { fixed (Quaternion* pQ = &q) - return !Vector4.AnyWhereAllBitsSet(Vector4.IsNaN(*(Vector4*)pQ)); + return Vector4.AllWhereAllBitsSet(Vector4.IsFinite(*(Vector4*)pQ)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsValid(this ref QAngle a) { fixed (QAngle* pA = &a) - return !Vector3.AnyWhereAllBitsSet(Vector3.IsNaN(*(Vector3*)pA)); + return Vector3.AllWhereAllBitsSet(Vector3.IsFinite(*(Vector3*)pA)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsValid(this ref RadianEuler R) { fixed (RadianEuler* pR = &R) - return !Vector3.AnyWhereAllBitsSet(Vector3.IsNaN(*(Vector3*)pR)); + return Vector3.AllWhereAllBitsSet(Vector3.IsFinite(*(Vector3*)pR)); } public static bool MatrixInverseGeneral(in Matrix4x4 src, out Matrix4x4 dst) { From fc005119c2aed3acf751d83bae2b2def0dd88ef0 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:32:29 +0000 Subject: [PATCH 5/9] LuaProjectedTexture --- Game.Client/GarrysMod/LuaProjectedTexture.cs | 619 ++++++++++++++++++ Game.Shared/GarrysMod/LuaGameSystem.cs | 9 + .../MaterialSystem/IMaterialSystem.cs | 9 + 3 files changed, 637 insertions(+) create mode 100644 Game.Client/GarrysMod/LuaProjectedTexture.cs diff --git a/Game.Client/GarrysMod/LuaProjectedTexture.cs b/Game.Client/GarrysMod/LuaProjectedTexture.cs new file mode 100644 index 00000000..42df96ab --- /dev/null +++ b/Game.Client/GarrysMod/LuaProjectedTexture.cs @@ -0,0 +1,619 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.GarrysMod.Lua; +using Source.Common.MaterialSystem; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Client.GarrysMod; + +public class ProjectedTexture +{ + public Color Color; + public float Brightness; + public FlashlightState State; + public ClientShadowHandle_t Handle; + public bool LightWorld; + public EHANDLE Target = new(); + + public ProjectedTexture() { + State = new() { + SpotlightTextureFrame = 0, + OrthoRight = 600.0f, + OrthoBottom = 800.0f, + }; + State.EnableShadows = LuaProjectedTexture.r_flashlightdepthtexture.GetInt() != 0; + State.ShadowMapResolution = LuaProjectedTexture.r_flashlightdepthres.GetInt(); + State.ShadowFilterSize = LuaProjectedTexture.r_projectedtexture_filter.GetFloat(); + Color = new(255, 255, 255, 255); + State.LightOrigin = default; + State.Orientation = default; + State.ShadowQuality = 1; + State.NearZ = 1.0f; + State.FarZ = 2048.0f; + State.HorizontalFOVDegrees = 90.0f; + State.VerticalFOVDegrees = 90.0f; + State.QuadraticAtten = 0.0f; + State.LinearAtten = 100.0f; + State.ConstantAtten = 0.0f; + State.ShadowSlopeScaleDepthBias = 2.0f; + State.ShadowDepthBias = 0.0001f; + LightWorld = true; + Brightness = 1.0f; + Target.Set(null); + State.Color[0] = 1.0f; + State.Color[1] = 1.0f; + State.Color[2] = 1.0f; + State.Color[3] = 1.0f; + Handle = ClientShadowMgrGlobals.g_ClientShadowMgr.CreateFlashlight(in State); + LuaProjectedTexture.ProjectedTextures.Add(this); + } + + public void Remove() { + if (Handle != CLIENTSHADOW_INVALID_HANDLE) + ClientShadowMgrGlobals.g_ClientShadowMgr.DestroyFlashlight(Handle); + Handle = CLIENTSHADOW_INVALID_HANDLE; + if (State.SpotlightTexture != null) { + State.SpotlightTexture.DecrementReferenceCount(); + State.SpotlightTexture = null; + } + } +} + +public static partial class LuaProjectedTexture +{ + public static readonly ConVar r_projectedtexture_filter = new("r_projectedtexture_filter", "1", 0); + public static ConVar r_flashlightdepthtexture => ClientShadowMgrGlobals.r_flashlightdepthtexture; + public static ConVar r_flashlightdepthres => ClientShadowMgrGlobals.r_flashlightdepthres; + + public static readonly List ProjectedTextures = []; + + [LuaClass(typeof(ProjectedTexture), NullError = "Tried to use a NULL ProjectedTexture!")] + public static readonly LuaClass LC_ProjectedTexture = new("ProjectedTexture", LuaType.ProjectedTexture, null, null); + + public static void RemoveAll() { + for (int i = 0; i < ProjectedTextures.Count; i++) + ProjectedTextures[i].Remove(); + } + + static ProjectedTexture? Get_ProjectedTexture(ILuaInterface lua) { + ProjectedTexture? pt = (ProjectedTexture?)LC_ProjectedTexture.Get(1); + if (pt == null) + lua.Error("Tried to use a NULL ProjectedTexture!"); + return pt; + } + + [LuaGlobal("ProjectedTexture")] + static int CreateProjectedTexture(ILuaInterface lua) { + LC_ProjectedTexture.Push(new ProjectedTexture()); + return 1; + } + + [LuaMethod] + static int ProjectedTexture____gc(ILuaInterface lua) { + ProjectedTexture? pt = (ProjectedTexture?)LC_ProjectedTexture.Get(1); + if (pt != null) { + pt.Remove(); + ProjectedTextures.Remove(pt); + } + lua.SetUserType(1, 0); + return 0; + } + + [LuaMethod] + static int ProjectedTexture____tostring(ILuaInterface lua) { + lua.PushString("ProjectedTexture"); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__IsValid(ILuaInterface lua) { + ProjectedTexture? pt = (ProjectedTexture?)LC_ProjectedTexture.Get(1); + lua.PushBool(pt != null && pt.Handle != CLIENTSHADOW_INVALID_HANDLE); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__Remove(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.Remove(); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__Update(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + if (pt.Handle != CLIENTSHADOW_INVALID_HANDLE) { + ClientShadowMgrGlobals.g_ClientShadowMgr.UpdateFlashlightState(pt.Handle, in pt.State); + ClientShadowMgrGlobals.g_ClientShadowMgr.SetFlashlightTarget(pt.Handle, pt.Target); + ClientShadowMgrGlobals.g_ClientShadowMgr.SetFlashlightLightWorld(pt.Handle, pt.LightWorld); + ClientShadowMgrGlobals.g_ClientShadowMgr.UpdateProjectedTexture(pt.Handle, true); + } + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetAngles(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + MathLib.QuaternionAngles(in pt.State.Orientation, out QAngle angles); + LuaAngle.Push_Angle(angles); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetAngles(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + QAngle angles = LuaAngle.Get_Angle(2); + MathLib.AngleQuaternion(in angles, out pt.State.Orientation); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetPos(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + LuaVector.Push_Vector(pt.State.LightOrigin); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetPos(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.LightOrigin = LuaVector.Get_Vector(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetBrightness(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.Brightness); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetBrightness(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + float brightness = (float)lua.CheckNumber(2); + pt.Brightness = brightness; + pt.State.Color[0] = pt.Color.R * 0.003921569f * brightness; + pt.State.Color[1] = pt.Color.G * 0.003921569f * brightness; + pt.State.Color[2] = pt.Color.B * 0.003921569f * brightness; + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetColor(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushColor(pt.Color); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetColor(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + Color color = lua.GetColor(2); + float brightness = pt.Brightness; + pt.Color = color; + pt.State.Color[0] = color.R * 0.003921569f * brightness; + pt.State.Color[1] = color.G * 0.003921569f * brightness; + pt.State.Color[2] = color.B * 0.003921569f * brightness; + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetConstantAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.ConstantAtten); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetConstantAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.ConstantAtten = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetLinearAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.LinearAtten); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetLinearAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.LinearAtten = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetQuadraticAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.QuadraticAtten); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetQuadraticAttenuation(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.QuadraticAtten = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetEnableShadows(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushBool(pt.State.EnableShadows); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetEnableShadows(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + if (lua.GetBool(2) && r_flashlightdepthtexture.GetInt() != 0) { + pt.State.EnableShadows = true; + return 0; + } + pt.State.EnableShadows = false; + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetNearZ(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.NearZ); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetNearZ(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.NearZ = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetFarZ(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.FarZ); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetFarZ(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.FarZ = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__SetFOV(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + float fov = (float)lua.CheckNumber(2); + pt.State.HorizontalFOVDegrees = fov; + pt.State.VerticalFOVDegrees = fov; + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetHorizontalFOV(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.HorizontalFOVDegrees); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetHorizontalFOV(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.HorizontalFOVDegrees = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetVerticalFOV(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.VerticalFOVDegrees); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetVerticalFOV(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.VerticalFOVDegrees = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetLightWorld(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushBool(pt.LightWorld); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetLightWorld(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.LightWorld = lua.GetBool(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetNoCull(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushBool(pt.State.NoCull); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetNoCull(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.NoCull = lua.GetBool(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetSkipShadowUpdates(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushBool(pt.State.SkipShadowUpdates); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetSkipShadowUpdates(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.SkipShadowUpdates = lua.GetBool(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetOrthographic(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + if (!pt.State.Ortho) { + lua.PushBool(false); + return 1; + } + float left = pt.State.OrthoLeft; + float top = pt.State.OrthoTop; + float right = pt.State.OrthoRight; + float bottom = pt.State.OrthoBottom; + lua.PushBool(true); + lua.PushNumber(MathF.Abs(left)); + lua.PushNumber(MathF.Abs(top)); + lua.PushNumber(right); + lua.PushNumber(bottom); + return 5; + } + + [LuaMethod] + static int ProjectedTexture__SetOrthographic(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + if (lua.Top() > 2) { + double bottom = lua.CheckNumber(6); + double right = lua.CheckNumber(5); + double top = lua.CheckNumber(4); + double left = lua.CheckNumber(3); + pt.State.Ortho = lua.GetBool(2); + if (pt.State.Ortho) { + pt.State.OrthoLeft = -MathF.Abs((float)left); + pt.State.OrthoTop = -MathF.Abs((float)top); + pt.State.OrthoRight = MathF.Abs((float)right); + pt.State.OrthoBottom = MathF.Abs((float)bottom); + } + return 0; + } + pt.State.Ortho = lua.GetBool(2); + if (pt.State.Ortho) { + pt.State.OrthoLeft = -0.0f; + pt.State.OrthoRight = 0.0f; + pt.State.OrthoBottom = 0.0f; + pt.State.OrthoTop = -0.0f; + } + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetShadowDepthBias(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.ShadowDepthBias); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetShadowDepthBias(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.ShadowDepthBias = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetShadowFilter(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.ShadowFilterSize); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetShadowFilter(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.ShadowFilterSize = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetShadowSlopeScaleDepthBias(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.ShadowSlopeScaleDepthBias); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetShadowSlopeScaleDepthBias(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.ShadowSlopeScaleDepthBias = (float)lua.CheckNumber(2); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetTargetEntity(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + LuaEntity.Push_Entity(pt.Target.Get()); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetTargetEntity(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + BaseEntity? ent = LuaEntity.Get_Entity(2, true); + if (ent == null) { + pt.Target.Set(null); + return 0; + } + pt.Target.Set(ent); + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetTexture(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + if (pt.State.SpotlightTexture == null) { + lua.PushNil(); + return 1; + } + LuaTexture.Push(pt.State.SpotlightTexture); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetTexture(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + ITexture? texture; + if (lua.GetType(2) == LuaType.String) + texture = materials.FindTexture(lua.CheckString(2), "Other textures", false, 0); + else + texture = (ITexture?)LuaTexture.LC_ITexture.Get(2); + + pt.State.SpotlightTexture?.DecrementReferenceCount(); + pt.State.SpotlightTexture = texture; + texture?.IncrementReferenceCount(); + + pt.State.SpotlightTextureFrame = 0; + if (pt.State.SpotlightTexture != null && pt.State.SpotlightTexture.IsRenderTarget()) + pt.State.SpotlightTextureFrame = 0; + return 0; + } + + [LuaMethod] + static int ProjectedTexture__GetTextureFrame(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + lua.PushNumber(pt.State.SpotlightTextureFrame); + return 1; + } + + [LuaMethod] + static int ProjectedTexture__SetTextureFrame(ILuaInterface lua) { + ProjectedTexture? pt = Get_ProjectedTexture(lua); + if (pt == null) + return 0; + pt.State.SpotlightTextureFrame = (int)lua.CheckNumber(2); + if (pt.State.SpotlightTexture != null && pt.State.SpotlightTexture.IsRenderTarget()) + pt.State.SpotlightTextureFrame = 0; + return 0; + } +} diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index e476d443..a108b51e 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -96,6 +96,15 @@ public override void LevelInitPostEntity() { gGM?.Call((int)LUA_POOLEDSTRING.InitPostEntity); } + public override void LevelShutdownPreEntity() { +#if CLIENT_DLL + LuaProjectedTexture.RemoveAll(); + // todo: IMesh delete list +#else + // todo: server LevelShutdownPreEntity +#endif + } + public void StopListeningForAllEvents() { if (RegisteredForEvents) { gameeventmanager?.RemoveListener(this); diff --git a/Source.Common/MaterialSystem/IMaterialSystem.cs b/Source.Common/MaterialSystem/IMaterialSystem.cs index 226ded16..33c83378 100644 --- a/Source.Common/MaterialSystem/IMaterialSystem.cs +++ b/Source.Common/MaterialSystem/IMaterialSystem.cs @@ -216,6 +216,15 @@ public FlashlightState() { public float ShadowJitterSeed; public float ShadowAtten; public int ShadowQuality; +#if GMOD_DLL + public float OrthoLeft; + public float OrthoTop; + public float OrthoRight; + public float OrthoBottom; + public bool Ortho; + public bool NoCull; + public bool SkipShadowUpdates; +#endif // Getters for scissor members public bool DoScissor() => Scissor; From cc87d59cfa96036dfae4c0d5182af74e01b68082 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:37:31 +0000 Subject: [PATCH 6/9] LuaBfRead --- Game.Client/GarrysMod/LuaBfRead.cs | 105 ++++++++++++++++++++++ Game.Shared/GarrysMod/LuaNetworkedVars.cs | 2 +- 2 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 Game.Client/GarrysMod/LuaBfRead.cs diff --git a/Game.Client/GarrysMod/LuaBfRead.cs b/Game.Client/GarrysMod/LuaBfRead.cs new file mode 100644 index 00000000..20f3e681 --- /dev/null +++ b/Game.Client/GarrysMod/LuaBfRead.cs @@ -0,0 +1,105 @@ +using Source.Common; +using Source.Common.Bitbuffers; +using Source.Common.GarrysMod.Lua; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Client.GarrysMod; + +public static partial class LuaBfRead +{ + [LuaClass(typeof(bf_read))] + public static readonly LuaClass LC_bf_read = new("bf_read", LuaType.UserMsg, null, null); + + public static void Push_bf_read(bf_read? buf) => LC_bf_read.Push(buf); + + [LuaMethod] + static int bf_read__ReadAngle(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + buf.ReadBitAngles(out QAngle angles); + LuaAngle.Push_Angle(angles); + return 1; + } + + [LuaMethod] + static int bf_read__ReadBool(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + lua.PushBool(buf.ReadOneBit() != 0); + return 1; + } + + [LuaMethod] + static int bf_read__ReadChar(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + lua.PushNumber(buf.ReadChar()); + return 1; + } + + [LuaMethod] + static int bf_read__ReadEntity(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + uint handle = LuaNetworkedVars.ReadEHandle(buf); + if (handle == 0xFFFFFFFF) + return 0; + if (handle == 0) { + LuaEntity.Push_Entity(null); + return 1; + } + LuaEntity.Push_Entity(new EHANDLE(handle).Get()); + return 1; + } + + [LuaMethod] + static int bf_read__ReadFloat(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + lua.PushNumber(buf.ReadFloat()); + return 1; + } + + [LuaMethod] + static int bf_read__ReadLong(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + lua.PushNumber(buf.ReadLong()); + return 1; + } + + [LuaMethod] + static int bf_read__ReadShort(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + lua.PushNumber(buf.ReadShort()); + return 1; + } + + [LuaMethod] + static int bf_read__ReadString(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + Span str = stackalloc byte[128]; + buf.ReadString(str, false, out int numChars); + lua.PushString(str[..numChars]); + return 1; + } + + [LuaMethod] + static int bf_read__ReadVector(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + buf.ReadBitVec3Coord(out Vector3 vec); + LuaVector.Push_Vector(vec); + return 1; + } + + [LuaMethod] + static int bf_read__ReadVectorNormal(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + buf.ReadBitVec3Normal(out Vector3 vec); + LuaVector.Push_Vector(vec); + return 1; + } + + [LuaMethod] + static int bf_read__Reset(ILuaInterface lua) { + bf_read buf = (bf_read)LC_bf_read.Get(1)!; + buf.Seek(0); + return 0; + } +} diff --git a/Game.Shared/GarrysMod/LuaNetworkedVars.cs b/Game.Shared/GarrysMod/LuaNetworkedVars.cs index 1ddf482d..ae0ad501 100644 --- a/Game.Shared/GarrysMod/LuaNetworkedVars.cs +++ b/Game.Shared/GarrysMod/LuaNetworkedVars.cs @@ -426,7 +426,7 @@ public static void RegisterUserMessages(UserMessages messages) { messages.HookMessage("NetworkedVar", MsgFunc_NetworkedVar); } - static uint ReadEHandle(bf_read msg) { + internal static uint ReadEHandle(bf_read msg) { uint value = (uint)msg.ReadLong(); if (value == Constants.INVALID_NETWORKED_EHANDLE_VALUE) return 0xFFFFFFFF; From ced23bc0195faee2c05f85095116911828945847 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:39:21 +0000 Subject: [PATCH 7/9] LuaDLight --- Game.Client/GarrysMod/LuaDLight.cs | 128 +++++++++++++++++++++++++++++ Source.Common/DLight.cs | 2 +- 2 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 Game.Client/GarrysMod/LuaDLight.cs diff --git a/Game.Client/GarrysMod/LuaDLight.cs b/Game.Client/GarrysMod/LuaDLight.cs new file mode 100644 index 00000000..060047ed --- /dev/null +++ b/Game.Client/GarrysMod/LuaDLight.cs @@ -0,0 +1,128 @@ +using Source; +using Source.Common; +using Source.Common.GarrysMod.Lua; + +namespace Game.Client.GarrysMod; + +public static partial class LuaDLight +{ + [LuaClass(typeof(DLight), NullError = "Tried to use a NULL dlight_t!")] + public static readonly LuaClass LC_dlight_t = new("dlight_t", LuaType.DLight, null, null); + + [LuaGlobal] + static int DynamicLight(ILuaInterface lua) { + int key = (int)lua.CheckNumber(1); + DLight? light; + if (lua.GetType(2) != LuaType.Nil && lua.GetBool(2)) + light = effects.AllocElight(key); + else + light = effects.AllocDlight(key); + if (light == null) + return 0; + LC_dlight_t.Push(light); + return 1; + } + + [LuaMethod] + static int dlight_t____tostring(ILuaInterface lua) { + DLight? light = (DLight?)LC_dlight_t.Get(1); + if (light == null) { + lua.Error("Tried to use a NULL dlight_t!"); + return 0; + } + lua.PushString($"dlight_t [{light.Key}]"); + return 1; + } + + [LuaMethod] + static int dlight_t____newindex(ILuaInterface lua) { + DLight? light = (DLight?)LC_dlight_t.Get(1); + if (light == null) { + lua.Error("Tried to use a NULL dlight_t!"); + return 0; + } + + string key = lua.CheckString(2); + if (key.Length == 0) + return 0; + + if (stricmp(key, "pos") == 0 || stricmp(key, "position") == 0) { + light.Origin = LuaVector.Get_Vector(3); + return 0; + } + if (stricmp(key, "noworld") == 0) { + if (lua.GetBool(3)) + light.Flags |= DLightFlags.NoWorldIllumination; + else + light.Flags &= ~DLightFlags.NoWorldIllumination; + return 0; + } + if (stricmp(key, "nomodel") == 0) { + if (lua.GetBool(3)) + light.Flags |= DLightFlags.NoModelIllumination; + else + light.Flags &= ~DLightFlags.NoModelIllumination; + return 0; + } + if (stricmp(key, "dir") == 0 || stricmp(key, "direction") == 0) { + light.Direction = LuaVector.Get_Vector(3); + return 0; + } + if (stricmp(key, "radius") == 0 || stricmp(key, "size") == 0) { + float radius = (float)lua.GetNumber(3); + if (radius <= 0.0f) + radius = 0.0f; + if (2048.0f <= radius) + radius = 2048.0f; + light.Radius = radius; + return 0; + } + if (stricmp(key, "die") == 0 || stricmp(key, "dietime") == 0) { + light.Die = lua.GetNumber(3); + return 0; + } + if (stricmp(key, "decay") == 0 || stricmp(key, "fade") == 0) { + light.Decay = (float)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "minlight") == 0) { + light.MinLight = (float)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "style") == 0) { + light.Style = (int)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "key") == 0) { + light.Key = (int)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "InnerAngle") == 0) { + light.InnerAngle = (float)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "OuterAngle") == 0) { + light.OuterAngle = (float)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "r") == 0) { + light.Color.R = (byte)(int)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "g") == 0) { + light.Color.G = (byte)(int)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "b") == 0) { + light.Color.B = (byte)(int)lua.GetNumber(3); + return 0; + } + if (stricmp(key, "Brightness") == 0) { + light.Color.Exponent = (sbyte)(int)lua.GetNumber(3); + return 0; + } + + lua.ErrorNoHalt($"Tried to set wrong key '{key}' on Dynamic Light object.\n Valid keys: Pos, Dir, Size, DieTime, Brightness, Decay, MinLight, Style, Key, InnerAngle, OuterAngle, r, g, b, nomodel, noworld.\n"); + return 0; + } +} diff --git a/Source.Common/DLight.cs b/Source.Common/DLight.cs index 45346764..4dab8149 100644 --- a/Source.Common/DLight.cs +++ b/Source.Common/DLight.cs @@ -18,7 +18,7 @@ public class DLight public Vector3 Origin; public float Radius; public ColorRGBExp32 Color; - public float Die; + public TimeUnit_t Die; public float Decay; public float MinLight; public int Key; From 2c64eb17f509d2b73d75b8717663f9735f6d6b04 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 00:43:03 +0000 Subject: [PATCH 8/9] Fixes --- Game.Client/GarrysMod/LuaBfRead.cs | 2 ++ Game.Shared/GarrysMod/LuaSurfaceInfo.cs | 1 + 2 files changed, 3 insertions(+) diff --git a/Game.Client/GarrysMod/LuaBfRead.cs b/Game.Client/GarrysMod/LuaBfRead.cs index 20f3e681..5733a177 100644 --- a/Game.Client/GarrysMod/LuaBfRead.cs +++ b/Game.Client/GarrysMod/LuaBfRead.cs @@ -1,3 +1,5 @@ +using Game.Shared; + using Source.Common; using Source.Common.Bitbuffers; using Source.Common.GarrysMod.Lua; diff --git a/Game.Shared/GarrysMod/LuaSurfaceInfo.cs b/Game.Shared/GarrysMod/LuaSurfaceInfo.cs index af04532a..b4b3ae1c 100644 --- a/Game.Shared/GarrysMod/LuaSurfaceInfo.cs +++ b/Game.Shared/GarrysMod/LuaSurfaceInfo.cs @@ -2,6 +2,7 @@ using Game.Shared; using Source.Common; +using Source.Common.Engine; using Source.Common.Formats.BSP; using Source.Common.GarrysMod.Lua; using Source.Common.MaterialSystem; From 52c1938e1f20c931eea2ce7e48026b5b63a71677 Mon Sep 17 00:00:00 2001 From: callumok2004 Date: Wed, 11 Nov 2026 01:44:37 +0000 Subject: [PATCH 9/9] Some lua analyzers --- .../LuaReferenceAnalyzer.cs | 335 ++++++++++++++++ Source.CodeAnalysis.Lua/LuaStackAnalyzer.cs | 369 ++++++++++++++++++ 2 files changed, 704 insertions(+) create mode 100644 Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs create mode 100644 Source.CodeAnalysis.Lua/LuaStackAnalyzer.cs diff --git a/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs b/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs new file mode 100644 index 00000000..630195bf --- /dev/null +++ b/Source.CodeAnalysis.Lua/LuaReferenceAnalyzer.cs @@ -0,0 +1,335 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Operations; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Source.CodeAnalysis.Lua +{ + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class LuaReferenceAnalyzer : DiagnosticAnalyzer + { + public const string DiagnosticId = "SRCLUA001"; + + static readonly DiagnosticDescriptor Rule = new( + DiagnosticId, + "LuaObject is not unreferenced", + "'{0}' may reach the end of the method without UnReference() being called", + "Lua", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + static readonly DiagnosticDescriptor OverwriteRule = new( + "SRCLUA002", + "LuaObject overwritten while still referenced", + "A LuaObject is assigned over a local that may still hold a reference; UnReference() it first", + "Lua", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule, OverwriteRule); + + public override void Initialize(AnalysisContext context) { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterCompilationStartAction(start => { + Ownership ownership = new(start.Compilation); + start.RegisterOperationBlockAction(block => ownership.AnalyzeBlock(block)); + }); + } + + sealed class FlowResult + { + public readonly HashSet Leaked = new(SymbolEqualityComparer.Default); + public readonly HashSet Overwrites = new(); + public readonly Dictionary Created = new(SymbolEqualityComparer.Default); + public bool ReturnsOwned; + } + + sealed class Ownership + { + readonly Compilation compilation; + readonly ConcurrentDictionary returnsCache = new(SymbolEqualityComparer.Default); + readonly ConcurrentDictionary takesCache = new(SymbolEqualityComparer.Default); + [ThreadStatic] static HashSet? inProgress; + + public Ownership(Compilation compilation) => this.compilation = compilation; + + public void AnalyzeBlock(OperationBlockAnalysisContext context) { + HashSet roots = new(); + foreach (IOperation block in context.OperationBlocks) { + IOperation root = block; + while (root.Parent != null) + root = root.Parent; + if (!roots.Add(root)) + continue; + ControlFlowGraph? cfg = CreateGraph(root); + if (cfg != null) + AnalyzeGraph(context.ReportDiagnostic, cfg); + } + } + + static ControlFlowGraph? CreateGraph(IOperation root) => root switch { + IMethodBodyOperation body => ControlFlowGraph.Create(body), + IConstructorBodyOperation ctor => ControlFlowGraph.Create(ctor), + IBlockOperation statements => ControlFlowGraph.Create(statements), + _ => null, + }; + + void AnalyzeGraph(Action report, ControlFlowGraph cfg) { + FlowResult result = Run(cfg, null); + foreach (ISymbol local in result.Leaked) + if (result.Created.TryGetValue(local, out Location? location)) + report(Diagnostic.Create(Rule, location, local.Name)); + foreach (Location location in result.Overwrites) + report(Diagnostic.Create(OverwriteRule, location)); + + foreach (IMethodSymbol fn in cfg.LocalFunctions) + AnalyzeGraph(report, cfg.GetLocalFunctionControlFlowGraph(fn)); + foreach (BasicBlock block in cfg.Blocks) + foreach (IOperation op in BlockOperations(block)) + foreach (IOperation d in op.DescendantsAndSelf()) + if (d is IFlowAnonymousFunctionOperation lambda) + AnalyzeGraph(report, cfg.GetAnonymousFunctionControlFlowGraph(lambda)); + } + + static bool IsLuaObject(ITypeSymbol? type) { + for (ITypeSymbol? t = type; t != null; t = t.BaseType) + if (t.Name == "LuaObject" && t.ContainingNamespace?.Name == "GarrysMod") + return true; + return false; + } + + static bool IsLuaObjectOrInterface(ITypeSymbol? type) => + type != null && (IsLuaObject(type) || (type.Name == "ILuaObject" && type.ContainingNamespace?.ToDisplayString() == "Source.Common.GarrysMod.Lua")); + + static bool IsInterfaceMember(IMethodSymbol method, string interfaceName, string methodName) { + if (method.Name != methodName) + return false; + if (method.ContainingType.Name == interfaceName && method.ContainingType.TypeKind == TypeKind.Interface) + return true; + foreach (INamedTypeSymbol iface in method.ContainingType.AllInterfaces) + if (iface.Name == interfaceName) + foreach (ISymbol member in iface.GetMembers(methodName)) + if (SymbolEqualityComparer.Default.Equals(method.ContainingType.FindImplementationForInterfaceMember(member), method)) + return true; + return false; + } + + static IOperation? Unwrap(IOperation? op) { + while (op is IConversionOperation conv) + op = conv.Operand; + return op; + } + + static ISymbol? AsTracked(IOperation? op) => Unwrap(op) switch { + ILocalReferenceOperation local => local.Local, + IParameterReferenceOperation parameter => parameter.Parameter, + _ => null, + }; + + bool IsOwnedValue(IOperation? op) => Unwrap(op) switch { + IObjectCreationOperation creation => IsLuaObject(creation.Type), + IInvocationOperation invocation => ReturnsOwnership(invocation.TargetMethod), + _ => false, + }; + + ControlFlowGraph? GraphFor(ISymbol symbol) { + foreach (SyntaxReference reference in symbol.DeclaringSyntaxReferences) { + SyntaxNode node = reference.GetSyntax(); + if (node is not BaseMethodDeclarationSyntax && node is not LocalFunctionStatementSyntax) + continue; + if (!compilation.ContainsSyntaxTree(node.SyntaxTree)) + continue; + SemanticModel model = compilation.GetSemanticModel(node.SyntaxTree); + IOperation? op = model.GetOperation(node); + if (op != null && CreateGraph(op) is ControlFlowGraph cfg) + return cfg; + } + return null; + } + + bool Guarded(ISymbol symbol, Func compute) { + inProgress ??= new HashSet(SymbolEqualityComparer.Default); + if (!inProgress.Add(symbol)) + return false; + try { + return compute(); + } + finally { + inProgress.Remove(symbol); + } + } + + bool ReturnsOwnership(IMethodSymbol method) { + method = method.OriginalDefinition; + if (IsInterfaceMember(method, "ILuaInterface", "CreateObject") || IsInterfaceMember(method, "ILuaGameCallback", "CreateLuaObject")) + return true; + if (!IsLuaObjectOrInterface(method.ReturnType)) + return false; + if (returnsCache.TryGetValue(method, out bool cached)) + return cached; + bool result = Guarded(method, () => GraphFor(method) is ControlFlowGraph cfg && Run(cfg, null).ReturnsOwned); + returnsCache[method] = result; + return result; + } + + bool TakesOwnership(IParameterSymbol? parameter) { + if (parameter == null) + return false; + parameter = parameter.OriginalDefinition; + if (parameter.ContainingSymbol is not IMethodSymbol method) + return false; + if (parameter.Ordinal == 0 && (IsInterfaceMember(method, "ILuaInterface", "DestroyObject") || IsInterfaceMember(method, "ILuaGameCallback", "DestroyLuaObject"))) + return true; + if (!IsLuaObjectOrInterface(parameter.Type)) + return false; + if (takesCache.TryGetValue(parameter, out bool cached)) + return cached; + bool result = Guarded(parameter, () => { + if (GraphFor(method) is not ControlFlowGraph cfg) + return false; + return !Run(cfg, parameter).Leaked.Contains(parameter); + }); + takesCache[parameter] = result; + return result; + } + + FlowResult Run(ControlFlowGraph cfg, IParameterSymbol? parameter) { + FlowResult result = new(); + foreach (BasicBlock block in cfg.Blocks) + foreach (IOperation op in BlockOperations(block)) + foreach (IOperation d in op.DescendantsAndSelf()) + if (d is ISimpleAssignmentOperation assign && Unwrap(assign.Target) is ILocalReferenceOperation local && !result.Created.ContainsKey(local.Local) && IsOwnedValue(assign.Value)) + result.Created[local.Local] = assign.Value.Syntax.GetLocation(); + + if (parameter != null) + result.Created[parameter] = Location.None; + + if (result.Created.Count == 0) { + foreach (BasicBlock block in cfg.Blocks) + if (block.FallThroughSuccessor?.Semantics == ControlFlowBranchSemantics.Return && IsOwnedValue(block.BranchValue)) + result.ReturnsOwned = true; + return result; + } + + HashSet?[] input = new HashSet?[cfg.Blocks.Length]; + input[0] = new HashSet(SymbolEqualityComparer.Default); + if (parameter != null) + input[0]!.Add(parameter); + Queue work = new(); + work.Enqueue(0); + + while (work.Count > 0) { + int ordinal = work.Dequeue(); + BasicBlock block = cfg.Blocks[ordinal]; + HashSet state = new(input[ordinal]!, SymbolEqualityComparer.Default); + + foreach (IOperation op in BlockOperations(block)) + foreach (IOperation d in op.DescendantsAndSelf()) + Transfer(d, state, result); + + if (block.Kind == BasicBlockKind.Exit) { + result.Leaked.UnionWith(state); + continue; + } + + if (block.FallThroughSuccessor?.Semantics == ControlFlowBranchSemantics.Return) { + if (AsTracked(block.BranchValue) is ISymbol returned && result.Created.ContainsKey(returned)) { + if (state.Remove(returned)) + result.ReturnsOwned = true; + } + else if (IsOwnedValue(block.BranchValue)) + result.ReturnsOwned = true; + } + + Propagate(cfg, result, block.FallThroughSuccessor, state, input, work); + Propagate(cfg, result, block.ConditionalSuccessor, state, input, work); + } + return result; + } + + static IEnumerable BlockOperations(BasicBlock block) { + foreach (IOperation op in block.Operations) + yield return op; + if (block.BranchValue != null) + yield return block.BranchValue; + } + + void Propagate(ControlFlowGraph cfg, FlowResult result, ControlFlowBranch? branch, HashSet state, HashSet?[] input, Queue work) { + if (branch?.Destination == null || branch.Semantics == ControlFlowBranchSemantics.Throw || branch.Semantics == ControlFlowBranchSemantics.Rethrow) + return; + if (!branch.FinallyRegions.IsEmpty) { + state = new HashSet(state, SymbolEqualityComparer.Default); + foreach (ControlFlowRegion region in branch.FinallyRegions) + for (int i = region.FirstBlockOrdinal; i <= region.LastBlockOrdinal; i++) + foreach (IOperation op in BlockOperations(cfg.Blocks[i])) + foreach (IOperation d in op.DescendantsAndSelf()) + Transfer(d, state, result); + } + int dest = branch.Destination.Ordinal; + if (input[dest] == null) { + input[dest] = new HashSet(state, SymbolEqualityComparer.Default); + work.Enqueue(dest); + return; + } + int before = input[dest]!.Count; + input[dest]!.UnionWith(state); + if (input[dest]!.Count != before) + work.Enqueue(dest); + } + + void ReleaseArguments(ImmutableArray arguments, HashSet state) { + foreach (IArgumentOperation arg in arguments) + if (AsTracked(arg.Value) is ISymbol owned && state.Contains(owned) && TakesOwnership(arg.Parameter)) + state.Remove(owned); + } + + void Transfer(IOperation op, HashSet state, FlowResult result) { + switch (op) { + case ISimpleAssignmentOperation assign: { + if (AsTracked(assign.Target) is ISymbol target && result.Created.ContainsKey(target) && IsOwnedValue(assign.Value)) { + if (!state.Add(target)) + result.Overwrites.Add(assign.Value.Syntax.GetLocation()); + break; + } + if (AsTracked(assign.Value) is ISymbol value && result.Created.ContainsKey(value)) + state.Remove(value); + break; + } + case ITupleOperation tuple: { + foreach (IOperation element in tuple.Elements) + if (AsTracked(element) is ISymbol tracked) + state.Remove(tracked); + break; + } + case IInvocationOperation invocation: { + if (invocation.TargetMethod.GetAttributes().Any(a => a.AttributeClass?.Name == "DoesNotReturnAttribute")) { + state.Clear(); + break; + } + if (invocation.TargetMethod.Name == "UnReference" && AsTracked(invocation.Instance) is ISymbol instance) + state.Remove(instance); + ReleaseArguments(invocation.Arguments, state); + break; + } + case IObjectCreationOperation ctor: { + ReleaseArguments(ctor.Arguments, state); + break; + } + case IFlowAnonymousFunctionOperation lambda: { + HashSet names = new(lambda.Syntax.DescendantNodes().OfType().Select(id => id.Identifier.ValueText)); + state.RemoveWhere(tracked => names.Contains(tracked.Name)); + break; + } + } + } + } + } +} diff --git a/Source.CodeAnalysis.Lua/LuaStackAnalyzer.cs b/Source.CodeAnalysis.Lua/LuaStackAnalyzer.cs new file mode 100644 index 00000000..7b468923 --- /dev/null +++ b/Source.CodeAnalysis.Lua/LuaStackAnalyzer.cs @@ -0,0 +1,369 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.FlowAnalysis; +using Microsoft.CodeAnalysis.Operations; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace Source.CodeAnalysis.Lua +{ + [DiagnosticAnalyzer(LanguageNames.CSharp)] + public sealed class LuaStackAnalyzer : DiagnosticAnalyzer + { + static readonly DiagnosticDescriptor ImbalanceRule = new( + "SRCLUA003", + "Lua stack is left unbalanced", + "Paths through '{0}' leave the Lua stack at different depths ({1})", + "Lua", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + static readonly DiagnosticDescriptor ReturnCountRule = new( + "SRCLUA004", + "Lua binding returns more values than it pushed", + "Binding returns {0} value(s) but only {1} were pushed on this path", + "Lua", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + static readonly DiagnosticDescriptor UseAfterFreeRule = new( + "SRCLUA005", + "LuaObject used after UnReference()", + "'{0}' is used after UnReference() was called on it", + "Lua", + DiagnosticSeverity.Warning, + isEnabledByDefault: true); + + public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(ImbalanceRule, ReturnCountRule, UseAfterFreeRule); + + public override void Initialize(AnalysisContext context) { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterCompilationStartAction(start => { + Stack stack = new(start.Compilation); + start.RegisterOperationBlockAction(block => stack.AnalyzeBlock(block)); + }); + } + + const int Unknown = int.MinValue; + + static readonly Dictionary FixedEffects = new() { + ["Push"] = 1, ["PushNil"] = 1, ["PushString"] = 1, ["PushNumber"] = 1, ["PushBool"] = 1, ["PushCFunction"] = 1, + ["PushUserdata"] = 1, ["ReferencePush"] = 1, ["PushSpecial"] = 1, ["PushAngle"] = 1, ["PushVector"] = 1, + ["PushUserType"] = 1, ["PushValueUserType"] = 1, ["PushObjectUserType"] = 1, ["PushColor"] = 1, ["PushLong"] = 1, + ["PushLuaObject"] = 1, ["PushLuaFunction"] = 1, ["PushPooledString"] = 1, ["CreateTable"] = 1, ["PreCreateTable"] = 1, + ["NewUserdata"] = 1, ["GetField"] = 1, + ["GetTable"] = 0, ["RawGet"] = 0, ["Insert"] = 0, ["ArgError"] = 0, ["CheckNumber"] = 0, ["CheckString"] = 0, + ["CheckType"] = 0, ["Equal"] = 0, ["RawEqual"] = 0, ["GetAngle"] = 0, ["GetBool"] = 0, ["GetCFunction"] = 0, + ["GetNumber"] = 0, ["GetString"] = 0, ["GetStringBytes"] = 0, ["GetType"] = 0, ["GetTypeName"] = 0, + ["GetUserdata"] = 0, ["GetVector"] = 0, ["IsType"] = 0, ["ObjLen"] = 0, ["Top"] = 0, ["ReferenceFree"] = 0, + ["SetUserType"] = 0, ["ReleaseUserTypeObject"] = 0, ["GetValueUserType"] = 0, ["GetObjectUserType"] = 0, + ["CheckNumberOpt"] = 0, ["CheckStringOpt"] = 0, ["GetColor"] = 0, ["GetStringOrError"] = 0, ["isUserData"] = 0, + ["IsServer"] = 0, ["IsClient"] = 0, ["IsMenu"] = 0, ["Msg"] = 0, ["MsgColour"] = 0, ["ErrorNoHalt"] = 0, + ["GetObject"] = 0, ["GetReturn"] = 0, ["Global"] = 0, ["CreateObject"] = 0, ["DestroyObject"] = 0, + ["GetNewTable"] = 0, ["NewTemporaryObject"] = 0, ["SetType"] = 0, ["GetActualTypeName"] = 0, ["SetMember"] = 0, + ["GetMetaTableObject"] = 0, ["NewGlobalTable"] = 0, ["GetPooledString"] = 0, + ["SetField"] = -1, ["SetMetaTable"] = -1, ["Remove"] = -1, ["ReferenceCreate"] = -1, + ["SetTable"] = -2, ["RawSet"] = -2, + }; + + static readonly HashSet ObjectPushers = new() { "Push", "PushMemberFast" }; + + static readonly HashSet Rereferencers = new() { "UnReference", "SetFromStack", "SetReference", "Set", "SetFromGlobal", "Init" }; + + sealed class Stack + { + readonly Compilation compilation; + readonly ConcurrentDictionary summaries = new(SymbolEqualityComparer.Default); + [ThreadStatic] static HashSet? inProgress; + + public Stack(Compilation compilation) => this.compilation = compilation; + + public void AnalyzeBlock(OperationBlockAnalysisContext context) { + if (context.OwningSymbol is not IMethodSymbol method) + return; + HashSet roots = new(); + foreach (IOperation block in context.OperationBlocks) { + IOperation root = block; + while (root.Parent != null) + root = root.Parent; + if (!roots.Add(root) || CreateGraph(root) is not ControlFlowGraph cfg) + continue; + RunStack(cfg, method, context.ReportDiagnostic); + RunUseAfterFree(cfg, context.ReportDiagnostic); + } + } + + static ControlFlowGraph? CreateGraph(IOperation root) => root switch { + IMethodBodyOperation body => ControlFlowGraph.Create(body), + IConstructorBodyOperation ctor => ControlFlowGraph.Create(ctor), + IBlockOperation statements => ControlFlowGraph.Create(statements), + _ => null, + }; + + static IEnumerable BlockOperations(BasicBlock block) { + foreach (IOperation op in block.Operations) + yield return op; + if (block.BranchValue != null) + yield return block.BranchValue; + } + + static IOperation? Unwrap(IOperation? op) { + while (op is IConversionOperation conv) + op = conv.Operand; + return op; + } + + static bool IsBinding(IMethodSymbol method) => + method.ReturnType.SpecialType == SpecialType.System_Int32 && + method.Parameters.Any(p => IsLuaApi(p.Type)); + + static bool IsLuaApi(ITypeSymbol? type) { + if (type == null) + return false; + if (type.Name is "ILuaBase" or "ILuaInterface" && type.ContainingNamespace?.ToDisplayString() == "Source.Common.GarrysMod.Lua") + return true; + return type.AllInterfaces.Any(i => i.Name is "ILuaBase" or "ILuaInterface"); + } + + static bool IsLuaObject(ITypeSymbol? type) { + if (type == null) + return false; + if (type.Name == "ILuaObject") + return true; + return type.AllInterfaces.Any(i => i.Name == "ILuaObject"); + } + + static bool DoesNotReturn(IMethodSymbol method) => method.GetAttributes().Any(a => a.AttributeClass?.Name == "DoesNotReturnAttribute"); + + static int? Constant(IOperation? op) { + op = Unwrap(op); + if (op?.ConstantValue.HasValue == true && op.ConstantValue.Value is int i) + return i; + return null; + } + + static int? Argument(IInvocationOperation invocation, int ordinal) { + foreach (IArgumentOperation arg in invocation.Arguments) + if (arg.Parameter?.Ordinal == ordinal) + return arg.ArgumentKind == ArgumentKind.DefaultValue && arg.Parameter.HasExplicitDefaultValue && arg.Parameter.ExplicitDefaultValue is int d ? d : Constant(arg.Value); + return null; + } + + int Effect(IInvocationOperation invocation) { + IMethodSymbol target = invocation.TargetMethod; + string name = target.Name; + + if (invocation.Instance != null && IsLuaApi(invocation.Instance.Type)) { + switch (name) { + case "Pop": + return Argument(invocation, 0) is int popped ? -popped : Unknown; + case "Call": + return Argument(invocation, 0) is int args && Argument(invocation, 1) is int results ? -(args + 1) + results : Unknown; + case "PushCClosure": + return Argument(invocation, 1) is int upvalues ? 1 - upvalues : Unknown; + case "SetMember": + return invocation.Arguments.Length == 2 ? -1 : 0; + } + return FixedEffects.TryGetValue(name, out int effect) ? effect : Unknown; + } + + int summary = Summary(target); + if (summary != NoSource) + return summary; + if (invocation.Instance != null && IsLuaObject(invocation.Instance.Type)) + return ObjectPushers.Contains(name) ? 1 : 0; + if (target.Parameters.Any(p => IsLuaApi(p.Type) || IsLuaObject(p.Type)) || name.StartsWith("Push", StringComparison.Ordinal) || name.StartsWith("Pop", StringComparison.Ordinal)) + return Unknown; + return 0; + } + + const int NoSource = int.MaxValue; + + int Summary(IMethodSymbol method) { + method = method.OriginalDefinition; + if (summaries.TryGetValue(method, out int cached)) + return cached; + inProgress ??= new HashSet(SymbolEqualityComparer.Default); + if (!inProgress.Add(method)) + return Unknown; + int result = NoSource; + try { + foreach (SyntaxReference reference in method.DeclaringSyntaxReferences) { + SyntaxNode node = reference.GetSyntax(); + if (node is not BaseMethodDeclarationSyntax && node is not LocalFunctionStatementSyntax && node is not AccessorDeclarationSyntax && node is not ArrowExpressionClauseSyntax) + continue; + if (!compilation.ContainsSyntaxTree(node.SyntaxTree)) + continue; + IOperation? op = compilation.GetSemanticModel(node.SyntaxTree).GetOperation(node); + if (op != null && CreateGraph(op) is ControlFlowGraph cfg) + result = RunStack(cfg, null, null); + break; + } + } + finally { + inProgress.Remove(method); + } + summaries[method] = result; + return result; + } + + int Apply(IOperation op, int depth, out bool ended) { + ended = false; + foreach (IOperation d in op.DescendantsAndSelf().Reverse()) { + if (d is not IInvocationOperation invocation) + continue; + if (DoesNotReturn(invocation.TargetMethod)) { + ended = true; + return depth; + } + int effect = Effect(invocation); + if (effect == Unknown) + return Unknown; + depth += effect; + } + return depth; + } + + int RunStack(ControlFlowGraph cfg, IMethodSymbol? method, Action? report) { + bool binding = method != null && IsBinding(method); + int?[] input = new int?[cfg.Blocks.Length]; + input[0] = 0; + Queue work = new(); + work.Enqueue(0); + HashSet exitDepths = new(); + bool unknown = false; + bool returnsMatchDepth = method?.ReturnType.SpecialType == SpecialType.System_Int32; + + while (work.Count > 0 && !unknown) { + int ordinal = work.Dequeue(); + BasicBlock block = cfg.Blocks[ordinal]; + int depth = input[ordinal]!.Value; + bool ended = false; + + foreach (IOperation op in BlockOperations(block)) { + depth = Apply(op, depth, out ended); + if (depth == Unknown || ended) + break; + } + if (depth == Unknown) { + unknown = true; + break; + } + if (ended) + continue; + + if (block.Kind == BasicBlockKind.Exit) { + exitDepths.Add(depth); + continue; + } + + if (block.FallThroughSuccessor?.Semantics == ControlFlowBranchSemantics.Return) { + int? returned = Constant(block.BranchValue); + if (returned != depth) + returnsMatchDepth = false; + if (binding && returned is int count && count > 0 && count > depth) + report?.Invoke(Diagnostic.Create(ReturnCountRule, block.BranchValue!.Syntax.GetLocation(), count, depth)); + } + + foreach (ControlFlowBranch? branch in new[] { block.FallThroughSuccessor, block.ConditionalSuccessor }) { + if (branch?.Destination == null || branch.Semantics is ControlFlowBranchSemantics.Throw or ControlFlowBranchSemantics.Rethrow) + continue; + int dest = branch.Destination.Ordinal; + if (branch.Destination.Kind == BasicBlockKind.Exit) { + exitDepths.Add(depth); + continue; + } + if (input[dest] == null) { + input[dest] = depth; + work.Enqueue(dest); + } + else if (input[dest] != depth) { + if (dest <= ordinal || binding) { + unknown = true; + break; + } + if (method != null && report != null && method.ReturnType.SpecialType != SpecialType.System_Boolean) + report(Diagnostic.Create(ImbalanceRule, method.Locations.FirstOrDefault(), method.Name, $"{input[dest]} vs {depth}")); + unknown = true; + break; + } + } + } + + if (unknown) + return Unknown; + if (exitDepths.Count > 1) { + if (!binding && !returnsMatchDepth && method != null && report != null && method.ReturnType.SpecialType != SpecialType.System_Boolean) + report(Diagnostic.Create(ImbalanceRule, method.Locations.FirstOrDefault(), method.Name, string.Join(" vs ", exitDepths))); + return Unknown; + } + return exitDepths.Count == 1 ? exitDepths.First() : 0; + } + + static ILocalSymbol? AsLocal(IOperation? op) => (Unwrap(op) as ILocalReferenceOperation)?.Local; + + static void FreeTransfer(BasicBlock block, HashSet released, List? report) { + foreach (IOperation op in BlockOperations(block)) + foreach (IOperation d in op.DescendantsAndSelf().Reverse()) { + switch (d) { + case ISimpleAssignmentOperation assign when AsLocal(assign.Target) is ILocalSymbol target: + released.Remove(target); + break; + case IInvocationOperation invocation when AsLocal(invocation.Instance) is ILocalSymbol local && IsLuaObject(local.Type): { + if (invocation.TargetMethod.Name == "UnReference") + released.Add(local); + else if (Rereferencers.Contains(invocation.TargetMethod.Name)) + released.Remove(local); + else if (released.Contains(local)) + report?.Add(Diagnostic.Create(UseAfterFreeRule, invocation.Syntax.GetLocation(), local.Name)); + break; + } + } + } + } + + void RunUseAfterFree(ControlFlowGraph cfg, Action report) { + HashSet?[] input = new HashSet?[cfg.Blocks.Length]; + input[0] = new HashSet(SymbolEqualityComparer.Default); + Queue work = new(); + work.Enqueue(0); + + while (work.Count > 0) { + int ordinal = work.Dequeue(); + BasicBlock block = cfg.Blocks[ordinal]; + HashSet released = new(input[ordinal]!, SymbolEqualityComparer.Default); + FreeTransfer(block, released, null); + + foreach (ControlFlowBranch? branch in new[] { block.FallThroughSuccessor, block.ConditionalSuccessor }) { + if (branch?.Destination == null) + continue; + int dest = branch.Destination.Ordinal; + if (input[dest] == null) { + input[dest] = new HashSet(released, SymbolEqualityComparer.Default); + work.Enqueue(dest); + } + else { + int before = input[dest]!.Count; + input[dest]!.IntersectWith(released); + if (input[dest]!.Count != before) + work.Enqueue(dest); + } + } + } + + List found = new(); + for (int i = 0; i < cfg.Blocks.Length; i++) + if (input[i] != null) + FreeTransfer(cfg.Blocks[i], new HashSet(input[i]!, SymbolEqualityComparer.Default), found); + foreach (Diagnostic diagnostic in found) + report(diagnostic); + } + } + } +}