/
SimModuleEngines.cs
375 lines (321 loc) · 14.7 KB
/
SimModuleEngines.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
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MechJebLib.Primitives;
using MechJebLib.Utils;
using static MechJebLib.Utils.Statics;
#nullable enable
namespace MechJebLib.Simulations.PartModules
{
public enum SimFlowMode
{
NO_FLOW,
ALL_VESSEL,
STAGE_PRIORITY_FLOW,
STACK_PRIORITY_SEARCH,
ALL_VESSEL_BALANCE,
STAGE_PRIORITY_FLOW_BALANCE,
STAGE_STACK_FLOW,
STAGE_STACK_FLOW_BALANCE,
NULL
}
public class SimModuleEngines : SimPartModule
{
private static readonly ObjectPool<SimModuleEngines> _pool = new ObjectPool<SimModuleEngines>(New, Clear);
public readonly List<SimPropellant> Propellants = new List<SimPropellant>();
public readonly Dictionary<int, SimFlowMode> PropellantFlowModes = new Dictionary<int, SimFlowMode>();
public readonly Dictionary<int, double> ResourceConsumptions = new Dictionary<int, double>();
public readonly List<double> ThrustTransformMultipliers = new List<double>();
public readonly List<V3> ThrustDirectionVectors = new List<V3>();
public bool IsOperational;
public double FlowMultiplier;
public V3 ThrustCurrent;
public V3 ThrustMax;
public V3 ThrustMin;
public double MassFlowRate;
public double ISP;
public float G;
public float MaxFuelFlow;
public float MaxThrust;
public float MinFuelFlow;
public float MinThrust;
public float MultIsp;
public float Clamp;
public float FlowMultCap;
public float FlowMultCapSharpness;
public bool ThrottleLocked;
public float ThrustPercentage;
public bool AtmChangeFlow;
public bool UseAtmCurve;
public bool UseAtmCurveIsp;
public bool UseThrottleIspCurve;
public bool UseThrustCurve;
public bool UseVelCurve;
public bool UseVelCurveIsp;
public double ModuleResiduals;
public double ModuleSpoolupTime;
public bool NoPropellants;
public readonly H1 ThrustCurve = H1.Get(true);
public readonly H1 ThrottleIspCurve = H1.Get(true);
public readonly H1 ThrottleIspCurveAtmStrength = H1.Get(true);
public readonly H1 VelCurve = H1.Get(true);
public readonly H1 VelCurveIsp = H1.Get(true);
public readonly H1 ATMCurve = H1.Get(true);
public readonly H1 ATMCurveIsp = H1.Get(true);
public readonly H1 AtmosphereCurve = H1.Get(true);
private double _throttle => Part.Vessel.MainThrottle;
private double _atmPressure => Part.Vessel.ATMPressure;
private double _atmDensity => Part.Vessel.ATMDensity;
private double _machNumber => Part.Vessel.MachNumber;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Activate()
{
IsOperational = true;
ThrustPercentage = 100f;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void UpdateEngineStatus()
{
if (CanDrawResources())
return;
IsOperational = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool CanDrawResources()
{
if (NoPropellants)
return false;
foreach (int resourceId in ResourceConsumptions.Keys)
switch (PropellantFlowModes[resourceId])
{
case SimFlowMode.NO_FLOW:
if (!PartHasResource(Part, resourceId))
return false;
break;
case SimFlowMode.ALL_VESSEL:
case SimFlowMode.ALL_VESSEL_BALANCE:
case SimFlowMode.STAGE_PRIORITY_FLOW:
case SimFlowMode.STAGE_PRIORITY_FLOW_BALANCE:
if (!PartsHaveResource(Part.Vessel.Parts, resourceId))
return false;
break;
case SimFlowMode.STAGE_STACK_FLOW:
case SimFlowMode.STAGE_STACK_FLOW_BALANCE:
case SimFlowMode.STACK_PRIORITY_SEARCH:
if (!PartsHaveResource(Part.CrossFeedPartSet, resourceId))
return false;
break;
case SimFlowMode.NULL:
return false;
default:
return false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool PartHasResource(SimPart part, int resourceId)
{
if (part.TryGetResource(resourceId, out SimResource resource))
return resource.Amount > part.Resources[resourceId].MaxAmount * ModuleResiduals + part.ResourceRequestRemainingThreshold;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool PartsHaveResource(IReadOnlyList<SimPart> parts, int resourceId)
{
for (int i = 0; i < parts.Count; i++)
if (PartHasResource(parts[i], resourceId))
return true;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Dispose()
{
_pool.Release(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SimModuleEngines Borrow(SimPart part)
{
SimModuleEngines engine = _pool.Borrow();
engine.Part = part;
return engine;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static SimModuleEngines New()
{
return new SimModuleEngines();
}
private static void Clear(SimModuleEngines m)
{
m.ThrustDirectionVectors.Clear();
m.PropellantFlowModes.Clear();
m.ResourceConsumptions.Clear();
m.Propellants.Clear();
m.ThrustTransformMultipliers.Clear();
m.ThrustCurve.Clear();
m.ThrottleIspCurve.Clear();
m.ThrottleIspCurveAtmStrength.Clear();
m.VelCurve.Clear();
m.VelCurveIsp.Clear();
m.ATMCurve.Clear();
m.ATMCurveIsp.Clear();
m.AtmosphereCurve.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool DrawingFuelFromPartDroppedInStage(SimPart p, int resourceId, int stageNum)
{
return PartHasResource(p, resourceId) && p.DecoupledInStage == stageNum;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool DrawingFuelFromPartsDroppedInStage(IList<SimPart> parts, int resourceId, int stageNum)
{
for (int i = 0; i < parts.Count; i++)
if (PartHasResource(parts[i], resourceId) && parts[i].DecoupledInStage == stageNum)
return true;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool WouldDropAccessibleFuelTank(int stageNum)
{
foreach (int resourceId in ResourceConsumptions.Keys)
switch (PropellantFlowModes[resourceId])
{
case SimFlowMode.NO_FLOW:
if (DrawingFuelFromPartDroppedInStage(Part, resourceId, stageNum))
return true;
break;
case SimFlowMode.ALL_VESSEL:
case SimFlowMode.ALL_VESSEL_BALANCE:
case SimFlowMode.STAGE_PRIORITY_FLOW:
case SimFlowMode.STAGE_PRIORITY_FLOW_BALANCE:
if (DrawingFuelFromPartsDroppedInStage(Part.Vessel.Parts, resourceId, stageNum))
return true;
break;
case SimFlowMode.STAGE_STACK_FLOW:
case SimFlowMode.STAGE_STACK_FLOW_BALANCE:
case SimFlowMode.STACK_PRIORITY_SEARCH:
if (DrawingFuelFromPartsDroppedInStage(Part.CrossFeedPartSet, resourceId, stageNum))
return true;
break;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Update()
{
ISP = ISPAtConditions();
FlowMultiplier = FlowMultiplierAtConditions();
MassFlowRate = FlowRateAtConditions();
RefreshThrust();
SetConsumptionRates();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double FlowRateAtConditions()
{
double minFuelFlow = MinFuelFlow;
double maxFuelFlow = MaxFuelFlow;
if (minFuelFlow == 0 && MinThrust > 0) minFuelFlow = MinThrust / (AtmosphereCurve.Evaluate(0f) * G);
if (maxFuelFlow == 0 && MaxThrust > 0) maxFuelFlow = MaxThrust / (AtmosphereCurve.Evaluate(0f) * G);
return Lerp(minFuelFlow, maxFuelFlow, _throttle * 0.01f * ThrustPercentage) * FlowMultiplier;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RefreshThrust()
{
ThrustCurrent = V3.zero;
ThrustMax = V3.zero;
ThrustMin = V3.zero;
double thrustLimiter = ThrustPercentage / 100f;
double maxThrust = MaxFuelFlow * FlowMultiplier * ISP * G * MultIsp;
double minThrust = MinFuelFlow * FlowMultiplier * ISP * G * MultIsp;
double eMaxThrust = minThrust + (maxThrust - minThrust) * thrustLimiter;
double eMinThrust = ThrottleLocked ? eMaxThrust : minThrust;
double eCurrentThrust = MassFlowRate * FlowMultiplier * ISP * G * MultIsp;
for (int i = 0; i < ThrustDirectionVectors.Count; i++)
{
V3 thrustDirectionVector = ThrustDirectionVectors[i];
double thrustTransformMultiplier = ThrustTransformMultipliers[i];
double tCurrentThrust = eCurrentThrust * thrustTransformMultiplier;
ThrustCurrent += tCurrentThrust * thrustDirectionVector;
ThrustMax += eMaxThrust * thrustDirectionVector * thrustTransformMultiplier;
ThrustMin += eMinThrust * thrustDirectionVector * thrustTransformMultiplier;
}
}
// for a single EngineModule, determine its flowMultiplier, subject to atmDensity + machNumber
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double FlowMultiplierAtConditions()
{
double flowMultiplier = 1;
if (AtmChangeFlow)
{
if (UseAtmCurve)
flowMultiplier = ATMCurve.Evaluate(_atmDensity * 40 / 49);
else
flowMultiplier = _atmDensity * 40 / 49;
}
if (UseThrustCurve)
flowMultiplier *= ThrustCurve.Evaluate(0.5);
if (UseVelCurve)
flowMultiplier *= VelCurve.Evaluate(_machNumber);
if (flowMultiplier > FlowMultCap)
{
double excess = flowMultiplier - FlowMultCap;
flowMultiplier = FlowMultCap + excess / (FlowMultCapSharpness + excess / FlowMultCap);
}
// some engines have e.Clamp set to float.MaxValue so we have to have the e.Clamp < 1 sanity check here
if (flowMultiplier < Clamp && Clamp < 1)
flowMultiplier = Clamp;
return flowMultiplier;
}
// for a single EngineModule, evaluate its ISP, subject to all the different possible curves
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private double ISPAtConditions()
{
double isp = AtmosphereCurve.Evaluate(_atmPressure);
if (UseThrottleIspCurve)
isp *= Lerp(1f, ThrottleIspCurve.Evaluate(_throttle), ThrottleIspCurveAtmStrength.Evaluate(_atmPressure));
if (UseAtmCurveIsp)
isp *= ATMCurveIsp.Evaluate(_atmDensity * 40 / 49);
if (UseVelCurveIsp)
isp *= VelCurveIsp.Evaluate(_machNumber);
return isp;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetConsumptionRates()
{
ResourceConsumptions.Clear();
PropellantFlowModes.Clear();
double totalDensity = 0;
for (int j = 0; j < Propellants.Count; j++)
{
SimPropellant p = Propellants[j];
double density = p.density;
// skip zero density (eC, air intakes, etc) assuming those are available and infinite
if (density <= 0)
continue;
PropellantFlowModes.TryAdd(p.id, p.FlowMode);
// ignoreForIsp fuels are not part of the total density
if (p.ignoreForIsp)
continue;
totalDensity += p.ratio * density;
}
// this is also the volume flow rate of the non-ignoreForIsp fuels. although this is a bit janky since the p.ratios in most
// stock engines sum up to 2, not 1 (1.1 + 0.9), so this is not per-liter but per-summed-ratios (the massflowrate you get out
// of the atmosphere curves (above) are also similarly adjusted by these ratios -- it is a bit of a horror show).
double volumeFlowRate = MassFlowRate / totalDensity;
for (int j = 0; j < Propellants.Count; j++)
{
SimPropellant p = Propellants[j];
double density = PartResourceLibrary.Instance.GetDefinition(p.id).density;
// this is the individual propellant volume rate. we are including the ignoreForIsp fuels in this loop and this will
// correctly calculate the volume rates of all the propellants, in L/sec. if you sum these it'll be larger than the
// volumeFlowRate by including both the ignoreForIsp fuels and if the ratios sum up to more than one.
double propVolumeRate = p.ratio * volumeFlowRate;
// skip zero density here as well
if (density <= 0)
continue;
if (ResourceConsumptions.ContainsKey(p.id))
ResourceConsumptions[p.id] += propVolumeRate;
else
ResourceConsumptions.Add(p.id, propVolumeRate);
}
}
}
}