forked from SodiumEyes/KerbalLiveFeed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KLFManager.cs
1950 lines (1539 loc) · 57.7 KB
/
KLFManager.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;
namespace KLF
{
public class KLFManager : MonoBehaviour
{
public struct VesselEntry
{
public KLFVessel vessel;
public float lastUpdateTime;
}
public struct VesselStatusInfo
{
public string ownerName;
public string vesselName;
public string detailText;
public Color color;
public KLFVesselInfo info;
public Orbit orbit;
public float lastUpdateTime;
}
//Singleton
public static GameObject GameObjectInstance;
//Properties
public const String INTEROP_CLIENT_FILENAME = "interopclient.txt";
public const String INTEROP_PLUGIN_FILENAME = "interopplugin.txt";
public const String GLOBAL_SETTINGS_FILENAME = "globalsettings.txt";
public const float INACTIVE_VESSEL_RANGE = 400000000.0f;
public const float DOCKING_TARGET_RANGE = 200.0f;
public const int MAX_INACTIVE_VESSELS_PER_UPDATE = 8;
public const int STATUS_ARRAY_MIN_SIZE = 2;
public const int MAX_VESSEL_NAME_LENGTH = 32;
public const float VESSEL_TIMEOUT_DELAY = 6.0f;
public const float IDLE_DELAY = 120.0f;
public const float PLUGIN_DATA_WRITE_INTERVAL = 5.0f;
public const float GLOBAL_SETTINGS_SAVE_INTERVAL = 10.0f;
public const int INTEROP_MAX_QUEUE_SIZE = 128;
public const float INTEROP_WRITE_INTERVAL = 0.1f;
public const float INTEROP_WRITE_TIMEOUT = 6.0f;
public UnicodeEncoding encoder = new UnicodeEncoding();
public String playerName = String.Empty;
public byte inactiveVesselsPerUpdate = 0;
public float updateInterval = 0.25f;
public Dictionary<String, VesselEntry> vessels = new Dictionary<string, VesselEntry>();
public SortedDictionary<String, VesselStatusInfo> playerStatus = new SortedDictionary<string, VesselStatusInfo>();
public RenderingManager renderManager;
public PlanetariumCamera planetariumCam;
public Queue<byte[]> interopOutQueue = new Queue<byte[]>();
private float lastGlobalSettingSaveTime = 0.0f;
private float lastPluginDataWriteTime = 0.0f;
private float lastPluginUpdateWriteTime = 0.0f;
private float lastInteropWriteTime = 0.0f;
private float lastKeyPressTime = 0.0f;
private Queue<KLFVesselUpdate> vesselUpdateQueue = new Queue<KLFVesselUpdate>();
GUIStyle playerNameStyle, vesselNameStyle, stateTextStyle, chatLineStyle, screenshotDescriptionStyle;
private bool isEditorLocked = false;
private bool mappingGUIToggleKey = false;
private bool mappingScreenshotKey = false;
public bool globalUIToggle
{
get
{
return renderManager == null || renderManager.uiElementsToDisable.Length < 1 || renderManager.uiElementsToDisable[0].activeSelf;
}
}
public bool sceneIsValid
{
get
{
switch (HighLogic.LoadedScene)
{
case GameScenes.SPACECENTER:
case GameScenes.EDITOR:
case GameScenes.FLIGHT:
case GameScenes.SPH:
case GameScenes.TRACKSTATION:
return true;
default:
return false;
}
}
}
public bool shouldDrawGUI
{
get
{
return sceneIsValid && KLFInfoDisplay.infoDisplayActive && globalUIToggle;
}
}
public static bool isInFlight
{
get
{
return FlightGlobals.ready && FlightGlobals.ActiveVessel != null;
}
}
public bool isIdle
{
get
{
return lastKeyPressTime > 0.0f && (UnityEngine.Time.realtimeSinceStartup - lastKeyPressTime) > IDLE_DELAY;
}
}
//Keys
public bool getAnyKeyDown(ref KeyCode key)
{
foreach (KeyCode keycode in Enum.GetValues(typeof(KeyCode)))
{
if (Input.GetKeyDown(keycode))
{
key = keycode;
return true;
}
}
return false;
}
//Updates
public void updateStep()
{
if (HighLogic.LoadedScene == GameScenes.LOADING)
return; //Don't do anything while the game is loading
if (planetariumCam != null && planetariumCam.gameObject.GetComponent<KLFCameraScript>() == null)
{
Debug.Log("Added KLF Camera Script");
KLFCameraScript script = planetariumCam.gameObject.AddComponent<KLFCameraScript>();
script.manager = this;
}
//Handle all queued vessel updates
while (vesselUpdateQueue.Count > 0)
{
handleVesselUpdate(vesselUpdateQueue.Dequeue());
}
readClientInterop();
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginUpdateWriteTime) > updateInterval
&& (Time.realtimeSinceStartup - lastInteropWriteTime) < INTEROP_WRITE_TIMEOUT)
{
writePluginUpdate();
lastPluginUpdateWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginDataWriteTime) > PLUGIN_DATA_WRITE_INTERVAL)
{
writePluginData();
writeScreenshotWatchUpdate();
lastPluginDataWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
//Write interop
if ((UnityEngine.Time.realtimeSinceStartup - lastInteropWriteTime) > INTEROP_WRITE_INTERVAL)
{
if (writePluginInterop())
lastInteropWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
//Save global settings periodically
if ((UnityEngine.Time.realtimeSinceStartup - lastGlobalSettingSaveTime) > GLOBAL_SETTINGS_SAVE_INTERVAL)
{
saveGlobalSettings();
//Keep track of when the name was last read so we don't read it every time
lastGlobalSettingSaveTime = UnityEngine.Time.realtimeSinceStartup;
}
//Update the positions of all the vessels
List<String> delete_list = new List<String>();
foreach (KeyValuePair<String, VesselEntry> pair in vessels) {
VesselEntry entry = pair.Value;
if ((UnityEngine.Time.realtimeSinceStartup-entry.lastUpdateTime) <= VESSEL_TIMEOUT_DELAY
&& entry.vessel != null && entry.vessel.gameObj != null)
{
entry.vessel.updateRenderProperties(
!KLFGlobalSettings.instance.showOtherShips ||
(!KLFGlobalSettings.instance.showInactiveShips && entry.vessel.info.state != State.ACTIVE)
);
entry.vessel.updatePosition();
}
else
{
delete_list.Add(pair.Key); //Mark the vessel for deletion
if (entry.vessel != null && entry.vessel.gameObj != null)
GameObject.Destroy(entry.vessel.gameObj);
}
}
//Delete what needs deletin'
foreach (String key in delete_list)
vessels.Remove(key);
delete_list.Clear();
//Delete outdated player status entries
foreach (KeyValuePair<String, VesselStatusInfo> pair in playerStatus)
{
if ((UnityEngine.Time.realtimeSinceStartup - pair.Value.lastUpdateTime) > VESSEL_TIMEOUT_DELAY)
delete_list.Add(pair.Key);
}
foreach (String key in delete_list)
playerStatus.Remove(key);
}
private void writePluginUpdate()
{
if (playerName == null || playerName.Length == 0)
return;
writePrimaryUpdate();
if (isInFlight)
writeSecondaryUpdates();
}
private void writePrimaryUpdate()
{
if (isInFlight)
{
//Write vessel status
KLFVesselUpdate update = getVesselUpdate(FlightGlobals.ActiveVessel);
//Update the player vessel info
VesselStatusInfo my_status = new VesselStatusInfo();
my_status.info = update;
my_status.orbit = FlightGlobals.ActiveVessel.orbit;
my_status.color = KLFVessel.generateActiveColor(playerName);
my_status.ownerName = playerName;
my_status.vesselName = FlightGlobals.ActiveVessel.vesselName;
my_status.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
if (playerStatus.ContainsKey(playerName))
playerStatus[playerName] = my_status;
else
playerStatus.Add(playerName, my_status);
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, KSP.IO.IOUtils.SerializeToBinary(update));
}
else
{
//Check if the player is building a ship
bool building_ship = HighLogic.LoadedSceneIsEditor
&& EditorLogic.fetch != null
&& EditorLogic.fetch.ship != null && EditorLogic.fetch.ship.Count > 0
&& EditorLogic.fetch.shipNameField != null
&& EditorLogic.fetch.shipNameField.Text != null && EditorLogic.fetch.shipNameField.Text.Length > 0;
String[] status_array = null;
if (building_ship)
{
status_array = new String[3];
//Vessel name
String shipname = EditorLogic.fetch.shipNameField.Text;
if (shipname.Length > MAX_VESSEL_NAME_LENGTH)
shipname = shipname.Substring(0, MAX_VESSEL_NAME_LENGTH); //Limit vessel name length
status_array[1] = "Building " + shipname;
//Vessel details
status_array[2] = "Parts: " + EditorLogic.fetch.ship.Count;
}
else
{
status_array = new String[2];
switch (HighLogic.LoadedScene)
{
case GameScenes.SPACECENTER:
status_array[1] = "At Space Center";
break;
case GameScenes.EDITOR:
status_array[1] = "In Vehicle Assembly Building";
break;
case GameScenes.SPH:
status_array[1] = "In Space Plane Hangar";
break;
case GameScenes.TRACKSTATION:
status_array[1] = "At Tracking Station";
break;
default:
status_array[1] = String.Empty;
break;
}
}
//Check if player is idle
if (isIdle)
status_array[1] = "(Idle) " + status_array[1];
status_array[0] = playerName;
//Serialize the update
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(status_array);
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
VesselStatusInfo my_status = statusArrayToInfo(status_array);
if (playerStatus.ContainsKey(playerName))
playerStatus[playerName] = my_status;
else
playerStatus.Add(playerName, my_status);
}
}
private void writeSecondaryUpdates()
{
if (inactiveVesselsPerUpdate > 0)
{
//Write the inactive vessels nearest the active vessel to the file
SortedList<float, Vessel> nearest_vessels = new SortedList<float, Vessel>();
foreach (Vessel vessel in FlightGlobals.Vessels)
{
if (vessel != FlightGlobals.ActiveVessel)
{
float distance = (float)Vector3d.Distance(vessel.GetWorldPos3D(), FlightGlobals.ActiveVessel.GetWorldPos3D());
if (distance < INACTIVE_VESSEL_RANGE)
{
try
{
nearest_vessels.Add(distance, vessel);
}
catch (ArgumentException)
{
}
}
}
}
int num_written_vessels = 0;
//Write inactive vessels to file in order of distance from active vessel
IEnumerator<KeyValuePair<float, Vessel>> enumerator = nearest_vessels.GetEnumerator();
while (num_written_vessels < inactiveVesselsPerUpdate
&& num_written_vessels < MAX_INACTIVE_VESSELS_PER_UPDATE && enumerator.MoveNext())
{
byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(getVesselUpdate(enumerator.Current.Value));
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.SECONDARY_PLUGIN_UPDATE, update_bytes);
num_written_vessels++;
}
}
}
private KLFVesselUpdate getVesselUpdate(Vessel vessel)
{
if (vessel == null || vessel.mainBody == null)
return null;
//Create a KLFVesselUpdate from the vessel data
KLFVesselUpdate update = new KLFVesselUpdate();
if (vessel.vesselName.Length <= MAX_VESSEL_NAME_LENGTH)
update.name = vessel.vesselName;
else
update.name = vessel.vesselName.Substring(0, MAX_VESSEL_NAME_LENGTH);
update.player = playerName;
update.id = vessel.id;
Vector3 pos = vessel.mainBody.transform.InverseTransformPoint(vessel.GetWorldPos3D());
Vector3 dir = vessel.mainBody.transform.InverseTransformDirection(vessel.transform.up);
Vector3 vel = vessel.mainBody.transform.InverseTransformDirection(vessel.GetObtVelocity());
for (int i = 0; i < 3; i++)
{
update.pos[i] = pos[i];
update.dir[i] = dir[i];
update.vel[i] = vel[i];
}
//Determine situation
if (vessel.loaded && vessel.GetTotalMass() <= 0.0)
update.situation = Situation.DESTROYED;
else
{
switch (vessel.situation)
{
case Vessel.Situations.LANDED:
update.situation = Situation.LANDED;
break;
case Vessel.Situations.SPLASHED:
update.situation = Situation.SPLASHED;
break;
case Vessel.Situations.PRELAUNCH:
update.situation = Situation.PRELAUNCH;
break;
case Vessel.Situations.SUB_ORBITAL:
if (vessel.orbit.timeToAp < vessel.orbit.period / 2.0)
update.situation = Situation.ASCENDING;
else
update.situation = Situation.DESCENDING;
break;
case Vessel.Situations.ORBITING:
update.situation = Situation.ORBITING;
break;
case Vessel.Situations.ESCAPING:
if (vessel.orbit.timeToPe > 0.0)
update.situation = Situation.ENCOUNTERING;
else
update.situation = Situation.ESCAPING;
break;
case Vessel.Situations.DOCKED:
update.situation = Situation.DOCKED;
break;
case Vessel.Situations.FLYING:
update.situation = Situation.FLYING;
break;
default:
update.situation = Situation.UNKNOWN;
break;
}
}
if (vessel == FlightGlobals.ActiveVessel)
{
update.state = State.ACTIVE;
//Set vessel details since it's the active vessel
update.detail = getVesselDetail(vessel);
}
else if (vessel.isCommandable)
update.state = State.INACTIVE;
else
update.state = State.DEAD;
update.timeScale = (float)Planetarium.TimeScale;
update.bodyName = vessel.mainBody.bodyName;
return update;
}
private KLFVesselDetail getVesselDetail(Vessel vessel)
{
KLFVesselDetail detail = new KLFVesselDetail();
detail.idle = isIdle;
detail.mass = vessel.GetTotalMass();
bool is_eva = false;
bool parachutes_open = false;
//Check if the vessel is an EVA Kerbal
if (vessel.isEVA && vessel.parts.Count > 0 && vessel.parts.First().Modules.Count > 0)
{
foreach (PartModule module in vessel.parts.First().Modules)
{
if (module is KerbalEVA)
{
KerbalEVA kerbal = (KerbalEVA)module;
detail.percentFuel = (byte)Math.Round(kerbal.Fuel / kerbal.FuelCapacity * 100);
detail.percentRCS = byte.MaxValue;
detail.numCrew = byte.MaxValue;
is_eva = true;
break;
}
}
}
if (!is_eva)
{
if (vessel.GetCrewCapacity() > 0)
detail.numCrew = (byte)vessel.GetCrewCount();
else
detail.numCrew = byte.MaxValue;
Dictionary<string, float> fuel_densities = new Dictionary<string, float>();
Dictionary<string, float> rcs_fuel_densities = new Dictionary<string, float>();
bool has_engines = false;
bool has_rcs = false;
foreach (Part part in vessel.parts)
{
foreach (PartModule module in part.Modules)
{
if (module is ModuleEngines)
{
//Determine what kinds of fuel this vessel can use and their densities
ModuleEngines engine = (ModuleEngines)module;
has_engines = true;
foreach (ModuleEngines.Propellant propellant in engine.propellants)
{
if (propellant.name == "ElectricCharge" || propellant.name == "IntakeAir")
{
continue;
}
if (!fuel_densities.ContainsKey(propellant.name))
fuel_densities.Add(propellant.name, PartResourceLibrary.Instance.GetDefinition(propellant.id).density);
}
}
if (module is ModuleRCS)
{
ModuleRCS rcs = (ModuleRCS)module;
if (rcs.requiresFuel)
{
has_rcs = true;
if (!rcs_fuel_densities.ContainsKey(rcs.resourceName))
rcs_fuel_densities.Add(rcs.resourceName, PartResourceLibrary.Instance.GetDefinition(rcs.resourceName).density);
}
}
if (module is ModuleParachute)
{
ModuleParachute parachute = (ModuleParachute)module;
if (parachute.deploymentState == ModuleParachute.deploymentStates.DEPLOYED)
parachutes_open = true;
}
}
}
//Determine how much fuel this vessel has and can hold
float fuel_capacity = 0.0f;
float fuel_amount = 0.0f;
float rcs_capacity = 0.0f;
float rcs_amount = 0.0f;
foreach (Part part in vessel.parts)
{
if (part != null && part.Resources != null)
{
foreach (PartResource resource in part.Resources)
{
float density = 0.0f;
//Check that this vessel can use this type of resource as fuel
if (has_engines && fuel_densities.TryGetValue(resource.resourceName, out density))
{
fuel_capacity += ((float)resource.maxAmount) * density;
fuel_amount += ((float)resource.amount) * density;
}
if (has_rcs && rcs_fuel_densities.TryGetValue(resource.resourceName, out density))
{
rcs_capacity += ((float)resource.maxAmount) * density;
rcs_amount += ((float)resource.amount) * density;
}
}
}
}
if (has_engines && fuel_capacity > 0.0f)
detail.percentFuel = (byte)Math.Round(fuel_amount / fuel_capacity * 100);
else
detail.percentFuel = byte.MaxValue;
if (has_rcs && rcs_capacity > 0.0f)
detail.percentRCS = (byte)Math.Round(rcs_amount / rcs_capacity * 100);
else
detail.percentRCS = byte.MaxValue;
}
//Determine vessel activity
if (parachutes_open)
detail.activity = Activity.PARACHUTING;
//Check if the vessel is aerobraking
if (vessel.orbit != null && vessel.orbit.referenceBody != null
&& vessel.orbit.referenceBody.atmosphere && vessel.orbit.altitude < vessel.orbit.referenceBody.maxAtmosphereAltitude)
{
//Vessel inside its body's atmosphere
switch (vessel.situation)
{
case Vessel.Situations.LANDED:
case Vessel.Situations.SPLASHED:
case Vessel.Situations.SUB_ORBITAL:
case Vessel.Situations.PRELAUNCH:
break;
default:
//If the apoapsis of the orbit is above the atmosphere, vessel is aerobraking
if (vessel.situation == Vessel.Situations.ESCAPING || (float)vessel.orbit.ApA > vessel.orbit.referenceBody.maxAtmosphereAltitude)
detail.activity = Activity.AEROBRAKING;
break;
}
}
//Check if the vessel is docking
if (detail.activity == Activity.NONE && FlightGlobals.fetch.VesselTarget != null && FlightGlobals.fetch.VesselTarget is ModuleDockingNode
&& Vector3.Distance(vessel.GetWorldPos3D(), FlightGlobals.fetch.VesselTarget.GetTransform().position) < DOCKING_TARGET_RANGE)
detail.activity = Activity.DOCKING;
return detail;
}
private void writePluginData()
{
//CurrentGameTitle
String current_game_title = String.Empty;
if (HighLogic.CurrentGame != null)
{
current_game_title = HighLogic.CurrentGame.Title;
//Remove the (Sandbox) portion of the title
const String remove = " (Sandbox)";
if (current_game_title.Length > remove.Length)
current_game_title = current_game_title.Remove(current_game_title.Length - remove.Length);
}
byte[] title_bytes = encoder.GetBytes(current_game_title);
//Build update byte array
byte[] update_bytes = new byte[1 + 4 + title_bytes.Length];
int index = 0;
//Activity
update_bytes[index] = isInFlight ? (byte)1 : (byte)0;
index++;
//Game title
KLFCommon.intToBytes(title_bytes.Length).CopyTo(update_bytes, index);
index += 4;
title_bytes.CopyTo(update_bytes, index);
index += title_bytes.Length;
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.PLUGIN_DATA, update_bytes);
}
private void writeScreenshotWatchUpdate()
{
String watch_player_name = "";
if (KLFScreenshotDisplay.windowEnabled && shouldDrawGUI)
watch_player_name = KLFScreenshotDisplay.watchPlayerName;
byte[] name_bytes = new UnicodeEncoding().GetBytes(watch_player_name);
int current_index = -1;
if (KLFScreenshotDisplay.screenshot != null && KLFScreenshotDisplay.screenshot.player == watch_player_name)
current_index = KLFScreenshotDisplay.screenshot.index;
byte[] bytes = new byte[8 + name_bytes.Length];
KLFCommon.intToBytes(KLFScreenshotDisplay.watchPlayerIndex).CopyTo(bytes, 0);
KLFCommon.intToBytes(current_index).CopyTo(bytes, 4);
name_bytes.CopyTo(bytes, 8);
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.SCREENSHOT_WATCH_UPDATE, bytes);
}
private VesselStatusInfo statusArrayToInfo(String[] status_array)
{
if (status_array != null && status_array.Length >= STATUS_ARRAY_MIN_SIZE)
{
//Read status array
VesselStatusInfo status = new VesselStatusInfo();
status.info = null;
status.ownerName = status_array[0];
status.vesselName = status_array[1];
if (status_array.Length >= 3)
status.detailText = status_array[2];
status.orbit = null;
status.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
status.color = KLFVessel.generateActiveColor(status.ownerName);
return status;
}
else
return new VesselStatusInfo();
}
private void shareScreenshot()
{
//Determine the scaled-down dimensions of the screenshot
int w = 0;
int h = 0;
KLFScreenshotDisplay.screenshotSettings.getBoundedDimensions(Screen.width, Screen.height, ref w, ref h);
//Read the screen pixels into a texture
Texture2D full_screen_tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
full_screen_tex.filterMode = FilterMode.Bilinear;
full_screen_tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, false);
full_screen_tex.Apply();
RenderTexture render_tex = new RenderTexture(w, h, 24);
render_tex.useMipMap = false;
if (KLFGlobalSettings.instance.smoothScreens && (Screen.width > w * 2 || Screen.height > h * 2))
{
//Blit the full texture to a double-sized texture to improve final quality
RenderTexture resize_tex = new RenderTexture(w * 2, h * 2, 24);
Graphics.Blit(full_screen_tex, resize_tex);
//Blit the double-sized texture to normal-sized texture
Graphics.Blit(resize_tex, render_tex);
}
else
Graphics.Blit(full_screen_tex, render_tex); //Blit the screen texture to a render texture
full_screen_tex = null;
RenderTexture.active = render_tex;
//Read the pixels from the render texture into a Texture2D
Texture2D resized_tex = new Texture2D(w, h, TextureFormat.RGB24, false);
resized_tex.ReadPixels(new Rect(0, 0, w, h), 0, 0);
resized_tex.Apply();
RenderTexture.active = null;
byte[] data = resized_tex.EncodeToPNG();
Screenshot screenshot = new Screenshot();
screenshot.player = playerName;
if (FlightGlobals.ready && FlightGlobals.ActiveVessel != null)
screenshot.description = FlightGlobals.ActiveVessel.vesselName;
screenshot.image = data;
Debug.Log("Sharing screenshot");
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.SCREENSHOT_SHARE, screenshot.toByteArray());
}
private void handleUpdate(object obj)
{
if (obj is KLFVesselUpdate)
{
handleVesselUpdate((KLFVesselUpdate)obj);
}
else if (obj is String[])
{
String[] status_array = (String[])obj;
VesselStatusInfo status = statusArrayToInfo(status_array);
if (status.ownerName != null && status.ownerName.Length > 0)
{
if (playerStatus.ContainsKey(status.ownerName))
playerStatus[status.ownerName] = status;
else
playerStatus.Add(status.ownerName, status);
}
}
}
private void handleVesselUpdate(KLFVesselUpdate vessel_update)
{
if (!isInFlight)
{
//While not in-flight don't create KLF vessel, just store the active vessel status info
if (vessel_update.state == State.ACTIVE) {
VesselStatusInfo status = new VesselStatusInfo();
status.info = vessel_update;
status.ownerName = vessel_update.player;
status.vesselName = vessel_update.name;
status.orbit = null;
status.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
status.color = KLFVessel.generateActiveColor(status.ownerName);
if (playerStatus.ContainsKey(status.ownerName))
playerStatus[status.ownerName] = status;
else
playerStatus.Add(status.ownerName, status);
}
return; //Don't handle updates while not flying a ship
}
//Build the key for the vessel
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(vessel_update.player);
sb.Append(vessel_update.id.ToString());
String vessel_key = sb.ToString();
KLFVessel vessel = null;
//Try to find the key in the vessel dictionary
VesselEntry entry;
if (vessels.TryGetValue(vessel_key, out entry))
{
vessel = entry.vessel;
if (vessel == null || vessel.gameObj == null || vessel.vesselName != vessel_update.name)
{
//Delete the vessel if it's null or needs to be renamed
vessels.Remove(vessel_key);
if (vessel != null && vessel.gameObj != null)
GameObject.Destroy(vessel.gameObj);
vessel = null;
}
else
{
//Update the entry's timestamp
VesselEntry new_entry = new VesselEntry();
new_entry.vessel = entry.vessel;
new_entry.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
vessels[vessel_key] = new_entry;
}
}
if (vessel == null) {
//Add the vessel to the dictionary
vessel = new KLFVessel(vessel_update.name, vessel_update.player, vessel_update.id);
entry = new VesselEntry();
entry.vessel = vessel;
entry.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
if (vessels.ContainsKey(vessel_key))
vessels[vessel_key] = entry;
else
vessels.Add(vessel_key, entry);
/*Queue this update for the next update call because updating a vessel on the same step as
* creating it usually causes problems for some reason */
vesselUpdateQueue.Enqueue(vessel_update);
}
else
applyVesselUpdate(vessel_update, vessel); //Apply the vessel update to the existing vessel
}
private void applyVesselUpdate(KLFVesselUpdate vessel_update, KLFVessel vessel)
{
//Find the CelestialBody that matches the one in the update
CelestialBody update_body = null;
if (vessel.mainBody != null && vessel.mainBody.bodyName == vessel_update.bodyName)
update_body = vessel.mainBody; //Vessel already has the correct body
else
{
//Find the celestial body in the list of bodies
foreach (CelestialBody body in FlightGlobals.Bodies)
{
if (body.bodyName == vessel_update.bodyName)
{
update_body = body;
break;
}
}
}
if (update_body != null)
{
//Convert float arrays to Vector3s
Vector3 pos = new Vector3(vessel_update.pos[0], vessel_update.pos[1], vessel_update.pos[2]);
Vector3 dir = new Vector3(vessel_update.dir[0], vessel_update.dir[1], vessel_update.dir[2]);
Vector3 vel = new Vector3(vessel_update.vel[0], vessel_update.vel[1], vessel_update.vel[2]);
vessel.info = vessel_update;
vessel.setOrbitalData(update_body, pos, vel, dir);
}
if (vessel_update.state == State.ACTIVE)
{
//Update the player status info
VesselStatusInfo status = new VesselStatusInfo();
status.info = vessel_update;
status.ownerName = vessel_update.player;
status.vesselName = vessel_update.name;
if (vessel.orbitValid)
status.orbit = vessel.orbitRenderer.driver.orbit;
status.lastUpdateTime = UnityEngine.Time.realtimeSinceStartup;
status.color = KLFVessel.generateActiveColor(status.ownerName);
if (playerStatus.ContainsKey(status.ownerName))
playerStatus[status.ownerName] = status;
else
playerStatus.Add(status.ownerName, status);
}
}
private void writeIntToStream(KSP.IO.FileStream stream, Int32 val)
{
stream.Write(KLFCommon.intToBytes(val), 0, 4);
}
private Int32 readIntFromStream(KSP.IO.FileStream stream)
{
byte[] bytes = new byte[4];
stream.Read(bytes, 0, 4);
return KLFCommon.intFromBytes(bytes);
}
private void safeDelete(String filename)
{
if (KSP.IO.File.Exists<KLFManager>(filename))
{
try
{
KSP.IO.File.Delete<KLFManager>(filename);
}
catch { }
}
}
private void enqueueChatOutMessage(String message)
{
String line = message.Replace("\n", ""); //Remove line breaks from message
if (line.Length > 0)
{
enqueuePluginInteropMessage(KLFCommon.PluginInteropMessageID.CHAT_SEND, encoder.GetBytes(line));
KLFChatDisplay.enqueueChatLine("[" + playerName + "] " + line);
}
}
public void updateVesselPositions()
{
foreach (KeyValuePair<String, VesselEntry> pair in vessels)
{
if (pair.Value.vessel != null)
pair.Value.vessel.updatePosition();
}
}
//Interop
private void readClientInterop()
{
if (KSP.IO.File.Exists<KLFManager>(INTEROP_CLIENT_FILENAME))
{
byte[] bytes = null;
try
{
bytes = KSP.IO.File.ReadAllBytes<KLFManager>(INTEROP_CLIENT_FILENAME);