From 747cacf4d323393803362f6b98dc9fff74fb056e Mon Sep 17 00:00:00 2001 From: Lamont Granquist Date: Mon, 12 Jun 2023 09:11:26 -0700 Subject: [PATCH] Automated Code Cleanup just rip off the rest of the bandage wholesale. Signed-off-by: Lamont Granquist --- LandingSites.cfg | 390 +-- MechJeb2/FlyingSim/SimulatedPart.cs | 1 - MechJeb2/FuelFlowSimulation.cs | 13 +- MechJeb2/FuelNode.cs | 93 +- MechJeb2/FuelStats.cs | 6 +- MechJeb2/Maneuver/OperationResonantOrbit.cs | 3 +- MechJeb2/Maneuver/OperationSemiMajor.cs | 3 +- MechJeb2/Maneuver/TransferCalculator.cs | 3 +- MechJeb2/MechJeb2.csproj | 516 ++-- MechJeb2/MechJebCore.cs | 4 +- MechJeb2/MechJebLib/Core/TwoBody/Shepperd.cs | 4 +- .../Maneuvers/ChangeOrbitalElement.cs | 11 +- .../MechJebLib/Maneuvers/ReturnFromMoon.cs | 23 +- MechJeb2/MechJebLib/PVG/AscentBuilder.cs | 23 +- MechJeb2/MechJebLib/PVG/InputLayout.cs | 8 +- .../PVG/Integrators/IPVGIntegrator.cs | 4 +- .../PVG/Integrators/VacuumCoastAnalytic.cs | 2 +- .../PVG/Integrators/VacuumThrustAnalytic.cs | 4 +- MechJeb2/MechJebLib/PVG/Optimizer.cs | 3 +- MechJeb2/MechJebLib/PVG/OutputLayout.cs | 5 +- MechJeb2/MechJebLib/PVG/Problem.cs | 26 +- MechJeb2/MechJebLib/PVG/ResidualWrapper.cs | 1 - .../PVG/Terminal/FlightPathAngle5Reduced.cs | 2 +- .../MechJebLib/PVG/Terminal/Kepler3Reduced.cs | 16 +- .../MechJebLib/PVG/Terminal/Kepler4Reduced.cs | 6 +- .../MechJebLib/PVG/Terminal/Kepler5Reduced.cs | 4 +- MechJeb2/MechJebLib/Primitives/H1.cs | 1 - MechJeb2/MechJebLib/Primitives/H3.cs | 1 - MechJeb2/MechJebLib/Primitives/Scale.cs | 14 +- MechJeb2/MechJebLib/Primitives/V3.cs | 7 +- MechJeb2/MechJebLib/Primitives/Vn.cs | 5 +- MechJeb2/MechJebLib/Utils/Logger.cs | 6 +- MechJeb2/MechJebModuleAirplaneAutopilot.cs | 39 +- MechJeb2/MechJebModuleAirplaneGuidance.cs | 453 ++- MechJeb2/MechJebModuleAscentBaseAutopilot.cs | 12 +- .../MechJebModuleAscentClassicAutopilot.cs | 6 +- .../MechJebModuleAscentClassicPathMenu.cs | 14 +- MechJeb2/MechJebModuleAscentGTAutopilot.cs | 32 +- MechJeb2/MechJebModuleAscentPVGAutopilot.cs | 4 +- .../MechJebModuleAscentPVGSettingsMenu.cs | 3 +- MechJeb2/MechJebModuleAscentSettings.cs | 4 +- MechJeb2/MechJebModuleAscentSettingsMenu.cs | 18 +- MechJeb2/MechJebModuleAttitudeAdjustment.cs | 88 +- MechJeb2/MechJebModuleAttitudeController.cs | 23 +- MechJeb2/MechJebModuleCustomInfoWindow.cs | 481 +-- MechJeb2/MechJebModuleDebugArrows.cs | 202 +- ...echJebModuleDeployableAntennaController.cs | 22 +- MechJeb2/MechJebModuleDeployableController.cs | 44 +- MechJeb2/MechJebModuleDockingAutopilot.cs | 132 +- MechJeb2/MechJebModuleDockingGuidance.cs | 66 +- MechJeb2/MechJebModuleFlightRecorder.cs | 128 +- MechJeb2/MechJebModuleFlightRecorderGraph.cs | 466 +-- MechJeb2/MechJebModuleGuidanceController.cs | 2 +- MechJeb2/MechJebModuleInfoItems.cs | 442 +-- MechJeb2/MechJebModuleLandingAutopilot.cs | 401 ++- MechJeb2/MechJebModuleLandingGuidance.cs | 173 +- MechJeb2/MechJebModuleLandingPredictions.cs | 218 +- MechJeb2/MechJebModuleManeuverPlanner.cs | 70 +- MechJeb2/MechJebModuleMenu.cs | 171 +- MechJeb2/MechJebModuleNodeEditor.cs | 115 +- MechJeb2/MechJebModuleNodeExecutor.cs | 103 +- MechJeb2/MechJebModuleRCSBalancer.cs | 80 +- MechJeb2/MechJebModuleRCSBalancerWindow.cs | 27 +- MechJeb2/MechJebModuleRCSController.cs | 66 +- MechJeb2/MechJebModuleRendezvousAutopilot.cs | 45 +- .../MechJebModuleRendezvousAutopilotWindow.cs | 34 +- MechJeb2/MechJebModuleRendezvousGuidance.cs | 57 +- MechJeb2/MechJebModuleRoverController.cs | 1024 ++++--- MechJeb2/MechJebModuleRoverWindow.cs | 323 +- MechJeb2/MechJebModuleScript.cs | 1264 ++++---- MechJeb2/MechJebModuleSettings.cs | 52 +- MechJeb2/MechJebModuleSmartASS.cs | 350 ++- MechJeb2/MechJebModuleSmartRcs.cs | 55 +- MechJeb2/MechJebModuleSolarPanelController.cs | 22 +- MechJeb2/MechJebModuleSpaceplaneAutopilot.cs | 258 +- MechJeb2/MechJebModuleSpaceplaneGuidance.cs | 65 +- MechJeb2/MechJebModuleSpinupController.cs | 11 +- MechJeb2/MechJebModuleStageStats.cs | 62 +- MechJeb2/MechJebModuleStagingController.cs | 3 +- MechJeb2/MechJebModuleTargetController.cs | 156 +- MechJeb2/MechJebModuleThrustController.cs | 318 +- MechJeb2/MechJebModuleThrustWindow.cs | 75 +- MechJeb2/MechJebModuleTranslatron.cs | 103 +- MechJeb2/MechJebModuleWarpController.cs | 81 +- MechJeb2/MechJebModuleWarpHelper.cs | 63 +- MechJeb2/MechJebModuleWaypointWindow.cs | 2672 +++++++++-------- MechJeb2/OrbitExtensions.cs | 26 +- MechJeb2/Properties/AssemblyInfo.cs | 5 +- MechJeb2/Properties/Resources.resx | 109 +- MechJeb2/ReentrySimulation.cs | 2 +- MechJeb2/ReentrySimulation/SimCurves.cs | 2 +- MechJeb2/VesselState.cs | 778 ++--- MechJebEdu.cfg | 10 +- MechJebLibTest/Maths/BS3Tests.c.cs | 1 - MechJebLibTest/Maths/BisectionTests.cs | 8 +- MechJebLibTest/MechJebLibTest.csproj | 56 +- MechJebLibTest/Structs/HTests.cs | 8 +- MechJebLibTest/Structs/M3Tests.cs | 2 +- MechJebLibTest/Structs/V3Tests.cs | 21 +- MechJebLibTest/TestInitialization.cs | 6 +- MechJebLibTest/Utils/StaticTests.cs | 176 +- 101 files changed, 7401 insertions(+), 6215 deletions(-) diff --git a/LandingSites.cfg b/LandingSites.cfg index 6c0c6c58e..6b44c094e 100644 --- a/LandingSites.cfg +++ b/LandingSites.cfg @@ -1,197 +1,197 @@ MechJeb2Landing { - // If you want to clean up the default site then you'll need an MM patch - // !MechJeb2Landing:HAS[#id[MechJeb2DefaultLandingSites]] { } - id = MechJeb2DefaultLandingSites - LandingSites - { - Site - { - name = KSC Pad - latitude = -0.09694444 - longitude = -74.5575 - // body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) - } - Site - { - name = VAB - latitude = -0.09694444 - longitude = -74.617 - // body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) - } - Site - { - name = Baikerbanur - latitude = 20.666 - longitude = 146.466 - body = Kerbin - } - Site - { - name = Cove - latitude = 3.70 - longitude = -72.2 - body = Kerbin - } - Site - { - name = Crater - latitude = 8.39 - longitude = -179.68 - body = Kerbin - } - Site - { - name = Dessert - latitude = 6.56 - longitude = 143.95 - body = Kerbin - } - Site - { - name = Glacier Lake - latitude = 73.56 - longitude = 84.27 - body = Kerbin - } - Site - { - name = Mahi Mahi - latitude = -49.80 - longitude = -120.77 - body = Kerbin - } - Site - { - name = Woomerang - latitude = 45.29 - longitude = 136.11 - body = Kerbin - } - Site - { - name = Greater Flats - latitude = -4.794139 - longitude = -11.575088 - body = Minmus - } - Site - { - name = Negan's Place - latitude = -19.669238 - longitude = 77.936054 - body = Minmus - } - } - Runways - { - Runway - { - name = KSC Runway 09 - body = "Kerbin" - touchdown = 100.0 - start - { - latitude = -0.0485981 - longitude = -74.726413 - altitude = 69 - } - end - { - latitude = -0.050185 - longitude = -74.490867 - altitude = 69 - } - } - Runway - { - name = KSC Runway 27 - body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) - touchdown = 100.0 // distance in meters from start point - start - { - latitude = -0.050185 - longitude = -74.490867 - altitude = 69 - } - end - { - latitude = -0.0485981 - longitude = -74.726413 - altitude = 69 - } - } - Runway - { - name = Island Runway 09 - body = "Kerbin" - touchdown = 25.0 - start - { - latitude = -1.517306 - longitude = -71.965488 - altitude = 132 - } - end - { - latitude = -1.515980 - longitude = -71.852408 - altitude = 132 - } - } - Runway - { - name = Island Runway 27 - body = "Kerbin" - touchdown = 25.0 - end - { - latitude = -1.515980 - longitude = -71.852408 - altitude = 132 - } - start - { - latitude = -1.517306 - longitude = -71.965488 - altitude = 132 - } - } - Runway - { - name = Desert Runway 18 - body = Kerbin - touchdown = 50.0 - start - { - latitude = -6.448288 - longitude = -144.038171 - altitude = 822.05 - } - end - { - latitude = -6.599329 - longitude = -144.040598 - altitude = 821.93 - } - } - Runway - { - name = Desert Runway 36 - body = Kerbin - touchdown = 50.0 - start - { - latitude = -6.599329 - longitude = -144.040598 - altitude = 821.93 - } - end - { - latitude = -6.448288 - longitude = -144.038171 - altitude = 822.05 - } - } - } -} \ No newline at end of file +// If you want to clean up the default site then you'll need an MM patch +// !MechJeb2Landing : HAS[#id[MechJeb2DefaultLandingSites]] { } +id = MechJeb2DefaultLandingSites +LandingSites +{ +Site +{ +name = KSC Pad +latitude = -0.09694444 +longitude = -74.5575 +// body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) +} +Site +{ +name = VAB +latitude = -0.09694444 +longitude = -74.617 +// body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) +} +Site +{ +name = Baikerbanur +latitude = 20.666 +longitude = 146.466 +body = Kerbin +} +Site +{ +name = Cove +latitude = 3.70 +longitude = -72.2 +body = Kerbin +} +Site +{ +name = Crater +latitude = 8.39 +longitude = -179.68 +body = Kerbin +} +Site +{ +name = Dessert +latitude = 6.56 +longitude = 143.95 +body = Kerbin +} +Site +{ +name = Glacier Lake +latitude = 73.56 +longitude = 84.27 +body = Kerbin +} +Site +{ +name = Mahi Mahi +latitude = -49.80 +longitude = -120.77 +body = Kerbin +} +Site +{ +name = Woomerang +latitude = 45.29 +longitude = 136.11 +body = Kerbin +} +Site +{ +name = Greater Flats +latitude = -4.794139 +longitude = -11.575088 +body = Minmus +} +Site +{ +name = Negan's Place +latitude = -19.669238 +longitude = 77.936054 +body = Minmus +} +} +Runways +{ +Runway +{ +name = KSC Runway 09 +body = "Kerbin" +touchdown = 100.0 +start +{ +latitude = -0.0485981 +longitude = -74.726413 +altitude = 69 +} +end +{ +latitude = -0.050185 +longitude = -74.490867 +altitude = 69 +} +} +Runway +{ +name = KSC Runway 27 +body = "Kerbin" // if not set defaults to the starting world (Kerbin, Earth for RSS) +touchdown = 100.0 // distance in meters from start point +start +{ +latitude = -0.050185 +longitude = -74.490867 +altitude = 69 +} +end +{ +latitude = -0.0485981 +longitude = -74.726413 +altitude = 69 +} +} +Runway +{ +name = Island Runway 09 +body = "Kerbin" +touchdown = 25.0 +start +{ +latitude = -1.517306 +longitude = -71.965488 +altitude = 132 +} +end +{ +latitude = -1.515980 +longitude = -71.852408 +altitude = 132 +} +} +Runway +{ +name = Island Runway 27 +body = "Kerbin" +touchdown = 25.0 +end +{ +latitude = -1.515980 +longitude = -71.852408 +altitude = 132 +} +start +{ +latitude = -1.517306 +longitude = -71.965488 +altitude = 132 +} +} +Runway +{ +name = Desert Runway 18 +body = Kerbin +touchdown = 50.0 +start +{ +latitude = -6.448288 +longitude = -144.038171 +altitude = 822.05 +} +end +{ +latitude = -6.599329 +longitude = -144.040598 +altitude = 821.93 +} +} +Runway +{ +name = Desert Runway 36 +body = Kerbin +touchdown = 50.0 +start +{ +latitude = -6.599329 +longitude = -144.040598 +altitude = 821.93 +} +end +{ +latitude = -6.448288 +longitude = -144.038171 +altitude = 822.05 +} +} +} +} diff --git a/MechJeb2/FlyingSim/SimulatedPart.cs b/MechJeb2/FlyingSim/SimulatedPart.cs index 6e87f9981..9657aae5d 100644 --- a/MechJeb2/FlyingSim/SimulatedPart.cs +++ b/MechJeb2/FlyingSim/SimulatedPart.cs @@ -237,7 +237,6 @@ protected void CopyDragCubesList(DragCubeList source, DragCubeList dest) dest.SetDragWeights(); simCurves.CopyTo(dest); - } protected static void CopyDragCube(DragCube source, DragCube dest) diff --git a/MechJeb2/FuelFlowSimulation.cs b/MechJeb2/FuelFlowSimulation.cs index ca41e4314..c9f836ca3 100644 --- a/MechJeb2/FuelFlowSimulation.cs +++ b/MechJeb2/FuelFlowSimulation.cs @@ -30,14 +30,15 @@ public void CopyFrom(FuelFlowSimulation f) _partLookup.Clear(); _kpaToAtmospheres = f._kpaToAtmospheres; - _simStage = f._simStage; + _simStage = f._simStage; Profiler.BeginSample("BorrowAndCopyFrom"); foreach (FuelNode n in f._nodes) { - FuelNode n2 = FuelNode.BorrowAndCopyFrom(n); + var n2 = FuelNode.BorrowAndCopyFrom(n); _nodes.Add(n2); } + Profiler.EndSample(); foreach (FuelNode node in _nodes) @@ -54,6 +55,7 @@ public void CopyFrom(FuelFlowSimulation f) Part p = node.part; node.AddCrossfeedSources(p.crossfeedPartSet.GetParts(), _nodeLookup); } + Profiler.EndSample(); Profiler.EndSample(); @@ -77,7 +79,7 @@ public void Init(List parts, bool dVLinearThrust) for (int index = 0; index < parts.Count; index++) { Part part = parts[index]; - FuelNode node = FuelNode.Borrow(part, dVLinearThrust); + var node = FuelNode.Borrow(part, dVLinearThrust); _nodeLookup[part] = node; _partLookup[node] = part; _nodes.Add(node); @@ -103,6 +105,7 @@ public void Init(List parts, bool dVLinearThrust) HashSet set = p.crossfeedPartSet.GetParts(); node.AddCrossfeedSources(set, _nodeLookup); } + if (node.decoupledInStage >= _simStage) _simStage = node.decoupledInStage + 1; } @@ -419,9 +422,10 @@ private double VesselThrustAndSpoolup(out double sumSpoolup) if (_simStage == activeEngines.value[i].inverseStage) { sumSpoolupThrust += thrust; - sumSpoolup += activeEngines.value[i].partSpoolupTime * thrust; + sumSpoolup += activeEngines.value[i].partSpoolupTime * thrust; } } + if (sumSpoolupThrust > 0) sumSpoolup /= sumSpoolupThrust; @@ -438,6 +442,7 @@ private Disposable> FindActiveEngines() if (n.isEngine && n.inverseStage >= _simStage && n.isDrawingResources && n.CanDrawNeededResources(_nodes)) activeEngines.value.Add(n); } + return activeEngines; } } diff --git a/MechJeb2/FuelNode.cs b/MechJeb2/FuelNode.cs index 3206e3db4..db498ec4a 100644 --- a/MechJeb2/FuelNode.cs +++ b/MechJeb2/FuelNode.cs @@ -24,15 +24,19 @@ public static void DoReflection() { if (ReflectionUtils.isAssemblyLoaded("RealFuels")) { - RFpredictedMaximumResiduals = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "predictedMaximumResiduals"); + RFpredictedMaximumResiduals = + ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "predictedMaximumResiduals"); if (RFpredictedMaximumResiduals == null) { - Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no predictedMaximumResiduals field, disabling residuals"); + Debug.Log( + "MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no predictedMaximumResiduals field, disabling residuals"); } - RFspoolUpTime = ReflectionUtils.getFieldByReflection("RealFuels","RealFuels.ModuleEnginesRF","effectiveSpoolUpTime"); + + RFspoolUpTime = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "effectiveSpoolUpTime"); if (RFspoolUpTime == null) { - Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no effectiveSpoolUpTime field, disabling spoolup"); + Debug.Log( + "MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no effectiveSpoolUpTime field, disabling spoolup"); } } } @@ -69,6 +73,7 @@ public EngineInfo(ModuleEngines engineModule) temp = 0; } } + moduleResiduals = temp ?? 0; float? temp2 = 0; @@ -84,32 +89,47 @@ public EngineInfo(ModuleEngines engineModule) temp2 = 0; } } + moduleSpoolupTime = temp2 ?? 0; } public EngineInfo(EngineInfo engineInfo) { - engineModule = engineInfo.engineModule; - thrustVector = engineInfo.thrustVector; - moduleResiduals = engineInfo.moduleResiduals; - maxThrust = engineInfo.maxThrust; + engineModule = engineInfo.engineModule; + thrustVector = engineInfo.thrustVector; + moduleResiduals = engineInfo.moduleResiduals; + maxThrust = engineInfo.maxThrust; moduleSpoolupTime = engineInfo.moduleSpoolupTime; } } - private readonly DefaultableDictionary resources = new DefaultableDictionary(0); //the resources contained in the part - private readonly DefaultableDictionary resourcesFull = new DefaultableDictionary(0); //the resources the part has when full - private readonly KeyableDictionary resourceConsumptions = new KeyableDictionary(); //the resources this part consumes per unit time when active at full throttle - private readonly DefaultableDictionary resourceDrains = new DefaultableDictionary(0); //the resources being drained from this part per unit time at the current simulation - private readonly DefaultableDictionary resourceResidual = new DefaultableDictionary(0); // the fraction of the resource which will be residual - private readonly DefaultableDictionary freeResources = new DefaultableDictionary(false); //the resources that are "free" and assumed to be infinite like IntakeAir + private readonly DefaultableDictionary + resources = new DefaultableDictionary(0); //the resources contained in the part + + private readonly DefaultableDictionary + resourcesFull = new DefaultableDictionary(0); //the resources the part has when full + + private readonly KeyableDictionary + resourceConsumptions = + new KeyableDictionary(); //the resources this part consumes per unit time when active at full throttle + + private readonly DefaultableDictionary + resourceDrains = + new DefaultableDictionary(0); //the resources being drained from this part per unit time at the current simulation + + private readonly DefaultableDictionary + resourceResidual = new DefaultableDictionary(0); // the fraction of the resource which will be residual + + private readonly DefaultableDictionary + freeResources = new DefaultableDictionary(false); //the resources that are "free" and assumed to be infinite like IntakeAir // if a resource amount falls below this amount we say that the resource has been drained // set to the smallest amount that the user can see is non-zero in the resource tab or by // right-clicking. private const double DRAINED = 1E-4; - private readonly KeyableDictionary propellantFlows = new KeyableDictionary(); //flow modes of propellants since the engine can override them + private readonly KeyableDictionary + propellantFlows = new KeyableDictionary(); //flow modes of propellants since the engine can override them private readonly List crossfeedSources = new List(); @@ -136,7 +156,7 @@ public EngineInfo(EngineInfo engineInfo) public string partName; //for debugging - public Part part; + public Part part; private bool dVLinearThrust; private Vector3d vesselOrientation; @@ -225,37 +245,37 @@ public static FuelNode BorrowAndCopyFrom(FuelNode n) node.engineInfos.Clear(); node.resources.Clear(); - foreach (var key in n.resources.KeysList) + foreach (int key in n.resources.KeysList) { node.resources.Add(key, n.resources[key]); } - foreach (var key in n.resourcesFull.KeysList) + foreach (int key in n.resourcesFull.KeysList) { node.resourcesFull.Add(key, n.resourcesFull[key]); } - foreach (var key in n.resourceConsumptions.KeysList) + foreach (int key in n.resourceConsumptions.KeysList) { node.resourceConsumptions.Add(key, n.resourceConsumptions[key]); } - foreach (var key in n.resourceDrains.KeysList) + foreach (int key in n.resourceDrains.KeysList) { node.resourceDrains.Add(key, n.resourceDrains[key]); } - foreach (var key in n.freeResources.KeysList) + foreach (int key in n.freeResources.KeysList) { node.freeResources.Add(key, n.freeResources[key]); } - foreach (var key in n.resourceResidual.KeysList) + foreach (int key in n.resourceResidual.KeysList) { node.resourceResidual.Add(key, n.resourceResidual[key]); } - foreach (var e in n.engineInfos) + foreach (EngineInfo e in n.engineInfos) { node.engineInfos.Add(new EngineInfo(e)); } @@ -324,11 +344,11 @@ private void Init(Part part, bool dVLinearThrust) } } - modulesUnstagedMass = part.GetModuleMassNoAlloc((float) dryMass, ModifierStagingSituation.UNSTAGED); + modulesUnstagedMass = part.GetModuleMassNoAlloc((float)dryMass, ModifierStagingSituation.UNSTAGED); - modulesStagedMass = part.GetModuleMassNoAlloc((float) dryMass, ModifierStagingSituation.STAGED); + modulesStagedMass = part.GetModuleMassNoAlloc((float)dryMass, ModifierStagingSituation.STAGED); - float currentModulesMass = part.GetModuleMassNoAlloc((float) dryMass, ModifierStagingSituation.CURRENT); + float currentModulesMass = part.GetModuleMassNoAlloc((float)dryMass, ModifierStagingSituation.CURRENT); // if it was manually staged if (currentModulesMass == modulesStagedMass) modulesUnstagedMass = modulesStagedMass; @@ -394,7 +414,7 @@ private void Init(Part part, bool dVLinearThrust) // find our max maxEngineResiduals for this engine part from all the modules foreach (EngineInfo e in engineInfos) { - maxEngineResiduals = Math.Max(maxEngineResiduals,e.moduleResiduals); + maxEngineResiduals = Math.Max(maxEngineResiduals, e.moduleResiduals); maxThrust += e.maxThrust; } } @@ -483,7 +503,9 @@ public void AssignDecoupledInStage(Part p, Part traversalParent, Dictionary 0) @@ -658,6 +680,7 @@ public void SetConsumptionRates(float throttle, double atmospheres, double atmDe } } } + if (partThrust > 0) partSpoolupTime /= partThrust; @@ -732,7 +755,7 @@ public double MaxTimeStep() foreach (int id in resourceDrains.KeysList) if (!freeResources[id] && resources[id] > ResidualThreshold(id)) - minDT = Math.Min(minDT, ( resources[id] - resourceResidual[id] * resourcesFull[id] ) / resourceDrains[id]); + minDT = Math.Min(minDT, (resources[id] - resourceResidual[id] * resourcesFull[id]) / resourceDrains[id]); return minDT; } @@ -767,7 +790,7 @@ public bool CanDrawNeededResources(List vessel) // enough intake air, and any other causes. // BIG FIXME: we're doing this in the thread and touching the KSP part object. - if (part.Modules[0] is ModuleEngines {flameout: true, statusL2: "No propellants"}) + if (part.Modules[0] is ModuleEngines { flameout: true, statusL2: "No propellants" }) return false; foreach (int type in resourceConsumptions.KeysList) @@ -810,18 +833,18 @@ public bool CanDrawResourceFrom(int type, FuelNode node) switch (resourceFlowMode) { case ResourceFlowMode.NO_FLOW: - return node == this; + return node == this; case ResourceFlowMode.ALL_VESSEL: case ResourceFlowMode.ALL_VESSEL_BALANCE: case ResourceFlowMode.STAGE_PRIORITY_FLOW: case ResourceFlowMode.STAGE_PRIORITY_FLOW_BALANCE: - return true; + return true; case ResourceFlowMode.STAGE_STACK_FLOW: case ResourceFlowMode.STAGE_STACK_FLOW_BALANCE: case ResourceFlowMode.STACK_PRIORITY_SEARCH: - return crossfeedSources.Contains(node); + return crossfeedSources.Contains(node); case ResourceFlowMode.NULL: default: diff --git a/MechJeb2/FuelStats.cs b/MechJeb2/FuelStats.cs index 2cbd69da5..287630ea4 100644 --- a/MechJeb2/FuelStats.cs +++ b/MechJeb2/FuelStats.cs @@ -2,7 +2,7 @@ namespace MuMech { - public partial class FuelFlowSimulation + public partial class FuelFlowSimulation { //A FuelStats struct describes the result of the simulation over a certain interval of time (e.g., one stage) public struct FuelStats @@ -50,7 +50,7 @@ public FuelStats Append(FuelStats s) { // we integrate to the time-averaged maxthrust to accomodate weirdness like ullage motors that burnout and tiny segments // that turn off the engines for some reason. this is so PVG has a number which is closest to reality. - MaxThrust = sumDT > 1e-10 ? (MaxThrust * DeltaTime + s.MaxThrust * sDeltaTime ) / ( DeltaTime + sDeltaTime) : MaxThrust, + MaxThrust = sumDT > 1e-10 ? (MaxThrust * DeltaTime + s.MaxThrust * sDeltaTime) / (DeltaTime + sDeltaTime) : MaxThrust, StartMass = StartMass, EndMass = s.EndMass, ResourceMass = StartMass - s.EndMass, @@ -61,7 +61,7 @@ public FuelStats Append(FuelStats s) DeltaTime = sumDT, DeltaV = DeltaV + s.DeltaV, // ReSharper disable once CompareOfFloatsByEqualityOperator - Isp = StartMass == s.EndMass ? 0 : (DeltaV + s.DeltaV) / (9.80665f * Math.Log(StartMass / s.EndMass)) + Isp = StartMass == s.EndMass ? 0 : (DeltaV + s.DeltaV) / (9.80665f * Math.Log(StartMass / s.EndMass)) }; } } diff --git a/MechJeb2/Maneuver/OperationResonantOrbit.cs b/MechJeb2/Maneuver/OperationResonantOrbit.cs index 4ff106c03..bb68c589c 100644 --- a/MechJeb2/Maneuver/OperationResonantOrbit.cs +++ b/MechJeb2/Maneuver/OperationResonantOrbit.cs @@ -22,7 +22,8 @@ public class OperationResonantOrbit : Operation public OperationResonantOrbit() { - _timeSelector = new TimeSelector(new[] { TimeReference.APOAPSIS, TimeReference.PERIAPSIS, TimeReference.X_FROM_NOW, TimeReference.ALTITUDE }); + _timeSelector = + new TimeSelector(new[] { TimeReference.APOAPSIS, TimeReference.PERIAPSIS, TimeReference.X_FROM_NOW, TimeReference.ALTITUDE }); } public override void DoParametersGUI(Orbit o, double universalTime, MechJebModuleTargetController target) diff --git a/MechJeb2/Maneuver/OperationSemiMajor.cs b/MechJeb2/Maneuver/OperationSemiMajor.cs index 64647b428..b7f70db89 100644 --- a/MechJeb2/Maneuver/OperationSemiMajor.cs +++ b/MechJeb2/Maneuver/OperationSemiMajor.cs @@ -18,7 +18,8 @@ public class OperationSemiMajor : Operation public OperationSemiMajor() { - _timeSelector = new TimeSelector(new[] { TimeReference.APOAPSIS, TimeReference.PERIAPSIS, TimeReference.X_FROM_NOW, TimeReference.ALTITUDE }); + _timeSelector = + new TimeSelector(new[] { TimeReference.APOAPSIS, TimeReference.PERIAPSIS, TimeReference.X_FROM_NOW, TimeReference.ALTITUDE }); } public override void DoParametersGUI(Orbit o, double universalTime, MechJebModuleTargetController target) diff --git a/MechJeb2/Maneuver/TransferCalculator.cs b/MechJeb2/Maneuver/TransferCalculator.cs index 6fb3564aa..e2723c71a 100644 --- a/MechJeb2/Maneuver/TransferCalculator.cs +++ b/MechJeb2/Maneuver/TransferCalculator.cs @@ -238,7 +238,8 @@ private static ManeuverParameters ComputeEjectionManeuver(Vector3d exitVelocity, { Dispatcher.InvokeAsync(() => { - Debug.Log($"[MechJeb TransferCalculator] BUG mu = {initialOrbit.referenceBody.gravParameter} r0 = {r0} v0 = {v0} vinf = {exitVelocity}"); + Debug.Log( + $"[MechJeb TransferCalculator] BUG mu = {initialOrbit.referenceBody.gravParameter} r0 = {r0} v0 = {v0} vinf = {exitVelocity}"); }); } diff --git a/MechJeb2/MechJeb2.csproj b/MechJeb2/MechJeb2.csproj index e7a7dbe0e..6b7def2d2 100644 --- a/MechJeb2/MechJeb2.csproj +++ b/MechJeb2/MechJeb2.csproj @@ -1,6 +1,6 @@  - + Debug AnyCPU @@ -12,7 +12,7 @@ v4.8 true 512 - + @@ -41,263 +41,263 @@ MechJeb2.ruleset - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - - - - - + + + + + + + @@ -359,12 +359,12 @@ False - + - + - + - - + + - + - - - - + + + + - - + + - - + + - - - - + + + + - + - + @@ -112,19 +114,26 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + - + shader;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - shader2;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + shader2;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + - shader3;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + shader3;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + - \ No newline at end of file + diff --git a/MechJeb2/ReentrySimulation.cs b/MechJeb2/ReentrySimulation.cs index 31b84f6bc..bc210b47d 100644 --- a/MechJeb2/ReentrySimulation.cs +++ b/MechJeb2/ReentrySimulation.cs @@ -44,7 +44,7 @@ public partial class ReentrySimulation // FIXME: that's a lie, its used all over the place. private CelestialBody _mainBody; - private double _maxThrustAccel; + private double _maxThrustAccel; // This is the height of the ground at the point we think we will land. It is infact calculated by getting the height of the previous prediction. It is used to decide when the parachutes will be deployed. private double _probableLandingSiteASL; diff --git a/MechJeb2/ReentrySimulation/SimCurves.cs b/MechJeb2/ReentrySimulation/SimCurves.cs index 835a666fd..6b445667e 100644 --- a/MechJeb2/ReentrySimulation/SimCurves.cs +++ b/MechJeb2/ReentrySimulation/SimCurves.cs @@ -48,7 +48,7 @@ private void Setup(CelestialBody newBody) _dragCurveTip = new FloatCurve(PhysicsGlobals.SurfaceCurves.dragCurveTip.Curve.keys); _liftCurve = new FloatCurve(PhysicsGlobals.BodyLiftCurve.liftCurve.Curve.keys); - LiftMachCurve = new FloatCurve(PhysicsGlobals.BodyLiftCurve.liftMachCurve.Curve.keys); + LiftMachCurve = new FloatCurve(PhysicsGlobals.BodyLiftCurve.liftMachCurve.Curve.keys); _dragCurve = new FloatCurve(PhysicsGlobals.BodyLiftCurve.dragCurve.Curve.keys); _dragMachCurve = new FloatCurve(PhysicsGlobals.BodyLiftCurve.dragMachCurve.Curve.keys); diff --git a/MechJeb2/VesselState.cs b/MechJeb2/VesselState.cs index 6f89ea864..e4a6dc142 100644 --- a/MechJeb2/VesselState.cs +++ b/MechJeb2/VesselState.cs @@ -1,66 +1,79 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Linq; -using Smooth.Pools; -using UnityEngine; using System.Reflection; using KSP.Localization; +using Smooth.Pools; +using UnityEngine; namespace MuMech { public class VesselState { - public static bool isLoadedPrincipia = false; - public static bool isLoadedProceduralFairing = false; - public static bool isLoadedRealFuels = false; + public static bool isLoadedPrincipia; + public static bool isLoadedProceduralFairing; + + public static bool isLoadedRealFuels; + // RealFuels.ModuleEngineRF ullageSet field to call via reflection public static FieldInfo RFullageSetField; + // RealFuels.ModuleEngineRF ignitions field to call via reflection public static FieldInfo RFignitionsField; + // RealFuels.ModuleEngineRF ignited field to call via reflection public static FieldInfo RFignitedField; + // RealFuels.ModuleEngineRF ullage field to call via reflection public static FieldInfo RFullageField; + // RealFuels.Ullage.UllageSet GetUllageStability method to call via reflection public static MethodInfo RFGetUllageStabilityMethod; + // RealFuels.Ullage.UllageSimulator fields to determine ullage status - public static double RFveryStableValue; + public static double RFveryStableValue; private static double RFstableValue; private static double RFriskyValue; private static double RFveryRiskyValue; private static double RFunstableValue; - public enum UllageState { + public enum UllageState + { VeryUnstable, Unstable, VeryRisky, Risky, Stable, - VeryStable // "Nominal" also winds up here + VeryStable // "Nominal" also winds up here } // lowestUllage is always VeryStable without RealFuels installed - public UllageState lowestUllage { get { return this.einfo.lowestUllage; } } + public UllageState lowestUllage => einfo.lowestUllage; + + public static bool isLoadedFAR; - public static bool isLoadedFAR = false; private delegate double FARVesselDelegate(Vessel v); + private static FARVesselDelegate FARVesselDragCoeff; private static FARVesselDelegate FARVesselRefArea; private static FARVesselDelegate FARVesselTermVelEst; private static FARVesselDelegate FARVesselDynPres; - private delegate void FARCalculateVesselAeroForcesDelegate(Vessel vessel, out Vector3 aeroForce, out Vector3 aeroTorque, Vector3 velocityWorldVector, double altitude); + + private delegate void FARCalculateVesselAeroForcesDelegate(Vessel vessel, out Vector3 aeroForce, out Vector3 aeroTorque, + Vector3 velocityWorldVector, double altitude); + private static FARCalculateVesselAeroForcesDelegate FARCalculateVesselAeroForces; - private Vessel vesselRef = null; + private Vessel vesselRef; + + private readonly EngineInfo einfo = new EngineInfo(); + private readonly IntakeInfo iinfo = new IntakeInfo(); + public readonly List enginesWrappers = new List(); - private readonly EngineInfo einfo = new EngineInfo(); - private readonly IntakeInfo iinfo = new IntakeInfo(); - public readonly List enginesWrappers = new List(); + [ValueInfoItem("#MechJeb_UniversalTime", InfoItem.Category.Recorder, format = ValueInfoItem.TIME)] //Universal Time + public double time; //planetarium time - [ValueInfoItem("#MechJeb_UniversalTime", InfoItem.Category.Recorder, format = ValueInfoItem.TIME)]//Universal Time - public double time; //planetarium time - public double deltaT; //TimeWarp.fixedDeltaTime + public double deltaT; //TimeWarp.fixedDeltaTime public Vector3d CoM; public Vector3d MoI; //Diagonal components of the inertia tensor (almost always the dominant components) @@ -68,7 +81,7 @@ public enum UllageState { public Vector3d up; public Vector3d north; public Vector3d east; - public Vector3d forward; //the direction the vessel is pointing + public Vector3d forward; //the direction the vessel is pointing public Vector3d horizontalOrbit; //unit vector in the direction of horizontal component of orbit velocity public Vector3d horizontalSurface; //unit vector in the direction of horizontal component of surface velocity public Vector3d rootPartPos; @@ -85,205 +98,237 @@ public enum UllageState { public Vector3d angularVelocity; public Vector3d angularMomentum; - public Vector3d radialPlus; //unit vector in the plane of up and velocityVesselOrbit and perpendicular to velocityVesselOrbit + public Vector3d radialPlus; //unit vector in the plane of up and velocityVesselOrbit and perpendicular to velocityVesselOrbit public Vector3d radialPlusSurface; //unit vector in the plane of up and velocityVesselSurface and perpendicular to velocityVesselSurface - public Vector3d normalPlus; //unit vector perpendicular to up and velocityVesselOrbit - public Vector3d normalPlusSurface; //unit vector perpendicular to up and velocityVesselSurface + public Vector3d normalPlus; //unit vector perpendicular to up and velocityVesselOrbit + public Vector3d normalPlusSurface; //unit vector perpendicular to up and velocityVesselSurface public Vector3d gravityForce; - [ValueInfoItem("#MechJeb_LocalGravity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "m/s²")]//Local gravity - public double localg; //magnitude of gravityForce + + [ValueInfoItem("#MechJeb_LocalGravity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "m/s²")] //Local gravity + public double localg; //magnitude of gravityForce //How about changing these so we store the instantaneous values and *also* //the smoothed MovingAverages? Sometimes we need the instantaneous value. - [ValueInfoItem("#MechJeb_OrbitalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")]//Orbital speed + [ValueInfoItem("#MechJeb_OrbitalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")] //Orbital speed public MovingAverage speedOrbital = new MovingAverage(); - [ValueInfoItem("#MechJeb_SurfaceSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")]//Surface speed + + [ValueInfoItem("#MechJeb_SurfaceSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")] //Surface speed public MovingAverage speedSurface = new MovingAverage(); - [ValueInfoItem("#MechJeb_VerticalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")]//Vertical speed + + [ValueInfoItem("#MechJeb_VerticalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")] //Vertical speed public MovingAverage speedVertical = new MovingAverage(); - [ValueInfoItem("#MechJeb_SurfaceHorizontalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")]//Surface horizontal speed + + [ValueInfoItem("#MechJeb_SurfaceHorizontalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, + units = "m/s")] //Surface horizontal speed public MovingAverage speedSurfaceHorizontal = new MovingAverage(); - [ValueInfoItem("#MechJeb_OrbitHorizontalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")]//Orbit horizontal speed + + [ValueInfoItem("#MechJeb_OrbitHorizontalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")] //Orbit horizontal speed public double speedOrbitHorizontal; - [ValueInfoItem("#MechJeb_Heading", InfoItem.Category.Surface, format = "F1", units = "º")]//Heading + + [ValueInfoItem("#MechJeb_Heading", InfoItem.Category.Surface, format = "F1", units = "º")] //Heading public MovingAverage vesselHeading = new MovingAverage(); - [ValueInfoItem("#MechJeb_Pitch", InfoItem.Category.Surface, format = "F1", units = "º")]//Pitch + + [ValueInfoItem("#MechJeb_Pitch", InfoItem.Category.Surface, format = "F1", units = "º")] //Pitch public MovingAverage vesselPitch = new MovingAverage(); - [ValueInfoItem("#MechJeb_Roll", InfoItem.Category.Surface, format = "F1", units = "º")]//Roll + + [ValueInfoItem("#MechJeb_Roll", InfoItem.Category.Surface, format = "F1", units = "º")] //Roll public MovingAverage vesselRoll = new MovingAverage(); - [ValueInfoItem("#MechJeb_Altitude_ASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")]//Altitude (ASL) + + [ValueInfoItem("#MechJeb_Altitude_ASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Altitude (ASL) public MovingAverage altitudeASL = new MovingAverage(); - [ValueInfoItem("#MechJeb_Altitude_true", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")]//Altitude (true) + + [ValueInfoItem("#MechJeb_Altitude_true", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Altitude (true) public MovingAverage altitudeTrue = new MovingAverage(); - [ValueInfoItem("#MechJeb_SurfaceAltitudeASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 4, units = "m")]//Surface altitude ASL + + [ValueInfoItem("#MechJeb_SurfaceAltitudeASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 4, + units = "m")] //Surface altitude ASL public double surfaceAltitudeASL; - [ValueInfoItem("#MechJeb_Apoapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6, category = InfoItem.Category.Orbit)]//Apoapsis + [ValueInfoItem("#MechJeb_Apoapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6, + category = InfoItem.Category.Orbit)] //Apoapsis public MovingAverage orbitApA = new MovingAverage(); - [ValueInfoItem("#MechJeb_Periapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6, category = InfoItem.Category.Orbit)]//Periapsis + + [ValueInfoItem("#MechJeb_Periapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6, + category = InfoItem.Category.Orbit)] //Periapsis public MovingAverage orbitPeA = new MovingAverage(); - [ValueInfoItem("#MechJeb_OrbitalPeriod", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 2, category = InfoItem.Category.Orbit)]//Orbital period + + [ValueInfoItem("#MechJeb_OrbitalPeriod", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 2, + category = InfoItem.Category.Orbit)] //Orbital period public MovingAverage orbitPeriod = new MovingAverage(); - [ValueInfoItem("#MechJeb_TimeToApoapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)]//Time to apoapsis + + [ValueInfoItem("#MechJeb_TimeToApoapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)] //Time to apoapsis public MovingAverage orbitTimeToAp = new MovingAverage(); - [ValueInfoItem("#MechJeb_TimeToPeriapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)]//Time to periapsis + + [ValueInfoItem("#MechJeb_TimeToPeriapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)] //Time to periapsis public MovingAverage orbitTimeToPe = new MovingAverage(); - [ValueInfoItem("#MechJeb_LAN", InfoItem.Category.Orbit, format = ValueInfoItem.ANGLE)]//LAN + + [ValueInfoItem("#MechJeb_LAN", InfoItem.Category.Orbit, format = ValueInfoItem.ANGLE)] //LAN public MovingAverage orbitLAN = new MovingAverage(); - [ValueInfoItem("#MechJeb_ArgumentOfPeriapsis", InfoItem.Category.Orbit, format = "F1", units = "º")]//Argument of periapsis + + [ValueInfoItem("#MechJeb_ArgumentOfPeriapsis", InfoItem.Category.Orbit, format = "F1", units = "º")] //Argument of periapsis public MovingAverage orbitArgumentOfPeriapsis = new MovingAverage(); - [ValueInfoItem("#MechJeb_Inclination", InfoItem.Category.Orbit, format = "F3", units = "º")]//Inclination + + [ValueInfoItem("#MechJeb_Inclination", InfoItem.Category.Orbit, format = "F3", units = "º")] //Inclination public MovingAverage orbitInclination = new MovingAverage(); - [ValueInfoItem("#MechJeb_Eccentricity", InfoItem.Category.Orbit, format = "F3")]//Eccentricity + + [ValueInfoItem("#MechJeb_Eccentricity", InfoItem.Category.Orbit, format = "F3")] //Eccentricity public MovingAverage orbitEccentricity = new MovingAverage(); - [ValueInfoItem("#MechJeb_SemiMajorAxis", InfoItem.Category.Orbit, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")]//Semi-major axis + + [ValueInfoItem("#MechJeb_SemiMajorAxis", InfoItem.Category.Orbit, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Semi-major axis public MovingAverage orbitSemiMajorAxis = new MovingAverage(); + [ValueInfoItem("Celestial Longitude", InfoItem.Category.Orbit, format = "F3")] public MovingAverage celestialLongitude = new MovingAverage(); - [ValueInfoItem("#MechJeb_Latitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_NS)]//Latitude + + [ValueInfoItem("#MechJeb_Latitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_NS)] //Latitude public MovingAverage latitude = new MovingAverage(); - [ValueInfoItem("#MechJeb_Longitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_EW)]//Longitude + + [ValueInfoItem("#MechJeb_Longitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_EW)] //Longitude public MovingAverage longitude = new MovingAverage(); - [ValueInfoItem("#MechJeb_AngleOfAttack", InfoItem.Category.Misc, format = "F2", units = "º")]//Angle of Attack + + [ValueInfoItem("#MechJeb_AngleOfAttack", InfoItem.Category.Misc, format = "F2", units = "º")] //Angle of Attack public MovingAverage AoA = new MovingAverage(); - [ValueInfoItem("#MechJeb_AngleOfSideslip", InfoItem.Category.Misc, format = "F2", units = "º")]//Angle of Sideslip + + [ValueInfoItem("#MechJeb_AngleOfSideslip", InfoItem.Category.Misc, format = "F2", units = "º")] //Angle of Sideslip public MovingAverage AoS = new MovingAverage(); - [ValueInfoItem("#MechJeb_DisplacementAngle", InfoItem.Category.Misc, format = "F2", units = "º")]//Displacement Angle + + [ValueInfoItem("#MechJeb_DisplacementAngle", InfoItem.Category.Misc, format = "F2", units = "º")] //Displacement Angle public MovingAverage displacementAngle = new MovingAverage(); public MovingAverage3d angularVelocityAvg = new MovingAverage3d(5); // instantaneous values - public double currentPitch - { - get - { - return (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x; - } - } + public double currentPitch => rotationVesselSurface.eulerAngles.x > 180 + ? 360.0 - rotationVesselSurface.eulerAngles.x + : -rotationVesselSurface.eulerAngles.x; - public double currentRoll - { - get - { - return (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z; - } - } + public double currentRoll => rotationVesselSurface.eulerAngles.z > 180 + ? rotationVesselSurface.eulerAngles.z - 360.0 + : rotationVesselSurface.eulerAngles.z; - public double currentHeading - { - get - { - return rotationVesselSurface.eulerAngles.y; - } - } + public double currentHeading => rotationVesselSurface.eulerAngles.y; - public double radius; //distance from planet center + public double radius; //distance from planet center public double mass; // Thrust is a vector. These are in the same frame of reference as forward and other vectors. - public Vector3d thrustVectorLastFrame = new Vector3d(); - public Vector3d thrustVectorMaxThrottle = new Vector3d(); - public Vector3d thrustVectorMinThrottle = new Vector3d(); + public Vector3d thrustVectorLastFrame; + public Vector3d thrustVectorMaxThrottle; + public Vector3d thrustVectorMinThrottle; // Thrust in the forward direction (for historical reasons). - public double thrustAvailable { get { return Vector3d.Dot(thrustVectorMaxThrottle, forward); } } - public double thrustMinimum { get { return Vector3d.Dot(thrustVectorMinThrottle, forward); } } - public double thrustCurrent { get { return Vector3d.Dot(thrustVectorLastFrame, forward); } } + public double thrustAvailable => Vector3d.Dot(thrustVectorMaxThrottle, forward); + public double thrustMinimum => Vector3d.Dot(thrustVectorMinThrottle, forward); + public double thrustCurrent => Vector3d.Dot(thrustVectorLastFrame, forward); // Forward direction of thrust (CoT-CoM).normalized public Vector3d thrustForward; // Acceleration in the forward direction, for when dividing by mass is too complicated. - public double maxThrustAccel { get { return thrustAvailable / mass; } } - public double minThrustAccel { get { return thrustMinimum / mass; } } - public double currentThrustAccel { get { return thrustCurrent / mass; } } + public double maxThrustAccel => thrustAvailable / mass; + public double minThrustAccel => thrustMinimum / mass; + public double currentThrustAccel => thrustCurrent / mass; - public double maxEngineResponseTime = 0; + public double maxEngineResponseTime; + + public bool rcsThrust; - public bool rcsThrust = false; /* the current throttle limit, this may include transient condition such as limiting to zero due to unstable propellants in RF */ public float throttleLimit = 1; + /* the fixed throttle limit (i.e. user limited in the GUI), does not include transient conditions as limiting to zero due to unstable propellants in RF */ - public float throttleFixedLimit = 1; - public double limitedMaxThrustAccel { get { return maxThrustAccel * throttleFixedLimit + minThrustAccel * (1 - throttleFixedLimit); } } + public float throttleFixedLimit = 1; + public double limitedMaxThrustAccel => maxThrustAccel * throttleFixedLimit + minThrustAccel * (1 - throttleFixedLimit); public Vector3d CoT; public Vector3d DoT; - public double CoTScalar; - + public double CoTScalar; public Vector3d pureDragV; - [ValueInfoItem("#MechJeb_PureDrag", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")]//Pure Drag + + [ValueInfoItem("#MechJeb_PureDrag", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Pure Drag public double pureDrag; public Vector3d pureLiftV; - [ValueInfoItem("#MechJeb_PureLift", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")]//Pure Lift + + [ValueInfoItem("#MechJeb_PureLift", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Pure Lift public double pureLift; // Drag is the force (pureDrag + PureLift) applied opposite of the surface vel public double drag; + // Drag is the force (pureDrag + PureLift) applied in the "Up" direction public double dragUp; + // Lift is the force (pureDrag + PureLift) applied in the "Lift" direction public double lift; + // Lift is the force (pureDrag + PureLift) applied in the "Up" direction public double liftUp; public Vector3d CoL; - public double CoLScalar; + public double CoLScalar; - - [ValueInfoItem("#MechJeb_Mach", InfoItem.Category.Vessel, format = "F2")]//Mach + [ValueInfoItem("#MechJeb_Mach", InfoItem.Category.Vessel, format = "F2")] //Mach public double mach; - [ValueInfoItem("#MechJeb_SpeedOfSound", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s")]//Speed of sound + [ValueInfoItem("#MechJeb_SpeedOfSound", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s")] //Speed of sound public double speedOfSound; - [ValueInfoItem("#MechJeb_DragCoefficient", InfoItem.Category.Vessel, format = "F2")]//Drag Coefficient + [ValueInfoItem("#MechJeb_DragCoefficient", InfoItem.Category.Vessel, format = "F2")] //Drag Coefficient public double dragCoef; // Product of the drag surface area, drag coefficient and the physic multiplers public double areaDrag; public double atmosphericDensity; - [ValueInfoItem("#MechJeb_AtmosphereDensity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "g/m³")]//Atmosphere density + + [ValueInfoItem("#MechJeb_AtmosphereDensity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "g/m³")] //Atmosphere density public double atmosphericDensityGrams; - [ValueInfoItem("#MechJeb_MaxDynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")]//Max dynamic pressure + + [ValueInfoItem("#MechJeb_MaxDynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")] //Max dynamic pressure public double maxDynamicPressure; - [ValueInfoItem("#MechJeb_DynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")]//Dynamic pressure + + [ValueInfoItem("#MechJeb_DynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")] //Dynamic pressure public double dynamicPressure; - [ValueInfoItem("#MechJeb_IntakeAir", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")]//Intake air + + [ValueInfoItem("#MechJeb_IntakeAir", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air public double intakeAir; - [ValueInfoItem("#MechJeb_IntakeAirAllIntakes", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")]//Intake air (all intakes open) + + [ValueInfoItem("#MechJeb_IntakeAirAllIntakes", InfoItem.Category.Vessel, format = ValueInfoItem.SI, + units = "kg/s")] //Intake air (all intakes open) public double intakeAirAllIntakes; - [ValueInfoItem("#MechJeb_IntakeAirNeeded", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")]//Intake air needed + + [ValueInfoItem("#MechJeb_IntakeAirNeeded", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air needed public double intakeAirNeeded; - [ValueInfoItem("#MechJeb_intakeAirAtMax", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")]//Intake air needed (max) + + [ValueInfoItem("#MechJeb_intakeAirAtMax", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air needed (max) public double intakeAirAtMax; - [ValueInfoItem("#MechJeb_AngleToPrograde", InfoItem.Category.Orbit, format = "F2", units = "º")]//Angle to prograde + + [ValueInfoItem("#MechJeb_AngleToPrograde", InfoItem.Category.Orbit, format = "F2", units = "º")] //Angle to prograde public double angleToPrograde; - [ValueInfoItem("#MechJeb_AerothermalFlux", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "W/m²")]//Aerothermal flux + + [ValueInfoItem("#MechJeb_AerothermalFlux", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "W/m²")] //Aerothermal flux public double freeMolecularAerothermalFlux; public Vector6 rcsThrustAvailable = new Vector6(); // thrust available from RCS thrusters public Vector6 rcsTorqueAvailable = new Vector6(); // torque available from RCS thrusters - // Total torque public Vector3d torqueAvailable; public Vector3d torqueReactionSpeed; // Torque from different components - public Vector6 torqueReactionWheel = new Vector6(); // torque available from Reaction wheels + public Vector6 torqueReactionWheel = new Vector6(); // torque available from Reaction wheels + //public Vector6 torqueRcs = new Vector6(); // torque available from RCS from stock code (not working properly ATM) public Vector6 torqueControlSurface = new Vector6(); // torque available from Aerodynamic control surfaces - public Vector6 torqueGimbal = new Vector6(); // torque available from Gimbaled engines - public Vector6 torqueOthers = new Vector6(); // torque available from Mostly FAR + public Vector6 torqueGimbal = new Vector6(); // torque available from Gimbaled engines + public Vector6 torqueOthers = new Vector6(); // torque available from Mostly FAR // Variable part of torque related to differential throttle public Vector3d torqueDiffThrottle; @@ -300,7 +345,8 @@ public double currentHeading // A convenient debug message to display in the UI public static string message; - [GeneralInfoItem("#MechJeb_DebugString", InfoItem.Category.Misc, showInEditor = true)]//Debug String + + [GeneralInfoItem("#MechJeb_DebugString", InfoItem.Category.Misc, showInEditor = true)] //Debug String public void DebugString() { GUILayout.BeginVertical(); @@ -310,25 +356,27 @@ public void DebugString() // Callbacks for external module public delegate void VesselStatePartExtension(Part p); + public delegate void VesselStatePartModuleExtension(PartModule pm); private readonly Dictionary engines = new Dictionary(); - public List vesselStatePartExtensions = new List(); + public List vesselStatePartExtensions = new List(); public List vesselStatePartModuleExtensions = new List(); + public delegate double DTerminalVelocity(); - private static bool reflectionInitDone = false; + private static bool reflectionInitDone; public void InitReflection() { - FARVesselDragCoeff = null; - FARVesselRefArea = null; - FARVesselTermVelEst = null; - FARVesselDynPres = null; + FARVesselDragCoeff = null; + FARVesselRefArea = null; + FARVesselTermVelEst = null; + FARVesselDynPres = null; isLoadedProceduralFairing = ReflectionUtils.isAssemblyLoaded("ProceduralFairings"); - isLoadedRealFuels = ReflectionUtils.isAssemblyLoaded("RealFuels"); - isLoadedPrincipia = ReflectionUtils.isAssemblyLoaded("principia.ksp_plugin_adapter"); + isLoadedRealFuels = ReflectionUtils.isAssemblyLoaded("RealFuels"); + isLoadedPrincipia = ReflectionUtils.isAssemblyLoaded("principia.ksp_plugin_adapter"); if (isLoadedRealFuels) { Debug.Log("MechJeb: RealFuels Assembly is loaded"); @@ -338,55 +386,68 @@ public void InitReflection() Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ullageSet field, disabling RF"); isLoadedRealFuels = false; } - RFGetUllageStabilityMethod = ReflectionUtils.getMethodByReflection("RealFuels", "RealFuels.Ullage.UllageSet", "GetUllageStability", BindingFlags.Public|BindingFlags.Instance); + + RFGetUllageStabilityMethod = ReflectionUtils.getMethodByReflection("RealFuels", "RealFuels.Ullage.UllageSet", "GetUllageStability", + BindingFlags.Public | BindingFlags.Instance); if (RFGetUllageStabilityMethod == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSet has no GetUllageStability method, disabling RF"); isLoadedRealFuels = false; } + RFignitionsField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ignitions"); if (RFignitionsField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ignitions field, disabling RF"); isLoadedRealFuels = false; } - RFignitedField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ignited", BindingFlags.NonPublic|BindingFlags.Instance); + + RFignitedField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ignited", + BindingFlags.NonPublic | BindingFlags.Instance); if (RFignitedField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ignited field, disabling RF"); isLoadedRealFuels = false; } + RFullageField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ullage"); if (RFullageField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ullage field, disabling RF"); isLoadedRealFuels = false; } - FieldInfo RFveryStableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryStable", BindingFlags.NonPublic|BindingFlags.Static); + + FieldInfo RFveryStableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryStable", + BindingFlags.NonPublic | BindingFlags.Static); if (RFveryStableField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no veryStable field, disabling RF"); isLoadedRealFuels = false; } + try { - RFveryStableValue = (double) RFveryStableField.GetValue(null); + RFveryStableValue = (double)RFveryStableField.GetValue(null); } catch (Exception e1) { - Debug.Log("MechJeb BUG Exception thrown while getting veryStable value from RealFuels, ullage integration disabled: " + e1.Message); + Debug.Log( + "MechJeb BUG Exception thrown while getting veryStable value from RealFuels, ullage integration disabled: " + e1.Message); isLoadedRealFuels = false; return; } - FieldInfo RFstableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "stable", BindingFlags.NonPublic|BindingFlags.Static); + + FieldInfo RFstableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "stable", + BindingFlags.NonPublic | BindingFlags.Static); if (RFstableField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no stable field, disabling RF"); isLoadedRealFuels = false; } + try { - RFstableValue = (double) RFstableField.GetValue(null); + RFstableValue = (double)RFstableField.GetValue(null); } catch (Exception e2) { @@ -394,15 +455,18 @@ public void InitReflection() isLoadedRealFuels = false; return; } - FieldInfo RFriskyField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "risky", BindingFlags.NonPublic|BindingFlags.Static); + + FieldInfo RFriskyField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "risky", + BindingFlags.NonPublic | BindingFlags.Static); if (RFriskyField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no risky field, disabling RF"); isLoadedRealFuels = false; } + try { - RFriskyValue = (double) RFriskyField.GetValue(null); + RFriskyValue = (double)RFriskyField.GetValue(null); } catch (Exception e3) { @@ -410,31 +474,38 @@ public void InitReflection() isLoadedRealFuels = false; return; } - FieldInfo RFveryRiskyField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryRisky", BindingFlags.NonPublic|BindingFlags.Static); + + FieldInfo RFveryRiskyField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryRisky", + BindingFlags.NonPublic | BindingFlags.Static); if (RFveryRiskyField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no veryRisky field, disabling RF"); isLoadedRealFuels = false; } + try { - RFveryRiskyValue = (double) RFveryRiskyField.GetValue(null); + RFveryRiskyValue = (double)RFveryRiskyField.GetValue(null); } catch (Exception e4) { - Debug.Log("MechJeb BUG Exception thrown while getting veryRisky value from RealFuels, ullage integration disabled: " + e4.Message); + Debug.Log("MechJeb BUG Exception thrown while getting veryRisky value from RealFuels, ullage integration disabled: " + + e4.Message); isLoadedRealFuels = false; return; } - FieldInfo RFunstableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "unstable", BindingFlags.NonPublic|BindingFlags.Static); + + FieldInfo RFunstableField = ReflectionUtils.getFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "unstable", + BindingFlags.NonPublic | BindingFlags.Static); if (RFunstableField == null) { Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no unstable field, disabling RF"); isLoadedRealFuels = false; } + try { - RFunstableValue = (double) RFunstableField.GetValue(null); + RFunstableValue = (double)RFunstableField.GetValue(null); } catch (Exception e5) { @@ -442,23 +513,25 @@ public void InitReflection() isLoadedRealFuels = false; return; } + if (isLoadedRealFuels) { Debug.Log("MechJeb: RealFuels Assembly is wired up properly"); } } + isLoadedFAR = ReflectionUtils.isAssemblyLoaded("FerramAerospaceResearch"); if (isLoadedFAR) { - List farNames = new List { "VesselDragCoeff", "VesselRefArea", "VesselTermVelEst", "VesselDynPres" }; - foreach (var name in farNames) + var farNames = new List { "VesselDragCoeff", "VesselRefArea", "VesselTermVelEst", "VesselDynPres" }; + foreach (string name in farNames) { - var methodInfo = ReflectionUtils.getMethodByReflection( + MethodInfo methodInfo = ReflectionUtils.getMethodByReflection( "FerramAerospaceResearch", "FerramAerospaceResearch.FARAPI", name, BindingFlags.Public | BindingFlags.Static, - new Type[] { typeof(Vessel) } + new[] { typeof(Vessel) } ); if (methodInfo == null) { @@ -467,26 +540,31 @@ public void InitReflection() } else { - typeof(VesselState).GetField("FAR" + name, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, (FARVesselDelegate)Delegate.CreateDelegate(typeof(FARVesselDelegate), methodInfo)); + typeof(VesselState).GetField("FAR" + name, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, + (FARVesselDelegate)Delegate.CreateDelegate(typeof(FARVesselDelegate), methodInfo)); } } - var FARCalculateVesselAeroForcesMethodInfo = ReflectionUtils.getMethodByReflection( + MethodInfo FARCalculateVesselAeroForcesMethodInfo = ReflectionUtils.getMethodByReflection( "FerramAerospaceResearch", "FerramAerospaceResearch.FARAPI", "CalculateVesselAeroForces", BindingFlags.Public | BindingFlags.Static, - new Type[] { typeof(Vessel), typeof(Vector3).MakeByRefType(), typeof(Vector3).MakeByRefType(), typeof(Vector3), typeof(double) } + new[] { typeof(Vessel), typeof(Vector3).MakeByRefType(), typeof(Vector3).MakeByRefType(), typeof(Vector3), typeof(double) } ); - if (FARCalculateVesselAeroForcesMethodInfo == null){ + if (FARCalculateVesselAeroForcesMethodInfo == null) + { Debug.Log("MJ BUG: FAR loaded, but FerramAerospaceResearch.FARAPI has no CalculateVesselAeroForces method, disabling FAR"); isLoadedFAR = false; } else { - FARCalculateVesselAeroForces = (FARCalculateVesselAeroForcesDelegate)Delegate.CreateDelegate(typeof(FARCalculateVesselAeroForcesDelegate), FARCalculateVesselAeroForcesMethodInfo); + FARCalculateVesselAeroForces = + (FARCalculateVesselAeroForcesDelegate)Delegate.CreateDelegate(typeof(FARCalculateVesselAeroForcesDelegate), + FARCalculateVesselAeroForcesMethodInfo); } } + reflectionInitDone = true; } @@ -518,7 +596,8 @@ public bool Update(Vessel vessel) if (time == Planetarium.GetUniversalTime()) return true; - if (vessel.rootPart.rb == null) return false; //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions. + if (vessel.rootPart.rb == null) + return false; //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions. TestStuff(vessel); @@ -633,24 +712,22 @@ private void TestStuff(Vessel vessel) //ListPool.Instance. } - // TODO memo for later. egg found out that vessel.pos is actually 1 frame in the future while vessel.obt_vel is not. // This should have changed in 1.1 // This most likely has some impact on the code. - - void UpdateVelocityAndCoM(Vessel vessel) + private void UpdateVelocityAndCoM(Vessel vessel) { - mass = vessel.totalMass; - CoM = vessel.CoMD; + mass = vessel.totalMass; + CoM = vessel.CoMD; orbitalVelocity = vessel.obt_velocity; orbitalPosition = CoM - vessel.mainBody.position; } // Calculate a bunch of simple quantities each frame. - void UpdateBasicInfo(Vessel vessel) + private void UpdateBasicInfo(Vessel vessel) { - time = Planetarium.GetUniversalTime(); + time = Planetarium.GetUniversalTime(); deltaT = TimeWarp.fixedDeltaTime; //CoM = °; @@ -659,54 +736,59 @@ void UpdateBasicInfo(Vessel vessel) Rigidbody rigidBody = vessel.rootPart.rb; if (rigidBody != null) rootPartPos = rigidBody.position; - north = vessel.north; - east = vessel.east; - forward = vessel.GetTransform().up; + north = vessel.north; + east = vessel.east; + forward = vessel.GetTransform().up; rotationSurface = Quaternion.LookRotation(north, up); - rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface); + rotationVesselSurface = + Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface); surfaceVelocity = orbitalVelocity - vessel.mainBody.getRFrmVel(CoM); velocityMainBodySurface = rotationSurface * surfaceVelocity; - horizontalOrbit = Vector3d.Exclude(up, orbitalVelocity).normalized; + horizontalOrbit = Vector3d.Exclude(up, orbitalVelocity).normalized; horizontalSurface = Vector3d.Exclude(up, surfaceVelocity).normalized; angularVelocity = vessel.angularVelocity; radialPlusSurface = Vector3d.Exclude(surfaceVelocity, up).normalized; - radialPlus = Vector3d.Exclude(orbitalVelocity, up).normalized; + radialPlus = Vector3d.Exclude(orbitalVelocity, up).normalized; normalPlusSurface = -Vector3d.Cross(radialPlusSurface, surfaceVelocity.normalized); - normalPlus = -Vector3d.Cross(radialPlus, orbitalVelocity.normalized); + normalPlus = -Vector3d.Cross(radialPlus, orbitalVelocity.normalized); mach = vessel.mach; gravityForce = FlightGlobals.getGeeForceAtPosition(CoM); // TODO vessel.gravityForPos or vessel.gravityTrue - localg = gravityForce.magnitude; + localg = gravityForce.magnitude; - speedOrbital.value = orbitalVelocity.magnitude; - speedSurface.value = surfaceVelocity.magnitude; + speedOrbital.value = orbitalVelocity.magnitude; + speedSurface.value = surfaceVelocity.magnitude; speedVertical.value = Vector3d.Dot(surfaceVelocity, up); - speedSurfaceHorizontal.value = Vector3d.Exclude(up, surfaceVelocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude; - speedOrbitHorizontal = (orbitalVelocity - (speedVertical * up)).magnitude; + speedSurfaceHorizontal.value = + Vector3d.Exclude(up, surfaceVelocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude; + speedOrbitHorizontal = (orbitalVelocity - speedVertical * up).magnitude; // Angle of Attack, angle between surface velocity and the ship-nose vector (KSP "up" vector) in the plane that has no ship-right/left in it - Vector3 srfProj = Vector3.ProjectOnPlane(surfaceVelocity.normalized, vessel.ReferenceTransform.right); - double tmpAoA = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.forward), Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up) ); + var srfProj = Vector3.ProjectOnPlane(surfaceVelocity.normalized, vessel.ReferenceTransform.right); + double tmpAoA = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.forward), + Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up)); AoA.value = double.IsNaN(tmpAoA) || speedSurface.value < 0.01 ? 0 : tmpAoA; // Angle of Sideslip, angle between surface velocity and the ship-nose vector (KSP "up" vector) in the plane that has no ship-top/bottom in it (KSP "forward"/"back") srfProj = Vector3.ProjectOnPlane(surfaceVelocity.normalized, vessel.ReferenceTransform.forward); - double tmpAoS = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.right), Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up) ); + double tmpAoS = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.right), + Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up)); AoS.value = double.IsNaN(tmpAoS) || speedSurface.value < 0.01 ? 0 : tmpAoS; // Displacement Angle, angle between surface velocity and the ship-nose vector (KSP "up" vector) -- ignores roll of the craft (0 to 180 degrees) - double tempAoD = UtilMath.Rad2Deg * Math.Acos(MuUtils.Clamp(Vector3.Dot(vessel.ReferenceTransform.up, surfaceVelocity.normalized), -1, 1)); + double tempAoD = UtilMath.Rad2Deg * + Math.Acos(MuUtils.Clamp(Vector3.Dot(vessel.ReferenceTransform.up, surfaceVelocity.normalized), -1, 1)); displacementAngle.value = double.IsNaN(tempAoD) || speedSurface.value < 0.01 ? 0 : tempAoD; vesselHeading.value = currentHeading; - vesselPitch.value = currentPitch; - vesselRoll.value = currentRoll; + vesselPitch.value = currentPitch; + vesselRoll.value = currentRoll; altitudeASL.value = vessel.mainBody.GetAltitude(CoM); @@ -720,7 +802,7 @@ void UpdateBasicInfo(Vessel vessel) double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody); //if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6) atmosphericPressure = 0; double temperature = FlightGlobals.getExternalTemperature(altitudeASL); - atmosphericDensity = FlightGlobals.getAtmDensity(atmosphericPressure, temperature); + atmosphericDensity = FlightGlobals.getAtmDensity(atmosphericPressure, temperature); atmosphericDensityGrams = atmosphericDensity * 1000; if (isLoadedFAR) { @@ -730,6 +812,7 @@ void UpdateBasicInfo(Vessel vessel) { dynamicPressure = vessel.dynamicPressurekPa * 1000; } + if (dynamicPressure > maxDynamicPressure) maxDynamicPressure = dynamicPressure; freeMolecularAerothermalFlux = 0.5 * atmosphericDensity * speedSurface * speedSurface * speedSurface; @@ -737,27 +820,28 @@ void UpdateBasicInfo(Vessel vessel) speedOfSound = vessel.speedOfSound; - orbitApA.value = vessel.orbit.ApA; - orbitPeA.value = vessel.orbit.PeA; - orbitPeriod.value = vessel.orbit.period; + orbitApA.value = vessel.orbit.ApA; + orbitPeA.value = vessel.orbit.PeA; + orbitPeriod.value = vessel.orbit.period; orbitTimeToAp.value = vessel.orbit.timeToAp; orbitTimeToPe.value = vessel.orbit.timeToPe; orbitLAN.value = vessel.orbit.LAN; orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis; - orbitInclination.value = vessel.orbit.inclination; - orbitEccentricity.value = vessel.orbit.eccentricity; - orbitSemiMajorAxis.value = vessel.orbit.semiMajorAxis; - celestialLongitude.value = Planetarium.right.AngleInPlane(-Planetarium.up, orbitalPosition); - latitude.value = vessel.mainBody.GetLatitude(CoM); - longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM)); + orbitInclination.value = vessel.orbit.inclination; + orbitEccentricity.value = vessel.orbit.eccentricity; + orbitSemiMajorAxis.value = vessel.orbit.semiMajorAxis; + celestialLongitude.value = Planetarium.right.AngleInPlane(-Planetarium.up, orbitalPosition); + latitude.value = vessel.mainBody.GetLatitude(CoM); + longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM)); if (vessel.mainBody != Planetarium.fetch.Sun) { Vector3d prograde = vessel.mainBody.orbit.getOrbitalVelocityAtUT(time).xzy; Vector3d normal = vessel.mainBody.orbit.GetOrbitNormal().xzy; - angleToPrograde = MuUtils.ClampDegrees360( (((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * orbitalPosition.AngleInPlane(normal, prograde) ); + angleToPrograde = MuUtils.ClampDegrees360((vessel.orbit.inclination > 90 || vessel.orbit.inclination < -90 ? 1 : -1) * + orbitalPosition.AngleInPlane(normal, prograde)); } else { @@ -771,7 +855,7 @@ void UpdateBasicInfo(Vessel vessel) vesselRef = vessel; } - void UpdateRCSThrustAndTorque(Vessel vessel) + private void UpdateRCSThrustAndTorque(Vessel vessel) { rcsThrustAvailable.Reset(); rcsTorqueAvailable.Reset(); @@ -781,14 +865,14 @@ void UpdateRCSThrustAndTorque(Vessel vessel) if (!vessel.ActionGroups[KSPActionGroup.RCS]) return; - var rcsbal = vessel.GetMasterMechJeb().rcsbal; + MechJebModuleRCSBalancer rcsbal = vessel.GetMasterMechJeb().rcsbal; if (rcsbal.enabled) { Vector3d rot = Vector3d.zero; for (int i = 0; i < Vector6.Values.Length; i++) { Vector6.Direction dir6 = Vector6.Values[i]; - Vector3d dir = Vector6.directions[(int) dir6]; + Vector3d dir = Vector6.directions[(int)dir6]; double[] throttles; List thrusters; rcsbal.GetThrottles(dir, out throttles, out thrusters); @@ -815,7 +899,7 @@ void UpdateRCSThrustAndTorque(Vessel vessel) Part p = vessel.parts[i]; for (int m = 0; m < p.Modules.Count; m++) { - ModuleRCS rcs = p.Modules[m] as ModuleRCS; + var rcs = p.Modules[m] as ModuleRCS; if (rcs == null) continue; @@ -832,9 +916,9 @@ void UpdateRCSThrustAndTorque(Vessel vessel) if (!p.ShieldedFromAirstream && rcs.rcsEnabled && rcs.isEnabled && !rcs.isJustForShow && !rcs.flameout && rcs.rcs_active) { - Vector3 attitudeControl = new Vector3(rcs.enablePitch ? 1 : 0, rcs.enableRoll ? 1 : 0, rcs.enableYaw ? 1 : 0); + var attitudeControl = new Vector3(rcs.enablePitch ? 1 : 0, rcs.enableRoll ? 1 : 0, rcs.enableYaw ? 1 : 0); - Vector3 translationControl = new Vector3(rcs.enableX ? 1 : 0f, rcs.enableZ ? 1 : 0, rcs.enableY ? 1 : 0); + var translationControl = new Vector3(rcs.enableX ? 1 : 0f, rcs.enableZ ? 1 : 0, rcs.enableY ? 1 : 0); for (int j = 0; j < rcs.thrusterTransforms.Count; j++) { Transform t = rcs.thrusterTransforms[j]; @@ -873,8 +957,10 @@ void UpdateRCSThrustAndTorque(Vessel vessel) // This is a cheap hack to get rcsTorque with the RCS balancer active. if (!rcsbal.enabled) { - rcsThrustAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterThrust), translationControl)); + rcsThrustAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterThrust), + translationControl)); } + Vector3d thrusterTorque = Vector3.Cross(thrusterPosition, thrusterThrust); // Convert in vessel local coordinate @@ -886,28 +972,27 @@ void UpdateRCSThrustAndTorque(Vessel vessel) } } - - [GeneralInfoItem("#MechJeb_RCSTranslation", InfoItem.Category.Vessel, showInEditor = true)]//RCS Translation + [GeneralInfoItem("#MechJeb_RCSTranslation", InfoItem.Category.Vessel, showInEditor = true)] //RCS Translation public void RCSTranslation() { GUILayout.BeginVertical(); - GUILayout.Label(Localizer.Format("#MechJeb_RCSTranslation"));//"RCS Translation" + GUILayout.Label(Localizer.Format("#MechJeb_RCSTranslation")); //"RCS Translation" GUILayout.BeginHorizontal(); - GUILayout.Label("Pos", GUILayout.ExpandWidth(true));// + GUILayout.Label("Pos", GUILayout.ExpandWidth(true)); // GUILayout.Label(MuUtils.PrettyPrint(rcsThrustAvailable.positive), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); - GUILayout.Label("Neg", GUILayout.ExpandWidth(true));// + GUILayout.Label("Neg", GUILayout.ExpandWidth(true)); // GUILayout.Label(MuUtils.PrettyPrint(rcsThrustAvailable.negative), GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); GUILayout.EndVertical(); } - [GeneralInfoItem("#MechJeb_RCSTorque", InfoItem.Category.Vessel, showInEditor = true)]//RCS Torque + [GeneralInfoItem("#MechJeb_RCSTorque", InfoItem.Category.Vessel, showInEditor = true)] //RCS Torque public void RCSTorque() { GUILayout.BeginVertical(); - GUILayout.Label(Localizer.Format("#MechJeb_RCSTorque"));//"RCS Torque" + GUILayout.Label(Localizer.Format("#MechJeb_RCSTorque")); //"RCS Torque" GUILayout.BeginHorizontal(); GUILayout.Label("Pos", GUILayout.ExpandWidth(true)); GUILayout.Label(MuUtils.PrettyPrint(rcsTorqueAvailable.positive), GUILayout.ExpandWidth(false)); @@ -922,15 +1007,17 @@ public void RCSTorque() } //FARCalculateVesselAeroForces(vessel,out farForce,out farTorque,surfaceVelocity,altitudeASL); - private Vector3 lastFarForce, lastFarTorque; - private Vector3d lastSurfaceVelocity; - private double lastAltitudeASL; - private float lastAoA; - private const double _dVelocitySqrThreshold = 100; - private const double _dVelocitySqrMinThreshold = 1; - private const double _dAltitudeThreshold = 300; - private const float _fAoAThreshold = 2; - private void CalculateVesselAeroForcesWithCache(Vessel v, out Vector3 farForce, out Vector3 farTorque, Vector3d surfaceVelocity, double altitudeASL) + private Vector3 lastFarForce, lastFarTorque; + private Vector3d lastSurfaceVelocity; + private double lastAltitudeASL; + private float lastAoA; + private const double _dVelocitySqrThreshold = 100; + private const double _dVelocitySqrMinThreshold = 1; + private const double _dAltitudeThreshold = 300; + private const float _fAoAThreshold = 2; + + private void CalculateVesselAeroForcesWithCache(Vessel v, out Vector3 farForce, out Vector3 farTorque, Vector3d surfaceVelocity, + double altitudeASL) { float AoA = Vector3.Angle(v.rootPart.transform.TransformDirection(Vector3.up), surfaceVelocity); if ((lastSurfaceVelocity - surfaceVelocity).sqrMagnitude > _dVelocitySqrThreshold @@ -939,26 +1026,27 @@ private void CalculateVesselAeroForcesWithCache(Vessel v, out Vector3 farForce, { FARCalculateVesselAeroForces(v, out farForce, out farTorque, surfaceVelocity, altitudeASL); lastSurfaceVelocity = surfaceVelocity; - lastAltitudeASL = altitudeASL; - lastAoA = AoA; - lastFarForce = farForce; - lastFarTorque = farTorque; - } else + lastAltitudeASL = altitudeASL; + lastAoA = AoA; + lastFarForce = farForce; + lastFarTorque = farTorque; + } + else { - farForce = lastFarForce; + farForce = lastFarForce; farTorque = lastFarTorque; } } // Loop over all the parts in the vessel and calculate some things. - void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) + private void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) { parachutes.Clear(); parachuteDeployed = false; torqueAvailable = Vector3d.zero; - Vector6 torqueReactionSpeed6 = new Vector6(); + var torqueReactionSpeed6 = new Vector6(); torqueReactionWheel.Reset(); torqueControlSurface.Reset(); @@ -979,12 +1067,12 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) areaDrag = 0; } - CoL = Vector3d.zero; + CoL = Vector3d.zero; CoLScalar = 0; - CoT = Vector3d.zero; - DoT = Vector3d.zero; - CoTScalar = 0; + CoT = Vector3d.zero; + DoT = Vector3d.zero; + CoTScalar = 0; thrustForward = Vector3d.zero; for (int i = 0; i < vessel.parts.Count; i++) @@ -1028,14 +1116,14 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) continue; } - ModuleLiftingSurface ls = pm as ModuleLiftingSurface; + var ls = pm as ModuleLiftingSurface; if (ls != null) { partPureLift += ls.liftForce; partPureDrag += ls.dragForce; } - ModuleReactionWheel rw = pm as ModuleReactionWheel; + var rw = pm as ModuleReactionWheel; if (rw != null) { Vector3 pos; @@ -1059,7 +1147,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) } else if (pm is ModuleParachute) { - ModuleParachute parachute = pm as ModuleParachute; + var parachute = pm as ModuleParachute; parachutes.Add(parachute); if (parachute.deploymentState == ModuleParachute.deploymentStates.DEPLOYED || @@ -1070,7 +1158,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) } else if (pm is ModuleControlSurface) // also does ModuleAeroSurface { - ModuleControlSurface cs = (pm as ModuleControlSurface); + var cs = pm as ModuleControlSurface; //if (p.ShieldedFromAirstream || cs.deploy) // continue; @@ -1083,18 +1171,19 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) torqueControlSurface.Add(ctrlTorquePos); torqueControlSurface.Add(ctrlTorqueNeg); - torqueReactionSpeed6.Add(Mathf.Abs(cs.ctrlSurfaceRange) / cs.actuatorSpeed * Vector3d.Max(ctrlTorquePos.Abs(), ctrlTorqueNeg.Abs())); + torqueReactionSpeed6.Add(Mathf.Abs(cs.ctrlSurfaceRange) / cs.actuatorSpeed * + Vector3d.Max(ctrlTorquePos.Abs(), ctrlTorqueNeg.Abs())); } else if (pm is ModuleGimbal) { - ModuleGimbal g = (pm as ModuleGimbal); + var g = pm as ModuleGimbal; if (g.engineMultsList == null) g.CreateEngineList(); for (int j = 0; j < g.engineMultsList.Count; j++) { - var engs = g.engineMultsList[j]; + List> engs = g.engineMultsList[j]; for (int k = 0; k < engs.Count; k++) { engines[engs[k].Key] = g; @@ -1111,7 +1200,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) torqueGimbal.Add(-neg); if (g.useGimbalResponseSpeed) - torqueReactionSpeed6.Add((Mathf.Abs(g.gimbalRange) / g.gimbalResponseSpeed) * Vector3d.Max(pos.Abs(), neg.Abs())); + torqueReactionSpeed6.Add(Mathf.Abs(g.gimbalRange) / g.gimbalResponseSpeed * Vector3d.Max(pos.Abs(), neg.Abs())); } else if (pm is ModuleRCS) { @@ -1119,7 +1208,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) } else if (pm is ITorqueProvider) // All mod that supports it. Including FAR { - ITorqueProvider tp = pm as ITorqueProvider; + var tp = pm as ITorqueProvider; Vector3 pos; Vector3 neg; @@ -1150,7 +1239,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) Vector3d partAeroForce = partPureDrag + partPureLift; - Vector3d partDrag = Vector3d.Project(partAeroForce, -surfaceVelocity); + var partDrag = Vector3d.Project(partAeroForce, -surfaceVelocity); Vector3d partLift = partAeroForce - partDrag; double partLiftScalar = partLift.magnitude; @@ -1158,7 +1247,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) if (p.rb != null && partLiftScalar > 0.01) { CoLScalar += partLiftScalar; - CoL += ((Vector3d)p.rb.worldCenterOfMass + (Vector3d)(p.partTransform.rotation * p.CoLOffset)) * partLiftScalar; + CoL += ((Vector3d)p.rb.worldCenterOfMass + (Vector3d)(p.partTransform.rotation * p.CoLOffset)) * partLiftScalar; } } @@ -1174,7 +1263,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) torqueAvailable += Vector3d.Max(torqueOthers.positive, torqueOthers.negative); // Mostly FAR - torqueDiffThrottle = Vector3d.Max(einfo.torqueDiffThrottle.positive, einfo.torqueDiffThrottle.negative); + torqueDiffThrottle = Vector3d.Max(einfo.torqueDiffThrottle.positive, einfo.torqueDiffThrottle.negative); torqueDiffThrottle.y = 0; if (torqueAvailable.sqrMagnitude > 0) @@ -1189,12 +1278,12 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) thrustVectorMaxThrottle = einfo.thrustMax; thrustVectorMinThrottle = einfo.thrustMin; - thrustVectorLastFrame = einfo.thrustCurrent; + thrustVectorLastFrame = einfo.thrustCurrent; if (CoTScalar > 0) { - CoT = CoT / CoTScalar; - thrustForward = ( CoM - CoT ).normalized; + CoT = CoT / CoTScalar; + thrustForward = (CoM - CoT).normalized; } DoT = DoT.normalized; @@ -1211,16 +1300,16 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) CalculateVesselAeroForcesWithCache(vessel, out farForce, out farTorque, surfaceVelocity, altitudeASL); Vector3d farDragVector = Vector3d.Dot(farForce, -surfaceVelocity.normalized) * -surfaceVelocity.normalized; - drag = farDragVector.magnitude / mass; - dragUp = Vector3d.Dot(farDragVector, up) / mass; + drag = farDragVector.magnitude / mass; + dragUp = Vector3d.Dot(farDragVector, up) / mass; pureDragV = farDragVector; - pureDrag = drag; + pureDrag = drag; Vector3d farLiftVector = Vector3d.Dot(farForce, liftDir) * liftDir; - lift = farLiftVector.magnitude / mass; - liftUp = Vector3d.Dot(farForce, up) / mass; // Use farForce instead of farLiftVector to match code for stock aero + lift = farLiftVector.magnitude / mass; + liftUp = Vector3d.Dot(farForce, up) / mass; // Use farForce instead of farLiftVector to match code for stock aero pureLiftV = farLiftVector; - pureLift = lift; + pureLift = lift; } else { @@ -1245,7 +1334,7 @@ void AnalyzeParts(Vessel vessel, EngineInfo einfo, IntakeInfo iinfo) maxEngineResponseTime = einfo.maxResponseTime; } - [GeneralInfoItem("#MechJeb_Torque", InfoItem.Category.Vessel, showInEditor = true)]//Torque + [GeneralInfoItem("#MechJeb_Torque", InfoItem.Category.Vessel, showInEditor = true)] //Torque public void TorqueCompare() { var reactionTorque = Vector3d.Max(torqueReactionWheel.positive, torqueReactionWheel.negative); @@ -1289,44 +1378,44 @@ public void TorqueCompare() GUILayout.EndHorizontal(); } - void UpdateResourceRequirements(EngineInfo einfo, IntakeInfo iinfo) + private void UpdateResourceRequirements(EngineInfo einfo, IntakeInfo iinfo) { // Convert the resource information from the einfo and iinfo format // to the more useful ResourceInfo format. ResourceInfo.Release(resources.Values); resources.Clear(); - foreach (var info in einfo.resourceRequired) + foreach (KeyValuePair info in einfo.resourceRequired) { int id = info.Key; - var req = info.Value; + EngineInfo.FuelRequirement req = info.Value; resources[id] = ResourceInfo.Borrow( - PartResourceLibrary.Instance.GetDefinition(id), - req.requiredLastFrame, - req.requiredAtMaxThrottle, - iinfo.getIntakes(id), - vesselRef); + PartResourceLibrary.Instance.GetDefinition(id), + req.requiredLastFrame, + req.requiredAtMaxThrottle, + iinfo.getIntakes(id), + vesselRef); } int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id; - intakeAir = 0; - intakeAirNeeded = 0; - intakeAirAtMax = 0; + intakeAir = 0; + intakeAirNeeded = 0; + intakeAirAtMax = 0; intakeAirAllIntakes = 0; if (resources.ContainsKey(intakeAirId)) { - intakeAir = resources[intakeAirId].intakeProvided; + intakeAir = resources[intakeAirId].intakeProvided; intakeAirAllIntakes = resources[intakeAirId].intakeAvailable; - intakeAirNeeded = resources[intakeAirId].required; - intakeAirAtMax = resources[intakeAirId].requiredAtMaxThrottle; + intakeAirNeeded = resources[intakeAirId].required; + intakeAirAtMax = resources[intakeAirId].requiredAtMaxThrottle; } } // Decide whether to control the RCS thrusters from the main throttle - void ToggleRCSThrust(Vessel vessel) + private void ToggleRCSThrust(Vessel vessel) { if (thrustVectorMaxThrottle.magnitude == 0 && vessel.ActionGroups[KSPActionGroup.RCS]) { - rcsThrust = true; + rcsThrust = true; thrustVectorMaxThrottle += forward * rcsThrustAvailable.down; } else @@ -1335,14 +1424,14 @@ void ToggleRCSThrust(Vessel vessel) } } - void UpdateMoIAndAngularMom(Vessel vessel) + private void UpdateMoIAndAngularMom(Vessel vessel) { - MoI = vessel.MOI; - angularMomentum = vessel.angularMomentum; + MoI = vessel.MOI; + angularMomentum = vessel.angularMomentum; angularVelocityAvg.value = angularVelocity; } - [ValueInfoItem("#MechJeb_TerminalVelocity", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s")]//Terminal velocity + [ValueInfoItem("#MechJeb_TerminalVelocity", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s")] //Terminal velocity public double TerminalVelocity() { return TerminalVelocityCall(); @@ -1354,7 +1443,7 @@ public double TerminalVelocityStockKSP() { if (mainBody == null || altitudeASL > mainBody.RealMaxAtmosphereAltitude()) return double.PositiveInfinity; - return Math.Sqrt((2000 * mass * localg) / (areaDrag * vesselRef.atmDensity)); + return Math.Sqrt(2000 * mass * localg / (areaDrag * vesselRef.atmDensity)); } public double TerminalVelocityFAR() @@ -1373,23 +1462,26 @@ public double HeadingFromDirection(Vector3d dir) } // Altitude of bottom of craft, only calculated when requested because it is a bit expensive - private bool altitudeBottomIsCurrent = false; + private bool altitudeBottomIsCurrent; private double _altitudeBottom; - [ValueInfoItem("#MechJeb_Altitude_bottom", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")]//Altitude (bottom) + + [ValueInfoItem("#MechJeb_Altitude_bottom", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, + units = "m")] //Altitude (bottom) public double altitudeBottom { get { if (!altitudeBottomIsCurrent) { - _altitudeBottom = ComputeVesselBottomAltitude(vesselRef); + _altitudeBottom = ComputeVesselBottomAltitude(vesselRef); altitudeBottomIsCurrent = true; } + return _altitudeBottom; } } - double ComputeVesselBottomAltitude(Vessel vessel) + private double ComputeVesselBottomAltitude(Vessel vessel) { if (vessel == null || vessel.rootPart.rb == null) return 0; double ret = altitudeTrue; @@ -1412,6 +1504,7 @@ public double altitudeBottom } } } + return ret; } @@ -1419,11 +1512,13 @@ public double altitudeBottom // variables later. public class EngineInfo { - public Vector3d thrustCurrent = new Vector3d(); // thrust at throttle achieved last frame - public Vector3d thrustMax = new Vector3d(); // thrust at full throttle - public Vector3d thrustMin = new Vector3d(); // thrust at zero throttle - public double maxResponseTime = 0; + public Vector3d thrustCurrent; // thrust at throttle achieved last frame + public Vector3d thrustMax; // thrust at full throttle + public Vector3d thrustMin; // thrust at zero throttle + public double maxResponseTime; + public Vector6 torqueDiffThrottle = new Vector6(); + // lowestUllage is always VeryStable without RealFuels installed public UllageState lowestUllage = UllageState.VeryStable; @@ -1432,18 +1527,19 @@ public struct FuelRequirement public double requiredLastFrame; public double requiredAtMaxThrottle; } + public Dictionary resourceRequired = new Dictionary(); - private Vector3d CoM; - private float atmP0; // pressure now - private float atmP1; // pressure after one timestep - private readonly Queue rotSave = new Queue(); + private Vector3d CoM; + private float atmP0; // pressure now + private float atmP1; // pressure after one timestep + private readonly Queue rotSave = new Queue(); public void Update(Vector3d c, Vessel vessel) { - thrustCurrent = Vector3d.zero; - thrustMax = Vector3d.zero; - thrustMin = Vector3d.zero; + thrustCurrent = Vector3d.zero; + thrustMax = Vector3d.zero; + thrustMin = Vector3d.zero; maxResponseTime = 0; torqueDiffThrottle.Reset(); @@ -1463,7 +1559,7 @@ public void CheckUllageStatus(ModuleEngines e) { // we report stable ullage for an unstable engine which is throttled up, so we let RF kill it // instead of having MJ throttle it down. - if ((e.getFlameoutState) || (!e.EngineIgnited) || (!e.isEnabled) || (e.requestedThrottle > 0.0F)) + if (e.getFlameoutState || !e.EngineIgnited || !e.isEnabled || e.requestedThrottle > 0.0F) { return; } @@ -1530,13 +1626,15 @@ public void CheckUllageStatus(ModuleEngines e) Debug.Log("MechJeb BUG: getting propellantStatus from RealFuels casted to null, ullage status likely broken"); return; } + try { - propellantStability = (double) RFGetUllageStabilityMethod.Invoke(ullageSet, Array.Empty()); + propellantStability = (double)RFGetUllageStabilityMethod.Invoke(ullageSet, Array.Empty()); } catch (Exception e4) { - Debug.Log("MechJeb BUG Exception thrown while calling GetUllageStability from RealFuels, ullage integration disabled: " + e4.Message); + Debug.Log("MechJeb BUG Exception thrown while calling GetUllageStability from RealFuels, ullage integration disabled: " + + e4.Message); RFullageSetField = null; return; } @@ -1567,9 +1665,10 @@ public void CheckUllageStatus(ModuleEngines e) } } - public void AddNewEngine(ModuleEngines e, ModuleGimbal gimbal, List enginesWrappers, ref Vector3d CoT, ref Vector3d DoT, ref double CoTScalar) + public void AddNewEngine(ModuleEngines e, ModuleGimbal gimbal, List enginesWrappers, ref Vector3d CoT, ref Vector3d DoT, + ref double CoTScalar) { - if ((!e.EngineIgnited) || (!e.isEnabled)) + if (!e.EngineIgnited || !e.isEnabled) { return; } @@ -1622,7 +1721,7 @@ public void AddNewEngine(ModuleEngines e, ModuleGimbal gimbal, List> allIntakes = new Dictionary>(); @@ -1719,6 +1818,7 @@ public void Update() { ListPool.Instance.Release(intakes); } + allIntakes.Clear(); } @@ -1734,23 +1834,23 @@ public void addIntake(ModuleResourceIntake intake) } else { - thelist = ListPool.Instance.Borrow(); + thelist = ListPool.Instance.Borrow(); allIntakes[id] = thelist; } + thelist.Add(intake); } private static readonly List empty = new List(); + public List getIntakes(int id) { if (allIntakes.ContainsKey(id)) { return allIntakes[id]; } - else - { - return empty; - } + + return empty; } } @@ -1762,44 +1862,46 @@ public class ResourceInfo // We use kg/s rather than the more common T/s because these numbers tend to be small. // One debate I've had is whether to use mass/s or unit/s. Dunno... - public double required = 0; // kg/s - public double requiredAtMaxThrottle = 0; // kg/s - public double intakeAvailable = 0; // kg/s + public double required; // kg/s + public double requiredAtMaxThrottle; // kg/s + public double intakeAvailable; // kg/s + public double intakeProvided - { // kg/s for currently-open intakes + { + // kg/s for currently-open intakes get { double sum = 0; for (int i = 0; i < intakes.Count; i++) { - var intakeData = intakes[i]; + IntakeData intakeData = intakes[i]; if (intakeData.intake.intakeEnabled) { sum += intakeData.predictedMassFlow; } } + return sum; } } + public List intakes = new List(); public struct IntakeData { public IntakeData(ModuleResourceIntake intake, double predictedMassFlow) { - this.intake = intake; + this.intake = intake; this.predictedMassFlow = predictedMassFlow; } + public ModuleResourceIntake intake; - public double predictedMassFlow; // min kg/s this timestep or next + public double predictedMassFlow; // min kg/s this timestep or next } private static readonly Pool pool = new Pool(Create, Reset); - public static int PoolSize - { - get { return pool.Size; } - } + public static int PoolSize => pool.Size; private static ResourceInfo Create() { @@ -1821,9 +1923,9 @@ public static void Release(Dictionary.ValueCollection objList private static void Reset(ResourceInfo obj) { - obj.required = 0; + obj.required = 0; obj.requiredAtMaxThrottle = 0; - obj.intakeAvailable = 0; + obj.intakeAvailable = 0; obj.intakes.Clear(); } @@ -1831,19 +1933,21 @@ private ResourceInfo() { } - public static ResourceInfo Borrow(PartResourceDefinition r, double req /* u per deltaT */, double atMax /* u per s */, List modules, Vessel vessel) + public static ResourceInfo Borrow(PartResourceDefinition r, double req /* u per deltaT */, double atMax /* u per s */, + List modules, Vessel vessel) { ResourceInfo resourceInfo = pool.Borrow(); resourceInfo.Init(r, req /* u per deltaT */, atMax /* u per s */, modules, vessel); return resourceInfo; } - private void Init(PartResourceDefinition r, double req /* u per deltaT */, double atMax /* u per s */, List modules, Vessel vessel) + private void Init(PartResourceDefinition r, double req /* u per deltaT */, double atMax /* u per s */, List modules, + Vessel vessel) { definition = r; double density = definition.density * 1000; // kg per unit (density is in T per unit) float dT = TimeWarp.fixedDeltaTime; - required = req * density / dT; + required = req * density / dT; requiredAtMaxThrottle = atMax * density; // For each intake, we want to know the min of what will (or can) be provided either now or at the end of the timestep. @@ -1874,8 +1978,8 @@ private void Init(PartResourceDefinition r, double req /* u per deltaT */, doubl int idx = 0; for (int index = 0; index < modules.Count; index++) { - var intake = modules[index]; - var intakeTransform = intake.intakeTransform; + ModuleResourceIntake intake = modules[index]; + Transform intakeTransform = intake.intakeTransform; if (intakeTransform == null) continue; Vector3d intakeFwd0 = intakeTransform.forward; // TODO : replace with the new public field @@ -1921,8 +2025,9 @@ private void Init(PartResourceDefinition r, double req /* u per deltaT */, doubl capacity += tank.maxAmount; // units per timestep } } + capacity = capacity * density / dT; // convert to kg/s - mass = Math.Min(mass, capacity); + mass = Math.Min(mass, capacity); intakes.Add(new IntakeData(intake, mass)); @@ -1933,9 +2038,10 @@ private void Init(PartResourceDefinition r, double req /* u per deltaT */, doubl // Return the number of kg of resource provided per second under certain conditions. // We use kg since the numbers are typically small. private double massProvided(double vesselSpeed, Vector3d normVesselSpeed, double atmDensity, double staticPressure, float mach, - ModuleResourceIntake intake, Vector3d intakeFwd) + ModuleResourceIntake intake, Vector3d intakeFwd) { - if ((intake.checkForOxygen && !FlightGlobals.currentMainBody.atmosphereContainsOxygen) || staticPressure < intake.kPaThreshold) // TODO : add the new test (the bool and maybe the attach node ?) + if ((intake.checkForOxygen && !FlightGlobals.currentMainBody.atmosphereContainsOxygen) || + staticPressure < intake.kPaThreshold) // TODO : add the new test (the bool and maybe the attach node ?) { return 0; } @@ -1946,7 +2052,7 @@ private void Init(PartResourceDefinition r, double req /* u per deltaT */, doubl double intakeSpeed = intake.intakeSpeed; // airspeed when the intake isn't moving double aoa = Vector3d.Dot(normVesselSpeed, intakeFwd); - if (aoa < 0) { aoa = 0; } + if (aoa < 0) { aoa = 0; } else if (aoa > 1) { aoa = 1; } double finalSpeed = intakeSpeed + aoa * vesselSpeed; @@ -1959,40 +2065,32 @@ private void Init(PartResourceDefinition r, double req /* u per deltaT */, doubl } } - public class EngineWrapper { public readonly ModuleEngines engine; public float thrustRatio { - get - { - return engine.thrustPercentage / 100; - } - set - { - engine.thrustPercentage = value * 100; - } + get => engine.thrustPercentage / 100; + set => engine.thrustPercentage = value * 100; } - private Vector3d _constantForce; - private Vector3d _maxVariableForce; - private Vector3d _constantTorque; - private Vector3d _maxVariableTorque; + public Vector3d constantForce { get; } + + public Vector3d maxVariableForce { get; } + + public Vector3d constantTorque { get; } - public Vector3d constantForce { get { return _constantForce; } } - public Vector3d maxVariableForce { get { return _maxVariableForce; } } - public Vector3d constantTorque { get { return _constantTorque; } } - public Vector3d maxVariableTorque { get { return _maxVariableTorque; } } + public Vector3d maxVariableTorque { get; } - public EngineWrapper(ModuleEngines module, Vector3d constantForce, Vector3d maxVariableForce, Vector3d constantTorque, Vector3d maxVariableTorque) + public EngineWrapper(ModuleEngines module, Vector3d constantForce, Vector3d maxVariableForce, Vector3d constantTorque, + Vector3d maxVariableTorque) { - engine = module; - _constantForce = constantForce; - _maxVariableForce = maxVariableForce; - _constantTorque = constantTorque; - _maxVariableTorque = maxVariableTorque; + engine = module; + this.constantForce = constantForce; + this.maxVariableForce = maxVariableForce; + this.constantTorque = constantTorque; + this.maxVariableTorque = maxVariableTorque; } } } diff --git a/MechJebEdu.cfg b/MechJebEdu.cfg index 30c8d76e0..ac18460b6 100644 --- a/MechJebEdu.cfg +++ b/MechJebEdu.cfg @@ -1,7 +1,7 @@ -@PART[*]:HAS[@MODULE[MechJebCore]]:Final +@PART[*] : HAS[@MODULE[MechJebCore]]:Final { - @MODULE[MechJebCore] - { - %eduMode = true - } +@MODULE[MechJebCore] +{ +%eduMode = true +} } diff --git a/MechJebLibTest/Maths/BS3Tests.c.cs b/MechJebLibTest/Maths/BS3Tests.c.cs index 76c91b1df..b16174461 100644 --- a/MechJebLibTest/Maths/BS3Tests.c.cs +++ b/MechJebLibTest/Maths/BS3Tests.c.cs @@ -9,7 +9,6 @@ using MechJebLib.Core.ODE; using MechJebLib.Primitives; using Xunit; -using static MechJebLib.Utils.Statics; namespace MechJebLibTest.Maths { diff --git a/MechJebLibTest/Maths/BisectionTests.cs b/MechJebLibTest/Maths/BisectionTests.cs index 62def4e11..db18b8c05 100644 --- a/MechJebLibTest/Maths/BisectionTests.cs +++ b/MechJebLibTest/Maths/BisectionTests.cs @@ -11,7 +11,7 @@ private void SingularityTest() { double x, fx; - (x, fx) = Bisection.Solve((t, o) => 1.0 / t, -1.0, 1.0, null, 0); + (x, fx) = Bisection.Solve((t, o) => 1.0 / t, -1.0, 1.0, null); x.ShouldEqual(-4.9406564584124654E-324, 0); fx.ShouldEqual(double.NegativeInfinity); (x, fx) = Bisection.Solve((t, o) => 1.0 / t, 1.0, -1.0, null, 0, false); @@ -20,7 +20,7 @@ private void SingularityTest() (x, fx) = Bisection.Solve((t, o) => 1.0 / t, -1.0, 1.0, null, 0, false); x.ShouldEqual(0, 0); fx.ShouldEqual(double.PositiveInfinity); - (x, fx) = Bisection.Solve((t, o) => 1.0 / t, 1.0, -1.0, null, 0); + (x, fx) = Bisection.Solve((t, o) => 1.0 / t, 1.0, -1.0, null); x.ShouldEqual(0, 0); fx.ShouldEqual(double.PositiveInfinity); } @@ -30,13 +30,13 @@ private void IrrationalTest() { double x, fx; - (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 2.0, 3.0, null, 0); + (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 2.0, 3.0, null); x.ShouldEqual(2.4494897427831779, 0); fx.ShouldEqual(-4.4408920985006262E-16); (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 2.0, 3.0, null, 0, false); x.ShouldEqual(2.4494897427831783, 0); fx.ShouldEqual(4.4408920985006262E-16); - (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 3.0, 2.0, null, 0); + (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 3.0, 2.0, null); x.ShouldEqual(2.4494897427831783, 0); fx.ShouldEqual(4.4408920985006262E-16); (x, fx) = Bisection.Solve((t, o) => 0.5 * t * t - 3.0, 3.0, 2.0, null, 0, false); diff --git a/MechJebLibTest/MechJebLibTest.csproj b/MechJebLibTest/MechJebLibTest.csproj index bec16f058..ab8ebc829 100644 --- a/MechJebLibTest/MechJebLibTest.csproj +++ b/MechJebLibTest/MechJebLibTest.csproj @@ -1,6 +1,6 @@  - + Debug AnyCPU @@ -38,10 +38,10 @@ ..\..\..\..\..\Library\Application Support\Steam\steamapps\common\Kerbal Space Program\KSP.app\Contents\Resources\Data\Managed\Assembly-CSharp.dll - - - - + + + + ..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll @@ -56,28 +56,28 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + @@ -85,7 +85,7 @@ MechJeb2 - +