/
MechJebModuleSpaceplaneAutopilot.cs
836 lines (690 loc) · 33.8 KB
/
MechJebModuleSpaceplaneAutopilot.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
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using KSP.Localization;
using UnityEngine;
namespace MuMech
{
[UsedImplicitly]
public class MechJebModuleSpaceplaneAutopilot : ComputerModule
{
public MechJebModuleSpaceplaneAutopilot(MechJebCore core) : base(core) { }
public MechJebModuleAirplaneAutopilot Autopilot => Core.GetComputerModule<MechJebModuleAirplaneAutopilot>();
public MechJebModuleRoverController RoverPilot => Core.GetComputerModule<MechJebModuleRoverController>();
/// <summary>
/// Set to true if reverse thrusters are engaged.
/// </summary>
private bool bEngagedReverseThrusters;
/// <summary>
/// Set to true if user wants reverse thrust upon touchdown.
/// </summary>
public bool bEngageReverseIfAvailable = true;
[Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))]
public bool bBreakAsSoonAsLanded = false;
/// <summary>
/// The runway to land at.
/// </summary>
public Runway runway;
/// <summary>
/// Glide slope angle for approach (3-5 seems to work best).
/// </summary>
[Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))]
public EditableDouble glideslope = 2.5;
/// <summary>
/// The angle between the runway centerline and an intercept to that
/// line where the lines intersect at the final approach point, on
/// both sides. This forms an approach where if the vessel is within
/// the cone, it will align with the final approach point. Otherwise,
/// it will fly towards the initial approach point and then turn
/// around and intercept the glide slope for final approach.
/// </summary>
private const double lateralApproachConeAngle = 30.0;
/// <summary>
/// Final approach distance in meters, at which point the aircraft
/// should be aligned with the runway and only minor adjustments should
/// be required.
/// </summary>
private const double lateralDistanceFromTouchdownToFinalApproach = 5000;
/// <summary>
/// Approach intercept angle; the angle at which the aircraft will
/// intercept the glide slope laterally.
/// </summary>
private const double lateralInterceptAngle = 30.0;
/// <summary>
/// Target angle of attack during flare.
/// </summary>
private const double targetFlareAoA = 15.0;
/// <summary>
/// Altitude in meters when flare will start.
/// </summary>
private const double startFlareAtAltitude = 20.0;
/// <summary>
/// Rate of turn in degrees per second.
/// </summary>
public const double targetRateOfTurn = 3.0;
/// <summary>
/// Minimum approach speed in meters per second. Stall + 10 seems to
/// result in a decent approach and landing.
/// </summary>
[Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))]
public EditableDouble approachSpeed = 80.0;
[Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))]
public EditableDouble touchdownSpeed = 60.0;
/// <summary>
/// Maximum allowed bank angle.
/// </summary>
[Persistent(pass = (int)(Pass.GLOBAL | Pass.LOCAL))]
public EditableDouble maximumSafeBankAngle = 25.0;
/// <summary>
/// Maximum allowed vertical speed to bring the vessel on the glideslope in m/s
/// </summary>
public const double maximumVerticalSpeedCorrection = 10.0;
/// <summary>
/// Angle of attack at the start of flare state.
/// </summary>
private double flareStartAoA;
/// <summary>
/// Angle between centerline and aircraft at the point where
/// the aircraft is perpendicular to the initial approach point
/// at a distance of turn diameter.
/// </summary>
private readonly double angleToFinalApproachPointTurnDiameter = 20.0;
/// <summary>
/// Touchdown AoA and speed recorded for smooth main gear touchdown.
/// </summary>
private double touchdownMomentAoA;
private double touchdownMomentSpeed;
/// <summary>
/// Threshold in seconds to move on to the next waypoint.
/// </summary>
private readonly double secondsThresholdToNextWaypoint = 5.0;
/// <summary>
/// The lowest altitude which may be used which will provide a minimum
/// clearence above all objects in the area.
/// </summary>
private readonly double minimumSectorAltitude = 1500;
public void Autoland(object controller)
{
Users.Add(controller);
Autopilot.Users.Add(this);
RoverPilot.Users.Add(this);
RoverPilot.ControlHeading = false;
RoverPilot.ControlSpeed = false;
approachState = AutolandApproachState.START;
bEngagedReverseThrusters = false;
}
public void AutopilotOff()
{
Users.Clear();
Autopilot.Users.Remove(this);
RoverPilot.Users.Remove(this);
Core.Attitude.attitudeDeactivate();
RoverPilot.ControlHeading = false;
}
public override void OnStart(PartModule.StartState state)
{
if (runways == null && HighLogic.LoadedSceneIsFlight)
InitRunwaysList();
}
protected override void OnModuleDisabled()
{
Core.Attitude.attitudeDeactivate();
}
public enum AutolandApproachState
{
START,
IAP,
FAP,
GLIDESLOPEINTERCEPT,
TOUCHDOWN,
WAITINGFORFLARE,
FLARE,
ROLLOUT
}
public AutolandApproachState approachState = AutolandApproachState.START;
public string AutolandApproachStateToHumanReadableDescription()
{
switch (approachState)
{
case AutolandApproachState.START:
return "";
case AutolandApproachState.IAP:
return Localizer.Format("#MechJeb_ApproAndLand_approachState1"); //Proceeding to the initial approach point
case AutolandApproachState.FAP:
return Localizer.Format("#MechJeb_ApproAndLand_approachState2"); //Proceeding to the final approach point
case AutolandApproachState.GLIDESLOPEINTERCEPT:
return Localizer.Format("#MechJeb_ApproAndLand_approachState3"); //Intercepting the glide slope
case AutolandApproachState.TOUCHDOWN:
return Localizer.Format("#MechJeb_ApproAndLand_approachState4"); //Proceeding to touchdown point
case AutolandApproachState.WAITINGFORFLARE:
return Localizer.Format("#MechJeb_ApproAndLand_approachState5"); //Waiting for flare
case AutolandApproachState.FLARE:
return Localizer.Format("#MechJeb_ApproAndLand_approachState6"); //Flaring
case AutolandApproachState.ROLLOUT:
return Localizer.Format("#MechJeb_ApproAndLand_approachState7"); //Rolling out
}
return "";
}
public override void Drive(FlightCtrlState s)
{
Vector3d vectorToWaypoint = GetAutolandTargetVector();
// Make sure autopilot is enabled properly
if (!Autopilot.HeadingHoldEnabled)
{
Autopilot.EnableHeadingHold();
Autopilot.HeadingTarget = VesselState.vesselHeading;
}
if (Autopilot.AltitudeHoldEnabled)
{
Autopilot.DisableAltitudeHold();
}
if (!Autopilot.VertSpeedHoldEnabled)
{
Autopilot.EnableVertSpeedHold();
Autopilot.VertSpeedTarget = VesselState.speedVertical;
}
if (!Autopilot.SpeedHoldEnabled)
{
Autopilot.EnableSpeedHold();
Autopilot.SpeedTarget = VesselState.speedSurface;
}
// Set autopilot target and max values for navigation
Autopilot.SpeedTarget = GetAutolandTargetSpeed();
Autopilot.HeadingTarget = RoverPilot.heading = GetAutolandTargetHeading(vectorToWaypoint);
Autopilot.VertSpeedTarget = GetAutolandTargetVerticalSpeed(vectorToWaypoint);
if (approachState == AutolandApproachState.FLARE)
{
double exponentPerMeter = (Math.Log(targetFlareAoA + 1) - Math.Log(1)) / startFlareAtAltitude;
double desiredAoA = Math.Exp((startFlareAtAltitude - VesselState.altitudeTrue) * exponentPerMeter) - 1;
//core.attitude.attitudeTo(Autopilot.HeadingTarget, Math.Max(desiredAoA, flareStartAoA), 0, this, true, false, false);
//Autopilot.DisableVertSpeedHold();
}
else if (approachState == AutolandApproachState.TOUCHDOWN)
{
Vessel.ActionGroups.SetGroup(KSPActionGroup.Gear, true);
}
else if (approachState == AutolandApproachState.ROLLOUT)
{
Autopilot.DisableVertSpeedHold();
Autopilot.DisableSpeedHold();
RoverPilot.ControlHeading = true;
// Smoothen the main gear touchdown
double exponentPerMeterPerSecond = (Math.Log(touchdownMomentAoA + 1) - Math.Log(1)) / touchdownMomentSpeed;
double desiredAoA = touchdownMomentAoA -
(Math.Exp(exponentPerMeterPerSecond * (touchdownMomentSpeed - VesselState.speedSurfaceHorizontal)) - 1);
double currentAoA = VesselState.AoA;
Core.Attitude.attitudeTo(Autopilot.HeadingTarget, Math.Min(desiredAoA, currentAoA), 0, this, true, false, false);
// Engage reverse thrusters and full throttle
SetReverseThrusters(bEngageReverseIfAvailable && VesselState.speedSurfaceHorizontal > 10);
if (bEngagedReverseThrusters)
s.mainThrottle = 1;
else
s.mainThrottle = 0;
if (bBreakAsSoonAsLanded)
{
Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, true);
}
else
{
// Apply brakes under 30 (if there are no reversers) otherwise under 10 m/s.
Vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes,
bEngagedReverseThrusters ? VesselState.speedSurfaceHorizontal < 10 : VesselState.speedSurfaceHorizontal < 30);
}
if (VesselState.speedSurface < 1.0)
{
Print("Disengaging autopilot!");
AutopilotOff();
// disable the autopilot if it was manually engaged by the user
Autopilot.Enabled = false;
Core.Thrust.ThrustOff();
}
}
}
private void SetReverseThrusters(bool bEngage)
{
if (bEngage == bEngagedReverseThrusters)
return;
foreach (Part part in Vessel.parts)
{
if (part.IsEngine())
{
foreach (ModuleAnimateGeneric module in part.FindModulesImplementing<ModuleAnimateGeneric>())
{
module.Toggle();
bEngagedReverseThrusters = bEngage;
}
}
}
}
public double GetAutolandTargetAltitude(Vector3d vectorToWaypoint)
{
runway.body.GetLatLonAlt(vectorToWaypoint, out double lat, out double lon, out double alt);
return alt;
}
public double GetAutolandTargetVerticalSpeed(Vector3d vectorToWaypoint)
{
if (approachState == AutolandApproachState.FLARE)
return -1.5;
double timeToWaypoint = LateralDistance(VesselState.CoM, vectorToWaypoint) / VesselState.speedSurfaceHorizontal;
double deltaAlt = GetAutolandTargetAltitude(vectorToWaypoint) - VesselState.altitudeASL;
double vertSpeed = deltaAlt / timeToWaypoint;
// If we are on final, we want to maintain glideslope as much as
// possible so that we don't overshoot or undershoot the runway.
if (approachState == AutolandApproachState.TOUCHDOWN || approachState == AutolandApproachState.FAP)
{
Debug.Assert(vertSpeed < 0);
double latDist = LateralDistance(VesselState.CoM, runway.GetVectorToTouchdown());
Vector3d vectorToCorrectPointOnGlideslope = runway.GetPointOnGlideslope(glideslope, latDist);
double desiredAlt = GetAutolandTargetAltitude(vectorToCorrectPointOnGlideslope);
double deltaToCorrectAlt = desiredAlt - VesselState.altitudeASL;
double expPerMeter = (Math.Log(maximumVerticalSpeedCorrection + 1) - Math.Log(1)) / desiredAlt;
double adjustment = Math.Exp(expPerMeter * Math.Abs(deltaToCorrectAlt)) - 1;
vertSpeed += deltaToCorrectAlt > 0 ? adjustment : -adjustment;
}
return vertSpeed;
}
public double GetAutolandAlignmentError(Vector3d vectorToWaypoint)
{
Vector3d runwayDir = (runway.End() - runway.Start()).normalized;
return Math.Atan2(Vector3d.Dot(runway.Up(), Vector3d.Cross(vectorToWaypoint, runwayDir)), Vector3d.Dot(vectorToWaypoint, runwayDir)) *
UtilMath.Rad2Deg;
}
public double GetAutolandTargetHeading(Vector3d vectorToWaypoint)
{
double targetHeading = VesselState.HeadingFromDirection(vectorToWaypoint);
// If we are on final, align with runway and maintain
switch (approachState)
{
case AutolandApproachState.FAP:
case AutolandApproachState.TOUCHDOWN:
case AutolandApproachState.WAITINGFORFLARE:
case AutolandApproachState.ROLLOUT:
case AutolandApproachState.FLARE:
{
double alignOffset = GetAutolandAlignmentError(vectorToWaypoint);
Debug.Assert(alignOffset < lateralInterceptAngle);
double exponentPerDegreeOfError = (Math.Log(3) - Math.Log(1)) / lateralInterceptAngle;
double offsetMultiplier = Math.Exp((lateralInterceptAngle - Math.Abs(alignOffset)) * exponentPerDegreeOfError);
targetHeading -= alignOffset * offsetMultiplier;
break;
}
}
return targetHeading;
}
public double GetAutolandMaxBankAngle()
{
if (approachState == AutolandApproachState.TOUCHDOWN)
return 10.0;
return maximumSafeBankAngle;
}
public double GetAutolandLateralDistanceFromTouchdownToFinalApproach()
{
// Formula is x = cot(omega) * 2r
return 1.0 / Math.Tan(angleToFinalApproachPointTurnDiameter * UtilMath.Deg2Rad) * GetAutolandTurnRadius() * 2.0 +
lateralDistanceFromTouchdownToFinalApproach;
}
public double GetAutolandTurnRadius()
{
// Formula is r = v / (RoT * (pi/180))
return VesselState.speedSurfaceHorizontal / (GetAutolandMaxRateOfTurn() * UtilMath.Deg2Rad);
}
public double GetAutolandMaxRateOfTurn()
{
// Formula is RoT = (g * (180/pi) * tan(Bank)) / v
return runway.GetGravitationalAcceleration() * UtilMath.Rad2Deg * Math.Tan(GetAutolandTargetBankAngle() * UtilMath.Deg2Rad) /
VesselState.speedSurfaceHorizontal;
}
public double GetAutolandTargetBankAngle()
{
// TODO: return Autopilot.RollLimit;
// Formula is Bank = atan((v * t) / (g * (180/pi)))
return Math.Min(
Math.Atan(VesselState.speedSurfaceHorizontal * targetRateOfTurn / (runway.GetGravitationalAcceleration() * UtilMath.Rad2Deg)) *
UtilMath.Rad2Deg, GetAutolandMaxBankAngle());
}
public double GetAutolandTargetSpeed()
{
if (Vessel.Landed)
return 0;
switch (approachState)
{
case AutolandApproachState.WAITINGFORFLARE:
case AutolandApproachState.TOUCHDOWN:
case AutolandApproachState.FLARE:
return touchdownSpeed;
case AutolandApproachState.FAP:
return (touchdownSpeed + approachSpeed) / 2;
case AutolandApproachState.ROLLOUT:
return 0;
}
return approachSpeed;
}
public double GetAutolandLateralDistanceToNextWaypoint()
{
return LateralDistance(VesselState.CoM, GetAutolandTargetVector());
}
/// <summary>
/// Computes and returns the target vector for approach and autoland.
/// </summary>
/// <returns></returns>
public Vector3d GetAutolandTargetVector()
{
// positions of the start and end of the runway
Vector3d runwayStart = runway.GetVectorToTouchdown();
Vector3d runwayEnd = runway.End();
// get the initial and final approach vectors
Vector3d initialApproachVector = GetInitialApproachPoint();
Vector3d finalApproachVector = GetFinalApproachPoint();
// determine whether the vessel is within the approach cone or not
Vector3d finalApproachVectorProjectedOnGroundPlane = finalApproachVector.ProjectOnPlane(runway.Up());
Vector3d initialApproachVectorProjectedOnGroundPlane = initialApproachVector.ProjectOnPlane(runway.Up());
Vector3d runwayDirectionVectorProjectedOnGroundPlane = (runwayEnd - runwayStart).ProjectOnPlane(runway.Up());
double lateralAngleOfFinalApproachVector =
Vector3d.Angle(finalApproachVectorProjectedOnGroundPlane, runwayDirectionVectorProjectedOnGroundPlane);
double lateralAngleOfInitialApproachVector =
Vector3d.Angle(initialApproachVectorProjectedOnGroundPlane, runwayDirectionVectorProjectedOnGroundPlane);
if (approachState == AutolandApproachState.START)
{
if (lateralAngleOfFinalApproachVector < lateralApproachConeAngle)
{
// We are within the approach cone, we can skip IAP and
// instead start intercepting the glideslope.
approachState = AutolandApproachState.GLIDESLOPEINTERCEPT;
return FindVectorToGlideslopeIntercept(finalApproachVector, lateralAngleOfFinalApproachVector);
}
approachState = AutolandApproachState.IAP;
return initialApproachVector;
}
if (approachState == AutolandApproachState.IAP)
{
if (lateralAngleOfInitialApproachVector > 180 - lateralApproachConeAngle)
{
// We are within the "bad" cone. We have to go all the way
// to IAP without cutting corners.
return initialApproachVector;
}
if (lateralAngleOfFinalApproachVector < lateralApproachConeAngle)
{
// We are in the approach cone, start glideslope intercept.
approachState = AutolandApproachState.GLIDESLOPEINTERCEPT;
return FindVectorToGlideslopeIntercept(finalApproachVector, lateralAngleOfFinalApproachVector);
}
return initialApproachVector;
}
if (approachState == AutolandApproachState.GLIDESLOPEINTERCEPT)
{
Vector3d vectorToGlideslopeIntercept = FindVectorToGlideslopeIntercept(finalApproachVector, lateralAngleOfFinalApproachVector);
// Determine whether we should start turning towards FAP.
double estimatedTimeToTurn = lateralInterceptAngle / GetAutolandMaxRateOfTurn();
double timeToGlideslopeIntercept = LateralDistance(VesselState.CoM, vectorToGlideslopeIntercept) / VesselState.speedSurfaceHorizontal;
if (estimatedTimeToTurn >= timeToGlideslopeIntercept)
{
approachState = AutolandApproachState.FAP;
return finalApproachVector;
}
// Otherwise, continue flying towards the glideslope intercept.
return vectorToGlideslopeIntercept;
}
if (approachState == AutolandApproachState.FAP)
{
if (lateralAngleOfFinalApproachVector > lateralInterceptAngle)
{
// Cancel final approach, go back to initial approach.
approachState = AutolandApproachState.IAP;
return initialApproachVector;
}
double timeToFAP = LateralDistance(VesselState.CoM, finalApproachVector) / VesselState.speedSurfaceHorizontal;
if (GetAutolandAlignmentError(finalApproachVector) < 3.0 && timeToFAP < secondsThresholdToNextWaypoint)
{
approachState = AutolandApproachState.TOUCHDOWN;
return runway.GetVectorToTouchdown();
}
return finalApproachVector;
}
if (approachState == AutolandApproachState.TOUCHDOWN)
{
if (VesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude + 5)
{
approachState = AutolandApproachState.WAITINGFORFLARE;
return runway.End();
}
return runway.GetVectorToTouchdown();
}
if (approachState == AutolandApproachState.WAITINGFORFLARE)
{
if (VesselState.altitudeASL < runway.start.altitude + startFlareAtAltitude)
{
approachState = AutolandApproachState.FLARE;
flareStartAoA = VesselState.AoA;
}
return runway.End();
}
if (approachState == AutolandApproachState.FLARE)
{
if (Vessel.Landed)
{
Print("Vessel landed!");
touchdownMomentAoA = VesselState.AoA;
touchdownMomentSpeed = VesselState.speedSurfaceHorizontal;
approachState = AutolandApproachState.ROLLOUT;
}
return runway.End();
}
if (approachState == AutolandApproachState.ROLLOUT)
{
return runway.End();
}
Debug.Assert(false);
return runway.Start();
}
/// <summary>
/// Returns the final approach point (FAP/FAF)
/// </summary>
/// <returns></returns>
public Vector3d GetFinalApproachPoint()
{
return runway.GetPointOnGlideslope(glideslope, lateralDistanceFromTouchdownToFinalApproach - runway.touchdownPoint);
}
/// <summary>
/// Returns the initial approach point (IAP/IAF)
/// </summary>
/// <returns></returns>
public Vector3d GetInitialApproachPoint()
{
Vector3d iap = runway.GetPointOnGlideslope(glideslope, GetAutolandLateralDistanceFromTouchdownToFinalApproach() - runway.touchdownPoint);
iap = PreventClimbingIntoGlideslope(iap);
iap = MaintainMinimalAltitude(iap);
return iap;
}
/// <summary>
/// Stops the vessel from climbing into the glideslope. If the vessel is below the glideslope maintain
/// the current altitude until we intercept the glide slope.
/// </summary>
/// <returns></returns>
private Vector3d PreventClimbingIntoGlideslope(Vector3d v)
{
runway.body.GetLatLonAlt(v, out double lat, out double lon, out double alt);
if (alt <= VesselState.altitudeASL)
return v;
return runway.body.GetWorldSurfacePosition(lat, lon, VesselState.altitudeASL);
}
/// <summary>
/// If the vessel is very low, we have to maintain a minimal altitude to prevent the vessel from crashing.
/// </summary>
/// <returns></returns>
private Vector3d MaintainMinimalAltitude(Vector3d v)
{
runway.body.GetLatLonAlt(v, out double lat, out double lon, out double alt);
if (alt >= minimumSectorAltitude)
return v;
return runway.body.GetWorldSurfacePosition(lat, lon, minimumSectorAltitude);
}
/// <summary>
/// Finds a point on the glide slope intercept where the angle between
/// vessel and the point is lateralInterceptAngle degrees.
/// </summary>
/// <param name="finalApproachVector"></param>
/// <param name="lateralAngleOfFinalApproachVector"></param>
/// <returns></returns>
private Vector3d FindVectorToGlideslopeIntercept(Vector3d finalApproachVector, double lateralAngleOfFinalApproachVector)
{
// Determine the three angles of the triangle, one of which is
// the lateral angle of final approach vector, and the other is
// 180 - lateral intercept angle.
double theta = 180 - lateralInterceptAngle;
double omega = 180 - lateralAngleOfFinalApproachVector - theta;
// We know the lateral distance to the final approach point, we
// want to find a point on the glide slope which we can
// intercept at a given angle.
double dist = LateralDistance(VesselState.CoM, finalApproachVector) * Math.Sin(UtilMath.Deg2Rad * omega) /
Math.Sin(UtilMath.Deg2Rad * theta);
// If this is a bad intercept, proceed to IAP.
if (dist < lateralDistanceFromTouchdownToFinalApproach)
{
approachState = AutolandApproachState.IAP;
return GetInitialApproachPoint();
}
Vector3d pointOnLocalizer = runway.GetPointOnGlideslope(glideslope, dist + lateralDistanceFromTouchdownToFinalApproach);
return PreventClimbingIntoGlideslope(pointOnLocalizer);
}
private double LateralDistance(Vector3d v1, Vector3d v2)
{
return Vector3d.Distance(v1.ProjectOnPlane(runway.Up()), v2.ProjectOnPlane(runway.Up()));
}
public static List<Runway> runways;
private void InitRunwaysList()
{
runways = new List<Runway>();
// Import landing sites form a user createded .cfg
foreach (UrlDir.UrlConfig mjConf in GameDatabase.Instance.GetConfigs("MechJeb2Landing"))
{
foreach (ConfigNode site in mjConf.config.GetNode("Runways").GetNodes("Runway"))
{
string runwayName = site.GetValue("name");
ConfigNode start = site.GetNode("start");
ConfigNode end = site.GetNode("end");
double touchdown = 0.0;
double.TryParse(site.GetValue("touchdown"), out touchdown);
if (runwayName == null || start == null || end == null)
continue;
string lat = start.GetValue("latitude");
string lon = start.GetValue("longitude");
string alt = start.GetValue("altitude");
if (lat == null || lon == null || alt == null)
continue;
double startLatitude, startLongitude, startAltitude;
double.TryParse(lat, out startLatitude);
double.TryParse(lon, out startLongitude);
double.TryParse(alt, out startAltitude);
lat = end.GetValue("latitude");
lon = end.GetValue("longitude");
alt = end.GetValue("altitude");
if (lat == null || lon == null || alt == null)
continue;
double endLatitude, endLongitude, endAltitude;
double.TryParse(lat, out endLatitude);
double.TryParse(lon, out endLongitude);
double.TryParse(alt, out endAltitude);
string bodyName = site.GetValue("body");
CelestialBody body = bodyName != null ? FlightGlobals.Bodies.Find(b => b.bodyName == bodyName) : Planetarium.fetch.Home;
if (body != null && !runways.Any(p => p.name == runwayName))
{
runways.Add(new Runway
{
name = runwayName,
body = body,
touchdownPoint = touchdown,
start = new Runway.Endpoint { latitude = startLatitude, longitude = startLongitude, altitude = startAltitude },
end = new Runway.Endpoint { latitude = endLatitude, longitude = endLongitude, altitude = endAltitude }
});
}
}
}
// TODO: deploy LandingSites.cfg?
if (!runways.Any(p => p.name == "KSC Runway 09"))
runways.Add(new Runway
{
name = "KSC Runway 09",
body = Planetarium.fetch.Home,
start = new Runway.Endpoint { latitude = -0.0485981, longitude = -74.726413, altitude = 69.01 },
end = new Runway.Endpoint { latitude = -0.050185, longitude = -74.490867, altitude = 69.01 },
touchdownPoint = 100.0
});
if (!runways.Any(p => p.name == "KSC Runway 27"))
runways.Add(new Runway
{
name = "KSC Runway 27",
body = Planetarium.fetch.Home,
start = new Runway.Endpoint { latitude = -0.050185, longitude = -74.490867, altitude = 69.01 },
end = new Runway.Endpoint { latitude = -0.0485981, longitude = -74.726413, altitude = 69.01 },
touchdownPoint = 100.0
});
if (!runways.Any(p => p.name == "Island Runway 09"))
runways.Add(new Runway
{
name = "Island Runway 09",
body = Planetarium.fetch.Home,
start = new Runway.Endpoint { latitude = -1.517306, longitude = -71.965488, altitude = 133.17 },
end = new Runway.Endpoint { latitude = -1.515980, longitude = -71.852408, altitude = 133.17 },
touchdownPoint = 25.0
});
if (!runways.Any(p => p.name == "Island Runway 27"))
runways.Add(new Runway
{
name = "Island Runway 27",
body = Planetarium.fetch.Home,
start = new Runway.Endpoint { latitude = -1.515980, longitude = -71.852408, altitude = 133.17 },
end = new Runway.Endpoint { latitude = -1.517306, longitude = -71.965488, altitude = 133.17 },
touchdownPoint = 25.0
});
}
}
public struct Runway
{
public struct Endpoint
{
public double latitude;
public double longitude;
public double altitude;
public Vector3d Position(CelestialBody body)
{
return body.GetWorldSurfacePosition(latitude, longitude, altitude);
}
public Vector3d Up(CelestialBody body)
{
return body.GetSurfaceNVector(latitude, longitude);
}
}
public string name;
public double touchdownPoint;
public CelestialBody body;
public Endpoint start;
public Endpoint end;
public Vector3d Start() { return start.Position(body); }
public Vector3d End() { return end.Position(body); }
public Vector3d Up() { return start.Up(body); }
public double GetGravitationalAcceleration()
{
return body.GeeASL * 9.81;
}
public Vector3d GetVectorToTouchdown()
{
Vector3d runwayStart = Start();
Vector3d runwayEnd = End();
Vector3d runwayDir = (runwayEnd - runwayStart).normalized;
runwayStart += touchdownPoint * runwayDir;
return runwayStart;
}
public Vector3d GetPointOnGlideslope(double glideslope, double distanceOnCenterline)
{
Vector3d runwayStart = Start();
Vector3d runwayEnd = End();
Vector3d runwayDir = (runwayEnd - runwayStart).normalized;
Vector3d pointOnGlideslope = runwayStart - distanceOnCenterline * runwayDir;
double altitude = start.altitude + Math.Tan(glideslope * Mathf.Deg2Rad) * distanceOnCenterline;
body.GetLatLonAlt(pointOnGlideslope, out double latAtDistance, out double lonAtDistance, out double altAtDistance);
return body.GetWorldSurfacePosition(latAtDistance, lonAtDistance, altitude);
}
}
}