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