]> 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     resetPropertyState();
148
149     fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
150
151     // Register ground callback.
152     fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
153
154     Atmosphere      = fdmex->GetAtmosphere();
155     FCS             = fdmex->GetFCS();
156     MassBalance     = fdmex->GetMassBalance();
157     Propulsion      = fdmex->GetPropulsion();
158     Aircraft        = fdmex->GetAircraft();
159     Propagate        = fdmex->GetPropagate();
160     Auxiliary       = fdmex->GetAuxiliary();
161     Inertial        = fdmex->GetInertial();
162     Aerodynamics    = fdmex->GetAerodynamics();
163     GroundReactions = fdmex->GetGroundReactions();
164
165     fgic=fdmex->GetIC();
166     needTrim=true;
167
168     SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
169
170     SGPath engine_path( fgGetString("/sim/aircraft-dir") );
171     engine_path.append( "Engine" );
172
173     SGPath systems_path( fgGetString("/sim/aircraft-dir") );
174     systems_path.append( "Systems" );
175
176 // deprecate sim-time-sec for simulation/sim-time-sec
177 // remove alias with increased configuration file version number (2.1 or later)
178     SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec");
179     fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node );
180 // end of sim-time-sec deprecation patch
181
182     fdmex->Setdt( dt );
183
184     result = fdmex->LoadModel( aircraft_path.str(),
185                                engine_path.str(),
186                                systems_path.str(),
187                                fgGetString("/sim/aero"), false );
188
189     if (result) {
190       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
191     } else {
192       SG_LOG( SG_FLIGHT, SG_INFO,
193               "  aero does not exist (you may have mis-typed the name).");
194       throw(-1);
195     }
196
197     SG_LOG( SG_FLIGHT, SG_INFO, "" );
198     SG_LOG( SG_FLIGHT, SG_INFO, "" );
199     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
200
201     int Neng = Propulsion->GetNumEngines();
202     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
203
204     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
205         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
206                 << GroundReactions->GetNumGearUnits() );
207         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
208         SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
209         SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
210         exit(-1);
211     }
212
213     init_gear();
214
215     // Set initial fuel levels if provided.
216     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
217       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
218       if (node->getChild("level-gal_us", 0, false) != 0) {
219         Propulsion->GetTank(i)->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
220       } else {
221         node->setDoubleValue("level-lbs", Propulsion->GetTank(i)->GetContents());
222         node->setDoubleValue("level-gal_us", Propulsion->GetTank(i)->GetContents() / 6.6);
223       }
224       node->setDoubleValue("capacity-gal_us",
225                            Propulsion->GetTank(i)->GetCapacity() / 6.6);
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 checkTied ( FGPropertyManager *node )
428 {
429   int N = node->nChildren();
430   string name;
431
432   for (int i=0; i<N; i++) {
433     if (node->getChild(i)->nChildren() ) {
434       checkTied( (FGPropertyManager*)node->getChild(i) );
435     }
436     if ( node->getChild(i)->isTied() ) {
437       name = ((FGPropertyManager*)node->getChild(i))->GetFullyQualifiedName();
438       node->Untie(name);
439     }
440   }
441 }
442
443 /******************************************************************************/
444
445 void FGJSBsim::unbind()
446 {
447   SGPropertyNode* instance = globals->get_props()->getNode("/fdm/jsbsim");
448   checkTied((FGPropertyManager*)instance);
449   FGInterface::unbind();
450 }
451
452 /******************************************************************************/
453
454 // Run an iteration of the EOM (equations of motion)
455
456 void FGJSBsim::update( double dt )
457 {
458     if(crashed) {
459       if(!fgGetBool("/sim/crashed"))
460         fgSetBool("/sim/crashed", true);
461       return;
462     }
463
464     if (is_suspended())
465       return;
466
467     int multiloop = _calc_multiloop(dt);
468
469     int i;
470
471     // Compute the radius of the aircraft. That is the radius of a ball
472     // where all gear units are in. At the moment it is at least 10ft ...
473     double acrad = 10.0;
474     int n_gears = GroundReactions->GetNumGearUnits();
475     for (i=0; i<n_gears; ++i) {
476       FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
477       double r = bl.Magnitude();
478       if (acrad < r)
479         acrad = r;
480     }
481
482     // Compute the potential movement of this aircraft and query for the
483     // ground in this area.
484     double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
485     double alt, slr, lat, lon;
486     FGLocation cart = Auxiliary->GetLocationVRP();
487     if ( needTrim && startup_trim->getBoolValue() ) {
488       alt = fgic->GetAltitudeASLFtIC();
489       slr = fgic->GetSeaLevelRadiusFtIC();
490       lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
491       lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
492       cart = FGLocation(lon, lat, alt+slr);
493     }
494     double cart_pos[3] = { cart(1), cart(2), cart(3) };
495     double t0 = fdmex->GetSimTime();
496     bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
497                                              groundCacheRadius );
498     if (!cache_ok) {
499       SG_LOG(SG_FLIGHT, SG_WARN,
500              "FGInterface is being called without scenery below the aircraft!");
501
502       alt = fgic->GetAltitudeASLFtIC();
503       SG_LOG(SG_FLIGHT, SG_WARN, "altitude         = " << alt);
504
505       slr = fgic->GetSeaLevelRadiusFtIC();
506       SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = " << slr);
507
508       lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
509       SG_LOG(SG_FLIGHT, SG_WARN, "latitude         = " << lat);
510
511       lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
512       SG_LOG(SG_FLIGHT, SG_WARN, "longitude        = " << lon);
513       //return;
514     }
515
516     copy_to_JSBsim();
517
518     trimmed->setBoolValue(false);
519
520     if ( needTrim ) {
521       if ( startup_trim->getBoolValue() ) {
522         double contact[3], d[3], vel[3], agl;
523         get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
524                    d, vel, d, &agl);
525         double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
526              + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
527
528         SG_LOG(SG_FLIGHT, SG_INFO,
529           "Ready to trim, terrain elevation is: "
530             << terrain_alt * SG_METER_TO_FEET );
531
532         if (fgGetBool("/sim/presets/onground")) {
533           FGColumnVector3 gndVelNED = cart.GetTec2l()
534                                     * FGColumnVector3(vel[0], vel[1], vel[2]);
535           fgic->SetVNorthFpsIC(gndVelNED(1));
536           fgic->SetVEastFpsIC(gndVelNED(2));
537           fgic->SetVDownFpsIC(gndVelNED(3));
538         }
539         fgic->SetTerrainElevationFtIC( terrain_alt );
540         do_trim();
541       } else {
542         fdmex->RunIC();  //apply any changes made through the set_ functions
543       }
544       needTrim = false;
545     }
546
547     for ( i=0; i < multiloop; i++ ) {
548       fdmex->Run();
549       update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());      
550     }
551
552     FGJSBBase::Message* msg;
553     while (msg = fdmex->ProcessNextMessage()) {
554 //      msg = fdmex->ProcessNextMessage();
555       switch (msg->type) {
556       case FGJSBBase::Message::eText:
557         if (msg->text == "Crash Detected: Simulation FREEZE.")
558           crashed = true;
559         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
560         break;
561       case FGJSBBase::Message::eBool:
562         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
563         break;
564       case FGJSBBase::Message::eInteger:
565         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
566         break;
567       case FGJSBBase::Message::eDouble:
568         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
569         break;
570       default:
571         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
572         break;
573       }
574     }
575
576     // translate JSBsim back to FG structure so that the
577     // autopilot (and the rest of the sim can use the updated values
578     copy_from_JSBsim();
579 }
580
581 /******************************************************************************/
582
583 // Convert from the FGInterface struct to the JSBsim generic_ struct
584
585 bool FGJSBsim::copy_to_JSBsim()
586 {
587     double tmp;
588     unsigned int i;
589
590     // copy control positions into the JSBsim structure
591
592     FCS->SetDaCmd( globals->get_controls()->get_aileron());
593     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
594     FCS->SetDeCmd( globals->get_controls()->get_elevator());
595     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
596     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
597     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
598     FCS->SetDsCmd( globals->get_controls()->get_rudder() );
599     FCS->SetDfCmd( globals->get_controls()->get_flaps() );
600     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
601     FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
602
603         // Parking brake sets minimum braking
604         // level for mains.
605     double parking_brake = globals->get_controls()->get_brake_parking();
606     double left_brake = globals->get_controls()->get_brake_left();
607     double right_brake = globals->get_controls()->get_brake_right();
608     
609     if (ab_brake_engaged->getBoolValue()) {
610       left_brake = ab_brake_left_pct->getDoubleValue();
611       right_brake = ab_brake_right_pct->getDoubleValue(); 
612     }
613     
614     FCS->SetLBrake(FMAX(left_brake, parking_brake));
615     FCS->SetRBrake(FMAX(right_brake, parking_brake));
616     
617     
618     FCS->SetCBrake( 0.0 );
619     // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
620
621     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
622     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
623       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
624
625       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
626       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
627       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
628       FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
629
630       switch (Propulsion->GetEngine(i)->GetType()) {
631       case FGEngine::etPiston:
632         { // FGPiston code block
633         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
634         eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
635         break;
636         } // end FGPiston code block
637       case FGEngine::etTurbine:
638         { // FGTurbine code block
639         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
640         eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
641         eng->SetReverse( globals->get_controls()->get_reverser(i) );
642         //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
643         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
644         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
645         break;
646         } // end FGTurbine code block
647       case FGEngine::etRocket:
648         { // FGRocket code block
649         FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
650         break;
651         } // end FGRocket code block
652       case FGEngine::etTurboprop:
653         { // FGTurboProp code block
654         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
655         eng->SetReverse( globals->get_controls()->get_reverser(i) );
656         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
657         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
658
659         eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
660         eng->SetCondition( globals->get_controls()->get_condition(i) );
661         break;
662         } // end FGTurboProp code block
663       default:
664         break;
665       }
666
667       { // FGEngine code block
668       FGEngine* eng = Propulsion->GetEngine(i);
669
670       eng->SetStarter( globals->get_controls()->get_starter(i) );
671       eng->SetRunning( node->getBoolValue("running") );
672       } // end FGEngine code block
673     }
674
675
676     Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
677
678     Atmosphere->SetExTemperature(
679                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
680     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
681     Atmosphere->SetExDensity(density->getDoubleValue());
682
683     tmp = turbulence_gain->getDoubleValue();
684     //Atmosphere->SetTurbGain(tmp * tmp * 100.0);
685
686     tmp = turbulence_rate->getDoubleValue();
687     //Atmosphere->SetTurbRate(tmp);
688
689     Atmosphere->SetWindNED( -wind_from_north->getDoubleValue(),
690                             -wind_from_east->getDoubleValue(),
691                             -wind_from_down->getDoubleValue() );
692 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
693 //                  << get_V_north_airmass() << ", "
694 //                  << get_V_east_airmass()  << ", "
695 //                  << get_V_down_airmass() );
696
697     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
698       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
699       FGTank * tank = Propulsion->GetTank(i);
700       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
701 //       tank->SetContents(node->getDoubleValue("level-lbs"));
702     }
703
704     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
705     fdmex->SetChild(slaved->getBoolValue());
706
707     return true;
708 }
709
710 /******************************************************************************/
711
712 // Convert from the JSBsim generic_ struct to the FGInterface struct
713
714 bool FGJSBsim::copy_from_JSBsim()
715 {
716     unsigned int i, j;
717 /*
718     _set_Inertias( MassBalance->GetMass(),
719                    MassBalance->GetIxx(),
720                    MassBalance->GetIyy(),
721                    MassBalance->GetIzz(),
722                    MassBalance->GetIxz() );
723 */
724     _set_CG_Position( MassBalance->GetXYZcg(1),
725                       MassBalance->GetXYZcg(2),
726                       MassBalance->GetXYZcg(3) );
727
728     _set_Accels_Body( Aircraft->GetBodyAccel(1),
729                       Aircraft->GetBodyAccel(2),
730                       Aircraft->GetBodyAccel(3) );
731
732     _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
733                             Aircraft->GetNcg(2),
734                             Aircraft->GetNcg(3) );
735
736     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
737                             Auxiliary->GetPilotAccel(2),
738                             Auxiliary->GetPilotAccel(3) );
739
740     _set_Nlf( Aircraft->GetNlf() );
741
742     // Velocities
743
744     _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
745                            Propagate->GetVel(FGJSBBase::eEast),
746                            Propagate->GetVel(FGJSBBase::eDown) );
747
748     _set_Velocities_Wind_Body( Propagate->GetUVW(1),
749                                Propagate->GetUVW(2),
750                                Propagate->GetUVW(3) );
751
752     // Make the HUD work ...
753     _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
754                             Propagate->GetVel(FGJSBBase::eEast),
755                             -Propagate->GetVel(FGJSBBase::eDown) );
756
757     _set_V_rel_wind( Auxiliary->GetVt() );
758
759     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
760
761     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
762
763     _set_V_ground_speed( Auxiliary->GetVground() );
764
765     _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
766                      Propagate->GetPQR(FGJSBBase::eQ),
767                      Propagate->GetPQR(FGJSBBase::eR) );
768
769     _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
770                       Auxiliary->GetEulerRates(FGJSBBase::eTht),
771                       Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
772
773     _set_Mach_number( Auxiliary->GetMach() );
774
775     // Positions of Visual Reference Point
776     FGLocation l = Auxiliary->GetLocationVRP();
777     _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
778                                l.GetRadius() - get_Sea_level_radius() );
779
780     _set_Altitude_AGL( Propagate->GetDistanceAGL() );
781     {
782       double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
783       double contact[3], d[3], sd, t;
784       is_valid_m(&t, d, &sd);
785       get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
786       double rwrad
787         = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
788       _set_Runway_altitude( rwrad - get_Sea_level_radius() );
789     }
790
791     _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
792                        Propagate->GetEuler(FGJSBBase::eTht),
793                        Propagate->GetEuler(FGJSBBase::ePsi) );
794
795     _set_Alpha( Auxiliary->Getalpha() );
796     _set_Beta( Auxiliary->Getbeta() );
797
798
799     _set_Gamma_vert_rad( Auxiliary->GetGamma() );
800
801     _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
802
803     _set_Climb_Rate( Propagate->Gethdot() );
804
805     const FGMatrix33& Tl2b = Propagate->GetTl2b();
806     for ( i = 1; i <= 3; i++ ) {
807         for ( j = 1; j <= 3; j++ ) {
808             _set_T_Local_to_Body( i, j, Tl2b(i,j) );
809         }
810     }
811
812     // Copy the engine values from JSBSim.
813     for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
814       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
815       SGPropertyNode * tnode = node->getChild("thruster", 0, true);
816       FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
817
818       switch (Propulsion->GetEngine(i)->GetType()) {
819       case FGEngine::etPiston:
820         { // FGPiston code block
821         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
822         node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
823         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
824         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
825         node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
826         // NOTE: mp-osi is not in ounces per square inch.
827         // This error is left for reasons of backwards compatibility with
828         // existing FlightGear sound and instrument configurations.
829         node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
830         node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
831         node->setDoubleValue("rpm", eng->getRPM());
832         } // end FGPiston code block
833         break;
834       case FGEngine::etRocket:
835         { // FGRocket code block
836         FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
837         } // end FGRocket code block
838         break;
839       case FGEngine::etTurbine:
840         { // FGTurbine code block
841         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
842         node->setDoubleValue("n1", eng->GetN1());
843         node->setDoubleValue("n2", eng->GetN2());
844         node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
845         node->setBoolValue("augmentation", eng->GetAugmentation());
846         node->setBoolValue("water-injection", eng->GetInjection());
847         node->setBoolValue("ignition", eng->GetIgnition());
848         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
849         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
850         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
851         node->setBoolValue("reversed", eng->GetReversed());
852         node->setBoolValue("cutoff", eng->GetCutoff());
853         node->setDoubleValue("epr", eng->GetEPR());
854         globals->get_controls()->set_reverser(i, eng->GetReversed() );
855         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
856         globals->get_controls()->set_water_injection(i, eng->GetInjection() );
857         globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
858         } // end FGTurbine code block
859         break;
860       case FGEngine::etTurboprop:
861         { // FGTurboProp code block
862         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
863         node->setDoubleValue("n1", eng->GetN1());
864         //node->setDoubleValue("n2", eng->GetN2());
865         node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
866         node->setBoolValue("ignition", eng->GetIgnition());
867         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
868         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
869         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
870         node->setBoolValue("reversed", eng->GetReversed());
871         node->setBoolValue("cutoff", eng->GetCutoff());
872         node->setBoolValue("starting", eng->GetEngStarting());
873         node->setBoolValue("generator-power", eng->GetGeneratorPower());
874         node->setBoolValue("damaged", eng->GetCondition());
875         node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
876         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
877 //        node->setBoolValue("onfire", eng->GetFire());
878         globals->get_controls()->set_reverser(i, eng->GetReversed() );
879         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
880         } // end FGTurboProp code block
881         break;
882       case FGEngine::etElectric:
883         { // FGElectric code block
884         FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
885         node->setDoubleValue("rpm", eng->getRPM());
886         } // end FGElectric code block
887         break;
888       case FGEngine::etUnknown:
889         break;
890       }
891
892       { // FGEngine code block
893       FGEngine* eng = Propulsion->GetEngine(i);
894       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
895       node->setDoubleValue("thrust_lb", thruster->GetThrust());
896       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
897       node->setBoolValue("running", eng->GetRunning());
898       node->setBoolValue("starter", eng->GetStarter());
899       node->setBoolValue("cranking", eng->GetCranking());
900       globals->get_controls()->set_starter(i, eng->GetStarter() );
901       } // end FGEngine code block
902
903       switch (thruster->GetType()) {
904       case FGThruster::ttNozzle:
905         { // FGNozzle code block
906         FGNozzle* noz = (FGNozzle*)thruster;
907         } // end FGNozzle code block
908         break;
909       case FGThruster::ttPropeller:
910         { // FGPropeller code block
911         FGPropeller* prop = (FGPropeller*)thruster;
912         tnode->setDoubleValue("rpm", thruster->GetRPM());
913         tnode->setDoubleValue("pitch", prop->GetPitch());
914         tnode->setDoubleValue("torque", prop->GetTorque());
915         tnode->setBoolValue("feathered", prop->GetFeather());
916         } // end FGPropeller code block
917         break;
918       case FGThruster::ttRotor:
919         { // FGRotor code block
920         FGRotor* rotor = (FGRotor*)thruster;
921         } // end FGRotor code block
922         break;
923       case FGThruster::ttDirect:
924         { // Direct code block
925         } // end Direct code block
926         break;
927       }
928
929     }
930
931     // Copy the fuel levels from JSBSim if fuel
932     // freeze not enabled.
933     if ( ! Propulsion->GetFuelFreeze() ) {
934       for (i = 0; i < Propulsion->GetNumTanks(); i++) {
935         SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
936         FGTank* tank = Propulsion->GetTank(i);
937         double contents = tank->GetContents();
938         double temp = tank->GetTemperature_degC();
939         node->setDoubleValue("level-gal_us", contents/6.6);
940         node->setDoubleValue("level-lbs", contents);
941         if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
942       }
943     }
944
945     update_gear();
946
947     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
948
949     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
950     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
951     right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
952     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
953     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
954     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
955     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
956     tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
957     wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
958
959     // force a sim crashed if crashed (altitude AGL < 0)
960     if (get_Altitude_AGL() < -100.0) {
961          fdmex->SuspendIntegration();
962          crashed = true;
963     }
964
965     return true;
966 }
967
968
969 bool FGJSBsim::ToggleDataLogging(void)
970 {
971   // ToDo: handle this properly
972   fdmex->DisableOutput();
973   return false;
974 }
975
976
977 bool FGJSBsim::ToggleDataLogging(bool state)
978 {
979     if (state) {
980       fdmex->EnableOutput();
981       return true;
982     } else {
983       fdmex->DisableOutput();
984       return false;
985     }
986 }
987
988
989 //Positions
990 void FGJSBsim::set_Latitude(double lat)
991 {
992     static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
993     double alt;
994     double sea_level_radius_meters, lat_geoc;
995
996     // In case we're not trimming
997     FGInterface::set_Latitude(lat);
998
999     if ( altitude->getDoubleValue() > -9990 ) {
1000       alt = altitude->getDoubleValue();
1001     } else {
1002       alt = 0.0;
1003     }
1004
1005     update_ic();
1006     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1007     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
1008
1009     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1010                       &sea_level_radius_meters, &lat_geoc );
1011     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
1012     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );
1013     fgic->SetLatitudeRadIC( lat_geoc );
1014     needTrim=true;
1015 }
1016
1017
1018 void FGJSBsim::set_Longitude(double lon)
1019 {
1020     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1021
1022     // In case we're not trimming
1023     FGInterface::set_Longitude(lon);
1024
1025     update_ic();
1026     fgic->SetLongitudeRadIC( lon );
1027     needTrim=true;
1028 }
1029
1030 // Sets the altitude above sea level.
1031 void FGJSBsim::set_Altitude(double alt)
1032 {
1033     static SGConstPropertyNode_ptr latitude = fgGetNode("/position/latitude-deg");
1034
1035     double sea_level_radius_meters,lat_geoc;
1036
1037     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1038     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
1039
1040     // In case we're not trimming
1041     FGInterface::set_Altitude(alt);
1042
1043     update_ic();
1044     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
1045                   &sea_level_radius_meters, &lat_geoc);
1046     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
1047     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
1048     SG_LOG(SG_FLIGHT, SG_INFO,
1049           "Terrain elevation: " << FGInterface::get_Runway_altitude() * SG_METER_TO_FEET );
1050     fgic->SetLatitudeRadIC( lat_geoc );
1051     fgic->SetAltitudeASLFtIC(alt);
1052     needTrim=true;
1053 }
1054
1055 void FGJSBsim::set_V_calibrated_kts(double vc)
1056 {
1057     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
1058
1059     // In case we're not trimming
1060     FGInterface::set_V_calibrated_kts(vc);
1061
1062     update_ic();
1063     fgic->SetVcalibratedKtsIC(vc);
1064     needTrim=true;
1065 }
1066
1067 void FGJSBsim::set_Mach_number(double mach)
1068 {
1069     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
1070
1071     // In case we're not trimming
1072     FGInterface::set_Mach_number(mach);
1073
1074     update_ic();
1075     fgic->SetMachIC(mach);
1076     needTrim=true;
1077 }
1078
1079 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1080 {
1081     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1082        << north << ", " <<  east << ", " << down );
1083
1084     // In case we're not trimming
1085     FGInterface::set_Velocities_Local(north, east, down);
1086
1087     update_ic();
1088     fgic->SetVNorthFpsIC(north);
1089     fgic->SetVEastFpsIC(east);
1090     fgic->SetVDownFpsIC(down);
1091     needTrim=true;
1092 }
1093
1094 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1095 {
1096     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1097        << u << ", " <<  v << ", " <<  w );
1098
1099     // In case we're not trimming
1100     FGInterface::set_Velocities_Wind_Body(u, v, w);
1101
1102     update_ic();
1103     fgic->SetUBodyFpsIC(u);
1104     fgic->SetVBodyFpsIC(v);
1105     fgic->SetWBodyFpsIC(w);
1106     needTrim=true;
1107 }
1108
1109 //Euler angles
1110 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1111 {
1112     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1113        << phi << ", " << theta << ", " << psi );
1114
1115     // In case we're not trimming
1116     FGInterface::set_Euler_Angles(phi, theta, psi);
1117
1118     update_ic();
1119     fgic->SetThetaRadIC(theta);
1120     fgic->SetPhiRadIC(phi);
1121     fgic->SetPsiRadIC(psi);
1122     needTrim=true;
1123 }
1124
1125 //Flight Path
1126 void FGJSBsim::set_Climb_Rate( double roc)
1127 {
1128     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1129
1130     // In case we're not trimming
1131     FGInterface::set_Climb_Rate(roc);
1132
1133     update_ic();
1134     //since both climb rate and flight path angle are set in the FG
1135     //startup sequence, something is needed to keep one from cancelling
1136     //out the other.
1137     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1138       fgic->SetClimbRateFpsIC(roc);
1139     }
1140     needTrim=true;
1141 }
1142
1143 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1144 {
1145     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1146
1147     update_ic();
1148     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1149       fgic->SetFlightPathAngleRadIC(gamma);
1150     }
1151     needTrim=true;
1152 }
1153
1154 void FGJSBsim::init_gear(void )
1155 {
1156     FGGroundReactions* gr=fdmex->GetGroundReactions();
1157     int Ngear=GroundReactions->GetNumGearUnits();
1158     for (int i=0;i<Ngear;i++) {
1159       FGLGear *gear = gr->GetGearUnit(i);
1160       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1161       node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1162       node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1163       node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1164       node->setBoolValue("wow", gear->GetWOW());
1165       node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1166       node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1167       node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1168       node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1169       node->setDoubleValue("compression-norm", gear->GetCompLen());
1170       node->setDoubleValue("compression-ft", gear->GetCompLen());
1171       if ( gear->GetSteerable() )
1172         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1173     }
1174 }
1175
1176 void FGJSBsim::update_gear(void)
1177 {
1178     FGGroundReactions* gr=fdmex->GetGroundReactions();
1179     int Ngear=GroundReactions->GetNumGearUnits();
1180     for (int i=0;i<Ngear;i++) {
1181       FGLGear *gear = gr->GetGearUnit(i);
1182       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1183       node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1184       node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1185       node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1186       gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1187       node->setDoubleValue("compression-norm", gear->GetCompLen());
1188       node->setDoubleValue("compression-ft", gear->GetCompLen());
1189       if ( gear->GetSteerable() )
1190         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1191     }
1192 }
1193
1194 void FGJSBsim::do_trim(void)
1195 {
1196   FGTrim *fgtrim;
1197
1198   if ( fgGetBool("/sim/presets/onground") )
1199   {
1200     fgtrim = new FGTrim(fdmex,tGround);
1201   } else {
1202     fgtrim = new FGTrim(fdmex,tLongitudinal);
1203   }
1204
1205   if ( !fgtrim->DoTrim() ) {
1206     fgtrim->Report();
1207     fgtrim->TrimStats();
1208   } else {
1209     trimmed->setBoolValue(true);
1210   }
1211   delete fgtrim;
1212
1213   pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1214   throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1215   aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1216   rudder_trim->setDoubleValue( FCS->GetDrCmd() );
1217
1218   globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1219   globals->get_controls()->set_elevator(FCS->GetDeCmd());
1220   globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
1221   FCS->GetThrottleCmd(0));
1222
1223   globals->get_controls()->set_aileron(FCS->GetDaCmd());
1224   globals->get_controls()->set_rudder( FCS->GetDrCmd());
1225
1226   SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
1227 }
1228
1229 void FGJSBsim::update_ic(void)
1230 {
1231    if ( !needTrim ) {
1232      fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1233      fgic->SetLongitudeRadIC( get_Longitude() );
1234      fgic->SetAltitudeASLFtIC( get_Altitude() );
1235      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1236      fgic->SetThetaRadIC( get_Theta() );
1237      fgic->SetPhiRadIC( get_Phi() );
1238      fgic->SetPsiRadIC( get_Psi() );
1239      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
1240    }
1241 }
1242
1243 bool
1244 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1245                      double contact[3], double normal[3], double vel[3],
1246                      double angularVel[3], double *agl)
1247 {
1248    const SGMaterial* material;
1249    simgear::BVHNode::Id id;
1250    if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1251                                 angularVel, material, id))
1252        return false;
1253    SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1254    SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1255    *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1256    return true;
1257 }
1258
1259 inline static double dot3(const FGColumnVector3& a, const FGColumnVector3& b)
1260 {
1261     return a(1) * b(1) + a(2) * b(2) + a(3) * b(3);
1262 }
1263
1264 inline static double sqr(double x)
1265 {
1266     return x * x;
1267 }
1268
1269 static double angle_diff(double a, double b)
1270 {
1271     double diff = fabs(a - b);
1272     if (diff > 180) diff = 360 - diff;
1273     
1274     return diff;
1275 }
1276
1277 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)
1278 {
1279     FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1280     double dist = dot3(tip, ground_normal_body);
1281     if (fabs(dist + E) < 0.0001) {
1282         sin_fis[*points] = sin_fi_guess;
1283         cos_fis[*points] = cos_fi_guess;
1284         fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1285         (*points)++;
1286     } 
1287 }
1288
1289
1290 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)
1291 {
1292     if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1293         double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1294         check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1295         if (fabs(cos_fi_guess) > SG_EPSILON) {
1296             check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1297         }
1298     }
1299 }
1300
1301 void FGJSBsim::update_external_forces(double t_off)
1302 {
1303     const FGMatrix33& Tb2l = Propagate->GetTb2l();
1304     const FGMatrix33& Tl2b = Propagate->GetTl2b();
1305     const FGLocation& Location = Propagate->GetLocation();
1306     const FGMatrix33& Tec2l = Location.GetTec2l();
1307         
1308     double hook_area[4][3];
1309     
1310     FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1311     FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l *   hook_root_body);
1312     hook_area[1][0] = hook_root(1);
1313     hook_area[1][1] = hook_root(2);
1314     hook_area[1][2] = hook_root(3);
1315     
1316     hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1317     double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1318     double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1319     double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1320     double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1321     double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1322
1323     FGColumnVector3 hook_tip_body = hook_root_body;
1324     hook_tip_body(1) -= hook_length * cos_fi;
1325     hook_tip_body(3) += hook_length * sin_fi;    
1326     
1327     double contact[3];
1328     double ground_normal[3];
1329     double ground_vel[3];
1330     double ground_angular_vel[3];
1331     double root_agl_ft;
1332
1333     if (!got_wire) {
1334         bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1335                               ground_vel, ground_angular_vel, &root_agl_ft);
1336         if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1337             FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1338             FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1339             double D = -dot3(contact_body, ground_normal_body);
1340
1341             // check hook tip agl against same ground plane
1342             double hook_tip_agl_ft = dot3(hook_tip_body, ground_normal_body) + D;
1343             if (hook_tip_agl_ft < 0) {
1344
1345                 // hook tip: hx - l cos, hy, hz + l sin
1346                 // on ground:  - n0 l cos + n2 l sin + E = 0
1347
1348                 double E = D + dot3(hook_root_body, ground_normal_body);
1349
1350                 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1351                 // and rearrange to get a quadratic with coeffs:
1352                 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1353                 double b = 2 * E * ground_normal_body(3) * hook_length;
1354                 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);   
1355
1356                 double disc = sqr(b) - 4 * a * c;
1357                 if (disc >= 0) {
1358                     double delta = sqrt(disc) / (2 * a);
1359                 
1360                     // allow 4 solutions for safety, should never happen
1361                     double sin_fis[4];
1362                     double cos_fis[4];
1363                     double fis[4];
1364                     int points = 0;
1365                 
1366                     double sin_fi_guess = -b / (2 * a) - delta;
1367                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1368                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1369                 
1370                     if (points == 2) {
1371                         double diff1 = angle_diff(fi, fis[0]);
1372                         double diff2 = angle_diff(fi, fis[1]);
1373                         int point = diff1 < diff2 ? 0 : 1;
1374                         fi = fis[point];
1375                         sin_fi = sin_fis[point];
1376                         cos_fi = cos_fis[point];
1377                         hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1378                         hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1379                     }
1380                 }
1381             }
1382         }
1383     } else {
1384         FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() *  hook_root_body));
1385         double wire_ends_ec[2][3];
1386         double wire_vel_ec[2][3];
1387         get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1388         FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1389         FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1390         FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1391         if (rel_vel.Magnitude() < 3) {
1392             got_wire = false;
1393             release_wire();
1394             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1395         } else {
1396             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;
1397             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;
1398             FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1399             force_plane_normal.Normalize();
1400             cos_fi = dot3(force_plane_normal, FGColumnVector3(0, 0, 1));
1401             if (cos_fi < 0) cos_fi = -cos_fi;
1402             sin_fi = sqrt(1 - sqr(cos_fi));
1403             fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1404         
1405             fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1406             fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1407             fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1408             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1409         }
1410     }
1411
1412     FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1413
1414     hook_area[0][0] = hook_tip(1);
1415     hook_area[0][1] = hook_tip(2);
1416     hook_area[0][2] = hook_tip(3);
1417
1418     if (!got_wire) {
1419         // The previous positions.
1420         hook_area[2][0] = last_hook_root[0];
1421         hook_area[2][1] = last_hook_root[1];
1422         hook_area[2][2] = last_hook_root[2];
1423         hook_area[3][0] = last_hook_tip[0];
1424         hook_area[3][1] = last_hook_tip[1];
1425         hook_area[3][2] = last_hook_tip[2];
1426
1427         // Check if we caught a wire.
1428         // Returns true if we caught one.
1429         if (caught_wire_ft(t_off, hook_area)) {
1430                 got_wire = true;
1431         }
1432     }
1433     
1434     // save actual position as old position ...
1435     last_hook_tip[0] = hook_area[0][0];
1436     last_hook_tip[1] = hook_area[0][1];
1437     last_hook_tip[2] = hook_area[0][2];
1438     last_hook_root[0] = hook_area[1][0];
1439     last_hook_root[1] = hook_area[1][1];
1440     last_hook_root[2] = hook_area[1][2];
1441     
1442     fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);
1443 }
1444
1445
1446 void FGJSBsim::resetPropertyState()
1447 {
1448 // this code works-around bug #222:
1449 // http://code.google.com/p/flightgear-bugs/issues/detail?id=222
1450 // for whatever reason, having an existing value for the WOW
1451 // property causes the NaNs. Should that be fixed, this code can die
1452   SGPropertyNode* gear = fgGetNode("/fdm/jsbsim/gear", false);
1453   if (!gear) {
1454     return;
1455   }
1456   
1457   int index = 0;
1458   SGPropertyNode* unitNode = NULL;
1459   for (; (unitNode = gear->getChild("unit", index)) != NULL; ++index) {
1460     unitNode->removeChild("WOW", 0, false);
1461   }
1462 }
1463