]> git.mxchange.org Git - flightgear.git/blob - src/FDM/IO360.cxx
MSVC fixups.
[flightgear.git] / src / FDM / IO360.cxx
1 // IO360.cxx - a piston engine model currently for the IO360 engine fitted to the C172
2 //             but with the potential to model other naturally aspirated piston engines
3 //             given appropriate config input.
4 //
5 // Written by David Luff, started 2000.
6 // Based on code by Phil Schubert, started 1999.
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 #include <simgear/compiler.h>
23
24 #include <math.h>
25
26 #include STL_FSTREAM
27 #include STL_IOSTREAM
28
29 #if !defined(SG_HAVE_NATIVE_SGI_COMPILERS)
30 SG_USING_STD(cout);
31 #endif
32
33 #include "IO360.hxx"
34 #include "LaRCsim/ls_constants.h"
35
36 #include <Main/fg_props.hxx>
37
38 //*************************************************************************************
39 // Initialise the engine model
40 void FGNewEngine::init(double dt) {
41
42     // These constants should probably be moved eventually
43     CONVERT_CUBIC_INCHES_TO_METERS_CUBED = 1.638706e-5;
44     CONVERT_HP_TO_WATTS = 745.6999;
45
46     // Properties of working fluids
47     Cp_air = 1005;      // J/KgK
48     Cp_fuel = 1700;     // J/KgK
49     calorific_value_fuel = 47.3e6;  // W/Kg  Note that this is only an approximate value
50     rho_fuel = 800;     // kg/m^3 - an estimate for now
51     R_air = 287.3;
52
53     // environment inputs
54     p_amb_sea_level = 101325;   // Pascals              
55
56     // Control inputs  - ARE THESE NEEDED HERE???
57     Throttle_Lever_Pos = 75;
58     Propeller_Lever_Pos = 75;
59     Mixture_Lever_Pos = 100;
60
61     //misc
62     IAS = 0;
63     time_step = dt;
64
65     // Engine Specific Variables that should be read in from a config file
66     MaxHP = 200;    //Lycoming IO360 -A-C-D series
67 //  MaxHP = 180;    //Current Lycoming IO360 ?
68 //  displacement = 520;  //Continental IO520-M
69     displacement = 360;  //Lycoming IO360
70     displacement_SI = displacement * CONVERT_CUBIC_INCHES_TO_METERS_CUBED;
71     engine_inertia = 0.2;  //kgm^2 - value taken from a popular family saloon car engine - need to find an aeroengine value !!!!!
72     prop_inertia = 0.05;  //kgm^2 - this value is a total guess - dcl
73     Max_Fuel_Flow = 130;  // Units??? Do we need this variable any more??
74
75     // Engine specific variables that maybe should be read in from config but are pretty generic and won't vary much for a naturally aspirated piston engine.
76     Max_Manifold_Pressure = 28.50;  //Inches Hg. An approximation - should be able to find it in the engine performance data
77     Min_Manifold_Pressure = 6.5;    //Inches Hg. This is a guess corresponding to approx 0.24 bar MAP (7 in Hg) - need to find some proper data for this
78     Max_RPM = 2700;
79     Min_RPM = 600;                  //Recommended idle from Continental data sheet
80     Mag_Derate_Percent = 5;
81     Gear_Ratio = 1;
82     n_R = 2;         // Number of crank revolutions per power cycle - 2 for a 4 stroke engine.
83
84     // Various bits of housekeeping describing the engines initial state.
85     running = false;
86     cranking = false;
87     crank_counter = false;
88     starter = false;
89
90     // Initialise Engine Variables used by this instance
91     if(running)
92         RPM = 600;
93     else
94         RPM = 0;
95     Percentage_Power = 0;
96     Manifold_Pressure = 29.96; // Inches
97     Fuel_Flow_gals_hr = 0;
98 //    Torque = 0;
99     Torque_SI = 0;
100     CHT = 298.0;                        //deg Kelvin
101     CHT_degF = (CHT_degF * 1.8) - 459.67;       //deg Fahrenheit
102     Mixture = 14;
103     Oil_Pressure = 0;   // PSI
104     Oil_Temp = 85;      // Deg C
105     current_oil_temp = 298.0;   //deg Kelvin
106     /**** one of these is superfluous !!!!***/
107     HP = 0;
108     RPS = 0;
109     Torque_Imbalance = 0;
110
111     // Initialise Propellor Variables used by this instance
112     FGProp1_RPS = 0;
113     // Hardcode propellor for now - the following two should be read from config eventually
114     prop_diameter = 1.8;         // meters
115     blade_angle = 23.0;          // degrees
116 }
117
118 //*****************************************************************************
119 // update the engine model based on current control positions
120 void FGNewEngine::update() {
121
122 /*
123     // Hack for testing - should output every 5 seconds
124     static int count1 = 0;
125     if(count1 == 0) {
126 //      cout << "P_atmos = " << p_amb << "  T_atmos = " << T_amb << '\n';
127 //      cout << "Manifold pressure = " << Manifold_Pressure << "  True_Manifold_Pressure = " << True_Manifold_Pressure << '\n';
128 //      cout << "p_amb_sea_level = " << p_amb_sea_level << '\n';
129 //      cout << "equivalence_ratio = " << equivalence_ratio << '\n';
130 //      cout << "combustion_efficiency = " << combustion_efficiency << '\n';
131 //      cout << "AFR = " << 14.7 / equivalence_ratio << '\n';
132 //      cout << "Mixture lever = " << Mixture_Lever_Pos << '\n';
133 //      cout << "n = " << RPM << " rpm\n";
134 //      cout << "T_amb = " << T_amb << '\n';
135 //      cout << "running = " << running << '\n';
136         cout << "fuel = " << fgGetFloat("/consumables/fuel/tank[0]/level-gal_us") << '\n';
137 //      cout << "Percentage_Power = " << Percentage_Power << '\n';
138 //      cout << "current_oil_temp = " << current_oil_temp << '\n';
139         cout << "EGT = " << EGT << '\n';
140     }
141     count1++;
142     if(count1 == 100)
143         count1 = 0;
144 */
145
146     // Check parameters that may alter the operating state of the engine. 
147     // (spark, fuel, starter motor etc)
148
149     // Check for spark
150     bool Magneto_Left = false;
151     bool Magneto_Right = false;
152     // Magneto positions:
153     // 0 -> off
154     // 1 -> left only
155     // 2 -> right only
156     // 3 -> both
157     if(mag_pos != 0) {
158         spark = true;
159     } else {
160         spark = false;
161     }  // neglects battery voltage, master on switch, etc for now.
162     if((mag_pos == 1) || (mag_pos > 2)) 
163         Magneto_Left = true;
164     if(mag_pos > 1)
165         Magneto_Right = true;
166  
167     // crude check for fuel
168     if((fgGetFloat("/consumables/fuel/tank[0]/level-gal_us") > 0) || (fgGetFloat("/consumables/fuel/tank[1]/level-gal_us") > 0)) {
169         fuel = true;
170     } else {
171         fuel = false;
172     }  // Need to make this better, eg position of fuel selector switch.
173
174     // Check if we are turning the starter motor
175     if(cranking != starter) {
176         // This check saves .../cranking from getting updated every loop - they only update when changed.
177         cranking = starter;
178         crank_counter = 0;
179     }
180     // Note that although /engines/engine[0]/starter and /engines/engine[0]/cranking might appear to be duplication it is
181     // not since the starter may be engaged with the battery voltage too low for cranking to occur (or perhaps the master 
182     // switch just left off) and the sound manager will read .../cranking to determine wether to play a cranking sound.
183     // For now though none of that is implemented so cranking can be set equal to .../starter without further checks.
184
185 //    int Alternate_Air_Pos =0; // Off = 0. Reduces power by 3 % for same throttle setting
186     // DCL - don't know what this Alternate_Air_Pos is - this is a leftover from the Schubert code.
187
188     //Check mode of engine operation
189     if(cranking) {
190         crank_counter++;
191         if(RPM <= 480) {
192             RPM += 100;
193             if(RPM > 480)
194                 RPM = 480;
195         } else {
196             // consider making a horrible noise if the starter is engaged with the engine running
197         }
198     }
199     if((!running) && (spark) && (fuel) && (crank_counter > 120)) {
200         // start the engine if revs high enough
201         if(RPM > 450) {
202             // For now just instantaneously start but later we should maybe crank for a bit
203             running = true;
204 //          RPM = 600;
205         }
206     }
207     if( (running) && ((!spark)||(!fuel)) ) {
208         // Cut the engine
209         // note that we only cut the power - the engine may continue to spin if the prop is in a moving airstream
210         running = false;
211     }
212
213     // Now we've ascertained whether the engine is running or not we can start to do the engine calculations 'proper'
214
215     // Calculate Sea Level Manifold Pressure
216     Manifold_Pressure = Calc_Manifold_Pressure( Throttle_Lever_Pos, Max_Manifold_Pressure, Min_Manifold_Pressure );
217     // cout << "manifold pressure = " << Manifold_Pressure << endl;
218
219     //Then find the actual manifold pressure (the calculated one is the sea level pressure)
220     True_Manifold_Pressure = Manifold_Pressure * p_amb / p_amb_sea_level;
221
222     //Do the fuel flow calculations
223     Calc_Fuel_Flow_Gals_Hr();
224
225     //Calculate engine power
226     Calc_Percentage_Power(Magneto_Left, Magneto_Right);
227     HP = Percentage_Power * MaxHP / 100.0;
228     Power_SI = HP * CONVERT_HP_TO_WATTS;
229
230     // FMEP calculation.  For now we will just use this during motored operation.
231     // Eventually we will calculate IMEP and use the FMEP all the time to give BMEP (maybe!)
232     if(!running) {
233         // This FMEP data is from the Patton paper, assumes fully warm conditions.
234         FMEP = 1e-12*pow(RPM,4) - 1e-8*pow(RPM,3) + 5e-5*pow(RPM,2) - 0.0722*RPM + 154.85;
235         // Gives FMEP in kPa - now convert to Pa
236         FMEP *= 1000;
237     } else {
238         FMEP = 0.0;
239     }
240     // Is this total FMEP or friction FMEP ???
241
242     Torque_FMEP = (FMEP * displacement_SI) / (2.0 * LS_PI * n_R);
243
244     // Calculate Engine Torque. Check for div by zero since percentage power correlation does not guarantee zero power at zero rpm.
245     // However this is problematical since there is a resistance to movement even at rest
246     // Ie this is a dynamics equation not a statics one.  This can be solved by going over to MEP based torque calculations.
247     if(RPM == 0) {
248         Torque_SI = 0 - Torque_FMEP;
249     }
250     else {
251         Torque_SI = ((Power_SI * 60.0) / (2.0 * LS_PI * RPM)) - Torque_FMEP;  //Torque = power / angular velocity
252         // cout << Torque << " Nm\n";
253     }
254
255     //Calculate Exhaust gas temperature
256     if(running)
257         Calc_EGT();
258     else
259         EGT = 298.0;
260
261     // Calculate Cylinder Head Temperature
262     Calc_CHT();
263     
264     // Calculate oil temperature
265     current_oil_temp = Calc_Oil_Temp(current_oil_temp);
266     
267     // Calculate Oil Pressure
268     Oil_Pressure = Calc_Oil_Press( Oil_Temp, RPM );
269     
270     // Now do the Propeller Calculations
271     Do_Prop_Calcs();
272     
273 // Now do the engine - prop torque balance to calculate final RPM
274     
275     //Calculate new RPM from torque balance and inertia.
276     Torque_Imbalance = Torque_SI - prop_torque;  //This gives a +ve value when the engine torque exeeds the prop torque
277     // (Engine torque is +ve when it acts in the direction of engine revolution, prop torque is +ve when it opposes the direction of engine revolution)
278     
279     angular_acceleration = Torque_Imbalance / (engine_inertia + prop_inertia);
280     angular_velocity_SI += (angular_acceleration * time_step);
281     // Don't let the engine go into reverse
282     if(angular_velocity_SI < 0)
283         angular_velocity_SI = 0;
284     RPM = (angular_velocity_SI * 60) / (2.0 * LS_PI);
285
286     // And finally a last check on the engine state after doing the torque balance with the prop - have we stalled?
287     if(running) { 
288         //Check if we have stalled the engine
289         if (RPM == 0) {
290             running = false;
291         } else if((RPM <= 480) && (cranking)) {
292             //Make sure the engine noise dosn't play if the engine won't start due to eg mixture lever pulled out.
293             running = false;
294             EGT = 298.0;
295         }
296     }
297
298     // And finally, do any unit conversions from internal units to output units
299     EGT_degF = (EGT * 1.8) - 459.67;
300     CHT_degF = (CHT * 1.8) - 459.67;
301 }
302
303 //*****************************************************************************************************
304
305 // FGNewEngine member functions
306
307 ////////////////////////////////////////////////////////////////////////////////////////////
308 // Return the combustion efficiency as a function of equivalence ratio
309 //
310 // Combustion efficiency values from Heywood, 
311 // "Internal Combustion Engine Fundamentals", ISBN 0-07-100499-8
312 ////////////////////////////////////////////////////////////////////////////////////////////
313 float FGNewEngine::Lookup_Combustion_Efficiency(float thi_actual)
314 {
315     const int NUM_ELEMENTS = 11;
316     float thi[NUM_ELEMENTS] = {0.0, 0.9, 1.0, 1.05, 1.1, 1.15, 1.2, 1.3, 1.4, 1.5, 1.6};  //array of equivalence ratio values
317     float neta_comb[NUM_ELEMENTS] = {0.98, 0.98, 0.97, 0.95, 0.9, 0.85, 0.79, 0.7, 0.63, 0.57, 0.525};  //corresponding array of combustion efficiency values
318     float neta_comb_actual = 0.0f;
319     float factor;
320
321     int i;
322     int j = NUM_ELEMENTS;  //This must be equal to the number of elements in the lookup table arrays
323
324     for(i=0;i<j;i++)
325     {
326         if(i == (j-1)) {
327             // Assume linear extrapolation of the slope between the last two points beyond the last point
328             float dydx = (neta_comb[i] - neta_comb[i-1]) / (thi[i] - thi[i-1]);
329             neta_comb_actual = neta_comb[i] + dydx * (thi_actual - thi[i]);
330             return neta_comb_actual;
331         }
332         if(thi_actual == thi[i]) {
333             neta_comb_actual = neta_comb[i];
334             return neta_comb_actual;
335         }
336         if((thi_actual > thi[i]) && (thi_actual < thi[i + 1])) {
337             //do linear interpolation between the two points
338             factor = (thi_actual - thi[i]) / (thi[i+1] - thi[i]);
339             neta_comb_actual = (factor * (neta_comb[i+1] - neta_comb[i])) + neta_comb[i];
340             return neta_comb_actual;
341         }
342     }
343
344     //if we get here something has gone badly wrong
345     cout << "ERROR: error in FGNewEngine::Lookup_Combustion_Efficiency\n";
346     return neta_comb_actual;
347 }
348
349 ////////////////////////////////////////////////////////////////////////////////////////////
350 // Return the percentage of best mixture power available at a given mixture strength
351 //
352 // Based on data from "Technical Considerations for Catalysts for the European Market"
353 // by H S Gandi, published 1988 by IMechE
354 //
355 // Note that currently no attempt is made to set a lean limit on stable combustion
356 ////////////////////////////////////////////////////////////////////////////////////////////
357 float FGNewEngine::Power_Mixture_Correlation(float thi_actual)
358 {
359     float AFR_actual = 14.7 / thi_actual;
360     // thi and thi_actual are equivalence ratio
361     const int NUM_ELEMENTS = 13;
362     // The lookup table is in AFR because the source data was.  I added the two end elements to make sure we are almost always in it.
363     float AFR[NUM_ELEMENTS] = {(14.7/1.6), 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, (14.7/0.6)};  //array of equivalence ratio values
364     float mixPerPow[NUM_ELEMENTS] = {78, 86, 93.5, 98, 100, 99, 96.4, 92.5, 88, 83, 78.5, 74, 58};  //corresponding array of combustion efficiency values
365     float mixPerPow_actual = 0.0f;
366     float factor;
367     float dydx;
368
369     int i;
370     int j = NUM_ELEMENTS;  //This must be equal to the number of elements in the lookup table arrays
371
372     for(i=0;i<j;i++)
373     {
374         if(i == (j-1)) {
375             // Assume linear extrapolation of the slope between the last two points beyond the last point
376             dydx = (mixPerPow[i] - mixPerPow[i-1]) / (AFR[i] - AFR[i-1]);
377             mixPerPow_actual = mixPerPow[i] + dydx * (AFR_actual - AFR[i]);
378             return mixPerPow_actual;
379         }
380         if((i == 0) && (AFR_actual < AFR[i])) {
381             // Assume linear extrapolation of the slope between the first two points for points before the first point
382             dydx = (mixPerPow[i] - mixPerPow[i-1]) / (AFR[i] - AFR[i-1]);
383             mixPerPow_actual = mixPerPow[i] + dydx * (AFR_actual - AFR[i]);
384             return mixPerPow_actual;
385         }
386         if(AFR_actual == AFR[i]) {
387             mixPerPow_actual = mixPerPow[i];
388             return mixPerPow_actual;
389         }
390         if((AFR_actual > AFR[i]) && (AFR_actual < AFR[i + 1])) {
391             //do linear interpolation between the two points
392             factor = (AFR_actual - AFR[i]) / (AFR[i+1] - AFR[i]);
393             mixPerPow_actual = (factor * (mixPerPow[i+1] - mixPerPow[i])) + mixPerPow[i];
394             return mixPerPow_actual;
395         }
396     }
397
398     //if we get here something has gone badly wrong
399     cout << "ERROR: error in FGNewEngine::Power_Mixture_Correlation\n";
400     return mixPerPow_actual;
401 }
402
403 // Calculate Cylinder Head Temperature
404 // Crudely models the cylinder head as an arbitary lump of arbitary size and area with one third of combustion energy
405 // as heat input and heat output as a function of airspeed and temperature.  Could be improved!!!
406 void FGNewEngine::Calc_CHT()
407 {
408     float h1 = -95.0;   //co-efficient for free convection
409     float h2 = -3.95;   //co-efficient for forced convection
410     float h3 = -0.05;   //co-efficient for forced convection due to prop backwash
411     float v_apparent;   //air velocity over cylinder head in m/s
412     float v_dot_cooling_air;
413     float m_dot_cooling_air;
414     float temperature_difference;
415     float arbitary_area = 1.0;
416     float dqdt_from_combustion;
417     float dqdt_forced;      //Rate of energy transfer to/from cylinder head due to forced convection (Joules) (sign convention: to cylinder head is +ve)
418     float dqdt_free;        //Rate of energy transfer to/from cylinder head due to free convection (Joules) (sign convention: to cylinder head is +ve)
419     float dqdt_cylinder_head;       //Overall energy change in cylinder head
420     float CpCylinderHead = 800.0;   //FIXME - this is a guess - I need to look up the correct value
421     float MassCylinderHead = 8.0;   //Kg - this is a guess - it dosn't have to be absolutely accurate but can be varied to alter the warm-up rate
422     float HeatCapacityCylinderHead;
423     float dCHTdt;
424
425     // The above values are hardwired to give reasonable results for an IO360 (C172 engine)
426     // Now adjust to try to compensate for arbitary sized engines - this is currently untested
427     arbitary_area *= (MaxHP / 180.0);
428     MassCylinderHead *= (MaxHP / 180.0);
429
430     temperature_difference = CHT - T_amb;
431
432     v_apparent = IAS * 0.5144444;  //convert from knots to m/s
433     v_dot_cooling_air = arbitary_area * v_apparent;
434     m_dot_cooling_air = v_dot_cooling_air * rho_air;
435
436     //Calculate rate of energy transfer to cylinder head from combustion
437     dqdt_from_combustion = m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
438     
439     //Calculate rate of energy transfer from cylinder head due to cooling  NOTE is calculated as rate to but negative
440     dqdt_forced = (h2 * m_dot_cooling_air * temperature_difference) + (h3 * RPM * temperature_difference);
441     dqdt_free = h1 * temperature_difference;
442     
443     //Calculate net rate of energy transfer to or from cylinder head
444     dqdt_cylinder_head = dqdt_from_combustion + dqdt_forced + dqdt_free;
445     
446     HeatCapacityCylinderHead = CpCylinderHead * MassCylinderHead;
447     
448     dCHTdt = dqdt_cylinder_head / HeatCapacityCylinderHead;
449     
450     CHT += (dCHTdt * time_step);
451 }
452
453 // Calculate exhaust gas temperature
454 void FGNewEngine::Calc_EGT()
455 {
456     combustion_efficiency = Lookup_Combustion_Efficiency(equivalence_ratio);  //The combustion efficiency basically tells us what proportion of the fuels calorific value is released
457
458     //now calculate energy release to exhaust
459     //We will assume a three way split of fuel energy between useful work, the coolant system and the exhaust system
460     //This is a reasonable first suck of the thumb estimate for a water cooled automotive engine - whether it holds for an air cooled aero engine is probably open to question
461     //Regardless - it won't affect the variation of EGT with mixture, and we can always put a multiplier on EGT to get a reasonable peak value.
462     enthalpy_exhaust = m_dot_fuel * calorific_value_fuel * combustion_efficiency * 0.33;
463     heat_capacity_exhaust = (Cp_air * m_dot_air) + (Cp_fuel * m_dot_fuel);
464     delta_T_exhaust = enthalpy_exhaust / heat_capacity_exhaust;
465
466     EGT = T_amb + delta_T_exhaust;
467
468     //The above gives the exhaust temperature immediately prior to leaving the combustion chamber
469     //Now derate to give a more realistic figure as measured downstream
470     //For now we will aim for a peak of around 400 degC (750 degF)
471
472     EGT *= 0.444 + ((0.544 - 0.444) * Percentage_Power / 100.0);
473 }
474
475 // Calculate Manifold Pressure based on Throttle lever Position
476 float FGNewEngine::Calc_Manifold_Pressure ( float LeverPosn, float MaxMan, float MinMan)
477 {
478     float Inches;
479
480     //Note that setting the manifold pressure as a function of lever position only is not strictly accurate
481     //MAP is also a function of engine speed. (and ambient pressure if we are going for an actual MAP model)
482     Inches = MinMan + (LeverPosn * (MaxMan - MinMan) / 100);
483
484     //allow for idle bypass valve or slightly open throttle stop
485     if(Inches < MinMan)
486         Inches = MinMan;
487
488     //Check for stopped engine (crudest way of compensating for engine speed)
489     if(RPM == 0)
490         Inches = 29.92;
491
492     return Inches;
493 }
494
495 // Calculate fuel flow in gals/hr
496 void FGNewEngine::Calc_Fuel_Flow_Gals_Hr()
497 {
498     //DCL - calculate mass air flow into engine based on speed and load - separate this out into a function eventually
499     //t_amb is actual temperature calculated from altitude
500     //calculate density from ideal gas equation
501     rho_air = p_amb / ( R_air * T_amb );
502     rho_air_manifold = rho_air * Manifold_Pressure / 29.6;  //This is a bit of a roundabout way of calculating this but it works !!  If we put manifold pressure into SI units we could do it simpler.
503     //calculate ideal engine volume inducted per second
504     swept_volume = (displacement_SI * (RPM / 60)) / 2;  //This equation is only valid for a four stroke engine
505     //calculate volumetric efficiency - for now we will just use 0.8, but actually it is a function of engine speed and the exhaust to manifold pressure ratio
506     //Note that this is cylinder vol eff - the throttle drop is already accounted for in the MAP calculation
507     volumetric_efficiency = 0.8;
508     //Now use volumetric efficiency to calculate actual air volume inducted per second
509     v_dot_air = swept_volume * volumetric_efficiency;
510     //Now calculate mass flow rate of air into engine
511     m_dot_air = v_dot_air * rho_air_manifold;
512
513 //**************
514
515     //DCL - now calculate fuel flow into engine based on air flow and mixture lever position
516     //assume lever runs from no flow at fully out to thi = 1.3 at fully in at sea level
517     //also assume that the injector linkage is ideal - hence the set mixture is maintained at a given altitude throughout the speed and load range
518     thi_sea_level = 1.3 * ( Mixture_Lever_Pos / 100.0 );
519     equivalence_ratio = thi_sea_level * p_amb_sea_level / p_amb; //ie as we go higher the mixture gets richer for a given lever position
520     m_dot_fuel = m_dot_air / 14.7 * equivalence_ratio;
521     Fuel_Flow_gals_hr = (m_dot_fuel / rho_fuel) * 264.172 * 3600.0;  // Note this assumes US gallons
522 }
523
524 // Calculate the percentage of maximum rated power delivered as a function of Manifold pressure multiplied by engine speed (rpm)
525 // This is not necessarilly the best approach but seems to work for now.
526 // May well need tweaking at the bottom end if the prop model is changed.
527 void FGNewEngine::Calc_Percentage_Power(bool mag_left, bool mag_right)
528 {
529     // For a given Manifold Pressure and RPM calculate the % Power
530     // Multiply Manifold Pressure by RPM
531     float ManXRPM = True_Manifold_Pressure * RPM;
532
533 /*
534 //  Phil's %power correlation
535     //  Calculate % Power
536     Percentage_Power = (+ 7E-09 * ManXRPM * ManXRPM) + ( + 7E-04 * ManXRPM) - 0.1218;
537     // cout << Percentage_Power <<  "%" << "\t";
538 */
539
540 // DCL %power correlation - basically Phil's correlation modified to give slighty less power at the low end
541 // might need some adjustment as the prop model is adjusted
542 // My aim is to match the prop model and engine model at the low end to give the manufacturer's recommended idle speed with the throttle closed - 600rpm for the Continental IO520
543     //  Calculate % Power for Nev's prop model
544     //Percentage_Power = (+ 6E-09 * ManXRPM * ManXRPM) + ( + 8E-04 * ManXRPM) - 1.8524;
545
546     // Calculate %power for DCL prop model
547     Percentage_Power = (7e-9 * ManXRPM * ManXRPM) + (7e-4 * ManXRPM) - 1.0;
548
549     // Power de-rating for altitude has been removed now that we are basing the power
550     // on the actual manifold pressure, which takes air pressure into account.  However - this fails to
551     // take the temperature into account - this is TODO.
552
553     // Adjust power for temperature - this is temporary until the power is done as a function of mass flow rate induced
554     // Adjust for Temperature - Temperature above Standard decrease
555     // power by 7/120 % per degree F increase, and incease power for
556     // temps below at the same ratio
557     float T_amb_degF = (T_amb * 1.8) - 459.67;
558     float T_amb_sea_lev_degF = (288 * 1.8) - 459.67; 
559     Percentage_Power = Percentage_Power + ((T_amb_sea_lev_degF - T_amb_degF) * 7 /120);
560
561     //DCL - now adjust power to compensate for mixture
562     Percentage_of_best_power_mixture_power = Power_Mixture_Correlation(equivalence_ratio);
563     Percentage_Power = Percentage_Power * Percentage_of_best_power_mixture_power / 100.0;
564
565     // Now Derate engine for the effects of Bad/Switched off magnetos
566     //if (Magneto_Left == 0 && Magneto_Right == 0) {
567     if(!running) {
568         // cout << "Both OFF\n";
569         Percentage_Power = 0;
570     } else if (mag_left && mag_right) {
571         // cout << "Both On    ";
572     } else if (mag_left == 0 || mag_right== 0) {
573         // cout << "1 Magneto Failed   ";
574         Percentage_Power = Percentage_Power * ((100.0 - Mag_Derate_Percent)/100.0);
575         //  cout << FGEng1_Percentage_Power <<  "%" << "\t";
576     }
577 /*
578     //DCL - stall the engine if RPM drops below 450 - this is possible if mixture lever is pulled right out
579     //This is a kludge that I should eliminate by adding a total fmep estimation.
580     if(RPM < 450)
581         Percentage_Power = 0;
582 */
583     if(Percentage_Power < 0)
584         Percentage_Power = 0;
585 }
586
587 // Calculate Oil Temperature in degrees Kelvin
588 float FGNewEngine::Calc_Oil_Temp (float oil_temp)
589 {
590     float idle_percentage_power = 2.3;  // approximately
591     float target_oil_temp;          // Steady state oil temp at the current engine conditions
592     float time_constant;            // The time constant for the differential equation
593     if(running) {
594         target_oil_temp = 363;
595         time_constant = 500;        // Time constant for engine-on idling.
596         if(Percentage_Power > idle_percentage_power) {
597             time_constant /= ((Percentage_Power / idle_percentage_power) / 10.0);       // adjust for power 
598         }
599     } else {
600         target_oil_temp = 298;
601         time_constant = 1000;  // Time constant for engine-off; reflects the fact that oil is no longer getting circulated
602     }
603
604     float dOilTempdt = (target_oil_temp - oil_temp) / time_constant;
605
606     oil_temp += (dOilTempdt * time_step);
607
608     return (oil_temp);
609 }
610
611 // Calculate Oil Pressure
612 float FGNewEngine::Calc_Oil_Press (float Oil_Temp, float Engine_RPM)
613 {
614     float Oil_Pressure = 0;                     //PSI
615     float Oil_Press_Relief_Valve = 60;  //PSI
616     float Oil_Press_RPM_Max = 1800;
617     float Design_Oil_Temp = 85;         //Celsius
618     float Oil_Viscosity_Index = 0.25;   // PSI/Deg C
619 //    float Temp_Deviation = 0;         // Deg C
620
621     Oil_Pressure = (Oil_Press_Relief_Valve / Oil_Press_RPM_Max) * Engine_RPM;
622
623     // Pressure relief valve opens at Oil_Press_Relief_Valve PSI setting
624     if (Oil_Pressure >= Oil_Press_Relief_Valve) {
625         Oil_Pressure = Oil_Press_Relief_Valve;
626     }
627
628     // Now adjust pressure according to Temp which affects the viscosity
629
630     Oil_Pressure += (Design_Oil_Temp - Oil_Temp) * Oil_Viscosity_Index;
631
632     return Oil_Pressure;
633 }
634
635
636 // Propeller calculations.
637 void FGNewEngine::Do_Prop_Calcs()
638 {
639     float Gear_Ratio = 1.0;
640     float forward_velocity;             // m/s
641     float prop_power_consumed_SI;       // Watts
642     double J;                           // advance ratio - dimensionless
643     double Cp_20;                   // coefficient of power for 20 degree blade angle
644     double Cp_25;                   // coefficient of power for 25 degree blade angle
645     double Cp;                      // Our actual coefficient of power
646     double neta_prop_20;
647     double neta_prop_25;
648     double neta_prop;               // prop efficiency
649
650     FGProp1_RPS = RPM * Gear_Ratio / 60.0; 
651     angular_velocity_SI = 2.0 * LS_PI * RPM / 60.0;
652     forward_velocity = IAS * 0.514444444444;        // Convert to m/s
653     
654     if(FGProp1_RPS == 0)
655         J = 0;
656     else
657         J = forward_velocity / (FGProp1_RPS * prop_diameter);
658     //cout << "advance_ratio = " << J << '\n';
659     
660     //Cp correlations based on data from McCormick
661     Cp_20 = 0.0342*J*J*J*J - 0.1102*J*J*J + 0.0365*J*J - 0.0133*J + 0.064;
662     Cp_25 = 0.0119*J*J*J*J - 0.0652*J*J*J + 0.018*J*J - 0.0077*J + 0.0921;
663     
664     //cout << "Cp_20 = " << Cp_20 << '\n';
665     //cout << "Cp_25 = " << Cp_25 << '\n';
666     
667     //Assume that the blade angle is between 20 and 25 deg - reasonable for fixed pitch prop but won't hold for variable one !!!
668     Cp = Cp_20 + ( (Cp_25 - Cp_20) * ((blade_angle - 20)/(25 - 20)) );
669     //cout << "Cp = " << Cp << '\n';
670     //cout << "RPM = " << RPM << '\n';
671     //cout << "angular_velocity_SI = " << angular_velocity_SI << '\n';
672     
673     prop_power_consumed_SI = Cp * rho_air * pow(FGProp1_RPS,3.0f) * pow(float(prop_diameter),5.0f);
674     //cout << "prop HP consumed = " << prop_power_consumed_SI / 745.699 << '\n';
675     if(angular_velocity_SI == 0)
676         prop_torque = 0;
677         // However this can give problems - if rpm == 0 but forward velocity increases the prop should be able to generate a torque to start the engine spinning
678         // Unlikely to happen in practice - but I suppose someone could move the lever of a stopped large piston engine from feathered to windmilling.
679         // This *does* give problems - if the plane is put into a steep climb whilst windmilling the engine friction will eventually stop it spinning.
680         // When put back into a dive it never starts re-spinning again.  Although it is unlikely that anyone would do this in real life, they might well do it in a sim!!!
681     else
682         prop_torque = prop_power_consumed_SI / angular_velocity_SI;
683     
684     // calculate neta_prop here
685     neta_prop_20 = 0.1328*J*J*J*J - 1.3073*J*J*J + 0.3525*J*J + 1.5591*J + 0.0007;
686     neta_prop_25 = -0.3121*J*J*J*J + 0.4234*J*J*J - 0.7686*J*J + 1.5237*J - 0.0004;
687     neta_prop = neta_prop_20 + ( (neta_prop_25 - neta_prop_20) * ((blade_angle - 20)/(25 - 20)) );
688     
689     // Check for zero forward velocity to avoid divide by zero
690     if(forward_velocity < 0.0001)
691         prop_thrust = 0.0;
692         // I don't see how this works - how can the plane possibly start from rest ???
693         // Hmmmm - it works because the forward_velocity at present never drops below about 0.03 even at rest
694         // We can't really rely on this in the future - needs fixing !!!!
695         // The problem is that we're doing this calculation backwards - we're working out the thrust from the power consumed and the velocity, which becomes invalid as velocity goes to zero.
696         // It would be far more natural to work out the power consumed from the thrust - FIXME!!!!!.
697     else
698         prop_thrust = neta_prop * prop_power_consumed_SI / forward_velocity;       //TODO - rename forward_velocity to IAS_SI
699     //cout << "prop_thrust = " << prop_thrust << '\n';
700 }