From 02b4826123816b4aed6e34bf80f1c020f415b4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:04:41 +0200 Subject: [PATCH 1/5] Record map entity refs while loading the map --- Game.Server/GameInterface.cs | 3 ++- Game.Server/MapEntities.cs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Game.Server/GameInterface.cs b/Game.Server/GameInterface.cs index 032255fa..63dd6b90 100644 --- a/Game.Server/GameInterface.cs +++ b/Game.Server/GameInterface.cs @@ -560,7 +560,7 @@ public bool LevelInit(ReadOnlySpan pMapName, ReadOnlyMemory pMapEnti gpGlobals.LoadType = MapLoadType.NewGame; // Clear out entity references, and parse the entities into it. - // g_MapEntityRefs.Purge(); + g_MapEntityRefs.Clear(); MapLoadEntityFilter filter = new(); MapEntity_ParseAllEntities(pMapEntities, filter); @@ -1183,6 +1183,7 @@ class MapLoadEntityFilter : IMapEntityFilter entref.SerialNumber = ret.Edict()!.NetworkSerialNumber; } + g_MapEntityRefs.Add(entref); return ret; } } diff --git a/Game.Server/MapEntities.cs b/Game.Server/MapEntities.cs index e7fe1b56..f5fab742 100644 --- a/Game.Server/MapEntities.cs +++ b/Game.Server/MapEntities.cs @@ -37,6 +37,8 @@ public static class MapEntities { static ref Edict? g_pForceAttachEdict => ref BaseEntity.g_pForceAttachEdict; + internal static readonly List g_MapEntityRefs = []; + // creates an entity by string name, but does not spawn it public static BaseEntity? CreateEntityByName(ReadOnlySpan className, int forceEdictIndex = -1) { if (forceEdictIndex != -1) { From c51a93bf47914b0e8a0354ec4b0a17f0930f054d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:37:16 +0200 Subject: [PATCH 2/5] Port GMODGameRules.CleanUpMap and its map entity filter --- Game.Shared/GarrysMod/GMODGameRules.cs | 123 +++++++++++++++++++++++++ 1 file changed, 123 insertions(+) diff --git a/Game.Shared/GarrysMod/GMODGameRules.cs b/Game.Shared/GarrysMod/GMODGameRules.cs index bcadcdee..f99d77d2 100644 --- a/Game.Shared/GarrysMod/GMODGameRules.cs +++ b/Game.Shared/GarrysMod/GMODGameRules.cs @@ -822,6 +822,129 @@ public override void InitDefaultAIRelationships() { BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.PlayerAllyVital, Disposition.LI, 0); BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.HackedRollermine, Disposition.LI, 0); } + + public static bool CleaningUpMap; + + static readonly string[] PreserveEnts = [ + "ai_network", + "ai_hint", + "env_sun", + "env_wind", + "env_fog_controller", + "infodecal", + "info_projecteddecal", + "info_node", + "info_node_hint", + "info_hint", + "info_node_air", + "info_node_air_hint", + "info_node_climb", + "info_node_air", + "info_map_parameters", + "info_ladder", + "player", + "path_corner", + "scene_manager", + "shadow_control", + "sky_camera", + "soundent", + "viewmodel", + "predicted_viewmodel", + "worldspawn", + "point_devshot_camera", + "physgun_beam", + "player_manager", + "gmod_gamerules", + "trigger_soundscape", + "env_soundscape", + "env_soundscape_proxy", + "env_soundscape_triggerable", + "env_sound", + "env_skypaint", + "gmod_hands", + ]; + + static bool IsPreservedClass(ReadOnlySpan className) { + foreach (string name in PreserveEnts) { + if (stricmp(name, className) == 0) + return true; + } + return false; + } + + static bool CleanupFilterContains(ILuaObject? filters, ReadOnlySpan className) { + if (filters == null || !filters.isTable()) + return false; + + 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); + return true; + } + lua.Pop(1); + } + lua.Pop(1); + return false; + } + + sealed class GMODMapEntityFilter(ILuaObject? filters) : IMapEntityFilter + { + int Iterator; + + public bool ShouldCreateEntity(ReadOnlySpan className) { + if (!IsPreservedClass(className) && !CleanupFilterContains(filters, className)) + return true; + + if (Iterator < g_MapEntityRefs.Count) + Iterator++; + return false; + } + + public BaseEntity? CreateNextEntity(ReadOnlySpan className) { + if (Iterator >= g_MapEntityRefs.Count) + return null; + + MapEntityRef entRef = g_MapEntityRefs[Iterator++]; + if (entRef.Edict != -1 && engine.PEntityOfEntIndex(entRef.Edict) == null) + return CreateEntityByName(className, entRef.Edict); + return CreateEntityByName(className); + } + } + + public void CleanUpMap(ILuaObject? filters) { + BaseEntity? ent = gEntList.FirstEnt(); + AI_DynamicLink.gm_bInitialized = false; + // todo: AI_DynamicLink.PurgeDynamicLinks(); + // todo: AI_DynamicLink.ResetStates(); + + CleaningUpMap = true; + while (ent != null) { + if (ent is BaseCombatWeapon weapon) { + BaseEntity? owner = weapon.GetOwner(); + if ((owner == null || !owner.IsPlayer()) && !ent.IsEFlagSet(EFL.KeepOnRecreateEntities)) + Util.Remove(ent); + } + else { + ReadOnlySpan className = ent.GetClassname(); + if (!IsPreservedClass(className) && !ent.IsEFlagSet(EFL.KeepOnRecreateEntities) && !LuaEnts.IsProtectedEntity(ent) && !CleanupFilterContains(filters, className)) + Util.Remove(ent); + } + ent = gEntList.NextEnt(ent); + } + CleaningUpMap = false; + + gEntList.CleanupDeleteList(); + g_EventQueue.Clear(); + engine.AllowImmediateEdictReuse(); + + MapEntity_ParseAllEntities(engine.GetMapEntitiesString(), new GMODMapEntityFilter(filters), true); + + AI_DynamicLink.InitDynamicLinks(); + // todo: unidentified reset call that follows InitDynamicLinks + } #endif } #endif From 6b70ee1adaec9961b68b796750fbcc9e839c9aa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:18:53 +0200 Subject: [PATCH 3/5] Port game.CleanUpMap on the server --- Game.Shared/GarrysMod/LuaGame.cs | 84 ++++++++++++++++++++++++++ Game.Shared/GarrysMod/LuaGameSystem.cs | 2 +- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index 8ebdb17f..177fe2b9 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -139,6 +139,90 @@ static int SetGlobalCounter(ILuaInterface lua) { GlobalEntity.SetCounter(index, counter); return 0; } + + public static bool MapCleanupRunning; + public static bool MapCleanupDeferred; + static bool MapCleanupPending; + static bool MapCleanupDontSendToClients; + static readonly LuaObject MapCleanupFilters = new(); + static readonly LuaObject MapCleanupCallback = new(); + + [LuaFunction] + static int CleanUpMap(ILuaInterface lua) { + // todo: refuse with "Cannot run game.CleanUpMap while deleting entities!\n" while entities are being deleted + if (MapCleanupRunning || MapCleanupPending) { + lua.ErrorFromLua("Cannot run game.CleanUpMap while it is already running!\n"); + return 0; + } + + bool dontSendToClients = lua.GetType(1) != LuaType.Nil && lua.GetBool(1); + + LuaObject filters = new(2, LuaType.None); + if (!filters.isNil() && !filters.isTable()) { + filters.UnReference(); + lua.TypeError("table", 2); + } + + LuaObject callback = new(3, LuaType.None); + if (!callback.isNil() && !callback.isFunction()) { + callback.UnReference(); + filters.UnReference(); + lua.TypeError("function", 3); + } + + if (callback.isNil()) + DoCleanUpMap(dontSendToClients, filters); + else { + MapCleanupPending = true; + MapCleanupCallback.Set(callback); + MapCleanupFilters.Set(filters); + MapCleanupDontSendToClients = dontSendToClients; + } + + callback.UnReference(); + filters.UnReference(); + return 0; + } + + static void DoCleanUpMap(bool dontSendToClients, ILuaObject filters) { + MapCleanupRunning = true; + gGM?.Call((int)LUA_POOLEDSTRING.PreCleanupMap); + + if (g_pGameRules is GMODGameRules rules) + rules.CleanUpMap(filters); + + if (!dontSendToClients) { + RecipientFilter filter = new(); + filter.AddAllPlayers(); + filter.MakeReliable(); + GarrysMod.BroadcastLua(filter, "game.CleanUpMap()"); + } + + // todo: unidentified step between the client broadcast and AllowImmediateEdictReuse + engine.AllowImmediateEdictReuse(); + + gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap); + MapCleanupRunning = false; + } + + public static void RunMapCleanupIfNeeded() { + if (!MapCleanupPending) + return; + + MapCleanupDeferred = true; + DoCleanUpMap(MapCleanupDontSendToClients, MapCleanupFilters); + MapCleanupDeferred = false; + MapCleanupPending = false; + + if (g_Lua != null && MapCleanupCallback.isFunction()) { + MapCleanupCallback.Push(); + g_Lua.CallInternalNoReturns(0); + } + + MapCleanupCallback.UnReference(); + MapCleanupFilters.UnReference(); + MapCleanupDontSendToClients = false; + } #endif [LuaFunction] diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index 1d73224b..228ea92a 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -81,7 +81,7 @@ public override void FrameUpdatePreEntityThink() { garrysmod.Think(); // RemoveQueuedRecipientFilters(); LuaEntity.RemoveQueuedEntities(); - // RunMapCleanupIfNeeded(); + LuaGame.RunMapCleanupIfNeeded(); if (gpGlobals.TickCount != LastTick) { LastTick = gpGlobals.TickCount; gGM.Call((int)LUA_POOLEDSTRING.Tick); From 4e09bea25f7b35b0f688ba3043a2f9d74623ba40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:42:09 +0200 Subject: [PATCH 4/5] Defer deletes and keep global states during map cleanup --- Game.Server/BaseEntity.cs | 6 +++++- Game.Server/EntityList.cs | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 6e2f300e..8a007cf7 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -973,7 +973,11 @@ public virtual void UpdateOnRemove() { } } - if (GlobalName != null) { + if (GlobalName != null +#if GMOD_DLL + && !GMODGameRules.CleaningUpMap +#endif + ) { // NOTE: During level shutdown the global list will suppress this // it assumes your changing levels or the game will end // causing the whole list to be flushed diff --git a/Game.Server/EntityList.cs b/Game.Server/EntityList.cs index db164c2d..16ef7366 100644 --- a/Game.Server/EntityList.cs +++ b/Game.Server/EntityList.cs @@ -284,6 +284,10 @@ public void AddListenerEntity(IEntityListener listener) { public void RemoveListenerEntity(IEntityListener listener) => EntityListeners.Remove(listener); public void CleanupDeleteList() { +#if GMOD_DLL + if (GarrysMod.LuaGame.MapCleanupRunning && !GarrysMod.LuaGame.MapCleanupDeferred) + return; +#endif PhysOnCleanupDeleteList(); Util.g_bDisableEhandleAccess = true; From 486eaa97ecd1575d819d8f29ee6f5464f1258777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:30:35 +0200 Subject: [PATCH 5/5] Port game.CleanUpMap on the client --- Game.Shared/GarrysMod/LuaGame.cs | 61 ++++++++++++++++++++++++++ Game.Shared/GarrysMod/LuaGameSystem.cs | 2 +- 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs index 177fe2b9..18987026 100644 --- a/Game.Shared/GarrysMod/LuaGame.cs +++ b/Game.Shared/GarrysMod/LuaGame.cs @@ -225,6 +225,67 @@ public static void RunMapCleanupIfNeeded() { } #endif +#if CLIENT_DLL + public static bool MapCleanupRunning; + static bool MapCleanupPending; + static readonly LuaObject MapCleanupCallback = new(); + + [LuaFunction] + static int CleanUpMap(ILuaInterface lua) { + // todo: refuse with "Cannot run game.CleanUpMap while deleting entities!\n" while entities are being deleted + if (MapCleanupRunning || MapCleanupPending) { + lua.ErrorFromLua("Cannot run game.CleanUpMap while it is already running!\n"); + return 0; + } + + LuaObject callback = new(3, LuaType.None); + if (!callback.isNil() && !callback.isFunction()) { + callback.UnReference(); + lua.TypeError("function", 3); + } + + if (callback.isNil()) + DoCleanUpMap(); + else { + MapCleanupPending = true; + MapCleanupCallback.Set(callback); + } + + callback.UnReference(); + return 0; + } + + static void DoCleanUpMap() { + MapCleanupRunning = true; + gGM?.Call((int)LUA_POOLEDSTRING.PreCleanupMap); + + // todo: remove the Lua-created clientside entities + 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 + + gGM?.Call((int)LUA_POOLEDSTRING.PostCleanupMap); + MapCleanupRunning = false; + } + + public static void RunMapCleanupIfNeeded() { + if (!MapCleanupPending) + return; + + DoCleanUpMap(); + MapCleanupPending = false; + + if (g_Lua != null && MapCleanupCallback.isFunction()) { + MapCleanupCallback.Push(); + g_Lua.CallInternalNoReturns(0); + } + + MapCleanupCallback.UnReference(); + } +#endif + [LuaFunction] static int GetTimeScale(ILuaInterface lua) { if (g_pGameRules is not GMODGameRules rules) diff --git a/Game.Shared/GarrysMod/LuaGameSystem.cs b/Game.Shared/GarrysMod/LuaGameSystem.cs index 228ea92a..19b30959 100644 --- a/Game.Shared/GarrysMod/LuaGameSystem.cs +++ b/Game.Shared/GarrysMod/LuaGameSystem.cs @@ -53,7 +53,7 @@ public override void Update(double frametime) { LuaMesh.FlushPendingDestroy(); // RemoveQueuedRenderTargets(); LuaEntity.RemoveQueuedEntities(); - // RunMapCleanupIfNeeded(); + LuaGame.RunMapCleanupIfNeeded(); if (g_Lua == null || GarrysMod.g_LuaManager == null || gGM == null) return;