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