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