Rise
The Vieneo Province
Loading...
Searching...
No Matches
propulsion.cpp
Go to the documentation of this file.
1#include "propulsion.h"
2#include "GroundTireGrip.h"
3#include "VehicleWear.h"
11
12#include "Viewscreen.h"
13#include "../MathUtilities.h"
19
20#include <cmath>
21#include <fcntl.h> // For _O_RDWR, _O_BINARY, _O_RDONLY, O_TEXT
22#include <sys/stat.h> // For _S_IWRITE, _S_IREAD
23
24#include "AirfoilType.h"
25
26#define ODB2
27#define frictionLoggingC
28
30{
31 viewscreen = ptr;
32 logger = ptr->logger;
33
34 logger->Log("propulsion::ctor");
35
36 gndcontactG = 0.0f;
37 halfsec = 0.0f;
41 olddesiredvsi = 0.0f; // @todo move to AFCS
42 apPitchLastInput = 0.0f; // @todo move to AFCS
43 apPitchLastAttitude = 0.0f; // @todo move to AFCS
44 apTrimTimer = 0.0f; // @todo move to AFCS
51
52 oldOdoPosition = centerC; // flag to initialize for odometer tracking
53 oldOdoReference = 0; // will be initialized with above
54
55 msg[0] = 0;
56 for (int i = 0; i < MAX_ENGINES; i++)
57 {
58 ThrustReverserOutput[i] = 0.0f;
59 EngineThrustOutput[i] = 0.0f;
60 }
61}
62
64{
65 float aoaDeg = RiseMath::ToDegree(aoaRad);
66 float cL = 0.0f; // stalled
67 float clMod45 = 0.0f;
68
69 switch (type)
70 {
71 case AirfoilType::NACA64A410: // Cl max 1.193 is 9 degrees
72 aoaDeg -= -15.0f * ClDelta; // Cl max 2.625 is -6 degrees
73 cL = -0.0002934f * powf(aoaDeg, 3) + 0.0002334f * powf(aoaDeg, 2) + 0.1178f * aoaDeg + 0.3770f;
74 clMod45 = 2.2f;
75 break;
76 case AirfoilType::NACA0011SC: // Cl max 1.205 is 13.5 degrees
77 aoaDeg -= -18.5f * ClDelta; // Cl max 2.57 is -5 degrees
78 cL = -0.0002591f * powf(aoaDeg, 3) - 0.00005135f * powf(aoaDeg, 2) + 0.1210f * aoaDeg + 0.003282f;
79 clMod45 = 2.133f;
80 break;
81 case AirfoilType::NACA4412: // Cl max 1.649 is 13 degrees
82 aoaDeg -= -9.0f * ClDelta; // Cl max 3.967 is 4 degrees
83 cL = -0.0002016f * powf(aoaDeg, 3) - 0.0002088f * powf(aoaDeg, 2) + 0.1223f * aoaDeg + 0.5325f;
84 clMod45 = 2.4057f;
85 break;
86 case AirfoilType::NACA64A210: // Cl max 1.033 is 10 degrees
87 aoaDeg -= -16.5f * ClDelta; // Cl max 2.417 is -6.5 degrees
88 cL = -0.0003062f * powf(aoaDeg, 3) + 0.0009440f * powf(aoaDeg, 2) + 0.1173f * aoaDeg + 0.1833f;
89 clMod45 = 2.34f;
90 break;
91 }
92
93 // formulas unreliable past 15 degrees
94 if (cL < 0 && aoaDeg > 15)
95 cL = 0.0f;
96 else if (cL > 0 && aoaDeg < -15)
97 cL = 0.0f;
98 else
99 cL *= 1.0f + ClDelta * clMod45;
100
101 return cL;
102}
103
105{
106 float aoaDeg = RiseMath::ToDegree(aoaRad);
107 float cD = flatPlateDragCoefficient; // flat plate
108 float cdMod45 = 0.0f;
109
110 switch (type)
111 {
112 case AirfoilType::NACA64A410: // Cl max 1.193 is 9 degrees ... Cd 0.01287
113 aoaDeg -= -15.0f * CdDelta; // Cl max 2.625 is -6 degrees ... Cd 0.04165
114 cdMod45 = 3.236f;
115 cD = 0.000003614f * powf(aoaDeg, 3) + 0.0005239f * powf(aoaDeg, 2) - 0.001852f * aoaDeg + 0.006429f;
116 break;
117 case AirfoilType::NACA0011SC: // Cl max 1.205 is 13.5 degrees ... Cd 0.01541
118 aoaDeg -= -19.5f * CdDelta; // Cl max 2.57 is -5 degrees ... Cd 0.04223
119 cdMod45 = 2.74f;
120 cD = 0.0000003991f * powf(aoaDeg, 3) + 0.0005349f * powf(aoaDeg, 2) - 0.00004159f * aoaDeg - 0.002295f;
121 break;
122 case AirfoilType::NACA4412: // Cl max 1.649 is 13 degrees ... Cd 0.02025
123 aoaDeg -= -9.0f * CdDelta; // Cl max 3.967 is 4 degrees ... Cd 0.06994
124 cdMod45 = 3.454f;
125 cD = 0.00001122f * powf(aoaDeg, 3) + 0.0003242f * powf(aoaDeg, 2) - 0.0002158f * aoaDeg + 0.005358f;
126 break;
127 case AirfoilType::NACA64A210: // Cl max is 10 degrees ... Cd 0.01212
128 aoaDeg -= -16.5f * CdDelta; // Cl max is -6.5 degrees ... Cd 0.03846
129 cdMod45 = 3.17f;
130 cD = -0.000005516f * powf(aoaDeg, 3) + 0.0005084f * powf(aoaDeg, 2) - 0.001149f * aoaDeg + 0.005004f;
131 break;
132 }
133
134 cD *= 1.0f + CdDelta * cdMod45; // 10% of wing is 31% increase
135 cD = Clamp(cD, 0, flatPlateDragCoefficient);
136
137 return cD;
138}
139
140float propulsion::CalculateClMax(AirfoilType type, float ClDelta)
141{
142 float clMax = 0.0f;
143 float clMod45 = 0.0f;
144
145 switch (type)
146 {
147 case AirfoilType::NACA64A410: // Cl max 1.193 is 9 degrees
148 clMax = 1.193f; // Cl max 2.625 is -6 degrees
149 clMod45 = 2.2f;
150 break;
151 case AirfoilType::NACA0011SC: // Cl max 1.205 is 13.5 degrees
152 clMax = 1.205f; // Cl max 2.57 is -5 degrees
153 clMod45 = 2.133f;
154 break;
155 case AirfoilType::NACA4412: // Cl max 1.649 is 13 degrees
156 clMax = 1.649f; // Cl max 3.967 is 4 degrees
157 clMod45 = 2.4057f;
158 break;
159 case AirfoilType::NACA64A210: // Cl max 1.033 is 10 degrees
160 clMax = 1.033f; // Cl max 2.417 is -6.5 degrees
161 clMod45 = 2.34f;
162 break;
163 }
164
165 return clMax * (1.0f + ClDelta * clMod45);
166}
167
168float propulsion::CalculateAoaMax(AirfoilType type, float ClDelta)
169{
170 float aoaMax = 0.0f;
171 float plainFlapAoaMaxAdj = 0.0f;
172
173 switch (type)
174 {
175 case AirfoilType::NACA64A410: // Cl max 1.193 is 9 degrees
176 aoaMax = 9.0f; // Cl max 2.625 is -6 degrees
177 plainFlapAoaMaxAdj = -15.0f;
178 break;
179 case AirfoilType::NACA0011SC: // Cl max 1.205 is 13.5 degrees
180 aoaMax = 13.5f; // Cl max 2.57 is -5 degrees
181 plainFlapAoaMaxAdj = -18.5f;
182 break;
183 case AirfoilType::NACA4412: // Cl max 1.649 is 13 degrees
184 aoaMax = 13.0f; // Cl max 3.967 is 4 degrees
185 plainFlapAoaMaxAdj = -9.0f;
186 break;
187 case AirfoilType::NACA64A210: // Cl max 1.033 is 10 degrees
188 aoaMax = 10.0f; // Cl max 2.417 is -6.5 degrees
189 plainFlapAoaMaxAdj = -16.5f;
190 break;
191 }
192
193 return RiseMath::ToRadian(aoaMax + ClDelta * plainFlapAoaMaxAdj);
194}
195
196void propulsion::GetTerrainRollingCoefficients(const unsigned char type, float* rollingResistanceCrr, float* terrainRoughnessJitterCoef)
197{
198 float rollingResistanceCrrContribution = 0.0f;
199 float roughnessJitterContribution = 0.0f;
200
201 switch (type)
202 {
203 case 0: rollingResistanceCrrContribution = 0.149252459f; roughnessJitterContribution = 0.140034499f; break;
204 case 1: rollingResistanceCrrContribution = 3.0f; break;
205 case 2: rollingResistanceCrrContribution = 0.155294699f; roughnessJitterContribution = 0.110395962f; break;
206 case 3: rollingResistanceCrrContribution = 0.19890972f; roughnessJitterContribution = 0.075400626f; break;
207 case 4: rollingResistanceCrrContribution = 0.3f; roughnessJitterContribution = 0.279197232f; break;
208 case 5: rollingResistanceCrrContribution = 0.188024219f; roughnessJitterContribution = 0.16794517f; break;
209 case 6: rollingResistanceCrrContribution = 0.142987307f; roughnessJitterContribution = 0.036592876f; break;
210 case 7: rollingResistanceCrrContribution = 0.164080576f; roughnessJitterContribution = 0.041991001f; break;
211 case 8: rollingResistanceCrrContribution = 0.137754924f; roughnessJitterContribution = 0.089029615f; break;
212 case 9: rollingResistanceCrrContribution = 0.252407802f; roughnessJitterContribution = 0.250432014f; break;
213 case 10: rollingResistanceCrrContribution = 0.031694275f; roughnessJitterContribution = 0.010107074f; break;
214 case 11: rollingResistanceCrrContribution = 0.117426575f; roughnessJitterContribution = 0.110174209f; break;
215 case 12: rollingResistanceCrrContribution = 0.143053466f; roughnessJitterContribution = 0.089767837f; break;
216 case 13: rollingResistanceCrrContribution = 0.095765193f; roughnessJitterContribution = 0.018145682f; break;
217 case 14: rollingResistanceCrrContribution = 0.18167668f; roughnessJitterContribution = 0.059555865f; break;
218 case 15: rollingResistanceCrrContribution = 0.090375496f; roughnessJitterContribution = 0.039227343f; break;
219 case 16: rollingResistanceCrrContribution = 0.0462223f; roughnessJitterContribution = 0.004436346f; break;
220 case 17: rollingResistanceCrrContribution = 0.139361155f; roughnessJitterContribution = 0.109465749f; break;
221 case 18: rollingResistanceCrrContribution = 0.243311063f; roughnessJitterContribution = 0.189429028f; break;
222 case 19: rollingResistanceCrrContribution = 0.244358393f; roughnessJitterContribution = 0.214655836f; break;
223 case 20: rollingResistanceCrrContribution = 0.110182991f; roughnessJitterContribution = 0.023593817f; break;
224 case 21: rollingResistanceCrrContribution = 0.172887321f; roughnessJitterContribution = 0.092974959f; break;
225 case 22: rollingResistanceCrrContribution = 0.251099364f; roughnessJitterContribution = 0.204277683f; break;
226 case 23: rollingResistanceCrrContribution = 0.153308566f; roughnessJitterContribution = 0.124721617f; break;
227 case 24: rollingResistanceCrrContribution = 0.014f; roughnessJitterContribution = 0.002153018f; break;
228 case 25: rollingResistanceCrrContribution = 0.18702122f; roughnessJitterContribution = 0.04422358f; break;
229 case 26: rollingResistanceCrrContribution = 0.142394658f; roughnessJitterContribution = 0.069383043f; break;
230 case 27: rollingResistanceCrrContribution = 0.188285943f; roughnessJitterContribution = 0.127695657f; break;
231 case 28: rollingResistanceCrrContribution = 0.065420895f; roughnessJitterContribution = 0.026730762f; break;
232 case 29: rollingResistanceCrrContribution = 0.152859968f; roughnessJitterContribution = 0.100728901f; break;
233 case 30: rollingResistanceCrrContribution = 0.240485841f; roughnessJitterContribution = 0.211254006f; break;
234 case 31: rollingResistanceCrrContribution = 0.080389436f; roughnessJitterContribution = 0.01810045f; break;
235 }
236
237 *rollingResistanceCrr += rollingResistanceCrrContribution * 0.1f;
238 *terrainRoughnessJitterCoef += roughnessJitterContribution * 0.1f;
239}
240
241void propulsion::SendTelemetryUpstream(float fElapsedTime)
242{
243 SClientPacketNew outpacket = {};
244 const double sampleMilliseconds = std::floor(Telemetry::MonotonicSeconds() * 1000.0);
245 outpacket.sampleTimeMs = static_cast<unsigned short>(static_cast<std::uint64_t>(sampleMilliseconds));
246 outpacket.reference = playerships[0].reference; // local reference system
247
248 // for odometer
249 if (oldOdoPosition == centerC)
250 {
253 }
254
255 if (outpacket.reference < REF_INANOTHER)
256 {
257 outpacket.velocity = playerships[0].velocity;
258 outpacket.position = playerships[0].position;
259 if (outpacket.reference == oldOdoReference && outpacket.reference == REF_ONGROUND && playerships[0].groundvehicle)
260 {
261 RiseMath::Vector3 result = outpacket.position - oldOdoPosition;
263 }
264 }
265 else
266 {
267 outpacket.velocity = playerships[0].dockingvel;
268 outpacket.position = playerships[0].dockoffset;
269 }
270
271 oldOdoPosition = outpacket.position;
272 oldOdoReference = outpacket.reference;
273
274 outpacket.fuel = static_cast<unsigned short>(fuel);
275 outpacket.orientation = playerships[0].orientation;
276 outpacket.pitch1 = static_cast<short>(playerships[0].pitch / rotlimitC * 32767.0f);
277 outpacket.roll1 = static_cast<short>(playerships[0].rollRadPerSec / rotlimitC * 32767.0f);
278 outpacket.yaw1 = static_cast<short>(playerships[0].yawRadPerSec / rotlimitC * 32767.0f);
279 if (viewscreen->gameclass->bus->FlightFreeze || fElapsedTime == 0)
280 {
281 outpacket.ai = 0;
282 outpacket.aj = 0;
283 outpacket.ak = static_cast<short>(1.14f / MaxAcceleration * 32767.0f);
284 }
285 else
286 {
287 const float ai = viewscreen->sumofforces.x * oneOvergForceKmssC / fElapsedTime;
288 outpacket.ai = static_cast<short>(ai / MaxAcceleration * 32767.0f);
289 const float aj = viewscreen->sumofforces.y * oneOvergForceKmssC / fElapsedTime;
290 outpacket.aj = static_cast<short>(aj / MaxAcceleration * 32767.0f);
291 const float ak = viewscreen->sumofforces.z * oneOvergForceKmssC / fElapsedTime;
292 outpacket.ak = static_cast<short>(ak / MaxAcceleration * 32767.0f);
293 }
294 outpacket.tx = static_cast<char>(playerships[0].tx * 127.0f); // -127 to 127
295 outpacket.ty = static_cast<char>(playerships[0].ty * 127.0f); // -127 to 127
296 outpacket.tz = static_cast<char>(playerships[0].tz * 127.0f); // -127 to 127
297 outpacket.pitchdeflect = static_cast<char>(playerships[0].pitchdeflect * 127.0f); // percent*127
298 outpacket.rolldeflect = static_cast<char>(playerships[0].rolldeflect * 127.0f);
299 outpacket.yawdeflect = static_cast<char>(playerships[0].yawdeflect * 127.0f);
300 // Skid-steer vehicles have no visible steering angle. Their actual turn is already
301 // represented on the wire by orientation and yaw rate.
303 ? 0
304 : static_cast<char>(playerships[0].steerdeflect * 127.0f);
305 outpacket.airframeTemp = static_cast<short>(airframeTempCelsius * 10.0f);
306 outpacket.airIceAccumulationMm = static_cast<unsigned char>(airIceAccumulationMm);
307 outpacket.groundIceAccumulationMm = static_cast<unsigned char>(groundIceAccumulationMm);
308 outpacket.pitchTrim = static_cast<short>(viewscreen->gameclass->bus->PitchTrimScalar * 32767.0f);
309 outpacket.cabinPressureMb = static_cast<short>(viewscreen->gameclass->bus->CabinPressureMb);
310 if (viewscreen->AssertTelemetry("Propulsion::Update2", 0))
311 {
313 }
314}
315
321
322void propulsion::Update(float fElapsedTime)
323{
324 logger->AddToCallStack("propulsion::Update");
325 auto& orbitActuation=viewscreen->gameclass->bus->orbit.actuation;
326 // This stamp belongs to the physics update, which can run several times
327 // between planner turns. A skipped force application must not look fresh.
328 orbitActuation.valid=false;
329 orbitActuation.rotationEffort={};
330
331 // Recompute from usage; never compound wear into the vehicle base specifications.
333
334 RiseMath::Quaternion quaternionTemp;
335 RiseMath::Matrix matrixInverse, matrixTemp;
336 RiseMath::Vector3 result, cross;
337 float f_temp;
338
339 // reset
341
346 {
347 logger->Log("weightC was calculated to be below the ourcockpit.emptyweight!", Logger::Level::Error);
348 sprintf_s(msg, sizeof msg, "fuel %.1f pl %.1f ice %.1f type %i", fuel, payload, viewscreen->gameclass->bus->IceWeightLbs, ourcockpit.texturelib);
351 }
352 const float weightFactor = totalWeightLbs / ourcockpit.emptyWeightLbs;
353
354 viewscreen->AssertTelemetry("Propulsion::Update1", 0);
355
356
357
358 // TURN TURN TURN -------------------------------------------------------------------------------
359 RiseMath::QuaternionRotationYawPitchRoll(&quaternionTemp, playerships[0].yawRadPerSec * fElapsedTime, playerships[0].pitch * fElapsedTime, playerships[0].rollRadPerSec * fElapsedTime);
360 RiseMath::QuaternionMultiply(&playerships[0].orientation, &playerships[0].orientation, &quaternionTemp);
361 RiseMath::QuaternionNormalize(&playerships[0].orientation, &playerships[0].orientation);
362 RiseMath::MatrixRotationQuaternion(&matrixInverse, &playerships[0].orientation);
363 RiseMath::MatrixInverse(&playerships[0].matrixWorld, nullptr, &matrixInverse);
364 // TURN TURN TURN -------------------------------------------------------------------------------
365
366#pragma region debug
367 if (matrixInverse._11 > 1000.0f || matrixInverse._11 < -1000.0f || _isnan(matrixInverse._11) || isinf(matrixInverse._11) ||
368 matrixInverse._12 > 1000.0f || matrixInverse._12 < -1000.0f || _isnan(matrixInverse._12) || isinf(matrixInverse._12) ||
369 matrixInverse._13 > 1000.0f || matrixInverse._13 < -1000.0f || _isnan(matrixInverse._13) || isinf(matrixInverse._13) ||
370 matrixInverse._14 > 1000.0f || matrixInverse._14 < -1000.0f || _isnan(matrixInverse._14) || isinf(matrixInverse._14))
371 {
372 sprintf_s(msg, sizeof(msg), "Trapped a violation after world matrix calculation...");
374 }
375 if (matrixInverse._21 > 1000.0f || matrixInverse._21 < -1000.0f || _isnan(matrixInverse._21) || isinf(matrixInverse._21) ||
376 matrixInverse._22 > 1000.0f || matrixInverse._22 < -1000.0f || _isnan(matrixInverse._22) || isinf(matrixInverse._22) ||
377 matrixInverse._23 > 1000.0f || matrixInverse._23 < -1000.0f || _isnan(matrixInverse._23) || isinf(matrixInverse._23) ||
378 matrixInverse._24 > 1000.0f || matrixInverse._24 < -1000.0f || _isnan(matrixInverse._24) || isinf(matrixInverse._24))
379 {
380 sprintf_s(msg, sizeof(msg), "Trapped a violation after world matrix calculation...");
382 }
383 if (matrixInverse._31 > 1000.0f || matrixInverse._31 < -1000.0f || _isnan(matrixInverse._31) || isinf(matrixInverse._31) ||
384 matrixInverse._32 > 1000.0f || matrixInverse._32 < -1000.0f || _isnan(matrixInverse._32) || isinf(matrixInverse._32) ||
385 matrixInverse._33 > 1000.0f || matrixInverse._33 < -1000.0f || _isnan(matrixInverse._33) || isinf(matrixInverse._33) ||
386 matrixInverse._34 > 1000.0f || matrixInverse._34 < -1000.0f || _isnan(matrixInverse._34) || isinf(matrixInverse._34))
387 {
388 sprintf_s(msg, sizeof(msg), "Trapped a violation after world matrix calculation...");
390 }
391 if (matrixInverse._41 > 1000.0f || matrixInverse._41 < -1000.0f || _isnan(matrixInverse._41) || isinf(matrixInverse._41) ||
392 matrixInverse._42 > 1000.0f || matrixInverse._42 < -1000.0f || _isnan(matrixInverse._42) || isinf(matrixInverse._42) ||
393 matrixInverse._43 > 1000.0f || matrixInverse._43 < -1000.0f || _isnan(matrixInverse._43) || isinf(matrixInverse._43) ||
394 matrixInverse._44 > 1000.0f || matrixInverse._44 < -1000.0f || _isnan(matrixInverse._44) || isinf(matrixInverse._44))
395 {
396 sprintf_s(msg, sizeof(msg), "Trapped a violation after world matrix calculation...");
398 }
399#pragma endregion
400
401 // Publish the physical contact state every frame. FPA availability must
402 // not read the bus default (true) after liftoff. Docking is not ground contact.
404
405 // Velocity must save after turning
406 // &velocity is now our ship-axis-oriented velocity
407 RiseMath::Vec3TransformNormal(&localVelocity, &playerships[0].velocity, &matrixInverse);
408
409 RiseMath::Vector3 Tdockingvel;
410 if (playerships[0].reference >= REF_INANOTHER)
411 RiseMath::Vec3TransformNormal(&Tdockingvel, &playerships[0].dockingvel, &matrixInverse);
412
413 // Acceleration twice per second?, must be compared after turning
414 halfsec += fElapsedTime;
415 if (halfsec > 0.5f && playerships[0].mslKm != -1.0f)
416 {
417 // for VSI
418 const float oldgroundspeed = groundSpeedKms;
420 result = oldvelocity - playerships[0].barycentric; // in km/s
421 f_temp = RiseMath::Vec3Length(&result);
423 if (f_temp > 0.0f)
424 grounditerate = (sqrtf(f_temp) - oldgroundspeed) * 0.5f;
425 else
426 grounditerate = -oldgroundspeed * 0.5f;
427
428 if (playerships[0].mslKm > 15.0f && oldmsl <= 15.0f)
430
432
434
435 halfsec = 0.0f;
436 }
437
438 groundSpeedKms += grounditerate * fElapsedTime;
439 if (!playerships[0].groundvehicle)
441
442
443 logger->AddToCallStack("StraightAheadVector");
444
445 // Straight ahead vector
446 result.x = 0.0f; result.y = 0.0f; result.z = -1.0f; // local
447 RiseMath::Vec3TransformNormal(&viewscreen->forwardVector, &result, &playerships[0].matrixWorld); // Find straight ahead vector, world coord
448
449 // so we moved some stuff out like weather, temperature and wind speed
450
451 logger->AddToCallStack("GroundVecPropulsion");
452
453 RiseMath::Vector3 localBarycentric;
454 // Need to convert barycentric velocity to ship oriented axis velocity
455 RiseMath::Vec3TransformNormal(&localBarycentric, &playerships[0].barycentric, &matrixInverse);
456 // Adjust the ship oriented axis velocity by the barycentric ship oriented axis velocity
457 RiseMath::Vec3Subtract(&groundvec, &localBarycentric, &localVelocity);
458 // @todo this one is backwards from the locvel ... someday we need to inverse everything that uses it and swap it for locvel
459
460#pragma region debug
461 if (groundvec.x > 100.0f || groundvec.x < -100.0f || _isnan(groundvec.x) || isinf(groundvec.x) ||
462 groundvec.y>100.0f || groundvec.y < -100.0f || _isnan(groundvec.y) || isinf(groundvec.y) ||
463 groundvec.z>100.0f || groundvec.z < -100.0f || _isnan(groundvec.z) || isinf(groundvec.z) ||
464 _isnan(localBarycentric.x) || _isnan(localBarycentric.y) || _isnan(localBarycentric.z) ||
465 isinf(localBarycentric.x) || isinf(localBarycentric.y) || isinf(localBarycentric.z))
466 {
467 sprintf_s(msg, sizeof(msg), "\tbarycentric I: %f", localBarycentric.x);
469 sprintf_s(msg, sizeof(msg), "\tbarycentric J: %f", localBarycentric.y);
471 sprintf_s(msg, sizeof(msg), "\tbarycentric K: %f", localBarycentric.z);
473 sprintf_s(msg, sizeof(msg), "\tvelocity I: %f", localVelocity.x);
475 sprintf_s(msg, sizeof(msg), "\tvelocity J: %f", localVelocity.y);
477 sprintf_s(msg, sizeof(msg), "\tvelocity K: %f", localVelocity.z);
479 sprintf_s(msg, sizeof(msg), "\tour barycentric I: %f", playerships[0].barycentric.x);
481 sprintf_s(msg, sizeof(msg), "\tour barycentric J: %f", playerships[0].barycentric.y);
483 sprintf_s(msg, sizeof(msg), "\tour barycentric K: %f", playerships[0].barycentric.z);
485 sprintf_s(msg, sizeof(msg), "Trapped a violation after groundvec calculation...");
487 }
488#pragma endregion
489
490
491 logger->AddToCallStack("WindDirection");
492
493 RiseMath::Vector3 windDirectionOnly;
494 const RiseMath::Vector3 negPosNormal = -viewscreen->posnorml;
496 RiseMath::Vec3TransformNormal(&windDirectionOnly, &viewscreen->compassnorth, &matrixTemp);
497
498 // this is a vector that is why we are modulating with wind dir
499 windVectorTrueKms = viewscreen->ptrWeather->GetWindspeedKms() * windDirectionOnly;
500
501 if (windVectorTrueKms.x > 100.0f || windVectorTrueKms.x < -100.0f || _isnan(windVectorTrueKms.x) || isinf(windVectorTrueKms.x) ||
502 windVectorTrueKms.y > 100.0f || windVectorTrueKms.y < -100.0f || _isnan(windVectorTrueKms.y) || isinf(windVectorTrueKms.y) ||
503 windVectorTrueKms.z > 100.0f || windVectorTrueKms.z < -100.0f || _isnan(windVectorTrueKms.z) || isinf(windVectorTrueKms.z))
504 {
505 sprintf_s(msg, sizeof(msg), "Trapped a violation when windspeed was calculated...");
507 sprintf_s(msg, sizeof(msg), "\twindspeed: %f", viewscreen->ptrWeather->GetWindspeedKms());
509 sprintf_s(msg, sizeof(msg), "\tturbulence: %f", viewscreen->ptrWeather->GetTurbulence());
511 sprintf_s(msg, sizeof(msg), "\twinddir I: %f", windDirectionOnly.x);
513 sprintf_s(msg, sizeof(msg), "\twinddir J: %f", windDirectionOnly.y);
515 sprintf_s(msg, sizeof(msg), "\twinddir K: %f", windDirectionOnly.z);
517 }
518
519#ifdef _DEBUG
520 //viewscreen->ptrWeather->turbulence = 1.0f;
521 //viewscreen->ptrWeather->windspeed = 0.041f; // half full
522 //if (viewscreen->gameclass->GUI->IsAdmin)
523 // viewscreen->ptrWeather->turbulence = 1.0f;
524#endif
525
526 if (playerships[0].reference == REF_INANOTHER)
527 {
528 // here we are in the bay of another vehicle... if the door is open or we are on outside camera
529 if (playerships[0].mslKm != -1.0f &&
530 (playerships[playerships[0].inarray].baydoor || viewscreen->camera->outside)) // Hold off until altitude is calculated
531 {
532 // as of 5/23/2018 we take into account density adjustment based on temperature too! this is really called "delta"
533 staticDensity = expf(-fabsf(playerships[0].mslKm) / ScaleHeightC);// *288.15f / (viewscreen->ptrWeather->GetTemperatureCelsius() + ZeroCelsiusToKelvin);
534 // turned this back off 2/1/2023 since we added pressurization system this doesn't seem to be correct!
535 }
536 else
537 {
538 staticDensity = 1.0f;
539 }
540 }
541 else if (playerships[0].reference != REF_BUILDING && playerships[0].reference != REF_WINDOWLESS)
542 {
543 if (playerships[0].mslKm != -1.0f) // Hold off until altitude is calculated
544 {
545 // as of 5/23/2018 we take into account density adjustment based on temperature too! this is really called "delta"
546 staticDensity = expf(-fabsf(playerships[0].mslKm) / ScaleHeightC);// *288.15f / (viewscreen->ptrWeather->GetTemperatureCelsius() + ZeroCelsiusToKelvin);
547 // turned this back off 2/1/2023 since we added pressurization system this doesn't seem to be correct!
548 }
549 else
550 {
551 staticDensity = 1.0f;
552 }
553 }
554 else
555 {
556 staticDensity = 1.0f;
557 }
558
559
560 // @bug https://jira.risetvp.com/view.php?id=1727
561 float machWaveEffect;
562 if (mach <= 1.0f)
563 machWaveEffect = powf(mach, 12.622f);
564 else
565 machWaveEffect = 1.0f / ((powf(mach + 0.169f, 2.0f) - 1.0f) * 2.73f);
567
568
569 logger->AddToCallStack("MoreWindTurbulenceCrap");
570
571 RiseMath::Vec3TransformNormal(&localWindVector, &windVectorTrueKms, &matrixInverse); // makes it ship oriented
572
573 const float turbInput = viewscreen->ptrWeather->GetTurbulence();
574 if (turbInput > 0.0f)
575 {
576 viewscreen->turbTime += fElapsedTime;
577
578 // smooth turbulence energy (adds memory / clustering)
579 viewscreen->turbEnergy += (turbInput - viewscreen->turbEnergy) * fElapsedTime * 0.2f;
580
582
583 // relative wind magnitude (IAS proxy)
584 const float penetrationSpeed = RiseMath::Vec3Length(&relativeWindTrueKms);
585
586 // penetration response scaling (fast flight = sharper response)
587 const float penetrationResponse = RiseMath::Min(RiseMath::Max(penetrationSpeed / 0.05f, 0.2f), 1.5f);
588
589 // --- multi-scale noise (cheap, deterministic) ---
590 // low frequency = heave
591 viewscreen->turbLow = sinf(viewscreen->turbTime * 0.7f) * 0.5f + sinf(viewscreen->turbTime * 0.31f) * 0.5f;
593 {
594 // The same advected pockets obscure wings and vary rain. Preserve
595 // the calibrated gust strength and clear-air/simulator response.
596 const float inCloud=viewscreen->ptrWeather->cloudTurbulenceBlend;
598 viewscreen->ptrWeather->cloudPocket*2.f-1.f,inCloud);
599 }
600
601 // mid frequency = chop
602 const float mid = sinf(viewscreen->turbTime * 2.3f) * 0.5f + sinf(viewscreen->turbTime * 1.7f) * 0.5f;
603
604 // high frequency = light buzz (suppressed in dense atmosphere)
605 const float high = sinf(viewscreen->turbTime * 8.1f) * 0.5f + sinf(viewscreen->turbTime * 6.3f) * 0.5f;
606
607 // vertical dominance (Vieneo = dense, heavy air)
608 float vertical = (viewscreen->turbLow * 0.6f + mid * 0.3f + high * 0.1f) * t * penetrationResponse;
609
610 // horizontal components are weaker
611 float lateralX =
612 (sinf(viewscreen->turbTime * 1.3f) * 0.5f +
613 sinf(viewscreen->turbTime * 0.77f) * 0.3f +
614 sinf(viewscreen->turbTime * 2.6f) * 0.2f) *
615 0.3f * t * penetrationResponse;
616
617 float lateralZ =
618 (sinf(viewscreen->turbTime * 1.6f) * 0.5f +
619 sinf(viewscreen->turbTime * 0.93f) * 0.3f +
620 sinf(viewscreen->turbTime * 2.9f) * 0.2f) *
621 0.3f * t * penetrationResponse;
622
623 // build gust vector directly (DO NOT normalize)
625 gust.x = lateralX * 0.01581f;
626 gust.y = vertical * 0.01581f;
627 gust.z = lateralZ * 0.01581f;
628 // so 1/17/2026 we use the square of the turbEnergy (so 0.5 effectively becomes half at 0.25) ... and the Vieneo adjusted EDR plus a 1.5x design limit assumption lands us at 15.81 m/s (~32 kts) which is strong in 2.6 bar ...
629 // @ref https://chatgpt.com/g/g-p-68331f298f88819189596309160f7056/c/696271f4-46ec-8328-a2d5-775295a619ea
630
631 // apply gust directly
632 localWindVector += gust;
633
634 // cockpit physiological response (rare, not rhythmic)
635 if (playerships[0].reference != Reference::REF_ONGROUND &&
636 fabsf(vertical) > 0.5f * t)
637 {
638 ourcockpit.adrenolinBPM += 10.0f * t * fElapsedTime;
639 }
640
641 // safety clamp
642 if (localWindVector.x > 100.0f || localWindVector.x < -100.0f ||
643 localWindVector.y > 100.0f || localWindVector.y < -100.0f ||
644 localWindVector.z > 100.0f || localWindVector.z < -100.0f ||
645 _isnan(localWindVector.x) || _isnan(localWindVector.y) || _isnan(localWindVector.z) ||
646 isinf(localWindVector.x) || isinf(localWindVector.y) || isinf(localWindVector.z))
647 {
648 sprintf_s(msg, sizeof(msg), "Turbulence clamp triggered");
650 }
651 }
652
654
655
656#pragma region debug
657 if (localWindVector.x > 100.0f || localWindVector.x < -100.0f || _isnan(localWindVector.x) || isinf(localWindVector.x) ||
658 localWindVector.y > 100.0f || localWindVector.y < -100.0f || _isnan(localWindVector.y) || isinf(localWindVector.y) ||
659 localWindVector.z > 100.0f || localWindVector.z < -100.0f || _isnan(localWindVector.z) || isinf(localWindVector.z))
660 {
661 sprintf_s(msg, sizeof(msg), "Trapped a violation after windspeed transformed by inverse matrix...");
663 }
664#pragma endregion
665
666 // Evaluate weather alerts after this frame's ambient wind and gusts are available.
669
670 logger->AddToCallStack("RelativeWindCalculation");
671
673
674 // Feed reactive windshear from the same ambient + gust velocity used by
675 // flight physics. matrixWorld maps body to world; this is a velocity TO,
676 // regardless of the weather display's meteorological direction convention.
682 const auto& windSample = viewscreen->gameclass->bus->WindshearWind;
683 viewscreen->gameclass->bus->WindUpdraftMs = windSample.valid ?
684 GpwsWindshear::Dot(windSample.windToMs,windSample.up) : 0.f;
685
686#pragma region debug
687 if (relativeWindTrueKms.x > 100.0f || relativeWindTrueKms.x < -100.0f || _isnan(relativeWindTrueKms.x) || isinf(relativeWindTrueKms.x) ||
688 relativeWindTrueKms.y > 100.0f || relativeWindTrueKms.y < -100.0f || _isnan(relativeWindTrueKms.y) || isinf(relativeWindTrueKms.y) ||
689 relativeWindTrueKms.z > 100.0f || relativeWindTrueKms.z < -100.0f || _isnan(relativeWindTrueKms.z) || isinf(relativeWindTrueKms.z))
690 {
691 sprintf_s(msg, sizeof(msg), "Trapped a violation after wind calculation...");
693 sprintf_s(msg, sizeof(msg), "\tdensity: %f", staticDensity);
695 sprintf_s(msg, sizeof(msg), "\tgroundvec I: %f", groundvec.x);
697 sprintf_s(msg, sizeof(msg), "\tgroundvec J: %f", groundvec.y);
699 sprintf_s(msg, sizeof(msg), "\tgroundvec K: %f", groundvec.z);
701 sprintf_s(msg, sizeof(msg), "\tlocalWindVector I: %f", localWindVector.x);
703 sprintf_s(msg, sizeof(msg), "\tlocalWindVector J: %f", localWindVector.y);
705 sprintf_s(msg, sizeof(msg), "\tlocalWindVector K: %f", localWindVector.z);
707 deathinhibit = FLT_MAX;
709 return;
710 }
711#pragma endregion
712
714
715 logger->AddToCallStack("PropulsionSection");
716
717 // Propulsion section ---------------------------------------------------------------------------
718 if (playerships[0].reference != REF_BUILDING && playerships[0].reference != REF_WINDOWLESS)
719 {
720 logger->AddToCallStack("CurrentRelativeVelocity");
721
722 RiseMath::Vector3 tvmTargetVelocity, dorTargetVelocity = playerships[0].velocity;
723 if (viewscreen->gameclass->bus->targetC == -1) // User waypoint, ground reference
724 {
725 tvmTargetVelocity = playerships[0].barycentric;
726 }
727 else if (viewscreen->gameclass->bus->targetC >= 0) // ship in contact list
728 {
731 if (network_objects.reference == REF_INANOTHER)
732 {
733 s_network_objects parent = playerships[network_objects.inarray];
734 tvmTargetVelocity = parent.velocity;
735 }
736 else if (network_objects.reference < REF_INANOTHER)
737 tvmTargetVelocity = network_objects.velocity;
738 else
739 tvmTargetVelocity = network_objects.dockingvel;
740 }
741 else if (viewscreen->gameclass->bus->targetC < -1) // Docks
742 {
743 if (playerships[0].reference < REF_INANOTHER)
744 tvmTargetVelocity = allobjects[-viewscreen->gameclass->bus->targetC - 2].velocity;
745 else
746 tvmTargetVelocity = centerC;
747 }
748
749 logger->AddToCallStack("CurrentLocalVelocity");
750
751 // Current local velocity
752 if (playerships[0].reference >= REF_INANOTHER)
753 RiseMath::Vec3Subtract(&tvmRelativeVelocity, &playerships[0].dockingvel, &tvmTargetVelocity);
754 else
755 RiseMath::Vec3Subtract(&tvmRelativeVelocity, &playerships[0].velocity, &tvmTargetVelocity);
757 {
760 dorRelativeVelocity = RiseMath::Vector3(float(error.x), float(error.y), float(error.z));
761 }
762 else if (playerships[0].reference >= REF_INANOTHER)
763 RiseMath::Vec3Subtract(&dorRelativeVelocity, &playerships[0].dockingvel, &dorTargetVelocity);
764 else
765 RiseMath::Vec3Subtract(&dorRelativeVelocity, &playerships[0].velocity, &dorTargetVelocity);
766
767 // Convert to relative velocities in x, y, z
771 const auto& entryBus=viewscreen->gameclass->bus->orbit;
772 const bool entryFresh=viewscreen->gameclass->bus->ProgramTime>=entryBus.sourceTime&&
774 const bool continuousEntry=viewscreen->gameclass->bus->AFCS.DorOn&&entryFresh&&
775 (entryBus.guidance.entryControl||entryBus.guidance.ascentControl||entryBus.guidance.poweredRendezvous)&&entryBus.guidance.valid&&entryBus.guidance.thrust;
776 const bool entrySpeedHold=viewscreen->gameclass->bus->AFCS.AutothrottleEngaged&&
777 entryFresh&&entryBus.speedHoldValid;
778 RiseMath::Vector3 entryAcceleration{};
779 if(continuousEntry) {
780 const auto command=entryBus.guidance.accelerationCommand;
781 entryAcceleration={float(command.x),float(command.y),float(command.z)};
782 RiseMath::Vec3TransformNormal(&entryAcceleration,&entryAcceleration,&matrixInverse);
783 } else if(entrySpeedHold) entryAcceleration.z=float(entryBus.speedHoldAcceleration);
784
785
786 float bypassMod = 1.0f;
787 float bypassGrowl = 0.0f;
789 {
790 float compressorDensity;
792 compressorDensity = staticDensity;
794 compressorDensity = expf(-fabsf(playerships[0].mslKm - ourcockpit.criticalEngineAltitudeKm) / ScaleHeightC);
795 else
796 compressorDensity = 1.0f;
797 // so if we are 50% bypass then we keep 50% plus static density times the other 50
798 // so if we are 20% bypass that is 0.2 ... we lerp 0.0 to 0.2 based on density (1 is ground so we get 0.2!)
799
800 bypassMod = 1.0f - ourcockpit.bypassPercentage;
801 if (!playerships[0].isSimulator)
802 bypassGrowl = Lerp(0, ourcockpit.bypassPercentage, compressorDensity);
803 bypassMod += bypassGrowl;
804 }
805
806 logger->AddToCallStack("EngineOutput");
807
808 // Logic for the tail engine that we have no discreet control over
809 if (ourcockpit.engines == 3)
811
812 float antiIceEffectiveness = 0.0f;
814 antiIceEffectiveness = static_cast<float>(ourcockpit.vdat.antiIce) / 127.0f;
815
816 const float rainAirThrustMultiplier = RainAir::ThrustMultiplier(viewscreen->gameclass->bus->RainAirStatus);
817
818 // Calculate output of each engine
819 float zThrustAvgPercent = 0.0f, zThrustAcceleration = 0.0f, zThrustAcceleration4FF = 0.0f, rcsThrustYPR = 0.0f;
820 for (int i = 0; i < ourcockpit.engines; i++)
821 {
822 // Adjust velocity (fire mains)
823 const auto& orbital = viewscreen->gameclass->bus->orbit;
824 const bool dorThrust = orbital.guidance.valid && orbital.guidance.thrust &&
825 viewscreen->gameclass->bus->ProgramTime >= orbital.sourceTime &&
826 viewscreen->gameclass->bus->ProgramTime - orbital.sourceTime < .5;
827 if(continuousEntry||entrySpeedHold) {
828 const auto command=Orbital::EntryControl::MainEngine(entryAcceleration.z,
829 entryBus.entryForwardAcceleration,entryBus.entryReverseAcceleration,
832 viewscreen->gameclass->bus->EngineThrustLever[i]=float(command.lever);
833 viewscreen->gameclass->bus->ThrustReverserCommand[i]=command.reverse;
834 }
835 else if ((viewscreen->gameclass->bus->AFCS.DorOn && !dorThrust)||
836 (viewscreen->gameclass->bus->AFCS.AutothrottleEngaged&&!entrySpeedHold))
837 {
839 // Continuous control interlocks bucket travel before resuming
840 // power, so inhibition can retain its commanded direction.
841 // Legacy orbital burns still prepare forward idle while aligning.
842 if(!orbital.guidance.entryControl&&!orbital.guidance.ascentControl&&!orbital.guidance.poweredRendezvous&&
845 }
847 {
848 // distance velocity acceleration jerk
849 // distance velocity acceleration
850 // a = 2 * (Δd - v_i * Δt) / Δt²,
851 // jerk = 2 * (Δv - acceleration * Δt) / Δt²
853 f_temp = viewscreen->gameclass->bus->AFCS.DesiredClosingSpeed - tvmRelativeVelocity.z; // difference in zvelocity
854 else
855 f_temp = -dorRelativeVelocity.z; // difference in zvelocity
857 //float timeToChange = fabsf(f_temp / currentThrust);
859 f_temp = 2.0f * (f_temp - currentThrust * ourcockpit.spoolTime * 0.5f) / powf(ourcockpit.spoolTime * 0.5f, 2.0f);
861 if (f_temp > 0)
862 {
863 // desired is 1.0kms and we are at 0.9kms = 0.1kms² / 0.0338f for the A-4 is 2.958579881656805 or 100%
864 // it takes him ourcockpit.spoolTime 16.9 seconds to adjust 100% of the thrust
865 // so we have a target velocity
868 }
869 else
870 {
874 }
875 }
876
877 // Reversers
879 {
880 ThrustReverserOutput[i] += fElapsedTime * 0.5f; // 2 seconds
881 if (ThrustReverserOutput[i] > 1.0f)
882 ThrustReverserOutput[i] = 1.0f;
883 }
884 else
885 {
886 ThrustReverserOutput[i] -= fElapsedTime * 0.5f; // 2 seconds
887 if (ThrustReverserOutput[i] < 0.0f)
888 ThrustReverserOutput[i] = 0.0f;
889 }
890
892
893 // for CAS to watch
894 if (viewscreen->gameclass->bus->EngineThrustCommand[i] > f_temp)
895 {
896 if (ourcockpit.spoolTime > 0)
898 else
899 viewscreen->gameclass->bus->EngineThrustCommand[i] -= 0.02f * fElapsedTime;
900
901 if (viewscreen->gameclass->bus->EngineThrustCommand[i] < f_temp)
903 }
904 else if (viewscreen->gameclass->bus->EngineThrustCommand[i] < f_temp)
905 {
906 if (ourcockpit.spoolTime > 0)
908 else
909 viewscreen->gameclass->bus->EngineThrustCommand[i] += 0.02f * fElapsedTime;
910 if (viewscreen->gameclass->bus->EngineThrustCommand[i] > f_temp)
912 }
913
914 // also need to adjust based on ourcockpit.power, before engine thrust output because we actually stop FCU from working
915 f_temp *= ourcockpit.power;
916
917 // for fuel flow (before damage and engine critical altitude)
919 zThrustAcceleration4FF += ourcockpit.fwdthrustlimit * f_temp / static_cast<float>(ourcockpit.engines);
920 else
921 logger->Log("Yup, this was it... divide by zero error on ourcockpit.engines #1", Logger::Level::Debug);
922
923 // we need to kill percent thrust based on damage on engines, before engine thrust output because this is what we want to base alert on!
924 if (i == 0)
925 {
926 const float leftHealth = ourcockpit.vdat.leftengine > -1 ? static_cast<float>(ourcockpit.vdat.leftengine) / 127.0f : 0;
927 f_temp *= leftHealth;
928 }
929 else if ((i == 1 && ourcockpit.engines == 2) || (i == 2 && ourcockpit.engines == 3))
930 {
931 const float rightHealth = ourcockpit.vdat.rightengine > -1 ? static_cast<float>(ourcockpit.vdat.rightengine) / 127.0f : 0;
932 f_temp *= rightHealth;
933 }
934 else if (i == 1 && ourcockpit.engines == 3)
935 {
936 const float centerHealth = ourcockpit.vdat.clengine > -1 ? static_cast<float>(ourcockpit.vdat.clengine) / 127.0f : 0;
937 f_temp *= centerHealth;
938 }
939
940 // smoothly seek the desired output
941 if (viewscreen->gameclass->bus->EngineThrustOutput[i] > f_temp)
942 {
943 if (ourcockpit.spoolTime > 0)
945 else
946 viewscreen->gameclass->bus->EngineThrustOutput[i] -= 0.02f * fElapsedTime;
947
948 if (viewscreen->gameclass->bus->EngineThrustOutput[i] < f_temp)
950 }
951 else if (viewscreen->gameclass->bus->EngineThrustOutput[i] < f_temp)
952 {
953 if (ourcockpit.spoolTime > 0)
955 else
956 viewscreen->gameclass->bus->EngineThrustOutput[i] += 0.02f * fElapsedTime;
957 if (viewscreen->gameclass->bus->EngineThrustOutput[i] > f_temp)
959 }
960
961 // this is the end of what is now displayed for the engine output and what the ENG FAIL message will be cued by
962 // can no longer use f_temp
963
964 // average for transmitting
965 zThrustAvgPercent += viewscreen->gameclass->bus->EngineThrustOutput[i] * Lerp(1, -1, ThrustReverserOutput[i]);
966
967 // reverser 0-1 means lerp between fwdthrustlimit and revthrustlimit
969 if (_isnan(zThrustAcceleration) || isinf(zThrustAcceleration))
970 {
971 logger->Log("Yup, this was it...", Logger::Level::Debug);
972 sprintf_s(msg, sizeof(msg), "\tourcockpit.fwdthrustlimit: %f", ourcockpit.fwdthrustlimit);
974 sprintf_s(msg, sizeof(msg), "\tourcockpit.revthrustlimit: %f", ourcockpit.revthrustlimit);
976 sprintf_s(msg, sizeof(msg), "\tThrustReverserOutput[%i]: %f", i, ThrustReverserOutput[i]);
978 sprintf_s(msg, sizeof(msg), "\tEngineThrustOutput[%i]: %f", i, viewscreen->gameclass->bus->EngineThrustOutput[i]);
980 zThrustAcceleration = 0.0f;
981 }
982
983 // Main engine sound
984 if (!playerships[0].groundvehicle || ourcockpit.texturelib == VehicleType::T27)
985 {
986 const int source = EngineAudio::SlotForEngine(ourcockpit.engines, i);
987 const SOUNDS soundEnum = source >= 0 ? static_cast<SOUNDS>(SOUND_COCKPITENGINELEFT + source) : SOUND_NONE;
988 const float pan = source == EngineAudio::Left ? -1.f : source == EngineAudio::Right ? 1.f : 0.f;
989
991 if (soundEnum != SOUND_NONE)
992 {
994 {
995 const float vol = ourcockpit.power * RiseMath::Max(sqrtf(viewscreen->gameclass->bus->EngineThrustOutput[i]), 0.25f);
996 viewscreen->gameclass->sound->PlayEx(soundEnum, true, vol, ourcockpit.power * 0.2f + 0.8f * viewscreen->gameclass->bus->EngineThrustOutput[i], pan, false, true, true);
997
998 }
999 else // Mammoth
1000 {
1001 const float vol = ourcockpit.power * (sqrtf(viewscreen->gameclass->bus->EngineThrustOutput[i]) * 0.4f + 0.6f);
1002 viewscreen->gameclass->sound->PlayEx(soundEnum, true, vol, ourcockpit.power * (1.0f + viewscreen->gameclass->bus->EngineThrustOutput[i]), pan, false, true, true);
1004 }
1005 }
1006 }
1007 }
1008
1009 // One shared bypass recording represents all engines, not whichever engine
1010 // happened to update it last. The external mixer weights their cached positions.
1011 if (!playerships[0].groundvehicle && ourcockpit.engines > 0)
1012 {
1013 float strength = 0.f, weightedPitch = 0.f;
1014 for (int engine = 0; engine < ourcockpit.engines; ++engine)
1015 {
1016 const float output = viewscreen->gameclass->bus->EngineThrustOutput[engine];
1017 const float weight = EngineAudio::Strength(output);
1018 strength += weight;
1019 weightedPitch += weight * (.2f + .8f * output);
1020 }
1022 ourcockpit.power * bypassGrowl * strength / float(ourcockpit.engines),
1023 strength > 0.f ? weightedPitch / strength : .2f, 0.f, false, true, false);
1024 }
1025
1026 if (ourcockpit.engines)
1027 zThrustAvgPercent /= static_cast<float>(ourcockpit.engines);
1028
1029 // also need to affect based on engine critical altitude, normal and expected loss of power
1030 zThrustAcceleration *= bypassMod;
1031
1032 // also need to affect based on vacuum efficiency, normal and expected loss of power
1033 zThrustAcceleration *= Lerp(1.0f, ourcockpit.engineEfficiencyAtSeaLevelScalar, staticDensity);
1034
1035 // Anti-ice, normal and expected loss of power
1037 {
1038 if (zThrustAcceleration > 0)
1039 {
1040 zThrustAcceleration -= 0.05f * ourcockpit.fwdthrustlimit * antiIceEffectiveness;
1041 if (zThrustAcceleration < 0.0f)
1042 zThrustAcceleration = 0.0f;
1043 }
1044 else
1045 {
1046 zThrustAcceleration += 0.05f * ourcockpit.revthrustlimit * antiIceEffectiveness;
1047 if (zThrustAcceleration > 0.0f)
1048 zThrustAcceleration = 0.0f;
1049 }
1050 }
1051
1052 // Compressor bleed reduces delivered thrust, not indicated engine output
1053 // or fuel demand. Apply after anti-ice, equally in forward and reverse.
1054 zThrustAcceleration *= rainAirThrustMultiplier;
1055
1056#pragma region RCS
1057
1058 if (playerships[0].docked)
1060 else if (viewscreen->gameclass->bus->AFCS.TvmOn)
1061 {
1062 viewscreen->rcsThrustRequestX -= tvmRelativeVelocity.x; // difference in xvelocity
1063 viewscreen->rcsThrustRequestY -= tvmRelativeVelocity.y; // difference in yvelocity
1064 if (!ourcockpit.engines) // for EVA Suit MMU we don't have mains
1065 viewscreen->rcsThrustRequestZ -= tvmRelativeVelocity.z; // difference in zvelocity
1066 }
1067 else if (viewscreen->gameclass->bus->AFCS.DorOn)
1068 {
1069 if(entryBus.guidance.entryControl||entryBus.guidance.ascentControl||entryBus.guidance.poweredRendezvous) {
1070 // Convert requested physical acceleration back to the existing
1071 // gross-weight RCS command. Its filter, power, limits and fuel remain.
1072 const float scale=totalWeightLbs/(std::max)(1.f,ourcockpit.maxGrossLbs)/
1073 (std::max)(.001f,float(wear.thrust*ourcockpit.power));
1074 viewscreen->rcsThrustRequestX=continuousEntry?entryAcceleration.x*scale:0;
1075 viewscreen->rcsThrustRequestY=continuousEntry?entryAcceleration.y*scale:0;
1077 } else {
1078 const auto trim=Orbital::OrbitalRcsRequest(
1080 zThrustAcceleration,ourcockpit.engines>0);
1081 viewscreen->rcsThrustRequestX += float(trim.x);
1082 viewscreen->rcsThrustRequestY += float(trim.y);
1083 viewscreen->rcsThrustRequestZ += float(trim.z);
1084 }
1085 }
1086
1087 static float rcsThrustOutputX = 0.0f, rcsThrustOutputY = 0.0f, rcsThrustOutputZ = 0.0f;
1088 rcsThrustOutputX += (viewscreen->rcsThrustRequestX - rcsThrustOutputX) * fElapsedTime;
1089 rcsThrustOutputY += (viewscreen->rcsThrustRequestY - rcsThrustOutputY) * fElapsedTime;
1090 rcsThrustOutputZ += (viewscreen->rcsThrustRequestZ - rcsThrustOutputZ) * fElapsedTime;
1091 viewscreen->rcsThrustOutputX = rcsThrustOutputX;
1092 viewscreen->rcsThrustOutputY = rcsThrustOutputY;
1093 viewscreen->rcsThrustOutputZ = rcsThrustOutputZ;
1094
1095 if (ourcockpit.power < 1.0f) // this is a good save-all, loses containment or some BS like that
1096 {
1100 }
1101
1102 // Result of all thrust inputs
1115
1116
1117 // how much we are actually thrusting ... will be adjusted by weight and friction an everything else
1120 playerships[0].tz = Clamp(viewscreen->rcsThrustOutputZ / ourcockpit.fwdthrustlimit + zThrustAvgPercent, -1, 1);
1121 // not sure if we should be doing this as 0-100% thrust or in meters per second
1122 // doppler sound should be based on weight of vehicle times thrust output over max?
1123
1124
1125 // adjust for engine critical altitude
1126 //viewscreen->rcsThrustOutputX *= bypassMod;
1127 //viewscreen->rcsThrustOutputY *= bypassMod;
1128 //viewscreen->rcsThrustOutputZ *= bypassMod;
1129
1130#pragma endregion
1131
1132 // Ground effect
1133 const float gearOrSuspensionHeightKm = playerships[0].groundvehicle
1136 const float wingElevationM = (f_AGL - citystuff.elevation + ourcockpit.strutsrettoCGKm + gearOrSuspensionHeightKm) * 1000.0f + ourcockpit.wingElevationM; // km to m
1137 float groundEffect = 1.0f; // so we multiply lift by this number... so we want it to never go below 1.0f
1138 if (ourcockpit.wingspanM > 0.0f && wingElevationM < ourcockpit.wingspanM && wingElevationM >= 0.0f)
1139 {
1140 // 1.0f-1.5f times (0-50% increase) when one wingspan to 0.0f AGL
1141 groundEffect = 1.5f - powf(wingElevationM / ourcockpit.wingspanM, 2.0f) * 0.5f;
1142 // the blast from the bottom increases too when there is a surface to resist it
1143 viewscreen->rcsThrustOutputY *= groundEffect;
1144 }
1145
1146
1147 logger->AddToCallStack("PropulsionForGroundVehicle");
1148
1149#pragma region Automatic Transmission
1150
1151 if (playerships[0].groundvehicle)
1152 {
1153 float signedSpeedKph = viewscreen->gameclass->bus->SpeedometerKPH;
1154
1155 if (playerships[0].reference == REF_ONGROUND)
1156 {
1158 signedSpeedKph = result.z * 3600.0f; // signed
1159 }
1160
1161 // Kill tiny near-zero jitter that can make the wheel tach flip sign at rest.
1162 if (fabsf(signedSpeedKph) < 0.25f)
1163 signedSpeedKph = 0.0f;
1164
1165 auto GetRatio = [&]() -> float
1166 {
1167 if (ourcockpit.gearshift == -1)
1168 return ourcockpit.ratios[0];
1169
1170 if (ourcockpit.gearshift > 0)
1172
1173 return FLT_MAX;
1174 };
1175
1176 auto Lerp = [](float a, float b, float t) -> float
1177 {
1178 return a + (b - a) * t;
1179 };
1180
1181 auto Curve = [&](float x, float x0, float y0, float x1, float y1) -> float
1182 {
1183 float t = 0.0f;
1184 if (x1 != x0)
1185 t = Clamp((x - x0) / (x1 - x0), 0.0f, 1.0f);
1186
1187 return Lerp(y0, y1, t);
1188 };
1189
1190 auto EngineTorqueCurve = [&](float tachNorm) -> float
1191 {
1192 // Generic old road-engine torque curve.
1193 // tachNorm is normalized to redline, where 1.0 is redline.
1194 // Returns multiplier relative to peak torque.
1195 const float idleNorm = ourcockpit.idleRPM / ourcockpit.redlineRPM;
1196
1197 float t = Clamp(tachNorm, idleNorm, 1.0f);
1198
1199 if (t < 0.25f)
1200 return Curve(t, idleNorm, 0.45f, 0.25f, 0.78f);
1201
1202 if (t < 0.50f)
1203 return Curve(t, 0.25f, 0.78f, 0.50f, 1.00f);
1204
1205 if (t < 0.75f)
1206 return Curve(t, 0.50f, 1.00f, 0.75f, 0.92f);
1207
1208 return Curve(t, 0.75f, 0.92f, 1.00f, 0.70f);
1209 };
1210
1211 float ratio = GetRatio();
1212 // Ground-vehicle fwdthrustlimit values are tuned/commented as C2 horsepower
1213 // equivalents. Use the C2 calibration to derive engine power, then convert
1214 // power through the selected gear and tire radius into tractive force.
1215 const float groundVehicleReferenceFwdLimit = 0.0085f; // C2/C2A-era 100 hp baseline
1216 const float enginePowerHp = RiseMath::Max(ourcockpit.fwdthrustlimit, 0.0f) * (100.0f / groundVehicleReferenceFwdLimit);
1217 const float enginePowerW = enginePowerHp * 745.699872f * wear.thrust;
1218 const float maxGrossMassKg = RiseMath::Max(ourcockpit.maxGrossLbs / Kg2Lbs, 1.0f);
1219 const float driveLiveWeightScale = Clamp(ourcockpit.maxGrossLbs / RiseMath::Max(totalWeightLbs, 1.0f), 0.0f, 4.0f);
1220 float launchTractiveEffortG = 0.0f;
1221
1222 const float idleNorm = ourcockpit.idleRPM / ourcockpit.redlineRPM;
1223 const float rawPedal = viewscreen->gameclass->bus->EngineThrustLever[0];
1224
1225 float desiredTach = Clamp(rawPedal, idleNorm, 1.0f);
1226 desiredTach *= ourcockpit.power;
1227
1228 const float idleTach = idleNorm * ourcockpit.power;
1229 const float groundVehicleLeverIdle = playerships[0].groundvehicle ? 0.10f * ourcockpit.power : 0.0f;
1230 const float zeroDemandTach = RiseMath::Max(idleTach, groundVehicleLeverIdle);
1231
1232 float throttleDemand = 0.0f;
1233 float speedLimiterScale = 1.0f;
1234 if (ourcockpit.power > 0.0f)
1235 {
1236 // Keyboard/controller ground vehicles use 0.10 as the at-rest lever floor.
1237 // Treat that floor as idle so direct-drive profiles do not coast with 10% drive demand.
1238 throttleDemand = Clamp((desiredTach - zeroDemandTach) / RiseMath::Max(1.0f - zeroDemandTach, 0.001f), 0.0f, 1.0f);
1239 }
1240
1241 float speedLimiterMotionKph = 0.0f;
1242 if (ratio != FLT_MAX && (ourcockpit.gearshift > 0 || ourcockpit.gearshift == -1))
1243 {
1244 const float limiterDriveDirection = (ratio >= 0.0f) ? 1.0f : -1.0f;
1245 speedLimiterMotionKph = signedSpeedKph * limiterDriveDirection;
1246 }
1247
1248 if (ourcockpit.speedLimiterKph > 0.0f &&
1249 speedLimiterMotionKph > ourcockpit.speedLimiterKph * 0.95f)
1250 {
1251 const float buffer = RiseMath::Max(ourcockpit.speedLimiterKph * 1.05f - speedLimiterMotionKph, 0.0f);
1252 const float limiterScale = buffer / (ourcockpit.speedLimiterKph * 0.05f);
1253 speedLimiterScale = Clamp(limiterScale, 0.0f, 1.0f);
1254
1255 desiredTach *= speedLimiterScale;
1256 throttleDemand *= speedLimiterScale;
1257 }
1258
1259 // Fuel
1260 const float oldFuel = fuel;
1263
1264 if (oldFuel > ourcockpit.fuelmax * 0.5f && fuel <= ourcockpit.fuelmax * 0.25f)
1266
1269
1271
1272 if (fuel < 0.0f)
1273 desiredTach = fuel = 0.0f;
1274
1276
1277 // clutchhold is seconds remaining in the shift/clutch transition.
1278 // ChangeGear() should set clutchhold = clutchtime.
1280
1281 const float shiftBlend =
1283
1284 const bool canAutoShift = ourcockpit.clutchhold <= 0.0f;
1285
1286 float wheelTach = 0.0f;
1287 if (ratio != FLT_MAX)
1288 wheelTach = signedSpeedKph / ratio / 77.7f;
1289
1290 wheelTach = Clamp(wheelTach, -1.0f, 1.0f);
1291
1292 auto ComputeEngineTach = [&](float wheel, float desired, float shiftSlipBlend) -> float
1293 {
1294 // At low road speed, an automatic needs torque-converter slip.
1295 // Without this, the engine is locked to a stopped wheel and produces no launch torque.
1296 const float absWheel = fabsf(wheel);
1297
1298 float converterSlip = 0.0f;
1299 if (throttleDemand > 0.0f && desired > idleTach)
1300 {
1301 const float stallSlip = 0.65f;
1302 const float speedSlip = Clamp(1.0f - absWheel / RiseMath::Max(desired, idleTach + 0.001f), 0.0f, 1.0f);
1303 converterSlip = stallSlip * speedSlip * throttleDemand;
1304 }
1305
1306 const float slipBlend = RiseMath::Max(shiftSlipBlend, converterSlip);
1307
1308 float tach = wheel + (desired - wheel) * slipBlend;
1309
1310 // Engine tach is not allowed to mathematically stall while the engine has power.
1311 tach = RiseMath::Max(tach, idleTach);
1312
1313 return Clamp(tach, 0.0f, 1.2f);
1314 };
1315
1316 float engineTach = desiredTach;
1317 bool shifted = false;
1318
1319 if (ratio != FLT_MAX && (ourcockpit.gearshift > 0 || ourcockpit.gearshift == -1))
1320 {
1321 engineTach = ComputeEngineTach(wheelTach, desiredTach, shiftBlend);
1322
1323 if (ourcockpit.gearshift > 0)
1324 {
1325 float downshiftWheelTach = 0.30f;
1326 float kickdownWheelTach = 0.44f;
1327
1328 if (ourcockpit.gearshift == 3)
1329 {
1330 downshiftWheelTach = 0.36f;
1331 kickdownWheelTach = 0.45f;
1332 }
1333 else if (ourcockpit.gearshift == 2)
1334 {
1335 downshiftWheelTach = 0.30f;
1336 kickdownWheelTach = 0.44f;
1337 }
1338
1339 const float upshiftEngineTach = 0.82f;
1340 const float minWheelTachForUpshift = 0.48f;
1341
1342 if (canAutoShift &&
1343 engineTach > upshiftEngineTach &&
1344 wheelTach > minWheelTachForUpshift &&
1346 {
1348 shifted = true;
1349 }
1350 else if (canAutoShift && ourcockpit.gearshift > 1)
1351 {
1352 const bool coastingDownshift =
1353 wheelTach < downshiftWheelTach;
1354
1355 const bool kickdownDownshift =
1356 throttleDemand > 0.55f && wheelTach < kickdownWheelTach;
1357
1358 if (coastingDownshift || kickdownDownshift)
1359 {
1361 shifted = true;
1362 }
1363 }
1364 }
1365 }
1366
1367 if (shifted)
1368 {
1369 ratio = GetRatio();
1370
1371 if (ratio != FLT_MAX)
1372 wheelTach = signedSpeedKph / ratio / 77.7f;
1373 else
1374 wheelTach = 0.0f;
1375
1376 wheelTach = Clamp(wheelTach, -1.0f, 1.0f);
1377
1378 // ChangeGear() should have reset clutchhold to clutchtime.
1379 // Recompute shiftBlend locally for the new gear.
1380 const float newShiftBlend =
1382
1383 engineTach = ComputeEngineTach(wheelTach, desiredTach, newShiftBlend);
1384 }
1385
1386 float slip = 0.0f;
1387 float torqueMultiplier = 0.0f;
1388 float torqueAcceleration = 0.0f;
1389 float powerAcceleration = 0.0f;
1390 float engineAcceleration = 0.0f;
1391 float netAcceleration = 0.0f;
1392 float powerReferenceKph = 0.0f;
1393 float torqueConverterRatioLog = 1.0f;
1394 float driveDemand = throttleDemand;
1395 float gearEngagement = 0.0f;
1396 float idleCreepDemand = 0.0f;
1397 float antiRollbackDemand = 0.0f;
1398
1399 if (ratio != FLT_MAX && (ourcockpit.gearshift > 0 || ourcockpit.gearshift == -1))
1400 {
1401 slip = engineTach - wheelTach;
1402
1403 const float absRatio = RiseMath::Max(fabsf(ratio), 0.001f);
1404 const float driveDirection = (ratio >= 0.0f) ? 1.0f : -1.0f;
1405 const float currentShiftBlend =
1407
1408 torqueMultiplier = EngineTorqueCurve(engineTach);
1409
1410 const bool atGroundVehicleIdleLever = playerships[0].groundvehicle && rawPedal <= 0.101f;
1411 gearEngagement = 1.0f - currentShiftBlend;
1412 const float idleCreepAtRestDemand = ourcockpit.fwdgears > 1 ? 0.12f : 0.08f;
1413 idleCreepDemand = atGroundVehicleIdleLever ?
1414 gearEngagement * Curve(fabsf(signedSpeedKph), 0.0f, idleCreepAtRestDemand, 8.0f, 0.0f) :
1415 0.0f;
1416
1417 // Tire static friction is the traction budget, not a neutral-hold force.
1418 // Use a gentle torque-converter hold when an idling ground vehicle rolls
1419 // opposite the selected gear; this avoids tuning top speed with thrust.
1420 const float selectedMotionKph = signedSpeedKph * driveDirection;
1421 if (atGroundVehicleIdleLever && selectedMotionKph < -0.25f)
1422 antiRollbackDemand = gearEngagement * Curve(-selectedMotionKph, 0.25f, 0.10f, 4.0f, 0.55f);
1423
1424 driveDemand = RiseMath::Max(throttleDemand, RiseMath::Max(idleCreepDemand, antiRollbackDemand));
1425
1426 // Power-limited drive acceleration.
1427 // Real engines cannot maintain the same wheel force as speed rises.
1428 // Since power = force * speed, force and acceleration fall roughly as 1 / speed.
1429 //
1430 // Derive the reference speed from current gear redline speed and a generic
1431 // peak-power RPM around 80 percent of redline. This avoids a per-profile
1432 // magic powerReferenceKph value while still adapting per gear/vehicle.
1433 const float peakPowerTachNorm = 0.80f;
1434 const float gearRedlineKph = RiseMath::Max(absRatio * 77.7f, 1.0f);
1435 powerReferenceKph = RiseMath::Max(gearRedlineKph * peakPowerTachNorm, 10.0f);
1436
1437 const float redlineRadPerSec = RiseMath::Max(ourcockpit.redlineRPM, 1.0f) * RiseMath::Pi / 30.0f;
1438 const float peakPowerRadPerSec = RiseMath::Max(redlineRadPerSec * peakPowerTachNorm, 1.0f);
1439 const float peakEngineTorqueNm = enginePowerW / peakPowerRadPerSec;
1440 const float wheelRadiusM = RiseMath::Max(ourcockpit.tireRadiusKm * 1000.0f, 0.05f);
1441 const float gearRedlineMps = RiseMath::Max(gearRedlineKph / 3.6f, 0.5f);
1442 const float gearReduction = RiseMath::Max(redlineRadPerSec * wheelRadiusM / gearRedlineMps, 0.1f);
1443 const float converterSlipRatio =
1444 Clamp(fabsf(slip) / RiseMath::Max(RiseMath::Max(engineTach, idleTach), 0.001f), 0.0f, 1.0f);
1445
1446 // Single-speed ground drives represent torque-converter, hydrostatic, or electric
1447 // final drives. They need more stall multiplication than a multi-gear car automatic,
1448 // while still blending back to direct drive as the wheel speed catches the engine.
1449 const float stallTorqueRatio = (ourcockpit.fwdgears <= 1) ? 3.5f : 2.2f;
1450 const float torqueConverterRatio = 1.0f + (stallTorqueRatio - 1.0f) * converterSlipRatio;
1451 const float drivelineEfficiency = 0.85f;
1452
1453 torqueConverterRatioLog = torqueConverterRatio;
1454
1455 const float maxTorqueLimitedForceN =
1456 torqueMultiplier *
1457 peakEngineTorqueNm *
1458 gearReduction *
1459 torqueConverterRatio *
1460 drivelineEfficiency /
1461 wheelRadiusM;
1462
1463 // Torque-limited drive acceleration.
1464 // This dominates at launch and lower road speeds.
1465 torqueAcceleration =
1466 driveDirection *
1467 driveDemand *
1468 maxTorqueLimitedForceN /
1469 maxGrossMassKg *
1470 0.001f;
1471
1472 launchTractiveEffortG = fabsf(torqueAcceleration) * oneOvergForceKmssC;
1473
1474 const float speedKphAbs = fabsf(signedSpeedKph);
1475 const float speedMps = RiseMath::Max(speedKphAbs / 3.6f, 0.5f);
1476 const float powerLimitedForceN =
1477 driveDemand *
1478 torqueMultiplier *
1479 enginePowerW *
1480 drivelineEfficiency /
1481 speedMps;
1482
1483 powerAcceleration =
1484 driveDirection *
1485 powerLimitedForceN /
1486 maxGrossMassKg *
1487 0.001f;
1488
1489 // Real drivetrain output is limited by both torque and horsepower.
1490 // Use the smaller magnitude while preserving direction.
1491 engineAcceleration = torqueAcceleration;
1492 if (fabsf(powerAcceleration) < fabsf(engineAcceleration))
1493 engineAcceleration = powerAcceleration;
1494
1495 // Mild engine braking / converter drag when the driver lifts.
1496 // This must oppose the vehicle's current motion. Using driveDirection here
1497 // accelerates a vehicle that is rolling opposite the selected gear.
1498 const float engineBrakeStrength = 0.12f;
1499 const float engineBrakeDemand = 1.0f - driveDemand;
1500 const float wheelSpinForBrake = Clamp(fabsf(wheelTach) - idleTach, 0.0f, 1.0f);
1501
1502 float motionDirection = driveDirection;
1503 if (signedSpeedKph > 0.25f)
1504 motionDirection = 1.0f;
1505 else if (signedSpeedKph < -0.25f)
1506 motionDirection = -1.0f;
1507 else if (wheelTach > 0.001f)
1508 motionDirection = 1.0f;
1509 else if (wheelTach < -0.001f)
1510 motionDirection = -1.0f;
1511
1512 const float engineBrakeAcceleration =
1513 -motionDirection *
1514 engineBrakeDemand *
1515 wheelSpinForBrake *
1516 engineBrakeStrength *
1517 maxTorqueLimitedForceN /
1518 maxGrossMassKg *
1519 0.001f;
1520
1521 engineAcceleration += engineBrakeAcceleration;
1522
1523 // Tire traction limit. Above this, the drive wheels would spin or slide.
1524 const float tireMu = 0.80f;
1525 const float tractionLimit = tireMu * gravityKmssC;
1526
1527 netAcceleration = Clamp(engineAcceleration, -tractionLimit, tractionLimit);
1528 }
1529
1530 ourcockpit.tach = Clamp(engineTach, 0.0f, 1.2f);
1531 float engineSoundTach = ourcockpit.tach;
1532
1533 if (playerships[0].groundvehicle && speedLimiterScale < 1.0f)
1534 engineSoundTach = RiseMath::Min(engineSoundTach, RiseMath::Max(desiredTach, zeroDemandTach));
1535
1536 if (playerships[0].reference != REF_ONGROUND &&
1537 ratio != FLT_MAX &&
1539 {
1540 signedSpeedKph = engineTach * fabsf(ratio) * 77.7f;
1541 }
1542
1543 viewscreen->gameclass->bus->SpeedometerKPH = fabsf(signedSpeedKph);
1544
1545 if (ourcockpit.power > 0.25f)
1546 {
1547 if (playerships[0].type != VehicleType::T120 && playerships[0].type != VehicleType::T121)
1548 viewscreen->gameclass->sound->PlayEx(SOUND_COCKPITENGINECENTER, true, (0.2f + engineSoundTach * 0.8f), 0.2f + 2.0f * engineSoundTach, 0, false, true, true);
1549 else
1550 viewscreen->gameclass->sound->PlayEx(SOUND_COCKPITENGINECENTER, true, (0.3f + engineSoundTach * 0.7f), 0.2f + 2.0f * engineSoundTach, 0, false, true, true);
1551 }
1552 else
1553 {
1554 if (playerships[0].type != VehicleType::T120 && playerships[0].type != VehicleType::T121)
1555 viewscreen->gameclass->sound->PlayEx(SOUND_COCKPITENGINECENTER, true, (0.2f * ourcockpit.power / 0.25f), 0.2f * ourcockpit.power / 0.25f, 0, false, true, true);
1556 else
1557 viewscreen->gameclass->sound->PlayEx(SOUND_COCKPITENGINECENTER, true, (0.3f * ourcockpit.power / 0.25f), 0.2f * ourcockpit.power / 0.25f, 0, false, true, true);
1558 }
1559
1560 actual.x = 0.0f;
1561 actual.y = 0.0f;
1562
1563 if (playerships[0].groundvehicle &&
1564 (playerships[0].reference != REF_ONGROUND ||
1565 fabsf(levelerroll) > 0.9f ||
1566 levelerpitch > 0.001f))
1567 actual.z = 0.0f;
1568 else
1569 actual.z = netAcceleration;
1570
1571#ifdef ODB2
1573 {
1574 static OptionalDiagnosticFile odb2("odb2.log");
1575 odb2.Printf(
1576 "%7.3f (VT %u CT %i VID %u WT %.0f WF %.2f HP %.0f TEG %.3f LWS %.4f)(spd %5.1f kph)(gear %+i/%4.2f)"
1577 "(pedal %.2f target %.2f lim %.2f snd %.2f idle %.2f demand %.2f drive %.2f creep %.2f hold %.2f engage %.2f clutch %.2f shift %.2f)"
1578 "(engine %2.2f/%4.0f RPM)"
1579 "(wheel %2.2f/%4.0f RPM)"
1580 "(slip %+.4f tq %.2f TCR %.2f tqAcc %+.4f powRef %.1f powAcc %+.4f engAcc %+.4f acc %+.4f actualZ %+.4f drvZ %+.4f)"
1581 "(ref %i roll %.4f pitch %.4f)\n",
1583 static_cast<unsigned int>(playerships[0].type),
1584 static_cast<int>(ourcockpit.texturelib),
1585 static_cast<unsigned int>(playerships[0].vehicleId),
1587 weightFactor,
1588 enginePowerHp,
1589 launchTractiveEffortG,
1590 driveLiveWeightScale,
1593 ratio,
1594 rawPedal,
1595 desiredTach,
1596 speedLimiterScale,
1597 engineSoundTach,
1598 zeroDemandTach,
1599 throttleDemand,
1600 driveDemand,
1601 idleCreepDemand,
1602 antiRollbackDemand,
1603 gearEngagement,
1608 wheelTach,
1609 wheelTach * ourcockpit.redlineRPM,
1610 slip,
1611 torqueMultiplier,
1612 torqueConverterRatioLog,
1613 torqueAcceleration,
1614 powerReferenceKph,
1615 powerAcceleration,
1616 engineAcceleration,
1617 netAcceleration,
1618 actual.z,
1619 actual.z * driveLiveWeightScale,
1622 levelerpitch);
1623
1624 }
1625#endif
1626
1627 }
1628 else
1629 {
1632 actual.z = (viewscreen->rcsThrustOutputZ + zThrustAcceleration) * wear.thrust;
1633 }
1634
1635#pragma endregion
1636
1637 logger->AddToCallStack("EffectivenessOfThrust");
1638
1639
1640 result.x = actual.x * fElapsedTime; result.y = actual.y * fElapsedTime; result.z = actual.z * fElapsedTime;
1641
1642#pragma region debug
1643 if (result.x > 100.0f || result.x < -100.0f || _isnan(result.x) || isinf(result.x) ||
1644 result.y > 100.0f || result.y < -100.0f || _isnan(result.y) || isinf(result.y) ||
1645 result.z > 100.0f || result.z < -100.0f || _isnan(result.z) || isinf(result.z))
1646 {
1647 sprintf_s(msg, sizeof(msg), "\tET: %f", fElapsedTime);
1649 sprintf_s(msg, sizeof(msg), "\tactual I: %f", actual.x);
1651 sprintf_s(msg, sizeof(msg), "\tactual J: %f", actual.y);
1653 sprintf_s(msg, sizeof(msg), "\tactual K: %f", actual.z);
1655 sprintf_s(msg, sizeof(msg), "\tresult I: %f", result.x);
1657 sprintf_s(msg, sizeof(msg), "\tresult J: %f", result.y);
1659 sprintf_s(msg, sizeof(msg), "\tresult K: %f", result.z);
1661 sprintf_s(msg, sizeof(msg), "\tgndvehicle: %u", playerships[0].groundvehicle);
1663 sprintf_s(msg, sizeof(msg), "\trcsThrustOutputZ: %f", viewscreen->rcsThrustOutputZ);
1665 sprintf_s(msg, sizeof(msg), "\tzThrustAcceleration: %f", zThrustAcceleration);
1667 sprintf_s(msg, sizeof(msg), "Trapped a violation after xy thrust spoolup...");
1669 }
1670#pragma endregion
1671
1672 RiseMath::Vec3Scale(&result, &result, ourcockpit.maxGrossLbs / totalWeightLbs); // bias the BOW so at gross this is 0.625
1673
1674#pragma region debug
1675 if (result.x > 100.0f || result.x < -100.0f || _isnan(result.x) || isinf(result.x) ||
1676 result.y > 100.0f || result.y < -100.0f || _isnan(result.y) || isinf(result.y) ||
1677 result.z > 100.0f || result.z < -100.0f || _isnan(result.z) || isinf(result.z))
1678 {
1679 sprintf_s(msg, sizeof(msg), "\tET: %f", fElapsedTime);
1681 sprintf_s(msg, sizeof(msg), "\tourcockpit.maxgross: %f", ourcockpit.maxGrossLbs);
1683 sprintf_s(msg, sizeof(msg), "\tourcockpit.emptyweight: %f", ourcockpit.emptyWeightLbs);
1685 sprintf_s(msg, sizeof(msg), "\tfuel: %f", fuel);
1687 sprintf_s(msg, sizeof(msg), "\tpayload: %f", payload);
1689 sprintf_s(msg, sizeof(msg), "\tweightC: %f", totalWeightLbs);
1691 sprintf_s(msg, sizeof(msg), "\tresult I: %f", result.x);
1693 sprintf_s(msg, sizeof(msg), "\tresult J: %f", result.y);
1695 sprintf_s(msg, sizeof(msg), "\tresult K: %f", result.z);
1697 sprintf_s(msg, sizeof(msg), "Trapped a violation after weight adjustment spoolup...");
1699 }
1700#pragma endregion
1701
1702 if (fElapsedTime != 0)
1703 {
1704 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f thrust", result.x * oneOvergForceKmssC / fElapsedTime, result.y * oneOvergForceKmssC / fElapsedTime, result.z * oneOvergForceKmssC / fElapsedTime);
1705 viewscreen->sofTracking.emplace_back(msg);
1706 }
1707
1708 // verified result is scaled to fElapsedTime
1709 viewscreen->sumofforces += result; // thrust
1710 {
1711 const auto& orbitBus=*viewscreen->gameclass->bus;
1712 auto vector=[](const RiseMath::Vector3& v) {return Orbital::Vec{v.x,v.y,v.z};};
1713 orbitActuation.sequence++;
1714 orbitActuation.programTime=orbitBus.ProgramTime;
1715 orbitActuation.guidanceTime=orbitBus.orbit.sourceTime;
1716 orbitActuation.dt=fElapsedTime;orbitActuation.dor=orbitBus.AFCS.DorOn;
1717 orbitActuation.phase=orbitBus.orbit.guidance.phase;
1718 orbitActuation.thrust=orbitBus.orbit.guidance.thrust;
1719 orbitActuation.valid=true;
1720 const double weightScale=ourcockpit.maxGrossLbs/totalWeightLbs;
1721 orbitActuation.mainBodyKms2={0,0,zThrustAcceleration*wear.thrust*weightScale};
1722 const Orbital::Vec delivered=fElapsedTime>0?vector(result)/fElapsedTime:Orbital::Vec{};
1723 orbitActuation.rcsBodyKms2=delivered-orbitActuation.mainBodyKms2;
1724 RiseMath::Vector3 world;
1725 RiseMath::Vec3TransformNormal(&world,&result,&playerships[0].matrixWorld);
1726 orbitActuation.thrustWorldKms2=fElapsedTime>0?vector(world)/fElapsedTime:Orbital::Vec{};
1727 orbitActuation.velocityErrorBodyKms=vector(dorRelativeVelocity);
1730 static_assert(MAX_ENGINES==3,"Update Orbit actuation capture for the engine layout");
1731 for(int i=0;i<MAX_ENGINES;++i) {
1732 orbitActuation.lever[i]=orbitBus.EngineThrustLever[i];
1733 orbitActuation.output[i]=orbitBus.EngineThrustOutput[i];
1734 orbitActuation.reverse[i]=ThrustReverserOutput[i];
1735 }
1736 orbitActuation.Accumulate(fElapsedTime,orbitActuation.mainBodyKms2,orbitActuation.rcsBodyKms2);
1737 }
1738
1739#pragma region debug
1740 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
1741 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
1742 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
1743 {
1744 sprintf_s(msg, sizeof(msg), "\tET: %f", fElapsedTime);
1746 sprintf_s(msg, sizeof(msg), "\tsumofforces I: %f", viewscreen->sumofforces.x);
1748 sprintf_s(msg, sizeof(msg), "\tsumofforces J: %f", viewscreen->sumofforces.y);
1750 sprintf_s(msg, sizeof(msg), "\tsumofforces K: %f", viewscreen->sumofforces.z);
1752 sprintf_s(msg, sizeof(msg), "\tresult I: %f", result.x);
1754 sprintf_s(msg, sizeof(msg), "\tresult J: %f", result.y);
1756 sprintf_s(msg, sizeof(msg), "\tresult K: %f", result.z);
1759 sprintf_s(msg, sizeof(msg), "Trapped a violation after thrust adjusted...");
1761 }
1762#pragma endregion
1763
1764
1765
1766 const auto beforeAerodynamics = viewscreen->sumofforces;
1767 orbitActuation.aeroSampleTime = -1;
1768 logger->AddToCallStack("AtmosphericPhysics");
1769
1770#pragma region Atmospheric Physics
1771 // Atmospheric functions ************************************************************************
1772 // YAW DAMPER EMPLOYED
1773 // Only question right now are movement of the Cp
1774 // Also whether or not fuselage should block lift when in a slip/skid situation
1775 // AOA increases by atanf( (2.0f*sinf(RiseMath::Pi-roll))/(1.0f-2.0f*cosf(RiseMath::Pi-roll)) ) w/ deflect
1776
1777 if (playerships[0].reference != REF_INANOTHER)
1778 {
1779 if (playerships[0].mslKm != -1.0f) // Hold off until altitude is calculated
1780 {
1781 float S, tempaoa = 0.0f;
1782 float tempDragTail = 0.0f;
1783
1784
1785 // wind sensors
1786 static float fullsec = 0.0f;
1787 fullsec += fElapsedTime;
1788 if (fullsec > 1.0f)
1789 {
1792 fullsec = 0.0f;
1793 }
1794
1795
1796 // air density sensor (static pressure sensor)
1798
1799 // Solve for forward dynamic pressure
1803
1804
1805 // this is the pitot tube impact pressure (or qc) adjusted for the sea level pressure
1806 // just the forward part, used for St. Elmo's, possibly fan cooled engines, and IAS bus value below
1807 const float qcOverRho0 = 0.5f * dynamicDensityScalar * powf(RiseMath::Max(-relativeWindTrueKms.z, 0), 2.0f);
1808
1809 // @ref https://aerotoolbox.com/airspeed-conversions/
1810 ias = sqrtf(2 * qcOverRho0);
1811
1812 // ias sensor, cannot sense backwards (ram air sensor)
1813 if (ias < 0.020f)
1815 else
1817
1818 const float tas = RiseMath::Vec3Length(&relativeWindTrueKms); // any direction for mach and heating? and ice ... km/s
1819
1820 // @todo this one is for thermodynamics ... will get split into qx and qy since we already have qz above
1821 const float qxyz_lbsPerSqFt = dynamicDensityScalar * rhoOver2SlugsCuFt2 * powf(tas * feetPerKilometerC, 2.0f);
1822
1823 // oat sensor (static air temperature sensor)
1825 // tas calculation is based on indicated airspeed and density, that is all we have
1827
1828 const float outsideAirTemperatureKelvin = ZeroCelsiusToKelvin + viewscreen->ptrWeather->GetTemperatureCelsius();
1829 viewscreen->gameclass->bus->OutsideAirTemperatureKelvin = outsideAirTemperatureKelvin;
1830
1831 // angular velocity sensor?
1833
1834
1835 const float molarMass = 0.9914103f + 29.5230397f / (1.0f + powf(RiseMath::Max(playerships[0].mslKm, 0) / 378.4386f, 1.425581f)); // 29 at sea level, 18 at 300km
1836 const float molarMassMod = 29.0f / molarMass; // 1 at sea level, 1.61 at 300km
1837 speedOfSoundKms = sqrtf(adiabaticIndex * gasConstantm2s2K * outsideAirTemperatureKelvin * molarMassMod) * 0.001f;
1838 if (_isnan(speedOfSoundKms) || isinf(speedOfSoundKms))
1839 {
1840 sprintf_s(msg, sizeof msg, "speedOfSoundKms was NAN, OAT %.3f MMM %.3f", outsideAirTemperatureKelvin, molarMassMod);
1843 }
1845
1846 mach = tas / speedOfSoundKms; // real mach the airframe sees
1848
1849
1850 tatCelsius = viewscreen->ptrWeather->GetTemperatureCelsius() + outsideAirTemperatureKelvin * (adiabaticIndex - 1.0f) * 0.5f * mach * mach;
1851 // tat calculation
1854
1855
1856
1857#pragma region Thermodynamics
1859 const float airframeTempKelvin = ZeroCelsiusToKelvin + airframeTempCelsius;
1860 // result is in Watts, convert to Celsius heat units (IT) per second * 0.000526565066841
1864 // we use SAT because it is a relatively small amount of air that is increased temp compared to the surrounding environment
1865 // tried using heat coefficient but it is not 0-1 ... so it exploded the server! .001 for emissivity seems right for some reason
1866 float radiationRate = 0.001f * 0.000000056703f * (powf(outsideAirTemperatureKelvin, 4.0f) - powf(airframeTempKelvin, 4.0f)) * (ourcockpit.i12WingAreaOneSideSqFt * 4.0f * 0.092903f) * 0.000526565066841f;
1867 // tried modulating outsideAirTemperatureKelvin with density but even at 300 meters it was 90% which was 30 degrees below SAT... so I put it back
1868 // now we just don't let it heat up the ship when in thermosphere
1869 if (radiationRate > 0)
1870 radiationRate = 0;
1872 convectionRate = (tatCelsius - airframeTempCelsius) * ourcockpit.f20FrontBackDragCoeff * 0.00004f * qxyz_lbsPerSqFt; // f20 is 2.56 .. doubled from 0.000018 to 0.00004 on 6/2/2019
1874 float outsideConductionRate = (tatCelsius - airframeTempCelsius) * ourcockpit.f20FrontBackDragCoeff * 0.000008f * dynamicDensityScalar;
1875 if (playerships[0].baydoor) outsideConductionRate *= 1.2f; // 0000983: Heat management
1876
1877 /*if (viewscreen->gameclass->GUI->IsAdmin)
1878 {
1879 static int tempDumpFile = -1;
1880 if (tempDumpFile == -1)
1881 _sopen_s(&tempDumpFile, "tempdata.log", _O_RDWR | _O_CREAT | _O_TRUNC | _O_TEXT | _O_SEQUENTIAL, SH_DENYWR, S_IWRITE);
1882 if (halfsec == 0.0f)
1883 {
1884 char msg1[999];
1885 sprintf_s(msg1, 999, "Alt: %.1f D: %.3f M: %.3f Q: %.3f SAT: %.1f AFT: %.1f TAT: %.1f Q*TAT: %.0f Rad/s: %.6f Cnv/s: %.6f OCnd/s: %.6f\n",
1886 playerships[0].mslKm, dynamicDensity, mach, qxyz, viewscreen->ptrWeather->GetTemperatureCelsius(), airframeTempCelsius, tatCelsius, tat_mod_qz_x, radiationRate * ourcockpit.exteriorInsulationHeatTransferCoefficient,
1887 convectionRate * ourcockpit.exteriorInsulationHeatTransferCoefficient, outsideConductionRate * ourcockpit.exteriorInsulationHeatTransferCoefficient);
1888 _write(tempDumpFile, msg1, strlen(msg1));
1889 }
1890 }*/
1891
1892 airframeTempCelsius += ourcockpit.exteriorInsulationHeatTransferCoefficient * (convectionRate + radiationRate + outsideConductionRate) * fElapsedTime;
1894 if (airframeTempCelsius > 3276.7f) airframeTempCelsius = 3276.7f; // we use short*10 for data transfer
1895
1896 // airframe temp sensor
1904 // Passive entry calibration: full air-relative vector (including wind),
1905 // not the forward-only TAS instrument or the orbital density estimate.
1906 orbitActuation.airVelocityBodyKms={-relativeWindTrueKms.x,-relativeWindTrueKms.y,-relativeWindTrueKms.z};
1907 orbitActuation.airQPa=qxyz_lbsPerSqFt*47.88025898;
1908 orbitActuation.airframeC=airframeTempCelsius;
1909 orbitActuation.airMach=mach;orbitActuation.airIasKms=ias;orbitActuation.airTatC=tatCelsius;
1910 orbitActuation.airSampleTime=viewscreen->gameclass->bus->ProgramTime;
1911
1913 {
1914 // 350 is published limit ... stay there for a minute and get rid of 120 ... getting rid of 2 per second
1915 static bool favorLeft = rand() % 2 == 0;
1916 static float leftWing = 0.0f;
1917 static float rightWing = 0.0f;
1918 leftWing += powf(airframeTempCelsius / 525.0f, 8.0f) * RandomFloat() * (favorLeft ? 4.0f : 3.0f) * fElapsedTime;
1919 rightWing += powf(airframeTempCelsius / 525.0f, 8.0f) * RandomFloat() * (favorLeft ? 3.0f : 4.0f) * fElapsedTime;
1920 if (leftWing >= 1.0f)
1921 {
1922 if (leftWing > ourcockpit.vdat.leftwing)
1923 {
1924 viewscreen->gameclass->sound->PlayEx(SOUND_ODEATH2, false, 1, 1, -1);
1926 favorLeft = rand() % 2 == 0;
1927 }
1928 else
1929 {
1930 ourcockpit.vdat.leftwing -= (char)leftWing;
1932 if (rand() % 32) viewscreen->gameclass->bus->ComponentRcsRollFail = true;
1933 if (rand() % 32) viewscreen->gameclass->bus->ComponentFcsRollFail = true;
1934 }
1935 ourcockpit.vdatChanged = true;
1936 leftWing = 0;
1937 }
1938 if (rightWing >= 1.0f)
1939 {
1940 if (rightWing > ourcockpit.vdat.rightwing)
1941 {
1942 viewscreen->gameclass->sound->PlayEx(SOUND_ODEATH2, false, 1, 1, 1);
1944 favorLeft = rand() % 2 == 0;
1945 }
1946 else
1947 {
1948 ourcockpit.vdat.rightwing -= (char)rightWing;
1950 if (rand() % 32) viewscreen->gameclass->bus->ComponentRcsRollFail = true;
1951 if (rand() % 32) viewscreen->gameclass->bus->ComponentFcsRollFail = true;
1952 }
1953 ourcockpit.vdatChanged = true;
1954 rightWing = 0;
1955 }
1956 }
1957#pragma endregion
1958
1959
1960
1961#pragma region Icing
1962 float cloudSeverity = 0.0f;
1963 if (f_ACL < 0.150f && f_BCL < 0.150f) // ACL is above upper cloud level, BCL is below cloud bases
1964 {
1965 // Icing can be most intense near the cloud tops, where the amount of liquid water is often greatest.
1967 // if we are at 0 BCL that means we are at base, BCL is -cloudThickness at top
1968 cloudSeverity = fabsf(f_BCL) / viewscreen->ptrWeather->cloudThickness; // 0-1 from bottom to top
1969 cloudSeverity *= 0.2f; // 0 to .2 which is precip of 6 (ensures minimum in clouds)
1970 // A 3D cloud column can have clear gaps below its uppermost top.
1971 // Gate only the cloud contribution by moisture at the vehicle;
1972 // preserve the existing fog/rain and thermal icing behavior.
1974 cloudSeverity *= viewscreen->ptrWeather->cloudTurbulenceBlend;
1975 }
1976 // new is vis below 400 meters it will adhere
1977 if (viewscreen->ptrWeather->GetVisibilityKm() < 0.400f)
1978 cloudSeverity = RiseMath::Max(cloudSeverity, 0.2f * (1.0f - viewscreen->ptrWeather->GetVisibilityKm() / 0.400f));
1979 // this will be 0-1 based on precip of 4 to 16
1980 float dropSeverity = RiseMath::Max((viewscreen->ptrWeather->GetPrecip() - 4.0f) / 12.0f, 0.0f); // 0-1
1981
1982 // inverse of turbulence is what dictates how cold our droplets can be
1984
1985 // 107 is from the FCOM 14-10-2
1986 // if temp is -5 we can only heat to 102, if temp is 10 we can only heat to 107 ... so it is 107-ambient ... 107 means 0 added, 106 means 1 added, -5 means
1987 const float ductTempCelsius = fabsf(zThrustAvgPercent) > 0 ? (viewscreen->gameclass->bus->AntiIce ? 107.0f * antiIceEffectiveness : 0) : 0;
1988 const float riseAvailable = RiseMath::Min(ductTempCelsius - airframeTempCelsius, 107.0f); // 107 minus 0 is 107 ... 107 minus -5 is 107 ... -5 minus -5 is 0
1989 const float leadingEdgeTempCelsius = airframeTempCelsius + RiseMath::Max(0.0f, riseAvailable);
1990
1991 // SAT is at or above waterFreezesAt and AFT is below freezing
1992 // OAT is 0 to -15 and in clouds or below 0 in rain
1994 float temperatureSeverity = 0.0f;
1995 if (leadingEdgeTempCelsius <= 0)
1996 temperatureSeverity = -leadingEdgeTempCelsius / 35.0f; // -10 is .3 .. -35 is 1
1997 const float iceIntensity = (dropSeverity + cloudSeverity) * temperatureSeverity; // temp differential, clouds, precipitation ... highest at top of clouds
1998 if (iceIntensity && playerships[0].reference != REF_INANOTHER)
1999 {
2000 if (playerships[0].reference == REF_ONGROUND)
2001 {
2002 if (holdOverTime <= 0)
2003 {
2004 const float iceAccretion = 11.0f * iceIntensity * fElapsedTime / 60.0f / 60.0f; // aka max 7 mm per hour NET (so we add 4 for sublimation)
2005 groundIceAccumulationMm += iceAccretion;
2006 }
2007 else
2008 holdOverTime -= fElapsedTime;
2009 }
2010 else
2011 {
2012 // 25 NET ... so we add 4 for sublimation
2013 const float iceAccretion = tas / 16.0f * fElapsedTime * 29.0f * iceIntensity; // aka 25 mm in 16 km ... should be a max of 7 inches or 177 mm per hour
2015 viewscreen->gameclass->bus->IceDetectorMm += iceAccretion;
2016 airIceAccumulationMm += iceAccretion;
2017 }
2018 }
2019 // *** now sublimate, melt, and de-ice and cycle probe!!
2020 // melt is based on AFT ... sublimate is NOT speed based... see Server.NET for ChatGPT comments
2022 // pressureFactor is a 35% reduction if you double the atmospheric pressure
2023 // so at 1atm it is 1 (-0)... at 2atm it is -.35 ... at .5atm it is +.35
2024 const float pressureFactor = 0.8166667f - 1.05f * atmospheres + 0.2333333f * atmospheres * atmospheres;
2025 const float sublimation = RiseMath::Max(0, (1.0f + pressureFactor) * (viewscreen->ptrWeather->GetTemperatureCelsius() / 10.0f * 3.0f + 4.0f) / 3600.0f * fElapsedTime);
2026 viewscreen->gameclass->bus->IceDetectorMm -= sublimation;
2027 airIceAccumulationMm -= sublimation;
2028 groundIceAccumulationMm -= sublimation;
2029 // icing systems only work up to heavy icing which is .72 inches (18.288 mm) per 16 km at 230 knots
2030 // 70 degrees based on pitot heat temperature (electric)
2031 const float probeHeaterCelsius = (viewscreen->gameclass->bus->IceDetectorHeat ? 70 : viewscreen->ptrWeather->GetTemperatureCelsius());
2032 const float probeRiseAvailable = RiseMath::Min(probeHeaterCelsius - viewscreen->ptrWeather->GetTemperatureCelsius(), 70);
2033 const float probeTempCelsius = viewscreen->ptrWeather->GetTemperatureCelsius() + RiseMath::Max(0, probeRiseAvailable);
2034
2035 float melt = probeTempCelsius / 70.0f * 18.288f / 135.224f * fElapsedTime;
2036 if (melt > 0)
2038 // can't comment this out because of the sublimation above
2041 if (leadingEdgeTempCelsius > 0)
2042 {
2043 melt = leadingEdgeTempCelsius / 107.0f * 18.288f / 135.224f * fElapsedTime;
2044 airIceAccumulationMm -= melt;
2045 }
2046 if (airframeTempCelsius > 0)
2047 {
2048 melt = airframeTempCelsius / 107.0f * 18.288f / 135.224f * fElapsedTime;
2050 }
2053
2056
2057 // *** disrupt airflow
2058 // 1/2 of an inch (12.7mm) reduces lift by 50% and increases drag 50%
2059 // #40 grit (0.425 mm) can reduce lift by 30% ... 12.7 is 50% reduction
2060 // reduce lift by up to 30% ... large horn ice accumulation is 40-50% reduction
2061 // increase drag to 40% (large horn ice can do 80-200%)
2062 // clamp to .5 on the low end because we have no evidence that it ever drops below 50%
2063 const float liftIceMod = RiseMath::Max(0.5f, 1.0f - 0.003f * powf(airIceAccumulationMm, 2.0f)); // 1-0 ... @ref not curvefit but fn=1-.003*x^2 on fooplot.com ..
2064 const float dragIceMod = 1.0f + 0.14f * powf(airIceAccumulationMm, 0.5f); // 1-2 ... @ref not curvefit but fn=1+.14*x^.5 on fooplot.com .. 204 mm is 300% drag!
2065 //if (viewscreen->gameclass->GUI->IsAdmin)
2066 //{
2067 // static int iceDumpFile = -1;
2068 // if (iceDumpFile == -1)
2069 // _sopen_s(&iceDumpFile, "icedata.log", _O_RDWR | _O_CREAT | _O_TRUNC | _O_TEXT | _O_SEQUENTIAL, SH_DENYWR, S_IWRITE);
2070 // if (halfsec == 0.0f)
2071 // {
2072 // char msg1[999];
2073 // sprintf_s(msg1, 999, "MSL: %.3f TAS: %.3f DSV: %.1f TSV: %.1f CSV: %.1f THK: %.1f SAT: %+.1f AFT: %+.1f INT: %.1f ACC: %.3f I/D: %.1f (%i) A/F: %.1f SUB: %.1f LET: %.1f (%i) LFT: %.1f DRG: %.1f\n",
2074 // playerships[0].mslKm, tas, dropSeverity, temperatureSeverity, cloudSeverity, viewscreen->ptrWeather->cloudThickness, viewscreen->ptrWeather->GetTemperatureCelsius(), airframeTempCelsius, iceIntensity, iceAccretion, // adding
2075 // viewscreen->gameclass->bus->IceDetectorMm, viewscreen->gameclass->bus->IceDetectorHeat ? 1 : 0, airIceAccumulationMm, // accumulated
2076 // sublimation, leadingEdgeTempCelsius, viewscreen->gameclass->bus->AntiIce ? 1 : 0, liftIceMod, dragIceMod); // removing
2077 // _write(iceDumpFile, msg1, strlen(msg1));
2078 // }
2079 //}
2080#pragma endregion
2081
2082
2083 // St. Elmo's Fire
2084 const float charge = viewscreen->ptrWeather->GetTurbulence() * cloudSeverity * ias / 0.09f * 1.4f; // 175 kts ... and I think this worked empirically ... Chat GPT suggested 40% faster rate on Vieneo
2085 if (charge > 0.05f) // dissipated by static wicks
2086 staticBuildup += charge * fElapsedTime;
2087
2088
2089 // Scaled adjustment based on V2
2091 {
2092 // 77 - 67 (10) / 33.5 = 0.2985074626865672 (0.7)
2093 // 80 at 32k ... (80-67)/(67*0.5) ... 78% thrust aug power ...
2094 f_temp = Clamp((viewscreen->gameclass->bus->IndicatedAirspeedKms - ourcockpit.Vs2) / (ourcockpit.Vs2 * 0.5f), 0, 1); // 0.078 is 2.0*Vs1-0.078f, 100% at 78 or less, 0% at 85
2095
2096 // so this way it is 77 / 67 which is 1 (0) @todo once we get the freaking vehicles to fly like real aircraft we can use this one?
2097 //f_temp = Clamp(viewscreen->gameclass->bus->IndicatedAirspeedKms / ourcockpit.Vs2, 0, 1); // 0.078 is 2.0*Vs1-0.078f, 100% at 78 or less, 0% at 85
2098
2099 f_augment = sqrtf(1.0f - f_temp); // didn't used to be exponential
2100 //f_augment = 1.0f - viewscreen->gameclass->bus->AirDensityScalar;
2101 f_augment *= static_cast<float>(ourcockpit.vdat.thrustaug) / 127.0f;
2102 }
2103 else
2104 f_augment = 0.0f;
2105
2106
2107 // DOR's aircraft leg uses wing support to fade augmentation:
2108 // some spaceplane Vs2 settings exceed Vne and never fade it.
2111
2112 // reduce deflection of control surfaces based on stall speed
2113 // deflect is 0-30° to 220 m/s
2114 float f_deflect; // % to deflect based on velocity, 0% to 0.078f, 100% at 0.078f to 25% at 0.176f
2115 if (playerships[0].groundvehicle)
2116 f_deflect = 1.0f;
2117 else if (viewscreen->gameclass->bus->IndicatedAirspeedKms > viewscreen->gameclass->bus->ComputedVsKms) // stall (thrust aug uses vs2)
2118 {
2119 // so if we are at 80 at 32km and stall is 25 that is (80-25)/(VcMSL-25)
2121 if (f_deflect > 1.0f)
2122 f_deflect = 1.0f;
2123 // 0 at stall to 1 above stall to 0.75 at full speed
2124 f_deflect = sqrtf(1.0f - f_deflect);
2125 if (f_deflect < 0.25f)
2126 f_deflect = 0.25f;
2127 }
2128 else
2129 f_deflect = 1.0f;
2130
2131
2132#pragma region AUTOFLYTE SYSTEM
2138
2141
2142 constexpr float glsUsableRangeKm = 42.6f; // Shared LOC/G/S capture and G/S tracking limit.
2144 float dme;
2145 if (viewscreen->gameclass->bus->WPtargetC >= 0 && viewscreen->gameclass->bus->WPtargetC < static_cast<int>(viewscreen->gameclass->bus->waypoint.size()))
2146 {
2149 dme = RiseMath::Vec3Length(&result); // - playerships[0].mslKm;
2150 }
2151 else
2152 {
2153 dme = 999.0f;
2154 }
2155
2156#pragma region Vertical modes
2158 {
2159 // evaluate engines running
2162 if (ourcockpit.vdat.leftengine >= 64)
2164 if (ourcockpit.vdat.clengine >= 64)
2166 if (ourcockpit.vdat.rightengine >= 64)
2168 }
2170 {
2171 // check distance
2172 if (dme > glsUsableRangeKm)
2173 {
2174 sprintf_s(msg, sizeof msg, "LVT DME %.3f > %.1f", dme, glsUsableRangeKm);
2176 }
2177 else
2178 {
2179 viewscreen->gameclass->bus->AFCS.DesiredAltitudeKm = dme / 16.0f * 0.840f + currentWaypoint.elevationKm; // AGL along localizer path
2180 // so if we are at 500 and we are supposed to be at 400 then it is 100 we overcorrect down to 300
2182 viewscreen->verticaltime = 4.0f;
2183 }
2184 }
2185
2186 // don't check LOC active here because we always want to calculate to show G/S deviation
2189 {
2190 if (dme <= glsUsableRangeKm && // Leave G/S armed until within the usable range.
2191 fabsf(viewscreen->gameclass->bus->GlideslopeDeviationRadians) < 0.003125f && // make sure this is below not above
2194 {
2195 logger->Log("###CAPTURE GS!!");
2198 Command command;
2199 command.name = "AuralGlideslopeCaptured";
2200 viewscreen->gameclass->bus->commandStream.emplace_back(command);
2201 }
2202 }
2203
2205 {
2207 if (playerships[0].mslKm > cloudTopsMslC)
2208 {
2209 sprintf_s(msg, sizeof msg, "LVT AGL MSL %.1f > %.1f", playerships[0].mslKm, cloudTopsMslC);
2211 }
2212 else
2213 {
2214 viewscreen->gameclass->bus->AFCS.DesiredVsiKms = viewscreen->gameclass->bus->AFCS.DesiredAltitudeKm - f_AGL; // 10% of altitude 1000 fpm we stop 100 short so (tgt-cur)*0.1
2215 if ((fabsf(olddesiredvsi) > 0.300 && fabsf(viewscreen->gameclass->bus->AFCS.DesiredVsiKms) <= 0.300) ||
2216 (fabsf(olddesiredvsi) < 0.060 && fabsf(viewscreen->gameclass->bus->AFCS.DesiredVsiKms) >= 0.060))
2217 {
2218 if (ourcockpit.power > 0.5f)
2219 {
2222 }
2223 }
2226 // limit +/- 6000 fpm (30.5 m/s)
2227 if (viewscreen->gameclass->bus->AFCS.DesiredVsiKms > 0.0305f)
2229 else if (viewscreen->gameclass->bus->AFCS.DesiredVsiKms < -0.0305f)
2231
2232 // sprintf_s(msg, sizeof msg, "\t AGL\tcur %.3f ", f_AGL);
2233 // _write(logfile, msg, strlen(msg));
2234 }
2235 }
2236
2239 {
2240 viewscreen->gameclass->bus->AFCS.DesiredVsiKms = viewscreen->gameclass->bus->AFCS.DesiredAltitudeKm - playerships[0].mslKm; // 10% of altitude 1000 fpm we stop 100 short so (tgt-cur)*0.1
2241 if ((fabsf(olddesiredvsi) > 0.300f && fabsf(viewscreen->gameclass->bus->AFCS.DesiredVsiKms) <= 0.300f) ||
2242 (fabsf(olddesiredvsi) < 0.060f && fabsf(viewscreen->gameclass->bus->AFCS.DesiredVsiKms) >= 0.060f))
2243 {
2244 if (ourcockpit.power > 0.5f)
2245 {
2248 }
2249 }
2251 // 0.050 *= .2/4 is 0.05 ... which means a 50 m/s deviation asks for a 2.5 m/s adjustment which wasn't happening
2252 viewscreen->gameclass->bus->AFCS.DesiredVsiKms *= 0.025f * ourcockpit.appitagr * weightFactor; // 100 meters we will do 10 m/s to get there
2253 // so T-1 with 2 is .1 but E-10 with 3.5 is .05
2254 // limit +/- 6000 fpm (30.5 m/s)
2255 if (viewscreen->gameclass->bus->AFCS.DesiredVsiKms > 0.0305f)
2257 else if (viewscreen->gameclass->bus->AFCS.DesiredVsiKms < -0.0305f)
2259 // desiredvsi*=0.012695510867357302457850903920374;
2260 // sprintf_s(msg, sizeof msg, "\t MSL\tcur %.3f", playerships[0].mslKm);
2261 // _write(logfile, msg, strlen(msg));
2262 }
2264 {
2265 // 0.090 - 0.080 is +0.010 is 1 deg so *100
2267 const float targetpitch = viewscreen->gameclass->bus->PitchAttitudeRadians + deltaias * 3.0f; // was 10
2268 float diff = targetpitch - viewscreen->gameclass->bus->AFCS.DesiredPitchRadians;
2269 if (diff > 0.052359877559829887307710723054658f) // 3 degrees per second
2270 diff = 0.052359877559829887307710723054658f;
2271 else if (diff < -0.052359877559829887307710723054658f)
2272 diff = -0.052359877559829887307710723054658f;
2273 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians += diff * fElapsedTime; // 0.1-0.01=0.09
2274 // deg limit
2275 if (viewscreen->gameclass->bus->AFCS.DesiredPitchRadians > 0.34906585039886591538473815369772f) // nose up 20
2276 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians = 0.34906585039886591538473815369772f;
2277 else if (viewscreen->gameclass->bus->AFCS.DesiredPitchRadians < -0.26179938779914943653855361527329f) // nose down 15
2278 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians = -0.26179938779914943653855361527329f;
2279 // sprintf_s(msg, sizeof msg, "\t VSI\tcur %.3f tgt %.3f", vsi, desiredvsi);
2280 // _write(logfile, msg, strlen(msg));
2281 }
2282
2283
2285 auto& afcs = viewscreen->gameclass->bus->AFCS;
2286 const auto& flight = *viewscreen->gameclass->bus;
2287 if (flight.OnGround || !FlightPath::Valid(flight.GroundSpeedKms, flight.VerticalSpeedKms)) {
2288 afcs.CurrentVerticalMode = Bus::Afcs::Pitch;
2289 afcs.DesiredPitchRadians = flight.PitchAttitudeRadians;
2290 } else {
2291 afcs.DesiredPitchRadians = float(FlightPath::Pitch(afcs.DesiredFpaRadians,
2292 flight.GroundSpeedKms, flight.VerticalSpeedKms, flight.PitchAttitudeRadians,
2293 afcs.DesiredPitchRadians, fElapsedTime));
2294 }
2295 }
2299 {
2300 // 0.020 - 0.010 is +0.010 is 1 deg so *100
2302 const float targetpitch = viewscreen->gameclass->bus->PitchAttitudeRadians + deltavsi * 2.0f * (viewscreen->gameclass->bus->AirDensityScalar + 0.5f); // was 10
2303 float diff = targetpitch - viewscreen->gameclass->bus->AFCS.DesiredPitchRadians;
2304 if (diff > 0.052359877559829887307710723054658f) // 3 degrees per second
2305 diff = 0.052359877559829887307710723054658f;
2306 else if (diff < -0.05235987755982988730771072305465f)
2307 diff = -0.05235987755982988730771072305465f;
2308 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians += diff * fElapsedTime; // 0.1-0.01=0.09
2309 // deg limit
2310 if (viewscreen->gameclass->bus->AFCS.DesiredPitchRadians > 0.34906585039886591538473815369772f) // nose up 20
2311 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians = 0.34906585039886591538473815369772f;
2312 else if (viewscreen->gameclass->bus->AFCS.DesiredPitchRadians < -0.26179938779914943653855361527329f) // nose down 15
2313 viewscreen->gameclass->bus->AFCS.DesiredPitchRadians = -0.26179938779914943653855361527329f;
2314 // sprintf_s(msg, sizeof msg, "\t VSI\tcur %.3f tgt %.3f", vsi, desiredvsi);
2315 // _write(logfile, msg, strlen(msg));
2316 }
2317
2318 //float basePitch = viewscreen->gameclass->bus->AFCS.DesiredPitchRadians;
2319
2321 //if (viewscreen->gameclass->bus->AFCS.CurrentVerticalMode == Bus::Afcs::VerticalModes::VerticalSpeed ||
2322 // viewscreen->gameclass->bus->AFCS.CurrentVerticalMode > Bus::Afcs::VerticalModes::SpeedPitch)
2323 //{
2324 // float bank = fabsf(rollAtt);
2325 // float cosb = RiseMath::Max(0.2f, cosf(bank)); // prevent silliness > 75°
2326 // float loadFactor = 1.0f / cosb;
2327 // float excessG = loadFactor - 1.0f;
2328
2329 // float turnPitchBias = excessG * ourcockpit.pitchDegreesAddPerG;
2330 //}
2331
2332 static AfcsControl::PitchController afcsPitch;
2333 static bool previousDorAircraft=false;
2334 const bool dorAircraft=viewscreen->gameclass->bus->AFCS.DorAircraft;
2335 if(previousDorAircraft!=dorAircraft) {
2336 afcsPitch.Reset();apTrimTimer=0;
2338 previousDorAircraft=dorAircraft;
2339 }
2341 afcsPitch.Reset();
2344 {
2346 {
2348 return;
2349 }
2350
2351 const float dt=Clamp(fElapsedTime,1.0f/240.0f,1.0f/20.0f);
2352 const float pitchAtt=viewscreen->gameclass->bus->PitchAttitudeRadians;
2353 const float desiredPitch=viewscreen->gameclass->bus->AFCS.DesiredPitchRadians;
2354 const auto pitchResult=afcsPitch.Step(pitchAtt,desiredPitch,viewscreen->pitchInput,qz_lbsPerSqFt,f_augment,fElapsedTime);
2355 viewscreen->pitchInput=pitchResult.stick;
2356 const auto [unusedStick,pitchError,desiredRate,rateError,uP,uUnsat,uSat,KpStick,KiStick,maxRate,saturated]=pitchResult;
2357 const float pitchRateFilt=afcsPitch.pitchRateFilt,rateI=afcsPitch.rateI;
2358 // ---------------- Logging ----------------
2359#pragma region Logging
2360 static float logTimer = 0.0f;
2361 static int logFile = -1;
2362 if (logFile == -1)
2363 {
2364 _sopen_s(&logFile, "pitchPid.log",
2365 _O_RDWR | _O_CREAT | _O_TRUNC | _O_TEXT | _O_SEQUENTIAL,
2366 SH_DENYWR, S_IWRITE);
2367 }
2368
2369 logTimer += dt;
2370 if (logTimer >= 0.25f)
2371 {
2372 logTimer = 0.0f;
2373 char msg[768];
2374 sprintf_s(msg, sizeof(msg),
2375 "AP_PITCH | p=%.2f des=%.2f err=%.2f | "
2376 "pRate=%.2f desR=%.2f rErr=%.2f | "
2377 "uP=%.3f I=%.3f uUns=%.3f uSat=%.3f sat=%d | "
2378 "Kp=%.3f Ki=%.3f maxR=%.2f in=%.3f\n",
2379 RiseMath::ToDegree(pitchAtt),
2380 RiseMath::ToDegree(desiredPitch),
2381 RiseMath::ToDegree(pitchError),
2382 RiseMath::ToDegree(pitchRateFilt),
2383 RiseMath::ToDegree(desiredRate),
2384 RiseMath::ToDegree(rateError),
2385 uP,
2386 rateI,
2387 uUnsat,
2388 uSat,
2389 saturated ? 1 : 0,
2390 KpStick,
2391 KiStick,
2392 RiseMath::ToDegree(maxRate),
2394
2395 _write(logFile, msg, (unsigned)strlen(msg));
2396 }
2397#pragma endregion
2398
2400
2401
2402
2403
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414 // --- parameters ---
2415 const float trimRateDegPerSec = 0.20f; // typical transport autopilot trim rate
2416 const float trimRateRadPerSec = trimRateDegPerSec * (RiseMath::Pi / 180.0f);
2417
2418 // elevator threshold beyond which trim begins transferring
2419 const float trimThreshold = 0.10f; // 10% elevator = typical trigger
2420
2421 float elevator = viewscreen->pitchInput;
2422
2423 // 1: detect sustained elevator force
2424 if (fabsf(elevator) > trimThreshold)
2425 {
2426 apTrimTimer += fElapsedTime;
2427 }
2428 else
2429 {
2430 apTrimTimer = 0.0f;
2431 }
2432
2433 // 2: only trim if elevator has been displaced for long enough
2434 if (apTrimTimer > 0.5f) // 0.5 sec continuous
2435 {
2436 // determine trim direction
2437 float trimDirection = (elevator > 0 ? 1.0f : -1.0f);
2438
2439 // compute trim change for this frame
2440 float trimDelta = trimDirection * trimRateRadPerSec * fElapsedTime;
2441
2442 // apply trim
2444
2445 // clamp trim
2447 Clamp(viewscreen->gameclass->bus->PitchTrimScalar, -1.0f, 1.0f);
2448
2449 // remove that amount from elevator input (trim relief)
2450 elevator -= (trimDelta / trimlimiterC);
2451 }
2452
2453 // 3: apply updated elevator
2454 viewscreen->pitchInput = Clamp(elevator, -1.0f, 1.0f);
2455
2457
2458
2459
2460 }
2461 else
2462 {
2464 }
2465
2466
2467
2468
2469
2470#pragma endregion
2471
2472 // THIS IS LOC
2475 currentWaypoint.ils > 0 && dme <= 75.0f) // Just G/S is 63 ... LOC and G/S is 127 ... GBAS is 23 NM (42.596) but Bill begged for 75
2476 {
2477 float hdg2obj = viewscreen->insthdgDegrees + viewscreen->gameclass->bus->TargetBearingDeg; // 020+020 is 040
2478 if (hdg2obj > 360.0f)
2479 hdg2obj -= 360.0f;
2480 else if (hdg2obj <= 0.0f)
2481 hdg2obj += 360.0f;
2482 viewscreen->gameclass->bus->DebugHdg2Rwy = hdg2obj;
2484
2485 float correct = hdg2obj - static_cast<float>(currentWaypoint.heading); // 030-360 is -330
2486 if (correct > 180.0f) // 359
2487 correct -= 360.0f; // to fix case of 359-0 is 359 instead of -1
2488 else if (correct < -180.0f)
2489 correct += 360.0f;
2490 if (correct > 90.0f) // 179
2491 correct = 180.0f - correct; // 1 to the right
2492 else if (correct < -90.0f) // -179
2493 correct = -180.0f - correct;
2494
2496
2499 }
2500 else
2501 {
2503 }
2504
2505 if (currentWaypoint.ils == 127) // localizer AND glideslope are operational
2507 else
2509
2510#pragma region Lateral modes
2511 // check to see if close enough to capture
2514 {
2515 float hdgdiff = fabsf(viewscreen->insthdgDegrees - currentWaypoint.heading);
2516 // 360-0 is 360, 0-360 is 360 359-2
2517 if (hdgdiff > 180.0f)
2518 hdgdiff -= 360.0f;
2519
2520 // Leave LOC armed outside the usable range; check bearing difference and sequencer.
2521 if (dme <= glsUsableRangeKm && fabsf(hdgdiff) <= 35.0f && currentWaypoint.ils > 0 && fabsf(RiseMath::ToDegree(viewscreen->gameclass->bus->LocalizerDeviationRadians)) <= 1.0f) // 1km capture tolerance within 35 deg of course and found runway TDZ waypoint
2522 {
2523 logger->Log("###CAPTURE LOC!!");
2526 Command command;
2527 command.name = "AuralLocalizerCaptured";
2528 viewscreen->gameclass->bus->commandStream.emplace_back(command);
2529 }
2530 }
2531
2533 {
2534 // start with desiredcrs given
2535 // heading to object
2536 float hdg2obj = viewscreen->insthdgDegrees + viewscreen->gameclass->bus->TargetBearingDeg; // 020+020 is 040
2537 if (hdg2obj > 360.0f)
2538 hdg2obj -= 360.0f;
2539 else if (hdg2obj <= 0.0f)
2540 hdg2obj += 360.0f;
2541
2542 // difference between them should be 0
2543 // this is where we need to look for flyover vs. flyby
2544 // https://jira.risetvp.com/view.php?id=456
2545
2546 float correct = hdg2obj - RiseMath::ToDegree(viewscreen->gameclass->bus->AFCS.DesiredCourseRadians); // 020-350 is -330
2547 if (correct > 180.0f) // 359
2548 correct -= 360.0f; // to fix case of 359-0 is 359 instead of -1
2549 else if (correct < -180.0f)
2550 correct += 360.0f;
2551 if (correct > 90.0f) // 179
2552 correct = 180.0f - correct; // 1 to the right
2553 else if (correct < -90.0f) // -179
2554 correct = -180.0f - correct;
2555
2557 {
2558 // so we are 5 degrees right of course ... we want to overcorrect by 10 degrees
2560 correct *= 2.0f;
2561 else
2562 correct *= 4.0f;
2563
2564 // But never more than 45 degrees
2565 if (correct > 45.0f)
2566 correct = 45.0f;
2567 else if (correct < -45.0f)
2568 correct = -45.0f;
2569
2570 // and if we are close to the point then we scale back the correction
2571 if (dme < 4.0f)
2572 correct *= dme * 0.25f;
2573
2574 // if insttrk is 320 and we are 330 then we need to pretend we are +10
2575 float trkadj = viewscreen->insthdgDegrees - viewscreen->insttrk; // +10
2576 if (trkadj > 360.0f)
2577 trkadj -= 360.0f;
2578 else if (trkadj <= 0.0f)
2579 trkadj += 360.0f;
2580
2586 }
2587 }
2588
2590 {
2591 float desiredrollDegrees = RiseMath::ToDegree(viewscreen->gameclass->bus->AFCS.DesiredHeadingRadians) - viewscreen->insthdgDegrees - viewscreen->gameclass->bus->SlipSkidRadians; // we were 030 and selected 360, that is 330 greater than 180
2592 if (desiredrollDegrees < -180.0f)
2593 desiredrollDegrees = 360.0f + desiredrollDegrees;
2594 else if (desiredrollDegrees > 180.0f) // more than 180 to right
2595 desiredrollDegrees = desiredrollDegrees - 360.0f;
2596 if (playerships[0].mslKm > 9.63168f) // 31600 feet ...
2597 desiredrollDegrees = Clamp(desiredrollDegrees, -15, 15);
2598 else if (viewscreen->gameclass->bus->RadioAltitudeKm < 0.1524f) // 500 ft AGL
2599 {
2600 // linearly reduces from 30 degrees at 500 AGL to 5 degrees at 0 AGL
2601 float t = Clamp(viewscreen->gameclass->bus->RadioAltitudeKm / 0.1524f, 0.0f, 1.0f);
2602 // taper from 30° at 500 AGL → 5° at 0 AGL
2603 float maxBank = Lerp(5.0f, 30.0f, t);
2604 // now clamp autopilot output to this low-altitude–safe envelope
2605 desiredrollDegrees = Clamp(desiredrollDegrees, -maxBank, maxBank);
2606 }
2607 else
2608 desiredrollDegrees = Clamp(desiredrollDegrees, -30, 30);
2609
2611 desiredrollDegrees=RiseMath::ToDegree(float(Orbital::Ascent::HeadingBank(
2617 }
2618
2619 if (viewscreen->gameclass->bus->AFCS.CurrentLateralMode && viewscreen->gameclass->bus->AFCS.AutopilotEngaged) // roll mode is lateralmode==1, this also covers TO/TO at -1
2620 {
2621 const auto& afcs=viewscreen->gameclass->bus->AFCS;
2622 viewscreen->rollInput=AfcsControl::RollInput(afcs.DesiredRollRadians,
2624 viewscreen->rollInput,ourcockpit.aprolagr,weightFactor,fElapsedTime);
2625 }
2626#pragma endregion
2627
2628 if (initFromDeflect)
2629 {
2634 else
2636 initFromDeflect = false;
2637 }
2638 else
2639 {
2640 playerships[0].rolldeflect = VehicleWear::ApplyControlPlay(viewscreen->rollInput, wear.controlPlay) * f_deflect; // Percent of available AOA deflection
2643 {
2645 playerships[0].pitchdeflect = Clamp(playerships[0].pitchdeflect, -1.0f, 1.0f);
2646 }
2647 else
2648 playerships[0].pitchdeflect = 0.0f;
2649 }
2650
2652
2654
2655#pragma region debug
2656 if (playerships[0].pitchdeflect > 1.0f || playerships[0].pitchdeflect < -1.0f || _isnan(playerships[0].pitchdeflect) || isinf(playerships[0].pitchdeflect))
2657 {
2658 sprintf_s(msg, sizeof(msg), "Trapped a violation computing propulsion... Pitch: %f (%f, %f, %f)", playerships[0].pitchdeflect, viewscreen->pitchInput, viewscreen->gameclass->bus->PitchTrimScalar, f_deflect);
2660 playerships[0].pitchdeflect = 0.0f;
2661 }
2662
2663 if (playerships[0].rolldeflect > 1.0f || playerships[0].rolldeflect < -1.0f || _isnan(playerships[0].rolldeflect) || isinf(playerships[0].rolldeflect))
2664 {
2665 sprintf_s(msg, sizeof(msg), "Trapped a violation computing propulsion... Roll: %f (%f, %f)", playerships[0].rolldeflect, viewscreen->rollInput, f_deflect);
2667 playerships[0].rolldeflect = 0.0f;
2668 }
2669
2670 if (playerships[0].yawdeflect > 1.0f || playerships[0].yawdeflect < -1.0f || _isnan(playerships[0].yawdeflect) || isinf(playerships[0].yawdeflect))
2671 {
2672 sprintf_s(msg, sizeof(msg), "Trapped a violation computing propulsion... Yaw: %f (%f, %f)", playerships[0].yawdeflect, viewscreen->yawInput, f_deflect);
2674 playerships[0].yawdeflect = 0.0f;
2675 }
2676
2677 if (playerships[0].steerdeflect > 1.0f || playerships[0].steerdeflect < -1.0f || _isnan(playerships[0].steerdeflect) || isinf(playerships[0].steerdeflect))
2678 {
2679 sprintf_s(msg, sizeof(msg), "Trapped a violation computing propulsion... Steer %f (%f, %f)", playerships[0].steerdeflect, viewscreen->steerInput, f_deflect);
2681 playerships[0].steerdeflect = 0.0f;
2682 }
2683#pragma endregion
2684
2685#pragma endregion
2686
2687
2688
2689
2690 // RCS pitch roll and yaw THRUST AUGMENTATION SYSTEM
2691 float rollThrustTotal = (-playerships[0].rollRadPerSec / limiterC + VehicleWear::ApplyControlPlay(viewscreen->rollInput, wear.controlPlay)) * f_augment * ourcockpit.power * 10.0f; // roll rad/s
2693 //if (viewscreen->gameclass->GUI->IsAdmin)
2694 //yawThrust = rollThrustTotal = 0.0f;
2696
2697 // TVM ground-reference landing assist. Ordinary AFCS and DOR
2698 // remain separate owners; manual augmentation supplies authority.
2699 const auto& tvmBus = *viewscreen->gameclass->bus;
2700 const auto& tvmShip = playerships[0];
2701 const auto& tvmBody = tvmShip.matrixWorld;
2702 TvmLeveling::Input leveling;
2703 leveling.enabled = tvmBus.AFCS.TvmOn && !tvmBus.AFCS.DorOn &&
2704 !tvmBus.AFCS.AutopilotEngaged && ourcockpit.power >= .5f;
2705 leveling.groundReference = leveling.enabled &&
2707 leveling.airborne = !tvmShip.groundvehicle && !tvmShip.docked &&
2708 (tvmShip.reference == REF_APNMODE || tvmShip.reference == REF_ACLMODE);
2709 leveling.frozen = tvmBus.FlightFreeze;
2710 leveling.ias = tvmBus.IndicatedAirspeedKms;
2711 leveling.stall = tvmBus.ComputedVsKms;
2712 leveling.airspeed = tas; // full airflow vector, including reverse/vertical flight
2713 leveling.soundSpeed = speedOfSoundKms; // local Vieneo temperature/composition model
2714 leveling.dt = fElapsedTime;
2715 leveling.radial = {tvmShip.position.x,tvmShip.position.y,tvmShip.position.z};
2716 leveling.rotation.frame = {{tvmBody._11,tvmBody._12,tvmBody._13},
2717 {tvmBody._21,tvmBody._22,tvmBody._23},{tvmBody._31,tvmBody._32,tvmBody._33}};
2718 leveling.rotation.rates = {-tvmShip.pitch,-tvmShip.yawRadPerSec,-tvmShip.rollRadPerSec};
2719 leveling.rotation.effort = (std::clamp)(double(f_augment),0.0,1.0) *
2720 (std::clamp)(double(ourcockpit.power),0.0,1.0);
2721 auto tvmWingHealth = [](int health) { return health == -1 ? 1.0 : (std::clamp)(health/127.0,0.0,1.0); };
2725 tvmWingHealth(ourcockpit.vdat.rightwing),leveling.rotation.effort,wear.thrust);
2729 const auto levelCommand = TvmLeveling::Command(leveling,
2730 Clamp(pitchThrust,-1.0f,1.0f),Clamp(rollThrustTotal,-1.0f,1.0f));
2731 pitchThrust = float(levelCommand.pitch);
2732 rollThrustTotal = float(levelCommand.roll);
2733
2734 // DOR owns rotational RCS while engaged, independently of manual
2735 // augmentation/IAS fading. Demand includes power and RCS health;
2736 // the same force caps, wing damage, wear, moments and fuel model follow.
2738 {
2739 const auto& orbitBus = *viewscreen->gameclass->bus;
2740 // Reapply live availability between the module's scheduled updates.
2741 const double available = (ourcockpit.power >= .5f && !playerships[0].docked &&
2742 playerships[0].reference != REF_ONGROUND && !orbitBus.FlightFreeze) ?
2743 (std::clamp)(double(ourcockpit.power),0.0,1.0) *
2744 (std::clamp)(double(ourcockpit.vdat.thrustaug)/127,0.0,1.0) : 0;
2745 auto rotation = Orbital::RotationCommand(orbitBus.orbit, orbitBus.ProgramTime, available);
2746 if (orbitBus.orbit.guidance.phase == Orbital::Phase::Wait || orbitBus.orbit.guidance.phase == Orbital::Phase::Coast)
2747 {
2748 const auto& body = playerships[0].matrixWorld;
2750 coast.frame = {{body._11,body._12,body._13},{body._21,body._22,body._23},{body._31,body._32,body._33}};
2752 coast.effort = available;
2753 auto wing = [](int health) { return health == -1 ? 1.0 : (std::clamp)(health/127.0,0.0,1.0); };
2756 wing(ourcockpit.vdat.leftwing),wing(ourcockpit.vdat.rightwing),available,wear.thrust);
2757 rotation = Orbital::CoastRotationCommand(orbitBus.orbit,orbitBus.ProgramTime,coast,
2758 {VehicleWear::ApplyControlPlay(viewscreen->pitchInput,wear.controlPlay),
2759 VehicleWear::ApplyControlPlay(viewscreen->yawInput,wear.controlPlay),
2760 VehicleWear::ApplyControlPlay(viewscreen->rollInput,wear.controlPlay)});
2761 }
2762 pitchThrust = static_cast<float>(rotation.x);
2763 yawThrust = static_cast<float>(rotation.y);
2764 rollThrustTotal = static_cast<float>(rotation.z);
2765 }
2766
2767 orbitActuation.rotationEffort={Clamp(pitchThrust,-1.0f,1.0f),Clamp(yawThrust,-1.0f,1.0f),Clamp(rollThrustTotal,-1.0f,1.0f)};
2768 rollThrustTotal = Clamp(rollThrustTotal, -1.0f, 1.0f) * static_cast<float>(Orbital::RollRcsForce); // 870 pounds, * 40 because shuttle is too slow!?
2769 // to keep it simple we will say that postive values for both left and right mean positive roll right...
2770 // if one wing is missing then it will still roll right at half the torque (should actually be less?) but also translate
2771 float rollRightThrustLeftSide = rollThrustTotal;
2772 if (ourcockpit.vdat.leftwing != -1)
2773 rollRightThrustLeftSide *= RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.leftwing)) / 127.0f;
2774 float rollRightThrustRightSide = rollThrustTotal;
2775 if (ourcockpit.vdat.rightwing != -1)
2776 rollRightThrustRightSide *= RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.rightwing)) / 127.0f;
2777
2778
2779 yawThrust = Clamp(yawThrust, -1.0f, 1.0f) * static_cast<float>(Orbital::YawRcsForce); // 870 pounds, *100 because shuttle is too slow!?
2780 pitchThrust = Clamp(pitchThrust, -1.0f, 1.0f) * static_cast<float>(Orbital::PitchRcsForce); // 870 pounds, *67 because shuttle is too slow!?
2781
2782 rcsThrustYPR = (fabsf(rollRightThrustLeftSide + rollRightThrustRightSide) + fabsf(yawThrust) + fabsf(pitchThrust)) / totalWeightLbs * gForceKmSSC;
2783
2784 // Fuel reflects commanded effort before the loss of useful thrust.
2785 rollRightThrustLeftSide *= wear.thrust;
2786 rollRightThrustRightSide *= wear.thrust;
2787 yawThrust *= wear.thrust;
2788 pitchThrust *= wear.thrust;
2789
2790
2792 float flapClCdDelta = ourcockpit.flapExtent * ourcockpit.flapMaxDegrees / 45.0f;
2793 flapClCdDelta *= (ourcockpit.flapAreaModTE * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.flapsTE)) / 127.0f + ourcockpit.flapAreaModLE * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.flapsLE)) / 127.0f);
2794 // 10% of wing is 23% lift reduction ... we wanted 40%
2795 const float spoilerClCdDelta = RiseMath::Max(viewscreen->gameclass->bus->GroundSpoilerPositionScalar, viewscreen->gameclass->bus->FlightSpoilerPositionScalar) * ourcockpit.spoilerAreaMod;// *RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.rightaileron)) / 127.0f;
2796
2797
2798 if (relativeWindTrueKms.z < 0)
2799 aoaRad = atanf(-relativeWindTrueKms.y / relativeWindTrueKms.z); // stick shaker and display value
2800 else
2801 aoaRad = RiseMath::HalfPi; // stalled
2803 // @ref 14 CFR § 25.207 - Stall warning.
2804 // FAR Stall warning with sufficient margin to prevent inadvertent stalling with the flaps and landing gear in any normal position must be clearand distinctive to the pilot in straightand turning flight.
2805 // stall warning is 3 degrees before critical angle (hard-coded for all vehicles) and IAS of >20m/s and not WOW
2807 {
2808 // we don't consider ailerons lol
2809 float clMax = CalculateClMax(ourcockpit.wings, flapClCdDelta - spoilerClCdDelta);
2810 // @ref https://www.ajdesigner.com/phpwinglift/wing_lift_equation_surface_velocity.php#ajscroll
2812 // formula provides TAS ... we want IAS so we remove the AirDensityScalar modulation
2813
2814 // we don't consider ailerons lol
2815 float aoaMax = CalculateAoaMax(ourcockpit.wings, flapClCdDelta);
2816 if ((viewscreen->gameclass->bus->AngleOfAttackRadians + 0.0523599f) >= aoaMax &&
2820 {
2821 Command command;
2822 command.name = "AuralStall";
2823 viewscreen->gameclass->bus->AddCommand(command, true);
2825 }
2826 }
2827 else
2828 {
2830 }
2831
2832 // Relative wind for the wings based on roll rate and yaw rate (unverified)
2833 // what would these be, wing roll arm?
2834 const float velinc1 = ourcockpit.b12WingRollArmM * playerships[0].rollRadPerSec * 0.001f; // km in a second for the arc
2835 const float velinc2 = ourcockpit.c9WingYawArmM * playerships[0].yawRadPerSec * 0.001f; // km in a second for the arc
2836
2837 // Right wing (AOA changes with current roll and yaw rates)
2838 f_temp = relativeWindTrueKms.z - velinc2; // apparent wind velocity (could include pitch too?)
2839 float tempq = dynamicDensityScalar * rhoOver2SlugsCuFt2 * powf(f_temp * feetPerKilometerC, 2.0f);
2840
2841 float tempLiftWingRight = 0.0f; float tempDragWingRight = 0.0f;
2842 if (ourcockpit.vdat.rightwing > 0 && f_temp != 0.0f)
2843 {
2844 // aileron needs to be baked into CLDelta and CDDelta like flaps
2845 const float aileronClCdDelta = playerships[0].rolldeflect * ourcockpit.aileronAreaMod * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.rightaileron)) / 127.0f;
2846
2847 // Surface area I12 each wing ft² (this is effective vertical area translated to the CG)
2849 tempaoa = atanf((-relativeWindTrueKms.y - velinc1) / f_temp) + ourcockpit.aoiWingRad; // roll+right produces - wind on y
2850 const float Cl = CalculateLiftCoefficient(ourcockpit.wings, tempaoa, flapClCdDelta - aileronClCdDelta - spoilerClCdDelta);
2851 tempLiftWingRight = Cl * tempq * S * static_cast<float>(ourcockpit.vdat.rightwing) / 127.0f * liftIceMod;// *spoilerLiftMod;
2852 const float Cd = CalculateDragCoefficient(ourcockpit.wings, tempaoa, flapClCdDelta - aileronClCdDelta + spoilerClCdDelta);
2853 tempDragWingRight = Cd * tempq * S * static_cast<float>(ourcockpit.vdat.rightwing) / 127.0f * dragIceMod;// *spoilerDragMod;
2854 }
2855
2856 // Left wing (AOA changes with current roll and yaw rates)
2857 f_temp = relativeWindTrueKms.z + velinc2; // apparent wind velocity (could include pitch too?)
2858 tempq = dynamicDensityScalar * rhoOver2SlugsCuFt2 * powf(f_temp * feetPerKilometerC, 2.0f); // convert to ft/s from km/s
2859
2860 float tempLiftWingLeft = 0.0f; float tempDragWingLeft = 0.0f;
2861 if (ourcockpit.vdat.leftwing > 0 && f_temp != 0.0f)
2862 {
2863 // aileron needs to be baked into CLDelta and CDDelta like flaps
2864 const float aileronClCdDelta = playerships[0].rolldeflect * (ourcockpit.aileronAreaMod * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.leftaileron)) / 127.0f);
2865
2866 // Surface area I12 each wing ft² (this is effective vertical area translated to the CG)
2868 tempaoa = atanf((-relativeWindTrueKms.y + velinc1) / f_temp) + ourcockpit.aoiWingRad; // roll+right produces + wind on y
2869 const float Cl = CalculateLiftCoefficient(ourcockpit.wings, tempaoa, flapClCdDelta + aileronClCdDelta - spoilerClCdDelta);
2870 tempLiftWingLeft = Cl * tempq * S * static_cast<float>(ourcockpit.vdat.leftwing) / 127.0f * liftIceMod;// *spoilerLiftMod;
2871 const float Cd = CalculateDragCoefficient(ourcockpit.wings, tempaoa, flapClCdDelta + aileronClCdDelta + spoilerClCdDelta);
2872 tempDragWingLeft = Cd * tempq * S * static_cast<float>(ourcockpit.vdat.leftwing) / 127.0f * dragIceMod;// *spoilerDragMod;
2873 }
2874
2875 // Where they are equal, we get vertical lift (smaller of the two is the vertical rise)
2876 // Perpendicular to roll and pitch, but not quite over CG (95.7% effective)
2877 f_temp = (tempLiftWingRight + tempLiftWingLeft + rollRightThrustLeftSide - rollRightThrustRightSide) * gForceKmSSC / totalWeightLbs * fElapsedTime; // negative is going up
2878 f_temp *= groundEffect;
2879
2880 if (fElapsedTime != 0.0f)
2881 {
2882 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f wing lift", 0.0f, f_temp * oneOvergForceKmssC / fElapsedTime, 0.0f);
2883 viewscreen->sofTracking.emplace_back(msg);
2884 }
2885
2886 // verified f_temp is scaled to fElapsedTime
2887 viewscreen->sumofforces.y += f_temp; // lift
2888
2889#pragma region debug
2890 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
2891 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
2892 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
2893 {
2894 sprintf_s(msg, sizeof(msg), "\tET: %f", fElapsedTime);
2896 sprintf_s(msg, sizeof(msg), "\tsumofforces I: %f", viewscreen->sumofforces.x);
2898 sprintf_s(msg, sizeof(msg), "\tsumofforces J: %f", viewscreen->sumofforces.y);
2900 sprintf_s(msg, sizeof(msg), "\tsumofforces K: %f", viewscreen->sumofforces.z);
2902 sprintf_s(msg, sizeof(msg), "\tlift2: %f", f_temp);
2904 sprintf_s(msg, sizeof(msg), "\ttotalWeightLbs: %f", totalWeightLbs);
2906 sprintf_s(msg, sizeof(msg), "\ttempLiftWingRight: %f", tempLiftWingRight);
2908 sprintf_s(msg, sizeof(msg), "\ttempLiftWingLeft: %f", tempLiftWingLeft);
2910 sprintf_s(msg, sizeof(msg), "\trollRightThrustLeftSide: %f", rollRightThrustLeftSide);
2912 sprintf_s(msg, sizeof(msg), "\trollRightThrustRightSide: %f", rollRightThrustRightSide);
2914 sprintf_s(msg, sizeof(msg), "\tgroundeffect: %f", groundEffect);
2917 sprintf_s(msg, sizeof(msg), "Trapped a violation after lift2 application...");
2919 }
2920#pragma endregion
2921
2922
2923 float momentp = -ourcockpit.b15WingPitchArmM * (tempLiftWingRight + tempLiftWingLeft); // B15 lb-m the wing, applied aft of CG nose up is +, nose down is - (verified)
2924
2925 // But the difference causes rolling moment on the wing arm
2926 // B12 rolling moment in lb-m (verified)
2927 // wingspan in meters is total width... must be halved
2928 float momentr = ourcockpit.b12WingRollArmM * (tempLiftWingLeft - tempLiftWingRight) + ourcockpit.wingspanM * 0.5f * (rollRightThrustLeftSide + rollRightThrustRightSide);
2929
2930 // arm in m gives us velocity times roll rate to get average velocity ***
2931 // Rolling drag, using weighted arm in ft (arm²) to find average velocity in ft, then square
2932 f_temp = powf(ourcockpit.e65wase61 * 3.2808f * playerships[0].rollRadPerSec, 2.0f); // E63 ft/s
2933 // Multiplied pounds of drag the surface area corrected for Cd max, to ft², rho/2, at arm (m)
2934 if (playerships[0].rollRadPerSec > 0.0f)
2935 momentr -= ourcockpit.d65wasd61 * f_temp * dynamicDensityScalar; // D63
2936 else
2937 momentr += ourcockpit.d65wasd61 * f_temp * dynamicDensityScalar; // D63
2938
2939 rollAccelerationSnapshot = momentr / (ourcockpit.momentr * totalWeightLbs) * fElapsedTime;
2940 // Left wing more lift rolls right, convert to angular velocity by dividing by MI about Z
2941 //if (!ourcockpit.gndvehicle) // to test for bill, shouldn't need to exclude
2942 playerships[0].rollRadPerSec += rollAccelerationSnapshot; // (verified intertial) 107.901512
2943
2944
2945 // Longitudinal pitching moment -------------------------------------------------------------
2946 // up is +, down is -
2947 // Use the live wing/tail/body/engine moments, not an Earth trim
2948 // schedule. RCS alone cannot counter the E-11's dense-air moment.
2949 const double windY = relativeWindTrueKms.y * feetPerKilometerC;
2950 const double weatherMoment = (ourcockpit.i66wasi62 + ourcockpit.k66wask62 *
2951 (std::max)(0.0, double(ourcockpit.vdat.htail)/127)) *
2952 -std::copysign(windY*windY, windY) * dynamicDensityScalar;
2953 const double engineMoment = ourcockpit.l48AverageEnginePitchArmM * ourcockpit.maxGrossLbs *
2954 zThrustAcceleration * oneOvergForceKmssC * wear.thrust;
2955 const double externalMoment = momentp + weatherMoment + engineMoment;
2956 const auto& pitchBus = *viewscreen->gameclass->bus;
2957 const bool dorPitch = Orbital::AscentPitchControl(pitchBus.orbit,pitchBus.AFCS.DorOn,
2958 pitchBus.ProgramTime,playerships[0].reference!=REF_ONGROUND&&!playerships[0].docked,
2959 pitchBus.FlightFreeze) && ourcockpit.power>=.5f;
2960 if (dorPitch) {
2961 auto tailMoment = [&](double surface) {
2962 return std::abs(ourcockpit.b6DistanceToHTailM) *
2964 float(surface*ourcockpit.elevatorAreaMod*(std::max)(0.0,double(ourcockpit.vdat.elevator))/127.0)) *
2966 (std::max)(0.0,double(ourcockpit.vdat.htail))/127.0 * liftIceMod;
2967 };
2968 const double available = (std::clamp)(double(ourcockpit.power),0.0,1.0) *
2969 (std::clamp)(double(ourcockpit.vdat.thrustaug)/127,0.0,1.0);
2970 const double capacity = Orbital::PitchRcsForce * ourcockpit.rcsYParmM * wear.thrust * available;
2971 const double previous = orbitActuation.ascentPitchActive?orbitActuation.elevator:playerships[0].pitchdeflect;
2972 const auto allocation = Orbital::AllocatePitch(ourcockpit.rcsYParmM*pitchThrust,externalMoment,
2973 capacity,previous,f_deflect,fElapsedTime,tailMoment);
2974 playerships[0].pitchdeflect=float(allocation.surface);
2975 const double applied = ourcockpit.rcsYParmM>0?allocation.rcsMoment/ourcockpit.rcsYParmM:0;
2976 if(wear.thrust>0) {
2977 rcsThrustYPR += float((std::abs(applied)-std::abs(pitchThrust))/wear.thrust/totalWeightLbs*gForceKmSSC);
2978 orbitActuation.rotationEffort.x=applied/(wear.thrust*Orbital::PitchRcsForce);
2979 }
2980 pitchThrust=float(applied);
2981 orbitActuation.pitchResidualMoment=allocation.residual;
2982 } else orbitActuation.pitchResidualMoment=0;
2983 orbitActuation.ascentPitchActive=dorPitch;
2984 orbitActuation.elevator=playerships[0].pitchdeflect;
2985 orbitActuation.pitchExternalMoment=externalMoment;
2986 orbitActuation.pitchRcsMoment=ourcockpit.rcsYParmM*pitchThrust;
2987 float tempLiftElevator = 0.0f;
2988 if (ourcockpit.vdat.htail > 0)
2989 {
2990 // Determine Cl's for Htail
2991 tempaoa = -aoaRad + ourcockpit.hStabAngleOfIncidenceRad; // Add AOI (negative is nose down VERIFIED) .03 = 1.72 degrees
2993
2994 // elevator needs to be baked into CLDelta and CDDelta like flaps
2995 const float elevatorClCdDelta = playerships[0].pitchdeflect * (ourcockpit.elevatorAreaMod * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.elevator)) / 127.0f);
2996
2997 const float Cl = CalculateLiftCoefficient(AirfoilType::NACA0011SC, tempaoa, elevatorClCdDelta);
2998 tempLiftElevator = Cl * qz_lbsPerSqFt * S * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.htail)) / 127.0f * liftIceMod; // qz figured in vertical translation area
2999 const float Cd = CalculateDragCoefficient(AirfoilType::NACA0011SC, tempaoa, elevatorClCdDelta);
3000 tempDragTail += Cd * qz_lbsPerSqFt * S * RiseMath::Max(0, static_cast<float>(ourcockpit.vdat.htail)) / 127.0f * dragIceMod; // qz figured in vertical translation area
3001 if (_isnan(tempDragTail) || isinf(tempDragTail))
3002 {
3003 sprintf_s(msg, sizeof(msg), "Going to crap out on air friction tempDragHTail!");
3005 tempDragTail = 0;
3006 sprintf_s(msg, sizeof(msg), "Cd: %f", Cd);
3008 sprintf_s(msg, sizeof(msg), "qz: %f", qz_lbsPerSqFt);
3010 sprintf_s(msg, sizeof(msg), "S: %f", S);
3012 sprintf_s(msg, sizeof(msg), "ourcockpit.vdat.htail: %i", ourcockpit.vdat.htail);
3014 sprintf_s(msg, sizeof(msg), "dragIceMod: %f", dragIceMod);
3016 }
3017 }
3018
3019 // Convert to torque at arm (variable with Cp)
3020 // positive value pushes down (nose up), negative value pulls up (nose down) (lb-m)
3021 orbitActuation.pitchTailMoment = fabsf(ourcockpit.b6DistanceToHTailM) * tempLiftElevator;
3022 momentp += fabsf(ourcockpit.b6DistanceToHTailM) * tempLiftElevator + ourcockpit.rcsYParmM * pitchThrust; // B6 (verified)
3023 f_temp = tempLiftElevator * gForceKmSSC / totalWeightLbs * fElapsedTime; // negative is going up
3024
3025 if (fElapsedTime != 0.0f)
3026 {
3027 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f htail lift", 0.0f, f_temp * oneOvergForceKmssC / fElapsedTime, 0.0f);
3028 viewscreen->sofTracking.emplace_back(msg);
3029 }
3030
3031 // verified f_temp is scaled to fElapsedTime
3032 viewscreen->sumofforces.y += f_temp; // lift
3033
3034#pragma region debug
3035 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
3036 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
3037 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
3038 {
3039 sprintf_s(msg, sizeof(msg), "\tET: %f", fElapsedTime);
3041 sprintf_s(msg, sizeof(msg), "\tsumofforces I: %f", viewscreen->sumofforces.x);
3043 sprintf_s(msg, sizeof(msg), "\tsumofforces J: %f", viewscreen->sumofforces.y);
3045 sprintf_s(msg, sizeof(msg), "\tsumofforces K: %f", viewscreen->sumofforces.z);
3047 sprintf_s(msg, sizeof(msg), "\tlift: %f", f_temp);
3050 sprintf_s(msg, sizeof(msg), "Trapped a violation after lift application...");
3052 }
3053#pragma endregion
3054
3055 // Weathervaning tendency
3056 f_temp = powf(relativeWindTrueKms.y * feetPerKilometerC, 2.0f);
3057 if (relativeWindTrueKms.y > 0.0f)
3058 f_temp = -f_temp;
3059 // Pitching drag, using arm in ft to find average velocity in ft/s
3060 // if (playerships[0].pitch<0.0f)
3061 // f_temp+=powf(ourcockpit.b6*3.2808f*playerships[0].pitch, 2.0f);
3062 // else
3063 // f_temp-=powf(ourcockpit.b6*3.2808f*playerships[0].pitch, 2.0f);
3064 // Multiplied pounds of drag the surface area corrected for Cd max, to ft², rho/2, at arm (m)
3065 if (ourcockpit.vdat.htail > 0)
3066 momentp += (ourcockpit.i66wasi62 + ourcockpit.k66wask62 * static_cast<float>(ourcockpit.vdat.htail) / 127.0f) * f_temp * dynamicDensityScalar; // lbs at m
3067 else
3068 momentp += ourcockpit.i66wasi62 * f_temp * dynamicDensityScalar; // lbs at m
3069
3070 // pounds at meters business is accelleration km/s so convert to pounds of force
3071 momentp += ourcockpit.l48AverageEnginePitchArmM * ourcockpit.maxGrossLbs * zThrustAcceleration * oneOvergForceKmssC * wear.thrust;
3072
3073
3074 // Convert to angular velocity by dividing by inertial moment about X axis
3075
3076 pitchAccelerationSnapshot = momentp / (ourcockpit.momentp * totalWeightLbs) * fElapsedTime;
3077 playerships[0].pitch += pitchAccelerationSnapshot; // (verified inertial) 154.817291
3078
3079
3080 // Longitudinal pitching moment -------------------------------------------------------------
3081
3082
3083#pragma region Directional Moment
3084
3085 float tempLiftRudder = 0.0f;
3086 if (ourcockpit.vdat.vtail > 0)
3087 {
3088 // AOA plus rate of turn adds relative wind plus deflection changes camber
3089 if (relativeWindTrueKms.z != 0.0f && ias > 0.02f)
3090 {
3091 tempaoa = atanf(relativeWindTrueKms.x / relativeWindTrueKms.z);
3093 }
3094 else
3095 {
3096 tempaoa = RiseMath::HalfPi; // Stalled
3098 }
3099
3100 const bool YawDampEnable = viewscreen->gameclass->bus->YawDamperStatus && ourcockpit.vdat.yawdamper > 0; // 1 = on
3101
3102 if (YawDampEnable && playerships[0].reference != REF_ONGROUND)
3103 viewscreen->gameclass->bus->YawDamperCommand = Clamp(playerships[0].yawRadPerSec * 2.0f * static_cast<float>(ourcockpit.vdat.yawdamper) / 127.0f, -1, 1);
3104 else
3106
3107
3108 const float yawDeflect = Clamp(viewscreen->gameclass->bus->YawDamperCommand + playerships[0].yawdeflect, -1, 1);
3109 S = ourcockpit.d17VTailWithRudderSqFt; // I9 Surface area in ft² of the HCl tail including rudder area
3110 const float rudderClCdDelta = yawDeflect * ourcockpit.h9RudderSqFt / S / 0.25f * fmaxf(0, ourcockpit.vdat.rudder) / 127.0f;
3111 const float Cl = CalculateLiftCoefficient(AirfoilType::NACA0011SC, tempaoa, rudderClCdDelta);
3112 tempLiftRudder = Cl * qz_lbsPerSqFt * S * static_cast<float>(ourcockpit.vdat.vtail) / 127.0f * liftIceMod; // qz figured in vertical translation area
3113 const float Cd = CalculateDragCoefficient(AirfoilType::NACA0011SC, tempaoa, rudderClCdDelta);
3114 tempDragTail += Cd * qz_lbsPerSqFt * S * static_cast<float>(ourcockpit.vdat.vtail) / 127.0f * dragIceMod; // qz figured in vertical translation area
3115 if (_isnan(tempDragTail) || isinf(tempDragTail))
3116 {
3117 sprintf_s(msg, sizeof(msg), "Going to crap out on air friction tempDragVTail!");
3119 tempDragTail = 0;
3120 sprintf_s(msg, sizeof(msg), "Cd: %f", Cd);
3122 sprintf_s(msg, sizeof(msg), "qz: %f", qz_lbsPerSqFt);
3124 sprintf_s(msg, sizeof(msg), "S: %f", S);
3126 sprintf_s(msg, sizeof(msg), "ourcockpit.vdat.vtail: %i", ourcockpit.vdat.vtail);
3128 sprintf_s(msg, sizeof(msg), "dragIceMod: %f", dragIceMod);
3130 }
3131 }
3132 else
3134
3135
3136 float momenty = ourcockpit.b9DistanceToVTailM * tempLiftRudder + ourcockpit.rcsYParmM * yawThrust; // B9 verified DV (m)
3137 momenty += ourcockpit.c9WingYawArmM * (tempDragWingRight - tempDragWingLeft); // adverse yaw
3138
3139
3140 // asymmetric thrust
3141 if (ourcockpit.engines > 1)
3142 {
3143 // Convert to torque at arm (variable with Cp)
3144 // Add difference of the two engines (lb-m)
3145 float business = 0.0f;
3147 if (ourcockpit.engines == 2)
3148 {
3150 }
3151 else if (ourcockpit.engines == 3)
3152 {
3154 }
3155 // pounds at meters business is accelleration km/s so convert to pounds of force
3156
3157 momenty += ourcockpit.i48CriticalEngineYawArmM * ourcockpit.maxGrossLbs * business * oneOvergForceKmssC * wear.thrust * rainAirThrustMultiplier;
3158 }
3159
3160
3161 // Weathervaning tendency weathervane
3162 f_temp = powf(relativeWindTrueKms.x * feetPerKilometerC, 2.0f);
3163 if (relativeWindTrueKms.x > 0.0f)
3164 f_temp = -f_temp;
3165 // Pitching drag, using arm in ft to find average velocity in ft/s
3166 // if (playerships[0].pitch<0.0f)
3167 // f_temp+=powf(ourcockpit.b6*3.2808f*playerships[0].pitch, 2.0f);
3168 // else
3169 // f_temp-=powf(ourcockpit.b6*3.2808f*playerships[0].pitch, 2.0f);
3170 // Multiplied pounds of drag the surface area corrected for Cd max, to ft², rho/2, at arm (m)
3171 if (ourcockpit.vdat.vtail > 0)
3172 momenty += (ourcockpit.i65wasi61 + ourcockpit.k65wask61 * static_cast<float>(ourcockpit.vdat.vtail) / 127.0f) * f_temp * dynamicDensityScalar; // lbs at m
3173 else
3174 momenty += ourcockpit.i65wasi61 * f_temp * dynamicDensityScalar; // lbs at m
3175
3176
3177 yawAccelerationSnapshot = momenty / (ourcockpit.momenty * totalWeightLbs) * fElapsedTime;
3178 // Convert to angular velocity by dividing by inertial moment about Y axis
3179 if (playerships[0].reference != REF_ONGROUND)
3180 {
3181 playerships[0].yawRadPerSec -= yawAccelerationSnapshot; // (verified inertial) 246.996033
3182 }
3183 else
3184 {
3185 // wheels must be on ground
3186 if ((playerships[0].groundvehicle || ourcockpit.wheeled) &&
3187 fabsf(levelerroll) <= 0.9f && // can't be rolled more than 60 deg
3188 levelerpitch <= 0.1f) // steering wheels must be on ground
3189 {
3190 float tireTurnForce = 0.0f;
3191 float steeringCenteringForce = 0.0f;
3192
3194 {
3195 // This is force that will make the steering tires turn one way or the other.
3196 // More steering tires make this feedback harder to overcome.
3197 tireTurnForce = yawAccelerationSnapshot * groundvec.z / ourcockpit.steerTires * 200.0f;
3198
3200 steeringCenteringForce = copysignf(sqrtf(fabsf(viewscreen->steerInput)), viewscreen->steerInput) *
3201 -fabsf(groundvec.z) * ourcockpit.steerTires;
3202 }
3204 {
3205 steeringCenteringForce = copysignf(sqrtf(fabsf(viewscreen->steerInput)), viewscreen->steerInput) *
3207 }
3208
3209 viewscreen->steerInput -= tireTurnForce;
3210
3211 // so for C-2 to work right we have to do 10% of this force
3212 // for T-1 to work right we need 100%
3213
3214 const float oldSteerInput = viewscreen->steerInput;
3215 viewscreen->steerInput += steeringCenteringForce;
3216 if ((viewscreen->steerInput > 0 && oldSteerInput < 0) ||
3217 (viewscreen->steerInput < 0 && oldSteerInput > 0))
3219
3221
3223
3224 // Wheel steering uses the effective wheel angle and distance to the CG. Skid steering
3225 // instead turns from the speed difference between the left and right wheel banks.
3226 float oldYaw = playerships[0].yawRadPerSec;
3228 {
3229 if (ourcockpit.suspensionTrackWidthKm > FLT_EPSILON)
3230 {
3231 const float differentialSideSpeedKms =
3233 playerships[0].yawRadPerSec = differentialSideSpeedKms / ourcockpit.suspensionTrackWidthKm;
3234 }
3235 else
3236 {
3237 playerships[0].yawRadPerSec = 0.0f;
3238 }
3239 }
3240 else if (ourcockpit.noseWheelToCgKm > FLT_EPSILON)
3241 {
3242 playerships[0].yawRadPerSec = f_temp * groundvec.z / ourcockpit.noseWheelToCgKm * 1.57f * 0.6f;
3243 }
3244 // @todo setting it makes it snap to what we think it should be... whereas if we look at difference and let it slip and
3245 // @todo cause damage by a high value differential?
3246
3247
3248 // This is ground speed until wind is factored in
3250 viewscreen->gameclass->bus->DebugFloat4 = tireTurnForce;
3251 viewscreen->gameclass->bus->DebugFloat5 = steeringCenteringForce;
3253 }
3254 }
3255
3256#pragma endregion
3257
3258
3259
3260
3261 // normal velocity changes
3262
3263 // Atmospheric drag in pounds (once multiplied by Cx which equates to Cd, q at MSL, and S)
3264 // Convert to thrust
3266 // Then fix for fraction of second
3267 f_temp *= fElapsedTime;
3268
3269
3270 result = centerC;
3271 // damage to tail, wings should increase the drag by 33% from 127 to 64 then taper to 0
3272 // ****@@@@****@@@@***
3273 if (relativeWindTrueKms.z > 0.0f) // Frontal
3274 {
3275 result.z += ourcockpit.f20FrontBackDragCoeff * f_temp * powf(relativeWindTrueKms.z * feetPerKilometerC, 2.0f);
3276 result.z += ourcockpit.f25 * ourcockpit.gearextent * f_temp * powf(relativeWindTrueKms.z * feetPerKilometerC, 2.0f);
3277 result.z += (tempDragWingRight + tempDragWingLeft + tempDragTail) * fElapsedTime * gForceKmSSC / totalWeightLbs;
3278 }
3279 else // Rear
3280 {
3281 result.z -= ourcockpit.f20FrontBackDragCoeff * f_temp * powf(relativeWindTrueKms.z * feetPerKilometerC, 2.0f);
3282 result.z -= ourcockpit.f25 * ourcockpit.gearextent * f_temp * powf(relativeWindTrueKms.z * feetPerKilometerC, 2.0f);
3283 result.z -= (tempDragWingRight + tempDragWingLeft + tempDragTail) * fElapsedTime * gForceKmSSC / totalWeightLbs;
3284 }
3285 if (_isnan(result.z) || isinf(result.z))
3286 {
3287 sprintf_s(msg, sizeof(msg), "Going to crap out on air friction result.z!");
3289 result.z = 0;
3290 sprintf_s(msg, sizeof(msg), "f_temp: %f", f_temp);
3292 sprintf_s(msg, sizeof(msg), "relativeWindTrueKms.z: %f", relativeWindTrueKms.z);
3294 sprintf_s(msg, sizeof(msg), "ourcockpit.f20FrontBackDragCoeff: %f", ourcockpit.f20FrontBackDragCoeff);
3296 sprintf_s(msg, sizeof(msg), "ourcockpit.f25: %f", ourcockpit.f25);
3298 sprintf_s(msg, sizeof(msg), "ourcockpit.gearextent: %f", ourcockpit.gearextent);
3300 sprintf_s(msg, sizeof(msg), "tempDragWingRight: %f", tempDragWingRight);
3302 sprintf_s(msg, sizeof(msg), "tempDragWingLeft: %f", tempDragWingLeft);
3304 sprintf_s(msg, sizeof(msg), "tempDragTail: %f", tempDragTail);
3306 sprintf_s(msg, sizeof(msg), "totalWeightLbs: %f", totalWeightLbs);
3308 sprintf_s(msg, sizeof(msg), "fElapsedTime: %f", fElapsedTime);
3310 }
3311
3312 if (relativeWindTrueKms.y > 0.0f) // Lower F27
3313 result.y += ourcockpit.f27PlanDragCoefficient * f_temp * powf(relativeWindTrueKms.y * feetPerKilometerC, 2.0f);
3314 else // Upper F28
3315 result.y -= ourcockpit.f27PlanDragCoefficient * f_temp * powf(relativeWindTrueKms.y * feetPerKilometerC, 2.0f);
3316 if (relativeWindTrueKms.x > 0.0f) // Sideways left F29
3317 {
3318 result.x += ourcockpit.f28SideDragCoefficient * f_temp * powf(relativeWindTrueKms.x * feetPerKilometerC, 2.0f);
3319 // should include gear extended case someday
3320 }
3321 else // Sideways right F29
3322 {
3323 result.x -= ourcockpit.f28SideDragCoefficient * f_temp * powf(relativeWindTrueKms.x * feetPerKilometerC, 2.0f);
3324 // should include gear extended case someday
3325 }
3326
3327 // Scale complete aerodynamic drag, including wings, tail and gear.
3328 result *= wear.drag;
3329
3330 if (fabsf(result.x) > 100.0f || _isnan(result.x) || isinf(result.x) ||
3331 fabsf(result.y) > 100.0f || _isnan(result.y) || isinf(result.y) ||
3332 fabsf(result.z) > 100.0f || _isnan(result.z) || isinf(result.z))
3333 {
3334 sprintf_s(msg, sizeof(msg), "ET: %f", fElapsedTime);
3336 sprintf_s(msg, sizeof(msg), "Result I: %f", result.x);
3338 sprintf_s(msg, sizeof(msg), "Result J: %f", result.y);
3340 sprintf_s(msg, sizeof(msg), "Result K: %f", result.z);
3342 sprintf_s(msg, sizeof(msg), "Relative I: %f", relativeWindTrueKms.x);
3344 sprintf_s(msg, sizeof(msg), "Relative J: %f", relativeWindTrueKms.y);
3346 sprintf_s(msg, sizeof(msg), "Relative K: %f", relativeWindTrueKms.z);
3348 sprintf_s(msg, sizeof(msg), "Weight: %f", totalWeightLbs);
3350 sprintf_s(msg, sizeof(msg), "Density: %f", staticDensity);
3352 sprintf_s(msg, sizeof(msg), "f_temp: %f", f_temp);
3354 sprintf_s(msg, sizeof(msg), "Empty Weight: %f", ourcockpit.emptyWeightLbs);
3356 sprintf_s(msg, sizeof(msg), "Trapped a violation after air friction...");
3358 }
3359 else
3360 {
3361 if (fElapsedTime != 0.0f)
3362 {
3363 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f air friction", result.x * oneOvergForceKmssC / fElapsedTime, result.y * oneOvergForceKmssC / fElapsedTime, result.z * oneOvergForceKmssC / fElapsedTime);
3364 viewscreen->sofTracking.emplace_back(msg);
3365 }
3366
3367#ifdef ODB2
3369 {
3370 static OptionalDiagnosticFile draglog("drag.log");
3371
3372 draglog.Printf(
3373 "%7.3f AIR VT%u CT%i VID%u WT%.0f WF%.2f spd%.1f dens%.3f relZ%+.5f dragGZ%+.3f qZ%.3f CxZ%.6f\n",
3375 static_cast<unsigned int>(playerships[0].type),
3376 static_cast<int>(ourcockpit.texturelib),
3377 static_cast<unsigned int>(playerships[0].vehicleId),
3379 weightFactor,
3383 fElapsedTime > 0.0f ? result.z * oneOvergForceKmssC / fElapsedTime : 0.0f,
3386 }
3387#endif
3388
3389 // verified result is based on f_temp which is scaled by fElapsedTime
3390 viewscreen->sumofforces += result; // drag from air friction
3391 }
3392
3393
3394
3395
3396 if(fElapsedTime>0) {
3397 const auto aeroDelta=viewscreen->sumofforces-beforeAerodynamics;
3398 orbitActuation.aeroBodyKms2={aeroDelta.x/fElapsedTime,aeroDelta.y/fElapsedTime,aeroDelta.z/fElapsedTime};
3399 orbitActuation.aeroSampleTime=pitchBus.ProgramTime;
3400 }
3401
3402 // Velocity local to ship orientation section -----------------------------------------------
3403
3404 } // MSL=-1 contained in identity because altitude is not yet determined
3405 else
3407 }
3408 else
3409 {
3411 }
3412 // Atmospheric functions ************************************************************************
3413#pragma endregion
3414
3415 //float mag = RiseMath::Vec3Length(&viewscreen->sumofforces);
3416 //if (mag > 0.002f)
3417 //{
3418 // viewscreen->DumpSofTracking();
3419 //}
3420
3421 if (playerships[0].reference == REF_INANOTHER)
3422 {
3423 logger->AddToCallStack("SumOfForcesInAnotherVessel");
3424
3428 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f parent",
3429 playerships[playerships[0].inarray].acc.x,
3432 viewscreen->sofTracking.emplace_back(msg);
3433
3434 // CalculateAGLd also refreshes the moving and street map position within the current terrain tile.
3435 // Keep that position current while contained without applying ground or leveling physics.
3437 {
3440 }
3441 }
3442 else
3443 {
3444 logger->AddToCallStack("AddSumOfForcesToVel");
3445#pragma region debug
3446 // ok, this is the exciting part... need to add sumofforces to velocity
3447 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
3448 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
3449 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
3450 {
3451 sprintf_s(msg, sizeof(msg), "ET: %f", fElapsedTime);
3453 sprintf_s(msg, sizeof(msg), "sumofforces I: %f", viewscreen->sumofforces.x);
3455 sprintf_s(msg, sizeof(msg), "sumofforces J: %f", viewscreen->sumofforces.y);
3457 sprintf_s(msg, sizeof(msg), "sumofforces K: %f", viewscreen->sumofforces.z);
3459 sprintf_s(msg, sizeof(msg), "velocity I: %f", localVelocity.x);
3461 sprintf_s(msg, sizeof(msg), "velocity J: %f", localVelocity.y);
3463 sprintf_s(msg, sizeof(msg), "velocity K: %f", localVelocity.z);
3466 sprintf_s(msg, sizeof(msg), "Trapped a violation before sumofforces application...");
3468 }
3469#pragma endregion
3470
3472
3473 // put velocity back into universe terms, keep sumofforces in local terms
3474 RiseMath::Vec3TransformNormal(&playerships[0].velocity, &localVelocity, &playerships[0].matrixWorld); // Velocity local back to ship orientation
3475 if (playerships[0].reference >= REF_DOCKENUMCPOC)
3476 {
3477 Tdockingvel += viewscreen->sumofforces;
3478 RiseMath::Vec3TransformNormal(&playerships[0].dockingvel, &Tdockingvel, &playerships[0].matrixWorld); // Velocity local to ship orientation Tdockingvel.z+=f_temp*fElapsedTime;
3479 }
3480
3481 if (playerships[0].velocity.x > 100.0f || playerships[0].velocity.x < -100.0f || _isnan(playerships[0].velocity.x) || isinf(playerships[0].velocity.x) ||
3482 playerships[0].velocity.y > 100.0f || playerships[0].velocity.y < -100.0f || _isnan(playerships[0].velocity.y) || isinf(playerships[0].velocity.y) ||
3483 playerships[0].velocity.z > 100.0f || playerships[0].velocity.z < -100.0f || _isnan(playerships[0].velocity.z) || isinf(playerships[0].velocity.z))
3484 {
3485 sprintf_s(msg, sizeof(msg), "ET: %f", fElapsedTime);
3487 sprintf_s(msg, sizeof(msg), "universe I: %f", playerships[0].velocity.x);
3489 sprintf_s(msg, sizeof(msg), "universe J: %f", playerships[0].velocity.y);
3491 sprintf_s(msg, sizeof(msg), "universe K: %f", playerships[0].velocity.z);
3493 sprintf_s(msg, sizeof(msg), "local I: %f", localVelocity.x);
3495 sprintf_s(msg, sizeof(msg), "local J: %f", localVelocity.y);
3497 sprintf_s(msg, sizeof(msg), "local K: %f", localVelocity.z);
3499 sprintf_s(msg, sizeof(msg), "Trapped a violation after putting velocity in universe terms...");
3501 }
3502
3503
3504
3505
3506
3507 // Always needed for our altitude BCL
3509 {
3510 //logger->AddToCallStack("Viewscreen::Movement BCL");
3511
3512 // this can't be using proposed position because the map may not have shifted yet
3513 // this one is smoother and supports remote assay
3515 // over a seam, not shifted to next plate terpos yet?
3516 if (f_temp != -1.0f)
3517 f_AGL = f_temp;
3518
3519 // f_AGL is the CG height ... if we get within bounding sphere of ground we can do additional checks
3520 float f_AGLeye = f_AGL;
3521 if (f_AGL < playerships[0].bound)
3522 {
3523 RiseMath::Vector3 eyeWorldPos;
3524 RiseMath::Vec3TransformCoord(&eyeWorldPos, &viewscreen->cockpitCamera->position, &playerships[0].matrixWorld); // matrixWorld is just the inverse orientation
3525 const float eyeAGL = viewscreen->CalculateAGLd(viewscreen->terpos, viewscreen->terprecisionx, viewscreen->terprecisiony, viewscreen->terprecisionz, playerships[0].precisionx + eyeWorldPos.x, playerships[0].precisiony + eyeWorldPos.y, playerships[0].precisionz + eyeWorldPos.z, playerships[0].position + eyeWorldPos, false);
3526 if (eyeAGL != -1.0f)
3527 {
3528 f_AGLeye = eyeAGL - 0.0007f;
3529 viewscreen->gameclass->bus->DebugAglEye = f_AGLeye;
3530 }
3531 else
3532 viewscreen->gameclass->bus->DebugAglEye = eyeAGL;
3533 }
3534 else
3536
3537
3538
3539 // Things that use this like GPWS would be calibrated at ZERO when the struts are on the ground right-side up
3543
3544
3545 // leveling
3546 if (fabsf(viewscreen->leveler.x) > 0.0f || fabsf(viewscreen->leveler.y) > 0.0f || fabsf(viewscreen->leveler.z) > 0.0f)
3547 {
3548 RiseMath::Matrix matrixInverse;
3549 RiseMath::MatrixInverse(&matrixInverse, nullptr, &playerships[0].matrixWorld);
3550 RiseMath::Vec3TransformNormal(&cross, &viewscreen->leveler, &matrixInverse);
3551
3552 if (fabsf(cross.y) > FLT_EPSILON)
3553 {
3554 if (cross.y > 0.0f) // Right-side up
3555 levelerroll = -atanf(cross.x / cross.y);
3556 else if (cross.x < 0.0f)
3557 levelerroll = RiseMath::Pi - atanf(cross.x / cross.y);
3558 else
3559 levelerroll = -RiseMath::Pi - atanf(cross.x / cross.y);
3560 levelerpitch = atanf(cross.z / sqrtf(cross.y * cross.y + cross.x * cross.x));
3561 }
3562 else
3563 levelerroll = levelerpitch = 0.0f;
3564 if (cross.y > 0.0f && playerships[0].geardown) // right-side up
3565 {
3566 if (ourcockpit.vdat.noseStrut == 0)
3567 levelerpitch += 0.25f;
3568 if (ourcockpit.vdat.leftStrut == 0)
3569 levelerroll += 0.25f;
3570 if (ourcockpit.vdat.rightStrut == 0)
3571 levelerroll -= 0.25f;
3572 }
3573 if (cross.y > 0.0f && playerships[0].groundvehicle && playerships[0].reference == REF_ONGROUND)
3574 {
3577 }
3578 }
3579 else
3580 {
3581 levelerroll = levelerpitch = 0.0f;
3582 // sprintf_s(msg, sizeof(msg), "-*- Trapped a leveler issue...");
3583 // _write(logfile, msg, strlen(msg));
3584 }
3585
3586
3587 // so our CG is 0.000535 above the grade
3588 // our struttoret is 0.000535
3589 // that means we are 0 above
3590
3591 float f_AGLcg = f_AGL;
3592 if (fabsf(levelerroll) > 1.5708f) // upside down
3593 f_AGLcg -= ourcockpit.rooftoCGKm;
3594 else
3595 f_AGLcg -= ourcockpit.strutsrettoCGKm +
3597
3598 const float finalAglKm = RiseMath::Min(f_AGLcg, f_AGLeye) - citystuff.elevation - citystuff.curbelev;
3599 // Test the authored lamp mounts before terrain response lifts/levels
3600 // the vehicle. Positions/velocities in propulsion have the opposite
3601 // sign to exterior rendering coordinates.
3602 if (f_AGL < playerships[0].bound && playerships[0].reference < REF_INANOTHER &&
3603 gridarray[31][31].pri_landform != 1 && gridarray[31][31].pri_landform != 2 && gridarray[31][31].pri_landform != 3)
3604 {
3605 RiseMath::Vector3 normalBody;
3606 RiseMath::Vec3TransformNormal(&normalBody, &viewscreen->leveler, &matrixInverse);
3608 localBarycentric - localVelocity, "ground");
3609 }
3610
3611 // Determine whether our acceleration vector takes us up or down
3612 RiseMath::Vector3 sumOfForcesNormal;
3613 RiseMath::Vec3Normalize(&sumOfForcesNormal, &viewscreen->sumofforces);
3614
3615 // portion of our thrust that is in direction of gravity
3616 RiseMath::Vector3 locgrav;
3618
3619 // 1.0f means that overall acceleration is away from Vieneo CM
3620 const float cmDot = RiseMath::Vec3Dot(&locgrav, &sumOfForcesNormal);
3621 //game->gameclass->bus->DebugFloat = cmDot;
3622
3623 // Touchdown ... say I am 50 feet off ground and structure is 50 feet tall then we are on structure
3624 // say I am 40 and structure is 50 then we will reposition to 50
3625 // so I am 50.0002 and structure is 50 ... 40-50 is <0 50.0002 - 50 is 0.0002
3627 bool touchdown = false;
3628 if (finalAglKm < -0.000025f && playerships[0].reference < REF_INANOTHER)//&& cmDot <= 0.0f)
3629 {
3630 //sprintf_s(msg, sizeof msg, "Movement snapping us back to 0 as we were at %.4f,%.4f (%.4f) %.4f", f_AGLcg, f_AGLeye, citystuff.elevation, finalAglKm);
3631 //logger->Log(msg);
3632 //
3633 // interpolate to tempaltitude above radius
3634 const float target = -finalAglKm;
3635 double gx = playerships[0].precisionx;
3636 double gy = playerships[0].precisiony;
3637 double gz = playerships[0].precisionz;
3638 const double mag = 1.0 / sqrt(gx * gx + gy * gy + gz * gz);
3639 // Normalized
3640 gx *= mag; gy *= mag; gz *= mag;
3641 gx *= static_cast<double>(target); gy *= static_cast<double>(target); gz *= static_cast<double>(target);
3642 playerships[0].precisionx += gx;
3643 playerships[0].precisiony += gy;
3644 playerships[0].precisionz += gz;
3645
3647 {
3648 // Placing a teleported vehicle on newly loaded terrain is not
3649 // an impact. Keep the separate touchdown/contact velocity forces.
3650 if (target > 0.01f)
3651 {
3652 sprintf_s(msg, sizeof msg, "REPOSITION terrain placement %.6f km; positional correction excluded from G forces", target);
3653 logger->Log(msg);
3654 }
3655 }
3656 else
3657 {
3658 RiseMath::Vector3 impactSof(static_cast<float>(gx), static_cast<float>(gy), static_cast<float>(gz));
3659 RiseMath::Vec3TransformNormal(&impactSof, &impactSof, &matrixInverse);
3660 if (fElapsedTime != 0.0f)
3661 {
3662 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f ground", impactSof.x * oneOvergForceKmssC / fElapsedTime, impactSof.y * oneOvergForceKmssC / fElapsedTime, impactSof.z * oneOvergForceKmssC / fElapsedTime);
3663 viewscreen->sofTracking.emplace_back(msg);
3664 }
3665 viewscreen->sumofforces += impactSof;
3666 }
3667
3668 if (citystuff.elevation == 0.0f)
3669 {
3671 if (gridarray[31][31].pri_landform == 1) // water
3673 else
3675 }
3676 else
3678
3679 if (playerships[0].reference != REF_ONGROUND)
3680 {
3682 touchdown = true;
3683
3684 if (viewscreen->causechain == 9) // water
3685 {
3686 logger->Log("Viewscreen::Movement Splashdown!");
3687 if (rand() < 16384)
3689 else
3691 }
3692 else
3693 {
3694 logger->Log("Viewscreen::Movement Touchdown!");
3696 }
3697
3698 // ReSharper disable once CppExpressionWithoutSideEffects
3700 // ReSharper disable once CppExpressionWithoutSideEffects
3702
3707
3708
3709 // The cabin announcement manager qualifies the flight and waits for a stable,
3710 // idle-thrust touchdown before accepting the landing announcement.
3712 }
3713 }
3714 else if ((finalAglKm > 0.000025f || cmDot > 0.0f) && playerships[0].reference == REF_ONGROUND) // i am 50 and structure is 40 then 10
3715 {
3716 // this is what should allow us to become airborne again if we roll of the top of a building
3717 // so say if it is within 0.000025 then we can snap otherwise we need to become airborne again
3718 // 0.0001524 is a standard curb
3719 if (finalAglKm > 0.0001524f || cmDot > 0.0f)
3720 {
3721 sprintf_s(msg, sizeof msg, "Movement releasing us to APN mode... we were at %.4f,%.4f (%.4f) %.4f", f_AGLcg, f_AGLeye, citystuff.elevation, finalAglKm);
3722 logger->Log(msg);
3723
3725
3726 //logger->Log("FRICTION Doesn't think he is on the ground!");
3732 tireSkidSoundWasActive = false;
3733
3734 holdOverTime = 0; // reset anti-ice benefit once airborne
3735 }
3736 else
3737 {
3738 // so this is the issue ... if we somehow diverge from the ground we need to be snapped back to the ground
3739 sprintf_s(msg, sizeof msg, "Movement snapping us back to 0 as we were at %.4f,%.4f (%.4f) %.4f", f_AGLcg, f_AGLeye, citystuff.elevation, finalAglKm);
3740 logger->Log(msg);
3741 // interpolate to tempaltitude above radius
3742 const float target = -finalAglKm;
3743 double gx = playerships[0].precisionx;
3744 double gy = playerships[0].precisiony;
3745 double gz = playerships[0].precisionz;
3746 const double mag = 1.0 / sqrt(gx * gx + gy * gy + gz * gz);
3747 gx *= mag; gy *= mag; gz *= mag;
3748 gx *= static_cast<double>(target); gy *= static_cast<double>(target); gz *= static_cast<double>(target);
3749 playerships[0].precisionx += gx;
3750 playerships[0].precisiony += gy;
3751 playerships[0].precisionz += gz;
3752 //playerships[0].position += gthrust * target;
3753 }
3754 }
3755
3756 if (playerships[0].reference == REF_ONGROUND && totalWeightLbs > 0)
3757 {
3758 // Spring-driven body roll/pitch crosses the leveling target during ordinary
3759 // driving. It is not a new wheel impact; touchdown/curb sounds handle impacts.
3760 const bool playLevelingContactSound =
3762 static float oldlevelerroll = 0.0f, oldlevelerpitch = 0.0f;
3763 f_temp = fElapsedTime * sqrtf(277581.7f / totalWeightLbs) * 0.2f;
3764 if (levelerroll > 0.001f && levelerroll < (RiseMath::HalfPi - 0.001f))
3765 {
3766 playerships[0].rollRadPerSec -= cosf(levelerroll) * f_temp;
3767 }
3769 {
3770 playerships[0].rollRadPerSec += cosf(levelerroll) * f_temp;
3771 }
3772 else if (levelerroll > (RiseMath::HalfPi + 0.001f) && levelerroll < (RiseMath::Pi - 0.001f))
3773 {
3774 playerships[0].rollRadPerSec -= cosf(levelerroll) * f_temp;
3775 }
3776 else if (levelerroll<(-RiseMath::HalfPi - 0.001f) && levelerroll>(-RiseMath::Pi + 0.001f))
3777 {
3778 playerships[0].rollRadPerSec += cosf(levelerroll) * f_temp;
3779 }
3780 else
3781 playerships[0].rollRadPerSec *= 0.6f * f_temp;
3782
3783 f_temp = fElapsedTime * sqrtf(277581.7f / totalWeightLbs) * 0.15f;
3784 if (fabsf(levelerroll) < RiseMath::HalfPi)
3785 {
3786 if (levelerpitch > 0.001f && levelerpitch <= RiseMath::HalfPi)
3787 {
3788 playerships[0].pitch -= cosf(levelerpitch) * f_temp;
3789 }
3791 {
3792 playerships[0].pitch += cosf(levelerpitch) * f_temp;
3793 }
3794 else
3795 playerships[0].pitch *= 0.5f * f_temp;
3797 }
3798 else // Upside-down
3799 {
3800 if (levelerpitch > 0.001f && levelerpitch <= RiseMath::HalfPi)
3801 {
3802 playerships[0].pitch += cosf(levelerpitch) * f_temp;
3803 }
3805 {
3806 playerships[0].pitch -= cosf(levelerpitch) * f_temp;
3807 }
3808 else
3809 playerships[0].pitch *= 0.5f * f_temp;
3811 }
3812
3813 if (fabsf(levelerroll) < RiseMath::HalfPi)
3814 {
3815 if ((levelerroll > 0.001f && oldlevelerroll < 0.001f) ||
3817 {
3818 playerships[0].rollRadPerSec *= 0.6f * f_temp; // kill the momentum
3819 if (playLevelingContactSound && fabsf(playerships[0].rollRadPerSec) > FLT_EPSILON &&
3820 gridarray[31][31].pri_landform != 1 && gridarray[31][31].pri_landform != 2 && gridarray[31][31].pri_landform != 3) // not water
3821 {
3822 logger->Log("Viewscreen::Movement Leveling roll...");
3824 }
3825 }
3826 }
3827 else // upside down
3828 {
3829 if ((levelerroll < 0.0f && oldlevelerroll > 0.0f) || (levelerroll > 0.0f && oldlevelerroll < 0.0f))
3830 playerships[0].rollRadPerSec *= 0.6f * f_temp;
3831 }
3832
3833 if ((levelerpitch > 0.0f && oldlevelerpitch < 0.0f) || (levelerpitch < 0.0f && oldlevelerpitch > 0.0f))
3834 {
3835 playerships[0].pitch *= 0.5f * f_temp;
3836
3837 if (playLevelingContactSound && fabsf(playerships[0].pitch) > FLT_EPSILON &&
3838 gridarray[31][31].pri_landform != 1 && gridarray[31][31].pri_landform != 2 && gridarray[31][31].pri_landform != 3) // not water
3839 {
3840 logger->Log("Viewscreen::Movement Leveling pitch...");
3842 }
3843 }
3844 oldlevelerroll = levelerroll; oldlevelerpitch = levelerpitch;
3845
3846
3847 // not the steering but the arresting of yaw on the ground
3848 if (!(playerships[0].groundvehicle || ourcockpit.wheeled) || fabsf(levelerroll) > 0.9f)
3849 playerships[0].yawRadPerSec *= 0.001f * f_temp; // friction with the surface, not auto-centering because it doesn't touch viewscreen->yaw
3850 }
3851
3852
3853 // Handle on the ground stuff
3854 if (playerships[0].reference == REF_ONGROUND)
3855 {
3856 RiseMath::Vector3 loclev;
3857 RiseMath::Vec3TransformNormal(&loclev, &viewscreen->leveler, &matrixInverse);
3858
3859 // sprintf_s(msg, sizeof(msg), "on ground, loclev %+.3f %+.3f %+.3f normsum %+.3f %+.3f %+.3f", loclev.x, loclev.y, loclev.z, normsum.x, normsum.y, normsum.z );
3860 // _write(logfile, msg, strlen(msg));
3861
3862 RiseMath::Vector3 locvel = localVelocity - localBarycentric;
3863 RiseMath::Vec3Normalize(&cross, &locvel);
3864 const float surfaceDot = RiseMath::Vec3Dot(&cross, &loclev);
3865
3866 RiseMath::Vector3 gravport; // has to be done BEFORE we block the force down with the terrain plate
3867 gravport.x = viewscreen->sumofforces.x * locgrav.x;
3868 gravport.y = viewscreen->sumofforces.y * locgrav.y;
3869 gravport.z = viewscreen->sumofforces.z * locgrav.z;
3870
3871 // Portion that is perpendicular to the terrain plate
3872 cross.x = 0.0f;// locvel.x*fabsf(loclev.x);
3873 cross.y = locvel.y * fabsf(loclev.y);
3874 cross.z = 0.0f;// locvel.z*fabsf(loclev.z);
3875
3876 float leftMain = 0.0f, rightMain = 0.0f, noseStrut = 0.0f;
3877 bool gldDeploy = false;
3878
3879 if (surfaceDot < 0.0f && fElapsedTime != 0.0f) // into the ground WOW
3880 {
3881 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f touchdown", -cross.x * oneOvergForceKmssC / fElapsedTime, -cross.y * oneOvergForceKmssC / fElapsedTime, -cross.z * oneOvergForceKmssC / fElapsedTime);
3882 viewscreen->sofTracking.emplace_back(msg);
3883
3884 locvel -= cross;
3885 viewscreen->sumofforces -= cross; // in km/s
3886
3887 // need to research how shocks actually work
3888 float shockKmss = -cross.y / fElapsedTime;
3889 if (shockKmss > gravityKmssC)
3890 {
3891 // @todo tried to comment out 10/5/2021 but bill talked me out of it
3892 // if i hold a plane an inch off the ground and then drop it it will compress the shocks
3893 shockKmss -= gravityKmssC; // might be 0-50m/s above 1G
3894 float shockKms = shockKmss * fElapsedTime;
3895
3896 // 10fps or 3m/s touchdown on mains is some kind of FAA standard
3897
3898 float absorbKms = 0.0f;
3899 if (!playerships[0].groundvehicle && ourcockpit.struts > 0)
3900 {
3901 float absorbCapacityKms = ourcockpit.landingGearAbsorbKms;
3902 absorbCapacityKms *= ourcockpit.gearextent; // length is restricted
3903
3904 if (ourcockpit.vdat.leftStrut > 0)
3905 {
3906 leftMain = 1.0f;
3909 {
3910 // pitch should be between -3 and +30 or tail strike
3912 leftMain = 0.0f;
3913 }
3914 else
3915 {
3916 // pitch should be between 3 and -30 or nose strike
3917 if (levelerpitch > 0.05f || levelerpitch < -0.5f)
3918 leftMain = 0.0f;
3919 }
3920 // roll should be between 3 and -30 or wing strike
3921 if (levelerroll > 0.05f || levelerroll < -0.5f)
3922 leftMain = 0.0f;
3923 if (playerships[0].geardown)
3924 leftMain *= ourcockpit.vdat.leftStrut / 127.0f;
3925 absorbKms += leftMain * absorbCapacityKms;
3926
3927 if (touchdown)
3928 {
3929 sprintf_s(msg, sizeof(msg), "*** Left Main absorbed %.3f (%.3f/s) %.3fG, levelerpitch %.3f levelerroll %.3f", leftMain * absorbCapacityKms, leftMain * absorbCapacityKms / fElapsedTime, leftMain * absorbCapacityKms * oneOvergForceKmssC, levelerpitch, levelerroll);
3930 logger->Log(msg);
3931 }
3932 }
3933 if (ourcockpit.vdat.rightStrut > 0)
3934 {
3935 rightMain = 1.0f;
3938 {
3939 // pitch should be between -3 and +30 or tail strike
3941 rightMain = 0.0f;
3942 }
3943 else
3944 {
3945 // pitch should be between 3 and -30 or nose strike
3946 if (levelerpitch > 0.05f || levelerpitch < -0.5f)
3947 rightMain = 0.0f;
3948 }
3949 // roll should be between -3 and 30 or wing strike
3951 rightMain = 0.0f;
3952 if (playerships[0].geardown)
3953 rightMain *= ourcockpit.vdat.rightStrut / 127.0f;
3954 absorbKms += rightMain * absorbCapacityKms;
3955
3956 if (touchdown)
3957 {
3958 sprintf_s(msg, sizeof(msg), "*** Right Main absorbed %.3f/f (%.3f/s) %.3fG, levelerpitch %.3f levelerroll %.3f", rightMain * absorbCapacityKms, rightMain * absorbCapacityKms / fElapsedTime, rightMain * absorbCapacityKms * oneOvergForceKmssC, levelerpitch, levelerroll);
3959 logger->Log(msg);
3960 }
3961 }
3962 if (ourcockpit.vdat.noseStrut > 0)
3963 {
3964 noseStrut = 1.0f;
3967 {
3968 // pitch should be less than +3 degrees
3969 if (levelerpitch > 0.05f)
3970 noseStrut = 0.0f;
3971 }
3972 else
3973 {
3974 // pitch should be less than +3 degrees
3975 if (levelerpitch < -0.05f)
3976 noseStrut = 0.0f;
3977 }
3978 // wings must be level unless we are pitching down a lot
3979 if (fabsf(levelerroll) > fabsf(levelerpitch))
3980 noseStrut = 0.0f;
3981 if (playerships[0].geardown)
3982 noseStrut *= ourcockpit.vdat.noseStrut / 127.0f;
3983 absorbKms += noseStrut * absorbCapacityKms;
3984
3985 if (touchdown)
3986 {
3987 sprintf_s(msg, sizeof(msg), "*** Nose gear absorbed %.3f/f (%.3f/s) %.3fG, levelerpitch %.3f", noseStrut * absorbCapacityKms, noseStrut * absorbCapacityKms / fElapsedTime, noseStrut * absorbCapacityKms * oneOvergForceKmssC, levelerpitch);
3988 logger->Log(msg);
3989 }
3990 }
3991 }
3992 else if (playerships[0].groundvehicle)
3993 {
3994 const float bumpTravelKm = viewscreen->GetAverageSuspensionBumpTravelKm();
3995 const float compliantTravelKm = bumpTravelKm + ourcockpit.tireComplianceKm;
3996 const float verticalDisplacementKm = (shockKms * shockKms) / (2.0f * gravityKmssC);
3997 const float absorbedRatio = verticalDisplacementKm > FLT_EPSILON
3998 ? RiseMath::Min(1.0f, compliantTravelKm / verticalDisplacementKm)
3999 : 1.0f;
4000 absorbKms = shockKms * absorbedRatio;
4001 const float suspensionShare = compliantTravelKm > FLT_EPSILON
4002 ? bumpTravelKm / compliantTravelKm
4003 : 0.0f;
4004 viewscreen->ApplySuspensionImpact(shockKms * absorbedRatio * suspensionShare);
4005 }
4006
4007 if (absorbKms > shockKms)
4008 absorbKms = shockKms; // can't absorb more than what is presented
4009
4010 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f struts", 0.0f, -absorbKms * oneOvergForceKmssC / fElapsedTime, 0.0f);
4011 viewscreen->sofTracking.emplace_back(msg);
4012
4013 viewscreen->sumofforces.y -= absorbKms;
4014 // Only the unabsorbed touchdown shock is an impact. The
4015 // gravity/support impulse grows with dt even while parked.
4016 if (!playerships[0].isSimulator)
4017 viewscreen->structuralImpactImpulse.y += shockKms - absorbKms;
4018
4019 if (touchdown)
4020 {
4021 sprintf_s(msg, sizeof(msg), "*** TD force was %.3f/f (%.3f/s) %.3fG, absorbed %.3f/f (%.3f/s) %.3fG", -cross.y, -cross.y / fElapsedTime, -cross.y * oneOvergForceKmssC, absorbKms, absorbKms / fElapsedTime, absorbKms * oneOvergForceKmssC);
4022 logger->Log(msg);
4023
4024
4025 float remainingG = (-cross.y - absorbKms) * oneOvergForceKmssC;
4026
4027 sprintf_s(msg, sizeof(msg), "*** Remaining force was %.3fG", remainingG);
4028 logger->Log(msg);
4029
4030 if (remainingG * noseStrut > 0.333f)
4031 {
4033 ourcockpit.vdatChanged = true;
4034 // too much on nose, has collapsed at 0.5 in reality
4035 logger->Log("Collapsed nose strut!", Logger::Level::Warn);
4036 }
4037 if (remainingG * leftMain > 0.5f)
4038 {
4040 ourcockpit.vdatChanged = true;
4041 // too much on leftMain
4042 logger->Log("Collapsed left main strut!", Logger::Level::Warn);
4043 }
4044 if (remainingG * rightMain > 0.5f)
4045 {
4047 ourcockpit.vdatChanged = true;
4048 // too much on rightMain
4049 logger->Log("Collapsed right main strut!", Logger::Level::Warn);
4050 }
4051 }
4052 }
4053
4054 RiseMath::Vec3TransformNormal(&cross, &cross, &playerships[0].matrixWorld);
4055 RiseMath::Vec3Subtract(&playerships[0].velocity, &playerships[0].velocity, &cross);
4056
4057
4058#pragma region Ground Friction
4059
4060 logger->AddToCallStack("GroundFriction");
4061
4062 // locvel is in kms ... diff of vel and bary
4063 if (_isnan(locvel.x) || _isnan(locvel.y) || _isnan(locvel.z) ||
4064 isinf(locvel.x) || isinf(locvel.y) || isinf(locvel.z))
4065 {
4066 logger->Log("Skipping ground friction, locvel had NAN components!", Logger::Level::Debug);
4067 }
4068 else if (fElapsedTime != 0.0f)
4069 {
4070 RiseMath::Vector3 newlocvel = cross = locvel;
4071
4072 auto IsBadFloat = [](float v) -> bool
4073 {
4074 return _isnan(v) || isinf(v);
4075 };
4076
4077 auto ClampFloat = [](float v, float lo, float hi) -> float
4078 {
4079 if (v < lo)
4080 return lo;
4081 if (v > hi)
4082 return hi;
4083 return v;
4084 };
4085
4086 auto ApproachZero = [](float value, float amount) -> float
4087 {
4088 if (amount <= 0.0f)
4089 return value;
4090
4091 if (value > 0.0f)
4092 {
4093 value -= amount;
4094 return value < 0.0f ? 0.0f : value;
4095 }
4096
4097 if (value < 0.0f)
4098 {
4099 value += amount;
4100 return value > 0.0f ? 0.0f : value;
4101 }
4102
4103 return 0.0f;
4104 };
4105
4106 auto Length2D = [](float x, float z) -> float
4107 {
4108 return sqrtf(x * x + z * z);
4109 };
4110
4111 // Downward force.
4112 // gndcontactG is the local normal force proxy in Vieneo-G units.
4113 if (cmDot < 0.0f)
4114 gndcontactG = RiseMath::Vec3Length(&gravport) / fElapsedTime / gravityKmssC;
4115 else
4116 gndcontactG = 0.0f;
4117
4118 if (IsBadFloat(gndcontactG) || gndcontactG < 0.0f)
4119 {
4120 logger->Log("gndcontactG was invalid", Logger::Error);
4121 gndcontactG = 0.0f;
4122 }
4123
4124 // Surface model.
4125 // Crr is unitless rolling resistance: 0.02 is 2%, roughly 2% effective grade.
4126 // The roughness jitter coefficient is not IRI; it perturbs local grip/rolling loss.
4127 float muStatic = 0.60f;
4128 float muKinetic = 0.45f;
4129 float rollingResistanceCrr = 0.025f;
4130 float terrainRoughnessJitterCoef = 0.005f;
4131
4133 {
4134 if (viewscreen->ptrWeather->GetPrecip() > 5.0f)
4135 {
4136 // Wet pavement.
4137 muStatic = 0.65f;
4138 muKinetic = 0.50f;
4139 rollingResistanceCrr = 0.017f;
4140 terrainRoughnessJitterCoef = 0.005f;
4141 }
4142 else
4143 {
4144 // Dry pavement.
4145 muStatic = 1.00f;
4146 muKinetic = 0.75f;
4147 rollingResistanceCrr = 0.014f;
4148 terrainRoughnessJitterCoef = 0.001f;
4149 }
4150 }
4151 else
4152 {
4153 // Off-road default. Terrain-specific code below can adjust Crr and roughness jitter.
4154 muStatic = 0.60f;
4155 muKinetic = 0.45f;
4156 rollingResistanceCrr = 0.0f;
4157 terrainRoughnessJitterCoef = 0.0f;
4158
4159 GetTerrainRollingCoefficients(gridarray[31][31].pri_landform, &rollingResistanceCrr, &terrainRoughnessJitterCoef);
4160
4161 if (gridarray[31][31].pri_transition)
4162 {
4163 GetTerrainRollingCoefficients(gridarray[31][31].sec_landform, &rollingResistanceCrr, &terrainRoughnessJitterCoef);
4164
4165 if (gridarray[31][31].sec_transition)
4166 {
4167 GetTerrainRollingCoefficients(gridarray[31][31].ter_landform, &rollingResistanceCrr, &terrainRoughnessJitterCoef);
4168 rollingResistanceCrr /= 3.0f;
4169 terrainRoughnessJitterCoef /= 3.0f;
4170 }
4171 else
4172 {
4173 rollingResistanceCrr *= 0.5f;
4174 terrainRoughnessJitterCoef *= 0.5f;
4175 }
4176 }
4177
4178 // If your terrain coefficients come back as zero, keep a sane off-road fallback.
4179 if (rollingResistanceCrr <= 0.0f)
4180 rollingResistanceCrr = 0.025f;
4181
4182 // Optionally map high rolling terrain to lower tire grip.
4183 // This is intentionally conservative; tune per landform later if desired.
4184 if (rollingResistanceCrr >= 0.060f)
4185 {
4186 muStatic = 0.35f;
4187 muKinetic = 0.30f;
4188 }
4189 else if (rollingResistanceCrr >= 0.035f)
4190 {
4191 muStatic = 0.50f;
4192 muKinetic = 0.40f;
4193 }
4194 }
4195
4196 if (IsBadFloat(rollingResistanceCrr))
4197 {
4198 rollingResistanceCrr = 0.025f;
4199 logger->Log("rollingResistanceCrr was NAN", Logger::Error);
4200 }
4201
4202 if (IsBadFloat(terrainRoughnessJitterCoef))
4203 {
4204 terrainRoughnessJitterCoef = 0.0f;
4205 logger->Log("terrainRoughnessJitterCoef was NAN", Logger::Error);
4206 }
4207
4208 if (IsBadFloat(muStatic))
4209 {
4210 muStatic = 0.60f;
4211 logger->Log("muStatic was NAN", Logger::Error);
4212 }
4213
4214 if (IsBadFloat(muKinetic))
4215 {
4216 muKinetic = 0.45f;
4217 logger->Log("muKinetic was NAN", Logger::Error);
4218 }
4219
4220 // Keep coefficients physically meaningful.
4221 // Put gameplay exaggeration here instead of multiplying coefficients by 75.
4222 const float GAME_ROLLING_RESISTANCE_SCALE = 1.0f;
4223 const float GAME_ROUGHNESS_JITTER_SCALE = 1.0f;
4224 const float GAME_SLIDING_FRICTION_SCALE = 1.0f;
4225 const float BRAKE_POWER_SCALE = 1.5f;
4226
4227 rollingResistanceCrr *= GAME_ROLLING_RESISTANCE_SCALE;
4228 terrainRoughnessJitterCoef *= GAME_ROUGHNESS_JITTER_SCALE;
4229
4230 rollingResistanceCrr = ClampFloat(rollingResistanceCrr, 0.0f, 0.250f);
4231 terrainRoughnessJitterCoef = ClampFloat(terrainRoughnessJitterCoef, 0.0f, 0.250f);
4232 muStatic = ClampFloat(muStatic, 0.0f, 2.0f);
4233 muKinetic = ClampFloat(muKinetic, 0.0f, 2.0f);
4234
4235 // IRI is a road-profile roughness metric in m/km. This is not IRI; it is
4236 // a terrain-driven coefficient jitter that varies local friction over distance.
4237 static float targetRoughnessFrictionJitter = 0.0f;
4238
4239 if (terrainRoughnessJitterCoef <= 0.0f)
4240 {
4241 targetRoughnessFrictionJitter = 0.0f;
4243 }
4244 else
4245 {
4246 float diff = targetRoughnessFrictionJitter - terrainRoughnessFrictionJitter;
4247
4248 if (fabsf(diff) < 0.0001f)
4249 {
4250 targetRoughnessFrictionJitter = RandomFloat() * terrainRoughnessJitterCoef * 2.0f;
4251 diff = targetRoughnessFrictionJitter - terrainRoughnessFrictionJitter;
4252 }
4253
4254 if (IsBadFloat(targetRoughnessFrictionJitter))
4255 {
4256 targetRoughnessFrictionJitter = 0.0f;
4257 logger->Log("targetRoughnessFrictionJitter was NAN", Logger::Error);
4258 }
4259
4260 if (IsBadFloat(diff))
4261 {
4262 diff = 0.0f;
4263 logger->Log("diff was NAN", Logger::Error);
4264 }
4265
4266 if (IsBadFloat(terrainRoughnessFrictionJitter) || fabsf(terrainRoughnessFrictionJitter) > 10.0f)
4267 {
4268 sprintf_s(msg, sizeof(msg), "groundSpeedKms: %f", groundSpeedKms);
4270 sprintf_s(msg, sizeof(msg), "diff: %f", diff);
4272 sprintf_s(msg, sizeof(msg), "fElapsedTime: %f", fElapsedTime);
4274 sprintf_s(msg, sizeof(msg), "terrainRoughnessFrictionJitter was %f before +=", terrainRoughnessFrictionJitter);
4277 }
4278
4279 terrainRoughnessFrictionJitter += diff * fElapsedTime * fabsf(groundSpeedKms) * 300.0f;
4280
4281 if (IsBadFloat(terrainRoughnessFrictionJitter) || fabsf(terrainRoughnessFrictionJitter) > 10.0f)
4282 {
4283 sprintf_s(msg, sizeof(msg), "groundSpeedKms: %f", groundSpeedKms);
4285 sprintf_s(msg, sizeof(msg), "diff: %f", diff);
4287 sprintf_s(msg, sizeof(msg), "fElapsedTime: %f", fElapsedTime);
4289 sprintf_s(msg, sizeof(msg), "terrainRoughnessFrictionJitter was %f after +=", terrainRoughnessFrictionJitter);
4292 }
4293
4294 terrainRoughnessFrictionJitter = ClampFloat(terrainRoughnessFrictionJitter, 0.0f, terrainRoughnessJitterCoef * 2.0f);
4295 }
4296
4297 if (IsBadFloat(groundSpeedKms))
4298 {
4299 groundSpeedKms = 0.0f;
4300 logger->Log("groundSpeedKms was NAN", Logger::Error);
4301 }
4302
4303 const float normalG = fmaxf(gndcontactG, 0.0f);
4304
4305 const float effectiveMuStatic = ClampFloat(muStatic + terrainRoughnessFrictionJitter, 0.0f, 2.5f);
4306 const float effectiveMuKinetic = ClampFloat((muKinetic + terrainRoughnessFrictionJitter) * GAME_SLIDING_FRICTION_SCALE, 0.0f, 2.5f);
4307 const float effectiveRollingResistanceCrr = ClampFloat(rollingResistanceCrr + terrainRoughnessFrictionJitter * 0.10f, 0.0f, 0.300f);
4308 const float startingRollingResistanceCrr = ClampFloat(
4309 effectiveRollingResistanceCrr + terrainRoughnessJitterCoef * (viewscreen->ptrBuildings->g_bRoad ? 0.75f : 3.0f),
4310 effectiveRollingResistanceCrr,
4311 viewscreen->ptrBuildings->g_bRoad ? 0.035f : 0.120f);
4312
4313 float staticDeltaV = effectiveMuStatic * normalG * gravityKmssC * fElapsedTime;
4314 float kineticDeltaV = effectiveMuKinetic * normalG * gravityKmssC * fElapsedTime;
4315 float rollingDeltaV = effectiveRollingResistanceCrr * normalG * gravityKmssC * fElapsedTime;
4316 float startingRollingDeltaV = startingRollingResistanceCrr * normalG * gravityKmssC * fElapsedTime;
4317
4318 if (IsBadFloat(staticDeltaV))
4319 {
4320 staticDeltaV = 0.0f;
4321 logger->Log("staticDeltaV was NAN", Logger::Error);
4322 }
4323
4324 if (IsBadFloat(kineticDeltaV))
4325 {
4326 kineticDeltaV = 0.0f;
4327 logger->Log("kineticDeltaV was NAN", Logger::Error);
4328 }
4329
4330 if (IsBadFloat(rollingDeltaV))
4331 {
4332 rollingDeltaV = 0.0f;
4333 logger->Log("rollingDeltaV was NAN", Logger::Error);
4334 }
4335
4336 if (IsBadFloat(startingRollingDeltaV))
4337 {
4338 startingRollingDeltaV = 0.0f;
4339 logger->Log("startingRollingDeltaV was NAN", Logger::Error);
4340 }
4341
4342 // Cap per-frame friction so it cannot exceed 1 G worth of velocity change unless
4343 // you intentionally raise this for stylized gameplay.
4344 const float maxGroundDeltaV = gravityKmssC * fElapsedTime;
4345
4346 if (staticDeltaV > maxGroundDeltaV)
4347 staticDeltaV = maxGroundDeltaV;
4348
4349 if (kineticDeltaV > maxGroundDeltaV)
4350 kineticDeltaV = maxGroundDeltaV;
4351
4352 // Rolling resistance should be much weaker than sliding friction.
4353 if (rollingDeltaV > maxGroundDeltaV)
4354 rollingDeltaV = maxGroundDeltaV;
4355
4356 if (startingRollingDeltaV > maxGroundDeltaV)
4357 startingRollingDeltaV = maxGroundDeltaV;
4358
4359 bool brakeSkid = false;
4360
4361 // SIDE TO SIDE
4362 // Rolling ground-vehicle tires retain static grip until lateral demand exceeds
4363 // its budget. Always using kinetic friction made pavement behave as if already sliding.
4364 const float oldLateralVelX = newlocvel.x;
4365 const float oldVerticalVelY = newlocvel.y;
4366
4367 const bool groundTiresSupporting = playerships[0].groundvehicle && ourcockpit.wheeled &&
4368 fabsf(levelerroll) < 0.5f && fabsf(levelerpitch) < 0.5f;
4369 newlocvel.x = groundTiresSupporting
4370 ? GroundTireGrip::ResolveLateralVelocity(newlocvel.x, staticDeltaV, kineticDeltaV)
4371 : ApproachZero(newlocvel.x, kineticDeltaV);
4372 const float remainingLateralSlipKms = fabsf(newlocvel.x);
4373
4374 // If the craft is on its side or otherwise contacting terrain, arrest local vertical
4375 // scraping motion with kinetic friction as well.
4376 newlocvel.y = ApproachZero(newlocvel.y, kineticDeltaV);
4377
4378#pragma region Landing Gear Shear Force
4379
4380 // Constants: lateral-per-vertical-g limits for transport-category gear.
4381 // Tune per type if needed.
4382 const float NOSE_SHEAR_LIMIT = 0.35f;
4383 const float MAIN_SHEAR_LIMIT = 0.55f;
4384
4385 // Convertors and guards.
4386 const float vertical_g = fmaxf(gndcontactG, 0.10f);
4387 const float inv_g = oneOvergForceKmssC;
4388
4389 float groundSpeedInstantKms = Length2D(newlocvel.x, newlocvel.z);
4390
4391 // Nose side load from steering curvature: a = v^2 * tan(delta) / wheelbase.
4392 float lateral_g_nose = 0.0f;
4393 if (ourcockpit.wheelBaseKm > 0.0f)
4394 {
4395 lateral_g_nose = fabsf(
4396 groundSpeedInstantKms *
4397 groundSpeedInstantKms *
4398 tanf(playerships[0].steerdeflect * ourcockpit.steerLimitRadian) /
4400 inv_g);
4401 }
4402
4403 if (IsBadFloat(lateral_g_nose))
4404 lateral_g_nose = 0.0f;
4405
4406 // Main gear side load should use lateral acceleration, not lateral velocity.
4407 float lateralDeltaVKms = fabsf(oldLateralVelX - newlocvel.x);
4408 float lateral_g_main = 0.0f;
4409
4410 if (fElapsedTime > 0.0f)
4411 lateral_g_main = lateralDeltaVKms / fElapsedTime * inv_g;
4412
4413 if (IsBadFloat(lateral_g_main))
4414 lateral_g_main = 0.0f;
4415
4416 const float lateral_g_left = lateral_g_main;
4417 const float lateral_g_right = lateral_g_main;
4418
4419 const float nose_shear_ratio = lateral_g_nose / vertical_g;
4420 const float left_shear_ratio = lateral_g_left / vertical_g;
4421 const float right_shear_ratio = lateral_g_right / vertical_g;
4422
4423 const float nose_capacity_limit = NOSE_SHEAR_LIMIT * fmaxf(noseStrut, 0.0f);
4424 const float main_capacity_limitL = MAIN_SHEAR_LIMIT * fmaxf(leftMain, 0.0f);
4425 const float main_capacity_limitR = MAIN_SHEAR_LIMIT * fmaxf(rightMain, 0.0f);
4426
4427 if (nose_capacity_limit > 0.0f && nose_shear_ratio > nose_capacity_limit)
4428 {
4430 ourcockpit.vdatChanged = true;
4431 sprintf_s(msg, sizeof(msg),
4432 "*** Nose gear collapse (side load) def %.3f gs %.3f vlat %.3f vg %.2f rawG %.2f lat_g %.3f ratio %.3f limit %.3f vvel %.3f wb %.3f",
4434 groundSpeedInstantKms,
4435 newlocvel.x,
4436 vertical_g,
4438 lateral_g_nose,
4439 nose_shear_ratio,
4440 nose_capacity_limit,
4441 newlocvel.y,
4444 }
4445
4446 if (main_capacity_limitL > 0.0f && left_shear_ratio > main_capacity_limitL)
4447 {
4449 ourcockpit.vdatChanged = true;
4450 sprintf_s(msg, sizeof(msg),
4451 "*** Left main collapse (side load) vlat %.3f vg %.2f rawG %.2f lat_g %.3f ratio %.3f limit %.3f vvel %.3f",
4452 newlocvel.x,
4453 vertical_g,
4455 lateral_g_left,
4456 left_shear_ratio,
4457 main_capacity_limitL,
4458 newlocvel.y);
4460 }
4461
4462 if (main_capacity_limitR > 0.0f && right_shear_ratio > main_capacity_limitR)
4463 {
4465 ourcockpit.vdatChanged = true;
4466 sprintf_s(msg, sizeof(msg),
4467 "*** Right main collapse (side load) vlat %.3f vg %.2f rawG %.2f lat_g %.3f ratio %.3f limit %.3f vvel %.3f",
4468 newlocvel.x,
4469 vertical_g,
4471 lateral_g_right,
4472 right_shear_ratio,
4473 main_capacity_limitR,
4474 newlocvel.y);
4476 }
4477
4478#pragma endregion
4479
4480 // FRONT TO BACK
4481 float dynamicMod = 0.0f;
4482 float effectiveLeftBrake = 0.0f;
4483 float effectiveRightBrake = 0.0f;
4484 float shiftHoldBrake = 0.0f;
4485
4487 {
4488 effectiveLeftBrake = 0.5f * fmaxf(0.0f, ourcockpit.vdat.parkingBrake) / 127.0f;
4489 effectiveRightBrake = effectiveLeftBrake;
4490 }
4491 else
4492 {
4493 effectiveLeftBrake = viewscreen->gameclass->bus->LeftBrake;
4494 effectiveRightBrake = viewscreen->gameclass->bus->RightBrake;
4495
4496 if (playerships[0].groundvehicle)
4497 {
4498 const bool brakelight = viewscreen->gameclass->bus->LeftBrake > 0.0f || viewscreen->gameclass->bus->RightBrake > 0.0f;
4499 if (brakelight != playerships[0].brakelight)
4500 {
4501 playerships[0].brakelight = brakelight;
4503 }
4504 }
4505 }
4506
4507 // Park override.
4508 if (playerships[0].groundvehicle && ourcockpit.gearshift == -2)
4509 {
4510 effectiveLeftBrake = 1.0f;
4511 effectiveRightBrake = 1.0f;
4512 }
4513 else if (playerships[0].groundvehicle &&
4514 ourcockpit.clutchhold > 0.0f &&
4516 viewscreen->gameclass->bus->EngineThrustLever[0] <= 0.101f)
4517 {
4518 shiftHoldBrake = Clamp(
4520 0.0f,
4521 1.0f);
4522 effectiveLeftBrake = RiseMath::Max(effectiveLeftBrake, shiftHoldBrake);
4523 effectiveRightBrake = RiseMath::Max(effectiveRightBrake, shiftHoldBrake);
4524 }
4525
4526 effectiveLeftBrake *= fmaxf(0.0f, ourcockpit.vdat.leftBrake) / 127.0f;
4527 effectiveRightBrake *= fmaxf(0.0f, ourcockpit.vdat.rightBrake) / 127.0f;
4528
4529 effectiveLeftBrake = ClampFloat(effectiveLeftBrake, 0.0f, 1.0f);
4530 effectiveRightBrake = ClampFloat(effectiveRightBrake, 0.0f, 1.0f);
4531
4532 if (!playerships[0].groundvehicle && ourcockpit.wheeled)
4533 {
4534 dynamicMod += 1.0f;
4536 dynamicMod -= ourcockpit.gearextent;
4537 }
4538
4539 if (!playerships[0].groundvehicle && !ourcockpit.wheeled)
4540 {
4541 dynamicMod += 1.0f;
4542 }
4543 else if (fabsf(levelerroll) >= 0.5f || fabsf(levelerpitch) >= 0.5f)
4544 {
4545 dynamicMod += 1.0f;
4546 }
4547
4548 dynamicMod = ClampFloat(dynamicMod, 0.0f, 1.0f);
4549
4550#ifdef frictionLoggingC
4551 static OptionalDiagnosticFile frictionLog("friction.log");
4552#endif
4553
4554 // Rolling resistance for wheels.
4556 {
4557 const float oldForwardVelZ = newlocvel.z;
4558 const float startRollingFadeSpeedKms =
4559 viewscreen->ptrBuildings->g_bRoad ? 0.0015f : 0.0060f;
4560 const float startRollingBlend =
4561 ClampFloat(1.0f - fabsf(newlocvel.z) / startRollingFadeSpeedKms, 0.0f, 1.0f);
4562 float appliedRollingDeltaV =
4563 RiseMath::Max(rollingDeltaV, startingRollingDeltaV * startRollingBlend);
4564
4565 newlocvel.z = ApproachZero(newlocvel.z, appliedRollingDeltaV);
4566
4567#ifdef frictionLoggingC
4568 if (oldForwardVelZ != newlocvel.z)
4569 {
4570 const float appliedRollDeltaV = fabsf(oldForwardVelZ - newlocvel.z);
4571 frictionLog.Printf("%8.3f rol VT%u CT%i WT%.0f WF%.2f GV%i GR%+i WH%i GE%.1f LB%.1f RB%.1f SH%.2f RFI%.6f RFS%.3f RFG%.3f SRB%.2f SRG%.3f V0%.3f V%.3f G%.1f R%.3f P%.3f LF%u/%u/%u TR%u/%u CrrBase%.4f CrrStart%.4f RghJitCoef%.4f RghJit%.4f CrrEff%.4f MuS%.3f MuK%.3f\n",
4573 static_cast<unsigned int>(playerships[0].type),
4574 static_cast<int>(ourcockpit.texturelib),
4576 weightFactor,
4577 playerships[0].groundvehicle ? 1 : 0,
4579 ourcockpit.wheeled ? 1 : 0,
4581 effectiveLeftBrake,
4582 effectiveRightBrake,
4583 shiftHoldBrake,
4584 appliedRollDeltaV,
4585 appliedRollDeltaV / fElapsedTime,
4586 appliedRollDeltaV / fElapsedTime * oneOvergForceKmssC,
4587 startRollingBlend,
4588 fElapsedTime > 0.0f ? startingRollingDeltaV * startRollingBlend / fElapsedTime * oneOvergForceKmssC : 0.0f,
4589 oldForwardVelZ,
4590 newlocvel.z,
4594 static_cast<unsigned int>(gridarray[31][31].pri_landform),
4595 static_cast<unsigned int>(gridarray[31][31].sec_landform),
4596 static_cast<unsigned int>(gridarray[31][31].ter_landform),
4597 static_cast<unsigned int>(gridarray[31][31].pri_transition),
4598 static_cast<unsigned int>(gridarray[31][31].sec_transition),
4599 rollingResistanceCrr,
4600 startingRollingResistanceCrr,
4601 terrainRoughnessJitterCoef,
4603 effectiveRollingResistanceCrr,
4604 effectiveMuStatic,
4605 effectiveMuKinetic);
4606 }
4607#endif
4608 }
4609
4610 // Braking and scraping.
4611 // Brakes request static friction. If requested braking exceeds the static traction
4612 // budget, the tire locks and kinetic friction is applied instead.
4613 const float brakeInput = RiseMath::Max(effectiveLeftBrake, effectiveRightBrake);
4614 const float tireSlipForwardVelZ = newlocvel.z;
4615
4616 if (dynamicMod > 0.0f || brakeInput > 0.0f)
4617 {
4618 float appliedLongitudinalDeltaV = 0.0f;
4619 const float oldForwardVelZ = newlocvel.z;
4620
4621 if (dynamicMod > 0.0f)
4622 {
4623 const float scrapeDeltaV = kineticDeltaV * dynamicMod;
4624 newlocvel.z = ApproachZero(newlocvel.z, scrapeDeltaV);
4625 appliedLongitudinalDeltaV += fabsf(oldForwardVelZ - newlocvel.z);
4626 }
4627
4628 if (brakeInput > 0.0f)
4629 {
4630 const float beforeBrakeVelZ = newlocvel.z;
4631 const float requestedBrakeDeltaV = brakeInput * BRAKE_POWER_SCALE * staticDeltaV;
4632
4633 if (requestedBrakeDeltaV <= staticDeltaV)
4634 {
4635 newlocvel.z = ApproachZero(newlocvel.z, requestedBrakeDeltaV);
4636 }
4637 else
4638 {
4639 brakeSkid = true;
4640 newlocvel.z = ApproachZero(newlocvel.z, kineticDeltaV);
4641 }
4642
4643 appliedLongitudinalDeltaV += fabsf(beforeBrakeVelZ - newlocvel.z);
4644 }
4645
4646#ifdef frictionLoggingC
4647 if (appliedLongitudinalDeltaV != 0.0f)
4648 {
4649 frictionLog.Printf("%8.3f BRK VT%u CT%i WT%.0f WF%.2f GV%i GR%+i WH%i GE%.1f LB%.1f RB%.1f SH%.2f DVI%.6f DVS%.3f DVG%.3f V0%.3f V%.3f G%.1f R%.1f P%.1f LF%u/%u/%u TR%u/%u CrrBase%.4f RghJitCoef%.4f RghJit%.4f MuS%.3f MuK%.3f Skid%i Dyn%.2f\n",
4651 static_cast<unsigned int>(playerships[0].type),
4652 static_cast<int>(ourcockpit.texturelib),
4654 weightFactor,
4655 playerships[0].groundvehicle ? 1 : 0,
4657 ourcockpit.wheeled ? 1 : 0,
4659 effectiveLeftBrake,
4660 effectiveRightBrake,
4661 shiftHoldBrake,
4662 appliedLongitudinalDeltaV,
4663 appliedLongitudinalDeltaV / fElapsedTime,
4664 appliedLongitudinalDeltaV / fElapsedTime * oneOvergForceKmssC,
4665 oldForwardVelZ,
4666 newlocvel.z,
4670 static_cast<unsigned int>(gridarray[31][31].pri_landform),
4671 static_cast<unsigned int>(gridarray[31][31].sec_landform),
4672 static_cast<unsigned int>(gridarray[31][31].ter_landform),
4673 static_cast<unsigned int>(gridarray[31][31].pri_transition),
4674 static_cast<unsigned int>(gridarray[31][31].sec_transition),
4675 rollingResistanceCrr,
4676 terrainRoughnessJitterCoef,
4678 effectiveMuStatic,
4679 effectiveMuKinetic,
4680 brakeSkid ? 1 : 0,
4681 dynamicMod);
4682 }
4683#endif
4684 }
4685
4686 // Rubber tire scrub on pavement. Qualify cornering demand for a short time before
4687 // starting the loop, and require meaningful wheel load. Brief contact unloading and
4688 // ordinary lateral-velocity correction must not restart the sample as a chirp.
4689 const float tireSlipSpeedKms = Length2D(oldLateralVelX, tireSlipForwardVelZ);
4690 // Compare demand and the solver's capped grip budget in the same Earth-G units.
4691 const float availableLateralGripG = staticDeltaV / fElapsedTime * oneOvergForceKmssC;
4692 // Ground steering sets the yaw rate directly. Use that actual turn rate instead
4693 // of the aircraft wheelBaseKm default inherited by several ground vehicles.
4694 const float tireCorneringDemandG = playerships[0].groundvehicle
4695 ? fabsf(tireSlipForwardVelZ * playerships[0].yawRadPerSec) * oneOvergForceKmssC
4696 : lateral_g_nose;
4697 const float minimumTireSkidNormalG = 0.25f;
4698 const float corneringTireSkidOnsetSeconds = 0.12f;
4699 const bool tireLoadedForSkidSound = normalG >= minimumTireSkidNormalG;
4700 const bool movingForTireSkid =
4701 fabsf(tireSlipForwardVelZ) > 0.003f &&
4702 tireSlipSpeedKms > 0.001f;
4703 const bool corneringSkidRequested =
4704 tireLoadedForSkidSound &&
4705 movingForTireSkid &&
4706 tireCorneringDemandG > availableLateralGripG &&
4707 (!playerships[0].groundvehicle || remainingLateralSlipKms > 0.001f);
4708 const bool corneringSkidSustained =
4709 tireLoadedForSkidSound &&
4710 movingForTireSkid &&
4711 tireCorneringDemandG > availableLateralGripG * 0.80f &&
4712 (!playerships[0].groundvehicle || remainingLateralSlipKms > 0.0005f);
4713 const bool hardBrakeSkid =
4714 tireLoadedForSkidSound &&
4715 movingForTireSkid &&
4716 brakeInput * BRAKE_POWER_SCALE > 1.0f;
4717 const bool tireSkidSurface =
4720 tireSlipSpeedKms > 0.001f;
4721
4722 if (!tireSkidSurface)
4723 {
4726 }
4727 else if (corneringTireSkidActive)
4728 {
4729 corneringTireSkidActive = corneringSkidSustained;
4732 }
4733 else if (corneringSkidRequested)
4734 {
4735 corneringTireSkidDemandSeconds += RiseMath::Min(fElapsedTime, 0.1f);
4736 corneringTireSkidActive = corneringTireSkidDemandSeconds >= corneringTireSkidOnsetSeconds;
4737 }
4738 else
4739 {
4741 }
4742
4743 const bool tireSkidSoundActive =
4744 tireSkidSurface && tireLoadedForSkidSound &&
4745 (brakeSkid || corneringTireSkidActive || hardBrakeSkid);
4746
4747#ifdef frictionLoggingC
4748 if (tireSkidSoundActive != tireSkidSoundWasActive)
4749 {
4750 frictionLog.Printf(
4751 "%8.3f SND tireSkid=%i brake=%i corner=%i demand=%.3fs speed=%.3f latG=%.3f gripG=%.3f normalG=%.3f\n",
4752 Rendering::ClientTime(), tireSkidSoundActive ? 1 : 0, brakeSkid ? 1 : 0,
4754 tireSlipSpeedKms, tireCorneringDemandG, availableLateralGripG, normalG);
4755 }
4756#endif
4757 const double tireDiagnosticTime = Rendering::ClientTime();
4758 if (playerships[0].groundvehicle &&
4759 (tireSkidSoundActive != tireSkidSoundWasActive ||
4760 (tireSlipSpeedKms > 0.001f && tireDiagnosticTime >= nextGroundTireDiagnosticTime)))
4761 {
4762 sprintf_s(msg, sizeof msg,
4763 "GROUND_TIRE type=%u road=%i support=%i speed=%.1fkph lateral=(%.3f->%.3f)mps "
4764 "normal=%.3fVg mu=(%.3f,%.3f) demand=%.3fEg grip=%.3fEg "
4765 "squeal=%i brake=%i corner=%i",
4766 static_cast<unsigned int>(playerships[0].type), viewscreen->ptrBuildings->g_bRoad ? 1 : 0,
4767 groundTiresSupporting ? 1 : 0, tireSlipSpeedKms * 3600.0f,
4768 oldLateralVelX * 1000.0f, newlocvel.x * 1000.0f, normalG,
4769 effectiveMuStatic, effectiveMuKinetic, tireCorneringDemandG, availableLateralGripG,
4770 tireSkidSoundActive ? 1 : 0, (brakeSkid || hardBrakeSkid) ? 1 : 0,
4771 corneringTireSkidActive ? 1 : 0);
4772 logger->Log(msg);
4773 nextGroundTireDiagnosticTime = tireDiagnosticTime + 1.0;
4774 }
4775 tireSkidSoundWasActive = tireSkidSoundActive;
4776
4777 if (tireSkidSoundActive)
4778 {
4779 const float skidVolume = ClampFloat(tireSlipSpeedKms / 0.020f * normalG, 0.0f, 1.0f);
4780 const float skidPitch = ClampFloat(0.75f + tireSlipSpeedKms / 0.040f, 0.75f, 1.50f);
4781 const float skidPan =
4782 fabsf(oldLateralVelX) > 0.001f ? (oldLateralVelX > 0.0f ? 1.0f : -1.0f) : 0.0f;
4785 true,
4786 skidVolume,
4787 skidPitch,
4788 skidPan,
4789 false,
4790 true,
4791 true);
4792 }
4793 else
4794 {
4796 }
4797
4798 cross -= newlocvel;
4799
4800 if (fElapsedTime != 0.0f)
4801 {
4802 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f ground friction", -cross.x * oneOvergForceKmssC / fElapsedTime, -cross.y * oneOvergForceKmssC / fElapsedTime, -cross.z * oneOvergForceKmssC / fElapsedTime);
4803 viewscreen->sofTracking.emplace_back(msg);
4804 }
4805
4806 // cross is a delta-velocity. Keep it in sumofforces for the existing integrator;
4807 // writing directly to velocity here destabilizes terrain/touchdown collision.
4808 viewscreen->sumofforces -= cross;
4809
4810 // Ground scrape sound.
4811 static float oldScrapeVol = 0.0f;
4812 const float scrapevel = sqrtf(newlocvel.x * newlocvel.x + newlocvel.z * newlocvel.z);
4813 const float scrapevol = RiseMath::Min(1.0f, scrapevel / 0.01f * gndcontactG) * dynamicMod;
4814
4815 if (scrapevol > MIN_VOL)
4816 {
4818 oldScrapeVol = scrapevol;
4819 }
4820 else if (oldScrapeVol > MIN_VOL)
4821 {
4822 viewscreen->gameclass->sound->PlayEx(SOUND_GROUNDSCRAPESTOP, false, oldScrapeVol);
4824 oldScrapeVol = 0.0f;
4825 }
4826
4827 // Road noise sound.
4828 const float rollvol = RiseMath::Min(1.0f, fabsf(newlocvel.z) / 0.026f) * gndcontactG;
4829
4830 if (ourcockpit.wheeled && (playerships[0].groundvehicle || ourcockpit.gearextent > 0.0f) && rollvol > MIN_VOL)
4832 else
4834
4835 RiseMath::Vec3TransformNormal(&cross, &cross, &playerships[0].matrixWorld);
4836 RiseMath::Vec3Subtract(&playerships[0].velocity, &playerships[0].velocity, &cross);
4837
4838 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
4839 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
4840 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
4841 {
4842 sprintf_s(msg, sizeof(msg), "ET: %f", fElapsedTime);
4844 sprintf_s(msg, sizeof(msg), "Groundspeed: %f", groundSpeedKms);
4846 sprintf_s(msg, sizeof(msg), "sumofforces I: %f", viewscreen->sumofforces.x);
4848 sprintf_s(msg, sizeof(msg), "sumofforces J: %f", viewscreen->sumofforces.y);
4850 sprintf_s(msg, sizeof(msg), "sumofforces K: %f", viewscreen->sumofforces.z);
4852 sprintf_s(msg, sizeof(msg), "cross I: %f", cross.x);
4854 sprintf_s(msg, sizeof(msg), "cross J: %f", cross.y);
4856 sprintf_s(msg, sizeof(msg), "cross K: %f", cross.z);
4858 sprintf_s(msg, sizeof(msg), "newlocvel I: %f", newlocvel.x);
4860 sprintf_s(msg, sizeof(msg), "newlocvel J: %f", newlocvel.y);
4862 sprintf_s(msg, sizeof(msg), "newlocvel K: %f", newlocvel.z);
4864 sprintf_s(msg, sizeof(msg), "staticDeltaV: %f", staticDeltaV);
4866 sprintf_s(msg, sizeof(msg), "kineticDeltaV: %f", kineticDeltaV);
4868 sprintf_s(msg, sizeof(msg), "rollingDeltaV: %f", rollingDeltaV);
4870 sprintf_s(msg, sizeof(msg), "rollingResistanceCrr: %f", rollingResistanceCrr);
4872 sprintf_s(msg, sizeof(msg), "terrainRoughnessJitterCoef: %f", terrainRoughnessJitterCoef);
4874 sprintf_s(msg, sizeof(msg), "terrainRoughnessFrictionJitter: %f", terrainRoughnessFrictionJitter);
4876 sprintf_s(msg, sizeof(msg), "muStatic: %f", muStatic);
4878 sprintf_s(msg, sizeof(msg), "muKinetic: %f", muKinetic);
4881 sprintf_s(msg, sizeof(msg), "Trapped a violation with ground friction...");
4883 }
4884 }
4885
4886#pragma endregion
4887
4888 // we are in WOW
4889 gldDeploy = ourcockpit.spoilerAreaMod > 0 && // installed
4890 viewscreen->ptrPropulsion->ias > 0.008f && // 16 KTS, can't use bus value because it is unusable below 40 KTS, can't use speedometer!?
4894 } // end of WOW
4895
4896#pragma region Ground Lift Dump (GLD)
4897
4898 if (gldDeploy && viewscreen->gameclass->bus->GroundSpoilerPositionScalar != 1.0f)
4899 {
4903 }
4904 else if (!gldDeploy && viewscreen->gameclass->bus->GroundSpoilerPositionScalar != 0.0f)
4905 {
4909 }
4910
4911#pragma endregion
4912
4913 }
4914 }
4915
4916
4917 if (playerships[0].reference < REF_INANOTHER)
4918 {
4919 if (fElapsedTime != 0.0f)
4920 {
4921 sprintf_s(msg, sizeof(msg), "X%7.3f Y%7.3f Z%7.3f gravity2", viewscreen->gravityacc.x * oneOvergForceKmssC / fElapsedTime, viewscreen->gravityacc.y * oneOvergForceKmssC / fElapsedTime, viewscreen->gravityacc.z * oneOvergForceKmssC / fElapsedTime);
4922 viewscreen->sofTracking.emplace_back(msg);
4923 }
4924
4925 // gravityacc is in kmss already (fElapsedTime applied)
4926 viewscreen->sumofforces += viewscreen->gravityacc; // gravity affects vehicles and occupant individually
4927 }
4928 }
4929
4930#pragma region debug
4931 if (viewscreen->sumofforces.x > 100.0f || viewscreen->sumofforces.x < -100.0f || _isnan(viewscreen->sumofforces.x) || isinf(viewscreen->sumofforces.x) ||
4932 viewscreen->sumofforces.y > 100.0f || viewscreen->sumofforces.y < -100.0f || _isnan(viewscreen->sumofforces.y) || isinf(viewscreen->sumofforces.y) ||
4933 viewscreen->sumofforces.z > 100.0f || viewscreen->sumofforces.z < -100.0f || _isnan(viewscreen->sumofforces.z) || isinf(viewscreen->sumofforces.z))
4934 {
4935 sprintf_s(msg, sizeof(msg), "ET: %f", fElapsedTime);
4937 sprintf_s(msg, sizeof(msg), "sumofforces I: %f", viewscreen->sumofforces.x);
4939 sprintf_s(msg, sizeof(msg), "sumofforces J: %f", viewscreen->sumofforces.y);
4941 sprintf_s(msg, sizeof(msg), "sumofforces K: %f", viewscreen->sumofforces.z);
4943 sprintf_s(msg, sizeof(msg), "gravityacc I: %f", viewscreen->gravityacc.x);
4945 sprintf_s(msg, sizeof(msg), "gravityacc J: %f", viewscreen->gravityacc.y);
4947 sprintf_s(msg, sizeof(msg), "gravityacc K: %f", viewscreen->gravityacc.z);
4950 sprintf_s(msg, sizeof(msg), "Trapped a violation after gravityacc application...");
4952 }
4953#pragma endregion
4954
4955
4956
4957
4958
4959 logger->AddToCallStack("EffectOnFuel");
4960
4961 // Effect on fuel
4962 if (!playerships[0].groundvehicle)
4963 {
4964 ourcockpit.currentFuelFlowPoundsPerSecond = (fabsf(viewscreen->rcsThrustOutputX) + fabsf(viewscreen->rcsThrustOutputY) + fabsf(viewscreen->rcsThrustOutputZ) + fabsf(zThrustAcceleration4FF) + rcsThrustYPR) * ourcockpit.ffmax;
4965 const int dockArray = playerships[0].reference - REF_DOCKENUMCPOC;
4966 const bool idleFuel=!playerships[0].docked || (dockArray >= 0 && dockArray < maxdockC && !allobjects[dockArray].powered);
4967 if (idleFuel)
4970 // Passive component integrals of the existing fuel model. The tank
4971 // remains authoritative; float tank quantization can differ slightly.
4972 const double fuelTime=fElapsedTime*wear.fuelFlow/Kg2Lbs;
4973 orbitActuation.mainFuelKg+=fabsf(zThrustAcceleration4FF)*ourcockpit.ffmax*fuelTime;
4974 orbitActuation.translationFuelKg+=(fabsf(viewscreen->rcsThrustOutputX)+
4976 orbitActuation.rotationFuelKg+=rcsThrustYPR*ourcockpit.ffmax*fuelTime;
4977 if(idleFuel) orbitActuation.idleFuelKg+=ourcockpit.fuelFlowIdleLbsPerSec*ourcockpit.power*fuelTime;
4981 fuel = RiseMath::Max(fuel, 0.0f);
4983 }
4984
4985
4987
4988
4989 logger->AddToCallStack("ThrustSounds");
4990
4991#pragma region RCS Thrust Sounds
4992 const float pan = -viewscreen->rcsThrustOutputX;
4993 float volume = fabsf(viewscreen->rcsThrustOutputX);
4994 float maxVolume = ourcockpit.lrtranslimit;
4995
4996 volume += fabsf(viewscreen->rcsThrustOutputY);
4998
4999 volume += fabsf(viewscreen->rcsThrustOutputZ);
5000 maxVolume += 0.002f;
5001
5002 if (volume == 0.0f)
5004 else
5005 {
5006 if (_isnan(pan))
5007 logger->Log("We are getting a NAN pan from Propulsion::Update", Logger::Level::Debug);
5008 viewscreen->gameclass->sound->PlayEx(SOUND_THRUST, true, Clamp(volume / maxVolume * 3.0f, 0, 1), 1, Clamp(pan / volume, -1, 1), false, true, true);
5009 }
5010#pragma endregion
5011
5012
5013
5014 viewscreen->AssertTelemetry("Propulsion::Update3", 0);
5015
5016
5017 // Propulsion section -----------------------------------------------------------------------
5018 }
5019 else
5021
5022
5023 logger->AddToCallStack("SendTelemetryUpstream");
5024
5025 if (telemetryUploadGate.Advance(fElapsedTime))
5026 {
5027 //if (playerships[0].isSimulator)
5028 //{
5029 //}
5030 //else
5031 if (playerships[0].reference == REF_INANOTHER || playerships[0].reference == REF_BUILDING || playerships[0].reference == REF_WINDOWLESS)
5032 {
5033 //SClientPacket ourpacket; // NOLINT
5034 //ourpacket.type = 6; // character movement
5035 //ourpacket.f_x = viewscreen->gameclass->GUI->player[ourcockpit.ourplyrC].startx;
5036 //ourpacket.f_y = viewscreen->gameclass->GUI->player[ourcockpit.ourplyrC].starty;
5037 //ourpacket.f_z = viewscreen->gameclass->GUI->player[ourcockpit.ourplyrC].hdg;
5038 //ourpacket.f_w = 0.0f; // static_cast<float>(viewscreen->gameclass->GUI->player[ourcockpit.ourplyrC].ani);
5039 //viewscreen->gameclass->networking->SendToServer(&ourpacket, sizeof(SClientPacket), true);
5040 }
5041 else
5042 {
5043 SendTelemetryUpstream(fElapsedTime);
5044 }
5045 }
5046
5047 if (discordPresenceGate.Advance(fElapsedTime))
5049
5050
5051
5052 logger->AddToCallStack("DamageControl");
5053
5054 // damage control
5056 {
5057 ourcockpit.vdatTime += fElapsedTime;
5058 if (ourcockpit.vdatTime > 5.0f) // wait 5 seconds
5059 {
5060 ourcockpit.vdatChanged = false;
5061 ourcockpit.vdatTime = 0.0f;
5062
5063 if (!playerships[0].isSimulator)
5064 {
5065 logger->Log("Sent damage control!");
5066
5067 SPacketBig outpacket; // NOLINT
5068 outpacket.type = 11; // damage control
5069 outpacket.vdat = ourcockpit.vdat;
5070 outpacket.ship = ourcockpit.hitpoints;
5071 outpacket.array = 0; // unused
5072 outpacket.inarray = 0; // unused
5073 outpacket.vehicleId = playerships[0].vehicleId;
5074 viewscreen->gameclass->networking->SendToServer(&outpacket, sizeof(SPacketBig), true);
5075 }
5076 }
5077 }
5078 else
5079 {
5080 ourcockpit.vdatTime = 0.0f;
5081 }
5082
5083
5084 logger->AddToCallStack("Propulsion::Update End");
5085}
5086
5087/*
5088RiseMath::Vector3 propulsion::EvaluateRotationalForces()
5089{
5090
5091 // so wings currently only care about Y load
5092 // they should fly off if roll or yaw is too high ...
5093 ourcockpit.c9WingYawArmM;
5094 ourcockpit.b12WingRollArmM;
5095 // but then what the hell is the ultimate limit for this?
5096
5097
5098 // tail should care about Z only probably?
5099 ourcockpit.b6DistanceToHTailM;
5100 ourcockpit.b9DistanceToVTailM;
5101 // geez, I thought I had something here with the american airbus 300 but that is shear bending and torsion https://lessonslearned.faa.gov/American587/AAR0404.pdf
5102 Table 6. A300-600 Design Limit Loads for the A300-600 and A310-300 and the 1986
5103 Full-Scale Certification Test Loads
5104 Load type
5105 A300-600 design limit loads A310-300 design limit loads A310-300 full-scale certification test loads
5106 Shear (in N) -215,800 -223,390 -424,440
5107 Bending moment (in Nm) 861,650 883,300 1,677,700
5108 Torsion (in Nm) 152,680 161,000 340,720
5109
5110
5111 // Passed structural limitation rot/s
5112 if (viewscreen->advanceframe && (playerships[0].yaw > rotlimitC || playerships[0].yaw < -rotlimitC))
5113 {
5114 viewscreen->causechain = 2; // rotation
5115 if (ourcockpit.vdat.vtail > 0)
5116 {
5117 char damage = (char)(rand() % ourcockpit.vdat.vtail + 1); // thanks canary
5118 ourcockpit.vdat.vtail -= damage;
5119 ourcockpit.vdatChanged = true;
5120 if (damage > 32)
5121 {
5122 if (rand() < 16384)
5123 viewscreen->gameclass->sound->Play(SOUND_TDEATH1);
5124 else
5125 viewscreen->gameclass->sound->Play(SOUND_TDEATH2);
5126 }
5127 }
5128 if (ourcockpit.vdat.htail > 0)
5129 {
5130 char damage = (char)(rand() % ourcockpit.vdat.htail + 1); // thanks canary
5131 ourcockpit.vdat.htail -= damage;
5132 ourcockpit.vdatChanged = true;
5133 if (damage > 32)
5134 {
5135 if (rand() < 16384)
5136 viewscreen->gameclass->sound->Play(SOUND_TDEATH1);
5137 else
5138 viewscreen->gameclass->sound->Play(SOUND_TDEATH2);
5139 }
5140 }
5141 }
5142
5143 // Passed structural limitation rot/s
5144 if (viewscreen->advanceframe && (playerships[0].roll > rotlimitC || playerships[0].roll < -rotlimitC))
5145 {
5146 viewscreen->causechain = 2; // rotation
5147 if (ourcockpit.vdat.leftwing > 0)
5148 {
5149 char damage = (char)(rand() % ourcockpit.vdat.leftwing + 1); // thanks canary 1-254 is 2 to 255 or 1 to 254
5150 ourcockpit.vdat.leftwing -= damage;
5151 ourcockpit.vdatChanged = true;
5152 if (damage > 32)
5153 {
5154 viewscreen->gameclass->sound->Play(SOUND_ODEATH1);
5155 }
5156 }
5157 if (ourcockpit.vdat.rightwing > 0)
5158 {
5159 char damage = (char)(rand() % ourcockpit.vdat.rightwing + 1); // thanks canary
5160 ourcockpit.vdat.rightwing -= damage;
5161 ourcockpit.vdatChanged = true;
5162 if (damage > 32)
5163 {
5164 viewscreen->gameclass->sound->Play(SOUND_ODEATH2);
5165 }
5166 }
5167 }
5168
5169 // Passed structural limitation rot/s
5170 if (viewscreen->advanceframe && (playerships[0].pitch > rotlimitC || playerships[0].pitch < -rotlimitC))
5171 {
5172 viewscreen->causechain = 2; // rotation
5173 if (ourcockpit.vdat.htail > 0)
5174 {
5175 char damage = (char)(rand() % ourcockpit.vdat.htail + 1); // thanks canary
5176 ourcockpit.vdat.htail -= damage;
5177 ourcockpit.vdatChanged = true;
5178 if (damage > 32)
5179 {
5180 if (rand() < 16384)
5181 viewscreen->gameclass->sound->Play(SOUND_TDEATH1);
5182 else
5183 viewscreen->gameclass->sound->Play(SOUND_TDEATH2);
5184 }
5185 }
5186 }
5187}
5188*/
5189
5190
5197
5199{
5201}
@ AirframeTemp200
Definition ActiveHelp.h:379
@ UpsideDown
Definition ActiveHelp.h:357
@ AirframeTemp300
Definition ActiveHelp.h:380
@ AirframeTemp100
Definition ActiveHelp.h:378
@ LowFuel
Definition ActiveHelp.h:433
AirfoilType
Definition AirfoilType.h:4
@ NACA4412
Definition AirfoilType.h:7
@ NACA0011SC
Definition AirfoilType.h:6
@ NACA64A410
Definition AirfoilType.h:5
@ NACA64A210
Definition AirfoilType.h:8
float Lerp(float val1, float val2, float lerp)
float RandomFloat()
constexpr auto Clamp(T1 val, T2 min, T3 max)
@ EVENT_BRAKELIGHT_OFF
Definition Networking.h:58
@ EVENT_SPOILERSETTING
Definition Networking.h:65
@ EVENT_BRAKELIGHT_ON
Definition Networking.h:57
#define rotlimitC
@ E10
Definition ServerTypes.h:63
@ T120
Definition ServerTypes.h:67
@ T27
Definition ServerTypes.h:82
@ E11
Definition ServerTypes.h:68
@ T121
Definition ServerTypes.h:89
#define MAX_ENGINES
#define maxdockC
const RiseMath::Vector3 centerC
@ REF_BUILDING
Definition ServerTypes.h:46
@ REF_ACLMODE
Definition ServerTypes.h:44
@ REF_DOCKENUMCPOC
Definition ServerTypes.h:53
@ REF_INANOTHER
Definition ServerTypes.h:45
@ REF_APNMODE
Definition ServerTypes.h:42
@ REF_ONGROUND
Definition ServerTypes.h:43
@ REF_WINDOWLESS
Definition ServerTypes.h:50
#define limiterC
SOUNDS
Definition Sound.h:23
@ SOUND_GROUNDSCRAPELOOP
Definition Sound.h:269
@ SOUND_HIGHBYPASS
Definition Sound.h:216
@ SOUND_ODEATH2
Definition Sound.h:245
@ SOUND_APCCHORD
Definition Sound.h:172
@ SOUND_NONE
Definition Sound.h:24
@ SOUND_COCKPITLEVEL
Definition Sound.h:29
@ SOUND_WLAND2
Definition Sound.h:254
@ SOUND_CRUISE
Definition Sound.h:185
@ SOUND_WLAND1
Definition Sound.h:253
@ SOUND_ROADNOISELOOP
Definition Sound.h:271
@ SOUND_GROUNDSCRAPESTOP
Definition Sound.h:270
@ SOUND_THRUST
Definition Sound.h:268
@ SOUND_COCKPITENGINELEFT
Definition Sound.h:30
@ SOUND_COCKPITENGINECENTER
Definition Sound.h:32
@ SOUND_COCKPITLAND
Definition Sound.h:28
@ SOUND_TIRESKID
Definition Sound.h:250
@ SOUND_LANDED
Definition Sound.h:188
#define MIN_VOL
Definition Sound.h:18
float RightBrake
Definition Bus.h:383
float OutsideAirTemperatureKelvin
Definition Bus.h:80
float LinearVelocityKms
Definition Bus.h:455
bool IceDetectorHeat
Definition Bus.h:369
float Mach
Definition Bus.h:456
float RollAttitudeRadians
Definition Bus.h:48
float EngineThrustOutput[MAX_ENGINES]
Definition Bus.h:54
float DebugFloat5
Definition Bus.h:543
float DebugHdg2Rwy
Definition Bus.h:547
float DebugRwyHeading
Definition Bus.h:548
float GroundSpeedKms
Definition Bus.h:179
float PitchAttitudeRadians
Definition Bus.h:47
float EngineThrustCommand[MAX_ENGINES]
Definition Bus.h:360
float WindUpdraftMs
Definition Bus.h:308
RainAir::State RainAirStatus
Definition Bus.h:488
float DebugAirIce
Definition Bus.h:556
float IceDetectorMm
Definition Bus.h:368
float StaticAirTemperatureCelsius
Definition Bus.h:79
float DynPresFwdLbsPerSqFt
Definition Bus.h:454
float CabinPressureMb
Definition Bus.h:403
float DebugSurfaceIce
Definition Bus.h:555
float LeftBrake
Definition Bus.h:383
float DebugFloat3
Definition Bus.h:541
short targetC
Definition Bus.h:480
bool OnGround
Definition Bus.h:173
float LocalizerDeviationRadians
Definition Bus.h:158
float EngineThrustLever[MAX_ENGINES]
Definition Bus.h:357
RiseMath::Vector3 NormalAcceleration
Definition Bus.h:45
float GrossWeightLbs() const noexcept
Definition Bus.h:466
float IndicatedAirspeedKms
Definition Bus.h:34
float IceWeightLbs
Definition Bus.h:370
struct Bus::Afcs AFCS
float YawDamperCommand
Definition Bus.h:436
float DebugAglEye
Definition Bus.h:552
float FuelFlowKgh
Definition Bus.h:463
float SlipSkidRadians
Definition Bus.h:387
float SpeedOfSoundKms
Definition Bus.h:457
float FlightSpoilerPositionScalar
Definition Bus.h:76
float AirDensityScalar
Definition Bus.h:453
bool AntiIce
Definition Bus.h:392
float AirframeTemperatureCelsius
Definition Bus.h:82
std::vector< Swaypoint > waypoint
Definition Bus.h:500
float PitchTrimScalar
Definition Bus.h:415
void AddCommand(const Command &command, bool onlyOne)
Definition Bus.cpp:5
GpwsWindshear::Sample WindshearWind
Definition Bus.h:309
float ComputedVsKms
Definition Bus.h:37
float SpeedometerKPH
Definition Bus.h:180
bool YawDamperStatus
Definition Bus.h:433
float RadioAltitudeKm
Definition Bus.h:157
bool ComponentFcsRollFail
Definition Bus.h:492
short scanslot[MAX_SCAN]
Definition Bus.h:485
float TotalAirTemperatureCelsius
Definition Bus.h:81
int WPtargetC
Definition Bus.h:499
float DebugTurbulence
Definition Bus.h:552
bool FlightFreeze
Definition Bus.h:474
double ProgramTime
Definition Bus.h:473
float WindDirectionDegrees
Definition Bus.h:306
float PitchTrimSurfacePositionDegrees
Definition Bus.h:64
float GlideslopeDeviationRadians
Definition Bus.h:159
float DebugFloat4
Definition Bus.h:542
float GroundSpoilerPositionScalar
Definition Bus.h:75
float WindSpeedMs
Definition Bus.h:307
float VerticalSpeedKms
Definition Bus.h:451
float TargetBearingDeg
Definition Bus.h:503
Orbital::BusState orbit
Definition Bus.h:481
float TrueAirspeedKms
Definition Bus.h:448
float DebugFloat6
Definition Bus.h:544
bool ComponentRcsRollFail
Definition Bus.h:491
float AngleOfAttackRadians
Definition Bus.h:175
bool ThrustReverserCommand[MAX_ENGINES]
Definition Bus.h:72
std::vector< Command > commandStream
Definition Bus.h:442
std::unique_ptr< Bus > bus
Definition GameClass.h:108
std::unique_ptr< HMI > GUI
Definition GameClass.h:106
std::unique_ptr< Sound > sound
Definition GameClass.h:104
void LostVerticalTarget(const char *msg) const
bool TurnOffTVM() const
std::unique_ptr< Networking > networking
Definition GameClass.h:103
std::unique_ptr< DiscordIntegration > discord
Definition GameClass.h:111
bool TurnOffDOR(bool preserveGuidance=false) const
void ChangeGear(char newGear, bool isInit=false) const
void AutopilotDisconnect() const
InformationDialog * informationDialog
Definition gui.h:1120
bool DismissHelp(int helpId, int nControlID=GUI_UNDERSTOOD)
bool PopUpHelp(short helpId, bool allowDismiss=true, bool isLearnMore=false)
void Log(const char *msg, Level level=Info, int errorCode=0)
Definition Logger.cpp:283
void AddToCallStack(const char *msg)
Definition Logger.cpp:355
@ Debug
Definition Logger.h:27
@ Warn
Definition Logger.h:26
@ Fatal
Definition Logger.h:29
@ Error
Definition Logger.h:28
void SendTelemetry(SClientPacketNew *pData) const
void SendToServer(void *pData, DWORD dwSize, bool bGuaranteed, PacketOrdering order=ORDERING_NONE) const
void SendEvent(EventType eventType, float extent=0.0f) const
bool Printf(const char *format, Args... args)
RiseMath::Vector3 position
Definition Camera.h:11
bool outside
Definition Camera.h:17
void Stop(SOUNDS soundEnum) const
Definition Sound.cpp:3397
void PrecipWindSoundBarrier(RiseMath::Vector3 relativeWindTrueKms)
Definition Sound.cpp:3126
void PlayCabinAnnouncement(SOUNDS sound_enum)
Definition Sound.cpp:3456
float Play(SOUNDS soundEnum, float volume=1.0f)
Definition Sound.cpp:802
void PlayEx(SOUNDS soundEnum, bool loop, float volume=1.0f, float frequencyMod=1.0f, float pan=0.0f, bool restart=true, bool fromOutside=false, bool partOfHull=false)
Definition Sound.cpp:1006
void EnvironmentalEffects()
Definition Sound.cpp:2031
bool Advance(double elapsedSeconds)
float turbLow
Definition Viewscreen.h:97
RiseMath::Vector3 position
Definition Viewscreen.h:382
float rcsThrustRequestY
Definition Viewscreen.h:374
float GetSuspensionRollOffsetRadians() const
float steerInput
Definition Viewscreen.h:372
float GetSuspensionPitchOffsetRadians() const
float yawInput
Definition Viewscreen.h:372
bool advanceframe
Definition Viewscreen.h:375
float rcsThrustOutputZ
Definition Viewscreen.h:373
RiseMath::Vector3 UniverseRelativeVelocityKms
Definition Viewscreen.h:125
float pitchInput
Definition Viewscreen.h:372
float GetAverageSuspensionBumpTravelKm() const
DeathType causechain
Definition Viewscreen.h:376
RiseMath::Vector3 gravityacc
Definition Viewscreen.h:112
bool VolumeCloudsEnabled() const
Definition Viewscreen.h:404
RiseMath::Vector3 leveler
Definition Viewscreen.h:143
GameClass * gameclass
Definition Viewscreen.h:439
RiseMath::Vector3 compassnorth
Definition Viewscreen.h:107
std::unique_ptr< propulsion > ptrPropulsion
Definition Viewscreen.h:432
std::unique_ptr< weather > ptrWeather
Definition Viewscreen.h:434
RiseMath::Vector3 posnorml
Definition Viewscreen.h:383
std::unique_ptr< grid > ptrGrid
Definition Viewscreen.h:426
bool IsRepositionSettling() const
Definition Viewscreen.h:152
std::vector< std::string > sofTracking
Definition Viewscreen.h:134
float turbTime
Definition Viewscreen.h:96
bool AssertTelemetry(const char *location, short id)
float CalculateAGLd(RiseMath::Vector3 terpos, double terprecisionx, double terprecisiony, double terprecisionz, double proposedx, double proposedy, double proposedz, RiseMath::Vector3 proposed, bool makeleveler)
double terprecisionz
Definition Viewscreen.h:370
float rcsThrustOutputX
Definition Viewscreen.h:373
float rollInput
Definition Viewscreen.h:372
float UniverseRelativeSpeedKms
Definition Viewscreen.h:126
float turbEnergy
Definition Viewscreen.h:98
float verticaltime
Definition Viewscreen.h:378
void DumpSofTracking()
void DamageLandingLights(const RiseMath::Vector3 &surfaceNormalBody, float planeDistanceKm, const RiseMath::Vector3 &impactVelocityBody, const char *cause)
std::unique_ptr< buildings > ptrBuildings
Definition Viewscreen.h:428
float insthdgDegrees
Definition Viewscreen.h:369
float rcsThrustOutputY
Definition Viewscreen.h:373
void ApplySuspensionImpact(float absorbedVelocityKms)
RiseMath::Vector3 sumofforces
Definition Viewscreen.h:108
double terprecisionx
Definition Viewscreen.h:370
float rcsThrustRequestX
Definition Viewscreen.h:374
float insttrk
Definition Viewscreen.h:369
RiseMath::Vector3 terpos
Definition Viewscreen.h:368
float rcsThrustRequestZ
Definition Viewscreen.h:374
SCamera * cockpitCamera
Definition Viewscreen.h:138
RiseMath::Vector3 forwardVector
Definition Viewscreen.h:363
double terprecisiony
Definition Viewscreen.h:370
Logger * logger
Definition Viewscreen.h:440
SCamera * camera
Definition Viewscreen.h:137
RiseMath::Vector3 structuralImpactImpulse
Definition Viewscreen.h:111
bool g_bRoad
Definition buildings.h:62
bool dataReady
Definition grid.h:36
float grounditerate
Definition propulsion.h:64
float apPitchLastAttitude
Definition propulsion.h:39
static void GetTerrainRollingCoefficients(unsigned char type, float *rollingResistanceCrr, float *terrainRoughnessJitterCoef)
float speedOfSoundKms
Definition propulsion.h:82
Logger * logger
Definition propulsion.h:31
RiseMath::Vector3 groundvec
Definition propulsion.h:100
float levelerpitch
Definition propulsion.h:97
static float CalculateAoaMax(AirfoilType type, float CdDelta)
void Update(float fElapsedTime)
float gndcontactG
Definition propulsion.h:33
void ResetControlLoops()
float totalWeightLbs
Definition propulsion.h:81
float f_augment
Definition propulsion.h:66
RiseMath::Vector3 relativeWindTrueKms
Definition propulsion.h:61
bool corneringTireSkidActive
Definition propulsion.h:43
RiseMath::Vector3 localWindVector
Definition propulsion.h:99
float staticDensity
Definition propulsion.h:94
float dynamicDensityScalar
Definition propulsion.h:95
float aoaRad
Definition propulsion.h:65
float tatCelsius
Definition propulsion.h:88
char msg[512]
Definition propulsion.h:56
float groundSpeedKms
Definition propulsion.h:62
RiseMath::Vector3 tvmRelativeVelocity
Definition propulsion.h:58
Swaypoint currentWaypoint
Definition propulsion.h:79
float EngineThrustOutput[MAX_ENGINES]
Definition propulsion.h:50
float olddesiredvsi
Definition propulsion.h:37
float GetTotalThrust() const
float yawAccelerationSnapshot
Definition propulsion.h:93
propulsion(Viewscreen *ptr)
Telemetry::PeriodicGate discordPresenceGate
Definition propulsion.h:47
Telemetry::PeriodicGate telemetryUploadGate
Definition propulsion.h:46
float convectionRate
Definition propulsion.h:91
float airIceAccumulationMm
Definition propulsion.h:85
static float CalculateDragCoefficient(AirfoilType type, float aoaRad, float CdDelta)
float holdOverTime
Definition propulsion.h:96
RiseMath::Vector3 dorRelativeVelocity
Definition propulsion.h:59
Viewscreen * viewscreen
Definition propulsion.h:30
float halfsec
Definition propulsion.h:33
float rollAccelerationSnapshot
Definition propulsion.h:93
float mach
Definition propulsion.h:87
float staticBuildup
Definition propulsion.h:83
RiseMath::Vector3 windgust
Definition propulsion.h:36
RiseMath::Vector3 oldOdoPosition
Definition propulsion.h:53
bool initFromDeflect
Definition propulsion.h:80
float oldmsl
Definition propulsion.h:34
RiseMath::Vector3 actual
Definition propulsion.h:35
char oldOdoReference
Definition propulsion.h:54
double nextGroundTireDiagnosticTime
Definition propulsion.h:45
static float CalculateClMax(AirfoilType type, float CdDelta)
RiseMath::Vector3 windVectorTrueKms
Definition propulsion.h:60
float groundIceAccumulationMm
Definition propulsion.h:86
float ias
Definition propulsion.h:90
float pitchAccelerationSnapshot
Definition propulsion.h:93
float apPitchLastInput
Definition propulsion.h:38
RiseMath::Vector3 oldvelocity
Definition propulsion.h:63
float qz_lbsPerSqFt
Definition propulsion.h:89
float apTrimTimer
Definition propulsion.h:40
static float CalculateLiftCoefficient(AirfoilType type, float aoaRad, float ClDelta)
float levelerroll
Definition propulsion.h:98
float airframeTempCelsius
Definition propulsion.h:84
void SendTelemetryUpstream(float fElapsedTime)
float corneringTireSkidDemandSeconds
Definition propulsion.h:42
float ThrustReverserOutput[MAX_ENGINES]
Definition propulsion.h:49
RiseMath::Vector3 localVelocity
Definition propulsion.h:67
float terrainRoughnessFrictionJitter
Definition propulsion.h:41
bool tireSkidSoundWasActive
Definition propulsion.h:44
float GetPrecip() const
Definition weather.cpp:1365
float GetTurbulence() const
Definition weather.cpp:1436
float GetWindspeedKms() const
Definition weather.cpp:1352
float GetWindDirectionRadians() const
Definition weather.cpp:1428
float cloudPocket
Definition weather.h:218
float cloudThickness
Definition weather.h:215
CloudVolume::Parameters cloudParameters
Definition weather.h:216
float cloudTurbulenceBlend
Definition weather.h:219
float GetVisibilityKm() const
Definition weather.cpp:1411
float GetTemperatureCelsius() const
Definition weather.cpp:1470
float fuel
Definition globals.cpp:90
s_city_stuff citystuff
Definition globals.cpp:110
float deathfuel
Definition globals.cpp:91
DeathType dead
Definition globals.cpp:37
float f_ACL
Definition globals.cpp:11
float f_AGL
Definition globals.cpp:9
s_network_objects playerships[MAX_SCAN]
Definition globals.cpp:112
float f_BCL
Definition globals.cpp:12
float deathinhibit
Definition globals.cpp:39
s_universe_object allobjects[maxstarC]
Definition globals.cpp:108
Scockpit ourcockpit
Definition globals.cpp:114
bool g_bAboveClouds
Definition globals.cpp:16
LOCALGRID2 gridarray[64][64]
Definition globals.cpp:100
float payload
Definition globals.cpp:92
bool g_bAugment
Definition globals.cpp:47
#define iceWeightLbsPerSqFtPerMm
Definition globals.h:92
#define adiabaticIndex
Definition globals.h:96
#define oneOvergForceKmssC
Definition globals.h:109
#define MaxAcceleration
Definition globals.h:45
#define rhoOver2SlugsCuFt2
Definition globals.h:95
#define feetPerKilometerC
Definition globals.h:101
#define gasConstantm2s2K
Definition globals.h:97
#define ScaleHeightC
Definition globals.h:98
#define radiusC
Definition globals.h:87
#define SeaLevelPressureMb
Definition globals.h:102
@ CFIT
Definition globals.h:151
@ Ditching
Definition globals.h:159
@ VesselHadAProblem
Definition globals.h:158
@ TwinTowers
Definition globals.h:154
#define trimlimiterC
Definition globals.h:44
#define SeaLevelSpeedOfSoundKms
Definition globals.h:103
#define cloudTopsMslC
Definition globals.h:110
#define flatPlateDragCoefficient
Definition globals.h:93
#define gForceKmSSC
Definition globals.h:108
#define Kg2Lbs
Definition globals.h:40
#define Lbs2NC
Definition globals.h:41
#define SeaLevelDensityKgM3
Definition globals.h:99
#define SqFt2SqMC
Definition globals.h:106
#define ZeroCelsiusToKelvin
Definition globals.h:42
#define gravityKmssC
Definition globals.h:88
#define OneAtmosphereMb
Definition globals.h:104
@ GUI_REMINDME
Definition gui.h:984
float RollInput(float desired, float actual, float rate, float previous, float aggression, float weight, float dt)
Definition AfcsControl.h:81
float Lerp(float a, float b, float t)
Definition CloudVolume.h:50
int SlotForEngine(int engineCount, int engine)
Definition EngineAudio.h:12
float Strength(float output)
bool Valid(double horizontal, double vertical)
Definition FlightPath.h:11
double Pitch(double selected, double horizontal, double vertical, double pitch, double previous, double dt)
Definition FlightPath.h:24
void Publish(Sample &sample, float elapsed, const Vector3 &bodyWindKms, const RiseMath::Matrix &bodyToWorld, const Vector3 &groundVelocityKms, const Vector3 &position, int vehicle, bool simulator, bool available)
float Dot(const Vector3 &a, const Vector3 &b)
float ResolveLateralVelocity(float velocityKms, float staticDeltaVKms, float kineticDeltaVKms)
double HeadingBank(double desired, double actual, double limit)
MainCommand MainEngine(double acceleration, double forward, double reverse, double output, double reverser, bool reverseCommand=false)
constexpr double YawRcsForce
Vec CoastRotationCommand(const BusState &data, double now, const RotationState &in, Vec pilot)
bool AscentPitchControl(const BusState &b, bool engaged, double now, bool airborne, bool frozen)
Vec OrbitalRcsRequest(Vec deltaBody, double mainGrossAcceleration, bool hasMains)
Definition OrbitBurn.h:10
constexpr double RollRcsForce
Vec ControlVelocityError(const BusState &data, double now)
Definition OrbitState.h:359
constexpr double PitchRcsForce
Vec RotationAuthority(double weight, double pitchInertia, double yawInertia, double rollInertia, double arm, double span, double leftWing, double rightWing, double effort, double wear)
Vec RotationCommand(const BusState &data, double now, double available=1)
PitchAllocation AllocatePitch(double desired, double external, double rcsCapacity, double previous, double surfaceLimit, double dt, TailMoment tail)
float ThrustMultiplier(State state)
Definition RainAir.h:23
double ClientTime()
auto ToRadian(T value)
Definition ClientMath.h:13
float Vec3Length(const Vector3 *a)
Definition ClientMath.h:95
constexpr float Pi
Definition ClientMath.h:12
constexpr auto Min(A first, B second)
Definition ClientMath.h:15
Vector3 * Vec3TransformCoord(Vector3 *out, const Vector3 *a, const Matrix *m)
Definition ClientMath.h:109
Quaternion * QuaternionMultiply(Quaternion *out, const Quaternion *a, const Quaternion *b)
Definition ClientMath.h:168
Matrix * MatrixRotationQuaternion(Matrix *out, const Quaternion *q)
Definition ClientMath.h:135
Quaternion * QuaternionNormalize(Quaternion *out, const Quaternion *q)
Definition ClientMath.h:165
Vector3 * Vec3Subtract(Vector3 *out, const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:97
Quaternion * QuaternionRotationYawPitchRoll(Quaternion *out, float yaw, float pitch, float roll)
Definition ClientMath.h:169
Vector3 * Vec3TransformNormal(Vector3 *out, const Vector3 *a, const Matrix *m)
Definition ClientMath.h:107
Matrix * MatrixInverse(Matrix *out, float *determinant, const Matrix *a)
Definition ClientMath.h:118
constexpr float Tau
Definition ClientMath.h:12
Matrix * MatrixRotationAxis(Matrix *out, const Vector3 *axis, float angle)
Definition ClientMath.h:129
float Vec3Dot(const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:93
Vector3 * Vec3Normalize(Vector3 *out, const Vector3 *a)
Definition ClientMath.h:103
Vector3 * Vec3Scale(Vector3 *out, const Vector3 *a, float scale)
Definition ClientMath.h:98
auto ToDegree(T value)
Definition ClientMath.h:14
constexpr auto Max(A first, B second)
Definition ClientMath.h:16
constexpr float HalfPi
Definition ClientMath.h:12
double MonotonicSeconds()
Result Command(const Input &in, double manualPitch, double manualRoll)
Definition TvmLeveling.h:37
bool GroundReference(const Bus &bus, const Ship(&ships)[Count], int onGround, int inAnother, double radius)
Definition TvmLeveling.h:9
float ApplyControlPlay(float input, float play)
Definition VehicleWear.h:37
Factors Calculate(float usage, bool groundVehicle)
Definition VehicleWear.h:24
float RestoreControlInput(float output, float play)
Definition VehicleWear.h:49
#define maxDragIncreaseApproachingMachC
Definition propulsion.h:25
Result Step(float pitchAtt, float desiredPitch, float stick, float qz, float f_augment, float elapsed)
Definition AfcsControl.h:15
float DesiredPitchRadians
Definition Bus.h:141
float DesiredRollRadians
Definition Bus.h:140
float DesiredAltitudeKm
Definition Bus.h:122
@ Navigation
Definition Bus.h:115
@ LateralMode_Off
Definition Bus.h:112
@ Localizer
Definition Bus.h:116
@ Heading
Definition Bus.h:114
@ LateralMode_TakeOff
Definition Bus.h:111
float DorHeadingRadians
Definition Bus.h:150
float DesiredHeadingRadians
Definition Bus.h:133
@ Glideslope
Definition Bus.h:104
@ FlightPathAngle
Definition Bus.h:99
@ SpeedPitch
Definition Bus.h:101
@ Pitch
Definition Bus.h:98
@ VerticalMode_Off
Definition Bus.h:97
@ VerticalMode_TakeOff
Definition Bus.h:96
@ VerticalSpeed
Definition Bus.h:100
@ AltitudeAgl
Definition Bus.h:103
@ AltitudeMsl
Definition Bus.h:102
bool DorOn
Definition Bus.h:148
float TvmCurrentClosingSpeed
Definition Bus.h:153
bool AutothrottleEngaged
Definition Bus.h:88
float PitchInput
Definition Bus.h:144
bool TvmOn
Definition Bus.h:151
enum Bus::Afcs::LateralModes CurrentLateralMode
float DesiredVsiKms
Definition Bus.h:129
float DesiredCourseRadians
Definition Bus.h:136
bool AutopilotEngaged
Definition Bus.h:87
bool DorAircraft
Definition Bus.h:149
float DesiredClosingSpeed
Definition Bus.h:152
enum Bus::Afcs::VerticalModes StandbyVerticalMode
enum Bus::Afcs::LateralModes StandbyLateralMode
float DesiredIasKms
Definition Bus.h:126
enum Bus::Afcs::VerticalModes CurrentVerticalMode
std::string name
Definition Command.h:11
unsigned char sec_landform
Definition globals.h:280
unsigned char pri_landform
Definition globals.h:278
unsigned char sec_transition
Definition globals.h:281
unsigned char pri_transition
Definition globals.h:279
unsigned char ter_landform
Definition globals.h:282
ActuationTelemetry actuation
Definition OrbitState.h:349
unsigned short sampleTimeMs
unsigned char airIceAccumulationMm
RiseMath::Vector3 velocity
RiseMath::Quaternion orientation
unsigned short fuel
unsigned char groundIceAccumulationMm
RiseMath::Vector3 position
unsigned char array
unsigned char ship
unsigned char inarray
unsigned char type
char leftaileron
char leftengine
char rightaileron
char autoflyte
char parkingBrake
char rightBrake
char rightStrut
char leftwing
char noseStrut
char elevator
char rightwing
char rightengine
char yawdamper
char thrustaug
char leftStrut
char leftBrake
char clengine
float Vs2
Definition globals.h:644
float dntranslimit
Definition globals.h:601
float tireComplianceKm
Definition globals.h:620
float revthrustlimit
Definition globals.h:601
float skidSteerDifferentialRatio
Definition globals.h:654
float d17VTailWithRudderSqFt
Definition globals.h:638
float f28SideDragCoefficient
Definition globals.h:638
float maxGrossLbs
Definition globals.h:634
short texturelib
Definition globals.h:602
float elevatorAreaMod
Definition globals.h:720
float c9WingYawArmM
Definition globals.h:639
float lrtranslimit
Definition globals.h:601
float momentr
Definition globals.h:636
float flapAreaModTE
Definition globals.h:716
char fwdgears
Definition globals.h:677
float h9RudderSqFt
Definition globals.h:638
float wingspanM
Definition globals.h:640
float i66wasi62
Definition globals.h:640
float b12WingRollArmM
Definition globals.h:639
float b6DistanceToHTailM
Definition globals.h:639
float fuelFlowIdleLbsPerSec
Definition globals.h:647
float d65wasd61
Definition globals.h:640
float aprolagr
Definition globals.h:648
float steerLimitRadian
Definition globals.h:651
float k65wask61
Definition globals.h:640
float uptranslimit
Definition globals.h:601
float f27PlanDragCoefficient
Definition globals.h:638
float speedLimiterKph
Definition globals.h:735
float ffmax
Definition globals.h:647
float e65wase61
Definition globals.h:640
float d15TotalWingAreaSqFt
Definition globals.h:718
float power
Definition globals.h:599
float currentFuelFlowPoundsPerSecond
Definition globals.h:673
float appitagr
Definition globals.h:648
float bypassPercentage
Definition globals.h:711
float aileronAreaMod
Definition globals.h:719
float momentp
Definition globals.h:636
float tireRadiusKm
Definition globals.h:733
float d27DerivedPlanAreaSqFt
Definition globals.h:641
float VcMSL
Definition globals.h:642
float flapExtent
Definition globals.h:660
float momenty
Definition globals.h:636
float fuelmax
Definition globals.h:647
float engineEfficiencyAtSeaLevelScalar
Definition globals.h:738
float f20FrontBackDragCoeff
Definition globals.h:638
float d16HTailWithElevatorSqFt
Definition globals.h:639
AirfoilType wings
Definition globals.h:659
float skidSteerInputCenteringScale
Definition globals.h:656
float i65wasi61
Definition globals.h:640
float emptyWeightLbs
Definition globals.h:633
float redlineRPM
Definition globals.h:679
float machAngleDragScalar
Definition globals.h:736
float rcsYParmM
Definition globals.h:640
SVesselDC vdat
Definition globals.h:664
float noseWheelToCgKm
Definition globals.h:650
float wingElevationM
Definition globals.h:640
float aoiWingRad
Definition globals.h:657
char gearshift
Definition globals.h:677
float l48AverageEnginePitchArmM
Definition globals.h:713
float b15WingPitchArmM
Definition globals.h:639
float tach
Definition globals.h:676
float gearextent
Definition globals.h:617
float flapMaxDegrees
Definition globals.h:714
float f25
Definition globals.h:638
float landingGearLengthKm
Definition globals.h:617
float i12WingAreaOneSideSqFt
Definition globals.h:638
float suspensionTravelKm
Definition globals.h:618
float hStabAngleOfIncidenceRad
Definition globals.h:658
float adrenolinBPM
Definition globals.h:741
float clutchtime
Definition globals.h:676
bool parkingBrake
Definition globals.h:709
float suspensionTrackWidthKm
Definition globals.h:619
float idleRPM
Definition globals.h:679
float spoilerAreaMod
Definition globals.h:717
bool vdatChanged
Definition globals.h:665
unsigned char hitpoints
Definition globals.h:686
bool wheeled
Definition globals.h:596
float criticalEngineAltitudeKm
Definition globals.h:712
float strutsrettoCGKm
Definition globals.h:624
float usage
Definition globals.h:670
float landingGearAbsorbKms
Definition globals.h:617
float b9DistanceToVTailM
Definition globals.h:639
float wheelBaseKm
Definition globals.h:752
float clutchhold
Definition globals.h:676
float suspensionRideHeightKm
Definition globals.h:618
float flapAreaModLE
Definition globals.h:715
GroundSteeringMode groundSteeringMode
Definition globals.h:652
float ratios[8]
Definition globals.h:678
char engines
Definition globals.h:630
float exteriorInsulationHeatTransferCoefficient
https://en.wikipedia.org/wiki/List_of_thermal_conductivities
Definition globals.h:729
char struts
Definition globals.h:630
float i48CriticalEngineYawArmM
Definition globals.h:649
float vdatTime
Definition globals.h:666
float rooftoCGKm
Definition globals.h:624
char steerTires
Definition globals.h:628
float spoolTime
Definition globals.h:601
float pitchLimitRadians
Definition globals.h:734
float k66wask62
Definition globals.h:640
float fwdthrustlimit
Definition globals.h:601
float elevationKm
short heading
RiseMath::Vector3 location
Orbital::Vec pilot
Definition TvmLeveling.h:30
Orbital::Vec radial
Definition TvmLeveling.h:30
Orbital::RotationState rotation
Definition TvmLeveling.h:29
float curbelev
Definition globals.h:477
float elevation
Definition globals.h:476
RiseMath::Vector3 barycentric
Definition globals.h:500
RiseMath::Quaternion orientation
Definition globals.h:521
RiseMath::Vector3 dockingvel
Definition globals.h:500
RiseMath::Vector3 position
Definition globals.h:511
double precisionz
Definition globals.h:512
RiseMath::Vector3 acc
Definition globals.h:504
RiseMath::Vector3 dockoffset
Definition globals.h:511
unsigned short vehicleId
Definition globals.h:537
double precisiony
Definition globals.h:512
RiseMath::Vector3 velocity
Definition globals.h:500
float rollRadPerSec
Definition globals.h:523
double precisionx
Definition globals.h:512
unsigned char inarray
Definition globals.h:509
RiseMath::Matrix matrixWorld
Definition globals.h:517
RiseMath::Vector3 velocity
Definition globals.h:461