-
Notifications
You must be signed in to change notification settings - Fork 53
/
KMPManager.cs
5892 lines (5136 loc) · 228 KB
/
KMPManager.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 System.Xml.Serialization;
using System.Collections;
using System.Threading;
namespace KMP
{
public class LoadedFileInfo
{
/// <summary>
/// The full absolute path on this computer. Uses the local system's directory separator character ('/' for Unix, '\' for Windows).
/// </summary>
public string FullPath;
/// <summary>
/// The relative path starting at the KSP main directory. Uses Unix directory separator ('/') so it will match the server's mod config file.
/// </summary>
public string LoadedPath;
/// <summary>
/// The directory that this mod has been loaded into (usually 'GameData', but could be 'Plugins' or 'Parts').
/// </summary>
public string ModDirectory;
/// <summary>
/// The relative path starting in the 'GameData', 'Plugins', or 'Parts' directory (will not have that directory name included). Uses Unix directory separator ('/') so it will match the server's mod config file.
/// </summary>
public string ModPath;
/// <summary>
/// The SHA256 hash of this file.
/// </summary>
public string SHA256;
public LoadedFileInfo(string filepath) {
FullPath = filepath.Replace('\\', '/');
string location = new System.IO.DirectoryInfo(KSPUtil.ApplicationRootPath).FullName;
LoadedPath = filepath.Substring(location.Length).Replace('\\', '/');
ModPath = LoadedPath.Substring(LoadedPath.IndexOf('/')+1); // +1 is to cut off remaining directory separator character
ModDirectory = LoadedPath.Substring(0, LoadedPath.IndexOf('/'));
}
public void HandleHash(System.Object state)
{
try {
using (System.IO.Stream hashStream = new System.IO.FileStream(FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (System.Security.Cryptography.SHA256Managed sha = new System.Security.Cryptography.SHA256Managed()) {
byte[] hash = sha.ComputeHash(hashStream);
SHA256 = BitConverter.ToString(hash).Replace("-", String.Empty);
}
Log.Debug("Added and hashed: " + ModPath + "=" + SHA256);
}
}
catch (Exception e) {
Log.Debug("Failed to hash: " + ModPath + ", exception: " + e.Message.ToString());
}
if (Interlocked.Decrement(ref KMPManager.numberOfFilesToCheck) == 0)
{
Log.Debug("All SHA hashing completed!");
KMPManager.ShaFinishedEvent.Set();
}
}
}
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class KMPManager : MonoBehaviour
{
public KMPManager()
{
//Initialize client
KMPClientMain.InitMPClient(this);
Log.Debug("Client Initialized.");
}
public class VesselEntry
{
public KMPVessel vessel;
public float lastUpdateTime;
}
public class VesselStatusInfo
{
public string ownerName;
public string vesselName;
public string detailText;
public Color color;
public KMPVesselInfo info;
public Orbit orbit;
public float lastUpdateTime;
public int currentSubspaceID;
public Guid vesselID;
}
//Singleton
public static GameObject GameObjectInstance;
//Properties
public const String GLOBAL_SETTINGS_FILENAME = "globalsettings.txt";
public const int MAX_SHA_THREADS = 20;
public const float INACTIVE_VESSEL_RANGE = 2500.0f;
public const float DOCKING_TARGET_RANGE = 200.0f;
public const int MAX_INACTIVE_VESSELS_PER_UPDATE = 16;
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 = 0.333f;
public const float GLOBAL_SETTINGS_SAVE_INTERVAL = 10.0f;
public const double MIN_SAFETY_BUBBLE_DISTANCE = 100d;
public const double SAFETY_BUBBLE_CEILING = 35000d;
public const float SCENARIO_UPDATE_INTERVAL = 30.0f;
public const int MAX_VESSEL_LOAD_ATTEMPTS = 3;
public const float FULL_PROTOVESSEL_UPDATE_TIMEOUT = 45f;
public const double PRIVATE_VESSEL_MIN_TARGET_DISTANCE = 500d;
public const string SYNC_PLATE_ID = "14ccd14d-32d3-4f51-a021-cb020ca9cbfe";
//Rendezvous smoothing
public const double SMOOTH_RENDEZ_UPDATE_MAX_DIFFPOS_SQRMAG_INCREASE_SCALE = 100d;
public const double SMOOTH_RENDEZ_UPDATE_MAX_DIFFVEL_SQRMAG_INCREASE_SCALE = 100d;
public const double SMOOTH_RENDEZ_UPDATE_EXPIRE = 5d;
public const double SMOOTH_RENDEZ_UPDATE_MIN_DELAY = 0.1d;
public const int ALLOW_RENDEZ_OBT_UPDATE_LIMIT = 250;
public const double RENDEZ_OBT_UPDATE_RELPOS_MIN_SQRMAG = 62500d;
public const double RENDEZ_OBT_UPDATE_RELVEL_MIN_SQRMAG = 62500d;
public const double RENDEZ_OBT_UPDATE_SCALE_FACTOR = 0.35d;
public const ControlTypes BLOCK_ALL_CONTROLS = ControlTypes.ALL_SHIP_CONTROLS | ControlTypes.ACTIONS_ALL | ControlTypes.EVA_INPUT | ControlTypes.TIMEWARP | ControlTypes.MISC | ControlTypes.GROUPS_ALL | ControlTypes.CUSTOM_ACTION_GROUPS;
public UnicodeEncoding encoder = new UnicodeEncoding();
public String playerName = String.Empty;
public byte inactiveVesselsPerUpdate = 0;
public float updateInterval = 1.0f;
public Dictionary<String, VesselEntry> vessels = new Dictionary<string, VesselEntry>();
public SortedDictionary<String, VesselStatusInfo> playerStatus = new SortedDictionary<string, VesselStatusInfo>();
public PauseMenu pauseMenu;
public RenderingManager renderManager;
public PlanetariumCamera planetariumCam;
public static List<LoadedFileInfo> LoadedModfiles;
public Queue<byte[]> interopInQueue = new Queue<byte[]>();
public static object interopInQueueLock = new object();
public int numberOfShips = 0;
public int gameMode = 0; //0=Sandbox, 1=Career
public bool gameCheatsEnabled = false; //Allow built-in KSP cheats
public bool gameArrr = false; //Allow private vessels to be taken if other user can successfully dock manually
public static int numberOfFilesToCheck = 0;
public static ManualResetEvent ShaFinishedEvent;
private float lastGlobalSettingSaveTime = 0.0f;
private float lastPluginDataWriteTime = 0.0f;
private float lastPluginUpdateWriteTime = 0.0f;
private float lastKeyPressTime = 0.0f;
private float lastFullProtovesselUpdate = 0.0f;
private float lastScenarioUpdateTime = 0.0f;
private float lastTimeSyncTime = 0.0f;
public float lastSubspaceLockChange = 0.0f;
//NTP-style time syncronize settings
private bool forceNTP = false;
private bool isSkewingTime = false;
private Int64 offsetSyncTick = 0; //The difference between the servers system clock and ours.
private Int64 latencySyncTick = 0; //The network lag detected by NTP.
private Int64 estimatedServerLag = 0; //The server lag detected by NTP.
private List<Int64> listClientTimeSyncLatency = new List<Int64>(); //Holds old sync time messages so we can filter bad ones
private List<Int64> listClientTimeSyncOffset = new List<Int64>(); //Holds old sync time messages so we can filter bad ones
private List<float> listClientTimeWarp = new List<float>(); //Holds the average time skew so we can tell the server how badly we are lagging.
public float listClientTimeWarpAverage = 1; //Uses this varible to avoid locking the queue.
private bool isTimeSyncronized;
public bool displayNTP = false; //Show NTP stats on the client
private const Int64 SYNC_TIME_LATENCY_FILTER = 5000000; //500 milliseconds, Must receive reply within this time or the message is discarded
private const float SYNC_TIME_INTERVAL = 30f; //How often to sync time.
private const int SYNC_TIME_VALID_COUNT = 4; //Number of SYNC_TIME's to receive until time is valid.
private const int MAX_TIME_SYNC_HISTORY = 10; //The last 10 SYNC_TIME's are used for the offset filter.
private ScreenMessage skewMessage;
private ScreenMessage vesselLoadedMessage;
private Queue<KMPVesselUpdate> vesselUpdateQueue = new Queue<KMPVesselUpdate>();
private Queue<KMPVesselUpdate> newVesselUpdateQueue = new Queue<KMPVesselUpdate>();
private Queue<KMPScenarioUpdate> scenarioUpdateQueue = new Queue<KMPScenarioUpdate>();
GUIStyle playerNameStyle, vesselNameStyle, stateTextStyle, chatLineStyle, screenshotDescriptionStyle;
private bool isEditorLocked = false;
private bool mappingGUIToggleKey = false;
private bool mappingScreenshotKey = false;
private bool mappingScreenshotToggleKey = false;
private bool mappingChatKey = false;
private bool mappingChatDXToggleKey = false;
private bool isGameHUDHidden = false;
PlatformID platform;
private bool addPressed = false;
private string newHost = "localhost";
private string newPort = "2076";
private string newFamiliar = "Server";
public bool forceQuit = false;
public bool delayForceQuit = true;
public bool gameStart = false;
public bool terminateConnection = true;
public bool gameRunning = false;
private bool activeTermination = false;
private bool clearEditorPartList = false;
private bool closePauseMenu = false;
//Vessel dictionaries
public Dictionary<Guid, Vessel.Situations> sentVessels_Situations = new Dictionary<Guid, Vessel.Situations>();
public Dictionary<Guid, Guid> serverVessels_RemoteID = new Dictionary<Guid, Guid>();
public Dictionary<Guid, int> serverVessels_PartCounts = new Dictionary<Guid, int>();
public Dictionary<Guid, List<Part>> serverVessels_Parts = new Dictionary<Guid, List<Part>>();
public Dictionary<Guid, ConfigNode> serverVessels_ProtoVessels = new Dictionary<Guid, ConfigNode>();
public Dictionary<int, string> serverKerbals_AssignedKerbals = new Dictionary<int, string>();
public Dictionary<Guid, bool> serverVessels_InUse = new Dictionary<Guid, bool>();
public Dictionary<Guid, bool> serverVessels_IsPrivate = new Dictionary<Guid, bool>();
public Dictionary<Guid, bool> serverVessels_IsMine = new Dictionary<Guid, bool>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_LastUpdateDistanceTime = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, float> serverVessels_LoadDelay = new Dictionary<Guid, float>();
public Dictionary<Guid, bool> serverVessels_InPresent = new Dictionary<Guid, bool>();
public Dictionary<Guid, float> serverVessels_ObtSyncDelay = new Dictionary<Guid, float>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_RendezvousSmoothPos = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, KeyValuePair<double,double>> serverVessels_RendezvousSmoothVel = new Dictionary<Guid, KeyValuePair<double,double>>();
public Dictionary<Guid, int> serverVessels_SkippedRendezvousUpdates = new Dictionary<Guid, int>();
public Dictionary<Guid, float> newFlags = new Dictionary<Guid, float>();
public Dictionary<uint, int> serverParts_CrewCapacity = new Dictionary<uint, int>();
private Krakensbane krakensbane;
public double lastTick = 0d;
public double skewTargetTick = 0;
public long skewServerTime = 0;
public float skewSubspaceSpeed = 1f;
public Vector3d kscPosition = Vector3d.zero;
public Vector3 activeVesselPosition = Vector3d.zero;
public Dictionary<Guid, Vector3d> dockingRelVel = new Dictionary<Guid, Vector3d>();
public GameObject ksc = null;
private bool warping = false;
private bool syncing = false;
private bool docking = false;
private bool vesselsLoaded = false;
private bool sdoReceived = false;
private float lastWarpRate = 1f;
private int chatMessagesWaiting = 0;
private Vessel lastEVAVessel = null;
private bool showServerSync = false;
private bool inGameSyncing = false;
private List<Guid> vesselUpdatesLoaded = new List<Guid>();
private bool configRead = false;
public double safetyBubbleRadius = 2000d;
private bool safetyTransparency;
private bool isVerified = false;
private IButton KMPToggleButton;
private bool KMPToggleButtonState = true;
private bool KMPToggleButtonInitialized;
public static bool showConnectionWindow = false;
public bool globalUIToggle
{
get
{
return renderManager == null || renderManager.uiElementsToDisable.Length < 1 || renderManager.uiElementsToDisable[0].activeSelf;
}
}
public bool shouldDrawGUI
{
get
{
switch (HighLogic.LoadedScene)
{
case GameScenes.SPACECENTER:
case GameScenes.EDITOR:
case GameScenes.FLIGHT:
case GameScenes.SPH:
case GameScenes.TRACKSTATION:
return KMPInfoDisplay.infoDisplayActive && globalUIToggle && KMPToggleButtonState;
default:
return false;
}
}
}
public static bool isInFlight
{
get
{
return FlightGlobals.ready && FlightGlobals.ActiveVessel != null && KMPClientMain.handshakeCompleted && KMPClientMain.receivedSettings;
}
}
public static bool isInFlightOrTracking
{
get
{
return HighLogic.LoadedScene == GameScenes.TRACKSTATION || isInFlight;
}
}
public bool isObserving
{
get
{
return isInFlight && (serverVessels_InUse.ContainsKey(FlightGlobals.ActiveVessel.id) && serverVessels_InUse[FlightGlobals.ActiveVessel.id]) ||
(serverVessels_IsPrivate.ContainsKey(FlightGlobals.ActiveVessel.id) && serverVessels_IsPrivate[FlightGlobals.ActiveVessel.id] &&
(!serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id) || !serverVessels_IsMine[FlightGlobals.ActiveVessel.id]));
}
}
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()
{
try
{
if (HighLogic.LoadedScene == GameScenes.LOADING || !gameRunning)
return; //Don't do anything while the game is loading or not in KMP game
//Queue a time sync if needed
if (isTimeSyncronized && (UnityEngine.Time.realtimeSinceStartup > lastTimeSyncTime + SYNC_TIME_INTERVAL)) {
SyncTime();
}
//Do the Phys-warp NTP time sync dance.
SkewTime();
if (syncing)
{
if (vesselLoadedMessage != null)
{
vesselLoadedMessage.duration = 0f;
}
if (isTimeSyncronized)
{
if (!inGameSyncing)
{
if (numberOfShips != 0)
{
if (!vesselsLoaded) {
vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing vessels: " + vesselUpdatesLoaded.Count + "/" + numberOfShips + " (" + (vesselUpdatesLoaded.Count * 100 / numberOfShips) + "%)", 1f, ScreenMessageStyle.UPPER_RIGHT);
} else {
vesselLoadedMessage = ScreenMessages.PostScreenMessage("Universe synchronized!",1f,ScreenMessageStyle.UPPER_RIGHT);
}
}
else
{
vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronized new universe!", 1f, ScreenMessageStyle.UPPER_RIGHT);
}
}
else
{
vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing vessels: " + FlightGlobals.Vessels.Count, 1f, ScreenMessageStyle.UPPER_RIGHT);
}
}
else
{
vesselLoadedMessage = ScreenMessages.PostScreenMessage("Synchronizing to server clock: " + listClientTimeSyncOffset.Count + "/" + SYNC_TIME_VALID_COUNT + " (" + (listClientTimeSyncOffset.Count * 100 / SYNC_TIME_VALID_COUNT) + "%)", 1f, ScreenMessageStyle.UPPER_RIGHT);
}
}
if (!isInFlight && HighLogic.LoadedScene == GameScenes.TRACKSTATION)
{
try {
SpaceTracking st = (SpaceTracking) GameObject.FindObjectOfType(typeof(SpaceTracking));
if (st.mainCamera.target.vessel != null && (serverVessels_IsMine[st.mainCamera.target.vessel.id] || !serverVessels_IsPrivate[st.mainCamera.target.vessel.id]))
{
//Public/owned vessel
st.FlyButton.Unlock();
st.DeleteButton.Unlock();
if (st.mainCamera.target.vessel.mainBody.bodyName == "Kerbin" && (st.mainCamera.target.vessel.situation == Vessel.Situations.LANDED || st.mainCamera.target.vessel.situation == Vessel.Situations.SPLASHED))
st.RecoverButton.Unlock();
else st.RecoverButton.Lock();
}
else
{
//Private unowned vessel
st.FlyButton.Lock();
st.DeleteButton.Lock();
st.RecoverButton.Lock();
}
} catch {}
}
if (lastWarpRate != TimeWarp.CurrentRate)
{
lastWarpRate = TimeWarp.CurrentRate;
OnTimeWarpRateChanged();
}
if (warping) {
writeUpdates();
return;
}
foreach (Vessel vessel in FlightGlobals.Vessels.Where(v => v.vesselType == VesselType.SpaceObject && !serverVessels_RemoteID.ContainsKey(v.id)))
{
Log.Debug("New space object!");
sendVesselMessage(vessel, false);
}
if (EditorPartList.Instance != null && clearEditorPartList)
{
clearEditorPartList = false;
EditorPartList.Instance.Refresh();
}
while (scenarioUpdateQueue.Count > 0 && vesselsLoaded)
{
applyScenarioUpdate(scenarioUpdateQueue.Dequeue());
}
if (syncing) lastScenarioUpdateTime = UnityEngine.Time.realtimeSinceStartup;
else if ((UnityEngine.Time.realtimeSinceStartup-lastScenarioUpdateTime) >= SCENARIO_UPDATE_INTERVAL)
{
sendScenarios();
}
//Update Tracking Station names for unavailable vessels
if (!isInFlight)
{
foreach (Vessel vessel in FlightGlobals.Vessels)
{
string baseName = vessel.vesselName;
if (baseName.StartsWith("* ")) baseName = baseName.Substring(2);
vessel.vesselName = (((serverVessels_InUse.ContainsKey(vessel.id) ? serverVessels_InUse[vessel.id] : false) || ((serverVessels_IsPrivate.ContainsKey(vessel.id) ? serverVessels_IsPrivate[vessel.id]: false) && (serverVessels_IsMine.ContainsKey(vessel.id) ? !serverVessels_IsMine[vessel.id] : false))) ? "* " : "") + baseName;
}
}
else //Kill Kraken-debris, clean names
{
foreach (Vessel vessel in FlightGlobals.Vessels.FindAll(v => v.vesselName.Contains("> Debris")))
{
try { if (!vessel.isEVA) killVessel(vessel); } catch (Exception e) { Log.Debug("Exception thrown in updateStep(), catch 1, Exception: {0}", e.ToString()); }
}
}
//Ensure player never touches something under another player's control
bool controlsLocked = false;
if (isInFlight && !docking && serverVessels_InUse.ContainsKey(FlightGlobals.ActiveVessel.id))
{
if (serverVessels_InUse[FlightGlobals.ActiveVessel.id])
{
ScreenMessages.PostScreenMessage("This vessel is currently controlled by another player...", 2.5f,ScreenMessageStyle.UPPER_CENTER);
InputLockManager.SetControlLock(BLOCK_ALL_CONTROLS,"KMP_Occupied");
controlsLocked = true;
}
else
{
if (InputLockManager.GetControlLock("KMP_Occupied") == (BLOCK_ALL_CONTROLS)) InputLockManager.RemoveControlLock("KMP_Occupied");
}
}
//Ensure player never touches a private vessel they don't own
if (isInFlight && !docking && serverVessels_IsPrivate.ContainsKey(FlightGlobals.ActiveVessel.id) && serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id))
{
if (!serverVessels_IsMine[FlightGlobals.ActiveVessel.id] && serverVessels_IsPrivate[FlightGlobals.ActiveVessel.id])
{
ScreenMessages.PostScreenMessage("This vessel is private...", 2.5f,ScreenMessageStyle.UPPER_CENTER);
InputLockManager.SetControlLock(BLOCK_ALL_CONTROLS,"KMP_Private");
controlsLocked = true;
}
else
{
if (InputLockManager.GetControlLock("KMP_Private") == (BLOCK_ALL_CONTROLS)) InputLockManager.RemoveControlLock("KMP_Private");
}
}
if (isInFlight && !docking && FlightGlobals.fetch.VesselTarget != null)
{
//Get targeted vessel
Vessel vesselTarget = null;
if (FlightGlobals.fetch.VesselTarget is ModuleDockingNode)
{
ModuleDockingNode moduleTarget = (ModuleDockingNode) FlightGlobals.fetch.VesselTarget;
if (moduleTarget.part.vessel != null) vesselTarget = moduleTarget.part.vessel;
}
if (FlightGlobals.fetch.VesselTarget is Vessel)
{
vesselTarget = (Vessel) FlightGlobals.fetch.VesselTarget;
}
if (vesselTarget != null) {
double distanceToTarget = Vector3d.Distance(vesselTarget.GetWorldPos3D(), FlightGlobals.ship_position);
//Check if target is private and too close
if (distanceToTarget < PRIVATE_VESSEL_MIN_TARGET_DISTANCE && serverVessels_IsPrivate.ContainsKey(vesselTarget.id) && serverVessels_IsMine.ContainsKey(vesselTarget.id))
{
if (!serverVessels_IsMine[vesselTarget.id] && serverVessels_IsPrivate[vesselTarget.id])
{
Log.Debug("Tried to target private vessel");
ScreenMessages.PostScreenMessage("Can't dock - Target vessel is Private", 4f, ScreenMessageStyle.UPPER_CENTER);
FlightGlobals.fetch.SetVesselTarget(null);
}
}
}
}
if (isInFlight && !docking && !gameArrr)
{
foreach (Vessel possible_target in FlightGlobals.Vessels.ToList())
{
checkVesselPrivacy(possible_target);
}
}
//Reset the safety bubble transparency setting so it works when we go back into flight.
if (!isInFlight)
{
safetyTransparency = false;
}
//Let's let the user know they are actually inside the bubble.
if (FlightGlobals.fetch.activeVessel != null)
{
Vessel activeVessel = FlightGlobals.fetch.activeVessel;
if (isInSafetyBubble(activeVessel.GetWorldPos3D(), activeVessel.mainBody, activeVessel.altitude) != safetyTransparency)
{
safetyTransparency = !safetyTransparency;
foreach (Part part in FlightGlobals.fetch.activeVessel.parts)
{
if (safetyTransparency)
{
setPartOpacity(part, 0.75f);
}
else
{
setPartOpacity(part, 1f);
}
}
}
}
writeUpdates();
//Once all updates are processed, update the vesselUpdateQueue with new entries
vesselUpdateQueue = newVesselUpdateQueue;
//If in flight, check remote vessels, set position variable for docking-mode position updates
if (isInFlight)
{
VesselRecoveryButton vrb = null;
try { vrb = (VesselRecoveryButton) GameObject.FindObjectOfType(typeof(VesselRecoveryButton)); } catch {}
if (controlsLocked)
{
//Prevent EVA'ing crew or vessel recovery
lockCrewGUI();
if (vrb != null) vrb.ssuiButton.Lock();
}
else
{
//Clear locks
if (!KMPChatDX.showInput)
{
InputLockManager.RemoveControlLock("KMP_ChatActive");
}
unlockCrewGUI();
if (vrb != null && FlightGlobals.ActiveVessel.mainBody.bodyName == "Kerbin" && (FlightGlobals.ActiveVessel.situation == Vessel.Situations.LANDED || FlightGlobals.ActiveVessel.situation == Vessel.Situations.SPLASHED)) vrb.ssuiButton.Unlock();
else if (vrb != null) vrb.ssuiButton.Lock();
}
checkRemoteVesselIntegrity();
activeVesselPosition = FlightGlobals.ship_CoM;
dockingRelVel.Clear();
}
//Handle all queued vessel updates
while (vesselUpdateQueue.Count > 0)
{
handleVesselUpdate(vesselUpdateQueue.Dequeue());
}
if (HighLogic.CurrentGame.flightState.universalTime < Planetarium.GetUniversalTime()) HighLogic.CurrentGame.flightState.universalTime = Planetarium.GetUniversalTime();
processClientInterop();
//Update the displayed player orbit positions
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(!KMPGlobalSettings.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)
{
Log.Debug("deleted player status for timeout: " + pair.Key + " " + pair.Value.vesselName);
delete_list.Add(pair.Key);
}
}
foreach (String key in delete_list)
playerStatus.Remove(key);
} catch (Exception ex) { Log.Debug("Exception thrown in updateStep(), catch 4, Exception: {0}", ex.ToString()); Log.Debug("uS err: " + ex.Message + " " + ex.StackTrace); }
}
private void removeKMPControlLocks()
{
InputLockManager.RemoveControlLock("KMP_Occupied");
InputLockManager.RemoveControlLock("KMP_Private");
InputLockManager.RemoveControlLock("KMP_ChatActive");
}
private void checkVesselPrivacy(Vessel vessel)
{
if (!vessel.packed && serverVessels_IsPrivate.ContainsKey(vessel.id) && serverVessels_IsMine.ContainsKey(vessel.id))
{
foreach (Part part in vessel.Parts)
{
bool enabled = !serverVessels_IsPrivate[vessel.id] || serverVessels_IsMine[vessel.id];
if (!enabled && !serverParts_CrewCapacity.ContainsKey(part.uid))
{
serverParts_CrewCapacity[part.uid] = part.CrewCapacity;
}
if (!enabled)
{
part.CrewCapacity = 0;
}
else if (serverParts_CrewCapacity.ContainsKey(part.uid))
{
part.CrewCapacity = serverParts_CrewCapacity[part.uid];
serverParts_CrewCapacity.Remove(part.uid);
}
foreach (PartModule module in part.Modules)
{
if (module is ModuleDockingNode)
{
ModuleDockingNode dmodule = (ModuleDockingNode) module;
float absCaptureRange = Math.Abs(dmodule.captureRange);
dmodule.captureRange = (enabled ? 1 : -1) * absCaptureRange;
dmodule.isEnabled = enabled;
}
if (module is ModuleGrappleNode)
{
ModuleGrappleNode gmodule = (ModuleGrappleNode) module;
float absCaptureRange = Math.Abs(gmodule.captureRange);
gmodule.captureRange = (enabled ? 1 : -1) * absCaptureRange;
gmodule.isEnabled = enabled;
}
}
}
}
}
private void dockedKickToTrackingStation()
{
if (syncing && docking)
{
GameEvents.onFlightReady.Remove(this.OnFlightReady);
HighLogic.CurrentGame = GamePersistence.LoadGame("start",HighLogic.SaveFolder,false,true);
HighLogic.CurrentGame.Start();
Invoke("OnFirstFlightReady",1f);
}
}
private void kickToTrackingStation()
{
if (!syncing)
{
Log.Debug("Selected unavailable vessel, switching");
ScreenMessages.PostScreenMessage("Selected vessel is controlled from past or destroyed!", 5f,ScreenMessageStyle.UPPER_RIGHT);
syncing = true;
StartCoroutine(returnToTrackingStation());
}
}
private void writeUpdates()
{
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginUpdateWriteTime) > updateInterval)
{
writePluginUpdate();
lastPluginUpdateWriteTime = UnityEngine.Time.realtimeSinceStartup;
}
if ((UnityEngine.Time.realtimeSinceStartup - lastPluginDataWriteTime) > PLUGIN_DATA_WRITE_INTERVAL)
{
writePluginData();
lastPluginDataWriteTime = 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;
}
}
private void checkRemoteVesselIntegrity()
{
try
{
if (!isInFlight || syncing || warping || docking) return;
foreach (Vessel vessel in FlightGlobals.Vessels.FindAll(v => v.loaded && v.id != FlightGlobals.ActiveVessel.id && serverVessels_PartCounts.ContainsKey(v.id) && serverVessels_ProtoVessels.ContainsKey(v.id)))
{
if (serverVessels_PartCounts[vessel.id] > 0 && serverVessels_PartCounts[vessel.id] > vessel.Parts.Count)
{
Log.Debug("checkRemoteVesselIntegrity killing vessel: " + vessel.id);
serverVessels_PartCounts[vessel.id] = 0;
foreach (Part part in serverVessels_Parts[vessel.id])
{
try { if (!part.vessel.isEVA && part.vessel.id != FlightGlobals.ActiveVessel.id) killVessel(part.vessel); } catch (Exception e) { Log.Debug("Exception thrown in checkRemoteVesselIntegrity(), catch 1, Exception: {0}", e.ToString()); }
}
ConfigNode protoNode = serverVessels_ProtoVessels[vessel.id];
checkProtoNodeCrew(protoNode);
ProtoVessel protovessel = new ProtoVessel(protoNode, HighLogic.CurrentGame);
addRemoteVessel(protovessel,vessel.id);
serverVessels_LoadDelay[vessel.id] = UnityEngine.Time.realtimeSinceStartup + 10f;
}
}
}
catch (Exception ex)
{
Log.Debug("Exception thrown in checkRemoteVesselIntegrity(), catch 2, Exception: {0}", ex.ToString());
Log.Debug("cRVI err: " + ex.Message + " " + ex.StackTrace);
}
}
public void disconnect(string message = "")
{
KMPClientMain.handshakeCompleted = false;
forceQuit = delayForceQuit; //If we get disconnected straight away, we should forceQuit anyway.
if (HighLogic.LoadedSceneIsFlight || HighLogic.LoadedSceneIsEditor)
{
ScreenMessages.PostScreenMessage("You have been disconnected. Please return to the Main Menu to reconnect.",300f,ScreenMessageStyle.UPPER_CENTER);
if (!String.IsNullOrEmpty(message)) ScreenMessages.PostScreenMessage(message, 300f,ScreenMessageStyle.UPPER_CENTER);
}
else
{
forceQuit = true;
ScreenMessages.PostScreenMessage("You have been disconnected. Please return to the Main Menu to reconnect.",300f,ScreenMessageStyle.UPPER_CENTER);
if (!String.IsNullOrEmpty(message)) ScreenMessages.PostScreenMessage(message, 300f,ScreenMessageStyle.UPPER_CENTER);
}
if (String.IsNullOrEmpty(message)) KMPClientMain.SetMessage("Disconnected");
else KMPClientMain.SetMessage("Disconnected: " + message);
saveGlobalSettings();
gameRunning = false;
terminateConnection = true;
//Clear any left over locks.
InputLockManager.ClearControlLocks();
}
private void writePluginUpdate()
{
if (playerName == null || playerName.Length == 0)
return;
if (!docking) writePrimaryUpdate();
bool activeVesselOk = false;
bool activeVesselIsInBubble = false;
bool activeVesselIsMine = false;
if (FlightGlobals.ActiveVessel != null)
{
activeVesselOk = true;
activeVesselIsInBubble = isInSafetyBubble(FlightGlobals.ship_position, FlightGlobals.ActiveVessel.mainBody, FlightGlobals.ActiveVessel.altitude);
activeVesselIsMine = (serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id) ? serverVessels_IsMine[FlightGlobals.ActiveVessel.id] : true);
}
if (isInFlight && !syncing && !warping && activeVesselOk && !activeVesselIsInBubble && activeVesselIsMine) {
//nearby vessels
writeSecondaryUpdates();
}
}
private void writePrimaryUpdate()
{
bool activeVesselOk = false;
bool activeVesselIsInBubble = false;
bool activeVesselLoaded = false;
bool activeVesselPacked = false;
bool activeVesselIsSyncPlate = false;
if (FlightGlobals.ActiveVessel != null)
{
activeVesselOk = true;
activeVesselIsInBubble = isInSafetyBubble(FlightGlobals.ship_position, FlightGlobals.ActiveVessel.mainBody, FlightGlobals.ActiveVessel.altitude);
activeVesselLoaded = FlightGlobals.ActiveVessel.loaded;
activeVesselPacked = FlightGlobals.ActiveVessel.packed;
activeVesselIsSyncPlate = (FlightGlobals.ActiveVessel.id.ToString() == SYNC_PLATE_ID);
}
if (!syncing && isInFlight && !warping && !isObserving && activeVesselOk && !activeVesselIsInBubble && activeVesselLoaded && !activeVesselPacked && !activeVesselIsSyncPlate)
{
lastTick = Planetarium.GetUniversalTime();
//Write vessel status
KMPVesselUpdate update = getVesselUpdate(FlightGlobals.ActiveVessel);
if (FlightGlobals.ActiveVessel.vesselType == VesselType.EVA) lastEVAVessel = 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 = KMPVessel.generateActiveColor(playerName);
my_status.ownerName = playerName;
if (FlightGlobals.ActiveVessel.vesselName.Contains(" <") && FlightGlobals.ActiveVessel.vesselName.Contains(">"))
FlightGlobals.ActiveVessel.vesselName = FlightGlobals.ActiveVessel.vesselName.Substring(0,FlightGlobals.ActiveVessel.vesselName.IndexOf(" <"));
if (String.IsNullOrEmpty(FlightGlobals.ActiveVessel.vesselName.Trim())) FlightGlobals.ActiveVessel.vesselName = "Unknown";
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);
Log.Debug("sending primary update");
try{
enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, KSP.IO.IOUtils.SerializeToBinary(update));
} catch (Exception e) { Log.Debug("Exception thrown in writePrimaryUpdate(), catch 1, Exception: {0}", e.ToString()); Log.Debug("err: " + e.Message); }
}
else
{
lastTick = 0d;
//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 if (warping)
{
status_array = new String[2];
status_array[1] = "Warping";
}
else if (syncing)
{
status_array = new String[2];
status_array[1] = "Synchronizing";
}
else
{
status_array = new String[2];
switch (HighLogic.LoadedScene)
{
case GameScenes.FLIGHT:
if (FlightGlobals.ActiveVessel != null)
{
if (serverVessels_IsMine.ContainsKey(FlightGlobals.ActiveVessel.id) ? serverVessels_IsMine[FlightGlobals.ActiveVessel.id] : true)
{
status_array[1] = "Preparing/launching from KSC";
}
else
{
status_array[1] = "Spectating " + FlightGlobals.ActiveVessel.vesselName;
}
}
else
{
status_array[1] = "Preparing/launching from KSC";
}
break;
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(KMPCommon.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
SortedList<float, Vessel> nearest_vessels = new SortedList<float, Vessel>();
foreach (Vessel vessel in FlightGlobals.Vessels)
{
if (vessel != FlightGlobals.ActiveVessel && vessel.loaded && !vessel.name.Contains(" [Past]") && !vessel.name.Contains(" [Future]") && vessel.id.ToString() != SYNC_PLATE_ID)
{
float distance = (float)Vector3d.Distance(vessel.GetWorldPos3D(), FlightGlobals.ship_position);
if (distance < INACTIVE_VESSEL_RANGE)