Skip to content

Commit

Permalink
Update to C# 9.0, add partial suicide burn overhaul
Browse files Browse the repository at this point in the history
This is kinda weird, its got a half-finished fully numerical suicide
burn overhaul I did which needs to be finished, also bumps the version
to C# 9 and fixes a problem with the FlightRecorder using the 'record'
newly reserved word, along with some support for BackgroundJob in the
MechJebUtils class.

What I really want is that support for BackgroundJobs to use with the
delta-V overhaul, and all this work is drifting and merge conflicting as
I rename things, so I'm going to merge the suicide burn timer a bit
half-done.  The module isn't wired up anywhere so shouldn't run.

Signed-off-by: Lamont Granquist <lamont@scriptkiddie.org>
  • Loading branch information
lamont-granquist committed Jul 1, 2023
1 parent f6905a3 commit c206ba6
Show file tree
Hide file tree
Showing 10 changed files with 220 additions and 18 deletions.
7 changes: 5 additions & 2 deletions MechJeb2/MechJeb2.csproj
Expand Up @@ -15,6 +15,7 @@
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<LangVersion>9</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand All @@ -26,7 +27,6 @@
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>None</DebugType>
Expand All @@ -37,7 +37,6 @@
<WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
<CodeAnalysisRuleSet>MechJeb2.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
Expand Down Expand Up @@ -153,6 +152,9 @@
<Compile Include="MechJebLib\PVG\Terminal\Kepler3Reduced.cs" />
<Compile Include="MechJebLib\PVG\Terminal\Kepler4Reduced.cs" />
<Compile Include="MechJebLib\PVG\Terminal\Kepler5Reduced.cs" />
<Compile Include="MechJebLib\Suicide.cs" />
<Compile Include="MechJebLib\SuicideBuilder.cs" />
<Compile Include="MechJebLib\Utils\BackgroundJob.cs" />
<Compile Include="MechJebLib\Utils\Check.cs" />
<Compile Include="MechJebLib\Utils\Logger.cs" />
<Compile Include="MechJebLib\Utils\ObjectPool.cs" />
Expand Down Expand Up @@ -204,6 +206,7 @@
<Compile Include="MechJebModuleSpinupController.cs" />
<Compile Include="MechJebModuleStageStats.cs" />
<Compile Include="MechJebModuleStagingController.cs" />
<Compile Include="MechJebModuleSuicideTimer.cs" />
<Compile Include="MechJebModuleTargetController.cs" />
<Compile Include="MechJebModuleThrustController.cs" />
<Compile Include="MechJebModuleThrustWindow.cs" />
Expand Down
24 changes: 24 additions & 0 deletions MechJeb2/MechJebLib/Suicide.cs
@@ -0,0 +1,24 @@
using MechJebLib.Primitives;
using MechJebLib.Utils;

namespace MuMech.MechJebLib
{
public partial class Suicide : BackgroundJob<Suicide.SuicideResult>
{
public struct SuicideResult
{
public V3 Rf;
public double Tf;
}

public static SuicideBuilder Builder()
{
return new SuicideBuilder();
}

protected override SuicideResult Execute()
{
throw new System.NotImplementedException();
}
}
}
38 changes: 38 additions & 0 deletions MechJeb2/MechJebLib/SuicideBuilder.cs
@@ -0,0 +1,38 @@
using System.Collections.Generic;
using MechJebLib.Primitives;
using MechJebLib.PVG;

namespace MuMech.MechJebLib
{
public partial class Suicide
{
public class SuicideBuilder
{
private readonly List<Phase> _phases = new List<Phase>();

public Suicide Build()
{
var suicide = new Suicide();

return suicide;
}

public SuicideBuilder Initial(V3 r0, V3 v0, V3 u0, double t0, double mu, double rbody)
{
return this;
}

public SuicideBuilder AddStageUsingFinalMass(double m0, double mf, double isp, double bt, int kspStage)
{
_phases.Add(Phase.NewStageUsingFinalMass(m0, mf, isp, bt, kspStage));

return this;
}

public SuicideBuilder SetGround(double height)
{
return this;
}
}
}
}
52 changes: 52 additions & 0 deletions MechJeb2/MechJebLib/Utils/BackgroundJob.cs
@@ -0,0 +1,52 @@
using System;
using System.Threading.Tasks;

#nullable enable

namespace MechJebLib.Utils
{
// TODO:
// - cancellation
// - timeout
public abstract class BackgroundJob<T>
{
private Task<T>? _task;
public T Result = default!;

protected abstract T Execute();

public void Cancel()
{
throw new NotImplementedException();
}

public bool IsRunning()
{
return _task is not { IsCompleted: true };
}

protected virtual void OnTaskCompleted(Task<T> task)
{
Result = task.Result;
_task = null;
}

protected virtual void OnTaskFaulted(Task<T> task)
{
_task = null;
}

protected virtual void OnTaskCancelled(Task<T> task)
{
_task = null;
}

public void Run()
{
_task = Task.Run(Execute);
_task.ContinueWith(OnTaskCompleted, TaskContinuationOptions.OnlyOnRanToCompletion);
_task.ContinueWith(OnTaskFaulted, TaskContinuationOptions.OnlyOnFaulted);
_task.ContinueWith(OnTaskCancelled, TaskContinuationOptions.OnlyOnCanceled);
}
}
}
2 changes: 1 addition & 1 deletion MechJeb2/MechJebModuleAscentClassicPathMenu.cs
Expand Up @@ -198,7 +198,7 @@ private void DrawnTrajectory(Rect r, MechJebModuleFlightRecorder recorder)

while (t <= recorder.historyIdx && t < recorder.history.Length)
{
MechJebModuleFlightRecorder.record rec = recorder.history[t];
MechJebModuleFlightRecorder.RecordStruct rec = recorder.history[t];
p2.x = r.xMin + (float)(rec.downRange / scale);
p2.y = r.yMax - (float)(rec.altitudeASL / scale);

Expand Down
10 changes: 5 additions & 5 deletions MechJeb2/MechJebModuleFlightRecorder.cs
Expand Up @@ -10,7 +10,7 @@ namespace MuMech
public class MechJebModuleFlightRecorder : ComputerModule
{
// TODO : this is already nearly an array so use a list and allow to add any generic ValueInfoItem
public struct record
public struct RecordStruct
{
public double timeSinceMark;
public int currentStage;
Expand Down Expand Up @@ -102,7 +102,7 @@ public enum recordType
DeltaVExpended
}

public record[] history = new record[1];
public RecordStruct[] history = new RecordStruct[1];

public int historyIdx = -1;

Expand Down Expand Up @@ -237,7 +237,7 @@ public MechJebModuleFlightRecorder(MechJebCore core)
public override void OnStart(PartModule.StartState state)
{
if (history.Length != historySize)
history = new record[historySize];
history = new RecordStruct[historySize];
Users.Add(this); //flight recorder should always run.
}

Expand Down Expand Up @@ -347,8 +347,8 @@ public void DumpCSV()

for (int idx = 0; idx <= historyIdx; idx++)
{
record r = history[idx];
writer.Write(r[0]);
RecordStruct r = history[idx];
writer.Write(r[(recordType)0]);
for (int i = 1; i < typeCount; i++)
{
writer.Write(',');
Expand Down
4 changes: 2 additions & 2 deletions MechJeb2/MechJebModuleFlightRecorderGraph.cs
Expand Up @@ -622,7 +622,7 @@ private void DrawnPath(Rect r, MechJebModuleFlightRecorder.recordType type, floa

while (t <= recorder.historyIdx && t < recorder.history.Length)
{
MechJebModuleFlightRecorder.record rec = recorder.history[t];
MechJebModuleFlightRecorder.RecordStruct rec = recorder.history[t];
p2.x = xBase + (float)((downRange ? rec.downRange : rec.timeSinceMark) * invScaleX);
p2.y = yBase - (float)(rec[type] * invScaleY);

Expand Down Expand Up @@ -651,7 +651,7 @@ private void DrawnStages(Rect r, double scaleX, bool downRange)
int t = 1;
while (t <= recorder.historyIdx && t < recorder.history.Length)
{
MechJebModuleFlightRecorder.record rec = recorder.history[t];
MechJebModuleFlightRecorder.RecordStruct rec = recorder.history[t];
if (rec.currentStage != lastStage)
{
lastStage = rec.currentStage;
Expand Down
8 changes: 1 addition & 7 deletions MechJeb2/MechJebModulePVGGlueBall.cs
Expand Up @@ -72,12 +72,6 @@ private void HandleStageEvent(int data)
_blockOptimizerUntilTime = VesselState.time + _ascentSettings.OptimizerPauseTime;
}

private bool VesselOffGround()
{
return Vessel.situation != Vessel.Situations.LANDED && Vessel.situation != Vessel.Situations.PRELAUNCH &&
Vessel.situation != Vessel.Situations.SPLASHED;
}

private bool IsUnguided(int s)
{
return _ascentSettings.UnguidedStages.Contains(s);
Expand Down Expand Up @@ -153,7 +147,7 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d
attR = apR;
}

if (VesselOffGround())
if (Vessel.VesselOffGround())
{
bool hasGuided = false;

Expand Down
85 changes: 85 additions & 0 deletions MechJeb2/MechJebModuleSuicideTimer.cs
@@ -0,0 +1,85 @@
#nullable enable

using System.Threading.Tasks;
using JetBrains.Annotations;
using MechJebLib.Primitives;
using MuMech.MechJebLib;

namespace MuMech
{
[UsedImplicitly]
public class MechJebModuleSuicideTimer : ComputerModule
{
private Suicide? _suicide;
private Suicide.SuicideResult _lastResult;
public Vector3d Rf => _lastResult.Rf.V3ToWorldRotated();

public MechJebModuleSuicideTimer(MechJebCore core) : base(core)
{
}

protected override void OnModuleEnabled()
{
Reset();
}

protected override void OnModuleDisabled()
{
Reset();
}

private void Reset()
{
_lastResult.Rf = V3.zero;
_lastResult.Tf = VesselState.time;
_suicide?.Cancel();
_suicide = null;
}


private double GetGroundHeight()
{
if (Rf == Vector3d.zero)
return MainBody.Radius;

Vector3d latlng = MainBody.GetLatitudeAndLongitude(Rf, true);
return MainBody.TerrainAltitude(latlng[0], latlng[1]);
}

public override void OnFixedUpdate()
{
if (!Vessel.VesselOffGround())
return;

// make sure our orbit at least dips into the atmosphere, or bodyRadius plus some maximum height of mountains

Core.StageStats.RequestUpdate(this);

if (Core.StageStats.vacStats.Length <= 0)
return;

if (_suicide != null)
{
if (_suicide.IsRunning())
return;

_lastResult = _suicide.Result;
}

Suicide.SuicideBuilder suicideBuilder = Suicide.Builder()
.Initial(VesselState.orbitalPosition.WorldToV3Rotated(), VesselState.orbitalVelocity.WorldToV3Rotated(),
VesselState.forward.WorldToV3Rotated(), VesselState.time, MainBody.gravParameter, MainBody.Radius)
.SetGround(GetGroundHeight());

for (int i = Core.StageStats.vacStats.Length - 1; i >= 0; i--)
{
FuelFlowSimulation.FuelStats fuelStats = Core.StageStats.vacStats[i];

suicideBuilder.AddStageUsingFinalMass(fuelStats.StartMass * 1000, fuelStats.EndMass * 1000, fuelStats.Isp, fuelStats.DeltaTime, i);
}

_suicide = suicideBuilder.Build();
_suicide.Run();
}
}
}
8 changes: 7 additions & 1 deletion MechJeb2/VesselExtensions.cs
Expand Up @@ -9,6 +9,12 @@ namespace MuMech
{
public static class VesselExtensions
{
public static bool VesselOffGround(this Vessel vessel)
{
return vessel.situation is Vessel.Situations.FLYING or Vessel.Situations.ESCAPING
or Vessel.Situations.ORBITING or Vessel.Situations.SUB_ORBITAL;
}

public static List<ITargetable> GetTargetables(this Vessel vessel)
{
List<Part> parts;
Expand Down Expand Up @@ -76,7 +82,7 @@ public static List<ITargetable> GetTargetables(this Vessel vessel)
}

private static float lastFixedTime;
private static readonly Dictionary<Guid, MechJebCore> masterMechJeb = new Dictionary<Guid, MechJebCore>();
private static readonly Dictionary<Guid, MechJebCore> masterMechJeb = new();

public static MechJebCore GetMasterMechJeb(this Vessel vessel)
{
Expand Down

0 comments on commit c206ba6

Please sign in to comment.