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