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