Skip to content

Commit

Permalink
Add RestoreMaxPhysicsDT (#95)
Browse files Browse the repository at this point in the history
When using physics warp, Unity will set the max physics dt to be at least as high as the scaled physics dt.  But KSP will never restore it back to the normal value from the settings.  This can degrade performance as it allows more FixedUpdates to run per frame.

reported by Wilds on the forum: https://forum.kerbalspaceprogram.com/index.php?/topic/184740-solved-losing-300-performance-after-time-warping/
  • Loading branch information
JonnyOThan authored Sep 14, 2022
1 parent 9c5c432 commit 1d523f9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions GameData/KSPCommunityFixes/Settings.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,10 @@ KSP_COMMUNITY_FIXES
// speed up reading) at the cost of human readability.
SkipIndentsOnSavesAndCraftFiles = false

// After using physics warp, Unity's max physics dt will never be returned to the value specified in
// game settings which can degrade performance in some cases
RestoreMaxPhysicsDT = true
// ##########################
// Modding
// ##########################
Expand Down
30 changes: 30 additions & 0 deletions KSPCommunityFixes/BugFixes/RestoreMaxPhysicsDT.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace KSPCommunityFixes.BugFixes
{
public class RestoreMaxPhysicsDT : BasePatch
{
protected override void ApplyPatches(List<PatchInfo> patches)
{
patches.Add(new PatchInfo(
PatchMethodType.Prefix,
AccessTools.Method(typeof(TimeWarp), "updateRate"),
this));
}

static void TimeWarp_updateRate_Prefix()
{
// when you use physics warp, it increases Time.fixedDeltaTime
// Unity will internally increase maximumDeltaTime to be at least as high as fixedDeltaTime
// But nothing in the KSP code will ever return maximumDeltaTime to the value from the settings when time warp is over
// Setting it just before TimeWarp sets fixedDeltaTime guarantees that all points of code will have the correct value
Time.maximumDeltaTime = GameSettings.PHYSICS_FRAME_DT_LIMIT;
}
}
}
1 change: 1 addition & 0 deletions KSPCommunityFixes/KSPCommunityFixes.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
<Compile Include="Modding\ModUpgradePipeline.cs" />
<Compile Include="Performance\AsteroidAndCometDrillCache.cs" />
<Compile Include="BugFixes\DoubleCurvePreserveTangents.cs" />
<Compile Include="BugFixes\RestoreMaxPhysicsDT.cs" />
<Compile Include="Performance\CommNetThrottling.cs" />
<Compile Include="Performance\DisableMapUpdateInFlight.cs" />
<Compile Include="Performance\MemoryLeaks.cs" />
Expand Down

0 comments on commit 1d523f9

Please sign in to comment.