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