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