]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/FGFDMExec.cpp
Merge branch 'next' of git://gitorious.org/fg/flightgear
[flightgear.git] / src / FDM / JSBSim / FGFDMExec.cpp
1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2
3  Module:       FGFDMExec.cpp
4  Author:       Jon S. Berndt
5  Date started: 11/17/98
6  Purpose:      Schedules and runs the model routines.
7
8  ------------- Copyright (C) 1999  Jon S. Berndt (jon@jsbsim.org) -------------
9
10  This program is free software; you can redistribute it and/or modify it under
11  the terms of the GNU Lesser General Public License as published by the Free Software
12  Foundation; either version 2 of the License, or (at your option) any later
13  version.
14
15  This program is distributed in the hope that it will be useful, but WITHOUT
16  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
18  details.
19
20  You should have received a copy of the GNU Lesser General Public License along with
21  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
22  Place - Suite 330, Boston, MA  02111-1307, USA.
23
24  Further information about the GNU Lesser General Public License can also be found on
25  the world wide web at http://www.gnu.org.
26
27 FUNCTIONAL DESCRIPTION
28 --------------------------------------------------------------------------------
29
30 This class wraps up the simulation scheduling routines.
31
32 HISTORY
33 --------------------------------------------------------------------------------
34 11/17/98   JSB   Created
35
36 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
37 COMMENTS, REFERENCES,  and NOTES
38 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
39
40 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41 INCLUDES
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
43
44 #include "FGFDMExec.h"
45 #include "models/FGAtmosphere.h"
46 #include "models/atmosphere/FGMSIS.h"
47 #include "models/atmosphere/FGMars.h"
48 #include "models/FGFCS.h"
49 #include "models/FGPropulsion.h"
50 #include "models/FGMassBalance.h"
51 #include "models/FGGroundReactions.h"
52 #include "models/FGExternalReactions.h"
53 #include "models/FGBuoyantForces.h"
54 #include "models/FGAerodynamics.h"
55 #include "models/FGInertial.h"
56 #include "models/FGAircraft.h"
57 #include "models/FGPropagate.h"
58 #include "models/FGAuxiliary.h"
59 #include "models/FGInput.h"
60 #include "models/FGOutput.h"
61 #include "initialization/FGInitialCondition.h"
62 //#include "initialization/FGTrimAnalysis.h" // Remove until later
63 #include "input_output/FGPropertyManager.h"
64 #include "input_output/FGScript.h"
65
66 #include <iostream>
67 #include <iterator>
68 #include <cstdlib>
69
70 using namespace std;
71
72 namespace JSBSim {
73
74 static const char *IdSrc = "$Id: FGFDMExec.cpp,v 1.91 2011/04/05 20:20:21 andgi Exp $";
75 static const char *IdHdr = ID_FDMEXEC;
76
77 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
78 CLASS IMPLEMENTATION
79 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
80
81 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82 // Constructor
83
84 FGFDMExec::FGFDMExec(FGPropertyManager* root, unsigned int* fdmctr) : Root(root), FDMctr(fdmctr)
85 {
86
87   Frame           = 0;
88   Error           = 0;
89   GroundCallback  = 0;
90   Atmosphere      = 0;
91   FCS             = 0;
92   Propulsion      = 0;
93   MassBalance     = 0;
94   Aerodynamics    = 0;
95   Inertial        = 0;
96   GroundReactions = 0;
97   ExternalReactions = 0;
98   BuoyantForces   = 0;
99   Aircraft        = 0;
100   Propagate       = 0;
101   Auxiliary       = 0;
102   Input           = 0;
103   IC              = 0;
104   Trim            = 0;
105   Script          = 0;
106
107   RootDir = "";
108
109   modelLoaded = false;
110   IsChild = false;
111   holding = false;
112   Terminate = false;
113   StandAlone = false;
114
115   sim_time = 0.0;
116   dT = 1.0/120.0; // a default timestep size. This is needed for when JSBSim is
117                   // run in standalone mode with no initialization file.
118
119   AircraftPath = "aircraft";
120   EnginePath = "engine";
121   SystemsPath = "systems";
122
123   try {
124     char* num = getenv("JSBSIM_DEBUG");
125     if (num) debug_lvl = atoi(num); // set debug level
126   } catch (...) {                   // if error set to 1
127     debug_lvl = 1;
128   }
129
130   if (Root == 0) {                 // Then this is the root FDM
131     Root = new FGPropertyManager;  // Create the property manager
132     StandAlone = true;
133   }
134
135   if (FDMctr == 0) {
136     FDMctr = new unsigned int;     // Create and initialize the child FDM counter
137     (*FDMctr) = 0;
138   }
139
140   // Store this FDM's ID
141   IdFDM = (*FDMctr); // The main (parent) JSBSim instance is always the "zeroth"
142                                                                       
143   // Prepare FDMctr for the next child FDM id
144   (*FDMctr)++;       // instance. "child" instances are loaded last.
145
146   instance = Root->GetNode("/fdm/jsbsim",IdFDM,true);
147   Debug(0);
148   // this is to catch errors in binding member functions to the property tree.
149   try {
150     Allocate();
151   } catch ( string msg ) {
152     cout << "Caught error: " << msg << endl;
153     exit(1);
154   }
155
156   trim_status = false;
157   ta_mode     = 99;
158
159   Constructing = true;
160   typedef int (FGFDMExec::*iPMF)(void) const;
161 //  instance->Tie("simulation/do_trim_analysis", this, (iPMF)0, &FGFDMExec::DoTrimAnalysis, false);
162   instance->Tie("simulation/do_simple_trim", this, (iPMF)0, &FGFDMExec::DoTrim, false);
163   instance->Tie("simulation/reset", this, (iPMF)0, &FGFDMExec::ResetToInitialConditions, false);
164   instance->Tie("simulation/terminate", (int *)&Terminate);
165   instance->Tie("simulation/sim-time-sec", this, &FGFDMExec::GetSimTime);
166   instance->Tie("simulation/jsbsim-debug", this, &FGFDMExec::GetDebugLevel, &FGFDMExec::SetDebugLevel);
167   instance->Tie("simulation/frame", (int *)&Frame, false);
168
169   Constructing = false;
170 }
171
172 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
173
174 FGFDMExec::~FGFDMExec()
175 {
176   try {
177     Unbind();
178     DeAllocate();
179     
180     if (IdFDM == 0) { // Meaning this is no child FDM
181       if(Root != 0) {
182          if(StandAlone)
183             delete Root;
184          Root = 0;
185       }
186       if(FDMctr != 0) {
187          delete FDMctr;
188          FDMctr = 0;
189       }
190     }
191   } catch ( string msg ) {
192     cout << "Caught error: " << msg << endl;
193   }
194
195   for (unsigned int i=1; i<ChildFDMList.size(); i++) delete ChildFDMList[i]->exec;
196   ChildFDMList.clear();
197
198   PropertyCatalog.clear();
199
200   FDMctr--;
201
202   Debug(1);
203 }
204
205 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
206
207 bool FGFDMExec::Allocate(void)
208 {
209   bool result=true;
210
211   Atmosphere      = new FGAtmosphere(this);
212   FCS             = new FGFCS(this);
213   Propulsion      = new FGPropulsion(this);
214   MassBalance     = new FGMassBalance(this);
215   Aerodynamics    = new FGAerodynamics (this);
216   Inertial        = new FGInertial(this);
217
218   GroundCallback  = new FGGroundCallback(Inertial->GetRefRadius());
219
220   GroundReactions = new FGGroundReactions(this);
221   ExternalReactions = new FGExternalReactions(this);
222   BuoyantForces   = new FGBuoyantForces(this);
223   Aircraft        = new FGAircraft(this);
224   Propagate       = new FGPropagate(this);
225   Auxiliary       = new FGAuxiliary(this);
226   Input           = new FGInput(this);
227
228   // Schedule a model. The second arg (the integer) is the pass number. For
229   // instance, the atmosphere model could get executed every fifth pass it is called.
230   
231   Schedule(Input,           1);
232   Schedule(Atmosphere,      1);
233   Schedule(FCS,             1);
234   Schedule(Propulsion,      1);
235   Schedule(MassBalance,     1);
236   Schedule(Aerodynamics,    1);
237   Schedule(Inertial,        1);
238   Schedule(GroundReactions, 1);
239   Schedule(ExternalReactions, 1);
240   Schedule(BuoyantForces,   1);
241   Schedule(Aircraft,        1);
242   Schedule(Propagate,       1);
243   Schedule(Auxiliary,       1);
244
245   // Initialize models so they can communicate with each other
246
247   vector <FGModel*>::iterator it;
248   for (it = Models.begin(); it != Models.end(); ++it) (*it)->InitModel();
249
250   IC = new FGInitialCondition(this);
251
252   modelLoaded = false;
253
254   return result;
255 }
256
257 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
258
259 bool FGFDMExec::DeAllocate(void)
260 {
261   delete Input;
262   delete Atmosphere;
263   delete FCS;
264   delete Propulsion;
265   delete MassBalance;
266   delete Aerodynamics;
267   delete Inertial;
268   delete GroundReactions;
269   delete ExternalReactions;
270   delete BuoyantForces;
271   delete Aircraft;
272   delete Propagate;
273   delete Auxiliary;
274   delete Script;
275
276   for (unsigned i=0; i<Outputs.size(); i++) delete Outputs[i];
277   Outputs.clear();
278
279   delete IC;
280   delete Trim;
281
282   delete GroundCallback;
283
284   Error       = 0;
285
286   Input           = 0;
287   Atmosphere      = 0;
288   FCS             = 0;
289   Propulsion      = 0;
290   MassBalance     = 0;
291   Aerodynamics    = 0;
292   Inertial        = 0;
293   GroundReactions = 0;
294   ExternalReactions = 0;
295   BuoyantForces   = 0;
296   Aircraft        = 0;
297   Propagate       = 0;
298   Auxiliary       = 0;
299   Script          = 0;
300
301   Models.clear();
302
303   modelLoaded = false;
304   return modelLoaded;
305 }
306
307 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
308
309 void FGFDMExec::Schedule(FGModel* model, int rate)
310 {
311   model->SetRate(rate);
312   Models.push_back(model);
313 }
314
315 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
316
317 bool FGFDMExec::Run(void)
318 {
319   bool success=true;
320
321   Debug(2);
322
323   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
324     ChildFDMList[i]->AssignState(Propagate); // Transfer state to the child FDM
325     ChildFDMList[i]->Run();
326   }
327
328   // returns true if success, false if complete
329   if (Script != 0 && !IntegrationSuspended()) success = Script->RunScript();
330
331   vector <FGModel*>::iterator it;
332   for (it = Models.begin(); it != Models.end(); ++it) (*it)->Run();
333
334   Frame++;
335   if (!Holding()) IncrTime();
336   if (Terminate) success = false;
337
338   return (success);
339 }
340
341 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
342 // This call will cause the sim time to reset to 0.0
343
344 bool FGFDMExec::RunIC(void)
345 {
346   SuspendIntegration(); // saves the integration rate, dt, then sets it to 0.0.
347   Initialize(IC);
348   Run();
349   ResumeIntegration(); // Restores the integration rate to what it was.
350
351   return true;
352 }
353
354 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
355
356 void FGFDMExec::Initialize(FGInitialCondition *FGIC)
357 {
358   Setsim_time(0.0);
359
360   Propagate->SetInitialState( FGIC );
361
362   Atmosphere->Run();
363   Atmosphere->SetWindNED( FGIC->GetWindNFpsIC(),
364                           FGIC->GetWindEFpsIC(),
365                           FGIC->GetWindDFpsIC() );
366
367   FGColumnVector3 vAeroUVW;
368
369   //ToDo: move this to the Auxiliary class !?
370
371   vAeroUVW = Propagate->GetUVW() + Propagate->GetTl2b()*Atmosphere->GetTotalWindNED();
372
373   double alpha, beta;
374   if (vAeroUVW(eW) != 0.0)
375     alpha = vAeroUVW(eU)*vAeroUVW(eU) > 0.0 ? atan2(vAeroUVW(eW), vAeroUVW(eU)) : 0.0;
376   else
377     alpha = 0.0;
378   if (vAeroUVW(eV) != 0.0)
379     beta = vAeroUVW(eU)*vAeroUVW(eU)+vAeroUVW(eW)*vAeroUVW(eW) > 0.0 ? atan2(vAeroUVW(eV), (fabs(vAeroUVW(eU))/vAeroUVW(eU))*sqrt(vAeroUVW(eU)*vAeroUVW(eU) + vAeroUVW(eW)*vAeroUVW(eW))) : 0.0;
380   else
381     beta = 0.0;
382
383   Auxiliary->SetAB(alpha, beta);
384
385   double Vt = vAeroUVW.Magnitude();
386   Auxiliary->SetVt(Vt);
387
388   Auxiliary->SetMach(Vt/Atmosphere->GetSoundSpeed());
389
390   double qbar = 0.5*Vt*Vt*Atmosphere->GetDensity();
391   Auxiliary->Setqbar(qbar);
392 }
393
394 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
395 //
396 // A private, internal function call for Tie-ing to a property, so it needs an
397 // argument.
398
399 void FGFDMExec::ResetToInitialConditions(int mode)
400 {
401   if (mode == 1) {
402     for (unsigned int i=0; i<Outputs.size(); i++) {
403       Outputs[i]->SetStartNewFile(true); 
404     }
405   }
406   
407   ResetToInitialConditions();
408 }
409
410 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
411
412 void FGFDMExec::ResetToInitialConditions(void)
413 {
414   if (Constructing) return;
415
416   vector <FGModel*>::iterator it;
417   for (it = Models.begin(); it != Models.end(); ++it) (*it)->InitModel();
418
419   RunIC();
420   if (Script) Script->ResetEvents();
421 }
422
423 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
424
425 void FGFDMExec::SetGroundCallback(FGGroundCallback* p)
426 {
427   delete GroundCallback;
428   GroundCallback = p;
429 }
430
431 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
432
433 vector <string> FGFDMExec::EnumerateFDMs(void)
434 {
435   vector <string> FDMList;
436
437   FDMList.push_back(Aircraft->GetAircraftName());
438
439   for (unsigned int i=1; i<ChildFDMList.size(); i++) {
440     FDMList.push_back(ChildFDMList[i]->exec->GetAircraft()->GetAircraftName());
441   }
442
443   return FDMList;
444 }
445
446 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
447
448 bool FGFDMExec::LoadScript(const string& script, double deltaT)
449 {
450   bool result;
451
452   Script = new FGScript(this);
453   result = Script->LoadScript(RootDir + script, deltaT);
454
455   return result;
456 }
457
458 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
459
460 bool FGFDMExec::LoadModel(const string& AircraftPath, const string& EnginePath, const string& SystemsPath,
461                 const string& model, bool addModelToPath)
462 {
463   FGFDMExec::AircraftPath = RootDir + AircraftPath;
464   FGFDMExec::EnginePath = RootDir + EnginePath;
465   FGFDMExec::SystemsPath = RootDir + SystemsPath;
466
467   return LoadModel(model, addModelToPath);
468 }
469
470 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
471
472 bool FGFDMExec::LoadModel(const string& model, bool addModelToPath)
473 {
474   string token;
475   string aircraftCfgFileName;
476   Element* element = 0L;
477   bool result = false; // initialize result to false, indicating input file not yet read
478
479   modelName = model; // Set the class modelName attribute
480
481   if( AircraftPath.empty() || EnginePath.empty() || SystemsPath.empty()) {
482     cerr << "Error: attempted to load aircraft with undefined ";
483     cerr << "aircraft, engine, and system paths" << endl;
484     return false;
485   }
486
487   FullAircraftPath = AircraftPath;
488   if (addModelToPath) FullAircraftPath += "/" + model;
489   aircraftCfgFileName = FullAircraftPath + "/" + model + ".xml";
490
491   if (modelLoaded) {
492     DeAllocate();
493     Allocate();
494   }
495
496   int saved_debug_lvl = debug_lvl;
497
498   document = LoadXMLDocument(aircraftCfgFileName); // "document" is a class member
499   if (document) {
500     if (IsChild) debug_lvl = 0;
501
502     ReadPrologue(document);
503
504     if (IsChild) debug_lvl = saved_debug_lvl;
505
506     // Process the fileheader element in the aircraft config file. This element is OPTIONAL.
507     element = document->FindElement("fileheader");
508     if (element) {
509       result = ReadFileHeader(element);
510       if (!result) {
511         cerr << endl << "Aircraft fileheader element has problems in file " << aircraftCfgFileName << endl;
512         return result;
513       }
514     }
515
516     if (IsChild) debug_lvl = 0;
517
518     // Process the metrics element. This element is REQUIRED.
519     element = document->FindElement("metrics");
520     if (element) {
521       result = Aircraft->Load(element);
522       if (!result) {
523         cerr << endl << "Aircraft metrics element has problems in file " << aircraftCfgFileName << endl;
524         return result;
525       }
526     } else {
527       cerr << endl << "No metrics element was found in the aircraft config file." << endl;
528       return false;
529     }
530
531     // Process the mass_balance element. This element is REQUIRED.
532     element = document->FindElement("mass_balance");
533     if (element) {
534       result = MassBalance->Load(element);
535       if (!result) {
536         cerr << endl << "Aircraft mass_balance element has problems in file " << aircraftCfgFileName << endl;
537         return result;
538       }
539     } else {
540       cerr << endl << "No mass_balance element was found in the aircraft config file." << endl;
541       return false;
542     }
543
544     // Process the ground_reactions element. This element is REQUIRED.
545     element = document->FindElement("ground_reactions");
546     if (element) {
547       result = GroundReactions->Load(element);
548       if (!result) {
549         cerr << endl << "Aircraft ground_reactions element has problems in file " << aircraftCfgFileName << endl;
550         return result;
551       }
552     } else {
553       cerr << endl << "No ground_reactions element was found in the aircraft config file." << endl;
554       return false;
555     }
556
557     // Process the external_reactions element. This element is OPTIONAL.
558     element = document->FindElement("external_reactions");
559     if (element) {
560       result = ExternalReactions->Load(element);
561       if (!result) {
562         cerr << endl << "Aircraft external_reactions element has problems in file " << aircraftCfgFileName << endl;
563         return result;
564       }
565     }
566
567     // Process the buoyant_forces element. This element is OPTIONAL.
568     element = document->FindElement("buoyant_forces");
569     if (element) {
570       result = BuoyantForces->Load(element);
571       if (!result) {
572         cerr << endl << "Aircraft buoyant_forces element has problems in file " << aircraftCfgFileName << endl;
573         return result;
574       }
575     }
576
577     // Process the propulsion element. This element is OPTIONAL.
578     element = document->FindElement("propulsion");
579     if (element) {
580       result = Propulsion->Load(element);
581       if (!result) {
582         cerr << endl << "Aircraft propulsion element has problems in file " << aircraftCfgFileName << endl;
583         return result;
584       }
585     }
586
587     // Process the system element[s]. This element is OPTIONAL, and there may be more than one.
588     element = document->FindElement("system");
589     while (element) {
590       result = FCS->Load(element, FGFCS::stSystem);
591       if (!result) {
592         cerr << endl << "Aircraft system element has problems in file " << aircraftCfgFileName << endl;
593         return result;
594       }
595       element = document->FindNextElement("system");
596     }
597
598     // Process the autopilot element. This element is OPTIONAL.
599     element = document->FindElement("autopilot");
600     if (element) {
601       result = FCS->Load(element, FGFCS::stAutoPilot);
602       if (!result) {
603         cerr << endl << "Aircraft autopilot element has problems in file " << aircraftCfgFileName << endl;
604         return result;
605       }
606     }
607
608     // Process the flight_control element. This element is OPTIONAL.
609     element = document->FindElement("flight_control");
610     if (element) {
611       result = FCS->Load(element, FGFCS::stFCS);
612       if (!result) {
613         cerr << endl << "Aircraft flight_control element has problems in file " << aircraftCfgFileName << endl;
614         return result;
615       }
616     }
617
618     // Process the aerodynamics element. This element is OPTIONAL, but almost always expected.
619     element = document->FindElement("aerodynamics");
620     if (element) {
621       result = Aerodynamics->Load(element);
622       if (!result) {
623         cerr << endl << "Aircraft aerodynamics element has problems in file " << aircraftCfgFileName << endl;
624         return result;
625       }
626     } else {
627       cerr << endl << "No expected aerodynamics element was found in the aircraft config file." << endl;
628     }
629
630     // Process the input element. This element is OPTIONAL.
631     element = document->FindElement("input");
632     if (element) {
633       result = Input->Load(element);
634       if (!result) {
635         cerr << endl << "Aircraft input element has problems in file " << aircraftCfgFileName << endl;
636         return result;
637       }
638     }
639
640     // Process the output element[s]. This element is OPTIONAL, and there may be more than one.
641     unsigned int idx=0;
642     typedef double (FGOutput::*iOPMF)(void) const;
643     typedef int (FGFDMExec::*iOPV)(void) const;
644     typedef void (FGFDMExec::*vOPI)(int) const;
645     element = document->FindElement("output");
646     while (element) {
647       if (debug_lvl > 0) cout << endl << "  Output data set: " << idx << "  ";
648       FGOutput* Output = new FGOutput(this);
649       Output->InitModel();
650       Schedule(Output, 1);
651       result = Output->Load(element);
652       if (!result) {
653         cerr << endl << "Aircraft output element has problems in file " << aircraftCfgFileName << endl;
654         return result;
655       } else {
656         Outputs.push_back(Output);
657         string outputProp = CreateIndexedPropertyName("simulation/output",idx);
658         instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate, false);
659         instance->Tie("simulation/force-output", this, (iOPV)0, &FGFDMExec::ForceOutput, false);
660         idx++;
661       }
662       element = document->FindNextElement("output");
663     }
664
665     // Lastly, process the child element. This element is OPTIONAL - and NOT YET SUPPORTED.
666     element = document->FindElement("child");
667     if (element) {
668       result = ReadChild(element);
669       if (!result) {
670         cerr << endl << "Aircraft child element has problems in file " << aircraftCfgFileName << endl;
671         return result;
672       }
673     }
674
675     modelLoaded = true;
676
677     if (debug_lvl > 0) {
678       MassBalance->Run(); // Update all mass properties for the report.
679       MassBalance->GetMassPropertiesReport();
680
681       cout << endl << fgblue << highint
682            << "End of vehicle configuration loading." << endl
683            << "-------------------------------------------------------------------------------"
684            << reset << endl;
685     }
686     
687     if (IsChild) debug_lvl = saved_debug_lvl;
688
689   } else {
690     cerr << fgred
691          << "  JSBSim failed to open the configuration file: " << aircraftCfgFileName
692          << fgdef << endl;
693   }
694
695   if (result) {
696     struct PropertyCatalogStructure masterPCS;
697     masterPCS.base_string = "";
698     masterPCS.node = (FGPropertyManager*)Root;
699     BuildPropertyCatalog(&masterPCS);
700   }
701
702   return result;
703 }
704
705 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
706
707 void FGFDMExec::BuildPropertyCatalog(struct PropertyCatalogStructure* pcs)
708 {
709   struct PropertyCatalogStructure* pcsNew = new struct PropertyCatalogStructure;
710   int node_idx = 0;
711
712   for (int i=0; i<pcs->node->nChildren(); i++) {
713     pcsNew->base_string = pcs->base_string + "/" + pcs->node->getChild(i)->getName();
714     node_idx = pcs->node->getChild(i)->getIndex();
715     if (node_idx != 0) {
716       pcsNew->base_string = CreateIndexedPropertyName(pcsNew->base_string, node_idx);
717     }
718     if (pcs->node->getChild(i)->nChildren() == 0) {
719       if (pcsNew->base_string.substr(0,11) == string("/fdm/jsbsim")) {
720         pcsNew->base_string = pcsNew->base_string.erase(0,12);
721       }
722       PropertyCatalog.push_back(pcsNew->base_string);
723     } else {
724       pcsNew->node = (FGPropertyManager*)pcs->node->getChild(i);
725       BuildPropertyCatalog(pcsNew);
726     }
727   }
728   delete pcsNew;
729 }
730
731 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
732
733 string FGFDMExec::QueryPropertyCatalog(const string& in)
734 {
735   string results="";
736   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
737     if (PropertyCatalog[i].find(in) != string::npos) results += PropertyCatalog[i] + "\n";
738   }
739   if (results.empty()) return "No matches found\n";
740   return results;
741 }
742
743 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
744
745 void FGFDMExec::PrintPropertyCatalog(void)
746 {
747   cout << endl;
748   cout << "  " << fgblue << highint << underon << "Property Catalog for "
749        << modelName << reset << endl << endl;
750   for (unsigned i=0; i<PropertyCatalog.size(); i++) {
751     cout << "    " << PropertyCatalog[i] << endl;
752   }
753 }
754
755 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
756
757 bool FGFDMExec::ReadFileHeader(Element* el)
758 {
759   bool result = true; // true for success
760
761   if (debug_lvl == 0) return result;
762
763   if (IsChild) {
764     cout << endl <<highint << fgblue << "Reading child model: " << IdFDM << reset << endl << endl;
765   }
766
767   if (el->FindElement("description"))
768     cout << "  Description:   " << el->FindElement("description")->GetDataLine() << endl;
769   if (el->FindElement("author"))
770     cout << "  Model Author:  " << el->FindElement("author")->GetDataLine() << endl;
771   if (el->FindElement("filecreationdate"))
772     cout << "  Creation Date: " << el->FindElement("filecreationdate")->GetDataLine() << endl;
773   if (el->FindElement("version"))
774     cout << "  Version:       " << el->FindElement("version")->GetDataLine() << endl;
775
776   return result;
777 }
778
779 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
780
781 bool FGFDMExec::ReadPrologue(Element* el) // el for ReadPrologue is the document element
782 {
783   bool result = true; // true for success
784
785   if (!el) return false;
786
787   string AircraftName = el->GetAttributeValue("name");
788   Aircraft->SetAircraftName(AircraftName);
789
790   if (debug_lvl & 1) cout << underon << "Reading Aircraft Configuration File"
791             << underoff << ": " << highint << AircraftName << normint << endl;
792
793   CFGVersion = el->GetAttributeValue("version");
794   Release    = el->GetAttributeValue("release");
795
796   if (debug_lvl & 1)
797     cout << "                            Version: " << highint << CFGVersion
798                                                     << normint << endl;
799   if (CFGVersion != needed_cfg_version) {
800     cerr << endl << fgred << "YOU HAVE AN INCOMPATIBLE CFG FILE FOR THIS AIRCRAFT."
801             " RESULTS WILL BE UNPREDICTABLE !!" << endl;
802     cerr << "Current version needed is: " << needed_cfg_version << endl;
803     cerr << "         You have version: " << CFGVersion << endl << fgdef << endl;
804     return false;
805   }
806
807   if (Release == "ALPHA" && (debug_lvl & 1)) {
808     cout << endl << endl
809          << highint << "This aircraft model is an " << fgred << Release
810          << reset << highint << " release!!!" << endl << endl << reset
811          << "This aircraft model may not even properly load, and probably"
812          << " will not fly as expected." << endl << endl
813          << fgred << highint << "Use this model for development purposes ONLY!!!"
814          << normint << reset << endl << endl;
815   } else if (Release == "BETA" && (debug_lvl & 1)) {
816     cout << endl << endl
817          << highint << "This aircraft model is a " << fgred << Release
818          << reset << highint << " release!!!" << endl << endl << reset
819          << "This aircraft model probably will not fly as expected." << endl << endl
820          << fgblue << highint << "Use this model for development purposes ONLY!!!"
821          << normint << reset << endl << endl;
822   } else if (Release == "PRODUCTION" && (debug_lvl & 1)) {
823     cout << endl << endl
824          << highint << "This aircraft model is a " << fgblue << Release
825          << reset << highint << " release." << endl << endl << reset;
826   } else if (debug_lvl & 1) {
827     cout << endl << endl
828          << highint << "This aircraft model is an " << fgred << Release
829          << reset << highint << " release!!!" << endl << endl << reset
830          << "This aircraft model may not even properly load, and probably"
831          << " will not fly as expected." << endl << endl
832          << fgred << highint << "Use this model for development purposes ONLY!!!"
833          << normint << reset << endl << endl;
834   }
835
836   return result;
837 }
838
839 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
840
841 bool FGFDMExec::ReadChild(Element* el)
842 {
843   // Add a new childData object to the child FDM list
844   // Populate that childData element with a new FDMExec object
845   // Set the IsChild flag for that FDMExec object
846   // Get the aircraft name
847   // set debug level to print out no additional data for child objects
848   // Load the model given the aircraft name
849   // reset debug level to prior setting
850
851   string token;
852
853   struct childData* child = new childData;
854
855   child->exec = new FGFDMExec(Root, FDMctr);
856   child->exec->SetChild(true);
857
858   string childAircraft = el->GetAttributeValue("name");
859   string sMated = el->GetAttributeValue("mated");
860   if (sMated == "false") child->mated = false; // child objects are mated by default.
861   string sInternal = el->GetAttributeValue("internal");
862   if (sInternal == "true") child->internal = true; // child objects are external by default.
863
864   child->exec->SetAircraftPath( AircraftPath );
865   child->exec->SetEnginePath( EnginePath );
866   child->exec->SetSystemsPath( SystemsPath );
867   child->exec->LoadModel(childAircraft);
868
869   Element* location = el->FindElement("location");
870   if (location) {
871     child->Loc = location->FindElementTripletConvertTo("IN");
872   } else {
873     cerr << endl << highint << fgred << "  No location was found for this child object!" << reset << endl;
874     exit(-1);
875   }
876   
877   Element* orientation = el->FindElement("orient");
878   if (orientation) {
879     child->Orient = orientation->FindElementTripletConvertTo("RAD");
880   } else if (debug_lvl > 0) {
881     cerr << endl << highint << "  No orientation was found for this child object! Assuming 0,0,0." << reset << endl;
882   }
883
884   ChildFDMList.push_back(child);
885
886   return true;
887 }
888
889 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
890
891 FGPropertyManager* FGFDMExec::GetPropertyManager(void)
892 {
893   return instance;
894 }
895
896 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
897
898 FGTrim* FGFDMExec::GetTrim(void)
899 {
900   delete Trim;
901   Trim = new FGTrim(this,tNone);
902   return Trim;
903 }
904
905 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
906
907 void FGFDMExec::DisableOutput(void)
908 {
909   for (unsigned i=0; i<Outputs.size(); i++) {
910     Outputs[i]->Disable();
911   }
912 }
913
914 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
915
916 void FGFDMExec::EnableOutput(void)
917 {
918   for (unsigned i=0; i<Outputs.size(); i++) {
919     Outputs[i]->Enable();
920   }
921 }
922
923 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
924
925 void FGFDMExec::ForceOutput(int idx)
926 {
927   if (idx >= 0 && idx < Outputs.size()) Outputs[idx]->Print();
928 }
929         
930 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
931
932 bool FGFDMExec::SetOutputDirectives(const string& fname)
933 {
934   bool result;
935
936   FGOutput* Output = new FGOutput(this);
937   Output->SetDirectivesFile(RootDir + fname);
938   Output->InitModel();
939   Schedule(Output, 1);
940   result = Output->Load(0);
941
942   if (result) {
943     Outputs.push_back(Output);
944     typedef double (FGOutput::*iOPMF)(void) const;
945     string outputProp = CreateIndexedPropertyName("simulation/output",Outputs.size()-1);
946     instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate, false);
947   }
948
949   return result;
950 }
951
952 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
953
954 void FGFDMExec::DoTrim(int mode)
955 {
956   double saved_time;
957
958   if (Constructing) return;
959
960   if (mode < 0 || mode > JSBSim::tNone) {
961     cerr << endl << "Illegal trimming mode!" << endl << endl;
962     return;
963   }
964   saved_time = sim_time;
965   FGTrim trim(this, (JSBSim::TrimMode)mode);
966   if ( !trim.DoTrim() ) cerr << endl << "Trim Failed" << endl << endl;
967   trim.Report();
968   sim_time = saved_time;
969 }
970
971 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
972 /*
973 void FGFDMExec::DoTrimAnalysis(int mode)
974 {
975   double saved_time;
976   if (Constructing) return;
977
978   if (mode < 0 || mode > JSBSim::taNone) {
979     cerr << endl << "Illegal trimming mode!" << endl << endl;
980     return;
981   }
982   saved_time = sim_time;
983
984   FGTrimAnalysis trimAnalysis(this, (JSBSim::TrimAnalysisMode)mode);
985
986   if ( !trimAnalysis.Load(IC->GetInitFile(), false) ) {
987     cerr << "A problem occurred with trim configuration file " << trimAnalysis.Load(IC->GetInitFile()) << endl;
988     exit(-1);
989   }
990
991   bool result = trimAnalysis.DoTrim();
992
993   if ( !result ) cerr << endl << "Trim Failed" << endl << endl;
994
995   trimAnalysis.Report();
996   Setsim_time(saved_time);
997
998   EnableOutput();
999   cout << "\nOutput: " << GetOutputFileName() << endl;
1000
1001 }
1002 */
1003 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1004
1005 void FGFDMExec::UseAtmosphereMSIS(void)
1006 {
1007   FGAtmosphere *oldAtmosphere = Atmosphere;
1008   Atmosphere = new MSIS(this);
1009   if (!Atmosphere->InitModel()) {
1010     cerr << fgred << "MSIS Atmosphere model init failed" << fgdef << endl;
1011     Error+=1;
1012   }
1013   delete oldAtmosphere;
1014 }
1015
1016 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1017
1018 void FGFDMExec::UseAtmosphereMars(void)
1019 {
1020 /*
1021   FGAtmosphere *oldAtmosphere = Atmosphere;
1022   Atmosphere = new FGMars(this);
1023   if (!Atmosphere->InitModel()) {
1024     cerr << fgred << "Mars Atmosphere model init failed" << fgdef << endl;
1025     Error+=1;
1026   }
1027   delete oldAtmosphere;
1028 */
1029 }
1030
1031 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032 //    The bitmasked value choices are as follows:
1033 //    unset: In this case (the default) JSBSim would only print
1034 //       out the normally expected messages, essentially echoing
1035 //       the config files as they are read. If the environment
1036 //       variable is not set, debug_lvl is set to 1 internally
1037 //    0: This requests JSBSim not to output any messages
1038 //       whatsoever.
1039 //    1: This value explicity requests the normal JSBSim
1040 //       startup messages
1041 //    2: This value asks for a message to be printed out when
1042 //       a class is instantiated
1043 //    4: When this value is set, a message is displayed when a
1044 //       FGModel object executes its Run() method
1045 //    8: When this value is set, various runtime state variables
1046 //       are printed out periodically
1047 //    16: When set various parameters are sanity checked and
1048 //       a message is printed out when they go out of bounds
1049
1050 void FGFDMExec::Debug(int from)
1051 {
1052   if (debug_lvl <= 0) return;
1053
1054   if (debug_lvl & 1 && IdFDM == 0) { // Standard console startup message output
1055     if (from == 0) { // Constructor
1056       cout << "\n\n     " << highint << underon << "JSBSim Flight Dynamics Model v"
1057                                      << JSBSim_version << underoff << normint << endl;
1058       cout << halfint << "            [JSBSim-ML v" << needed_cfg_version << "]\n\n";
1059       cout << normint << "JSBSim startup beginning ...\n\n";
1060     } else if (from == 3) {
1061       cout << "\n\nJSBSim startup complete\n\n";
1062     }
1063   }
1064   if (debug_lvl & 2 ) { // Instantiation/Destruction notification
1065     if (from == 0) cout << "Instantiated: FGFDMExec" << endl;
1066     if (from == 1) cout << "Destroyed:    FGFDMExec" << endl;
1067   }
1068   if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
1069     if (from == 2) {
1070       cout << "================== Frame: " << Frame << "  Time: "
1071            << sim_time << " dt: " << dT << endl;
1072     }
1073   }
1074   if (debug_lvl & 8 ) { // Runtime state variables
1075   }
1076   if (debug_lvl & 16) { // Sanity checking
1077   }
1078   if (debug_lvl & 64) {
1079     if (from == 0) { // Constructor
1080       cout << IdSrc << endl;
1081       cout << IdHdr << endl;
1082     }
1083   }
1084 }
1085 }
1086
1087