]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
More turbulence tweaks and fixes.
[flightgear.git] / src / FDM / JSBSim / JSBSim.cxx
1 // JSBsim.cxx -- interface to the JSBsim flight model
2 //
3 // Written by Curtis Olson, started February 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #include STL_STRING
35
36 #include <simgear/constants.h>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/math/sg_geodesy.hxx>
39 #include <simgear/misc/sg_path.hxx>
40
41 #include <FDM/flight.hxx>
42
43 #include <Aircraft/aircraft.hxx>
44 #include <Controls/controls.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47
48 #include <FDM/JSBSim/FGFDMExec.h>
49 #include <FDM/JSBSim/FGAircraft.h>
50 #include <FDM/JSBSim/FGFCS.h>
51 #include <FDM/JSBSim/FGPosition.h>
52 #include <FDM/JSBSim/FGRotation.h>
53 #include <FDM/JSBSim/FGState.h>
54 #include <FDM/JSBSim/FGTranslation.h>
55 #include <FDM/JSBSim/FGAuxiliary.h>
56 #include <FDM/JSBSim/FGInitialCondition.h>
57 #include <FDM/JSBSim/FGTrim.h>
58 #include <FDM/JSBSim/FGAtmosphere.h>
59 #include <FDM/JSBSim/FGMassBalance.h>
60 #include <FDM/JSBSim/FGAerodynamics.h>
61 #include <FDM/JSBSim/FGLGear.h>
62 #include <FDM/JSBSim/FGPropertyManager.h>
63 #include "JSBSim.hxx"
64
65 static inline double
66 FMAX (double a, double b)
67 {
68   return a > b ? a : b;
69 }
70
71
72 /******************************************************************************/
73
74 FGJSBsim::FGJSBsim( double dt ) 
75   : FGInterface(dt)
76 {
77     bool result;
78    
79     fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
80     
81     State           = fdmex->GetState();
82     Atmosphere      = fdmex->GetAtmosphere();
83     FCS             = fdmex->GetFCS();
84     MassBalance     = fdmex->GetMassBalance();
85     Propulsion      = fdmex->GetPropulsion();
86     Aircraft        = fdmex->GetAircraft();
87     Translation     = fdmex->GetTranslation();
88     Rotation        = fdmex->GetRotation();
89     Position        = fdmex->GetPosition();
90     Auxiliary       = fdmex->GetAuxiliary();
91     Aerodynamics    = fdmex->GetAerodynamics();
92     GroundReactions = fdmex->GetGroundReactions(); 
93     
94     fgic=fdmex->GetIC();
95     needTrim=true;
96   
97     SGPath aircraft_path( globals->get_fg_root() );
98     aircraft_path.append( "Aircraft" );
99
100     SGPath engine_path( globals->get_fg_root() );
101     engine_path.append( "Engine" );
102     State->Setdt( dt );
103
104     result = fdmex->LoadModel( aircraft_path.str(),
105                                engine_path.str(),
106                                fgGetString("/sim/aero") );
107     
108     if (result) {
109       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
110     } else {
111       SG_LOG( SG_FLIGHT, SG_INFO,
112               "  aero does not exist (you may have mis-typed the name).");
113       throw(-1);
114     }
115
116     SG_LOG( SG_FLIGHT, SG_INFO, "" );
117     SG_LOG( SG_FLIGHT, SG_INFO, "" );
118     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
119
120     int Neng = Propulsion->GetNumEngines();
121     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
122     
123     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
124         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
125                 << GroundReactions->GetNumGearUnits() );
126         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
127          SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
128          SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
129          exit(-1);
130     }
131         
132     
133     init_gear();
134
135                                 // Set initial fuel levels if provided.
136     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
137       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
138       if (node->getChild("level-gal_us", 0, false) != 0)
139         Propulsion->GetTank(i)
140           ->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
141     }
142     
143     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
144     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
145     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
146     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
147
148     startup_trim = fgGetNode("/sim/presets/trim", true);
149
150     trimmed = fgGetNode("/fdm/trim/trimmed", true);
151     trimmed->setBoolValue(false);
152
153     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
154     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
155     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
156     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
157     
158     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
159     stall_warning->setDoubleValue(0);
160     
161
162     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
163     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
164     left_aileron_pos_pct
165         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
166     right_aileron_pos_pct
167         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
168     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
169     speedbrake_pos_pct
170         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
171     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
172     
173
174     elevator_pos_pct->setDoubleValue(0);
175     left_aileron_pos_pct->setDoubleValue(0);
176     right_aileron_pos_pct->setDoubleValue(0);
177     rudder_pos_pct->setDoubleValue(0);
178     flap_pos_pct->setDoubleValue(0);
179     speedbrake_pos_pct->setDoubleValue(0);
180     spoilers_pos_pct->setDoubleValue(0);
181
182     temperature = fgGetNode("/environment/temperature-degc",true);
183     pressure = fgGetNode("/environment/pressure-inhg",true);
184     density = fgGetNode("/environment/density-slugft3",true);
185     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
186     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
187     
188     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
189     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
190     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
191      
192
193 }
194 /******************************************************************************/
195 FGJSBsim::~FGJSBsim(void) {
196         delete fdmex;
197 }
198
199 /******************************************************************************/
200
201 // Initialize the JSBsim flight model, dt is the time increment for
202 // each subsequent iteration through the EOM
203
204 void FGJSBsim::init() {
205
206     double tmp;
207     
208     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
209
210     // Explicitly call the superclass's
211     // init method first.
212
213 #ifdef FG_WEATHERCM
214     Atmosphere->UseInternal();
215 #else
216     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
217       Atmosphere->UseExternal();
218       Atmosphere->SetExTemperature(
219                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
220       Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
221       Atmosphere->SetExDensity(density->getDoubleValue());
222
223       tmp = turbulence_gain->getDoubleValue();
224       Atmosphere->SetTurbGain(tmp * tmp * 100.0);
225
226       tmp = turbulence_rate->getDoubleValue();
227       if (tmp <= 0)
228           tmp = 1.0;
229       Atmosphere->SetTurbRate(tmp);
230
231     } else {
232       Atmosphere->UseInternal();
233     }
234 #endif
235     
236     fgic->SetVnorthFpsIC( wind_from_north->getDoubleValue() );
237     fgic->SetVeastFpsIC( wind_from_east->getDoubleValue() );
238     fgic->SetVdownFpsIC( wind_from_down->getDoubleValue() );
239
240     //Atmosphere->SetExTemperature(get_Static_temperature());
241     //Atmosphere->SetExPressure(get_Static_pressure());
242     //Atmosphere->SetExDensity(get_Density());
243     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
244      << ", " << fdmex->GetAtmosphere()->GetPressure() 
245      << ", " << fdmex->GetAtmosphere()->GetDensity() );
246
247     common_init();
248     copy_to_JSBsim();
249     
250
251     fdmex->RunIC(); //loop JSBSim once w/o integrating
252     copy_from_JSBsim(); //update the bus
253
254     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
255
256     switch(fgic->GetSpeedSet()) {
257     case setned:
258         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
259                << Position->GetVn() << ", "
260                << Position->GetVe() << ", "
261                << Position->GetVd() << " ft/s");
262     break;
263     case setuvw:
264         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
265                << Translation->GetUVW(1) << ", "
266                << Translation->GetUVW(2) << ", "
267                << Translation->GetUVW(3) << " ft/s");
268     break;
269     case setmach:
270         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
271                << Translation->GetMach() );
272     break;
273     case setvc:
274     default:
275         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
276                << Auxiliary->GetVcalibratedKTS() << " knots" );
277     break;
278     }
279     
280     stall_warning->setDoubleValue(0);
281     
282     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
283             <<  Rotation->Getphi()*RADTODEG << " deg" );
284     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
285             << Rotation->Gettht()*RADTODEG << " deg" );
286     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
287             << Rotation->Getpsi()*RADTODEG << " deg" );
288     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
289             << Position->GetLatitude() << " deg" );
290     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
291             << Position->GetLongitude() << " deg" );
292     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
293         << Position->Geth() << " feet" );
294     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
295
296     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
297
298     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
299     
300     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " << 
301                                   globals->get_controls()->get_gear_down() );
302     
303
304    
305 }
306
307 /******************************************************************************/
308
309 // Run an iteration of the EOM (equations of motion)
310
311 void
312 FGJSBsim::update( double dt ) {
313
314     if (is_suspended())
315       return;
316
317     int multiloop = _calc_multiloop(dt);
318
319     int i;
320
321     // double save_alt = 0.0;
322
323     copy_to_JSBsim();
324
325     trimmed->setBoolValue(false);
326     
327     if ( needTrim ) {
328       if ( startup_trim->getBoolValue() ) {
329         SG_LOG(SG_FLIGHT, SG_INFO,
330           "Ready to trim, terrain altitude is: " 
331             << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
332         fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
333         do_trim();
334       } else {
335         fdmex->RunIC();  //apply any changes made through the set_ functions
336       }
337       needTrim = false;  
338     }    
339     
340     for ( i=0; i < multiloop; i++ ) {
341         fdmex->Run();
342     }
343
344     FGJSBBase::Message* msg;
345     while (fdmex->ReadMessage()) {
346       msg = fdmex->ProcessMessage();
347       switch (msg->type) {
348       case FGJSBBase::Message::eText:
349         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
350         break;
351       case FGJSBBase::Message::eBool:
352         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
353         break;
354       case FGJSBBase::Message::eInteger:
355         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
356         break;
357       case FGJSBBase::Message::eDouble:
358         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
359         break;
360       default:
361         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
362         break;
363       }
364     }
365
366     // translate JSBsim back to FG structure so that the
367     // autopilot (and the rest of the sim can use the updated values
368     copy_from_JSBsim();
369 }
370
371 /******************************************************************************/
372
373 // Convert from the FGInterface struct to the JSBsim generic_ struct
374
375 bool FGJSBsim::copy_to_JSBsim() {
376     double tmp;
377     unsigned int i;
378
379     // copy control positions into the JSBsim structure
380
381     FCS->SetDaCmd( globals->get_controls()->get_aileron());
382     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
383     FCS->SetDeCmd( globals->get_controls()->get_elevator());
384     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
385     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
386     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
387     FCS->SetDfCmd(  globals->get_controls()->get_flaps() );
388     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() ); 
389     FCS->SetDspCmd( globals->get_controls()->get_spoilers() ); 
390
391                                 // Parking brake sets minimum braking
392                                 // level for mains.
393     double parking_brake = globals->get_controls()->get_parking_brake();
394     FCS->SetLBrake(FMAX(globals->get_controls()->get_brake(0), parking_brake));
395     FCS->SetRBrake(FMAX(globals->get_controls()->get_brake(1), parking_brake));
396     FCS->SetCBrake( globals->get_controls()->get_brake(2) );
397
398     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
399     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
400       FGEngine * eng = Propulsion->GetEngine(i);
401       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
402       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
403       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
404       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
405       Propulsion->GetThruster(i)->SetRPM(node->getDoubleValue("rpm"));
406       eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
407       eng->SetStarter( globals->get_controls()->get_starter(i) );
408       eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
409       eng->SetReverse( globals->get_controls()->get_reverser(i) );
410       eng->SetInjection( globals->get_controls()->get_water_injection(i) );
411       eng->SetIgnition( globals->get_controls()->get_ignition(i) );
412       eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
413       eng->SetNitrous( globals->get_controls()->get_nitrous_injection(i) );
414     }
415
416     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
417     Position->SetSeaLevelRadius( get_Sea_level_radius() );
418     Position->SetRunwayRadius( get_Runway_altitude() 
419                                + get_Sea_level_radius() );
420
421     Atmosphere->SetExTemperature(
422                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
423     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
424     Atmosphere->SetExDensity(density->getDoubleValue());
425
426     tmp = turbulence_gain->getDoubleValue();
427     Atmosphere->SetTurbGain(tmp * tmp * 100.0);
428
429     if (turbulence_rate->hasValue())
430         tmp = turbulence_rate->getDoubleValue();
431     else
432         tmp = 1.0;
433     Atmosphere->SetTurbRate(tmp);
434
435     Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
436                             wind_from_east->getDoubleValue(),
437                             wind_from_down->getDoubleValue() );
438 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
439 //                  << get_V_north_airmass() << ", "
440 //                  << get_V_east_airmass()  << ", "
441 //                  << get_V_down_airmass() );
442
443     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
444       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
445       FGTank * tank = Propulsion->GetTank(i);
446       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
447 //       tank->SetContents(node->getDoubleValue("level-lb"));
448     }
449
450     return true;
451 }
452
453 /******************************************************************************/
454
455 // Convert from the JSBsim generic_ struct to the FGInterface struct
456
457 bool FGJSBsim::copy_from_JSBsim() {
458     unsigned int i, j;
459
460     _set_Inertias( MassBalance->GetMass(),
461                    MassBalance->GetIxx(),
462                    MassBalance->GetIyy(),
463                    MassBalance->GetIzz(),
464                    MassBalance->GetIxz() );
465
466     _set_CG_Position( MassBalance->GetXYZcg(1),
467                       MassBalance->GetXYZcg(2),
468                       MassBalance->GetXYZcg(3) );
469
470     _set_Accels_Body( Aircraft->GetBodyAccel()(1),
471                       Aircraft->GetBodyAccel()(2),
472                       Aircraft->GetBodyAccel()(3) );
473
474     //_set_Accels_CG_Body( Aircraft->GetBodyAccel()(1),
475     //                     Aircraft->GetBodyAccel()(2),
476     //                     Aircraft->GetBodyAccel()(3) );
477     //
478     _set_Accels_CG_Body_N ( Aircraft->GetNcg()(1),
479                             Aircraft->GetNcg()(2),
480                             Aircraft->GetNcg()(3) );
481     
482     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel()(1),
483                             Auxiliary->GetPilotAccel()(2),
484                             Auxiliary->GetPilotAccel()(3) );
485
486    // _set_Accels_Pilot_Body_N( Auxiliary->GetPilotAccel()(1)/32.1739,
487    //                           Auxiliary->GetNpilot(2)/32.1739,
488    //                           Auxiliary->GetNpilot(3)/32.1739 );
489
490     _set_Nlf( Aircraft->GetNlf() );
491
492     // Velocities
493
494     _set_Velocities_Local( Position->GetVn(),
495                            Position->GetVe(),
496                            Position->GetVd() );
497
498     _set_Velocities_Wind_Body( Translation->GetUVW(1),
499                                Translation->GetUVW(2),
500                                Translation->GetUVW(3) );
501
502     _set_V_rel_wind( Translation->GetVt() );
503
504     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
505
506     // _set_V_calibrated( Auxiliary->GetVcalibratedFPS() );
507
508     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
509
510     _set_V_ground_speed( Position->GetVground() );
511
512     _set_Omega_Body( Rotation->GetPQR(1),
513                      Rotation->GetPQR(2),
514                      Rotation->GetPQR(3) );
515
516     _set_Euler_Rates( Rotation->GetEulerRates(1),
517                       Rotation->GetEulerRates(2),
518                       Rotation->GetEulerRates(3) );
519
520     _set_Geocentric_Rates(Position->GetLatitudeDot(),
521                           Position->GetLongitudeDot(),
522                           Position->Gethdot() );
523
524     _set_Mach_number( Translation->GetMach() );
525
526     // Positions
527     _updateGeocentricPosition( Position->GetLatitude(),
528                                Position->GetLongitude(),
529                                Position->Geth() );
530
531     _set_Altitude_AGL( Position->GetDistanceAGL() );
532
533     _set_Euler_Angles( Rotation->Getphi(),
534                        Rotation->Gettht(),
535                        Rotation->Getpsi() );
536
537     _set_Alpha( Translation->Getalpha() );
538     _set_Beta( Translation->Getbeta() );
539
540
541     _set_Gamma_vert_rad( Position->GetGamma() );
542     // set_Gamma_horiz_rad( Gamma_horiz_rad );
543
544     _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
545
546     _set_Climb_Rate( Position->Gethdot() );
547
548
549     for ( i = 1; i <= 3; i++ ) {
550         for ( j = 1; j <= 3; j++ ) {
551             _set_T_Local_to_Body( i, j, State->GetTl2b(i,j) );
552         }
553     }
554
555                                 // Copy the engine values from JSBSim.
556     for( i=0; i < Propulsion->GetNumEngines(); i++ ) {
557       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
558       FGEngine * eng = Propulsion->GetEngine(i);
559       FGThruster * thrust = Propulsion->GetThruster(i);
560
561       node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
562       node->setDoubleValue("rpm", thrust->GetRPM());
563       node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
564       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
565       node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
566       node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
567       node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
568       node->setDoubleValue("thrust_lb", eng->GetThrust());
569       node->setDoubleValue("N1", eng->GetN1());
570       node->setDoubleValue("N2", eng->GetN2());
571       node->setDoubleValue("EGT_degC", eng->GetEGT());
572       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
573       node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
574       node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
575       node->setBoolValue("running", eng->GetRunning());
576       node->setBoolValue("cranking", eng->GetCranking());
577       node->setBoolValue("ignition", eng->GetIgnition());
578       node->setBoolValue("augmentation", eng->GetAugmentation());
579       node->setBoolValue("water-injection", eng->GetInjection());
580       node->setBoolValue("reversed", eng->GetReversed());
581       node->setBoolValue("cutoff", eng->GetCutoff());
582       node->setBoolValue("nitrous", eng->GetNitrous());
583     }
584
585     static const SGPropertyNode *fuel_freeze
586         = fgGetNode("/sim/freeze/fuel");
587
588                                 // Copy the fuel levels from JSBSim if fuel
589                                 // freeze not enabled.
590     if ( ! fuel_freeze->getBoolValue() ) {
591         for (i = 0; i < Propulsion->GetNumTanks(); i++) {
592             SGPropertyNode * node
593                 = fgGetNode("/consumables/fuel/tank", i, true);
594             double contents = Propulsion->GetTank(i)->GetContents();
595             node->setDoubleValue("level-gal_us", contents/6.6);
596             node->setDoubleValue("level-lb", contents);
597             // node->setDoubleValue("temperature_degC", 
598         }
599     }
600
601     update_gear();
602     
603     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
604     
605     /* elevator_pos_deg->setDoubleValue( FCS->GetDePos()*SG_RADIANS_TO_DEGREES );
606     left_aileron_pos_deg->setDoubleValue( FCS->GetDaLPos()*SG_RADIANS_TO_DEGREES );
607     right_aileron_pos_deg->setDoubleValue( FCS->GetDaRPos()*SG_RADIANS_TO_DEGREES );
608     rudder_pos_deg->setDoubleValue( -1*FCS->GetDrPos()*SG_RADIANS_TO_DEGREES );
609     flap_pos_deg->setDoubleValue( FCS->GetDfPos() ); */
610
611     
612     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
613     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
614     right_aileron_pos_pct->setDoubleValue( -1*FCS->GetDaLPos(ofNorm) );
615     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
616     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
617     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
618     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
619
620     
621     return true;
622 }
623
624 bool FGJSBsim::ToggleDataLogging(void) {
625     return fdmex->GetOutput()->Toggle();
626 }
627
628
629 bool FGJSBsim::ToggleDataLogging(bool state) {
630     if (state) {
631       fdmex->GetOutput()->Enable();
632       return true;
633     } else {
634       fdmex->GetOutput()->Disable();
635       return false;
636     }
637 }
638
639
640 //Positions
641 void FGJSBsim::set_Latitude(double lat) {
642     static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
643     double alt;
644     double sea_level_radius_meters, lat_geoc;
645
646                                 // In case we're not trimming
647     FGInterface::set_Latitude(lat);
648     
649     if ( altitude->getDoubleValue() > -9990 ) {
650       alt = altitude->getDoubleValue();
651     } else {
652       alt = 0.0;
653     }
654    
655     update_ic();
656     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
657     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
658
659     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER, 
660                       &sea_level_radius_meters, &lat_geoc );
661     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
662     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );    
663     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
664     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
665     fgic->SetLatitudeRadIC( lat_geoc );
666     needTrim=true;
667 }
668
669 void FGJSBsim::set_Longitude(double lon) {
670
671     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
672
673                                 // In case we're not trimming
674     FGInterface::set_Longitude(lon);
675
676     update_ic();
677     fgic->SetLongitudeRadIC( lon );
678     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
679     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
680     needTrim=true;
681 }
682
683 void FGJSBsim::set_Altitude(double alt) {
684     static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
685
686     double sea_level_radius_meters,lat_geoc;
687
688     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
689     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
690     
691                                 // In case we're not trimming
692     FGInterface::set_Altitude(alt);
693
694     update_ic();
695     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
696                   &sea_level_radius_meters, &lat_geoc);
697     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
698     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
699     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
700     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
701     SG_LOG(SG_FLIGHT, SG_INFO,
702           "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
703     fgic->SetLatitudeRadIC( lat_geoc );
704     fgic->SetAltitudeFtIC(alt);
705     needTrim=true;
706 }
707
708 void FGJSBsim::set_V_calibrated_kts(double vc) {
709     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
710
711                                 // In case we're not trimming
712     FGInterface::set_V_calibrated_kts(vc);
713
714     update_ic();
715     fgic->SetVcalibratedKtsIC(vc);
716     needTrim=true;
717 }
718
719 void FGJSBsim::set_Mach_number(double mach) {
720     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
721     
722                                 // In case we're not trimming
723     FGInterface::set_Mach_number(mach);
724
725     update_ic();
726     fgic->SetMachIC(mach);
727     needTrim=true;
728 }
729
730 void FGJSBsim::set_Velocities_Local( double north, double east, double down ){
731     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
732        << north << ", " <<  east << ", " << down );
733     
734                                 // In case we're not trimming
735     FGInterface::set_Velocities_Local(north, east, down);
736
737     update_ic();
738     fgic->SetVnorthFpsIC(north);
739     fgic->SetVeastFpsIC(east);
740     fgic->SetVdownFpsIC(down);
741     needTrim=true;
742 }
743
744 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w){
745     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
746        << u << ", " <<  v << ", " <<  w );
747     
748                                 // In case we're not trimming
749     FGInterface::set_Velocities_Wind_Body(u, v, w);
750
751     update_ic();
752     fgic->SetUBodyFpsIC(u);
753     fgic->SetVBodyFpsIC(v);
754     fgic->SetWBodyFpsIC(w);
755     needTrim=true;
756 }
757
758 //Euler angles
759 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi ) {
760     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
761        << phi << ", " << theta << ", " << psi );
762     
763                                 // In case we're not trimming
764     FGInterface::set_Euler_Angles(phi, theta, psi);
765
766     update_ic();
767     fgic->SetPitchAngleRadIC(theta);
768     fgic->SetRollAngleRadIC(phi);
769     fgic->SetTrueHeadingRadIC(psi);
770     needTrim=true;
771 }
772
773 //Flight Path
774 void FGJSBsim::set_Climb_Rate( double roc) {
775     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
776     
777                                 // In case we're not trimming
778     FGInterface::set_Climb_Rate(roc);
779
780     update_ic();
781     //since both climb rate and flight path angle are set in the FG
782     //startup sequence, something is needed to keep one from cancelling
783     //out the other.
784     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
785       fgic->SetClimbRateFpsIC(roc);
786     }  
787     needTrim=true;
788 }
789
790 void FGJSBsim::set_Gamma_vert_rad( double gamma) {
791     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
792     
793     update_ic();
794     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
795       fgic->SetFlightPathAngleRadIC(gamma);
796     }  
797     needTrim=true;
798 }
799
800 void FGJSBsim::init_gear(void ) {
801     
802     FGGroundReactions* gr=fdmex->GetGroundReactions();
803     int Ngear=GroundReactions->GetNumGearUnits();
804     for (int i=0;i<Ngear;i++) {
805       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
806       node->setDoubleValue("xoffset-in",
807                            gr->GetGearUnit(i)->GetBodyLocation()(1));
808       node->setDoubleValue("yoffset-in",
809                            gr->GetGearUnit(i)->GetBodyLocation()(2));
810       node->setDoubleValue("zoffset-in",
811                            gr->GetGearUnit(i)->GetBodyLocation()(3));
812       node->setBoolValue("wow", gr->GetGearUnit(i)->GetWOW());
813       node->setBoolValue("has-brake", gr->GetGearUnit(i)->GetBrakeGroup() > 0);
814       node->setDoubleValue("position-norm", FCS->GetGearPos());
815     }  
816 }
817
818 void FGJSBsim::update_gear(void) {
819     
820     FGGroundReactions* gr=fdmex->GetGroundReactions();
821     int Ngear=GroundReactions->GetNumGearUnits();
822     for (int i=0;i<Ngear;i++) {
823       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
824       node->getChild("wow", 0, true)
825         ->setBoolValue(gr->GetGearUnit(i)->GetWOW());
826       node->getChild("position-norm", 0, true)
827         ->setDoubleValue(FCS->GetGearPos());
828     }  
829 }
830
831 void FGJSBsim::do_trim(void) {
832
833         FGTrim *fgtrim;
834         if( fgGetBool("/sim/presets/onground") ) {
835             fgic->SetVcalibratedKtsIC(0.0);
836             fgtrim=new FGTrim(fdmex,tGround);
837         } else {
838             fgtrim=new FGTrim(fdmex,tLongitudinal);
839         }
840         if( !fgtrim->DoTrim() ) {
841             fgtrim->Report();
842             fgtrim->TrimStats();
843         } else {
844             trimmed->setBoolValue(true);
845         }
846         State->ReportState();
847         delete fgtrim;
848         pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
849         throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
850         aileron_trim->setDoubleValue( FCS->GetDaCmd() );
851         rudder_trim->setDoubleValue( FCS->GetDrCmd() );
852
853         globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
854         globals->get_controls()->set_elevator(FCS->GetDeCmd());
855         globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
856                                               FCS->GetThrottleCmd(0));
857
858         globals->get_controls()->set_aileron(FCS->GetDaCmd());
859         globals->get_controls()->set_rudder( FCS->GetDrCmd());
860     
861         SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
862 }          
863
864 void FGJSBsim::update_ic(void) {       
865    if( !needTrim ) {
866      fgic->SetLatitudeRadIC(get_Lat_geocentric() );       
867      fgic->SetLongitudeRadIC( get_Longitude() );       
868      fgic->SetAltitudeFtIC( get_Altitude() );       
869      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );       
870      fgic->SetPitchAngleRadIC( get_Theta() );       
871      fgic->SetRollAngleRadIC( get_Phi() );       
872      fgic->SetTrueHeadingRadIC( get_Psi() );       
873      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
874    }  
875 }
876