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