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