]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Merge branch 'maint' into next
[flightgear.git] / src / FDM / JSBSim / models / propulsion / FGPiston.cpp
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3  Module:       FGPiston.cpp
4  Author:       Jon S. Berndt, JSBSim framework
5                Dave Luff, Piston engine model
6                Ronald Jensen, Piston engine model
7  Date started: 09/12/2000
8  Purpose:      This module models a Piston engine
9
10  ------------- Copyright (C) 2000  Jon S. Berndt (jsb@hal-pc.org) --------------
11
12  This program is free software; you can redistribute it and/or modify it under
13  the terms of the GNU Lesser General Public License as published by the Free Software
14  Foundation; either version 2 of the License, or (at your option) any later
15  version.
16
17  This program is distributed in the hope that it will be useful, but WITHOUT
18  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
20  details.
21
22  You should have received a copy of the GNU Lesser General Public License along with
23  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
24  Place - Suite 330, Boston, MA  02111-1307, USA.
25
26  Further information about the GNU Lesser General Public License can also be found on
27  the world wide web at http://www.gnu.org.
28
29 FUNCTIONAL DESCRIPTION
30 --------------------------------------------------------------------------------
31
32 This class descends from the FGEngine class and models a Piston engine based on
33 parameters given in the engine config file for this class
34
35 HISTORY
36 --------------------------------------------------------------------------------
37 09/12/2000  JSB  Created
38
39 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40 INCLUDES
41 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
42
43 #include <sstream>
44
45 #include "FGPiston.h"
46 #include <models/FGPropulsion.h>
47 #include "FGPropeller.h"
48
49 namespace JSBSim {
50
51 static const char *IdSrc = "$Id$";
52 static const char *IdHdr = ID_PISTON;
53
54 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55 CLASS IMPLEMENTATION
56 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
57
58 FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number)
59   : FGEngine(exec, el, engine_number),
60   R_air(287.3),                  // Gas constant for air J/Kg/K
61   rho_fuel(800),                 // estimate
62   calorific_value_fuel(47.3e6),
63   Cp_air(1005),                  // Specific heat (constant pressure) J/Kg/K
64   Cp_fuel(1700)
65 {
66   string token;
67
68   // Defaults and initializations
69
70   Type = etPiston;
71   dt = State->Getdt();
72
73   // These items are read from the configuration file
74
75   Cycles = 2;
76   IdleRPM = 600;
77   MaxRPM = 2800;
78   Displacement = 360;
79   SparkFailDrop = 1.0;
80   MaxHP = 200;
81   MinManifoldPressure_inHg = 6.5;
82   MaxManifoldPressure_inHg = 28.5;
83   BSFC = -1;
84
85   // Initialisation
86   volumetric_efficiency = 0.8;  // Actually f(speed, load) but this will get us running
87
88   // These are internal program variables
89
90   crank_counter = 0;
91   Magnetos = 0;
92   minMAP = 21950;
93   maxMAP = 96250;
94
95   ResetToIC();
96
97   // Supercharging
98   BoostSpeeds = 0;  // Default to no supercharging
99   BoostSpeed = 0;
100   Boosted = false;
101   BoostOverride = 0;
102   bBoostOverride = false;
103   bTakeoffBoost = false;
104   TakeoffBoost = 0.0;   // Default to no extra takeoff-boost
105   int i;
106   for (i=0; i<FG_MAX_BOOST_SPEEDS; i++) {
107     RatedBoost[i] = 0.0;
108     RatedPower[i] = 0.0;
109     RatedAltitude[i] = 0.0;
110     BoostMul[i] = 1.0;
111     RatedMAP[i] = 100000;
112     RatedRPM[i] = 2500;
113     TakeoffMAP[i] = 100000;
114   }
115   for (i=0; i<FG_MAX_BOOST_SPEEDS-1; i++) {
116     BoostSwitchAltitude[i] = 0.0;
117     BoostSwitchPressure[i] = 0.0;
118   }
119
120   // First column is thi, second is neta (combustion efficiency)
121   Lookup_Combustion_Efficiency = new FGTable(12);
122   *Lookup_Combustion_Efficiency << 0.00 << 0.980;
123   *Lookup_Combustion_Efficiency << 0.90 << 0.980;
124   *Lookup_Combustion_Efficiency << 1.00 << 0.970;
125   *Lookup_Combustion_Efficiency << 1.05 << 0.950;
126   *Lookup_Combustion_Efficiency << 1.10 << 0.900;
127   *Lookup_Combustion_Efficiency << 1.15 << 0.850;
128   *Lookup_Combustion_Efficiency << 1.20 << 0.790;
129   *Lookup_Combustion_Efficiency << 1.30 << 0.700;
130   *Lookup_Combustion_Efficiency << 1.40 << 0.630;
131   *Lookup_Combustion_Efficiency << 1.50 << 0.570;
132   *Lookup_Combustion_Efficiency << 1.60 << 0.525;
133   *Lookup_Combustion_Efficiency << 2.00 << 0.345;
134
135   Mixture_Efficiency_Correlation = new FGTable(15);
136   *Mixture_Efficiency_Correlation << 0.05000 << 0.00000;
137   *Mixture_Efficiency_Correlation << 0.05137 << 0.00862;
138   *Mixture_Efficiency_Correlation << 0.05179 << 0.21552;
139   *Mixture_Efficiency_Correlation << 0.05430 << 0.48276;
140   *Mixture_Efficiency_Correlation << 0.05842 << 0.70690;
141   *Mixture_Efficiency_Correlation << 0.06312 << 0.83621;
142   *Mixture_Efficiency_Correlation << 0.06942 << 0.93103;
143   *Mixture_Efficiency_Correlation << 0.07786 << 1.00000;
144   *Mixture_Efficiency_Correlation << 0.08845 << 1.00000;
145   *Mixture_Efficiency_Correlation << 0.09270 << 0.98276;
146   *Mixture_Efficiency_Correlation << 0.10120 << 0.93103;
147   *Mixture_Efficiency_Correlation << 0.11455 << 0.72414;
148   *Mixture_Efficiency_Correlation << 0.12158 << 0.45690;
149   *Mixture_Efficiency_Correlation << 0.12435 << 0.23276;
150   *Mixture_Efficiency_Correlation << 0.12500 << 0.00000;
151
152
153   // Read inputs from engine data file where present.
154
155   if (el->FindElement("minmp")) // Should have ELSE statement telling default value used?
156     MinManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("minmp","INHG");
157   if (el->FindElement("maxmp"))
158     MaxManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("maxmp","INHG");
159   if (el->FindElement("displacement"))
160     Displacement = el->FindElementValueAsNumberConvertTo("displacement","IN3");
161   if (el->FindElement("maxhp"))
162     MaxHP = el->FindElementValueAsNumberConvertTo("maxhp","HP");
163   if (el->FindElement("sparkfaildrop"))
164     SparkFailDrop = Constrain(0, 1 - el->FindElementValueAsNumber("sparkfaildrop"), 1);
165   if (el->FindElement("cycles"))
166     Cycles = el->FindElementValueAsNumber("cycles");
167   if (el->FindElement("idlerpm"))
168     IdleRPM = el->FindElementValueAsNumber("idlerpm");
169   if (el->FindElement("maxrpm"))
170     MaxRPM = el->FindElementValueAsNumber("maxrpm");
171   if (el->FindElement("maxthrottle"))
172     MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
173   if (el->FindElement("minthrottle"))
174     MinThrottle = el->FindElementValueAsNumber("minthrottle");
175   if (el->FindElement("bsfc"))
176     BSFC = el->FindElementValueAsNumberConvertTo("bsfc", "LBS/HP*HR");
177   if (el->FindElement("volumetric-efficiency"))
178     volumetric_efficiency = el->FindElementValueAsNumber("volumetric-efficiency");
179   if (el->FindElement("numboostspeeds")) { // Turbo- and super-charging parameters
180     BoostSpeeds = (int)el->FindElementValueAsNumber("numboostspeeds");
181     if (el->FindElement("boostoverride"))
182       BoostOverride = (int)el->FindElementValueAsNumber("boostoverride");
183     if (el->FindElement("takeoffboost"))
184       TakeoffBoost = el->FindElementValueAsNumberConvertTo("takeoffboost", "PSI");
185     if (el->FindElement("ratedboost1"))
186       RatedBoost[0] = el->FindElementValueAsNumberConvertTo("ratedboost1", "PSI");
187     if (el->FindElement("ratedboost2"))
188       RatedBoost[1] = el->FindElementValueAsNumberConvertTo("ratedboost2", "PSI");
189     if (el->FindElement("ratedboost3"))
190       RatedBoost[2] = el->FindElementValueAsNumberConvertTo("ratedboost3", "PSI");
191     if (el->FindElement("ratedpower1"))
192       RatedPower[0] = el->FindElementValueAsNumberConvertTo("ratedpower1", "HP");
193     if (el->FindElement("ratedpower2"))
194       RatedPower[1] = el->FindElementValueAsNumberConvertTo("ratedpower2", "HP");
195     if (el->FindElement("ratedpower3"))
196       RatedPower[2] = el->FindElementValueAsNumberConvertTo("ratedpower3", "HP");
197     if (el->FindElement("ratedrpm1"))
198       RatedRPM[0] = el->FindElementValueAsNumber("ratedrpm1");
199     if (el->FindElement("ratedrpm2"))
200       RatedRPM[1] = el->FindElementValueAsNumber("ratedrpm2");
201     if (el->FindElement("ratedrpm3"))
202       RatedRPM[2] = el->FindElementValueAsNumber("ratedrpm3");
203     if (el->FindElement("ratedaltitude1"))
204       RatedAltitude[0] = el->FindElementValueAsNumberConvertTo("ratedaltitude1", "FT");
205     if (el->FindElement("ratedaltitude2"))
206       RatedAltitude[1] = el->FindElementValueAsNumberConvertTo("ratedaltitude2", "FT");
207     if (el->FindElement("ratedaltitude3"))
208       RatedAltitude[2] = el->FindElementValueAsNumberConvertTo("ratedaltitude3", "FT");
209   }
210
211   MaxManifoldPressure_Percent = MaxManifoldPressure_inHg / 29.92;
212   // Create a BSFC to match the engine if not provided
213   if (BSFC < 0) {
214       BSFC = ( Displacement * MaxRPM * volumetric_efficiency ) / (9411 * MaxHP);
215       BSFC *= (MaxManifoldPressure_Percent * MaxManifoldPressure_Percent * MaxManifoldPressure_Percent);
216   }
217   if ( MaxManifoldPressure_inHg > 29.9 ) {   // Don't allow boosting with a bogus number
218       MaxManifoldPressure_inHg = 29.9;
219       MaxManifoldPressure_Percent = MaxManifoldPressure_inHg / 29.92;
220   }
221
222   char property_name[80];
223   snprintf(property_name, 80, "propulsion/engine[%d]/power-hp", EngineNumber);
224   PropertyManager->Tie(property_name, &HP);
225   snprintf(property_name, 80, "propulsion/engine[%d]/bsfc-lbs_hphr", EngineNumber);
226   PropertyManager->Tie(property_name, &BSFC);
227   snprintf(property_name, 80, "propulsion/engine[%d]/volumetric-efficiency", EngineNumber);
228   PropertyManager->Tie(property_name, &volumetric_efficiency);
229   minMAP = MinManifoldPressure_inHg * inhgtopa;  // inHg to Pa
230   maxMAP = MaxManifoldPressure_inHg * inhgtopa;
231   StarterHP = sqrt(MaxHP) * 0.4;
232
233   // Set up and sanity-check the turbo/supercharging configuration based on the input values.
234   if (TakeoffBoost > RatedBoost[0]) bTakeoffBoost = true;
235   for (i=0; i<BoostSpeeds; ++i) {
236     bool bad = false;
237     if (RatedBoost[i] <= 0.0) bad = true;
238     if (RatedPower[i] <= 0.0) bad = true;
239     if (RatedAltitude[i] < 0.0) bad = true;  // 0.0 is deliberately allowed - this corresponds to unregulated supercharging.
240     if (i > 0 && RatedAltitude[i] < RatedAltitude[i - 1]) bad = true;
241     if (bad) {
242       // We can't recover from the above - don't use this supercharger speed.
243       BoostSpeeds--;
244       // TODO - put out a massive error message!
245       break;
246     }
247     // Now sanity-check stuff that is recoverable.
248     if (i < BoostSpeeds - 1) {
249       if (BoostSwitchAltitude[i] < RatedAltitude[i]) {
250         // TODO - put out an error message
251         // But we can also make a reasonable estimate, as below.
252         BoostSwitchAltitude[i] = RatedAltitude[i] + 1000;
253       }
254       BoostSwitchPressure[i] = Atmosphere->GetPressure(BoostSwitchAltitude[i]) * psftopa;
255       //cout << "BoostSwitchAlt = " << BoostSwitchAltitude[i] << ", pressure = " << BoostSwitchPressure[i] << '\n';
256       // Assume there is some hysteresis on the supercharger gear switch, and guess the value for now
257       BoostSwitchHysteresis = 1000;
258     }
259     // Now work out the supercharger pressure multiplier of this speed from the rated boost and altitude.
260     RatedMAP[i] = Atmosphere->GetPressureSL() * psftopa + RatedBoost[i] * 6895;  // psi*6895 = Pa.
261     // Sometimes a separate BCV setting for takeoff or extra power is fitted.
262     if (TakeoffBoost > RatedBoost[0]) {
263       // Assume that the effect on the BCV is the same whichever speed is in use.
264       TakeoffMAP[i] = RatedMAP[i] + ((TakeoffBoost - RatedBoost[0]) * 6895);
265       bTakeoffBoost = true;
266     } else {
267       TakeoffMAP[i] = RatedMAP[i];
268       bTakeoffBoost = false;
269     }
270     BoostMul[i] = RatedMAP[i] / (Atmosphere->GetPressure(RatedAltitude[i]) * psftopa);
271
272   }
273
274   if (BoostSpeeds > 0) {
275     Boosted = true;
276     BoostSpeed = 0;
277   }
278   bBoostOverride = (BoostOverride == 1 ? true : false);
279   if (MinThrottle < 0.12) MinThrottle = 0.12;  //MinThrottle is limited to 0.12 to prevent the
280                                                // throttle area equation from going negative
281                                                // 0.12 is 1% of maximum area
282   Debug(0); // Call Debug() routine from constructor if needed
283 }
284
285 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
286
287 FGPiston::~FGPiston()
288 {
289   delete Lookup_Combustion_Efficiency;
290   delete Mixture_Efficiency_Correlation;
291   Debug(1); // Call Debug() routine from constructor if needed
292 }
293
294 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
295
296 void FGPiston::ResetToIC(void)
297 {
298   FGEngine::ResetToIC();
299
300   ManifoldPressure_inHg = Atmosphere->GetPressure() * psftoinhg; // psf to in Hg
301   MAP = Atmosphere->GetPressure() * psftopa;
302   double airTemperature_degK = RankineToKelvin(Atmosphere->GetTemperature());
303   OilTemp_degK = airTemperature_degK;
304   CylinderHeadTemp_degK = airTemperature_degK;
305   ExhaustGasTemp_degK = airTemperature_degK;
306   EGT_degC = ExhaustGasTemp_degK - 273;
307   Thruster->SetRPM(0.0);
308   RPM = 0.0;
309   OilPressure_psi = 0.0;
310 }
311
312 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313
314 double FGPiston::Calculate(void)
315 {
316   if (FuelFlow_gph > 0.0) ConsumeFuel();
317
318   Throttle = FCS->GetThrottlePos(EngineNumber);
319   // calculate the throttle plate angle.  1 unit is pi/2 radians.
320   ThrottleAngle = MinThrottle+((MaxThrottle-MinThrottle)*Throttle );
321   Mixture = FCS->GetMixturePos(EngineNumber);
322
323   //
324   // Input values.
325   //
326
327   p_amb = Atmosphere->GetPressure() * psftopa;
328   p_amb_sea_level = Atmosphere->GetPressureSL() * psftopa;
329   T_amb = RankineToKelvin(Atmosphere->GetTemperature());
330
331   RPM = Thruster->GetRPM() * Thruster->GetGearRatio();
332
333   IAS = Auxiliary->GetVcalibratedKTS();
334
335   doEngineStartup();
336   if (Boosted) doBoostControl();
337   doMAP();
338   doAirFlow();
339   doFuelFlow();
340
341   //Now that the fuel flow is done check if the mixture is too lean to run the engine
342   //Assume lean limit at 22 AFR for now - thats a thi of 0.668
343   //This might be a bit generous, but since there's currently no audiable warning of impending
344   //cutout in the form of misfiring and/or rough running its probably reasonable for now.
345 //  if (equivalence_ratio < 0.668)
346 //    Running = false;
347
348   doEnginePower();
349   if (HP < 0.1250) Running = false;
350
351   doEGT();
352   doCHT();
353   doOilTemperature();
354   doOilPressure();
355
356   if (Thruster->GetType() == FGThruster::ttPropeller) {
357     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
358     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
359   }
360
361   PowerAvailable = (HP * hptoftlbssec) - Thruster->GetPowerRequired();
362
363   return Thruster->Calculate(PowerAvailable);
364 }
365
366 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
367
368 double FGPiston::CalcFuelNeed(void)
369 {
370   double dT = State->Getdt() * Propulsion->GetRate();
371   FuelExpended = FuelFlowRate * dT;
372   return FuelExpended;
373 }
374
375 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
376
377 int FGPiston::InitRunning(void) {
378   Magnetos=3;
379   //Thruster->SetRPM( 1.1*IdleRPM/Thruster->GetGearRatio() );
380   Thruster->SetRPM( 1000 );
381   Running=true;
382   return 1;
383 }
384
385 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
386 /**
387  * Start or stop the engine.
388  */
389
390 void FGPiston::doEngineStartup(void)
391 {
392   // Check parameters that may alter the operating state of the engine.
393   // (spark, fuel, starter motor etc)
394   bool spark;
395   bool fuel;
396
397   // Check for spark
398   Magneto_Left = false;
399   Magneto_Right = false;
400   // Magneto positions:
401   // 0 -> off
402   // 1 -> left only
403   // 2 -> right only
404   // 3 -> both
405   if (Magnetos != 0) {
406     spark = true;
407   } else {
408     spark = false;
409   }  // neglects battery voltage, master on switch, etc for now.
410
411   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
412   if (Magnetos > 1)  Magneto_Right = true;
413
414   // Assume we have fuel for now
415   fuel = !Starved;
416
417   // Check if we are turning the starter motor
418   if (Cranking != Starter) {
419     // This check saves .../cranking from getting updated every loop - they
420     // only update when changed.
421     Cranking = Starter;
422     crank_counter = 0;
423   }
424
425   if (Cranking) crank_counter++;  //Check mode of engine operation
426
427   if (!Running && spark && fuel) {  // start the engine if revs high enough
428     if (Cranking) {
429       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
430         Running = true;                         // on the starter
431     } else {
432       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
433         Running = true;                         // when windmilling
434     }
435   }
436
437   // Cut the engine *power* - Note: the engine may continue to
438   // spin if the prop is in a moving airstream
439
440   if ( Running && (!spark || !fuel) ) Running = false;
441
442   // Check for stalling (RPM = 0).
443   if (Running) {
444     if (RPM == 0) {
445       Running = false;
446     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
447       Running = false;
448     }
449   }
450 }
451
452 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
453
454 /**
455  * Calculate the Current Boost Speed
456  *
457  * This function calculates the current turbo/supercharger boost speed
458  * based on altitude and the (automatic) boost-speed control valve configuration.
459  *
460  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
461  *
462  * Outputs: BoostSpeed
463  */
464
465 void FGPiston::doBoostControl(void)
466 {
467   if(BoostSpeed < BoostSpeeds - 1) {
468     // Check if we need to change to a higher boost speed
469     if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
470       BoostSpeed++;
471     }
472   } else if(BoostSpeed > 0) {
473     // Check if we need to change to a lower boost speed
474     if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
475       BoostSpeed--;
476     }
477   }
478 }
479
480 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
481
482 /**
483  * Calculate the manifold absolute pressure (MAP) in inches hg
484  *
485  * This function calculates manifold absolute pressure (MAP)
486  * from the throttle position, turbo/supercharger boost control
487  * system, engine speed and local ambient air density.
488  *
489  * Inputs: p_amb, Throttle, MaxManifoldPressure_Percent, ThrottleAngle
490  *         RPM, MaxRPM
491  *
492  * Outputs: MAP, ManifoldPressure_inHg
493  */
494
495 void FGPiston::doMAP(void)
496 {
497  // estimate throttle plate area.  This maps 0.2 -> 0.1 for historical performance reasons
498     double throttle_area = ThrottleAngle * 1.125 - 0.125;
499     map_coefficient = pow ((throttle_area * MaxManifoldPressure_Percent),RPM/MaxRPM);
500     MAP = p_amb * map_coefficient;
501
502     if(Boosted) {
503       // If takeoff boost is fitted, we currently assume the following throttle map:
504       // (In throttle % - actual input is 0 -> 1)
505       // 99 / 100 - Takeoff boost
506       // 96 / 97 / 98 - Rated boost
507       // 0 - 95 - Idle to Rated boost (MinManifoldPressure to MaxManifoldPressure)
508       // In real life, most planes would be fitted with a mechanical 'gate' between
509       // the rated boost and takeoff boost positions.
510       double T = Throttle; // processed throttle value.
511       bool bTakeoffPos = false;
512       if(bTakeoffBoost) {
513         if(Throttle > 0.98) {
514           //cout << "Takeoff Boost!!!!\n";
515           bTakeoffPos = true;
516         } else if(Throttle <= 0.95) {
517           bTakeoffPos = false;
518           T *= 1.0 / 0.95;
519         } else {
520           bTakeoffPos = false;
521           //cout << "Rated Boost!!\n";
522           T = 1.0;
523         }
524       }
525       // Boost the manifold pressure.
526       double boost_factor = BoostMul[BoostSpeed] * map_coefficient * RPM/RatedRPM[BoostSpeed];
527       if (boost_factor < 1.0) boost_factor = 1.0;  // boost will never reduce the MAP
528       MAP *= boost_factor;
529       // Now clip the manifold pressure to BCV or Wastegate setting.
530       if(bTakeoffPos) {
531         if(MAP > TakeoffMAP[BoostSpeed]) {
532           MAP = TakeoffMAP[BoostSpeed];
533         }
534       } else {
535         if(MAP > RatedMAP[BoostSpeed]) {
536           MAP = RatedMAP[BoostSpeed];
537         }
538       }
539     }
540
541   // And set the value in American units as well
542   ManifoldPressure_inHg = MAP / inhgtopa;
543 }
544
545 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
546 /**
547  * Calculate the air flow through the engine.
548  * Also calculates ambient air density
549  * (used in CHT calculation for air-cooled engines).
550  *
551  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
552  *   RPM, volumetric_efficiency, ThrottleAngle
553  *
554  * TODO: Model inlet manifold air temperature.
555  *
556  * Outputs: rho_air, m_dot_air
557  */
558
559 void FGPiston::doAirFlow(void)
560 {
561   rho_air = p_amb / (R_air * T_amb);
562   double displacement_SI = Displacement * in3tom3;
563   double swept_volume = (displacement_SI * (RPM/60)) / 2;
564   double v_dot_air = swept_volume * volumetric_efficiency * map_coefficient;
565
566   double rho_air_manifold = MAP / (R_air * T_amb);
567   m_dot_air = v_dot_air * rho_air_manifold;
568 }
569
570 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
571 /**
572  * Calculate the fuel flow into the engine.
573  *
574  * Inputs: Mixture, thi_sea_level, p_amb_sea_level, p_amb, m_dot_air
575  *
576  * Outputs: equivalence_ratio, m_dot_fuel
577  */
578
579 void FGPiston::doFuelFlow(void)
580 {
581   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
582   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
583 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
584 //  m_dot_fuel = m_dot_air / AFR;
585   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
586   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
587   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
588   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
589 }
590
591 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
592 /**
593  * Calculate the power produced by the engine.
594  *
595  * Currently, the JSBSim propellor model does not allow the
596  * engine to produce enough RPMs to get up to a high horsepower.
597  * When tested with sufficient RPM, it has no trouble reaching
598  * 200HP.
599  *
600  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb,
601  *   Mixture_Efficiency_Correlation, Cycles, MaxHP
602  *
603  * Outputs: Percentage_Power, HP
604  */
605
606 void FGPiston::doEnginePower(void)
607 {
608   if (Running) {
609     double T_amb_degF = KelvinToFahrenheit(T_amb);
610     double T_amb_sea_lev_degF = KelvinToFahrenheit(288);
611
612     // FIXME: this needs to be generalized
613     double ME, friction, percent_RPM, power;  // Convienience term for use in the calculations
614     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
615
616     percent_RPM = RPM/MaxRPM;
617     friction = 1 - (percent_RPM * percent_RPM * percent_RPM * percent_RPM/10);
618     if (friction < 0 ) friction = 0;
619     power = friction;
620
621     if ( Magnetos != 3 ) power *= SparkFailDrop;
622
623
624     HP = (FuelFlow_gph * 6.0 / BSFC )* ME * map_coefficient * power;
625
626   } else {
627
628     // Power output when the engine is not running
629     if (Cranking) {
630       if (RPM < 10) {
631         HP = StarterHP;
632       } else if (RPM < IdleRPM*0.8) {
633         HP = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
634         // This is a guess - would be nice to find a proper starter moter torque curve
635       } else {
636         HP = StarterHP;
637       }
638     } else {
639       // Quick hack until we port the FMEP stuff
640       if (RPM > 0.0)
641         HP = -1.5;
642       else
643         HP = 0.0;
644     }
645   }
646   Percentage_Power = HP / MaxHP ;
647 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
648 }
649
650 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
651 /**
652  * Calculate the exhaust gas temperature.
653  *
654  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
655  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, Percentage_Power
656  *
657  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
658  */
659
660 void FGPiston::doEGT(void)
661 {
662   double delta_T_exhaust;
663   double enthalpy_exhaust;
664   double heat_capacity_exhaust;
665   double dEGTdt;
666
667   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
668     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
669     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
670                               combustion_efficiency * 0.33;
671     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
672     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
673     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
674     ExhaustGasTemp_degK *= 0.444 + ((0.544 - 0.444) * Percentage_Power);
675   } else {  // Drop towards ambient - guess an appropriate time constant for now
676     combustion_efficiency = 0;
677     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
678     delta_T_exhaust = dEGTdt * dt;
679     ExhaustGasTemp_degK += delta_T_exhaust;
680   }
681 }
682
683 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
684 /**
685  * Calculate the cylinder head temperature.
686  *
687  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
688  *   combustion_efficiency, RPM, MaxRPM
689  *
690  * Outputs: CylinderHeadTemp_degK
691  */
692
693 void FGPiston::doCHT(void)
694 {
695   double h1 = -95.0;
696   double h2 = -3.95;
697   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
698
699   double arbitary_area = 1.0;
700   double CpCylinderHead = 800.0;
701   double MassCylinderHead = 8.0;
702
703   double temperature_difference = CylinderHeadTemp_degK - T_amb;
704   double v_apparent = IAS * 0.5144444;
705   double v_dot_cooling_air = arbitary_area * v_apparent;
706   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
707   double dqdt_from_combustion =
708     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
709   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
710     (h3 * RPM * temperature_difference / MaxRPM);
711   double dqdt_free = h1 * temperature_difference;
712   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
713
714   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
715
716   CylinderHeadTemp_degK +=
717     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
718 }
719
720 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
721 /**
722  * Calculate the oil temperature.
723  *
724  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
725  *
726  * Outputs: OilTemp_degK
727  */
728
729 void FGPiston::doOilTemperature(void)
730 {
731   double idle_percentage_power = 0.023;        // approximately
732   double target_oil_temp;        // Steady state oil temp at the current engine conditions
733   double time_constant;          // The time constant for the differential equation
734   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
735
736 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
737 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
738   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
739
740   if (OilPressure_psi > 5.0 ) {
741     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
742                                             // The higher the pressure the faster it reaches
743                                             // target temperature.  Oil pressure should be about
744                                             // 60 PSI yielding a TC of about 80.
745   } else {
746     time_constant = 1000;  // Time constant for engine-off; reflects the fact
747                            // that oil is no longer getting circulated
748   }
749
750   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
751
752   OilTemp_degK += (dOilTempdt * dt);
753 }
754
755 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
756 /**
757  * Calculate the oil pressure.
758  *
759  * Inputs: RPM, MaxRPM, OilTemp_degK
760  *
761  * Outputs: OilPressure_psi
762  */
763
764 void FGPiston::doOilPressure(void)
765 {
766   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
767   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
768   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
769   double Oil_Viscosity_Index = 0.25;
770
771   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
772
773   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
774     OilPressure_psi = Oil_Press_Relief_Valve;
775   }
776
777   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
778 }
779
780 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
781
782 string FGPiston::GetEngineLabels(string delimeter)
783 {
784   std::ostringstream buf;
785
786   buf << Name << " Power Available (engine " << EngineNumber << " in HP)" << delimeter
787       << Name << " HP (engine " << EngineNumber << ")" << delimeter
788       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimeter
789       << Name << " MAP (engine " << EngineNumber << ")" << delimeter
790       << Thruster->GetThrusterLabels(EngineNumber, delimeter);
791
792   return buf.str();
793 }
794
795 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
796
797 string FGPiston::GetEngineValues(string delimeter)
798 {
799   std::ostringstream buf;
800
801   buf << PowerAvailable << delimeter << HP << delimeter
802       << equivalence_ratio << delimeter << MAP << delimeter
803       << Thruster->GetThrusterValues(EngineNumber, delimeter);
804
805   return buf.str();
806 }
807
808 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
809 //
810 //    The bitmasked value choices are as follows:
811 //    unset: In this case (the default) JSBSim would only print
812 //       out the normally expected messages, essentially echoing
813 //       the config files as they are read. If the environment
814 //       variable is not set, debug_lvl is set to 1 internally
815 //    0: This requests JSBSim not to output any messages
816 //       whatsoever.
817 //    1: This value explicity requests the normal JSBSim
818 //       startup messages
819 //    2: This value asks for a message to be printed out when
820 //       a class is instantiated
821 //    4: When this value is set, a message is displayed when a
822 //       FGModel object executes its Run() method
823 //    8: When this value is set, various runtime state variables
824 //       are printed out periodically
825 //    16: When set various parameters are sanity checked and
826 //       a message is printed out when they go out of bounds
827
828 void FGPiston::Debug(int from)
829 {
830   if (debug_lvl <= 0) return;
831
832   if (debug_lvl & 1) { // Standard console startup message output
833     if (from == 0) { // Constructor
834
835       cout << "\n    Engine Name: "         << Name << endl;
836       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
837       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
838       cout << "      MinMaP (Pa):         " << minMAP << endl;
839       cout << "      MaxMaP (Pa): "         << maxMAP << endl;
840       cout << "      Displacement: "        << Displacement             << endl;
841       cout << "      MaxHP: "               << MaxHP                    << endl;
842       cout << "      Cycles: "              << Cycles                   << endl;
843       cout << "      IdleRPM: "             << IdleRPM                  << endl;
844       cout << "      MaxThrottle: "         << MaxThrottle              << endl;
845       cout << "      MinThrottle: "         << MinThrottle              << endl;
846       cout << "      BSFC: "                << BSFC                     << endl;
847
848       cout << endl;
849       cout << "      Combustion Efficiency table:" << endl;
850       Lookup_Combustion_Efficiency->Print();
851       cout << endl;
852
853       cout << endl;
854       cout << "      Mixture Efficiency Correlation table:" << endl;
855       Mixture_Efficiency_Correlation->Print();
856       cout << endl;
857
858     }
859   }
860   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
861     if (from == 0) cout << "Instantiated: FGPiston" << endl;
862     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
863   }
864   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
865   }
866   if (debug_lvl & 8 ) { // Runtime state variables
867   }
868   if (debug_lvl & 16) { // Sanity checking
869   }
870   if (debug_lvl & 64) {
871     if (from == 0) { // Constructor
872       cout << IdSrc << endl;
873       cout << IdHdr << endl;
874     }
875   }
876 }
877 } // namespace JSBSim