1 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5 file The header file for the JSBSim executive.
7 ------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
9 This program is free software; you can redistribute it and/or modify it under
10 the terms of the GNU Lesser General Public License as published by the Free Software
11 Foundation; either version 2 of the License, or (at your option) any later
14 This program is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
19 You should have received a copy of the GNU Lesser General Public License along with
20 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
21 Place - Suite 330, Boston, MA 02111-1307, USA.
23 Further information about the GNU Lesser General Public License can also be found on
24 the world wide web at http://www.gnu.org.
27 --------------------------------------------------------------------------------
29 7/31/99 TP Added RunIC function that runs the sim so that every frame
30 begins with the IC values from the given FGInitialCondition
33 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
37 #ifndef FGFDMEXEC_HEADER_H
38 #define FGFDMEXEC_HEADER_H
40 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
47 #include "FGJSBBase.h"
48 #include "input_output/FGPropertyManager.h"
49 #include "models/FGPropagate.h"
50 #include "math/FGColumnVector3.h"
51 #include "models/FGOutput.h"
53 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
55 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
57 #define ID_FDMEXEC "$Id: FGFDMExec.h,v 1.95 2015/02/07 17:52:36 bcoconni Exp $"
59 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
61 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
70 class FGAccelerations;
73 class FGBuoyantForces;
74 class FGExternalReactions;
75 class FGGroundReactions;
83 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
87 /** Encapsulates the JSBSim simulation executive.
88 This class is the executive class through which all other simulation classes
89 are instantiated, initialized, and run. When integrated with FlightGear (or
90 other flight simulator) this class is typically instantiated by an interface
91 class on the simulator side.
93 At the time of simulation initialization, the interface
94 class creates an instance of this executive class. The
95 executive is subsequently directed to load the chosen aircraft specification
99 fdmex = new FGFDMExec( ... );
100 result = fdmex->LoadModel( ... );
103 When an aircraft model is loaded, the config file is parsed and for each of the
104 sections of the config file (propulsion, flight control, etc.) the
105 corresponding Load() method is called (e.g. FGFCS::Load()).
107 Subsequent to the creation of the executive and loading of the model,
108 initialization is performed. Initialization involves copying control inputs
109 into the appropriate JSBSim data storage locations, configuring it for the set
110 of user supplied initial conditions, and then copying state variables from
111 JSBSim. The state variables are used to drive the instrument displays and to
112 place the vehicle model in world space for visual rendering:
115 copy_to_JSBsim(); // copy control inputs to JSBSim
116 fdmex->RunIC(); // loop JSBSim once w/o integrating
117 copy_from_JSBsim(); // update the bus
120 Once initialization is complete, cyclic execution proceeds:
123 copy_to_JSBsim(); // copy control inputs to JSBSim
124 fdmex->Run(); // execute JSBSim
125 copy_from_JSBsim(); // update the bus
128 JSBSim can be used in a standalone mode by creating a compact stub program
129 that effectively performs the same progression of steps as outlined above for
130 the integrated version, but with two exceptions. First, the copy_to_JSBSim()
131 and copy_from_JSBSim() functions are not used because the control inputs are
132 handled directly by the scripting facilities and outputs are handled by the
133 output (data logging) class. Second, the name of a script file can be supplied
134 to the stub program. Scripting (see FGScript) provides a way to supply command
135 inputs to the simulation:
138 FDMExec = new JSBSim::FGFDMExec();
139 FDMExec->LoadScript( ScriptName ); // the script loads the aircraft and ICs
140 result = FDMExec->Run();
141 while (result) { // cyclic execution
142 result = FDMExec->Run(); // execute JSBSim
146 The standalone mode has been useful for verifying changes before committing
147 updates to the source code repository. It is also useful for running sets of
148 tests that reveal some aspects of simulated aircraft performance, such as
149 range, time-to-climb, takeoff distance, etc.
151 <h3>JSBSim Debugging Directives</h3>
153 This describes to any interested entity the debug level
154 requested by setting the JSBSIM_DEBUG environment variable.
155 The bitmasked value choices are as follows:
156 - <b>unset</b>: In this case (the default) JSBSim would only print
157 out the normally expected messages, essentially echoing
158 the config files as they are read. If the environment
159 variable is not set, debug_lvl is set to 1 internally
160 - <b>0</b>: This requests JSBSim not to output any messages
162 - <b>1</b>: This value explicity requests the normal JSBSim
164 - <b>2</b>: This value asks for a message to be printed out when
165 a class is instantiated
166 - <b>4</b>: When this value is set, a message is displayed when a
167 FGModel object executes its Run() method
168 - <b>8</b>: When this value is set, various runtime state variables
169 are printed out periodically
170 - <b>16</b>: When set various parameters are sanity checked and
171 a message is printed out when they go out of bounds
174 @property simulator/do_trim (write only) Can be set to the integer equivalent to one of
175 tLongitudinal (0), tFull (1), tGround (2), tPullup (3),
176 tCustom (4), tTurn (5). Setting this to a legal value
177 (such as by a script) causes a trim to be performed. This
178 property actually maps toa function call of DoTrim().
180 @author Jon S. Berndt
181 @version $Revision: 1.95 $
184 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
186 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
188 class FGFDMExec : public FGJSBBase
194 FGColumnVector3 Orient;
200 Loc = FGColumnVector3(0,0,0);
201 Orient = FGColumnVector3(0,0,0);
206 void Run(void) {exec->Run();}
207 void AssignState(FGPropagate* source_prop) {
208 exec->GetPropagate()->SetVState(source_prop->GetVState());
218 /// Default constructor
219 FGFDMExec(FGPropertyManager* root = 0, unsigned int* fdmctr = 0);
221 /// Default destructor
224 // This list of enums is very important! The order in which models are listed
225 // here determines the order of execution of the models.
227 // There are some conditions that need to be met :
228 // 1. FCS can request mass geometry changes via the inertia/pointmass-*
229 // properties so it must be executed before MassBalance
230 // 2. MassBalance must be executed before Propulsion, Aerodynamics,
231 // GroundReactions, ExternalReactions and BuoyantForces to ensure that
232 // their moments are computed with the updated CG position.
233 enum eModels { ePropagate=0,
249 eNumStandardModels };
251 /** Unbind all tied JSBSim properties. */
252 void Unbind(void) {instance->Unbind();}
254 /** This function executes each scheduled model in succession.
255 @return true if successful, false if sim should be ended */
258 /** Initializes the sim from the initial condition object and executes
259 each scheduled model without integrating i.e. dt=0.
260 @return true if successful */
263 /** Sets the ground callback pointer. For optimal memory management, a shared
264 pointer is used internally that maintains a reference counter. The calling
265 application must therefore use FGGroundCallback_ptr 'smart pointers' to
266 manage their copy of the ground callback.
267 @param gc A pointer to a ground callback object
268 @see FGGroundCallback
270 void SetGroundCallback(FGGroundCallback* gc) { FGLocation::SetGroundCallback(gc); }
272 /** Loads an aircraft model.
273 @param AircraftPath path to the aircraft/ directory. For instance:
274 "aircraft". Under aircraft, then, would be directories for various
275 modeled aircraft such as C172/, x15/, etc.
276 @param EnginePath path to the directory under which engine config
277 files are kept, for instance "engine"
278 @param SystemsPath path to the directory under which systems config
279 files are kept, for instance "systems"
280 @param model the name of the aircraft model itself. This file will
281 be looked for in the directory specified in the AircraftPath variable,
282 and in turn under the directory with the same name as the model. For
283 instance: "aircraft/x15/x15.xml"
284 @param addModelToPath set to true to add the model name to the
285 AircraftPath, defaults to true
286 @return true if successful */
287 bool LoadModel(const std::string& AircraftPath, const std::string& EnginePath,
288 const std::string& SystemsPath, const std::string& model,
289 bool addModelToPath = true);
291 /** Loads an aircraft model. The paths to the aircraft and engine
292 config file directories must be set prior to calling this. See
294 @param model the name of the aircraft model itself. This file will
295 be looked for in the directory specified in the AircraftPath variable,
296 and in turn under the directory with the same name as the model. For
297 instance: "aircraft/x15/x15.xml"
298 @param addModelToPath set to true to add the model name to the
299 AircraftPath, defaults to true
300 @return true if successful*/
301 bool LoadModel(const std::string& model, bool addModelToPath = true);
304 @param Script The full path name and file name for the script to be loaded.
305 @param deltaT The simulation integration step size, if given. If no value is supplied
306 then 0.0 is used and the value is expected to be supplied in
307 the script file itself.
308 @param initfile The initialization file that will override the initialization file
309 specified in the script file. If no file name is given on the command line,
310 the file specified in the script will be used. If an initialization file
311 is not given in either place, an error will result.
312 @return true if successfully loads; false otherwise. */
313 bool LoadScript(const std::string& Script, double deltaT=0.0,
314 const std::string initfile="");
316 /** Sets the path to the engine config file directories.
317 @param path path to the directory under which engine config
318 files are kept, for instance "engine" */
319 bool SetEnginePath(const std::string& path) { EnginePath = RootDir + path; return true; }
321 /** Sets the path to the aircraft config file directories.
322 @param path path to the aircraft directory. For instance:
323 "aircraft". Under aircraft, then, would be directories for various
324 modeled aircraft such as C172/, x15/, etc. */
325 bool SetAircraftPath(const std::string& path) { AircraftPath = RootDir + path; return true; }
327 /** Sets the path to the systems config file directories.
328 @param path path to the directory under which systems config
329 files are kept, for instance "systems" */
330 bool SetSystemsPath(const std::string& path) { SystemsPath = RootDir + path; return true; }
332 /// @name Top-level executive State and Model retrieval mechanism
334 /// Returns the FGAtmosphere pointer.
335 FGAtmosphere* GetAtmosphere(void) {return (FGAtmosphere*)Models[eAtmosphere];}
336 /// Returns the FGAccelerations pointer.
337 FGAccelerations* GetAccelerations(void) {return (FGAccelerations*)Models[eAccelerations];}
338 /// Returns the FGWinds pointer.
339 FGWinds* GetWinds(void) {return (FGWinds*)Models[eWinds];}
340 /// Returns the FGFCS pointer.
341 FGFCS* GetFCS(void) {return (FGFCS*)Models[eSystems];}
342 /// Returns the FGPropulsion pointer.
343 FGPropulsion* GetPropulsion(void) {return (FGPropulsion*)Models[ePropulsion];}
344 /// Returns the FGAircraft pointer.
345 FGMassBalance* GetMassBalance(void) {return (FGMassBalance*)Models[eMassBalance];}
346 /// Returns the FGAerodynamics pointer
347 FGAerodynamics* GetAerodynamics(void){return (FGAerodynamics*)Models[eAerodynamics];}
348 /// Returns the FGInertial pointer.
349 FGInertial* GetInertial(void) {return (FGInertial*)Models[eInertial];}
350 /// Returns the FGGroundReactions pointer.
351 FGGroundReactions* GetGroundReactions(void) {return (FGGroundReactions*)Models[eGroundReactions];}
352 /// Returns the FGExternalReactions pointer.
353 FGExternalReactions* GetExternalReactions(void) {return (FGExternalReactions*)Models[eExternalReactions];}
354 /// Returns the FGBuoyantForces pointer.
355 FGBuoyantForces* GetBuoyantForces(void) {return (FGBuoyantForces*)Models[eBuoyantForces];}
356 /// Returns the FGAircraft pointer.
357 FGAircraft* GetAircraft(void) {return (FGAircraft*)Models[eAircraft];}
358 /// Returns the FGPropagate pointer.
359 FGPropagate* GetPropagate(void) {return (FGPropagate*)Models[ePropagate];}
360 /// Returns the FGAuxiliary pointer.
361 FGAuxiliary* GetAuxiliary(void) {return (FGAuxiliary*)Models[eAuxiliary];}
362 /// Returns the FGInput pointer.
363 FGInput* GetInput(void) {return (FGInput*)Models[eInput];}
364 /** Get a pointer to the ground callback currently used. It is recommanded
365 to store the returned pointer in a 'smart pointer' FGGroundCallback_ptr.
366 @return A pointer to the current ground callback object.
367 @see FGGroundCallback
369 FGGroundCallback* GetGroundCallback(void) {return FGLocation::GetGroundCallback();}
370 /// Retrieves the script object
371 FGScript* GetScript(void) {return Script;}
372 /// Returns a pointer to the FGInitialCondition object
373 FGInitialCondition* GetIC(void) {return IC;}
374 /// Returns a pointer to the FGTrim object
375 FGTrim* GetTrim(void);
378 /// Retrieves the engine path.
379 const std::string& GetEnginePath(void) {return EnginePath;}
380 /// Retrieves the aircraft path.
381 const std::string& GetAircraftPath(void) {return AircraftPath;}
382 /// Retrieves the systems path.
383 const std::string& GetSystemsPath(void) {return SystemsPath;}
384 /// Retrieves the full aircraft path name.
385 const std::string& GetFullAircraftPath(void) {return FullAircraftPath;}
387 /** Retrieves the value of a property.
388 @param property the name of the property
389 @result the value of the specified property */
390 inline double GetPropertyValue(const std::string& property)
391 { return instance->GetNode()->GetDouble(property); }
393 /** Sets a property value.
394 @param property the property to be set
395 @param value the value to set the property to */
396 inline void SetPropertyValue(const std::string& property, double value) {
397 instance->GetNode()->SetDouble(property, value);
400 /// Returns the model name.
401 const std::string& GetModelName(void) const { return modelName; }
403 /// Returns a pointer to the property manager object.
404 FGPropertyManager* GetPropertyManager(void);
405 /// Returns a vector of strings representing the names of all loaded models (future)
406 std::vector <std::string> EnumerateFDMs(void);
407 /// Gets the number of child FDMs.
408 int GetFDMCount(void) const {return (int)ChildFDMList.size();}
409 /// Gets a particular child FDM.
410 childData* GetChildFDM(int i) const {return ChildFDMList[i];}
411 /// Marks this instance of the Exec object as a "child" object.
412 void SetChild(bool ch) {IsChild = ch;}
414 /** Sets the output (logging) mechanism for this run.
415 Calling this function passes the name of an output directives file to
416 the FGOutput object associated with this run. The call to this function
417 should be made prior to loading an aircraft model. This call results in an
418 FGOutput object being built as the first Output object in the FDMExec-managed
419 list of Output objects that may be created for an aircraft model. If this call
420 is made after an aircraft model is loaded, there is no effect. Any Output
421 objects added by the aircraft model itself (in an <output> element) will be
422 added after this one. Care should be taken not to refer to the same file
424 An output directives file contains an <output> </output> element, within
425 which should be specified the parameters or parameter groups that should
427 @param fname the filename of an output directives file.
429 bool SetOutputDirectives(const std::string& fname)
430 {return Output->SetDirectivesFile(RootDir + fname);}
432 /** Forces the specified output object to print its items once */
433 void ForceOutput(int idx=0) { Output->ForceOutput(idx); }
435 /** Sets the logging rate for all output objects (if any). */
436 void SetLoggingRate(double rate) { Output->SetRate(rate); }
438 /** Sets (or overrides) the output filename
439 @param n index of file
440 @param fname the name of the file to output data to
441 @return true if successful, false if there is no output specified for the flight model */
442 bool SetOutputFileName(const int n, const std::string& fname) { return Output->SetOutputName(n, fname); }
444 /** Retrieves the current output filename.
445 @param n index of file
446 @return the name of the output file for the output specified by the flight model.
447 If none is specified, the empty string is returned. */
448 std::string GetOutputFileName(int n) const { return Output->GetOutputName(n); }
450 /** Executes trimming in the selected mode.
451 * @param mode Specifies how to trim:
459 void DoTrim(int mode);
460 void DoSimplexTrim(int mode);
462 /** Executes linearization with state-space output
463 * You must trim first to get an accurate state-space model
465 void DoLinearization(int mode);
467 /// Disables data logging to all outputs.
468 void DisableOutput(void) { Output->Disable(); }
469 /// Enables data logging to all outputs.
470 void EnableOutput(void) { Output->Enable(); }
471 /// Pauses execution by preventing time from incrementing.
472 void Hold(void) {holding = true;}
473 /// Turn on hold after increment
474 void EnableIncrementThenHold(int Timesteps) {TimeStepsUntilHold = Timesteps; IncrementThenHolding = true;}
475 /// Checks if required to hold afer increment
476 void CheckIncrementalHold(void);
477 /// Resumes execution from a "Hold".
478 void Resume(void) {holding = false;}
479 /// Returns true if the simulation is Holding (i.e. simulation time is not moving).
480 bool Holding(void) {return holding;}
481 /** Resets the initial conditions object and prepares the simulation to run
482 again. If mode is set to 1 the output instances will take special actions
483 such as closing the current output file and open a new one with a
485 @param mode Sets the reset mode.*/
486 void ResetToInitialConditions(int mode);
487 /// Sets the debug level.
488 void SetDebugLevel(int level) {debug_lvl = level;}
490 struct PropertyCatalogStructure {
491 /// Name of the property.
492 std::string base_string;
493 /// The node for the property.
494 FGPropertyNode_ptr node;
497 /** Builds a catalog of properties.
498 * This function descends the property tree and creates a list (an STL vector)
499 * containing the name and node for all properties.
500 * @param pcs The "root" property catalog structure pointer. */
501 void BuildPropertyCatalog(struct PropertyCatalogStructure* pcs);
503 /** Retrieves property or properties matching the supplied string.
504 * A string is returned that contains a carriage return delimited list of all
505 * strings in the property catalog that matches the supplied check string.
506 * @param check The string to search for in the property catalog.
507 * @return the carriage-return-delimited string containing all matching strings
509 std::string QueryPropertyCatalog(const std::string& check);
511 // Print the contents of the property catalog for the loaded aircraft.
512 void PrintPropertyCatalog(void);
514 // Print the simulation configuration
515 void PrintSimulationConfiguration(void) const;
517 std::vector<std::string>& GetPropertyCatalog(void) {return PropertyCatalog;}
519 void SetTrimStatus(bool status){ trim_status = status; }
520 bool GetTrimStatus(void) const { return trim_status; }
521 void SetTrimMode(int mode){ ta_mode = mode; }
522 int GetTrimMode(void) const { return ta_mode; }
524 std::string GetPropulsionTankReport();
526 /// Returns the cumulative simulation time in seconds.
527 double GetSimTime(void) const { return sim_time; }
529 /// Returns the simulation delta T.
530 double GetDeltaT(void) const {return dT;}
532 /// Suspends the simulation and sets the delta T to zero.
533 void SuspendIntegration(void) {saved_dT = dT; dT = 0.0;}
535 /// Resumes the simulation by resetting delta T to the correct value.
536 void ResumeIntegration(void) {dT = saved_dT;}
538 /** Returns the simulation suspension state.
539 @return true if suspended, false if executing */
540 bool IntegrationSuspended(void) const {return dT == 0.0;}
542 /** Sets the current sim time.
543 @param cur_time the current time
544 @return the current simulation time. */
545 double Setsim_time(double cur_time) {
547 GetGroundCallback()->SetTime(sim_time);
551 /** Sets the integration time step for the simulation executive.
552 @param delta_t the time step in seconds. */
553 void Setdt(double delta_t) { dT = delta_t; }
555 /** Sets the root directory where JSBSim starts looking for its system directories.
556 @param rootDir the string containing the root directory. */
557 void SetRootDir(const std::string& rootDir) {RootDir = rootDir;}
559 /** Retrieves the Root Directory.
560 @return the string representing the root (base) JSBSim directory. */
561 const std::string& GetRootDir(void) const {return RootDir;}
563 /** Increments the simulation time if not in Holding mode. The Frame counter
565 @return the new simulation time. */
566 double IncrTime(void) {
567 if (!holding) sim_time += dT;
568 GetGroundCallback()->SetTime(sim_time);
573 /** Retrieves the current debug level setting. */
574 int GetDebugLevel(void) const {return debug_lvl;};
576 /** Initializes the simulation with initial conditions
577 @param FGIC The initial conditions that will be passed to the simulation. */
578 void Initialize(FGInitialCondition *FGIC);
585 unsigned short Terminate;
590 bool IncrementThenHolding;
591 int TimeStepsUntilHold;
595 std::string modelName;
596 std::string AircraftPath;
597 std::string FullAircraftPath;
598 std::string EnginePath;
599 std::string SystemsPath;
600 std::string CFGVersion;
604 // Standard Model pointers - shortcuts for internal executive use only.
605 FGPropagate* Propagate;
606 FGInertial* Inertial;
607 FGAtmosphere* Atmosphere;
609 FGAuxiliary* Auxiliary;
611 FGPropulsion* Propulsion;
612 FGAerodynamics* Aerodynamics;
613 FGGroundReactions* GroundReactions;
614 FGExternalReactions* ExternalReactions;
615 FGBuoyantForces* BuoyantForces;
616 FGMassBalance* MassBalance;
617 FGAircraft* Aircraft;
618 FGAccelerations* Accelerations;
623 unsigned int ResetMode;
626 FGInitialCondition* IC;
629 FGPropertyManager* Root;
631 FGPropertyManager* instance;
633 // The FDM counter is used to give each child FDM an unique ID. The root FDM has the ID 0
634 unsigned int* FDMctr;
636 std::vector <std::string> PropertyCatalog;
637 std::vector <childData*> ChildFDMList;
638 std::vector <FGModel*> Models;
640 bool ReadFileHeader(Element*);
641 bool ReadChild(Element*);
642 bool ReadPrologue(Element*);
644 void LoadInputs(unsigned int idx);
645 void LoadPlanetConstants(void);
646 void LoadModelConstants(void);
648 bool DeAllocate(void);
649 int GetDisperse(void) const {return disperse;}
651 void Debug(int from);
654 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%