/
MechJebModulePVGGlueBall.cs
265 lines (209 loc) · 9.28 KB
/
MechJebModulePVGGlueBall.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
* Copyright Lamont Granquist (lamont@scriptkiddie.org)
* Dual licensed under the MIT (MIT-LICENSE) license
* and GPLv2 (GPLv2-LICENSE) license or any later version.
*/
using System;
using System.Threading.Tasks;
using MechJebLib.Core;
using MechJebLib.PVG;
using MechJebLib.Simulations;
using UnityEngine;
using static MechJebLib.Utils.Statics;
#nullable enable
namespace MuMech
{
/// <summary>
/// This class isolates a bunch of glue between MJ and the PVG optimizer that I don't
/// yet understand how to write correctly.
/// </summary>
public class MechJebModulePVGGlueBall : ComputerModule
{
private double _blockOptimizerUntilTime;
public int SuccessfulConverges;
public int LastLmStatus;
public int MaxLmIterations;
public int LastLmIterations;
public Exception? Exception;
public double Staleness;
public double LastZnorm;
private double _lastTime;
public MechJebModulePVGGlueBall(MechJebCore core) : base(core) { }
private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings;
private Task? _task;
private Ascent? _ascent;
protected override void OnModuleEnabled()
{
SuccessfulConverges = LastLmStatus = MaxLmIterations = 0;
LastLmStatus = LastLmIterations = 0;
Staleness = LastZnorm = _lastTime = 0;
}
protected override void OnModuleDisabled()
{
}
public override void OnFixedUpdate()
{
Core.StageStats.RequestUpdate(this);
}
public override void OnStart(PartModule.StartState state)
{
GameEvents.onStageActivate.Add(HandleStageEvent);
}
public override void OnDestroy()
{
GameEvents.onStageActivate.Remove(HandleStageEvent);
}
private void HandleStageEvent(int data)
{
_blockOptimizerUntilTime = VesselState.time + _ascentSettings.OptimizerPauseTime;
}
private bool IsUnguided(int s)
{
return _ascentSettings.UnguidedStages.Contains(s);
}
// FIXME: maybe this could be a callback to the Task?
private void HandleDoneTask()
{
if (!(_task is { IsCompleted: true }) || _ascent == null)
return;
Optimizer? pvg = _ascent.GetOptimizer();
if (pvg != null)
{
if (pvg.Success())
{
Core.Guidance.SetSolution(pvg.GetSolution());
SuccessfulConverges += 1;
_lastTime = VesselState.time;
Staleness = 0;
}
else
{
Debug.Log("failed guidance, znorm: " + pvg.Znorm);
}
LastLmStatus = pvg.LmStatus;
LastLmIterations = pvg.LmIterations;
LastZnorm = pvg.Znorm;
if (LastLmIterations > MaxLmIterations)
MaxLmIterations = LastLmIterations;
}
_task = null;
}
private void GatherException()
{
if (!(_task is { IsCompleted: true }))
return;
Exception = _task.Exception?.InnerException;
Debug.Log(Exception);
}
public void SetTarget(double peR, double apR, double attR, double inclination, double lan, double fpa, bool attachAltFlag, bool lanflag)
{
// initialize the first time we hit SetTarget to avoid initial large staleness values
if (_lastTime == 0)
_lastTime = VesselState.time;
Staleness = VesselState.time - _lastTime;
GatherException();
HandleDoneTask();
if (_task is { IsCompleted: false })
{
Debug.Log("active PVG task not completed");
return;
}
if (_ascentSettings.OptimizeStageFlag)
{
// clamp the AttR between peR and apR but not if we're using AttR for a fixed time rocket
if (attR < peR)
attR = peR;
if (attR > apR && apR > peR)
attR = apR;
}
if (Vessel.VesselOffGround())
{
bool hasGuided = false;
for (int mjPhase = Core.StageStats.vacStats.Count - 1; mjPhase >= _ascentSettings.LastStage; mjPhase--)
{
double dv = Core.StageStats.vacStats[mjPhase].DeltaV;
int kspStage = Core.StageStats.vacStats[mjPhase].KSPStage;
// skip the zero length stages
if (dv == 0)
continue;
if (!IsUnguided(kspStage))
hasGuided = true;
}
// if we have only inertially guided stages we can't run the optimizer
if (!hasGuided)
return;
}
// check for readiness (not terminal guidance and not finished)
if (!Core.Guidance.IsReady())
return;
if (Core.Guidance.Solution != null)
{
int solutionIndex = Core.Guidance.Solution.IndexForKSPStage(Vessel.currentStage, Core.Guidance.IsCoasting());
if (solutionIndex >= 0)
{
// check for prestaging as the current stage gets low
if (Core.Guidance.Solution?.Tgo(VesselState.time, solutionIndex) < _ascentSettings.PreStageTime)
{
_blockOptimizerUntilTime = VesselState.time + _ascentSettings.OptimizerPauseTime;
return;
}
}
}
if (_blockOptimizerUntilTime > VesselState.time)
return;
Ascent.AscentBuilder ascentBuilder = Ascent.Builder()
.Initial(VesselState.orbitalPosition.WorldToV3Rotated(), VesselState.orbitalVelocity.WorldToV3Rotated(),
VesselState.forward.WorldToV3Rotated(),
VesselState.time, MainBody.gravParameter, MainBody.Radius)
.SetTarget(peR, apR, attR, Deg2Rad(inclination), Deg2Rad(lan), fpa, attachAltFlag, lanflag)
.TerminalConditions(Maths.HmagFromApsides(MainBody.gravParameter, peR, apR));
if (Core.Guidance.Solution != null)
ascentBuilder.OldSolution(Core.Guidance.Solution);
bool optimizedStageFound = false;
for (int mjPhase = Core.StageStats.vacStats.Count - 1; mjPhase >= _ascentSettings.LastStage; mjPhase--)
{
FuelStats fuelStats = Core.StageStats.vacStats[mjPhase];
int kspStage = Core.StageStats.vacStats[mjPhase].KSPStage;
if (!Core.Guidance.HasGoodSolutionWithNoFutureCoast())
{
if ((kspStage == _ascentSettings.CoastStage && _ascentSettings.CoastBeforeFlag) ||
(kspStage == _ascentSettings.CoastStage - 1 && !_ascentSettings.CoastBeforeFlag))
{
double ct = _ascentSettings.FixedCoastLength;
double maxt = _ascentSettings.MaxCoast;
double mint = _ascentSettings.MinCoast;
if (kspStage == Vessel.currentStage && Core.Guidance.IsCoasting())
{
ct = Math.Max(ct - (VesselState.time - Core.Guidance.StartCoast), 0);
maxt = Math.Max(maxt - (VesselState.time - Core.Guidance.StartCoast), 0);
mint = Math.Max(mint - (VesselState.time - Core.Guidance.StartCoast), 0);
}
if (_ascentSettings.FixedCoast)
{
ascentBuilder.AddFixedCoast(fuelStats.StartMass * 1000, ct, _ascentSettings.CoastStage, mjPhase);
}
else
{
ascentBuilder.AddOptimizedCoast(fuelStats.StartMass * 1000, mint, maxt, _ascentSettings.CoastStage, mjPhase);
}
}
}
// skip sep motors. we already avoid running if the bottom stage has burned below this margin.
if (fuelStats.DeltaV < _ascentSettings.MinDeltaV)
continue;
bool optimizeTime = _ascentSettings.OptimizeStage == kspStage;
if (optimizeTime)
optimizedStageFound = true;
bool unguided = IsUnguided(kspStage);
ascentBuilder.AddStageUsingFinalMass(fuelStats.StartMass * 1000, fuelStats.EndMass * 1000, fuelStats.Isp, fuelStats.DeltaTime,
kspStage, mjPhase,
optimizeTime, unguided);
}
ascentBuilder.FixedBurnTime(!optimizedStageFound); // FIXME: can ascentbuilder just figure this out?
_ascent = ascentBuilder.Build();
_task = new Task(_ascent.Run);
_task.Start();
_blockOptimizerUntilTime = VesselState.time + 1;
}
}
}