]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
fd81aca96e950c3abbb4c8dd291287acc9c9a81d
[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       Atmosphere->SetTurbRate(tmp);
228
229     } else {
230       Atmosphere->UseInternal();
231     }
232 #endif
233     
234     fgic->SetVnorthFpsIC( wind_from_north->getDoubleValue() );
235     fgic->SetVeastFpsIC( wind_from_east->getDoubleValue() );
236     fgic->SetVdownFpsIC( wind_from_down->getDoubleValue() );
237
238     //Atmosphere->SetExTemperature(get_Static_temperature());
239     //Atmosphere->SetExPressure(get_Static_pressure());
240     //Atmosphere->SetExDensity(get_Density());
241     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
242      << ", " << fdmex->GetAtmosphere()->GetPressure() 
243      << ", " << fdmex->GetAtmosphere()->GetDensity() );
244
245     common_init();
246     copy_to_JSBsim();
247     
248
249     fdmex->RunIC(); //loop JSBSim once w/o integrating
250     copy_from_JSBsim(); //update the bus
251
252     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
253
254     switch(fgic->GetSpeedSet()) {
255     case setned:
256         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
257                << Position->GetVn() << ", "
258                << Position->GetVe() << ", "
259                << Position->GetVd() << " ft/s");
260     break;
261     case setuvw:
262         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
263                << Translation->GetUVW(1) << ", "
264                << Translation->GetUVW(2) << ", "
265                << Translation->GetUVW(3) << " ft/s");
266     break;
267     case setmach:
268         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
269                << Translation->GetMach() );
270     break;
271     case setvc:
272     default:
273         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
274                << Auxiliary->GetVcalibratedKTS() << " knots" );
275     break;
276     }
277     
278     stall_warning->setDoubleValue(0);
279     
280     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
281             <<  Rotation->Getphi()*RADTODEG << " deg" );
282     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
283             << Rotation->Gettht()*RADTODEG << " deg" );
284     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
285             << Rotation->Getpsi()*RADTODEG << " deg" );
286     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
287             << Position->GetLatitude() << " deg" );
288     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
289             << Position->GetLongitude() << " deg" );
290     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
291         << Position->Geth() << " feet" );
292     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
293
294     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
295
296     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
297     
298     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " << 
299                                   globals->get_controls()->get_gear_down() );
300     
301
302    
303 }
304
305 /******************************************************************************/
306
307 // Run an iteration of the EOM (equations of motion)
308
309 void
310 FGJSBsim::update( double dt ) {
311
312     if (is_suspended())
313       return;
314
315     int multiloop = _calc_multiloop(dt);
316
317     int i;
318
319     // double save_alt = 0.0;
320
321     copy_to_JSBsim();
322
323     trimmed->setBoolValue(false);
324     
325     if ( needTrim ) {
326       if ( startup_trim->getBoolValue() ) {
327         SG_LOG(SG_FLIGHT, SG_INFO,
328           "Ready to trim, terrain altitude is: " 
329             << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
330         fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
331         do_trim();
332       } else {
333         fdmex->RunIC();  //apply any changes made through the set_ functions
334       }
335       needTrim = false;  
336     }    
337     
338     for ( i=0; i < multiloop; i++ ) {
339         fdmex->Run();
340     }
341
342     FGJSBBase::Message* msg;
343     while (fdmex->ReadMessage()) {
344       msg = fdmex->ProcessMessage();
345       switch (msg->type) {
346       case FGJSBBase::Message::eText:
347         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
348         break;
349       case FGJSBBase::Message::eBool:
350         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
351         break;
352       case FGJSBBase::Message::eInteger:
353         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
354         break;
355       case FGJSBBase::Message::eDouble:
356         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
357         break;
358       default:
359         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
360         break;
361       }
362     }
363
364     // translate JSBsim back to FG structure so that the
365     // autopilot (and the rest of the sim can use the updated values
366     copy_from_JSBsim();
367 }
368
369 /******************************************************************************/
370
371 // Convert from the FGInterface struct to the JSBsim generic_ struct
372
373 bool FGJSBsim::copy_to_JSBsim() {
374     double tmp;
375     unsigned int i;
376
377     // copy control positions into the JSBsim structure
378
379     FCS->SetDaCmd( globals->get_controls()->get_aileron());
380     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
381     FCS->SetDeCmd( globals->get_controls()->get_elevator());
382     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
383     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
384     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
385     FCS->SetDfCmd(  globals->get_controls()->get_flaps() );
386     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() ); 
387     FCS->SetDspCmd( globals->get_controls()->get_spoilers() ); 
388
389                                 // Parking brake sets minimum braking
390                                 // level for mains.
391     double parking_brake = globals->get_controls()->get_parking_brake();
392     FCS->SetLBrake(FMAX(globals->get_controls()->get_brake(0), parking_brake));
393     FCS->SetRBrake(FMAX(globals->get_controls()->get_brake(1), parking_brake));
394     FCS->SetCBrake( globals->get_controls()->get_brake(2) );
395
396     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
397     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
398       FGEngine * eng = Propulsion->GetEngine(i);
399       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
400       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
401       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
402       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
403       Propulsion->GetThruster(i)->SetRPM(node->getDoubleValue("rpm"));
404       eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
405       eng->SetStarter( globals->get_controls()->get_starter(i) );
406       eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
407       eng->SetReverse( globals->get_controls()->get_reverser(i) );
408       eng->SetInjection( globals->get_controls()->get_water_injection(i) );
409       eng->SetIgnition( globals->get_controls()->get_ignition(i) );
410       eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
411       eng->SetNitrous( globals->get_controls()->get_nitrous_injection(i) );
412     }
413
414     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
415     Position->SetSeaLevelRadius( get_Sea_level_radius() );
416     Position->SetRunwayRadius( get_Runway_altitude() 
417                                + get_Sea_level_radius() );
418
419     Atmosphere->SetExTemperature(
420                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
421     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
422     Atmosphere->SetExDensity(density->getDoubleValue());
423
424     tmp = turbulence_gain->getDoubleValue();
425     Atmosphere->SetTurbGain(tmp * tmp * 100.0);
426
427     tmp = turbulence_rate->getDoubleValue();
428     Atmosphere->SetTurbRate(tmp);
429
430     Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
431                             wind_from_east->getDoubleValue(),
432                             wind_from_down->getDoubleValue() );
433 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
434 //                  << get_V_north_airmass() << ", "
435 //                  << get_V_east_airmass()  << ", "
436 //                  << get_V_down_airmass() );
437
438     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
439       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
440       FGTank * tank = Propulsion->GetTank(i);
441       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
442 //       tank->SetContents(node->getDoubleValue("level-lb"));
443     }
444
445     return true;
446 }
447
448 /******************************************************************************/
449
450 // Convert from the JSBsim generic_ struct to the FGInterface struct
451
452 bool FGJSBsim::copy_from_JSBsim() {
453     unsigned int i, j;
454
455     _set_Inertias( MassBalance->GetMass(),
456                    MassBalance->GetIxx(),
457                    MassBalance->GetIyy(),
458                    MassBalance->GetIzz(),
459                    MassBalance->GetIxz() );
460
461     _set_CG_Position( MassBalance->GetXYZcg(1),
462                       MassBalance->GetXYZcg(2),
463                       MassBalance->GetXYZcg(3) );
464
465     _set_Accels_Body( Aircraft->GetBodyAccel()(1),
466                       Aircraft->GetBodyAccel()(2),
467                       Aircraft->GetBodyAccel()(3) );
468
469     //_set_Accels_CG_Body( Aircraft->GetBodyAccel()(1),
470     //                     Aircraft->GetBodyAccel()(2),
471     //                     Aircraft->GetBodyAccel()(3) );
472     //
473     _set_Accels_CG_Body_N ( Aircraft->GetNcg()(1),
474                             Aircraft->GetNcg()(2),
475                             Aircraft->GetNcg()(3) );
476     
477     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel()(1),
478                             Auxiliary->GetPilotAccel()(2),
479                             Auxiliary->GetPilotAccel()(3) );
480
481    // _set_Accels_Pilot_Body_N( Auxiliary->GetPilotAccel()(1)/32.1739,
482    //                           Auxiliary->GetNpilot(2)/32.1739,
483    //                           Auxiliary->GetNpilot(3)/32.1739 );
484
485     _set_Nlf( Aircraft->GetNlf() );
486
487     // Velocities
488
489     _set_Velocities_Local( Position->GetVn(),
490                            Position->GetVe(),
491                            Position->GetVd() );
492
493     _set_Velocities_Wind_Body( Translation->GetUVW(1),
494                                Translation->GetUVW(2),
495                                Translation->GetUVW(3) );
496
497     _set_V_rel_wind( Translation->GetVt() );
498
499     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
500
501     // _set_V_calibrated( Auxiliary->GetVcalibratedFPS() );
502
503     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
504
505     _set_V_ground_speed( Position->GetVground() );
506
507     _set_Omega_Body( Rotation->GetPQR(1),
508                      Rotation->GetPQR(2),
509                      Rotation->GetPQR(3) );
510
511     _set_Euler_Rates( Rotation->GetEulerRates(1),
512                       Rotation->GetEulerRates(2),
513                       Rotation->GetEulerRates(3) );
514
515     _set_Geocentric_Rates(Position->GetLatitudeDot(),
516                           Position->GetLongitudeDot(),
517                           Position->Gethdot() );
518
519     _set_Mach_number( Translation->GetMach() );
520
521     // Positions
522     _updateGeocentricPosition( Position->GetLatitude(),
523                                Position->GetLongitude(),
524                                Position->Geth() );
525
526     _set_Altitude_AGL( Position->GetDistanceAGL() );
527
528     _set_Euler_Angles( Rotation->Getphi(),
529                        Rotation->Gettht(),
530                        Rotation->Getpsi() );
531
532     _set_Alpha( Translation->Getalpha() );
533     _set_Beta( Translation->Getbeta() );
534
535
536     _set_Gamma_vert_rad( Position->GetGamma() );
537     // set_Gamma_horiz_rad( Gamma_horiz_rad );
538
539     _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
540
541     _set_Climb_Rate( Position->Gethdot() );
542
543
544     for ( i = 1; i <= 3; i++ ) {
545         for ( j = 1; j <= 3; j++ ) {
546             _set_T_Local_to_Body( i, j, State->GetTl2b(i,j) );
547         }
548     }
549
550                                 // Copy the engine values from JSBSim.
551     for( i=0; i < Propulsion->GetNumEngines(); i++ ) {
552       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
553       FGEngine * eng = Propulsion->GetEngine(i);
554       FGThruster * thrust = Propulsion->GetThruster(i);
555
556       node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
557       node->setDoubleValue("rpm", thrust->GetRPM());
558       node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
559       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
560       node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
561       node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
562       node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
563       node->setDoubleValue("thrust_lb", eng->GetThrust());
564       node->setDoubleValue("N1", eng->GetN1());
565       node->setDoubleValue("N2", eng->GetN2());
566       node->setDoubleValue("EGT_degC", eng->GetEGT());
567       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
568       node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
569       node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
570       node->setBoolValue("running", eng->GetRunning());
571       node->setBoolValue("cranking", eng->GetCranking());
572       node->setBoolValue("ignition", eng->GetIgnition());
573       node->setBoolValue("augmentation", eng->GetAugmentation());
574       node->setBoolValue("water-injection", eng->GetInjection());
575       node->setBoolValue("reversed", eng->GetReversed());
576       node->setBoolValue("cutoff", eng->GetCutoff());
577       node->setBoolValue("nitrous", eng->GetNitrous());
578     }
579
580     static const SGPropertyNode *fuel_freeze
581         = fgGetNode("/sim/freeze/fuel");
582
583                                 // Copy the fuel levels from JSBSim if fuel
584                                 // freeze not enabled.
585     if ( ! fuel_freeze->getBoolValue() ) {
586         for (i = 0; i < Propulsion->GetNumTanks(); i++) {
587             SGPropertyNode * node
588                 = fgGetNode("/consumables/fuel/tank", i, true);
589             double contents = Propulsion->GetTank(i)->GetContents();
590             node->setDoubleValue("level-gal_us", contents/6.6);
591             node->setDoubleValue("level-lb", contents);
592             // node->setDoubleValue("temperature_degC", 
593         }
594     }
595
596     update_gear();
597     
598     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
599     
600     /* elevator_pos_deg->setDoubleValue( FCS->GetDePos()*SG_RADIANS_TO_DEGREES );
601     left_aileron_pos_deg->setDoubleValue( FCS->GetDaLPos()*SG_RADIANS_TO_DEGREES );
602     right_aileron_pos_deg->setDoubleValue( FCS->GetDaRPos()*SG_RADIANS_TO_DEGREES );
603     rudder_pos_deg->setDoubleValue( -1*FCS->GetDrPos()*SG_RADIANS_TO_DEGREES );
604     flap_pos_deg->setDoubleValue( FCS->GetDfPos() ); */
605
606     
607     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
608     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
609     right_aileron_pos_pct->setDoubleValue( -1*FCS->GetDaLPos(ofNorm) );
610     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
611     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
612     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
613     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
614
615     
616     return true;
617 }
618
619 bool FGJSBsim::ToggleDataLogging(void) {
620     return fdmex->GetOutput()->Toggle();
621 }
622
623
624 bool FGJSBsim::ToggleDataLogging(bool state) {
625     if (state) {
626       fdmex->GetOutput()->Enable();
627       return true;
628     } else {
629       fdmex->GetOutput()->Disable();
630       return false;
631     }
632 }
633
634
635 //Positions
636 void FGJSBsim::set_Latitude(double lat) {
637     static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
638     double alt;
639     double sea_level_radius_meters, lat_geoc;
640
641                                 // In case we're not trimming
642     FGInterface::set_Latitude(lat);
643     
644     if ( altitude->getDoubleValue() > -9990 ) {
645       alt = altitude->getDoubleValue();
646     } else {
647       alt = 0.0;
648     }
649    
650     update_ic();
651     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
652     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
653
654     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER, 
655                       &sea_level_radius_meters, &lat_geoc );
656     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
657     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );    
658     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
659     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
660     fgic->SetLatitudeRadIC( lat_geoc );
661     needTrim=true;
662 }
663
664 void FGJSBsim::set_Longitude(double lon) {
665
666     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
667
668                                 // In case we're not trimming
669     FGInterface::set_Longitude(lon);
670
671     update_ic();
672     fgic->SetLongitudeRadIC( lon );
673     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
674     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
675     needTrim=true;
676 }
677
678 void FGJSBsim::set_Altitude(double alt) {
679     static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
680
681     double sea_level_radius_meters,lat_geoc;
682
683     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
684     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
685     
686                                 // In case we're not trimming
687     FGInterface::set_Altitude(alt);
688
689     update_ic();
690     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
691                   &sea_level_radius_meters, &lat_geoc);
692     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
693     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
694     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
695     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
696     SG_LOG(SG_FLIGHT, SG_INFO,
697           "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
698     fgic->SetLatitudeRadIC( lat_geoc );
699     fgic->SetAltitudeFtIC(alt);
700     needTrim=true;
701 }
702
703 void FGJSBsim::set_V_calibrated_kts(double vc) {
704     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
705
706                                 // In case we're not trimming
707     FGInterface::set_V_calibrated_kts(vc);
708
709     update_ic();
710     fgic->SetVcalibratedKtsIC(vc);
711     needTrim=true;
712 }
713
714 void FGJSBsim::set_Mach_number(double mach) {
715     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
716     
717                                 // In case we're not trimming
718     FGInterface::set_Mach_number(mach);
719
720     update_ic();
721     fgic->SetMachIC(mach);
722     needTrim=true;
723 }
724
725 void FGJSBsim::set_Velocities_Local( double north, double east, double down ){
726     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
727        << north << ", " <<  east << ", " << down );
728     
729                                 // In case we're not trimming
730     FGInterface::set_Velocities_Local(north, east, down);
731
732     update_ic();
733     fgic->SetVnorthFpsIC(north);
734     fgic->SetVeastFpsIC(east);
735     fgic->SetVdownFpsIC(down);
736     needTrim=true;
737 }
738
739 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w){
740     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
741        << u << ", " <<  v << ", " <<  w );
742     
743                                 // In case we're not trimming
744     FGInterface::set_Velocities_Wind_Body(u, v, w);
745
746     update_ic();
747     fgic->SetUBodyFpsIC(u);
748     fgic->SetVBodyFpsIC(v);
749     fgic->SetWBodyFpsIC(w);
750     needTrim=true;
751 }
752
753 //Euler angles
754 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi ) {
755     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
756        << phi << ", " << theta << ", " << psi );
757     
758                                 // In case we're not trimming
759     FGInterface::set_Euler_Angles(phi, theta, psi);
760
761     update_ic();
762     fgic->SetPitchAngleRadIC(theta);
763     fgic->SetRollAngleRadIC(phi);
764     fgic->SetTrueHeadingRadIC(psi);
765     needTrim=true;
766 }
767
768 //Flight Path
769 void FGJSBsim::set_Climb_Rate( double roc) {
770     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
771     
772                                 // In case we're not trimming
773     FGInterface::set_Climb_Rate(roc);
774
775     update_ic();
776     //since both climb rate and flight path angle are set in the FG
777     //startup sequence, something is needed to keep one from cancelling
778     //out the other.
779     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
780       fgic->SetClimbRateFpsIC(roc);
781     }  
782     needTrim=true;
783 }
784
785 void FGJSBsim::set_Gamma_vert_rad( double gamma) {
786     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
787     
788     update_ic();
789     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
790       fgic->SetFlightPathAngleRadIC(gamma);
791     }  
792     needTrim=true;
793 }
794
795 void FGJSBsim::init_gear(void ) {
796     
797     FGGroundReactions* gr=fdmex->GetGroundReactions();
798     int Ngear=GroundReactions->GetNumGearUnits();
799     for (int i=0;i<Ngear;i++) {
800       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
801       node->setDoubleValue("xoffset-in",
802                            gr->GetGearUnit(i)->GetBodyLocation()(1));
803       node->setDoubleValue("yoffset-in",
804                            gr->GetGearUnit(i)->GetBodyLocation()(2));
805       node->setDoubleValue("zoffset-in",
806                            gr->GetGearUnit(i)->GetBodyLocation()(3));
807       node->setBoolValue("wow", gr->GetGearUnit(i)->GetWOW());
808       node->setBoolValue("has-brake", gr->GetGearUnit(i)->GetBrakeGroup() > 0);
809       node->setDoubleValue("position-norm", FCS->GetGearPos());
810     }  
811 }
812
813 void FGJSBsim::update_gear(void) {
814     
815     FGGroundReactions* gr=fdmex->GetGroundReactions();
816     int Ngear=GroundReactions->GetNumGearUnits();
817     for (int i=0;i<Ngear;i++) {
818       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
819       node->getChild("wow", 0, true)
820         ->setBoolValue(gr->GetGearUnit(i)->GetWOW());
821       node->getChild("position-norm", 0, true)
822         ->setDoubleValue(FCS->GetGearPos());
823     }  
824 }
825
826 void FGJSBsim::do_trim(void) {
827
828         FGTrim *fgtrim;
829         if( fgGetBool("/sim/presets/onground") ) {
830             fgic->SetVcalibratedKtsIC(0.0);
831             fgtrim=new FGTrim(fdmex,tGround);
832         } else {
833             fgtrim=new FGTrim(fdmex,tLongitudinal);
834         }
835         if( !fgtrim->DoTrim() ) {
836             fgtrim->Report();
837             fgtrim->TrimStats();
838         } else {
839             trimmed->setBoolValue(true);
840         }
841         State->ReportState();
842         delete fgtrim;
843         pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
844         throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
845         aileron_trim->setDoubleValue( FCS->GetDaCmd() );
846         rudder_trim->setDoubleValue( FCS->GetDrCmd() );
847
848         globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
849         globals->get_controls()->set_elevator(FCS->GetDeCmd());
850         globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
851                                               FCS->GetThrottleCmd(0));
852
853         globals->get_controls()->set_aileron(FCS->GetDaCmd());
854         globals->get_controls()->set_rudder( FCS->GetDrCmd());
855     
856         SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
857 }          
858
859 void FGJSBsim::update_ic(void) {       
860    if( !needTrim ) {
861      fgic->SetLatitudeRadIC(get_Lat_geocentric() );       
862      fgic->SetLongitudeRadIC( get_Longitude() );       
863      fgic->SetAltitudeFtIC( get_Altitude() );       
864      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );       
865      fgic->SetPitchAngleRadIC( get_Theta() );       
866      fgic->SetRollAngleRadIC( get_Phi() );       
867      fgic->SetTrueHeadingRadIC( get_Psi() );       
868      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
869    }  
870 }
871