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