-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathEngineIgnitor.cs
More file actions
453 lines (394 loc) · 18.4 KB
/
EngineIgnitor.cs
File metadata and controls
453 lines (394 loc) · 18.4 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
using System;
using System.Collections.Generic;
using System.Linq;
using KSP.IO;
using UnityEngine;
namespace EngineIgnitor
{
public class OnboardIgnitorResource
{
public int Id;
public string Name;
public float Request;
public double Amount;
public double MaxAmount;
}
public class ModuleEngineIgnitor : PartModule
{
private bool _isEngineMouseOver;
public enum EngineIgnitionState
{
INVALID = -1,
NOT_IGNITED = 0,
HIGH_TEMP = 1,
IGNITED = 2,
}
public bool InRange;
public bool IsExternal;
private double _hypergolicFluidAmount = 0;
private double _hypergolicFluidMaxAmount = 0;
[KSPField(isPersistant = false)]
public int IgnitionsAvailable = -1; //-1: Infinite. 0: Unavailable. 1~...: As is.
[KSPField(isPersistant = true)]
public int IgnitionsRemained = -1;
[KSPField(isPersistant = false, guiActive = true, guiName = "Ignitions")]
public string IgnitionsAvailableString = "";
[KSPField(isPersistant = false)]
public float AutoIgnitionTemperature = 800;
[KSPField(isPersistant = false, guiActive = true, guiName = "Auto-Ignite")]
public string AutoIgnitionState = "?/800";
// In case we have multiple engines...
[KSPField(isPersistant = false)]
public int EngineIndex = 0;
[KSPField(isPersistant = false)]
public string IgnitorType = "T0";
[KSPField(isPersistant = false)]
public bool UseUllageSimulation = true;
[KSPField(isPersistant = false, guiActive = true, guiName = "Fuel Flow")]
public string UllageState;
[KSPField]
public float ChanceWhenUnstable = 0.2f;
private float _fuelFlowStability;
private float _oldFuelFlowStability;
// List of all engines. So we can pick the one we are corresponding to.
private List<EngineWrapper> _engines = new List<EngineWrapper>();
private EngineWrapper _engine = null;
// A state for the FSM.
[KSPField(isPersistant = false, guiActive = true, guiName = "Engine State")]
private EngineIgnitionState _engineState = EngineIgnitionState.INVALID;
private StartState _startState = StartState.None;
public List<string> IgnitorResourcesStr;
public List<IgnitorResource> IgnitorResources;
public override void OnStart(StartState state)
{
_startState = state;
_engines.Clear();
foreach (PartModule module in part.Modules)
{
if (module is ModuleEngines)
{
_engines.Add(new EngineWrapper(module as ModuleEngines));
}
if (module is ModuleEnginesFX)
{
_engines.Add(new EngineWrapper(module as ModuleEnginesFX));
}
}
_engine = _engines.Count > EngineIndex ? _engines[EngineIndex] : null;
if (state == StartState.Editor) IgnitionsRemained = IgnitionsAvailable;
IgnitorResources.Clear();
foreach (string str in IgnitorResourcesStr) IgnitorResources.Add(IgnitorResource.FromString(str));
}
public override void OnAwake()
{
base.OnAwake();
if (IgnitorResources == null) IgnitorResources = new List<IgnitorResource>();
if (IgnitorResourcesStr == null) IgnitorResourcesStr = new List<string>();
}
public override string GetInfo()
{
if (IgnitionsAvailable != -1)
return "Can ignite for " + IgnitionsAvailable + " time(s).\n" + "Ignitor type: " + IgnitorType + "\n";
return "Can ignite for infinite times.\n" + "Ignitor type: " + IgnitorType + "\n";
}
public void OnMouseEnter()
{
if (HighLogic.LoadedSceneIsEditor) _isEngineMouseOver = true;
}
public void OnMouseExit()
{
if (HighLogic.LoadedSceneIsEditor) _isEngineMouseOver = false;
}
void OnGUI()
{
if (_isEngineMouseOver == false) return;
string ignitorInfo = "Ignitor: ";
if (IgnitionsRemained == -1) ignitorInfo += IgnitorType + "(Infinite).";
else ignitorInfo += IgnitorType + " (" + IgnitionsRemained + ").";
string resourceRequired = "No resource requirement for ignition.";
if (IgnitorResources.Count > 0)
{
resourceRequired = "Ignition requires: ";
for (int i = 0; i < IgnitorResources.Count; ++i)
{
IgnitorResource resource = IgnitorResources[i];
resourceRequired += resource.Name + "(" + resource.Amount.ToString("F1") + ")";
if (i != IgnitorResources.Count - 1) resourceRequired += ", ";
else resourceRequired += ".";
}
}
var ullageInfo = UseUllageSimulation ? "Need settling down fuel before ignition." : "Ullage simulation disabled.";
Vector2 screenCoords = Camera.main.WorldToScreenPoint(part.transform.position);
Rect ignitorInfoRect = new Rect(screenCoords.x - 100.0f, Screen.height - screenCoords.y - 10, 200.0f, 20.0f);
GUIStyle ignitorInfoStyle = new GUIStyle { fontSize = 14, fontStyle = FontStyle.Bold };
ignitorInfoStyle.alignment = TextAnchor.MiddleCenter;
ignitorInfoStyle.normal.textColor = Color.red;
GUI.Label(ignitorInfoRect, ignitorInfo, ignitorInfoStyle);
Rect ignitorResourceListRect = new Rect(screenCoords.x - 100.0f, Screen.height - screenCoords.y + 10.0f, 200.0f, 20.0f);
GUI.Label(ignitorResourceListRect, resourceRequired, ignitorInfoStyle);
Rect ullageInfoRect = new Rect(screenCoords.x - 100.0f, Screen.height - screenCoords.y + 30.0f, 200.0f, 20.0f);
GUI.Label(ullageInfoRect, ullageInfo, ignitorInfoStyle);
}
private void Update()
{
if (!HighLogic.LoadedSceneIsFlight || _engine == null || !_engine.allowShutdown) return;
if (vessel.Landed)
{
IsExternal = CheckExternalIgnitor();
if (IsExternal)
IgnitionsAvailableString = "Provided from Ground" + " - [ " + IgnitionsRemained + "/" + IgnitionsAvailable + " ]";
else if (IgnitionsRemained != -1)
IgnitionsAvailableString = IgnitorType + " - [ " + IgnitionsRemained + "/" + IgnitionsAvailable + " ]";
}
else
IsExternal = false;
if (part != null)
AutoIgnitionState = part.temperature.ToString("F1") + "/" + AutoIgnitionTemperature.ToString("F1");
else
AutoIgnitionState = "?/" + AutoIgnitionTemperature.ToString("F1");
var totalRes = new List<OnboardIgnitorResource>();
for (int i = 0; i < IgnitorResources.Count; i++)
{
double resourceAmount = 0f;
double resourceMaxAmount = 0f;
int resourceId = PartResourceLibrary.Instance.GetDefinition(IgnitorResources[i].Name).id;
if (part != null) part.GetConnectedResourceTotals(resourceId, out resourceAmount, out resourceMaxAmount);
var foundResource = new OnboardIgnitorResource
{
Id = resourceId,
Name = IgnitorResources[i].Name,
Request = IgnitorResources[i].Amount,
Amount = resourceAmount,
MaxAmount = resourceMaxAmount
};
totalRes.Add(foundResource);
}
int hypergolicFluidId = PartResourceLibrary.Instance.GetDefinition("HypergolicFluid").id;
if (part != null)
part.GetConnectedResourceTotals(hypergolicFluidId, out _hypergolicFluidAmount, out _hypergolicFluidMaxAmount);
if (FlightGlobals.ActiveVessel != null)
{
Events["ReloadIgnitor"].guiActiveUnfocused = FlightGlobals.ActiveVessel.isEVA;
Events["ReloadIgnitor"].guiName = "Reload Ignitor (" + IgnitionsAvailableString + ")";
Events["ReloadHypergolicFluid"].guiActiveUnfocused = FlightGlobals.ActiveVessel.isEVA;
Events["ReloadHypergolicFluid"].guiName = "Reload Hypergolic Fluid (" + _hypergolicFluidAmount + "/" + _hypergolicFluidMaxAmount + ")";
}
var oldState = _engineState;
DecideNewState(oldState);
_oldFuelFlowStability = _fuelFlowStability;
CheckUllageState();
var isIgnited = IgnitionProcess(oldState, IsExternal, totalRes);
IgnitionResult(IsExternal, isIgnited);
}
private void DecideNewState(EngineIgnitionState oldState)
{
if (_engine.requestedThrust <= 0.0f || _engine.flameout || (_engine.EngineIgnited == false && _engine.allowShutdown))
{
if (_engine.part.temperature >= AutoIgnitionTemperature)
_engineState = EngineIgnitionState.HIGH_TEMP;
else
_engineState = EngineIgnitionState.NOT_IGNITED;
}
else
{
if (oldState != EngineIgnitionState.IGNITED)
{
//When changing from not-ignited to ignited, we must ensure that the throttle is non-zero or locked (SRBs)
if (vessel.ctrlState.mainThrottle > 0.0f || _engine.throttleLocked)
_engineState = EngineIgnitionState.IGNITED;
}
}
}
private void CheckUllageState()
{
if (UseUllageSimulation)
{
if (vessel.geeForce_immediate >= 0.01 || vessel.Landed)
{
UllageState = "Stable";
_fuelFlowStability = 1.0f;
//return true;
}
UllageState = "UnStable (Chance " + ChanceWhenUnstable + ")";
_fuelFlowStability = ChanceWhenUnstable;
//return false;
}
UllageState = "Very Stable";
_fuelFlowStability = 1.0f;
//return true;
}
private bool IgnitionProcess(EngineIgnitionState oldState, bool isExternal, List<OnboardIgnitorResource> aaa)
{
if (oldState == EngineIgnitionState.NOT_IGNITED && _engineState == EngineIgnitionState.IGNITED)
{
if (isExternal)
{
IgnitionsRemained--;
return true;
}
if (IgnitionsRemained > 0 || IgnitionsRemained == -1)
{
IgnitionsRemained--;
if (IgnitorResources.Count > 0)
{
string aa = null;
foreach (var a in aaa)
{
if (a.Amount >= a.Request)
part.RequestResource(a.Id, a.Request);
else
{
aa = a.Name;
break;
}
}
if (aa != null)
{
ScreenMessages.PostScreenMessage("DO NOT HAVE ENOUGH " + aa, 3f, ScreenMessageStyle.UPPER_CENTER);
_engineState = EngineIgnitionState.NOT_IGNITED;
return false;
}
}
}
float minPotential = 1.0f;
if (UseUllageSimulation)
{
minPotential *= _oldFuelFlowStability;
var chance = UnityEngine.Random.Range(0.0f, 1.0f);
var attempt = chance <= minPotential;
if (!attempt)
{
ScreenMessages.PostScreenMessage("FAILED BECAUSE OF FUEL FLOW UNSTABILITY", 3f, ScreenMessageStyle.UPPER_CENTER);
_engineState = EngineIgnitionState.NOT_IGNITED;
return false;
}
}
}
if (oldState == EngineIgnitionState.HIGH_TEMP && _engineState == EngineIgnitionState.IGNITED)
{
_engineState = EngineIgnitionState.IGNITED;
return true;
}
return true;
}
private void IgnitionResult(bool isExternal, bool isIgnited)
{
if (_engineState == EngineIgnitionState.NOT_IGNITED && ((IgnitionsRemained == 0 && !isExternal) || !isIgnited))
{
if (_engine.EngineIgnited)
{
if (IgnitionsRemained == 0)
ScreenMessages.PostScreenMessage("NO AVAILABLE IGNITIONS", 3f, ScreenMessageStyle.UPPER_CENTER);
_engine.BurstFlameoutGroups();
_engine.SetRunningGroupsActive(false);
foreach (BaseEvent baseEvent in _engine.Events)
{
if (baseEvent.name.IndexOf("shutdown", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
baseEvent.Invoke();
}
}
_engine.SetRunningGroupsActive(false);
}
}
}
private bool CheckExternalIgnitor()
{
InRange = false;
for (int i = 0; i < ModuleExternalIgnitor.ExternalIgnitors.Count; ++i)
{
ModuleExternalIgnitor itor = ModuleExternalIgnitor.ExternalIgnitors[i];
if (itor.vessel == null || itor.vessel.transform == null || itor.part == null || itor.part.transform == null)
{
ModuleExternalIgnitor.ExternalIgnitors.RemoveAt(i);
--i;
}
}
foreach (ModuleExternalIgnitor extIgnitor in ModuleExternalIgnitor.ExternalIgnitors)
{
if (extIgnitor.vessel == null || extIgnitor.vessel.transform == null || extIgnitor.part == null ||
extIgnitor.part.transform == null)
ModuleExternalIgnitor.ExternalIgnitors.Remove(extIgnitor);
Vector3 range = new Vector3();
if (extIgnitor.vessel != null && extIgnitor.part != null && extIgnitor.vessel.transform != null)
range = extIgnitor.vessel.transform.TransformPoint(extIgnitor.part.orgPos) -
_engine.vessel.transform.TransformPoint(_engine.part.orgPos);
InRange = range.magnitude < extIgnitor.IgniteRange;
}
if (InRange) return true;
return false;
}
[KSPEvent(name = "ReloadIgnitor", guiName = "Reload Ignitor", active = true, externalToEVAOnly = true, guiActive = false, guiActiveUnfocused = true, unfocusedRange = 3.0f)]
public void ReloadIgnitor()
{
if (IgnitionsAvailable == -1 || IgnitionsRemained == IgnitionsAvailable) return;
var eva = FlightGlobals.ActiveVessel;
var evaKerbalExp = eva.GetVesselCrew().First().experienceTrait.Title;
double engineIgnitorsAmountEva = 0;
double engineIgnitorsMaxAmountEva = 0;
int engineIgnitorsId = PartResourceLibrary.Instance.GetDefinition("EngineIgnitors").id;
eva.rootPart.GetConnectedResourceTotals(engineIgnitorsId, out engineIgnitorsAmountEva, out engineIgnitorsMaxAmountEva);
if (evaKerbalExp.Equals("Engineer"))
{
if (IgnitionsRemained < IgnitionsAvailable && engineIgnitorsAmountEva > 0)
{
eva.rootPart.RequestResource("EngineIgnitors", 1);
IgnitionsRemained++;
}
else
ScreenMessages.PostScreenMessage("Nothing to load", 4.0f, ScreenMessageStyle.UPPER_CENTER);
}
else
ScreenMessages.PostScreenMessage("Requires engineer power.", 4.0f, ScreenMessageStyle.UPPER_CENTER);
}
[KSPEvent(name = "ReloadHypergolicFluid", guiName = "Reload Hypergolic Fluid", active = true, externalToEVAOnly = true, guiActive = false, guiActiveUnfocused = true, unfocusedRange = 3.0f)]
public void ReloadHypergolicFluid()
{
int hypergolicFluidId = PartResourceLibrary.Instance.GetDefinition("HypergolicFluid").id;
part.GetConnectedResourceTotals(hypergolicFluidId, out _hypergolicFluidAmount, out _hypergolicFluidMaxAmount);
if (_hypergolicFluidAmount == _hypergolicFluidMaxAmount) return;
double hypergolicFluidAmountEva = 0;
double hypergolicFluidMaxAmountEva = 0;
var eva = FlightGlobals.ActiveVessel;
var evaKerbalExp = eva.GetVesselCrew().First().experienceTrait.Title;
eva.rootPart.GetConnectedResourceTotals(hypergolicFluidId, out hypergolicFluidAmountEva, out hypergolicFluidMaxAmountEva);
if (evaKerbalExp.Equals("Engineer"))
{
if (_hypergolicFluidAmount < _hypergolicFluidMaxAmount && hypergolicFluidAmountEva > 0)
{
eva.rootPart.RequestResource("HypergolicFluid", 1);
part.RequestResource("HypergolicFluid", -1);
}
else
ScreenMessages.PostScreenMessage("Nothing to load", 4.0f, ScreenMessageStyle.UPPER_CENTER);
}
else
ScreenMessages.PostScreenMessage("Requires engineer power.", 4.0f, ScreenMessageStyle.UPPER_CENTER);
}
public override void OnSave(ConfigNode node)
{
foreach (IgnitorResource ignitorResource in IgnitorResources)
{
ignitorResource.Save(node.AddNode("IGNITOR_RESOURCE"));
}
base.OnSave(node);
}
public override void OnLoad(ConfigNode node)
{
base.OnLoad(node);
IgnitorResourcesStr = new List<string>();
IgnitorResources = new List<IgnitorResource>();
foreach (ConfigNode subNode in node.GetNodes("IGNITOR_RESOURCE"))
{
if (subNode.HasValue("name") == false || subNode.HasValue("amount") == false)
{
continue;
}
IgnitorResource newIgnitorResource = new IgnitorResource();
newIgnitorResource.Load(subNode);
IgnitorResources.Add(newIgnitorResource);
IgnitorResourcesStr.Add(newIgnitorResource.ToString());
}
}
}
}