-
Notifications
You must be signed in to change notification settings - Fork 22
/
VesselWrapper.cs
488 lines (438 loc) · 16.4 KB
/
VesselWrapper.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
// Author:
// Allis Tauri <[email protected]>
//
// Copyright (c) 2015 Allis Tauri
//
// This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.
// To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/
// or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using UnityEngine;
using KSP.UI.Screens;
using AT_Utils;
namespace ThrottleControlledAvionics
{
public class VesselWrapper
{
public ModuleTCA TCA { get; private set; }
public VesselConfig CFG { get; private set; }
private static Globals GLB => Globals.Instance;
public TCAState State;
public void SetState(TCAState state) => State |= state;
public bool IsStateSet(TCAState state) => (State & state) == state;
public Vessel vessel { get; private set; }
public Transform refT; //transform of the controller-part
public FlightCtrlState PreUpdateControls;
public FlightCtrlState PostUpdateControls;
public PhysicalProps Physics;
public AltitudeProps Altitude;
public VerticalSpeedProps VerticalSpeed;
public HorizontalSpeedProps HorizontalSpeed;
public EnginesProps Engines;
public ControlProps Controls;
public InfoProps Info;
public OnPlanetProps OnPlanetParams;
public TorqueProps Torque;
public GeometryProps Geometry;
List<VesselProps> AllPros = new List<VesselProps>();
static List<FieldInfo> AllPropFields = typeof(VesselWrapper)
.GetFields(BindingFlags.Instance|BindingFlags.Public)
.Where(fi => fi.FieldType.IsSubclassOf(typeof(VesselProps))).ToList();
//state
public CelestialBody Body => vessel.mainBody;
public Orbit orbit => vessel.orbit;
public bool OnPlanet { get; private set; }
public bool InOrbit { get; private set; }
public bool IsActiveVessel { get; private set; }
public bool LandedOrSplashed =>
vessel.LandedOrSplashed || vessel.situation == Vessel.Situations.PRELAUNCH;
public Vessel.Situations Situation => vessel.situation;
public bool AutopilotDisabled;
public bool HasUserInput;
public bool HasManeuverNode =>
vessel.patchedConicSolver != null
&& vessel.patchedConicSolver.maneuverNodes.Count > 0
&& vessel.patchedConicSolver.maneuverNodes[0] != null
|| vessel.flightPlanNode.nodes.Count > 0;
public ManeuverNode FirstManeuverNode => vessel.patchedConicSolver.maneuverNodes[0];
#region Target
public HashSet<TCAModule> TargetUsers = new HashSet<TCAModule>();
public ITargetable Target
{
get
{
var t = vessel.targetObject;
if(t == null || t is CelestialBody)
{
t = NavWayPoint ?? CFG.Target;
if(t == null && CFG.Path.Count > 0)
t = CFG.Path.Peek();
}
return t;
}
set
{
vessel.targetObject = value;
}
}
public bool HasTarget
{
get
{
return
vessel.targetObject != null &&
!(vessel.targetObject is CelestialBody) ||
NavWaypoint.fetch != null && NavWaypoint.fetch.IsActive ||
CFG.Target ||
CFG.Path.Count > 0;
}
}
public Vessel TargetVessel
{
get
{
var t = Target;
return t == null? null : t.GetVessel();
}
}
public bool TargetIsNavPoint
{
get
{
return
vessel.targetObject == null &&
NavWaypoint.fetch != null &&
NavWaypoint.fetch.IsActive;
}
}
public bool TargetIsWayPoint { get { return Target is WayPoint; } }
public void UpdateTarget(WayPoint wp)
{
if(wp != null && CFG.Target && wp != CFG.Target)
{
var t = wp.GetTarget();
if(IsActiveVessel)
FlightGlobals.fetch.SetVesselTarget(t, true);
else Target = t;
CFG.Target = wp;
CFG.Target.Update(this);
}
}
public void SetTarget(TCAModule user, WayPoint wp = null)
{
if(wp == null)
{
TargetUsers.Remove(user);
if(TargetUsers.Count == 0)
{
CFG.Target = null;
if(vessel.targetObject is WayPoint)
Target = null;
}
}
else
{
if(user != null)
TargetUsers.Add(user);
var t = wp.GetTarget();
if(IsActiveVessel && wp != CFG.Target)
FlightGlobals.fetch.SetVesselTarget(t, true);
else Target = t;
CFG.Target = wp;
CFG.Target.Update(this);
}
}
public WayPoint TargetAsWP
{
get
{
var t = Target;
if(t == null) return null;
return t as WayPoint ?? new WayPoint(t);
}
}
public WayPoint NavWayPoint
{
get
{
var nvp = NavWaypoint.fetch;
if(nvp == null || !nvp.IsActive) return null;
var wp = new WayPoint(nvp.Latitude, nvp.Longitude, nvp.Altitude+nvp.Height);
wp.Name = nvp.name;
return wp;
}
}
#endregion
#region Utils
public void Log(string msg, params object[] args) => vessel.Log(msg, args);
public Vector3 LocalDir(Vector3 worldV) => refT.InverseTransformDirection(worldV);
public Vector3 WorldDir(Vector3 localV) => refT.TransformDirection(localV);
public Vector3d PredictedSrfVelocity(float time) => vessel.srf_velocity + vessel.acceleration * time;
#endregion
#region VesselRanges
VesselRanges saved_ranges;
public void SetUnpackDistance(float distance)
{
saved_ranges = vessel.SetUnpackDistance(distance);
}
public void RestoreUnpackDistance()
{
if(saved_ranges == null) return;
vessel.vesselRanges = saved_ranges;
saved_ranges = null;
}
public void OnEnableTCA(bool enable)
{
AllPros.ForEach(p => p.OnEnableTCA(enable));
if(enable)
SetUnpackDistance(GLB.UnpackDistance);
else
RestoreUnpackDistance();
}
#endregion
void create_props()
{
AllPros.Clear();
foreach(var fi in AllPropFields)
{
var constructor = fi.FieldType.GetConstructor(new [] {typeof(VesselWrapper)});
if(constructor == null)
throw new MissingMemberException(string.Format("No suitable constructor found for {0}", fi.FieldType.Name));
var prop = constructor.Invoke(new [] {this}) as VesselProps;
if(prop != null) AllPros.Add(prop);
fi.SetValue(this, prop);
}
}
public VesselWrapper(ModuleTCA tca)
{
TCA = tca;
CFG = tca.CFG;
vessel = TCA.vessel;
create_props();
OnPlanet = vessel.OnPlanet();
InOrbit = vessel.InOrbit();
PreUpdateState(vessel.ctrlState);
UpdatePhysics();
UpdateParts();
}
public void Init()
{
UpdateEngines();
Geometry.Update();
}
public void ConnectAutopilotOutput()
{ vessel.OnAutopilotUpdate += ApplyAutopilotSteering; }
public void Reset()
{
vessel.OnAutopilotUpdate -= ApplyAutopilotSteering;
RestoreUnpackDistance();
}
public void ApplyAutopilotSteering(FlightCtrlState s)
{
if(!CFG.Enabled || Controls.AutopilotSteering.IsZero()) return;
s.pitch = Utils.Clamp(Controls.AutopilotSteering.x, -1, 1);
s.roll = Utils.Clamp(Controls.AutopilotSteering.y, -1, 1);
s.yaw = Utils.Clamp(Controls.AutopilotSteering.z, -1, 1);
}
public void PreUpdateState(FlightCtrlState s)
{
//update control info
PreUpdateControls = s;
IsActiveVessel = vessel != null && vessel == FlightGlobals.ActiveVessel;
HasUserInput =
!Mathfx.Approx(PreUpdateControls.pitch, PreUpdateControls.pitchTrim, 0.01f) ||
!Mathfx.Approx(PreUpdateControls.roll, PreUpdateControls.rollTrim, 0.01f) ||
!Mathfx.Approx(PreUpdateControls.yaw, PreUpdateControls.yawTrim, 0.01f);
AutopilotDisabled = HasUserInput;
//update onPlanet state
var on_planet = vessel.OnPlanet();
var in_orbit = vessel.InOrbit();
if(on_planet != OnPlanet)
{
if(CFG.Enabled)
CFG.EnginesProfiles.OnPlanetChanged(on_planet);
if(!on_planet)
{
if(CFG.BlockThrottle)
{
var THR = TCA.GetModule<ThrottleControl>();
if(THR != null) THR.Throttle = 0f;
}
CFG.DisableVSC();
CFG.Nav.Off();
CFG.HF.Off();
if(IsActiveVessel && TCAGui.Instance.ORB != null)
TCAGui.Instance.ActiveTab = TCAGui.Instance.ORB;
}
}
OnPlanet = on_planet;
InOrbit = in_orbit;
}
public void PostUpdateState(FlightCtrlState s)
{
PostUpdateControls = s;
Controls.Update(s);
}
[SuppressMessage("ReSharper", "InvertIf")]
public void UpdatePhysics()
{
Physics.Update();
Altitude.Update();
if(OnPlanet)
{
VerticalSpeed.Update();
HorizontalSpeed.Update();
OnPlanetParams.UpdateAeroForces();
}
if(CFG.Target)
{
CFG.Target.Update(this);
if(!CFG.Target.Valid)
{
CFG.Target = null;
TargetUsers.Clear();
}
}
}
public void UpdateEngines()
{
Engines.Sort();
Engines.Update();
Torque.Update();
if(OnPlanet)
OnPlanetParams.Update();
}
public void ClearFrameState()
{
AllPros.ForEach(p => p.ClearFrameState());
}
public void OnModulesUpdated()
{
if(Controls.PauseWhenStopped)
{
if(!(CFG.AP1 || CFG.AP2 || HorizontalSpeed.Mooving))
{
Controls.PauseWhenStopped = false;
PauseMenu.Display();
}
}
}
public void FinalUpdate() {}
public static bool AddModule<M>(PartModule m, List<M> db)
where M : PartModule
{
var module = m as M;
if(module == null) return false;
db.Add(module);
return true;
}
public void UpdateParts()
{
EngineWrapper.ThrustPI.setMaster(CFG.Engines);
Engines.Clear();
Torque.Clear();
Physics.Clear();
OnPlanetParams.Clear();
var drag_parts = 0;
var parts_count = vessel.Parts.Count;
var max_active_stage = -1;
for(int i = 0; i < parts_count; i++)
{
Part p = vessel.Parts[i];
if(p.State == PartStates.ACTIVE && p.inverseStage > max_active_stage)
max_active_stage = p.inverseStage;
Physics.UpdateMaxTemp(p);
if(p.angularDragByFI) { Physics.AngularDrag += p.angularDrag; drag_parts += 1; }
for(int j = 0, pModulesCount = p.Modules.Count; j < pModulesCount; j++)
{
var module = p.Modules[j];
if(Engines.AddEngine(module)) continue;
if(Engines.AddRCS(module)) continue;
if(OnPlanetParams.AddLaunchClamp(module)) continue;
if(OnPlanetParams.AddParachute(module)) continue;
if(OnPlanetParams.AddGear(module)) continue;
if(Torque.AddTorqueProvider(module)) continue;
}
}
Physics.AngularDrag /= drag_parts;
Engines.Clusters.Update();
if(max_active_stage >= 0 &&
(vessel.currentStage < 0 || vessel.currentStage > max_active_stage))
vessel.currentStage = StageManager.RecalculateVesselStaging(vessel);
if(CFG.EnginesProfiles.Empty) CFG.EnginesProfiles.AddProfile(Engines.All);
else if(CFG.Enabled && TCA.ProfileSyncAllowed) CFG.ActiveProfile.Update(Engines.All);
}
bool stage_is_empty(int stage)
{ return !vessel.parts.Any(p => p.hasStagingIcon && p.inverseStage == stage); }
public void ActivateNextStageImmidiate()
{
var next_stage = vessel.currentStage;
while(next_stage >= 0 && stage_is_empty(next_stage)) next_stage--;
if(next_stage == vessel.currentStage) next_stage--;
if(next_stage < 0) return;
//Log(vessel.parts.Aggregate("\n", (s, p) => s+Utils.Format("{}: {}, stage {}\n", p.Title(), p.State, p.inverseStage)));//debug
//Log("current stage {}, next stage {}, next engines {}", vessel.currentStage, next_stage, Engines.NearestEnginedStage);//debug
if(IsActiveVessel)
{
StageManager.ActivateStage(next_stage);
vessel.ActionGroups.ToggleGroup(KSPActionGroup.Stage);
if(ResourceDisplay.Instance != null)
ResourceDisplay.Instance.isDirty = true;
}
else
{
GameEvents.onStageActivate.Fire(next_stage);
vessel.parts.ForEach(p => p.activate(next_stage, vessel));
vessel.currentStage = next_stage;
vessel.ActionGroups.ToggleGroup(KSPActionGroup.Stage);
}
}
readonly ActionDamper next_cooldown = new ActionDamper(0.5);
public void ActivateNextStage() { next_cooldown.Run(ActivateNextStageImmidiate); }
public void XToggleWithEngines<T>(Multiplexer<T> mp, T cmd) where T : struct
{
if(mp[cmd]) mp.XOff();
else Engines.ActivateEnginesAndRun(() => mp.XOn(cmd));
}
public void GearOn(bool enable = true)
{
if(!CFG.AutoGear) return;
if(vessel.ActionGroups[KSPActionGroup.Gear] != enable)
vessel.ActionGroups.SetGroup(KSPActionGroup.Gear, enable);
}
public void BrakesOn(bool enable = true)
{
if(!CFG.AutoBrakes) return;
if(vessel.ActionGroups[KSPActionGroup.Brakes] != enable)
vessel.ActionGroups.SetGroup(KSPActionGroup.Brakes, enable);
}
}
/// <summary>
/// Binary flags of TCA state.
/// They should to be checked in this particular order, as they are set sequentially:
/// If a previous flag is not set, the next ones are not either.
/// </summary>
[Flags]
public enum TCAState
{
//basic state
Disabled = 0,
Enabled = 1,
HaveEC = 1 << 1,
HaveActiveEngines = 1 << 2,
Unoptimized = 1 << 3,
//vertical flight
LoosingAltitude = 1 << 4,
//cruise radar
VesselCollision = 1 << 5,
GroundCollision = 1 << 6,
Ascending = 1 << 7,
//autopilot
VTOLAssist = 1 << 8,
StabilizeFlight = 1 << 9,
}
}