forked from Majiir/MuMechLib
/
MechJebModuleRendezvous.cs
1192 lines (980 loc) · 46.4 KB
/
MechJebModuleRendezvous.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 OrbitExtensions;
namespace MuMech
{
public class MechJebModuleRendezvous : ComputerModule
{
public MechJebModuleRendezvous(MechJebCore core) : base(core) { }
public override string getName()
{
return "Rendezvous Module";
}
//advanced autopilot capabilities can be turned on or off in the .cfg file with the automation variable.
public bool automation = true;
#region UI State
protected Rect WindowPos;
private Vector2 _scrollPosition = new Vector2(0, 0);
public enum UIMode
{
OFF,
TARGET_SELECTION,
SELECTED,
RENDEZVOUS,
ALIGN,
SYNC
}
protected static string[] sel_texts = { "Bodies", "Debris", "Vessels" };
public enum TgtMode
{
BODIES,
DEBRIS,
VESSELS
}
public TgtMode TargetMode = TgtMode.BODIES;
private UIMode _mode = UIMode.TARGET_SELECTION;
private bool _modeChanged;
public UIMode Mode
{
get { return _mode; }
set
{
if (_mode == value)
return;
_mode = value;
_modeChanged = true;
}
}
private int _selectedFlyMode;
/// <summary>
/// The selected vessel's location in FlightGlobals.Vessels[LIST].
/// </summary>
private int _selectedVesselIndex;
/// <summary>
/// Unique Instance ID of selected vessel
/// </summary>
private int _selectedVesselInstanceId;
NavBall navball;
Transform defaultPurpleWaypoint;
bool waypointHijacked = false;
#endregion
#region Sync State
private const int NumberOfPredictedSyncPoints = 4;
public enum SynchronizationType
{
TargetPeriapsis,
TargetApoapsis,
ShipPeriapsis,
ShipApoapsis
}
public SynchronizationType SyncMode = SynchronizationType.TargetPeriapsis;
private double _minimumPredictedTimeFromTarget;
private double _rendezvousAnomaly = 180;
private readonly float[] _shipTimeToRendezvous = new float[4];
private readonly float[] _targetTimeToRendezvous = new float[4];
private readonly string[] _syncString = new string[4];
private int _closestApproachOrbit;
private double _rendezvousRecalculationTimer;
#endregion
#region Auto Align State
private bool _autoAlign = false;
private bool _autoAlignBurnTriggered = false;
#endregion
#region Orbit Phaser State
private bool _autoPhaser = false;
private enum AutoPhaserState
{
// To auto sync:
// (I believe apo/peri can be swapped through this.)
// 1. Wait till we hit apoapsis of target.
Step1WaitForTargetApsis,
// 2. Burn to match periapsis of target.
Step2BurnToMatchNextApsis,
// 3. Wait till we hit periapsis.
Step3WaitForTargetApsis,
// 4. Accelerate until one of next N orbits has a rendezvous time match.
Step4BurnToRendezvous,
// 5. Wait till we hit that time.
Step5WaitForRendezvous,
// 6. Match orbital velocity with target.
Step6BurnToMatchVelocity
};
private AutoPhaserState _autoPhaserState;
private double _autoPhaserVelocityGoal;
private bool _autoPhaseBurnComplete = false;
#endregion
#region Rendezvous State
private Vector3 _relativeVelocity;
private float _relativeInclination;
private Vector3 _vectorToTarget;
private float _targetDistance;
private bool _killRelativeVelocity = false;
private Vector3 _localRelativeVelocity = Vector3.zero;
private bool _homeOnRelativePosition = false;
private Vector3 _localRelativePosition = Vector3.zero;
#endregion
#region Warp State
double[] warpLookaheadTimes = new double[] { 0, 10, 20, 25, 50, 500, 5000, 500000 };
#endregion
#region FlyByWire PID Controller State
public enum Orient
{
Off,
RelativeVelocity,
RelativeVelocityAway,
Target,
TargetAway,
Normal,
AntiNormal,
MatchTarget,
MatchTargetAway,
Prograde,
Retrograde
}
public string[] ControlModeCaptions = new[] { "RVel+", "Rvel-", "TGT+", "TGT-", "Match+", "Match-" };
public string[] AlignmentCaptions = new[] { "NML\n+", "NML\n-" };
public Orient PointAt = Orient.Off;
private bool _flyByWire;
private Vector3 _tgtFwd;
private Vector3 _tgtUp;
private Vector3 _deriv = Vector3.zero;
private Vector3 _integral = Vector3.zero;
private Vector3 _headingError = Vector3.zero;
private Vector3 _prevErr = Vector3.zero;
private Vector3 _act = Vector3.zero;
public float Kp = 20.0F;
public float Ki = 0.0F;
public float Kd = 40.0F;
#endregion
#region User Interface
protected override void WindowGUI(int windowID)
{
// Set up the UI style.
var but = new GUIStyle(GUI.skin.button);
but.normal.textColor = but.focused.textColor = Color.white;
but.hover.textColor = but.active.textColor = Color.yellow;
but.onNormal.textColor = but.onFocused.textColor = but.onHover.textColor = but.onActive.textColor = Color.green;
but.padding = new RectOffset(8, 8, 8, 8);
var sty = new GUIStyle(GUI.skin.label);
GUILayout.BeginVertical();
if (Mode == UIMode.OFF)
RenderOffUI(sty, but);
if (Mode == UIMode.TARGET_SELECTION)
RenderTargetSelectUI(sty, but);
if (Mode == UIMode.SELECTED)
RenderTargetInfoUI(sty, but);
/* used to reroute vessels and debris to old menus
if (Mode == UIMode.SELECTED && core.targetType==MechJebCore.TargetType.BODY)
RenderTargetInfoUI(sty,but);
if (Mode == UIMode.SELECTED && core.targetType!=MechJebCore.TargetType.BODY)
RenderSelectedUI(sty,but);
*/
if (Mode == UIMode.ALIGN)
RenderAlignUI(sty, but);
// TIME TO NODES
// BURN TIMER?
// DELTA RINC
// ORIENTATION FOR NEXT BURN (NORMAL/ANTINORMAL)
// AUTOPILOT(NORMAL/ANTINORMAL)
if (Mode == UIMode.SYNC)
RenderSyncUI(sty, but);
if (Mode == UIMode.RENDEZVOUS)
RenderRendezvousUI(sty, but);
GUILayout.EndVertical();
GUI.DragWindow();
}
private void RenderOffUI(GUIStyle sty, GUIStyle but)
{
if (GUILayout.Button("OPEN", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.TARGET_SELECTION;
}
}
private void RenderTargetInfoUI(GUIStyle sty, GUIStyle but)
{
windowPos = new Rect(windowPos.x, windowPos.y, 10, 10);
GUILayout.BeginVertical();
if (GUILayout.Button("Back", but))
{
Mode = UIMode.TARGET_SELECTION;
core.setTarget();
}
//align planes data
GUILayout.Label("Time to AN : " + part.vessel.orbit.GetTimeToRelAN(core.targetOrbit()).ToString("F2"), sty);
GUILayout.Label("Time to DN : " + part.vessel.orbit.GetTimeToRelDN(core.targetOrbit()).ToString("F2"), sty);
GUILayout.Label("Relative Inclination :" + (core.targetOrbit().inclination - vesselState.orbitInclination).ToString("F2"), sty);
//rendevous data
if (core.distanceFromTarget() > 10000)
{
GUILayout.Label("Distance: " + (core.distanceFromTarget() / 1000).ToString("F1") + "km", GUILayout.Width(300));
}
else
{
GUILayout.Label("Distance: " + core.distanceFromTarget().ToString("F1") + "m", GUILayout.Width(300));
}
GUILayout.Label("Relative Velocity: " + core.relativeVelocityToTarget().magnitude.ToString("F2"));
GUILayout.EndVertical();
}
private void RenderTargetSelectUI(GUIStyle sty, GUIStyle but)
{
GUILayout.Label("Select Target", sty);
TargetMode = (TgtMode)GUILayout.SelectionGrid((int)TargetMode, sel_texts, 3, but);
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, GUILayout.Width(300), GUILayout.Height(300));
List<Vessel> vesselList = new List<Vessel>(FlightGlobals.Vessels);
List<CelestialBody> bodyList = new List<CelestialBody>(FlightGlobals.Bodies);
switch (TargetMode)
{
case TgtMode.BODIES:
for (int i = 1; i < bodyList.Count; i++)
{
if (bodyList[i].orbit.referenceBody != this.part.vessel.orbit.referenceBody)
continue;
if (GUILayout.Button(bodyList[i].name, but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
core.setTarget(bodyList[i]);
}
}
break;
case TgtMode.DEBRIS:
for (int i = 0; i < vesselList.Count; i++)
{
// skip real vessels
if (vesselList[i].isCommandable == true)
continue;
// Skip stuff around other worlds.
if (part.vessel.orbit.referenceBody != vesselList[i].orbit.referenceBody)
continue;
if (GUILayout.Button(vesselList[i].vesselName, but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
_selectedVesselInstanceId = vesselList[i].GetInstanceID();
_selectedVesselIndex = FlightGlobals.Vessels.IndexOf(vesselList[i]);
core.setTarget(vesselList[i]);
}
}
break;
case TgtMode.VESSELS:
var vdc = new VesselDistanceComparer();
vdc.OriginVessel = part.vessel;
vesselList.Sort(vdc);
for (int i = 0; i < vesselList.Count; i++)
{
// Skip ourselves.
if (vesselList[i] == part.vessel)
continue;
if (vesselList[i].LandedOrSplashed)
continue;
// Skip stuff around other worlds.
if (part.vessel.orbit.referenceBody != vesselList[i].orbit.referenceBody)
continue;
//Skip Debris
if (vesselList[i].isCommandable == false)
continue;
// Calculate the distance.
float d = Vector3.Distance(vesselList[i].transform.position, part.vessel.transform.position);
if (GUILayout.Button((d / 1000).ToString("F1") + "km " + vesselList[i].vesselName, but,
GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
_selectedVesselInstanceId = vesselList[i].GetInstanceID();
_selectedVesselIndex = FlightGlobals.Vessels.IndexOf(vesselList[i]);
core.setTarget(vesselList[i]);
}
}
break;
}
GUILayout.EndScrollView();
}
private void RenderVesselsUI(GUIStyle sty, GUIStyle but)
{
GUILayout.Box("Select Target", sty);
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, GUILayout.Width(300), GUILayout.Height(300));
// Generate and sort an array of vessels by distance.
List<Vessel> vesselList = new List<Vessel>(FlightGlobals.Vessels);
var vdc = new VesselDistanceComparer();
vdc.OriginVessel = part.vessel;
vesselList.Sort(vdc);
for (int i = 0; i < vesselList.Count; i++)
{
// Skip ourselves.
if (vesselList[i] == part.vessel)
continue;
if (vesselList[i].LandedOrSplashed)
continue;
// Skip stuff around other worlds.
if (part.vessel.orbit.referenceBody != vesselList[i].orbit.referenceBody)
continue;
// Calculate the distance.
float d = Vector3.Distance(vesselList[i].transform.position, part.vessel.transform.position);
if (GUILayout.Button((d / 1000).ToString("F1") + "km " + vesselList[i].vesselName, but,
GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
_selectedVesselInstanceId = vesselList[i].GetInstanceID();
_selectedVesselIndex = FlightGlobals.Vessels.IndexOf(vesselList[i]);
core.setTarget(vesselList[i]);
}
}
GUILayout.EndScrollView();
}
private void RenderSelectedUI(GUIStyle sty, GUIStyle but)
{
if (core.targetType == MechJebCore.TargetType.VESSEL)
{
if (!CheckVessel())
{
_flyByWire = false;
Mode = UIMode.TARGET_SELECTION;
}
}
if (GUILayout.Button((FlightGlobals.Vessels[_selectedVesselIndex].vesselName), but, GUILayout.ExpandWidth(true)))
{
_flyByWire = false;
Mode = UIMode.TARGET_SELECTION;
core.setTarget();
}
if (GUILayout.Button("Align Planes", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.ALIGN;
}
if (GUILayout.Button("Sync Orbits", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SYNC;
}
if (GUILayout.Button("Rendezvous", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.RENDEZVOUS;
}
}
private void RenderAlignUI(GUIStyle sty, GUIStyle but)
{
if (!CheckVessel())
{
_flyByWire = false;
Mode = UIMode.SELECTED;
}
if (GUILayout.Button("Align Planes", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
_flyByWire = false;
}
GUILayout.Box("Time to AN : " + part.vessel.orbit.GetTimeToRelAN(FlightGlobals.Vessels[_selectedVesselIndex].orbit).ToString("F2"));
GUILayout.Box("Time to DN : " + part.vessel.orbit.GetTimeToRelDN(FlightGlobals.Vessels[_selectedVesselIndex].orbit).ToString("F2"));
GUILayout.Box("Relative Inclination :" + _relativeInclination.ToString("F2"));
if (automation == true)
{
if (GUILayout.Button(_autoAlign ? "ALIGNING" : "Auto-Align", but, GUILayout.ExpandWidth(true)))
{
_autoAlignBurnTriggered = false;
_autoAlign = !_autoAlign;
}
}
if (_flyByWire == false)
{
if (GUILayout.Button("Orbit Normal", but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.Normal;
}
if (GUILayout.Button("Anti Normal", but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.AntiNormal;
}
}
if (_flyByWire)
{
if (GUILayout.Button("Disable " + PointAt.ToString(), but, GUILayout.ExpandWidth(true)))
{
FlightInputHandler.SetNeutralControls();
_flyByWire = false;
_modeChanged = true;
}
}
}
private void RenderSyncUI(GUIStyle sty, GUIStyle but)
{
if (!CheckVessel())
{
_flyByWire = false;
Mode = UIMode.SELECTED;
}
if (GUILayout.Button("Sync Orbits", but, GUILayout.ExpandWidth(true)))
{
Mode = UIMode.SELECTED;
_flyByWire = false;
}
GUILayout.EndVertical();
GUILayout.BeginHorizontal();
for (int i = 0; i < NumberOfPredictedSyncPoints; i++)
{
if (i != (int)SyncMode)
continue;
if (GUILayout.Button(SyncMode.ToString(), but, GUILayout.ExpandWidth(true)))
{
if (i == NumberOfPredictedSyncPoints - 1) SyncMode = 0;
else SyncMode = SyncMode + 1;
}
//GUILayout.Box(SyncMode.ToString(),but);
}
GUILayout.EndHorizontal();
GUILayout.BeginVertical();
GUILayout.Box("Orbit ShipToR TgtToR ", GUILayout.ExpandWidth(true));
for (int i = 0; i < 4; i++)
GUILayout.Box(_syncString[i]);
GUILayout.Label("Closest Approach on Orbit " + _closestApproachOrbit.ToString(), sty);
GUILayout.Label("Min Separation (sec) : " + _minimumPredictedTimeFromTarget.ToString("f1"), sty);
if (automation == true)
{
if (GUILayout.Button(_autoPhaser ? _autoPhaserState.ToString() : "Auto Sync", but, GUILayout.ExpandWidth(true)))
{
_autoPhaser = !_autoPhaser;
_autoPhaserState = AutoPhaserState.Step1WaitForTargetApsis;
}
}
}
private void RenderRendezvousUI(GUIStyle sty, GUIStyle but)
{
if (!CheckVessel())
{
_flyByWire = false;
Mode = UIMode.SELECTED;
}
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
if (GUILayout.Button(selectedVessel.vesselName, but, GUILayout.ExpandWidth(true)))
{
_flyByWire = false;
Mode = UIMode.SELECTED;
}
if (_targetDistance > 10000)
{
GUILayout.Box("Distance: " + (_targetDistance / 1000).ToString("F1") + "km", GUILayout.Width(300));
}
else
{
GUILayout.Box("Distance: " + _targetDistance.ToString("F1") + "m", GUILayout.Width(300));
}
GUILayout.Box("Rel Inc : " + _relativeInclination.ToString("F3"));
GUILayout.Box("Rel VelM: " + _relativeVelocity.magnitude.ToString("F2"));
// Take the relative velocity and project into ship local space.
_localRelativeVelocity = part.vessel.transform.worldToLocalMatrix.MultiplyVector(_relativeVelocity);
_localRelativePosition = part.vessel.transform.worldToLocalMatrix.MultiplyPoint(selectedVessel.transform.position);
if (automation == true)
{
if (GUILayout.Button(_killRelativeVelocity == false ? "Kill Rel Vel" : "FIRING", but, GUILayout.ExpandWidth(true)))
_killRelativeVelocity = !_killRelativeVelocity;
if (GUILayout.Button(_homeOnRelativePosition == false ? "Home on Y+ 5m" : "HOMING", but, GUILayout.ExpandWidth(true)))
_homeOnRelativePosition = !_homeOnRelativePosition;
}
GUILayout.Box("Rel Vel : " + _localRelativeVelocity.x.ToString("F2") + ", " + _localRelativeVelocity.y.ToString("F2") + ", " + _localRelativeVelocity.z.ToString("F2"));
if (_targetDistance > 10000)
{
GUILayout.Box("Rel Pos : " + (_localRelativePosition.x / 1000).ToString("F2") + "km, " + (_localRelativePosition.y / 1000).ToString("F2") + "km, " + (_localRelativePosition.z / 1000).ToString("F2") + "km");
}
else
{
GUILayout.Box("Rel Pos : " + _localRelativePosition.x.ToString("F2") + ", " + _localRelativePosition.y.ToString("F2") + ", " + _localRelativePosition.z.ToString("F2"));
}
if (_flyByWire == false)
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(ControlModeCaptions[0], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.RelativeVelocity;
_modeChanged = true;
_selectedFlyMode = 0;
}
if (GUILayout.Button(ControlModeCaptions[1], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.RelativeVelocityAway;
_modeChanged = true;
_selectedFlyMode = 1;
}
if (GUILayout.Button(ControlModeCaptions[2], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.Target;
_modeChanged = true;
_selectedFlyMode = 2;
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button(ControlModeCaptions[3], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.TargetAway;
_modeChanged = true;
_selectedFlyMode = 3;
}
if (GUILayout.Button(ControlModeCaptions[4], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.MatchTarget;
_modeChanged = true;
_selectedFlyMode = 4;
}
if (GUILayout.Button(ControlModeCaptions[5], but, GUILayout.ExpandWidth(true)))
{
_flyByWire = true;
PointAt = Orient.MatchTargetAway;
_modeChanged = true;
_selectedFlyMode = 5;
}
GUILayout.EndHorizontal();
}
if (_flyByWire)
{
if (GUILayout.Button("Disable " + ControlModeCaptions[_selectedFlyMode], but, GUILayout.ExpandWidth(true)))
{
FlightInputHandler.SetNeutralControls();
_flyByWire = false;
_modeChanged = true;
}
}
}
#endregion
#region Control Logic
/// <summary>
/// Checks if the selected vessel is still where we expect it.
/// </summary>
/// <returns>
/// The vessel.
/// </returns>
private bool CheckVessel()
{
//does Vessels[selVessel] contain a vessel?
if (FlightGlobals.Vessels.Count - 1 < _selectedVesselIndex)
return false;
// Does the ID match the vessel selected?
int id = FlightGlobals.Vessels[_selectedVesselIndex].GetInstanceID();
if (id == _selectedVesselInstanceId)
return true;
// doesn't match, search vessels for matching id
for (int i = 0; i < FlightGlobals.Vessels.Count; i++)
{
id = FlightGlobals.Vessels[i].GetInstanceID();
if (id != _selectedVesselInstanceId)
continue;
// found it!
_selectedVesselIndex = i;
return true;
}
// Couldn't find it.
return false;
}
/// <summary>
/// Updates the vectors.
/// </summary>
private void UpdateVectors()
{
Vector3 up = (part.vessel.findWorldCenterOfMass() - part.vessel.mainBody.position).normalized;
Vector3 prograde = part.vessel.orbit.GetRelativeVel().normalized;
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
_relativeVelocity = selectedVessel.orbit.GetVel() - part.vessel.orbit.GetVel();
_vectorToTarget = selectedVessel.transform.position - part.vessel.transform.position;
_targetDistance = Vector3.Distance(selectedVessel.transform.position, part.vessel.transform.position);
_relativeInclination = (float)selectedVessel.orbit.inclination - (float)part.vessel.orbit.inclination;
switch (PointAt)
{
case Orient.RelativeVelocity:
_tgtFwd = _relativeVelocity;
_tgtUp = Vector3.Cross(_tgtFwd.normalized, part.vessel.orbit.vel.normalized);
break;
case Orient.RelativeVelocityAway:
_tgtFwd = -_relativeVelocity;
_tgtUp = Vector3.Cross(_tgtFwd.normalized, part.vessel.orbit.vel.normalized);
break;
case Orient.Target:
_tgtFwd = _vectorToTarget;
_tgtUp = Vector3.Cross(_tgtFwd.normalized, part.vessel.orbit.vel.normalized);
break;
case Orient.TargetAway:
_tgtFwd = -_vectorToTarget;
_tgtUp = Vector3.Cross(_tgtFwd.normalized, part.vessel.orbit.vel.normalized);
break;
case Orient.Normal:
_tgtFwd = Vector3.Cross(prograde, up);
_tgtUp = up;
break;
case Orient.AntiNormal:
_tgtFwd = -Vector3.Cross(prograde, up);
_tgtUp = up;
break;
case Orient.MatchTarget:
_tgtFwd = selectedVessel.transform.up;
_tgtUp = selectedVessel.transform.right;
break;
case Orient.MatchTargetAway:
_tgtFwd = -selectedVessel.transform.up;
_tgtUp = selectedVessel.transform.right;
break;
case Orient.Prograde:
_tgtFwd = part.vessel.rigidbody.velocity.normalized;
_tgtUp = new Vector3(0, 0, 1);
break;
case Orient.Retrograde:
_tgtFwd = -part.vessel.rigidbody.velocity.normalized;
_tgtUp = new Vector3(0, 0, 1);
break;
}
}
private void CalculateNearestRendezvousInSeconds(out double timeToRendezvous, out double minDeltaTime)
{
// Build up the times for apses for the next 4 orbis for the target.
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
// Find the next few times of apsis for the target and the ship.
double targetApoapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 180);
double targetPeriapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 0);
double[] targetApses = new double[8];
double[] shipApses = new double[8];
for (int i = 0; i < 4; i++)
{
targetApses[i * 2 + 0] = selectedVessel.orbit.GetTimeToTrue(0) + i * selectedVessel.orbit.period;
targetApses[i * 2 + 1] = selectedVessel.orbit.GetTimeToTrue(0) + i * selectedVessel.orbit.period;
shipApses[i * 2 + 0] = part.vessel.orbit.GetTimeToTrue(targetApoapsisAnomaly) + i * part.vessel.orbit.period;
shipApses[i * 2 + 1] = part.vessel.orbit.GetTimeToTrue(targetPeriapsisAnomaly) + i * part.vessel.orbit.period;
}
// Walk the lists and find the nearest times. This could be optimized
// but it doesn't matter.
double closestPeriDeltaT = double.MaxValue;
int closestPeriIndex = -1;
double closestApoDeltaT = double.MaxValue;
int closestApoIndex = -1;
for (int i = 0; i < 4; i++)
{
double shipApoT = shipApses[i * 2 + 0];
double shipPeriT = shipApses[i * 2 + 1];
for (int j = 0; j < 4; j++)
{
double targApoT = targetApses[j * 2 + 0];
double deltaApo = Math.Abs(shipApoT - targApoT);
if (deltaApo < closestApoDeltaT)
{
closestApoDeltaT = deltaApo;
closestApoIndex = j * 2 + 0;
}
double targPeriT = targetApses[j * 2 + 1];
double deltaPeri = Math.Abs(shipPeriT - targPeriT);
if (deltaPeri < closestPeriDeltaT)
{
closestPeriDeltaT = deltaPeri;
closestPeriIndex = j * 2 + 1;
}
}
}
if (closestApoDeltaT < closestPeriDeltaT)
{
timeToRendezvous = shipApses[closestApoIndex];
minDeltaTime = closestApoDeltaT;
}
else
{
timeToRendezvous = shipApses[closestPeriIndex];
minDeltaTime = closestPeriDeltaT;
}
}
private double CalculateTimeTillNextTargetApsis()
{
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
double targetApoapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 180);
double targetPeriapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 0);
double shipTimeToTargetApoapsis = part.vessel.orbit.GetTimeToTrue(targetApoapsisAnomaly);
double shipTimeToTargetPeriapsis = part.vessel.orbit.GetTimeToTrue(targetPeriapsisAnomaly);
return Math.Min(shipTimeToTargetApoapsis, shipTimeToTargetPeriapsis);
}
private double CalculateTimeTillFurtherTargetApsis()
{
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
double targetApoapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 180);
double targetPeriapsisAnomaly = selectedVessel.orbit.TranslateAnomaly(part.vessel.orbit, 0);
double shipTimeToTargetApoapsis = part.vessel.orbit.GetTimeToTrue(targetApoapsisAnomaly);
double shipTimeToTargetPeriapsis = part.vessel.orbit.GetTimeToTrue(targetPeriapsisAnomaly);
return Math.Max(shipTimeToTargetApoapsis, shipTimeToTargetPeriapsis);
}
private void DriveShip(FlightCtrlState controls)
{
if (!CheckVessel())
return;
Vessel selectedVessel = FlightGlobals.Vessels[_selectedVesselIndex] as Vessel;
if (_autoAlign)
{
// Is it time to burn? Find soonest node.
double timeToBurnAN = part.vessel.orbit.GetTimeToRelAN(selectedVessel.orbit);
double timeToBurnDN = part.vessel.orbit.GetTimeToRelDN(selectedVessel.orbit);
bool ascendingSoonest = timeToBurnAN < timeToBurnDN;
double timeToBurnNode = ascendingSoonest ? timeToBurnAN : timeToBurnDN;
if (timeToBurnNode > 30)
{
core.warpTo(this, timeToBurnNode - 30, warpLookaheadTimes);
}
// Figure out which way we want to burn to adjust our inclination.
_flyByWire = true;
if (!_autoAlignBurnTriggered)
{
if (_relativeInclination < 0.0)
PointAt = ascendingSoonest ? Orient.Normal : Orient.AntiNormal;
else
PointAt = ascendingSoonest ? Orient.AntiNormal : Orient.Normal;
}
// Do a burn just ahead of the ascending node - in the 5 seconds preceding.
if ((timeToBurnNode < 10.0 || _autoAlignBurnTriggered) && _headingError.magnitude < 5.0 && Math.Abs(_relativeInclination) > 0.01)
{
_autoAlignBurnTriggered = true;
if (Math.Abs(_relativeInclination) > 0.1)
{
controls.mainThrottle = 1.0f;
}
else
{
controls.mainThrottle = 0.25f;
}
}
else
{
controls.mainThrottle = 0.0f;
}
if (Math.Abs(_relativeInclination) < 0.02)
{
_autoAlignBurnTriggered = false;
_autoAlign = false;
}
}
if (_autoPhaser)
{
switch (_autoPhaserState)
{
case AutoPhaserState.Step1WaitForTargetApsis:
double timeLeft = CalculateTimeTillNextTargetApsis();
// Set the PointAt based on who is faster at that point in time.
_flyByWire = true;
if (part.vessel.orbit.getOrbitalSpeedAt(timeLeft) > selectedVessel.orbit.getOrbitalSpeedAt(timeLeft))
PointAt = Orient.Retrograde;
else
PointAt = Orient.Prograde;
// Advance if it's time.
if (timeLeft < 5.0)
{
_autoPhaserState = AutoPhaserState.Step2BurnToMatchNextApsis;
_autoPhaserVelocityGoal = selectedVessel.orbit.getOrbitalSpeedAt(CalculateTimeTillFurtherTargetApsis());
_autoPhaseBurnComplete = false;
}
break;
case AutoPhaserState.Step2BurnToMatchNextApsis:
double predictedVelocity = part.vessel.orbit.getOrbitalSpeedAt(CalculateTimeTillFurtherTargetApsis());
if (_headingError.magnitude < 5.0 && !_autoPhaseBurnComplete)
{
controls.mainThrottle = 1;
}
else
{
controls.mainThrottle = 0;
}
// Advance to next state if we hit our goal.
if (Math.Abs(predictedVelocity - _autoPhaserVelocityGoal) < 10)
{
_autoPhaseBurnComplete = true;
controls.mainThrottle = 0;
}
// Wait till we pass the apsis so we don't double advance.
if (_autoPhaseBurnComplete && CalculateTimeTillNextTargetApsis() > 10.0)
_autoPhaserState = AutoPhaserState.Step3WaitForTargetApsis;
break;
case AutoPhaserState.Step3WaitForTargetApsis:
timeLeft = CalculateTimeTillNextTargetApsis();
// Set the PointAt based on who is faster at that point in time.
_flyByWire = true;
PointAt = Orient.Prograde;
// Advance if it's time.
if (timeLeft < 5.0)
{
_autoPhaserState = AutoPhaserState.Step4BurnToRendezvous;
}
break;
case AutoPhaserState.Step4BurnToRendezvous:
// TODO: Make sure we are only considering the apsis that
// is spatially similar to ours, otherwise we get in sync
// orbitally but go into step 5 super far away.
double timeToRendezvous = 0.0, minDeltaT = 0.0;
CalculateNearestRendezvousInSeconds(out timeToRendezvous, out minDeltaT);
if (minDeltaT > 5)
controls.mainThrottle = 0.25f;
else
{
controls.mainThrottle = 0.0f;
_autoPhaserState = AutoPhaserState.Step5WaitForRendezvous;
}
break;
case AutoPhaserState.Step5WaitForRendezvous:
timeToRendezvous = 0.0;
minDeltaT = 0.0;
CalculateNearestRendezvousInSeconds(out timeToRendezvous, out minDeltaT);
if (timeToRendezvous < 2)
_autoPhaserState = AutoPhaserState.Step6BurnToMatchVelocity;
break;
case AutoPhaserState.Step6BurnToMatchVelocity:
if (_relativeVelocity.magnitude > 5)
{
_flyByWire = true;
PointAt = Orient.RelativeVelocityAway;