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