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