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