-
Notifications
You must be signed in to change notification settings - Fork 1
/
MechJebModuleAscentAutopilot.cs
1458 lines (1191 loc) · 68.8 KB
/
MechJebModuleAscentAutopilot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using SharpLua.LuaTypes;
/*
* Todo:
*
* -Enable launch-to-plane (auto-time and auto set inclination)
*
* Future:
*
* -add a roll input (may require improved attitude controller)
*
*/
namespace MuMech
{
public class MechJebModuleAscentAutopilot : ComputerModule
{
public MechJebModuleAscentAutopilot(MechJebCore core) : base(core) { }
public override void onModuleDisabled()
{
turnOffSteering();
}
public override void onControlLost()
{
turnOffSteering();
}
void turnOffSteering()
{
if (mode != AscentMode.DISENGAGED)
{
if (autoStage)
{
core.autoStageDeactivate(this);
}
if (mode != AscentMode.ON_PAD)
{
FlightInputHandler.SetNeutralControls(); //makes sure we leave throttle at zero
}
mode = AscentMode.DISENGAGED;
core.attitudeDeactivate(this);
}
}
public const double BEACH_ALTITUDE = 100001.6;
public const double BEACH_INCLINATION = 24.0;
public override void registerLuaMembers(LuaTable index)
{
index.Register("launchTo", proxyLaunchTo);
}
public LuaValue proxyLaunchTo(LuaValue[] args)
{
if (args.Count() != 2) throw new Exception("launchTo usage: launchTo(altitude [in meters], inclination [in degrees])");
double orbitAltitude;
double orbitInclination;
try
{
orbitAltitude = ((LuaNumber)args[0]).Number;
}
catch (Exception)
{
throw new Exception("launchTo: invalid orbit altitude");
}
try
{
orbitInclination = ((LuaNumber)args[1]).Number;
}
catch (Exception)
{
throw new Exception("launchTo: invalid orbit inclination");
}
launchTo(orbitAltitude, orbitInclination);
return LuaNil.Nil;
}
//programmatic interface to the module.
public void launchTo(double orbitAltitude, double orbitInclination)
{
this.enabled = true;
core.controlClaim(this);
desiredOrbitAltitude = orbitAltitude;
desiredInclination = orbitInclination;
desiredOrbitAltitudeKmString = (desiredOrbitAltitude / 1000.0).ToString();
desiredInclinationString = desiredInclination.ToString();
//currently this only gets called from lua scripts, and the scripter probably
//wants a fully automatic launch, so turn on all the auto stuff
autoStage = true;
seizeThrottle = true;
autoWarpToApoapsis = true;
//lift off if we haven't yet:
core.launch(this);
mode = AscentMode.VERTICAL_ASCENT;
}
////////////////////////////////////
// GLOBAL DATA /////////////////////
////////////////////////////////////
//autopilot modes
public enum AscentMode { ON_PAD, VERTICAL_ASCENT, GRAVITY_TURN, COAST_TO_APOAPSIS, CIRCULARIZE, DISENGAGED };
String[] modeStrings = new String[] { "Awaiting liftoff", "Vertical ascent", "Gravity turn", "Coasting to apoapsis", "Circularizing", "Disengaged" };
public AscentMode mode = AscentMode.DISENGAGED;
//control errors
Vector3d lastThrustError = Vector3d.zero;
//control gains
const double velocityKP = 5.0;
const double thrustKP = 3.0;
const double thrustKD = 15.0;
//double thrustGainAttenuator = 1;
//GUI stuff
bool minimized = false;
bool showHelpWindow = false;
Texture2D pathTexture = new Texture2D(400, 100);
Vector2 helpScrollPosition;
//things the drive code needs to remember between frames
//double lastAccelerationTime = 0;
//int lastAttemptedWarpIndex = 0;
double totalDVExpended;
double gravityLosses;
double dragLosses;
double steeringLosses;
double launchTime;
double mecoTime;
double launchLongitude;
double launchMass;
double launchPhaseAngle;
bool timeIgnitionForRendezvous = false;
bool choosingRendezvousTarget = false;
double predictedLaunchPhaseAngle;
String predictedLaunchPhaseAngleString = "";
Vessel rendezvousTarget;
Vector2 rendezvousTargetScrollPos = new Vector2();
double rendezvousIgnitionCountdown;
bool rendezvousIgnitionCountdownHolding;
//user inputs
double _gravityTurnStartAltitude = 10000.0;
double gravityTurnStartAltitude
{
get { return _gravityTurnStartAltitude; }
set
{
if (_gravityTurnStartAltitude != value) core.settingsChanged = true;
_gravityTurnStartAltitude = value;
}
}
String gravityTurnStartAltitudeKmString = "10";
double _gravityTurnEndAltitude = 70000.0;
double gravityTurnEndAltitude
{
get { return _gravityTurnEndAltitude; }
set
{
if (_gravityTurnEndAltitude != value) core.settingsChanged = true;
_gravityTurnEndAltitude = value;
}
}
String gravityTurnEndAltitudeKmString = "70";
double _gravityTurnEndPitch = 0.0;
double gravityTurnEndPitch
{
get { return _gravityTurnEndPitch; }
set
{
if (_gravityTurnEndPitch != value) core.settingsChanged = true;
_gravityTurnEndPitch = value;
}
}
String gravityTurnEndPitchString = "0";
double _gravityTurnShapeExponent = 0.4;
double gravityTurnShapeExponent
{
get { return _gravityTurnShapeExponent; }
set
{
if (_gravityTurnShapeExponent != value) core.settingsChanged = true;
_gravityTurnShapeExponent = value;
}
}
double _desiredOrbitAltitude = 100000.0;
double desiredOrbitAltitude
{
get { return _desiredOrbitAltitude; }
set
{
if (_desiredOrbitAltitude != value) core.settingsChanged = true;
_desiredOrbitAltitude = value;
}
}
String desiredOrbitAltitudeKmString = "100";
double _desiredInclination = 0.0;
double desiredInclination
{
get { return _desiredInclination; }
set
{
if (_desiredInclination != value) core.settingsChanged = true;
_desiredInclination = value;
}
}
String desiredInclinationString = "0";
double _launchHeading = 90.0;
double launchHeading
{
get { return _launchHeading; }
set
{
if (_launchHeading != value) core.settingsChanged = true;
_launchHeading = value;
}
}
String launchHeadingString = "90";
bool _headingNotInc = false;
bool headingNotInc
{
get { return _headingNotInc; }
set
{
if (_headingNotInc != value) core.settingsChanged = true;
_headingNotInc = value;
}
}
bool _autoStage = true;
bool autoStage
{
get { return _autoStage; }
set
{
if (_autoStage != value) core.settingsChanged = true;
_autoStage = value;
if (mode != AscentMode.DISENGAGED)
{
if (autoStage)
{
core.autoStageActivate(this, autoStageDelay, autoStageLimit);
}
else
{
core.autoStageDeactivate(this);
}
}
}
}
double _autoStageDelay = 1.0;
double autoStageDelay
{
get { return _autoStageDelay; }
set
{
if (_autoStageDelay != value) core.settingsChanged = true;
_autoStageDelay = value;
}
}
String autoStageDelayString = "1.0";
int _autoStageLimit = 0;
int autoStageLimit
{
get { return _autoStageLimit; }
set
{
if (_autoStageLimit != value) core.settingsChanged = true;
_autoStageLimit = value;
}
}
String autoStageLimitString = "0";
bool _autoWarpToApoapsis = true;
bool autoWarpToApoapsis
{
get { return _autoWarpToApoapsis; }
set
{
if (_autoWarpToApoapsis != value) core.settingsChanged = true;
_autoWarpToApoapsis = value;
}
}
bool _seizeThrottle = true;
bool seizeThrottle
{
get { return _seizeThrottle; }
set
{
if (_seizeThrottle != value) core.settingsChanged = true;
_seizeThrottle = value;
}
}
Rect _pathWindowPos;
Rect pathWindowPos
{
get { return _pathWindowPos; }
set
{
if (_pathWindowPos.x != value.x || _pathWindowPos.y != value.y) core.settingsChanged = true;
_pathWindowPos = value;
}
}
protected Rect _helpWindowPos;
Rect helpWindowPos
{
get { return _helpWindowPos; }
set
{
if (_helpWindowPos.x != value.x || _helpWindowPos.y != value.y) core.settingsChanged = true;
_helpWindowPos = value;
}
}
protected Rect _statsWindowPos;
Rect statsWindowPos
{
get { return _statsWindowPos; }
set
{
if (_statsWindowPos.x != value.x || _statsWindowPos.y != value.y) core.settingsChanged = true;
_statsWindowPos = value;
}
}
bool _showPathWindow = false;
bool showPathWindow
{
get { return _showPathWindow; }
set
{
if (_showPathWindow != value) core.settingsChanged = true;
_showPathWindow = value;
}
}
bool _showStats = false;
bool showStats
{
get { return _showStats; }
set
{
if (_showStats != value) core.settingsChanged = true;
_showStats = value;
}
}
public override void onLoadGlobalSettings(SettingsManager settings)
{
base.onLoadGlobalSettings(settings);
gravityTurnStartAltitude = settings["AA_gravityTurnStartAltitude"].valueDecimal(10000.0);
gravityTurnStartAltitudeKmString = (gravityTurnStartAltitude / 1000.0).ToString();
gravityTurnEndAltitude = settings["AA_gravityTurnEndAltitude"].valueDecimal(70000.0);
gravityTurnEndAltitudeKmString = (gravityTurnEndAltitude / 1000.0).ToString();
gravityTurnEndPitch = settings["AA_gravityTurnEndPitch"].valueDecimal(0.0);
gravityTurnEndPitchString = gravityTurnEndPitch.ToString();
gravityTurnShapeExponent = settings["AA_gravityTurnShapeExponent"].valueDecimal(0.4);
desiredOrbitAltitude = settings["AA_desiredOrbitAltitude"].valueDecimal(100000.0);
desiredOrbitAltitudeKmString = (desiredOrbitAltitude / 1000.0).ToString();
desiredInclination = settings["AA_desiredInclination"].valueDecimal(0.0);
desiredInclinationString = desiredInclination.ToString();
launchHeading = settings["AA_launchHeading"].valueDecimal(90.0);
launchHeadingString = launchHeading.ToString();
headingNotInc = settings["AA_headingNotInc"].valueBool(false);
autoStage = settings["AA_autoStage"].valueBool(true);
autoStageDelay = settings["AA_autoStageDelay"].valueDecimal(1.0);
autoStageLimit = settings["AA_autoStageLimit"].valueInteger(0);
autoStageDelayString = String.Format("{0:0.0}", autoStageDelay);
autoStageLimitString = autoStageLimit.ToString();
autoWarpToApoapsis = settings["AA_autoWarpToApoapsis"].valueBool(true);
seizeThrottle = settings["AA_seizeThrottle"].valueBool(true);
predictedLaunchPhaseAngle = settings["AA_predictedLaunchPhaseAngle"].valueDecimal(0.0);
predictedLaunchPhaseAngleString = String.Format("{0:0.00}", predictedLaunchPhaseAngle);
Vector4 savedPathWindowPos = settings["AA_pathWindowPos"].valueVector(new Vector4(Screen.width / 2, Screen.height / 2));
pathWindowPos = new Rect(savedPathWindowPos.x, savedPathWindowPos.y, 10, 10);
Vector4 savedHelpWindowPos = settings["AA_helpWindowPos"].valueVector(new Vector4(150, 50));
helpWindowPos = new Rect(savedHelpWindowPos.x, savedHelpWindowPos.y, 10, 10);
Vector4 savedStatsWindowPos = settings["AA_statsWindowPos"].valueVector(new Vector4(150, 50));
statsWindowPos = new Rect(savedStatsWindowPos.x, savedStatsWindowPos.y, 10, 10);
showPathWindow = settings["AA_showPathWindow"].valueBool(false);
showStats = settings["AA_showStatsWindow"].valueBool(false);
}
public override void onSaveGlobalSettings(SettingsManager settings)
{
base.onSaveGlobalSettings(settings);
settings["AA_gravityTurnStartAltitude"].value_decimal = gravityTurnStartAltitude;
settings["AA_gravityTurnEndAltitude"].value_decimal = gravityTurnEndAltitude;
settings["AA_gravityTurnEndPitch"].value_decimal = gravityTurnEndPitch;
settings["AA_gravityTurnShapeExponent"].value_decimal = gravityTurnShapeExponent;
settings["AA_desiredOrbitAltitude"].value_decimal = desiredOrbitAltitude;
settings["AA_desiredInclination"].value_decimal = desiredInclination;
settings["AA_launchHeading"].value_decimal = launchHeading;
settings["AA_headingNotInc"].value_bool = headingNotInc;
settings["AA_autoStage"].value_bool = autoStage;
settings["AA_autoStageDelay"].value_decimal = autoStageDelay;
settings["AA_autoStageLimit"].value_integer = autoStageLimit;
settings["AA_autoWarpToApoapsis"].value_bool = autoWarpToApoapsis;
settings["AA_seizeThrottle"].value_bool = seizeThrottle;
settings["AA_predictedLaunchPhaseAngle"].value_decimal = predictedLaunchPhaseAngle;
settings["AA_pathWindowPos"].value_vector = new Vector4(pathWindowPos.x, pathWindowPos.y);
settings["AA_helpWindowPos"].value_vector = new Vector4(helpWindowPos.x, helpWindowPos.y);
settings["AA_statsWindowPos"].value_vector = new Vector4(statsWindowPos.x, statsWindowPos.y);
settings["AA_showPathWindow"].value_bool = showPathWindow;
settings["AA_showStatsWindow"].value_bool = showStats;
}
////////////////////////////////////////
// ASCENT PATH /////////////////////////
////////////////////////////////////////
//controls the ascent path. by "pitch" we mean the pitch of the velocity vector in the rotating frame
private double unsmoothedDesiredPitch(double altitude)
{
if (altitude < gravityTurnStartAltitude) return 90.0;
if (altitude > gravityTurnEndAltitude) return gravityTurnEndPitch;
return Mathf.Clamp((float)(90.0 - Math.Pow((altitude - gravityTurnStartAltitude) / (gravityTurnEndAltitude - gravityTurnStartAltitude), gravityTurnShapeExponent) * (90.0 - gravityTurnEndPitch)), 0.01F, 89.99F);
}
private double desiredPitch(double altitude)
{
return unsmoothedDesiredPitch(altitude);
}
//some 3d geometry relates the bearing of our ground velocity with the inclination and the latitude:
private double desiredSurfaceAngle(double latitudeRadians, double referenceFrameBlend)
{
double cosDesiredSurfaceAngle = Math.Cos(desiredInclination * Math.PI / 180) / Math.Cos(latitudeRadians);
double desiredSurfaceAngle;
if (Math.Abs(cosDesiredSurfaceAngle) > 1.0)
{
if (Math.Abs(desiredInclination) < 90) desiredSurfaceAngle = 0;
else desiredSurfaceAngle = Math.PI;
}
else
{
desiredSurfaceAngle = Math.Acos(cosDesiredSurfaceAngle);
if (desiredInclination > 0) desiredSurfaceAngle = -desiredSurfaceAngle;
}
return desiredSurfaceAngle;
}
///////////////////////////////////////
// FLYING THE ROCKET //////////////////
///////////////////////////////////////
//called every frame or so; this is where we manipulate the flight controls
public override void drive(FlightCtrlState s)
{
if (mode == AscentMode.DISENGAGED) return;
if (mode == AscentMode.ON_PAD && Staging.CurrentStage <= Staging.lastStage) mode = AscentMode.VERTICAL_ASCENT;
switch (mode)
{
case AscentMode.VERTICAL_ASCENT:
driveVerticalAscent(s);
break;
case AscentMode.GRAVITY_TURN:
driveGravityTurn(s);
break;
case AscentMode.COAST_TO_APOAPSIS:
driveCoastToApoapsis(s);
break;
case AscentMode.CIRCULARIZE:
driveCircularizationBurn(s);
break;
}
driveLimitOverheat(s);
driveRendezvousStuff(s);
driveUpdateStats(s);
}
void driveLimitOverheat(FlightCtrlState s)
{
//limit the throttle if something is close to overheating
double maxTempRatio = ARUtils.maxTemperatureRatio(part.vessel);
double tempSafetyMargin = 0.05;
if (maxTempRatio > (1 - tempSafetyMargin) && seizeThrottle)
{
s.mainThrottle = Mathf.Clamp(s.mainThrottle, 0.0F, (float)((1 - maxTempRatio) / tempSafetyMargin));
}
}
void driveUpdateStats(FlightCtrlState s)
{
if (mode != AscentMode.DISENGAGED && mode != AscentMode.ON_PAD)
{
totalDVExpended += vesselState.deltaT * vesselState.thrustAccel(s.mainThrottle);
gravityLosses += vesselState.deltaT * Vector3d.Dot(-vesselState.velocityVesselSurfaceUnit, vesselState.gravityForce);
gravityLosses -= vesselState.deltaT * Vector3d.Dot(vesselState.velocityVesselSurfaceUnit, vesselState.up * vesselState.radius * Math.Pow(1 / part.vessel.mainBody.rotationPeriod, 2));
steeringLosses += vesselState.deltaT * vesselState.thrustAccel(s.mainThrottle) * (1 - Vector3.Dot(vesselState.velocityVesselSurfaceUnit, vesselState.forward));
dragLosses += vesselState.deltaT * ARUtils.computeDragAccel(vesselState.CoM, vesselState.velocityVesselOrbit, vesselState.massDrag / vesselState.mass, part.vessel.mainBody).magnitude;
double netVelocity = totalDVExpended - gravityLosses - steeringLosses - dragLosses;
double targetCircularPeriod = 2 * Math.PI * Math.Sqrt(Math.Pow(part.vessel.mainBody.Radius + desiredOrbitAltitude, 3) / part.vessel.mainBody.gravParameter);
double longitudeTraversed = (vesselState.longitude - launchLongitude) + 360 * (vesselState.time - launchTime) / part.vessel.mainBody.rotationPeriod;
launchPhaseAngle = ARUtils.clampDegrees(360 * (vesselState.time - launchTime) / targetCircularPeriod - longitudeTraversed);
}
}
void driveRendezvousStuff(FlightCtrlState s)
{
if (mode == AscentMode.ON_PAD && timeIgnitionForRendezvous && rendezvousTarget != null)
{
double phaseAngle = ARUtils.clampDegrees(vesselState.longitude - part.vessel.mainBody.GetLongitude(rendezvousTarget.transform.position));
double[] warpLookaheadTimes = new double[] { 10, 12.5, 15, 25, 50, 500, 10000, 100000 };
double angleDifference = ARUtils.clampDegrees(phaseAngle - predictedLaunchPhaseAngle);
double angleRate = 360.0 / rendezvousTarget.orbit.period - 360 / part.vessel.mainBody.rotationPeriod;
rendezvousIgnitionCountdown = angleDifference / angleRate;
if (rendezvousIgnitionCountdown < 0.0 && rendezvousIgnitionCountdown > -1.0)
{
mode = AscentMode.VERTICAL_ASCENT;
Staging.ActivateNextStage();
}
else
{
if (rendezvousIgnitionCountdown < 0)
{
rendezvousIgnitionCountdown = rendezvousTarget.orbit.period / 2;
rendezvousIgnitionCountdownHolding = true;
}
else
{
rendezvousIgnitionCountdownHolding = false;
}
core.warpTo(this, rendezvousIgnitionCountdown, warpLookaheadTimes);
}
}
}
///////////////////////////////////////
// VERTICAL ASCENT AND GRAVITY TURN ///
///////////////////////////////////////
//gives a throttle setting that will not waste too much fuel blasting through dense atmosphere
//the algorithm keeps the velocity just slightly above terminal velocity
//thanks to jebbe on the forums for suggesting this efficiency improvement
float efficientThrottle()
{
if (vesselState.altitudeASL > part.vessel.mainBody.maxAtmosphereAltitude) return 1.0F;
double ratioTarget = 1.0;
double falloff = 15.0;
double velocityRatio = Vector3d.Dot(vesselState.velocityVesselSurface, vesselState.up) / ARUtils.terminalVelocity(part.vessel, vesselState.CoM);
if (velocityRatio < ratioTarget) return 1.0F;
return Mathf.Clamp((float)(1.0 - falloff * (velocityRatio - ratioTarget)), 0.0F, 1.0F);
}
//gives a throttle setting that reduces as we approach the desired apoapsis
//so that we can precisely match the desired apoapsis instead of overshooting it
float throttleToRaiseApoapsis(double currentApoapsisRadius, double finalApoapsisRadius)
{
if (currentApoapsisRadius > finalApoapsisRadius + 5.0) return 0.0F;
else if (part.vessel.orbit.ApA < part.vessel.mainBody.maxAtmosphereAltitude) return 1.0F; //throttle hard to escape atmosphere
double GM = vesselState.localg * vesselState.radius * vesselState.radius;
double potentialDifference = GM / currentApoapsisRadius - GM / finalApoapsisRadius;
double finalKineticEnergy = 0.5 * vesselState.speedOrbital * vesselState.speedOrbital + potentialDifference;
double speedDifference = Math.Sqrt(2 * finalKineticEnergy) - vesselState.speedOrbital;
if (speedDifference > 100) return 1.0F;
return Mathf.Clamp((float)(speedDifference / (1.0 * vesselState.maxThrustAccel)), 0.05F, 1.0F); //1 second time constant for throttle reduction
//return Mathf.Clamp((float)(speedDifference / 100.0), 0.05F, 1.0F);
}
void driveVerticalAscent(FlightCtrlState s)
{
//during the vertical ascent we just thrust straight up at max throttle
if (seizeThrottle) s.mainThrottle = efficientThrottle();
if (vesselState.altitudeASL > gravityTurnStartAltitude) mode = AscentMode.GRAVITY_TURN;
if (seizeThrottle && part.vessel.orbit.ApA > desiredOrbitAltitude)
{
//lastAccelerationTime = vesselState.time;
mode = AscentMode.COAST_TO_APOAPSIS;
}
core.attitudeTo(Vector3d.up, MechJebCore.AttitudeReference.SURFACE_NORTH, this);
}
void driveGravityTurn(FlightCtrlState s)
{
//stop the gravity turn when our apoapsis reaches the desired altitude
if (seizeThrottle && part.vessel.orbit.ApA > desiredOrbitAltitude)
{
mode = AscentMode.COAST_TO_APOAPSIS;
//lastAccelerationTime = vesselState.time;
core.attitudeTo(Vector3d.forward, MechJebCore.AttitudeReference.ORBIT, this);
return;
}
if (vesselState.altitudeASL < gravityTurnStartAltitude)
{
mode = AscentMode.VERTICAL_ASCENT;
core.attitudeTo(Vector3d.up, MechJebCore.AttitudeReference.SURFACE_NORTH, this);
return;
}
if (seizeThrottle)
{
float gentleThrottle = throttleToRaiseApoapsis(part.vessel.orbit.ApR, desiredOrbitAltitude + part.vessel.mainBody.Radius);
if (gentleThrottle < 1.0F)
{
//when we are bringing down the throttle to make the apoapsis accurate, we're liable to point in weird
//directions because thrust goes down and so "difficulty" goes up. so just burn prograde
s.mainThrottle = gentleThrottle;
core.attitudeTo(Vector3d.forward, MechJebCore.AttitudeReference.ORBIT, this);
return;
}
else
{
s.mainThrottle = efficientThrottle();
}
}
//transition gradually from the rotating to the non-rotating reference frame. this calculation ensures that
//when our maximum possible apoapsis, given our orbital energy, is desiredOrbitalRadius, then we are
//fully in the non-rotating reference frame and thus doing the correct calculations to get the right inclination
double GM = vesselState.localg * vesselState.radius * vesselState.radius;
double potentialDifferenceWithApoapsis = GM / vesselState.radius - GM / (part.vessel.mainBody.Radius + desiredOrbitAltitude);
double verticalSpeedForDesiredApoapsis = Math.Sqrt(2 * potentialDifferenceWithApoapsis);
//double referenceFrameBlend = Mathf.Clamp((float)(1.5 * vesselState.speedOrbital / verticalSpeedForDesiredApoapsis - 0.5), 0.0F, 1.0F);
double referenceFrameBlend = Mathf.Clamp((float)(vesselState.speedOrbital / verticalSpeedForDesiredApoapsis), 0.0F, 1.0F);
Vector3d actualVelocityUnit = ((1 - referenceFrameBlend) * vesselState.velocityVesselSurfaceUnit
+ referenceFrameBlend * vesselState.velocityVesselOrbitUnit).normalized;
//minus sign is there because somewhere a sign got flipped in integrating with MechJeb
double surfaceAngle = -desiredSurfaceAngle(vesselState.latitude * Math.PI / 180.0, referenceFrameBlend);
Vector3d desiredSurfaceHeading = Math.Cos(surfaceAngle) * vesselState.east + Math.Sin(surfaceAngle) * vesselState.north;
double desPitch = desiredPitch(vesselState.altitudeASL);
//double desPitch = 90;
Vector3d desiredVelocityUnit = Math.Cos(desPitch * Math.PI / 180) * desiredSurfaceHeading
+ Math.Sin(desPitch * Math.PI / 180) * vesselState.up;
Vector3d velocityError = (desiredVelocityUnit - actualVelocityUnit);
//"difficulty" accounts for the difficulty of changing a large velocity vector given our current thrust
double difficulty = vesselState.velocityVesselSurface.magnitude / (50 + 10 * vesselState.thrustAccel(s.mainThrottle));
if (difficulty > 5) difficulty = 5;
if (vesselState.maxThrustAccel == 0) difficulty = 1.0; //so we don't freak out over having no thrust between stages
Vector3d desiredThrustVector;
desiredThrustVector = desiredVelocityUnit;
Vector3d steerOffset = velocityKP * difficulty * velocityError;
double maxOffset = 10 * Math.PI / 180;
if (desPitch > 80) maxOffset = (90 - desPitch) * Math.PI / 180;
if (steerOffset.magnitude > maxOffset) steerOffset = maxOffset * steerOffset.normalized;
desiredThrustVector += steerOffset;
desiredThrustVector = desiredThrustVector.normalized;
core.attitudeTo(desiredThrustVector, MechJebCore.AttitudeReference.INERTIAL, this);
}
///////////////////////////////////////
// COAST AND CIRCULARIZATION //////////
///////////////////////////////////////
double thrustPitchForZeroVerticalAcc(double orbitRadius, double currentHorizontalSpeed, double thrustAcceleration, double currentVerticalSpeed)
{
double centrifugalAcceleration = currentHorizontalSpeed * currentHorizontalSpeed / orbitRadius;
double gravityAcceleration = gAtRadius(orbitRadius);
double downwardAcceleration = gravityAcceleration - centrifugalAcceleration;
downwardAcceleration -= currentVerticalSpeed / 1.0; //1.0 = 1 second time constant for killing existing vertical speed
if (Math.Abs(downwardAcceleration) > thrustAcceleration) return 0; //we're screwed, just burn horizontal
return Math.Asin(downwardAcceleration / thrustAcceleration);
}
double expectedSpeedAtApoapsis()
{
// (1/2)(orbitSpeed)^2 - g(r)*r = constant
double currentTotalEnergy = 0.5 * vesselState.speedOrbital * vesselState.speedOrbital - vesselState.localg * vesselState.radius;
double gAtApoapsis = gAtRadius(part.vessel.orbit.ApR);
double potentialEnergyAtApoapsis = -gAtApoapsis * part.vessel.orbit.ApR;
double kineticEnergyAtApoapsis = currentTotalEnergy - potentialEnergyAtApoapsis;
return Math.Sqrt(2 * kineticEnergyAtApoapsis);
}
double circularizationBurnThrottle(double currentSpeed, double finalSpeed)
{
if (vesselState.maxThrustAccel == 0)
{
//then we are powerless
return 0;
}
double desiredThrustAccel = (finalSpeed - currentSpeed) / 1.0; //5 second time constant for throttling down
float throttleCommand = (float)((desiredThrustAccel - vesselState.minThrustAccel) / (vesselState.maxThrustAccel - vesselState.minThrustAccel));
return Mathf.Clamp(throttleCommand, 0.01F, 1.0F);
}
double gAtRadius(double radius)
{
return FlightGlobals.getGeeForceAtPosition(part.vessel.mainBody.position + radius * vesselState.up).magnitude;
}
double circularSpeedAtRadius(double radius)
{
return Math.Sqrt(gAtRadius(radius) * radius);
}
void driveCoastToApoapsis(FlightCtrlState s)
{
s.mainThrottle = 0.0F;
if (Vector3d.Dot(vesselState.velocityVesselOrbit, vesselState.up) < 0) //if we have started to descend, i.e. reached apoapsis, circularize
{
mode = AscentMode.CIRCULARIZE;
if (TimeWarp.CurrentRateIndex != 0) TimeWarp.SetRate(0, false);
return;
}
if (part.vessel.orbit.ApA < desiredOrbitAltitude - 1000.0)
{
mode = AscentMode.GRAVITY_TURN;
core.attitudeTo(Vector3.forward, MechJebCore.AttitudeReference.ORBIT, this);
return;
}
//if we are running physics, we can do burns if the apoapsis falls, and we can maintain our orientation in preparation for circularization
//if our Ap is too low and we are pointing reasonably along our velocity
double[] lookaheadTimes = new double[] { 0, 32.5, 35, 50, 75, 500, 10000, 100000 };
if (part.vessel.orbit.ApA < desiredOrbitAltitude - 10)
{
if ((TimeWarp.WarpMode == TimeWarp.Modes.LOW) || (TimeWarp.CurrentRate <= TimeWarp.MaxPhysicsRate))
{
//lastAccelerationTime = vesselState.time;
core.attitudeTo(Vector3.forward, MechJebCore.AttitudeReference.ORBIT, this);
if (Vector3d.Dot(vesselState.forward, vesselState.velocityVesselOrbitUnit) > 0.75)
{
s.mainThrottle = throttleToRaiseApoapsis(part.vessel.orbit.ApR, desiredOrbitAltitude + part.vessel.mainBody.Radius);
}
else
{
s.mainThrottle = 0.0F;
}
return;
}
else
{
core.warpPhysics(this);
}
}
else if (autoWarpToApoapsis)
{
//if we're allowed to autowarp, do so
core.warpTo(this, part.vessel.orbit.timeToAp, lookaheadTimes);
}
//if we are out of the atmosphere and have a high enough apoapsis and aren't near apoapsis, play dead to
//prevent acceleration from interfering with time warp. otherwise point in the direction that we will
//want to point at the start of the circularization burn
if (autoWarpToApoapsis
&& vesselState.altitudeASL > part.vessel.mainBody.maxAtmosphereAltitude
&& part.vessel.orbit.timeToAp > lookaheadTimes[2]
&& part.vessel.orbit.ApA > desiredOrbitAltitude - 10)
{
//don't steer
core.attitudeDeactivate(this);
}
else
{
double expectedApoapsisThrottle = circularizationBurnThrottle(expectedSpeedAtApoapsis(), circularSpeedAtRadius(part.vessel.orbit.ApR));
double desiredThrustPitch = thrustPitchForZeroVerticalAcc(part.vessel.orbit.ApR, expectedSpeedAtApoapsis(),
vesselState.thrustAccel(expectedApoapsisThrottle), 0);
Vector3d groundHeading = Vector3d.Exclude(vesselState.up, part.vessel.orbit.GetVel()).normalized;
Vector3d desiredThrustVector = (Math.Cos(desiredThrustPitch) * groundHeading + Math.Sin(desiredThrustPitch) * vesselState.up);
core.attitudeTo(desiredThrustVector, MechJebCore.AttitudeReference.INERTIAL, this);
return;
}
}
void driveCircularizationBurn(FlightCtrlState s)
{
if (part.vessel.orbit.ApA < desiredOrbitAltitude - 1000.0)
{
mode = AscentMode.GRAVITY_TURN;
core.attitudeTo(Vector3.forward, MechJebCore.AttitudeReference.ORBIT, this);
return;
}
double orbitalRadius = (vesselState.CoM - part.vessel.mainBody.position).magnitude;
double circularSpeed = Math.Sqrt(orbitalRadius * vesselState.localg);
//we start the circularization burn at apoapsis, and the orbit is about as circular as it is going to get when the
//periapsis has moved closer to us than the apoapsis
if (Math.Min(part.vessel.orbit.timeToPe, part.vessel.orbit.period - part.vessel.orbit.timeToPe) <
Math.Min(part.vessel.orbit.timeToAp, part.vessel.orbit.period - part.vessel.orbit.timeToAp)
|| vesselState.speedOrbital > circularSpeed + 1.0) //makes sure we don't keep burning forever if we are somehow way off course
{
predictedLaunchPhaseAngle = launchPhaseAngle;
predictedLaunchPhaseAngleString = String.Format("{0:00}", predictedLaunchPhaseAngle);
mecoTime = vesselState.time;
s.mainThrottle = 0.0F;
turnOffSteering();
core.controlRelease(this);
//if (!showStats) enabled = false;
return;
}
//During circularization we think in the *non-rotating* frame, but allow ourselves to discuss centrifugal acceleration
//as the tendency for the altitude to rise because of our large horizontal velocity.
//To get a circular orbit we need to reach orbital horizontal speed while simultaneously getting zero vertical speed.
//We compute the thrust vector needed to get zero vertical acceleration, taking into account gravity and centrifugal
//acceleration. If we currently have a nonzero vertical velocity we then adjust the thrust vector to bring that to zero
s.mainThrottle = (float)circularizationBurnThrottle(vesselState.speedOrbital, circularSpeed);
double thrustAcceleration = vesselState.thrustAccel(s.mainThrottle);
Vector3d groundHeading = Vector3d.Exclude(vesselState.up, vesselState.velocityVesselOrbit).normalized;
double horizontalSpeed = Vector3d.Dot(groundHeading, vesselState.velocityVesselOrbit);
double verticalSpeed = Vector3d.Dot(vesselState.up, vesselState.velocityVesselOrbit);
//test the following modification: pitch = 0 if throttle < 1
double desiredThrustPitch = thrustPitchForZeroVerticalAcc(orbitalRadius, horizontalSpeed, thrustAcceleration, verticalSpeed);
//Vector3d desiredThrustVector = Math.Cos(desiredThrustPitch) * groundHeading + Math.Sin(desiredThrustPitch) * vesselState.up;
Vector3d desiredThrustVector = Math.Cos(desiredThrustPitch) * Vector3d.forward + Math.Sin(desiredThrustPitch) * Vector3d.up;
core.attitudeTo(desiredThrustVector, MechJebCore.AttitudeReference.ORBIT_HORIZONTAL, this);
}
///////////////////////////////////////////////
// GUI ////////// /////////////////////////////
///////////////////////////////////////////////
public override void drawGUI(int baseWindowID)
{
GUI.skin = HighLogic.Skin;
if (minimized)
{
windowPos = GUILayout.Window(baseWindowID, windowPos, WindowGUI, "Ascent", GUILayout.Width(100), GUILayout.Height((choosingRendezvousTarget ? 600 : 30)));
}
else
{
windowPos = GUILayout.Window(baseWindowID, windowPos, WindowGUI, "Ascent Autopilot", GUILayout.Width(200), GUILayout.Height(100));
if (showPathWindow)
{
pathWindowPos = GUILayout.Window(baseWindowID + 1, pathWindowPos, PathWindowGUI, "Ascent Path", GUILayout.Width(300), GUILayout.Height(100));
}
if (showStats)
{
statsWindowPos = GUILayout.Window(baseWindowID + 2, statsWindowPos, StatsWindowGUI, "Ascent Stats", GUILayout.Width(225), GUILayout.Height(250));
}
}
if (showHelpWindow)
{
helpWindowPos = GUILayout.Window(baseWindowID + 3, helpWindowPos, HelpWindowGUI, "Ascent Autopilot Help", GUILayout.Width(400), GUILayout.Height(500));
}
}
protected override void WindowGUI(int windowID)
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUIStyle s = new GUIStyle(GUI.skin.button);
if (mode == AscentMode.DISENGAGED)
{
s.normal.textColor = Color.green;
if (GUILayout.Button("Engage", s))
{
initializeInternals();
core.controlClaim(this);
if (autoStage)
{
core.autoStageActivate(this, autoStageDelay, autoStageLimit);
}
mode = AscentMode.ON_PAD;
}
}
else
{
s.normal.textColor = Color.red;
if (GUILayout.Button("Disengage", s))
{
core.controlRelease(this);
//enabled = false;
}
}
if (minimized)
{
if (GUILayout.Button("Maximize"))
{
minimized = false;
}
}
else
{
if (GUILayout.Button("Minimize"))
{
minimized = true;
}
}
showHelpWindow = GUILayout.Toggle(showHelpWindow, "?", new GUIStyle(GUI.skin.button));
GUILayout.EndHorizontal();
if (!minimized)
{
if (seizeThrottle)
{
desiredOrbitAltitude = ARUtils.doGUITextInput("Orbit altitude: ", 100.0F, desiredOrbitAltitudeKmString, 30.0F, "km", 30.0F, out desiredOrbitAltitudeKmString, desiredOrbitAltitude, 1000.0);
}
else
{
GUILayout.Label(String.Format("Apoapsis: {0:0.0} km", part.vessel.orbit.ApA / 1000.0));