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