]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/models/propulsion/FGPiston.cpp
Merge branch 'next' of git://gitorious.org/fg/flightgear 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 (jon@jsbsim.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/FGAtmosphere.h"
47 #include "models/FGAuxiliary.h"
48 #include "models/FGPropulsion.h"
49 #include "FGPropeller.h"
50 #include <iostream>
51
52 using namespace std;
53
54 namespace JSBSim {
55
56 static const char *IdSrc = "$Id: FGPiston.cpp,v 1.58 2011/06/13 15:23:09 jentron Exp $";
57 static const char *IdHdr = ID_PISTON;
58
59 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
60 CLASS IMPLEMENTATION
61 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
62
63 FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number)
64   : FGEngine(exec, el, engine_number),
65   R_air(287.3),                  // Gas constant for air J/Kg/K
66   rho_fuel(800),                 // estimate
67   calorific_value_fuel(47.3e6),  // J/Kg
68   Cp_air(1005),                  // Specific heat (constant pressure) J/Kg/K
69   Cp_fuel(1700),
70   standard_pressure(101320.73)
71 {
72   string token;
73
74   // Defaults and initializations
75
76   Type = etPiston;
77   dt = FDMExec->GetDeltaT();
78
79   // These items are read from the configuration file
80   // Defaults are from a Lycoming O-360, more or less
81
82   Cycles = 4;
83   IdleRPM = 600;
84   MaxRPM = 2800;
85   Displacement = 360;
86   SparkFailDrop = 1.0;
87   MaxHP = 200;
88   MinManifoldPressure_inHg = 6.5;
89   MaxManifoldPressure_inHg = 28.5;
90   ISFC = -1;
91   volumetric_efficiency = 0.85;
92   Bore = 5.125;
93   Stroke = 4.375;
94   Cylinders = 4;
95   CylinderHeadMass = 2; //kg
96   CompressionRatio = 8.5;
97   Z_airbox = -999;
98   Ram_Air_Factor = 1;
99   PeakMeanPistonSpeed_fps = 100;
100   FMEPDynamic= 18400;
101   FMEPStatic = 46500;
102   Cooling_Factor = 0.5144444;
103   StaticFriction_HP = 1.5;
104
105   // These are internal program variables
106
107   crank_counter = 0;
108   Magnetos = 0;
109   minMAP = 21950;
110   maxMAP = 96250;
111
112   ResetToIC();
113
114   // Supercharging
115   BoostSpeeds = 0;  // Default to no supercharging
116   BoostSpeed = 0;
117   Boosted = false;
118   BoostOverride = 0;
119   BoostManual = 0;
120   bBoostOverride = false;
121   bTakeoffBoost = false;
122   TakeoffBoost = 0.0;   // Default to no extra takeoff-boost
123   int i;
124   for (i=0; i<FG_MAX_BOOST_SPEEDS; i++) {
125     RatedBoost[i] = 0.0;
126     RatedPower[i] = 0.0;
127     RatedAltitude[i] = 0.0;
128     BoostMul[i] = 1.0;
129     RatedMAP[i] = 100000;
130     RatedRPM[i] = 2500;
131     TakeoffMAP[i] = 100000;
132   }
133   for (i=0; i<FG_MAX_BOOST_SPEEDS-1; i++) {
134     BoostSwitchAltitude[i] = 0.0;
135     BoostSwitchPressure[i] = 0.0;
136   }
137
138   // First column is thi, second is neta (combustion efficiency)
139   Lookup_Combustion_Efficiency = new FGTable(12);
140   *Lookup_Combustion_Efficiency << 0.00 << 0.980;
141   *Lookup_Combustion_Efficiency << 0.90 << 0.980;
142   *Lookup_Combustion_Efficiency << 1.00 << 0.970;
143   *Lookup_Combustion_Efficiency << 1.05 << 0.950;
144   *Lookup_Combustion_Efficiency << 1.10 << 0.900;
145   *Lookup_Combustion_Efficiency << 1.15 << 0.850;
146   *Lookup_Combustion_Efficiency << 1.20 << 0.790;
147   *Lookup_Combustion_Efficiency << 1.30 << 0.700;
148   *Lookup_Combustion_Efficiency << 1.40 << 0.630;
149   *Lookup_Combustion_Efficiency << 1.50 << 0.570;
150   *Lookup_Combustion_Efficiency << 1.60 << 0.525;
151   *Lookup_Combustion_Efficiency << 2.00 << 0.345;
152
153   Mixture_Efficiency_Correlation = new FGTable(15);
154   *Mixture_Efficiency_Correlation << 0.05000 << 0.00000;
155   *Mixture_Efficiency_Correlation << 0.05137 << 0.00862;
156   *Mixture_Efficiency_Correlation << 0.05179 << 0.21552;
157   *Mixture_Efficiency_Correlation << 0.05430 << 0.48276;
158   *Mixture_Efficiency_Correlation << 0.05842 << 0.70690;
159   *Mixture_Efficiency_Correlation << 0.06312 << 0.83621;
160   *Mixture_Efficiency_Correlation << 0.06942 << 0.93103;
161   *Mixture_Efficiency_Correlation << 0.07786 << 1.00000;
162   *Mixture_Efficiency_Correlation << 0.08845 << 1.00000;
163   *Mixture_Efficiency_Correlation << 0.09270 << 0.98276;
164   *Mixture_Efficiency_Correlation << 0.10120 << 0.93103;
165   *Mixture_Efficiency_Correlation << 0.11455 << 0.72414;
166   *Mixture_Efficiency_Correlation << 0.12158 << 0.45690;
167   *Mixture_Efficiency_Correlation << 0.12435 << 0.23276;
168   *Mixture_Efficiency_Correlation << 0.12500 << 0.00000;
169
170
171   // Read inputs from engine data file where present.
172
173   if (el->FindElement("minmp")) // Should have ELSE statement telling default value used?
174     MinManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("minmp","INHG");
175   if (el->FindElement("maxmp"))
176     MaxManifoldPressure_inHg = el->FindElementValueAsNumberConvertTo("maxmp","INHG");
177   if (el->FindElement("displacement"))
178     Displacement = el->FindElementValueAsNumberConvertTo("displacement","IN3");
179   if (el->FindElement("maxhp"))
180     MaxHP = el->FindElementValueAsNumberConvertTo("maxhp","HP");
181   if (el->FindElement("static-friction"))
182     StaticFriction_HP = el->FindElementValueAsNumberConvertTo("static-friction","HP");
183   if (el->FindElement("sparkfaildrop"))
184     SparkFailDrop = Constrain(0, 1 - el->FindElementValueAsNumber("sparkfaildrop"), 1);
185   if (el->FindElement("cycles"))
186     Cycles = el->FindElementValueAsNumber("cycles");
187   if (el->FindElement("idlerpm"))
188     IdleRPM = el->FindElementValueAsNumber("idlerpm");
189   if (el->FindElement("maxrpm"))
190     MaxRPM = el->FindElementValueAsNumber("maxrpm");
191   if (el->FindElement("maxthrottle"))
192     MaxThrottle = el->FindElementValueAsNumber("maxthrottle");
193   if (el->FindElement("minthrottle"))
194     MinThrottle = el->FindElementValueAsNumber("minthrottle");
195   if (el->FindElement("bsfc"))
196     ISFC = el->FindElementValueAsNumberConvertTo("bsfc", "LBS/HP*HR");
197   if (el->FindElement("volumetric-efficiency"))
198     volumetric_efficiency = el->FindElementValueAsNumber("volumetric-efficiency");
199   if (el->FindElement("compression-ratio"))
200     CompressionRatio = el->FindElementValueAsNumber("compression-ratio");
201   if (el->FindElement("bore"))
202     Bore = el->FindElementValueAsNumberConvertTo("bore","IN");
203   if (el->FindElement("stroke"))
204     Stroke = el->FindElementValueAsNumberConvertTo("stroke","IN");
205   if (el->FindElement("cylinders"))
206     Cylinders = el->FindElementValueAsNumber("cylinders");
207   if (el->FindElement("cylinder-head-mass"))
208     CylinderHeadMass = el->FindElementValueAsNumberConvertTo("cylinder-head-mass","KG");
209   if (el->FindElement("air-intake-impedance-factor"))
210     Z_airbox = el->FindElementValueAsNumber("air-intake-impedance-factor");
211   if (el->FindElement("ram-air-factor"))
212     Ram_Air_Factor  = el->FindElementValueAsNumber("ram-air-factor");
213   if (el->FindElement("cooling-factor"))
214     Cooling_Factor  = el->FindElementValueAsNumber("cooling-factor");
215   if (el->FindElement("dynamic-fmep"))
216     FMEPDynamic= el->FindElementValueAsNumberConvertTo("dynamic-fmep","PA");
217   if (el->FindElement("static-fmep"))
218     FMEPStatic = el->FindElementValueAsNumberConvertTo("static-fmep","PA");
219   if (el->FindElement("peak-piston-speed"))
220     PeakMeanPistonSpeed_fps  = el->FindElementValueAsNumber("peak-piston-speed");
221   if (el->FindElement("numboostspeeds")) { // Turbo- and super-charging parameters
222     BoostSpeeds = (int)el->FindElementValueAsNumber("numboostspeeds");
223     if (el->FindElement("boostoverride"))
224       BoostOverride = (int)el->FindElementValueAsNumber("boostoverride");
225     if (el->FindElement("boostmanual"))
226       BoostManual = (int)el->FindElementValueAsNumber("boostmanual");
227     if (el->FindElement("takeoffboost"))
228       TakeoffBoost = el->FindElementValueAsNumberConvertTo("takeoffboost", "PSI");
229     if (el->FindElement("ratedboost1"))
230       RatedBoost[0] = el->FindElementValueAsNumberConvertTo("ratedboost1", "PSI");
231     if (el->FindElement("ratedboost2"))
232       RatedBoost[1] = el->FindElementValueAsNumberConvertTo("ratedboost2", "PSI");
233     if (el->FindElement("ratedboost3"))
234       RatedBoost[2] = el->FindElementValueAsNumberConvertTo("ratedboost3", "PSI");
235     if (el->FindElement("ratedpower1"))
236       RatedPower[0] = el->FindElementValueAsNumberConvertTo("ratedpower1", "HP");
237     if (el->FindElement("ratedpower2"))
238       RatedPower[1] = el->FindElementValueAsNumberConvertTo("ratedpower2", "HP");
239     if (el->FindElement("ratedpower3"))
240       RatedPower[2] = el->FindElementValueAsNumberConvertTo("ratedpower3", "HP");
241     if (el->FindElement("ratedrpm1"))
242       RatedRPM[0] = el->FindElementValueAsNumber("ratedrpm1");
243     if (el->FindElement("ratedrpm2"))
244       RatedRPM[1] = el->FindElementValueAsNumber("ratedrpm2");
245     if (el->FindElement("ratedrpm3"))
246       RatedRPM[2] = el->FindElementValueAsNumber("ratedrpm3");
247     if (el->FindElement("ratedaltitude1"))
248       RatedAltitude[0] = el->FindElementValueAsNumberConvertTo("ratedaltitude1", "FT");
249     if (el->FindElement("ratedaltitude2"))
250       RatedAltitude[1] = el->FindElementValueAsNumberConvertTo("ratedaltitude2", "FT");
251     if (el->FindElement("ratedaltitude3"))
252       RatedAltitude[2] = el->FindElementValueAsNumberConvertTo("ratedaltitude3", "FT");
253   }
254
255   StarterHP = sqrt(MaxHP) * 0.4;
256   displacement_SI = Displacement * in3tom3;
257   RatedMeanPistonSpeed_fps =  ( MaxRPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
258
259   // Create IFSC to match the engine if not provided
260   if (ISFC < 0) {
261       double pmep = 29.92 - MaxManifoldPressure_inHg;
262       pmep *= inhgtopa  * volumetric_efficiency;
263       double fmep = (FMEPDynamic * RatedMeanPistonSpeed_fps * fttom + FMEPStatic);
264       double hp_loss = ((pmep + fmep) * displacement_SI * MaxRPM)/(Cycles*22371);
265       ISFC = ( 1.1*Displacement * MaxRPM * volumetric_efficiency *(MaxManifoldPressure_inHg / 29.92) ) / (9411 * (MaxHP+hp_loss-StaticFriction_HP));
266 // cout <<"FMEP: "<< fmep <<" PMEP: "<< pmep << " hp_loss: " <<hp_loss <<endl;
267   }
268   if ( MaxManifoldPressure_inHg > 29.9 ) {   // Don't allow boosting with a bogus number
269       MaxManifoldPressure_inHg = 29.9;
270   }
271   minMAP = MinManifoldPressure_inHg * inhgtopa;  // inHg to Pa
272   maxMAP = MaxManifoldPressure_inHg * inhgtopa;
273
274 // For throttle
275 /*
276  * Pm = ( Ze / ( Ze + Zi + Zt ) ) * Pa
277  * Where:
278  * Pm = Manifold Pressure
279  * Pa = Ambient Pressre
280  * Ze = engine impedance, Ze is effectively 1 / Mean Piston Speed
281  * Zi = airbox impedance
282  * Zt = throttle impedance
283  *
284  * For the calculation below throttle is fully open or Zt = 0
285  *
286  *
287  *
288  */
289
290   if(Z_airbox < 0.0){
291     double Ze=PeakMeanPistonSpeed_fps/RatedMeanPistonSpeed_fps; // engine impedence
292     Z_airbox = (standard_pressure *Ze / maxMAP) - Ze; // impedence of airbox
293   }
294   // Constant for Throttle impedence
295   Z_throttle=(PeakMeanPistonSpeed_fps/((IdleRPM * Stroke) / 360))*(standard_pressure/minMAP - 1) - Z_airbox; 
296   //  Z_throttle=(MaxRPM/IdleRPM )*(standard_pressure/minMAP+2); // Constant for Throttle impedence
297
298   string property_name, base_property_name;
299   base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNumber);
300   property_name = base_property_name + "/power-hp";
301   PropertyManager->Tie(property_name, &HP);
302   property_name = base_property_name + "/bsfc-lbs_hphr";
303   PropertyManager->Tie(property_name, &ISFC);
304   property_name = base_property_name + "/volumetric-efficiency";
305   PropertyManager->Tie(property_name, &volumetric_efficiency);
306   property_name = base_property_name + "/map-pa";
307   PropertyManager->Tie(property_name, &MAP);
308   property_name = base_property_name + "/map-inhg";
309   PropertyManager->Tie(property_name, &ManifoldPressure_inHg);
310   property_name = base_property_name + "/air-intake-impedance-factor";
311   PropertyManager->Tie(property_name, &Z_airbox);
312   property_name = base_property_name + "/ram-air-factor";
313   PropertyManager->Tie(property_name, &Ram_Air_Factor);
314   property_name = base_property_name + "/cooling-factor";
315   PropertyManager->Tie(property_name, &Cooling_Factor);
316   property_name = base_property_name + "/boost-speed";
317   PropertyManager->Tie(property_name, &BoostSpeed);
318   property_name = base_property_name + "/cht-degF";
319   PropertyManager->Tie(property_name, this, &FGPiston::getCylinderHeadTemp_degF);
320   property_name = base_property_name + "/engine-rpm";
321   PropertyManager->Tie(property_name, this, &FGPiston::getRPM);
322   property_name = base_property_name + "/oil-temperature-degF";
323   PropertyManager->Tie(property_name, this, &FGPiston::getOilTemp_degF);
324   property_name = base_property_name + "/oil-pressure-psi";
325   PropertyManager->Tie(property_name, this, &FGPiston::getOilPressure_psi);
326   property_name = base_property_name + "/egt-degF";
327   PropertyManager->Tie(property_name, this, &FGPiston::getExhaustGasTemp_degF);
328
329   // Set up and sanity-check the turbo/supercharging configuration based on the input values.
330   if (TakeoffBoost > RatedBoost[0]) bTakeoffBoost = true;
331   for (i=0; i<BoostSpeeds; ++i) {
332     bool bad = false;
333     if (RatedBoost[i] <= 0.0) bad = true;
334     if (RatedPower[i] <= 0.0) bad = true;
335     if (RatedAltitude[i] < 0.0) bad = true;  // 0.0 is deliberately allowed - this corresponds to unregulated supercharging.
336     if (i > 0 && RatedAltitude[i] < RatedAltitude[i - 1]) bad = true;
337     if (bad) {
338       // We can't recover from the above - don't use this supercharger speed.
339       BoostSpeeds--;
340       // TODO - put out a massive error message!
341       break;
342     }
343     // Now sanity-check stuff that is recoverable.
344     if (i < BoostSpeeds - 1) {
345       if (BoostSwitchAltitude[i] < RatedAltitude[i]) {
346         // TODO - put out an error message
347         // But we can also make a reasonable estimate, as below.
348         BoostSwitchAltitude[i] = RatedAltitude[i] + 1000;
349       }
350       BoostSwitchPressure[i] = Atmosphere->GetPressure(BoostSwitchAltitude[i]) * psftopa;
351       //cout << "BoostSwitchAlt = " << BoostSwitchAltitude[i] << ", pressure = " << BoostSwitchPressure[i] << '\n';
352       // Assume there is some hysteresis on the supercharger gear switch, and guess the value for now
353       BoostSwitchHysteresis = 1000;
354     }
355     // Now work out the supercharger pressure multiplier of this speed from the rated boost and altitude.
356     RatedMAP[i] = Atmosphere->GetPressureSL() * psftopa + RatedBoost[i] * 6895;  // psi*6895 = Pa.
357     // Sometimes a separate BCV setting for takeoff or extra power is fitted.
358     if (TakeoffBoost > RatedBoost[0]) {
359       // Assume that the effect on the BCV is the same whichever speed is in use.
360       TakeoffMAP[i] = RatedMAP[i] + ((TakeoffBoost - RatedBoost[0]) * 6895);
361       bTakeoffBoost = true;
362     } else {
363       TakeoffMAP[i] = RatedMAP[i];
364       bTakeoffBoost = false;
365     }
366     BoostMul[i] = RatedMAP[i] / (Atmosphere->GetPressure(RatedAltitude[i]) * psftopa);
367
368   }
369
370   if (BoostSpeeds > 0) {
371     Boosted = true;
372     BoostSpeed = 0;
373   }
374   bBoostOverride = (BoostOverride == 1 ? true : false);
375   bBoostManual   = (BoostManual   == 1 ? true : false);
376   Debug(0); // Call Debug() routine from constructor if needed
377 }
378
379 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
380
381 FGPiston::~FGPiston()
382 {
383   delete Lookup_Combustion_Efficiency;
384   delete Mixture_Efficiency_Correlation;
385   Debug(1); // Call Debug() routine from constructor if needed
386 }
387
388 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
389
390 void FGPiston::ResetToIC(void)
391 {
392   FGEngine::ResetToIC();
393
394   ManifoldPressure_inHg = Atmosphere->GetPressure() * psftoinhg; // psf to in Hg
395   MAP = Atmosphere->GetPressure() * psftopa;
396   TMAP = MAP;
397   double airTemperature_degK = RankineToKelvin(Atmosphere->GetTemperature());
398   OilTemp_degK = airTemperature_degK;
399   CylinderHeadTemp_degK = airTemperature_degK;
400   ExhaustGasTemp_degK = airTemperature_degK;
401   EGT_degC = ExhaustGasTemp_degK - 273;
402   Thruster->SetRPM(0.0);
403   RPM = 0.0;
404   OilPressure_psi = 0.0;
405 }
406
407 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
408 void FGPiston::Calculate(void)
409 {
410   RunPreFunctions();
411
412   if (FuelFlow_gph > 0.0) ConsumeFuel();
413
414   Throttle = FCS->GetThrottlePos(EngineNumber);
415   Mixture = FCS->GetMixturePos(EngineNumber);
416
417   // Input values.
418
419   p_amb = Atmosphere->GetPressure() * psftopa;
420   double p = Auxiliary->GetTotalPressure() * psftopa;
421   p_ram = (p - p_amb) * Ram_Air_Factor + p_amb;
422   T_amb = RankineToKelvin(Atmosphere->GetTemperature());
423
424   RPM = Thruster->GetRPM() * Thruster->GetGearRatio();
425   MeanPistonSpeed_fps =  ( RPM * Stroke) / (360); // AKA 2 * (RPM/60) * ( Stroke / 12) or 2NS
426
427   IAS = Auxiliary->GetVcalibratedKTS();
428
429   doEngineStartup();
430   if (Boosted) doBoostControl();
431   doMAP();
432   doAirFlow();
433   doFuelFlow();
434
435   //Now that the fuel flow is done check if the mixture is too lean to run the engine
436   //Assume lean limit at 22 AFR for now - thats a thi of 0.668
437   //This might be a bit generous, but since there's currently no audiable warning of impending
438   //cutout in the form of misfiring and/or rough running its probably reasonable for now.
439
440   //  if (equivalence_ratio < 0.668)
441   //    Running = false;
442
443   doEnginePower();
444   if (IndicatedHorsePower < 0.1250) Running = false;
445
446   doEGT();
447   doCHT();
448   doOilTemperature();
449   doOilPressure();
450
451   if (Thruster->GetType() == FGThruster::ttPropeller) {
452     ((FGPropeller*)Thruster)->SetAdvance(FCS->GetPropAdvance(EngineNumber));
453     ((FGPropeller*)Thruster)->SetFeather(FCS->GetPropFeather(EngineNumber));
454   }
455
456   Thruster->Calculate(HP * hptoftlbssec);
457
458   RunPostFunctions();
459 }
460
461 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
462
463 double FGPiston::CalcFuelNeed(void)
464 {
465   double dT = FDMExec->GetDeltaT() * Propulsion->GetRate();
466   FuelExpended = FuelFlowRate * dT;
467   return FuelExpended;
468 }
469
470 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
471
472 int FGPiston::InitRunning(void) {
473   Magnetos=3;
474   p_amb = Atmosphere->GetPressure() * psftopa;
475   double mix= p_amb / (101325.0*1.3);
476   FCS->SetMixturePos(EngineNumber, mix);
477   Thruster->SetRPM( 2.*IdleRPM/Thruster->GetGearRatio() );
478   //Thruster->SetRPM( 1000 );
479   Running=true;
480 // cout <<"Set Running in FGPiston. RPM:" << Thruster->GetRPM()*Thruster->GetGearRatio() <<" Pressure:"<<p_amb<<" Mixture:"<< mix <<endl;
481   return 1;
482 }
483
484 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
485 /**
486  * Start or stop the engine.
487  */
488
489 void FGPiston::doEngineStartup(void)
490 {
491   // Check parameters that may alter the operating state of the engine.
492   // (spark, fuel, starter motor etc)
493   bool spark;
494   bool fuel;
495   // Check for spark
496   Magneto_Left = false;
497   Magneto_Right = false;
498   // Magneto positions:
499   // 0 -> off
500   // 1 -> left only
501   // 2 -> right only
502   // 3 -> both
503   if (Magnetos != 0) {
504     spark = true;
505   } else {
506     spark = false;
507   }  // neglects battery voltage, master on switch, etc for now.
508
509   if ((Magnetos == 1) || (Magnetos > 2)) Magneto_Left = true;
510   if (Magnetos > 1)  Magneto_Right = true;
511
512   // Assume we have fuel for now
513   fuel = !Starved;
514
515   // Check if we are turning the starter motor
516   if (Cranking != Starter) {
517     // This check saves .../cranking from getting updated every loop - they
518     // only update when changed.
519     Cranking = Starter;
520     crank_counter = 0;
521   }
522
523   if (Cranking) crank_counter++;  //Check mode of engine operation
524
525   if (!Running && spark && fuel) {  // start the engine if revs high enough
526     if (Cranking) {
527       if ((RPM > IdleRPM*0.8) && (crank_counter > 175)) // Add a little delay to startup
528         Running = true;                         // on the starter
529     } else {
530       if (RPM > IdleRPM*0.8)                            // This allows us to in-air start
531         Running = true;                         // when windmilling
532     }
533   }
534
535   // Cut the engine *power* - Note: the engine may continue to
536   // spin if the prop is in a moving airstream
537
538   if ( Running && (!spark || !fuel) ) Running = false;
539
540   // Check for stalling (RPM = 0).
541   if (Running) {
542     if (RPM == 0) {
543       Running = false;
544     } else if ((RPM <= IdleRPM *0.8 ) && (Cranking)) {
545       Running = false;
546     }
547   }
548 }
549
550 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
551
552 /**
553  * Calculate the Current Boost Speed
554  *
555  * This function calculates the current turbo/supercharger boost speed
556  * based on altitude and the (automatic) boost-speed control valve configuration.
557  *
558  * Inputs: p_amb, BoostSwitchPressure, BoostSwitchHysteresis
559  *
560  * Outputs: BoostSpeed
561  */
562
563 void FGPiston::doBoostControl(void)
564 {
565   if(BoostManual) {
566     if(BoostSpeed > BoostSpeeds-1) BoostSpeed = BoostSpeeds-1;
567     if(BoostSpeed < 0) BoostSpeed = 0;
568   } else {
569     if(BoostSpeed < BoostSpeeds - 1) {
570       // Check if we need to change to a higher boost speed
571       if(p_amb < BoostSwitchPressure[BoostSpeed] - BoostSwitchHysteresis) {
572         BoostSpeed++;
573       }
574     } if(BoostSpeed > 0) {
575       // Check if we need to change to a lower boost speed
576       if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) {
577         BoostSpeed--;
578       }
579     }
580   }
581 }
582
583 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
584
585 /**
586  * Calculate the manifold absolute pressure (MAP) in inches hg
587  *
588  * This function calculates manifold absolute pressure (MAP)
589  * from the throttle position, turbo/supercharger boost control
590  * system, engine speed and local ambient air density.
591  *
592  * Inputs: p_amb, Throttle,
593  *         MeanPistonSpeed_fps, dt
594  *
595  * Outputs: MAP, ManifoldPressure_inHg, TMAP
596  */
597
598 void FGPiston::doMAP(void)
599 {
600   double Zt = (1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence
601   double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence
602
603   double map_coefficient = Ze/(Ze+Z_airbox+Zt);
604
605   // Add a one second lag to manifold pressure changes
606   double dMAP = (TMAP - p_ram * map_coefficient) * dt;
607   TMAP -=dMAP;
608
609   // Find the mean effective pressure required to achieve this manifold pressure
610   // Fixme: determine the HP consumed by the supercharger
611
612   PMEP = (TMAP - p_amb) * volumetric_efficiency; // Fixme: p_amb should be exhaust manifold pressure
613
614   if (Boosted) {
615     // If takeoff boost is fitted, we currently assume the following throttle map:
616     // (In throttle % - actual input is 0 -> 1)
617     // 99 / 100 - Takeoff boost
618     // In real life, most planes would be fitted with a mechanical 'gate' between
619     // the rated boost and takeoff boost positions.
620
621     bool bTakeoffPos = false;
622     if (bTakeoffBoost) {
623       if (Throttle > 0.98) {
624         bTakeoffPos = true;
625       }
626     }
627     // Boost the manifold pressure.
628     double boost_factor = (( BoostMul[BoostSpeed] - 1 ) / RatedRPM[BoostSpeed] ) * RPM + 1;
629     MAP = TMAP * boost_factor;
630     // Now clip the manifold pressure to BCV or Wastegate setting.
631     if (bTakeoffPos) {
632       if (MAP > TakeoffMAP[BoostSpeed]) MAP = TakeoffMAP[BoostSpeed];
633     } else {
634       if (MAP > RatedMAP[BoostSpeed]) MAP = RatedMAP[BoostSpeed];
635     }
636   } else {
637       MAP = TMAP;
638   }
639
640   // And set the value in American units as well
641   ManifoldPressure_inHg = MAP / inhgtopa;
642 }
643
644 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
645 /**
646  * Calculate the air flow through the engine.
647  * Also calculates ambient air density
648  * (used in CHT calculation for air-cooled engines).
649  *
650  * Inputs: p_amb, R_air, T_amb, MAP, Displacement,
651  *   RPM, volumetric_efficiency,
652  *
653  * TODO: Model inlet manifold air temperature.
654  *
655  * Outputs: rho_air, m_dot_air
656  */
657
658 void FGPiston::doAirFlow(void)
659 {
660   double gamma = 1.3; // specific heat constants
661 // loss of volumentric efficiency due to difference between MAP and exhaust pressure
662 // Eq 6-10 from The Internal Combustion Engine - Charles Taylor Vol 1
663   double ve =((gamma-1)/gamma) +( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1));
664 // FGAtmosphere::GetDensity() * FGJSBBase::m3toft3 / FGJSBBase::kgtoslug;
665   rho_air = p_amb / (R_air * T_amb);
666   double swept_volume = (displacement_SI * (RPM/60)) / 2;
667   double v_dot_air = swept_volume * volumetric_efficiency *ve;
668
669   double rho_air_manifold = MAP / (R_air * T_amb);
670   m_dot_air = v_dot_air * rho_air_manifold;
671
672 }
673
674 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
675 /**
676  * Calculate the fuel flow into the engine.
677  *
678  * Inputs: Mixture, thi_sea_level, p_amb, m_dot_air
679  *
680  * Outputs: equivalence_ratio, m_dot_fuel
681  */
682
683 void FGPiston::doFuelFlow(void)
684 {
685   double thi_sea_level = 1.3 * Mixture; // Allows an AFR of infinity:1 to 11.3075:1
686   equivalence_ratio = thi_sea_level * 101325.0 / p_amb;
687 //  double AFR = 10+(12*(1-Mixture));// mixture 10:1 to 22:1
688 //  m_dot_fuel = m_dot_air / AFR;
689   m_dot_fuel = (m_dot_air * equivalence_ratio) / 14.7;
690   FuelFlowRate =  m_dot_fuel * 2.2046;  // kg to lb
691   FuelFlow_pph = FuelFlowRate  * 3600;  // seconds to hours
692   FuelFlow_gph = FuelFlow_pph / 6.0;    // Assumes 6 lbs / gallon
693 }
694
695 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
696 /**
697  * Calculate the power produced by the engine.
698  *
699  * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb, ISFC,
700  *   Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP,
701  *   MeanPistonSpeed_fps
702  *
703  * Outputs: PctPower, HP, FMEP, IndicatedHorsePower
704  */
705
706 void FGPiston::doEnginePower(void)
707 {
708   IndicatedHorsePower = 0;
709   FMEP = 0;
710   if (Running) {
711     // FIXME: this needs to be generalized
712     double ME, percent_RPM, power;  // Convienience term for use in the calculations
713     ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air);
714
715     percent_RPM = RPM/MaxRPM;
716 // Guestimate engine friction losses from Figure 4.4 of "Engines: An Introduction", John Lumley
717     FMEP = (-FMEPDynamic * MeanPistonSpeed_fps * fttom - FMEPStatic);
718
719     power = 1;
720
721     if ( Magnetos != 3 ) power *= SparkFailDrop;
722
723
724     IndicatedHorsePower = (FuelFlow_pph / ISFC )* ME * power;
725
726   } else {
727     // Power output when the engine is not running
728     if (Cranking) {
729       if (RPM < 10) {
730         IndicatedHorsePower = StarterHP;
731       } else if (RPM < IdleRPM*0.8) {
732         IndicatedHorsePower = StarterHP + ((IdleRPM*0.8 - RPM) / 8.0);
733         // This is a guess - would be nice to find a proper starter moter torque curve
734       } else {
735         IndicatedHorsePower = StarterHP;
736       }
737     }
738   }
739
740   // Constant is (1/2) * 60 * 745.7
741   // (1/2) convert cycles, 60 minutes to seconds, 745.7 watts to hp.
742   double pumping_hp = ((PMEP + FMEP) * displacement_SI * RPM)/(Cycles*22371);
743
744   HP = IndicatedHorsePower + pumping_hp - StaticFriction_HP; //FIXME static friction should depend on oil temp and configuration
745 //  cout << "pumping_hp " <<pumping_hp << FMEP << PMEP <<endl;
746   PctPower = HP / MaxHP ;
747 //  cout << "Power = " << HP << "  RPM = " << RPM << "  Running = " << Running << "  Cranking = " << Cranking << endl;
748 }
749
750 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
751 /**
752  * Calculate the exhaust gas temperature.
753  *
754  * Inputs: equivalence_ratio, m_dot_fuel, calorific_value_fuel,
755  *   Cp_air, m_dot_air, Cp_fuel, m_dot_fuel, T_amb, PctPower
756  *
757  * Outputs: combustion_efficiency, ExhaustGasTemp_degK
758  */
759
760 void FGPiston::doEGT(void)
761 {
762   double delta_T_exhaust;
763   double enthalpy_exhaust;
764   double heat_capacity_exhaust;
765   double dEGTdt;
766
767   if ((Running) && (m_dot_air > 0.0)) {  // do the energy balance
768     combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio);
769     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel *
770                               combustion_efficiency * 0.30;
771     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
772     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
773     ExhaustGasTemp_degK = T_amb + delta_T_exhaust;
774   } else {  // Drop towards ambient - guess an appropriate time constant for now
775     combustion_efficiency = 0;
776     dEGTdt = (RankineToKelvin(Atmosphere->GetTemperature()) - ExhaustGasTemp_degK) / 100.0;
777     delta_T_exhaust = dEGTdt * dt;
778     ExhaustGasTemp_degK += delta_T_exhaust;
779   }
780 }
781
782 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
783 /**
784  * Calculate the cylinder head temperature.
785  *
786  * Inputs: T_amb, IAS, rho_air, m_dot_fuel, calorific_value_fuel,
787  *   combustion_efficiency, RPM, MaxRPM, Displacement, Cylinders
788  *
789  * Outputs: CylinderHeadTemp_degK
790  */
791
792 void FGPiston::doCHT(void)
793 {
794   double h1 = -95.0;
795   double h2 = -3.95;
796   double h3 = -140.0; // -0.05 * 2800 (default maxrpm)
797
798   double arbitary_area = Displacement/360.0;
799   double CpCylinderHead = 800.0;
800   double MassCylinderHead = CylinderHeadMass * Cylinders;
801
802   double temperature_difference = CylinderHeadTemp_degK - T_amb;
803   double v_apparent = IAS * Cooling_Factor;
804   double v_dot_cooling_air = arbitary_area * v_apparent;
805   double m_dot_cooling_air = v_dot_cooling_air * rho_air;
806   double dqdt_from_combustion =
807     m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
808   double dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) +
809     (h3 * RPM * temperature_difference / MaxRPM);
810   double dqdt_free = h1 * temperature_difference * arbitary_area;
811   double dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
812
813   double HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
814
815   CylinderHeadTemp_degK +=
816     (dqdt_cylinder_head / HeatCapacityCylinderHead) * dt;
817 }
818
819 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
820 /**
821  * Calculate the oil temperature.
822  *
823  * Inputs: CylinderHeadTemp_degK, T_amb, OilPressure_psi.
824  *
825  * Outputs: OilTemp_degK
826  */
827
828 void FGPiston::doOilTemperature(void)
829 {
830   double target_oil_temp;        // Steady state oil temp at the current engine conditions
831   double time_constant;          // The time constant for the differential equation
832   double efficiency = 0.667;     // The aproximate oil cooling system efficiency // FIXME: may vary by engine
833
834 //  Target oil temp is interpolated between ambient temperature and Cylinder Head Tempurature
835 //  target_oil_temp = ( T_amb * efficiency ) + (CylinderHeadTemp_degK *(1-efficiency)) ;
836   target_oil_temp = CylinderHeadTemp_degK + efficiency * (T_amb - CylinderHeadTemp_degK) ;
837
838   if (OilPressure_psi > 5.0 ) {
839     time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil.
840                                             // The higher the pressure the faster it reaches
841                                             // target temperature.  Oil pressure should be about
842                                             // 60 PSI yielding a TC of about 80.
843   } else {
844     time_constant = 1000;  // Time constant for engine-off; reflects the fact
845                            // that oil is no longer getting circulated
846   }
847
848   double dOilTempdt = (target_oil_temp - OilTemp_degK) / time_constant;
849
850   OilTemp_degK += (dOilTempdt * dt);
851 }
852
853 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
854 /**
855  * Calculate the oil pressure.
856  *
857  * Inputs: RPM, MaxRPM, OilTemp_degK
858  *
859  * Outputs: OilPressure_psi
860  */
861
862 void FGPiston::doOilPressure(void)
863 {
864   double Oil_Press_Relief_Valve = 60; // FIXME: may vary by engine
865   double Oil_Press_RPM_Max = MaxRPM * 0.75;    // 75% of max rpm FIXME: may vary by engine
866   double Design_Oil_Temp = 358;          // degK; FIXME: may vary by engine
867   double Oil_Viscosity_Index = 0.25;
868
869   OilPressure_psi = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * RPM;
870
871   if (OilPressure_psi >= Oil_Press_Relief_Valve) {
872     OilPressure_psi = Oil_Press_Relief_Valve;
873   }
874
875   OilPressure_psi += (Design_Oil_Temp - OilTemp_degK) * Oil_Viscosity_Index * OilPressure_psi / Oil_Press_Relief_Valve;
876 }
877
878 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
879
880 string FGPiston::GetEngineLabels(const string& delimiter)
881 {
882   std::ostringstream buf;
883
884   buf << Name << " Power Available (engine " << EngineNumber << " in ft-lbs/sec)" << delimiter
885       << Name << " HP (engine " << EngineNumber << ")" << delimiter
886       << Name << " equivalent ratio (engine " << EngineNumber << ")" << delimiter
887       << Name << " MAP (engine " << EngineNumber << " in inHg)" << delimiter
888       << Thruster->GetThrusterLabels(EngineNumber, delimiter);
889
890   return buf.str();
891 }
892
893 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
894
895 string FGPiston::GetEngineValues(const string& delimiter)
896 {
897   std::ostringstream buf;
898
899   buf << (HP * hptoftlbssec) << delimiter << HP << delimiter
900       << equivalence_ratio << delimiter << ManifoldPressure_inHg << delimiter
901       << Thruster->GetThrusterValues(EngineNumber, delimiter);
902
903   return buf.str();
904 }
905
906 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
907 //
908 //    The bitmasked value choices are as follows:
909 //    unset: In this case (the default) JSBSim would only print
910 //       out the normally expected messages, essentially echoing
911 //       the config files as they are read. If the environment
912 //       variable is not set, debug_lvl is set to 1 internally
913 //    0: This requests JSBSim not to output any messages
914 //       whatsoever.
915 //    1: This value explicity requests the normal JSBSim
916 //       startup messages
917 //    2: This value asks for a message to be printed out when
918 //       a class is instantiated
919 //    4: When this value is set, a message is displayed when a
920 //       FGModel object executes its Run() method
921 //    8: When this value is set, various runtime state variables
922 //       are printed out periodically
923 //    16: When set various parameters are sanity checked and
924 //       a message is printed out when they go out of bounds
925
926 void FGPiston::Debug(int from)
927 {
928   if (debug_lvl <= 0) return;
929
930   if (debug_lvl & 1) { // Standard console startup message output
931     if (from == 0) { // Constructor
932
933       cout << "\n    Engine Name: "         << Name << endl;
934       cout << "      MinManifoldPressure: " << MinManifoldPressure_inHg << endl;
935       cout << "      MaxManifoldPressure: " << MaxManifoldPressure_inHg << endl;
936       cout << "      MinMaP (Pa):         " << minMAP << endl;
937       cout << "      MaxMaP (Pa):         " << maxMAP << endl;
938       cout << "      Displacement: "        << Displacement             << endl;
939       cout << "      Bore: "                << Bore                     << endl;
940       cout << "      Stroke: "              << Stroke                   << endl;
941       cout << "      Cylinders: "           << Cylinders                << endl;
942       cout << "      Cylinders Head Mass: " <<CylinderHeadMass          << endl;
943       cout << "      Compression Ratio: "   << CompressionRatio         << endl;
944       cout << "      MaxHP: "               << MaxHP                    << endl;
945       cout << "      Cycles: "              << Cycles                   << endl;
946       cout << "      IdleRPM: "             << IdleRPM                  << endl;
947       cout << "      MaxRPM: "              << MaxRPM                   << endl;
948       cout << "      Throttle Constant: "   << Z_throttle               << endl;
949       cout << "      ISFC: "                << ISFC                     << endl;
950       cout << "      Volumetric Efficiency: " << volumetric_efficiency    << endl;
951       cout << "      PeakMeanPistonSpeed_fps: " << PeakMeanPistonSpeed_fps << endl;
952       cout << "      Intake Impedance Factor: " << Z_airbox << endl;
953       cout << "      Dynamic FMEP Factor: " << FMEPDynamic << endl;
954       cout << "      Static FMEP Factor: " << FMEPStatic << endl;
955
956       cout << endl;
957       cout << "      Combustion Efficiency table:" << endl;
958       Lookup_Combustion_Efficiency->Print();
959       cout << endl;
960
961       cout << endl;
962       cout << "      Mixture Efficiency Correlation table:" << endl;
963       Mixture_Efficiency_Correlation->Print();
964       cout << endl;
965
966     }
967   }
968   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
969     if (from == 0) cout << "Instantiated: FGPiston" << endl;
970     if (from == 1) cout << "Destroyed:    FGPiston" << endl;
971   }
972   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
973   }
974   if (debug_lvl & 8 ) { // Runtime state variables
975   }
976   if (debug_lvl & 16) { // Sanity checking
977   }
978   if (debug_lvl & 64) {
979     if (from == 0) { // Constructor
980       cout << IdSrc << endl;
981       cout << IdHdr << endl;
982     }
983   }
984 }
985 } // namespace JSBSim