-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathKerbalFlightData.cs
More file actions
1724 lines (1520 loc) · 59 KB
/
Copy pathKerbalFlightData.cs
File metadata and controls
1724 lines (1520 loc) · 59 KB
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
/*
Copyright 2014 DaMichel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using System.ComponentModel;
using UnityEngine;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
namespace KerbalFlightData
{
#region utilities
public class DMDebug
{
#if DEBUG
StringBuilder sb = new StringBuilder();
HashSet<int> visited = new HashSet<int>();
bool CheckAndAddVisited(UnityEngine.Object o)
{
int key = o.GetInstanceID();
if (visited.Contains(key)) return true;
visited.Add(key);
return false;
}
public void Out(String s, int indent)
{
var indentStr = new String(' ', indent);
var arr = s.Split('\n');
foreach (String s_ in arr)
{
String tmp = s_.Trim('\n', '\r', ' ', '\t').Trim();
if (tmp.Length == 0) continue;
sb.AppendLine(indentStr + tmp);
}
}
bool IsInterestingType(Type typeToCheck)
{
var types = new Type[] {
typeof(UnityEngine.Component),
typeof(UnityEngine.GameObject),
typeof(UnityEngine.Renderer),
typeof(UnityEngine.Mesh),
typeof(UnityEngine.Material),
typeof(UnityEngine.Texture)
};
foreach (Type t in types)
{
if (t.IsAssignableFrom(typeToCheck)) return true;
}
return false;
}
bool IsOkayToExpand(string name, Type type)
{
if (!IsInterestingType(type)) return false;
return true;
}
public void PrintGameObjectHierarchy(GameObject o, int indent)
{
Out(o.name + ", lp = " + o.transform.localPosition.ToString("F3") + ", p = " + o.transform.position.ToString("F3") + ", s = " + o.transform.localScale.ToString("F1") + ", en = " + o.activeSelf.ToString(), indent);
var rt = o.GetComponent<UnityEngine.RectTransform>();
if (rt)
{
Out(String.Format(", rtlp = {0}, rtp = {1}, rect = {2}", rt.localPosition.ToString("F3"), rt.position.ToString("F3"), rt.rect.ToString("F2")), indent + o.name.Length);
}
//Out("[", indent);
foreach (var comp in o.GetComponents<UnityEngine.Component>())
{
if (rt && comp == rt)
continue;
Out("<"+comp.GetType().Name+" "+comp.name+">", indent);
}
//Out("]", indent);
foreach (Transform t in o.transform)
{
PrintGameObjectHierarchy(t.gameObject, indent + 2);
}
}
public void PrintGameObjectHierarchUp(GameObject o, out int indent)
{
if (o.transform.parent)
PrintGameObjectHierarchUp(o.transform.parent.gameObject, out indent);
else
indent = 0;
indent += 2;
Out(o.name + ", lp = " + o.transform.localPosition.ToString("F3") + ", p = " + o.transform.position.ToString("F3"), indent);
}
public void PrintHierarchy(UnityEngine.Object instance, int indent = 0, bool recursive = true)
{
try
{
if (instance == null || CheckAndAddVisited(instance)) return;
var t = instance.GetType();
Out("{ " + instance.name + "(" + t.Name + ")", indent); //<" + instance.GetInstanceID() + ">"
foreach (var field in t.GetFields(BindingFlags.Instance | BindingFlags.Public))
{
var value = field.GetValue(instance);
Out(field.FieldType.Name + " " + field.Name + " = " + value, indent + 1);
if (IsOkayToExpand(field.Name, field.FieldType) && recursive)
{
PrintHierarchy((UnityEngine.Object)value, indent + 2, recursive);
}
}
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
object value = null;
try
{
value = prop.GetValue(instance, null);
}
catch (Exception e)
{
value = e.ToString();
}
Out(prop.PropertyType.Name + " " + prop.Name + " = " + value, indent + 1);
if (IsOkayToExpand(prop.Name, prop.PropertyType) && recursive)
{
PrintHierarchy((UnityEngine.Object)value, indent + 2, recursive);
}
}
if (typeof(GameObject).IsAssignableFrom(t))
{
Out("[Components of " + instance.name + " ]", indent + 1);
foreach (var comp in ((GameObject)instance).GetComponents<UnityEngine.Component>())
{
PrintHierarchy(comp, indent + 2, recursive);
}
}
Out("}", indent);
}
catch (Exception e)
{
Out("Error: " + e.ToString(), indent);
}
}
public override String ToString()
{
return sb.ToString();
}
public static GameObject GetRoot(GameObject o)
{
while (o.transform.parent != null)
{
o = o.transform.parent.gameObject;
}
return o;
}
public static String ToString(object o)
{
if (o == null)
return "null";
return o.ToString();
}
#endif
[System.Diagnostics.Conditional("DEBUG")] // this makes it execute only in debug builds, including argument evaluations. It is very efficient. the compiler will just skip those calls.
public static void Log2(string s)
{
DMDebug.Log(s);
}
public static void Log(string s)
{
Debug.Log("KerbalFlightData: " + s);
}
public static void LogWarning(string s)
{
Debug.LogWarning("KerbalFlightData: " + s);
}
}
public static class Util
{
public static void SetColor(this GUIStyle s, Color c)
{
s.hover.textColor = s.active.textColor = s.normal.textColor = s.focused.textColor = s.onNormal.textColor = s.onFocused.textColor = s.onHover.textColor = s.onActive.textColor = c;
}
public static Vector2 ScreenSizeToWorldSize(Camera cam, Vector2 s)
{
Vector3 p0 = cam.ScreenToWorldPoint(Vector3.zero);
Vector3 p1 = cam.ScreenToWorldPoint(s);
return p1-p0;
}
public static bool AlmostEqual(double a, double b, double eps)
{
return Math.Abs(a-b) < eps;
}
public static bool AlmostEqualRel(double a, double b, double eps)
{
return Math.Abs(a-b) <= (Math.Abs(a)+Math.Abs(b))*eps;
}
public static void TryReadValue<T>(ref T target, ConfigNode node, string name)
{
if (node.HasValue(name))
{
try
{
target = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(node.GetValue(name));
}
catch
{
// just skip over it
}
}
// skip again
}
// point from frame a to the corresponding point in frame b
public static Vector2 TransformPoint(Transform a, Transform b, float x, float y)
{
var p = a.TransformPoint(x, y, 0);
p = b.InverseTransformPoint(p);
return new Vector2(p.x, p.y);
}
public static Vector2 TransformPoint(Transform a, Transform b, Vector2 p)
{
return TransformPoint(a, b, p.x, p.y);
}
};
#endregion
#region DataAcquisition
public class Data
{
public double machNumber;
public double airAvailability;
public double stallPercentage;
public double q;
public bool hasAirAvailability = false;
public bool hasAerodynamics = false; // mach, q
public bool hasStalls = false;
public bool hasEnginePerf = false;
public double airBreatherThrust;
public double throttle;
public double totalThrust;
public bool hasAirBreathingEngines; // also if they are active
public int warnQ;
public int warnStall;
public int warnAir;
public int warnTemp;
public double apoapsis = 0;
public double periapsis = 0;
public double timeToNode = 0;
public enum NextNode
{
Ap, Pe, Escape, Maneuver, Encounter
};
public NextNode nextNode = NextNode.Ap;
public bool isAtmosphericLowLevelFlight;
public bool isInAtmosphere;
public bool isLanded;
public bool isDisplayingRadarAlt;
public double altitude = 0;
public double radarAltitude = 0;
public double verticalSpeed = 0;
public double radarAltitudeDeriv = 0;
public double timeToImpact = 0;
public double highestTemp = 0;
public double highestTempMax = 0;
public double tempWarnMetric = 0;
public bool highestTempIsSkinTemp = false;
public bool hasTemp = false;
};
class DataFAR
{
private static Type FARAPI = null;
private static bool farDataIsObtainedOkay = false;
private static MethodInfo VesselStallFrac;
private static MethodInfo VesselDynPres;
private static MethodInfo VesselFlightInfo;
public static bool obtainIntakeData = true;
public static void Init(Type FARAPI_)
{
FARAPI = FARAPI_;
DMDebug.Log2(String.Format("FARAPI = {0}", FARAPI.ToString()));
foreach (var method in FARAPI.GetMethods(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public))
{
DMDebug.Log2(String.Format("method = {0}", method.Name));
if (method.Name == "VesselStallFrac")
VesselStallFrac = method;
else if (method.Name == "VesselDynPres")
VesselDynPres = method;
else if (method.Name == "VesselFlightInfo")
VesselFlightInfo = method;
}
}
private static bool GetFARData_Internal(Data data, Vessel vessel)
{
var arg = new object[] {vessel};
object instance = VesselFlightInfo.Invoke(null, arg); // this looks stupidly costly, but what can we do?!
//DMDebug.Log2("FAR seems to be " + ((instance == null) ? "not " : "") + "ready");
if (instance == null)
{
data.hasAerodynamics = false;
data.hasStalls = false;
//data.hasAirAvailability = false;
return false;
}
else
{
//DMDebug.Log2("q");
// any error here though, is a real error. It would probably mean that the assumptions about FARControlSys were invalidated by version updates.
//data.q = (double)VesselDynPres.Invoke(null, arg);
data.q = vessel.dynamicPressurekPa * 1000.0;
//DMDebug.Log2("m");
data.machNumber = vessel.mach;
//data.airAvailability = obtainIntakeData ? (double)fieldAir.GetValue(null) : 1.0;
//DMDebug.Log2("stall");
data.stallPercentage = (double)VesselStallFrac.Invoke(null, arg);
data.hasAerodynamics = true;
data.hasStalls = true;
//data.hasAirAvailability = obtainIntakeData;
}
return true;
}
public static bool GetFARData(Data data, Vessel vessel)
{
bool ok = GetFARData_Internal(data, vessel);
if (ok)
{
if (!farDataIsObtainedOkay)
{
DMDebug.Log("Data from FAR obtained successfully");
farDataIsObtainedOkay = true;
}
}
else
{
if (farDataIsObtainedOkay)
{
DMDebug.Log("Failed to get data from FAR although it was obtained successfully before");
farDataIsObtainedOkay = false;
}
}
return ok;
}
};
class DataSources
{
private static PartResourceLibrary l = PartResourceLibrary.Instance;
private static bool hasFAR = false;
//private static bool hasDre = false;
//private static bool hasAJE = false;
private static double airDemand = 0;
private static double airAvailable = 0;
private static bool hasEngine = false;
private static bool lastPartIsEngine = false;
private static bool needsTemp = false;
private const double tempWarnThreshold1 = 0.5;
private const double tempWarnThreshold2 = 0.2;
private const double tempWarnThreshold3 = 0.05;
public static void Init()
{
foreach (var assembly in AssemblyLoader.loadedAssemblies)
{
//DMDebug.Log2(assembly.name);
if (assembly.name == "FerramAerospaceResearch")
{
var types = assembly.assembly.GetExportedTypes();
foreach (Type t in types)
{
//DMDebug.Log2(t.FullName);
if (t.FullName.Equals("FerramAerospaceResearch.FARAPI"))
{
DataFAR.Init(t);
hasFAR = true;
}
}
}
//else if (assembly.name == "DeadlyReentry")
//{
// hasDre = true;
//}
//else if (assembly.name == "AJE")
//{
// hasAJE = true;
//}
}
}
/*
* collects engine data, intake air and determines if the part is an engine.
*/
private static void VisitModule(Data data, PartModule m, Part p, Vessel vessel)
{
double fixedDeltaTime = TimeWarp.fixedDeltaTime;
if (m is ModuleEngines)
{
ModuleEngines e = m as ModuleEngines;
if (e.EngineIgnited && !e.engineShutdown)
{
bool needsAir = false;
//if (obtainIntakeAir || ) // don't iterate propellants if we don't have to
{
foreach (Propellant v in e.propellants)
{
string propName = v.name;
PartResourceDefinition r = l.resourceDefinitions[propName];
if (propName == "IntakeAir")
{
airDemand += v.currentRequirement;
needsAir = true;
continue;
}
}
}
if (needsAir)
{
data.airBreatherThrust += e.finalThrust;
data.hasAirBreathingEngines = true;
}
data.totalThrust += e.finalThrust;
lastPartIsEngine = true;
}
}
else if (m is ModuleEnginesFX)
{
ModuleEnginesFX e = m as ModuleEnginesFX;
if (e.EngineIgnited && !e.engineShutdown)
{
bool needsAir = false;
//if (obtainIntakeAir) // don't iterate propellants if we don't have to
{
foreach (Propellant v in e.propellants)
{
string propName = v.name;
PartResourceDefinition r = l.resourceDefinitions[propName];
if (propName == "IntakeAir")
{
airDemand += v.currentRequirement;
needsAir = true;
continue;
}
}
}
if (needsAir)
{
data.airBreatherThrust += e.finalThrust;
data.hasAirBreathingEngines = true;
}
data.totalThrust += e.finalThrust;
lastPartIsEngine = true;
}
}
else if (m is ModuleResourceIntake)
{
ModuleResourceIntake i = m as ModuleResourceIntake;
if (i.intakeEnabled)
{
airAvailable += i.airFlow * fixedDeltaTime;
}
}
}
private static void FillLocationData(Data data, Vessel vessel)
{
Orbit o = vessel.orbit;
CelestialBody b = vessel.mainBody;
if (o != null && b != null)
{
data.periapsis = o.PeA;
data.apoapsis = o.ApA;
double time = Planetarium.GetUniversalTime();
double timeToEnd = o.EndUT - time;
double timeToAp = o.timeToAp;
double timeToPe = o.timeToPe;
if (data.apoapsis < data.periapsis || timeToAp <= 0)
timeToAp = double.PositiveInfinity; // not gona happen
if (timeToPe <= 0)
timeToPe = double.PositiveInfinity;
if (timeToEnd <= timeToPe && timeToEnd <= timeToAp && o.patchEndTransition != Orbit.PatchTransitionType.FINAL && o.patchEndTransition != Orbit.PatchTransitionType.INITIAL)
{
data.timeToNode = timeToEnd;
if (o.patchEndTransition == Orbit.PatchTransitionType.ESCAPE) data.nextNode = Data.NextNode.Escape;
else if (o.patchEndTransition == Orbit.PatchTransitionType.ENCOUNTER) data.nextNode = Data.NextNode.Encounter;
else data.nextNode = Data.NextNode.Maneuver;
}
else if (timeToAp < timeToPe)
{
data.timeToNode = o.timeToAp;
data.nextNode = Data.NextNode.Ap;
}
else
{
data.timeToNode = timeToPe;
data.nextNode = Data.NextNode.Pe;
}
if (b.atmosphere)
{
double hmin = (double)(((int)(b.atmosphereDepth * 0.33333333e-3))) * 1000;
data.isAtmosphericLowLevelFlight = !(data.apoapsis > hmin || data.periapsis > hmin);
}
else
data.isAtmosphericLowLevelFlight = false;
data.isInAtmosphere = b.atmosphere && vessel.altitude < b.atmosphereDepth;
}
data.altitude = vessel.altitude;
// for data.radarAltitude see FixedUpdate()
data.verticalSpeed = vessel.verticalSpeed;
data.timeToImpact = data.radarAltitudeDeriv < 0 ? -data.radarAltitude/data.radarAltitudeDeriv : double.PositiveInfinity;
data.isLanded = false;
if (vessel.LandedOrSplashed)
{
double srfSpeedSqr = vessel.GetSrfVelocity().sqrMagnitude;
if (srfSpeedSqr < 0.01)
data.isLanded = true;
}
}
private static void UpdateWarningIndicators(Data data)
{
if (data.hasAerodynamics)
{
if (data.q < 10)
{
data.warnQ = MyStyleId.Greyed;
data.warnStall = MyStyleId.Greyed;
}
else
{
if (data.q > 40000)
data.warnQ = MyStyleId.Warn1;
else
data.warnQ = MyStyleId.Greyed;
if (data.stallPercentage > 0.5)
data.warnStall = MyStyleId.Warn2;
else if (data.stallPercentage > 0.005)
data.warnStall = MyStyleId.Warn1;
else
data.warnStall = MyStyleId.Greyed;
}
}
if (data.hasAirAvailability)
{
if (data.airAvailability < 1.05)
data.warnAir = MyStyleId.Warn2;
else if (data.airAvailability < 1.5)
data.warnAir = MyStyleId.Warn1;
else
data.warnAir = MyStyleId.Greyed;
}
if (data.hasTemp)
{
if (data.tempWarnMetric < tempWarnThreshold3)
data.warnTemp = MyStyleId.Warn2;
else if (data.tempWarnMetric < tempWarnThreshold2)
data.warnTemp = MyStyleId.Warn1;
else if (data.tempWarnMetric < tempWarnThreshold1)
data.warnTemp = MyStyleId.Emph;
else
data.warnTemp = MyStyleId.Greyed;
}
}
public static void FillDataInstance(Data data, Vessel vessel)
{
// air for the engines
airAvailable = 0;
airDemand = 0;
// engine perf
data.totalThrust = 0;
data.airBreatherThrust = 0;
data.hasAirBreathingEngines = false;
// location, put stuff in data, need for further processing if we are atmospheric
FillLocationData(data, vessel);
// temp
needsTemp = data.isInAtmosphere;
data.highestTemp = double.PositiveInfinity;
double maxScore = double.PositiveInfinity;
//double tempWeight = 0;
//double averageTempMetric = 0;
// iterate over the vessel parts
double fixedDeltaTime = TimeWarp.fixedDeltaTime;
int partCnt = vessel.parts.Count;
for (int iPart = 0; iPart < partCnt; ++iPart)
{
Part p = vessel.parts[iPart];
if (p == null)
continue;
lastPartIsEngine = false;
// visit modules
int moduleCnt = p.Modules.Count;
for (int jModule = 0; jModule < moduleCnt; ++jModule)
{
PartModule m = p.Modules[jModule];
if (m == null)
continue;
// do things with modules
VisitModule(data, m, p, vessel);
}
hasEngine |= lastPartIsEngine;
// do things with parts
if (p.temperature != 0f && needsTemp) // small gear box has p.temperature==0 - always! Bug? Who knows. Anyway i want to ignore it.
{
//double score = p.maxTemp/(Math.Max(0, 1.0 - p.temperature / p.maxTemp) + 1.0e-6) * (1.0 + Math.Max(0.0, p.thermalRadiationFlux + p.thermalConvectionFlux + p.thermalConductionFlux)*p.thermalMassReciprocal*fixedDeltaTime/p.maxTemp);
//averageTempMetric += score * Math.Max(0, p.maxTemp - p.temperature);
double t = p.temperature;
double tskin = p.skinTemperature;
double tMax = p.maxTemp > 0 ? p.maxTemp : 2000.0;
double tskinMax = p.skinMaxTemp > 0 ? p.skinMaxTemp : 2000.0;
double score = (tMax - t)/tMax;
double scoreSkin = (tskinMax - tskin)/tskinMax;
//tempWeight += score;
if (score < maxScore)
{
maxScore = score;
data.highestTemp = t;
data.highestTempMax = tMax;
data.tempWarnMetric = tMax - t;
data.highestTempIsSkinTemp = false;
}
if (scoreSkin < maxScore)
{
maxScore = scoreSkin;
data.highestTemp = tskin;
data.highestTempMax = tskinMax;
data.tempWarnMetric = tskinMax - tskin;
data.highestTempIsSkinTemp = true;
}
//DMDebug.Log(string.Format("{0} tmax {1}, t {2}, diff {3}", p.name, p.maxTemp.ToString(), p.temperature.ToString(), (p.maxTemp - p.temperature).ToString()));
}
}
// air
//DMDebug.Log(string.Format("air avail: {0}, demand {1}", airAvailable, airDemand));
data.airAvailability = airAvailable / airDemand;
// data.hasAirAvailability = data.isInAtmosphere && !hasAJE;
data.hasAirAvailability = false;
// engine
data.throttle = vessel.ctrlState.mainThrottle;
data.hasEnginePerf = hasEngine;
// temperature
data.tempWarnMetric = data.tempWarnMetric / data.highestTempMax;
data.hasTemp = needsTemp && data.tempWarnMetric < tempWarnThreshold1;
//DMDebug.Log(string.Format("tempWarnMetric = {0}, hasTemp = {1}", data.tempWarnMetric.ToString("F3"), data.hasTemp.ToString()));
if (hasFAR)
DataFAR.GetFARData(data, vessel);
else
{
data.hasAerodynamics = true;
data.machNumber = vessel.mach;
data.q = vessel.dynamicPressurekPa * 1.0e3; // convert to Pa
}
UpdateWarningIndicators(data);
}
static public void FixedUpdate(Data data, bool computeDerivsAllowed)
{
Vessel vessel = FlightGlobals.ActiveVessel;
double radarAltitude = vessel.altitude - Math.Max(0, vessel.terrainAltitude); // terrainAltitude is the deviation of the terrain from the sea level.
if (computeDerivsAllowed)
data.radarAltitudeDeriv = (radarAltitude - data.radarAltitude) / TimeWarp.fixedDeltaTime;
else
data.radarAltitudeDeriv = 0;
data.radarAltitude = radarAltitude;
data.isDisplayingRadarAlt = data.radarAltitude < 5000.0;
//DMDebug.Log(string.Format("vertical speed = {0} (?)", data.verticalSpeed));
}
};
#endregion
#region GUI classes
public static class MyStyleId
{
public const int Plain = 0;
public const int Greyed = 1;
public const int Warn1 = 2;
public const int Warn2 = 3;
public const int Emph = 4;
};
public struct KfiTextStyle
{
public Color color;
public FontStyle fontStyle;
public static KfiTextStyle plainWhite
{
get {
KfiTextStyle s;
s.color = Color.white;
s.fontStyle = FontStyle.Normal;
return s;
}
}
};
public struct KFDContent
{
public KFDContent(string text_, int styleId_)
{
this.text = text_;
this.styleId = styleId_;
}
public readonly string text;
public readonly int styleId;
};
/* On how to create GUI by script: http://answers.unity3d.com/questions/849176/how-to-create-a-canvas-and-text-ui-46-object-using.html */
public class KFDText : MonoBehaviour
{
UnityEngine.UI.Text gt1_;
int styleId_ = -1;
Func<Data, KFDContent> getContent_;
Func<Data, bool> hasChanged_;
public static KFDText Create(string id, int styleId, Func<Data, KFDContent> getContent, Func<Data, bool> hasChanged)
{
// foreground text
GameObject textGO = new GameObject("KFD-" + id);
textGO.layer = 12; // navball layer
KFDText kfi = textGO.AddComponent<KFDText>();
kfi.gt1_ = textGO.AddComponent<UnityEngine.UI.Text>();
var shadow = textGO.AddComponent<UnityEngine.UI.Shadow>();
shadow.effectColor = new Color(0, 0, 0, 0.5f);
shadow.effectDistance = new Vector2(1.0f, -2.0f);
var shadow2 = textGO.AddComponent<UnityEngine.UI.Shadow>();
shadow2.effectColor = Color.black;
shadow2.effectDistance = new Vector2(0.5f, -1.0f);
kfi.ForceUpdateStyles(styleId);
kfi.getContent_ = getContent;
kfi.hasChanged_ = hasChanged;
return kfi;
}
private void ForceUpdateStyles(int styleId)
{
this.styleId_ = styleId;
KfiTextStyle s = KFDGuiController.instance.styles[styleId];
this.gt1_.fontStyle = s.fontStyle;
this.gt1_.fontSize = KFDGuiController.instance.fontSize;
this.gt1_.font = KFDGuiController.instance.font;
this.gt1_.color = s.color;
}
public void UpdateText(Data data)
{
if (hasChanged_(data))
{
//DMDebug.Log2(name + " has changed");
KFDContent c = getContent_(data);
if (this.styleId_ != c.styleId) // careful because of potentially costly update
{
ForceUpdateStyles(c.styleId);
}
// Not going to compare here, since probably the text has actually changed.
this.gt1_.text = c.text;
}
//else
//DMDebug.Log2(name + " unchanged");
}
public void OnDestroy()
{
//DMDebug.Log2(this.name + " OnDestroy");
// release links to make it easier for the gc
gt1_ = null;
hasChanged_ = null;
getContent_ = null;
}
public int fontSize
{
set
{
this.gt1_.fontSize = value;
}
}
public bool enableGameObject
{
set
{
if (this.gameObject.activeSelf != value)
{
//DMDebug.Log2(this.name + " enabled=" + value);
this.gameObject.SetActive(value);
}
}
get { return this.gameObject.activeSelf; }
}
};
public enum VerticalAlignment
{
Top = 1,
Bottom = -1
};
/* This class represents the left/right text areas. Texts are managed as children (by Unity GameObjects).
* Since Unity 5 we can use the new UI systems which provides automatic layouting controller such as
* VerticalLayoutGroup. The latter takes care of the arrangement of texts.
* */
public class KFDArea : MonoBehaviour
{
public List<KFDText> items;
public static KFDArea Create(string id, Vector2 position_, TextAlignment alignment_, Transform parent) // factory, creates game object with attached FKIArea
{
GameObject go = new GameObject("KFD-AREA-"+id);
KFDArea kfi = go.AddComponent<KFDArea>();
var layout = go.AddComponent<UnityEngine.UI.VerticalLayoutGroup>();
layout.childForceExpandHeight = false;
layout.childForceExpandWidth = false;
var fitter = go.AddComponent<UnityEngine.UI.ContentSizeFitter>();
fitter.horizontalFit = UnityEngine.UI.ContentSizeFitter.FitMode.PreferredSize;
fitter.verticalFit = UnityEngine.UI.ContentSizeFitter.FitMode.PreferredSize;
var recttrafo = go.GetComponent<UnityEngine.RectTransform>();
if (alignment_ == TextAlignment.Left)
{
recttrafo.pivot = new Vector2(0, 0);
layout.childAlignment = TextAnchor.LowerLeft;
}
else if (alignment_ == TextAlignment.Right)
{
recttrafo.pivot = new Vector2(1, 0);
layout.childAlignment = TextAnchor.LowerRight;
}
kfi.items = new List<KFDText>();
go.transform.SetParent(parent, false);
go.transform.localPosition = position_;
return kfi;
}
void OnDestroy()
{
//DMDebug.Log2(this.name + " OnDestroy");
items.Clear();
}
public void Add(KFDText t)
{
t.gameObject.transform.SetParent(this.gameObject.transform, false);
items.Add(t);
}
public VerticalAlignment verticalAlignment
{
set
{
var rt = this.gameObject.GetComponent<UnityEngine.RectTransform>();
var layout = this.gameObject.GetComponent<UnityEngine.UI.VerticalLayoutGroup>();
var pivot = rt.pivot;
if (value == VerticalAlignment.Bottom)
{
pivot.y = 0;
}
else
{
pivot.y = 1;
}
rt.pivot = pivot;
}
}
public bool enableGameObject
{
set
{
if (this.gameObject.activeSelf != value)
{
//DMDebug.Log2(this.name + " enabled=" + value);
this.gameObject.SetActive(value);
}
}
get { return this.gameObject.activeSelf; }
}
};
/* this class contains information for styling and positioning of the texts */
public class KFDGuiController
{
static KFDGuiController instance_ = new KFDGuiController(); // allocate when the code loads
GameObject goAnchor = null;
GameObject goNavball = null;
GameObject goAutopilotModes = null;
GameObject goDVGauge = null;
GameObject goNavballIVACollapse = null;
int timeSecondsPerDay;
int timeSecondsPerYear;
float baseFontSizeIVA = 16; // font size @ 100% UI scale setting
float baseFontSizeExternal = 16;
float topAnchorOffsetX = 0.0f;
public int fontSize;
public float screenAnchorRight;
public float screenAnchorLeft;
public float screenAnchorVertical;
public bool ready = false;
public bool isIVA = false;
public bool isMapMode = false;
public UnityEngine.Font font = null;
public KfiTextStyle[] styles = null;
// gui stuff
KFDText[] texts = null;
int[] markers = null;
int markerMaster = 0;
KFDArea leftArea, rightArea;
enum TxtIdx
{
MACH = 0, AIR, ALT, STALL, Q, TEMP, TNODE, AP, PE, ENGINEPERF, VSPEED, COUNT
};
public void LoadSettings(ConfigNode settings)
{
Util.TryReadValue(ref baseFontSizeIVA, settings, "baseFontSizeIVA");
Util.TryReadValue(ref baseFontSizeExternal, settings, "baseFontSizeExternal");
Util.TryReadValue(ref topAnchorOffsetX, settings, "topAnchorOffsetX");
}
public void SaveSettings(ConfigNode settings)
{