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