]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
72faca87596fce5c7a55e3e58e0c0d8821d63ea4
[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 #include <simgear/compiler.h>
25
26 #ifdef SG_MATH_EXCEPTION_CLASH
27 #  include <math.h>
28 #endif
29
30 #include STL_STRING
31
32 #include <simgear/constants.h>
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/misc/sg_path.hxx>
36
37 #include <Scenery/scenery.hxx>
38
39 #include <Aircraft/aircraft.hxx>
40 #include <Controls/controls.hxx>
41 #include <Main/globals.hxx>
42 #include <Main/fg_props.hxx>
43
44 #include <FDM/JSBSim/FGFDMExec.h>
45 #include <FDM/JSBSim/FGAircraft.h>
46 #include <FDM/JSBSim/FGFCS.h>
47 #include <FDM/JSBSim/FGPosition.h>
48 #include <FDM/JSBSim/FGRotation.h>
49 #include <FDM/JSBSim/FGState.h>
50 #include <FDM/JSBSim/FGTranslation.h>
51 #include <FDM/JSBSim/FGAuxiliary.h>
52 #include <FDM/JSBSim/FGInitialCondition.h>
53 #include <FDM/JSBSim/FGTrim.h>
54 #include <FDM/JSBSim/FGAtmosphere.h>
55 #include <FDM/JSBSim/FGMassBalance.h>
56 #include <FDM/JSBSim/FGAerodynamics.h>
57 #include <FDM/JSBSim/FGLGear.h>
58 #include "JSBSim.hxx"
59
60 /******************************************************************************/
61
62 FGJSBsim::FGJSBsim( double dt ) 
63   : FGInterface(dt)
64 {
65     bool result;
66    
67     fdmex = new FGFDMExec;
68     
69     State           = fdmex->GetState();
70     Atmosphere      = fdmex->GetAtmosphere();
71     FCS             = fdmex->GetFCS();
72     MassBalance     = fdmex->GetMassBalance();
73     Propulsion      = fdmex->GetPropulsion();
74     Aircraft        = fdmex->GetAircraft();
75     Translation     = fdmex->GetTranslation();
76     Rotation        = fdmex->GetRotation();
77     Position        = fdmex->GetPosition();
78     Auxiliary       = fdmex->GetAuxiliary();
79     Aerodynamics    = fdmex->GetAerodynamics();
80     GroundReactions = fdmex->GetGroundReactions();  
81   
82     
83     Atmosphere->UseInternal();
84     
85     fgic=new FGInitialCondition(fdmex);
86     needTrim=true;
87   
88     SGPath aircraft_path( globals->get_fg_root() );
89     aircraft_path.append( "Aircraft" );
90
91     SGPath engine_path( globals->get_fg_root() );
92     engine_path.append( "Engine" );
93     set_delta_t( dt );
94     State->Setdt( dt );
95
96     result = fdmex->LoadModel( aircraft_path.str(),
97                                engine_path.str(),
98                                fgGetString("/sim/aero") );
99     
100     if (result) {
101       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
102     } else {
103       SG_LOG( SG_FLIGHT, SG_INFO,
104               "  aero does not exist (you may have mis-typed the name).");
105       throw(-1);
106     }
107
108     SG_LOG( SG_FLIGHT, SG_INFO, "" );
109     SG_LOG( SG_FLIGHT, SG_INFO, "" );
110     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
111
112     int Neng = Propulsion->GetNumEngines();
113     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
114     
115     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
116         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
117                 << GroundReactions->GetNumGearUnits() );
118         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
119          SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
120          SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
121          exit(-1);
122     }
123         
124     
125     init_gear();
126
127                                 // Set initial fuel levels if provided.
128     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
129       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
130       if (node->getChild("level-gal_us", 0, false) != 0)
131         Propulsion->GetTank(i)
132           ->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
133     }
134     
135     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
136     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
137     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
138     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
139
140     startup_trim = fgGetNode("/sim/startup/trim", true);
141
142     trimmed = fgGetNode("/fdm/trim/trimmed", true);
143     trimmed->setBoolValue(false);
144
145     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
146     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
147     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
148     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
149     
150     
151     stall_warning = fgGetNode("/sim/aero/alarms/stall-warning",true);
152     stall_warning->setDoubleValue(0);
153     
154     elevator_pos=fgGetNode("/surface-positions/elevator-pos-deg",true);
155     left_aileron_pos=fgGetNode("/surface-positions/left-aileron-pos-deg",true);
156     right_aileron_pos=fgGetNode("/surface-positions/right-aileron-pos-deg",true);
157     rudder_pos=fgGetNode("/surface-positions/rudder-pos-deg",true);
158     flap_pos=fgGetNode("/surface-positions/flap-pos-deg",true);
159     
160     elevator_pos->setDoubleValue(0);
161     left_aileron_pos->setDoubleValue(0);
162     right_aileron_pos->setDoubleValue(0);
163     rudder_pos->setDoubleValue(0);
164     flap_pos->setDoubleValue(0);
165
166 }
167 /******************************************************************************/
168 FGJSBsim::~FGJSBsim(void) {
169     if (fdmex != NULL) {
170         delete fdmex; fdmex=NULL;
171         delete fgic; fgic=NULL;
172     }  
173 }
174
175 /******************************************************************************/
176
177 // Initialize the JSBsim flight model, dt is the time increment for
178 // each subsequent iteration through the EOM
179
180 void FGJSBsim::init() {
181     
182     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
183    
184     // Explicitly call the superclass's
185     // init method first.
186     common_init();
187     copy_to_JSBsim();
188
189     fdmex->RunIC(fgic); //loop JSBSim once w/o integrating
190     copy_from_JSBsim(); //update the bus
191
192     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
193
194     switch(fgic->GetSpeedSet()) {
195     case setned:
196         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
197                << Position->GetVn() << ", "
198                << Position->GetVe() << ", "
199                << Position->GetVd() << " ft/s");
200     break;
201     case setuvw:
202         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
203                << Translation->GetUVW(1) << ", "
204                << Translation->GetUVW(2) << ", "
205                << Translation->GetUVW(3) << " ft/s");
206     break;
207     case setmach:
208         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
209                << Translation->GetMach() );
210     break;
211     case setvc:
212     default:
213         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
214                << Auxiliary->GetVcalibratedKTS() << " knots" );
215     break;
216     }
217     
218     stall_warning->setDoubleValue(0);
219     
220     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
221             <<  Rotation->Getphi()*RADTODEG << " deg" );
222     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
223             << Rotation->Gettht()*RADTODEG << " deg" );
224     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
225             << Rotation->Getpsi()*RADTODEG << " deg" );
226     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
227             << Position->GetLatitude() << " deg" );
228     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
229             << Position->GetLongitude() << " deg" );
230     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
231         << Position->Geth() << " feet" );
232     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
233
234     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
235
236     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
237     
238     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " << 
239                                   globals->get_controls()->get_gear_down() );
240     
241
242    
243 }
244
245 /******************************************************************************/
246
247 // Run an iteration of the EOM (equations of motion)
248
249 void
250 FGJSBsim::update( int multiloop ) {
251
252     int i;
253
254     // double save_alt = 0.0;
255
256     copy_to_JSBsim();
257
258     trimmed->setBoolValue(false);
259     
260
261     
262     if ( needTrim ) {
263       if ( startup_trim->getBoolValue() ) {
264         SG_LOG(SG_FLIGHT, SG_INFO,
265           "Ready to trim, terrain altitude is: " 
266             << scenery.get_cur_elev() * SG_METER_TO_FEET );
267         fgic->SetTerrainAltitudeFtIC( scenery.get_cur_elev() * SG_METER_TO_FEET );
268         do_trim();
269       } else {
270         fdmex->RunIC(fgic);  //apply any changes made through the set_ functions
271       }
272       needTrim = false;  
273     }    
274     
275     for ( i=0; i < multiloop; i++ ) {
276         fdmex->Run();
277     }
278
279     FGJSBBase::Message* msg;
280     while (fdmex->ReadMessage()) {
281       msg = fdmex->ProcessMessage();
282       switch (msg->type) {
283       case FGJSBBase::Message::eText:
284         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
285         break;
286       case FGJSBBase::Message::eBool:
287         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
288         break;
289       case FGJSBBase::Message::eInteger:
290         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
291         break;
292       case FGJSBBase::Message::eDouble:
293         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
294         break;
295       default:
296         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
297         break;
298       }
299     }
300
301     // translate JSBsim back to FG structure so that the
302     // autopilot (and the rest of the sim can use the updated values
303     copy_from_JSBsim();
304 }
305
306 /******************************************************************************/
307
308 // Convert from the FGInterface struct to the JSBsim generic_ struct
309
310 bool FGJSBsim::copy_to_JSBsim() {
311     unsigned int i;
312
313     // copy control positions into the JSBsim structure
314
315     FCS->SetDaCmd( globals->get_controls()->get_aileron());
316     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
317     FCS->SetDeCmd( globals->get_controls()->get_elevator());
318     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
319     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
320     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
321     FCS->SetDfCmd(  globals->get_controls()->get_flaps() );
322     FCS->SetDsbCmd( 0.0 ); //speedbrakes
323     FCS->SetDspCmd( 0.0 ); //spoilers
324     FCS->SetLBrake( globals->get_controls()->get_brake( 0 ) );
325     FCS->SetRBrake( globals->get_controls()->get_brake( 1 ) );
326     FCS->SetCBrake( globals->get_controls()->get_brake( 2 ) );
327     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
328     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
329       FGEngine * eng = Propulsion->GetEngine(i);
330       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
331       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
332       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
333       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
334       Propulsion->GetThruster(i)->SetRPM(node->getDoubleValue("rpm"));
335       eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
336       eng->SetStarter( globals->get_controls()->get_starter(i) );
337     }
338
339     _set_Runway_altitude( scenery.get_cur_elev() * SG_METER_TO_FEET );
340     Position->SetSeaLevelRadius( get_Sea_level_radius() );
341     Position->SetRunwayRadius( get_Runway_altitude() 
342                                + get_Sea_level_radius() );
343
344     Atmosphere->SetExTemperature(get_Static_temperature());
345     Atmosphere->SetExPressure(get_Static_pressure());
346     Atmosphere->SetExDensity(get_Density());
347     Atmosphere->SetWindNED(get_V_north_airmass(),
348                            get_V_east_airmass(),
349                            get_V_down_airmass());
350 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
351 //                  << get_V_north_airmass() << ", "
352 //                  << get_V_east_airmass()  << ", "
353 //                  << get_V_down_airmass() );
354
355     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
356       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
357       FGTank * tank = Propulsion->GetTank(i);
358       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
359 //       tank->SetContents(node->getDoubleValue("level-lb"));
360     }
361
362     return true;
363 }
364
365 /******************************************************************************/
366
367 // Convert from the JSBsim generic_ struct to the FGInterface struct
368
369 bool FGJSBsim::copy_from_JSBsim() {
370     unsigned int i, j;
371
372     _set_Inertias( MassBalance->GetMass(),
373                    MassBalance->GetIxx(),
374                    MassBalance->GetIyy(),
375                    MassBalance->GetIzz(),
376                    MassBalance->GetIxz() );
377
378     _set_CG_Position( MassBalance->GetXYZcg(1),
379                       MassBalance->GetXYZcg(2),
380                       MassBalance->GetXYZcg(3) );
381
382     _set_Accels_Body( Aircraft->GetBodyAccel()(1),
383                       Aircraft->GetBodyAccel()(2),
384                       Aircraft->GetBodyAccel()(3) );
385
386     //_set_Accels_CG_Body( Aircraft->GetBodyAccel()(1),
387     //                     Aircraft->GetBodyAccel()(2),
388     //                     Aircraft->GetBodyAccel()(3) );
389     //
390     _set_Accels_CG_Body_N ( Aircraft->GetNcg()(1),
391                             Aircraft->GetNcg()(2),
392                             Aircraft->GetNcg()(3) );
393     
394     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel()(1),
395                             Auxiliary->GetPilotAccel()(2),
396                             Auxiliary->GetPilotAccel()(3) );
397
398    // _set_Accels_Pilot_Body_N( Auxiliary->GetPilotAccel()(1)/32.1739,
399    //                           Auxiliary->GetNpilot(2)/32.1739,
400    //                           Auxiliary->GetNpilot(3)/32.1739 );
401
402     _set_Nlf( Aircraft->GetNlf() );
403
404     // Velocities
405
406     _set_Velocities_Local( Position->GetVn(),
407                            Position->GetVe(),
408                            Position->GetVd() );
409
410     _set_Velocities_Wind_Body( Translation->GetUVW(1),
411                                Translation->GetUVW(2),
412                                Translation->GetUVW(3) );
413
414     _set_V_rel_wind( Translation->GetVt() );
415
416     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
417
418     // _set_V_calibrated( Auxiliary->GetVcalibratedFPS() );
419
420     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
421
422     _set_V_ground_speed( Position->GetVground() );
423
424     _set_Omega_Body( Rotation->GetPQR(1),
425                      Rotation->GetPQR(2),
426                      Rotation->GetPQR(3) );
427
428     _set_Euler_Rates( Rotation->GetEulerRates(1),
429                       Rotation->GetEulerRates(2),
430                       Rotation->GetEulerRates(3) );
431
432     _set_Geocentric_Rates(Position->GetLatitudeDot(),
433                           Position->GetLongitudeDot(),
434                           Position->Gethdot() );
435
436     _set_Mach_number( Translation->GetMach() );
437
438     // Positions
439     _updateGeocentricPosition( Position->GetLatitude(),
440                                Position->GetLongitude(),
441                                Position->Geth() );
442
443     _set_Altitude_AGL( Position->GetDistanceAGL() );
444
445     _set_Euler_Angles( Rotation->Getphi(),
446                        Rotation->Gettht(),
447                        Rotation->Getpsi() );
448
449     _set_Alpha( Translation->Getalpha() );
450     _set_Beta( Translation->Getbeta() );
451
452
453     _set_Gamma_vert_rad( Position->GetGamma() );
454     // set_Gamma_horiz_rad( Gamma_horiz_rad );
455
456     _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
457
458     _set_Climb_Rate( Position->Gethdot() );
459
460
461     for ( i = 1; i <= 3; i++ ) {
462         for ( j = 1; j <= 3; j++ ) {
463             _set_T_Local_to_Body( i, j, State->GetTl2b(i,j) );
464         }
465     }
466
467                                 // Copy the engine values from JSBSim.
468     for( i=0; i < Propulsion->GetNumEngines(); i++ ) {
469       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
470       FGEngine * eng = Propulsion->GetEngine(i);
471       FGThruster * thrust = Propulsion->GetThruster(i);
472
473       node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
474       node->setDoubleValue("rpm", thrust->GetRPM());
475       node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
476       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
477       node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
478       node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
479       node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
480       node->setBoolValue("running", eng->GetRunning());
481       node->setBoolValue("cranking", eng->GetCranking());
482     }
483
484     static const SGPropertyNode *fuel_freeze
485         = fgGetNode("/sim/freeze/fuel");
486
487                                 // Copy the fuel levels from JSBSim if fuel
488                                 // freeze not enabled.
489     if ( ! fuel_freeze->getBoolValue() ) {
490         for (i = 0; i < Propulsion->GetNumTanks(); i++) {
491             SGPropertyNode * node
492                 = fgGetNode("/consumables/fuel/tank", i, true);
493             double contents = Propulsion->GetTank(i)->GetContents();
494             node->setDoubleValue("level-gal_us", contents/6.6);
495             // node->setDoubleValue("level-lb", contents);
496         }
497     }
498
499     update_gear();
500     
501     stall_warning->setDoubleValue( Aircraft->GetStallWarn() );
502     
503     elevator_pos->setDoubleValue( FCS->GetDePos()*SG_RADIANS_TO_DEGREES );
504     left_aileron_pos->setDoubleValue( FCS->GetDaPos()*SG_RADIANS_TO_DEGREES );
505     right_aileron_pos->setDoubleValue( -1*FCS->GetDaPos()*SG_RADIANS_TO_DEGREES );
506     rudder_pos->setDoubleValue( -1*FCS->GetDrPos()*SG_RADIANS_TO_DEGREES );
507     flap_pos->setDoubleValue( FCS->GetDfPos() );
508
509     
510     return true;
511 }
512
513 bool FGJSBsim::ToggleDataLogging(void) {
514     return fdmex->GetOutput()->Toggle();
515 }
516
517
518 bool FGJSBsim::ToggleDataLogging(bool state) {
519     if (state) {
520       fdmex->GetOutput()->Enable();
521       return true;
522     } else {
523       fdmex->GetOutput()->Disable();
524       return false;
525     }
526 }
527
528
529 //Positions
530 void FGJSBsim::set_Latitude(double lat) {
531     static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
532     double alt;
533     double sea_level_radius_meters, lat_geoc;
534     
535     if ( altitude->getDoubleValue() > -9990 ) {
536       alt = altitude->getDoubleValue();
537     } else {
538       alt = 0.0;
539     }
540    
541     update_ic();
542     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
543     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
544
545     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER, 
546                       &sea_level_radius_meters, &lat_geoc );
547     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
548     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );    
549     _set_Runway_altitude(  scenery.get_cur_elev() * SG_METER_TO_FEET  );
550     fgic->SetTerrainAltitudeFtIC( scenery.get_cur_elev() * SG_METER_TO_FEET  );
551     fgic->SetLatitudeRadIC( lat_geoc );
552     needTrim=true;
553 }
554
555 void FGJSBsim::set_Longitude(double lon) {
556
557     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
558     update_ic();
559     fgic->SetLongitudeRadIC( lon );
560     _set_Runway_altitude( scenery.get_cur_elev() * SG_METER_TO_FEET  );
561     fgic->SetTerrainAltitudeFtIC( scenery.get_cur_elev() * SG_METER_TO_FEET  );
562     needTrim=true;
563 }
564
565 void FGJSBsim::set_Altitude(double alt) {
566     static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
567
568     double sea_level_radius_meters,lat_geoc;
569
570     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
571     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
572     
573     update_ic();
574     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
575                   &sea_level_radius_meters, &lat_geoc);
576     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
577     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
578     _set_Runway_altitude( scenery.get_cur_elev() * SG_METER_TO_FEET  );
579     fgic->SetTerrainAltitudeFtIC( scenery.get_cur_elev() * SG_METER_TO_FEET  );
580     SG_LOG(SG_FLIGHT, SG_INFO,
581           "Terrain altitude: " << scenery.get_cur_elev() * SG_METER_TO_FEET );
582     fgic->SetLatitudeRadIC( lat_geoc );
583     fgic->SetAltitudeFtIC(alt);
584     needTrim=true;
585 }
586
587 void FGJSBsim::set_V_calibrated_kts(double vc) {
588     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
589     
590     update_ic();
591     fgic->SetVcalibratedKtsIC(vc);
592     needTrim=true;
593 }
594
595 void FGJSBsim::set_Mach_number(double mach) {
596     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
597     
598     update_ic();
599     fgic->SetMachIC(mach);
600     needTrim=true;
601 }
602
603 void FGJSBsim::set_Velocities_Local( double north, double east, double down ){
604     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
605        << north << ", " <<  east << ", " << down );
606     
607     update_ic();
608     fgic->SetVnorthFpsIC(north);
609     fgic->SetVeastFpsIC(east);
610     fgic->SetVdownFpsIC(down);
611     needTrim=true;
612 }
613
614 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w){
615     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
616        << u << ", " <<  v << ", " <<  w );
617     
618     update_ic();
619     fgic->SetUBodyFpsIC(u);
620     fgic->SetVBodyFpsIC(v);
621     fgic->SetWBodyFpsIC(w);
622     needTrim=true;
623 }
624
625 //Euler angles
626 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi ) {
627     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
628        << phi << ", " << theta << ", " << psi );
629     
630     update_ic();
631     fgic->SetPitchAngleRadIC(theta);
632     fgic->SetRollAngleRadIC(phi);
633     fgic->SetTrueHeadingRadIC(psi);
634     needTrim=true;
635 }
636
637 //Flight Path
638 void FGJSBsim::set_Climb_Rate( double roc) {
639     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
640     
641     update_ic();
642     //since both climb rate and flight path angle are set in the FG
643     //startup sequence, something is needed to keep one from cancelling
644     //out the other.
645     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
646       fgic->SetClimbRateFpsIC(roc);
647     }  
648     needTrim=true;
649 }
650
651 void FGJSBsim::set_Gamma_vert_rad( double gamma) {
652     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
653     
654     update_ic();
655     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
656       fgic->SetFlightPathAngleRadIC(gamma);
657     }  
658     needTrim=true;
659 }
660
661 void FGJSBsim::set_Static_pressure(double p) {
662     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Static_pressure: " << p );
663     
664     update_ic();
665     Atmosphere->SetExPressure(p);
666     if(Atmosphere->External() == true)
667       needTrim=true;
668 }
669
670 void FGJSBsim::set_Static_temperature(double T) {
671     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Static_temperature: " << T );
672     
673     Atmosphere->SetExTemperature(T);
674     if(Atmosphere->External() == true)
675       needTrim=true;
676 }
677  
678
679 void FGJSBsim::set_Density(double rho) {
680     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Density: " << rho );
681     
682     Atmosphere->SetExDensity(rho);
683     if(Atmosphere->External() == true)
684       needTrim=true;
685 }
686   
687 void FGJSBsim::set_Velocities_Local_Airmass (double wnorth, 
688                          double weast, 
689                          double wdown ) {
690     //SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local_Airmass: " 
691     //   << wnorth << ", " << weast << ", " << wdown );
692     
693     _set_Velocities_Local_Airmass( wnorth, weast, wdown );
694     fgic->SetWindNEDFpsIC( wnorth, weast, wdown );
695     if(Atmosphere->External() == true)
696         needTrim=true;
697 }     
698
699 void FGJSBsim::init_gear(void ) {
700     
701     FGGroundReactions* gr=fdmex->GetGroundReactions();
702     int Ngear=GroundReactions->GetNumGearUnits();
703     for (int i=0;i<Ngear;i++) {
704       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
705       node->setDoubleValue("xoffset-in",
706                            gr->GetGearUnit(i)->GetBodyLocation()(1));
707       node->setDoubleValue("yoffset-in",
708                            gr->GetGearUnit(i)->GetBodyLocation()(2));
709       node->setDoubleValue("zoffset-in",
710                            gr->GetGearUnit(i)->GetBodyLocation()(3));
711       node->setBoolValue("wow", gr->GetGearUnit(i)->GetWOW());
712       node->setBoolValue("has-brake", gr->GetGearUnit(i)->GetBrakeGroup() > 0);
713       node->setDoubleValue("position", FCS->GetGearPos());
714     }  
715 }
716
717 void FGJSBsim::update_gear(void) {
718     
719     FGGroundReactions* gr=fdmex->GetGroundReactions();
720     int Ngear=GroundReactions->GetNumGearUnits();
721     for (int i=0;i<Ngear;i++) {
722       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
723       node->getChild("wow", 0, true)
724         ->setBoolValue(gr->GetGearUnit(i)->GetWOW());
725       node->getChild("position", 0, true)
726         ->setDoubleValue(FCS->GetGearPos());
727     }  
728 }
729
730 void FGJSBsim::do_trim(void) {
731
732         FGTrim *fgtrim;
733         if(fgic->GetVcalibratedKtsIC() < 10 ) {
734             fgic->SetVcalibratedKtsIC(0.0);
735             fgtrim=new FGTrim(fdmex,fgic,tGround);
736         } else {
737             fgtrim=new FGTrim(fdmex,fgic,tLongitudinal);
738         }
739         if( !fgtrim->DoTrim() ) {
740             fgtrim->Report();
741             fgtrim->TrimStats();
742         } else {
743             trimmed->setBoolValue(true);
744         }
745         State->ReportState();
746         delete fgtrim;
747         pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
748         throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
749         aileron_trim->setDoubleValue( FCS->GetDaCmd() );
750         rudder_trim->setDoubleValue( FCS->GetDrCmd() );
751
752         globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
753         globals->get_controls()->set_elevator(FCS->GetDeCmd());
754         globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
755                                               FCS->GetThrottleCmd(0));
756
757         globals->get_controls()->set_aileron(FCS->GetDaCmd());
758         globals->get_controls()->set_rudder( FCS->GetDrCmd());
759     
760         SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
761 }          
762
763 void FGJSBsim::update_ic(void) {       
764    if( !needTrim ) {
765      fgic->SetLatitudeRadIC(get_Lat_geocentric() );       
766      fgic->SetLongitudeRadIC( get_Longitude() );       
767      fgic->SetAltitudeFtIC( get_Altitude() );       
768      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );       
769      fgic->SetPitchAngleRadIC( get_Theta() );       
770      fgic->SetRollAngleRadIC( get_Phi() );       
771      fgic->SetTrueHeadingRadIC( get_Psi() );       
772      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
773    }  
774 }