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