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