Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotfix: SIT GC #287

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 16 additions & 19 deletions Source/Configuration/PluginConfigSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,37 +38,34 @@ public void GetSettings()

}

internal sealed class ConfigurationManagerAttributes
{
public bool? IsAdvanced = false;
public bool? ShowRangeAsPercent;
}

public class SITAdvancedSettings
{
public const string Advanced = "Advanced";
public ConfigFile Config { get; }
public ManualLogSource Logger { get; }

public bool SETTING_EnableSITGC
{
get
{
return StayInTarkovPlugin.Instance.Config.Bind
(Advanced, "EnableSITGC", false, new ConfigDescription("Enable SIT's own Garbage Collector")).Value;
}
}

public uint SETTING_SITGCMemoryThreshold
{
get
{
return StayInTarkovPlugin.Instance.Config.Bind
(Advanced, "SITGCMemoryThreshold", 90u, new ConfigDescription("SIT's Garbage Collector. System Memory % before SIT forces a Garbage Collection.")).Value;
}
}
public bool SETTING_EnableSITGC { get; set; }

public uint SETTING_SITGCMemoryThreshold { get; set; }
public uint SETTING_SITGCMemoryCheckTime { get; set; }

public SITAdvancedSettings(ManualLogSource logger, ConfigFile config)
{
Logger = logger;
Config = config;
_ = SETTING_EnableSITGC;
_ = SETTING_SITGCMemoryThreshold;
SETTING_EnableSITGC = StayInTarkovPlugin.Instance.Config.Bind
(Advanced, "EnableSITGC", false, new ConfigDescription("Enable SIT's own Garbage Collector")).Value;
SETTING_SITGCMemoryThreshold = StayInTarkovPlugin.Instance.Config.Bind
(Advanced, "SITGCMemoryThreshold", 90u, new ConfigDescription("System Memory usage % limit, above that, SIT forces the run of Garbage Collection.", new AcceptableValueRange<uint>(50u, 95u), new ConfigurationManagerAttributes { IsAdvanced = true, ShowRangeAsPercent = true })).Value;
SETTING_SITGCMemoryCheckTime = StayInTarkovPlugin.Instance.Config.Bind
(Advanced, "SITGCMemoryCheckTime", 300u, new ConfigDescription("Set how many seconds to wait between SIT's Garbage Collector checks.", new AcceptableValueRange<uint>(60u, 900u), new ConfigurationManagerAttributes { IsAdvanced = true })).Value;

}

}
Expand Down
57 changes: 3 additions & 54 deletions Source/Coop/Components/CoopGameComponents/SITGameComponent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@

public bool RunAsyncTasks { get; set; } = true;

float screenScale = 1.0f;

Check warning on line 127 in Source/Coop/Components/CoopGameComponents/SITGameComponent.cs

View workflow job for this annotation

GitHub Actions / Build-SIT (Debug)

The field 'SITGameComponent.screenScale' is assigned but its value is never used

Camera GameCamera { get; set; }

Expand Down Expand Up @@ -331,8 +331,7 @@
// CoopSITGame.SendPlayerDataToServer((LocalPlayer)Singleton<GameWorld>.Instance.RegisteredPlayers.First(x => x.IsYourPlayer));
//}

GarbageCollect();
StartCoroutine(GarbageCollectSIT());
this.GetOrAddComponent<SITGameGCComponent>();

StartCoroutine(SendPlayerStatePacket());

Expand All @@ -358,58 +357,7 @@
ListOfInteractiveObjects = FindObjectsOfType<WorldInteractiveObject>();
}

private void GarbageCollect()
{
// Start the SIT Garbage Collector
Logger.LogDebug($"{nameof(GarbageCollect)}");
BSGMemoryGC.RunHeapPreAllocation();
BSGMemoryGC.Collect(force: true);
BSGMemoryGC.EmptyWorkingSet();
BSGMemoryGC.GCEnabled = true;
//Resources.UnloadUnusedAssets();
}

/// <summary>
/// Runs the Garbage Collection every 5 minutes
/// </summary>
/// <returns></returns>
private IEnumerator GarbageCollectSIT()
{
while(true)
{
if (PluginConfigSettings.Instance.AdvancedSettings.SETTING_EnableSITGC)
{
var nearestEnemyDist = float.MaxValue;
foreach(var p in Players)
{
if (p.Key == Singleton<GameWorld>.Instance.MainPlayer.ProfileId)
continue;

var dist = Vector3.Distance(p.Value.Transform.position, Singleton<GameWorld>.Instance.MainPlayer.Transform.position);
if(dist < nearestEnemyDist)
nearestEnemyDist = dist;
}

if (nearestEnemyDist > 10)
{
var mem = MemoryInfo.GetCurrentStatus();
if (mem == null)
{
yield return new WaitForSeconds(1);
continue;
}

var memPercentInUse = mem.dwMemoryLoad;
Logger.LogDebug($"Total memory used: {mem.dwMemoryLoad}%");
if (memPercentInUse > PluginConfigSettings.Instance.AdvancedSettings.SETTING_SITGCMemoryThreshold)
GarbageCollect();

}
}

yield return new WaitForSeconds(60);
}
}


/// <summary>
/// This is a simple coroutine to allow methods to run every second.
Expand Down Expand Up @@ -595,6 +543,7 @@
StopCoroutine(EverySecondCoroutine());

CoopPatches.EnableDisablePatches();
GameObject.Destroy(this.GetComponent<SITGameGCComponent>());
}

TimeSpan LateUpdateSpan = TimeSpan.Zero;
Expand Down
102 changes: 102 additions & 0 deletions Source/Coop/Components/CoopGameComponents/SITGameGCComponent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using Comfort.Common;
using EFT;
using StayInTarkov.Configuration;
using StayInTarkov.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace StayInTarkov.Coop.Components.CoopGameComponents
{
public sealed class SITGameGCComponent : MonoBehaviour
{
private DateTime LastTimeRun { get; set; } = DateTime.MinValue;
private BepInEx.Logging.ManualLogSource Logger { get; set; }

private int LastNumberOfPlayers { get; set; }

private int NumberOfAlivePlayers => Singleton<GameWorld>.Instance.AllAlivePlayersList.Count;

#region Unity methods

void Awake()
{
Logger = BepInEx.Logging.Logger.CreateLogSource(nameof(SITGameGCComponent));
Logger.LogDebug($"{nameof(SITGameGCComponent)}:{nameof(Awake)}");
}

void Start()
{
Logger.LogDebug($"{nameof(SITGameGCComponent)}:{nameof(Start)}");
GarbageCollect();
}

void Update()
{
if((DateTime.Now - LastTimeRun).TotalSeconds > PluginConfigSettings.Instance.AdvancedSettings.SETTING_SITGCMemoryCheckTime)
{
LastTimeRun = DateTime.Now;
GarbageCollectSIT();
}

if (NumberOfAlivePlayers != LastNumberOfPlayers)
{
LastNumberOfPlayers = NumberOfAlivePlayers;
BSGMemoryGC.Collect(force: false);
}
}

#endregion

private void GarbageCollect()
{
Logger.LogDebug($"{nameof(GarbageCollect)}");
BSGMemoryGC.RunHeapPreAllocation();
BSGMemoryGC.Collect(force: true);
BSGMemoryGC.EmptyWorkingSet();
BSGMemoryGC.GCEnabled = true;
Resources.UnloadUnusedAssets();
}

/// <summary>
/// Runs the Garbage Collection
/// </summary>
/// <returns></returns>
private void GarbageCollectSIT()
{
if (!PluginConfigSettings.Instance.AdvancedSettings.SETTING_EnableSITGC)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we move this early return up into the Update function so that nothing runs if this is false?
this way, we can disable all custom GC code we have, in case of user issues

return;

var nearestEnemyDist = float.MaxValue;
foreach (var p in Singleton<GameWorld>.Instance.AllAlivePlayersList)
{
if (p.ProfileId == Singleton<GameWorld>.Instance.MainPlayer.ProfileId)
continue;

var dist = Vector3.Distance(p.Transform.position, Singleton<GameWorld>.Instance.MainPlayer.Transform.position);
if (dist < nearestEnemyDist)
nearestEnemyDist = dist;
}

if (nearestEnemyDist > 10)
{
var mem = MemoryInfo.GetCurrentStatus();
if (mem == null)
{
return;
}

var memPercentInUse = mem.dwMemoryLoad;
Logger.LogDebug($"Total memory used: {mem.dwMemoryLoad}%");
if (memPercentInUse > PluginConfigSettings.Instance.AdvancedSettings.SETTING_SITGCMemoryThreshold)
GarbageCollect();

}
}

}
}
Loading