Skip to content
2 changes: 1 addition & 1 deletion MechJeb2.UI/src/PSGSolutionGraphView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ string StatusText()
if (Plan.Count == 0)
statusText = "No PSG solution yet: engage the PSG ascent";
else
statusText = $"Solution {g.Sampled}: MET {Plan.T0:F0} to {Plan.Tf:F0} s, {Plan.PhaseBoundaries.Count - 1} phases" +
statusText = $"Solution {g.Sampled}: MET {Plan.T0:F0} to {Plan.Tf:F0} s, {Plan.PhaseCount} phases" +
(current ? "" : g.Hold ? " (held, guidance has a newer one)" : " (guidance has none now)");
return statusText;
}
Expand Down
8 changes: 7 additions & 1 deletion MechJeb2/MechJebModuleAscentClassicAutopilot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,13 @@ public override void Drive(FlightCtrlState s)
return;
}

if (Countdown.HoldForLiftoff(Status)) return;
// the countdown stages at T-0: until then the vessel waits on the pad
if (Countdown.Active)
{
Status.Set(Localizer.Format("#MechJeb_Ascent_status6")); //"Awaiting liftoff"
Core.Attitude.SetAxisControl(false, false, false);
return;
}

Core.Solarpanel.DriveForAscent();
Core.AntennaControl.DriveForAscent();
Expand Down
37 changes: 19 additions & 18 deletions MechJeb2/MechJebModuleLaunchCountdown.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System.Collections.Generic;
using KSP.Localization;
using KSP.UI.Screens;
using MechJebLib.Functions;

namespace MuMech
{
/// <summary>
/// The launch sequence the ascent autopilots share: the countdown, warping to it, staging at T-0 and the prelaunch hold.
/// The launch sequence the ascent autopilots share: the countdown, warping to it, the prelaunch, and staging at T-0, which
/// waits while an autopilot isn't ready to fly (SetLaunchHold). The autopilots hold the vessel on the pad until T-0.
/// An engaged autopilot adds itself to Users, so a countdown started while no autopilot is engaged doesn't run until one is.
/// The countdown owns the launch mode (the three Launching* flags of the ascent settings): only Abort ends it, not a window.
/// </summary>
Expand All @@ -30,9 +32,21 @@ private enum LaunchKind { PLANE_OF_TARGET, TARGET_LAN, LAN }
/// <summary>The target's LAN when a launch into its plane or to its LAN started: the LAN that launch flies to.</summary>
public double TargetLan { get; private set; }

// Starting a countdown flushes the PSG solution and the optimizer restarts cold late in the countdown, which can take longer
// than the countdown does. Staging with no solution would release the rocket at zero throttle, so T-0 waits for one.
private bool WaitingForGuidance => AscentSettings.AscentType == AscentType.PSG && Core.PSGAutopilot.Solution == null;
// the users holding T-0, the staging, until they are ready to fly
private readonly HashSet<object> _launchHolds = new HashSet<object>();

/// <summary>
/// Holds T-0, the staging, while user isn't ready to fly: the PSG autopilot until it has a Solution. Starting a
/// countdown flushes the PSG solution and the optimizer restarts cold late in the countdown, which can take longer than
/// the countdown does, and staging with no solution would release the rocket at zero throttle.
/// </summary>
public void SetLaunchHold(object user, bool hold)
{
if (hold)
_launchHolds.Add(user);
else
_launchHolds.Remove(user);
}

// the target inclination, one for both ascent types
public EditableDouble InclinationSetting => AscentSettings.DesiredInclination;
Expand Down Expand Up @@ -123,19 +137,6 @@ public bool DrivePrelaunch(AscentStatus status)
return false;
}

/// <summary>Returns true while the countdown is still running after prelaunch, when the autopilot must not fly yet.</summary>
public bool HoldForLiftoff(AscentStatus status)
{
if (!Active)
return false;

status.Set(TMinus <= 0 && WaitingForGuidance
? "Holding launch for guidance"
: Localizer.Format("#MechJeb_Ascent_status6")); //"Awaiting liftoff"
Core.Attitude.SetAxisControl(false, false, false);
return true;
}

// The countdown only runs while an autopilot is engaged. One started with none engaged and engaged after T-0 counts down
// to the next launch of the same kind, rather than launch at once, off the window it was timed for.
protected override void OnModuleEnabled()
Expand Down Expand Up @@ -167,7 +168,7 @@ public override void OnFixedUpdate()
if (TMinus < 3 * VesselState.DeltaT || (TMinus > 10.0 && _lastTMinus < 1.0))
{
// StageManager stages the active vessel, so T-0 holds while the player is on another one
if (!WaitingForGuidance && Vessel.isActiveVessel)
if (_launchHolds.Count == 0 && Vessel.isActiveVessel)
{
if (VesselState.ThrustAvailable < 10E-4) // only stage if we have no engines active
StageManager.ActivateNextStage();
Expand Down
109 changes: 56 additions & 53 deletions MechJeb2/MechJebModulePSGAutopilot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { }

public bool IsCoasting => _machine.IsCoasting;

public bool IsTerminal => _machine.IsTerminal;

public bool IsFinished => _machine.IsFinished;

/// <summary>Set when the coast starts, and kept after it: the Solution's burns before the coast are behind the vessel.</summary>
Expand All @@ -84,9 +82,6 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { }
// what guidance does with RCS (PSGFeedback), said once at each change
private ScreenMessage _rcsCoastMessage = null!, _rcsTrimMessage = null!, _rcsOffMessage = null!;

// the countdown holds the throttle
private bool _allowThrottle;

// Countdown.DrivePrelaunch is done
private bool _prelaunchDone;

Expand All @@ -95,7 +90,9 @@ public MechJebModulePSGAutopilot(MechJebCore core) : base(core) { }
private Vessel? _partIdsVessel;
private int _partIdsCount = -1;

private string? _awaitingComputing, _awaitingProgress, _awaitingProgressFrom;
// the status while the first solve runs on the pad (AwaitingComputing), and what it was built from
private string? _awaitingStatus, _awaitingFrom;
private bool _awaitingHolding;
private string? _lockStatus, _lockStatusId;

public override void OnStart(PartModule.StartState state)
Expand Down Expand Up @@ -144,6 +141,7 @@ protected override void OnModuleDisabled()
Core.Staging.AutoStageLimitRemove(this);
Core.Spinup.Users.Remove(this);
_countdown.Users.Remove(this);
_countdown.SetLaunchHold(this, false);
_ascentSettings.ReleaseOwnValues(this);

_countdown.Abort();
Expand All @@ -160,7 +158,6 @@ private void ResetGuidance()
{
_machine.ResetGuidance();
PadSolution = null;
_allowThrottle = false;
_prelaunchDone = false;
}

Expand Down Expand Up @@ -200,22 +197,16 @@ private void UpdateFlightPlan()
Core.PSGSimulation.UpdateLogicalPlan();
}

// the optimizer starts late in a countdown (or at once without one), and the throttle waits for the countdown to end
// The optimizer starts late in a countdown (or at once without one), and T-0 waits until the autopilot is ready to fly.
// The vessel itself waits on the pad in PRELAUNCH (AscentInputs.CountdownActive).
private void UpdateCountdownGate()
{
if (_countdown.Active)
{
if (_countdown.TMinus <= Math.Max(_ascentSettings.WarpCountDown, 0))
Core.PSGSimulation.Users.Add(this);
else
Core.PSGSimulation.Users.Remove(this);
_allowThrottle = false;
}
else
{
if (!_countdown.Active || _countdown.TMinus <= Math.Max(_ascentSettings.WarpCountDown, 0))
Core.PSGSimulation.Users.Add(this);
_allowThrottle = true;
}
else
Core.PSGSimulation.Users.Remove(this);

_countdown.SetLaunchHold(this, !_prelaunchDone || Solution == null);
}

/*
Expand Down Expand Up @@ -250,7 +241,7 @@ private AscentInputs GatherInputs()
VacT = Core.StageStats.VacT,
PartIds = _partIds,
PrelaunchDone = _prelaunchDone,
AllowThrottle = _allowThrottle,
CountdownActive = _countdown.Active,
PitchStartHeight = _ascentSettings.PitchStartHeight,
PitchRate = _ascentSettings.PitchRate,
UllageLeadTime = UllageLeadTime,
Expand All @@ -272,16 +263,13 @@ private void UpdatePartIds()
_partIds.Add(part.persistentId);
}

// the transitions' part of the command, then (unless the countdown holds for liftoff) the tick's
// the transitions' part of the command, then the tick's
private void Apply(in AscentCommand cmd)
{
ApplyTransition(cmd);

_ascentSettings.LimitingAoA = false;

if (cmd.CheckLiftoffHold && _countdown.HoldForLiftoff(Status))
return;

if (cmd.DriveAscentParts)
{
Core.Solarpanel.DriveForAscent();
Expand Down Expand Up @@ -363,6 +351,9 @@ private void ApplyAttitude(in AscentCommand cmd)
{
switch (cmd.Attitude)
{
case AscentAttitude.OFF:
Core.Attitude.SetAxisControl(false, false, false);
break;
case AscentAttitude.VERTICAL:
//during the vertical ascent we just thrust straight up at max throttle
Core.Attitude.AttitudeToVerticalLaunch(cmd.Heading,
Expand Down Expand Up @@ -408,14 +399,23 @@ private void UpdateStatus()
{
switch (State)
{
case PSGState.PRELAUNCH:
// the countdown's prelaunch says what it is doing until it is done, and is skipped off the pad
if (!_prelaunchDone || !IsGrounded())
break;

// the first solve can take minutes on a slow machine: say so, or the pad looks stuck (the optimizer only
// starts late in a countdown)
if (Solution == null && Core.PSGSimulation.Enabled)
Status.Set(AwaitingComputing(_countdown.Active && _countdown.TMinus <= 0)); //"Awaiting liftoff: computing the ascent…"
else
Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff"
break;
case PSGState.VERTICAL_ASCENT:
// on the pad from T-0 until the clamps let go
if (!LiftedOff())
{
// the first solve can take minutes on a slow machine: say so, or the pad looks stuck
if (Solution == null)
Status.Set(AwaitingComputing()); //"Awaiting liftoff: computing the ascent…"
else
Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff"
Status.Set(Localizer.Format("#MechJeb_Ascent_status12")); //"Awaiting liftoff"
break;
}

Expand Down Expand Up @@ -481,50 +481,52 @@ private Vector3d ApplyAoALimiter(Vector3d desiredThrustVector)
* Solutions
*/

// guidance flies in SI units and MET seconds, so this takes a DeNormalized() Solution
public void SetSolution(Solution solution)
/// <summary>Whether SetSolution takes a Solution now: in PRELAUNCH, BURNING and COASTING (AscentStateMachine.TakesSolution).</summary>
public bool TakesSolution => _machine.TakesSolution;

// guidance flies in SI units and MET seconds, so this takes a DeNormalized() Solution. False if it was ignored
// (TakesSolution).
public bool SetSolution(Solution solution)
{
if (_machine.SetSolution(solution) && solution.T0 <= 0)
if (!_machine.SetSolution(solution))
return false;

if (solution.FromPad)
PadSolution = solution;
return true;
}

/// <summary>
/// Drops a Solution that no longer applies and goes back to waiting for one. Only for use on the ground, the timed launch
/// buttons and kOS suffixes require a landed vessel. Does nothing while disabled, so a countdown started before engaging
/// leaves the throttle alone.
/// Drops a Solution that no longer applies and goes back to waiting for one, in PRELAUNCH with the throttle off, which
/// runs the countdown's prelaunch again. Only for use on the ground, the timed launch buttons and kOS suffixes require a
/// landed vessel. Does nothing while disabled.
/// </summary>
public void FlushSolution()
{
if (!Enabled)
return;

bool prelaunchDone = _prelaunchDone;
ResetGuidance();
_prelaunchDone = prelaunchDone;

// engaging without a countdown leaves the throttle up on the pad, and once the autopilot has left prelaunch nothing
// else lowers it before T-0
ThrustOff();
}

/*
* Status and drawing
*/

// "Awaiting liftoff: computing the ascent, step 2 of 5 (1m 12s)", rebuilt only when the progress text changes
private string AwaitingComputing()
// "Awaiting liftoff: computing the ascent, step 2 of 5 (1m 12s)", or "Holding launch for guidance: …" once T-0 waits for
// it, rebuilt only when the progress text or the hold changes
private string AwaitingComputing(bool holding)
{
string? progress = Core.PSGSimulation.ProgressShort;
if (progress == null)
return _awaitingComputing ??= Localizer.Format("#MechJeb_Ascent_status12") + ": computing the ascent…"; //"Awaiting liftoff"

if (!ReferenceEquals(progress, _awaitingProgressFrom) || _awaitingProgress == null)
if (_awaitingStatus == null || !ReferenceEquals(progress, _awaitingFrom) || holding != _awaitingHolding)
{
_awaitingProgressFrom = progress;
_awaitingProgress = Localizer.Format("#MechJeb_Ascent_status12") + ": " + progress;
_awaitingFrom = progress;
_awaitingHolding = holding;
_awaitingStatus = (holding ? "Holding launch for guidance" : Localizer.Format("#MechJeb_Ascent_status12")) + //"Awaiting liftoff"
": " + (progress ?? "computing the ascent…");
}

return _awaitingProgress;
return _awaitingStatus;
}

// says why MechJeb can't fly the vessel while another mod has taken its controls; the string is rebuilt only when the lock
Expand Down Expand Up @@ -561,11 +563,12 @@ private void DrawTrajectory()
const int SEGMENTS = 50;

_trajectory.Clear();
double dt = (Solution.Tf - Solution.T0) / SEGMENTS;
// from the ground, with the vertical rise
double dt = (Solution.Tf - Solution.TStart) / SEGMENTS;

for (int i = 0; i <= SEGMENTS; i++)
{
double t = Solution.T0 + dt * i;
double t = Solution.TStart + dt * i;

_trajectory.Add(Solution.R(t).V3ToWorldRotated() + MainBody.position);
}
Expand Down
Loading
Loading