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