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