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