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