From 00891f801674b4aa34046339c051a8b3d151b1c6 Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Mon, 19 Jun 2023 09:29:28 -0700 Subject: [PATCH] ComputerModule breaking API changes Cleanup the API. Like other PRs similar to this the name changes are intended to be breaking changes, the visibility changes can be reversed and aren't intended to force people to use reflection to call private APIs (please don't) and can be switched back to public. Signed-off-by: Lamont Granquist --- .../BaseAttitudeController.cs | 12 +- .../AttitudeControllers/BetterController.cs | 46 +- .../AttitudeControllers/HybridController.cs | 20 +- .../KosAttitudeController.cs | 16 +- .../MJAttitudeController.cs | 34 +- MechJeb2/ComputerModule.cs | 196 ++++---- MechJeb2/DisplayModule.cs | 58 +-- MechJeb2/GuiUtils.cs | 2 +- .../LandingAutopilot/CoastToDeceleration.cs | 12 +- MechJeb2/LandingAutopilot/CourseCorrection.cs | 2 +- MechJeb2/Maneuver/OperationApoapsis.cs | 2 +- .../Maneuver/OperationCourseCorrection.cs | 6 +- MechJeb2/Maneuver/OperationEccentricity.cs | 2 +- MechJeb2/Maneuver/OperationEllipticize.cs | 4 +- MechJeb2/Maneuver/OperationInclination.cs | 2 +- .../OperationInterplanetaryTransfer.cs | 2 +- MechJeb2/Maneuver/OperationLambert.cs | 2 +- MechJeb2/Maneuver/OperationMoonReturn.cs | 2 +- MechJeb2/Maneuver/OperationPeriapsis.cs | 2 +- MechJeb2/Maneuver/OperationResonantOrbit.cs | 4 +- MechJeb2/Maneuver/OperationSemiMajor.cs | 2 +- MechJeb2/Maneuver/OperationTransfer.cs | 8 +- MechJeb2/Maneuver/TimeSelector.cs | 6 +- MechJeb2/MechJebAR202.cs | 2 +- MechJeb2/MechJebCore.cs | 32 +- MechJeb2/MechJebModuleAirplaneAutopilot.cs | 64 +-- MechJeb2/MechJebModuleAirplaneGuidance.cs | 22 +- MechJeb2/MechJebModuleAscentBaseAutopilot.cs | 154 +++--- .../MechJebModuleAscentClassicAutopilot.cs | 52 +-- .../MechJebModuleAscentClassicPathMenu.cs | 12 +- MechJeb2/MechJebModuleAscentGTAutopilot.cs | 66 +-- MechJeb2/MechJebModuleAscentMenu.cs | 143 +++--- MechJeb2/MechJebModuleAscentPVGAutopilot.cs | 70 +-- .../MechJebModuleAscentPVGSettingsMenu.cs | 14 +- MechJeb2/MechJebModuleAscentSettings.cs | 202 ++++---- MechJeb2/MechJebModuleAscentSettingsMenu.cs | 30 +- MechJeb2/MechJebModuleAttitudeAdjustment.cs | 28 +- MechJeb2/MechJebModuleAttitudeController.cs | 126 ++--- MechJeb2/MechJebModuleCustomInfoWindow.cs | 100 ++-- MechJeb2/MechJebModuleDebugArrows.cs | 80 ++-- MechJeb2/MechJebModuleDeployableController.cs | 28 +- MechJeb2/MechJebModuleDockingAutopilot.cs | 80 ++-- MechJeb2/MechJebModuleDockingGuidance.cs | 40 +- MechJeb2/MechJebModuleFlightRecorder.cs | 112 ++--- MechJeb2/MechJebModuleFlightRecorderGraph.cs | 32 +- MechJeb2/MechJebModuleGuidanceController.cs | 128 ++--- MechJeb2/MechJebModuleInfoItems.cs | 440 +++++++++--------- MechJeb2/MechJebModuleLandingAutopilot.cs | 162 +++---- MechJeb2/MechJebModuleLandingGuidance.cs | 124 ++--- MechJeb2/MechJebModuleLandingPredictions.cs | 52 +-- MechJeb2/MechJebModuleManeuverPlanner.cs | 66 +-- MechJeb2/MechJebModuleMenu.cs | 68 +-- MechJeb2/MechJebModuleNodeEditor.cs | 70 +-- MechJeb2/MechJebModuleNodeExecutor.cs | 146 +++--- MechJeb2/MechJebModulePVGGlueBall.cs | 66 +-- MechJeb2/MechJebModuleRCSBalancer.cs | 30 +- MechJeb2/MechJebModuleRCSBalancerWindow.cs | 12 +- MechJeb2/MechJebModuleRCSController.cs | 48 +- MechJeb2/MechJebModuleRendezvousAutopilot.cs | 166 +++---- .../MechJebModuleRendezvousAutopilotWindow.cs | 26 +- MechJeb2/MechJebModuleRendezvousGuidance.cs | 114 ++--- MechJeb2/MechJebModuleRoverController.cs | 138 +++--- MechJeb2/MechJebModuleRoverWindow.cs | 38 +- MechJeb2/MechJebModuleSettings.cs | 30 +- MechJeb2/MechJebModuleSmartASS.cs | 68 +-- MechJeb2/MechJebModuleSmartRcs.cs | 24 +- MechJeb2/MechJebModuleSpaceplaneAutopilot.cs | 110 ++--- MechJeb2/MechJebModuleSpaceplaneGuidance.cs | 20 +- MechJeb2/MechJebModuleSpinupController.cs | 36 +- MechJeb2/MechJebModuleStageStats.cs | 26 +- MechJeb2/MechJebModuleStagingController.cs | 122 ++--- MechJeb2/MechJebModuleTargetController.cs | 58 +-- MechJeb2/MechJebModuleThrustController.cs | 194 ++++---- MechJeb2/MechJebModuleThrustWindow.cs | 68 +-- MechJeb2/MechJebModuleTranslatron.cs | 72 +-- MechJeb2/MechJebModuleWarpController.cs | 50 +- MechJeb2/MechJebModuleWarpHelper.cs | 56 +-- MechJeb2/MechJebModuleWaypointWindow.cs | 112 ++--- MechJeb2/MechJebStageStatsHelper.cs | 6 +- MechJeb2/VesselState.cs | 4 +- 80 files changed, 2438 insertions(+), 2443 deletions(-) diff --git a/MechJeb2/AttitudeControllers/BaseAttitudeController.cs b/MechJeb2/AttitudeControllers/BaseAttitudeController.cs index 0a573388b..68a8000f8 100644 --- a/MechJeb2/AttitudeControllers/BaseAttitudeController.cs +++ b/MechJeb2/AttitudeControllers/BaseAttitudeController.cs @@ -24,16 +24,16 @@ public virtual void OnStart() public virtual void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global) { if (global != null && global.HasNode(GetType().Name)) - ConfigNode.LoadObjectFromConfig(this, global.GetNode(GetType().Name), (int)Pass.Global); - if (type != null && type.HasNode(GetType().Name)) ConfigNode.LoadObjectFromConfig(this, type.GetNode(GetType().Name), (int)Pass.Type); - if (local != null && local.HasNode(GetType().Name)) ConfigNode.LoadObjectFromConfig(this, local.GetNode(GetType().Name), (int)Pass.Local); + ConfigNode.LoadObjectFromConfig(this, global.GetNode(GetType().Name), (int)Pass.GLOBAL); + if (type != null && type.HasNode(GetType().Name)) ConfigNode.LoadObjectFromConfig(this, type.GetNode(GetType().Name), (int)Pass.TYPE); + if (local != null && local.HasNode(GetType().Name)) ConfigNode.LoadObjectFromConfig(this, local.GetNode(GetType().Name), (int)Pass.LOCAL); } public virtual void OnSave(ConfigNode local, ConfigNode type, ConfigNode global) { - if (global != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.Global, null).CopyTo(global.AddNode(GetType().Name)); - if (type != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.Type, null).CopyTo(type.AddNode(GetType().Name)); - if (local != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.Local, null).CopyTo(local.AddNode(GetType().Name)); + if (global != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.GLOBAL, null).CopyTo(global.AddNode(GetType().Name)); + if (type != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.TYPE, null).CopyTo(type.AddNode(GetType().Name)); + if (local != null) ConfigNode.CreateConfigFromObject(this, (int)Pass.LOCAL, null).CopyTo(local.AddNode(GetType().Name)); } public virtual void ResetConfig() diff --git a/MechJeb2/AttitudeControllers/BetterController.cs b/MechJeb2/AttitudeControllers/BetterController.cs index 13647f789..2cc9a06fc 100644 --- a/MechJeb2/AttitudeControllers/BetterController.cs +++ b/MechJeb2/AttitudeControllers/BetterController.cs @@ -8,67 +8,67 @@ namespace MuMech.AttitudeControllers internal class BetterController : BaseAttitudeController { private static readonly Vector3d _vector3dnan = new Vector3d(double.NaN, double.NaN, double.NaN); - private Vessel Vessel => ac.vessel; + private Vessel Vessel => ac.Vessel; /* FIXME: when you do that look at ModuleGimbal gimbalResponseSpeed and model the time delay and use the XLR11 since it has slow gimbal */ - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble PosKp = new EditableDouble(1.98); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble PosDeadband = new EditableDouble(0.002); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelKp = new EditableDouble(10); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelKi = new EditableDouble(20); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelKd = new EditableDouble(0.425); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelN = new EditableDouble(84.1994541201249); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelB = new EditableDouble(0.994); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelC = new EditableDouble(0.0185); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelDeadband = new EditableDouble(0.0001); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private bool VelClegg; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelSmoothIn = new EditableDouble(1); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble VelSmoothOut = new EditableDouble(1); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble PosSmoothIn = new EditableDouble(1); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble maxStoppingTime = new EditableDouble(2.0); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble minFlipTime = new EditableDouble(120); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble rollControlRange = new EditableDouble(5); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private bool useControlRange = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private bool useFlipTime = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private bool useStoppingTime = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private int _version = -1; private void Defaults() @@ -188,7 +188,7 @@ private void UpdatePredictionPI() Vector3d controlTorque = ac.torque; // needed to stop wiggling at higher phys warp - double warpFactor = ac.vesselState.deltaT / 0.02; + double warpFactor = ac.VesselState.deltaT / 0.02; // see https://archive.is/NqoUm and the "Alt Hold Controller", the acceleration PID is not implemented so we only // have the first two PIDs in the cascade. @@ -243,7 +243,7 @@ private void UpdatePredictionPI() _pid[i].N = VelN; _pid[i].B = VelB; _pid[i].C = VelC; - _pid[i].Ts = ac.vesselState.deltaT; + _pid[i].Ts = ac.VesselState.deltaT; _pid[i].SmoothIn = MuUtils.Clamp01(VelSmoothIn); _pid[i].SmoothOut = MuUtils.Clamp01(VelSmoothOut); _pid[i].MinOutput = -1; diff --git a/MechJeb2/AttitudeControllers/HybridController.cs b/MechJeb2/AttitudeControllers/HybridController.cs index 326825229..47c228c8f 100644 --- a/MechJeb2/AttitudeControllers/HybridController.cs +++ b/MechJeb2/AttitudeControllers/HybridController.cs @@ -6,13 +6,13 @@ namespace MuMech.AttitudeControllers { internal class HybridController : BaseAttitudeController { - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private readonly EditableDouble maxStoppingTime = new EditableDouble(2); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private readonly EditableDoubleMult rollControlRange = new EditableDoubleMult(5 * Mathf.Deg2Rad, Mathf.Deg2Rad); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private bool useControlRange = true; public TorquePI pitchPI = new TorquePI(); @@ -23,7 +23,7 @@ internal class HybridController : BaseAttitudeController public KosPIDLoop yawRatePI = new KosPIDLoop(1, 0.1, 0, extraUnwind: true); public KosPIDLoop rollRatePI = new KosPIDLoop(1, 0.1, 0, extraUnwind: true); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool useInertia = true; private Vector3d Actuation = Vector3d.zero; @@ -59,7 +59,7 @@ public override void DrivePre(FlightCtrlState s, out Vector3d act, out Vector3d public void UpdatePhi() { - Transform vesselTransform = ac.vessel.ReferenceTransform; + Transform vesselTransform = ac.Vessel.ReferenceTransform; // 1. The Euler(-90) here is because the unity transform puts "up" as the pointy end, which is wrong. The rotation means that // "forward" becomes the pointy end, and "up" and "right" correctly define e.g. AoA/pitch and AoS/yaw. This is just KSP being KSP. @@ -97,13 +97,13 @@ public void UpdatePhi() private void UpdatePredictionPI() { - Omega = -ac.vessel.angularVelocity; + Omega = -ac.Vessel.angularVelocity; UpdatePhi(); for (int i = 0; i < 3; i++) { - MaxOmega[i] = ControlTorque[i] * maxStoppingTime / ac.vesselState.MoI[i]; + MaxOmega[i] = ControlTorque[i] * maxStoppingTime / ac.VesselState.MoI[i]; } TargetOmega[0] = pitchRatePI.Update(phiVector[0], 0, MaxOmega[0]); @@ -116,9 +116,9 @@ private void UpdatePredictionPI() rollRatePI.ResetI(); } - TargetTorque[0] = pitchPI.Update(Omega[0], TargetOmega[0], ac.vesselState.MoI[0], ControlTorque[0]); - TargetTorque[1] = rollPI.Update(Omega[1], TargetOmega[1], ac.vesselState.MoI[1], ControlTorque[1]); - TargetTorque[2] = yawPI.Update(Omega[2], TargetOmega[2], ac.vesselState.MoI[2], ControlTorque[2]); + TargetTorque[0] = pitchPI.Update(Omega[0], TargetOmega[0], ac.VesselState.MoI[0], ControlTorque[0]); + TargetTorque[1] = rollPI.Update(Omega[1], TargetOmega[1], ac.VesselState.MoI[1], ControlTorque[1]); + TargetTorque[2] = yawPI.Update(Omega[2], TargetOmega[2], ac.VesselState.MoI[2], ControlTorque[2]); } public override void Reset() diff --git a/MechJeb2/AttitudeControllers/KosAttitudeController.cs b/MechJeb2/AttitudeControllers/KosAttitudeController.cs index 62703ad2e..3d7ece2c6 100644 --- a/MechJeb2/AttitudeControllers/KosAttitudeController.cs +++ b/MechJeb2/AttitudeControllers/KosAttitudeController.cs @@ -5,10 +5,10 @@ namespace MuMech.AttitudeControllers { internal class KosAttitudeController : BaseAttitudeController { - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private readonly EditableDouble maxStoppingTime = new EditableDouble(2); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private readonly EditableDoubleMult rollControlRange = new EditableDoubleMult(5 * Mathf.Deg2Rad, Mathf.Deg2Rad); //public double RollControlRange { // get { return this.rollControlRange; } @@ -67,7 +67,7 @@ public override void DrivePre(FlightCtrlState s, out Vector3d act, out Vector3d private void UpdateStateVectors() { /* FIXME: may get called more than once per tick */ - vesselRotation = ac.vessel.ReferenceTransform.rotation * Quaternion.Euler(-90, 0, 0); + vesselRotation = ac.Vessel.ReferenceTransform.rotation * Quaternion.Euler(-90, 0, 0); vesselForward = vesselRotation * Vector3d.forward; vesselTop = vesselRotation * Vector3d.up; vesselStarboard = vesselRotation * Vector3d.right; @@ -76,7 +76,7 @@ private void UpdateStateVectors() targetTop = ac.RequestedAttitude * Vector3d.up; /* targetStarboard = target * Vector3d.right; */ - Omega = -ac.vessel.angularVelocity; + Omega = -ac.Vessel.angularVelocity; } public double PhiTotal() @@ -115,7 +115,7 @@ private void UpdatePredictionPI() for (int i = 0; i < 3; i++) { - MaxOmega[i] = ControlTorque[i] * maxStoppingTime / ac.vesselState.MoI[i]; + MaxOmega[i] = ControlTorque[i] * maxStoppingTime / ac.VesselState.MoI[i]; } TargetOmega[0] = pitchRatePI.Update(-phiVector[0], 0, MaxOmega[0]); @@ -128,9 +128,9 @@ private void UpdatePredictionPI() rollRatePI.ResetI(); } - TargetTorque[0] = pitchPI.Update(Omega[0], TargetOmega[0], ac.vesselState.MoI[0], ControlTorque[0]); - TargetTorque[1] = rollPI.Update(Omega[1], TargetOmega[1], ac.vesselState.MoI[1], ControlTorque[1]); - TargetTorque[2] = yawPI.Update(Omega[2], TargetOmega[2], ac.vesselState.MoI[2], ControlTorque[2]); + TargetTorque[0] = pitchPI.Update(Omega[0], TargetOmega[0], ac.VesselState.MoI[0], ControlTorque[0]); + TargetTorque[1] = rollPI.Update(Omega[1], TargetOmega[1], ac.VesselState.MoI[1], ControlTorque[1]); + TargetTorque[2] = yawPI.Update(Omega[2], TargetOmega[2], ac.VesselState.MoI[2], ControlTorque[2]); } public override void Reset() diff --git a/MechJeb2/AttitudeControllers/MJAttitudeController.cs b/MechJeb2/AttitudeControllers/MJAttitudeController.cs index 8eb795153..d4ce61c33 100644 --- a/MechJeb2/AttitudeControllers/MJAttitudeController.cs +++ b/MechJeb2/AttitudeControllers/MJAttitudeController.cs @@ -12,37 +12,37 @@ internal class MJAttitudeController : BaseAttitudeController public Vector3d pidAction; //info public Vector3d error; //info - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool Tf_autoTune = true; public Vector3d TfV = new Vector3d(0.3, 0.3, 0.3); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private Vector3 TfVec = new Vector3(0.3f, 0.3f, 0.3f); // use the serialize since Vector3d does not - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double TfMin = 0.1; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double TfMax = 0.5; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool lowPassFilter = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double kpFactor = 3; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double kiFactor = 6; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double kdFactor = 0.5; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double deadband = 0.0001; //Lower value of "kWlimit" reduces maximum angular velocity - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble kWlimit = 0.15; private readonly Vector3d defaultTfV = new Vector3d(0.3, 0.3, 0.3); @@ -110,14 +110,14 @@ public void setPIDParameters() public void tuneTf(Vector3d torque) { var ratio = new Vector3d( - torque.x != 0 ? ac.vesselState.MoI.x / torque.x : 0, - torque.y != 0 ? ac.vesselState.MoI.y / torque.y : 0, - torque.z != 0 ? ac.vesselState.MoI.z / torque.z : 0 + torque.x != 0 ? ac.VesselState.MoI.x / torque.x : 0, + torque.y != 0 ? ac.VesselState.MoI.y / torque.y : 0, + torque.z != 0 ? ac.VesselState.MoI.z / torque.z : 0 ); TfV = 0.05 * ratio; - Vector3d delayFactor = Vector3d.one + 2 * ac.vesselState.torqueReactionSpeed; + Vector3d delayFactor = Vector3d.one + 2 * ac.VesselState.torqueReactionSpeed; TfV.Scale(delayFactor); @@ -149,7 +149,7 @@ public override void Reset() public override void DrivePre(FlightCtrlState s, out Vector3d act, out Vector3d deltaEuler) { - Transform vesselTransform = ac.vessel.ReferenceTransform; + Transform vesselTransform = ac.Vessel.ReferenceTransform; // Find out the real shorter way to turn where we wan to. // Thanks to HoneyFox @@ -184,12 +184,12 @@ public override void DrivePre(FlightCtrlState s, out Vector3d act, out Vector3d Math.Max(-Math.PI, Math.Min(Math.PI, err.z))); // ( MoI / available torque ) factor: - var NormFactor = Vector3d.Scale(ac.vesselState.MoI, ac.torque.InvertNoNaN()); + var NormFactor = Vector3d.Scale(ac.VesselState.MoI, ac.torque.InvertNoNaN()); err.Scale(NormFactor); // angular velocity: - Vector3d omega = ac.vessel.angularVelocity; + Vector3d omega = ac.Vessel.angularVelocity; //omega.x = vessel.angularVelocity.x; //omega.y = vessel.angularVelocity.z; // y <=> z //omega.z = vessel.angularVelocity.y; // z <=> y diff --git a/MechJeb2/ComputerModule.cs b/MechJeb2/ComputerModule.cs index ebdb52b35..beaa68a0e 100644 --- a/MechJeb2/ComputerModule.cs +++ b/MechJeb2/ComputerModule.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using JetBrains.Annotations; using UnityEngine; using UnityEngine.Profiling; @@ -8,81 +9,81 @@ namespace MuMech { public class ComputerModule : IComparable { - public Part part; - public MechJebCore core; - public VesselState vesselState; + public readonly MechJebCore Core; //conveniences: - public Vessel vessel => part.vessel; - public CelestialBody mainBody => part.vessel.mainBody; - public Orbit orbit => part.vessel.orbit; + public Vessel Vessel => Part.vessel; + public CelestialBody MainBody => Part.vessel.mainBody; + public VesselState VesselState => Core.VesselState; - public int priority; + [UsedImplicitly] + public Part Part => Core.part; - [Persistent(pass = (int)Pass.Local)] - public string unlockParts = ""; + [UsedImplicitly] + public Orbit Orbit => Part.vessel.orbit; - [Persistent(pass = (int)Pass.Local)] - public string unlockTechs = ""; + [UsedImplicitly] + public int Priority; - public bool unlockChecked; + [UsedImplicitly] + [Persistent(pass = (int)Pass.LOCAL)] + public readonly string UnlockParts = ""; + + [UsedImplicitly] + [Persistent(pass = (int)Pass.LOCAL)] + public readonly string UnlockTechs = ""; + + public bool UnlockChecked; public int CompareTo(ComputerModule other) { - if (other == null) return 1; - return priority.CompareTo(other.priority); + return other == null ? 1 : Priority.CompareTo(other.Priority); } - protected bool _enabled; + private bool _enabled; - public bool enabled + public bool Enabled { get => _enabled; set { - if (value != _enabled) - { - dirty = true; - _enabled = value; - if (_enabled) - { - OnModuleEnabled(); - } - else - { - OnModuleDisabled(); - } - } + if (value == _enabled) return; + + Dirty = true; + _enabled = value; + + if (_enabled) + OnModuleEnabled(); + else + OnModuleDisabled(); } } - public string profilerName; + public readonly string ProfilerName; // Has this module config changed and should it be saved - public bool dirty; + public bool Dirty; //The UserPool is an alternative way to handle enabling/disabling of a ComputerModule. //Users can add and remove themselves from the user pool and the ComputerModule will be //enabled if and only if there is at least one user. For consistency, it's probably //best that a given ComputerModule be controlled either entirely through enabled, or //entirely through users, and that the two not be mixed. - public UserPool users; + public readonly UserPool Users; - public ComputerModule(MechJebCore core) + protected ComputerModule(MechJebCore core) { - this.core = core; - part = core.part; - vesselState = core.VesselState; - profilerName = GetType().Name; + Core = core; + ProfilerName = GetType().Name; - users = new UserPool(this); + Users = new UserPool(this); } - public virtual void OnModuleEnabled() + protected virtual void OnModuleEnabled() { } - public virtual void OnModuleDisabled() + protected virtual void OnModuleDisabled() { } @@ -134,9 +135,9 @@ public virtual void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global) { try { - if (global != null) ConfigNode.LoadObjectFromConfig(this, global, (int)Pass.Global); - if (type != null) ConfigNode.LoadObjectFromConfig(this, type, (int)Pass.Type); - if (local != null) ConfigNode.LoadObjectFromConfig(this, local, (int)Pass.Local); + if (global != null) ConfigNode.LoadObjectFromConfig(this, global, (int)Pass.GLOBAL); + if (type != null) ConfigNode.LoadObjectFromConfig(this, type, (int)Pass.TYPE); + if (local != null) ConfigNode.LoadObjectFromConfig(this, local, (int)Pass.LOCAL); } catch (Exception e) { @@ -151,25 +152,25 @@ public virtual void OnSave(ConfigNode local, ConfigNode type, ConfigNode global) if (global != null) { Profiler.BeginSample("ComputerModule.OnSave.global"); - ConfigNode.CreateConfigFromObject(this, (int)Pass.Global, global); + ConfigNode.CreateConfigFromObject(this, (int)Pass.GLOBAL, global); Profiler.EndSample(); } if (type != null) { Profiler.BeginSample("ComputerModule.OnSave.type"); - ConfigNode.CreateConfigFromObject(this, (int)Pass.Type, type); + ConfigNode.CreateConfigFromObject(this, (int)Pass.TYPE, type); Profiler.EndSample(); } if (local != null) { Profiler.BeginSample("ComputerModule.OnSave.local"); - ConfigNode.CreateConfigFromObject(this, (int)Pass.Local, local); + ConfigNode.CreateConfigFromObject(this, (int)Pass.LOCAL, local); Profiler.EndSample(); } - dirty = false; + Dirty = false; } catch (Exception e) { @@ -181,65 +182,64 @@ public virtual void OnDestroy() { } - public virtual bool IsSpaceCenterUpgradeUnlocked() + protected virtual bool IsSpaceCenterUpgradeUnlocked() { return true; } public virtual void UnlockCheck() { - if (!unlockChecked) - { - bool unlock = true; + if (UnlockChecked) return; - if (ResearchAndDevelopment.Instance != null) + bool unlock = true; + + if (ResearchAndDevelopment.Instance != null) + { + string[] parts = UnlockParts.Split(new[] { ' ', ',', ';', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length > 0) { - string[] parts = unlockParts.Split(new[] { ' ', ',', ';', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length > 0) + unlock = false; + foreach (string p in parts) { - unlock = false; - foreach (string p in parts) + if (PartLoader.LoadedPartsList.Count(a => a.name == p) > 0 && + ResearchAndDevelopment.PartModelPurchased(PartLoader.LoadedPartsList.First(a => a.name == p))) { - if (PartLoader.LoadedPartsList.Count(a => a.name == p) > 0 && - ResearchAndDevelopment.PartModelPurchased(PartLoader.LoadedPartsList.First(a => a.name == p))) - { - unlock = true; - break; - } + unlock = true; + break; } } + } - string[] techs = unlockTechs.Split(new[] { ' ', ',', ';', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); - if (techs.Length > 0) + string[] techs = UnlockTechs.Split(new[] { ' ', ',', ';', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + if (techs.Length > 0) + { + if (parts.Length == 0) { - if (parts.Length == 0) - { - unlock = false; - } + unlock = false; + } - foreach (string t in techs) + foreach (string t in techs) + { + if (ResearchAndDevelopment.GetTechnologyState(t) == RDTech.State.Available) { - if (ResearchAndDevelopment.GetTechnologyState(t) == RDTech.State.Available) - { - unlock = true; - break; - } + unlock = true; + break; } } } + } - unlock = unlock && IsSpaceCenterUpgradeUnlocked(); + unlock = unlock && IsSpaceCenterUpgradeUnlocked(); - unlockChecked = true; - if (!unlock) - { - enabled = false; - core.someModuleAreLocked = true; - } + UnlockChecked = true; + if (!unlock) + { + Enabled = false; + Core.someModuleAreLocked = true; } } - public static void print(object message) + protected static void Print(object message) { MonoBehaviour.print("[MechJeb2] " + message); } @@ -248,62 +248,56 @@ public static void print(object message) [Flags] public enum Pass { - Local = 1, - Type = 2, - Global = 4 + LOCAL = 1, + TYPE = 2, + GLOBAL = 4 } //Lets multiple users enable and disable a computer module, such that the //module only gets disabled when all of its users have disabled it. public class UserPool : List { - private readonly ComputerModule controlledModule; + private readonly ComputerModule _controlledModule; public UserPool(ComputerModule controlledModule) { - this.controlledModule = controlledModule; + _controlledModule = controlledModule; } public new void Add(object user) { if (user != null && !Contains(user)) - { base.Add(user); - } - controlledModule.enabled = true; + _controlledModule.Enabled = true; } public new void Remove(object user) { if (user != null && Contains(user)) - { base.Remove(user); - } - if (Count == 0) controlledModule.enabled = false; + if (Count == 0) _controlledModule.Enabled = false; } public new void Clear() { base.Clear(); - controlledModule.enabled = false; + _controlledModule.Enabled = false; } public bool RecursiveUser(object user) { if (Contains(user)) - { return true; - } foreach (object o in this) { - var c = o as ComputerModule; - if (c != null && c != controlledModule) - { - if (c.users.RecursiveUser(user)) return true; - } + if (!(o is ComputerModule c) || c == _controlledModule) + continue; + + if (c.Users.RecursiveUser(user)) + return true; } return false; diff --git a/MechJeb2/DisplayModule.cs b/MechJeb2/DisplayModule.cs index 6e0735ea5..ea0ff5395 100644 --- a/MechJeb2/DisplayModule.cs +++ b/MechJeb2/DisplayModule.cs @@ -30,7 +30,7 @@ public Rect windowPos { if (windowVector != newPos) { - dirty = true; + Dirty = true; windowVector = newPos; } } @@ -38,7 +38,7 @@ public Rect windowPos { if (windowVectorEditor != newPos) { - dirty = true; + Dirty = true; windowVectorEditor = newPos; } } @@ -47,14 +47,14 @@ public Rect windowPos // Those field should be private but Persistent has a bug that prevent it to work properly on parent class private fields - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public Vector4 windowVector = new Vector4(10, 40, 0, 0); //Persistence is via a Vector4 since ConfigNode doesn't know how to serialize Rects - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public Vector4 windowVectorEditor = new Vector4(10, 40, 0, 0); //Persistence is via a Vector4 since ConfigNode doesn't know how to serialize Rects - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showInFlight = true; public bool ShowInFlight @@ -65,12 +65,12 @@ public bool ShowInFlight if (showInFlight != value) { showInFlight = value; - dirty = true; + Dirty = true; } } } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showInEditor; public bool ShowInEditor @@ -81,12 +81,12 @@ public bool ShowInEditor if (showInEditor != value) { showInEditor = value; - dirty = true; + Dirty = true; } } } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool isOverlay; public bool IsOverlay @@ -97,12 +97,12 @@ public bool IsOverlay if (isOverlay != value) { isOverlay = value; - dirty = true; + Dirty = true; } } } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool locked; public bool Locked @@ -113,7 +113,7 @@ public bool Locked if (locked != value) { locked = value; - dirty = true; + Dirty = true; } } } @@ -144,7 +144,7 @@ protected void WindowGUI(int windowID, bool draggable) { if (!isOverlay && GUI.Button(new Rect(windowPos.width - 18, 2, 16, 16), "")) { - enabled = false; + Enabled = false; } // if (GUI.Button(new Rect(windowPos.width - 40, 2, 20, 16), (locked ? "X" : "O"))) // lock button needs an icon, letters look crap @@ -153,7 +153,7 @@ protected void WindowGUI(int windowID, bool draggable) // } bool allowDrag = !locked; - if (!locked && !isOverlay && core.Settings.useTitlebarDragging) + if (!locked && !isOverlay && Core.Settings.useTitlebarDragging) { float x = Mouse.screenPos.x / GuiUtils.scale; float y = Mouse.screenPos.y / GuiUtils.scale; @@ -218,9 +218,9 @@ public override void OnSave(ConfigNode local, ConfigNode type, ConfigNode global if (global != null) { if (HighLogic.LoadedSceneIsEditor) - enabledEditor = enabled; + enabledEditor = Enabled; if (HighLogic.LoadedSceneIsFlight) - enabledFlight = enabled; + enabledFlight = Enabled; global.AddValue("enabledEditor", enabledEditor); global.AddValue("enabledFlight", enabledFlight); @@ -241,7 +241,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global enabledEditor = loadedEnabled; useOldConfig = false; if (HighLogic.LoadedSceneIsEditor) - enabled = loadedEnabled; + Enabled = loadedEnabled; } } @@ -253,7 +253,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global enabledFlight = loadedEnabled; useOldConfig = false; if (HighLogic.LoadedSceneIsFlight) - enabled = loadedEnabled; + Enabled = loadedEnabled; } } @@ -264,12 +264,12 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global bool loadedEnabled; if (bool.TryParse(global.GetValue("enabled"), out loadedEnabled)) { - enabled = loadedEnabled; + Enabled = loadedEnabled; } } - enabledEditor = enabled; - enabledFlight = enabled; + enabledEditor = Enabled; + enabledFlight = Enabled; } // if (global != null && global.HasValue("locked")) @@ -284,7 +284,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global public virtual bool isActive() { if (makesActive == null) - makesActive = new ComputerModule[] { core.Attitude, core.Thrust, core.Rover, core.Node, core.RCS, core.Rcsbal }; + makesActive = new ComputerModule[] { Core.Attitude, Core.Thrust, Core.Rover, Core.Node, Core.RCS, Core.Rcsbal }; bool active = false; for (int i = 0; i < makesActive.Length; i++) @@ -292,7 +292,7 @@ public virtual bool isActive() ComputerModule m = makesActive[i]; if (m != null) { - if (active |= m.users.RecursiveUser(this)) + if (active |= m.Users.RecursiveUser(this)) break; } } @@ -302,21 +302,21 @@ public virtual bool isActive() public override void UnlockCheck() { - if (!unlockChecked) + if (!UnlockChecked) { - bool prevEn = enabled; - enabled = true; + bool prevEn = Enabled; + Enabled = true; base.UnlockCheck(); - if (unlockParts.Trim().Length > 0 || unlockTechs.Trim().Length > 0 || !IsSpaceCenterUpgradeUnlocked()) + if (UnlockParts.Trim().Length > 0 || UnlockTechs.Trim().Length > 0 || !IsSpaceCenterUpgradeUnlocked()) { - hidden = !enabled; + hidden = !Enabled; if (hidden) { prevEn = false; } } - enabled = prevEn; + Enabled = prevEn; } } diff --git a/MechJeb2/GuiUtils.cs b/MechJeb2/GuiUtils.cs index 81fbe624b..3a2291727 100644 --- a/MechJeb2/GuiUtils.cs +++ b/MechJeb2/GuiUtils.cs @@ -798,7 +798,7 @@ public static bool MouseIsOverWindow(MechJebCore core) //try to check if the mouse is over any active DisplayModule foreach (DisplayModule m in core.GetComputerModules()) { - if (m.enabled && m.showInCurrentScene && !m.IsOverlay + if (m.Enabled && m.showInCurrentScene && !m.IsOverlay && m.windowPos.Contains(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y) / scale)) { return true; diff --git a/MechJeb2/LandingAutopilot/CoastToDeceleration.cs b/MechJeb2/LandingAutopilot/CoastToDeceleration.cs index 1b59ba32e..564164a79 100644 --- a/MechJeb2/LandingAutopilot/CoastToDeceleration.cs +++ b/MechJeb2/LandingAutopilot/CoastToDeceleration.cs @@ -23,11 +23,11 @@ public override AutopilotStep Drive(FlightCtrlState s) if (!Core.Landing.RCSAdjustment) return this; if (deltaV.magnitude > 3) - Core.RCS.enabled = true; + Core.RCS.Enabled = true; else if (deltaV.magnitude < 0.01) - Core.RCS.enabled = false; + Core.RCS.Enabled = false; - if (Core.RCS.enabled) + if (Core.RCS.Enabled) Core.RCS.SetWorldVelocityError(deltaV); return this; @@ -53,7 +53,7 @@ public override AutopilotStep OnFixedUpdate() { Core.Warp.MinimumWarp(); if (Core.Landing.RCSAdjustment) - Core.RCS.enabled = false; + Core.RCS.Enabled = false; return new DecelerationBurn(Core); } @@ -70,7 +70,7 @@ public override AutopilotStep OnFixedUpdate() { Core.Warp.MinimumWarp(); if (Core.Landing.RCSAdjustment) - Core.RCS.enabled = false; + Core.RCS.Enabled = false; return new CourseCorrection(Core); } } @@ -87,7 +87,7 @@ public override AutopilotStep OnFixedUpdate() { Core.Warp.MinimumWarp(); if (Core.Landing.RCSAdjustment) - Core.RCS.enabled = false; + Core.RCS.Enabled = false; return new DecelerationBurn(Core); } diff --git a/MechJeb2/LandingAutopilot/CourseCorrection.cs b/MechJeb2/LandingAutopilot/CourseCorrection.cs index 626a91619..791fb30d6 100644 --- a/MechJeb2/LandingAutopilot/CourseCorrection.cs +++ b/MechJeb2/LandingAutopilot/CourseCorrection.cs @@ -32,7 +32,7 @@ public override AutopilotStep Drive(FlightCtrlState s) { Core.Thrust.targetThrottle = 0; if (Core.Landing.RCSAdjustment) - Core.RCS.enabled = true; + Core.RCS.Enabled = true; return new CoastToDeceleration(Core); } diff --git a/MechJeb2/Maneuver/OperationApoapsis.cs b/MechJeb2/Maneuver/OperationApoapsis.cs index ce49ae401..0d1b74206 100644 --- a/MechJeb2/Maneuver/OperationApoapsis.cs +++ b/MechJeb2/Maneuver/OperationApoapsis.cs @@ -10,7 +10,7 @@ public class OperationApoapsis : Operation public override string GetName() { return Localizer.Format("#MechJeb_Ap_title"); } //change apoapsis [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableDoubleMult NewApA = new EditableDoubleMult(200000, 1000); private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationCourseCorrection.cs b/MechJeb2/Maneuver/OperationCourseCorrection.cs index 8f2e1a808..e12db7d97 100644 --- a/MechJeb2/Maneuver/OperationCourseCorrection.cs +++ b/MechJeb2/Maneuver/OperationCourseCorrection.cs @@ -11,11 +11,11 @@ public class OperationCourseCorrection : Operation public override string GetName() { return Localizer.Format("#MechJeb_approach_title"); } //fine tune closest approach to target [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult CourseCorrectFinalPeA = new EditableDoubleMult(200000, 1000); [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult InterceptDistance = new EditableDoubleMult(200); public override void DoParametersGUI(Orbit o, double universalTime, MechJebModuleTargetController target) @@ -42,7 +42,7 @@ protected override List MakeNodesImpl(Orbit o, double ut, Me break; } - correctionPatch = target.core.vessel.GetNextPatch(correctionPatch); + correctionPatch = target.Core.vessel.GetNextPatch(correctionPatch); } if (correctionPatch == null || correctionPatch.referenceBody != target.TargetOrbit.referenceBody) diff --git a/MechJeb2/Maneuver/OperationEccentricity.cs b/MechJeb2/Maneuver/OperationEccentricity.cs index 3b55739d7..d51d33bd8 100644 --- a/MechJeb2/Maneuver/OperationEccentricity.cs +++ b/MechJeb2/Maneuver/OperationEccentricity.cs @@ -8,7 +8,7 @@ public class OperationEccentricity : Operation public override string GetName() { return "change eccentricity"; } [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableDoubleMult NewEcc = new EditableDouble(0); private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationEllipticize.cs b/MechJeb2/Maneuver/OperationEllipticize.cs index 8f3b8c6c4..1fa18dc32 100644 --- a/MechJeb2/Maneuver/OperationEllipticize.cs +++ b/MechJeb2/Maneuver/OperationEllipticize.cs @@ -11,11 +11,11 @@ public class OperationEllipticize : Operation public override string GetName() { return Localizer.Format("#MechJeb_both_title"); } //change both Pe and Ap [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult NewApA = new EditableDoubleMult(200000, 1000); [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult NewPeA = new EditableDoubleMult(100000, 1000); private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationInclination.cs b/MechJeb2/Maneuver/OperationInclination.cs index bc4991503..d30eb81a4 100644 --- a/MechJeb2/Maneuver/OperationInclination.cs +++ b/MechJeb2/Maneuver/OperationInclination.cs @@ -10,7 +10,7 @@ public class OperationInclination : Operation public override string GetName() { return Localizer.Format("#MechJeb_inclination_title"); } //change inclination [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble NewInc = 0; private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationInterplanetaryTransfer.cs b/MechJeb2/Maneuver/OperationInterplanetaryTransfer.cs index f4fd8d59d..370e544db 100644 --- a/MechJeb2/Maneuver/OperationInterplanetaryTransfer.cs +++ b/MechJeb2/Maneuver/OperationInterplanetaryTransfer.cs @@ -11,7 +11,7 @@ public class OperationInterplanetaryTransfer : Operation public override string GetName() { return Localizer.Format("#MechJeb_transfer_title"); } //transfer to another planet [UsedImplicitly] - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public bool WaitForPhaseAngle = true; public override void DoParametersGUI(Orbit o, double universalTime, MechJebModuleTargetController target) diff --git a/MechJeb2/Maneuver/OperationLambert.cs b/MechJeb2/Maneuver/OperationLambert.cs index f8e2f1376..9e44bdaeb 100644 --- a/MechJeb2/Maneuver/OperationLambert.cs +++ b/MechJeb2/Maneuver/OperationLambert.cs @@ -10,7 +10,7 @@ public class OperationLambert : Operation public override string GetName() { return Localizer.Format("#MechJeb_intercept_title"); } //intercept target at chosen time [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableTime InterceptInterval = 3600; private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationMoonReturn.cs b/MechJeb2/Maneuver/OperationMoonReturn.cs index 701b0feca..8eea9d2b0 100644 --- a/MechJeb2/Maneuver/OperationMoonReturn.cs +++ b/MechJeb2/Maneuver/OperationMoonReturn.cs @@ -11,7 +11,7 @@ public class OperationMoonReturn : Operation public override string GetName() { return Localizer.Format("#MechJeb_return_title"); } //return from a moon [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult MoonReturnAltitude = new EditableDoubleMult(100000, 1000); public override void DoParametersGUI(Orbit o, double universalTime, MechJebModuleTargetController target) diff --git a/MechJeb2/Maneuver/OperationPeriapsis.cs b/MechJeb2/Maneuver/OperationPeriapsis.cs index 407cabc9b..83cb93b7b 100644 --- a/MechJeb2/Maneuver/OperationPeriapsis.cs +++ b/MechJeb2/Maneuver/OperationPeriapsis.cs @@ -11,7 +11,7 @@ public class OperationPeriapsis : Operation public override string GetName() { return Localizer.Format("#MechJeb_Pe_title"); } //change periapsis [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableDoubleMult NewPeA = new EditableDoubleMult(100000, 1000); private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationResonantOrbit.cs b/MechJeb2/Maneuver/OperationResonantOrbit.cs index bb68c589c..449d96eee 100644 --- a/MechJeb2/Maneuver/OperationResonantOrbit.cs +++ b/MechJeb2/Maneuver/OperationResonantOrbit.cs @@ -11,11 +11,11 @@ public class OperationResonantOrbit : Operation public override string GetName() { return Localizer.Format("#MechJeb_resonant_title"); } //resonant orbit [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableInt ResonanceNumerator = 2; [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableInt ResonanceDenominator = 3; private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationSemiMajor.cs b/MechJeb2/Maneuver/OperationSemiMajor.cs index b7f70db89..cd7f4ca64 100644 --- a/MechJeb2/Maneuver/OperationSemiMajor.cs +++ b/MechJeb2/Maneuver/OperationSemiMajor.cs @@ -11,7 +11,7 @@ public class OperationSemiMajor : Operation public override string GetName() { return Localizer.Format("#MechJeb_Sa_title"); } //change semi-major axis [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDoubleMult NewSma = new EditableDoubleMult(800000, 1000); private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/OperationTransfer.cs b/MechJeb2/Maneuver/OperationTransfer.cs index e91891595..acb4151ec 100644 --- a/MechJeb2/Maneuver/OperationTransfer.cs +++ b/MechJeb2/Maneuver/OperationTransfer.cs @@ -14,17 +14,17 @@ public class OperationGeneric : Operation public bool InterceptOnly; [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble PeriodOffset = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableTime MinDepartureUT = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableTime MaxDepartureUT = 0; [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool SimpleTransfer; private readonly TimeSelector _timeSelector; diff --git a/MechJeb2/Maneuver/TimeSelector.cs b/MechJeb2/Maneuver/TimeSelector.cs index 86a8c4f2a..89432fa4b 100644 --- a/MechJeb2/Maneuver/TimeSelector.cs +++ b/MechJeb2/Maneuver/TimeSelector.cs @@ -20,18 +20,18 @@ public class TimeSelector private readonly TimeReference[] allowedTimeRef; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private int _currentTimeRef; public TimeReference TimeReference => allowedTimeRef[_currentTimeRef]; // Input parameters [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableTime LeadTime = 0; [UsedImplicitly] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableDoubleMult CircularizeAltitude = new EditableDoubleMult(150000, 1000); public TimeSelector(TimeReference[] allowedTimeRef) diff --git a/MechJeb2/MechJebAR202.cs b/MechJeb2/MechJebAR202.cs index b5eaa0731..5e47154db 100644 --- a/MechJeb2/MechJebAR202.cs +++ b/MechJeb2/MechJebAR202.cs @@ -100,7 +100,7 @@ private void HandleLights() foreach (DisplayModule display in core.GetDisplayModules(MechJebModuleMenu.DisplayOrder.instance)) { if (display is MechJebModuleMenu) continue; - if (display.enabled && display.showInCurrentScene) + if (display.Enabled && display.showInCurrentScene) { somethingEnabled = true; } diff --git a/MechJeb2/MechJebCore.cs b/MechJeb2/MechJebCore.cs index cc4674f45..fd70ce846 100644 --- a/MechJeb2/MechJebCore.cs +++ b/MechJeb2/MechJebCore.cs @@ -294,7 +294,7 @@ private void EngageTranslatronControl(MechJebModuleThrustController.TMode mode) if (moduleTranslatron is { hidden: false }) { - if (Thrust.users.Count > 1 && !Thrust.users.Contains(moduleTranslatron)) + if (Thrust.Users.Count > 1 && !Thrust.Users.Contains(moduleTranslatron)) return; moduleTranslatron.SetMode(mode); @@ -601,10 +601,10 @@ public void FixedUpdate() foreach (ComputerModule module in GetComputerModules()) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { - if (module.enabled) + if (module.Enabled) { module.OnFixedUpdate(); } @@ -627,7 +627,7 @@ private bool NeedToSave() { //if (module.dirty) // print(module.profilerName + " is dirty"); - needToSave |= module.dirty; + needToSave |= module.Dirty; } return needToSave; @@ -666,7 +666,7 @@ public void Update() Profiler.EndSample(); - if (ResearchAndDevelopment.Instance != null && _unorderedComputerModules.Any(a => !a.unlockChecked)) + if (ResearchAndDevelopment.Instance != null && _unorderedComputerModules.Any(a => !a.UnlockChecked)) { foreach (ComputerModule module in GetComputerModules()) { @@ -693,10 +693,10 @@ public void Update() foreach (ComputerModule module in GetComputerModules()) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { - if (module.enabled) module.OnUpdate(); + if (module.Enabled) module.OnUpdate(); } catch (Exception e) { @@ -969,7 +969,7 @@ public override void OnSave(ConfigNode sfsNode) Profiler.BeginSample("MechJebCore.OnSave.loop"); foreach (ComputerModule module in GetComputerModules()) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { string moduleTypeName = module.GetType().Name; @@ -1086,10 +1086,10 @@ private void Drive(FlightCtrlState s) { foreach (ComputerModule module in GetComputerModules()) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { - if (module.enabled) module.Drive(s); + if (module.Enabled) module.Drive(s); } catch (Exception e) { @@ -1154,10 +1154,10 @@ private void OnGUI() foreach (ComputerModule computerModule in GetComputerModules()) { var module = (DisplayModule)computerModule; - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { - if (module.enabled) module.DrawGUI(HighLogic.LoadedSceneIsEditor); + if (module.Enabled) module.DrawGUI(HighLogic.LoadedSceneIsEditor); } catch (Exception e) { @@ -1247,9 +1247,9 @@ private void OnVesselWasModified(Vessel v) const string SAMPLE_NAME = "MechJebCore.OnVesselWasModified"; Profiler.BeginSample(SAMPLE_NAME); - foreach (ComputerModule module in GetComputerModules().Where(x => x.enabled)) + foreach (ComputerModule module in GetComputerModules().Where(x => x.Enabled)) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { module.OnVesselWasModified(v); @@ -1273,9 +1273,9 @@ private void OnVesselStandardModification(Vessel v) const string SAMPLE_NAME = "MechJebCore.OnVesselStandardModification"; Profiler.BeginSample(SAMPLE_NAME); - foreach (ComputerModule module in GetComputerModules().Where(x => x.enabled)) + foreach (ComputerModule module in GetComputerModules().Where(x => x.Enabled)) { - Profiler.BeginSample(module.profilerName); + Profiler.BeginSample(module.ProfilerName); try { module.OnVesselStandardModification(v); diff --git a/MechJeb2/MechJebModuleAirplaneAutopilot.cs b/MechJeb2/MechJebModuleAirplaneAutopilot.cs index d0a9736d8..e375d63ff 100644 --- a/MechJeb2/MechJebModuleAirplaneAutopilot.cs +++ b/MechJeb2/MechJebModuleAirplaneAutopilot.cs @@ -11,28 +11,28 @@ namespace MuMech [UsedImplicitly] public class MechJebModuleAirplaneAutopilot : ComputerModule { - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool HeadingHoldEnabled, AltitudeHoldEnabled, VertSpeedHoldEnabled, RollHoldEnabled, SpeedHoldEnabled; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public double AltitudeTarget = 0, HeadingTarget = 90, RollTarget = 0, SpeedTarget = 0, VertSpeedTarget = 0; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public double BankAngle = 30; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public readonly EditableDouble AccKp = 0.5, AccKi = 0.5, AccKd = 0.005; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public readonly EditableDouble PitKp = 2.0, PitKi = 1.0, PitKd = 0.005; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public readonly EditableDouble RolKp = 0.5, RolKi = 0.02, RolKd = 0.5; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public readonly EditableDouble YawKp = 1.0, YawKi = 0.25, YawKd = 0.02; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public readonly EditableDouble YawLimit = 10, RollLimit = 45, PitchDownLimit = 15, PitchUpLimit = 25; public PIDController AccelerationPIDController, PitchPIDController, RollPIDController, YawPIDController; @@ -59,7 +59,7 @@ public override void OnStart(PartModule.StartState state) YawPIDController = new PIDController(YawKp, YawKi, YawKd); } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { if (AltitudeHoldEnabled) EnableAltitudeHold(); @@ -67,11 +67,11 @@ public override void OnModuleEnabled() EnableSpeedHold(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { if (SpeedHoldEnabled) { - core.Thrust.users.Remove(this); + Core.Thrust.Users.Remove(this); } } @@ -93,27 +93,27 @@ public void DisableHeadingHold() public void EnableSpeedHold() { - if (!enabled) + if (!Enabled) return; - Spd = vesselState.speedSurface; + Spd = VesselState.speedSurface; SpeedHoldEnabled = true; - core.Thrust.users.Add(this); + Core.Thrust.Users.Add(this); AccelerationPIDController.Reset(); } public void DisableSpeedHold() { - if (!enabled) + if (!Enabled) return; SpeedHoldEnabled = false; - core.Thrust.users.Remove(this); + Core.Thrust.Users.Remove(this); } public void EnableVertSpeedHold() { - if (!enabled) + if (!Enabled) return; VertSpeedHoldEnabled = true; @@ -123,7 +123,7 @@ public void EnableVertSpeedHold() public void DisableVertSpeedHold() { - if (!enabled) + if (!Enabled) return; VertSpeedHoldEnabled = false; @@ -131,7 +131,7 @@ public void DisableVertSpeedHold() public void EnableAltitudeHold() { - if (!enabled) + if (!Enabled) return; AltitudeHoldEnabled = true; @@ -147,7 +147,7 @@ public void EnableAltitudeHold() public void DisableAltitudeHold() { - if (!enabled) + if (!Enabled) return; AltitudeHoldEnabled = false; @@ -210,8 +210,8 @@ private void SynchronizePIDs(FlightCtrlState s) private double ComputeYaw() { // probably not perfect, especially when the aircraft is turning - double path = vesselState.HeadingFromDirection(vesselState.surfaceVelocity); - double nose = vesselState.HeadingFromDirection(vesselState.forward); + double path = VesselState.HeadingFromDirection(VesselState.surfaceVelocity); + double nose = VesselState.HeadingFromDirection(VesselState.forward); double angle = MuUtils.ClampDegrees180(nose - path); return angle; @@ -225,7 +225,7 @@ public override void Drive(FlightCtrlState s) //SpeedHold (set AccelerationTarget automatically to hold speed) if (SpeedHoldEnabled) { - double spd = vesselState.speedSurface; + double spd = VesselState.speedSurface; CurAcc = (spd - Spd) / Time.fixedDeltaTime; Spd = spd; RealAccelerationTarget = (SpeedTarget - spd) / 4; @@ -234,11 +234,11 @@ public override void Drive(FlightCtrlState s) double tAct = AccelerationPIDController.Compute(AErr); if (!double.IsNaN(tAct)) { - core.Thrust.targetThrottle = (float)MuUtils.Clamp(tAct, 0, 1); + Core.Thrust.targetThrottle = (float)MuUtils.Clamp(tAct, 0, 1); } else { - core.Thrust.targetThrottle = 0.0f; + Core.Thrust.targetThrottle = 0.0f; AccelerationPIDController.Reset(); } } @@ -250,7 +250,7 @@ public override void Drive(FlightCtrlState s) // There is about 0.4 between altitudeASL and the altitude that is displayed in KSP in the top center // i.e. 3000.4m (altitudeASL) equals 3000m ingame. // maybe there is something wrong with the way we calculate altitudeASL. Idk - double deltaAltitude = AltitudeTarget + 0.4 - vesselState.altitudeASL; + double deltaAltitude = AltitudeTarget + 0.4 - VesselState.altitudeASL; RealVertSpeedTarget = convertAltitudeToVerticalSpeed(deltaAltitude, 10); RealVertSpeedTarget = UtilMath.Clamp(RealVertSpeedTarget, -VertSpeedTarget, VertSpeedTarget); @@ -268,13 +268,13 @@ public override void Drive(FlightCtrlState s) // deltaAltitude = 2 * PI * r * deltaPitch / 360 // Vvertical = 2 * PI * TAS * deltaPitch / 360 // deltaPitch = Vvertical / Vhorizontal * 180 / PI - double deltaVertSpeed = RealVertSpeedTarget - vesselState.speedVertical; - double adjustment = deltaVertSpeed / vesselState.speedSurface * 180 / Math.PI; + double deltaVertSpeed = RealVertSpeedTarget - VesselState.speedVertical; + double adjustment = deltaVertSpeed / VesselState.speedSurface * 180 / Math.PI; - RealPitchTarget = vesselState.vesselPitch + adjustment; + RealPitchTarget = VesselState.vesselPitch + adjustment; RealPitchTarget = UtilMath.Clamp(RealPitchTarget, -PitchDownLimit, PitchUpLimit); - PitchErr = MuUtils.ClampDegrees180(RealPitchTarget - vesselState.vesselPitch); + PitchErr = MuUtils.ClampDegrees180(RealPitchTarget - VesselState.vesselPitch); PitchPIDController.intAccum = UtilMath.Clamp(PitchPIDController.intAccum, -100 / PitKi, 100 / PitKi); PitchAct = PitchPIDController.Compute(PitchErr) / 100; @@ -298,7 +298,7 @@ public override void Drive(FlightCtrlState s) //HeadingHold if (HeadingHoldEnabled) { - double toturn = MuUtils.ClampDegrees180(HeadingTarget - vesselState.currentHeading); + double toturn = MuUtils.ClampDegrees180(HeadingTarget - VesselState.currentHeading); if (Math.Abs(toturn) < 0.2) { @@ -323,7 +323,7 @@ public override void Drive(FlightCtrlState s) { RealRollTarget = UtilMath.Clamp(RealRollTarget, -BankAngle, BankAngle); RealRollTarget = UtilMath.Clamp(RealRollTarget, -RollLimit, RollLimit); - RollErr = MuUtils.ClampDegrees180(RealRollTarget - -vesselState.currentRoll); + RollErr = MuUtils.ClampDegrees180(RealRollTarget - -VesselState.currentRoll); RollPIDController.intAccum = MuUtils.Clamp(RollPIDController.intAccum, -100 / RolKi, 100 / RolKi); RollAct = RollPIDController.Compute(RollErr) / 100; diff --git a/MechJeb2/MechJebModuleAirplaneGuidance.cs b/MechJeb2/MechJebModuleAirplaneGuidance.cs index b891e9600..e625cf7d1 100644 --- a/MechJeb2/MechJebModuleAirplaneGuidance.cs +++ b/MechJeb2/MechJebModuleAirplaneGuidance.cs @@ -11,16 +11,16 @@ internal class MechJebModuleAirplaneGuidance : DisplayModule { private static GUIStyle btNormal, btActive, btAuto, btGreen, btWhite; - public MechJebModuleAirplaneAutopilot autopilot => core.GetComputerModule(); + public MechJebModuleAirplaneAutopilot autopilot => Core.GetComputerModule(); public MechJebModuleAirplaneGuidance(MechJebCore core) : base(core) { } - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] private bool showpid; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableDouble AltitudeTargettmp = 0, HeadingTargettmp = 90, RollTargettmp = 0, @@ -58,18 +58,18 @@ protected override void WindowGUI(int windowID) btAuto.onActive = btAuto.onFocused = btAuto.onHover = btAuto.onNormal = btAuto.active = btAuto.focused = btAuto.hover = btAuto.normal; } - if (autopilot.enabled) + if (autopilot.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_Aircraftauto_button1"), btActive)) { //Disengage autopilot - autopilot.users.Remove(this); + autopilot.Users.Remove(this); } } - else if (core.Attitude.enabled && core.Attitude.users.Count(u => !Equals(u)) > 0) + else if (Core.Attitude.Enabled && Core.Attitude.Users.Count(u => !Equals(u)) > 0) { - if (core.Attitude.users.Contains(this)) - core.Attitude.users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes + if (Core.Attitude.Users.Contains(this)) + Core.Attitude.Users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes GUILayout.Button("Auto", btAuto, GUILayout.ExpandWidth(true)); } else @@ -77,7 +77,7 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Aircraftauto_button2"))) { //Engage autopilot - autopilot.users.Add(this); + autopilot.Users.Add(this); } } @@ -365,7 +365,7 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); if (autopilot.VertSpeedHoldEnabled) GUILayout.Label(Localizer.Format("#MecgJeb_Aircraftauto_error2", autopilot.PitchErr.ToString("F2"), - autopilot.RealPitchTarget.ToString("F2"), vesselState.currentPitch.ToString("F2"), autopilot.PitchAct.ToString("F5"), + autopilot.RealPitchTarget.ToString("F2"), VesselState.currentPitch.ToString("F2"), autopilot.PitchAct.ToString("F5"), GUILayout.ExpandWidth(false))); //error:" Target:"" Cur:" GUILayout.BeginHorizontal(); @@ -379,7 +379,7 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); if (autopilot.RollHoldEnabled) GUILayout.Label(Localizer.Format("#MecgJeb_Aircraftauto_error2", autopilot.RollErr.ToString("F2"), - autopilot.RealRollTarget.ToString("F2"), (-vesselState.currentRoll).ToString("F2"), autopilot.RollAct.ToString("F5"), + autopilot.RealRollTarget.ToString("F2"), (-VesselState.currentRoll).ToString("F2"), autopilot.RollAct.ToString("F5"), GUILayout.ExpandWidth(false))); //error:" Target:"" Cur:" GUILayout.BeginHorizontal(); diff --git a/MechJeb2/MechJebModuleAscentBaseAutopilot.cs b/MechJeb2/MechJebModuleAscentBaseAutopilot.cs index af9efa397..a064dbe95 100644 --- a/MechJeb2/MechJebModuleAscentBaseAutopilot.cs +++ b/MechJeb2/MechJebModuleAscentBaseAutopilot.cs @@ -11,7 +11,7 @@ public abstract class MechJebModuleAscentBaseAutopilot : ComputerModule public string Status = ""; - protected MechJebModuleAscentSettings AscentSettings => core.AscentSettings; + protected MechJebModuleAscentSettings AscentSettings => Core.AscentSettings; public bool TimedLaunch; private double _launchTime; @@ -22,7 +22,7 @@ public abstract class MechJebModuleAscentBaseAutopilot : ComputerModule // FIXME?: any time we lift off from a rock this should probably be set to that time? private double _launchStarted; - public double TMinus => _launchTime - vesselState.time; + public double TMinus => _launchTime - VesselState.time; //internal state: private enum AscentMode { PRELAUNCH, ASCEND, CIRCULARIZE } @@ -34,7 +34,7 @@ private enum AscentMode { PRELAUNCH, ASCEND, CIRCULARIZE } // wiring for launchStarted private void OnLaunch(EventReport report) { - _launchStarted = vesselState.time; + _launchStarted = VesselState.time; Debug.Log("[MechJebModuleAscentAutopilot] LaunchStarted = " + _launchStarted); } @@ -48,38 +48,38 @@ public override void OnStart(PartModule.StartState state) private void FixupLaunchStart() { // continuously update the launchStarted time if we're sitting on the ground on the water anywhere (once we are not, then we've launched) - if (vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.PRELAUNCH || - vessel.situation == Vessel.Situations.SPLASHED) - _launchStarted = vesselState.time; + if (Vessel.situation == Vessel.Situations.LANDED || Vessel.situation == Vessel.Situations.PRELAUNCH || + Vessel.situation == Vessel.Situations.SPLASHED) + _launchStarted = VesselState.time; } // various events can cause launchStarted to be before or after vessel.launchTime, but the most recent one is so far always the most accurate // (physics wobbles can start vessel.launchTime (KSP's zero MET) early, while staging before engaging the autopilot can cause launchStarted to happen early) // this will only be valid AFTER launching - protected double MET => vesselState.time - (_launchStarted > vessel.launchTime ? _launchStarted : vessel.launchTime); + protected double MET => VesselState.time - (_launchStarted > Vessel.launchTime ? _launchStarted : Vessel.launchTime); - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { _mode = AscentMode.PRELAUNCH; _placedCircularizeNode = false; - core.Attitude.users.Add(this); - core.Thrust.users.Add(this); - if (AscentSettings.Autostage) core.Staging.users.Add(this); + Core.Attitude.Users.Add(this); + Core.Thrust.Users.Add(this); + if (AscentSettings.Autostage) Core.Staging.Users.Add(this); Status = Localizer.Format("#MechJeb_Ascent_status1"); //"Pre Launch" } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Attitude.attitudeDeactivate(); - if (!core.RssMode) - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); - core.Staging.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + if (!Core.RssMode) + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); + Core.Staging.Users.Remove(this); - if (_placedCircularizeNode) core.Node.Abort(); + if (_placedCircularizeNode) Core.Node.Abort(); Status = Localizer.Format("#MechJeb_Ascent_status2"); //"Off" } @@ -94,22 +94,22 @@ public void StartCountdown(double time) public override void OnFixedUpdate() { if (AscentSettings.AscentType == AscentType.PVG) - core.StageStats.RequestUpdate(this); + Core.StageStats.RequestUpdate(this); FixupLaunchStart(); if (TimedLaunch) { - if (TMinus < 3 * vesselState.deltaT || (TMinus > 10.0 && _lastTMinus < 1.0)) + if (TMinus < 3 * VesselState.deltaT || (TMinus > 10.0 && _lastTMinus < 1.0)) { - if (enabled && vesselState.thrustAvailable < 10E-4) // only stage if we have no engines active + if (Enabled && VesselState.thrustAvailable < 10E-4) // only stage if we have no engines active StageManager.ActivateNextStage(); TimedLaunchHook(); // let ascentPath modules do stuff edge triggered on launch starting TimedLaunch = false; } else { - if (core.Node.autowarp) - core.Warp.WarpToUT(_launchTime - AscentSettings.WarpCountDown); + if (Core.Node.autowarp) + Core.Warp.WarpToUT(_launchTime - AscentSettings.WarpCountDown); } _lastTMinus = TMinus; @@ -140,28 +140,28 @@ private void DriveDeployableComponents() { if (AscentSettings.AutodeploySolarPanels) { - if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) + if (VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) { - core.Solarpanel.ExtendAll(); + Core.Solarpanel.ExtendAll(); } else { - core.Solarpanel.RetractAll(); + Core.Solarpanel.RetractAll(); } } if (AscentSettings.AutoDeployAntennas) { - if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) - core.AntennaControl.ExtendAll(); + if (VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) + Core.AntennaControl.ExtendAll(); else - core.AntennaControl.RetractAll(); + Core.AntennaControl.RetractAll(); } } private void DrivePrelaunch() { - if (vessel.LiftedOff() && !vessel.Landed) + if (Vessel.LiftedOff() && !Vessel.Landed) { Status = Localizer.Format("#MechJeb_Ascent_status4"); //"Vessel is not landed, skipping pre-launch" _mode = AscentMode.ASCEND; @@ -169,9 +169,9 @@ private void DrivePrelaunch() } Debug.Log("prelaunch killing throttle"); - core.Thrust.ThrustOff(); + Core.Thrust.ThrustOff(); - core.Attitude.SetAxisControl(false, false, false); + Core.Attitude.SetAxisControl(false, false, false); if (TimedLaunch && TMinus > 10.0) { @@ -179,10 +179,10 @@ private void DrivePrelaunch() return; } - if (AscentSettings.AutodeploySolarPanels && mainBody.atmosphere) + if (AscentSettings.AutodeploySolarPanels && MainBody.atmosphere) { - core.Solarpanel.RetractAll(); - if (core.Solarpanel.AllRetracted()) + Core.Solarpanel.RetractAll(); + if (Core.Solarpanel.AllRetracted()) { Debug.Log("Prelaunch -> Ascend"); _mode = AscentMode.ASCEND; @@ -205,9 +205,9 @@ private void DriveAscent() Debug.Log("Awaiting Liftoff"); Status = Localizer.Format("#MechJeb_Ascent_status6"); //"Awaiting liftoff" // kill the optimizer if it is running. - core.Guidance.enabled = false; + Core.Guidance.Enabled = false; - core.Attitude.SetAxisControl(false, false, false); + Core.Attitude.SetAxisControl(false, false, false); return; } @@ -227,9 +227,9 @@ private void DriveAscent() private void DriveCircularizationBurn() { - if (!vessel.patchedConicsUnlocked() || AscentSettings.SkipCircularization) + if (!Vessel.patchedConicsUnlocked() || AscentSettings.SkipCircularization) { - users.Clear(); + Users.Clear(); return; } @@ -237,22 +237,22 @@ private void DriveCircularizationBurn() if (_placedCircularizeNode) { - if (vessel.patchedConicSolver.maneuverNodes.Count == 0) + if (Vessel.patchedConicSolver.maneuverNodes.Count == 0) { - MechJebModuleFlightRecorder recorder = core.GetComputerModule(); + MechJebModuleFlightRecorder recorder = Core.GetComputerModule(); if (recorder != null) AscentSettings.LaunchPhaseAngle.val = recorder.phaseAngleFromMark; - if (recorder != null) AscentSettings.LaunchLANDifference.val = vesselState.orbitLAN - recorder.markLAN; + if (recorder != null) AscentSettings.LaunchLANDifference.val = VesselState.orbitLAN - recorder.markLAN; //finished circularize - users.Clear(); + Users.Clear(); return; } } else { //place circularization node - vessel.RemoveAllManeuverNodes(); - double ut = orbit.NextApoapsisTime(vesselState.time); + Vessel.RemoveAllManeuverNodes(); + double ut = Orbit.NextApoapsisTime(VesselState.time); //During the circularization burn, try to correct any inclination errors because it's better to combine the two burns. // For example, if you're about to do a 1500 m/s circularization burn, if you combine a 200 m/s inclination correction // into it, you actually only spend 1513 m/s to execute combined manuver. Mechjeb should also do correction burns before @@ -261,17 +261,17 @@ private void DriveCircularizationBurn() // FIXME? this inclination correction is unlikely to be at tha AN/DN and will throw the LAN off with anything other than high // TWR launches from equatorial launch sites -- should probably be made optional (or clip it if the correction is too large). Vector3d inclinationCorrection = - OrbitalManeuverCalculator.DeltaVToChangeInclination(orbit, ut, Math.Abs(AscentSettings.DesiredInclination)); - Vector3d smaCorrection = OrbitalManeuverCalculator.DeltaVForSemiMajorAxis(orbit.PerturbedOrbit(ut, inclinationCorrection), ut, - AscentSettings.DesiredOrbitAltitude + mainBody.Radius); + OrbitalManeuverCalculator.DeltaVToChangeInclination(Orbit, ut, Math.Abs(AscentSettings.DesiredInclination)); + Vector3d smaCorrection = OrbitalManeuverCalculator.DeltaVForSemiMajorAxis(Orbit.PerturbedOrbit(ut, inclinationCorrection), ut, + AscentSettings.DesiredOrbitAltitude + MainBody.Radius); Vector3d dV = inclinationCorrection + smaCorrection; - vessel.PlaceManeuverNode(orbit, dV, ut); + Vessel.PlaceManeuverNode(Orbit, dV, ut); _placedCircularizeNode = true; - core.Node.ExecuteOneNode(this); + Core.Node.ExecuteOneNode(this); } - Status = Localizer.Format(core.Node.burnTriggered ? "#MechJeb_Ascent_status7" : "#MechJeb_Ascent_status8"); + Status = Localizer.Format(Core.Node.burnTriggered ? "#MechJeb_Ascent_status7" : "#MechJeb_Ascent_status8"); } protected abstract bool DriveAscent2(); @@ -297,11 +297,11 @@ protected float ThrottleToRaiseApoapsis(double currentApR, double finalApR) { desiredThrottle = 0.0F; //done, throttle down } - else if (_raiseApoapsisLastUT > vesselState.time - 1) + else if (_raiseApoapsisLastUT > VesselState.time - 1) { //reduce throttle as apoapsis nears target double instantRatePerThrottle = - (orbit.ApR - _raiseApoapsisLastApR) / ((vesselState.time - _raiseApoapsisLastUT) * _raiseApoapsisLastThrottle); + (Orbit.ApR - _raiseApoapsisLastApR) / ((VesselState.time - _raiseApoapsisLastUT) * _raiseApoapsisLastThrottle); instantRatePerThrottle = Math.Max(1.0, instantRatePerThrottle); //avoid problems from negative rates _raiseApoapsisRatePerThrottle.value = instantRatePerThrottle; double desiredApRate = (finalApR - currentApR) / 1.0; @@ -314,26 +314,26 @@ protected float ThrottleToRaiseApoapsis(double currentApR, double finalApR) //record data for next frame _raiseApoapsisLastThrottle = desiredThrottle; - _raiseApoapsisLastApR = orbit.ApR; - _raiseApoapsisLastUT = vesselState.time; + _raiseApoapsisLastApR = Orbit.ApR; + _raiseApoapsisLastUT = VesselState.time; return desiredThrottle; } protected double SrfvelPitch() { - return 90.0 - Vector3d.Angle(vesselState.surfaceVelocity, vesselState.up); + return 90.0 - Vector3d.Angle(VesselState.surfaceVelocity, VesselState.up); } protected double SrfvelHeading() { - return vesselState.HeadingFromDirection(vesselState.surfaceVelocity.ProjectOnPlane(vesselState.up)); + return VesselState.HeadingFromDirection(VesselState.surfaceVelocity.ProjectOnPlane(VesselState.up)); } // this provides ground track heading based on desired inclination and is what most consumers should call protected void AttitudeTo(double desiredPitch) { - double desiredHeading = OrbitalManeuverCalculator.HeadingForLaunchInclination(vessel, vesselState, AscentSettings.DesiredInclination); + double desiredHeading = OrbitalManeuverCalculator.HeadingForLaunchInclination(Vessel, VesselState, AscentSettings.DesiredInclination); AttitudeTo(desiredPitch, desiredHeading); } @@ -356,27 +356,27 @@ protected void AttitudeTo(double desiredPitch, double desiredHeading) } */ - Vector3d desiredHeadingVector = Math.Sin(desiredHeading * UtilMath.Deg2Rad) * vesselState.east + - Math.Cos(desiredHeading * UtilMath.Deg2Rad) * vesselState.north; + Vector3d desiredHeadingVector = Math.Sin(desiredHeading * UtilMath.Deg2Rad) * VesselState.east + + Math.Cos(desiredHeading * UtilMath.Deg2Rad) * VesselState.north; Vector3d desiredThrustVector = Math.Cos(desiredPitch * UtilMath.Deg2Rad) * desiredHeadingVector - + Math.Sin(desiredPitch * UtilMath.Deg2Rad) * vesselState.up; + + Math.Sin(desiredPitch * UtilMath.Deg2Rad) * VesselState.up; desiredThrustVector = desiredThrustVector.normalized; /* old style AoA limiter */ if (AscentSettings.LimitAoA && !AscentSettings.LimitQaEnabled) { - float fade = vesselState.dynamicPressure < AscentSettings.AOALimitFadeoutPressure - ? (float)(AscentSettings.AOALimitFadeoutPressure / vesselState.dynamicPressure) + float fade = VesselState.dynamicPressure < AscentSettings.AOALimitFadeoutPressure + ? (float)(AscentSettings.AOALimitFadeoutPressure / VesselState.dynamicPressure) : 1; CurrentMaxAoA = Math.Min(fade * AscentSettings.MaxAoA, 180d); - AscentSettings.LimitingAoA = vessel.altitude < mainBody.atmosphereDepth && - Vector3.Angle(vesselState.surfaceVelocity, desiredThrustVector) > CurrentMaxAoA; + AscentSettings.LimitingAoA = Vessel.altitude < MainBody.atmosphereDepth && + Vector3.Angle(VesselState.surfaceVelocity, desiredThrustVector) > CurrentMaxAoA; if (AscentSettings.LimitingAoA) { - desiredThrustVector = Vector3.RotateTowards(vesselState.surfaceVelocity, desiredThrustVector, + desiredThrustVector = Vector3.RotateTowards(VesselState.surfaceVelocity, desiredThrustVector, (float)(CurrentMaxAoA * Mathf.Deg2Rad), 1).normalized; } } @@ -386,18 +386,18 @@ protected void AttitudeTo(double desiredPitch, double desiredHeading) { double lim = MuUtils.Clamp(AscentSettings.LimitQa, 0, 10000); AscentSettings.LimitingAoA = - vesselState.dynamicPressure * Vector3.Angle(vesselState.surfaceVelocity, desiredThrustVector) * UtilMath.Deg2Rad > lim; + VesselState.dynamicPressure * Vector3.Angle(VesselState.surfaceVelocity, desiredThrustVector) * UtilMath.Deg2Rad > lim; if (AscentSettings.LimitingAoA) { - CurrentMaxAoA = lim / vesselState.dynamicPressure * UtilMath.Rad2Deg; - desiredThrustVector = Vector3.RotateTowards(vesselState.surfaceVelocity, desiredThrustVector, + CurrentMaxAoA = lim / VesselState.dynamicPressure * UtilMath.Rad2Deg; + desiredThrustVector = Vector3.RotateTowards(VesselState.surfaceVelocity, desiredThrustVector, (float)(CurrentMaxAoA * UtilMath.Deg2Rad), 1).normalized; } } - bool liftedOff = vessel.LiftedOff() && !vessel.Landed && vesselState.altitudeBottom > 5; + bool liftedOff = Vessel.LiftedOff() && !Vessel.Landed && VesselState.altitudeBottom > 5; - double pitch = 90 - Vector3d.Angle(desiredThrustVector, vesselState.up); + double pitch = 90 - Vector3d.Angle(desiredThrustVector, VesselState.up); double hdg; @@ -407,22 +407,22 @@ protected void AttitudeTo(double desiredPitch, double desiredHeading) } else { - hdg = MuUtils.ClampDegrees360(UtilMath.Rad2Deg * Math.Atan2(Vector3d.Dot(desiredThrustVector, vesselState.east), - Vector3d.Dot(desiredThrustVector, vesselState.north))); + hdg = MuUtils.ClampDegrees360(UtilMath.Rad2Deg * Math.Atan2(Vector3d.Dot(desiredThrustVector, VesselState.east), + Vector3d.Dot(desiredThrustVector, VesselState.north))); } if (AscentSettings.ForceRoll) { // ReSharper disable once CompareOfFloatsByEqualityOperator - core.Attitude.attitudeTo(hdg, pitch, desiredPitch == 90.0 ? AscentSettings.VerticalRoll : AscentSettings.TurnRoll, this, - liftedOff, liftedOff, liftedOff && vesselState.altitudeBottom > AscentSettings.RollAltitude, true); + Core.Attitude.attitudeTo(hdg, pitch, desiredPitch == 90.0 ? AscentSettings.VerticalRoll : AscentSettings.TurnRoll, this, + liftedOff, liftedOff, liftedOff && VesselState.altitudeBottom > AscentSettings.RollAltitude, true); } else { - core.Attitude.attitudeTo(desiredThrustVector, AttitudeReference.INERTIAL_COT, this); + Core.Attitude.attitudeTo(desiredThrustVector, AttitudeReference.INERTIAL_COT, this); } - core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && vesselState.altitudeBottom > AscentSettings.RollAltitude); + Core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && VesselState.altitudeBottom > AscentSettings.RollAltitude); } } } diff --git a/MechJeb2/MechJebModuleAscentClassicAutopilot.cs b/MechJeb2/MechJebModuleAscentClassicAutopilot.cs index d709c102b..11765a03c 100644 --- a/MechJeb2/MechJebModuleAscentClassicAutopilot.cs +++ b/MechJeb2/MechJebModuleAscentClassicAutopilot.cs @@ -12,16 +12,16 @@ public class MechJebModuleAscentClassicAutopilot : MechJebModuleAscentBaseAutopi private double _actualTurnStart; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { base.OnModuleEnabled(); _mode = AscentMode.VERTICAL_ASCENT; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { base.OnModuleDisabled(); - AscentSettings.enabled = false; + AscentSettings.Enabled = false; } public double VerticalAscentEnd() @@ -88,41 +88,41 @@ protected override bool DriveAscent2() private void DriveVerticalAscent() { - if (!IsVerticalAscent(vesselState.altitudeTrue, vesselState.speedSurface)) _mode = AscentMode.GRAVITY_TURN; - if (orbit.ApA > AscentSettings.DesiredOrbitAltitude) _mode = AscentMode.COAST_TO_APOAPSIS; + if (!IsVerticalAscent(VesselState.altitudeTrue, VesselState.speedSurface)) _mode = AscentMode.GRAVITY_TURN; + if (Orbit.ApA > AscentSettings.DesiredOrbitAltitude) _mode = AscentMode.COAST_TO_APOAPSIS; //during the vertical ascent we just thrust straight up at max throttle AttitudeTo(90); - bool liftedOff = vessel.LiftedOff() && !vessel.Landed; + bool liftedOff = Vessel.LiftedOff() && !Vessel.Landed; - core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && vesselState.altitudeBottom > AscentSettings.RollAltitude); + Core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && VesselState.altitudeBottom > AscentSettings.RollAltitude); - core.Thrust.targetThrottle = 1.0F; + Core.Thrust.targetThrottle = 1.0F; - if (!vessel.LiftedOff() || vessel.Landed) Status = Localizer.Format("#MechJeb_Ascent_status6"); //"Awaiting liftoff" + if (!Vessel.LiftedOff() || Vessel.Landed) Status = Localizer.Format("#MechJeb_Ascent_status6"); //"Awaiting liftoff" else Status = Localizer.Format("#MechJeb_Ascent_status18"); //"Vertical ascent" } private void DriveGravityTurn() { //stop the gravity turn when our apoapsis reaches the desired altitude - if (orbit.ApA > AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA > AscentSettings.DesiredOrbitAltitude) { _mode = AscentMode.COAST_TO_APOAPSIS; return; } //if we've fallen below the turn start altitude, go back to vertical ascent - if (IsVerticalAscent(vesselState.altitudeTrue, vesselState.speedSurface)) + if (IsVerticalAscent(VesselState.altitudeTrue, VesselState.speedSurface)) { _mode = AscentMode.VERTICAL_ASCENT; return; } - core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(orbit.ApR, AscentSettings.DesiredOrbitAltitude + mainBody.Radius); - if (core.Thrust.targetThrottle < 1.0F) + Core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(Orbit.ApR, AscentSettings.DesiredOrbitAltitude + MainBody.Radius); + if (Core.Thrust.targetThrottle < 1.0F) { // follow surface velocity to reduce flipping AttitudeTo(SrfvelPitch()); @@ -130,16 +130,16 @@ private void DriveGravityTurn() return; } - double desiredFlightPathAngle = FlightPathAngle(vesselState.altitudeASL, vesselState.speedSurface) * UtilMath.Deg2Rad; + double desiredFlightPathAngle = FlightPathAngle(VesselState.altitudeASL, VesselState.speedSurface) * UtilMath.Deg2Rad; if (AscentSettings.CorrectiveSteering) { - double actualFlightPathAngle = Math.Atan2(vesselState.speedVertical, vesselState.speedSurfaceHorizontal) * UtilMath.Rad2Deg; + double actualFlightPathAngle = Math.Atan2(VesselState.speedVertical, VesselState.speedSurfaceHorizontal) * UtilMath.Rad2Deg; /* form an isosceles triangle with unit vectors pointing in the desired and actual flight path angle directions and find the length of the base */ double velocityError = 2 * Math.Sin((desiredFlightPathAngle - actualFlightPathAngle) / 2); - double difficulty = vesselState.surfaceVelocity.magnitude * 0.02 / vesselState.ThrustAccel(core.Thrust.targetThrottle); + double difficulty = VesselState.surfaceVelocity.magnitude * 0.02 / VesselState.ThrustAccel(Core.Thrust.targetThrottle); difficulty = MuUtils.Clamp(difficulty, 0.1, 1.0); double steerOffset = AscentSettings.CorrectiveSteeringGain * difficulty * velocityError; @@ -155,37 +155,37 @@ private void DriveGravityTurn() private void DriveCoastToApoapsis() { - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; - if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) + if (VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) { _mode = AscentMode.EXIT; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); return; } //if our apoapsis has fallen too far, resume the gravity turn - if (orbit.ApA < AscentSettings.DesiredOrbitAltitude - 1000.0) + if (Orbit.ApA < AscentSettings.DesiredOrbitAltitude - 1000.0) { _mode = AscentMode.GRAVITY_TURN; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); return; } - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; // follow surface velocity to reduce flipping AttitudeTo(SrfvelPitch()); - if (orbit.ApA < AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA < AscentSettings.DesiredOrbitAltitude) { - core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(orbit.ApR, AscentSettings.DesiredOrbitAltitude + mainBody.Radius); + Core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(Orbit.ApR, AscentSettings.DesiredOrbitAltitude + MainBody.Radius); } - if (core.Node.autowarp) + if (Core.Node.autowarp) { //warp at x2 physical warp: - core.Warp.WarpPhysicsAtRate(2); + Core.Warp.WarpPhysicsAtRate(2); } Status = Localizer.Format("#MechJeb_Ascent_status23"); //"Coasting to edge of atmosphere" diff --git a/MechJeb2/MechJebModuleAscentClassicPathMenu.cs b/MechJeb2/MechJebModuleAscentClassicPathMenu.cs index 0a768b81f..b37941af6 100644 --- a/MechJeb2/MechJebModuleAscentClassicPathMenu.cs +++ b/MechJeb2/MechJebModuleAscentClassicPathMenu.cs @@ -23,9 +23,9 @@ public MechJebModuleAscentClassicPathMenu(MechJebCore core) public override void OnStart(PartModule.StartState state) { - _recorder = core.GetComputerModule(); - _ascentSettings = core.GetComputerModule(); - _path = core.GetComputerModule(); + _recorder = Core.GetComputerModule(); + _ascentSettings = Core.GetComputerModule(); + _path = Core.GetComputerModule(); } public override GUILayoutOption[] WindowOptions() @@ -36,10 +36,10 @@ public override GUILayoutOption[] WindowOptions() protected override void WindowGUI(int windowID) { // ReSharper disable once CompareOfFloatsByEqualityOperator - if (_lastMaxAtmosphereAltitude != mainBody.RealMaxAtmosphereAltitude()) + if (_lastMaxAtmosphereAltitude != MainBody.RealMaxAtmosphereAltitude()) { - _lastMaxAtmosphereAltitude = mainBody.RealMaxAtmosphereAltitude(); - UpdateAtmoTexture(_pathTexture, mainBody, + _lastMaxAtmosphereAltitude = MainBody.RealMaxAtmosphereAltitude(); + UpdateAtmoTexture(_pathTexture, MainBody, _ascentSettings.AutoPath ? _ascentSettings.AutoTurnEndAltitude : _ascentSettings.TurnEndAltitude); } diff --git a/MechJeb2/MechJebModuleAscentGTAutopilot.cs b/MechJeb2/MechJebModuleAscentGTAutopilot.cs index b15b45d03..745608d3c 100644 --- a/MechJeb2/MechJebModuleAscentGTAutopilot.cs +++ b/MechJeb2/MechJebModuleAscentGTAutopilot.cs @@ -14,7 +14,7 @@ public class MechJebModuleAscentGTAutopilot : MechJebModuleAscentBaseAutopilot { public MechJebModuleAscentGTAutopilot(MechJebCore core) : base(core) { } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { base.OnModuleEnabled(); _maxholdAPTime = 0.0F; @@ -71,26 +71,26 @@ protected override bool DriveAscent2() private void DriveVerticalAscent() { - if (!IsVerticalAscent(vesselState.altitudeTrue, vesselState.speedSurface)) _mode = AscentMode.INITIATE_TURN; - if (orbit.ApA > AscentSettings.IntermediateAltitude) _mode = AscentMode.GRAVITY_TURN; + if (!IsVerticalAscent(VesselState.altitudeTrue, VesselState.speedSurface)) _mode = AscentMode.INITIATE_TURN; + if (Orbit.ApA > AscentSettings.IntermediateAltitude) _mode = AscentMode.GRAVITY_TURN; //during the vertical ascent we just thrust straight up at max throttle AttitudeTo(90); - bool liftedOff = vessel.LiftedOff() && !vessel.Landed; + bool liftedOff = Vessel.LiftedOff() && !Vessel.Landed; - core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && vesselState.altitudeBottom > AscentSettings.RollAltitude); + Core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && VesselState.altitudeBottom > AscentSettings.RollAltitude); - core.Thrust.targetThrottle = 1.0F; + Core.Thrust.targetThrottle = 1.0F; - if (!vessel.LiftedOff() || vessel.Landed) Status = Localizer.Format("#MechJeb_Ascent_status6"); //"Awaiting liftoff" + if (!Vessel.LiftedOff() || Vessel.Landed) Status = Localizer.Format("#MechJeb_Ascent_status6"); //"Awaiting liftoff" else Status = Localizer.Format("#MechJeb_Ascent_status18"); //"Vertical ascent" } private void DriveInitiateTurn() { //stop the intermediate "burn" when our apoapsis reaches the desired altitude - if (orbit.ApA > AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA > AscentSettings.DesiredOrbitAltitude) { _mode = AscentMode.COAST_TO_APOAPSIS; return; @@ -102,14 +102,14 @@ private void DriveInitiateTurn() return; } - if (orbit.ApA > AscentSettings.IntermediateAltitude) + if (Orbit.ApA > AscentSettings.IntermediateAltitude) { _mode = AscentMode.GRAVITY_TURN; return; } //if we've fallen below the turn start altitude, go back to vertical ascent - if (IsVerticalAscent(vesselState.altitudeTrue, vesselState.speedSurface)) + if (IsVerticalAscent(VesselState.altitudeTrue, VesselState.speedSurface)) { _mode = AscentMode.VERTICAL_ASCENT; return; @@ -118,8 +118,8 @@ private void DriveInitiateTurn() AttitudeTo(90 - AscentSettings.TurnStartPitch); - core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(orbit.ApR, AscentSettings.IntermediateAltitude + mainBody.Radius); - if (core.Thrust.targetThrottle < 1.0F) + Core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(Orbit.ApR, AscentSettings.IntermediateAltitude + MainBody.Radius); + if (Core.Thrust.targetThrottle < 1.0F) { Status = Localizer.Format("#MechJeb_Ascent_status19"); //"Fine tuning intermediate altitude" return; @@ -131,9 +131,9 @@ private void DriveInitiateTurn() private double FixedTimeToAp() { - if (vessel.orbit.timeToPe < vessel.orbit.timeToAp) - return vessel.orbit.timeToAp - vessel.orbit.period; - return vessel.orbit.timeToAp; + if (Vessel.orbit.timeToPe < Vessel.orbit.timeToAp) + return Vessel.orbit.timeToAp - Vessel.orbit.period; + return Vessel.orbit.timeToAp; } private double _maxholdAPTime; @@ -141,7 +141,7 @@ private double FixedTimeToAp() private void DriveGravityTurn() { //stop the intermediate "burn" when our apoapsis reaches the desired altitude - if (orbit.ApA > AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA > AscentSettings.DesiredOrbitAltitude) { _mode = AscentMode.COAST_TO_APOAPSIS; return; @@ -157,13 +157,13 @@ private void DriveGravityTurn() _maxholdAPTime = Math.Max(_maxholdAPTime, FixedTimeToAp()); // fade pitch from AoA at 90% of intermediateAltitude to 0 at 95% of intermediateAltitude - double pitchfade = MuUtils.Clamp(-20 * vesselState.altitudeASL / AscentSettings.IntermediateAltitude + 19, 0.0, 1.0); + double pitchfade = MuUtils.Clamp(-20 * VesselState.altitudeASL / AscentSettings.IntermediateAltitude + 19, 0.0, 1.0); // srfvelPitch == zero AoA AttitudeTo(SrfvelPitch() * pitchfade); - core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(orbit.ApR, AscentSettings.IntermediateAltitude + mainBody.Radius); - if (core.Thrust.targetThrottle < 1.0F) + Core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(Orbit.ApR, AscentSettings.IntermediateAltitude + MainBody.Radius); + if (Core.Thrust.targetThrottle < 1.0F) { Status = Localizer.Format("#MechJeb_Ascent_status19"); //"Fine tuning intermediate altitude" return; @@ -176,7 +176,7 @@ private void DriveGravityTurn() private void DriveHoldAP() { //stop the intermediate "burn" when our apoapsis reaches the desired altitude - if (orbit.ApA > AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA > AscentSettings.DesiredOrbitAltitude) { _mode = AscentMode.COAST_TO_APOAPSIS; return; @@ -184,7 +184,7 @@ private void DriveHoldAP() // generally this is in response to typing numbers into the intermediate altitude text box and // an accidental transition to later in the state machine - if (orbit.ApA < 0.98 * AscentSettings.IntermediateAltitude) + if (Orbit.ApA < 0.98 * AscentSettings.IntermediateAltitude) { _mode = AscentMode.GRAVITY_TURN; return; @@ -192,46 +192,46 @@ private void DriveHoldAP() AttitudeTo(0); /* FIXME: corrective steering */ - core.Thrust.targetThrottle = FixedTimeToAp() < AscentSettings.HoldAPTime ? 1.0F : 0.1F; + Core.Thrust.targetThrottle = FixedTimeToAp() < AscentSettings.HoldAPTime ? 1.0F : 0.1F; Status = Localizer.Format("#MechJeb_Ascent_status24"); //"Holding AP" } private void DriveCoastToApoapsis() { - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; - if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) + if (VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) { _mode = AscentMode.EXIT; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); return; } //if our apoapsis has fallen too far, resume the gravity turn - if (orbit.ApA < AscentSettings.DesiredOrbitAltitude - 1000.0) + if (Orbit.ApA < AscentSettings.DesiredOrbitAltitude - 1000.0) { _mode = AscentMode.HOLD_AP; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); return; } - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; // follow surface velocity to reduce flipping AttitudeTo(SrfvelPitch()); - if (orbit.ApA < AscentSettings.DesiredOrbitAltitude) + if (Orbit.ApA < AscentSettings.DesiredOrbitAltitude) { - core.Warp.WarpPhysicsAtRate(1); - core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(orbit.ApR, AscentSettings.DesiredOrbitAltitude + mainBody.Radius); + Core.Warp.WarpPhysicsAtRate(1); + Core.Thrust.targetThrottle = ThrottleToRaiseApoapsis(Orbit.ApR, AscentSettings.DesiredOrbitAltitude + MainBody.Radius); } else { - if (core.Node.autowarp) + if (Core.Node.autowarp) { //warp at x2 physical warp: - core.Warp.WarpPhysicsAtRate(2); + Core.Warp.WarpPhysicsAtRate(2); } } diff --git a/MechJeb2/MechJebModuleAscentMenu.cs b/MechJeb2/MechJebModuleAscentMenu.cs index 3129eee66..259025f99 100644 --- a/MechJeb2/MechJebModuleAscentMenu.cs +++ b/MechJeb2/MechJebModuleAscentMenu.cs @@ -49,40 +49,40 @@ private bool _launchingToLan private bool _launchingWithAnyPlaneControl => _launchingToPlane || _launchingToRendezvous || _launchingToMatchLan || _launchingToLan; - private MechJebModuleAscentBaseAutopilot _autopilot => core.Ascent; - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; + private MechJebModuleAscentBaseAutopilot _autopilot => Core.Ascent; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; private MechJebModuleAscentClassicPathMenu _classicPathMenu; private MechJebModuleAscentPVGSettingsMenu _pvgSettingsMenu; private MechJebModuleAscentSettingsMenu _settingsMenu; public override void OnStart(PartModule.StartState state) { - _pvgSettingsMenu = core.GetComputerModule(); - _settingsMenu = core.GetComputerModule(); - _classicPathMenu = core.GetComputerModule(); + _pvgSettingsMenu = Core.GetComputerModule(); + _settingsMenu = Core.GetComputerModule(); + _classicPathMenu = Core.GetComputerModule(); } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private bool _lastPVGSettingsEnabled; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private bool _lastSettingsMenuEnabled; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { - _pvgSettingsMenu.enabled = _lastPVGSettingsEnabled; - _settingsMenu.enabled = _lastSettingsMenuEnabled; + _pvgSettingsMenu.Enabled = _lastPVGSettingsEnabled; + _settingsMenu.Enabled = _lastSettingsMenuEnabled; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { _launchingToPlane = false; _launchingToRendezvous = false; _launchingToMatchLan = false; - _lastPVGSettingsEnabled = _pvgSettingsMenu.enabled; - _lastSettingsMenuEnabled = _settingsMenu.enabled; - _pvgSettingsMenu.enabled = false; - _settingsMenu.enabled = false; + _lastPVGSettingsEnabled = _pvgSettingsMenu.Enabled; + _lastSettingsMenuEnabled = _settingsMenu.Enabled; + _pvgSettingsMenu.Enabled = false; + _settingsMenu.Enabled = false; } private static GUIStyle _btNormal, _btActive; @@ -111,10 +111,10 @@ private void VisibleSectionsGUIElements() Profiler.BeginSample("MJ.GUIWindow.TopButtons"); GUILayout.BeginVertical(GUI.skin.box); - if (_autopilot.enabled && GUILayout.Button(CachedLocalizer.Instance.MechJeb_Ascent_button1)) //Disengage autopilot - _autopilot.users.Remove(this); - else if (!_autopilot.enabled && GUILayout.Button(CachedLocalizer.Instance.MechJeb_Ascent_button2)) //Engage autopilot - _autopilot.users.Add(this); + if (_autopilot.Enabled && GUILayout.Button(CachedLocalizer.Instance.MechJeb_Ascent_button1)) //Disengage autopilot + _autopilot.Users.Remove(this); + else if (!_autopilot.Enabled && GUILayout.Button(CachedLocalizer.Instance.MechJeb_Ascent_button2)) //Engage autopilot + _autopilot.Users.Add(this); GUILayout.EndVertical(); Profiler.EndSample(); } @@ -162,10 +162,10 @@ private void ShowTargetingGUIElements() GuiUtils.SimpleTextBox(CachedLocalizer.Instance.MechJeb_Ascent_label6, _ascentSettings.DesiredInclination, "º", 75, GuiUtils.skin.label, false); //Orbit inc. if (GUILayout.Button(CachedLocalizer.Instance.MechJeb_Ascent_button13, GuiUtils.ExpandWidth(false))) //Current - _ascentSettings.DesiredInclination.val = Math.Round(vesselState.latitude, 3); + _ascentSettings.DesiredInclination.val = Math.Round(VesselState.latitude, 3); GUILayout.EndHorizontal(); - double delta = Math.Abs(vesselState.latitude) - Math.Abs(_ascentSettings.DesiredInclination); + double delta = Math.Abs(VesselState.latitude) - Math.Abs(_ascentSettings.DesiredInclination); if (2.001 < delta) GUILayout.Label(Localizer.Format("#MechJeb_Ascent_label7", delta), GuiUtils.redLabel); //inc {0:F1}º below current latitude @@ -206,11 +206,11 @@ private void ShowStatusGUIElements() { GUILayout.BeginVertical(GUI.skin.box); - if (core.Guidance.Solution != null) + if (Core.Guidance.Solution != null) { - Solution solution = core.Guidance.Solution; + Solution solution = Core.Guidance.Solution; for (int i = solution.Segments - 1; i >= 0; i--) - GUILayout.Label($"{PhaseString(solution, vesselState.time, i)}"); + GUILayout.Label($"{PhaseString(solution, VesselState.time, i)}"); GUILayout.Label(solution.TerminalString()); } @@ -224,9 +224,9 @@ private void ShowStatusGUIElements() GUILayout.Label(pitch, GuiUtils.LayoutWidth(100)); GUILayout.EndHorizontal(); GUIStyle si; - if (core.Guidance.IsStable()) + if (Core.Guidance.IsStable()) si = GuiUtils.greenLabel; - else if (core.Guidance.IsInitializing() || core.Guidance.Status == PVGStatus.FINISHED) + else if (Core.Guidance.IsInitializing() || Core.Guidance.Status == PVGStatus.FINISHED) si = GuiUtils.orangeLabel; else si = GuiUtils.redLabel; @@ -240,7 +240,7 @@ private void ShowStatusGUIElements() GUILayout.Label(n, GuiUtils.LayoutWidth(90)); GUILayout.Label(znorm); GUILayout.EndHorizontal(); - if (core.Glueball.Exception != null) + if (Core.Glueball.Exception != null) { GUILayout.Label(label30, GuiUtils.redLabel); //LAST FAILURE: } @@ -254,16 +254,16 @@ private void ShowStatusGUIElements() private void ShowAutoWarpGUIElements() { - if (!vessel.LandedOrSplashed) return; + if (!Vessel.LandedOrSplashed) return; const int LAN_WIDTH = 60; Profiler.BeginSample("MJ.GUIWindow.ShowAutoWarp"); GUILayout.BeginVertical(GUI.skin.box); - if (core.Node.autowarp) + if (Core.Node.autowarp) GuiUtils.SimpleTextBox(CachedLocalizer.Instance.MechJeb_Ascent_label33, _ascentSettings.WarpCountDown, "s", 35); //Launch countdown: - bool targetExists = core.Target.NormalTargetExists; + bool targetExists = Core.Target.NormalTargetExists; if (!_launchingWithAnyPlaneControl && !targetExists) { _launchingToPlane = _launchingToRendezvous = _launchingToMatchLan = false; @@ -278,9 +278,9 @@ private void ShowAutoWarpGUIElements() width: 40)) //Launch to rendezvous: { _launchingToRendezvous = true; - _autopilot.StartCountdown(vesselState.time + + _autopilot.StartCountdown(VesselState.time + TimeToPhaseAngle(_ascentSettings.LaunchPhaseAngle, - mainBody, vesselState.longitude, core.Target.TargetOrbit)); + MainBody, VesselState.longitude, Core.Target.TargetOrbit)); } //Launch into plane of target @@ -289,13 +289,13 @@ private void ShowAutoWarpGUIElements() { _launchingToPlane = true; (double timeToPlane, double inclination) = Maths.MinimumTimeToPlane( - mainBody.rotationPeriod, - vesselState.latitude, - vesselState.celestialLongitude, - core.Target.TargetOrbit.LAN - _ascentSettings.LaunchLANDifference, - core.Target.TargetOrbit.inclination + MainBody.rotationPeriod, + VesselState.latitude, + VesselState.celestialLongitude, + Core.Target.TargetOrbit.LAN - _ascentSettings.LaunchLANDifference, + Core.Target.TargetOrbit.inclination ); - _autopilot.StartCountdown(vesselState.time + timeToPlane); + _autopilot.StartCountdown(VesselState.time + timeToPlane); _ascentSettings.DesiredInclination.val = inclination; } @@ -306,12 +306,12 @@ private void ShowAutoWarpGUIElements() "º", width: LAN_WIDTH)) //Launch to target LAN { _launchingToMatchLan = true; - _autopilot.StartCountdown(vesselState.time + + _autopilot.StartCountdown(VesselState.time + Maths.TimeToPlane( - mainBody.rotationPeriod, - vesselState.latitude, - vesselState.celestialLongitude, - core.Target.TargetOrbit.LAN - _ascentSettings.LaunchLANDifference, + MainBody.rotationPeriod, + VesselState.latitude, + VesselState.celestialLongitude, + Core.Target.TargetOrbit.LAN - _ascentSettings.LaunchLANDifference, _ascentSettings.DesiredInclination ) ); @@ -324,11 +324,11 @@ private void ShowAutoWarpGUIElements() width: LAN_WIDTH)) //Launch to LAN { _launchingToLan = true; - _autopilot.StartCountdown(vesselState.time + + _autopilot.StartCountdown(VesselState.time + Maths.TimeToPlane( - mainBody.rotationPeriod, - vesselState.latitude, - vesselState.celestialLongitude, + MainBody.rotationPeriod, + VesselState.latitude, + VesselState.celestialLongitude, _ascentSettings.DesiredLan, _ascentSettings.DesiredInclination ) @@ -352,7 +352,7 @@ private void ShowAutoWarpGUIElements() private string vgo, heading, tgo, pitch, label26, label27, label28, n, label29, znorm, label30, launchTimer, autopilotStatus; private TimeSpan _refreshInterval = TimeSpan.FromSeconds(0.1); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableInt _refreshRate = 10; private void UpdateStrings() @@ -362,25 +362,25 @@ private void UpdateStrings() _lastRefresh = now; Profiler.BeginSample("MJ.GUIWindow.UpdateStrings.StringOps"); - vgo = $"vgo: {core.Guidance.VGO:F1}"; - heading = $"heading: {core.Guidance.Heading:F1}"; - tgo = $"tgo: {core.Guidance.Tgo:F3}"; - pitch = $"pitch: {core.Guidance.Pitch:F1}"; - label26 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label26}{core.Guidance.Status}"; - label27 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label27}{core.Glueball.SuccessfulConverges}"; - label28 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label28}{core.Glueball.LastLmStatus}"; - n = $"n: {core.Glueball.LastLmIterations}({core.Glueball.MaxLmIterations})"; - label29 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label29} {GuiUtils.TimeToDHMS(core.Glueball.Staleness)}"; - znorm = $"znorm: {core.Glueball.LastZnorm:G5}"; - if (core.Glueball.Exception != null) - label30 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label30}{core.Glueball.Exception.Message}"; + vgo = $"vgo: {Core.Guidance.VGO:F1}"; + heading = $"heading: {Core.Guidance.Heading:F1}"; + tgo = $"tgo: {Core.Guidance.Tgo:F3}"; + pitch = $"pitch: {Core.Guidance.Pitch:F1}"; + label26 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label26}{Core.Guidance.Status}"; + label27 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label27}{Core.Glueball.SuccessfulConverges}"; + label28 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label28}{Core.Glueball.LastLmStatus}"; + n = $"n: {Core.Glueball.LastLmIterations}({Core.Glueball.MaxLmIterations})"; + label29 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label29} {GuiUtils.TimeToDHMS(Core.Glueball.Staleness)}"; + znorm = $"znorm: {Core.Glueball.LastZnorm:G5}"; + if (Core.Glueball.Exception != null) + label30 = $"{CachedLocalizer.Instance.MechJeb_Ascent_label30}{Core.Glueball.Exception.Message}"; if (_launchingToPlane) launchTimer = CachedLocalizer.Instance.MechJeb_Ascent_msg2; //Launching to target plane else if (_launchingToRendezvous) launchTimer = CachedLocalizer.Instance.MechJeb_Ascent_msg3; //Launching to rendezvous else if (_launchingToMatchLan) launchTimer = CachedLocalizer.Instance.MechJeb_Ascent_LaunchingToTargetLAN; //Launching to target LAN else if (_launchingToLan) launchTimer = CachedLocalizer.Instance.MechJeb_Ascent_LaunchingToManualLAN; //Launching to manual LAN else launchTimer = string.Empty; - if (_autopilot.TMinus > 3 * vesselState.deltaT) + if (_autopilot.TMinus > 3 * VesselState.deltaT) launchTimer += $": T-{GuiUtils.TimeToDHMS(_autopilot.TMinus, 1)}"; autopilotStatus = CachedLocalizer.Instance.MechJeb_Ascent_label35 + _autopilot.Status; @@ -413,24 +413,25 @@ protected override void WindowGUI(int windowID) GUILayout.BeginVertical(GUI.skin.box); GUILayout.BeginHorizontal(); - _settingsMenu.enabled = GUILayout.Toggle(_settingsMenu.enabled, "Ascent Settings"); + _settingsMenu.Enabled = GUILayout.Toggle(_settingsMenu.Enabled, "Ascent Settings"); if (_ascentSettings.AscentType == AscentType.PVG) { - core.StageStats.RequestUpdate(this); - _pvgSettingsMenu.enabled = GUILayout.Toggle(_pvgSettingsMenu.enabled, "PVG Settings"); + Core.StageStats.RequestUpdate(this); + _pvgSettingsMenu.Enabled = GUILayout.Toggle(_pvgSettingsMenu.Enabled, "PVG Settings"); } + GUILayout.EndHorizontal(); GUILayout.EndVertical(); ShowStatusGUIElements(); ShowAutoWarpGUIElements(); - if (_autopilot.enabled) GUILayout.Label(autopilotStatus); //Autopilot status: - if (core.DeactivateControl) + if (_autopilot.Enabled) GUILayout.Label(autopilotStatus); //Autopilot status: + if (Core.DeactivateControl) GUILayout.Label(CachedLocalizer.Instance.MechJeb_Ascent_label36, GuiUtils.redLabel); //CONTROL DISABLED (AVIONICS) - if (!vessel.patchedConicsUnlocked() && _ascentSettings.AscentType != AscentType.PVG) + if (!Vessel.patchedConicsUnlocked() && _ascentSettings.AscentType != AscentType.PVG) { GUILayout.Label(CachedLocalizer.Instance .MechJeb_Ascent_label37); //"Warning: MechJeb is unable to circularize without an upgraded Tracking Station." @@ -450,8 +451,8 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); if (_ascentSettings.AscentType == AscentType.CLASSIC) - _classicPathMenu.enabled = - GUILayout.Toggle(_classicPathMenu.enabled, CachedLocalizer.Instance.MechJeb_Ascent_checkbox10); //Edit ascent path + _classicPathMenu.Enabled = + GUILayout.Toggle(_classicPathMenu.Enabled, CachedLocalizer.Instance.MechJeb_Ascent_checkbox10); //Edit ascent path RefreshRateGUI(); @@ -505,8 +506,8 @@ private string PhaseString(Solution solution, double t, int n) int kspStage = solution.KSPStage(n); - if (kspStage < core.StageStats.vacStats.Length) - stageDeltaV = core.StageStats.vacStats[kspStage].DeltaV; + if (kspStage < Core.StageStats.vacStats.Length) + stageDeltaV = Core.StageStats.vacStats[kspStage].DeltaV; double excessDV = stageDeltaV - solution.DV(t, n); diff --git a/MechJeb2/MechJebModuleAscentPVGAutopilot.cs b/MechJeb2/MechJebModuleAscentPVGAutopilot.cs index dc849fa2d..7af8ae307 100644 --- a/MechJeb2/MechJebModuleAscentPVGAutopilot.cs +++ b/MechJeb2/MechJebModuleAscentPVGAutopilot.cs @@ -15,21 +15,21 @@ public MechJebModuleAscentPVGAutopilot(MechJebCore core) : base(core) { } - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { base.OnModuleEnabled(); _mode = AscentMode.VERTICAL_ASCENT; - core.Guidance.enabled = true; - core.Glueball.enabled = true; + Core.Guidance.Enabled = true; + Core.Glueball.Enabled = true; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { base.OnModuleDisabled(); - core.Guidance.enabled = false; - core.Glueball.enabled = false; + Core.Guidance.Enabled = false; + Core.Glueball.Enabled = false; } private enum AscentMode @@ -46,13 +46,13 @@ private enum AscentMode protected override void TimedLaunchHook() { // timedLaunch kills the optimizer so re-enable it here - core.Guidance.enabled = true; + Core.Guidance.Enabled = true; } protected override bool DriveAscent2() { SetTarget(); - core.Guidance.AssertStart(); + Core.Guidance.AssertStart(); switch (_mode) { case AscentMode.VERTICAL_ASCENT: @@ -77,16 +77,16 @@ protected override bool DriveAscent2() private void SetTarget() { - double peR = mainBody.Radius + AscentSettings.DesiredOrbitAltitude; - double apR = mainBody.Radius + AscentSettings.DesiredApoapsis; + double peR = MainBody.Radius + AscentSettings.DesiredOrbitAltitude; + double apR = MainBody.Radius + AscentSettings.DesiredApoapsis; if (_ascentSettings.DesiredApoapsis < 0) apR = _ascentSettings.DesiredApoapsis; - double attR = mainBody.Radius + + double attR = MainBody.Radius + (AscentSettings.OptimizeStage < 0 ? AscentSettings.DesiredAttachAltFixed : AscentSettings.DesiredAttachAlt); bool lanflag = _ascentSettings.LaunchingToPlane || _ascentSettings.LaunchingToMatchLan || _ascentSettings.LaunchingToLan; double lan = _ascentSettings.LaunchingToPlane || _ascentSettings.LaunchingToMatchLan - ? core.Target.TargetOrbit.LAN + ? Core.Target.TargetOrbit.LAN : (double)AscentSettings.DesiredLan; double inclination = AscentSettings.DesiredInclination; @@ -95,10 +95,10 @@ private void SetTarget() // if we are launchingToPlane other code in MJ fixes the sign of the inclination to be correct // FIXME: can we just use autopilot.desiredInclination here and rely on the other code to update that value? if (_ascentSettings.LaunchingToPlane) - inclination = Math.Sign(inclination) * core.Target.TargetOrbit.inclination; + inclination = Math.Sign(inclination) * Core.Target.TargetOrbit.inclination; // FIXME: kinda need to break this up it is getting very magical with all the non-obvious ignored combinations of options - core.Glueball.SetTarget(peR, apR, attR, inclination, lan, AscentSettings.DesiredFPA, attachAltFlag, lanflag); + Core.Glueball.SetTarget(peR, apR, attR, inclination, lan, AscentSettings.DesiredFPA, attachAltFlag, lanflag); } private double _pitchStartTime; @@ -106,12 +106,12 @@ private void SetTarget() private void DriveVerticalAscent() { //during the vertical ascent we just thrust straight up at max throttle - AttitudeTo(90, core.Guidance.Heading); + AttitudeTo(90, Core.Guidance.Heading); - bool liftedOff = vessel.LiftedOff() && !vessel.Landed && vesselState.altitudeBottom > 5; + bool liftedOff = Vessel.LiftedOff() && !Vessel.Landed && VesselState.altitudeBottom > 5; - core.Attitude.SetActuationControl(liftedOff, liftedOff, liftedOff); - core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && vesselState.altitudeBottom > AscentSettings.RollAltitude); + Core.Attitude.SetActuationControl(liftedOff, liftedOff, liftedOff); + Core.Attitude.SetAxisControl(liftedOff, liftedOff, liftedOff && VesselState.altitudeBottom > AscentSettings.RollAltitude); if (!liftedOff) { @@ -119,14 +119,14 @@ private void DriveVerticalAscent() } else { - if (vesselState.surfaceVelocity.magnitude > AscentSettings.PitchStartVelocity) + if (VesselState.surfaceVelocity.magnitude > AscentSettings.PitchStartVelocity) { _mode = AscentMode.PITCHPROGRAM; _pitchStartTime = MET; return; } - double dv = AscentSettings.PitchStartVelocity - vesselState.surfaceVelocity.magnitude; + double dv = AscentSettings.PitchStartVelocity - VesselState.surfaceVelocity.magnitude; Status = Localizer.Format("#MechJeb_Ascent_status13", string.Format("{0:F2}", dv)); //Vertical ascent <<1>>m/s to go } } @@ -138,14 +138,14 @@ private void DrivePitchProgram() double pitch = 90 - theta; // we need to initiate by at least 3 degrees, then transition to zerolift when srfvel catches up - if (vesselState.currentPitch > SrfvelPitch() && vesselState.currentPitch < 87) + if (VesselState.currentPitch > SrfvelPitch() && VesselState.currentPitch < 87) { _mode = AscentMode.ZEROLIFT; return; } if (!AscentSettings.StagingTriggerFlag) - Status = Localizer.Format("#MechJeb_Ascent_status15", $"{pitch - core.Guidance.Pitch:F}"); //Pitch program <<1>>° to guidance + Status = Localizer.Format("#MechJeb_Ascent_status15", $"{pitch - Core.Guidance.Pitch:F}"); //Pitch program <<1>>° to guidance else Status = $"Pitch Program until stage {AscentSettings.StagingTrigger.val}"; @@ -155,25 +155,25 @@ private void DrivePitchProgram() return; } - AttitudeTo(pitch, core.Guidance.Heading); + AttitudeTo(pitch, Core.Guidance.Heading); } private bool CheckForGuidanceTransition(double pitch) { - if (!mainBody.atmosphere) return true; + if (!MainBody.atmosphere) return true; if (!AscentSettings.StagingTriggerFlag) { - if (pitch <= core.Guidance.Pitch && core.Guidance.IsStable()) return true; + if (pitch <= Core.Guidance.Pitch && Core.Guidance.IsStable()) return true; // dynamic pressure needs to fall by 10% before we level trigger - if (vesselState.maxDynamicPressure > vesselState.dynamicPressure * 1.1) - if (vesselState.dynamicPressure < AscentSettings.DynamicPressureTrigger) + if (VesselState.maxDynamicPressure > VesselState.dynamicPressure * 1.1) + if (VesselState.dynamicPressure < AscentSettings.DynamicPressureTrigger) return true; } else { - if (core.Guidance.IsStable() && vessel.currentStage <= AscentSettings.StagingTrigger) return true; + if (Core.Guidance.IsStable() && Vessel.currentStage <= AscentSettings.StagingTrigger) return true; } return false; @@ -184,7 +184,7 @@ private void DriveZeroLift() double pitch = SrfvelPitch(); if (!AscentSettings.StagingTriggerFlag) - Status = Localizer.Format("#MechJeb_Ascent_status14", $"{pitch - core.Guidance.Pitch:F}"); //Gravity Turn <<1>>° to guidance + Status = Localizer.Format("#MechJeb_Ascent_status14", $"{pitch - Core.Guidance.Pitch:F}"); //Gravity Turn <<1>>° to guidance else Status = $"Gravity Turn until stage {AscentSettings.StagingTrigger.val}"; @@ -194,27 +194,27 @@ private void DriveZeroLift() return; } - AttitudeTo(pitch, core.Guidance.Heading); + AttitudeTo(pitch, Core.Guidance.Heading); } private void DriveGuidance() { - if (core.Guidance.Status == PVGStatus.FINISHED) + if (Core.Guidance.Status == PVGStatus.FINISHED) { _mode = AscentMode.EXIT; return; } - if (!core.Guidance.IsStable()) + if (!Core.Guidance.IsStable()) { - double pitch = Math.Min(Math.Min(90, SrfvelPitch()), vesselState.vesselPitch); + double pitch = Math.Min(Math.Min(90, SrfvelPitch()), VesselState.vesselPitch); AttitudeTo(pitch, SrfvelHeading()); Status = Localizer.Format("#MechJeb_Ascent_status16"); //"WARNING: Unstable Guidance" } else { Status = Localizer.Format("#MechJeb_Ascent_status17"); //"Stable Guidance" - AttitudeTo(core.Guidance.Pitch, core.Guidance.Heading); + AttitudeTo(Core.Guidance.Pitch, Core.Guidance.Heading); } } } diff --git a/MechJeb2/MechJebModuleAscentPVGSettingsMenu.cs b/MechJeb2/MechJebModuleAscentPVGSettingsMenu.cs index bef95571e..55bf8f783 100644 --- a/MechJeb2/MechJebModuleAscentPVGSettingsMenu.cs +++ b/MechJeb2/MechJebModuleAscentPVGSettingsMenu.cs @@ -12,7 +12,7 @@ public MechJebModuleAscentPVGSettingsMenu(MechJebCore core) : base(core) hidden = true; } - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; private static GUIStyle _btNormal; private static GUIStyle _btActive; @@ -47,16 +47,16 @@ protected override void WindowGUI(int windowID) int topstage = -1; - if (_ascentSettings.LastStage < core.StageStats.vacStats.Length && core.StageStats.vacStats.Length > 0) + if (_ascentSettings.LastStage < Core.StageStats.vacStats.Length && Core.StageStats.vacStats.Length > 0) { GUILayout.BeginVertical(GUI.skin.box); - _ascentSettings.LastStage.val = Clamp(_ascentSettings.LastStage.val, 0, core.StageStats.vacStats.Length - 1); + _ascentSettings.LastStage.val = Clamp(_ascentSettings.LastStage.val, 0, Core.StageStats.vacStats.Length - 1); - for (int i = _ascentSettings.LastStage; i < core.StageStats.vacStats.Length; i++) + for (int i = _ascentSettings.LastStage; i < Core.StageStats.vacStats.Length; i++) { - FuelFlowSimulation.FuelStats stats = core.StageStats.vacStats[i]; + FuelFlowSimulation.FuelStats stats = Core.StageStats.vacStats[i]; if (stats.DeltaV < _ascentSettings.MinDeltaV.val) continue; @@ -96,7 +96,7 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); //GuiUtils.SimpleTextBox("Max Coast: ", _ascentSettings.MaxCoast, "s", width: 60); GuiUtils.ToggledTextBox(ref _ascentSettings.FixedCoast, "Fixed Coast Length:", _ascentSettings.FixedCoastLength, "s", width: 40); - GuiUtils.SimpleTextBox("Ullage lead time: ", core.Guidance.UllageLeadTime, "s", 60); + GuiUtils.SimpleTextBox("Ullage lead time: ", Core.Guidance.UllageLeadTime, "s", 60); GUILayout.EndVertical(); GUILayout.BeginVertical(GUI.skin.box); @@ -126,7 +126,7 @@ protected override void WindowGUI(int windowID) GuiUtils.yellowLabel); //Qα limit is recommended to be 1000 to 4000 Pa-rad } - core.Guidance.ShouldDrawTrajectory = GUILayout.Toggle(core.Guidance.ShouldDrawTrajectory, "Draw Trajectory on Map"); + Core.Guidance.ShouldDrawTrajectory = GUILayout.Toggle(Core.Guidance.ShouldDrawTrajectory, "Draw Trajectory on Map"); GUILayout.EndVertical(); base.WindowGUI(windowID); diff --git a/MechJeb2/MechJebModuleAscentSettings.cs b/MechJeb2/MechJebModuleAscentSettings.cs index 561e54872..529d76add 100644 --- a/MechJeb2/MechJebModuleAscentSettings.cs +++ b/MechJeb2/MechJebModuleAscentSettings.cs @@ -14,52 +14,52 @@ public MechJebModuleAscentSettings(MechJebCore core) : base(core) { } - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble PitchStartVelocity = new EditableDouble(PITCH_START_VELOCITY_DEFAULT); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble PitchRate = new EditableDouble(PITCH_RATE_DEFAULT); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DesiredApoapsis = new EditableDoubleMult(0, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DesiredAttachAlt = new EditableDoubleMult(DESIRED_ATTACH_ALT_DEFAULT, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DesiredAttachAltFixed = new EditableDoubleMult(DESIRED_ATTACH_ALT_DEFAULT, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DesiredFPA = new EditableDoubleMult(DESIRED_FPA_DEFAULT, PI / 180); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DynamicPressureTrigger = new EditableDoubleMult(DYNAMIC_PRESSURE_TRIGGER_DEFAULT, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableInt StagingTrigger = new EditableInt(1); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool AttachAltFlag = ATTACH_ALT_FLAG_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool StagingTriggerFlag = STAGING_TRIGGER_FLAG_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult TurnStartAltitude = new EditableDoubleMult(500, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult TurnStartVelocity = new EditableDoubleMult(50); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult TurnStartPitch = new EditableDoubleMult(25); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult IntermediateAltitude = new EditableDoubleMult(45000, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult HoldAPTime = new EditableDoubleMult(1); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private int _ascentTypeInteger; public AscentType AscentType @@ -74,43 +74,43 @@ public AscentType AscentType public MechJebModuleAscentBaseAutopilot AscentAutopilot => GetAscentModule(AscentType); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult DesiredOrbitAltitude = new EditableDoubleMult(100000, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble DesiredInclination = new EditableDouble(0.0); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble DesiredLan = new EditableDouble(0.0); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool CorrectiveSteering = false; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble CorrectiveSteeringGain = 0.6; //control gain - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool ForceRoll = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble VerticalRoll = new EditableDouble(0); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble TurnRoll = new EditableDouble(0); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool AutodeploySolarPanels = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool AutoDeployAntennas = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool SkipCircularization = false; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble RollAltitude = new EditableDouble(50); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] private bool _autostage = true; public bool Autostage @@ -121,146 +121,146 @@ public bool Autostage bool changed = value != _autostage; _autostage = value; if (!changed) return; - if (_autostage && enabled) + if (_autostage && Enabled) { - core.Staging.users.Add(this); + Core.Staging.Users.Add(this); } else if (!_autostage) { - core.Staging.users.Remove(this); + Core.Staging.Users.Remove(this); } } } /* classic AoA limter */ - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool LimitAoA = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble MaxAoA = 5; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult AOALimitFadeoutPressure = new EditableDoubleMult(2500); - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool LimitingAoA = false; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble LimitQa = new EditableDouble(LIMIT_QA_DEFAULT); - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool LimitQaEnabled = LIMIT_QA_ENABLED_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble LaunchPhaseAngle = LAUNCH_PHASE_ANGLE_DEFAULT; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableDouble LaunchLANDifference = LAUNCH_LAN_DIFFERENCE; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public readonly EditableInt WarpCountDown = 11; /* * "Classic" ascent path settings */ - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult TurnEndAltitude = new EditableDoubleMult(60000, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble TurnEndAngle = 0; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult TurnShapeExponent = new EditableDoubleMult(0.4, 0.01); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool AutoPath = true; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public float AutoTurnPerc = 0.05f; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public float AutoTurnSpdFactor = 18.5f; public double AutoTurnStartAltitude => - vessel.mainBody.atmosphere ? vessel.mainBody.RealMaxAtmosphereAltitude() * AutoTurnPerc : vessel.terrainAltitude + 25; + Vessel.mainBody.atmosphere ? Vessel.mainBody.RealMaxAtmosphereAltitude() * AutoTurnPerc : Vessel.terrainAltitude + 25; - public double AutoTurnStartVelocity => vessel.mainBody.atmosphere + public double AutoTurnStartVelocity => Vessel.mainBody.atmosphere ? AutoTurnSpdFactor * AutoTurnSpdFactor * AutoTurnSpdFactor * 0.015625f : double.PositiveInfinity; public double AutoTurnEndAltitude => - vessel.mainBody.atmosphere - ? Math.Min(vessel.mainBody.RealMaxAtmosphereAltitude() * 0.85, DesiredOrbitAltitude) + Vessel.mainBody.atmosphere + ? Math.Min(Vessel.mainBody.RealMaxAtmosphereAltitude() * 0.85, DesiredOrbitAltitude) : Math.Min(30000, DesiredOrbitAltitude * 0.85); /* * PVG Staging values */ - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble MinDeltaV = MIN_DELTAV_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble MaxCoast = MAX_COAST_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble MinCoast = MIN_COAST_DEFAULT; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool CoastBeforeFlag = false; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool FixedCoast = FIXED_COAST_DEFAULT; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble FixedCoastLength = FIXED_COAST_LENGTH_DEFAULT; // deliberately not in the UI or in global, edit the ship file with an editor - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableDouble PreStageTime = PRE_STAGE_TIME_DEFAULT; // deliberately not in the UI or in global, edit the ship file with an editor - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableDouble OptimizerPauseTime = OPTIMIZER_PAUSE_TIME_DEFAULT; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableInt LastStage = -1; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableInt CoastStageInternal = -1; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool CoastStageFlag; public int CoastStage => CoastStageFlag ? CoastStageInternal.val : -1; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool OptimizeStageFlag = true; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableInt OptimizeStageInternal = -1; public int OptimizeStage => OptimizeStageFlag ? OptimizeStageInternal.val : -1; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool SpinupStageFlag = true; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableInt SpinupStageInternal = -1; public int SpinupStage => SpinupStageFlag ? SpinupStageInternal.val : -1; - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableDouble SpinupLeadTime = 50; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDoubleMult SpinupAngularVelocity = new EditableDoubleMult(TAU / 6.0, TAU / 60.0); - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public readonly EditableIntList UnguidedStagesInternal = new EditableIntList(); - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool UnguidedStagesFlag; private readonly List _emptyList = new List(); @@ -287,13 +287,13 @@ private MechJebModuleAscentBaseAutopilot GetAscentModule(AscentType type) switch (type) { case AscentType.CLASSIC: - return core.GetComputerModule(); + return Core.GetComputerModule(); case AscentType.GRAVITYTURN: - return core.GetComputerModule(); + return Core.GetComputerModule(); case AscentType.PVG: - return core.GetComputerModule(); + return Core.GetComputerModule(); default: - return core.GetComputerModule(); + return Core.GetComputerModule(); } } @@ -301,7 +301,7 @@ private void DisableAscentModules() { foreach (AscentType type in _values) if (type != AscentType) - GetAscentModule(type).enabled = false; + GetAscentModule(type).Enabled = false; } public override void OnFixedUpdate() @@ -342,40 +342,40 @@ public void ApplyRODefaults() if (DesiredOrbitAltitude.val < 145000) DesiredOrbitAltitude.val = 145000; - if (Math.Abs(DesiredInclination.val) < Math.Abs(vesselState.latitude)) - DesiredInclination.val = Math.Round(vesselState.latitude, 3); + if (Math.Abs(DesiredInclination.val) < Math.Abs(VesselState.latitude)) + DesiredInclination.val = Math.Round(VesselState.latitude, 3); - if (Math.Abs(DesiredInclination.val) > 180 - Math.Abs(vesselState.latitude)) - DesiredInclination.val = 180 - Math.Round(vesselState.latitude, 3); + if (Math.Abs(DesiredInclination.val) > 180 - Math.Abs(VesselState.latitude)) + DesiredInclination.val = 180 - Math.Round(VesselState.latitude, 3); - core.Guidance.UllageLeadTime.val = 20; + Core.Guidance.UllageLeadTime.val = 20; - core.Settings.rssMode = true; + Core.Settings.rssMode = true; /* set the thrust controller to sane RO/RSS defaults */ - core.Thrust.limitToPreventUnstableIgnition = false; - core.Thrust.autoRCSUllaging = true; - core.Thrust.minThrottle.val = 0.05; - core.Thrust.limiterMinThrottle = true; - core.Thrust.limitThrottle = false; - core.Thrust.limitAcceleration = false; - core.Thrust.limitToPreventOverheats = false; - core.Thrust.limitDynamicPressure = false; - core.Thrust.maxDynamicPressure.val = 20000; + Core.Thrust.limitToPreventUnstableIgnition = false; + Core.Thrust.autoRCSUllaging = true; + Core.Thrust.minThrottle.val = 0.05; + Core.Thrust.limiterMinThrottle = true; + Core.Thrust.limitThrottle = false; + Core.Thrust.limitAcceleration = false; + Core.Thrust.limitToPreventOverheats = false; + Core.Thrust.limitDynamicPressure = false; + Core.Thrust.maxDynamicPressure.val = 20000; /* reset all of the staging controller, and turn on hotstaging and drop solids */ Autostage = true; - core.Staging.autostagePreDelay.val = 0.0; - core.Staging.autostagePostDelay.val = 0.5; - core.Staging.autostageLimit.val = 0; - core.Staging.fairingMaxDynamicPressure.val = 5000; - core.Staging.fairingMinAltitude.val = 50000; - core.Staging.clampAutoStageThrustPct.val = 0.99; - core.Staging.fairingMaxAerothermalFlux.val = 1135; - core.Staging.hotStaging = true; - core.Staging.hotStagingLeadTime.val = 1.0; - core.Staging.dropSolids = true; - core.Staging.dropSolidsLeadTime.val = 1.0; + Core.Staging.autostagePreDelay.val = 0.0; + Core.Staging.autostagePostDelay.val = 0.5; + Core.Staging.autostageLimit.val = 0; + Core.Staging.fairingMaxDynamicPressure.val = 5000; + Core.Staging.fairingMinAltitude.val = 50000; + Core.Staging.clampAutoStageThrustPct.val = 0.99; + Core.Staging.fairingMaxAerothermalFlux.val = 1135; + Core.Staging.hotStaging = true; + Core.Staging.hotStagingLeadTime.val = 1.0; + Core.Staging.dropSolids = true; + Core.Staging.dropSolidsLeadTime.val = 1.0; } private const double LAUNCH_LAN_DIFFERENCE = 0; diff --git a/MechJeb2/MechJebModuleAscentSettingsMenu.cs b/MechJeb2/MechJebModuleAscentSettingsMenu.cs index 901efc2bd..dd65580da 100644 --- a/MechJeb2/MechJebModuleAscentSettingsMenu.cs +++ b/MechJeb2/MechJebModuleAscentSettingsMenu.cs @@ -12,8 +12,8 @@ public MechJebModuleAscentSettingsMenu(MechJebCore core) : base(core) hidden = true; } - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; - private MechJebModuleAscentBaseAutopilot _autopilot => core.Ascent; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; + private MechJebModuleAscentBaseAutopilot _autopilot => Core.Ascent; private readonly string _climbString = $"{CachedLocalizer.Instance.MechJeb_Ascent_label22}: "; private readonly string _turnString = $"{CachedLocalizer.Instance.MechJeb_Ascent_label23}: "; @@ -23,18 +23,18 @@ private void ShowAscentSettingsGUIElements() Profiler.BeginSample("MJ.GUIWindow.AscentItems"); GUILayout.BeginVertical(GUI.skin.box); - core.Thrust.LimitToPreventOverheatsInfoItem(); - core.Thrust.LimitToMaxDynamicPressureInfoItem(); - core.Thrust.LimitAccelerationInfoItem(); - if (_ascentSettings.AscentType != AscentType.PVG) core.Thrust.LimitThrottleInfoItem(); - core.Thrust.LimiterMinThrottleInfoItem(); - if (_ascentSettings.AscentType != AscentType.PVG) core.Thrust.LimitElectricInfoItem(); + Core.Thrust.LimitToPreventOverheatsInfoItem(); + Core.Thrust.LimitToMaxDynamicPressureInfoItem(); + Core.Thrust.LimitAccelerationInfoItem(); + if (_ascentSettings.AscentType != AscentType.PVG) Core.Thrust.LimitThrottleInfoItem(); + Core.Thrust.LimiterMinThrottleInfoItem(); + if (_ascentSettings.AscentType != AscentType.PVG) Core.Thrust.LimitElectricInfoItem(); if (_ascentSettings.AscentType == AscentType.PVG) { - core.Thrust.limitThrottle = false; - core.Thrust.limitToTerminalVelocity = false; - core.Thrust.electricThrottle = false; + Core.Thrust.limitThrottle = false; + Core.Thrust.limitToTerminalVelocity = false; + Core.Thrust.electricThrottle = false; } _ascentSettings.ForceRoll = GUILayout.Toggle(_ascentSettings.ForceRoll, CachedLocalizer.Instance.MechJeb_Ascent_checkbox2); //Force Roll @@ -60,7 +60,7 @@ private void ShowAscentSettingsGUIElements() { GUILayout.BeginHorizontal(); GUILayout.Space(25); - GUIStyle sl = _ascentSettings.LimitingAoA && vesselState.dynamicPressure < _ascentSettings.AOALimitFadeoutPressure + GUIStyle sl = _ascentSettings.LimitingAoA && VesselState.dynamicPressure < _ascentSettings.AOALimitFadeoutPressure ? GuiUtils.greenLabel : GuiUtils.skin.label; GuiUtils.SimpleTextBox(CachedLocalizer.Instance.MechJeb_Ascent_label24, _ascentSettings.AOALimitFadeoutPressure, "Pa", 50, @@ -85,7 +85,7 @@ private void ShowAscentSettingsGUIElements() } _ascentSettings.Autostage = GUILayout.Toggle(_ascentSettings.Autostage, CachedLocalizer.Instance.MechJeb_Ascent_checkbox5); //Autostage - if (_ascentSettings.Autostage) core.Staging.AutostageSettingsInfoItem(); + if (_ascentSettings.Autostage) Core.Staging.AutostageSettingsInfoItem(); _ascentSettings.AutodeploySolarPanels = GUILayout.Toggle(_ascentSettings.AutodeploySolarPanels, CachedLocalizer.Instance.MechJeb_Ascent_checkbox6); //Auto-deploy solar panels @@ -93,7 +93,7 @@ private void ShowAscentSettingsGUIElements() GUILayout.Toggle(_ascentSettings.AutoDeployAntennas, CachedLocalizer.Instance.MechJeb_Ascent_checkbox7); //Auto-deploy antennas GUILayout.BeginHorizontal(); - core.Node.autowarp = GUILayout.Toggle(core.Node.autowarp, CachedLocalizer.Instance.MechJeb_Ascent_checkbox8); //Auto-warp + Core.Node.autowarp = GUILayout.Toggle(Core.Node.autowarp, CachedLocalizer.Instance.MechJeb_Ascent_checkbox8); //Auto-warp if (_ascentSettings.AscentType != AscentType.PVG) { _ascentSettings.SkipCircularization = @@ -108,7 +108,7 @@ private void ShowAscentSettingsGUIElements() GUILayout.EndHorizontal(); if (_ascentSettings.AscentType == AscentType.PVG) - core.Settings.rssMode = GUILayout.Toggle(core.Settings.rssMode, "Module disabling does not kill throttle"); + Core.Settings.rssMode = GUILayout.Toggle(Core.Settings.rssMode, "Module disabling does not kill throttle"); GUILayout.EndVertical(); Profiler.EndSample(); diff --git a/MechJeb2/MechJebModuleAttitudeAdjustment.cs b/MechJeb2/MechJebModuleAttitudeAdjustment.cs index a691663b0..2a2f20455 100644 --- a/MechJeb2/MechJebModuleAttitudeAdjustment.cs +++ b/MechJeb2/MechJebModuleAttitudeAdjustment.cs @@ -7,7 +7,7 @@ namespace MuMech [UsedImplicitly] public class MechJebModuleAttitudeAdjustment : DisplayModule { - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showInfos; public MechJebModuleAttitudeAdjustment(MechJebCore core) : base(core) { } @@ -18,9 +18,9 @@ protected override void WindowGUI(int windowID) //core.GetComputerModule().registry.Find(i => i.id == "Toggle:AttitudeController.useSAS").DrawItem(); - core.Attitude.RCS_auto = GUILayout.Toggle(core.Attitude.RCS_auto, Localizer.Format("#MechJeb_AttitudeAdjust_checkbox1")); //RCS auto mode + Core.Attitude.RCS_auto = GUILayout.Toggle(Core.Attitude.RCS_auto, Localizer.Format("#MechJeb_AttitudeAdjust_checkbox1")); //RCS auto mode - int currentController = core.Attitude.activeController; + int currentController = Core.Attitude.activeController; if (GUILayout.Toggle(currentController == 0, Localizer.Format("#MechJeb_AttitudeAdjust_checkbox2"))) //MJAttitudeController { currentController = 0; @@ -44,13 +44,13 @@ protected override void WindowGUI(int windowID) GUILayout.BeginHorizontal(); GUILayout.Space(20); GUILayout.BeginVertical(); - core.Attitude.Controller.GUI(); + Core.Attitude.Controller.GUI(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); - if (currentController != core.Attitude.activeController) + if (currentController != Core.Attitude.activeController) { - core.Attitude.SetActiveController(currentController); + Core.Attitude.SetActiveController(currentController); } showInfos = GUILayout.Toggle(showInfos, Localizer.Format("#MechJeb_AttitudeAdjust_checkbox5")); //Show Numbers @@ -58,23 +58,23 @@ protected override void WindowGUI(int windowID) { GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label1"), GUILayout.ExpandWidth(true)); //Axis Control - GUILayout.Label(MuUtils.PrettyPrint(core.Attitude.AxisControl, "F0"), GUILayout.ExpandWidth(false)); + GUILayout.Label(MuUtils.PrettyPrint(Core.Attitude.AxisControl, "F0"), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label2"), GUILayout.ExpandWidth(true)); //Torque - GUILayout.Label("|" + core.Attitude.torque.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(core.Attitude.torque), + GUILayout.Label("|" + Core.Attitude.torque.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(Core.Attitude.torque), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label3"), GUILayout.ExpandWidth(true)); //torqueReactionSpeed GUILayout.Label( - "|" + vesselState.torqueReactionSpeed.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(vesselState.torqueReactionSpeed), + "|" + VesselState.torqueReactionSpeed.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(VesselState.torqueReactionSpeed), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); - var ratio = Vector3d.Scale(vesselState.MoI, core.Attitude.torque.InvertNoNaN()); + var ratio = Vector3d.Scale(VesselState.MoI, Core.Attitude.torque.InvertNoNaN()); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label4"), GUILayout.ExpandWidth(true)); //MOI / torque @@ -83,20 +83,20 @@ protected override void WindowGUI(int windowID) GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label5"), GUILayout.ExpandWidth(true)); //MOI - GUILayout.Label("|" + vesselState.MoI.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(vesselState.MoI), + GUILayout.Label("|" + VesselState.MoI.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(VesselState.MoI), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label6"), GUILayout.ExpandWidth(true)); //Angular Velocity - GUILayout.Label("|" + vessel.angularVelocity.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(vessel.angularVelocity), + GUILayout.Label("|" + Vessel.angularVelocity.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(Vessel.angularVelocity), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_AttitudeAdjust_Label7"), GUILayout.ExpandWidth(true)); //"Angular M" GUILayout.Label( - "|" + vesselState.angularMomentum.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(vesselState.angularMomentum), + "|" + VesselState.angularMomentum.magnitude.ToString("F3") + "| " + MuUtils.PrettyPrint(VesselState.angularMomentum), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); @@ -107,7 +107,7 @@ protected override void WindowGUI(int windowID) } - MechJebModuleDebugArrows arrows = core.GetComputerModule(); + MechJebModuleDebugArrows arrows = Core.GetComputerModule(); GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_AttitudeAdjust_Label9"), arrows.arrowsLength, "", 50); //Arrows length diff --git a/MechJeb2/MechJebModuleAttitudeController.cs b/MechJeb2/MechJebModuleAttitudeController.cs index f4a1e4862..9b49466c0 100644 --- a/MechJeb2/MechJebModuleAttitudeController.cs +++ b/MechJeb2/MechJebModuleAttitudeController.cs @@ -33,7 +33,7 @@ public class MechJebModuleAttitudeController : ComputerModule public bool RCS_auto = false; private readonly bool attitudeRCScontrol = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] [ValueInfoItem("#MechJeb_SteeringError", InfoItem.Category.Vessel, format = "F1", units = "º")] //Steering error public MovingAverage steeringError = new MovingAverage(); @@ -51,7 +51,7 @@ public class MechJebModuleAttitudeController : ComputerModule public BaseAttitudeController Controller { get; private set; } private readonly List _controllers = new List(); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int activeController = 3; public void SetActiveController(int i) @@ -61,7 +61,7 @@ public void SetActiveController(int i) Controller.OnStart(); } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { timeCount = 50; SetAxisControl(true, true, true); @@ -115,7 +115,7 @@ private set public MechJebModuleAttitudeController(MechJebCore core) : base(core) { - priority = 800; + Priority = 800; _controllers.Add(new MJAttitudeController(this)); _controllers.Add(new KosAttitudeController(this)); @@ -126,9 +126,9 @@ public MechJebModuleAttitudeController(MechJebCore core) Controller = new BetterController(this); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - if (useSAS) part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); + if (useSAS) Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); Controller.OnModuleDisabled(); } @@ -170,7 +170,7 @@ public Quaternion attitudeGetReferenceRotation(AttitudeReference reference) Vector3 fwd, up; Quaternion rotRef = Quaternion.identity; - if (core.Target.Target == null && (reference == AttitudeReference.TARGET || reference == AttitudeReference.TARGET_ORIENTATION || + if (Core.Target.Target == null && (reference == AttitudeReference.TARGET || reference == AttitudeReference.TARGET_ORIENTATION || reference == AttitudeReference.RELATIVE_VELOCITY)) { attitudeDeactivate(); @@ -178,79 +178,79 @@ public Quaternion attitudeGetReferenceRotation(AttitudeReference reference) } if ((reference == AttitudeReference.MANEUVER_NODE || reference == AttitudeReference.MANEUVER_NODE_COT) && - vessel.patchedConicSolver.maneuverNodes.Count == 0) + Vessel.patchedConicSolver.maneuverNodes.Count == 0) { attitudeDeactivate(); return rotRef; } - Vector3d thrustForward = vesselState.thrustForward; + Vector3d thrustForward = VesselState.thrustForward; // the off-axis thrust modifications get into a fight with the differential throttle so do not use them when diffthrottle is used - if (core.Thrust.differentialThrottle) - thrustForward = vesselState.forward; + if (Core.Thrust.differentialThrottle) + thrustForward = VesselState.forward; switch (reference) { case AttitudeReference.INERTIAL_COT: - rotRef = Quaternion.FromToRotation(thrustForward, vesselState.forward) * rotRef; + rotRef = Quaternion.FromToRotation(thrustForward, VesselState.forward) * rotRef; break; case AttitudeReference.ORBIT: - rotRef = Quaternion.LookRotation(vesselState.orbitalVelocity.normalized, vesselState.up); + rotRef = Quaternion.LookRotation(VesselState.orbitalVelocity.normalized, VesselState.up); break; case AttitudeReference.ORBIT_HORIZONTAL: - rotRef = Quaternion.LookRotation(Vector3d.Exclude(vesselState.up, vesselState.orbitalVelocity.normalized), vesselState.up); + rotRef = Quaternion.LookRotation(Vector3d.Exclude(VesselState.up, VesselState.orbitalVelocity.normalized), VesselState.up); break; case AttitudeReference.SURFACE_NORTH: - rotRef = vesselState.rotationSurface; + rotRef = VesselState.rotationSurface; break; case AttitudeReference.SURFACE_NORTH_COT: - rotRef = vesselState.rotationSurface; - rotRef = Quaternion.FromToRotation(thrustForward, vesselState.forward) * rotRef; + rotRef = VesselState.rotationSurface; + rotRef = Quaternion.FromToRotation(thrustForward, VesselState.forward) * rotRef; break; case AttitudeReference.SURFACE_VELOCITY: - rotRef = Quaternion.LookRotation(vesselState.surfaceVelocity.normalized, vesselState.up); + rotRef = Quaternion.LookRotation(VesselState.surfaceVelocity.normalized, VesselState.up); break; case AttitudeReference.TARGET: - fwd = (core.Target.Position - vessel.GetTransform().position).normalized; - up = Vector3d.Cross(fwd, vesselState.normalPlus); + fwd = (Core.Target.Position - Vessel.GetTransform().position).normalized; + up = Vector3d.Cross(fwd, VesselState.normalPlus); Vector3.OrthoNormalize(ref fwd, ref up); rotRef = Quaternion.LookRotation(fwd, up); break; case AttitudeReference.RELATIVE_VELOCITY: - fwd = core.Target.RelativeVelocity.normalized; - up = Vector3d.Cross(fwd, vesselState.normalPlus); + fwd = Core.Target.RelativeVelocity.normalized; + up = Vector3d.Cross(fwd, VesselState.normalPlus); Vector3.OrthoNormalize(ref fwd, ref up); rotRef = Quaternion.LookRotation(fwd, up); break; case AttitudeReference.TARGET_ORIENTATION: - Transform targetTransform = core.Target.Transform; + Transform targetTransform = Core.Target.Transform; Vector3 targetUp = targetTransform.up; - rotRef = core.Target.CanAlign + rotRef = Core.Target.CanAlign ? Quaternion.LookRotation(targetTransform.forward, targetUp) : Quaternion.LookRotation(targetUp, targetTransform.right); break; case AttitudeReference.MANEUVER_NODE: - fwd = vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit); - up = Vector3d.Cross(fwd, vesselState.normalPlus); + fwd = Vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(Orbit); + up = Vector3d.Cross(fwd, VesselState.normalPlus); Vector3.OrthoNormalize(ref fwd, ref up); rotRef = Quaternion.LookRotation(fwd, up); break; case AttitudeReference.MANEUVER_NODE_COT: - fwd = vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit); - up = Vector3d.Cross(fwd, vesselState.normalPlus); + fwd = Vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(Orbit); + up = Vector3d.Cross(fwd, VesselState.normalPlus); Vector3.OrthoNormalize(ref fwd, ref up); rotRef = Quaternion.LookRotation(fwd, up); - rotRef = Quaternion.FromToRotation(thrustForward, vesselState.forward) * rotRef; + rotRef = Quaternion.FromToRotation(thrustForward, VesselState.forward) * rotRef; break; case AttitudeReference.SUN: - Orbit baseOrbit = vessel.mainBody == Planetarium.fetch.Sun ? vessel.orbit : orbit.TopParentOrbit(); - up = vesselState.CoM - Planetarium.fetch.Sun.transform.position; + Orbit baseOrbit = Vessel.mainBody == Planetarium.fetch.Sun ? Vessel.orbit : Orbit.TopParentOrbit(); + up = VesselState.CoM - Planetarium.fetch.Sun.transform.position; fwd = Vector3d.Cross(-baseOrbit.GetOrbitNormal().xzy.normalized, up); rotRef = Quaternion.LookRotation(fwd, up); break; case AttitudeReference.SURFACE_HORIZONTAL: - rotRef = Quaternion.LookRotation(Vector3d.Exclude(vesselState.up, vesselState.surfaceVelocity.normalized), vesselState.up); + rotRef = Quaternion.LookRotation(Vector3d.Exclude(VesselState.up, VesselState.surfaceVelocity.normalized), VesselState.up); break; } @@ -270,7 +270,7 @@ private Vector3d attitudeReferenceToWorld(Vector3d vector, AttitudeReference ref public void attitudeTo(Quaternion attitude, AttitudeReference reference, object controller, bool AxisCtrlPitch = true, bool AxisCtrlYaw = true, bool AxisCtrlRoll = true) { - users.Add(controller); + Users.Add(controller); attitudeReference = reference; attitudeTarget = attitude; SetAxisControl(AxisCtrlPitch, AxisCtrlYaw, AxisCtrlRoll); @@ -282,8 +282,8 @@ public void attitudeTo(Vector3d direction, AttitudeReference reference, object c Vector3 up, dir = direction; - if (!enabled) - up = attitudeWorldToReference(-vessel.GetTransform().forward, reference); + if (!Enabled) + up = attitudeWorldToReference(-Vessel.GetTransform().forward, reference); else up = attitudeWorldToReference(attitudeReferenceToWorld(attitudeTarget * Vector3d.up, reference), reference); Vector3.OrthoNormalize(ref dir, ref up); @@ -303,21 +303,21 @@ public void attitudeTo(Vector3d direction, AttitudeReference reference, object c public void attitudeDeactivate() { - users.Clear(); + Users.Clear(); attitudeChanged = true; } //angle in degrees between the vessel's current pointing direction and the attitude target, ignoring roll public double attitudeAngleFromTarget() { - return enabled - ? Math.Abs(Vector3d.Angle(attitudeGetReferenceRotation(attitudeReference) * attitudeTarget * Vector3d.forward, vesselState.forward)) + return Enabled + ? Math.Abs(Vector3d.Angle(attitudeGetReferenceRotation(attitudeReference) * attitudeTarget * Vector3d.forward, VesselState.forward)) : 0; } public Vector3d targetAttitude() { - if (enabled) + if (Enabled) return attitudeGetReferenceRotation(attitudeReference) * attitudeTarget * Vector3d.forward; return Vector3d.zero; @@ -330,17 +330,17 @@ public override void OnFixedUpdate() if (useSAS) return; - torque = vesselState.torqueAvailable; - if (core.Thrust.differentialThrottle && - core.Thrust.differentialThrottleSuccess == MechJebModuleThrustController.DifferentialThrottleStatus.Success) - torque += vesselState.torqueDiffThrottle * vessel.ctrlState.mainThrottle / 2.0; + torque = VesselState.torqueAvailable; + if (Core.Thrust.differentialThrottle && + Core.Thrust.differentialThrottleSuccess == MechJebModuleThrustController.DifferentialThrottleStatus.Success) + torque += VesselState.torqueDiffThrottle * Vessel.ctrlState.mainThrottle / 2.0; // Inertia is a bad name. It's the "angular distance to stop" inertia = 0.5 * Vector3d.Scale( - vesselState.angularMomentum.Sign(), + VesselState.angularMomentum.Sign(), Vector3d.Scale( - Vector3d.Scale(vesselState.angularMomentum, vesselState.angularMomentum), - Vector3d.Scale(torque, vesselState.MoI).InvertNoNaN() + Vector3d.Scale(VesselState.angularMomentum, VesselState.angularMomentum), + Vector3d.Scale(torque, VesselState.MoI).InvertNoNaN() ) ); Controller.OnFixedUpdate(); @@ -370,23 +370,23 @@ public override void Drive(FlightCtrlState s) // TODO : This most likely require some love to use all the new SAS magic RequestedAttitude = attitudeGetReferenceRotation(attitudeReference) * attitudeTarget * Quaternion.Euler(90, 0, 0); - if (!part.vessel.ActionGroups[KSPActionGroup.SAS]) + if (!Part.vessel.ActionGroups[KSPActionGroup.SAS]) { - part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); - part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, false); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); + Part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, false); lastSAS = RequestedAttitude; } else if (Quaternion.Angle(lastSAS, RequestedAttitude) > 10) { - part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, false); + Part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, false); lastSAS = RequestedAttitude; } else { - part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, true); + Part.vessel.Autopilot.SAS.SetTargetOrientation(RequestedAttitude * Vector3.up, true); } - core.Thrust.differentialThrottleDemandedTorque = Vector3d.zero; + Core.Thrust.differentialThrottleDemandedTorque = Vector3d.zero; } else { @@ -401,9 +401,9 @@ public override void Drive(FlightCtrlState s) act = new Vector3d(s.pitch, s.roll, s.yaw); // Feed the control torque to the differential throttle - if (core.Thrust.differentialThrottleSuccess == MechJebModuleThrustController.DifferentialThrottleStatus.Success) - core.Thrust.differentialThrottleDemandedTorque = - -Vector3d.Scale(act, vesselState.torqueDiffThrottle * vessel.ctrlState.mainThrottle); + if (Core.Thrust.differentialThrottleSuccess == MechJebModuleThrustController.DifferentialThrottleStatus.Success) + Core.Thrust.differentialThrottleDemandedTorque = + -Vector3d.Scale(act, VesselState.torqueDiffThrottle * Vessel.ctrlState.mainThrottle); } } @@ -415,13 +415,13 @@ private void SetFlightCtrlState(Vector3d act, Vector3d deltaEuler, FlightCtrlSta // Disable the new SAS so it won't interfere. But enable it while in timewarp for compatibility with PersistentRotation if (TimeWarp.WarpMode != TimeWarp.Modes.HIGH || TimeWarp.CurrentRateIndex == 0) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); if (attitudeKILLROT) - if (lastReferencePart != vessel.GetReferenceTransformPart() || userCommandingPitch || userCommandingYaw || userCommandingRoll) + if (lastReferencePart != Vessel.GetReferenceTransformPart() || userCommandingPitch || userCommandingYaw || userCommandingRoll) { - attitudeTo(Quaternion.LookRotation(vessel.GetTransform().up, -vessel.GetTransform().forward), AttitudeReference.INERTIAL, null); - lastReferencePart = vessel.GetReferenceTransformPart(); + attitudeTo(Quaternion.LookRotation(Vessel.GetTransform().up, -Vessel.GetTransform().forward), AttitudeReference.INERTIAL, null); + lastReferencePart = Vessel.GetReferenceTransformPart(); } if (userCommandingPitch) @@ -458,17 +458,17 @@ private void SetFlightCtrlState(Vector3d act, Vector3d deltaEuler, FlightCtrlSta else { if (RCS_auto) - if (attitudeRCScontrol && core.RCS.users.Count == 0) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); + if (attitudeRCScontrol && Core.RCS.Users.Count == 0) + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); } } else if (absErr.x > 1.0 || absErr.y > 1.0 || absErr.z > 1.0) { timeCount = 0; if (RCS_auto && (absErr.x > 3.0 || absErr.y > 3.0 || absErr.z > 3.0) && - core.Thrust.limiter != MechJebModuleThrustController.LimitMode.UnstableIgnition) + Core.Thrust.limiter != MechJebModuleThrustController.LimitMode.UnstableIgnition) if (attitudeRCScontrol) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } } // end of SetFlightCtrlState } diff --git a/MechJeb2/MechJebModuleCustomInfoWindow.cs b/MechJeb2/MechJebModuleCustomInfoWindow.cs index 6210c7cd2..373a84cd3 100644 --- a/MechJeb2/MechJebModuleCustomInfoWindow.cs +++ b/MechJeb2/MechJebModuleCustomInfoWindow.cs @@ -12,14 +12,14 @@ namespace MuMech { public class MechJebModuleCustomInfoWindow : DisplayModule { - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public string title = Localizer.Format("#MechJeb_WindowEd_CustomInfoWindow_title"); //Custom Info Window - [Persistent(collectionIndex = "InfoItem", pass = (int)Pass.Global)] + [Persistent(collectionIndex = "InfoItem", pass = (int)Pass.GLOBAL)] public List items = new List(); [SerializeField] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private bool isCompact; public bool IsCompact @@ -27,15 +27,15 @@ public bool IsCompact get => isCompact; set { - dirty = isCompact != value; + Dirty = isCompact != value; isCompact = value; } } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public Color backgroundColor = new Color(0, 0, 0, 1); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public Color text = new Color(1, 1, 1, 1); public Texture2D background; @@ -46,7 +46,7 @@ public bool IsCompact private DateTime lastRefresh = DateTime.MinValue; [SerializeField] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableInt refreshRate = 10; public void UpdateRefreshRate() @@ -120,10 +120,10 @@ protected override void WindowGUI(int windowID) if (!IsOverlay && GUI.Button(new Rect(10, 0, 13, 20), "E", GuiUtils.yellowOnHover)) { - MechJebModuleCustomWindowEditor editor = core.GetComputerModule(); + MechJebModuleCustomWindowEditor editor = Core.GetComputerModule(); if (editor != null) { - editor.enabled = true; + editor.Enabled = true; editor.editedWindow = this; } } @@ -225,7 +225,7 @@ public class MechJebModuleCustomWindowEditor : DisplayModule public MechJebModuleCustomInfoWindow editedWindow; private int selectedItemIndex = -1; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private InfoItem.Category itemCategory = InfoItem.Category.Orbit; private static readonly string[] categories = Enum.GetNames(typeof(InfoItem.Category)); @@ -241,8 +241,8 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global registry.Clear(); editedWindow = null; - RegisterInfoItems(vesselState); - foreach (ComputerModule m in core.GetComputerModules()) + RegisterInfoItems(VesselState); + foreach (ComputerModule m in Core.GetComputerModules()) { RegisterInfoItems(m); } @@ -253,7 +253,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global ConfigNode[] windowNodes = global.GetNodes(typeof(MechJebModuleCustomInfoWindow).Name); foreach (ConfigNode windowNode in windowNodes) { - var window = new MechJebModuleCustomInfoWindow(core); + var window = new MechJebModuleCustomInfoWindow(Core); ConfigNode.LoadObjectFromConfig(window, windowNode); @@ -268,7 +268,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global window.enabledEditor = loadedEnabled; useOldConfig = false; if (HighLogic.LoadedSceneIsEditor) - window.enabled = loadedEnabled; + window.Enabled = loadedEnabled; } } @@ -280,7 +280,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global window.enabledFlight = loadedEnabled; useOldConfig = false; if (HighLogic.LoadedSceneIsFlight) - window.enabled = loadedEnabled; + window.Enabled = loadedEnabled; } } @@ -291,14 +291,14 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global bool loadedEnabled; if (bool.TryParse(windowNode.GetValue("enabled"), out loadedEnabled)) { - window.enabled = loadedEnabled; - window.enabledEditor = window.enabled; - window.enabledFlight = window.enabled; + window.Enabled = loadedEnabled; + window.enabledEditor = window.Enabled; + window.enabledFlight = window.Enabled; } } - window.enabledEditor = window.enabled; - window.enabledFlight = window.enabled; + window.enabledEditor = window.Enabled; + window.enabledFlight = window.Enabled; } window.items = new List(); @@ -315,7 +315,7 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global } } - core.AddComputerModuleLater(window); + Core.AddComputerModuleLater(window); } } @@ -326,26 +326,26 @@ public override void OnSave(ConfigNode local, ConfigNode type, ConfigNode global //Save custom info windows within our ConfigNode: if (global == null) return; - foreach (MechJebModuleCustomInfoWindow window in core.GetComputerModules()) + foreach (MechJebModuleCustomInfoWindow window in Core.GetComputerModules()) { string name = typeof(MechJebModuleCustomInfoWindow).Name; - var windowNode = ConfigNode.CreateConfigFromObject(window, (int)Pass.Global, null); + var windowNode = ConfigNode.CreateConfigFromObject(window, (int)Pass.GLOBAL, null); if (HighLogic.LoadedSceneIsEditor) - window.enabledEditor = window.enabled; + window.enabledEditor = window.Enabled; if (HighLogic.LoadedSceneIsFlight) - window.enabledFlight = window.enabled; + window.enabledFlight = window.Enabled; windowNode.AddValue("enabledFlight", window.enabledFlight); windowNode.AddValue("enabledEditor", window.enabledEditor); windowNode.CopyTo(global.AddNode(name)); - window.dirty = false; + window.Dirty = false; } } public override void OnStart(PartModule.StartState state) { - editedWindow = core.GetComputerModule(); + editedWindow = Core.GetComputerModule(); } private void RegisterInfoItems(object obj) @@ -369,20 +369,20 @@ private void RegisterInfoItems(object obj) private void AddNewWindow() { - editedWindow = new MechJebModuleCustomInfoWindow(core); + editedWindow = new MechJebModuleCustomInfoWindow(Core); if (HighLogic.LoadedSceneIsEditor) editedWindow.ShowInEditor = true; if (HighLogic.LoadedSceneIsFlight) editedWindow.ShowInFlight = true; - core.AddComputerModule(editedWindow); - editedWindow.enabled = true; - editedWindow.dirty = true; + Core.AddComputerModule(editedWindow); + editedWindow.Enabled = true; + editedWindow.Dirty = true; } private void RemoveCurrentWindow() { if (editedWindow == null) return; - core.RemoveComputerModule(editedWindow); - editedWindow = core.GetComputerModule(); + Core.RemoveComputerModule(editedWindow); + editedWindow = Core.GetComputerModule(); } public override void DrawGUI(bool inEditor) @@ -402,7 +402,7 @@ public override void DrawGUI(bool inEditor) editedWindow.backgroundColor = newColor; editedWindow.background.SetPixel(0, 0, editedWindow.backgroundColor); editedWindow.background.Apply(); - editedWindow.dirty = true; + editedWindow.Dirty = true; } } } @@ -415,7 +415,7 @@ public override void DrawGUI(bool inEditor) if (editedWindow.text != newColor) { editedWindow.text = newColor; - editedWindow.dirty = true; + editedWindow.Dirty = true; } } } @@ -427,7 +427,7 @@ protected override void WindowGUI(int windowID) { GUILayout.BeginVertical(); - if (editedWindow == null) editedWindow = core.GetComputerModule(); + if (editedWindow == null) editedWindow = Core.GetComputerModule(); if (editedWindow == null) { @@ -443,7 +443,7 @@ protected override void WindowGUI(int windowID) if (editedWindow != null) { - List allWindows = core.GetComputerModules(); + List allWindows = Core.GetComputerModules(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_WindowEd_Edtitle"), GUILayout.ExpandWidth(false)); //Title: @@ -455,7 +455,7 @@ protected override void WindowGUI(int windowID) if (editedWindow.title != newTitle) { editedWindow.title = newTitle; - editedWindow.dirty = true; + editedWindow.Dirty = true; } }); editedWindow = (MechJebModuleCustomInfoWindow)allWindows[editedWindowIndex]; @@ -591,15 +591,15 @@ public MechJebModuleCustomWindowEditor(MechJebCore core) public void AddDefaultWindows() { - CreateWindowFromSharingString(CustomWindowPresets.presets[0].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[1].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[2].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[3].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[4].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[5].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[6].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[7].sharingString).enabled = false; - CreateWindowFromSharingString(CustomWindowPresets.presets[10].sharingString).enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[0].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[1].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[2].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[3].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[4].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[5].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[6].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[7].sharingString).Enabled = false; + CreateWindowFromSharingString(CustomWindowPresets.presets[10].sharingString).Enabled = false; } public MechJebModuleCustomInfoWindow CreateWindowFromSharingString(string sharingString) @@ -612,9 +612,9 @@ public MechJebModuleCustomInfoWindow CreateWindowFromSharingString(string sharin return null; } - var window = new MechJebModuleCustomInfoWindow(core); - core.AddComputerModule(window); - window.enabled = true; + var window = new MechJebModuleCustomInfoWindow(Core); + Core.AddComputerModule(window); + window.Enabled = true; window.FromSharingString(lines, registry); diff --git a/MechJeb2/MechJebModuleDebugArrows.cs b/MechJeb2/MechJebModuleDebugArrows.cs index 7ec4d5f97..7947cf5f8 100644 --- a/MechJeb2/MechJebModuleDebugArrows.cs +++ b/MechJeb2/MechJebModuleDebugArrows.cs @@ -10,46 +10,46 @@ namespace MuMech [UsedImplicitly] internal class MechJebModuleDebugArrows : ComputerModule { - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool displayAtCoM; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool seeThrough; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool comSphereActive; public static DebugIcoSphere comSphere; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool colSphereActive; public static DebugIcoSphere colSphere; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool cotSphereActive; public static DebugIcoSphere cotSphere; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble comSphereRadius = new EditableDouble(0.09); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool srfVelocityArrowActive; public static DebugArrow srfVelocityArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool obtVelocityArrowActive; public static DebugArrow obtVelocityArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool dotArrowActive; public static DebugArrow dotArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool forwardArrowActive; public static DebugArrow forwardArrow; @@ -59,17 +59,17 @@ internal class MechJebModuleDebugArrows : ComputerModule //public bool avgForwardArrowActive; //public static DebugArrow avgForwardArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool requestedAttitudeArrowActive; public static DebugArrow requestedAttitudeArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool debugArrowActive; public static DebugArrow debugArrow; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool debugArrow2Active; public static DebugArrow debugArrow2; @@ -77,12 +77,12 @@ internal class MechJebModuleDebugArrows : ComputerModule public static Vector3d debugVector = Vector3d.one; public static Vector3d debugVector2 = Vector3d.one; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble arrowsLength = new EditableDouble(4); public MechJebModuleDebugArrows(MechJebCore core) : base(core) { - enabled = true; + Enabled = true; } public override void OnDestroy() @@ -126,7 +126,7 @@ public override void OnDestroy() // TODO : I should probably use an array and an enum to lower code dup ... public override void OnUpdate() { - if (vessel != FlightGlobals.ActiveVessel) + if (Vessel != FlightGlobals.ActiveVessel) return; if (comSphere == null) @@ -152,63 +152,63 @@ public override void OnUpdate() Vector3d frameVel = - (vesselState.orbitalVelocity - Krakensbane.GetFrameVelocity() - vessel.orbit.GetRotFrameVel(vessel.orbit.referenceBody).xzy) * + (VesselState.orbitalVelocity - Krakensbane.GetFrameVelocity() - Vessel.orbit.GetRotFrameVel(Vessel.orbit.referenceBody).xzy) * Time.fixedDeltaTime; - Vector3d instantCoM = vesselState.CoM + frameVel; + Vector3d instantCoM = VesselState.CoM + frameVel; Vector3 arrowPos = displayAtCoM ? instantCoM - : (Vector3d)vessel.ReferenceTransform.position; + : (Vector3d)Vessel.ReferenceTransform.position; - comSphere.State(comSphereActive && core.ShowGui); + comSphere.State(comSphereActive && Core.ShowGui); if (comSphereActive) { comSphere.Set(instantCoM); comSphere.SetRadius((float)comSphereRadius.val); } - colSphere.State(colSphereActive && vesselState.CoLScalar > 0 && core.ShowGui); + colSphere.State(colSphereActive && VesselState.CoLScalar > 0 && Core.ShowGui); if (colSphereActive) { - colSphere.Set(vesselState.CoL + frameVel); + colSphere.Set(VesselState.CoL + frameVel); colSphere.SetRadius((float)comSphereRadius.val); } - cotSphere.State(cotSphereActive && vesselState.CoTScalar > 0 && core.ShowGui); + cotSphere.State(cotSphereActive && VesselState.CoTScalar > 0 && Core.ShowGui); if (cotSphereActive) { - cotSphere.Set(vesselState.CoT + frameVel); + cotSphere.Set(VesselState.CoT + frameVel); cotSphere.SetRadius((float)comSphereRadius.val); } - srfVelocityArrow.State(srfVelocityArrowActive && core.ShowGui); + srfVelocityArrow.State(srfVelocityArrowActive && Core.ShowGui); if (srfVelocityArrowActive) { - srfVelocityArrow.Set(arrowPos, vessel.srf_velocity); + srfVelocityArrow.Set(arrowPos, Vessel.srf_velocity); srfVelocityArrow.SetLength((float)arrowsLength.val); srfVelocityArrow.SeeThrough(seeThrough); } - obtVelocityArrow.State(obtVelocityArrowActive && core.ShowGui); + obtVelocityArrow.State(obtVelocityArrowActive && Core.ShowGui); if (obtVelocityArrowActive) { - obtVelocityArrow.Set(arrowPos, vessel.obt_velocity); + obtVelocityArrow.Set(arrowPos, Vessel.obt_velocity); obtVelocityArrow.SetLength((float)arrowsLength.val); obtVelocityArrow.SeeThrough(seeThrough); } - dotArrow.State(dotArrowActive && vesselState.thrustCurrent > 0 && core.ShowGui); + dotArrow.State(dotArrowActive && VesselState.thrustCurrent > 0 && Core.ShowGui); if (dotArrowActive) { - dotArrow.Set(vesselState.CoT + frameVel, vesselState.DoT); - dotArrow.SetLength((float)Math.Log10(vesselState.thrustCurrent + 1)); + dotArrow.Set(VesselState.CoT + frameVel, VesselState.DoT); + dotArrow.SetLength((float)Math.Log10(VesselState.thrustCurrent + 1)); dotArrow.SeeThrough(seeThrough); } - forwardArrow.State(forwardArrowActive && core.ShowGui); + forwardArrow.State(forwardArrowActive && Core.ShowGui); if (forwardArrowActive) { - forwardArrow.Set(arrowPos, vessel.GetTransform().up); + forwardArrow.Set(arrowPos, Vessel.GetTransform().up); forwardArrow.SetLength((float)arrowsLength.val); forwardArrow.SeeThrough(seeThrough); } @@ -223,23 +223,23 @@ public override void OnUpdate() } */ - requestedAttitudeArrow.State(requestedAttitudeArrowActive && core.Attitude.enabled && core.ShowGui); - if (requestedAttitudeArrowActive && core.Attitude.enabled) + requestedAttitudeArrow.State(requestedAttitudeArrowActive && Core.Attitude.Enabled && Core.ShowGui); + if (requestedAttitudeArrowActive && Core.Attitude.Enabled) { - requestedAttitudeArrow.Set(arrowPos, core.Attitude.RequestedAttitude); + requestedAttitudeArrow.Set(arrowPos, Core.Attitude.RequestedAttitude); requestedAttitudeArrow.SetLength((float)arrowsLength.val); requestedAttitudeArrow.SeeThrough(seeThrough); } - debugArrow.State(debugArrowActive && core.ShowGui); + debugArrow.State(debugArrowActive && Core.ShowGui); if (debugArrowActive) { - debugArrow.Set(vessel.ReferenceTransform.position, debugVector); + debugArrow.Set(Vessel.ReferenceTransform.position, debugVector); debugArrow.SetLength((float)debugVector.magnitude); debugArrow.SeeThrough(seeThrough); } - debugArrow2.State(debugArrow2Active && core.ShowGui); + debugArrow2.State(debugArrow2Active && Core.ShowGui); if (debugArrow2Active) { //debugArrow2.Set(vessel.ReferenceTransform.position, debugVector2); @@ -247,7 +247,7 @@ public override void OnUpdate() //debugArrow2.SetLength((float)debugVector2.magnitude); //debugArrow2.SeeThrough(seeThrough); - Vector3d vector3d = vesselState.CoL - instantCoM + frameVel; + Vector3d vector3d = VesselState.CoL - instantCoM + frameVel; debugArrow2.Set(instantCoM, vector3d); debugArrow2.SetLength((float)vector3d.magnitude); diff --git a/MechJeb2/MechJebModuleDeployableController.cs b/MechJeb2/MechJebModuleDeployableController.cs index 29991f59a..623e29db2 100644 --- a/MechJeb2/MechJebModuleDeployableController.cs +++ b/MechJeb2/MechJebModuleDeployableController.cs @@ -7,17 +7,17 @@ public abstract class MechJebModuleDeployableController : ComputerModule { public MechJebModuleDeployableController(MechJebCore core) : base(core) { - priority = 200; - enabled = true; + Priority = 200; + Enabled = true; } protected string buttonText; protected bool extended; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autoDeploy = false; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] protected bool prev_shouldDeploy; public bool prev_autoDeploy = true; @@ -29,7 +29,7 @@ public MechJebModuleDeployableController(MechJebCore core) : base(core) protected void DiscoverDeployablePartModules() { cachedPartModules.Clear(); - foreach (Part p in vessel.Parts) + foreach (Part p in Vessel.Parts) foreach (PartModule pm in p.Modules) if (pm != null && pm is ModuleDeployablePart mdp && isModules(mdp)) cachedPartModules.Add(mdp); @@ -64,27 +64,27 @@ public bool AllRetracted() public bool ShouldDeploy() { - if (!mainBody.atmosphere) + if (!MainBody.atmosphere) return true; - if (!vessel.LiftedOff()) + if (!Vessel.LiftedOff()) return false; - if (vessel.LandedOrSplashed) + if (Vessel.LandedOrSplashed) return false; // True adds too many complex case double dt = 10; double min_alt; // minimum altitude between now and now+dt seconds double t = Planetarium.GetUniversalTime(); - double PeT = orbit.NextPeriapsisTime(t) - t; + double PeT = Orbit.NextPeriapsisTime(t) - t; if (PeT > 0 && PeT < dt) - min_alt = orbit.PeA; + min_alt = Orbit.PeA; else - min_alt = Math.Sqrt(Math.Min(orbit.getRelativePositionAtUT(t).sqrMagnitude, orbit.getRelativePositionAtUT(t + dt).sqrMagnitude)) - - mainBody.Radius; + min_alt = Math.Sqrt(Math.Min(Orbit.getRelativePositionAtUT(t).sqrMagnitude, Orbit.getRelativePositionAtUT(t + dt).sqrMagnitude)) - + MainBody.Radius; - if (min_alt > mainBody.RealMaxAtmosphereAltitude()) + if (min_alt > MainBody.RealMaxAtmosphereAltitude()) return true; return false; @@ -93,7 +93,7 @@ public bool ShouldDeploy() public override void OnFixedUpdate() { // Let the ascent guidance handle the solar panels to retract them before launch - if (autoDeploy && !core.Ascent.enabled) + if (autoDeploy && !Core.Ascent.Enabled) { bool tmp = ShouldDeploy(); diff --git a/MechJeb2/MechJebModuleDockingAutopilot.cs b/MechJeb2/MechJebModuleDockingAutopilot.cs index 71ef33ea1..5bcd82df4 100644 --- a/MechJeb2/MechJebModuleDockingAutopilot.cs +++ b/MechJeb2/MechJebModuleDockingAutopilot.cs @@ -10,23 +10,23 @@ public class MechJebModuleDockingAutopilot : ComputerModule { public string status = ""; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] [EditableInfoItem("#MechJeb_DockingSpeedLimit", InfoItem.Category.Thrust, rightLabel = "m/s")] //Docking speed limit public EditableDouble speedLimit = 1; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble rol = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool forceRol = false; [EditableInfoItem("#MechJeb_DockingSpeedLimit", InfoItem.Category.Thrust, rightLabel = "m/s")] //Docking speed limit public EditableDouble overridenSafeDistance = 5; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool overrideSafeDistance = false; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool overrideTargetSize = false; [EditableInfoItem("#MechJeb_DockingSpeedLimit", InfoItem.Category.Thrust, rightLabel = "m/s")] //Docking speed limit @@ -73,14 +73,14 @@ public override void OnStart(PartModule.StartState state) { if (state != PartModule.StartState.None && state != PartModule.StartState.Editor) { - core.AddToPostDrawQueue(DrawBoundingBox); + Core.AddToPostDrawQueue(DrawBoundingBox); // Turn off docking AP on successful docking (in case other checks for successful docking fail) GameEvents.onPartCouple.Add(ev => { if (dockingStep != DockingStep.OFF) { - if (ev.from.vessel == vessel || ev.to.vessel == vessel) + if (ev.from.vessel == Vessel || ev.to.vessel == Vessel) { EndDocking(); } @@ -89,17 +89,17 @@ public override void OnStart(PartModule.StartState state) } } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { - core.RCS.users.Add(this); - core.Attitude.users.Add(this); + Core.RCS.Users.Add(this); + Core.Attitude.Users.Add(this); dockingStep = DockingStep.INIT; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.RCS.users.Remove(this); - core.Attitude.attitudeDeactivate(); + Core.RCS.Users.Remove(this); + Core.Attitude.attitudeDeactivate(); dockingStep = DockingStep.OFF; drawBoundingBox = false; } @@ -121,14 +121,14 @@ private double FixSpeed(double s) // Maximum speed to brake in time = sqrt( 2 * a * d ) private double MaxSpeedForDistance(double distance, Vector3d axis) { - Vector3d localAxis = vessel.ReferenceTransform.InverseTransformDirection(axis); - return FixSpeed(Math.Sqrt(2.0 * Math.Abs(distance) * vesselState.rcsThrustAvailable.GetMagnitude(localAxis) * core.RCS.rcsAccelFactor() / - vesselState.mass)); + Vector3d localAxis = Vessel.ReferenceTransform.InverseTransformDirection(axis); + return FixSpeed(Math.Sqrt(2.0 * Math.Abs(distance) * VesselState.rcsThrustAvailable.GetMagnitude(localAxis) * Core.RCS.rcsAccelFactor() / + VesselState.mass)); } public override void Drive(FlightCtrlState s) { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { EndDocking(); return; @@ -137,7 +137,7 @@ public override void Drive(FlightCtrlState s) if (dockingStep == DockingStep.OFF || dockingStep == DockingStep.INIT) return; - Vector3d targetVel = core.Target.TargetOrbit.GetVel(); + Vector3d targetVel = Core.Target.TargetOrbit.GetVel(); double zApproachSpeed = MaxSpeedForDistance(Math.Max(zSep - acquireRange, 0), -zAxis); double latApproachSpeed = MaxSpeedForDistance(lateralSep.magnitude, -lateralSep); // TODO check if it should be +lateralSep @@ -216,13 +216,13 @@ public override void Drive(FlightCtrlState s) } if (!align) - core.Attitude.attitudeTo(Quaternion.LookRotation(vessel.GetTransform().up, -vessel.GetTransform().forward), + Core.Attitude.attitudeTo(Quaternion.LookRotation(Vessel.GetTransform().up, -Vessel.GetTransform().forward), AttitudeReference.INERTIAL, this); else if (forceRol) - core.Attitude.attitudeTo(Quaternion.LookRotation(Vector3d.back, Vector3d.up) * Quaternion.AngleAxis(-(float)rol, Vector3d.back), + Core.Attitude.attitudeTo(Quaternion.LookRotation(Vector3d.back, Vector3d.up) * Quaternion.AngleAxis(-(float)rol, Vector3d.back), AttitudeReference.TARGET_ORIENTATION, this); else - core.Attitude.attitudeTo(Vector3d.back, AttitudeReference.TARGET_ORIENTATION, this); + Core.Attitude.attitudeTo(Vector3d.back, AttitudeReference.TARGET_ORIENTATION, this); // Purpose of of this section is to compensate for relative velocities because the docking code does poorly with very low speed limits // And can't seem to keep up if relative velocities are greater than the speed limit. @@ -233,14 +233,14 @@ public override void Drive(FlightCtrlState s) Vector3d adjustment = -lateralSep.normalized * latApproachSpeed + zApproachSpeed * zAxis; - core.RCS.SetTargetWorldVelocity(targetVel + adjustment); + Core.RCS.SetTargetWorldVelocity(targetVel + adjustment); MechJebModuleDebugArrows.debugVector = adjustment; - MechJebModuleDebugArrows.debugVector2 = -core.Target.RelativePosition; + MechJebModuleDebugArrows.debugVector2 = -Core.Target.RelativePosition; } public override void OnFixedUpdate() { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { EndDocking(); return; @@ -313,21 +313,21 @@ public override void OnFixedUpdate() private void UpdateDistance() { - Vector3d separation = core.Target.RelativePosition; - zAxis = core.Target.DockingAxis.normalized; + Vector3d separation = Core.Target.RelativePosition; + zAxis = Core.Target.DockingAxis.normalized; zSep = -Vector3d.Dot(separation, zAxis); //positive if we are in front of the target, negative if behind lateralSep = Vector3d.Exclude(zAxis, separation); - relativeZ = Vector3d.Dot(core.Target.RelativeVelocity, zAxis); - relativeLateral = Vector3d.Dot(lateralSep, core.Target.RelativeVelocity); + relativeZ = Vector3d.Dot(Core.Target.RelativeVelocity, zAxis); + relativeLateral = Vector3d.Dot(lateralSep, Core.Target.RelativeVelocity); } private void InitDocking() { - lastTarget = core.Target.Target; + lastTarget = Core.Target.Target; try { - vesselBoundingBox = vessel.GetBoundingBox(); + vesselBoundingBox = Vessel.GetBoundingBox(); targetBoundingBox = lastTarget.GetVessel().GetBoundingBox(); if (!overrideTargetSize) @@ -340,14 +340,14 @@ private void InitDocking() else safeDistance = (float)overridenSafeDistance.val; - if (core.Target.Target is ModuleDockingNode) - acquireRange = ((ModuleDockingNode)core.Target.Target).acquireRange * 0.5; + if (Core.Target.Target is ModuleDockingNode) + acquireRange = ((ModuleDockingNode)Core.Target.Target).acquireRange * 0.5; else acquireRange = 0.25; } catch (Exception e) { - print(e); + Print(e); } if (zSep < 0) //we're behind the target @@ -376,20 +376,20 @@ private void InitDocking() private void EndDocking() { dockingStep = DockingStep.OFF; - users.Clear(); - enabled = false; + Users.Clear(); + Enabled = false; } private void DrawBoundingBox() { - if (drawBoundingBox && vessel == FlightGlobals.ActiveVessel) + if (drawBoundingBox && Vessel == FlightGlobals.ActiveVessel) { - vesselBoundingBox = vessel.GetBoundingBox(); - GLUtils.DrawBoundingBox(vessel.mainBody, vessel, vesselBoundingBox, Color.green); + vesselBoundingBox = Vessel.GetBoundingBox(); + GLUtils.DrawBoundingBox(Vessel.mainBody, Vessel, vesselBoundingBox, Color.green); - if (core.Target.Target != null) + if (Core.Target.Target != null) { - Vessel targetVessel = core.Target.Target.GetVessel(); + Vessel targetVessel = Core.Target.Target.GetVessel(); targetBoundingBox = targetVessel.GetBoundingBox(); GLUtils.DrawBoundingBox(targetVessel.mainBody, targetVessel, targetBoundingBox, Color.blue); } diff --git a/MechJeb2/MechJebModuleDockingGuidance.cs b/MechJeb2/MechJebModuleDockingGuidance.cs index c562bc50a..7dd3398ea 100644 --- a/MechJeb2/MechJebModuleDockingGuidance.cs +++ b/MechJeb2/MechJebModuleDockingGuidance.cs @@ -14,12 +14,12 @@ public class MechJebModuleDockingGuidance : DisplayModule public override void OnStart(PartModule.StartState state) { - autopilot = core.GetComputerModule(); + autopilot = Core.GetComputerModule(); } protected override void WindowGUI(int windowID) { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { GUILayout.Label(Localizer.Format("#MechJeb_Docking_label1")); //"Choose a target to dock with" base.WindowGUI(windowID); @@ -29,23 +29,23 @@ protected override void WindowGUI(int windowID) GUILayout.BeginVertical(); // GetReferenceTransformPart is null after undocking ... - if (vessel.GetReferenceTransformPart() == null || !vessel.GetReferenceTransformPart().Modules.Contains("ModuleDockingNode")) + if (Vessel.GetReferenceTransformPart() == null || !Vessel.GetReferenceTransformPart().Modules.Contains("ModuleDockingNode")) { GUILayout.Label(Localizer.Format("#MechJeb_Docking_label2"), GuiUtils.yellowLabel); //Warning: You need to control the vessel from a docking port. Right click a docking port and select "Control from here" } - if (!(core.Target.Target is ModuleDockingNode)) + if (!(Core.Target.Target is ModuleDockingNode)) { GUILayout.Label(Localizer.Format("#MechJeb_Docking_label3"), GuiUtils.yellowLabel); //Warning: target is not a docking port. Right click the target docking port and select "Set as target" } bool onAxisNodeExists = false; - foreach (ITargetable node in vessel.GetTargetables() + foreach (ITargetable node in Vessel.GetTargetables() .Where(t => t.GetTargetingMode() == VesselTargetModes.DirectionVelocityAndOrientation)) { - if (Vector3d.Angle(node.GetTransform().forward, vessel.ReferenceTransform.up) < 2) + if (Vector3d.Angle(node.GetTransform().forward, Vessel.ReferenceTransform.up) < 2) { onAxisNodeExists = true; break; @@ -58,7 +58,7 @@ protected override void WindowGUI(int windowID) GuiUtils.yellowLabel); //Warning: this vessel is not controlled from a docking node. Right click the desired docking node on this vessel and select "Control from here." } - bool active = GUILayout.Toggle(autopilot.enabled, Localizer.Format("#MechJeb_Docking_checkbox1")); // "Autopilot enabled" + bool active = GUILayout.Toggle(autopilot.Enabled, Localizer.Format("#MechJeb_Docking_checkbox1")); // "Autopilot enabled" GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_Docking_label5"), autopilot.speedLimit, "m/s"); //"Speed limit" autopilot.overrideSafeDistance = @@ -82,11 +82,11 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Docking_button"))) //"Dump Bounding Box Info" { - vessel.GetBoundingBox(true); + Vessel.GetBoundingBox(true); - if (core.Target.Target != null) + if (Core.Target.Target != null) { - Vessel targetVessel = core.Target.Target.GetVessel(); + Vessel targetVessel = Core.Target.Target.GetVessel(); targetVessel.GetBoundingBox(true); } } @@ -109,25 +109,25 @@ protected override void WindowGUI(int windowID) GUILayout.Label("°", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); - if (autopilot.enabled != active) + if (autopilot.Enabled != active) { if (active) { - autopilot.users.Add(this); + autopilot.Users.Add(this); } else { - autopilot.users.Remove(this); + autopilot.Users.Remove(this); } } - if (autopilot.enabled) + if (autopilot.Enabled) { GUILayout.Label(Localizer.Format("#MechJeb_Docking_label9", autopilot.status)); //"Status: <<1>>" - Vector3d error = core.RCS.targetVelocity - vesselState.orbitalVelocity; - double error_x = Vector3d.Dot(error, vessel.GetTransform().right); - double error_y = Vector3d.Dot(error, vessel.GetTransform().forward); - double error_z = Vector3d.Dot(error, vessel.GetTransform().up); + Vector3d error = Core.RCS.targetVelocity - VesselState.orbitalVelocity; + double error_x = Vector3d.Dot(error, Vessel.GetTransform().right); + double error_y = Vector3d.Dot(error, Vessel.GetTransform().forward); + double error_z = Vector3d.Dot(error, Vessel.GetTransform().up); GUILayout.Label(Localizer.Format("#MechJeb_Docking_label10", error_x.ToString("F2")) + " m/s [L/J]"); //Error X: <<1>> GUILayout.Label(Localizer.Format("#MechJeb_Docking_label11", error_y.ToString("F2")) + " m/s [I/K]"); //Error Y: <<1>> GUILayout.Label(Localizer.Format("#MechJeb_Docking_label12", error_z.ToString("F2")) + " m/s [H/N]"); //Error Z: <<1>> @@ -147,9 +147,9 @@ public override GUILayoutOption[] WindowOptions() return new[] { GUILayout.Width(300), GUILayout.Height(50) }; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - if (autopilot != null) autopilot.users.Remove(this); + if (autopilot != null) autopilot.Users.Remove(this); } public override string GetName() diff --git a/MechJeb2/MechJebModuleFlightRecorder.cs b/MechJeb2/MechJebModuleFlightRecorder.cs index 6abbdc2ff..e2bd230ce 100644 --- a/MechJeb2/MechJebModuleFlightRecorder.cs +++ b/MechJeb2/MechJebModuleFlightRecorder.cs @@ -106,25 +106,25 @@ public enum recordType public int historyIdx = -1; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int historySize = 3000; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double precision = 0.2; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool downrange = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool realAtmo = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool stages = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int hSize = 4; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int vSize = 2; private static readonly int typeCount = Enum.GetValues(typeof(recordType)).Length; @@ -134,49 +134,49 @@ public enum recordType private readonly bool paused = false; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MarkUT", InfoItem.Category.Recorder, format = ValueInfoItem.TIME)] //Mark UT public double markUT; [ValueInfoItem("#MechJeb_TimeSinceMark", InfoItem.Category.Recorder, format = ValueInfoItem.TIME)] //Time since mark public double timeSinceMark; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_DVExpended", InfoItem.Category.Recorder, format = "F1", units = "m/s")] //ΔV expended public double deltaVExpended; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_DragLosses", InfoItem.Category.Recorder, format = "F1", units = "m/s")] //Drag losses public double dragLosses; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_GravityLosses", InfoItem.Category.Recorder, format = "F1", units = "m/s")] //Gravity losses public double gravityLosses; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_SteeringLosses", InfoItem.Category.Recorder, format = "F1", units = "m/s")] //Steering losses public double steeringLosses; [ValueInfoItem("#MechJeb_PhaseAngleFromMark", InfoItem.Category.Recorder, format = "F2", units = "º")] //Phase angle from mark public double phaseAngleFromMark; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MarkLAN", InfoItem.Category.Recorder, format = ValueInfoItem.ANGLE_EW)] //Mark LAN public double markLAN; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MarkLatitude", InfoItem.Category.Recorder, format = ValueInfoItem.ANGLE_NS)] //Mark latitude public double markLatitude; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MarkLongitude", InfoItem.Category.Recorder, format = ValueInfoItem.ANGLE_EW)] //Mark longitude public double markLongitude; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MarkAltitudeASL", InfoItem.Category.Recorder, format = ValueInfoItem.SI, units = "m")] //Mark altitude ASL public double markAltitude; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public int markBodyIndex = 1; [ValueInfoItem("#MechJeb_MarkBody", InfoItem.Category.Recorder)] //Mark body @@ -185,7 +185,7 @@ public enum recordType [ValueInfoItem("#MechJeb_DistanceFromMark", InfoItem.Category.Recorder, format = ValueInfoItem.SI, units = "m")] //Distance from mark public double DistanceFromMark() { - return Vector3d.Distance(vesselState.CoM, + return Vector3d.Distance(VesselState.CoM, FlightGlobals.Bodies[markBodyIndex].GetWorldSurfacePosition(markLatitude, markLongitude, markAltitude) - FlightGlobals.Bodies[markBodyIndex].position); } @@ -195,25 +195,25 @@ public double GroundDistanceFromMark() { CelestialBody markBody = FlightGlobals.Bodies[markBodyIndex]; Vector3d markVector = markBody.GetSurfaceNVector(markLatitude, markLongitude); - Vector3d vesselVector = vesselState.CoM - markBody.transform.position; + Vector3d vesselVector = VesselState.CoM - markBody.transform.position; return markBody.Radius * Vector3d.Angle(markVector, vesselVector) * UtilMath.Deg2Rad; } - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] [ValueInfoItem("#MechJeb_MaxDragGees", InfoItem.Category.Recorder, format = "F2")] //Max drag gees public double maxDragGees; [ActionInfoItem("MARK", InfoItem.Category.Recorder)] public void Mark() { - markUT = vesselState.time; + markUT = VesselState.time; deltaVExpended = dragLosses = gravityLosses = steeringLosses = 0; phaseAngleFromMark = 0; - markLatitude = vesselState.latitude; - markLongitude = vesselState.longitude; - markLAN = vesselState.orbitLAN; - markAltitude = vesselState.altitudeASL; - markBodyIndex = FlightGlobals.Bodies.IndexOf(mainBody); + markLatitude = VesselState.latitude; + markLongitude = VesselState.longitude; + markLAN = VesselState.orbitLAN; + markAltitude = VesselState.altitudeASL; + markBodyIndex = FlightGlobals.Bodies.IndexOf(MainBody); maxDragGees = 0; timeSinceMark = 0; for (int t = 0; t < maximums.Length; t++) @@ -229,7 +229,7 @@ public void Mark() public MechJebModuleFlightRecorder(MechJebCore core) : base(core) { - priority = 2000; + Priority = 2000; maximums = new double[typeCount]; minimums = new double[typeCount]; } @@ -238,7 +238,7 @@ public override void OnStart(PartModule.StartState state) { if (history.Length != historySize) history = new record[historySize]; - users.Add(this); //flight recorder should always run. + Users.Add(this); //flight recorder should always run. } private double lastRecordTime; @@ -247,29 +247,29 @@ public override void OnFixedUpdate() { if (markUT == 0) Mark(); - timeSinceMark = vesselState.time - markUT; + timeSinceMark = VesselState.time - markUT; - if (vessel.situation == Vessel.Situations.PRELAUNCH) + if (Vessel.situation == Vessel.Situations.PRELAUNCH) { Mark(); //keep resetting stats until we launch return; } - if (vesselState.currentThrustAccel > 0) + if (VesselState.currentThrustAccel > 0) { - gravityLosses += vesselState.deltaT * Vector3d.Dot(-vesselState.orbitalVelocity.normalized, vesselState.gravityForce); + gravityLosses += VesselState.deltaT * Vector3d.Dot(-VesselState.orbitalVelocity.normalized, VesselState.gravityForce); } - dragLosses += vesselState.deltaT * vesselState.drag; - deltaVExpended += vesselState.deltaT * vesselState.currentThrustAccel; - steeringLosses += vesselState.deltaT * vesselState.currentThrustAccel * - (1 - Vector3d.Dot(vesselState.orbitalVelocity.normalized, vesselState.forward)); + dragLosses += VesselState.deltaT * VesselState.drag; + deltaVExpended += VesselState.deltaT * VesselState.currentThrustAccel; + steeringLosses += VesselState.deltaT * VesselState.currentThrustAccel * + (1 - Vector3d.Dot(VesselState.orbitalVelocity.normalized, VesselState.forward)); - maxDragGees = Math.Max(maxDragGees, vesselState.drag / 9.81); + maxDragGees = Math.Max(maxDragGees, VesselState.drag / 9.81); - double circularPeriod = 2 * Math.PI * vesselState.radius / OrbitalManeuverCalculator.CircularOrbitSpeed(mainBody, vesselState.radius); - double angleTraversed = vesselState.longitude - markLongitude + 360 * (vesselState.time - markUT) / part.vessel.mainBody.rotationPeriod; - phaseAngleFromMark = MuUtils.ClampDegrees360(360 * (vesselState.time - markUT) / circularPeriod - angleTraversed); + double circularPeriod = 2 * Math.PI * VesselState.radius / OrbitalManeuverCalculator.CircularOrbitSpeed(MainBody, VesselState.radius); + double angleTraversed = VesselState.longitude - markLongitude + 360 * (VesselState.time - markUT) / Part.vessel.mainBody.rotationPeriod; + phaseAngleFromMark = MuUtils.ClampDegrees360(360 * (VesselState.time - markUT) / circularPeriod - angleTraversed); if (paused) return; @@ -278,9 +278,9 @@ public override void OnFixedUpdate() //historyIdx = Mathf.Min(Mathf.FloorToInt((float)(timeSinceMark / precision)), history.Length - 1); - if (vesselState.time >= lastRecordTime + precision && historyIdx < history.Length - 1) + if (VesselState.time >= lastRecordTime + precision && historyIdx < history.Length - 1) { - lastRecordTime = vesselState.time; + lastRecordTime = VesselState.time; historyIdx++; Record(historyIdx); //if (TimeWarp.WarpMode == TimeWarp.Modes.HIGH) @@ -295,15 +295,15 @@ public override void OnFixedUpdate() private void Record(int idx) { history[idx].timeSinceMark = timeSinceMark; - history[idx].altitudeASL = vesselState.altitudeASL; + history[idx].altitudeASL = VesselState.altitudeASL; history[idx].downRange = GroundDistanceFromMark(); - history[idx].speedSurface = vesselState.speedSurface; - history[idx].speedOrbital = vesselState.speedOrbital; - history[idx].acceleration = vessel.geeForce; - history[idx].Q = vesselState.dynamicPressure; - history[idx].altitudeTrue = vesselState.altitudeTrue; - history[idx].pitch = vesselState.vesselPitch; - history[idx].mass = vesselState.mass; + history[idx].speedSurface = VesselState.speedSurface; + history[idx].speedOrbital = VesselState.speedOrbital; + history[idx].acceleration = Vessel.geeForce; + history[idx].Q = VesselState.dynamicPressure; + history[idx].altitudeTrue = VesselState.altitudeTrue; + history[idx].pitch = VesselState.vesselPitch; + history[idx].mass = VesselState.mass; history[idx].gravityLosses = gravityLosses; history[idx].dragLosses = dragLosses; history[idx].steeringLosses = steeringLosses; @@ -311,16 +311,16 @@ private void Record(int idx) if (TimeWarp.WarpMode != TimeWarp.Modes.HIGH) { - history[idx].currentStage = vessel.currentStage; + history[idx].currentStage = Vessel.currentStage; } else { - history[idx].currentStage = idx > 0 ? history[idx - 1].currentStage : vessel.currentStage; + history[idx].currentStage = idx > 0 ? history[idx - 1].currentStage : Vessel.currentStage; } - history[idx].AoA = vesselState.AoA; - history[idx].AoS = vesselState.AoS; - history[idx].AoD = vesselState.displacementAngle; + history[idx].AoA = VesselState.AoA; + history[idx].AoS = VesselState.AoS; + history[idx].AoD = VesselState.displacementAngle; for (int t = 0; t < typeCount; t++) { double current = history[idx][(recordType)t]; @@ -336,7 +336,7 @@ public void DumpCSV() if (!Directory.Exists(exportPath)) Directory.CreateDirectory(exportPath); - string vesselName = vessel != null ? string.Join("_", vessel.vesselName.Split(Path.GetInvalidFileNameChars())) : ""; + string vesselName = Vessel != null ? string.Join("_", Vessel.vesselName.Split(Path.GetInvalidFileNameChars())) : ""; string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); diff --git a/MechJeb2/MechJebModuleFlightRecorderGraph.cs b/MechJeb2/MechJebModuleFlightRecorderGraph.cs index 426aac785..9260634cf 100644 --- a/MechJeb2/MechJebModuleFlightRecorderGraph.cs +++ b/MechJeb2/MechJebModuleFlightRecorderGraph.cs @@ -30,31 +30,31 @@ public void Reset() } } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool downrange = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool realAtmo; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool stages; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int hSize = 4; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int vSize = 2; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autoScale = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int timeScale; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int downrangeScale; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int scaleIdx; public bool ascentPath = false; @@ -81,7 +81,7 @@ public void Reset() public MechJebModuleFlightRecorderGraph(MechJebCore core) : base(core) { - priority = 2000; + Priority = 2000; graphStates = new graphState[typeCount]; } @@ -92,7 +92,7 @@ public override void OnStart(PartModule.StartState state) width = 128 * hSize; height = 128 * vSize; - recorder = core.GetComputerModule(); + recorder = Core.GetComputerModule(); ResetScale(); } @@ -100,7 +100,7 @@ protected override void WindowGUI(int windowID) { //DefaultAscentPath path = (DefaultAscentPath)core.GetComputerModule().ascentPath; - if (oldMainBody != mainBody || lastMaximumAltitude != graphStates[(int)MechJebModuleFlightRecorder.recordType.AltitudeASL].maximum || + if (oldMainBody != MainBody || lastMaximumAltitude != graphStates[(int)MechJebModuleFlightRecorder.recordType.AltitudeASL].maximum || height != backgroundTexture.height) { UpdateScale(); @@ -112,8 +112,8 @@ protected override void WindowGUI(int windowID) backgroundTexture = new Texture2D(1, height); } - MechJebModuleAscentClassicPathMenu.UpdateAtmoTexture(backgroundTexture, vessel.mainBody, lastMaximumAltitude, realAtmo); - oldMainBody = mainBody; + MechJebModuleAscentClassicPathMenu.UpdateAtmoTexture(backgroundTexture, Vessel.mainBody, lastMaximumAltitude, realAtmo); + oldMainBody = MainBody; } GUILayout.BeginVertical(); @@ -226,7 +226,7 @@ protected override void WindowGUI(int windowID) realAtmo = GUILayout.Toggle(realAtmo, Localizer.Format("#MechJeb_Flightrecord_checkbox2"), GUILayout.ExpandWidth(false)); //Real Atmo if (oldRealAtmo != realAtmo) - MechJebModuleAscentClassicPathMenu.UpdateAtmoTexture(backgroundTexture, vessel.mainBody, lastMaximumAltitude, realAtmo); + MechJebModuleAscentClassicPathMenu.UpdateAtmoTexture(backgroundTexture, Vessel.mainBody, lastMaximumAltitude, realAtmo); //GUILayout.Label("", GUILayout.ExpandWidth(true)); GUILayout.FlexibleSpace(); @@ -745,7 +745,7 @@ private void ResetScale() graphStates[(int)MechJebModuleFlightRecorder.recordType.SteeringLosses].minimum = 0; graphStates[(int)MechJebModuleFlightRecorder.recordType.AltitudeASL].maximum = - mainBody != null && mainBody.atmosphere ? mainBody.RealMaxAtmosphereAltitude() : 10000.0; + MainBody != null && MainBody.atmosphere ? MainBody.RealMaxAtmosphereAltitude() : 10000.0; graphStates[(int)MechJebModuleFlightRecorder.recordType.DownRange].maximum = 500; graphStates[(int)MechJebModuleFlightRecorder.recordType.Acceleration].maximum = 2; graphStates[(int)MechJebModuleFlightRecorder.recordType.SpeedSurface].maximum = 300; diff --git a/MechJeb2/MechJebModuleGuidanceController.cs b/MechJeb2/MechJebModuleGuidanceController.cs index ca41ec264..7ce928267 100644 --- a/MechJeb2/MechJebModuleGuidanceController.cs +++ b/MechJeb2/MechJebModuleGuidanceController.cs @@ -24,13 +24,13 @@ public class MechJebModuleGuidanceController : ComputerModule { public MechJebModuleGuidanceController(MechJebCore core) : base(core) { } - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble UllageLeadTime = 20; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool ShouldDrawTrajectory = true; - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; public double Pitch; public double Heading; @@ -46,28 +46,28 @@ public override void OnStart(PartModule.StartState state) { if (state != PartModule.StartState.None && state != PartModule.StartState.Editor) { - core.AddToPostDrawQueue(DrawTrajetory); + Core.AddToPostDrawQueue(DrawTrajetory); } } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { Status = PVGStatus.ENABLED; - core.Attitude.users.Add(this); - core.Thrust.users.Add(this); - core.Spinup.users.Add(this); + Core.Attitude.Users.Add(this); + Core.Thrust.Users.Add(this); + Core.Spinup.Users.Add(this); Solution = null; _allowExecution = false; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Attitude.attitudeDeactivate(); - if (!core.RssMode) - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); - core.Staging.users.Remove(this); - core.Spinup.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + if (!Core.RssMode) + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); + Core.Staging.Users.Remove(this); + Core.Spinup.Users.Remove(this); Solution = null; Status = PVGStatus.FINISHED; } @@ -90,7 +90,7 @@ public override void OnFixedUpdate() Done(); } - if (!enabled || Status == PVGStatus.ENABLED) + if (!Enabled || Status == PVGStatus.ENABLED) return; if (Status == PVGStatus.FINISHED) @@ -112,8 +112,8 @@ private bool WillDoRCSButNotYet() { // We might have wonky transforms and have a tiny bit of fore RCS, so require at least 10% of the max RCS thrust to be // in the pointy direction (which should be "up" / y-axis per KSP/Unity semantics). - bool hasRCS = vessel.hasEnabledRCSModules() && - vesselState.rcsThrustAvailable.up > 0.1 * vesselState.rcsThrustAvailable.MaxMagnitude(); + bool hasRCS = Vessel.hasEnabledRCSModules() && + VesselState.rcsThrustAvailable.up > 0.1 * VesselState.rcsThrustAvailable.MaxMagnitude(); return hasRCS && Status != PVGStatus.TERMINAL_RCS; } @@ -130,7 +130,7 @@ private void HandleTerminal() return; // if we've gone past the last stage we need to just stop - if (vessel.currentStage < _ascentSettings.LastStage) + if (Vessel.currentStage < _ascentSettings.LastStage) { Done(); return; @@ -138,8 +138,8 @@ private void HandleTerminal() // this handles termination of thrust for final stages of "fixed" burntime rockets (due to residuals Tgo may go less than zero so we // wait for natural termination of thrust). no support for RCS terminal trim. - if (_ascentSettings.OptimizeStage < 0 && vessel.currentStage <= _ascentSettings.LastStage && Solution.Tgo(vesselState.time) <= 0 && - vesselState.thrustAvailable == 0) + if (_ascentSettings.OptimizeStage < 0 && Vessel.currentStage <= _ascentSettings.LastStage && Solution.Tgo(VesselState.time) <= 0 && + VesselState.thrustAvailable == 0) { Done(); return; @@ -149,7 +149,7 @@ private void HandleTerminal() // then we have staged, so we need to reset that condition. Otherwise we need to wait for staging. if (Status == PVGStatus.TERMINAL_STAGING) { - if (vessel.currentStage == _ascentSettings.OptimizeStage) + if (Vessel.currentStage == _ascentSettings.OptimizeStage) return; Status = PVGStatus.BURNING; @@ -157,7 +157,7 @@ private void HandleTerminal() // We should either be in an non-upper stage optimized stage, or we should be within 10 seconds of the whole // burntime in order to enter terminal guidance. - if (vessel.currentStage != _ascentSettings.OptimizeStage && Solution.Tgo(vesselState.time) > 10) + if (Vessel.currentStage != _ascentSettings.OptimizeStage && Solution.Tgo(VesselState.time) > 10) return; // The includeCoast: false flag here is to skip a coast which is in the past in the Solution when @@ -169,20 +169,20 @@ private void HandleTerminal() // is in the "past" in the Solution but you're burning down residuals and you don't know when // the stage will actually run out (assuming it isn't a burn before a coast or an optimized burntime // so that we burn past the end of the stage and into whatever residuals are available). - int solutionIndex = Solution.IndexForKSPStage(vessel.currentStage, core.Guidance.IsCoasting()); + int solutionIndex = Solution.IndexForKSPStage(Vessel.currentStage, Core.Guidance.IsCoasting()); if (solutionIndex < 0) return; // Only enter terminal guidance within 10 seconds of the current stage - if (Solution.Tgo(vesselState.time, solutionIndex) > 10) + if (Solution.Tgo(VesselState.time, solutionIndex) > 10) return; if (Status != PVGStatus.TERMINAL_RCS) Status = PVGStatus.TERMINAL; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); - if (Status == PVGStatus.TERMINAL_RCS && !vessel.ActionGroups[KSPActionGroup.RCS]) // if someone manually disables RCS + if (Status == PVGStatus.TERMINAL_RCS && !Vessel.ActionGroups[KSPActionGroup.RCS]) // if someone manually disables RCS { Debug.Log("[MechJebModuleGuidanceController] terminating guidance due to manual deactivation of RCS."); TerminalDone(); @@ -194,11 +194,11 @@ private void HandleTerminal() // bit of a hack to predict velocity + position in the next tick or two // FIXME: what exactly does KSP do to integrate over timesteps? - Vector3d a0 = vessel.acceleration_immediate; + Vector3d a0 = Vessel.acceleration_immediate; double dt = ticks * TimeWarp.fixedDeltaTime; - Vector3d v1 = vesselState.orbitalVelocity + a0 * dt; - Vector3d x1 = vesselState.orbitalPosition + vesselState.orbitalVelocity * dt + 0.5 * a0 * dt * dt; + Vector3d v1 = VesselState.orbitalVelocity + a0 * dt; + Vector3d x1 = VesselState.orbitalPosition + VesselState.orbitalVelocity * dt + 0.5 * a0 * dt * dt; if (Solution.TerminalGuidanceSatisfied(x1.WorldToV3Rotated(), v1.WorldToV3Rotated(), solutionIndex)) { @@ -206,8 +206,8 @@ private void HandleTerminal() { Debug.Log("[MechJebModuleGuidanceController] transition to RCS terminal guidance."); Status = PVGStatus.TERMINAL_RCS; - if (!vessel.ActionGroups[KSPActionGroup.RCS]) - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } else { @@ -219,11 +219,11 @@ private void HandleTerminal() private void HandleSpinup() { - if (vessel.currentStage != _ascentSettings.SpinupStage) + if (Vessel.currentStage != _ascentSettings.SpinupStage) return; - core.Spinup.AssertStart(); - core.Spinup.RollAngularVelocity = _ascentSettings.SpinupAngularVelocity; + Core.Spinup.AssertStart(); + Core.Spinup.RollAngularVelocity = _ascentSettings.SpinupAngularVelocity; } public bool IsTerminal() @@ -299,29 +299,29 @@ private void HandleThrottle() // of autostaging to the top of the rocket. If we don't, then when we cut the engines and do the // RCS trim, autostaging will stage off the spent engine if there's no relights. This is unwanted // since the insertion stage may still have RCS which is necessary to complete the mission. - if (coastStage >= 0 && vessel.currentStage == coastStage && Solution.WillCoast(vesselState.time)) - core.Staging.autostageLimitInternal = coastStage; + if (coastStage >= 0 && Vessel.currentStage == coastStage && Solution.WillCoast(VesselState.time)) + Core.Staging.autostageLimitInternal = coastStage; - if (Solution.Coast(vesselState.time)) + if (Solution.Coast(VesselState.time)) { if (!IsCoasting()) { - StartCoast = vesselState.time; + StartCoast = VesselState.time; // force RCS on at the state transition - if (!vessel.ActionGroups[KSPActionGroup.RCS]) - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } Status = PVGStatus.COASTING; - if (Solution.StageTimeLeft(vesselState.time) < UllageLeadTime) + if (Solution.StageTimeLeft(VesselState.time) < UllageLeadTime) RCSOn(); ThrustOff(); return; } - core.Staging.autostageLimitInternal = Solution.TerminalStage(); + Core.Staging.autostageLimitInternal = Solution.TerminalStage(); ThrottleOn(); @@ -330,9 +330,9 @@ private void HandleThrottle() private bool IsGrounded() { - return vessel.situation == Vessel.Situations.LANDED || - vessel.situation == Vessel.Situations.PRELAUNCH || - vessel.situation == Vessel.Situations.SPLASHED; + return Vessel.situation == Vessel.Situations.LANDED || + Vessel.situation == Vessel.Situations.PRELAUNCH || + Vessel.situation == Vessel.Situations.SPLASHED; } private void UpdatePitchAndHeading() @@ -342,15 +342,15 @@ private void UpdatePitchAndHeading() // if we're not flying yet, continuously update the t0 of the solution if (IsGrounded()) - Solution.T0 = vesselState.time; + Solution.T0 = VesselState.time; if (Status != PVGStatus.TERMINAL_RCS) { - (double pitch, double heading) = Solution.PitchAndHeading(vesselState.time); + (double pitch, double heading) = Solution.PitchAndHeading(VesselState.time); Pitch = Rad2Deg(pitch); Heading = Rad2Deg(heading); - Tgo = Solution.Tgo(vesselState.time); - VGO = Solution.Vgo(vesselState.time); + Tgo = Solution.Tgo(VesselState.time); + VGO = Solution.Vgo(VesselState.time); } /* else leave pitch and heading at the last values, also stop updating vgo/tgo */ } @@ -363,7 +363,7 @@ private void DrawTrajetory() if (Solution == null) return; - if (!enabled) + if (!Enabled) return; if (!MapView.MapIsEnabled) @@ -381,33 +381,33 @@ private void DrawTrajetory() { double t = Solution.T0 + dt * i; - _trajectory.Add(Solution.R(t).V3ToWorldRotated() + mainBody.position); + _trajectory.Add(Solution.R(t).V3ToWorldRotated() + MainBody.position); } - GLUtils.DrawPath(mainBody, _trajectory, Color.red, MapView.MapIsEnabled); + GLUtils.DrawPath(MainBody, _trajectory, Color.red, MapView.MapIsEnabled); Vector3d rf = Planetarium.fetch.rotation * Solution.R(Solution.Tf).ToVector3d().xzy; Vector3d vf = Planetarium.fetch.rotation * Solution.V(Solution.Tf).ToVector3d().xzy; - _finalOrbit.UpdateFromStateVectors(rf.xzy, vf.xzy, mainBody, Solution.Tf); + _finalOrbit.UpdateFromStateVectors(rf.xzy, vf.xzy, MainBody, Solution.Tf); GLUtils.DrawOrbit(_finalOrbit, Color.yellow); } private void ThrottleOn() { - core.Thrust.targetThrottle = 1.0F; + Core.Thrust.targetThrottle = 1.0F; } private void RCSOn() { - core.Thrust.ThrustOff(); - vessel.ctrlState.Z = -1.0F; + Core.Thrust.ThrustOff(); + Vessel.ctrlState.Z = -1.0F; } private void ThrustOff() { - core.Thrust.ThrustOff(); + Core.Thrust.ThrustOff(); } private void TerminalDone() @@ -419,7 +419,7 @@ private void TerminalDone() } // if we still have a coast to do in this stage, start the coast - if (vessel.currentStage == Solution.CoastStage() && Solution.WillCoast(vesselState.time)) + if (Vessel.currentStage == Solution.CoastStage() && Solution.WillCoast(VesselState.time)) { ThrustOff(); Status = PVGStatus.COASTING; @@ -427,9 +427,9 @@ private void TerminalDone() } // if we have more un-optimized upper stages to burn, stage and use the TERMINAL_STAGING state - if (Solution.TerminalStage() != vessel.currentStage) + if (Solution.TerminalStage() != Vessel.currentStage) { - core.Staging.Stage(); + Core.Staging.Stage(); Status = PVGStatus.TERMINAL_STAGING; return; } @@ -440,11 +440,11 @@ private void TerminalDone() private void Done() { - users.Clear(); + Users.Clear(); ThrustOff(); Status = PVGStatus.FINISHED; Solution = null; - enabled = false; + Enabled = false; } public void SetSolution(Solution solution) @@ -462,7 +462,7 @@ public bool HasGoodSolutionWithNoFutureCoast() if (Solution == null) return false; - return !Solution.WillCoast(vesselState.time); + return !Solution.WillCoast(VesselState.time); } } } diff --git a/MechJeb2/MechJebModuleInfoItems.cs b/MechJeb2/MechJebModuleInfoItems.cs index 1d964f985..88c781d1b 100644 --- a/MechJeb2/MechJebModuleInfoItems.cs +++ b/MechJeb2/MechJebModuleInfoItems.cs @@ -23,32 +23,32 @@ public class MechJebModuleInfoItems : ComputerModule //Provides a unified interface for getting the parts list in the editor or in flight: private List parts => HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : - vessel == null ? new List() : vessel.Parts; + Vessel == null ? new List() : Vessel.Parts; [ValueInfoItem("#MechJeb_NodeBurnTime", InfoItem.Category.Misc)] //Node burn time public string NextManeuverNodeBurnTime() { - if (!vessel.patchedConicsUnlocked() || !vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; + if (!Vessel.patchedConicsUnlocked() || !Vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; - ManeuverNode node = vessel.patchedConicSolver.maneuverNodes.First(); - double burnTime = node.GetBurnVector(node.patch).magnitude / vesselState.limitedMaxThrustAccel; + ManeuverNode node = Vessel.patchedConicSolver.maneuverNodes.First(); + double burnTime = node.GetBurnVector(node.patch).magnitude / VesselState.limitedMaxThrustAccel; return GuiUtils.TimeToDHMS(burnTime); } [ValueInfoItem("#MechJeb_TimeToNode", InfoItem.Category.Misc)] //Time to node public string TimeToManeuverNode() { - if (!vessel.patchedConicsUnlocked() || !vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; + if (!Vessel.patchedConicsUnlocked() || !Vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; - return GuiUtils.TimeToDHMS(vessel.patchedConicSolver.maneuverNodes[0].UT - vesselState.time); + return GuiUtils.TimeToDHMS(Vessel.patchedConicSolver.maneuverNodes[0].UT - VesselState.time); } [ValueInfoItem("#MechJeb_NodedV", InfoItem.Category.Misc)] //Node dV public string NextManeuverNodeDeltaV() { - if (!vessel.patchedConicsUnlocked() || !vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; + if (!Vessel.patchedConicsUnlocked() || !Vessel.patchedConicSolver.maneuverNodes.Any()) return "N/A"; - return vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit).magnitude.ToSI() + "m/s"; + return Vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(Orbit).magnitude.ToSI() + "m/s"; } [ValueInfoItem("#MechJeb_SurfaceTWR", InfoItem.Category.Vessel, format = "F2", showInEditor = true)] //Surface TWR @@ -56,37 +56,37 @@ public double SurfaceTWR() { return HighLogic.LoadedSceneIsEditor ? MaxAcceleration() / 9.81 - : vesselState.thrustAvailable / (vesselState.mass * mainBody.GeeASL * 9.81); + : VesselState.thrustAvailable / (VesselState.mass * MainBody.GeeASL * 9.81); } [ValueInfoItem("#MechJeb_LocalTWR", InfoItem.Category.Vessel, format = "F2", showInEditor = false)] //Local TWR public double LocalTWR() { - return vesselState.thrustAvailable / (vesselState.mass * vesselState.gravityForce.magnitude); + return VesselState.thrustAvailable / (VesselState.mass * VesselState.gravityForce.magnitude); } [ValueInfoItem("#MechJeb_ThrottleTWR", InfoItem.Category.Vessel, format = "F2", showInEditor = false)] //Throttle TWR public double ThrottleTWR() { - return vesselState.thrustCurrent / (vesselState.mass * vesselState.gravityForce.magnitude); + return VesselState.thrustCurrent / (VesselState.mass * VesselState.gravityForce.magnitude); } [ValueInfoItem("#MechJeb_AtmosphericPressurePa", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")] //Atmospheric pressure (Pa) public double AtmosphericPressurekPA() { - return FlightGlobals.getStaticPressure(vesselState.CoM) * 1000; + return FlightGlobals.getStaticPressure(VesselState.CoM) * 1000; } [ValueInfoItem("#MechJeb_AtmosphericPressure", InfoItem.Category.Misc, format = "F3", units = "atm")] //Atmospheric pressure public double AtmosphericPressure() { - return FlightGlobals.getStaticPressure(vesselState.CoM) * PhysicsGlobals.KpaToAtmospheres; + return FlightGlobals.getStaticPressure(VesselState.CoM) * PhysicsGlobals.KpaToAtmospheres; } [ValueInfoItem("#MechJeb_Coordinates", InfoItem.Category.Surface)] //Coordinates public string GetCoordinateString() { - return Coordinates.ToStringDMS(vesselState.latitude, vesselState.longitude, true); + return Coordinates.ToStringDMS(VesselState.latitude, VesselState.longitude, true); } public string OrbitSummary(Orbit o) @@ -102,71 +102,71 @@ public string OrbitSummaryWithInclination(Orbit o) [ValueInfoItem("#MechJeb_MeanAnomaly", InfoItem.Category.Orbit, format = ValueInfoItem.ANGLE)] //Mean Anomaly public double MeanAnomaly() { - return orbit.meanAnomaly * UtilMath.Rad2Deg; + return Orbit.meanAnomaly * UtilMath.Rad2Deg; } [ValueInfoItem("#MechJeb_Orbit", InfoItem.Category.Orbit)] //Orbit public string CurrentOrbitSummary() { - return OrbitSummary(orbit); + return OrbitSummary(Orbit); } [ValueInfoItem("#MechJeb_TargetOrbit", InfoItem.Category.Target)] //Target orbit public string TargetOrbitSummary() { - if (!core.Target.NormalTargetExists) return "N/A"; - return OrbitSummary(core.Target.TargetOrbit); + if (!Core.Target.NormalTargetExists) return "N/A"; + return OrbitSummary(Core.Target.TargetOrbit); } [ValueInfoItem("#MechJeb_OrbitWithInc", InfoItem.Category.Orbit, description = "#MechJeb_OrbitWithInc_desc")] //Orbit||Orbit shape w/ inc. public string CurrentOrbitSummaryWithInclination() { - return OrbitSummaryWithInclination(orbit); + return OrbitSummaryWithInclination(Orbit); } [ValueInfoItem("#MechJeb_TargetOrbitWithInc", InfoItem.Category.Target, description = "#MechJeb_TargetOrbitWithInc_desc")] //Target orbit|Target orbit shape w/ inc. public string TargetOrbitSummaryWithInclination() { - if (!core.Target.NormalTargetExists) return "N/A"; - return OrbitSummaryWithInclination(core.Target.TargetOrbit); + if (!Core.Target.NormalTargetExists) return "N/A"; + return OrbitSummaryWithInclination(Core.Target.TargetOrbit); } [ValueInfoItem("#MechJeb_OrbitalEnergy", InfoItem.Category.Orbit, description = "#MechJeb_OrbitalEnergy_desc", format = ValueInfoItem.SI, units = "J/kg")] //Orbital energy||Specific orbital energy public double OrbitalEnergy() { - return orbit.orbitalEnergy; + return Orbit.orbitalEnergy; } [ValueInfoItem("#MechJeb_PotentialEnergy", InfoItem.Category.Orbit, description = "#MechJeb_PotentialEnergy_desc", format = ValueInfoItem.SI, units = "J/kg")] //Potential energy||Specific potential energy public double PotentialEnergy() { - return -orbit.referenceBody.gravParameter / orbit.radius; + return -Orbit.referenceBody.gravParameter / Orbit.radius; } [ValueInfoItem("#MechJeb_KineticEnergy", InfoItem.Category.Orbit, description = "#MechJeb_KineticEnergy_desc", format = ValueInfoItem.SI, units = "J/kg")] //Kinetic energy||Specific kinetic energy public double KineticEnergy() { - return orbit.orbitalEnergy + orbit.referenceBody.gravParameter / orbit.radius; + return Orbit.orbitalEnergy + Orbit.referenceBody.gravParameter / Orbit.radius; } //TODO: consider turning this into a binary search [ValueInfoItem("#MechJeb_TimeToImpact", InfoItem.Category.Misc)] //Time to impact public string TimeToImpact() { - if (orbit.PeA > 0 || vessel.Landed) return "N/A"; + if (Orbit.PeA > 0 || Vessel.Landed) return "N/A"; - double impactTime = vesselState.time; + double impactTime = VesselState.time; try { for (int iter = 0; iter < 10; iter++) { - Vector3d impactPosition = orbit.WorldPositionAtUT(impactTime); - double terrainRadius = mainBody.Radius + mainBody.TerrainAltitude(impactPosition); - impactTime = orbit.NextTimeOfRadius(vesselState.time, terrainRadius); + Vector3d impactPosition = Orbit.WorldPositionAtUT(impactTime); + double terrainRadius = MainBody.Radius + MainBody.TerrainAltitude(impactPosition); + impactTime = Orbit.NextTimeOfRadius(VesselState.time, terrainRadius); } } catch (ArgumentException) @@ -178,7 +178,7 @@ public string TimeToImpact() return GuiUtils.TimeToDHMS(0); } - return GuiUtils.TimeToDHMS(impactTime - vesselState.time); + return GuiUtils.TimeToDHMS(impactTime - VesselState.time); } [ValueInfoItem("#MechJeb_SuicideBurnCountdown", InfoItem.Category.Misc)] //Suicide burn countdown @@ -186,7 +186,7 @@ public string SuicideBurnCountdown() { try { - return GuiUtils.TimeToDHMS(OrbitExtensions.SuicideBurnCountdown(orbit, vesselState, vessel), 1); + return GuiUtils.TimeToDHMS(OrbitExtensions.SuicideBurnCountdown(Orbit, VesselState, Vessel), 1); } catch { @@ -208,9 +208,9 @@ private double RCSThrustNow() { double rcsThrust = 0; - for (int i = 0; i < vessel.parts.Count; i++) + for (int i = 0; i < Vessel.parts.Count; i++) { - Part p = vessel.parts[i]; + Part p = Vessel.parts[i]; foreach (ModuleRCS pm in p.Modules.OfType()) { if (p.Rigidbody == null || !pm.isEnabled || pm.isJustForShow) @@ -247,9 +247,9 @@ public string RCSTranslationEfficiency() direction.Normalize(); - for (int index = 0; index < vessel.parts.Count; index++) + for (int index = 0; index < Vessel.parts.Count; index++) { - Part p = vessel.parts[index]; + Part p = Vessel.parts[index]; foreach (ModuleRCS pm in p.Modules.OfType()) { if (p.Rigidbody == null || !pm.isEnabled || pm.isJustForShow) @@ -259,17 +259,17 @@ public string RCSTranslationEfficiency() // Find our distance from the vessel's center of mass, in // world coordinates. - Vector3 pos = p.Rigidbody.worldCenterOfMass - vesselState.CoM; + Vector3 pos = p.Rigidbody.worldCenterOfMass - VesselState.CoM; // Translate to the vessel's reference frame. - pos = Quaternion.Inverse(vessel.GetTransform().rotation) * pos; + pos = Quaternion.Inverse(Vessel.GetTransform().rotation) * pos; for (int i = 0; i < pm.thrustForces.Length; i++) { float force = pm.thrustForces[i]; Transform t = pm.thrusterTransforms[i]; - Vector3 thrusterDir = Quaternion.Inverse(vessel.GetTransform().rotation) * -t.up; + Vector3 thrusterDir = Quaternion.Inverse(Vessel.GetTransform().rotation) * -t.up; double thrusterEfficiency = Vector3.Dot(direction, thrusterDir.normalized); effectiveThrust += thrusterEfficiency * pm.thrusterPower * force; @@ -289,9 +289,9 @@ public double RCSDeltaVVacuum() int numThrusters = 0; double gForRCS = 9.81; - double monopropMass = vessel.TotalResourceMass("MonoPropellant"); + double monopropMass = Vessel.TotalResourceMass("MonoPropellant"); - foreach (ModuleRCS pm in vessel.GetModules()) + foreach (ModuleRCS pm in Vessel.GetModules()) { totalIsp += pm.atmosphereCurve.Evaluate(0); numThrusters++; @@ -308,7 +308,7 @@ public double RCSDeltaVVacuum() [ValueInfoItem("#MechJeb_AngularVelocity", InfoItem.Category.Vessel, showInEditor = false, showInFlight = true)] //Angular Velocity public string angularVelocity() { - return MuUtils.PrettyPrint(vesselState.angularVelocityAvg.value.xzy * UtilMath.Rad2Deg) + "°/s"; + return MuUtils.PrettyPrint(VesselState.angularVelocityAvg.value.xzy * UtilMath.Rad2Deg) + "°/s"; } [ValueInfoItem("#MechJeb_CurrentAcceleration", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Current acceleration @@ -320,46 +320,46 @@ public double CurrentAcceleration() [ValueInfoItem("#MechJeb_CurrentThrust", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "N")] //Current thrust public double CurrentThrust() { - return vesselState.thrustCurrent * 1000; + return VesselState.thrustCurrent * 1000; } [ValueInfoItem("#MechJeb_TimeToSoIWwitch", InfoItem.Category.Orbit)] //Time to SoI switch public string TimeToSOITransition() { - if (orbit.patchEndTransition == Orbit.PatchTransitionType.FINAL) return "N/A"; + if (Orbit.patchEndTransition == Orbit.PatchTransitionType.FINAL) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.EndUT - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.EndUT - VesselState.time); } [ValueInfoItem("#MechJeb_SurfaceGravity", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s²")] //Surface gravity public double SurfaceGravity() { - return mainBody.GeeASL * 9.81; + return MainBody.GeeASL * 9.81; } [ValueInfoItem("#MechJeb_EscapeVelocity", InfoItem.Category.Orbit, format = ValueInfoItem.SI, siSigFigs = 3, units = "m/s")] //Escape velocity public double EscapeVelocity() { - return Math.Sqrt(2 * mainBody.gravParameter / vesselState.radius); + return Math.Sqrt(2 * MainBody.gravParameter / VesselState.radius); } [ValueInfoItem("#MechJeb_VesselName", InfoItem.Category.Vessel, showInEditor = false)] //Vessel name public string VesselName() { - return vessel.vesselName; + return Vessel.vesselName; } [ValueInfoItem("#MechJeb_VesselType", InfoItem.Category.Vessel, showInEditor = false)] //Vessel type public string VesselType() { - return vessel != null ? vessel.vesselType.displayDescription() : "-"; + return Vessel != null ? Vessel.vesselType.displayDescription() : "-"; } [ValueInfoItem("#MechJeb_VesselMass", InfoItem.Category.Vessel, format = "F3", units = "t", showInEditor = true)] //Vessel mass public double VesselMass() { if (HighLogic.LoadedSceneIsEditor) return EditorLogic.fetch.ship.parts.Sum(p => p.mass + p.GetResourceMass()); - return vesselState.mass; + return VesselState.mass; } [ValueInfoItem("#MechJeb_MaxVesselMass", InfoItem.Category.Vessel, showInEditor = true, showInFlight = false)] //Max vessel mass @@ -384,21 +384,21 @@ public double DryMass() units = "t")] //Liquid fuel & oxidizer mass public double LiquidFuelAndOxidizerMass() { - return vessel.TotalResourceMass("LiquidFuel") + vessel.TotalResourceMass("Oxidizer"); + return Vessel.TotalResourceMass("LiquidFuel") + Vessel.TotalResourceMass("Oxidizer"); } [ValueInfoItem("#MechJeb_MonopropellantMass", InfoItem.Category.Vessel, showInEditor = true, format = "F2", units = "kg")] //Monopropellant mass public double MonoPropellantMass() { - return vessel.TotalResourceMass("MonoPropellant"); + return Vessel.TotalResourceMass("MonoPropellant"); } [ValueInfoItem("#MechJeb_TotalElectricCharge", InfoItem.Category.Vessel, showInEditor = true, format = ValueInfoItem.SI, units = "Ah")] //Total electric charge public double TotalElectricCharge() { - return vessel.TotalResourceAmount(PartResourceLibrary.ElectricityHashcode); + return Vessel.TotalResourceAmount(PartResourceLibrary.ElectricityHashcode); } [ValueInfoItem("#MechJeb_MaxThrust", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "N", showInEditor = true)] //Max thrust @@ -413,7 +413,7 @@ public double MaxThrust() return 1000 * engines.Sum(e => e.minThrust + e.thrustPercentage / 100f * (e.maxThrust - e.minThrust)); } - return 1000 * vesselState.thrustAvailable; + return 1000 * VesselState.thrustAvailable; } [ValueInfoItem("#MechJeb_MinThrust", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "N", showInEditor = true)] //Min thrust @@ -429,7 +429,7 @@ public double MinThrust() e.throttleLocked ? e.minThrust + e.thrustPercentage / 100f * (e.maxThrust - e.minThrust) : e.minThrust); } - return vesselState.thrustMinimum; + return VesselState.thrustMinimum; } [ValueInfoItem("#MechJeb_MaxAcceleration", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²", @@ -449,7 +449,7 @@ public double MinAcceleration() [ValueInfoItem("#MechJeb_Gforce", InfoItem.Category.Vessel, format = "F4", units = "g", showInEditor = true)] //G force public double Acceleration() { - return vessel != null ? vessel.geeForce : 0; + return Vessel != null ? Vessel.geeForce : 0; } [ValueInfoItem("#MechJeb_DragCoefficient", InfoItem.Category.Vessel, format = "F3", showInEditor = true)] //Drag Coefficient @@ -479,7 +479,7 @@ public double DragCoefficient() return 0; } - return vesselState.dragCoef; + return VesselState.dragCoef; } [ValueInfoItem("#MechJeb_PartCount", InfoItem.Category.Vessel, showInEditor = true)] //Part count @@ -525,7 +525,7 @@ public double VesselCost() [ValueInfoItem("#MechJeb_CrewCount", InfoItem.Category.Vessel)] //Crew count public int CrewCount() { - return vessel.GetCrewCount(); + return Vessel.GetCrewCount(); } [ValueInfoItem("#MechJeb_CrewCapacity", InfoItem.Category.Vessel, showInEditor = true)] //Crew capacity @@ -537,72 +537,72 @@ public int CrewCapacity() [ValueInfoItem("#MechJeb_DistanceToTarget", InfoItem.Category.Target)] //Distance to target public string TargetDistance() { - if (core.Target.Target == null) return "N/A"; - return core.Target.Distance.ToSI() + "m"; + if (Core.Target.Target == null) return "N/A"; + return Core.Target.Distance.ToSI() + "m"; } [ValueInfoItem("#MechJeb_HeadingToTarget", InfoItem.Category.Target)] //Heading to target public string HeadingToTarget() { - if (core.Target.Target == null) return "N/A"; - return vesselState.HeadingFromDirection(-core.Target.RelativePosition).ToString("F1") + "º"; + if (Core.Target.Target == null) return "N/A"; + return VesselState.HeadingFromDirection(-Core.Target.RelativePosition).ToString("F1") + "º"; } [ValueInfoItem("#MechJeb_RelativeVelocity", InfoItem.Category.Target)] //Relative velocity public string TargetRelativeVelocity() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.RelativeVelocity.magnitude.ToSI() + "m/s"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.RelativeVelocity.magnitude.ToSI() + "m/s"; } [ValueInfoItem("#MechJeb_TimeToClosestApproach", InfoItem.Category.Target)] //Time to closest approach public string TargetTimeToClosestApproach() { - if (core.Target.Target != null && vesselState.altitudeTrue < 1000.0) + if (Core.Target.Target != null && VesselState.altitudeTrue < 1000.0) { - return GuiUtils.TimeToDHMS(GuiUtils.FromToETA(vessel.CoM, core.Target.Transform.position)); + return GuiUtils.TimeToDHMS(GuiUtils.FromToETA(Vessel.CoM, Core.Target.Transform.position)); } - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (double.IsNaN(core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (double.IsNaN(Core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } - if (vesselState.altitudeTrue < 1000.0) + if (VesselState.altitudeTrue < 1000.0) { - double a = (vessel.mainBody.transform.position - vessel.transform.position).magnitude; - double b = (vessel.mainBody.transform.position - core.Target.Transform.position).magnitude; - double c = Vector3d.Distance(vessel.transform.position, core.Target.Position); + double a = (Vessel.mainBody.transform.position - Vessel.transform.position).magnitude; + double b = (Vessel.mainBody.transform.position - Core.Target.Transform.position).magnitude; + double c = Vector3d.Distance(Vessel.transform.position, Core.Target.Position); double ang = Math.Acos((a * a + b * b - c * c) / (2f * a * b)); - return GuiUtils.TimeToDHMS(ang * vessel.mainBody.Radius / vesselState.speedSurfaceHorizontal); + return GuiUtils.TimeToDHMS(ang * Vessel.mainBody.Radius / VesselState.speedSurfaceHorizontal); } - return GuiUtils.TimeToDHMS(orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_ClosestApproachDistance", InfoItem.Category.Target)] //Closest approach distance public string TargetClosestApproachDistance() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (vesselState.altitudeTrue < 1000.0) { return "N/A"; } + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (VesselState.altitudeTrue < 1000.0) { return "N/A"; } - if (double.IsNaN(core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } + if (double.IsNaN(Core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } - return orbit.NextClosestApproachDistance(core.Target.TargetOrbit, vesselState.time).ToSI() + "m"; + return Orbit.NextClosestApproachDistance(Core.Target.TargetOrbit, VesselState.time).ToSI() + "m"; } [ValueInfoItem("#MechJeb_RelativeVelocityAtClosestApproach", InfoItem.Category.Target)] //Rel. vel. at closest approach public string TargetClosestApproachRelativeVelocity() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (vesselState.altitudeTrue < 1000.0) { return "N/A"; } + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (VesselState.altitudeTrue < 1000.0) { return "N/A"; } - if (double.IsNaN(core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } + if (double.IsNaN(Core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } try { - double UT = orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time); + double UT = Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time); if (double.IsNaN(UT)) { @@ -610,7 +610,7 @@ public string TargetClosestApproachRelativeVelocity() } double relVel = - (orbit.WorldOrbitalVelocityAtUT(UT) - core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)) + (Orbit.WorldOrbitalVelocityAtUT(UT) - Core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)) .magnitude; return relVel.ToSI() + "m/s"; } @@ -623,20 +623,20 @@ public string TargetClosestApproachRelativeVelocity() [ValueInfoItem("#MechJeb_PeriapsisInTargetSoI", InfoItem.Category.Misc)] //Periapsis in target SoI public string PeriapsisInTargetSOI() { - if (!core.Target.NormalTargetExists) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; Orbit o; - if (vessel.patchedConicsUnlocked() && vessel.patchedConicSolver.maneuverNodes.Any()) + if (Vessel.patchedConicsUnlocked() && Vessel.patchedConicSolver.maneuverNodes.Any()) { - ManeuverNode node = vessel.patchedConicSolver.maneuverNodes.Last(); + ManeuverNode node = Vessel.patchedConicSolver.maneuverNodes.Last(); o = node.nextPatch; } else { - o = vessel.orbit; + o = Vessel.orbit; } - while (o != null && o.referenceBody != (CelestialBody)vessel.targetObject) + while (o != null && o.referenceBody != (CelestialBody)Vessel.targetObject) o = o.nextPatch; if (o == null) return "N/A"; @@ -647,10 +647,10 @@ public string PeriapsisInTargetSOI() [ValueInfoItem("#MechJeb_TargetCaptureDV", InfoItem.Category.Misc)] //ΔV for capture by target public string TargetCaptureDV() { - if (!core.Target.NormalTargetExists || !(vessel.targetObject is CelestialBody)) return "N/A"; + if (!Core.Target.NormalTargetExists || !(Vessel.targetObject is CelestialBody)) return "N/A"; - Orbit o = vessel.orbit; - while (o != null && o.referenceBody != (CelestialBody)vessel.targetObject) + Orbit o = Vessel.orbit; + while (o != null && o.referenceBody != (CelestialBody)Vessel.targetObject) o = o.nextPatch; if (o == null) return "N/A"; @@ -665,262 +665,262 @@ public string TargetCaptureDV() [ValueInfoItem("#MechJeb_TargetApoapsis", InfoItem.Category.Target)] //Target apoapsis public string TargetApoapsis() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.ApA.ToSI() + "m"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.ApA.ToSI() + "m"; } [ValueInfoItem("#MechJeb_TargetPeriapsis", InfoItem.Category.Target)] //Target periapsis public string TargetPeriapsis() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.PeA.ToSI() + "m"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.PeA.ToSI() + "m"; } [ValueInfoItem("#MechJeb_TargetInclination", InfoItem.Category.Target)] //Target inclination public string TargetInclination() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.inclination.ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.inclination.ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetOrbitPeriod", InfoItem.Category.Target)] //Target orbit period public string TargetOrbitPeriod() { - if (!core.Target.NormalTargetExists) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.period); + if (!Core.Target.NormalTargetExists) return "N/A"; + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.period); } [ValueInfoItem("#MechJeb_TargetOrbitSpeed", InfoItem.Category.Target)] //Target orbit speed public string TargetOrbitSpeed() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.GetVel().magnitude.ToSI() + "m/s"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.GetVel().magnitude.ToSI() + "m/s"; } [ValueInfoItem("#MechJeb_TargetTimeToAp", InfoItem.Category.Target)] //Target time to Ap public string TargetOrbitTimeToAp() { - if (!core.Target.NormalTargetExists) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.timeToAp); + if (!Core.Target.NormalTargetExists) return "N/A"; + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.timeToAp); } [ValueInfoItem("#MechJeb_TargetTimeToPe", InfoItem.Category.Target)] //Target time to Pe public string TargetOrbitTimeToPe() { - if (!core.Target.NormalTargetExists) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.timeToPe); + if (!Core.Target.NormalTargetExists) return "N/A"; + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.timeToPe); } [ValueInfoItem("#MechJeb_TargetLAN", InfoItem.Category.Target)] //Target LAN public string TargetLAN() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.LAN.ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.LAN.ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetLDN", InfoItem.Category.Target)] //Target LDN public string TargetLDN() { - if (!core.Target.NormalTargetExists) return "N/A"; - return MuUtils.ClampDegrees360(core.Target.TargetOrbit.LAN + 180).ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return MuUtils.ClampDegrees360(Core.Target.TargetOrbit.LAN + 180).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetTimeToAN", InfoItem.Category.Target)] //Target Time to AN public string TargetTimeToAscendingNode() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (!core.Target.TargetOrbit.AscendingNodeEquatorialExists()) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; + if (!Core.Target.TargetOrbit.AscendingNodeEquatorialExists()) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.TimeOfAscendingNodeEquatorial(vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.TimeOfAscendingNodeEquatorial(VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_TargetTimeToDN", InfoItem.Category.Target)] //Target Time to DN public string TargetTimeToDescendingNode() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (!core.Target.TargetOrbit.DescendingNodeEquatorialExists()) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; + if (!Core.Target.TargetOrbit.DescendingNodeEquatorialExists()) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.TimeOfDescendingNodeEquatorial(vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.TimeOfDescendingNodeEquatorial(VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_TargetAoP", InfoItem.Category.Target)] //Target AoP public string TargetAoP() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.argumentOfPeriapsis.ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.argumentOfPeriapsis.ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetEccentricity", InfoItem.Category.Target)] //Target eccentricity public string TargetEccentricity() { - if (!core.Target.NormalTargetExists) return "N/A"; - return GuiUtils.TimeToDHMS(core.Target.TargetOrbit.eccentricity); + if (!Core.Target.NormalTargetExists) return "N/A"; + return GuiUtils.TimeToDHMS(Core.Target.TargetOrbit.eccentricity); } [ValueInfoItem("#MechJeb_TargetSMA", InfoItem.Category.Target)] //Target SMA public string TargetSMA() { - if (!core.Target.NormalTargetExists) return "N/A"; - return core.Target.TargetOrbit.semiMajorAxis.ToSI() + "m"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return Core.Target.TargetOrbit.semiMajorAxis.ToSI() + "m"; } [ValueInfoItem("#MechJeb_TargetMeanAnomaly", InfoItem.Category.Target, format = ValueInfoItem.ANGLE)] //Target Mean Anomaly public string TargetMeanAnomaly() { - if (!core.Target.NormalTargetExists) return "N/A"; - return MuUtils.ClampDegrees360(core.Target.TargetOrbit.meanAnomaly * UtilMath.Rad2Deg).ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + return MuUtils.ClampDegrees360(Core.Target.TargetOrbit.meanAnomaly * UtilMath.Rad2Deg).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetTrueLongitude", InfoItem.Category.Target)] //Target Mean Anomaly public string TargetTrueLongitude() { - if (!core.Target.NormalTargetExists) return "N/A"; - double longitudeOfPeriapsis = core.Target.TargetOrbit.LAN + core.Target.TargetOrbit.argumentOfPeriapsis; - return MuUtils.ClampDegrees360(core.Target.TargetOrbit.trueAnomaly * UtilMath.Rad2Deg + longitudeOfPeriapsis).ToString("F2") + "º"; + if (!Core.Target.NormalTargetExists) return "N/A"; + double longitudeOfPeriapsis = Core.Target.TargetOrbit.LAN + Core.Target.TargetOrbit.argumentOfPeriapsis; + return MuUtils.ClampDegrees360(Core.Target.TargetOrbit.trueAnomaly * UtilMath.Rad2Deg + longitudeOfPeriapsis).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_AtmosphericDrag", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Atmospheric drag public double AtmosphericDrag() { - return vesselState.drag; + return VesselState.drag; } [ValueInfoItem("#MechJeb_SynodicPeriod", InfoItem.Category.Target)] //Synodic period public string SynodicPeriod() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.SynodicPeriod(core.Target.TargetOrbit)); + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + return GuiUtils.TimeToDHMS(Orbit.SynodicPeriod(Core.Target.TargetOrbit)); } [ValueInfoItem("#MechJeb_PhaseAngleToTarget", InfoItem.Category.Target)] //Phase angle to target public string PhaseAngle() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (double.IsNaN(core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (double.IsNaN(Core.Target.TargetOrbit.semiMajorAxis)) { return "N/A"; } - return orbit.PhaseAngle(core.Target.TargetOrbit, vesselState.time).ToString("F2") + "º"; + return Orbit.PhaseAngle(Core.Target.TargetOrbit, VesselState.time).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TargetPlanetPhaseAngle", InfoItem.Category.Target)] //Target planet phase angle public string TargetPlanetPhaseAngle() { - if (!(core.Target.Target is CelestialBody)) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody.referenceBody) return "N/A"; + if (!(Core.Target.Target is CelestialBody)) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody.referenceBody) return "N/A"; - return mainBody.orbit.PhaseAngle(core.Target.TargetOrbit, vesselState.time).ToString("F2") + "º"; + return MainBody.orbit.PhaseAngle(Core.Target.TargetOrbit, VesselState.time).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_RelativeInclination", InfoItem.Category.Target)] //Relative inclination public string RelativeInclinationToTarget() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; - return orbit.RelativeInclination(core.Target.TargetOrbit).ToString("F2") + "º"; + return Orbit.RelativeInclination(Core.Target.TargetOrbit).ToString("F2") + "º"; } [ValueInfoItem("#MechJeb_TimeToAN", InfoItem.Category.Target)] //Time to AN public string TimeToAscendingNodeWithTarget() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (!orbit.AscendingNodeExists(core.Target.TargetOrbit)) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (!Orbit.AscendingNodeExists(Core.Target.TargetOrbit)) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.TimeOfAscendingNode(core.Target.TargetOrbit, vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.TimeOfAscendingNode(Core.Target.TargetOrbit, VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_TimeToDN", InfoItem.Category.Target)] //Time to DN public string TimeToDescendingNodeWithTarget() { - if (!core.Target.NormalTargetExists) return "N/A"; - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) return "N/A"; - if (!orbit.DescendingNodeExists(core.Target.TargetOrbit)) return "N/A"; + if (!Core.Target.NormalTargetExists) return "N/A"; + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) return "N/A"; + if (!Orbit.DescendingNodeExists(Core.Target.TargetOrbit)) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.TimeOfDescendingNode(core.Target.TargetOrbit, vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.TimeOfDescendingNode(Core.Target.TargetOrbit, VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_TimeToEquatorialAN", InfoItem.Category.Orbit)] //Time to equatorial AN public string TimeToEquatorialAscendingNode() { - if (!orbit.AscendingNodeEquatorialExists()) return "N/A"; + if (!Orbit.AscendingNodeEquatorialExists()) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.TimeOfAscendingNodeEquatorial(vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.TimeOfAscendingNodeEquatorial(VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_TimeToEquatorialDN", InfoItem.Category.Orbit)] //Time to equatorial DN public string TimeToEquatorialDescendingNode() { - if (!orbit.DescendingNodeEquatorialExists()) return "N/A"; + if (!Orbit.DescendingNodeEquatorialExists()) return "N/A"; - return GuiUtils.TimeToDHMS(orbit.TimeOfDescendingNodeEquatorial(vesselState.time) - vesselState.time); + return GuiUtils.TimeToDHMS(Orbit.TimeOfDescendingNodeEquatorial(VesselState.time) - VesselState.time); } [ValueInfoItem("#MechJeb_CircularOrbitSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")] //Circular orbit speed public double CircularOrbitSpeed() { - return OrbitalManeuverCalculator.CircularOrbitSpeed(mainBody, vesselState.radius); + return OrbitalManeuverCalculator.CircularOrbitSpeed(MainBody, VesselState.radius); } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showStagedMass = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showBurnedMass = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showInitialMass = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showFinalMass = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showMaxThrust = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showVacInitialTWR = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showAtmoInitialTWR = false; // NK - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showAtmoMaxTWR = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showVacMaxTWR = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showVacDeltaV = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showTime = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showAtmoDeltaV = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showISP = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool liveSLT = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public float altSLTScale = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public float machScale = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int TWRBody = 1; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int StageDisplayState = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showEmpty = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool timeSeconds = false; private MechJebStageStatsHelper stageStatsHelper; @@ -942,7 +942,7 @@ public void UpdateItems() [ValueInfoItem("#MechJeb_StageDv_vac", InfoItem.Category.Vessel, format = "F0", units = "m/s", showInEditor = true)] //Stage ΔV (vac) public double StageDeltaVVacuum() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); if (stats.vacStats.Length == 0) return 0; @@ -953,7 +953,7 @@ public double StageDeltaVVacuum() [ValueInfoItem("#MechJeb_StageDV_atmo", InfoItem.Category.Vessel, format = "F0", units = "m/s", showInEditor = true)] //Stage ΔV (atmo) public double StageDeltaVAtmosphere() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); if (stats.atmoStats.Length == 0) return 0; @@ -964,7 +964,7 @@ public double StageDeltaVAtmosphere() [ValueInfoItem("#MechJeb_StageDV_atmo_vac", InfoItem.Category.Vessel, units = "m/s", showInEditor = true)] //Stage ΔV (atmo, vac) public string StageDeltaVAtmosphereAndVac() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); double atmDv = stats.atmoStats.Length == 0 ? 0 : stats.atmoStats[stats.atmoStats.Length - 1].DeltaV; @@ -977,7 +977,7 @@ public string StageDeltaVAtmosphereAndVac() showInEditor = true)] //Stage time (full throttle) public float StageTimeLeftFullThrottle() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); if (stats.vacStats.Length == 0 || stats.atmoStats.Length == 0) return 0; @@ -995,7 +995,7 @@ public float StageTimeLeftCurrentThrottle() float fullThrottleTime = StageTimeLeftFullThrottle(); if (fullThrottleTime == 0) return 0; - return fullThrottleTime / vessel.ctrlState.mainThrottle; + return fullThrottleTime / Vessel.ctrlState.mainThrottle; } [ValueInfoItem("#MechJeb_StageTimeHover", InfoItem.Category.Vessel, format = ValueInfoItem.TIME)] //Stage time (hover) @@ -1004,14 +1004,14 @@ public float StageTimeLeftHover() float fullThrottleTime = StageTimeLeftFullThrottle(); if (fullThrottleTime == 0) return 0; - double hoverThrottle = vesselState.localg / vesselState.maxThrustAccel; + double hoverThrottle = VesselState.localg / VesselState.maxThrustAccel; return fullThrottleTime / (float)hoverThrottle; } [ValueInfoItem("#MechJeb_TotalDV_vacuum", InfoItem.Category.Vessel, format = "F0", units = "m/s", showInEditor = true)] //Total ΔV (vacuum) public double TotalDeltaVVaccum() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); return stats.vacStats.Sum(s => s.DeltaV); } @@ -1019,7 +1019,7 @@ public double TotalDeltaVVaccum() [ValueInfoItem("#MechJeb_TotalDV_atmo", InfoItem.Category.Vessel, format = "F0", units = "m/s", showInEditor = true)] //Total ΔV (atmo) public double TotalDeltaVAtmosphere() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); return stats.atmoStats.Sum(s => s.DeltaV); } @@ -1027,7 +1027,7 @@ public double TotalDeltaVAtmosphere() [ValueInfoItem("#MechJeb_TotalDV_atmo_vac", InfoItem.Category.Vessel, units = "m/s", showInEditor = true)] //Total ΔV (atmo, vac) public string TotalDeltaVAtmosphereAndVac() { - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this); double atmDv = stats.atmoStats.Sum(s => s.DeltaV); @@ -1039,16 +1039,16 @@ public string TotalDeltaVAtmosphereAndVac() [GeneralInfoItem("#MechJeb_DockingGuidance_velocity", InfoItem.Category.Target)] //Docking guidance: velocity public void DockingGuidanceVelocity() { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_velocityNA")); //"Target-relative velocity: (N/A)" return; } - Vector3d relVel = core.Target.RelativeVelocity; - double relVelX = Vector3d.Dot(relVel, vessel.GetTransform().right); - double relVelY = Vector3d.Dot(relVel, vessel.GetTransform().forward); - double relVelZ = Vector3d.Dot(relVel, vessel.GetTransform().up); + Vector3d relVel = Core.Target.RelativeVelocity; + double relVelX = Vector3d.Dot(relVel, Vessel.GetTransform().right); + double relVelY = Vector3d.Dot(relVel, Vessel.GetTransform().forward); + double relVelZ = Vector3d.Dot(relVel, Vessel.GetTransform().up); GUILayout.BeginVertical(); GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_velocity")); //"Target-relative velocity:" GUILayout.Label("X: " + MuUtils.PadPositive(relVelX, "F2") + " m/s [L/J]"); @@ -1060,14 +1060,14 @@ public void DockingGuidanceVelocity() [GeneralInfoItem("#MechJeb_DockingGuidanceAngularVelocity", InfoItem.Category.Target)] //Docking guidance: Angular velocity public void DockingGuidanceAngularVelocity() { - if (!(core.Target.Target is Vessel)) + if (!(Core.Target.Target is Vessel)) { GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_label2")); //"Target-relative Angular velocity: (N/A)" return; } - var target = (Vessel)core.Target.Target; - Vector3d relw = Quaternion.Inverse(vessel.ReferenceTransform.rotation) * (target.angularVelocity - vessel.angularVelocity) * + var target = (Vessel)Core.Target.Target; + Vector3d relw = Quaternion.Inverse(Vessel.ReferenceTransform.rotation) * (target.angularVelocity - Vessel.angularVelocity) * Mathf.Rad2Deg; GUILayout.BeginVertical(); @@ -1081,16 +1081,16 @@ public void DockingGuidanceAngularVelocity() [GeneralInfoItem("#MechJeb_DockingGuidancePosition", InfoItem.Category.Target)] //Docking guidance: position public void DockingGuidancePosition() { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_label4")); //"Separation from target: (N/A)" return; } - Vector3d sep = core.Target.RelativePosition; - double sepX = Vector3d.Dot(sep, vessel.GetTransform().right); - double sepY = Vector3d.Dot(sep, vessel.GetTransform().forward); - double sepZ = Vector3d.Dot(sep, vessel.GetTransform().up); + Vector3d sep = Core.Target.RelativePosition; + double sepX = Vector3d.Dot(sep, Vessel.GetTransform().right); + double sepY = Vector3d.Dot(sep, Vessel.GetTransform().forward); + double sepZ = Vector3d.Dot(sep, Vessel.GetTransform().up); GUILayout.BeginVertical(); GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_label5")); //"Separation from target:" GUILayout.Label("X: " + MuUtils.PadPositive(sepX, "F2") + " m [L/J]"); @@ -1102,7 +1102,7 @@ public void DockingGuidancePosition() [GeneralInfoItem("#MechJeb_AllPlanetPhaseAngles", InfoItem.Category.Orbit)] //All planet phase angles public void AllPlanetPhaseAngles() { - Orbit o = orbit; + Orbit o = Orbit; while (o.referenceBody != Planetarium.fetch.Sun) o = o.referenceBody.orbit; GUILayout.BeginVertical(); @@ -1128,7 +1128,7 @@ public void AllPlanetPhaseAngles() GUILayout.BeginHorizontal(); GUILayout.Label(body.bodyName, GUILayout.ExpandWidth(true)); - GUILayout.Label(o.PhaseAngle(body.orbit, vesselState.time).ToString("F2") + "º", GUILayout.ExpandWidth(false)); + GUILayout.Label(o.PhaseAngle(body.orbit, VesselState.time).ToString("F2") + "º", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } @@ -1141,9 +1141,9 @@ public void AllMoonPhaseAngles() GUILayout.BeginVertical(); GUILayout.Label(Localizer.Format("#MechJeb_InfoItems_label7"), GuiUtils.middleCenterLabel); //"Moon phase angles" - if (orbit.referenceBody != Planetarium.fetch.Sun) + if (Orbit.referenceBody != Planetarium.fetch.Sun) { - Orbit o = orbit; + Orbit o = Orbit; while (o.referenceBody.referenceBody != Planetarium.fetch.Sun) o = o.referenceBody.orbit; for (int i = 0; i < o.referenceBody.orbitingBodies.Count; i++) @@ -1156,7 +1156,7 @@ public void AllMoonPhaseAngles() GUILayout.BeginHorizontal(); GUILayout.Label(body.bodyName, GUILayout.ExpandWidth(true)); - GUILayout.Label(o.PhaseAngle(body.orbit, vesselState.time).ToString("F2") + "º", GUILayout.ExpandWidth(false)); + GUILayout.Label(o.PhaseAngle(body.orbit, VesselState.time).ToString("F2") + "º", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } } @@ -1167,49 +1167,49 @@ public void AllMoonPhaseAngles() [ValueInfoItem("#MechJeb_SurfaceBiome", InfoItem.Category.Misc, showInEditor = false)] //Surface Biome public string CurrentRawBiome() { - if (vessel.landedAt != string.Empty) - return vessel.landedAt; - return mainBody.GetExperimentBiomeSafe(vessel.latitude, vessel.longitude); + if (Vessel.landedAt != string.Empty) + return Vessel.landedAt; + return MainBody.GetExperimentBiomeSafe(Vessel.latitude, Vessel.longitude); } [ValueInfoItem("#MechJeb_CurrentBiome", InfoItem.Category.Misc, showInEditor = false)] //Current Biome public string CurrentBiome() { - if (vessel.landedAt != string.Empty) - return vessel.landedAt; - if (mainBody.BiomeMap == null) + if (Vessel.landedAt != string.Empty) + return Vessel.landedAt; + if (MainBody.BiomeMap == null) return "N/A"; - string biome = mainBody.BiomeMap.GetAtt(vessel.latitude * UtilMath.Deg2Rad, vessel.longitude * UtilMath.Deg2Rad).displayname; + string biome = MainBody.BiomeMap.GetAtt(Vessel.latitude * UtilMath.Deg2Rad, Vessel.longitude * UtilMath.Deg2Rad).displayname; if (biome != "") biome = "'s " + biome; - switch (vessel.situation) + switch (Vessel.situation) { //ExperimentSituations.SrfLanded case Vessel.Situations.LANDED: case Vessel.Situations.PRELAUNCH: - return mainBody.displayName.LocalizeRemoveGender() + + return MainBody.displayName.LocalizeRemoveGender() + (biome == "" ? Localizer.Format("#MechJeb_InfoItems_VesselSituation5") : biome); //"'s surface" //ExperimentSituations.SrfSplashed case Vessel.Situations.SPLASHED: - return mainBody.displayName.LocalizeRemoveGender() + + return MainBody.displayName.LocalizeRemoveGender() + (biome == "" ? Localizer.Format("#MechJeb_InfoItems_VesselSituation6") : biome); //"'s oceans" case Vessel.Situations.FLYING: - if (vessel.altitude < mainBody.scienceValues.flyingAltitudeThreshold) + if (Vessel.altitude < MainBody.scienceValues.flyingAltitudeThreshold) //ExperimentSituations.FlyingLow return Localizer.Format("#MechJeb_InfoItems_VesselSituation1", - mainBody.displayName.LocalizeRemoveGender() + biome); //"Flying over <<1>>" + MainBody.displayName.LocalizeRemoveGender() + biome); //"Flying over <<1>>" //ExperimentSituations.FlyingHigh return Localizer.Format("#MechJeb_InfoItems_VesselSituation2", - mainBody.displayName.LocalizeRemoveGender() + biome); //"Upper atmosphere of <<1>>" + MainBody.displayName.LocalizeRemoveGender() + biome); //"Upper atmosphere of <<1>>" default: - if (vessel.altitude < mainBody.scienceValues.spaceAltitudeThreshold) + if (Vessel.altitude < MainBody.scienceValues.spaceAltitudeThreshold) //ExperimentSituations.InSpaceLow return Localizer.Format("#MechJeb_InfoItems_VesselSituation3", - mainBody.displayName.LocalizeRemoveGender() + biome); //"Space just above <<1>>" + MainBody.displayName.LocalizeRemoveGender() + biome); //"Space just above <<1>>" // ExperimentSituations.InSpaceHigh return Localizer.Format("#MechJeb_InfoItems_VesselSituation4", - mainBody.displayName.LocalizeRemoveGender() + biome); //"Space high over <<1>>" + MainBody.displayName.LocalizeRemoveGender() + biome); //"Space high over <<1>>" } } @@ -1219,8 +1219,8 @@ public void LatLonClipbardCopy() if (GUILayout.Button(Localizer.Format("#MechJeb_InfoItems_CopytoClipboard"))) //"Copy Lat/Lon/Alt to Clipboard" { var te = new TextEditor(); - string result = "latitude = " + vesselState.latitude.ToString("F6") + "\nlongitude = " + vesselState.longitude.ToString("F6") + - "\naltitude = " + vessel.altitude.ToString("F2") + "\n"; + string result = "latitude = " + VesselState.latitude.ToString("F6") + "\nlongitude = " + VesselState.longitude.ToString("F6") + + "\naltitude = " + Vessel.altitude.ToString("F2") + "\n"; te.text = result; te.SelectAll(); te.Copy(); diff --git a/MechJeb2/MechJebModuleLandingAutopilot.cs b/MechJeb2/MechJebModuleLandingAutopilot.cs index e15224068..bfe1180f4 100644 --- a/MechJeb2/MechJebModuleLandingAutopilot.cs +++ b/MechJeb2/MechJebModuleLandingAutopilot.cs @@ -18,22 +18,22 @@ public class MechJebModuleLandingAutopilot : AutopilotModule private bool _deployedGears; public bool LandAtTarget; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public readonly EditableDouble TouchdownSpeed = 0.5; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public bool DeployGears = true; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public readonly EditableInt LimitGearsStage = 0; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public bool DeployChutes = true; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public readonly EditableInt LimitChutesStage = 0; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public bool RCSAdjustment = true; // This is used to adjust the height at which the parachutes semi deploy as a means of @@ -96,8 +96,8 @@ public class MechJebModuleLandingAutopilot : AutopilotModule } public Vector3d LandingSite => - mainBody.GetWorldSurfacePosition(Prediction.EndPosition.Latitude, - Prediction.EndPosition.Longitude, _landingAltitude) - mainBody.position; // The current position of the landing site + MainBody.GetWorldSurfacePosition(Prediction.EndPosition.Latitude, + Prediction.EndPosition.Longitude, _landingAltitude) - MainBody.position; // The current position of the landing site private Vector3d _rotatedLandingSite => Prediction.WorldEndPosition(); // The position where the landing site will be when we land at it @@ -111,17 +111,17 @@ public MechJebModuleLandingAutopilot(MechJebCore core) public override void OnStart(PartModule.StartState state) { - _predictor = core.GetComputerModule(); + _predictor = Core.GetComputerModule(); } //public interface: public void LandAtPositionTarget(object controller) { LandAtTarget = true; - users.Add(controller); + Users.Add(controller); - _predictor.users.Add(this); - vessel.RemoveAllManeuverNodes(); // For the benefit of the landing predictions module + _predictor.Users.Add(this); + Vessel.RemoveAllManeuverNodes(); // For the benefit of the landing predictions module _deployedGears = false; @@ -129,18 +129,18 @@ public void LandAtPositionTarget(object controller) _parachutePlan = new ParachutePlan(this); _parachutePlan.StartPlanning(); - if (orbit.PeA < 0) - SetStep(new CourseCorrection(core)); + if (Orbit.PeA < 0) + SetStep(new CourseCorrection(Core)); else if (UseLowDeorbitStrategy()) - SetStep(new PlaneChange(core)); + SetStep(new PlaneChange(Core)); else - SetStep(new DeorbitBurn(core)); + SetStep(new DeorbitBurn(Core)); } public void LandUntargeted(object controller) { LandAtTarget = false; - users.Add(controller); + Users.Add(controller); _deployedGears = false; @@ -148,16 +148,16 @@ public void LandUntargeted(object controller) _parachutePlan = new ParachutePlan(this); _parachutePlan.StartPlanning(); - SetStep(new UntargetedDeorbit(core)); + SetStep(new UntargetedDeorbit(Core)); } public void StopLanding() { - users.Clear(); - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); - if (core.Landing.RCSAdjustment) - core.RCS.enabled = false; + Users.Clear(); + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); + if (Core.Landing.RCSAdjustment) + Core.RCS.Enabled = false; SetStep(null); } @@ -174,7 +174,7 @@ public override void Drive(FlightCtrlState s) // Consider lowering the langing gear { - double minalt = Math.Min(vesselState.altitudeBottom, Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue)); + double minalt = Math.Min(VesselState.altitudeBottom, Math.Min(VesselState.altitudeASL, VesselState.altitudeTrue)); if (DeployGears && !_deployedGears && minalt < 1000) DeployLandingGears(); } @@ -189,21 +189,21 @@ public override void OnFixedUpdate() DeployParachutes(); } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { - core.Attitude.users.Add(this); - core.Thrust.users.Add(this); + Core.Attitude.Users.Add(this); + Core.Thrust.Users.Add(this); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Attitude.attitudeDeactivate(); - _predictor.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + _predictor.Users.Remove(this); _predictor.descentSpeedPolicy = null; - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); - if (core.Landing.RCSAdjustment) - core.RCS.enabled = false; + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); + if (Core.Landing.RCSAdjustment) + Core.RCS.Enabled = false; SetStep(null); } @@ -212,17 +212,17 @@ public override void OnModuleDisabled() public Vector3d ComputeCourseCorrection(bool allowPrograde) { // actualLandingPosition is the predicted actual landing position - Vector3d actualLandingPosition = _rotatedLandingSite - mainBody.position; + Vector3d actualLandingPosition = _rotatedLandingSite - MainBody.position; // orbitLandingPosition is the point where our current orbit intersects the planet - double endRadius = mainBody.Radius + DecelerationEndAltitude() - 100; + double endRadius = MainBody.Radius + DecelerationEndAltitude() - 100; // Seems we are already landed ? - if (endRadius > orbit.ApR || vessel.LandedOrSplashed) + if (endRadius > Orbit.ApR || Vessel.LandedOrSplashed) StopLanding(); - Vector3d orbitLandingPosition = orbit.WorldBCIPositionAtUT( - orbit.PeR < endRadius ? orbit.NextTimeOfRadius(vesselState.time, endRadius) : orbit.NextPeriapsisTime(vesselState.time) + Vector3d orbitLandingPosition = Orbit.WorldBCIPositionAtUT( + Orbit.PeR < endRadius ? Orbit.NextTimeOfRadius(VesselState.time, endRadius) : Orbit.NextPeriapsisTime(VesselState.time) ); // convertOrbitToActual is a rotation that rotates orbitLandingPosition on actualLandingPosition @@ -231,7 +231,7 @@ public Vector3d ComputeCourseCorrection(bool allowPrograde) // Consider the effect small changes in the velocity in each of these three directions Vector3d[] perturbationDirections = { - vesselState.surfaceVelocity.normalized, vesselState.radialPlusSurface, vesselState.normalPlusSurface + VesselState.surfaceVelocity.normalized, VesselState.radialPlusSurface, VesselState.normalPlusSurface }; // Compute the effect burns in these directions would @@ -244,11 +244,11 @@ public Vector3d ComputeCourseCorrection(bool allowPrograde) const double PERTURBATION_DELTA_V = 1; Orbit perturbedOrbit = - orbit.PerturbedOrbit(vesselState.time, PERTURBATION_DELTA_V * perturbationDirections[i]); //compute the perturbed orbit + Orbit.PerturbedOrbit(VesselState.time, PERTURBATION_DELTA_V * perturbationDirections[i]); //compute the perturbed orbit double perturbedLandingTime = perturbedOrbit.PeR < endRadius - ? perturbedOrbit.NextTimeOfRadius(vesselState.time, endRadius) - : perturbedOrbit.NextPeriapsisTime(vesselState.time); + ? perturbedOrbit.NextTimeOfRadius(VesselState.time, endRadius) + : perturbedOrbit.NextPeriapsisTime(VesselState.time); Vector3d perturbedLandingPosition = perturbedOrbit.WorldBCIPositionAtUT(perturbedLandingTime); //find where it hits the planet @@ -272,9 +272,9 @@ public Vector3d ComputeCourseCorrection(bool allowPrograde) // into a position. We can't just get the current position of those coordinates, because the planet will // rotate during the descent, so we have to account for that. Vector3d desiredLandingPosition = - mainBody.GetWorldSurfacePosition(core.Target.targetLatitude, core.Target.targetLongitude, 0) - mainBody.position; - float bodyRotationAngleDuringDescent = (float)(360 * (Prediction.EndUT - vesselState.time) / mainBody.rotationPeriod); - var bodyRotationDuringFall = Quaternion.AngleAxis(bodyRotationAngleDuringDescent, mainBody.angularVelocity.normalized); + MainBody.GetWorldSurfacePosition(Core.Target.targetLatitude, Core.Target.targetLongitude, 0) - MainBody.position; + float bodyRotationAngleDuringDescent = (float)(360 * (Prediction.EndUT - VesselState.time) / MainBody.rotationPeriod); + var bodyRotationDuringFall = Quaternion.AngleAxis(bodyRotationAngleDuringDescent, MainBody.angularVelocity.normalized); desiredLandingPosition = bodyRotationDuringFall * desiredLandingPosition; Vector3d desiredDelta = desiredLandingPosition - actualLandingPosition; @@ -352,11 +352,11 @@ public void ControlParachutes() private void DeployParachutes() { - if (!(vesselState.mainBody.atmosphere && DeployChutes)) return; + if (!(VesselState.mainBody.atmosphere && DeployChutes)) return; - for (int i = 0; i < vesselState.parachutes.Count; i++) + for (int i = 0; i < VesselState.parachutes.Count; i++) { - ModuleParachute p = vesselState.parachutes[i]; + ModuleParachute p = VesselState.parachutes[i]; // what is the ASL at which we should deploy this parachute? It is the actual deployment height above the surface + the ASL of the predicted landing point. double landingSiteASL = _landingAltitude; double parachuteDeployAboveGroundAtLandingSite = p.deployAltitude * _parachutePlan.Multiplier; @@ -364,7 +364,7 @@ private void DeployParachutes() double aslDeployAltitude = parachuteDeployAboveGroundAtLandingSite + landingSiteASL; if (p.part.inverseStage >= LimitChutesStage && p.deploymentState == ModuleParachute.deploymentStates.STOWED && - aslDeployAltitude > vesselState.altitudeASL && p.deploymentSafeState == ModuleParachute.deploymentSafeStates.SAFE) + aslDeployAltitude > VesselState.altitudeASL && p.deploymentSafeState == ModuleParachute.deploymentSafeStates.SAFE) { p.Deploy(); //Debug.Log("Deploying parachute " + p.name + " at " + ASLDeployAltitude + ". (" + LandingSiteASL + " + " + ParachuteDeployAboveGroundAtLandingSite +")"); @@ -375,12 +375,12 @@ private void DeployParachutes() // This methods works out if there are any parachutes that are capable of being deployed public bool ParachutesDeployable() { - if (!vesselState.mainBody.atmosphere) return false; + if (!VesselState.mainBody.atmosphere) return false; if (!DeployChutes) return false; - for (int i = 0; i < vesselState.parachutes.Count; i++) + for (int i = 0; i < VesselState.parachutes.Count; i++) { - ModuleParachute p = vesselState.parachutes[i]; + ModuleParachute p = VesselState.parachutes[i]; if (Math.Max(p.part.inverseStage, 0) >= LimitChutesStage && p.deploymentState == ModuleParachute.deploymentStates.STOWED) { return true; @@ -393,14 +393,14 @@ public bool ParachutesDeployable() // This methods works out if there are any parachutes that have already been deployed (or semi deployed) private bool ParachutesDeployed() { - return vesselState.parachuteDeployed; + return VesselState.parachuteDeployed; } private void DeployLandingGears() { - for (int i = 0; i < vessel.parts.Count; i++) + for (int i = 0; i < Vessel.parts.Count; i++) { - Part p = vessel.parts[i]; + Part p = Vessel.parts[i]; if (p.HasModule()) { // p.inverseStage is -1 for some configuration ?!? @@ -422,11 +422,11 @@ private IDescentSpeedPolicy PickDescentSpeedPolicy() { if (UseAtmosphereToBrake()) { - return new PoweredCoastDescentSpeedPolicy(mainBody.Radius + DecelerationEndAltitude(), mainBody.GeeASL * 9.81, - vesselState.limitedMaxThrustAccel); + return new PoweredCoastDescentSpeedPolicy(MainBody.Radius + DecelerationEndAltitude(), MainBody.GeeASL * 9.81, + VesselState.limitedMaxThrustAccel); } - return new SafeDescentSpeedPolicy(mainBody.Radius + DecelerationEndAltitude(), mainBody.GeeASL * 9.81, vesselState.limitedMaxThrustAccel); + return new SafeDescentSpeedPolicy(MainBody.Radius + DecelerationEndAltitude(), MainBody.GeeASL * 9.81, VesselState.limitedMaxThrustAccel); } public double DecelerationEndAltitude() @@ -439,7 +439,7 @@ public double DecelerationEndAltitude() // if the atmosphere is thick, deceleration (meaning freefall through the atmosphere) // should end a safe height above the landing site in order to allow braking from terminal velocity // FIXME: Drag Length is quite large now without parachutes, check this better - double landingSiteDragLength = mainBody.DragLength(_landingAltitude, _vesselAverageDrag + ParachuteAddedDragCoef(), vesselState.mass); + double landingSiteDragLength = MainBody.DragLength(_landingAltitude, _vesselAverageDrag + ParachuteAddedDragCoef(), VesselState.mass); //MechJebCore.print("DecelerationEndAltitude Atmo " + (2 * landingSiteDragLength + LandingAltitude).ToString("F2")); return 1.1 * landingSiteDragLength + _landingAltitude; @@ -453,20 +453,20 @@ public double DecelerationEndAltitude() //expect to get slowed to near terminal velocity before impacting the ground. public bool UseAtmosphereToBrake() { - double landingSiteDragLength = mainBody.DragLength(_landingAltitude, _vesselAverageDrag + ParachuteAddedDragCoef(), vesselState.mass); + double landingSiteDragLength = MainBody.DragLength(_landingAltitude, _vesselAverageDrag + ParachuteAddedDragCoef(), VesselState.mass); //if (mainBody.RealMaxAtmosphereAltitude() > 0 && (ParachutesDeployable() || ParachutesDeployed())) - return mainBody.RealMaxAtmosphereAltitude() > 0 && - landingSiteDragLength < 0.7 * mainBody.RealMaxAtmosphereAltitude(); // the ratio is totally arbitrary until I get something better + return MainBody.RealMaxAtmosphereAltitude() > 0 && + landingSiteDragLength < 0.7 * MainBody.RealMaxAtmosphereAltitude(); // the ratio is totally arbitrary until I get something better } // Get an average drag for the whole vessel. Far from precise but fast. private double VesselAverageDrag() { float dragCoef = 0; - for (int i = 0; i < vessel.parts.Count; i++) + for (int i = 0; i < Vessel.parts.Count; i++) { - Part p = vessel.parts[i]; + Part p = Vessel.parts[i]; if (p.DragCubes.None || p.ShieldedFromAirstream) { continue; @@ -490,11 +490,11 @@ private double VesselAverageDrag() private double ParachuteAddedDragCoef() { double addedDragCoef = 0; - if (!vesselState.mainBody.atmosphere || !DeployChutes) return addedDragCoef * PhysicsGlobals.DragCubeMultiplier; + if (!VesselState.mainBody.atmosphere || !DeployChutes) return addedDragCoef * PhysicsGlobals.DragCubeMultiplier; - for (int i = 0; i < vesselState.parachutes.Count; i++) + for (int i = 0; i < VesselState.parachutes.Count; i++) { - ModuleParachute p = vesselState.parachutes[i]; + ModuleParachute p = VesselState.parachutes[i]; if (p.part.inverseStage < LimitChutesStage) continue; //addedDragMass += p.part.DragCubes.Cubes.Where(c => c.Name == "DEPLOYED").m @@ -521,23 +521,23 @@ private double ParachuteAddedDragCoef() private bool UseLowDeorbitStrategy() { - if (mainBody.atmosphere) return false; + if (MainBody.atmosphere) return false; - double periapsisSpeed = orbit.WorldOrbitalVelocityAtUT(orbit.NextPeriapsisTime(vesselState.time)).magnitude; - double stoppingDistance = Math.Pow(periapsisSpeed, 2) / (2 * vesselState.limitedMaxThrustAccel); + double periapsisSpeed = Orbit.WorldOrbitalVelocityAtUT(Orbit.NextPeriapsisTime(VesselState.time)).magnitude; + double stoppingDistance = Math.Pow(periapsisSpeed, 2) / (2 * VesselState.limitedMaxThrustAccel); - return orbit.PeA < 2 * stoppingDistance + mainBody.Radius / 4; + return Orbit.PeA < 2 * stoppingDistance + MainBody.Radius / 4; } public double MaxAllowedSpeed() { - return DescentSpeedPolicy.MaxAllowedSpeed(vesselState.CoM - mainBody.position, vesselState.surfaceVelocity); + return DescentSpeedPolicy.MaxAllowedSpeed(VesselState.CoM - MainBody.position, VesselState.surfaceVelocity); } public double MaxAllowedSpeedAfterDt(double dt) { - return DescentSpeedPolicy.MaxAllowedSpeed(vesselState.CoM + vesselState.orbitalVelocity * dt - mainBody.position, - vesselState.surfaceVelocity + dt * vesselState.gravityForce); + return DescentSpeedPolicy.MaxAllowedSpeed(VesselState.CoM + VesselState.orbitalVelocity * dt - MainBody.position, + VesselState.surfaceVelocity + dt * VesselState.gravityForce); } [ValueInfoItem("#MechJeb_ParachuteControlInfo", InfoItem.Category.Misc, showInEditor = false)] //ParachuteControlInfo @@ -555,8 +555,8 @@ public string ParachuteControlInfo() public void SetTargetKSC(MechJebCore controller) { - users.Add(controller); - core.Target.SetPositionTarget(mainBody, MechJebModuleLandingGuidance.LandingSites[0].Latitude, + Users.Add(controller); + Core.Target.SetPositionTarget(MainBody, MechJebModuleLandingGuidance.LandingSites[0].Latitude, MechJebModuleLandingGuidance.LandingSites[0].Longitude); } } @@ -727,7 +727,7 @@ public void AddResult(ReentrySimulation.Result newResult) } // What was the overshoot for this new result? - double overshoot = newResult.GetOvershoot(_autoPilot.core.Target.targetLatitude, _autoPilot.core.Target.targetLongitude); + double overshoot = newResult.GetOvershoot(_autoPilot.Core.Target.targetLatitude, _autoPilot.Core.Target.targetLongitude); //Debug.Log("overshoot: " + overshoot.ToString("F2") + " multiplier: " + newResult.parachuteMultiplier.ToString("F4") + " hasError:" + newResult.multiplierHasError); @@ -789,7 +789,7 @@ public ParachutePlan(MechJebModuleLandingAutopilot autopliot) _autoPilot = autopliot; // Take a note of which body this parachute plan is for. If we go to a different body, we will need a new plan! - _body = autopliot.vessel.orbit.referenceBody; + _body = autopliot.Vessel.orbit.referenceBody; } // Throw away any old data, and create a new empty dataset @@ -807,9 +807,9 @@ public void StartPlanning() _parachutePresent = false; // First assume that there are no parachutes. // TODO should we check if each of these parachutes is withing the staging limit? - for (int i = 0; i < _autoPilot.vesselState.parachutes.Count; i++) + for (int i = 0; i < _autoPilot.VesselState.parachutes.Count; i++) { - ModuleParachute p = _autoPilot.vesselState.parachutes[i]; + ModuleParachute p = _autoPilot.VesselState.parachutes[i]; if (p.minAirPressureToOpen > minSemiDeployPressure) // Although this is called "minSemiDeployPressure" we want to find the largest value for each of our parachutes. This can be used to calculate the corresponding height, and hence a height at which we can be guarenteed that all our parachutes will deploy if asked to. { diff --git a/MechJeb2/MechJebModuleLandingGuidance.cs b/MechJeb2/MechJebModuleLandingGuidance.cs index 76e8c44f8..267a681d0 100644 --- a/MechJeb2/MechJebModuleLandingGuidance.cs +++ b/MechJeb2/MechJebModuleLandingGuidance.cs @@ -14,7 +14,7 @@ public class MechJebModuleLandingGuidance : DisplayModule private MechJebModuleLandingPredictions _predictor; public static List LandingSites; - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] private int _landingSiteIdx; public struct LandingSite @@ -27,7 +27,7 @@ public struct LandingSite public override void OnStart(PartModule.StartState state) { - _predictor = core.GetComputerModule(); + _predictor = Core.GetComputerModule(); if (LandingSites == null && HighLogic.LoadedSceneIsFlight) InitLandingSitesList(); @@ -40,7 +40,7 @@ public override GUILayoutOption[] WindowOptions() private void MoveByMeter(ref EditableAngle angle, double distance, double alt) { - double angularDelta = distance * UtilMath.Rad2Deg / (alt + mainBody.Radius); + double angularDelta = distance * UtilMath.Rad2Deg / (alt + MainBody.Radius); angle += angularDelta; } @@ -48,63 +48,63 @@ protected override void WindowGUI(int windowID) { GUILayout.BeginVertical(); - if (core.Target.PositionTargetExists) + if (Core.Target.PositionTargetExists) { - double asl = core.vessel.mainBody.TerrainAltitude(core.Target.targetLatitude, core.Target.targetLongitude); + double asl = Core.vessel.mainBody.TerrainAltitude(Core.Target.targetLatitude, Core.Target.targetLongitude); GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label1")); //Target coordinates: GUILayout.BeginHorizontal(); - core.Target.targetLatitude.DrawEditGUI(EditableAngle.Direction.NS); + Core.Target.targetLatitude.DrawEditGUI(EditableAngle.Direction.NS); if (GUILayout.Button("▲")) { - MoveByMeter(ref core.Target.targetLatitude, 10, asl); + MoveByMeter(ref Core.Target.targetLatitude, 10, asl); } GUILayout.Label("10m"); if (GUILayout.Button("▼")) { - MoveByMeter(ref core.Target.targetLatitude, -10, asl); + MoveByMeter(ref Core.Target.targetLatitude, -10, asl); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); - core.Target.targetLongitude.DrawEditGUI(EditableAngle.Direction.EW); + Core.Target.targetLongitude.DrawEditGUI(EditableAngle.Direction.EW); if (GUILayout.Button("◄")) { - MoveByMeter(ref core.Target.targetLongitude, -10, asl); + MoveByMeter(ref Core.Target.targetLongitude, -10, asl); } GUILayout.Label("10m"); if (GUILayout.Button("►")) { - MoveByMeter(ref core.Target.targetLongitude, 10, asl); + MoveByMeter(ref Core.Target.targetLongitude, 10, asl); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("ASL: " + asl.ToSI() + "m"); - GUILayout.Label(core.Target.targetBody.GetExperimentBiomeSafe(core.Target.targetLatitude, core.Target.targetLongitude)); + GUILayout.Label(Core.Target.targetBody.GetExperimentBiomeSafe(Core.Target.targetLatitude, Core.Target.targetLongitude)); GUILayout.EndHorizontal(); } else { if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button1"))) //Enter target coordinates { - core.Target.SetPositionTarget(mainBody, core.Target.targetLatitude, core.Target.targetLongitude); + Core.Target.SetPositionTarget(MainBody, Core.Target.targetLatitude, Core.Target.targetLongitude); } } - if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button2"))) core.Target.PickPositionTargetOnMap(); //Pick target on map + if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button2"))) Core.Target.PickPositionTargetOnMap(); //Pick target on map - var availableLandingSites = LandingSites.Where(p => p.Body == mainBody).ToList(); + var availableLandingSites = LandingSites.Where(p => p.Body == MainBody).ToList(); if (availableLandingSites.Any()) { GUILayout.BeginHorizontal(); _landingSiteIdx = GuiUtils.ComboBox.Box(_landingSiteIdx, availableLandingSites.Select(p => p.Name).ToArray(), this); if (GUILayout.Button("Set", GUILayout.ExpandWidth(false))) { - core.Target.SetPositionTarget(mainBody, availableLandingSites[_landingSiteIdx].Latitude, + Core.Target.SetPositionTarget(MainBody, availableLandingSites[_landingSiteIdx].Latitude, availableLandingSites[_landingSiteIdx].Longitude); } @@ -113,55 +113,55 @@ protected override void WindowGUI(int windowID) DrawGUITogglePredictions(); - if (core.Landing != null) + if (Core.Landing != null) { GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label2")); //Autopilot: - _predictor.maxOrbits = core.Landing.enabled ? 0.5 : 4; - _predictor.noSkipToFreefall = !core.Landing.enabled; + _predictor.maxOrbits = Core.Landing.Enabled ? 0.5 : 4; + _predictor.noSkipToFreefall = !Core.Landing.Enabled; - if (core.Landing.enabled) + if (Core.Landing.Enabled) { - if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button3"))) core.Landing.StopLanding(); //Abort autoland + if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button3"))) Core.Landing.StopLanding(); //Abort autoland } else { GUILayout.BeginHorizontal(); - if (!core.Target.PositionTargetExists || vessel.LandedOrSplashed) GUI.enabled = false; + if (!Core.Target.PositionTargetExists || Vessel.LandedOrSplashed) GUI.enabled = false; if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button4"))) - core.Landing.LandAtPositionTarget(this); //Land at target - GUI.enabled = !vessel.LandedOrSplashed; - if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button5"))) core.Landing.LandUntargeted(this); //Land somewhere + Core.Landing.LandAtPositionTarget(this); //Land at target + GUI.enabled = !Vessel.LandedOrSplashed; + if (GUILayout.Button(Localizer.Format("#MechJeb_LandingGuidance_button5"))) Core.Landing.LandUntargeted(this); //Land somewhere GUI.enabled = true; GUILayout.EndHorizontal(); } - GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label3"), core.Landing.TouchdownSpeed, "m/s", + GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label3"), Core.Landing.TouchdownSpeed, "m/s", 35); //Touchdown speed: - if (core.Landing != null) - core.Node.autowarp = GUILayout.Toggle(core.Node.autowarp, Localizer.Format("#MechJeb_LandingGuidance_checkbox1")); //Auto-warp - - core.Landing.DeployGears = - GUILayout.Toggle(core.Landing.DeployGears, Localizer.Format("#MechJeb_LandingGuidance_checkbox2")); //Deploy Landing Gear - GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label4"), core.Landing.LimitGearsStage, "", 35); //"Stage Limit:" - core.Landing.DeployChutes = - GUILayout.Toggle(core.Landing.DeployChutes, Localizer.Format("#MechJeb_LandingGuidance_checkbox3")); //Deploy Parachutes - _predictor.deployChutes = core.Landing.DeployChutes; - GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label5"), core.Landing.LimitChutesStage, "", 35); //Stage Limit: - _predictor.limitChutesStage = core.Landing.LimitChutesStage; - core.Landing.RCSAdjustment = - GUILayout.Toggle(core.Landing.RCSAdjustment, + if (Core.Landing != null) + Core.Node.autowarp = GUILayout.Toggle(Core.Node.autowarp, Localizer.Format("#MechJeb_LandingGuidance_checkbox1")); //Auto-warp + + Core.Landing.DeployGears = + GUILayout.Toggle(Core.Landing.DeployGears, Localizer.Format("#MechJeb_LandingGuidance_checkbox2")); //Deploy Landing Gear + GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label4"), Core.Landing.LimitGearsStage, "", 35); //"Stage Limit:" + Core.Landing.DeployChutes = + GUILayout.Toggle(Core.Landing.DeployChutes, Localizer.Format("#MechJeb_LandingGuidance_checkbox3")); //Deploy Parachutes + _predictor.deployChutes = Core.Landing.DeployChutes; + GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_LandingGuidance_label5"), Core.Landing.LimitChutesStage, "", 35); //Stage Limit: + _predictor.limitChutesStage = Core.Landing.LimitChutesStage; + Core.Landing.RCSAdjustment = + GUILayout.Toggle(Core.Landing.RCSAdjustment, Localizer.Format("#MechJeb_LandingGuidance_checkbox4")); //Use RCS for small adjustment - if (core.Landing.enabled) + if (Core.Landing.Enabled) { - GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label6") + core.Landing.Status); //Status: + GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label6") + Core.Landing.Status); //Status: GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label7") + - (core.Landing.CurrentStep != null ? core.Landing.CurrentStep.GetType().Name : "N/A")); //Step: + (Core.Landing.CurrentStep != null ? Core.Landing.CurrentStep.GetType().Name : "N/A")); //Step: GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_label8") + - (core.Landing.DescentSpeedPolicy != null ? core.Landing.DescentSpeedPolicy.GetType().Name : "N/A") + " (" + - core.Landing.UseAtmosphereToBrake() + ")"); //Mode + (Core.Landing.DescentSpeedPolicy != null ? Core.Landing.DescentSpeedPolicy.GetType().Name : "N/A") + " (" + + Core.Landing.UseAtmosphereToBrake() + ")"); //Mode //GUILayout.Label("DecEndAlt: " + core.landing.DecelerationEndAltitude().ToString("F2")); //var dragLength = mainBody.DragLength(core.landing.LandingAltitude, core.landing.vesselAverageDrag, vesselState.mass); //GUILayout.Label("Drag Length: " + ( dragLength < double.MaxValue ? dragLength.ToString("F2") : "infinite")); @@ -182,14 +182,14 @@ protected override void WindowGUI(int windowID) public void SetAndLandTargetKSC() { LandingSite ksc = LandingSites.First(x => x.Name == "KSC Pad"); - core.Target.SetPositionTarget(mainBody, ksc.Latitude, ksc.Longitude); - core.Landing.LandAtPositionTarget(this); + Core.Target.SetPositionTarget(MainBody, ksc.Latitude, ksc.Longitude); + Core.Landing.LandAtPositionTarget(this); } public void LandSomewhere() { - core.Landing.StopLanding(); - core.Landing.LandUntargeted(this); + Core.Landing.StopLanding(); + Core.Landing.LandUntargeted(this); } [GeneralInfoItem("#MechJeb_LandingPredictions", InfoItem.Category.Misc)] //Landing predictions @@ -197,20 +197,20 @@ private void DrawGUITogglePredictions() { GUILayout.BeginVertical(); - bool active = GUILayout.Toggle(_predictor.enabled, Localizer.Format("#MechJeb_LandingGuidance_checkbox5")); //Show landing predictions - if (_predictor.enabled != active) + bool active = GUILayout.Toggle(_predictor.Enabled, Localizer.Format("#MechJeb_LandingGuidance_checkbox5")); //Show landing predictions + if (_predictor.Enabled != active) { if (active) { - _predictor.users.Add(this); + _predictor.Users.Add(this); } else { - _predictor.users.Remove(this); + _predictor.Users.Remove(this); } } - if (_predictor.enabled) + if (_predictor.Enabled) { _predictor.makeAerobrakeNodes = GUILayout.Toggle(_predictor.makeAerobrakeNodes, Localizer.Format("#MechJeb_LandingGuidance_checkbox6")); //"Show aerobrake nodes" @@ -239,12 +239,12 @@ private void DrawGUIPrediction() result.EndASL.ToSI() + "m"); GUILayout.Label(result.Body.GetExperimentBiomeSafe(result.EndPosition.Latitude, result.EndPosition.Longitude)); double error = Vector3d.Distance( - mainBody.GetWorldSurfacePosition(result.EndPosition.Latitude, result.EndPosition.Longitude, 0) - mainBody.position, - mainBody.GetWorldSurfacePosition(core.Target.targetLatitude, core.Target.targetLongitude, 0) - mainBody.position); + MainBody.GetWorldSurfacePosition(result.EndPosition.Latitude, result.EndPosition.Longitude, 0) - MainBody.position, + MainBody.GetWorldSurfacePosition(Core.Target.targetLatitude, Core.Target.targetLongitude, 0) - MainBody.position); GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label10") + error.ToSI() + "m" + Localizer.Format("#MechJeb_LandingGuidance_Label11") + result.MaxDragGees.ToString("F1") + "g" + Localizer.Format("#MechJeb_LandingGuidance_Label12") + result.DeltaVExpended.ToString("F1") + "m/s" - + Localizer.Format("#MechJeb_LandingGuidance_Label13") + (vessel.Landed + + Localizer.Format("#MechJeb_LandingGuidance_Label13") + (Vessel.Landed ? "0.0s" : GuiUtils.TimeToDHMS(result.EndUT - Planetarium.GetUniversalTime(), 1))); //Target difference = \nMax drag: \nDelta-v needed: \nTime to land: @@ -265,7 +265,7 @@ private void DrawGUIPrediction() case ReentrySimulation.Outcome.NO_REENTRY: GUILayout.Label(Localizer.Format("#MechJeb_LandingGuidance_Label18_1") - + orbit.PeA.ToSI(3) + "m Pe > " + mainBody.RealMaxAtmosphereAltitude().ToSI(3) + (mainBody.atmosphere + + Orbit.PeA.ToSI(3) + "m Pe > " + MainBody.RealMaxAtmosphereAltitude().ToSI(3) + (MainBody.atmosphere ? Localizer.Format("#MechJeb_LandingGuidance_Label18_2") : Localizer.Format( "#MechJeb_LandingGuidance_Label18_3"))); //"Orbit does not reenter:\n""m atmosphere height""m ground" @@ -287,14 +287,14 @@ private void InitLandingSitesList() { foreach (ConfigNode site in mjConf.config.GetNode("LandingSites").GetNodes("Site")) { - print("site " + site); + Print("site " + site); string launchSiteName = site.GetValue("name"); string lat = site.GetValue("latitude"); string lon = site.GetValue("longitude"); if (launchSiteName == null || lat == null || lon == null) { - print("Ignore landing site with null value"); + Print("Ignore landing site with null value"); continue; } @@ -306,7 +306,7 @@ private void InitLandingSitesList() if (LandingSites.All(p => p.Name != launchSiteName)) { - print("Adding " + launchSiteName); + Print("Adding " + launchSiteName); LandingSites.Add(new LandingSite { Name = launchSiteName, Latitude = latitude, Longitude = longitude, Body = body }); } } @@ -414,9 +414,9 @@ public override string IconName() return "Landing Guidance"; } - public override bool IsSpaceCenterUpgradeUnlocked() + protected override bool IsSpaceCenterUpgradeUnlocked() { - return vessel.patchedConicsUnlocked(); + return Vessel.patchedConicsUnlocked(); } public MechJebModuleLandingGuidance(MechJebCore core) : base(core) { } diff --git a/MechJeb2/MechJebModuleLandingPredictions.cs b/MechJeb2/MechJebModuleLandingPredictions.cs index a4d7b5011..bb1efac3a 100644 --- a/MechJeb2/MechJebModuleLandingPredictions.cs +++ b/MechJeb2/MechJebModuleLandingPredictions.cs @@ -91,16 +91,16 @@ public ReentrySimulation.Result GetErrorResult() public double simSpeedOfSound; //inputs: - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool makeAerobrakeNodes = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showTrajectory = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool worldTrajectory = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool camTrajectory = false; public bool deployChutes = false; @@ -170,16 +170,16 @@ public override void OnStart(PartModule.StartState state) random = new Random(); if (state != PartModule.StartState.None && state != PartModule.StartState.Editor) { - core.AddToPostDrawQueue(DoMapView); + Core.AddToPostDrawQueue(DoMapView); } } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { TryStartSimulation(false); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { stopwatch.Stop(); stopwatch.Reset(); @@ -199,7 +199,7 @@ private void TryStartSimulation(bool doErrorSim) { try { - if (!vessel.LandedOrSplashed) + if (!Vessel.LandedOrSplashed) { // We should be running simulations periodically. If one is not running right now, // check if enough time has passed since the last one to start a new one: @@ -256,7 +256,7 @@ protected void StartSimulation(bool addParachuteError) stopwatch.Start(); //starts a timer that times how long the simulation takes } - Orbit patch = GetReenteringPatch() ?? orbit; + Orbit patch = GetReenteringPatch() ?? Orbit; // Work out what the landing altitude was of the last prediction, and use that to pass into the next simulation if (result != null) { @@ -280,9 +280,9 @@ protected void StartSimulation(bool addParachuteError) //if (descentSpeedPolicy != null) // print(vesselState.limitedMaxThrustAccel.ToString("F2") + " " + descentSpeedPolicy.MaxAllowedSpeed(vesselState.CoM - mainBody.position, vesselState.surfaceVelocity).ToString("F2")); - var simVessel = SimulatedVessel.Borrow(vessel, simCurves, patch.StartUT, core.Landing.enabled && deployChutes ? limitChutesStage : -1); + var simVessel = SimulatedVessel.Borrow(Vessel, simCurves, patch.StartUT, Core.Landing.Enabled && deployChutes ? limitChutesStage : -1); var sim = ReentrySimulation.Borrow(patch, patch.StartUT, simVessel, simCurves, descentSpeedPolicy, decelEndAltitudeASL, - vesselState.limitedMaxThrustAccel, parachuteMultiplierForThisSimulation, altitudeOfPreviousPrediction, addParachuteError, dt, + VesselState.limitedMaxThrustAccel, parachuteMultiplierForThisSimulation, altitudeOfPreviousPrediction, addParachuteError, dt, Time.fixedDeltaTime, maxOrbits, noSkipToFreefall); //MechJebCore.print("Sim ran with dt=" + dt.ToString("F3")); @@ -397,7 +397,7 @@ private void CheckForResult() else { if (newResult.Exception != null) - print("Exception in the last simulation\n" + newResult.Exception.Message + "\n" + newResult.Exception.StackTrace); + Print("Exception in the last simulation\n" + newResult.Exception.Message + "\n" + newResult.Exception.StackTrace); newResult.Release(); } } @@ -406,7 +406,7 @@ private void CheckForResult() protected Orbit GetReenteringPatch() { - Orbit patch = orbit; + Orbit patch = Orbit; int i = 0; @@ -414,7 +414,7 @@ protected Orbit GetReenteringPatch() { i++; double reentryRadius = patch.referenceBody.Radius + patch.referenceBody.RealMaxAtmosphereAltitude(); - Orbit nextPatch = vessel.GetNextPatch(patch, aerobrakeNode); + Orbit nextPatch = Vessel.GetNextPatch(patch, aerobrakeNode); if (patch.PeR < reentryRadius) { if (patch.Radius(patch.StartUT) < reentryRadius) return patch; @@ -437,9 +437,9 @@ protected void MaintainAerobrakeNode() if (makeAerobrakeNodes) { //Remove node after finishing aerobraking: - if (aerobrakeNode != null && vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) + if (aerobrakeNode != null && Vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) { - if (aerobrakeNode.UT < vesselState.time && vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) + if (aerobrakeNode.UT < VesselState.time && VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) { aerobrakeNode.RemoveSelf(); aerobrakeNode = null; @@ -455,10 +455,10 @@ protected void MaintainAerobrakeNode() //Put the node at periapsis, unless we're past periapsis. In that case put the node at the current time. double UT; - if (preAerobrakeOrbit == orbit && - vesselState.altitudeASL < mainBody.RealMaxAtmosphereAltitude() && vesselState.speedVertical > 0) + if (preAerobrakeOrbit == Orbit && + VesselState.altitudeASL < MainBody.RealMaxAtmosphereAltitude() && VesselState.speedVertical > 0) { - UT = vesselState.time; + UT = VesselState.time; } else { @@ -470,7 +470,7 @@ protected void MaintainAerobrakeNode() Vector3d dV = OrbitalManeuverCalculator.DeltaVToChangeApoapsis(preAerobrakeOrbit, UT, postAerobrakeOrbit.ApR); - if (aerobrakeNode != null && vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) + if (aerobrakeNode != null && Vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) { //update the existing node Vector3d nodeDV = preAerobrakeOrbit.DeltaVToManeuverNodeCoordinates(UT, dV); @@ -479,13 +479,13 @@ protected void MaintainAerobrakeNode() else { //place a new node - aerobrakeNode = vessel.PlaceManeuverNode(preAerobrakeOrbit, dV, UT); + aerobrakeNode = Vessel.PlaceManeuverNode(preAerobrakeOrbit, dV, UT); } } else { //no aerobraking, remove the node: - if (aerobrakeNode != null && vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) + if (aerobrakeNode != null && Vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) { aerobrakeNode.RemoveSelf(); } @@ -494,7 +494,7 @@ protected void MaintainAerobrakeNode() else { //Remove aerobrake node when it is turned off: - if (aerobrakeNode != null && vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) + if (aerobrakeNode != null && Vessel.patchedConicSolver.maneuverNodes.Contains(aerobrakeNode)) { aerobrakeNode.RemoveSelf(); } @@ -503,7 +503,7 @@ protected void MaintainAerobrakeNode() private void DoMapView() { - if ((MapView.MapIsEnabled || camTrajectory) && !vessel.LandedOrSplashed && enabled) + if ((MapView.MapIsEnabled || camTrajectory) && !Vessel.LandedOrSplashed && Enabled) { ReentrySimulation.Result drawnResult = Result; if (drawnResult != null) @@ -519,8 +519,8 @@ private void DoMapView() //using (var list = drawnResult.WorldTrajectory(interval, worldTrajectory && MapView.MapIsEnabled)) using (Disposable> list = drawnResult.WorldTrajectory(interval, worldTrajectory)) { - if (!MapView.MapIsEnabled && (noSkipToFreefall || vessel.staticPressurekPa > 0)) - list.value[0] = vesselState.CoM; + if (!MapView.MapIsEnabled && (noSkipToFreefall || Vessel.staticPressurekPa > 0)) + list.value[0] = VesselState.CoM; GLUtils.DrawPath(drawnResult.Body, list.value, Color.red, MapView.MapIsEnabled); } } diff --git a/MechJeb2/MechJebModuleManeuverPlanner.cs b/MechJeb2/MechJebModuleManeuverPlanner.cs index 395fd4f1a..3faba844a 100644 --- a/MechJeb2/MechJebModuleManeuverPlanner.cs +++ b/MechJeb2/MechJebModuleManeuverPlanner.cs @@ -19,7 +19,7 @@ public MechJebModuleManeuverPlanner(MechJebCore core) : base(core) private readonly Operation[] operation = Operation.GetAvailableOperations(); private readonly string[] operationNames; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private int operationId; // Creation or replacement mode @@ -56,8 +56,8 @@ protected override void WindowGUI(int windowID) operationId = GuiUtils.ComboBox.Box(operationId, operationNames, this); // Compute orbit and universal time parameters for next maneuver - double UT = vesselState.time; - Orbit o = orbit; + double UT = VesselState.time; + Orbit o = Orbit; if (anyNodeExists) { if (createNode) @@ -76,7 +76,7 @@ protected override void WindowGUI(int windowID) try { - operation[operationId].DoParametersGUI(o, UT, core.Target); + operation[operationId].DoParametersGUI(o, UT, Core.Target); } catch (Exception) { } // TODO: Would be better to fix the problem but this will do for now @@ -92,7 +92,7 @@ protected override void WindowGUI(int windowID) executingNode = false; } - if (core.Node != null && GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button2"))) //"Create and execute" + if (Core.Node != null && GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button2"))) //"Create and execute" { makingNode = true; executingNode = true; @@ -102,19 +102,19 @@ protected override void WindowGUI(int windowID) if (makingNode) { - List nodeList = operation[operationId].MakeNodes(o, UT, core.Target); + List nodeList = operation[operationId].MakeNodes(o, UT, Core.Target); if (nodeList != null) { if (!createNode) maneuverNodes.Last().RemoveSelf(); for (int i = 0; i < nodeList.Count; i++) { - vessel.PlaceManeuverNode(o, nodeList[i].dV, nodeList[i].UT); + Vessel.PlaceManeuverNode(o, nodeList[i].dV, nodeList[i].UT); } } - if (executingNode && core.Node != null) - core.Node.ExecuteOneNode(this); + if (executingNode && Core.Node != null) + Core.Node.ExecuteOneNode(this); } if (operation[operationId].GetErrorMessage().Length > 0) @@ -124,60 +124,60 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button3"))) //Remove ALL nodes { - vessel.RemoveAllManeuverNodes(); + Vessel.RemoveAllManeuverNodes(); } - if (core.Node != null) + if (Core.Node != null) { - if (anyNodeExists && !core.Node.enabled) + if (anyNodeExists && !Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button4"))) //Execute next node { - core.Node.ExecuteOneNode(this); + Core.Node.ExecuteOneNode(this); } if (VesselState.isLoadedPrincipia && GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button7"))) //Execute next Principia node { - core.Node.ExecuteOnePNode(this); + Core.Node.ExecuteOnePNode(this); } - if (vessel.patchedConicSolver.maneuverNodes.Count > 1) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 1) { if (GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button5"))) //Execute all nodes { - core.Node.ExecuteAllNodes(this); + Core.Node.ExecuteAllNodes(this); } } } - else if (core.Node.enabled) + else if (Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_Maneu_button6"))) //Abort node execution { - core.Node.Abort(); + Core.Node.Abort(); } } GUILayout.BeginHorizontal(); - core.Node.autowarp = - GUILayout.Toggle(core.Node.autowarp, Localizer.Format("#MechJeb_Maneu_Autowarp"), GUILayout.ExpandWidth(true)); //"Auto-warp" + Core.Node.autowarp = + GUILayout.Toggle(Core.Node.autowarp, Localizer.Format("#MechJeb_Maneu_Autowarp"), GUILayout.ExpandWidth(true)); //"Auto-warp" GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_Maneu_Tolerance"), GUILayout.ExpandWidth(false)); //"Tolerance:" - core.Node.tolerance.text = GUILayout.TextField(core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); + Core.Node.tolerance.text = GUILayout.TextField(Core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); if (GUILayout.Button("+", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val += 0.1; + Core.Node.tolerance.val += 0.1; } if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val -= core.Node.tolerance.val > 0.1 ? 0.1 : 0.0; + Core.Node.tolerance.val -= Core.Node.tolerance.val > 0.1 ? 0.1 : 0.0; } if (GUILayout.Button("R", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val = 0.1; + Core.Node.tolerance.val = 0.1; } GUILayout.Label("m/s", GUILayout.ExpandWidth(false)); @@ -185,20 +185,20 @@ protected override void WindowGUI(int windowID) GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_Maneu_Lead_time"), GUILayout.ExpandWidth(false)); //Lead time: - core.Node.leadTime.text = GUILayout.TextField(core.Node.leadTime.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); + Core.Node.leadTime.text = GUILayout.TextField(Core.Node.leadTime.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); if (GUILayout.Button("+", GUILayout.ExpandWidth(false))) { - core.Node.leadTime.val += 1; + Core.Node.leadTime.val += 1; } if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) { - core.Node.leadTime.val -= 1; + Core.Node.leadTime.val -= 1; } if (GUILayout.Button("R", GUILayout.ExpandWidth(false))) { - core.Node.leadTime.val = 3; + Core.Node.leadTime.val = 3; } GUILayout.Label("s", GUILayout.ExpandWidth(false)); @@ -215,9 +215,9 @@ protected override void WindowGUI(int windowID) public List GetManeuverNodes() { - MechJebModuleLandingPredictions predictor = core.GetComputerModule(); - if (predictor == null) return vessel.patchedConicSolver.maneuverNodes; - return vessel.patchedConicSolver.maneuverNodes.Where(n => n != predictor.aerobrakeNode).ToList(); + MechJebModuleLandingPredictions predictor = Core.GetComputerModule(); + if (predictor == null) return Vessel.patchedConicSolver.maneuverNodes; + return Vessel.patchedConicSolver.maneuverNodes.Where(n => n != predictor.aerobrakeNode).ToList(); } public override GUILayoutOption[] WindowOptions() @@ -235,9 +235,9 @@ public override string IconName() return "Maneuver Planner"; } - public override bool IsSpaceCenterUpgradeUnlocked() + protected override bool IsSpaceCenterUpgradeUnlocked() { - return vessel.patchedConicsUnlocked(); + return Vessel.patchedConicsUnlocked(); } } } diff --git a/MechJeb2/MechJebModuleMenu.cs b/MechJeb2/MechJebModuleMenu.cs index d6fa940a0..0a5c1e544 100644 --- a/MechJeb2/MechJebModuleMenu.cs +++ b/MechJeb2/MechJebModuleMenu.cs @@ -16,8 +16,8 @@ public class MechJebModuleMenu : DisplayModule public MechJebModuleMenu(MechJebCore core) : base(core) { - priority = -1000; - enabled = true; + Priority = -1000; + Enabled = true; hidden = true; ShowInFlight = true; ShowInEditor = true; @@ -53,22 +53,22 @@ private struct Button public string texturePathActive; } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public WindowStat windowStat = WindowStat.HIDDEN; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public WindowSide windowSide = WindowSide.TOP; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public float windowProgr; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public float windowVPos = -185; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public float windowHPos = 250; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int columns = 2; private const int colWidth = 200; @@ -127,11 +127,11 @@ public Rect buttonPos private bool movingButton; [ToggleInfoItem("#MechJeb_HideMenuButton", InfoItem.Category.Misc)] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool hideButton = false; //Hide Menu Button [ToggleInfoItem("#MechJeb_UseAppLauncher", InfoItem.Category.Misc)] - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool useAppLauncher = true; //Use AppLauncher [GeneralInfoItem("#MechJeb_MenuPosition", InfoItem.Category.Misc)] //Menu Position @@ -208,7 +208,7 @@ protected override void WindowGUI(int windowID) toggleActive.normal.textColor = toggleActive.onNormal.textColor = Color.green; } - List displayModules = core.GetDisplayModules(DisplayOrder.instance); + List displayModules = Core.GetDisplayModules(DisplayOrder.instance); int i = 0; int step = Mathf.CeilToInt((float)(displayModules.Count(d => !d.hidden && d.showInCurrentScene) + 1) / columns); @@ -226,7 +226,7 @@ protected override void WindowGUI(int windowID) i = 0; } - module.enabled = GUILayout.Toggle(module.enabled, module.GetName(), module.isActive() ? toggleActive : toggleInactive); + module.Enabled = GUILayout.Toggle(module.Enabled, module.GetName(), module.isActive() ? toggleActive : toggleInactive); i++; } } @@ -239,7 +239,7 @@ protected override void WindowGUI(int windowID) GUILayout.EndVertical(); GUILayout.EndHorizontal(); - if (core.someModuleAreLocked) + if (Core.someModuleAreLocked) GUILayout.Label( Localizer.Format( "#MechJeb_ModuleAreLocked")); //"Some modules are disabled until you unlock the proper node in the R&D tree or upgrade the tracking station." @@ -278,7 +278,7 @@ public void SetupToolBarButtons() SetupMainToolbarButton(); - foreach (DisplayModule module in core.GetDisplayModules(DisplayOrder.instance).Where(m => !m.hidden)) + foreach (DisplayModule module in Core.GetDisplayModules(DisplayOrder.instance).Where(m => !m.hidden)) { Button button; if (!toolbarButtons.ContainsKey(module)) @@ -296,7 +296,7 @@ public void SetupToolBarButtons() if (GameDatabase.Instance.GetTexture(TexturePath, false) == null) { button.texturePath = Qmark; - print("No icon for " + name); + Print("No icon for " + name); } else { @@ -322,7 +322,7 @@ public void SetupToolBarButtons() .FirstOrDefault(m => m == module); if (mod != null) { - mod.enabled = !mod.enabled; + mod.Enabled = !mod.Enabled; } }; } @@ -338,22 +338,22 @@ public void SetupToolBarButtons() // create toolbar buttons for features if (featureButtons.Count == 0) { - MechJebModuleManeuverPlanner maneuverPlannerModule = core.GetComputerModule(); + MechJebModuleManeuverPlanner maneuverPlannerModule = Core.GetComputerModule(); if (!HighLogic.LoadedSceneIsEditor && maneuverPlannerModule != null && !maneuverPlannerModule.hidden) { CreateFeatureButton(maneuverPlannerModule, "Exec_Node", "MechJeb Execute Next Node", b => { - if (vessel.patchedConicSolver.maneuverNodes.Count > 0 && core.Node != null) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 0 && Core.Node != null) { - if (core.Node.enabled) + if (Core.Node.Enabled) { - core.Node.Abort(); + Core.Node.Abort(); } else { - if (vessel.patchedConicSolver.maneuverNodes[0].DeltaV.magnitude > 0.0001) + if (Vessel.patchedConicSolver.maneuverNodes[0].DeltaV.magnitude > 0.0001) { - core.Node.ExecuteOneNode(maneuverPlannerModule); + Core.Node.ExecuteOneNode(maneuverPlannerModule); } else { @@ -365,30 +365,30 @@ public void SetupToolBarButtons() { ScreenMessages.PostScreenMessage("No maneuver nodes", 2f); } - }, () => vessel.patchedConicSolver.maneuverNodes.Count > 0 && core.Node != null && core.Node.enabled); + }, () => Vessel.patchedConicSolver.maneuverNodes.Count > 0 && Core.Node != null && Core.Node.Enabled); CreateFeatureButton(maneuverPlannerModule, "Autostage_Once", "MechJeb Autostage Once", b => { - MechJebModuleThrustWindow w = core.GetComputerModule(); + MechJebModuleThrustWindow w = Core.GetComputerModule(); - if (core.Staging.enabled && core.Staging.autostagingOnce) + if (Core.Staging.Enabled && Core.Staging.autostagingOnce) { - if (core.Staging.users.Contains(w)) + if (Core.Staging.Users.Contains(w)) { - core.Staging.users.Remove(w); + Core.Staging.Users.Remove(w); w.autostageSavedState = false; } } else { - core.Staging.AutostageOnce(w); + Core.Staging.AutostageOnce(w); } - }, () => core.Staging.enabled && core.Staging.autostagingOnce); + }, () => Core.Staging.Enabled && Core.Staging.autostagingOnce); CreateFeatureButton(maneuverPlannerModule, "Auto_Warp", "MechJeb Auto-warp", b => { - core.Node.autowarp = !core.Node.autowarp; - }, () => core.Node.autowarp); + Core.Node.autowarp = !Core.Node.autowarp; + }, () => Core.Node.autowarp); } } } @@ -412,7 +412,7 @@ public void CreateFeatureButton(DisplayModule module, string nameId, string tool if (GameDatabase.Instance.GetTexture(texturePath, false) == null) { button.texturePath = Qmark; - print("No icon for " + nameId); + Print("No icon for " + nameId); } else { @@ -569,7 +569,7 @@ public override void DrawGUI(bool inEditor) if (windowStat != WindowStat.HIDDEN) { - windowPos = GUILayout.Window(GetType().FullName.GetHashCode(), displayedPos, WindowGUI, "MechJeb " + core.version, + windowPos = GUILayout.Window(GetType().FullName.GetHashCode(), displayedPos, WindowGUI, "MechJeb " + Core.version, GUILayout.Width(colWidth), GUILayout.Height(20)); } else @@ -622,7 +622,7 @@ public void OnMenuUpdate() } } - if (HighLogic.LoadedSceneIsEditor || (vessel != null && vessel.isActiveVessel)) + if (HighLogic.LoadedSceneIsEditor || (Vessel != null && Vessel.isActiveVessel)) { SetupAppLauncher(); SetupToolBarButtons(); diff --git a/MechJeb2/MechJebModuleNodeEditor.cs b/MechJeb2/MechJebModuleNodeEditor.cs index 9997ed021..4c1e4a368 100644 --- a/MechJeb2/MechJebModuleNodeEditor.cs +++ b/MechJeb2/MechJebModuleNodeEditor.cs @@ -12,16 +12,16 @@ public class MechJebModuleNodeEditor : DisplayModule private EditableDouble radialPlus = 0; private EditableDouble normalPlus = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableDouble progradeDelta = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableDouble radialPlusDelta = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private EditableDouble normalPlusDelta = 0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] private readonly EditableTime timeOffset = 0; private ManeuverNode node; @@ -47,8 +47,8 @@ private void GizmoUpdateHandler(Vector3d dV, double UT) private void MergeNext(int index) { - ManeuverNode cur = vessel.patchedConicSolver.maneuverNodes[index]; - ManeuverNode next = vessel.patchedConicSolver.maneuverNodes[index + 1]; + ManeuverNode cur = Vessel.patchedConicSolver.maneuverNodes[index]; + ManeuverNode next = Vessel.patchedConicSolver.maneuverNodes[index + 1]; double newUT = (cur.UT + next.UT) / 2; cur.UpdateNode(cur.patch.DeltaVToManeuverNodeCoordinates(newUT, cur.WorldDeltaV() + next.WorldDeltaV()), newUT); @@ -57,7 +57,7 @@ private void MergeNext(int index) protected override void WindowGUI(int windowID) { - if (vessel.patchedConicSolver.maneuverNodes.Count == 0) + if (Vessel.patchedConicSolver.maneuverNodes.Count == 0) { GUILayout.Label(Localizer.Format("#MechJeb_NodeEd_Label1")); //"No maneuver nodes to edit." RelativityModeSelectUI(); @@ -69,20 +69,20 @@ protected override void WindowGUI(int windowID) ManeuverNode oldNode = node; - if (vessel.patchedConicSolver.maneuverNodes.Count == 1) + if (Vessel.patchedConicSolver.maneuverNodes.Count == 1) { - node = vessel.patchedConicSolver.maneuverNodes[0]; + node = Vessel.patchedConicSolver.maneuverNodes[0]; } else { - if (!vessel.patchedConicSolver.maneuverNodes.Contains(node)) node = vessel.patchedConicSolver.maneuverNodes[0]; + if (!Vessel.patchedConicSolver.maneuverNodes.Contains(node)) node = Vessel.patchedConicSolver.maneuverNodes[0]; - int nodeIndex = vessel.patchedConicSolver.maneuverNodes.IndexOf(node); - int numNodes = vessel.patchedConicSolver.maneuverNodes.Count; + int nodeIndex = Vessel.patchedConicSolver.maneuverNodes.IndexOf(node); + int numNodes = Vessel.patchedConicSolver.maneuverNodes.Count; nodeIndex = GuiUtils.ArrowSelector(nodeIndex, numNodes, "Maneuver node #" + (nodeIndex + 1)); - node = vessel.patchedConicSolver.maneuverNodes[nodeIndex]; + node = Vessel.patchedConicSolver.maneuverNodes[nodeIndex]; if (nodeIndex < numNodes - 1 && GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button1"))) MergeNext(nodeIndex); //"Merge next node" } @@ -222,19 +222,19 @@ protected override void WindowGUI(int windowID) break; case Snap.REL_ASCENDING: - if (core.Target.NormalTargetExists && core.Target.TargetOrbit.referenceBody == o.referenceBody) + if (Core.Target.NormalTargetExists && Core.Target.TargetOrbit.referenceBody == o.referenceBody) { - if (o.AscendingNodeExists(core.Target.TargetOrbit)) - UT = o.TimeOfAscendingNode(core.Target.TargetOrbit, UT - o.period / 2); + if (o.AscendingNodeExists(Core.Target.TargetOrbit)) + UT = o.TimeOfAscendingNode(Core.Target.TargetOrbit, UT - o.period / 2); } break; case Snap.REL_DESCENDING: - if (core.Target.NormalTargetExists && core.Target.TargetOrbit.referenceBody == o.referenceBody) + if (Core.Target.NormalTargetExists && Core.Target.TargetOrbit.referenceBody == o.referenceBody) { - if (o.DescendingNodeExists(core.Target.TargetOrbit)) - UT = o.TimeOfDescendingNode(core.Target.TargetOrbit, UT - o.period / 2); + if (o.DescendingNodeExists(Core.Target.TargetOrbit)) + UT = o.TimeOfDescendingNode(Core.Target.TargetOrbit, UT - o.period / 2); } break; @@ -250,41 +250,41 @@ protected override void WindowGUI(int windowID) RelativityModeSelectUI(); - if (core.Node != null) + if (Core.Node != null) { - if (vessel.patchedConicSolver.maneuverNodes.Count > 0 && !core.Node.enabled) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 0 && !Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button4"))) //"Execute next node" { - core.Node.ExecuteOneNode(this); + Core.Node.ExecuteOneNode(this); } if (VesselState.isLoadedPrincipia && GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button7"))) //Execute next Principia node { - core.Node.ExecuteOnePNode(this); + Core.Node.ExecuteOnePNode(this); } - if (vessel.patchedConicSolver.maneuverNodes.Count > 1) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 1) { if (GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button5"))) //"Execute all nodes" { - core.Node.ExecuteAllNodes(this); + Core.Node.ExecuteAllNodes(this); } } } - else if (core.Node.enabled) + else if (Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_NodeEd_button6"))) //"Abort node execution" { - core.Node.Abort(); + Core.Node.Abort(); } } GUILayout.BeginHorizontal(); - core.Node.autowarp = - GUILayout.Toggle(core.Node.autowarp, Localizer.Format("#MechJeb_NodeEd_checkbox1"), GUILayout.ExpandWidth(true)); //"Auto-warp" + Core.Node.autowarp = + GUILayout.Toggle(Core.Node.autowarp, Localizer.Format("#MechJeb_NodeEd_checkbox1"), GUILayout.ExpandWidth(true)); //"Auto-warp" GUILayout.Label(Localizer.Format("#MechJeb_NodeEd_Label7"), GUILayout.ExpandWidth(false)); //"Tolerance:" - core.Node.tolerance.text = GUILayout.TextField(core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); + Core.Node.tolerance.text = GUILayout.TextField(Core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); GUILayout.Label("m/s", GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); } @@ -315,12 +315,12 @@ private void RelativityModeSelectUI() GUILayout.BeginHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_NodeEd_Label8"), GUILayout.ExpandWidth(false)); //"Conics mode:" - int newRelativityMode = GUILayout.SelectionGrid((int)vessel.patchedConicRenderer.relativityMode, relativityModeStrings, 5); - vessel.patchedConicRenderer.relativityMode = (PatchRendering.RelativityMode)newRelativityMode; + int newRelativityMode = GUILayout.SelectionGrid((int)Vessel.patchedConicRenderer.relativityMode, relativityModeStrings, 5); + Vessel.patchedConicRenderer.relativityMode = (PatchRendering.RelativityMode)newRelativityMode; GUILayout.EndHorizontal(); GUILayout.Label(Localizer.Format("#MechJeb_NodeEd_Label9", - vessel.patchedConicRenderer.relativityMode.ToString())); //"Current mode: <<1>>" + Vessel.patchedConicRenderer.relativityMode.ToString())); //"Current mode: <<1>>" GUILayout.EndVertical(); } @@ -340,9 +340,9 @@ public override string IconName() return "Maneuver Node Editor"; } - public override bool IsSpaceCenterUpgradeUnlocked() + protected override bool IsSpaceCenterUpgradeUnlocked() { - return vessel.patchedConicsUnlocked(); + return Vessel.patchedConicsUnlocked(); } public MechJebModuleNodeEditor(MechJebCore core) : base(core) { } diff --git a/MechJeb2/MechJebModuleNodeExecutor.cs b/MechJeb2/MechJebModuleNodeExecutor.cs index 6639cd45e..2bbdbb99c 100644 --- a/MechJeb2/MechJebModuleNodeExecutor.cs +++ b/MechJeb2/MechJebModuleNodeExecutor.cs @@ -8,19 +8,19 @@ namespace MuMech public class MechJebModuleNodeExecutor : ComputerModule { //public interface: - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autowarp = true; //whether to auto-warp to nodes - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble leadTime = 3; //how many seconds before a burn to end warp (note that we align with the node before warping) - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble tolerance = 0.1; //we decide we're finished the burn when the remaining dV falls below this value (in m/s) [ValueInfoItem("#MechJeb_NodeBurnLength", InfoItem.Category.Thrust)] //Node Burn Length public string NextNodeBurnTime() { - if (!vessel.patchedConicsUnlocked()) + if (!Vessel.patchedConicsUnlocked()) return "-"; double dV; @@ -30,10 +30,10 @@ public string NextNodeBurnTime() } else { - if (vessel.patchedConicSolver.maneuverNodes.Count == 0) + if (Vessel.patchedConicSolver.maneuverNodes.Count == 0) return "-"; - ManeuverNode node = vessel.patchedConicSolver.maneuverNodes[0]; - dV = node.GetBurnVector(orbit).magnitude; + ManeuverNode node = Vessel.patchedConicSolver.maneuverNodes[0]; + dV = node.GetBurnVector(Orbit).magnitude; } double halfBurnTime, spool; @@ -43,9 +43,9 @@ public string NextNodeBurnTime() [ValueInfoItem("#MechJeb_NodeBurnCountdown", InfoItem.Category.Thrust)] //Node Burn Countdown public string NextNodeCountdown() { - if (!vessel.patchedConicsUnlocked() || vessel.patchedConicSolver.maneuverNodes.Count == 0) + if (!Vessel.patchedConicsUnlocked() || Vessel.patchedConicSolver.maneuverNodes.Count == 0) return "-"; - ManeuverNode node = vessel.patchedConicSolver.maneuverNodes[0]; + ManeuverNode node = Vessel.patchedConicSolver.maneuverNodes[0]; double dV; bool isPrincipia = VesselState.isLoadedPrincipia; if (isPrincipia) @@ -54,7 +54,7 @@ public string NextNodeCountdown() } else { - dV = node.GetBurnVector(orbit).magnitude; + dV = node.GetBurnVector(Orbit).magnitude; } double UT = node.UT; @@ -65,13 +65,13 @@ public string NextNodeCountdown() else UT -= halfBurnTIme; // already takes spoolup into account - return GuiUtils.TimeToDHMS(UT - vesselState.time); + return GuiUtils.TimeToDHMS(UT - VesselState.time); } public void ExecuteOneNode(object controller) { mode = Mode.ONE_NODE; - users.Add(controller); + Users.Add(controller); burnTriggered = false; alignedForBurn = false; remainingDeltaV = 0; @@ -80,17 +80,17 @@ public void ExecuteOneNode(object controller) public void ExecuteOnePNode(object controller) //Principia Node { mode = Mode.ONE_PNODE; - users.Add(controller); + Users.Add(controller); burnTriggered = false; alignedForBurn = false; - remainingDeltaV = vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(orbit).magnitude; + remainingDeltaV = Vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(Orbit).magnitude; } public void ExecuteAllNodes(object controller) { mode = Mode.ALL_NODES; - users.Add(controller); + Users.Add(controller); burnTriggered = false; alignedForBurn = false; remainingDeltaV = 0; @@ -98,23 +98,23 @@ public void ExecuteAllNodes(object controller) public void Abort() { - core.Warp.MinimumWarp(); - users.Clear(); + Core.Warp.MinimumWarp(); + Users.Clear(); remainingDeltaV = 0; burnTriggered = false; } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { - core.Attitude.users.Add(this); - core.Thrust.users.Add(this); + Core.Attitude.Users.Add(this); + Core.Thrust.Users.Add(this); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Attitude.attitudeDeactivate(); - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); remainingDeltaV = 0; } @@ -129,14 +129,14 @@ protected enum Mode { ONE_NODE, ONE_PNODE, ALL_NODES } public override void Drive(FlightCtrlState s) { - if (!burnTriggered && nearingBurn && core.Thrust.limitToPreventUnstableIgnition && - vesselState.lowestUllage != VesselState.UllageState.VeryStable) + if (!burnTriggered && nearingBurn && Core.Thrust.limitToPreventUnstableIgnition && + VesselState.lowestUllage != VesselState.UllageState.VeryStable) { - if (vessel.hasEnabledRCSModules()) + if (Vessel.hasEnabledRCSModules()) { - if (!vessel.ActionGroups[KSPActionGroup.RCS]) + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) { - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } s.Z = -1.0F; @@ -148,8 +148,8 @@ public override void OnFixedUpdate() { nearingBurn = false; bool hasPrincipia = VesselState.isLoadedPrincipia; - bool hasNodes = vessel.patchedConicSolver.maneuverNodes.Count > 0; - if (!vessel.patchedConicsUnlocked() + bool hasNodes = Vessel.patchedConicSolver.maneuverNodes.Count > 0; + if (!Vessel.patchedConicsUnlocked() || (!hasPrincipia && !hasNodes)) { Abort(); @@ -167,60 +167,60 @@ public override void OnFixedUpdate() } //aim along the node - ManeuverNode node = hasNodes ? vessel.patchedConicSolver.maneuverNodes[0] : null; + ManeuverNode node = hasNodes ? Vessel.patchedConicSolver.maneuverNodes[0] : null; if (hasNodes) { - core.Attitude.attitudeTo(Vector3d.forward, AttitudeReference.MANEUVER_NODE_COT, this); + Core.Attitude.attitudeTo(Vector3d.forward, AttitudeReference.MANEUVER_NODE_COT, this); } else { - if (!core.Attitude.attitudeKILLROT) + if (!Core.Attitude.attitudeKILLROT) { - core.Attitude.attitudeTo(Quaternion.LookRotation(vessel.GetTransform().up, -vessel.GetTransform().forward), + Core.Attitude.attitudeTo(Quaternion.LookRotation(Vessel.GetTransform().up, -Vessel.GetTransform().forward), AttitudeReference.INERTIAL, this); - core.Attitude.attitudeKILLROT = true; + Core.Attitude.attitudeKILLROT = true; } } double halfBurnTime, spool; BurnTime(remainingDeltaV, out halfBurnTime, out spool); - double timeToNode = hasNodes ? node.UT - vesselState.time : -1; + double timeToNode = hasNodes ? node.UT - VesselState.time : -1; //print("$$$$$$$ Executor: Node in " + timeToNode + ", spool " + spool.ToString("F3")); if ((halfBurnTime > 0 && timeToNode <= spool) || timeToNode < 0) { burnTriggered = true; - if (!MuUtils.PhysicsRunning()) core.Warp.MinimumWarp(); + if (!MuUtils.PhysicsRunning()) Core.Warp.MinimumWarp(); } //autowarp, but only if we're already aligned with the node if (autowarp && !burnTriggered) { if (timeToNode > 600 || (MuUtils.PhysicsRunning() - ? core.Attitude.attitudeAngleFromTarget() < 1 && core.vessel.angularVelocity.magnitude < 0.001 - : core.Attitude.attitudeAngleFromTarget() < 10)) + ? Core.Attitude.attitudeAngleFromTarget() < 1 && Core.vessel.angularVelocity.magnitude < 0.001 + : Core.Attitude.attitudeAngleFromTarget() < 10)) { - core.Warp.WarpToUT(timeToNode + vesselState.time - spool - leadTime); + Core.Warp.WarpToUT(timeToNode + VesselState.time - spool - leadTime); } else { //realign - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); } } nearingBurn = timeToNode - spool - leadTime <= 0; - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; if (burnTriggered) { if (alignedForBurn) { - if (core.Attitude.attitudeAngleFromTarget() < 90) + if (Core.Attitude.attitudeAngleFromTarget() < 90) { - double timeConstant = remainingDeltaV > 10 || vesselState.minThrustAccel > 0.25 * vesselState.maxThrustAccel ? 0.5 : 2; - core.Thrust.ThrustForDV(remainingDeltaV + tolerance, timeConstant); + double timeConstant = remainingDeltaV > 10 || VesselState.minThrustAccel > 0.25 * VesselState.maxThrustAccel ? 0.5 : 2; + Core.Thrust.ThrustForDV(remainingDeltaV + tolerance, timeConstant); // We'll subtract delta V later. } else @@ -230,7 +230,7 @@ public override void OnFixedUpdate() } else { - if (core.Attitude.attitudeAngleFromTarget() < 2) + if (Core.Attitude.attitudeAngleFromTarget() < 2) { alignedForBurn = true; } @@ -243,17 +243,17 @@ public override void OnFixedUpdate() // Since this is Principia, we can't rely on the node's delta V itself updating, we have to do it ourselves. // We also can't just use vesselState.currentThrustAccel because only engines are counted. // NOTE: This *will* include acceleration from decouplers, which is pretty cool. - Vector3d dV = (vessel.acceleration_immediate - vessel.graviticAcceleration) * TimeWarp.fixedDeltaTime; - remainingDeltaV -= Vector3d.Dot(dV, core.Attitude.targetAttitude()); + Vector3d dV = (Vessel.acceleration_immediate - Vessel.graviticAcceleration) * TimeWarp.fixedDeltaTime; + remainingDeltaV -= Vector3d.Dot(dV, Core.Attitude.targetAttitude()); } } else if (hasNodes) { //check if we've finished a node: - ManeuverNode node = vessel.patchedConicSolver.maneuverNodes[0]; - double dVLeft = node.GetBurnVector(orbit).magnitude; + ManeuverNode node = Vessel.patchedConicSolver.maneuverNodes[0]; + double dVLeft = node.GetBurnVector(Orbit).magnitude; - if (dVLeft < tolerance && core.Attitude.attitudeAngleFromTarget() > 5) + if (dVLeft < tolerance && Core.Attitude.attitudeAngleFromTarget() > 5) { burnTriggered = false; @@ -267,60 +267,60 @@ public override void OnFixedUpdate() if (mode == Mode.ALL_NODES) { - if (vessel.patchedConicSolver.maneuverNodes.Count == 0) + if (Vessel.patchedConicSolver.maneuverNodes.Count == 0) { Abort(); return; } - node = vessel.patchedConicSolver.maneuverNodes[0]; + node = Vessel.patchedConicSolver.maneuverNodes[0]; } } //aim along the node - core.Attitude.attitudeTo(Vector3d.forward, AttitudeReference.MANEUVER_NODE_COT, this); + Core.Attitude.attitudeTo(Vector3d.forward, AttitudeReference.MANEUVER_NODE_COT, this); double halfBurnTime, spool; BurnTime(dVLeft, out halfBurnTime, out spool); - double timeToNode = node.UT - vesselState.time; + double timeToNode = node.UT - VesselState.time; //(!double.IsInfinity(num) && num > 0.0 && num2 < num) || num2 <= 0.0 if (mode == Mode.ONE_NODE || mode == Mode.ALL_NODES) { if (timeToNode < halfBurnTime) { burnTriggered = true; - if (!MuUtils.PhysicsRunning()) core.Warp.MinimumWarp(); + if (!MuUtils.PhysicsRunning()) Core.Warp.MinimumWarp(); } } //autowarp, but only if we're already aligned with the node if (autowarp && !burnTriggered) { - if ((core.Attitude.attitudeAngleFromTarget() < 1 && core.vessel.angularVelocity.magnitude < 0.001) || - (core.Attitude.attitudeAngleFromTarget() < 10 && !MuUtils.PhysicsRunning())) + if ((Core.Attitude.attitudeAngleFromTarget() < 1 && Core.vessel.angularVelocity.magnitude < 0.001) || + (Core.Attitude.attitudeAngleFromTarget() < 10 && !MuUtils.PhysicsRunning())) { - core.Warp.WarpToUT(node.UT - halfBurnTime - leadTime); + Core.Warp.WarpToUT(node.UT - halfBurnTime - leadTime); } - else if (!MuUtils.PhysicsRunning() && core.Attitude.attitudeAngleFromTarget() > 10 && timeToNode < 600) + else if (!MuUtils.PhysicsRunning() && Core.Attitude.attitudeAngleFromTarget() > 10 && timeToNode < 600) { //realign - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); } } nearingBurn = timeToNode - halfBurnTime - leadTime <= 0; - core.Thrust.targetThrottle = 0; + Core.Thrust.targetThrottle = 0; if (burnTriggered) { if (alignedForBurn) { - if (core.Attitude.attitudeAngleFromTarget() < 90) + if (Core.Attitude.attitudeAngleFromTarget() < 90) { - double timeConstant = dVLeft > 10 || vesselState.minThrustAccel > 0.25 * vesselState.maxThrustAccel ? 0.5 : 2; - core.Thrust.ThrustForDV(dVLeft + tolerance, timeConstant); + double timeConstant = dVLeft > 10 || VesselState.minThrustAccel > 0.25 * VesselState.maxThrustAccel ? 0.5 : 2; + Core.Thrust.ThrustForDV(dVLeft + tolerance, timeConstant); } else { @@ -329,7 +329,7 @@ public override void OnFixedUpdate() } else { - if (core.Attitude.attitudeAngleFromTarget() < 2) + if (Core.Attitude.attitudeAngleFromTarget() < 2) { alignedForBurn = true; } @@ -350,7 +350,7 @@ private double BurnTime(double dv, out double halfBurnTime, out double spoolupTi // Old code: // burnTime = dv / vesselState.limitedMaxThrustAccel; - MechJebModuleStageStats stats = core.GetComputerModule(); + MechJebModuleStageStats stats = Core.GetComputerModule(); stats.RequestUpdate(this, true); double lastStageBurnTime = 0; @@ -359,13 +359,13 @@ private double BurnTime(double dv, out double halfBurnTime, out double spoolupTi FuelFlowSimulation.FuelStats s = stats.vacStats[i]; if (s.DeltaV <= 0 || s.StartThrust <= 0) { - if (core.Staging.enabled) + if (Core.Staging.Enabled) { // We staged again before autostagePreDelay is elapsed. // Add the remaining wait time - if (burnTime - lastStageBurnTime < core.Staging.autostagePreDelay && i != stats.vacStats.Length - 1) - burnTime += core.Staging.autostagePreDelay - (burnTime - lastStageBurnTime); - burnTime += core.Staging.autostagePreDelay; + if (burnTime - lastStageBurnTime < Core.Staging.autostagePreDelay && i != stats.vacStats.Length - 1) + burnTime += Core.Staging.autostagePreDelay - (burnTime - lastStageBurnTime); + burnTime += Core.Staging.autostagePreDelay; lastStageBurnTime = burnTime; } @@ -392,7 +392,7 @@ private double BurnTime(double dv, out double halfBurnTime, out double spoolupTi // TODO: Be smarter about throttle limits on future stages. if (i == stats.vacStats.Length - 1) { - stageAvgAccel *= vesselState.throttleFixedLimit; + stageAvgAccel *= VesselState.throttleFixedLimit; } halfBurnTime += Math.Min(halfDvLeft, stageBurnDv) / stageAvgAccel; diff --git a/MechJeb2/MechJebModulePVGGlueBall.cs b/MechJeb2/MechJebModulePVGGlueBall.cs index d392dcc02..374fff965 100644 --- a/MechJeb2/MechJebModulePVGGlueBall.cs +++ b/MechJeb2/MechJebModulePVGGlueBall.cs @@ -35,26 +35,26 @@ public class MechJebModulePVGGlueBall : ComputerModule public MechJebModulePVGGlueBall(MechJebCore core) : base(core) { } - private MechJebModuleAscentSettings _ascentSettings => core.AscentSettings; + private MechJebModuleAscentSettings _ascentSettings => Core.AscentSettings; private Task? _task; private Ascent? _ascent; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { SuccessfulConverges = LastLmStatus = MaxLmIterations = 0; LastLmStatus = LastLmIterations = 0; Staleness = LastZnorm = _lastTime = 0; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { } public override void OnFixedUpdate() { - core.StageStats.RequestUpdate(this); + Core.StageStats.RequestUpdate(this); } public override void OnStart(PartModule.StartState state) @@ -69,13 +69,13 @@ public override void OnDestroy() private void HandleStageEvent(int data) { - _blockOptimizerUntilTime = vesselState.time + _ascentSettings.OptimizerPauseTime; + _blockOptimizerUntilTime = VesselState.time + _ascentSettings.OptimizerPauseTime; } private bool VesselOffGround() { - return vessel.situation != Vessel.Situations.LANDED && vessel.situation != Vessel.Situations.PRELAUNCH && - vessel.situation != Vessel.Situations.SPLASHED; + return Vessel.situation != Vessel.Situations.LANDED && Vessel.situation != Vessel.Situations.PRELAUNCH && + Vessel.situation != Vessel.Situations.SPLASHED; } private bool IsUnguided(int s) @@ -95,9 +95,9 @@ private void HandleDoneTask() { if (pvg.Success()) { - core.Guidance.SetSolution(pvg.GetSolution()); + Core.Guidance.SetSolution(pvg.GetSolution()); SuccessfulConverges += 1; - _lastTime = vesselState.time; + _lastTime = VesselState.time; Staleness = 0; } else @@ -130,9 +130,9 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d { // initialize the first time we hit SetTarget to avoid initial large staleness values if (_lastTime == 0) - _lastTime = vesselState.time; + _lastTime = VesselState.time; - Staleness = vesselState.time - _lastTime; + Staleness = VesselState.time - _lastTime; GatherException(); @@ -157,9 +157,9 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d { bool hasGuided = false; - for (int i = core.StageStats.vacStats.Length - 1; i >= _ascentSettings.LastStage; i--) + for (int i = Core.StageStats.vacStats.Length - 1; i >= _ascentSettings.LastStage; i--) { - double dv = core.StageStats.vacStats[i].DeltaV; + double dv = Core.StageStats.vacStats[i].DeltaV; // skip the zero length stages if (dv == 0) @@ -175,44 +175,44 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d } // check for readiness (not terminal guidance and not finished) - if (!core.Guidance.IsReady()) + if (!Core.Guidance.IsReady()) return; - if (core.Guidance.Solution != null) + if (Core.Guidance.Solution != null) { - int solutionIndex = core.Guidance.Solution.IndexForKSPStage(vessel.currentStage, core.Guidance.IsCoasting()); + 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) + if (Core.Guidance.Solution?.Tgo(VesselState.time, solutionIndex) < _ascentSettings.PreStageTime) { - _blockOptimizerUntilTime = vesselState.time + _ascentSettings.OptimizerPauseTime; + _blockOptimizerUntilTime = VesselState.time + _ascentSettings.OptimizerPauseTime; return; } } } - if (_blockOptimizerUntilTime > vesselState.time) + 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) + .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)); + .TerminalConditions(Maths.HmagFromApsides(MainBody.gravParameter, peR, apR)); - if (core.Guidance.Solution != null) - ascentBuilder.OldSolution(core.Guidance.Solution); + if (Core.Guidance.Solution != null) + ascentBuilder.OldSolution(Core.Guidance.Solution); bool optimizedStageFound = false; - for (int i = core.StageStats.vacStats.Length - 1; i >= _ascentSettings.LastStage; i--) + for (int i = Core.StageStats.vacStats.Length - 1; i >= _ascentSettings.LastStage; i--) { - FuelFlowSimulation.FuelStats fuelStats = core.StageStats.vacStats[i]; + FuelFlowSimulation.FuelStats fuelStats = Core.StageStats.vacStats[i]; - if (!core.Guidance.HasGoodSolutionWithNoFutureCoast()) + if (!Core.Guidance.HasGoodSolutionWithNoFutureCoast()) { if ((i == _ascentSettings.CoastStage && _ascentSettings.CoastBeforeFlag) || (i == _ascentSettings.CoastStage - 1 && !_ascentSettings.CoastBeforeFlag)) @@ -221,11 +221,11 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d double maxt = _ascentSettings.MaxCoast; double mint = _ascentSettings.MinCoast; - if (i == vessel.currentStage && core.Guidance.IsCoasting()) + if (i == 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); + 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) @@ -261,7 +261,7 @@ public void SetTarget(double peR, double apR, double attR, double inclination, d _task = new Task(_ascent.Run); _task.Start(); - _blockOptimizerUntilTime = vesselState.time + 1; + _blockOptimizerUntilTime = VesselState.time + 1; } } } diff --git a/MechJeb2/MechJebModuleRCSBalancer.cs b/MechJeb2/MechJebModuleRCSBalancer.cs index 2d45d8674..a680bc64d 100644 --- a/MechJeb2/MechJebModuleRCSBalancer.cs +++ b/MechJeb2/MechJebModuleRCSBalancer.cs @@ -10,34 +10,34 @@ namespace MuMech [UsedImplicitly] public class MechJebModuleRCSBalancer : ComputerModule { - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] [ToggleInfoItem("#MechJeb_smartTranslation", InfoItem.Category.Thrust)] //Smart RCS translation public bool smartTranslation = false; // Overdrive - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] [EditableInfoItem("#MechJeb_RCSBalancerOverdrive", InfoItem.Category.Thrust, rightLabel = "%")] //RCS balancer overdrive public EditableDoubleMult overdrive = new EditableDoubleMult(1, 0.01); // Advanced options - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool advancedOptions = false; // Advanced: overdrive scale. While 'overdrive' will range from 0..1, // we should reduce it slightly before using it to control the 'waste // threshold' tuning parameter, because waste thresholds of 1 or above // cause problems by allowing unhelpful thrusters to fire. - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble overdriveScale = 0.9; // Advanced: tuning parameters - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble tuningParamFactorTorque = 1; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble tuningParamFactorTranslate = 0.005; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble tuningParamFactorWaste = 1; // Variables for RCS solving. @@ -83,9 +83,9 @@ private void RCSThrusterStateInfoItem() bool firstRcsModule = true; string thrusterStates = ""; - for (int index = 0; index < vessel.parts.Count; index++) + for (int index = 0; index < Vessel.parts.Count; index++) { - Part p = vessel.parts[index]; + Part p = Vessel.parts[index]; foreach (ModuleRCS pm in p.Modules.OfType()) { if (!firstRcsModule) @@ -121,9 +121,9 @@ private void RCSPartThrottlesInfoItem() bool firstRcsModule = true; string thrusterStates = ""; - for (int index = 0; index < vessel.parts.Count; index++) + for (int index = 0; index < Vessel.parts.Count; index++) { - Part p = vessel.parts[index]; + Part p = Vessel.parts[index]; foreach (ModuleRCS pm in p.Modules.OfType()) { if (!firstRcsModule) @@ -156,10 +156,10 @@ private void ControlVectorInfoItem() public MechJebModuleRCSBalancer(MechJebCore core) : base(core) { - priority = 700; + Priority = 700; } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { UpdateTuningParameters(); solverThread.start(); @@ -167,7 +167,7 @@ public override void OnModuleEnabled() base.OnModuleEnabled(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { solverThread.stop(); @@ -181,7 +181,7 @@ public void ResetThrusterForces() public void GetThrottles(Vector3 direction, out double[] throttles, out List thrusters) { - solverThread.GetThrottles(vessel, vesselState, direction, out throttles, out thrusters); + solverThread.GetThrottles(Vessel, VesselState, direction, out throttles, out thrusters); } // Throttles RCS thrusters to keep a vessel balanced during translation. diff --git a/MechJeb2/MechJebModuleRCSBalancerWindow.cs b/MechJeb2/MechJebModuleRCSBalancerWindow.cs index 39193a3d0..ccabd06aa 100644 --- a/MechJeb2/MechJebModuleRCSBalancerWindow.cs +++ b/MechJeb2/MechJebModuleRCSBalancerWindow.cs @@ -12,11 +12,11 @@ public class MechJebModuleRCSBalancerWindow : DisplayModule public override void OnStart(PartModule.StartState state) { - balancer = core.GetComputerModule(); + balancer = Core.GetComputerModule(); if (balancer.smartTranslation) { - balancer.users.Add(this); + balancer.Users.Add(this); } base.OnStart(state); @@ -48,11 +48,11 @@ protected override void WindowGUI(int windowID) if (balancer.smartTranslation) { - balancer.users.Add(this); + balancer.Users.Add(this); } else { - balancer.users.Remove(this); + balancer.Users.Remove(this); } } @@ -105,11 +105,11 @@ protected override void WindowGUI(int windowID) if (balancer.smartTranslation) { - balancer.users.Add(this); + balancer.Users.Add(this); } else { - balancer.users.Remove(this); + balancer.Users.Remove(this); } GUILayout.EndVertical(); diff --git a/MechJeb2/MechJebModuleRCSController.cs b/MechJeb2/MechJebModuleRCSController.cs index 5e1d239a4..04d06f33f 100644 --- a/MechJeb2/MechJebModuleRCSController.cs +++ b/MechJeb2/MechJebModuleRCSController.cs @@ -24,45 +24,45 @@ private enum ControlType private ControlType controlType; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] [ToggleInfoItem("#MechJeb_conserveFuel", InfoItem.Category.Thrust)] //Conserve RCS fuel public bool conserveFuel = false; [EditableInfoItem("#MechJeb_conserveThreshold", InfoItem.Category.Thrust, rightLabel = "m/s")] //Conserve RCS fuel threshold public EditableDouble conserveThreshold = 0.05; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] [EditableInfoItem("#MechJeb_RCSTf", InfoItem.Category.Thrust)] //RCS Tf public EditableDouble Tf = 1; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public EditableDouble Kp = 0.125; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public EditableDouble Ki = 0.07; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public EditableDouble Kd = 0.53; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool rcsManualPID; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] [ToggleInfoItem("#MechJeb_RCSThrottle", InfoItem.Category.Thrust)] //RCS throttle when 0kn thrust public bool rcsThrottle = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] [ToggleInfoItem("#MechJeb_rcsForRotation", InfoItem.Category.Thrust)] //Use RCS for rotation public bool rcsForRotation = true; public MechJebModuleRCSController(MechJebCore core) : base(core) { - priority = 600; + Priority = 600; pid = new PIDControllerV2(Kp, Ki, Kd, 1, -1); } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { setPIDParameters(); pid.Reset(); @@ -75,7 +75,7 @@ public override void OnModuleEnabled() public bool rcsDeactivate() { - users.Clear(); + Users.Clear(); return true; } @@ -149,9 +149,9 @@ public double rcsAccelFactor() return pid.Kp; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); base.OnModuleDisabled(); } @@ -187,7 +187,7 @@ public override void Drive(FlightCtrlState s) // Removed the gravity since it also affect the target and we don't know the target pos here. // Since the difference is negligable for docking it's removed // TODO : add it back once we use the RCS Controler for other use than docking. Account for current acceleration beside gravity ? - worldVelocityDelta = vesselState.orbitalVelocity - targetVelocity; + worldVelocityDelta = VesselState.orbitalVelocity - targetVelocity; //worldVelocityDelta += TimeWarp.fixedDeltaTime * vesselState.gravityForce; //account for one frame's worth of gravity //worldVelocityDelta -= TimeWarp.fixedDeltaTime * gravityForce = FlightGlobals.getGeeForceAtPosition( Here be the target position ); ; //account for one frame's worth of gravity break; @@ -197,24 +197,24 @@ public override void Drive(FlightCtrlState s) break; case ControlType.VELOCITY_TARGET_REL: - if (core.Target.Target == null) + if (Core.Target.Target == null) { rcsDeactivate(); return; } - worldVelocityDelta = core.Target.RelativeVelocity - targetVelocity; + worldVelocityDelta = Core.Target.RelativeVelocity - targetVelocity; break; } // We work in local vessel coordinate - Vector3d velocityDelta = Quaternion.Inverse(vessel.GetTransform().rotation) * worldVelocityDelta; + Vector3d velocityDelta = Quaternion.Inverse(Vessel.GetTransform().rotation) * worldVelocityDelta; if (!conserveFuel || velocityDelta.magnitude > conserveThreshold) { - if (!vessel.ActionGroups[KSPActionGroup.RCS]) + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) { - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } var rcs = new Vector3d(); @@ -223,10 +223,10 @@ public override void Drive(FlightCtrlState s) { Vector6.Direction dir = Vector6.Values[i]; double dirDv = Vector3d.Dot(velocityDelta, Vector6.directions[(int)dir]); - double dirAvail = vesselState.rcsThrustAvailable[dir]; + double dirAvail = VesselState.rcsThrustAvailable[dir]; if (dirAvail > 0 && Math.Abs(dirDv) > 0.001) { - double dirAction = dirDv / (dirAvail * TimeWarp.fixedDeltaTime / vesselState.mass); + double dirAction = dirDv / (dirAvail * TimeWarp.fixedDeltaTime / VesselState.mass); if (dirAction > 0) { rcs += Vector6.directions[(int)dir] * dirAction; @@ -239,7 +239,7 @@ public override void Drive(FlightCtrlState s) switch (controlType) { case ControlType.TARGET_VELOCITY: - omega = Quaternion.Inverse(vessel.GetTransform().rotation) * (vessel.acceleration - vesselState.gravityForce); + omega = Quaternion.Inverse(Vessel.GetTransform().rotation) * (Vessel.acceleration - VesselState.gravityForce); break; case ControlType.VELOCITY_TARGET_REL: @@ -261,9 +261,9 @@ public override void Drive(FlightCtrlState s) } else if (conserveFuel) { - if (vessel.ActionGroups[KSPActionGroup.RCS]) + if (Vessel.ActionGroups[KSPActionGroup.RCS]) { - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false); } } diff --git a/MechJeb2/MechJebModuleRendezvousAutopilot.cs b/MechJeb2/MechJebModuleRendezvousAutopilot.cs index 72942a90a..379c6de6a 100644 --- a/MechJeb2/MechJebModuleRendezvousAutopilot.cs +++ b/MechJeb2/MechJebModuleRendezvousAutopilot.cs @@ -10,81 +10,81 @@ public class MechJebModuleRendezvousAutopilot : ComputerModule { public MechJebModuleRendezvousAutopilot(MechJebCore core) : base(core) { } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble desiredDistance = 100; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble maxPhasingOrbits = 5; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble maxClosingSpeed = 100; public string status = ""; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { - vessel.RemoveAllManeuverNodes(); - if (!MuUtils.PhysicsRunning()) core.Warp.MinimumWarp(); + Vessel.RemoveAllManeuverNodes(); + if (!MuUtils.PhysicsRunning()) Core.Warp.MinimumWarp(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Node.Abort(); //make sure we turn off node executor if we get disabled suddenly + Core.Node.Abort(); //make sure we turn off node executor if we get disabled suddenly } public override void Drive(FlightCtrlState s) { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { - users.Clear(); + Users.Clear(); return; } - core.Node.autowarp = core.Node.autowarp && core.Target.Distance > 1000; + Core.Node.autowarp = Core.Node.autowarp && Core.Target.Distance > 1000; //If we get within the target distance and then next maneuver node is still //far in the future, delete it and we will create a new one to match velocities immediately. //This can often happen because the target vessel's orbit shifts slightly when it is unpacked. - if (core.Target.Distance < desiredDistance - && vessel.patchedConicSolver.maneuverNodes.Count > 0 - && vessel.patchedConicSolver.maneuverNodes[0].UT > vesselState.time + 1) + if (Core.Target.Distance < desiredDistance + && Vessel.patchedConicSolver.maneuverNodes.Count > 0 + && Vessel.patchedConicSolver.maneuverNodes[0].UT > VesselState.time + 1) { - vessel.RemoveAllManeuverNodes(); + Vessel.RemoveAllManeuverNodes(); } - if (vessel.patchedConicSolver.maneuverNodes.Count > 0) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 0) { //If we have plotted a maneuver, execute it. - if (!core.Node.enabled) core.Node.ExecuteAllNodes(this); + if (!Core.Node.Enabled) Core.Node.ExecuteAllNodes(this); } - else if (core.Target.Distance < desiredDistance * 1.05 + 2 - && core.Target.RelativeVelocity.magnitude < 1) + else if (Core.Target.Distance < desiredDistance * 1.05 + 2 + && Core.Target.RelativeVelocity.magnitude < 1) { //finished - users.Clear(); - core.Thrust.ThrustOff(); + Users.Clear(); + Core.Thrust.ThrustOff(); status = Localizer.Format("#MechJeb_RZauto_statu1"); //"Successful rendezvous" } - else if (core.Target.Distance < desiredDistance * 1.05 + 2) + else if (Core.Target.Distance < desiredDistance * 1.05 + 2) { //We are within the target distance: match velocities - double UT = vesselState.time; - Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(orbit, UT, core.Target.TargetOrbit); - vessel.PlaceManeuverNode(orbit, dV, UT); + double UT = VesselState.time; + Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(Orbit, UT, Core.Target.TargetOrbit); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu2", desiredDistance.ToString()); //"Within " + + "m: matching velocities." } - else if (core.Target.Distance < vesselState.radius / 25) + else if (Core.Target.Distance < VesselState.radius / 25) { - if (orbit.NextClosestApproachDistance(core.Target.TargetOrbit, vesselState.time) < desiredDistance - && orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time) < vesselState.time + 150) + if (Orbit.NextClosestApproachDistance(Core.Target.TargetOrbit, VesselState.time) < desiredDistance + && Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time) < VesselState.time + 150) { //We're close to the target, and on a course that will take us closer. Kill relvel at closest approach - double UT = orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time); - Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(orbit, UT, core.Target.TargetOrbit); + double UT = Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(Orbit, UT, Core.Target.TargetOrbit); //adjust burn time so as to come to rest at the desired distance from the target: - double approachDistance = orbit.Separation(core.Target.TargetOrbit, UT); - double approachSpeed = (orbit.WorldOrbitalVelocityAtUT(UT) - core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)).magnitude; + double approachDistance = Orbit.Separation(Core.Target.TargetOrbit, UT); + double approachSpeed = (Orbit.WorldOrbitalVelocityAtUT(UT) - Core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)).magnitude; if (approachDistance < desiredDistance) { UT -= Math.Sqrt(Math.Abs(desiredDistance * desiredDistance - approachDistance * approachDistance)) / approachSpeed; @@ -93,35 +93,35 @@ public override void Drive(FlightCtrlState s) //if coming in hot, stop early to avoid crashing: if (approachSpeed > 10) UT -= 1; - vessel.PlaceManeuverNode(orbit, dV, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu3"); //"Planning to match velocities at closest approach." } else { //We're not far from the target. Close the distance - double closingSpeed = core.Target.Distance / 100; + double closingSpeed = Core.Target.Distance / 100; if (closingSpeed > maxClosingSpeed) closingSpeed = maxClosingSpeed; closingSpeed = Math.Max(0.01, closingSpeed); - double closingTime = core.Target.Distance / closingSpeed; - double UT = vesselState.time + 15; + double closingTime = Core.Target.Distance / closingSpeed; + double UT = VesselState.time + 15; - (Vector3d dV, _) = OrbitalManeuverCalculator.DeltaVToInterceptAtTime(orbit, UT, core.Target.TargetOrbit, closingTime); - vessel.PlaceManeuverNode(orbit, dV, UT); + (Vector3d dV, _) = OrbitalManeuverCalculator.DeltaVToInterceptAtTime(Orbit, UT, Core.Target.TargetOrbit, closingTime); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu4"); //"Close to target: plotting intercept" } } - else if (orbit.NextClosestApproachDistance(core.Target.TargetOrbit, vesselState.time) < core.Target.TargetOrbit.semiMajorAxis / 25) + else if (Orbit.NextClosestApproachDistance(Core.Target.TargetOrbit, VesselState.time) < Core.Target.TargetOrbit.semiMajorAxis / 25) { //We're not close to the target, but we're on an approximate intercept course. //Kill relative velocities at closest approach - double UT = orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time); - Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(orbit, UT, core.Target.TargetOrbit); + double UT = Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(Orbit, UT, Core.Target.TargetOrbit); //adjust burn time so as to come to rest at the desired distance from the target: - double approachDistance = (orbit.WorldPositionAtUT(UT) - core.Target.TargetOrbit.WorldPositionAtUT(UT)).magnitude; - double approachSpeed = (orbit.WorldOrbitalVelocityAtUT(UT) - core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)).magnitude; + double approachDistance = (Orbit.WorldPositionAtUT(UT) - Core.Target.TargetOrbit.WorldPositionAtUT(UT)).magnitude; + double approachSpeed = (Orbit.WorldOrbitalVelocityAtUT(UT) - Core.Target.TargetOrbit.WorldOrbitalVelocityAtUT(UT)).magnitude; if (approachDistance < desiredDistance) { UT -= Math.Sqrt(Math.Abs(desiredDistance * desiredDistance - approachDistance * approachDistance)) / approachSpeed; @@ -130,26 +130,26 @@ public override void Drive(FlightCtrlState s) //if coming in hot, stop early to avoid crashing: if (approachSpeed > 10) UT -= 1; - vessel.PlaceManeuverNode(orbit, dV, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu5"); //"On intercept course. Planning to match velocities at closest approach." } - else if (orbit.RelativeInclination(core.Target.TargetOrbit) < 0.05 && orbit.eccentricity < 0.05) + else if (Orbit.RelativeInclination(Core.Target.TargetOrbit) < 0.05 && Orbit.eccentricity < 0.05) { //We're not on an intercept course, but we have a circular orbit in the right plane. double hohmannUT; Vector3d hohmannDV = - OrbitalManeuverCalculator.DeltaVAndTimeForHohmannTransfer(orbit, core.Target.TargetOrbit, vesselState.time, out hohmannUT); + OrbitalManeuverCalculator.DeltaVAndTimeForHohmannTransfer(Orbit, Core.Target.TargetOrbit, VesselState.time, out hohmannUT); - double numPhasingOrbits = (hohmannUT - vesselState.time) / orbit.period; + double numPhasingOrbits = (hohmannUT - VesselState.time) / Orbit.period; double actualMaxPhasingOrbits = Math.Max(maxPhasingOrbits, 5); // ignore input values that are unreasonably small if (numPhasingOrbits < actualMaxPhasingOrbits) { //It won't be too long until the intercept window. Plot a Hohmann transfer intercept. - vessel.PlaceManeuverNode(orbit, hohmannDV, hohmannUT); + Vessel.PlaceManeuverNode(Orbit, hohmannDV, hohmannUT); status = Localizer.Format("#MechJeb_RZauto_statu6", numPhasingOrbits.ToString("F2")); //"Planning Hohmann transfer for intercept after " + + " phasing orbits." @@ -158,61 +158,61 @@ public override void Drive(FlightCtrlState s) { //We are in a circular orbit in the right plane, but we aren't phasing quickly enough. Move to a better phasing orbit double axisRatio = Math.Pow(1 + 1.25 / actualMaxPhasingOrbits, 2.0 / 3.0); - double lowPhasingRadius = core.Target.TargetOrbit.semiMajorAxis / axisRatio; - double highPhasingRadius = core.Target.TargetOrbit.semiMajorAxis * axisRatio; + double lowPhasingRadius = Core.Target.TargetOrbit.semiMajorAxis / axisRatio; + double highPhasingRadius = Core.Target.TargetOrbit.semiMajorAxis * axisRatio; - bool useLowPhasingRadius = lowPhasingRadius > mainBody.Radius + mainBody.RealMaxAtmosphereAltitude() + 3000 && - orbit.semiMajorAxis < core.Target.TargetOrbit.semiMajorAxis; + bool useLowPhasingRadius = lowPhasingRadius > MainBody.Radius + MainBody.RealMaxAtmosphereAltitude() + 3000 && + Orbit.semiMajorAxis < Core.Target.TargetOrbit.semiMajorAxis; double phasingOrbitRadius = useLowPhasingRadius ? lowPhasingRadius : highPhasingRadius; - if (orbit.ApR < phasingOrbitRadius) + if (Orbit.ApR < phasingOrbitRadius) { - double UT1 = vesselState.time + 15; - Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangeApoapsis(orbit, UT1, phasingOrbitRadius); - vessel.PlaceManeuverNode(orbit, dV1, UT1); - Orbit transferOrbit = vessel.patchedConicSolver.maneuverNodes[0].nextPatch; + double UT1 = VesselState.time + 15; + Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangeApoapsis(Orbit, UT1, phasingOrbitRadius); + Vessel.PlaceManeuverNode(Orbit, dV1, UT1); + Orbit transferOrbit = Vessel.patchedConicSolver.maneuverNodes[0].nextPatch; double UT2 = transferOrbit.NextApoapsisTime(UT1); Vector3d dV2 = OrbitalManeuverCalculator.DeltaVToCircularize(transferOrbit, UT2); - vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); + Vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); } - else if (orbit.PeR > phasingOrbitRadius) + else if (Orbit.PeR > phasingOrbitRadius) { - double UT1 = vesselState.time + 15; - Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangePeriapsis(orbit, UT1, phasingOrbitRadius); - vessel.PlaceManeuverNode(orbit, dV1, UT1); - Orbit transferOrbit = vessel.patchedConicSolver.maneuverNodes[0].nextPatch; + double UT1 = VesselState.time + 15; + Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangePeriapsis(Orbit, UT1, phasingOrbitRadius); + Vessel.PlaceManeuverNode(Orbit, dV1, UT1); + Orbit transferOrbit = Vessel.patchedConicSolver.maneuverNodes[0].nextPatch; double UT2 = transferOrbit.NextPeriapsisTime(UT1); Vector3d dV2 = OrbitalManeuverCalculator.DeltaVToCircularize(transferOrbit, UT2); - vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); + Vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); } else { - double UT = orbit.NextTimeOfRadius(vesselState.time, phasingOrbitRadius); - Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(orbit, UT); - vessel.PlaceManeuverNode(orbit, dV, UT); + double UT = Orbit.NextTimeOfRadius(VesselState.time, phasingOrbitRadius); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(Orbit, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } status = Localizer.Format("#MechJeb_RZauto_statu7", numPhasingOrbits.ToString("F1"), maxPhasingOrbits.text, - (phasingOrbitRadius - mainBody.Radius) + (phasingOrbitRadius - MainBody.Radius) .ToSI(0)); //"Next intercept window would be <<1>> orbits away, which is more than the maximum of <<2>> phasing orbits. Increasing phasing rate by establishing new phasing orbit at <<3>>m } } - else if (orbit.RelativeInclination(core.Target.TargetOrbit) < 0.05) + else if (Orbit.RelativeInclination(Core.Target.TargetOrbit) < 0.05) { //We're not on an intercept course. We're in the right plane, but our orbit isn't circular. Circularize. bool circularizeAtPe; - if (orbit.eccentricity > 1) circularizeAtPe = true; + if (Orbit.eccentricity > 1) circularizeAtPe = true; else - circularizeAtPe = Math.Abs(orbit.PeR - core.Target.TargetOrbit.semiMajorAxis) < - Math.Abs(orbit.ApR - core.Target.TargetOrbit.semiMajorAxis); + circularizeAtPe = Math.Abs(Orbit.PeR - Core.Target.TargetOrbit.semiMajorAxis) < + Math.Abs(Orbit.ApR - Core.Target.TargetOrbit.semiMajorAxis); double UT; - if (circularizeAtPe) UT = Math.Max(vesselState.time, orbit.NextPeriapsisTime(vesselState.time)); - else UT = orbit.NextApoapsisTime(vesselState.time); + if (circularizeAtPe) UT = Math.Max(VesselState.time, Orbit.NextPeriapsisTime(VesselState.time)); + else UT = Orbit.NextApoapsisTime(VesselState.time); - Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(orbit, UT); - vessel.PlaceManeuverNode(orbit, dV, UT); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(Orbit, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu8"); //"Circularizing." } @@ -220,10 +220,10 @@ public override void Drive(FlightCtrlState s) { //We're not on an intercept course, and we're not in the right plane. Match planes bool ascending; - if (orbit.eccentricity < 1) + if (Orbit.eccentricity < 1) { - if (orbit.TimeOfAscendingNode(core.Target.TargetOrbit, vesselState.time) < - orbit.TimeOfDescendingNode(core.Target.TargetOrbit, vesselState.time)) + if (Orbit.TimeOfAscendingNode(Core.Target.TargetOrbit, VesselState.time) < + Orbit.TimeOfDescendingNode(Core.Target.TargetOrbit, VesselState.time)) { ascending = true; } @@ -234,7 +234,7 @@ public override void Drive(FlightCtrlState s) } else { - if (orbit.AscendingNodeExists(core.Target.TargetOrbit)) + if (Orbit.AscendingNodeExists(Core.Target.TargetOrbit)) { ascending = true; } @@ -247,10 +247,10 @@ public override void Drive(FlightCtrlState s) double UT; Vector3d dV; if (ascending) - dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesAscending(orbit, core.Target.TargetOrbit, vesselState.time, out UT); - else dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesDescending(orbit, core.Target.TargetOrbit, vesselState.time, out UT); + dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesAscending(Orbit, Core.Target.TargetOrbit, VesselState.time, out UT); + else dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesDescending(Orbit, Core.Target.TargetOrbit, VesselState.time, out UT); - vessel.PlaceManeuverNode(orbit, dV, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); status = Localizer.Format("#MechJeb_RZauto_statu9"); //"Matching planes." } diff --git a/MechJeb2/MechJebModuleRendezvousAutopilotWindow.cs b/MechJeb2/MechJebModuleRendezvousAutopilotWindow.cs index 93b8a7281..cf09d38cb 100644 --- a/MechJeb2/MechJebModuleRendezvousAutopilotWindow.cs +++ b/MechJeb2/MechJebModuleRendezvousAutopilotWindow.cs @@ -11,20 +11,20 @@ public class MechJebModuleRendezvousAutopilotWindow : DisplayModule protected override void WindowGUI(int windowID) { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { GUILayout.Label(Localizer.Format("#MechJeb_RZauto_label1")); //"Select a target to rendezvous with." base.WindowGUI(windowID); return; } - MechJebModuleRendezvousAutopilot autopilot = core.GetComputerModule(); + MechJebModuleRendezvousAutopilot autopilot = Core.GetComputerModule(); - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) { GUILayout.Label(Localizer.Format("#MechJeb_RZauto_label2")); //"Rendezvous target must be in the same sphere of influence." - if (autopilot.enabled) - autopilot.users.Remove(this); + if (autopilot.Enabled) + autopilot.Users.Remove(this); base.WindowGUI(windowID); return; } @@ -33,15 +33,15 @@ protected override void WindowGUI(int windowID) if (autopilot != null) { - GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZauto_label3"), core.Target.Name); //"Rendezvous target" + GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZauto_label3"), Core.Target.Name); //"Rendezvous target" - if (!autopilot.enabled) + if (!autopilot.Enabled) { - if (GUILayout.Button(Localizer.Format("#MechJeb_RZauto_button1"))) autopilot.users.Add(this); //"Engage autopilot" + if (GUILayout.Button(Localizer.Format("#MechJeb_RZauto_button1"))) autopilot.Users.Add(this); //"Engage autopilot" } else { - if (GUILayout.Button(Localizer.Format("#MechJeb_RZauto_button2"))) autopilot.users.Remove(this); //"Disengage autopilot" + if (GUILayout.Button(Localizer.Format("#MechJeb_RZauto_button2"))) autopilot.Users.Remove(this); //"Disengage autopilot" } GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_RZauto_label4"), autopilot.desiredDistance, "m"); //"Desired final distance:" @@ -53,10 +53,10 @@ protected override void WindowGUI(int windowID) GUILayout.Label(Localizer.Format("#MechJeb_RZauto_label6"), GuiUtils.yellowLabel); //"Max # of phasing orbits must be at least 5." } - if (autopilot.enabled) GUILayout.Label(Localizer.Format("#MechJeb_RZauto_label7", autopilot.status)); //"Status: <<1>>" + if (autopilot.Enabled) GUILayout.Label(Localizer.Format("#MechJeb_RZauto_label7", autopilot.status)); //"Status: <<1>>" } - core.Node.autowarp = GUILayout.Toggle(core.Node.autowarp, Localizer.Format("#MechJeb_RZauto_checkbox1")); //"Auto-warp" + Core.Node.autowarp = GUILayout.Toggle(Core.Node.autowarp, Localizer.Format("#MechJeb_RZauto_checkbox1")); //"Auto-warp" GUILayout.EndVertical(); @@ -78,9 +78,9 @@ public override string IconName() return "Rendezvous Autopilot"; } - public override bool IsSpaceCenterUpgradeUnlocked() + protected override bool IsSpaceCenterUpgradeUnlocked() { - return vessel.patchedConicsUnlocked(); + return Vessel.patchedConicsUnlocked(); } } } diff --git a/MechJeb2/MechJebModuleRendezvousGuidance.cs b/MechJeb2/MechJebModuleRendezvousGuidance.cs index ca4f33e73..35f26fe42 100644 --- a/MechJeb2/MechJebModuleRendezvousGuidance.cs +++ b/MechJeb2/MechJebModuleRendezvousGuidance.cs @@ -15,14 +15,14 @@ public class MechJebModuleRendezvousGuidance : DisplayModule protected override void WindowGUI(int windowID) { - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) { GUILayout.Label(Localizer.Format("#MechJeb_RZplan_label1")); //"Select a target to rendezvous with." base.WindowGUI(windowID); return; } - if (core.Target.TargetOrbit.referenceBody != orbit.referenceBody) + if (Core.Target.TargetOrbit.referenceBody != Orbit.referenceBody) { GUILayout.Label(Localizer.Format("#MechJeb_RZplan_label2")); //"Rendezvous target must be in the same sphere of influence." base.WindowGUI(windowID); @@ -33,20 +33,20 @@ protected override void WindowGUI(int windowID) //Information readouts: - GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label3"), core.Target.Name); //"Rendezvous target" + GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label3"), Core.Target.Name); //"Rendezvous target" const double leadTime = 30; GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label4"), - core.Target.TargetOrbit.PeA.ToSI(3) + "m x " + core.Target.TargetOrbit.ApA.ToSI(3) + "m"); //"Target orbit" - GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label5"), orbit.PeA.ToSI(3) + "m x " + orbit.ApA.ToSI(3) + "m"); //"Current orbit" + Core.Target.TargetOrbit.PeA.ToSI(3) + "m x " + Core.Target.TargetOrbit.ApA.ToSI(3) + "m"); //"Target orbit" + GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label5"), Orbit.PeA.ToSI(3) + "m x " + Orbit.ApA.ToSI(3) + "m"); //"Current orbit" GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label6"), - orbit.RelativeInclination(core.Target.TargetOrbit).ToString("F2") + "º"); //"Relative inclination" + Orbit.RelativeInclination(Core.Target.TargetOrbit).ToString("F2") + "º"); //"Relative inclination" - double closestApproachTime = orbit.NextClosestApproachTime(core.Target.TargetOrbit, vesselState.time); + double closestApproachTime = Orbit.NextClosestApproachTime(Core.Target.TargetOrbit, VesselState.time); GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label7"), - GuiUtils.TimeToDHMS(closestApproachTime - vesselState.time)); //"Time until closest approach" + GuiUtils.TimeToDHMS(closestApproachTime - VesselState.time)); //"Time until closest approach" GuiUtils.SimpleLabel(Localizer.Format("#MechJeb_RZplan_label8"), - orbit.Separation(core.Target.TargetOrbit, closestApproachTime).ToSI() + "m"); //"Separation at closest approach" + Orbit.Separation(Core.Target.TargetOrbit, closestApproachTime).ToSI() + "m"); //"Separation at closest approach" //Maneuver planning buttons: @@ -55,51 +55,51 @@ protected override void WindowGUI(int windowID) { double UT; Vector3d dV; - if (orbit.AscendingNodeExists(core.Target.TargetOrbit)) + if (Orbit.AscendingNodeExists(Core.Target.TargetOrbit)) { - dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesAscending(orbit, core.Target.TargetOrbit, vesselState.time, out UT); + dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesAscending(Orbit, Core.Target.TargetOrbit, VesselState.time, out UT); } else { - dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesDescending(orbit, core.Target.TargetOrbit, vesselState.time, out UT); + dV = OrbitalManeuverCalculator.DeltaVAndTimeToMatchPlanesDescending(Orbit, Core.Target.TargetOrbit, VesselState.time, out UT); } - vessel.RemoveAllManeuverNodes(); - vessel.PlaceManeuverNode(orbit, dV, UT); + Vessel.RemoveAllManeuverNodes(); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } GUILayout.BeginHorizontal(); if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button2"))) //"Establish new orbit at" { - double phasingOrbitRadius = phasingOrbitAltitude + mainBody.Radius; + double phasingOrbitRadius = phasingOrbitAltitude + MainBody.Radius; - vessel.RemoveAllManeuverNodes(); - if (orbit.ApR < phasingOrbitRadius) + Vessel.RemoveAllManeuverNodes(); + if (Orbit.ApR < phasingOrbitRadius) { - double UT1 = vesselState.time + leadTime; - Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangeApoapsis(orbit, UT1, phasingOrbitRadius); - vessel.PlaceManeuverNode(orbit, dV1, UT1); - Orbit transferOrbit = vessel.patchedConicSolver.maneuverNodes[0].nextPatch; + double UT1 = VesselState.time + leadTime; + Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangeApoapsis(Orbit, UT1, phasingOrbitRadius); + Vessel.PlaceManeuverNode(Orbit, dV1, UT1); + Orbit transferOrbit = Vessel.patchedConicSolver.maneuverNodes[0].nextPatch; double UT2 = transferOrbit.NextApoapsisTime(UT1); Vector3d dV2 = OrbitalManeuverCalculator.DeltaVToCircularize(transferOrbit, UT2); - vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); + Vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); } - else if (orbit.PeR > phasingOrbitRadius) + else if (Orbit.PeR > phasingOrbitRadius) { - double UT1 = vesselState.time + leadTime; - Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangePeriapsis(orbit, UT1, phasingOrbitRadius); - vessel.PlaceManeuverNode(orbit, dV1, UT1); - Orbit transferOrbit = vessel.patchedConicSolver.maneuverNodes[0].nextPatch; + double UT1 = VesselState.time + leadTime; + Vector3d dV1 = OrbitalManeuverCalculator.DeltaVToChangePeriapsis(Orbit, UT1, phasingOrbitRadius); + Vessel.PlaceManeuverNode(Orbit, dV1, UT1); + Orbit transferOrbit = Vessel.patchedConicSolver.maneuverNodes[0].nextPatch; double UT2 = transferOrbit.NextPeriapsisTime(UT1); Vector3d dV2 = OrbitalManeuverCalculator.DeltaVToCircularize(transferOrbit, UT2); - vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); + Vessel.PlaceManeuverNode(transferOrbit, dV2, UT2); } else { - double UT = orbit.NextTimeOfRadius(vesselState.time, phasingOrbitRadius); - Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(orbit, UT); - vessel.PlaceManeuverNode(orbit, dV, UT); + double UT = Orbit.NextTimeOfRadius(VesselState.time, phasingOrbitRadius); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToCircularize(Orbit, UT); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } } @@ -110,75 +110,75 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button3"))) //"Intercept with Hohmann transfer" { double UT; - Vector3d dV = OrbitalManeuverCalculator.DeltaVAndTimeForHohmannTransfer(orbit, core.Target.TargetOrbit, vesselState.time, out UT); - vessel.RemoveAllManeuverNodes(); - vessel.PlaceManeuverNode(orbit, dV, UT); + Vector3d dV = OrbitalManeuverCalculator.DeltaVAndTimeForHohmannTransfer(Orbit, Core.Target.TargetOrbit, VesselState.time, out UT); + Vessel.RemoveAllManeuverNodes(); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button4"))) //"Match velocities at closest approach" { double UT = closestApproachTime; - Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(orbit, UT, core.Target.TargetOrbit); - vessel.RemoveAllManeuverNodes(); - vessel.PlaceManeuverNode(orbit, dV, UT); + Vector3d dV = OrbitalManeuverCalculator.DeltaVToMatchVelocities(Orbit, UT, Core.Target.TargetOrbit); + Vessel.RemoveAllManeuverNodes(); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button5"))) //"Get closer" { - double UT = vesselState.time; - (Vector3d dV, _) = OrbitalManeuverCalculator.DeltaVToInterceptAtTime(orbit, UT, core.Target.TargetOrbit, 100, 10); - vessel.RemoveAllManeuverNodes(); - vessel.PlaceManeuverNode(orbit, dV, UT); + double UT = VesselState.time; + (Vector3d dV, _) = OrbitalManeuverCalculator.DeltaVToInterceptAtTime(Orbit, UT, Core.Target.TargetOrbit, 100, 10); + Vessel.RemoveAllManeuverNodes(); + Vessel.PlaceManeuverNode(Orbit, dV, UT); } if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button9"))) //Remove ALL nodes { - vessel.RemoveAllManeuverNodes(); + Vessel.RemoveAllManeuverNodes(); } - if (core.Node != null) + if (Core.Node != null) { - if (vessel.patchedConicSolver.maneuverNodes.Any() && !core.Node.enabled) + if (Vessel.patchedConicSolver.maneuverNodes.Any() && !Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button6"))) //"Execute next node" { - core.Node.ExecuteOneNode(this); + Core.Node.ExecuteOneNode(this); } - if (vessel.patchedConicSolver.maneuverNodes.Count > 1) + if (Vessel.patchedConicSolver.maneuverNodes.Count > 1) { if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button7"))) //"Execute all nodes" { - core.Node.ExecuteAllNodes(this); + Core.Node.ExecuteAllNodes(this); } } } - else if (core.Node.enabled) + else if (Core.Node.Enabled) { if (GUILayout.Button(Localizer.Format("#MechJeb_RZplan_button8"))) //"Abort node execution" { - core.Node.Abort(); + Core.Node.Abort(); } } GUILayout.BeginHorizontal(); - core.Node.autowarp = - GUILayout.Toggle(core.Node.autowarp, Localizer.Format("#MechJeb_RZplan_checkbox"), GUILayout.ExpandWidth(true)); //"Auto-warp" + Core.Node.autowarp = + GUILayout.Toggle(Core.Node.autowarp, Localizer.Format("#MechJeb_RZplan_checkbox"), GUILayout.ExpandWidth(true)); //"Auto-warp" GUILayout.Label(Localizer.Format("#MechJeb_RZplan_label9"), GUILayout.ExpandWidth(false)); //"Tolerance:" - core.Node.tolerance.text = GUILayout.TextField(core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); + Core.Node.tolerance.text = GUILayout.TextField(Core.Node.tolerance.text, GUILayout.Width(35), GUILayout.ExpandWidth(false)); if (GUILayout.Button("+", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val += 0.1; + Core.Node.tolerance.val += 0.1; } if (GUILayout.Button("-", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val -= core.Node.tolerance.val > 0.1 ? 0.1 : 0.0; + Core.Node.tolerance.val -= Core.Node.tolerance.val > 0.1 ? 0.1 : 0.0; } if (GUILayout.Button("R", GUILayout.ExpandWidth(false))) { - core.Node.tolerance.val = 0.1; + Core.Node.tolerance.val = 0.1; } GUILayout.Label("m/s", GUILayout.ExpandWidth(false)); @@ -205,9 +205,9 @@ public override string IconName() return "Rendezvous Planner"; } - public override bool IsSpaceCenterUpgradeUnlocked() + protected override bool IsSpaceCenterUpgradeUnlocked() { - return vessel.patchedConicsUnlocked(); + return Vessel.patchedConicsUnlocked(); } } } diff --git a/MechJeb2/MechJebModuleRoverController.cs b/MechJeb2/MechJebModuleRoverController.cs index 934c75f6d..37609afde 100644 --- a/MechJeb2/MechJebModuleRoverController.cs +++ b/MechJeb2/MechJebModuleRoverController.cs @@ -15,41 +15,41 @@ public class MechJebModuleRoverController : ComputerModule public bool LoopWaypoints = false; [ToggleInfoItem("#MechJeb_ControlHeading", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Heading control + [Persistent(pass = (int)Pass.LOCAL)] // Heading control public bool ControlHeading; [EditableInfoItem("#MechJeb_Heading", InfoItem.Category.Rover, width = 40)] - [Persistent(pass = (int)Pass.Local)] // Heading + [Persistent(pass = (int)Pass.LOCAL)] // Heading public EditableDouble heading = 0; [ToggleInfoItem("#MechJeb_ControlSpeed", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Speed control + [Persistent(pass = (int)Pass.LOCAL)] // Speed control public bool ControlSpeed; [EditableInfoItem("#MechJeb_Speed", InfoItem.Category.Rover, width = 40)] - [Persistent(pass = (int)Pass.Local)] // Speed + [Persistent(pass = (int)Pass.LOCAL)] // Speed public EditableDouble speed = 10; [ToggleInfoItem("#MechJeb_BrakeOnEject", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Brake on Pilot Eject + [Persistent(pass = (int)Pass.LOCAL)] // Brake on Pilot Eject public bool BrakeOnEject = false; [ToggleInfoItem("#MechJeb_BrakeOnEnergyDepletion", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Brake on Energy Depletion + [Persistent(pass = (int)Pass.LOCAL)] // Brake on Energy Depletion public bool BrakeOnEnergyDepletion = false; [ToggleInfoItem("#MechJeb_WarpToDaylight", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Warp until Day if Depleted + [Persistent(pass = (int)Pass.LOCAL)] // Warp until Day if Depleted public bool WarpToDaylight = false; public bool waitingForDaylight; [ToggleInfoItem("#MechJeb_StabilityControl", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local)] // Stability Control + [Persistent(pass = (int)Pass.LOCAL)] // Stability Control public bool StabilityControl = false; [ToggleInfoItem("#MechJeb_LimitAcceleration", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Local | (int)Pass.Type)] // Limit Acceleration + [Persistent(pass = (int)Pass.LOCAL | (int)Pass.TYPE)] // Limit Acceleration public bool LimitAcceleration = false; public PIDController headingPID; @@ -58,39 +58,39 @@ public class MechJebModuleRoverController : ComputerModule // private LineRenderer line; [EditableInfoItem("#MechJeb_SafeTurnspeed", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Type)] // Safe turnspeed + [Persistent(pass = (int)Pass.TYPE)] // Safe turnspeed public EditableDouble turnSpeed = 3; [EditableInfoItem("#MechJeb_TerrainLookAhead", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Terrain Look Ahead + [Persistent(pass = (int)Pass.GLOBAL)] // Terrain Look Ahead public EditableDouble terrainLookAhead = 1.0; [EditableInfoItem("#MechJeb_BrakeSpeedLimit", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Type)] // Brake Speed Limit + [Persistent(pass = (int)Pass.TYPE)] // Brake Speed Limit public EditableDouble brakeSpeedLimit = 0.7; [EditableInfoItem("#MechJeb_HeadingPIDP", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Heading PID P + [Persistent(pass = (int)Pass.GLOBAL)] // Heading PID P public EditableDouble hPIDp = 0.03; // 0.01 [EditableInfoItem("#MechJeb_HeadingPIDI", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Heading PID I + [Persistent(pass = (int)Pass.GLOBAL)] // Heading PID I public EditableDouble hPIDi = 0.002; // 0.001 [EditableInfoItem("#MechJeb_HeadingPIDD", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Heading PID D + [Persistent(pass = (int)Pass.GLOBAL)] // Heading PID D public EditableDouble hPIDd = 0.005; [EditableInfoItem("#MechJeb_SpeedPIDP", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Speed PID P + [Persistent(pass = (int)Pass.GLOBAL)] // Speed PID P public EditableDouble sPIDp = 2.0; [EditableInfoItem("#MechJeb_SpeedPIDI", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Speed PID I + [Persistent(pass = (int)Pass.GLOBAL)] // Speed PID I public EditableDouble sPIDi = 0.1; [EditableInfoItem("#MechJeb_SpeedPIDD", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Speed PID D + [Persistent(pass = (int)Pass.GLOBAL)] // Speed PID D public EditableDouble sPIDd = 0.001; [ValueInfoItem("#MechJeb_SpeedIntAcc", InfoItem.Category.Rover, format = ValueInfoItem.SI, units = "m/s")] // Speed Int Acc @@ -100,7 +100,7 @@ public class MechJebModuleRoverController : ComputerModule public float traction; [EditableInfoItem("#MechJeb_TractionBrakeLimit", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Type)] // Traction Brake Limit + [Persistent(pass = (int)Pass.TYPE)] // Traction Brake Limit public EditableDouble tractionLimit = 75; public List<(PartModule, BaseField)> wheelbases = new List<(PartModule, BaseField)>(); @@ -110,9 +110,9 @@ public override void OnStart(PartModule.StartState state) headingPID = new PIDController(hPIDp, hPIDi, hPIDd); speedPID = new PIDController(sPIDp, sPIDi, sPIDd); - if (HighLogic.LoadedSceneIsFlight && orbit != null) + if (HighLogic.LoadedSceneIsFlight && Orbit != null) { - lastBody = orbit.referenceBody; + lastBody = Orbit.referenceBody; } // MechJebRouteRenderer.NewLineRenderer(ref line); @@ -130,7 +130,7 @@ public void OnVesselModified(Vessel v) try { wheelbases.Clear(); - wheelbases.AddRange(vessel.Parts.Where( + wheelbases.AddRange(Vessel.Parts.Where( p => p.HasModule() && p.GetModule().wheelType != WheelType.LEG ).Select(p => @@ -138,7 +138,7 @@ public void OnVesselModified(Vessel v) PartModule pm = p.Modules.GetModule("ModuleWheelBase"); return (pm, pm.Fields["isGrounded"]); })); - wheelbases.AddRange(vessel.Parts.Where( + wheelbases.AddRange(Vessel.Parts.Where( p => p.Modules.Contains("KSPWheelBase") && p.Modules.Contains("KSPWheelRotation") ).Select(p => @@ -164,7 +164,7 @@ public void OnVesselModified(Vessel v) public double HeadingToPos(Vector3 fromPos, Vector3 toPos) { - Transform origin = mainBody.transform; + Transform origin = MainBody.transform; // thanks to Cilph who did most of this since I don't understand anything ~ BR2k Vector3 up = fromPos - origin.position; // position relative to origin, "up" vector @@ -185,7 +185,7 @@ public float TurningSpeed(double speed, double error) public void CalculateTraction() { - if (wheelbases.Count == 0) { OnVesselModified(vessel); } + if (wheelbases.Count == 0) { OnVesselModified(Vessel); } traction = 0; @@ -200,13 +200,13 @@ public void CalculateTraction() traction /= wheelbases.Count; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - if (core.Attitude.users.Contains(this)) + if (Core.Attitude.Users.Contains(this)) { // line.enabled = false; - core.Attitude.attitudeDeactivate(); - core.Attitude.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + Core.Attitude.Users.Remove(this); } base.OnModuleDisabled(); @@ -219,7 +219,7 @@ public override void Drive(FlightCtrlState s) // TODO put the brake in when running out of power to prevent nighttime solar failures on hills, or atleast try to { // TODO make distance calculation for 'reached' determination consider the rover and waypoint on sealevel to prevent height differences from messing it up -- should be done now? - if (orbit.referenceBody != lastBody) + if (Orbit.referenceBody != lastBody) { WaypointIndex = -1; Waypoints.Clear(); @@ -227,17 +227,17 @@ public override void MechJebWaypoint wp = WaypointIndex > -1 && WaypointIndex < Waypoints.Count ? Waypoints[WaypointIndex] : null; - bool brake = vessel.ActionGroups[KSPActionGroup.Brakes]; // keep brakes locked if they are - curSpeed = Vector3d.Dot(vesselState.surfaceVelocity, vesselState.forward); + bool brake = Vessel.ActionGroups[KSPActionGroup.Brakes]; // keep brakes locked if they are + curSpeed = Vector3d.Dot(VesselState.surfaceVelocity, VesselState.forward); CalculateTraction(); speedIntAcc = speedPID.intAccum; - if (wp != null && wp.Body == orbit.referenceBody) + if (wp != null && wp.Body == Orbit.referenceBody) { if (ControlHeading) { - double newHeading = Math.Round(HeadingToPos(vessel.CoM, wp.Position), 1); + double newHeading = Math.Round(HeadingToPos(Vessel.CoM, wp.Position), 1); // update GUI text only if the value changed if (newHeading != heading) @@ -247,7 +247,7 @@ public override void if (ControlSpeed) { MechJebWaypoint nextWP = WaypointIndex < Waypoints.Count - 1 ? Waypoints[WaypointIndex + 1] : LoopWaypoints ? Waypoints[0] : null; - float distance = Vector3.Distance(vessel.CoM, wp.Position); + float distance = Vector3.Distance(Vessel.CoM, wp.Position); if (wp.Target != null) { distance += (float)(wp.Target.srfSpeed * curSpeed) / 2; } // var maxSpeed = (wp.MaxSpeed > 0 ? Math.Min((float)speed, wp.MaxSpeed) : speed); // use waypoints maxSpeed if set and smaller than set the speed or just stick with the set speed @@ -318,7 +318,7 @@ public override void } } - brake = brake || ((s.wheelThrottle == 0 || !vessel.isActiveVessel) && curSpeed < brakeSpeedLimit && newSpeed < brakeSpeedLimit); + brake = brake || ((s.wheelThrottle == 0 || !Vessel.isActiveVessel) && curSpeed < brakeSpeedLimit && newSpeed < brakeSpeedLimit); // ^ brake if needed to prevent rolling, hopefully tgtSpeed = newSpeed >= 0 ? newSpeed : 0; } @@ -328,9 +328,9 @@ public override void { headingPID.intAccum = Mathf.Clamp((float)headingPID.intAccum, -1, 1); - double instantaneousHeading = vesselState.rotationVesselSurface.eulerAngles.y; + double instantaneousHeading = VesselState.rotationVesselSurface.eulerAngles.y; headingErr = MuUtils.ClampDegrees180(instantaneousHeading - heading); - if (s.wheelSteer == s.wheelSteerTrim || FlightGlobals.ActiveVessel != vessel) + if (s.wheelSteer == s.wheelSteerTrim || FlightGlobals.ActiveVessel != Vessel) { float limit = Math.Abs(curSpeed) > turnSpeed ? Mathf.Clamp((float)((turnSpeed + 6) / Square(curSpeed)), 0.1f, 1f) : 1f; // turnSpeed needs to be higher than curSpeed or it will never steer as much as it could even at 0.2m/s above it @@ -344,7 +344,7 @@ public override void } // Brake if there is no controler (Pilot eject from seat) - if (BrakeOnEject && vessel.GetReferenceTransformPart() == null) + if (BrakeOnEject && Vessel.GetReferenceTransformPart() == null) { s.wheelThrottle = 0; brake = true; @@ -353,8 +353,8 @@ public override void { speedPID.intAccum = Mathf.Clamp((float)speedPID.intAccum, -5, 5); - speedErr = (WaypointIndex == -1 ? speed.val : tgtSpeed) - Vector3d.Dot(vesselState.surfaceVelocity, vesselState.forward); - if (s.wheelThrottle == s.wheelThrottleTrim || FlightGlobals.ActiveVessel != vessel) + speedErr = (WaypointIndex == -1 ? speed.val : tgtSpeed) - Vector3d.Dot(VesselState.surfaceVelocity, VesselState.forward); + if (s.wheelThrottle == s.wheelThrottleTrim || FlightGlobals.ActiveVessel != Vessel) { float act = (float)speedPID.Compute(speedErr); s.wheelThrottle = Mathf.Clamp(act, -1f, 1f); @@ -374,44 +374,44 @@ public override void if (StabilityControl) { RaycastHit hit; - Physics.Raycast(vessel.CoM + vesselState.surfaceVelocity * terrainLookAhead + vesselState.up * 100, -vesselState.up, out hit, 500, + Physics.Raycast(Vessel.CoM + VesselState.surfaceVelocity * terrainLookAhead + VesselState.up * 100, -VesselState.up, out hit, 500, 1 << 15, QueryTriggerInteraction.Ignore); Vector3 norm = hit.normal; - if (!core.Attitude.users.Contains(this)) + if (!Core.Attitude.Users.Contains(this)) { - core.Attitude.users.Add(this); + Core.Attitude.Users.Add(this); } float fSpeed = (float)curSpeed; Vector3 fwd = traction > 0 ? // V when the speed is low go for the vessels forward, else with a bit of velocity - vesselState.forward * 4 - vessel.transform.right * s.wheelSteer * Mathf.Sign(fSpeed) + VesselState.forward * 4 - Vessel.transform.right * s.wheelSteer * Mathf.Sign(fSpeed) : // and then add the steering - vesselState.surfaceVelocity; // in the air so follow velocity + VesselState.surfaceVelocity; // in the air so follow velocity Vector3.OrthoNormalize(ref norm, ref fwd); var quat = Quaternion.LookRotation(fwd, norm); - if (vesselState.torqueAvailable.sqrMagnitude > 0) - core.Attitude.attitudeTo(quat, AttitudeReference.INERTIAL, this); + if (VesselState.torqueAvailable.sqrMagnitude > 0) + Core.Attitude.attitudeTo(quat, AttitudeReference.INERTIAL, this); } if (BrakeOnEnergyDepletion) { - List batteries = vessel.Parts.FindAll(p => + List batteries = Vessel.Parts.FindAll(p => p.Resources.Contains(PartResourceLibrary.ElectricityHashcode) && p.Resources.Get(PartResourceLibrary.ElectricityHashcode).flowState); double energyLeft = batteries.Sum(p => p.Resources.Get(PartResourceLibrary.ElectricityHashcode).amount) / batteries.Sum(p => p.Resources.Get(PartResourceLibrary.ElectricityHashcode).maxAmount); bool openSolars = - vessel.mainBody.atmosphere && // true if in atmosphere and there are breakable solarpanels that aren't broken nor retracted - vessel.FindPartModulesImplementing().FindAll(p => + Vessel.mainBody.atmosphere && // true if in atmosphere and there are breakable solarpanels that aren't broken nor retracted + Vessel.FindPartModulesImplementing().FindAll(p => p.isBreakable && p.deployState != ModuleDeployablePart.DeployState.BROKEN && p.deployState != ModuleDeployablePart.DeployState.RETRACTED).Count > 0; if (openSolars && energyLeft > 0.99) { - vessel.FindPartModulesImplementing().FindAll(p => p.isBreakable && + Vessel.FindPartModulesImplementing().FindAll(p => p.isBreakable && p.deployState == ModuleDeployablePart.DeployState .EXTENDED).ForEach(p => p.Retract()); } @@ -429,7 +429,7 @@ public override void } if (curSpeed < 0.1 && energyLeft < 0.05 && !waitingForDaylight && - vessel.FindPartModulesImplementing() + Vessel.FindPartModulesImplementing() .FindAll(p => p.deployState == ModuleDeployablePart.DeployState.EXTENDED).Count > 0) { waitingForDaylight = true; @@ -441,7 +441,7 @@ public override void brake = false; // the AP or user want to drive into the direction of momentum so release the brake } - if (vessel.isActiveVessel) + if (Vessel.isActiveVessel) { if (GameSettings.BRAKES.GetKeyUp()) { @@ -455,7 +455,7 @@ public override void } tractionLimit = (double)Mathf.Clamp((float)tractionLimit, 0, 100); - vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, + Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, brake && (StabilityControl && (ControlHeading || ControlSpeed) ? traction >= tractionLimit : true)); // only let go of the brake when losing traction if the AP is driving, otherwise assume the player knows when to let go of it // also to not constantly turn off the parking brake from going over a small bump @@ -464,12 +464,12 @@ public override void public override void OnFixedUpdate() { - if (!core.GetComputerModule().enabled) + if (!Core.GetComputerModule().Enabled) { Waypoints.ForEach(wp => wp.Update()); // update waypoints unless the waypoint window is (hopefully) doing that already } - if (orbit != null && lastBody != orbit.referenceBody) { lastBody = orbit.referenceBody; } + if (Orbit != null && lastBody != Orbit.referenceBody) { lastBody = Orbit.referenceBody; } headingPID.Kp = hPIDp; headingPID.Ki = hPIDi; @@ -484,18 +484,18 @@ public override void OnFixedUpdate() lastETA = DateTime.Now.TimeOfDay.TotalSeconds; } - if (!core.GetComputerModule().enabled) + if (!Core.GetComputerModule().Enabled) { - core.GetComputerModule() + Core.GetComputerModule() .OnUpdate(); // update users for Stability Control, Brake on Eject and Brake on Energy Depletion } } public override void OnUpdate() { - if (WarpToDaylight && waitingForDaylight && vessel.isActiveVessel) + if (WarpToDaylight && waitingForDaylight && Vessel.isActiveVessel) { - List batteries = vessel.Parts.FindAll(p => + List batteries = Vessel.Parts.FindAll(p => p.Resources.Contains(PartResourceLibrary.ElectricityHashcode) && p.Resources.Get(PartResourceLibrary.ElectricityHashcode).flowState); double energyLeft = batteries.Sum(p => p.Resources.Get(PartResourceLibrary.ElectricityHashcode).amount) / @@ -503,17 +503,17 @@ public override void OnUpdate() if (waitingForDaylight) { - if (vessel.FindPartModulesImplementing() + if (Vessel.FindPartModulesImplementing() .FindAll(p => p.deployState == ModuleDeployablePart.DeployState.EXTENDED).Count == 0) { waitingForDaylight = false; } - core.Warp.WarpRegularAtRate(energyLeft < 0.9 ? 1000 : 50); + Core.Warp.WarpRegularAtRate(energyLeft < 0.9 ? 1000 : 50); if (energyLeft > 0.99) { waitingForDaylight = false; - core.Warp.MinimumWarp(); + Core.Warp.MinimumWarp(); } } } @@ -522,16 +522,16 @@ public override void OnUpdate() waitingForDaylight = false; } - if (!core.GetComputerModule().enabled) + if (!Core.GetComputerModule().Enabled) { - core.GetComputerModule() + Core.GetComputerModule() .OnUpdate(); // update users for Stability Control, Brake on Eject and Brake on Energy Depletion } - if (!StabilityControl && core.Attitude.users.Contains(this)) + if (!StabilityControl && Core.Attitude.Users.Contains(this)) { - core.Attitude.attitudeDeactivate(); - core.Attitude.users.Remove(this); + Core.Attitude.attitudeDeactivate(); + Core.Attitude.Users.Remove(this); } } diff --git a/MechJeb2/MechJebModuleRoverWindow.cs b/MechJeb2/MechJebModuleRoverWindow.cs index eec6135f0..a0763a940 100644 --- a/MechJeb2/MechJebModuleRoverWindow.cs +++ b/MechJeb2/MechJebModuleRoverWindow.cs @@ -14,7 +14,7 @@ public class MechJebModuleRoverWindow : DisplayModule public override void OnStart(PartModule.StartState state) { - autopilot = core.GetComputerModule(); + autopilot = Core.GetComputerModule(); } public override string GetName() @@ -34,14 +34,14 @@ public override GUILayoutOption[] WindowOptions() protected override void WindowGUI(int windowID) { - MechJebModuleCustomWindowEditor ed = core.GetComputerModule(); + MechJebModuleCustomWindowEditor ed = Core.GetComputerModule(); bool alt = GameSettings.MODIFIER_KEY.GetKey(); if (GUI.Button(new Rect(windowPos.width - 48, 0, 13, 20), "?", GuiUtils.yellowOnHover)) { - MechJebModuleWaypointHelpWindow help = core.GetComputerModule(); + MechJebModuleWaypointHelpWindow help = Core.GetComputerModule(); help.selTopic = ((IList)help.topics).IndexOf("Controller"); - help.enabled = help.selTopic > -1 || help.enabled; + help.Enabled = help.selTopic > -1 || help.Enabled; } ed.registry.Find(i => i.id == "Toggle:RoverController.ControlHeading").DrawItem(); @@ -64,7 +64,7 @@ protected override void WindowGUI(int windowID) ed.registry.Find(i => i.id == "Value:RoverController.speedErr").DrawItem(); ed.registry.Find(i => i.id == "Toggle:RoverController.StabilityControl").DrawItem(); - if (!core.Settings.hideBrakeOnEject) + if (!Core.Settings.hideBrakeOnEject) { ed.registry.Find(i => i.id == "Toggle:RoverController.BrakeOnEject").DrawItem(); } @@ -90,27 +90,27 @@ protected override void WindowGUI(int windowID) // GUILayout.Label("Debug1: " + autopilot.debug1.ToString("F3")); GUILayout.BeginHorizontal(); - if (core.Target != null && core.Target.Target != null) + if (Core.Target != null && Core.Target.Target != null) { - Vessel vssl = core.Target.Target.GetVessel(); + Vessel vssl = Core.Target.Target.GetVessel(); if (GUILayout.Button(Localizer.Format("#MechJeb_Rover_button1"))) // "To Target" { - core.GetComputerModule().selIndex = -1; + Core.GetComputerModule().selIndex = -1; autopilot.WaypointIndex = 0; autopilot.Waypoints.Clear(); if (vssl != null) { autopilot.Waypoints.Add(new MechJebWaypoint(vssl, 25f)); } - else { autopilot.Waypoints.Add(new MechJebWaypoint(core.Target.GetPositionTargetPosition())); } + else { autopilot.Waypoints.Add(new MechJebWaypoint(Core.Target.GetPositionTargetPosition())); } autopilot.ControlHeading = autopilot.ControlSpeed = true; - vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, false); + Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, false); autopilot.LoopWaypoints = alt; } if (GUILayout.Button(Localizer.Format("#MechJeb_Rover_button2"))) // "Add Target" { if (vssl != null) { autopilot.Waypoints.Add(new MechJebWaypoint(vssl, 25f)); } - else { autopilot.Waypoints.Add(new MechJebWaypoint(core.Target.GetPositionTargetPosition())); } + else { autopilot.Waypoints.Add(new MechJebWaypoint(Core.Target.GetPositionTargetPosition())); } } } @@ -140,9 +140,9 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Rover_button5"))) { // "Waypoints" - MechJebModuleWaypointWindow waypoints = core.GetComputerModule(); - waypoints.enabled = !waypoints.enabled; - if (waypoints.enabled) + MechJebModuleWaypointWindow waypoints = Core.GetComputerModule(); + waypoints.Enabled = !waypoints.Enabled; + if (waypoints.Enabled) { waypoints.Mode = MechJebModuleWaypointWindow.WaypointMode.Rover; } @@ -162,19 +162,19 @@ public override void OnUpdate() if (autopilot.ControlHeading || autopilot.ControlSpeed || autopilot.StabilityControl || autopilot.BrakeOnEnergyDepletion || autopilot.BrakeOnEject) { - autopilot.users.Add(this); + autopilot.Users.Add(this); } else { - autopilot.users.Remove(this); + autopilot.Users.Remove(this); } } } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.GetComputerModule().enabled = false; - core.GetComputerModule().enabled = false; + Core.GetComputerModule().Enabled = false; + Core.GetComputerModule().Enabled = false; base.OnModuleDisabled(); } } diff --git a/MechJeb2/MechJebModuleSettings.cs b/MechJeb2/MechJebModuleSettings.cs index 76fb7fbd6..b01b2abd0 100644 --- a/MechJeb2/MechJebModuleSettings.cs +++ b/MechJeb2/MechJebModuleSettings.cs @@ -13,31 +13,31 @@ public MechJebModuleSettings(MechJebCore core) : base(core) } // Kept for old conf compatibility - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool useOldSkin; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public int skinId = 2; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble UIScale = 1.0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool dontUseDropDownMenu; [ToggleInfoItem("#MechJeb_hideBrakeOnEject", InfoItem.Category.Misc)] - [Persistent(pass = (int)Pass.Global)] //Hide 'Brake on Eject' in Rover Controller + [Persistent(pass = (int)Pass.GLOBAL)] //Hide 'Brake on Eject' in Rover Controller public bool hideBrakeOnEject = false; [ToggleInfoItem("#MechJeb_useTitlebarDragging", InfoItem.Category.Misc)] - [Persistent(pass = (int)Pass.Global)] //Use only the titlebar for window dragging + [Persistent(pass = (int)Pass.GLOBAL)] //Use only the titlebar for window dragging public bool useTitlebarDragging = false; [ToggleInfoItem("#MechJeb_rssMode", InfoItem.Category.Misc)] - [Persistent(pass = (int)Pass.Global)] //Module disabling does not kill throttle (RSS/RO) + [Persistent(pass = (int)Pass.GLOBAL)] //Module disabling does not kill throttle (RSS/RO) public bool rssMode = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool showAdvancedWindowSettings; public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global) @@ -61,9 +61,9 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Settings_button1"))) //"\nRestore factory default settings\n" { FileInfo.CreateForType("mechjeb_settings_global.cfg").Delete(); - if (vessel != null && vessel.vesselName != null) - FileInfo.CreateForType("mechjeb_settings_type_" + vessel.vesselName + ".cfg").Delete(); - core.ReloadAllComputerModules(); + if (Vessel != null && Vessel.vesselName != null) + FileInfo.CreateForType("mechjeb_settings_type_" + Vessel.vesselName + ".cfg").Delete(); + Core.ReloadAllComputerModules(); GuiUtils.SetGUIScale(1); } @@ -109,21 +109,21 @@ protected override void WindowGUI(int windowID) showAdvancedWindowSettings = GUILayout.Toggle(showAdvancedWindowSettings, "Show Advanced Window Settings"); GuiUtils.showAdvancedWindowSettings = showAdvancedWindowSettings; - MechJebModuleCustomWindowEditor ed = core.GetComputerModule(); + MechJebModuleCustomWindowEditor ed = Core.GetComputerModule(); ed.registry.Find(i => i.id == "Toggle:Settings.hideBrakeOnEject").DrawItem(); ed.registry.Find(i => i.id == "Toggle:Settings.useTitlebarDragging").DrawItem(); ed.registry.Find(i => i.id == "Toggle:Menu.useAppLauncher").DrawItem(); - if (ToolbarManager.ToolbarAvailable || core.GetComputerModule().useAppLauncher) + if (ToolbarManager.ToolbarAvailable || Core.GetComputerModule().useAppLauncher) ed.registry.Find(i => i.id == "Toggle:Menu.hideButton").DrawItem(); ed.registry.Find(i => i.id == "General:Menu.MenuPosition").DrawItem(); ed.registry.Find(i => i.id == "Toggle:Settings.rssMode").DrawItem(); - core.Warp.activateSASOnWarp = - GUILayout.Toggle(core.Warp.activateSASOnWarp, Localizer.Format("#MechJeb_Settings_checkbox2")); //"Activate SAS on Warp" + Core.Warp.activateSASOnWarp = + GUILayout.Toggle(Core.Warp.activateSASOnWarp, Localizer.Format("#MechJeb_Settings_checkbox2")); //"Activate SAS on Warp" GUILayout.EndVertical(); diff --git a/MechJeb2/MechJebModuleSmartASS.cs b/MechJeb2/MechJebModuleSmartASS.cs index f33826d7e..94c098d21 100644 --- a/MechJeb2/MechJebModuleSmartASS.cs +++ b/MechJeb2/MechJebModuleSmartASS.cs @@ -109,56 +109,56 @@ public enum Target public static GUIStyle btNormal, btActive, btAuto; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public Mode mode = Mode.ORBITAL; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public Target target = Target.OFF; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfHdg = new EditableDouble(90); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfPit = new EditableDouble(90); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfRol = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfVelYaw = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfVelPit = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble srfVelRol = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble rol = new EditableDouble(0); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public AttitudeReference advReference = AttitudeReference.INERTIAL; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public Vector6.Direction advDirection = Vector6.Direction.FORWARD; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool forceRol; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool forcePitch = true; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool forceYaw = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autoDisableSmartASS = true; [GeneralInfoItem("#MechJeb_DisableSmartACSAutomatically", InfoItem.Category.Misc)] //Disable SmartACS automatically public void AutoDisableSmartASS() { autoDisableSmartASS = GUILayout.Toggle(autoDisableSmartASS, - core.eduMode + Core.eduMode ? Localizer.Format("#MechJeb_SmartASS_checkbox1") : Localizer.Format("#MechJeb_SmartASS_checkbox2")); //"Disable SmartACS automatically":"Disable SmartASS automatically" } @@ -234,13 +234,13 @@ protected override void WindowGUI(int windowID) } // If any other module use the attitude controler then let them do it - if (core.Attitude.enabled && core.Attitude.users.Count(u => !Equals(u)) > 0) + if (Core.Attitude.Enabled && Core.Attitude.Users.Count(u => !Equals(u)) > 0) { if (autoDisableSmartASS) { target = Target.OFF; - if (core.Attitude.users.Contains(this)) - core.Attitude.users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes + if (Core.Attitude.Users.Contains(this)) + Core.Attitude.Users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes } GUILayout.Button(Localizer.Format("#MechJeb_SmartASS_button57"), btAuto, GUILayout.ExpandWidth(true)); //"AUTO" @@ -252,7 +252,7 @@ protected override void WindowGUI(int windowID) GUILayout.BeginHorizontal(); TargetButton(Target.OFF); TargetButton(Target.KILLROT); - if (vessel.patchedConicsUnlocked()) + if (Vessel.patchedConicsUnlocked()) { TargetButton(Target.NODE); } @@ -399,7 +399,7 @@ protected override void WindowGUI(int windowID) Engage(false); } - core.Attitude.SetAxisControl(forcePitch, forceYaw, forceRol); + Core.Attitude.SetAxisControl(forcePitch, forceYaw, forceRol); } else if (target == Target.SURFACE_PROGRADE || target == Target.SURFACE_RETROGRADE) { @@ -421,7 +421,7 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button("CUR", GUILayout.ExpandWidth(false))) { - srfVelRol = -vesselState.vesselRoll.value; + srfVelRol = -VesselState.vesselRoll.value; changed = true; } @@ -449,7 +449,7 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button("CUR", GUILayout.ExpandWidth(false))) { - srfVelPit = vesselState.AoA.value; + srfVelPit = VesselState.AoA.value; changed = true; } @@ -477,7 +477,7 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button("CUR", GUILayout.ExpandWidth(false))) { - srfVelYaw = -vesselState.AoS.value; + srfVelYaw = -VesselState.AoS.value; changed = true; } @@ -498,12 +498,12 @@ protected override void WindowGUI(int windowID) Engage(false); } - core.Attitude.SetAxisControl(forcePitch, forceYaw, forceRol); + Core.Attitude.SetAxisControl(forcePitch, forceYaw, forceRol); } break; case Mode.TARGET: - if (core.Target.NormalTargetExists) + if (Core.Target.NormalTargetExists) { GUILayout.BeginHorizontal(); TargetButton(Target.TARGET_PLUS); @@ -558,11 +558,11 @@ public void Engage(bool resetPID = true) switch (target) { case Target.OFF: - core.Attitude.attitudeDeactivate(); + Core.Attitude.attitudeDeactivate(); return; case Target.KILLROT: - core.Attitude.attitudeKILLROT = true; - attitude = Quaternion.LookRotation(part.vessel.GetTransform().up, -part.vessel.GetTransform().forward); + Core.Attitude.attitudeKILLROT = true; + attitude = Quaternion.LookRotation(Part.vessel.GetTransform().up, -Part.vessel.GetTransform().forward); reference = AttitudeReference.INERTIAL; break; case Target.NODE: @@ -662,11 +662,11 @@ public void Engage(bool resetPID = true) } if (direction != Vector3d.zero) - core.Attitude.attitudeTo(direction, reference, this); + Core.Attitude.attitudeTo(direction, reference, this); else - core.Attitude.attitudeTo(attitude, reference, this); + Core.Attitude.attitudeTo(attitude, reference, this); - if (resetPID) { core.Attitude.Controller.Reset(); } + if (resetPID) { Core.Attitude.Controller.Reset(); } } public override GUILayoutOption[] WindowOptions() @@ -676,14 +676,14 @@ public override GUILayoutOption[] WindowOptions() public override string GetName() { - return core.eduMode + return Core.eduMode ? Localizer.Format("#MechJeb_SmartACS_title") : Localizer.Format("#MechJeb_SmartASS_title"); //"Smart A.C.S.":"Smart A.S.S." } public override string IconName() { - return core.eduMode ? "Smart A.C.S." : "Smart A.S.S."; + return Core.eduMode ? "Smart A.C.S." : "Smart A.S.S."; } } } diff --git a/MechJeb2/MechJebModuleSmartRcs.cs b/MechJeb2/MechJebModuleSmartRcs.cs index 81e5ee04b..0da45433d 100644 --- a/MechJeb2/MechJebModuleSmartRcs.cs +++ b/MechJeb2/MechJebModuleSmartRcs.cs @@ -21,7 +21,7 @@ public enum Target private static GUIStyle btNormal, btActive, btAuto; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autoDisableSmartRCS = true; [GeneralInfoItem("#MechJeb_DisableSmartRcsAutomatically", InfoItem.Category.Misc)] //Disable SmartRcs automatically @@ -68,18 +68,18 @@ protected override void WindowGUI(int windowID) } // Disable if RCS is used by an other module - if (core.RCS.enabled && core.RCS.users.Count(u => !Equals(u)) > 0) + if (Core.RCS.Enabled && Core.RCS.Users.Count(u => !Equals(u)) > 0) { if (autoDisableSmartRCS) { target = Target.OFF; - if (core.RCS.users.Contains(this)) - core.RCS.users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes + if (Core.RCS.Users.Contains(this)) + Core.RCS.Users.Remove(this); // so we don't suddenly turn on when the other autopilot finishes } GUILayout.Button(Localizer.Format("#MechJeb_SmartRcs_button3"), btAuto, GUILayout.ExpandWidth(true)); //"AUTO" } - else if (core.Target.Target == null) + else if (Core.Target.Target == null) { GUILayout.Label(Localizer.Format("#MechJeb_SmartRcs_label1")); //"Choose a target" } @@ -94,10 +94,10 @@ protected override void WindowGUI(int windowID) GUILayout.EndVertical(); } - core.RCS.rcsThrottle = - GUILayout.Toggle(core.RCS.rcsThrottle, Localizer.Format("#MechJeb_SmartRcs_checkbox2")); //" RCS throttle when engines are offline" - core.RCS.rcsForRotation = - GUILayout.Toggle(core.RCS.rcsForRotation, Localizer.Format("#MechJeb_SmartRcs_checkbox3")); // " Use RCS for rotation" + Core.RCS.rcsThrottle = + GUILayout.Toggle(Core.RCS.rcsThrottle, Localizer.Format("#MechJeb_SmartRcs_checkbox2")); //" RCS throttle when engines are offline" + Core.RCS.rcsForRotation = + GUILayout.Toggle(Core.RCS.rcsForRotation, Localizer.Format("#MechJeb_SmartRcs_checkbox3")); // " Use RCS for rotation" base.WindowGUI(windowID); } @@ -106,11 +106,11 @@ public void Engage() switch (target) { case Target.OFF: - core.RCS.users.Remove(this); + Core.RCS.Users.Remove(this); return; case Target.ZERO_RVEL: - core.RCS.users.Add(this); - core.RCS.SetTargetRelative(Vector3d.zero); + Core.RCS.Users.Add(this); + Core.RCS.SetTargetRelative(Vector3d.zero); break; } } diff --git a/MechJeb2/MechJebModuleSpaceplaneAutopilot.cs b/MechJeb2/MechJebModuleSpaceplaneAutopilot.cs index ed8d0812f..267dc80ac 100644 --- a/MechJeb2/MechJebModuleSpaceplaneAutopilot.cs +++ b/MechJeb2/MechJebModuleSpaceplaneAutopilot.cs @@ -12,9 +12,9 @@ public class MechJebModuleSpaceplaneAutopilot : ComputerModule { public MechJebModuleSpaceplaneAutopilot(MechJebCore core) : base(core) { } - public MechJebModuleAirplaneAutopilot Autopilot => core.GetComputerModule(); + public MechJebModuleAirplaneAutopilot Autopilot => Core.GetComputerModule(); - public MechJebModuleRoverController RoverPilot => core.GetComputerModule(); + public MechJebModuleRoverController RoverPilot => Core.GetComputerModule(); /// /// Set to true if reverse thrusters are engaged. @@ -26,7 +26,7 @@ public class MechJebModuleSpaceplaneAutopilot : ComputerModule /// public bool bEngageReverseIfAvailable = true; - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public bool bBreakAsSoonAsLanded = false; /// @@ -37,7 +37,7 @@ public class MechJebModuleSpaceplaneAutopilot : ComputerModule /// /// Glide slope angle for approach (3-5 seems to work best). /// - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public EditableDouble glideslope = 2.5; /// @@ -82,16 +82,16 @@ public class MechJebModuleSpaceplaneAutopilot : ComputerModule /// Minimum approach speed in meters per second. Stall + 10 seems to /// result in a decent approach and landing. /// - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public EditableDouble approachSpeed = 80.0; - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public EditableDouble touchdownSpeed = 60.0; /// /// Maximum allowed bank angle. /// - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public EditableDouble maximumSafeBankAngle = 25.0; /// @@ -131,9 +131,9 @@ public class MechJebModuleSpaceplaneAutopilot : ComputerModule public void Autoland(object controller) { - users.Add(controller); - Autopilot.users.Add(this); - RoverPilot.users.Add(this); + Users.Add(controller); + Autopilot.Users.Add(this); + RoverPilot.Users.Add(this); RoverPilot.ControlHeading = false; RoverPilot.ControlSpeed = false; @@ -144,10 +144,10 @@ public void Autoland(object controller) public void AutopilotOff() { - users.Clear(); - Autopilot.users.Remove(this); - RoverPilot.users.Remove(this); - core.Attitude.attitudeDeactivate(); + Users.Clear(); + Autopilot.Users.Remove(this); + RoverPilot.Users.Remove(this); + Core.Attitude.attitudeDeactivate(); RoverPilot.ControlHeading = false; } @@ -158,9 +158,9 @@ public override void OnStart(PartModule.StartState state) InitRunwaysList(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { - core.Attitude.attitudeDeactivate(); + Core.Attitude.attitudeDeactivate(); } public enum AutolandApproachState @@ -210,7 +210,7 @@ public override void Drive(FlightCtrlState s) if (!Autopilot.HeadingHoldEnabled) { Autopilot.EnableHeadingHold(); - Autopilot.HeadingTarget = vesselState.vesselHeading; + Autopilot.HeadingTarget = VesselState.vesselHeading; } if (Autopilot.AltitudeHoldEnabled) @@ -221,13 +221,13 @@ public override void Drive(FlightCtrlState s) if (!Autopilot.VertSpeedHoldEnabled) { Autopilot.EnableVertSpeedHold(); - Autopilot.VertSpeedTarget = vesselState.speedVertical; + Autopilot.VertSpeedTarget = VesselState.speedVertical; } if (!Autopilot.SpeedHoldEnabled) { Autopilot.EnableSpeedHold(); - Autopilot.SpeedTarget = vesselState.speedSurface; + Autopilot.SpeedTarget = VesselState.speedSurface; } // Set autopilot target and max values for navigation @@ -238,7 +238,7 @@ public override void Drive(FlightCtrlState s) if (approachState == AutolandApproachState.FLARE) { double exponentPerMeter = (Math.Log(targetFlareAoA + 1) - Math.Log(1)) / startFlareAtAltitude; - double desiredAoA = Math.Exp((startFlareAtAltitude - vesselState.altitudeTrue) * exponentPerMeter) - 1; + double desiredAoA = Math.Exp((startFlareAtAltitude - VesselState.altitudeTrue) * exponentPerMeter) - 1; //core.attitude.attitudeTo(Autopilot.HeadingTarget, Math.Max(desiredAoA, flareStartAoA), 0, this, true, false, false); @@ -246,7 +246,7 @@ public override void Drive(FlightCtrlState s) } else if (approachState == AutolandApproachState.TOUCHDOWN) { - vessel.ActionGroups.SetGroup(KSPActionGroup.Gear, true); + Vessel.ActionGroups.SetGroup(KSPActionGroup.Gear, true); } else if (approachState == AutolandApproachState.ROLLOUT) { @@ -257,12 +257,12 @@ public override void Drive(FlightCtrlState s) // Smoothen the main gear touchdown double exponentPerMeterPerSecond = (Math.Log(touchdownMomentAoA + 1) - Math.Log(1)) / touchdownMomentSpeed; double desiredAoA = touchdownMomentAoA - - (Math.Exp(exponentPerMeterPerSecond * (touchdownMomentSpeed - vesselState.speedSurfaceHorizontal)) - 1); - double currentAoA = vesselState.AoA; - core.Attitude.attitudeTo(Autopilot.HeadingTarget, Math.Min(desiredAoA, currentAoA), 0, this, true, false, false); + (Math.Exp(exponentPerMeterPerSecond * (touchdownMomentSpeed - VesselState.speedSurfaceHorizontal)) - 1); + double currentAoA = VesselState.AoA; + Core.Attitude.attitudeTo(Autopilot.HeadingTarget, Math.Min(desiredAoA, currentAoA), 0, this, true, false, false); // Engage reverse thrusters and full throttle - SetReverseThrusters(bEngageReverseIfAvailable && vesselState.speedSurfaceHorizontal > 10); + SetReverseThrusters(bEngageReverseIfAvailable && VesselState.speedSurfaceHorizontal > 10); if (bEngagedReverseThrusters) s.mainThrottle = 1; @@ -271,22 +271,22 @@ public override void Drive(FlightCtrlState s) if (bBreakAsSoonAsLanded) { - vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true); + Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true); } else { // Apply brakes under 30 (if there are no reversers) otherwise under 10 m/s. - vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, - bEngagedReverseThrusters ? vesselState.speedSurfaceHorizontal < 10 : vesselState.speedSurfaceHorizontal < 30); + Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, + bEngagedReverseThrusters ? VesselState.speedSurfaceHorizontal < 10 : VesselState.speedSurfaceHorizontal < 30); } - if (vesselState.speedSurface < 1.0) + if (VesselState.speedSurface < 1.0) { - print("Disengaging autopilot!"); + Print("Disengaging autopilot!"); AutopilotOff(); // disable the autopilot if it was manually engaged by the user - Autopilot.enabled = false; - core.Thrust.ThrustOff(); + Autopilot.Enabled = false; + Core.Thrust.ThrustOff(); } } } @@ -296,7 +296,7 @@ private void SetReverseThrusters(bool bEngage) if (bEngage == bEngagedReverseThrusters) return; - foreach (Part part in vessel.parts) + foreach (Part part in Vessel.parts) { if (part.IsEngine()) { @@ -321,8 +321,8 @@ public double GetAutolandTargetVerticalSpeed(Vector3d vectorToWaypoint) if (approachState == AutolandApproachState.FLARE) return -1.5; - double timeToWaypoint = LateralDistance(vesselState.CoM, vectorToWaypoint) / vesselState.speedSurfaceHorizontal; - double deltaAlt = GetAutolandTargetAltitude(vectorToWaypoint) - vesselState.altitudeASL; + double timeToWaypoint = LateralDistance(VesselState.CoM, vectorToWaypoint) / VesselState.speedSurfaceHorizontal; + double deltaAlt = GetAutolandTargetAltitude(vectorToWaypoint) - VesselState.altitudeASL; double vertSpeed = deltaAlt / timeToWaypoint; @@ -332,10 +332,10 @@ public double GetAutolandTargetVerticalSpeed(Vector3d vectorToWaypoint) { Debug.Assert(vertSpeed < 0); - double latDist = LateralDistance(vesselState.CoM, runway.GetVectorToTouchdown()); + double latDist = LateralDistance(VesselState.CoM, runway.GetVectorToTouchdown()); Vector3d vectorToCorrectPointOnGlideslope = runway.GetPointOnGlideslope(glideslope, latDist); double desiredAlt = GetAutolandTargetAltitude(vectorToCorrectPointOnGlideslope); - double deltaToCorrectAlt = desiredAlt - vesselState.altitudeASL; + double deltaToCorrectAlt = desiredAlt - VesselState.altitudeASL; double expPerMeter = (Math.Log(maximumVerticalSpeedCorrection + 1) - Math.Log(1)) / desiredAlt; double adjustment = Math.Exp(expPerMeter * Math.Abs(deltaToCorrectAlt)) - 1; @@ -354,7 +354,7 @@ public double GetAutolandAlignmentError(Vector3d vectorToWaypoint) public double GetAutolandTargetHeading(Vector3d vectorToWaypoint) { - double targetHeading = vesselState.HeadingFromDirection(vectorToWaypoint); + double targetHeading = VesselState.HeadingFromDirection(vectorToWaypoint); // If we are on final, align with runway and maintain switch (approachState) @@ -397,14 +397,14 @@ public double GetAutolandLateralDistanceFromTouchdownToFinalApproach() public double GetAutolandTurnRadius() { // Formula is r = v / (RoT * (pi/180)) - return vesselState.speedSurfaceHorizontal / (GetAutolandMaxRateOfTurn() * UtilMath.Deg2Rad); + return VesselState.speedSurfaceHorizontal / (GetAutolandMaxRateOfTurn() * UtilMath.Deg2Rad); } public double GetAutolandMaxRateOfTurn() { // Formula is RoT = (g * (180/pi) * tan(Bank)) / v return runway.GetGravitationalAcceleration() * UtilMath.Rad2Deg * Math.Tan(GetAutolandTargetBankAngle() * UtilMath.Deg2Rad) / - vesselState.speedSurfaceHorizontal; + VesselState.speedSurfaceHorizontal; } public double GetAutolandTargetBankAngle() @@ -412,13 +412,13 @@ public double GetAutolandTargetBankAngle() // TODO: return Autopilot.RollLimit; // Formula is Bank = atan((v * t) / (g * (180/pi))) return Math.Min( - Math.Atan(vesselState.speedSurfaceHorizontal * targetRateOfTurn / (runway.GetGravitationalAcceleration() * UtilMath.Rad2Deg)) * + Math.Atan(VesselState.speedSurfaceHorizontal * targetRateOfTurn / (runway.GetGravitationalAcceleration() * UtilMath.Rad2Deg)) * UtilMath.Rad2Deg, GetAutolandMaxBankAngle()); } public double GetAutolandTargetSpeed() { - if (vessel.Landed) + if (Vessel.Landed) return 0; switch (approachState) @@ -438,7 +438,7 @@ public double GetAutolandTargetSpeed() public double GetAutolandLateralDistanceToNextWaypoint() { - return LateralDistance(vesselState.CoM, GetAutolandTargetVector()); + return LateralDistance(VesselState.CoM, GetAutolandTargetVector()); } /// @@ -504,7 +504,7 @@ public Vector3d GetAutolandTargetVector() // Determine whether we should start turning towards FAP. double estimatedTimeToTurn = lateralInterceptAngle / GetAutolandMaxRateOfTurn(); - double timeToGlideslopeIntercept = LateralDistance(vesselState.CoM, vectorToGlideslopeIntercept) / vesselState.speedSurfaceHorizontal; + double timeToGlideslopeIntercept = LateralDistance(VesselState.CoM, vectorToGlideslopeIntercept) / VesselState.speedSurfaceHorizontal; if (estimatedTimeToTurn >= timeToGlideslopeIntercept) { @@ -525,7 +525,7 @@ public Vector3d GetAutolandTargetVector() return initialApproachVector; } - double timeToFAP = LateralDistance(vesselState.CoM, finalApproachVector) / vesselState.speedSurfaceHorizontal; + double timeToFAP = LateralDistance(VesselState.CoM, finalApproachVector) / VesselState.speedSurfaceHorizontal; if (GetAutolandAlignmentError(finalApproachVector) < 3.0 && timeToFAP < secondsThresholdToNextWaypoint) { @@ -538,7 +538,7 @@ public Vector3d GetAutolandTargetVector() if (approachState == AutolandApproachState.TOUCHDOWN) { - if (vesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude + 5) + if (VesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude + 5) { approachState = AutolandApproachState.WAITINGFORFLARE; return runway.End(); @@ -549,10 +549,10 @@ public Vector3d GetAutolandTargetVector() if (approachState == AutolandApproachState.WAITINGFORFLARE) { - if (vesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude) + if (VesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude) { approachState = AutolandApproachState.FLARE; - flareStartAoA = vesselState.AoA; + flareStartAoA = VesselState.AoA; } return runway.End(); @@ -560,11 +560,11 @@ public Vector3d GetAutolandTargetVector() if (approachState == AutolandApproachState.FLARE) { - if (vessel.Landed) + if (Vessel.Landed) { - print("Vessel landed!"); - touchdownMomentAoA = vesselState.AoA; - touchdownMomentSpeed = vesselState.speedSurfaceHorizontal; + Print("Vessel landed!"); + touchdownMomentAoA = VesselState.AoA; + touchdownMomentSpeed = VesselState.speedSurfaceHorizontal; approachState = AutolandApproachState.ROLLOUT; } @@ -612,10 +612,10 @@ private Vector3d PreventClimbingIntoGlideslope(Vector3d v) { runway.body.GetLatLonAlt(v, out double lat, out double lon, out double alt); - if (alt <= vesselState.altitudeASL) + if (alt <= VesselState.altitudeASL) return v; - return runway.body.GetWorldSurfacePosition(lat, lon, vesselState.altitudeASL); + return runway.body.GetWorldSurfacePosition(lat, lon, VesselState.altitudeASL); } /// @@ -650,7 +650,7 @@ private Vector3d FindVectorToGlideslopeIntercept(Vector3d finalApproachVector, d // We know the lateral distance to the final approach point, we // want to find a point on the glide slope which we can // intercept at a given angle. - double dist = LateralDistance(vesselState.CoM, finalApproachVector) * Math.Sin(UtilMath.Deg2Rad * omega) / + double dist = LateralDistance(VesselState.CoM, finalApproachVector) * Math.Sin(UtilMath.Deg2Rad * omega) / Math.Sin(UtilMath.Deg2Rad * theta); // If this is a bad intercept, proceed to IAP. diff --git a/MechJeb2/MechJebModuleSpaceplaneGuidance.cs b/MechJeb2/MechJebModuleSpaceplaneGuidance.cs index 647855d22..8d3cd2dfa 100644 --- a/MechJeb2/MechJebModuleSpaceplaneGuidance.cs +++ b/MechJeb2/MechJebModuleSpaceplaneGuidance.cs @@ -14,7 +14,7 @@ public class MechJebModuleSpaceplaneGuidance : DisplayModule protected bool _showLandingTarget; - [Persistent(pass = (int)(Pass.Global | Pass.Local))] + [Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))] public int runwayIndex; public bool showLandingTarget @@ -22,8 +22,8 @@ public bool showLandingTarget get => _showLandingTarget; set { - if (value && !_showLandingTarget) core.Target.SetDirectionTarget("ILS Guidance"); - if (!value && core.Target.Target is DirectionTarget && core.Target.Name == "ILS Guidance") core.Target.Unset(); + if (value && !_showLandingTarget) Core.Target.SetDirectionTarget("ILS Guidance"); + if (!value && Core.Target.Target is DirectionTarget && Core.Target.Name == "ILS Guidance") Core.Target.Unset(); _showLandingTarget = value; } } @@ -32,7 +32,7 @@ protected override void WindowGUI(int windowID) { GUILayout.BeginVertical(); - var availableRunways = MechJebModuleSpaceplaneAutopilot.runways.Where(p => p.body == mainBody).ToList(); + var availableRunways = MechJebModuleSpaceplaneAutopilot.runways.Where(p => p.body == MainBody).ToList(); if (runwayIndex > availableRunways.Count) runwayIndex = 0; @@ -44,14 +44,14 @@ protected override void WindowGUI(int windowID) autoland.runway = availableRunways[runwayIndex]; GUILayout.Label(Localizer.Format("#MechJeb_ApproAndLand_label2") + - Vector3d.Distance(vesselState.CoM, autoland.runway.Start()).ToSI() + "m"); //Distance to runway: + Vector3d.Distance(VesselState.CoM, autoland.runway.Start()).ToSI() + "m"); //Distance to runway: showLandingTarget = GUILayout.Toggle(showLandingTarget, Localizer.Format("#MechJeb_ApproAndLand_label3")); //Show landing navball guidance if (GUILayout.Button(Localizer.Format("#MechJeb_ApproAndLan_button1"))) //Autoland autoland.Autoland(this); - if (autoland.enabled && GUILayout.Button(Localizer.Format("#MechJeb_ApproAndLan_button2"))) //Abort + if (autoland.Enabled && GUILayout.Button(Localizer.Format("#MechJeb_ApproAndLan_button2"))) //Abort autoland.AutopilotOff(); GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_ApproAndLand_label14"), autoland.glideslope, "°"); //Autoland glideslope: @@ -64,7 +64,7 @@ protected override void WindowGUI(int windowID) autoland.bBreakAsSoonAsLanded = GUILayout.Toggle(autoland.bBreakAsSoonAsLanded, Localizer.Format("#MechJeb_ApproAndLand_label7")); //Brake as soon as landed - if (autoland.enabled) + if (autoland.Enabled) { GUILayout.Label(Localizer.Format("#MechJeb_ApproAndLand_label8") + autoland.AutolandApproachStateToHumanReadableDescription()); //State: @@ -95,17 +95,17 @@ public override void OnFixedUpdate() { if (showLandingTarget && autoland != null) { - if (!(core.Target.Target is DirectionTarget && core.Target.Name == "ILS Guidance")) showLandingTarget = false; + if (!(Core.Target.Target is DirectionTarget && Core.Target.Name == "ILS Guidance")) showLandingTarget = false; else { - core.Target.UpdateDirectionTarget(autoland.GetAutolandTargetVector()); + Core.Target.UpdateDirectionTarget(autoland.GetAutolandTargetVector()); } } } public override void OnStart(PartModule.StartState state) { - autoland = core.GetComputerModule(); + autoland = Core.GetComputerModule(); } public MechJebModuleSpaceplaneGuidance(MechJebCore core) : base(core) { } diff --git a/MechJeb2/MechJebModuleSpinupController.cs b/MechJeb2/MechJebModuleSpinupController.cs index ea1bdb390..2141c145b 100644 --- a/MechJeb2/MechJebModuleSpinupController.cs +++ b/MechJeb2/MechJebModuleSpinupController.cs @@ -25,21 +25,21 @@ public MechJebModuleSpinupController(MechJebCore core) : base(core) private SpinupState _state; private double _startTime; - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { _state = SpinupState.INITIALIZED; - _startTime = Math.Max(vesselState.time, _startTime); - core.Attitude.users.Add(this); + _startTime = Math.Max(VesselState.time, _startTime); + Core.Attitude.Users.Add(this); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { _state = SpinupState.FINISHED; - core.Attitude.SetOmegaTarget(roll: double.NaN); - core.Attitude.SetActuationControl(); + Core.Attitude.SetOmegaTarget(roll: double.NaN); + Core.Attitude.SetActuationControl(); // FIXME: this might overwrite someone else, but the only other consumer so far is the GuidanceController - core.Staging.autostageLimitInternal = 0; - core.Attitude.users.Remove(this); + Core.Staging.autostageLimitInternal = 0; + Core.Attitude.Users.Remove(this); base.OnModuleDisabled(); } @@ -57,7 +57,7 @@ private void HandleStageEvent(int data) { // wait a second to enable after staging because aerodynamics may kick us, // but on the first tick we may think we are stable - _startTime = vesselState.time + 1.0; + _startTime = VesselState.time + 1.0; } public override void Drive(FlightCtrlState s) @@ -65,27 +65,27 @@ public override void Drive(FlightCtrlState s) if (_state == SpinupState.INITIALIZED) return; - core.Staging.autostageLimitInternal = vessel.currentStage; + Core.Staging.autostageLimitInternal = Vessel.currentStage; - if (vesselState.time < _startTime) + if (VesselState.time < _startTime) return; if (_state == SpinupState.STARTING) _state = SpinupState.STABILIZING; - if (vessel.angularVelocityD.y / RollAngularVelocity >= 0.99) - enabled = false; + if (Vessel.angularVelocityD.y / RollAngularVelocity >= 0.99) + Enabled = false; - if (!vessel.ActionGroups[KSPActionGroup.RCS]) - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); - if (_state == SpinupState.STABILIZING && (core.Attitude.attitudeAngleFromTarget() > 1.0 || core.vessel.angularVelocity.magnitude > 0.001)) + if (_state == SpinupState.STABILIZING && (Core.Attitude.attitudeAngleFromTarget() > 1.0 || Core.vessel.angularVelocity.magnitude > 0.001)) return; _state = SpinupState.SPINUP; - core.Attitude.SetOmegaTarget(roll: RollAngularVelocity); - core.Attitude.SetActuationControl(false, false); + Core.Attitude.SetOmegaTarget(roll: RollAngularVelocity); + Core.Attitude.SetActuationControl(false, false); } public void AssertStart() diff --git a/MechJeb2/MechJebModuleStageStats.cs b/MechJeb2/MechJebModuleStageStats.cs index 57047906a..feca19f6d 100644 --- a/MechJeb2/MechJebModuleStageStats.cs +++ b/MechJeb2/MechJebModuleStageStats.cs @@ -31,7 +31,7 @@ public class MechJebModuleStageStats : ComputerModule public void RequestUpdate(object controller, bool wait = false) { - users.Add(controller); + Users.Add(controller); updateRequested = true; IsResultReady(); @@ -101,13 +101,13 @@ private void setDirty() needRebuild = 2; } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { millisecondsBetweenSimulations = 0; stopwatch.Start(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { stopwatch.Stop(); stopwatch.Reset(); @@ -144,7 +144,7 @@ private void IsResultReady() private bool TryStartSimulation() { - if (!simulationRunning && ((HighLogic.LoadedSceneIsEditor && editorBody != null) || vessel != null)) + if (!simulationRunning && ((HighLogic.LoadedSceneIsEditor && editorBody != null) || Vessel != null)) { //We should be running simulations periodically, but one is not running right now. //Check if enough time has passed since the last one to start a new one: @@ -161,7 +161,7 @@ private bool TryStartSimulation() return true; } - users.Clear(); + Users.Clear(); } } @@ -178,7 +178,7 @@ protected void StartSimulation() stopwatch.Start(); //starts a timer that times how long the simulation takes //Create two FuelFlowSimulations, one for vacuum and one for atmosphere - List parts = HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : vessel.parts; + List parts = HighLogic.LoadedSceneIsEditor ? EditorLogic.fetch.ship.parts : Vessel.parts; if (HighLogic.LoadedSceneIsEditor) { @@ -190,7 +190,7 @@ protected void StartSimulation() } else { - vessel.UpdateResourceSetsIfDirty(); + Vessel.UpdateResourceSetsIfDirty(); } Profiler.BeginSample("StartSimulation_Init"); @@ -210,7 +210,7 @@ protected void StartSimulation() } catch (Exception e) { - print("Exception in MechJebModuleStageStats.StartSimulation(): " + e + "\n" + e.StackTrace); + Print("Exception in MechJebModuleStageStats.StartSimulation(): " + e + "\n" + e.StackTrace); // Stop timing the simulation stopwatch.Stop(); @@ -229,15 +229,15 @@ protected void RunSimulation(object o) { try { - CelestialBody simBody = HighLogic.LoadedSceneIsEditor ? editorBody : vessel.mainBody; + CelestialBody simBody = HighLogic.LoadedSceneIsEditor ? editorBody : Vessel.mainBody; double staticPressureKpa = HighLogic.LoadedSceneIsEditor || !liveSLT ? simBody.atmosphere ? simBody.GetPressure(altSLT) : 0 - : vessel.staticPressurekPa; + : Vessel.staticPressurekPa; double atmDensity = (HighLogic.LoadedSceneIsEditor || !liveSLT ? simBody.GetDensity(simBody.GetPressure(altSLT), simBody.GetTemperature(0)) - : vessel.atmDensity) / 1.225; - double mach = HighLogic.LoadedSceneIsEditor ? this.mach : vessel.mach; + : Vessel.atmDensity) / 1.225; + double mach = HighLogic.LoadedSceneIsEditor ? this.mach : Vessel.mach; //Run the simulation newAtmoStats = sims[0].SimulateAllStages(1.0f, staticPressureKpa, atmDensity, mach); @@ -245,7 +245,7 @@ protected void RunSimulation(object o) } catch (Exception e) { - Dispatcher.InvokeAsync(() => print("Exception in MechJebModuleStageStats.RunSimulation(): " + e)); + Dispatcher.InvokeAsync(() => Print("Exception in MechJebModuleStageStats.RunSimulation(): " + e)); } //see how long the simulation took diff --git a/MechJeb2/MechJebModuleStagingController.cs b/MechJeb2/MechJebModuleStagingController.cs index 6fec58642..a49053ade 100644 --- a/MechJeb2/MechJebModuleStagingController.cs +++ b/MechJeb2/MechJebModuleStagingController.cs @@ -13,41 +13,41 @@ public class MechJebModuleStagingController : ComputerModule public MechJebModuleStagingController(MechJebCore core) : base(core) { - priority = 1000; + Priority = 1000; } //adjustable parameters: - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble autostagePreDelay = 0.0; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble autostagePostDelay = 0.5; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableInt autostageLimit = 0; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDoubleMult fairingMaxDynamicPressure = new EditableDoubleMult(5000, 1000); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDoubleMult fairingMinAltitude = new EditableDoubleMult(50000, 1000); - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public EditableDouble clampAutoStageThrustPct = 0.99; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDoubleMult fairingMaxAerothermalFlux = new EditableDoubleMult(1135); - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool hotStaging; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble hotStagingLeadTime = 1.0; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public bool dropSolids; - [Persistent(pass = (int)(Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.TYPE | Pass.GLOBAL))] public EditableDouble dropSolidsLeadTime = 1.0; public bool autostagingOnce; @@ -66,7 +66,7 @@ public MechJebModuleStagingController(MechJebCore core) private readonly Dictionary inverseStageReleasesClampsCache = new Dictionary(16); private readonly Dictionary hasStayingChutesCache = new Dictionary(16); private readonly Dictionary hasFairingCache = new Dictionary(16); - private MechJebModuleStageStats stats => core.GetComputerModule(); + private MechJebModuleStageStats stats => Core.GetComputerModule(); private FuelFlowSimulation.FuelStats[] vacStats => stats.vacStats; private enum RemoteStagingState @@ -80,7 +80,7 @@ private enum RemoteStagingState public override void OnStart(PartModule.StartState state) { - if (vessel != null && vessel.situation == Vessel.Situations.PRELAUNCH) + if (Vessel != null && Vessel.situation == Vessel.Situations.PRELAUNCH) waitingForFirstStaging = true; GameEvents.onStageActivate.Add(stageActivate); @@ -101,13 +101,13 @@ private void OnGUIStageSequenceModified() private void OnVesselModified(Vessel v) { - if (vessel == v) RegenerateCaches(); + if (Vessel == v) RegenerateCaches(); } private void BuildEnginesCache(List engines) { engines.Clear(); - foreach (Part p in vessel.Parts) + foreach (Part p in Vessel.Parts) if (p.IsEngine() && !p.IsSepratron()) engines.AddRange(p.FindModulesImplementing()); } @@ -115,7 +115,7 @@ private void BuildEnginesCache(List engines) private void BuildDecouplersCache(List decouplers) { decouplers.Clear(); - foreach (Part p in vessel.Parts) + foreach (Part p in Vessel.Parts) if (p.IsDecoupler()) foreach (PartModule pm in p.Modules) if (pm is ModuleDecouplerBase || pm is ModuleDockingNode || pm.moduleName == "ProceduralFairingDecoupler") @@ -154,16 +154,16 @@ private void stageActivate(int data) public void AutostageOnce(object user) { - users.Add(user); + Users.Add(user); autostagingOnce = true; } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { autostageLimitInternal = 0; } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { autostagingOnce = false; } @@ -220,7 +220,7 @@ public void AutostageSettingsInfoItem() [ValueInfoItem("#MechJeb_Autostagingstatus", InfoItem.Category.Misc)] //Autostaging status public string AutostageStatus() { - if (!enabled) return CachedLocalizer.Instance.MechJeb_Ascent_status9; //"Autostaging off" + if (!Enabled) return CachedLocalizer.Instance.MechJeb_Ascent_status9; //"Autostaging off" if (autostagingOnce) return CachedLocalizer.Instance.MechJeb_Ascent_status10; //"Will autostage next stage only" return CachedLocalizer.Instance.MechJeb_Ascent_status11 + (int)autostageLimit; //"Autostaging until stage #" } @@ -228,11 +228,11 @@ public string AutostageStatus() [GeneralInfoItem("#MechJeb_ClampAutostageThrust", InfoItem.Category.Misc)] //Clamp Autostage Thrust public void ClampAutostageThrust() { - double prev = core.Staging.clampAutoStageThrustPct; - GuiUtils.SimpleTextBox(CachedLocalizer.Instance.MechJeb_Ascent_label44, core.Staging.clampAutoStageThrustPct, "%", + double prev = Core.Staging.clampAutoStageThrustPct; + GuiUtils.SimpleTextBox(CachedLocalizer.Instance.MechJeb_Ascent_label44, Core.Staging.clampAutoStageThrustPct, "%", 50); //"Clamp AutoStage Thrust " - if (prev != core.Staging.clampAutoStageThrustPct) - core.Staging.clampAutoStageThrustPct = UtilMath.Clamp(core.Staging.clampAutoStageThrustPct, 0, 100); + if (prev != Core.Staging.clampAutoStageThrustPct) + Core.Staging.clampAutoStageThrustPct = UtilMath.Clamp(Core.Staging.clampAutoStageThrustPct, 0, 100); } //internal state: @@ -260,18 +260,18 @@ public override void OnUpdate() // if autostage enabled, and if we've already staged at least once, and if there are stages left, // and if we are allowed to continue staging, and if we didn't just fire the previous stage - if (waitingForFirstStaging || vessel.currentStage <= 0 || vessel.currentStage <= autostageLimit || - vesselState.time - lastStageTime < autostagePostDelay) + if (waitingForFirstStaging || Vessel.currentStage <= 0 || Vessel.currentStage <= autostageLimit || + VesselState.time - lastStageTime < autostagePostDelay) { return; } // this is for PVG preventing staging doing coasts, possibly it should be more specific of an API // (e.g. bool PVGIsCoasting) since it is getting tightly coupled. - if (vessel.currentStage <= autostageLimitInternal) + if (Vessel.currentStage <= autostageLimitInternal) { // force staging once if fairing conditions are met in the next stage - if (HasFairing(vessel.currentStage - 1) && !WaitingForFairing()) + if (HasFairing(Vessel.currentStage - 1) && !WaitingForFairing()) { Stage(); } @@ -285,35 +285,35 @@ public override void OnUpdate() UpdateBurnedResources(); // don't decouple active or idle engines or tanks - if (InverseStageDecouplesActiveOrIdleEngineOrTank(vessel.currentStage - 1, burnedResources, activeModuleEngines) && - !InverseStageReleasesClamps(vessel.currentStage - 1)) + if (InverseStageDecouplesActiveOrIdleEngineOrTank(Vessel.currentStage - 1, burnedResources, activeModuleEngines) && + !InverseStageReleasesClamps(Vessel.currentStage - 1)) return; // prevent staging if we have unstable ullage and we have RCS - if (InverseStageHasUnstableEngines(vessel.currentStage - 1) && core.Thrust.autoRCSUllaging && vessel.hasEnabledRCSModules() && - core.Thrust.LastThrottle > 0) + if (InverseStageHasUnstableEngines(Vessel.currentStage - 1) && Core.Thrust.autoRCSUllaging && Vessel.hasEnabledRCSModules() && + Core.Thrust.LastThrottle > 0) { - if (!vessel.ActionGroups[KSPActionGroup.RCS]) - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); return; } // always stage if we have no active engines - if (!InverseStageHasActiveEngines(vessel.currentStage)) + if (!InverseStageHasActiveEngines(Vessel.currentStage)) Stage(); // prevent staging when the current stage has active engines and the next stage has any engines (but not decouplers or clamps) - if (hotStaging && InverseStageHasEngines(vessel.currentStage - 1) && - !InverseStageFiresDecoupler(vessel.currentStage - 1) && !InverseStageReleasesClamps(vessel.currentStage - 1) && + if (hotStaging && InverseStageHasEngines(Vessel.currentStage - 1) && + !InverseStageFiresDecoupler(Vessel.currentStage - 1) && !InverseStageReleasesClamps(Vessel.currentStage - 1) && LastNonZeroDVStageBurnTime() > hotStagingLeadTime) return; // Don't fire a stage that will activate a parachute, unless that parachute gets decoupled: - if (HasStayingChutes(vessel.currentStage - 1)) + if (HasStayingChutes(Vessel.currentStage - 1)) return; // Always drop deactivated engines or tanks - if (InverseStageDecouplesDeactivatedEngineOrTank(vessel.currentStage - 1)) + if (InverseStageDecouplesDeactivatedEngineOrTank(Vessel.currentStage - 1)) Stage(); // only decouple fairings if the dynamic pressure, altitude, and aerothermal flux conditions are respected @@ -321,8 +321,8 @@ public override void OnUpdate() return; // only release launch clamps if we're at nearly full thrust and no failed engines - if ((vesselState.thrustCurrent / vesselState.thrustAvailable < clampAutoStageThrustPct || AnyFailedEngines(allModuleEngines)) && - InverseStageReleasesClamps(vessel.currentStage - 1)) + if ((VesselState.thrustCurrent / VesselState.thrustAvailable < clampAutoStageThrustPct || AnyFailedEngines(allModuleEngines)) && + InverseStageReleasesClamps(Vessel.currentStage - 1)) return; Stage(); @@ -330,16 +330,16 @@ public override void OnUpdate() private bool WaitingForFairing() { - if (!HasFairing(vessel.currentStage - 1)) + if (!HasFairing(Vessel.currentStage - 1)) return false; - if (core.VesselState.dynamicPressure > fairingMaxDynamicPressure) + if (Core.VesselState.dynamicPressure > fairingMaxDynamicPressure) return true; - if (core.VesselState.altitudeASL < fairingMinAltitude) + if (Core.VesselState.altitudeASL < fairingMinAltitude) return true; - if (core.VesselState.freeMolecularAerothermalFlux > fairingMaxAerothermalFlux) + if (Core.VesselState.freeMolecularAerothermalFlux > fairingMaxAerothermalFlux) return true; return false; @@ -351,21 +351,21 @@ public void Stage() //length given by autostagePreDelay) and only stage once that countdown finishes, if (countingDown) { - if (vesselState.time - stageCountdownStart > autostagePreDelay) + if (VesselState.time - stageCountdownStart > autostagePreDelay) { - if (InverseStageFiresDecoupler(vessel.currentStage - 1)) + if (InverseStageFiresDecoupler(Vessel.currentStage - 1)) { //if we decouple things, delay the next stage a bit to avoid exploding the debris - lastStageTime = vesselState.time; + lastStageTime = VesselState.time; } - if (!vessel.isActiveVessel) + if (!Vessel.isActiveVessel) { currentActiveVessel = FlightGlobals.ActiveVessel; - Debug.Log($"Mechjeb Autostage: Switching from {FlightGlobals.ActiveVessel.name} to vessel {vessel.name} to stage"); + Debug.Log($"Mechjeb Autostage: Switching from {FlightGlobals.ActiveVessel.name} to vessel {Vessel.name} to stage"); remoteStagingStatus = RemoteStagingState.WaitingFocus; - FlightGlobals.ForceSetActiveVessel(vessel); + FlightGlobals.ForceSetActiveVessel(Vessel); } else { @@ -387,13 +387,13 @@ public void Stage() countingDown = false; if (autostagingOnce) - users.Clear(); + Users.Clear(); } } else { countingDown = true; - stageCountdownStart = vesselState.time; + stageCountdownStart = VesselState.time; } } @@ -449,7 +449,7 @@ public bool AnyFailedEngines(List allEngines) foreach (ModuleEngines engine in allEngines) { Part p = engine.part; - if (p.inverseStage >= vessel.currentStage && !p.IsDecoupledInStage(vessel.currentStage - 1) && engine.isEnabled && + if (p.inverseStage >= Vessel.currentStage && !p.IsDecoupledInStage(Vessel.currentStage - 1) && engine.isEnabled && !engine.EngineIgnited && engine.allowShutdown) return true; } @@ -463,7 +463,7 @@ public void UpdateActiveModuleEngines(List allEngines) foreach (ModuleEngines engine in allEngines) { Part p = engine.part; - if (p.inverseStage >= vessel.currentStage && !p.IsDecoupledInStage(vessel.currentStage - 1) && engine.isEnabled) + if (p.inverseStage >= Vessel.currentStage && !p.IsDecoupledInStage(Vessel.currentStage - 1) && engine.isEnabled) activeModuleEngines.Add(engine); } } @@ -479,7 +479,7 @@ public void UpdateBurnedResources() public bool isBurnedOutSRBDecoupledInNextStage(Part p) { return dropSolids && p.IsThrottleLockedEngine() && LastNonZeroDVStageBurnTime() < dropSolidsLeadTime && - p.IsDecoupledInStage(vessel.currentStage - 1); + p.IsDecoupledInStage(Vessel.currentStage - 1); } //detect if a part is above an active or idle engine in the part tree @@ -541,7 +541,7 @@ public bool InverseStageFiresDecoupler(int inverseStage) { if (inverseStageFiresDecouplerCache.TryGetValue(inverseStage, out bool result)) return result; - result = vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsUnfiredDecoupler(out Part _)) != null; + result = Vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsUnfiredDecoupler(out Part _)) != null; inverseStageFiresDecouplerCache.Add(inverseStage, result); return result; } @@ -551,7 +551,7 @@ public bool InverseStageReleasesClamps(int inverseStage) { if (inverseStageReleasesClampsCache.TryGetValue(inverseStage, out bool result)) return result; - result = vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsLaunchClamp()) != null; + result = Vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsLaunchClamp()) != null; inverseStageReleasesClampsCache.Add(inverseStage, result); return result; } @@ -606,7 +606,7 @@ public bool HasStayingChutes(int inverseStage) { if (hasStayingChutesCache.TryGetValue(inverseStage, out bool result)) return result; - result = vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsParachute() && !p.IsDecoupledInStage(inverseStage)) != + result = Vessel.Parts.FirstOrDefault(p => p.inverseStage == inverseStage && p.IsParachute() && !p.IsDecoupledInStage(inverseStage)) != null; hasStayingChutesCache.Add(inverseStage, result); return result; @@ -627,7 +627,7 @@ private bool HasFairing(int inverseStage) private bool HasFairingUncached(int inverseStage) { _partsInStage.Clear(); - vessel.parts.Slinq().Where((p, s) => p.inverseStage == s, inverseStage).AddTo(_partsInStage); + Vessel.parts.Slinq().Where((p, s) => p.inverseStage == s, inverseStage).AddTo(_partsInStage); // proc parts are reasonably easy, but all the parts in the stage must be payload fairings for them to // be treated as payload fairings here. a payload fairing and a stack decoupler will bypass the fairing diff --git a/MechJeb2/MechJebModuleTargetController.cs b/MechJeb2/MechJebModuleTargetController.cs index b7d15fd9b..788790e53 100644 --- a/MechJeb2/MechJebModuleTargetController.cs +++ b/MechJeb2/MechJebModuleTargetController.cs @@ -23,10 +23,10 @@ public class MechJebModuleTargetController : ComputerModule public CelestialBody targetBody; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableAngle targetLatitude = new EditableAngle(0); - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableAngle targetLongitude = new EditableAngle(0); private Vector3d targetDirection; @@ -42,9 +42,9 @@ public class MechJebModuleTargetController : ComputerModule public void Set(ITargetable t) { Target = t; - if (vessel != null) + if (Vessel != null) { - vessel.targetObject = Target; + Vessel.targetObject = Target; } } @@ -87,7 +87,7 @@ public void PickPositionTargetOnMap() MapView.EnterMapView(); string message = Localizer.Format("#MechJeb_pickingPositionMsg", - mainBody.displayName.LocalizeRemoveGender()); // "Click to select a target on " + + "'s surface.\n(Leave map view to cancel.)" + MainBody.displayName.LocalizeRemoveGender()); // "Click to select a target on " + + "'s surface.\n(Leave map view to cancel.)" ScreenMessages.PostScreenMessage(message, 3.0f, ScreenMessageStyle.UPPER_CENTER); } @@ -127,11 +127,11 @@ public Orbit TargetOrbit public Vector3 Position => Transform.position; - public float Distance => Vector3.Distance(Position, vessel.GetTransform().position); + public float Distance => Vector3.Distance(Position, Vessel.GetTransform().position); - public Vector3d RelativeVelocity => vessel.orbit.GetVel() - TargetOrbit.GetVel(); + public Vector3d RelativeVelocity => Vessel.orbit.GetVel() - TargetOrbit.GetVel(); - public Vector3d RelativePosition => vessel.GetTransform().position - Position; + public Vector3d RelativePosition => Vessel.GetTransform().position - Position; public Transform Transform => Target.GetTransform(); @@ -153,31 +153,31 @@ public Vector3 DockingAxis public override void OnStart(PartModule.StartState state) { - core.AddToPostDrawQueue(DoMapView); + Core.AddToPostDrawQueue(DoMapView); - users.Add(this); //TargetController should always be running + Users.Add(this); //TargetController should always be running } public override void OnFixedUpdate() { //Restore the saved target when we are made active vessel - if (!wasActiveVessel && vessel.isActiveVessel) + if (!wasActiveVessel && Vessel.isActiveVessel) { if (Target != null && Target.GetVessel() != null) { - vessel.targetObject = Target; + Vessel.targetObject = Target; } } //notice when the user switches targets - if (Target != vessel.targetObject) + if (Target != Vessel.targetObject) { - Target = vessel.targetObject; - if (Target is Vessel && ((Vessel)Target).LandedOrSplashed && ((Vessel)Target).mainBody == vessel.mainBody) + Target = Vessel.targetObject; + if (Target is Vessel && ((Vessel)Target).LandedOrSplashed && ((Vessel)Target).mainBody == Vessel.mainBody) { - targetBody = vessel.mainBody; - targetLatitude = vessel.mainBody.GetLatitude(Target.GetTransform().position); - targetLongitude = vessel.mainBody.GetLongitude(Target.GetTransform().position); + targetBody = Vessel.mainBody; + targetLatitude = Vessel.mainBody.GetLatitude(Target.GetTransform().position); + targetLongitude = Vessel.mainBody.GetLongitude(Target.GetTransform().position); } if (Target is CelestialBody) @@ -188,20 +188,20 @@ public override void OnFixedUpdate() // .23 temp fix until I understand better what's going on if (targetBody == null) - targetBody = vessel.mainBody; + targetBody = Vessel.mainBody; //Update targets that need updating: if (Target is DirectionTarget) ((DirectionTarget)Target).Update(targetDirection); else if (Target is PositionTarget) ((PositionTarget)Target).Update(targetBody, targetLatitude, targetLongitude); - wasActiveVessel = vessel.isActiveVessel; + wasActiveVessel = Vessel.isActiveVessel; } public override void OnUpdate() { if (MapView.MapIsEnabled && pickingPositionTarget) { - if (!GuiUtils.MouseIsOverWindow(core) && GuiUtils.GetMouseCoordinates(mainBody) != null) + if (!GuiUtils.MouseIsOverWindow(Core) && GuiUtils.GetMouseCoordinates(MainBody) != null) Cursor.visible = false; else Cursor.visible = true; @@ -223,23 +223,23 @@ private void DoCoordinatePicking() if (!pickingPositionTarget) return; - if (MapView.MapIsEnabled && vessel.isActiveVessel) + if (MapView.MapIsEnabled && Vessel.isActiveVessel) { - if (!GuiUtils.MouseIsOverWindow(core)) + if (!GuiUtils.MouseIsOverWindow(Core)) { - Coordinates mouseCoords = GuiUtils.GetMouseCoordinates(mainBody); + Coordinates mouseCoords = GuiUtils.GetMouseCoordinates(MainBody); if (mouseCoords != null) { - GLUtils.DrawGroundMarker(mainBody, mouseCoords.latitude, mouseCoords.longitude, new Color(1.0f, 0.56f, 0.0f), true, 60); + GLUtils.DrawGroundMarker(MainBody, mouseCoords.latitude, mouseCoords.longitude, new Color(1.0f, 0.56f, 0.0f), true, 60); - string biome = mainBody.GetExperimentBiomeSafe(mouseCoords.latitude, mouseCoords.longitude); + string biome = MainBody.GetExperimentBiomeSafe(mouseCoords.latitude, mouseCoords.longitude); GUI.Label(new Rect(Input.mousePosition.x + 15, Screen.height - Input.mousePosition.y, 200, 50), mouseCoords.ToStringDecimal() + "\n" + biome); if (Input.GetMouseButtonDown(0)) { - SetPositionTarget(mainBody, mouseCoords.latitude, mouseCoords.longitude); + SetPositionTarget(MainBody, mouseCoords.latitude, mouseCoords.longitude); StopPickPositionTargetOnMap(); } } @@ -251,11 +251,11 @@ private void DrawMapViewTarget() { if (HighLogic.LoadedSceneIsEditor) return; if (!MapView.MapIsEnabled) return; - if (!vessel.isActiveVessel || vessel.GetMasterMechJeb() != core) return; + if (!Vessel.isActiveVessel || Vessel.GetMasterMechJeb() != Core) return; if (Target == null) return; if (!(Target is PositionTarget) && !(Target is Vessel)) return; - if (Target is Vessel && (!((Vessel)Target).LandedOrSplashed || ((Vessel)Target).mainBody != vessel.mainBody)) return; + if (Target is Vessel && (!((Vessel)Target).LandedOrSplashed || ((Vessel)Target).mainBody != Vessel.mainBody)) return; if (Target is DirectionTarget) return; GLUtils.DrawGroundMarker(targetBody, targetLatitude, targetLongitude, Color.red, true); diff --git a/MechJeb2/MechJebModuleThrustController.cs b/MechJeb2/MechJebModuleThrustController.cs index 5ee4b1db1..6e05356aa 100644 --- a/MechJeb2/MechJebModuleThrustController.cs +++ b/MechJeb2/MechJebModuleThrustController.cs @@ -19,7 +19,7 @@ public enum DifferentialThrottleStatus public MechJebModuleThrustController(MechJebCore core) : base(core) { - priority = 200; + Priority = 200; } public float trans_spd_act; @@ -40,10 +40,10 @@ public MechJebModuleThrustController(MechJebCore core) // limitToTerminalVelocity = GUILayout.Toggle(limitToTerminalVelocity, "Limit to terminal velocity", s); //} - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool limitDynamicPressure; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble maxDynamicPressure = 20000; [GeneralInfoItem("#MechJeb_LimittoMaxQ", InfoItem.Category.Thrust)] //Limit to Max Q @@ -53,7 +53,7 @@ public void LimitToMaxDynamicPressureInfoItem() GuiUtils.ToggledTextBox(ref limitDynamicPressure, CachedLocalizer.Instance.MechJeb_Ascent_checkbox11, maxDynamicPressure, "pa", s, 80); } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool limitToPreventOverheats; [GeneralInfoItem("#MechJeb_PreventEngineOverheats", InfoItem.Category.Thrust)] //Prevent engine overheats @@ -65,13 +65,13 @@ public void LimitToPreventOverheatsInfoItem() } [ToggleInfoItem("#MechJeb_SmoothThrottle", InfoItem.Category.Thrust)] //Smooth throttle - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool smoothThrottle = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public double throttleSmoothingTime = 1.0; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool limitToPreventFlameout; [GeneralInfoItem("#MechJeb_PreventJetFlameout", InfoItem.Category.Thrust)] //Prevent jet flameout @@ -82,7 +82,7 @@ public void LimitToPreventFlameoutInfoItem() GUILayout.Toggle(limitToPreventFlameout, CachedLocalizer.Instance.MechJeb_Ascent_checkbox13, s); //"Prevent jet flameout" } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool limitToPreventUnstableIgnition; [GeneralInfoItem("#MechJeb_PreventUnstableIgnition", InfoItem.Category.Thrust)] //Prevent unstable ignition @@ -93,7 +93,7 @@ public void LimitToPreventUnstableIgnitionInfoItem() GUILayout.Toggle(limitToPreventUnstableIgnition, CachedLocalizer.Instance.MechJeb_Ascent_checkbox14, s); //"Prevent unstable ignition" } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool autoRCSUllaging = true; [GeneralInfoItem("#MechJeb_UseRCStoullage", InfoItem.Category.Thrust)] //Use RCS to ullage @@ -104,17 +104,17 @@ public void AutoRCsUllageInfoItem() } // 5% safety margin on flameouts - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble flameoutSafetyPct = 5; [ToggleInfoItem("#MechJeb_ManageAirIntakes", InfoItem.Category.Thrust)] //Manage air intakes - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool manageIntakes = false; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool limitAcceleration; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableDouble maxAcceleration = 40; [GeneralInfoItem("#MechJeb_LimitAcceleration", InfoItem.Category.Thrust)] //Limit Acceleration @@ -125,10 +125,10 @@ public void LimitAccelerationInfoItem() 30); //"Limit acceleration to" } - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool limitThrottle; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDoubleMult maxThrottle = new EditableDoubleMult(1, 0.01); [GeneralInfoItem("#MechJeb_LimitThrottle", InfoItem.Category.Thrust)] //Limit throttle @@ -139,10 +139,10 @@ public void LimitThrottleInfoItem() 30); //"Limit throttle to" } - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public bool limiterMinThrottle = true; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] public EditableDoubleMult minThrottle = new EditableDoubleMult(0.05, 0.01); [GeneralInfoItem("#MechJeb_LowerThrottleLimit", InfoItem.Category.Thrust)] //Lower throttle limit @@ -153,34 +153,34 @@ public void LimiterMinThrottleInfoItem() 30); //"Keep limited throttle over" } - [Persistent(pass = (int)Pass.Type)] + [Persistent(pass = (int)Pass.TYPE)] public bool differentialThrottle; [GeneralInfoItem("#MechJeb_DifferentialThrottle", InfoItem.Category.Thrust)] //Differential throttle public void DifferentialThrottle() { - bool oldDifferentialThrottle = core.Thrust.differentialThrottle; - GUIStyle s = differentialThrottle && vessel.LiftedOff() - ? core.Thrust.differentialThrottleSuccess == DifferentialThrottleStatus.Success ? GuiUtils.greenToggle : GuiUtils.yellowToggle + bool oldDifferentialThrottle = Core.Thrust.differentialThrottle; + GUIStyle s = differentialThrottle && Vessel.LiftedOff() + ? Core.Thrust.differentialThrottleSuccess == DifferentialThrottleStatus.Success ? GuiUtils.greenToggle : GuiUtils.yellowToggle : GuiUtils.skin.toggle; differentialThrottle = GUILayout.Toggle(differentialThrottle, CachedLocalizer.Instance.MechJeb_Ascent_checkbox19, s); //"Differential throttle" - if (oldDifferentialThrottle && !core.Thrust.differentialThrottle) - core.Thrust.DisableDifferentialThrottle(); + if (oldDifferentialThrottle && !Core.Thrust.differentialThrottle) + Core.Thrust.DisableDifferentialThrottle(); } public Vector3d differentialThrottleDemandedTorque; public DifferentialThrottleStatus differentialThrottleSuccess = DifferentialThrottleStatus.Success; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool electricThrottle; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDoubleMult electricThrottleLo = new EditableDoubleMult(0.05, 0.01); - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDoubleMult electricThrottleHi = new EditableDoubleMult(0.15, 0.01); [GeneralInfoItem("#MechJeb_ElectricLimit", InfoItem.Category.Thrust)] //Electric limit @@ -190,7 +190,7 @@ public void LimitElectricInfoItem() GUIStyle s = GuiUtils.skin.label; if (limiter == LimitMode.Electric) { - if (vesselState.throttleLimit < 0.001) + if (VesselState.throttleLimit < 0.001) s = GuiUtils.redLabel; else s = GuiUtils.yellowLabel; @@ -263,25 +263,25 @@ public override void OnStart(PartModule.StartState state) new ScreenMessage(Localizer.Format("#MechJeb_Ascent_srcmsg1"), 2f, ScreenMessageStyle.UPPER_CENTER); //"[MechJeb]: Killing throttle to prevent unstable ignition" pid = new PIDController(0.05, 0.000001, 0.05); - users.Add(this); + Users.Add(this); base.OnStart(state); } public void ThrustOff() { - if (vessel == null || vessel.ctrlState == null) + if (Vessel == null || Vessel.ctrlState == null) return; targetThrottle = 0; - vessel.ctrlState.mainThrottle = 0; + Vessel.ctrlState.mainThrottle = 0; tmode = TMode.OFF; SetFlightGlobals(0); } private void SetFlightGlobals(double throttle) { - if (FlightGlobals.ActiveVessel != null && vessel == FlightGlobals.ActiveVessel) + if (FlightGlobals.ActiveVessel != null && Vessel == FlightGlobals.ActiveVessel) { FlightInputHandler.state.mainThrottle = (float)throttle; //so that the on-screen throttle gauge reflects the autopilot throttle } @@ -292,11 +292,11 @@ private void SetFlightGlobals(double throttle) // This function is nice because it will correctly handle engine spool-up/down times. public void ThrustForDV(double dV, double timeConstant) { - timeConstant += vesselState.maxEngineResponseTime; - double spooldownDV = vesselState.currentThrustAccel * vesselState.maxEngineResponseTime; + timeConstant += VesselState.maxEngineResponseTime; + double spooldownDV = VesselState.currentThrustAccel * VesselState.maxEngineResponseTime; double desiredAcceleration = (dV - spooldownDV) / timeConstant; - targetThrottle = Mathf.Clamp01((float)(desiredAcceleration / vesselState.maxThrustAccel)); + targetThrottle = Mathf.Clamp01((float)(desiredAcceleration / VesselState.maxThrustAccel)); } /* the current throttle limit, this may include transient condition such as limiting to zero due to unstable propellants in RF */ @@ -348,29 +348,29 @@ public override void Drive(FlightCtrlState s) userCommandingRotationSmoothed--; } - if (core.GetComputerModule().hidden && core.GetComputerModule().hidden) { return; } + if (Core.GetComputerModule().hidden && Core.GetComputerModule().hidden) { return; } - if (tmode != TMode.OFF && vesselState.thrustAvailable > 0) + if (tmode != TMode.OFF && VesselState.thrustAvailable > 0) { double spd = 0; switch (tmode) { case TMode.KEEP_ORBITAL: - spd = vesselState.speedOrbital; + spd = VesselState.speedOrbital; break; case TMode.KEEP_SURFACE: - spd = vesselState.speedSurface; + spd = VesselState.speedSurface; break; case TMode.KEEP_VERTICAL: - spd = vesselState.speedVertical; + spd = VesselState.speedVertical; Vector3d rot = Vector3d.up; if (trans_kill_h) { - var hsdir = Vector3.ProjectOnPlane(vesselState.surfaceVelocity, vesselState.up); - Vector3 dir = -hsdir + vesselState.up * Math.Max(Math.Abs(spd), 20 * mainBody.GeeASL); - if (Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) > 5000 && - hsdir.magnitude > Math.Max(Math.Abs(spd), 100 * mainBody.GeeASL) * 2) + var hsdir = Vector3.ProjectOnPlane(VesselState.surfaceVelocity, VesselState.up); + Vector3 dir = -hsdir + VesselState.up * Math.Max(Math.Abs(spd), 20 * MainBody.GeeASL); + if (Math.Min(VesselState.altitudeASL, VesselState.altitudeTrue) > 5000 && + hsdir.magnitude > Math.Max(Math.Abs(spd), 100 * MainBody.GeeASL) * 2) { tmode = TMode.DIRECT; trans_spd_act = 100; @@ -381,15 +381,15 @@ public override void Drive(FlightCtrlState s) rot = dir.normalized; } - core.Attitude.attitudeTo(rot, AttitudeReference.INERTIAL, null); + Core.Attitude.attitudeTo(rot, AttitudeReference.INERTIAL, null); } break; } - double t_err = (trans_spd_act - spd) / vesselState.maxThrustAccel; - if ((tmode == TMode.KEEP_ORBITAL && Vector3d.Dot(vesselState.forward, vesselState.orbitalVelocity) < 0) || - (tmode == TMode.KEEP_SURFACE && Vector3d.Dot(vesselState.forward, vesselState.surfaceVelocity) < 0)) + double t_err = (trans_spd_act - spd) / VesselState.maxThrustAccel; + if ((tmode == TMode.KEEP_ORBITAL && Vector3d.Dot(VesselState.forward, VesselState.orbitalVelocity) < 0) || + (tmode == TMode.KEEP_SURFACE && Vector3d.Dot(VesselState.forward, VesselState.surfaceVelocity) < 0)) { //allow thrust to declerate t_err *= -1; @@ -399,8 +399,8 @@ public override void Drive(FlightCtrlState s) if (tmode != TMode.KEEP_VERTICAL || !trans_kill_h - || core.Attitude.attitudeError < 2 - || (Math.Min(vesselState.altitudeASL, vesselState.altitudeTrue) < 1000 && core.Attitude.attitudeError < 90)) + || Core.Attitude.attitudeError < 2 + || (Math.Min(VesselState.altitudeASL, VesselState.altitudeTrue) < 1000 && Core.Attitude.attitudeError < 90)) { if (tmode == TMode.DIRECT) { @@ -413,16 +413,16 @@ public override void Drive(FlightCtrlState s) } else { - bool useGimbal = vesselState.torqueGimbal.positive.x > vesselState.torqueAvailable.x * 10 || - vesselState.torqueGimbal.positive.z > vesselState.torqueAvailable.z * 10; + bool useGimbal = VesselState.torqueGimbal.positive.x > VesselState.torqueAvailable.x * 10 || + VesselState.torqueGimbal.positive.z > VesselState.torqueAvailable.z * 10; - bool useDiffThrottle = vesselState.torqueDiffThrottle.x > vesselState.torqueAvailable.x * 10 || - vesselState.torqueDiffThrottle.z > vesselState.torqueAvailable.z * 10; + bool useDiffThrottle = VesselState.torqueDiffThrottle.x > VesselState.torqueAvailable.x * 10 || + VesselState.torqueDiffThrottle.z > VesselState.torqueAvailable.z * 10; - if (core.Attitude.attitudeError >= 2 && (useGimbal || (useDiffThrottle && core.Thrust.differentialThrottle))) + if (Core.Attitude.attitudeError >= 2 && (useGimbal || (useDiffThrottle && Core.Thrust.differentialThrottle))) { trans_prev_thrust = targetThrottle = 0.1F; - print(" targetThrottle = 0.1F"); + Print(" targetThrottle = 0.1F"); } else { @@ -433,7 +433,7 @@ public override void Drive(FlightCtrlState s) // Only set throttle if a module need it. Otherwise let the user or other mods set it // There is always at least 1 user : the module itself (why ?) - if (users.Count > 1) + if (Users.Count > 1) s.mainThrottle = targetThrottle; throttleLimit = 1; @@ -526,10 +526,10 @@ public override void Drive(FlightCtrlState s) /* prevent unstable ignitions */ if (limitToPreventUnstableIgnition && s.mainThrottle > 0.0F && throttleLimit > 0.0F) { - if (vesselState.lowestUllage < VesselState.UllageState.Stable) + if (VesselState.lowestUllage < VesselState.UllageState.Stable) { ScreenMessages.PostScreenMessage(preventingUnstableIgnitionsMessage); - Debug.Log("MechJeb Unstable Ignitions: preventing ignition in state: " + vesselState.lowestUllage); + Debug.Log("MechJeb Unstable Ignitions: preventing ignition in state: " + VesselState.lowestUllage); setTempLimit(0.0F, LimitMode.UnstableIgnition); } } @@ -537,7 +537,7 @@ public override void Drive(FlightCtrlState s) // we have to force the throttle here so that rssMode can work, otherwise we don't get our last throttle command // back on the next tick after disabling. we save this before applying the throttle limits so that we preserve // the requested throttle, and not the limited throttle. - if (core.RssMode) + if (Core.RssMode) { SetFlightGlobals(s.mainThrottle); } @@ -550,8 +550,8 @@ public override void Drive(FlightCtrlState s) if (double.IsNaN(throttleFixedLimit)) throttleFixedLimit = 1.0F; throttleFixedLimit = Mathf.Clamp01(throttleFixedLimit); - vesselState.throttleLimit = throttleLimit; - vesselState.throttleFixedLimit = throttleFixedLimit; + VesselState.throttleLimit = throttleLimit; + VesselState.throttleFixedLimit = throttleFixedLimit; if (s.mainThrottle < throttleLimit) limiter = LimitMode.None; @@ -567,14 +567,14 @@ public override void Drive(FlightCtrlState s) s.mainThrottle = Mathf.Clamp01(s.mainThrottle); - if (s.Z == 0 && core.RCS.rcsThrottle && vesselState.rcsThrust) s.Z = -s.mainThrottle; + if (s.Z == 0 && Core.RCS.rcsThrottle && VesselState.rcsThrust) s.Z = -s.mainThrottle; LastThrottle = s.mainThrottle; - if (!core.Attitude.enabled) + if (!Core.Attitude.Enabled) { var act = new Vector3d(s.pitch, s.yaw, s.roll); - differentialThrottleDemandedTorque = -Vector3d.Scale(act.xzy, vesselState.torqueDiffThrottle * s.mainThrottle * 0.5f); + differentialThrottleDemandedTorque = -Vector3d.Scale(act.xzy, VesselState.torqueDiffThrottle * s.mainThrottle * 0.5f); } } @@ -593,9 +593,9 @@ public override void OnFixedUpdate() //A throttle setting that throttles down when the vertical velocity of the ship exceeds terminal velocity private float TerminalVelocityThrottle() { - if (vesselState.altitudeASL > mainBody.RealMaxAtmosphereAltitude()) return 1.0F; + if (VesselState.altitudeASL > MainBody.RealMaxAtmosphereAltitude()) return 1.0F; - double velocityRatio = Vector3d.Dot(vesselState.surfaceVelocity, vesselState.up) / vesselState.TerminalVelocity(); + double velocityRatio = Vector3d.Dot(VesselState.surfaceVelocity, VesselState.up) / VesselState.TerminalVelocity(); if (velocityRatio < 1.0) return 1.0F; //full throttle if under terminal velocity @@ -609,7 +609,7 @@ private float MaximumDynamicPressureThrottle() { if (maxDynamicPressure <= 0) return 1.0F; - double pressureRatio = vesselState.dynamicPressure / maxDynamicPressure; + double pressureRatio = VesselState.dynamicPressure / maxDynamicPressure; if (pressureRatio < 1.0) return 1.0F; //full throttle if under maximum dynamic pressure @@ -621,7 +621,7 @@ private float MaximumDynamicPressureThrottle() //a throttle setting that throttles down if something is close to overheating private double TemperatureSafetyThrottle() { - double maxTempRatio = vessel.parts.Max(p => p.temperature / p.maxTemp); + double maxTempRatio = Vessel.parts.Max(p => p.temperature / p.maxTemp); //reduce throttle as the max temp. ratio approaches 1 within the safety margin const double tempSafetyMargin = 0.05f; @@ -632,8 +632,8 @@ private double TemperatureSafetyThrottle() private float SmoothThrottle(float mainThrottle) { return Mathf.Clamp(mainThrottle, - (float)(LastThrottle - vesselState.deltaT / throttleSmoothingTime), - (float)(LastThrottle + vesselState.deltaT / throttleSmoothingTime)); + (float)(LastThrottle - VesselState.deltaT / throttleSmoothingTime), + (float)(LastThrottle + VesselState.deltaT / throttleSmoothingTime)); } private float FlameoutSafetyThrottle() @@ -644,7 +644,7 @@ private float FlameoutSafetyThrottle() // much we need at full throttle, add a safety margin, and // that's the max throttle for that resource. Take the min of // the max throttles. - foreach (VesselState.ResourceInfo resource in vesselState.resources.Values) + foreach (VesselState.ResourceInfo resource in VesselState.resources.Values) { if (resource.intakes.Count == 0) { @@ -788,7 +788,7 @@ private void OptimizeIntakes(VesselState.ResourceInfo info, double requiredFlow) private bool ElectricEngineRunning() { - IEnumerable activeEngines = vessel.parts.Where(p => p.inverseStage >= vessel.currentStage && p.IsEngine() && !p.IsSepratron()); + IEnumerable activeEngines = Vessel.parts.Where(p => p.inverseStage >= Vessel.currentStage && p.IsEngine() && !p.IsSepratron()); IEnumerable engineModules = activeEngines.Select(p => p.Modules.OfType().First(e => e.isEnabled)); return engineModules.SelectMany(eng => eng.propellants).Any(p => p.id == PartResourceLibrary.ElectricityHashcode); @@ -796,10 +796,10 @@ private bool ElectricEngineRunning() private float ElectricThrottle() { - double totalElectric = vessel.MaxResourceAmount(PartResourceLibrary.ElectricityHashcode); + double totalElectric = Vessel.MaxResourceAmount(PartResourceLibrary.ElectricityHashcode); double lowJuice = totalElectric * electricThrottleLo; double highJuice = totalElectric * electricThrottleHi; - double curElectric = vessel.TotalResourceAmount(PartResourceLibrary.ElectricityHashcode); + double curElectric = Vessel.TotalResourceAmount(PartResourceLibrary.ElectricityHashcode); if (curElectric <= lowJuice) return 0; @@ -814,13 +814,13 @@ private float ElectricThrottle() //The throttle setting that will give an acceleration of maxAcceleration private float AccelerationLimitedThrottle() { - double throttleForMaxAccel = (maxAcceleration - vesselState.minThrustAccel) / (vesselState.maxThrustAccel - vesselState.minThrustAccel); + double throttleForMaxAccel = (maxAcceleration - VesselState.minThrustAccel) / (VesselState.maxThrustAccel - VesselState.minThrustAccel); return Mathf.Clamp((float)throttleForMaxAccel, 0, 1); } public override void OnUpdate() { - if (core.GetComputerModule().hidden && core.GetComputerModule().hidden) + if (Core.GetComputerModule().hidden && Core.GetComputerModule().hidden) { return; } @@ -829,7 +829,7 @@ public override void OnUpdate() { if (trans_kill_h && tmode == TMode.OFF) { - core.Attitude.attitudeDeactivate(); + Core.Attitude.attitudeDeactivate(); } pid.Reset(); @@ -837,11 +837,11 @@ public override void OnUpdate() FlightInputHandler.SetNeutralControls(); } - bool disableThrusters = userCommandingRotation && !core.RCS.rcsForRotation; + bool disableThrusters = userCommandingRotation && !Core.RCS.rcsForRotation; if (disableThrusters != lastDisableThrusters) { lastDisableThrusters = disableThrusters; - List rcsModules = vessel.FindPartModulesImplementing(); + List rcsModules = Vessel.FindPartModulesImplementing(); foreach (ModuleRCS pm in rcsModules) { if (disableThrusters) @@ -884,29 +884,29 @@ private void ProcessUllage(FlightCtrlState s) if (!autoRCSUllaging || s.mainThrottle <= 0F || throttleLimit <= 0F) return; - bool isStable = vesselState.lowestUllage == VesselState.UllageState.VeryStable; + bool isStable = VesselState.lowestUllage == VesselState.UllageState.VeryStable; if (!isStable) { - ullageUntil = vesselState.time + 0.15; + ullageUntil = VesselState.time + 0.15; } - if (vesselState.time >= ullageUntil) + if (VesselState.time >= ullageUntil) return; // Continue ullaging until at least one engine has spooled up enough to produce >1% of it's rated thrust - if (isStable && vesselState.enginesWrappers.Where(e => e.engine.requestedThrottle > 0.01) + if (isStable && VesselState.enginesWrappers.Where(e => e.engine.requestedThrottle > 0.01) .All(e => e.engine.currentThrottle < 0.01)) { - ullageUntil = vesselState.time + 0.15; + ullageUntil = VesselState.time + 0.15; } - Debug.Log("MechJeb RCS auto-ullaging: found state below very stable: " + vesselState.lowestUllage); - if (vessel.hasEnabledRCSModules()) + Debug.Log("MechJeb RCS auto-ullaging: found state below very stable: " + VesselState.lowestUllage); + if (Vessel.hasEnabledRCSModules()) { - if (!vessel.ActionGroups[KSPActionGroup.RCS]) + if (!Vessel.ActionGroups[KSPActionGroup.RCS]) { Debug.Log("MechJeb RCS auto-ullaging: enabling RCS action group for automatic ullaging"); - vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); + Vessel.ActionGroups.SetGroup(KSPActionGroup.RCS, true); } Debug.Log("MechJeb RCS auto-ullaging: firing RCS to stabilize ulllage"); @@ -928,7 +928,7 @@ private DifferentialThrottleStatus ComputeDifferentialThrottle(Vector3d torque) //var stopwatch = new Stopwatch(); //stopwatch.Start(); - float mainThrottle = vessel.ctrlState.mainThrottle; + float mainThrottle = Vessel.ctrlState.mainThrottle; if (mainThrottle == 0) { @@ -936,7 +936,7 @@ private DifferentialThrottleStatus ComputeDifferentialThrottle(Vector3d torque) mainThrottle = 1; } - int nb_engines = vesselState.enginesWrappers.Count; + int nb_engines = VesselState.enginesWrappers.Count; double torqueScale = 0; double forceScale = 0; @@ -944,14 +944,14 @@ private DifferentialThrottleStatus ComputeDifferentialThrottle(Vector3d torque) for (int i = 0; i < nb_engines; i++) { - torque -= vesselState.enginesWrappers[i].constantTorque; - torqueScale += vesselState.enginesWrappers[i].maxVariableTorque.magnitude; + torque -= VesselState.enginesWrappers[i].constantTorque; + torqueScale += VesselState.enginesWrappers[i].maxVariableTorque.magnitude; - force += Vector3d.Dot(mainThrottle * vesselState.enginesWrappers[i].maxVariableForce, Vector3d.up) * Vector3d.up; - forceScale += vesselState.enginesWrappers[i].maxVariableForce.magnitude * 10; + force += Vector3d.Dot(mainThrottle * VesselState.enginesWrappers[i].maxVariableForce, Vector3d.up) * Vector3d.up; + forceScale += VesselState.enginesWrappers[i].maxVariableForce.magnitude * 10; } - var engines = vesselState.enginesWrappers.Where(eng => !eng.engine.throttleLocked).ToList(); + var engines = VesselState.enginesWrappers.Where(eng => !eng.engine.throttleLocked).ToList(); int n = engines.Count; if (nb_engines == 0) @@ -1009,9 +1009,9 @@ private DifferentialThrottleStatus ComputeDifferentialThrottle(Vector3d torque) public void DisableDifferentialThrottle() { - for (int i = 0; i < vessel.parts.Count; i++) + for (int i = 0; i < Vessel.parts.Count; i++) { - Part p = vessel.parts[i]; + Part p = Vessel.parts[i]; for (int j = 0; j < p.Modules.Count; j++) { PartModule pm = p.Modules[j]; diff --git a/MechJeb2/MechJebModuleThrustWindow.cs b/MechJeb2/MechJebModuleThrustWindow.cs index a5b0e405c..66cc919f5 100644 --- a/MechJeb2/MechJebModuleThrustWindow.cs +++ b/MechJeb2/MechJebModuleThrustWindow.cs @@ -7,7 +7,7 @@ namespace MuMech [UsedImplicitly] public class MechJebModuleThrustWindow : DisplayModule { - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public bool autostageSavedState; public MechJebModuleThrustWindow(MechJebCore core) : base(core) { } @@ -16,36 +16,36 @@ public override void OnLoad(ConfigNode local, ConfigNode type, ConfigNode global { base.OnLoad(local, type, global); - if (autostageSavedState && !core.Staging.users.Contains(this)) + if (autostageSavedState && !Core.Staging.Users.Contains(this)) { - core.Staging.users.Add(this); + Core.Staging.Users.Add(this); } } [GeneralInfoItem("#MechJeb_AutostageOnce", InfoItem.Category.Misc)] //Autostage Once public void AutostageOnceItem() { - if (core.Staging.enabled) + if (Core.Staging.Enabled) { GUILayout.Label(Localizer.Format("#MechJeb_Utilities_label1", - core.Staging.autostagingOnce + Core.Staging.autostagingOnce ? Localizer.Format("#MechJeb_Utilities_label1_1") : " ")); //"Autostaging"<<1>>"Active" -------<<1>>" once ":"" } - if (!core.Staging.enabled && GUILayout.Button(Localizer.Format("#MechJeb_Utilities_button1"))) //"Autostage once" + if (!Core.Staging.Enabled && GUILayout.Button(Localizer.Format("#MechJeb_Utilities_button1"))) //"Autostage once" { - core.Staging.AutostageOnce(this); + Core.Staging.AutostageOnce(this); } } [GeneralInfoItem("#MechJeb_Autostage", InfoItem.Category.Misc)] //Autostage public void Autostage() { - bool oldAutostage = core.Staging.users.Contains(this); + bool oldAutostage = Core.Staging.Users.Contains(this); bool newAutostage = GUILayout.Toggle(oldAutostage, Localizer.Format("#MechJeb_Utilities_checkbox1")); //"Autostage" - if (newAutostage && !oldAutostage) core.Staging.users.Add(this); - if (!newAutostage && oldAutostage) core.Staging.users.Remove(this); + if (newAutostage && !oldAutostage) Core.Staging.Users.Add(this); + if (!newAutostage && oldAutostage) Core.Staging.Users.Remove(this); autostageSavedState = newAutostage; } @@ -55,29 +55,29 @@ protected override void WindowGUI(int windowID) GUILayout.BeginVertical(); //core.thrust.LimitToTerminalVelocityInfoItem(); - core.Thrust.LimitToMaxDynamicPressureInfoItem(); - core.Thrust.LimitToPreventOverheatsInfoItem(); - core.Thrust.LimitAccelerationInfoItem(); - core.Thrust.LimitThrottleInfoItem(); - core.Thrust.LimiterMinThrottleInfoItem(); - core.Thrust.LimitElectricInfoItem(); - core.Thrust.LimitToPreventFlameoutInfoItem(); + Core.Thrust.LimitToMaxDynamicPressureInfoItem(); + Core.Thrust.LimitToPreventOverheatsInfoItem(); + Core.Thrust.LimitAccelerationInfoItem(); + Core.Thrust.LimitThrottleInfoItem(); + Core.Thrust.LimiterMinThrottleInfoItem(); + Core.Thrust.LimitElectricInfoItem(); + Core.Thrust.LimitToPreventFlameoutInfoItem(); if (VesselState.isLoadedRealFuels) { // does nothing in stock, so we suppress displaying it if RF is not loaded - core.Thrust.LimitToPreventUnstableIgnitionInfoItem(); - core.Thrust.AutoRCsUllageInfoItem(); + Core.Thrust.LimitToPreventUnstableIgnitionInfoItem(); + Core.Thrust.AutoRCsUllageInfoItem(); } - core.Thrust.smoothThrottle = - GUILayout.Toggle(core.Thrust.smoothThrottle, Localizer.Format("#MechJeb_Utilities_checkbox2")); //"Smooth throttle" - core.Thrust.manageIntakes = - GUILayout.Toggle(core.Thrust.manageIntakes, Localizer.Format("#MechJeb_Utilities_checkbox3")); //"Manage air intakes" + Core.Thrust.smoothThrottle = + GUILayout.Toggle(Core.Thrust.smoothThrottle, Localizer.Format("#MechJeb_Utilities_checkbox2")); //"Smooth throttle" + Core.Thrust.manageIntakes = + GUILayout.Toggle(Core.Thrust.manageIntakes, Localizer.Format("#MechJeb_Utilities_checkbox3")); //"Manage air intakes" GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); try { GUILayout.Label(Localizer.Format("#MechJeb_Utilities_label2")); //"Jet safety margin" - core.Thrust.flameoutSafetyPct.text = GUILayout.TextField(core.Thrust.flameoutSafetyPct.text, 5); + Core.Thrust.flameoutSafetyPct.text = GUILayout.TextField(Core.Thrust.flameoutSafetyPct.text, 5); GUILayout.Label("%"); } finally @@ -85,11 +85,11 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); } - core.Thrust.DifferentialThrottle(); + Core.Thrust.DifferentialThrottle(); - if (core.Thrust.differentialThrottle && vessel.LiftedOff()) + if (Core.Thrust.differentialThrottle && Vessel.LiftedOff()) { - switch (core.Thrust.differentialThrottleSuccess) + switch (Core.Thrust.differentialThrottleSuccess) { case MechJebModuleThrustController.DifferentialThrottleStatus.MoreEnginesRequired: GUILayout.Label(Localizer.Format("#MechJeb_Utilities_label3"), @@ -108,17 +108,17 @@ protected override void WindowGUI(int windowID) } } - core.Solarpanel.SolarPanelDeployButton(); - core.AntennaControl.AntennaDeployButton(); + Core.Solarpanel.SolarPanelDeployButton(); + Core.AntennaControl.AntennaDeployButton(); Autostage(); - if (!core.Staging.enabled && GUILayout.Button(Localizer.Format("#MechJeb_Utilities_button1"))) - core.Staging.AutostageOnce(this); //"Autostage once" + if (!Core.Staging.Enabled && GUILayout.Button(Localizer.Format("#MechJeb_Utilities_button1"))) + Core.Staging.AutostageOnce(this); //"Autostage once" - if (core.Staging.enabled) core.Staging.AutostageSettingsInfoItem(); + if (Core.Staging.Enabled) Core.Staging.AutostageSettingsInfoItem(); - if (core.Staging.enabled) GUILayout.Label(core.Staging.AutostageStatus()); + if (Core.Staging.Enabled) GUILayout.Label(Core.Staging.AutostageStatus()); GUILayout.EndVertical(); @@ -132,7 +132,7 @@ public override GUILayoutOption[] WindowOptions() public override bool isActive() { - return core.Thrust.limiter != MechJebModuleThrustController.LimitMode.None; + return Core.Thrust.limiter != MechJebModuleThrustController.LimitMode.None; } public override string GetName() diff --git a/MechJeb2/MechJebModuleTranslatron.cs b/MechJeb2/MechJebModuleTranslatron.cs index ebb34288d..238ea0dfa 100644 --- a/MechJeb2/MechJebModuleTranslatron.cs +++ b/MechJeb2/MechJebModuleTranslatron.cs @@ -33,7 +33,7 @@ public enum AbortStage protected bool autoMode; - [Persistent(pass = (int)Pass.Local)] + [Persistent(pass = (int)Pass.LOCAL)] public EditableDouble trans_spd = new EditableDouble(0); private static GUIStyle buttonStyle; @@ -69,7 +69,7 @@ protected override void WindowGUI(int windowID) GUILayout.BeginVertical(); - if (core.Thrust.users.Count > 1 && !core.Thrust.users.Contains(this)) + if (Core.Thrust.Users.Count > 1 && !Core.Thrust.Users.Contains(this)) { if (!autoMode) { @@ -90,7 +90,7 @@ protected override void WindowGUI(int windowID) autoMode = false; } - var newMode = (MechJebModuleThrustController.TMode)GUILayout.SelectionGrid((int)core.Thrust.tmode, trans_texts, 2, buttonStyle); + var newMode = (MechJebModuleThrustController.TMode)GUILayout.SelectionGrid((int)Core.Thrust.tmode, trans_texts, 2, buttonStyle); SetMode(newMode); float @@ -98,7 +98,7 @@ protected override void WindowGUI(int windowID) ? 5 : 1; // change by 5 if the mod_key is held down, else by 1 -- would be better if it actually worked... - core.Thrust.trans_kill_h = GUILayout.Toggle(core.Thrust.trans_kill_h, Localizer.Format("#MechJeb_Trans_kill_h"), + Core.Thrust.trans_kill_h = GUILayout.Toggle(Core.Thrust.trans_kill_h, Localizer.Format("#MechJeb_Trans_kill_h"), GUILayout.ExpandWidth(true)); GUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_Trans_spd"), trans_spd, "", 37); @@ -125,14 +125,14 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_Trans_spd_act") + ":", buttonStyle, GUILayout.ExpandWidth(true)) || change) { - core.Thrust.trans_spd_act = (float)trans_spd.val; + Core.Thrust.trans_spd_act = (float)trans_spd.val; GUIUtility.keyboardControl = 0; } } - if (core.Thrust.tmode != MechJebModuleThrustController.TMode.OFF) + if (Core.Thrust.tmode != MechJebModuleThrustController.TMode.OFF) { - GUILayout.Label(Localizer.Format("#MechJeb_Trans_current_spd") + core.Thrust.trans_spd_act.ToSI() + "m/s", + GUILayout.Label(Localizer.Format("#MechJeb_Trans_current_spd") + Core.Thrust.trans_spd_act.ToSI() + "m/s", GUILayout.ExpandWidth(true)); } @@ -157,19 +157,19 @@ protected override void WindowGUI(int windowID) public void SetMode(MechJebModuleThrustController.TMode newMode) { - MechJebModuleThrustController.TMode oldMode = core.Thrust.tmode; - core.Thrust.tmode = newMode; - if (core.Thrust.tmode != oldMode) + MechJebModuleThrustController.TMode oldMode = Core.Thrust.tmode; + Core.Thrust.tmode = newMode; + if (Core.Thrust.tmode != oldMode) { - core.Thrust.trans_spd_act = Convert.ToInt16(trans_spd); + Core.Thrust.trans_spd_act = Convert.ToInt16(trans_spd); windowPos = new Rect(windowPos.x, windowPos.y, 10, 10); - if (core.Thrust.tmode == MechJebModuleThrustController.TMode.OFF) + if (Core.Thrust.tmode == MechJebModuleThrustController.TMode.OFF) { - core.Thrust.users.Remove(this); + Core.Thrust.Users.Remove(this); } else { - core.Thrust.users.Add(this); + Core.Thrust.Users.Add(this); } } } @@ -180,13 +180,13 @@ public void PanicSwitch() { if (abort == AbortStage.LAND || abort == AbortStage.LANDING) { - core.GetComputerModule().StopLanding(); + Core.GetComputerModule().StopLanding(); } else { - core.Thrust.ThrustOff(); - core.Thrust.users.Remove(this); - core.Attitude.attitudeDeactivate(); + Core.Thrust.ThrustOff(); + Core.Thrust.Users.Remove(this); + Core.Attitude.attitudeDeactivate(); } abort = AbortStage.OFF; @@ -194,16 +194,16 @@ public void PanicSwitch() else { abort = AbortStage.THRUSTOFF; - core.Thrust.users.Add(this); + Core.Thrust.Users.Add(this); } } public void recursiveDecouple() { int minStage = StageManager.LastStage; - for (int i = 0; i < part.vessel.parts.Count; i++) + for (int i = 0; i < Part.vessel.parts.Count; i++) { - Part child = part.vessel.parts[i]; + Part child = Part.vessel.parts[i]; // TODO Sarbian : Cleanup - not sure if any mod still use those and they are not supported in other part of the code if (child.HasModule()) { @@ -215,9 +215,9 @@ public void recursiveDecouple() } var decouplers = new List(); - for (int i = 0; i < part.vessel.parts.Count; i++) + for (int i = 0; i < Part.vessel.parts.Count; i++) { - Part child = part.vessel.parts[i]; + Part child = Part.vessel.parts[i]; if (child.inverseStage > minStage && (child.HasModule() || child.HasModule())) { @@ -230,7 +230,7 @@ public void recursiveDecouple() decouplers[i].force_activate(); } - if (part.vessel == FlightGlobals.ActiveVessel) + if (Part.vessel == FlightGlobals.ActiveVessel) { StageManager.ActivateStage(minStage); } @@ -240,14 +240,14 @@ public override void Drive(FlightCtrlState s) { // Fix the Translatron behavior which kill HS. // TODO : proper fix that register the attitude controler outside of Drive - if (!core.Attitude.users.Contains(this) && core.Thrust.trans_kill_h && core.Thrust.tmode != MechJebModuleThrustController.TMode.OFF) + if (!Core.Attitude.Users.Contains(this) && Core.Thrust.trans_kill_h && Core.Thrust.tmode != MechJebModuleThrustController.TMode.OFF) { - core.Attitude.users.Add(this); + Core.Attitude.Users.Add(this); } - if (core.Attitude.users.Contains(this) && (!core.Thrust.trans_kill_h || core.Thrust.tmode == MechJebModuleThrustController.TMode.OFF)) + if (Core.Attitude.Users.Contains(this) && (!Core.Thrust.trans_kill_h || Core.Thrust.tmode == MechJebModuleThrustController.TMode.OFF)) { - core.Attitude.users.Remove(this); + Core.Attitude.Users.Remove(this); } if (abort != AbortStage.OFF) @@ -265,12 +265,12 @@ public override void Drive(FlightCtrlState s) burnUpTime = Planetarium.GetUniversalTime(); break; case AbortStage.BURNUP: - if (Planetarium.GetUniversalTime() - burnUpTime < 2 || vesselState.speedVertical < 10) + if (Planetarium.GetUniversalTime() - burnUpTime < 2 || VesselState.speedVertical < 10) { - core.Thrust.tmode = MechJebModuleThrustController.TMode.DIRECT; - core.Attitude.attitudeTo(Vector3d.up, AttitudeReference.SURFACE_NORTH, this); - double int_error = Math.Abs(Vector3d.Angle(vesselState.up, vesselState.forward)); - core.Thrust.trans_spd_act = int_error < 90 ? 100 : 0; + Core.Thrust.tmode = MechJebModuleThrustController.TMode.DIRECT; + Core.Attitude.attitudeTo(Vector3d.up, AttitudeReference.SURFACE_NORTH, this); + double int_error = Math.Abs(Vector3d.Angle(VesselState.up, VesselState.forward)); + Core.Thrust.trans_spd_act = int_error < 90 ? 100 : 0; } else { @@ -279,12 +279,12 @@ public override void Drive(FlightCtrlState s) break; case AbortStage.LAND: - core.Thrust.users.Remove(this); - core.GetComputerModule().LandUntargeted(this); + Core.Thrust.Users.Remove(this); + Core.GetComputerModule().LandUntargeted(this); abort = AbortStage.LANDING; break; case AbortStage.LANDING: - if (vessel.LandedOrSplashed) + if (Vessel.LandedOrSplashed) { abort = AbortStage.OFF; } diff --git a/MechJeb2/MechJebModuleWarpController.cs b/MechJeb2/MechJebModuleWarpController.cs index 6df69051e..ef33bde78 100644 --- a/MechJeb2/MechJebModuleWarpController.cs +++ b/MechJeb2/MechJebModuleWarpController.cs @@ -12,8 +12,8 @@ public MechJebModuleWarpController(MechJebCore core) : base(core) { WarpPaused = false; - priority = 100; - enabled = true; + Priority = 100; + Enabled = true; } private double warpIncreaseAttemptTime; @@ -23,10 +23,10 @@ public MechJebModuleWarpController(MechJebCore core) public double warpToUT { get; private set; } public bool WarpPaused { get; private set; } - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool activateSASOnWarp = true; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public bool useQuickWarp; public void useQuickWarpInfoItem() @@ -53,8 +53,8 @@ public override void OnUpdate() if (!WarpPaused && lastAskedIndex > 0 && lastAskedIndex != TimeWarp.CurrentRateIndex) { // Rate limited by the altitude so we should not care - if (!vessel.LandedOrSplashed && TimeWarp.WarpMode == TimeWarp.Modes.HIGH && - TimeWarp.CurrentRateIndex == TimeWarp.fetch.GetMaxRateForAltitude(vessel.altitude, vessel.mainBody)) + if (!Vessel.LandedOrSplashed && TimeWarp.WarpMode == TimeWarp.Modes.HIGH && + TimeWarp.CurrentRateIndex == TimeWarp.fetch.GetMaxRateForAltitude(Vessel.altitude, Vessel.mainBody)) return; //print("Warppause : lastAskedIndex=" + lastAskedIndex + " CurrentRateIndex=" + TimeWarp.CurrentRateIndex + " WarpMode=" + TimeWarp.WarpMode + " MaxCurrentRate=" + TimeWarp.fetch.GetMaxRateForAltitude(vessel.altitude, vessel.mainBody)); @@ -76,7 +76,7 @@ private void PauseWarp() WarpPaused = true; if (activateSASOnWarp && TimeWarp.CurrentRateIndex == 0) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); } private void ResumeWarp() @@ -94,7 +94,7 @@ private void SetTimeWarpRate(int rateIndex, bool instant) if (rateIndex != TimeWarp.CurrentRateIndex) { if (activateSASOnWarp && TimeWarp.WarpMode == TimeWarp.Modes.HIGH && TimeWarp.CurrentRateIndex == 0) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, true); lastAskedIndex = rateIndex; if (WarpPaused) @@ -108,13 +108,13 @@ private void SetTimeWarpRate(int rateIndex, bool instant) } if (activateSASOnWarp && rateIndex == 0) - part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); + Part.vessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false); } } public void WarpToUT(double UT, double maxRate = -1) { - if (UT <= vesselState.time) + if (UT <= VesselState.time) { warpToUT = 0.0; return; @@ -127,11 +127,11 @@ public void WarpToUT(double UT, double maxRate = -1) if (useQuickWarp) { desiredRate = 1; - if (orbit.patchEndTransition != Orbit.PatchTransitionType.FINAL && orbit.EndUT < UT) + if (Orbit.patchEndTransition != Orbit.PatchTransitionType.FINAL && Orbit.EndUT < UT) { for (int i = 0; i < TimeWarp.fetch.warpRates.Length; i++) { - if (i * Time.fixedDeltaTime * TimeWarp.fetch.warpRates[i] <= orbit.EndUT - vesselState.time) + if (i * Time.fixedDeltaTime * TimeWarp.fetch.warpRates[i] <= Orbit.EndUT - VesselState.time) desiredRate = TimeWarp.fetch.warpRates[i] + 0.1; else break; } @@ -140,18 +140,18 @@ public void WarpToUT(double UT, double maxRate = -1) { for (int i = 0; i < TimeWarp.fetch.warpRates.Length; i++) { - if (i * Time.fixedDeltaTime * TimeWarp.fetch.warpRates[i] <= UT - vesselState.time) + if (i * Time.fixedDeltaTime * TimeWarp.fetch.warpRates[i] <= UT - VesselState.time) desiredRate = TimeWarp.fetch.warpRates[i] + 0.1; else break; } } } - else desiredRate = 1.0 * (UT - (vesselState.time + Time.fixedDeltaTime * TimeWarp.CurrentRateIndex)); + else desiredRate = 1.0 * (UT - (VesselState.time + Time.fixedDeltaTime * TimeWarp.CurrentRateIndex)); desiredRate = MuUtils.Clamp(desiredRate, 1, maxRate); - if (!vessel.LandedOrSplashed && - vesselState.altitudeASL < TimeWarp.fetch.GetAltitudeLimit(1, mainBody)) + if (!Vessel.LandedOrSplashed && + VesselState.altitudeASL < TimeWarp.fetch.GetAltitudeLimit(1, MainBody)) { //too low to use any regular warp rates. Use physics warp at a max of x2: WarpPhysicsAtRate((float)Math.Min(desiredRate, 2)); @@ -202,8 +202,8 @@ private bool CheckRegularWarp() { if (TimeWarp.WarpMode != TimeWarp.Modes.HIGH) { - double instantAltitudeASL = (vesselState.CoM - mainBody.position).magnitude - mainBody.Radius; - if (instantAltitudeASL > mainBody.RealMaxAtmosphereAltitude()) + double instantAltitudeASL = (VesselState.CoM - MainBody.position).magnitude - MainBody.Radius; + if (instantAltitudeASL > MainBody.RealMaxAtmosphereAltitude()) { TimeWarp.fetch.Mode = TimeWarp.Modes.HIGH; SetTimeWarpRate(0, true); @@ -235,18 +235,18 @@ private bool IncreaseRegularWarp(bool instant = false) //do a bunch of checks to see if we can increase the warp rate: if (TimeWarp.CurrentRateIndex + 1 == TimeWarp.fetch.warpRates.Length) return false; //already at max warp - if (!vessel.LandedOrSplashed) + if (!Vessel.LandedOrSplashed) { - double instantAltitudeASL = (vesselState.CoM - mainBody.position).magnitude - mainBody.Radius; - if (TimeWarp.fetch.GetAltitudeLimit(TimeWarp.CurrentRateIndex + 1, mainBody) > instantAltitudeASL) return false; + double instantAltitudeASL = (VesselState.CoM - MainBody.position).magnitude - MainBody.Radius; + if (TimeWarp.fetch.GetAltitudeLimit(TimeWarp.CurrentRateIndex + 1, MainBody) > instantAltitudeASL) return false; //altitude too low to increase warp } if (TimeWarp.fetch.warpRates[TimeWarp.CurrentRateIndex] != TimeWarp.CurrentRate) return false; //most recent warp change is not yet complete - if (vesselState.time - warpIncreaseAttemptTime < 2) return false; //we increased warp too recently + if (VesselState.time - warpIncreaseAttemptTime < 2) return false; //we increased warp too recently - warpIncreaseAttemptTime = vesselState.time; + warpIncreaseAttemptTime = VesselState.time; SetTimeWarpRate(TimeWarp.CurrentRateIndex + 1, instant); return true; } @@ -259,9 +259,9 @@ private bool IncreasePhysicsWarp(bool instant = false) if (TimeWarp.CurrentRateIndex + 1 == TimeWarp.fetch.physicsWarpRates.Length) return false; //already at max warp if (TimeWarp.fetch.physicsWarpRates[TimeWarp.CurrentRateIndex] != TimeWarp.CurrentRate) return false; //most recent warp change is not yet complete - if (vesselState.time - warpIncreaseAttemptTime < 2) return false; //we increased warp too recently + if (VesselState.time - warpIncreaseAttemptTime < 2) return false; //we increased warp too recently - warpIncreaseAttemptTime = vesselState.time; + warpIncreaseAttemptTime = VesselState.time; SetTimeWarpRate(TimeWarp.CurrentRateIndex + 1, instant); return true; } diff --git a/MechJeb2/MechJebModuleWarpHelper.cs b/MechJeb2/MechJebModuleWarpHelper.cs index 2a9151acf..8c1df3044 100644 --- a/MechJeb2/MechJebModuleWarpHelper.cs +++ b/MechJeb2/MechJebModuleWarpHelper.cs @@ -19,10 +19,10 @@ public enum WarpTarget { Periapsis, Apoapsis, Node, SoI, Time, PhaseAngleT, Suic Localizer.Format("#MechJeb_WarpHelper_Combobox_text7"), Localizer.Format("#MechJeb_WarpHelper_Combobox_text8") }; //"periapsis""apoapsis""maneuver node""SoI transition""Time""Phase angle""suicide burn""atmospheric entry" - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public WarpTarget warpTarget = WarpTarget.Periapsis; - [Persistent(pass = (int)Pass.Global)] + [Persistent(pass = (int)Pass.GLOBAL)] public EditableTime leadTime = 0; public bool warping; @@ -30,7 +30,7 @@ public enum WarpTarget { Periapsis, Apoapsis, Node, SoI, Time, PhaseAngleT, Suic private double targetUT; - [Persistent(pass = (int)(Pass.Local | Pass.Type | Pass.Global))] + [Persistent(pass = (int)(Pass.LOCAL | Pass.TYPE | Pass.GLOBAL))] private readonly EditableDouble phaseAngle = 0; protected override void WindowGUI(int windowID) @@ -52,7 +52,7 @@ protected override void WindowGUI(int windowID) else if (warpTarget == WarpTarget.PhaseAngleT) { // I wonder if I should check for target that don't make sense - if (!core.Target.NormalTargetExists) + if (!Core.Target.NormalTargetExists) GUILayout.Label(Localizer.Format("#MechJeb_WarpHelper_label3")); //"You need a target" else GuiUtils.SimpleTextBox(Localizer.Format("#MechJeb_WarpHelper_label4"), phaseAngle, "º", 60); //"Phase Angle:" @@ -67,7 +67,7 @@ protected override void WindowGUI(int windowID) if (GUILayout.Button(Localizer.Format("#MechJeb_WarpHelper_button1"))) //"Abort" { warping = false; - core.Warp.MinimumWarp(true); + Core.Warp.MinimumWarp(true); } } else @@ -79,44 +79,44 @@ protected override void WindowGUI(int windowID) switch (warpTarget) { case WarpTarget.Periapsis: - targetUT = orbit.NextPeriapsisTime(vesselState.time); + targetUT = Orbit.NextPeriapsisTime(VesselState.time); break; case WarpTarget.Apoapsis: - if (orbit.eccentricity < 1) targetUT = orbit.NextApoapsisTime(vesselState.time); + if (Orbit.eccentricity < 1) targetUT = Orbit.NextApoapsisTime(VesselState.time); break; case WarpTarget.SoI: - if (orbit.patchEndTransition != Orbit.PatchTransitionType.FINAL) targetUT = orbit.EndUT; + if (Orbit.patchEndTransition != Orbit.PatchTransitionType.FINAL) targetUT = Orbit.EndUT; break; case WarpTarget.Node: - if (vessel.patchedConicsUnlocked() && vessel.patchedConicSolver.maneuverNodes.Any()) - targetUT = vessel.patchedConicSolver.maneuverNodes[0].UT; + if (Vessel.patchedConicsUnlocked() && Vessel.patchedConicSolver.maneuverNodes.Any()) + targetUT = Vessel.patchedConicSolver.maneuverNodes[0].UT; break; case WarpTarget.Time: - targetUT = vesselState.time + timeOffset; + targetUT = VesselState.time + timeOffset; break; case WarpTarget.PhaseAngleT: - if (core.Target.NormalTargetExists) + if (Core.Target.NormalTargetExists) { Orbit reference; - if (core.Target.TargetOrbit.referenceBody == orbit.referenceBody) - reference = orbit; // we orbit arround the same body + if (Core.Target.TargetOrbit.referenceBody == Orbit.referenceBody) + reference = Orbit; // we orbit arround the same body else - reference = orbit.referenceBody.orbit; + reference = Orbit.referenceBody.orbit; // From Kerbal Alarm Clock - double angleChangePerSec = 360 / core.Target.TargetOrbit.period - 360 / reference.period; - double currentAngle = reference.PhaseAngle(core.Target.TargetOrbit, vesselState.time); + double angleChangePerSec = 360 / Core.Target.TargetOrbit.period - 360 / reference.period; + double currentAngle = reference.PhaseAngle(Core.Target.TargetOrbit, VesselState.time); double angleDigff = currentAngle - phaseAngle; if (angleDigff > 0 && angleChangePerSec > 0) angleDigff -= 360; if (angleDigff < 0 && angleChangePerSec < 0) angleDigff += 360; double TimeToTarget = Math.Floor(Math.Abs(angleDigff / angleChangePerSec)); - targetUT = vesselState.time + TimeToTarget; + targetUT = VesselState.time + TimeToTarget; } break; @@ -124,8 +124,8 @@ protected override void WindowGUI(int windowID) case WarpTarget.AtmosphericEntry: try { - targetUT = vessel.orbit.NextTimeOfRadius(vesselState.time, - vesselState.mainBody.Radius + vesselState.mainBody.RealMaxAtmosphereAltitude()); + targetUT = Vessel.orbit.NextTimeOfRadius(VesselState.time, + VesselState.mainBody.Radius + VesselState.mainBody.RealMaxAtmosphereAltitude()); } catch { @@ -137,7 +137,7 @@ protected override void WindowGUI(int windowID) case WarpTarget.SuicideBurn: try { - targetUT = OrbitExtensions.SuicideBurnCountdown(orbit, vesselState, vessel) + vesselState.time; + targetUT = OrbitExtensions.SuicideBurnCountdown(Orbit, VesselState, Vessel) + VesselState.time; } catch { @@ -147,7 +147,7 @@ protected override void WindowGUI(int windowID) break; default: - targetUT = vesselState.time; + targetUT = VesselState.time; break; } } @@ -155,13 +155,13 @@ protected override void WindowGUI(int windowID) GUILayout.EndHorizontal(); - core.Warp.useQuickWarpInfoItem(); + Core.Warp.useQuickWarpInfoItem(); if (warping) GUILayout.Label(Localizer.Format("#MechJeb_WarpHelper_label6") + (leadTime > 0 ? GuiUtils.TimeToDHMS(leadTime) + " before " : "") + warpTargetStrings[(int)warpTarget] + "."); //"Warping to " - core.Warp.ControlWarpButton(); + Core.Warp.ControlWarpButton(); GUILayout.EndVertical(); @@ -176,7 +176,7 @@ public override void OnFixedUpdate() { try { - targetUT = OrbitExtensions.SuicideBurnCountdown(orbit, vesselState, vessel) + vesselState.time; + targetUT = OrbitExtensions.SuicideBurnCountdown(Orbit, VesselState, Vessel) + VesselState.time; } catch { @@ -186,14 +186,14 @@ public override void OnFixedUpdate() double target = targetUT - leadTime; - if (target < vesselState.time + 1) + if (target < VesselState.time + 1) { - core.Warp.MinimumWarp(true); + Core.Warp.MinimumWarp(true); warping = false; } else { - core.Warp.WarpToUT(target); + Core.Warp.WarpToUT(target); } } diff --git a/MechJeb2/MechJebModuleWaypointWindow.cs b/MechJeb2/MechJebModuleWaypointWindow.cs index 0e5baf08f..b763200a6 100644 --- a/MechJeb2/MechJebModuleWaypointWindow.cs +++ b/MechJeb2/MechJebModuleWaypointWindow.cs @@ -219,67 +219,67 @@ public enum WaypointMode public static List Routes = new List(); [EditableInfoItem("#MechJeb_MohoMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Moho Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Moho Mapdist public EditableDouble MohoMapdist = 5000; [EditableInfoItem("#MechJeb_EveMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Eve Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Eve Mapdist public EditableDouble EveMapdist = 5000; [EditableInfoItem("#MechJeb_GillyMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Gilly Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Gilly Mapdist public EditableDouble GillyMapdist = -500; [EditableInfoItem("#MechJeb_KerbinMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Kerbin Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Kerbin Mapdist public EditableDouble KerbinMapdist = 500; [EditableInfoItem("#MechJeb_MunMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Mun Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Mun Mapdist public EditableDouble MunMapdist = 4000; [EditableInfoItem("#MechJeb_MinmusMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Minmus Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Minmus Mapdist public EditableDouble MinmusMapdist = 3500; [EditableInfoItem("#MechJeb_DunaMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Duna Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Duna Mapdist public EditableDouble DunaMapdist = 5000; [EditableInfoItem("#MechJeb_IkeMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Ike Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Ike Mapdist public EditableDouble IkeMapdist = 4000; [EditableInfoItem("#MechJeb_DresMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Dres Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Dres Mapdist public EditableDouble DresMapdist = 1500; [EditableInfoItem("#MechJeb_EelooMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Eeloo Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Eeloo Mapdist public EditableDouble EelooMapdist = 2000; [EditableInfoItem("#MechJeb_JoolMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Jool Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Jool Mapdist public EditableDouble JoolMapdist = 30000; [EditableInfoItem("#MechJeb_TyloMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Tylo Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Tylo Mapdist public EditableDouble TyloMapdist = 5000; [EditableInfoItem("#MechJeb_LaytheMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Laythe Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Laythe Mapdist public EditableDouble LaytheMapdist = 1000; [EditableInfoItem("#MechJeb_PolMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Pol Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Pol Mapdist public EditableDouble PolMapdist = 500; [EditableInfoItem("#MechJeb_BopMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Bop Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Bop Mapdist public EditableDouble BopMapdist = 1000; [EditableInfoItem("#MechJeb_VallMapdist", InfoItem.Category.Rover)] - [Persistent(pass = (int)Pass.Global)] // Vall Mapdist + [Persistent(pass = (int)Pass.GLOBAL)] // Vall Mapdist public EditableDouble VallMapdist = 5000; internal int selIndex = -1; @@ -318,11 +318,11 @@ private enum pages { waypoints, settings, routes } public override void OnStart(PartModule.StartState state) { hidden = true; - ap = core.GetComputerModule(); - if (HighLogic.LoadedSceneIsFlight && vessel.isActiveVessel) + ap = Core.GetComputerModule(); + if (HighLogic.LoadedSceneIsFlight && Vessel.isActiveVessel) { - renderer = MechJebRouteRenderer.AttachToMapView(core); - renderer.enabled = enabled; + renderer = MechJebRouteRenderer.AttachToMapView(Core); + renderer.enabled = Enabled; } // GameObject obj = new GameObject("LineRenderer"); @@ -343,14 +343,14 @@ public override void OnStart(PartModule.StartState state) base.OnStart(state); } - public override void OnModuleEnabled() + protected override void OnModuleEnabled() { if (renderer != null) { renderer.enabled = true; } base.OnModuleEnabled(); } - public override void OnModuleDisabled() + protected override void OnModuleDisabled() { if (renderer != null) { renderer.enabled = false; } @@ -627,20 +627,20 @@ public void DrawPageWaypoints() float minSpeed = wp.MinSpeed > 0 ? wp.MinSpeed : 0; if (MapView.MapIsEnabled && i == selIndex) { - GLUtils.DrawGroundMarker(mainBody, wp.Latitude, wp.Longitude, Color.red, true, - (DateTime.Now.Second + DateTime.Now.Millisecond / 1000f) * 6, mainBody.Radius / 100); + GLUtils.DrawGroundMarker(MainBody, wp.Latitude, wp.Longitude, Color.red, true, + (DateTime.Now.Second + DateTime.Now.Millisecond / 1000f) * 6, MainBody.Radius / 100); } if (i >= ap.WaypointIndex) { if (ap.WaypointIndex > -1) { - eta += GuiUtils.FromToETA(i == ap.WaypointIndex ? vessel.CoM : (Vector3)ap.Waypoints[i - 1].Position, wp.Position, + eta += GuiUtils.FromToETA(i == ap.WaypointIndex ? Vessel.CoM : (Vector3)ap.Waypoints[i - 1].Position, wp.Position, ap.etaSpeed > 0.1 && ap.etaSpeed < maxSpeed ? (float)Math.Round(ap.etaSpeed, 1) : maxSpeed); } dist += Vector3.Distance( - i == ap.WaypointIndex || (ap.WaypointIndex == -1 && i == 0) ? vessel.CoM : (Vector3)ap.Waypoints[i - 1].Position, + i == ap.WaypointIndex || (ap.WaypointIndex == -1 && i == 0) ? Vessel.CoM : (Vector3)ap.Waypoints[i - 1].Position, wp.Position); } @@ -766,8 +766,8 @@ public void DrawPageWaypoints() waitingForPick = true; if (MapView.MapIsEnabled) { - core.Target.Unset(); - core.Target.PickPositionTargetOnMap(); + Core.Target.Unset(); + Core.Target.PickPositionTargetOnMap(); } } else @@ -854,8 +854,8 @@ public void DrawPageSettings() { bool alt = GameSettings.MODIFIER_KEY.GetKey(); titleAdd = "Settings"; - MechJebModuleCustomWindowEditor ed = core.GetComputerModule(); - if (!ap.enabled) { ap.CalculateTraction(); } // keep calculating traction just for displaying it + MechJebModuleCustomWindowEditor ed = Core.GetComputerModule(); + if (!ap.Enabled) { ap.CalculateTraction(); } // keep calculating traction just for displaying it scroll = GUILayout.BeginScrollView(scroll); @@ -934,8 +934,8 @@ public void DrawPageSettings() if (GUILayout.Button("Help")) { - core.GetComputerModule().enabled = - !core.GetComputerModule().enabled; + Core.GetComputerModule().Enabled = + !Core.GetComputerModule().Enabled; } GUILayout.EndHorizontal(); @@ -944,10 +944,10 @@ public void DrawPageSettings() public void DrawPageRoutes() { bool alt = GameSettings.MODIFIER_KEY.GetKey(); - titleAdd = "Routes for " + vessel.mainBody.bodyName; + titleAdd = "Routes for " + Vessel.mainBody.bodyName; scroll = GUILayout.BeginScrollView(scroll); - List bodyWPs = Routes.FindAll(r => r.Body == vessel.mainBody && r.Mode == Mode.ToString()); + List bodyWPs = Routes.FindAll(r => r.Body == Vessel.mainBody && r.Mode == Mode.ToString()); for (int i = 0; i < bodyWPs.Count; i++) { GUILayout.BeginHorizontal(); @@ -961,7 +961,7 @@ public void DrawPageRoutes() { if (GUILayout.Button("Delete", GUILayout.Width(70))) { - Routes.RemoveAll(r => r.Name == bodyWPs[i].Name && r.Body == vessel.mainBody && r.Mode == Mode.ToString()); + Routes.RemoveAll(r => r.Name == bodyWPs[i].Name && r.Body == Vessel.mainBody && r.Mode == Mode.ToString()); SaveRoutes(); saveIndex = -1; } @@ -978,8 +978,8 @@ public void DrawPageRoutes() { if (saveName != "" && ap.Waypoints.Count > 0) { - MechJebWaypointRoute old = Routes.Find(r => r.Name == saveName && r.Body == vessel.mainBody && r.Mode == Mode.ToString()); - var wps = new MechJebWaypointRoute(saveName, vessel.mainBody); + MechJebWaypointRoute old = Routes.Find(r => r.Name == saveName && r.Body == Vessel.mainBody && r.Mode == Mode.ToString()); + var wps = new MechJebWaypointRoute(saveName, Vessel.mainBody); ap.Waypoints.ForEach(wp => wps.Add(wp)); if (old == null) { @@ -1029,7 +1029,7 @@ protected override void WindowGUI(int windowID) { if (GUI.Button(new Rect(windowPos.width - 48, 0, 13, 20), "?", GuiUtils.yellowOnHover)) { - MechJebModuleWaypointHelpWindow help = core.GetComputerModule(); + MechJebModuleWaypointHelpWindow help = Core.GetComputerModule(); switch (showPage) { case pages.waypoints: @@ -1043,7 +1043,7 @@ protected override void WindowGUI(int windowID) break; } - help.enabled = help.selTopic > -1 || help.enabled; + help.Enabled = help.selTopic > -1 || help.Enabled; } if (styleInactive == null) @@ -1081,38 +1081,38 @@ protected override void WindowGUI(int windowID) break; } - if (waitingForPick && vessel.isActiveVessel && Event.current.type == EventType.Repaint) + if (waitingForPick && Vessel.isActiveVessel && Event.current.type == EventType.Repaint) { if (MapView.MapIsEnabled) { - if (core.Target.pickingPositionTarget == false) + if (Core.Target.pickingPositionTarget == false) { - if (core.Target.PositionTargetExists) + if (Core.Target.PositionTargetExists) { if (selIndex > -1 && selIndex < ap.Waypoints.Count) { - ap.Waypoints.Insert(selIndex, new MechJebWaypoint(core.Target.GetPositionTargetPosition())); + ap.Waypoints.Insert(selIndex, new MechJebWaypoint(Core.Target.GetPositionTargetPosition())); tmpRadius = ap.Waypoints[selIndex].Radius.ToString(); tmpLat = LatToString(ap.Waypoints[selIndex].Latitude); tmpLon = LonToString(ap.Waypoints[selIndex].Longitude); } else { - ap.Waypoints.Add(new MechJebWaypoint(core.Target.GetPositionTargetPosition())); + ap.Waypoints.Add(new MechJebWaypoint(Core.Target.GetPositionTargetPosition())); } - core.Target.Unset(); + Core.Target.Unset(); waitingForPick = alt; } else { - core.Target.PickPositionTargetOnMap(); + Core.Target.PickPositionTargetOnMap(); } } } else { - if (!GuiUtils.MouseIsOverWindow(core)) + if (!GuiUtils.MouseIsOverWindow(Core)) { Coordinates mouseCoords = GetMouseFlightCoordinates(); if (mouseCoords != null) @@ -1143,7 +1143,7 @@ protected override void WindowGUI(int windowID) public override void OnFixedUpdate() { - if (vessel.isActiveVessel && (renderer == null || renderer.ap != ap)) { MechJebRouteRenderer.AttachToMapView(core); } + if (Vessel.isActiveVessel && (renderer == null || renderer.ap != ap)) { MechJebRouteRenderer.AttachToMapView(Core); } ap.Waypoints.ForEach(wp => wp.Update()); // float scale = Vector3.Distance(FlightCamera.fetch.mainCamera.transform.position, vessel.CoM) / 900f; @@ -1394,8 +1394,8 @@ public void OnPreRender() } //Debug.Log(ap.vessel.vesselName); - MechJebModuleWaypointWindow window = ap.core.GetComputerModule(); - switch (ap.vessel.mainBody.bodyName) + MechJebModuleWaypointWindow window = ap.Core.GetComputerModule(); + switch (ap.Vessel.mainBody.bodyName) { case "Moho": addHeight = window.MohoMapdist; @@ -1450,10 +1450,10 @@ public void OnPreRender() break; } - if (ap != null && ap.Waypoints.Count > 0 && ap.vessel.isActiveVessel && HighLogic.LoadedSceneIsFlight) + if (ap != null && ap.Waypoints.Count > 0 && ap.Vessel.isActiveVessel && HighLogic.LoadedSceneIsFlight) { float targetHeight = MapView.MapIsEnabled ? (float)addHeight : 3f; - float scale = Vector3.Distance(FlightCamera.fetch.mainCamera.transform.position, ap.vessel.CoM) / 700f; + float scale = Vector3.Distance(FlightCamera.fetch.mainCamera.transform.position, ap.Vessel.CoM) / 700f; float width = MapView.MapIsEnabled ? (float)(0.005 * PlanetariumCamera.fetch.Distance) : scale + 0.1f; //float width = (MapView.MapIsEnabled ? (float)mainBody.Radius / 10000 : 1); @@ -1466,7 +1466,7 @@ public void OnPreRender() selWP.gameObject.layer = pastPath.gameObject.layer = currPath.gameObject.layer = nextPath.gameObject.layer = MapView.MapIsEnabled ? 9 : 0; - int sel = ap.core.GetComputerModule().selIndex; + int sel = ap.Core.GetComputerModule().selIndex; selWP.enabled = sel > -1 && !MapView.MapIsEnabled; if (selWP.enabled) { @@ -1488,7 +1488,7 @@ public void OnPreRender() pastPath.SetPosition(i, RaisePositionOverTerrain(ap.Waypoints[i].Position, targetHeight)); } - pastPath.SetPosition(ap.WaypointIndex, RaisePositionOverTerrain(ap.vessel.CoM, targetHeight)); + pastPath.SetPosition(ap.WaypointIndex, RaisePositionOverTerrain(ap.Vessel.CoM, targetHeight)); // Debug.Log("pastPath drawn"); } else @@ -1501,7 +1501,7 @@ public void OnPreRender() { // Debug.Log("drawing currPath"); currPath.enabled = true; - currPath.SetPosition(0, RaisePositionOverTerrain(ap.vessel.CoM, targetHeight)); + currPath.SetPosition(0, RaisePositionOverTerrain(ap.Vessel.CoM, targetHeight)); currPath.SetPosition(1, RaisePositionOverTerrain(ap.Waypoints[ap.WaypointIndex].Position, targetHeight)); // Debug.Log("currPath drawn"); } @@ -1518,7 +1518,7 @@ public void OnPreRender() nextPath.enabled = true; nextPath.positionCount = nextCount; nextPath.SetPosition(0, - RaisePositionOverTerrain(ap.WaypointIndex == -1 ? ap.vessel.CoM : (Vector3)ap.Waypoints[ap.WaypointIndex].Position, + RaisePositionOverTerrain(ap.WaypointIndex == -1 ? ap.Vessel.CoM : (Vector3)ap.Waypoints[ap.WaypointIndex].Position, targetHeight)); for (int i = 0; i < nextCount - 1; i++) { diff --git a/MechJeb2/MechJebStageStatsHelper.cs b/MechJeb2/MechJebStageStatsHelper.cs index a5271f286..0d099228a 100644 --- a/MechJeb2/MechJebStageStatsHelper.cs +++ b/MechJeb2/MechJebStageStatsHelper.cs @@ -28,7 +28,7 @@ public class MechJebStageStatsHelper public MechJebStageStatsHelper(MechJebModuleInfoItems items) { infoItems = items; - core = items.core; + core = items.Core; stats = core.GetComputerModule(); showStagedMass = items.showStagedMass; showBurnedMass = items.showBurnedMass; @@ -170,7 +170,7 @@ private void SetAllStageVisibility(bool state) // This should only be called before Layout phase, and never in Repaint phase public void UpdateStageStats() { - double geeASL = HighLogic.LoadedSceneIsEditor ? FlightGlobals.Bodies[TWRBody].GeeASL : stats.mainBody.GeeASL; + double geeASL = HighLogic.LoadedSceneIsEditor ? FlightGlobals.Bodies[TWRBody].GeeASL : stats.MainBody.GeeASL; stats.RequestUpdate(this); GatherStages(stages); UpdateStageDisplayInfo(stages, geeASL); @@ -249,7 +249,7 @@ public void AllStageStats() GUILayout.EndHorizontal(); } else - stats.editorBody = stats.mainBody; + stats.editorBody = stats.MainBody; Profiler.EndSample(); diff --git a/MechJeb2/VesselState.cs b/MechJeb2/VesselState.cs index 197fd02cf..44551ca0a 100644 --- a/MechJeb2/VesselState.cs +++ b/MechJeb2/VesselState.cs @@ -866,7 +866,7 @@ private void UpdateRCSThrustAndTorque(Vessel vessel) return; MechJebModuleRCSBalancer rcsbal = vessel.GetMasterMechJeb().Rcsbal; - if (rcsbal.enabled) + if (rcsbal.Enabled) { Vector3d rot = Vector3d.zero; for (int i = 0; i < Vector6.Values.Length; i++) @@ -955,7 +955,7 @@ private void UpdateRCSThrustAndTorque(Vessel vessel) Vector3d thrusterThrust = thrustDirection * power; // This is a cheap hack to get rcsTorque with the RCS balancer active. - if (!rcsbal.enabled) + if (!rcsbal.Enabled) { rcsThrustAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterThrust), translationControl));