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