]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
Synchronized FG with the removal of 'using std::*' in simgear's easyxml
[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 Lesser 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 // Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id: JSBSim.cxx,v 1.64 2010/10/31 04:49:25 jberndt Exp $
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/sg_inlines.h>
30
31 #include <stdio.h>    //    size_t
32 #include <string>
33
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/structure/commands.hxx>
39
40 #include <FDM/flight.hxx>
41
42 #include <Aircraft/controls.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45
46 #include "JSBSim.hxx"
47 #include <FDM/JSBSim/FGFDMExec.h>
48 #include <FDM/JSBSim/FGJSBBase.h>
49 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
50 #include <FDM/JSBSim/initialization/FGTrim.h>
51 #include <FDM/JSBSim/models/FGModel.h>
52 #include <FDM/JSBSim/models/FGAircraft.h>
53 #include <FDM/JSBSim/models/FGFCS.h>
54 #include <FDM/JSBSim/models/FGPropagate.h>
55 #include <FDM/JSBSim/models/FGAuxiliary.h>
56 #include <FDM/JSBSim/models/FGInertial.h>
57 #include <FDM/JSBSim/models/FGAtmosphere.h>
58 #include <FDM/JSBSim/models/FGMassBalance.h>
59 #include <FDM/JSBSim/models/FGAerodynamics.h>
60 #include <FDM/JSBSim/models/FGLGear.h>
61 #include <FDM/JSBSim/models/FGGroundReactions.h>
62 #include <FDM/JSBSim/models/FGPropulsion.h>
63 #include <FDM/JSBSim/models/FGAccelerations.h>
64 #include <FDM/JSBSim/models/atmosphere/FGWinds.h>
65 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
66 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
67 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
68 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
69 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
70 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
71 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
72 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
73 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
74 #include <FDM/JSBSim/models/propulsion/FGTank.h>
75 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
76 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
77
78 using namespace JSBSim;
79
80 static inline double
81 FMAX (double a, double b)
82 {
83   return a > b ? a : b;
84 }
85
86 class FGFSGroundCallback : public FGGroundCallback {
87 public:
88   FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
89   virtual ~FGFSGroundCallback() {}
90
91   /** Get the altitude above sea level dependent on the location. */
92   virtual double GetAltitude(const FGLocation& l) const {
93     double pt[3] = { SG_FEET_TO_METER*l(FGJSBBase::eX),
94                      SG_FEET_TO_METER*l(FGJSBBase::eY),
95                      SG_FEET_TO_METER*l(FGJSBBase::eZ) };
96     double lat, lon, alt;
97     sgCartToGeod( pt, &lat, &lon, &alt);
98     return alt * SG_METER_TO_FEET;
99   }
100
101   /** Compute the altitude above ground. */
102   virtual double GetAGLevel(double t, const FGLocation& l,
103                             FGLocation& cont, FGColumnVector3& n,
104                             FGColumnVector3& v, FGColumnVector3& w) const {
105     double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
106     double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
107     mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
108                            vel, angularVel, &agl);
109     n = FGColumnVector3( normal[0], normal[1], normal[2] );
110     v = FGColumnVector3( vel[0], vel[1], vel[2] );
111     w = FGColumnVector3( angularVel[0], angularVel[1], angularVel[2] );
112     cont = FGColumnVector3( contact[0], contact[1], contact[2] );
113     return agl;
114   }
115
116   virtual double GetTerrainGeoCentRadius(double t, const FGLocation& l) const {
117     double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
118     double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
119     mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
120                            vel, angularVel, &agl);
121     return sqrt(contact[0]*contact[0]+contact[1]*contact[1]+contact[2]*contact[2]);
122   }
123
124   virtual double GetSeaLevelRadius(const FGLocation& l) const {
125     double seaLevelRadius, latGeoc;
126
127     sgGeodToGeoc(l.GetGeodLatitudeRad(), l.GetGeodAltitude(),
128                  &seaLevelRadius, &latGeoc);
129
130     return seaLevelRadius * SG_METER_TO_FEET;
131   }
132
133   virtual void SetTerrainGeoCentRadius(double radius) {}
134   virtual void SetSeaLevelRadius(double radius) {}
135 private:
136   FGJSBsim* mInterface;
137 };
138
139 // FG uses a squared normalized magnitude for turbulence
140 // this lookup table maps fg's severity levels 
141 // none(0), light(1/3), moderate(2/3) and severe(3/3)
142 // to the POE table indexes 0, 3, 4 and 7
143 class FGTurbulenceSeverityTable : public FGTable {
144 public:
145   FGTurbulenceSeverityTable() : FGTable(4) {
146     *this << (0.0/9.0) << 0.0;
147     *this << (1.0/9.0) << 3.0;
148     *this << (4.0/9.0) << 4.0;
149     *this << (9.0/9.0) << 7.0;
150   }
151 };
152
153 /******************************************************************************/
154 std::map<std::string,int> FGJSBsim::TURBULENCE_TYPE_NAMES;
155
156 static FGTurbulenceSeverityTable TurbulenceSeverityTable;
157
158 FGJSBsim::FGJSBsim( double dt )
159   : FGInterface(dt), got_wire(false)
160 {
161     bool result;
162     if( TURBULENCE_TYPE_NAMES.empty() ) {
163         TURBULENCE_TYPE_NAMES["ttNone"]     = FGWinds::ttNone;
164         TURBULENCE_TYPE_NAMES["ttStandard"] = FGWinds::ttStandard;
165         TURBULENCE_TYPE_NAMES["ttCulp"]     = FGWinds::ttCulp;
166         TURBULENCE_TYPE_NAMES["ttMilspec"]  = FGWinds::ttMilspec;
167         TURBULENCE_TYPE_NAMES["ttTustin"]   = FGWinds::ttTustin;
168     }
169
170     // Set up the debugging level
171     // FIXME: this will not respond to
172     // runtime changes
173
174                                 // if flight is excluded, don't bother
175     if ((sglog().get_log_classes() & SG_FLIGHT) != 0) {
176
177                                 // do a rough-and-ready mapping to
178                                 // the levels documented in FGFDMExec.h
179         switch (sglog().get_log_priority()) {
180         case SG_BULK:
181             FGJSBBase::debug_lvl = 0x1f;
182             break;
183         case SG_DEBUG:
184             FGJSBBase::debug_lvl = 0x0f;
185         case SG_INFO:
186             FGJSBBase::debug_lvl = 0x01;
187             break;
188         case SG_WARN:
189         case SG_ALERT:
190             FGJSBBase::debug_lvl = 0x00;
191             break;
192         }
193     }
194
195     PropertyManager = new FGPropertyManager( (FGPropertyNode*)globals->get_props() );
196     fdmex = new FGFDMExec( PropertyManager );
197
198     // Register ground callback.
199     fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
200
201     Atmosphere      = fdmex->GetAtmosphere();
202     Winds           = fdmex->GetWinds();
203     FCS             = fdmex->GetFCS();
204     MassBalance     = fdmex->GetMassBalance();
205     Propulsion      = fdmex->GetPropulsion();
206     Aircraft        = fdmex->GetAircraft();
207     Propagate       = fdmex->GetPropagate();
208     Auxiliary       = fdmex->GetAuxiliary();
209     Inertial        = fdmex->GetInertial();
210     Aerodynamics    = fdmex->GetAerodynamics();
211     GroundReactions = fdmex->GetGroundReactions();
212     Accelerations   = fdmex->GetAccelerations();
213
214     fgic=fdmex->GetIC();
215     needTrim=true;
216
217     SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
218
219     SGPath engine_path( fgGetString("/sim/aircraft-dir") );
220     engine_path.append( "Engine" );
221
222     SGPath systems_path( fgGetString("/sim/aircraft-dir") );
223     systems_path.append( "Systems" );
224
225 // deprecate sim-time-sec for simulation/sim-time-sec
226 // remove alias with increased configuration file version number (2.1 or later)
227     SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec");
228     fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node );
229 // end of sim-time-sec deprecation patch
230
231     fdmex->Setdt( dt );
232
233     result = fdmex->LoadModel( aircraft_path.str(),
234                                engine_path.str(),
235                                systems_path.str(),
236                                fgGetString("/sim/aero"), false );
237
238     if (result) {
239       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
240     } else {
241       SG_LOG( SG_FLIGHT, SG_INFO,
242               "  aero does not exist (you may have mis-typed the name).");
243       throw(-1);
244     }
245
246     SG_LOG( SG_FLIGHT, SG_INFO, "" );
247     SG_LOG( SG_FLIGHT, SG_INFO, "" );
248     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
249
250     int Neng = Propulsion->GetNumEngines();
251     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
252
253     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
254         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
255                 << GroundReactions->GetNumGearUnits() );
256         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
257         SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
258         SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
259         exit(-1);
260     }
261
262     init_gear();
263
264     // Set initial fuel levels if provided.
265     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
266       double d;
267       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
268       FGTank* tank = Propulsion->GetTank(i);
269
270       d = node->getNode( "density-ppg", true )->getDoubleValue();
271       if( d > 0.0 ) {
272         tank->SetDensity( d );
273       } else {
274         node->getNode( "density-ppg", true )->setDoubleValue( SG_MAX2<double>(tank->GetDensity(), 0.1) );
275       }
276
277       d = node->getNode( "level-lbs", true )->getDoubleValue();
278       if( d > 0.0 ) {
279         tank->SetContents( d );
280       } else {
281         node->getNode( "level-lbs", true )->setDoubleValue( tank->GetContents() );
282       }
283       /* Capacity is read-only in FGTank and can't be overwritten from FlightGear */
284       node->getNode("capacity-gal_us", true )->setDoubleValue( tank->GetCapacityGallons() );
285     }
286     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
287
288     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
289     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
290     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
291     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
292
293     startup_trim = fgGetNode("/sim/presets/trim", true);
294
295     trimmed = fgGetNode("/fdm/trim/trimmed", true);
296     trimmed->setBoolValue(false);
297
298     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
299     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
300     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
301     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
302
303     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
304     stall_warning->setDoubleValue(0);
305
306
307     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
308     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
309     left_aileron_pos_pct
310         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
311     right_aileron_pos_pct
312         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
313     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
314     speedbrake_pos_pct
315         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
316     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
317     tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
318     wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
319
320     elevator_pos_pct->setDoubleValue(0);
321     left_aileron_pos_pct->setDoubleValue(0);
322     right_aileron_pos_pct->setDoubleValue(0);
323     rudder_pos_pct->setDoubleValue(0);
324     flap_pos_pct->setDoubleValue(0);
325     speedbrake_pos_pct->setDoubleValue(0);
326     spoilers_pos_pct->setDoubleValue(0);
327
328     ab_brake_engaged = fgGetNode("/autopilot/autobrake/engaged", true);
329     ab_brake_left_pct = fgGetNode("/autopilot/autobrake/brake-left-output", true);
330     ab_brake_right_pct = fgGetNode("/autopilot/autobrake/brake-right-output", true);
331     
332     altitude = fgGetNode("/position/altitude-ft");
333     temperature = fgGetNode("/environment/temperature-degc",true);
334     pressure = fgGetNode("/environment/pressure-inhg",true);
335     pressureSL = fgGetNode("/environment/pressure-sea-level-inhg",true);
336     ground_wind = fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt",true);
337     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
338     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
339     turbulence_model = fgGetNode("/environment/params/jsbsim-turbulence-model",true);
340
341     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
342     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
343     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
344
345     slaved = fgGetNode("/sim/slaved/enabled", true);
346
347     for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
348       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
349       Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
350                      Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
351     }
352
353     hook_root_struct = FGColumnVector3(
354         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
355         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
356         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
357     last_hook_tip[0] = 0; last_hook_tip[1] = 0; last_hook_tip[2] = 0;
358     last_hook_root[0] = 0; last_hook_root[1] = 0; last_hook_root[2] = 0;
359
360     crashed = false;
361 }
362
363 /******************************************************************************/
364 FGJSBsim::~FGJSBsim(void)
365 {
366   delete fdmex;
367   delete PropertyManager;
368 }
369
370 /******************************************************************************/
371
372 // Initialize the JSBsim flight model, dt is the time increment for
373 // each subsequent iteration through the EOM
374
375 void FGJSBsim::init()
376 {
377     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
378
379     // Explicitly call the superclass's
380     // init method first.
381
382     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
383       Atmosphere->SetTemperature(temperature->getDoubleValue(), get_Altitude(), FGAtmosphere::eCelsius);
384       Atmosphere->SetPressureSL(FGAtmosphere::eInchesHg, pressureSL->getDoubleValue());
385       // initialize to no turbulence, these values get set in the update loop
386       Winds->SetTurbType(FGWinds::ttNone);
387       Winds->SetTurbGain(0.0);
388       Winds->SetTurbRate(0.0);
389       Winds->SetWindspeed20ft(0.0);
390       Winds->SetProbabilityOfExceedence(0.0);
391     }
392
393     fgic->SetWindNEDFpsIC( -wind_from_north->getDoubleValue(),
394                            -wind_from_east->getDoubleValue(),
395                            -wind_from_down->getDoubleValue() );
396
397     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << Atmosphere->GetTemperature()
398      << ", " << Atmosphere->GetPressure()
399      << ", " << Atmosphere->GetDensity() );
400
401     FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
402
403     needTrim = startup_trim->getBoolValue();
404     common_init();
405
406     copy_to_JSBsim();
407     fdmex->RunIC();     //loop JSBSim once w/o integrating
408     if (fgGetBool("/sim/presets/running")) {
409       Propulsion->InitRunning(-1);
410       for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
411         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
412         globals->get_controls()->set_magnetos(i, eng->GetMagnetos());
413         globals->get_controls()->set_mixture(i, FCS->GetMixtureCmd(i));
414       }
415     }
416
417     if ( needTrim ) {
418       FGLocation cart(fgic->GetLongitudeRadIC(), fgic->GetLatitudeRadIC(),
419                       get_Sea_level_radius() + fgic->GetAltitudeASLFtIC());
420       double cart_pos[3], contact[3], d[3], vel[3], agl;
421       update_ground_cache(cart, cart_pos, 0.01);
422
423       get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
424                  d, vel, d, &agl);
425       double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
426            + contact[2]*contact[2]) - get_Sea_level_radius();
427
428       SG_LOG(SG_FLIGHT, SG_INFO, "Ready to trim, terrain elevation is: "
429                                  << terrain_alt * SG_METER_TO_FEET );
430
431       if (fgGetBool("/sim/presets/onground")) {
432         FGColumnVector3 gndVelNED = cart.GetTec2l()
433                                   * FGColumnVector3(vel[0], vel[1], vel[2]);
434         fgic->SetVNorthFpsIC(gndVelNED(1));
435         fgic->SetVEastFpsIC(gndVelNED(2));
436         fgic->SetVDownFpsIC(gndVelNED(3));
437       }
438       fgic->SetTerrainElevationFtIC( terrain_alt );
439       do_trim();
440       needTrim = false;
441     }
442
443     copy_from_JSBsim(); //update the bus
444
445     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
446
447     switch(fgic->GetSpeedSet()) {
448     case setned:
449         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
450                << Propagate->GetVel(FGJSBBase::eNorth) << ", "
451                << Propagate->GetVel(FGJSBBase::eEast) << ", "
452                << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
453     break;
454     case setuvw:
455         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
456                << Propagate->GetUVW(1) << ", "
457                << Propagate->GetUVW(2) << ", "
458                << Propagate->GetUVW(3) << " ft/s");
459     break;
460     case setmach:
461         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
462                << Auxiliary->GetMach() );
463     break;
464     case setvc:
465     default:
466         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
467                << Auxiliary->GetVcalibratedKTS() << " knots" );
468     break;
469     }
470
471     stall_warning->setDoubleValue(0);
472
473     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
474             << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
475     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
476             << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
477     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
478             << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
479     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
480             << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
481     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
482             << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
483     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
484             << Propagate->GetAltitudeASL() << " feet" );
485     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
486
487     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
488
489     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
490
491     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
492                                   globals->get_controls()->get_gear_down() );
493 }
494
495 /******************************************************************************/
496
497 void FGJSBsim::unbind()
498 {
499   fdmex->Unbind();
500   FGInterface::unbind();
501 }
502
503 /******************************************************************************/
504
505 // Run an iteration of the EOM (equations of motion)
506
507 void FGJSBsim::update( double dt )
508 {
509     if(crashed) {
510       if(!fgGetBool("/sim/crashed"))
511         fgSetBool("/sim/crashed", true);
512       return;
513     }
514
515     if (is_suspended())
516       return;
517
518     int multiloop = _calc_multiloop(dt);
519     FGLocation cart = Auxiliary->GetLocationVRP();
520     double cart_pos[3];
521
522     update_ground_cache(cart, cart_pos, dt);
523
524     copy_to_JSBsim();
525
526     trimmed->setBoolValue(false);
527
528     for ( int i=0; i < multiloop; i++ ) {
529       fdmex->Run();
530       update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());
531     }
532
533     FGJSBBase::Message* msg;
534     while ((msg = fdmex->ProcessNextMessage()) != NULL) {
535 //      msg = fdmex->ProcessNextMessage();
536       switch (msg->type) {
537       case FGJSBBase::Message::eText:
538         if (msg->text == "Crash Detected: Simulation FREEZE.")
539           crashed = true;
540         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
541         break;
542       case FGJSBBase::Message::eBool:
543         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
544         break;
545       case FGJSBBase::Message::eInteger:
546         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
547         break;
548       case FGJSBBase::Message::eDouble:
549         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
550         break;
551       default:
552         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
553         break;
554       }
555     }
556
557     // translate JSBsim back to FG structure so that the
558     // autopilot (and the rest of the sim can use the updated values
559     copy_from_JSBsim();
560 }
561
562 /******************************************************************************/
563
564 void FGJSBsim::suspend()
565 {
566   fdmex->Hold();
567   SGSubsystem::suspend();
568 }
569
570 /******************************************************************************/
571
572 void FGJSBsim::resume()
573 {
574   fdmex->Resume();
575   SGSubsystem::resume();
576 }
577
578 /******************************************************************************/
579
580 // Convert from the FGInterface struct to the JSBsim generic_ struct
581
582 bool FGJSBsim::copy_to_JSBsim()
583 {
584     unsigned int i;
585
586     // copy control positions into the JSBsim structure
587
588     FCS->SetDaCmd( globals->get_controls()->get_aileron());
589     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
590     FCS->SetDeCmd( globals->get_controls()->get_elevator());
591     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
592     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
593     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
594     FCS->SetDsCmd( globals->get_controls()->get_rudder() );
595     FCS->SetDfCmd( globals->get_controls()->get_flaps() );
596     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
597     FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
598
599         // Parking brake sets minimum braking
600         // level for mains.
601     double parking_brake = globals->get_controls()->get_brake_parking();
602     double left_brake = globals->get_controls()->get_brake_left();
603     double right_brake = globals->get_controls()->get_brake_right();
604     
605     if (ab_brake_engaged->getBoolValue()) {
606       left_brake = ab_brake_left_pct->getDoubleValue();
607       right_brake = ab_brake_right_pct->getDoubleValue(); 
608     }
609     
610     FCS->SetLBrake(FMAX(left_brake, parking_brake));
611     FCS->SetRBrake(FMAX(right_brake, parking_brake));
612     
613     
614     FCS->SetCBrake( 0.0 );
615     // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
616
617     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
618     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
619       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
620
621       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
622       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
623       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
624       FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
625
626       switch (Propulsion->GetEngine(i)->GetType()) {
627       case FGEngine::etPiston:
628         { // FGPiston code block
629         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
630         eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
631         break;
632         } // end FGPiston code block
633       case FGEngine::etTurbine:
634         { // FGTurbine code block
635         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
636         eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
637         eng->SetReverse( globals->get_controls()->get_reverser(i) );
638         //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
639         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
640         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
641         break;
642         } // end FGTurbine code block
643       case FGEngine::etRocket:
644         { // FGRocket code block
645 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
646         break;
647         } // end FGRocket code block
648       case FGEngine::etTurboprop:
649         { // FGTurboProp code block
650         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
651         eng->SetReverse( globals->get_controls()->get_reverser(i) );
652         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
653         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
654
655         eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
656         eng->SetCondition( globals->get_controls()->get_condition(i) );
657         break;
658         } // end FGTurboProp code block
659       default:
660         break;
661       }
662
663       { // FGEngine code block
664       FGEngine* eng = Propulsion->GetEngine(i);
665
666       eng->SetStarter( globals->get_controls()->get_starter(i) );
667       eng->SetRunning( node->getBoolValue("running") );
668       } // end FGEngine code block
669     }
670
671     Atmosphere->SetTemperature(temperature->getDoubleValue(), get_Altitude(), FGAtmosphere::eCelsius);
672     Atmosphere->SetPressureSL(FGAtmosphere::eInchesHg, pressureSL->getDoubleValue());
673
674     Winds->SetTurbType((FGWinds::tType)TURBULENCE_TYPE_NAMES[turbulence_model->getStringValue()]);
675     switch( Winds->GetTurbType() ) {
676         case FGWinds::ttStandard:
677         case FGWinds::ttCulp: {
678             double tmp = turbulence_gain->getDoubleValue();
679             Winds->SetTurbGain(tmp * tmp * 100.0);
680             Winds->SetTurbRate(turbulence_rate->getDoubleValue());
681             break;
682         }
683         case FGWinds::ttMilspec:
684         case FGWinds::ttTustin: {
685             // milspec turbulence: 3=light, 4=moderate, 6=severe turbulence
686             // turbulence_gain normalized: 0: none, 1/3: light, 2/3: moderate, 3/3: severe
687             double tmp = turbulence_gain->getDoubleValue();
688             Winds->SetProbabilityOfExceedence(
689               SGMiscd::roundToInt(TurbulenceSeverityTable.GetValue( tmp ) )
690             );
691             Winds->SetWindspeed20ft(ground_wind->getDoubleValue());
692             break;
693         }
694
695         default:
696             break;
697     }
698
699     Winds->SetWindNED( -wind_from_north->getDoubleValue(),
700                        -wind_from_east->getDoubleValue(),
701                        -wind_from_down->getDoubleValue() );
702 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
703 //                  << get_V_north_airmass() << ", "
704 //                  << get_V_east_airmass()  << ", "
705 //                  << get_V_down_airmass() );
706
707     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
708       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
709       FGTank * tank = Propulsion->GetTank(i);
710       double fuelDensity = node->getDoubleValue("density-ppg");
711
712       if (fuelDensity < 0.1)
713         fuelDensity = 6.0; // Use average fuel value
714
715       tank->SetDensity(fuelDensity);
716       tank->SetContents(node->getDoubleValue("level-lbs"));
717     }
718
719     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
720     fdmex->SetChild(slaved->getBoolValue());
721
722     return true;
723 }
724
725 /******************************************************************************/
726
727 // Convert from the JSBsim generic_ struct to the FGInterface struct
728
729 bool FGJSBsim::copy_from_JSBsim()
730 {
731     unsigned int i, j;
732 /*
733     _set_Inertias( MassBalance->GetMass(),
734                    MassBalance->GetIxx(),
735                    MassBalance->GetIyy(),
736                    MassBalance->GetIzz(),
737                    MassBalance->GetIxz() );
738 */
739     _set_CG_Position( MassBalance->GetXYZcg(1),
740                       MassBalance->GetXYZcg(2),
741                       MassBalance->GetXYZcg(3) );
742
743     _set_Accels_Body( Accelerations->GetBodyAccel(1),
744                       Accelerations->GetBodyAccel(2),
745                       Accelerations->GetBodyAccel(3) );
746
747     _set_Accels_CG_Body_N ( Auxiliary->GetNcg(1),
748                             Auxiliary->GetNcg(2),
749                             Auxiliary->GetNcg(3) );
750
751     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
752                             Auxiliary->GetPilotAccel(2),
753                             Auxiliary->GetPilotAccel(3) );
754
755     _set_Nlf( Auxiliary->GetNlf() );
756
757     // Velocities
758
759     _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
760                            Propagate->GetVel(FGJSBBase::eEast),
761                            Propagate->GetVel(FGJSBBase::eDown) );
762
763     _set_Velocities_Body( Propagate->GetUVW(1),
764                           Propagate->GetUVW(2),
765                           Propagate->GetUVW(3) );
766
767     // Make the HUD work ...
768     _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
769                             Propagate->GetVel(FGJSBBase::eEast),
770                             -Propagate->GetVel(FGJSBBase::eDown) );
771
772     _set_V_rel_wind( Auxiliary->GetVt() );
773
774     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
775
776     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
777
778     _set_V_ground_speed( Auxiliary->GetVground() );
779
780     _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
781                      Propagate->GetPQR(FGJSBBase::eQ),
782                      Propagate->GetPQR(FGJSBBase::eR) );
783
784     _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
785                       Auxiliary->GetEulerRates(FGJSBBase::eTht),
786                       Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
787
788     _set_Mach_number( Auxiliary->GetMach() );
789
790     // Positions of Visual Reference Point
791     FGLocation l = Auxiliary->GetLocationVRP();
792     _updatePosition(SGGeoc::fromRadFt( l.GetLongitude(), l.GetLatitude(),
793                                        l.GetRadius() ));
794
795     _set_Altitude_AGL( Propagate->GetDistanceAGL() );
796     {
797       double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
798       double contact[3], d[3], sd, t;
799       is_valid_m(&t, d, &sd);
800       get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
801       double rwrad
802         = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
803       _set_Runway_altitude( rwrad - get_Sea_level_radius() );
804     }
805
806     _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
807                        Propagate->GetEuler(FGJSBBase::eTht),
808                        Propagate->GetEuler(FGJSBBase::ePsi) );
809
810     _set_Alpha( Auxiliary->Getalpha() );
811     _set_Beta( Auxiliary->Getbeta() );
812
813
814     _set_Gamma_vert_rad( Auxiliary->GetGamma() );
815
816     _set_Earth_position_angle( Propagate->GetEarthPositionAngle() );
817
818     _set_Climb_Rate( Propagate->Gethdot() );
819
820     const FGMatrix33& Tl2b = Propagate->GetTl2b();
821     for ( i = 1; i <= 3; i++ ) {
822         for ( j = 1; j <= 3; j++ ) {
823             _set_T_Local_to_Body( i, j, Tl2b(i,j) );
824         }
825     }
826
827     // Copy the engine values from JSBSim.
828     for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
829       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
830       SGPropertyNode * tnode = node->getChild("thruster", 0, true);
831       FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
832
833       switch (Propulsion->GetEngine(i)->GetType()) {
834       case FGEngine::etPiston:
835         { // FGPiston code block
836         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
837         node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
838         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
839         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
840         node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
841         // NOTE: mp-osi is not in ounces per square inch.
842         // This error is left for reasons of backwards compatibility with
843         // existing FlightGear sound and instrument configurations.
844         node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
845         node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
846         node->setDoubleValue("rpm", eng->getRPM());
847         } // end FGPiston code block
848         break;
849       case FGEngine::etRocket:
850         { // FGRocket code block
851 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
852         } // end FGRocket code block
853         break;
854       case FGEngine::etTurbine:
855         { // FGTurbine code block
856         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
857         node->setDoubleValue("n1", eng->GetN1());
858         node->setDoubleValue("n2", eng->GetN2());
859         node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
860         node->setBoolValue("augmentation", eng->GetAugmentation());
861         node->setBoolValue("water-injection", eng->GetInjection());
862         node->setBoolValue("ignition", eng->GetIgnition() != 0);
863         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
864         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
865         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
866         node->setBoolValue("reversed", eng->GetReversed());
867         node->setBoolValue("cutoff", eng->GetCutoff());
868         node->setDoubleValue("epr", eng->GetEPR());
869         globals->get_controls()->set_reverser(i, eng->GetReversed() );
870         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
871         globals->get_controls()->set_water_injection(i, eng->GetInjection() );
872         globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
873         } // end FGTurbine code block
874         break;
875       case FGEngine::etTurboprop:
876         { // FGTurboProp code block
877         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
878         node->setDoubleValue("n1", eng->GetN1());
879         //node->setDoubleValue("n2", eng->GetN2());
880         node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
881         node->setBoolValue("ignition", eng->GetIgnition() != 0);
882         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
883         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
884         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
885         node->setBoolValue("reversed", eng->GetReversed());
886         node->setBoolValue("cutoff", eng->GetCutoff());
887         node->setBoolValue("starting", eng->GetEngStarting());
888         node->setBoolValue("generator-power", eng->GetGeneratorPower());
889         node->setBoolValue("damaged", eng->GetCondition() != 0);
890         node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
891         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
892 //        node->setBoolValue("onfire", eng->GetFire());
893         globals->get_controls()->set_reverser(i, eng->GetReversed() );
894         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
895         } // end FGTurboProp code block
896         break;
897       case FGEngine::etElectric:
898         { // FGElectric code block
899         FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
900         node->setDoubleValue("rpm", eng->getRPM());
901         } // end FGElectric code block
902         break;
903       case FGEngine::etUnknown:
904         break;
905       }
906
907       { // FGEngine code block
908       FGEngine* eng = Propulsion->GetEngine(i);
909       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
910       node->setDoubleValue("thrust_lb", thruster->GetThrust());
911       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
912       node->setBoolValue("running", eng->GetRunning());
913       node->setBoolValue("starter", eng->GetStarter());
914       node->setBoolValue("cranking", eng->GetCranking());
915       globals->get_controls()->set_starter(i, eng->GetStarter() );
916       } // end FGEngine code block
917
918       switch (thruster->GetType()) {
919       case FGThruster::ttNozzle:
920         { // FGNozzle code block
921 //        FGNozzle* noz = (FGNozzle*)thruster;
922         } // end FGNozzle code block
923         break;
924       case FGThruster::ttPropeller:
925         { // FGPropeller code block
926         FGPropeller* prop = (FGPropeller*)thruster;
927         tnode->setDoubleValue("rpm", thruster->GetRPM());
928         tnode->setDoubleValue("pitch", prop->GetPitch());
929         tnode->setDoubleValue("torque", prop->GetTorque());
930         tnode->setBoolValue("feathered", prop->GetFeather());
931         } // end FGPropeller code block
932         break;
933       case FGThruster::ttRotor:
934         { // FGRotor code block
935 //        FGRotor* rotor = (FGRotor*)thruster;
936         } // end FGRotor code block
937         break;
938       case FGThruster::ttDirect:
939         { // Direct code block
940         } // end Direct code block
941         break;
942       }
943
944     }
945
946     // Copy the fuel levels from JSBSim if fuel
947     // freeze not enabled.
948     if ( ! Propulsion->GetFuelFreeze() ) {
949       for (i = 0; i < Propulsion->GetNumTanks(); i++) {
950         SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
951         FGTank* tank = Propulsion->GetTank(i);
952         double contents = tank->GetContents();
953         double temp = tank->GetTemperature_degC();
954         double fuelDensity = tank->GetDensity();
955
956         if (fuelDensity < 0.1)
957           fuelDensity = 6.0; // Use average fuel value
958
959         node->setDoubleValue("density-ppg" , fuelDensity);
960         node->setDoubleValue("level-lbs", contents);
961         if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
962       }
963     }
964
965     update_gear();
966
967     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
968
969     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
970     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
971     right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
972     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
973     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
974     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
975     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
976     tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
977     wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
978
979     // force a sim crashed if crashed (altitude AGL < 0)
980     if (get_Altitude_AGL() < -100.0) {
981          fdmex->SuspendIntegration();
982          crashed = true;
983     }
984
985     return true;
986 }
987
988
989 bool FGJSBsim::ToggleDataLogging(void)
990 {
991   // ToDo: handle this properly
992   fdmex->DisableOutput();
993   return false;
994 }
995
996
997 bool FGJSBsim::ToggleDataLogging(bool state)
998 {
999     if (state) {
1000       fdmex->EnableOutput();
1001       return true;
1002     } else {
1003       fdmex->DisableOutput();
1004       return false;
1005     }
1006 }
1007
1008
1009 //Positions
1010 void FGJSBsim::set_Latitude(double lat)
1011 {
1012   double alt = altitude->getDoubleValue();
1013   double sea_level_radius_meters, lat_geoc;
1014
1015   if ( alt < -9990 ) alt = 0.0;
1016
1017   SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1018   SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
1019
1020   sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1021                     &sea_level_radius_meters, &lat_geoc );
1022
1023   double sea_level_radius_ft = sea_level_radius_meters * SG_METER_TO_FEET;
1024   _set_Sea_level_radius( sea_level_radius_ft );
1025
1026   if (needTrim) {
1027     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_ft );
1028     fgic->SetLatitudeRadIC( lat_geoc );
1029   }
1030   else
1031     Propagate->SetLatitude(lat_geoc);
1032
1033   FGInterface::set_Latitude(lat);
1034 }
1035
1036
1037 void FGJSBsim::set_Longitude(double lon)
1038 {
1039   SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1040
1041   if (needTrim)
1042     fgic->SetLongitudeRadIC(lon);
1043   else
1044     Propagate->SetLongitude(lon);
1045
1046   FGInterface::set_Longitude(lon);
1047 }
1048
1049 // Sets the altitude above sea level.
1050 void FGJSBsim::set_Altitude(double alt)
1051 {
1052   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1053
1054   if (needTrim)
1055     fgic->SetAltitudeASLFtIC(alt);
1056   else
1057     Propagate->SetAltitudeASL(alt);
1058
1059   FGInterface::set_Altitude(alt);
1060 }
1061
1062 void FGJSBsim::set_V_calibrated_kts(double vc)
1063 {
1064     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
1065
1066   if (needTrim)
1067     fgic->SetVcalibratedKtsIC(vc);
1068   else {
1069     double p=pressure->getDoubleValue();
1070     double psl=fdmex->GetAtmosphere()->GetPressureSL();
1071     double rhosl=fdmex->GetAtmosphere()->GetDensitySL();
1072     double mach = FGJSBBase::MachFromVcalibrated(vc, p, psl, rhosl);
1073     double temp = 1.8*(temperature->getDoubleValue()+273.15);
1074     double soundSpeed = sqrt(1.4*1716.0*temp);
1075     FGColumnVector3 vUVW = Propagate->GetUVW();
1076     vUVW.Normalize();
1077     vUVW *= mach * soundSpeed;
1078     Propagate->SetUVW(1, vUVW(1));
1079     Propagate->SetUVW(2, vUVW(2));
1080     Propagate->SetUVW(3, vUVW(3));
1081   }
1082
1083   FGInterface::set_V_calibrated_kts(vc);
1084 }
1085
1086 void FGJSBsim::set_Mach_number(double mach)
1087 {
1088   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
1089
1090   if (needTrim)
1091     fgic->SetMachIC(mach);
1092   else {
1093     double temp = 1.8*(temperature->getDoubleValue()+273.15);
1094     double soundSpeed = sqrt(1.4*1716.0*temp);
1095     FGColumnVector3 vUVW = Propagate->GetUVW();
1096     vUVW.Normalize();
1097     vUVW *= mach * soundSpeed;
1098     Propagate->SetUVW(1, vUVW(1));
1099     Propagate->SetUVW(2, vUVW(2));
1100     Propagate->SetUVW(3, vUVW(3));
1101   }
1102
1103   FGInterface::set_Mach_number(mach);
1104 }
1105
1106 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1107 {
1108   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1109      << north << ", " <<  east << ", " << down );
1110
1111   if (needTrim) {
1112     fgic->SetVNorthFpsIC(north);
1113     fgic->SetVEastFpsIC(east);
1114     fgic->SetVDownFpsIC(down);
1115   }
1116   else {
1117     FGColumnVector3 vNED(north, east, down);
1118     FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1119     Propagate->SetUVW(1, vUVW(1));
1120     Propagate->SetUVW(2, vUVW(2));
1121     Propagate->SetUVW(3, vUVW(3));
1122   }
1123
1124   FGInterface::set_Velocities_Local(north, east, down);
1125 }
1126
1127 void FGJSBsim::set_Velocities_Body( double u, double v, double w)
1128 {
1129   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Body: "
1130      << u << ", " <<  v << ", " <<  w );
1131
1132   if (needTrim) {
1133     fgic->SetUBodyFpsIC(u);
1134     fgic->SetVBodyFpsIC(v);
1135     fgic->SetWBodyFpsIC(w);
1136   }
1137   else {
1138     Propagate->SetUVW(1, u);
1139     Propagate->SetUVW(2, v);
1140     Propagate->SetUVW(3, w);
1141   }
1142
1143   FGInterface::set_Velocities_Body(u, v, w);
1144 }
1145
1146 //Euler angles
1147 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1148 {
1149   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1150      << phi << ", " << theta << ", " << psi );
1151
1152   if (needTrim) {
1153     fgic->SetThetaRadIC(theta);
1154     fgic->SetPhiRadIC(phi);
1155     fgic->SetPsiRadIC(psi);
1156   }
1157   else {
1158     FGQuaternion quat(phi, theta, psi);
1159     FGMatrix33 Tl2b = quat.GetT();
1160     FGMatrix33 Ti2b = Tl2b*Propagate->GetTi2l();
1161     FGQuaternion Qi = Ti2b.GetQuaternion();
1162     Propagate->SetInertialOrientation(Qi);
1163   }
1164
1165   FGInterface::set_Euler_Angles(phi, theta, psi);
1166 }
1167
1168 //Flight Path
1169 void FGJSBsim::set_Climb_Rate( double roc)
1170 {
1171   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1172
1173   //since both climb rate and flight path angle are set in the FG
1174   //startup sequence, something is needed to keep one from cancelling
1175   //out the other.
1176   if( fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01 ) {
1177     if (needTrim)
1178       fgic->SetClimbRateFpsIC(roc);
1179     else {
1180       FGColumnVector3 vNED = Propagate->GetVel();
1181       vNED(FGJSBBase::eDown) = -roc;
1182       FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1183       Propagate->SetUVW(1, vUVW(1));
1184       Propagate->SetUVW(2, vUVW(2));
1185       Propagate->SetUVW(3, vUVW(3));
1186     }
1187
1188     FGInterface::set_Climb_Rate(roc);
1189   }
1190 }
1191
1192 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1193 {
1194   SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1195
1196   if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1197     if (needTrim)
1198       fgic->SetFlightPathAngleRadIC(gamma);
1199     else {
1200       FGColumnVector3 vNED = Propagate->GetVel();
1201       double vt = vNED.Magnitude();
1202       vNED(FGJSBBase::eDown) = -vt * sin(gamma);
1203       FGColumnVector3 vUVW = Propagate->GetTl2b() * vNED;
1204       Propagate->SetUVW(1, vUVW(1));
1205       Propagate->SetUVW(2, vUVW(2));
1206       Propagate->SetUVW(3, vUVW(3));
1207     }
1208
1209     FGInterface::set_Gamma_vert_rad(gamma);
1210   }
1211 }
1212
1213 void FGJSBsim::init_gear(void )
1214 {
1215     FGGroundReactions* gr=fdmex->GetGroundReactions();
1216     int Ngear=GroundReactions->GetNumGearUnits();
1217     for (int i=0;i<Ngear;i++) {
1218       FGLGear *gear = gr->GetGearUnit(i);
1219       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1220       node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1) * 12);
1221       node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2) * 12);
1222       node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3) * 12);
1223       node->setBoolValue("wow", gear->GetWOW());
1224       node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1225       node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1226       node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1227 //    node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1228       node->setDoubleValue("compression-norm", gear->GetCompLen());
1229       node->setDoubleValue("compression-ft", gear->GetCompLen());
1230       if ( gear->GetSteerable() )
1231         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1232     }
1233 }
1234
1235 void FGJSBsim::update_gear(void)
1236 {
1237     FGGroundReactions* gr=fdmex->GetGroundReactions();
1238     int Ngear=GroundReactions->GetNumGearUnits();
1239     for (int i=0;i<Ngear;i++) {
1240       FGLGear *gear = gr->GetGearUnit(i);
1241       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1242       node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1243       node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1244       node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1245 //    gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1246       node->setDoubleValue("compression-norm", gear->GetCompLen());
1247       node->setDoubleValue("compression-ft", gear->GetCompLen());
1248       if ( gear->GetSteerable() )
1249         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1250     }
1251 }
1252
1253 void FGJSBsim::do_trim(void)
1254 {
1255   FGTrim *fgtrim;
1256
1257   if ( fgGetBool("/sim/presets/onground") )
1258   {
1259     fgtrim = new FGTrim(fdmex,tGround);
1260   } else {
1261     fgtrim = new FGTrim(fdmex,tFull);
1262   }
1263
1264   if ( !fgtrim->DoTrim() ) {
1265     fgtrim->Report();
1266     fgtrim->TrimStats();
1267   } else {
1268     trimmed->setBoolValue(true);
1269   }
1270   delete fgtrim;
1271
1272   pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1273   throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1274   aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1275   rudder_trim->setDoubleValue( -FCS->GetDrCmd() );
1276
1277   globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1278   globals->get_controls()->set_elevator(FCS->GetDeCmd());
1279   for( unsigned i = 0; i < Propulsion->GetNumEngines(); i++ )
1280     globals->get_controls()->set_throttle(i, FCS->GetThrottleCmd(i));
1281
1282   globals->get_controls()->set_aileron(FCS->GetDaCmd());
1283   globals->get_controls()->set_rudder( -FCS->GetDrCmd());
1284
1285   SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
1286 }
1287
1288 bool FGJSBsim::update_ground_cache(FGLocation cart, double* cart_pos, double dt)
1289 {
1290   // Compute the radius of the aircraft. That is the radius of a ball
1291   // where all gear units are in. At the moment it is at least 10ft ...
1292   double acrad = 10.0;
1293   int n_gears = GroundReactions->GetNumGearUnits();
1294   for (int i=0; i<n_gears; ++i) {
1295     FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
1296     double r = bl.Magnitude();
1297     if (acrad < r)
1298       acrad = r;
1299   }
1300
1301   // Compute the potential movement of this aircraft and query for the
1302   // ground in this area.
1303   double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
1304   cart_pos[0] = cart(1);
1305   cart_pos[1] = cart(2);
1306   cart_pos[2] = cart(3);
1307   double t0 = fdmex->GetSimTime();
1308   bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
1309                                            groundCacheRadius );
1310   if (!cache_ok) {
1311     SG_LOG(SG_FLIGHT, SG_WARN,
1312            "FGInterface is being called without scenery below the aircraft!");
1313
1314     SG_LOG(SG_FLIGHT, SG_WARN, "altitude         = "
1315                       << fgic->GetAltitudeASLFtIC());
1316
1317     SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = "
1318                       << get_Sea_level_radius());
1319
1320     SG_LOG(SG_FLIGHT, SG_WARN, "latitude         = "
1321                       << fgic->GetLatitudeRadIC());
1322
1323     SG_LOG(SG_FLIGHT, SG_WARN, "longitude        = "
1324                       << fgic->GetLongitudeRadIC());
1325   }
1326
1327   return cache_ok;
1328 }
1329
1330 bool
1331 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1332                      double contact[3], double normal[3], double vel[3],
1333                      double angularVel[3], double *agl)
1334 {
1335    const simgear::BVHMaterial* material;
1336    simgear::BVHNode::Id id;
1337    if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1338                                 angularVel, material, id))
1339        return false;
1340    SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1341    SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1342    *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1343    return true;
1344 }
1345
1346 inline static double sqr(double x)
1347 {
1348     return x * x;
1349 }
1350
1351 static double angle_diff(double a, double b)
1352 {
1353     double diff = fabs(a - b);
1354     if (diff > 180) diff = 360 - diff;
1355     
1356     return diff;
1357 }
1358
1359 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double cos_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1360 {
1361     FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1362     double dist = DotProduct(tip, ground_normal_body);
1363     if (fabs(dist + E) < 0.0001) {
1364         sin_fis[*points] = sin_fi_guess;
1365         cos_fis[*points] = cos_fi_guess;
1366         fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1367         (*points)++;
1368     } 
1369 }
1370
1371
1372 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1373 {
1374     if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1375         double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1376         check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1377         if (fabs(cos_fi_guess) > SG_EPSILON) {
1378             check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1379         }
1380     }
1381 }
1382
1383 void FGJSBsim::update_external_forces(double t_off)
1384 {
1385     const FGMatrix33& Tb2l = Propagate->GetTb2l();
1386     const FGMatrix33& Tl2b = Propagate->GetTl2b();
1387     const FGLocation& Location = Propagate->GetLocation();
1388     const FGMatrix33& Tec2l = Location.GetTec2l();
1389         
1390     double hook_area[4][3];
1391     
1392     FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1393     FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l *   hook_root_body);
1394     hook_area[1][0] = hook_root(1);
1395     hook_area[1][1] = hook_root(2);
1396     hook_area[1][2] = hook_root(3);
1397     
1398     hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1399     double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1400     double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1401     double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1402     double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1403     double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1404
1405     FGColumnVector3 hook_tip_body = hook_root_body;
1406     hook_tip_body(1) -= hook_length * cos_fi;
1407     hook_tip_body(3) += hook_length * sin_fi;    
1408     
1409     double contact[3];
1410     double ground_normal[3];
1411     double ground_vel[3];
1412     double ground_angular_vel[3];
1413     double root_agl_ft;
1414
1415     if (!got_wire) {
1416         bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1417                               ground_vel, ground_angular_vel, &root_agl_ft);
1418         if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1419             FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1420             FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1421             double D = -DotProduct(contact_body, ground_normal_body);
1422
1423             // check hook tip agl against same ground plane
1424             double hook_tip_agl_ft = DotProduct(hook_tip_body, ground_normal_body) + D;
1425             if (hook_tip_agl_ft < 0) {
1426
1427                 // hook tip: hx - l cos, hy, hz + l sin
1428                 // on ground:  - n0 l cos + n2 l sin + E = 0
1429
1430                 double E = D + DotProduct(hook_root_body, ground_normal_body);
1431
1432                 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1433                 // and rearrange to get a quadratic with coeffs:
1434                 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1435                 double b = 2 * E * ground_normal_body(3) * hook_length;
1436                 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);   
1437
1438                 double disc = sqr(b) - 4 * a * c;
1439                 if (disc >= 0) {
1440                     double delta = sqrt(disc) / (2 * a);
1441                 
1442                     // allow 4 solutions for safety, should never happen
1443                     double sin_fis[4];
1444                     double cos_fis[4];
1445                     double fis[4];
1446                     int points = 0;
1447                 
1448                     double sin_fi_guess = -b / (2 * a) - delta;
1449                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1450                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1451                 
1452                     if (points == 2) {
1453                         double diff1 = angle_diff(fi, fis[0]);
1454                         double diff2 = angle_diff(fi, fis[1]);
1455                         int point = diff1 < diff2 ? 0 : 1;
1456                         fi = fis[point];
1457                         sin_fi = sin_fis[point];
1458                         cos_fi = cos_fis[point];
1459                         hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1460                         hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1461                     }
1462                 }
1463             }
1464         }
1465     } else {
1466         FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() *  hook_root_body));
1467         double wire_ends_ec[2][3];
1468         double wire_vel_ec[2][3];
1469         get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1470         FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1471         FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1472         FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1473         if (rel_vel.Magnitude() < 3) {
1474             got_wire = false;
1475             release_wire();
1476             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1477         } else {
1478             FGColumnVector3 wire_end1_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[0][0], wire_ends_ec[0][1], wire_ends_ec[0][2])) - hook_root_body;
1479             FGColumnVector3 wire_end2_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[1][0], wire_ends_ec[1][1], wire_ends_ec[1][2])) - hook_root_body;
1480             FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1481             force_plane_normal.Normalize();
1482             cos_fi = DotProduct(force_plane_normal, FGColumnVector3(0, 0, 1));
1483             if (cos_fi < 0) cos_fi = -cos_fi;
1484             sin_fi = sqrt(1 - sqr(cos_fi));
1485             fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1486         
1487             fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1488             fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1489             fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1490             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1491         }
1492     }
1493
1494     FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1495
1496     hook_area[0][0] = hook_tip(1);
1497     hook_area[0][1] = hook_tip(2);
1498     hook_area[0][2] = hook_tip(3);
1499
1500     if (!got_wire) {
1501         // The previous positions.
1502         hook_area[2][0] = last_hook_root[0];
1503         hook_area[2][1] = last_hook_root[1];
1504         hook_area[2][2] = last_hook_root[2];
1505         hook_area[3][0] = last_hook_tip[0];
1506         hook_area[3][1] = last_hook_tip[1];
1507         hook_area[3][2] = last_hook_tip[2];
1508
1509         // Check if we caught a wire.
1510         // Returns true if we caught one.
1511         if (caught_wire_ft(t_off, hook_area)) {
1512                 got_wire = true;
1513         }
1514     }
1515     
1516     // save actual position as old position ...
1517     last_hook_tip[0] = hook_area[0][0];
1518     last_hook_tip[1] = hook_area[0][1];
1519     last_hook_tip[2] = hook_area[0][2];
1520     last_hook_root[0] = hook_area[1][0];
1521     last_hook_root[1] = hook_area[1][1];
1522     last_hook_root[2] = hook_area[1][2];
1523     
1524     fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);
1525 }
1526