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