From: Frederic Bouvier Date: Sun, 29 Aug 2010 18:09:07 +0000 (+0200) Subject: Merge branch 'master' of git://gitorious.org/fg/flightgear into next X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=0bce31ae9a80c571b9126427c093b8dc3d3f6820;hp=8545e5926a5afbd1299b940a087fcf5c8e19bb90;p=flightgear.git Merge branch 'master' of git://gitorious.org/fg/flightgear into next --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..98517f567 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.deps +Makefile +Makefile.in +config.sub +config.guess +config.log +config.status +configure +aclocal.m4 +autom4te.cache +depcomp +install-sh +missing +INSTALL +*.o +lib*.a diff --git a/configure.ac b/configure.ac index df8ba3dcb..9225c0fa0 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autogen.sh to produce a working configure dnl script. AC_INIT -AC_CONFIG_SRCDIR([src/Aircraft/aircraft.cxx]) +AC_CONFIG_SRCDIR([src/Airports/simple.cxx]) dnl Require at least automake 2.52 AC_PREREQ(2.52) @@ -58,7 +58,7 @@ case "${host}" in dnl Thank you Christian Bauer from SheepSaver dnl Modified by Tatsuhiro Nishioka for accepting a given framework path - dnl AC_CHECK_FRAMEWORK($1=NAME, $2=INCLUDES, $3=FRAMEWORK_PATH) ; $3 is optional + dnl AC_CHECK_FRAMEWORK($1=NAME, $2=INCLUDES, $3=FRAMEWORK_PATH, $4=ACTION_IF_FOUND) ; AC_DEFUN([AC_CHECK_FRAMEWORK], [ AS_VAR_PUSHDEF([ac_Framework], [ac_cv_framework_$1])dnl AC_CACHE_CHECK([whether compiler supports framework $1], @@ -71,6 +71,7 @@ case "${host}" in FRAMEWORKS="$FRAMEWORKS -F$3" CXXFLAGS="$CXXFLAGS -F$3" CCFLAGS="$CCFLAGS -F$3" + CPPFLAGS="$CPPFLAGS -F$3" dnl This is needed for AC_TRY_LINK when a framework path is specified export DYLD_FRAMEWORK_PATH="${DYLD_FRAMEWORK_PATH}:$3" fi @@ -82,6 +83,7 @@ case "${host}" in AS_IF([test AS_VAR_GET(ac_Framework) = yes], [AC_DEFINE(AS_TR_CPP(HAVE_FRAMEWORK_$1), 1, [Define if framework $1 is available.])] ) + AS_IF([test AS_VAR_GET(ac_Framework) = yes], $4) AS_VAR_POPDEF([ac_Framework])dnl ]) @@ -107,9 +109,9 @@ case "${host}" in export DYLD_FRAMEWORK_PATH="$DYLD_FRAMEWORK_PATH:$with_plib_framework" fi - AC_ARG_WITH(openal_framework, [ --with-openal-framework=PREFIX Speicfy the prefix path to OpenAL.framework ]) - if test "x$with_openal_framework" != "x"; then - echo "OpenAL framework prefix is $with_openal_framework" + AC_ARG_WITH(alut_framework, [ --with-alut-framework=PREFIX Specify the prefix path to ALUT.framework ]) + if test "x$with_alut_framework" != "x"; then + echo "ALUT framework prefix is $with_alut_framework" fi ;; @@ -177,13 +179,13 @@ AM_CONDITIONAL(ENABLE_SP_FDM, test "x$enable_sp_fdms" != "xno") # Specify whether we want to compile ATCDCL. # default to with_atcdcl=yes -AC_ARG_ENABLE(atcdcl, [ --enable-atcdcl Compile and link the depricated atc/ai module], [enable_atcdcl="$enableval"] ) -if test "x$enable_atcdcl" != "xno"; then +AC_ARG_ENABLE(atcdcl, [ --enable-atcdcl Compile and link the depricated atc/ai module], [], [enable_atcdcl="$enableval"] ) +if test "x$enable_atcdcl" = "xyes"; then AC_DEFINE([ENABLE_ATCDCL], 1, [Define to include old ATC/AI module]) else AC_DEFINE([ENABLE_ATCDCL], 0, [Define to include old ATC/AI module]) fi -AM_CONDITIONAL(ENABLE_ATCDCL, test "x$enable_atcdcl" != "xno") +AM_CONDITIONAL(ENABLE_ATCDCL, test "x$enable_atcdcl" = "xyes") @@ -428,19 +430,15 @@ case "${host}" in *-apple-darwin*) dnl Mac OS X - # Mac OS X has OpenAL.framework with ALUT by default - # so we can use it without checking it. - # Note: SimGear needs to check the existance of alut.h since it includes the header. - LIBS="$LIBS -framework IOKit -framework OpenAL" - openal_LIBS="$LIBS" - OPENAL_OK="yes" - ALUT_OK="yes" + # Mac OS X has OpenAL.framework, but no ALUT, by default, so we + # require use of a non-Apple ALUT.framework which we provide + openal_LIBS="-framework IOKit -framework OpenAL" - dnl Check for OpenAL.framework when --with-openal-framework is specified - if test "x$with_openal_framework" != "x"; then - AC_CHECK_FRAMEWORK(OpenAL, [#include ], $with_openal_framework) - fi - + AC_CHECK_FRAMEWORK(OpenAL, [#include ], "", [OPENAL_OK="yes"]) + AC_CHECK_FRAMEWORK(ALUT, [#include ], $with_alut_framework, [ + ALUT_OK="yes" + openal_LIBS="$openal_LIBS -framework ALUT" + ]) ;; *) @@ -747,10 +745,9 @@ fi dnl Check for Subversion library support save_LIBS=$LIBS save_CPPFLAGS=$CPPFLAGS -LIBS="" +LIBS="`apr-1-config --link-ld`" CPPFLAGS="-I/usr/include/subversion-1 `apr-1-config --includes`" -AC_CHECK_LIB(svn_client-1, svn_client_checkout3) -AC_CHECK_HEADERS([svn_client.h glut.h]) +AC_CHECK_HEADERS([svn_client.h]) if test "x$ac_cv_header_svn_client_h" != "xyes"; then echo "TerraSync will shell out for command line subversion" svn_LIBS="" @@ -758,6 +755,7 @@ if test "x$ac_cv_header_svn_client_h" != "xyes"; then else echo "TerraSync will use integrated subversion library" AC_SEARCH_LIBS(svn_client_checkout, svn_client-1) + AC_SEARCH_LIBS(svn_cmdline_init, svn_subr-1) svn_LIBS=$LIBS svn_CPPFLAGS=$CPPFLAGS AC_SUBST(svn_LIBS) @@ -815,10 +813,6 @@ AC_CONFIG_FILES([ \ src/Makefile \ src/Include/Makefile \ src/Include/version.h \ - src/Include/config.h-msvc6 \ - src/Include/config.h-msvc71 \ - src/Include/config.h-msvc8 \ - src/Include/config.h-msvc90 \ src/Aircraft/Makefile \ src/Airports/Makefile \ src/ATC/Makefile \ @@ -914,7 +908,7 @@ else echo "Include special purpose flight models: no" fi -if test "x$enable_atcdcl" != "xno"; then +if test "x$enable_atcdcl" = "xyes"; then echo "Build depricated ATC/AI module: yes" else echo "Build depricated ATC/AI module: no" diff --git a/docs-mini/README.MSVC b/docs-mini/README.MSVC index 3549336d2..17e79095c 100644 --- a/docs-mini/README.MSVC +++ b/docs-mini/README.MSVC @@ -67,4 +67,49 @@ x64 build : projects / VC90 / -3rdParty.x64, boost_1_39_0 and install/msvc90-64 are included in the x32 3rdParty archive. +3rdParty.x64, boost_1_39_0 and install/msvc90-64 are included in the x64 3rdParty archive. + +Typical setup should decompose into the following steps : + + 1. Install Visual Studio 2008 Express (http://msdn.microsoft.com/fr-fr/express/aa975050.aspx) + 2. Install msysGit (http://code.google.com/p/msysgit/) + 3. Create a new directory, say D:\FGFSDevel (or anything else) + 4. Unzip precompiled Win32 3rd party archive in it + 5. Open a Git Bash session and cd to the new directory ( cd /d/FGFSDevel ) + 6. Get SimGear sources from Gitorious : git clone git://gitorious.org/fg/simgear.git SimGear + 7. Get FlightGear source from Gitorious : git clone git://gitorious.org/fg/flightgear.git FlightGear + 8. Go to D:\FGFSDevel\FlightGear\projects\VC90 and double-click on FlightGear.sln + 9. Select the "Release" configuration + 10. Open file D:\FGFSDevel\SimGear\simgear\version.h.in and change @VERSION@ into "2.0.0" or any current version + 11. Save file as version.h in the same directory + 12. Start build (usually F7) + 13. Get the data from Gitorious too : git clone git://gitorious.org/fg/fgdata.git fgdata + 14. Wait... + 15. Add /install/msvc90/OpenSceneGraph/bin and /3rdParty/bin to your PATH environment variable + 16. Enjoy - programs are in D:\FGFSDevel\FlightGear\projects\VC90\Win32\Release + +It is also possible to compile a Debug version. This is only useful when hacking the code because +a Debug version is way slower than the Release one. + +The 64bit build is only available to people having the Professional edition of Visual Studio 2008. In that case, 14. above should be : + 14. Add /install/msvc90-64/OpenSceneGraph/bin and /3rdParty.x64/bin to your PATH environment variable + +When the manual build works, it is possible to start it from the command line. This is useful +when setting up a build server or automating the process of retrieving the code and building +it in a scheduled task. To do that : + + 1. open a command line window + 2. execute "C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat" + or "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\vsvars32.bat" in a + 64bit environment (Vista 64-bit or Windows7 64-bit) + You should see : "Setting environment for using Microsoft Visual Studio 2008 x86 tools." + printed in the console + 3. cd to the FlightGear project directory : + D: + cd \FGFSDevel\FlightGear\projects\VC90 (for example) + 4. start the build with the command line below : + msbuild FlightGear.sln /p:Configuration=Release /m + or + msbuild FlightGear.sln /p:Configuration=Debug /m + +That's all... diff --git a/docs-mini/README.digitalfilters b/docs-mini/README.digitalfilters index dce9a80dd..9f65b8ae9 100644 --- a/docs-mini/README.digitalfilters +++ b/docs-mini/README.digitalfilters @@ -1,3 +1,9 @@ +NOTE: +This manual may contain outdated information. For documentation of the most recent features +refer to +http://wiki.flightgear.org/index.php/Howto:_Design_an_autopilot +http://wiki.flightgear.org/index.php/Autopilot_Configuration_Reference + COMMON SETTINGS ============================================================================== diff --git a/man/.gitignore b/man/.gitignore new file mode 100644 index 000000000..f7e585b87 --- /dev/null +++ b/man/.gitignore @@ -0,0 +1 @@ +*.1 diff --git a/projects/VC100/.gitignore b/projects/VC100/.gitignore new file mode 100644 index 000000000..994d77bf7 --- /dev/null +++ b/projects/VC100/.gitignore @@ -0,0 +1,8 @@ +FlightGear.suo +FlightGear.sdf +FlightGear.opensdf +Win32 +x64 +ipch +*.user +*.sln.cache diff --git a/projects/VC100/FlightGear.sln b/projects/VC100/FlightGear.sln new file mode 100644 index 000000000..e1ebfa828 --- /dev/null +++ b/projects/VC100/FlightGear.sln @@ -0,0 +1,163 @@ +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fgadmin", "fgadmin\fgadmin.vcxproj", "{7004E589-7EA0-4AFD-B432-3D5E00B55049}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fgjs", "fgjs\fgjs.vcxproj", "{6749547A-6493-4754-8E0E-49FB3137C4CA}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fgviewer", "fgviewer\fgviewer.vcxproj", "{0F13A557-EC52-481D-ADFB-9209C068FCEB}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FlightGear", "FlightGear\FlightGear.vcxproj", "{49142EAF-B264-4B9F-B096-F669999EBB2E}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GPSsmooth", "GPSsmooth\GPSsmooth.vcxproj", "{AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "metar", "metar\metar.vcxproj", "{FC424099-5D77-4BC2-A93F-2EE59F816B51}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MIDGsmooth", "MIDGsmooth\MIDGsmooth.vcxproj", "{92010FAB-17A3-4891-AE6D-507214FEA508}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "terrasync", "terrasync\terrasync.vcxproj", "{874D3F55-6048-4068-A7C2-7FA6AF1F30EA}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "UGsmooth", "UGsmooth\UGsmooth.vcxproj", "{EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xmlgrep", "xmlgrep\xmlgrep.vcxproj", "{1F40CF41-9836-4488-BAAF-560623665C12}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "yasim", "yasim\yasim.vcxproj", "{800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}" + ProjectSection(ProjectDependencies) = postProject + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} = {22540CD3-D3CA-4C86-A773-80AEEE3ACDED} + EndProjectSection +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimGear", "..\..\..\SimGear\projects\VC100\SimGear.vcxproj", "{22540CD3-D3CA-4C86-A773-80AEEE3ACDED}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Debug|Win32.ActiveCfg = Debug|Win32 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Debug|Win32.Build.0 = Debug|Win32 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Debug|x64.ActiveCfg = Debug|x64 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Debug|x64.Build.0 = Debug|x64 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Release|Win32.ActiveCfg = Release|Win32 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Release|Win32.Build.0 = Release|Win32 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Release|x64.ActiveCfg = Release|x64 + {7004E589-7EA0-4AFD-B432-3D5E00B55049}.Release|x64.Build.0 = Release|x64 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Debug|Win32.ActiveCfg = Debug|Win32 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Debug|Win32.Build.0 = Debug|Win32 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Debug|x64.ActiveCfg = Debug|x64 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Debug|x64.Build.0 = Debug|x64 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Release|Win32.ActiveCfg = Release|Win32 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Release|Win32.Build.0 = Release|Win32 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Release|x64.ActiveCfg = Release|x64 + {6749547A-6493-4754-8E0E-49FB3137C4CA}.Release|x64.Build.0 = Release|x64 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Debug|Win32.ActiveCfg = Debug|Win32 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Debug|Win32.Build.0 = Debug|Win32 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Debug|x64.ActiveCfg = Debug|x64 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Debug|x64.Build.0 = Debug|x64 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Release|Win32.ActiveCfg = Release|Win32 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Release|Win32.Build.0 = Release|Win32 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Release|x64.ActiveCfg = Release|x64 + {0F13A557-EC52-481D-ADFB-9209C068FCEB}.Release|x64.Build.0 = Release|x64 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Debug|Win32.ActiveCfg = Debug|Win32 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Debug|Win32.Build.0 = Debug|Win32 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Debug|x64.ActiveCfg = Debug|x64 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Debug|x64.Build.0 = Debug|x64 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Release|Win32.ActiveCfg = Release|Win32 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Release|Win32.Build.0 = Release|Win32 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Release|x64.ActiveCfg = Release|x64 + {49142EAF-B264-4B9F-B096-F669999EBB2E}.Release|x64.Build.0 = Release|x64 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Debug|Win32.ActiveCfg = Debug|Win32 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Debug|Win32.Build.0 = Debug|Win32 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Debug|x64.ActiveCfg = Debug|x64 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Debug|x64.Build.0 = Debug|x64 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Release|Win32.ActiveCfg = Release|Win32 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Release|Win32.Build.0 = Release|Win32 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Release|x64.ActiveCfg = Release|x64 + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA}.Release|x64.Build.0 = Release|x64 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Debug|Win32.ActiveCfg = Debug|Win32 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Debug|Win32.Build.0 = Debug|Win32 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Debug|x64.ActiveCfg = Debug|x64 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Debug|x64.Build.0 = Debug|x64 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Release|Win32.ActiveCfg = Release|Win32 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Release|Win32.Build.0 = Release|Win32 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Release|x64.ActiveCfg = Release|x64 + {FC424099-5D77-4BC2-A93F-2EE59F816B51}.Release|x64.Build.0 = Release|x64 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Debug|Win32.ActiveCfg = Debug|Win32 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Debug|Win32.Build.0 = Debug|Win32 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Debug|x64.ActiveCfg = Debug|x64 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Debug|x64.Build.0 = Debug|x64 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Release|Win32.ActiveCfg = Release|Win32 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Release|Win32.Build.0 = Release|Win32 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Release|x64.ActiveCfg = Release|x64 + {92010FAB-17A3-4891-AE6D-507214FEA508}.Release|x64.Build.0 = Release|x64 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Debug|Win32.ActiveCfg = Debug|Win32 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Debug|Win32.Build.0 = Debug|Win32 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Debug|x64.ActiveCfg = Debug|x64 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Release|Win32.ActiveCfg = Release|Win32 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Release|Win32.Build.0 = Release|Win32 + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA}.Release|x64.ActiveCfg = Release|x64 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Debug|Win32.ActiveCfg = Debug|Win32 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Debug|Win32.Build.0 = Debug|Win32 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Debug|x64.ActiveCfg = Debug|x64 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Debug|x64.Build.0 = Debug|x64 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Release|Win32.ActiveCfg = Release|Win32 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Release|Win32.Build.0 = Release|Win32 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Release|x64.ActiveCfg = Release|x64 + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99}.Release|x64.Build.0 = Release|x64 + {1F40CF41-9836-4488-BAAF-560623665C12}.Debug|Win32.ActiveCfg = Debug|Win32 + {1F40CF41-9836-4488-BAAF-560623665C12}.Debug|Win32.Build.0 = Debug|Win32 + {1F40CF41-9836-4488-BAAF-560623665C12}.Debug|x64.ActiveCfg = Debug|x64 + {1F40CF41-9836-4488-BAAF-560623665C12}.Debug|x64.Build.0 = Debug|x64 + {1F40CF41-9836-4488-BAAF-560623665C12}.Release|Win32.ActiveCfg = Release|Win32 + {1F40CF41-9836-4488-BAAF-560623665C12}.Release|Win32.Build.0 = Release|Win32 + {1F40CF41-9836-4488-BAAF-560623665C12}.Release|x64.ActiveCfg = Release|x64 + {1F40CF41-9836-4488-BAAF-560623665C12}.Release|x64.Build.0 = Release|x64 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Debug|Win32.ActiveCfg = Debug|Win32 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Debug|Win32.Build.0 = Debug|Win32 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Debug|x64.ActiveCfg = Debug|x64 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Debug|x64.Build.0 = Debug|x64 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Release|Win32.ActiveCfg = Release|Win32 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Release|Win32.Build.0 = Release|Win32 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Release|x64.ActiveCfg = Release|x64 + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2}.Release|x64.Build.0 = Release|x64 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Debug|Win32.ActiveCfg = Debug|Win32 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Debug|Win32.Build.0 = Debug|Win32 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Debug|x64.ActiveCfg = Debug|x64 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Debug|x64.Build.0 = Debug|x64 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Release|Win32.ActiveCfg = Release|Win32 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Release|Win32.Build.0 = Release|Win32 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Release|x64.ActiveCfg = Release|x64 + {22540CD3-D3CA-4C86-A773-80AEEE3ACDED}.Release|x64.Build.0 = Release|x64 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/projects/VC100/FlightGear/FlightGear.vcxproj b/projects/VC100/FlightGear/FlightGear.vcxproj new file mode 100644 index 000000000..fa563816b --- /dev/null +++ b/projects/VC100/FlightGear/FlightGear.vcxproj @@ -0,0 +1,1426 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {49142EAF-B264-4B9F-B096-F669999EBB2E} + FlightGear + + + + Application + false + MultiByte + + + Application + false + MultiByte + + + Application + false + MultiByte + + + Application + false + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + fgfs + fgfs + fgfs + fgfs + + + + .\Debug/FlightGear.tlb + + + Disabled + ..\..\..\src;..\..\..\src\include;..\..\..\..\SimGear;..\..\..\src\FDM\JSBSim;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + _DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + true + true + Level3 + true + EditAndContinue + Default + + + _DEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + /MACHINE:I386 %(AdditionalOptions) + opengl32.lib;glu32.lib;winmm.lib;wsock32.lib;sg_d.lib;net_d.lib;pui_d.lib;puaux_d.lib;fnt_d.lib;js_d.lib;ul_d.lib;zlibd.lib;OpenAL32.lib;ALut.lib;osgd.lib;osgDBd.lib;osgUtild.lib;osgViewerd.lib;osgGAd.lib;osgTextd.lib;osgParticled.lib;OpenThreadsd.lib;libjpegd.lib;%(AdditionalDependencies) + $(OutDir)fgfs.exe + true + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + %(IgnoreSpecificDefaultLibraries) + true + Console + false + + + MultiplyDefinedSymbolOnly + + + + + X64 + .\Debug/FlightGear.tlb + + + Disabled + ..\..\..\src;..\..\..\src\include;..\..\..\..\SimGear;..\..\..\src\FDM\JSBSim;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + _DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE;%(PreprocessorDefinitions) + true + Default + MultiThreadedDebugDLL + true + true + Level3 + true + EditAndContinue + Default + + + _DEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + opengl32.lib;glu32.lib;winmm.lib;wsock32.lib;sg_d.lib;net_d.lib;pui_d.lib;puaux_d.lib;fnt_d.lib;js_d.lib;ul_d.lib;zlibd.lib;OpenAL32.lib;ALut.lib;osgd.lib;osgDBd.lib;osgUtild.lib;osgViewerd.lib;osgGAd.lib;osgTextd.lib;osgParticled.lib;OpenThreadsd.lib;libjpegd.lib;%(AdditionalDependencies) + $(OutDir)fgfs.exe + true + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + %(IgnoreSpecificDefaultLibraries) + true + Console + false + + + MachineX64 + MultiplyDefinedSymbolOnly + + + + + .\Release/FlightGear.tlb + + + AnySuitable + ..\..\..\src;..\..\..\src\include;..\..\..\src\FDM\JSBSim;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + true + Level3 + true + ProgramDatabase + Default + + + NDEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + /MACHINE:I386 %(AdditionalOptions) + opengl32.lib;glu32.lib;winmm.lib;wsock32.lib;sg.lib;net.lib;pui.lib;puAux.lib;fnt.lib;js.lib;ul.lib;zlib.lib;OpenAL32.lib;ALut.lib;osg.lib;osgDB.lib;osgUtil.lib;osgViewer.lib;osgGA.lib;osgText.lib;osgParticle.lib;OpenThreads.lib;libjpeg.lib;%(AdditionalDependencies) + $(OutDir)fgfs.exe + true + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + %(IgnoreSpecificDefaultLibraries) + true + Console + false + + + MultiplyDefinedSymbolOnly + + + + + X64 + .\Release/FlightGear.tlb + + + OnlyExplicitInline + ..\..\..\src;..\..\..\src\include;..\..\..\src\FDM\JSBSim;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + true + Level3 + true + ProgramDatabase + Default + + + NDEBUG;%(PreprocessorDefinitions) + 0x0c09 + + + opengl32.lib;glu32.lib;winmm.lib;wsock32.lib;sg.lib;net.lib;pui.lib;puAux.lib;fnt.lib;js.lib;ul.lib;zlib.lib;OpenAL32.lib;ALut.lib;osg.lib;osgDB.lib;osgUtil.lib;osgViewer.lib;osgGA.lib;osgText.lib;osgParticle.lib;OpenThreads.lib;libjpeg.lib;%(AdditionalDependencies) + $(OutDir)fgfs.exe + true + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + %(IgnoreSpecificDefaultLibraries) + true + Console + false + + + MachineX64 + MultiplyDefinedSymbolOnly + + + + + + + + + + + + + + + + + + + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + + + + + + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + $(IntDir)%(Filename)1.obj + $(IntDir)%(Filename)1.obj + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + true + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Generation of config.h + copy %(FullPath) %(RootDir)%(Directory)\%(Filename).h + + ..\..\..\src\Include\config.h;%(Outputs) + Generation of config.h + copy %(FullPath) %(RootDir)%(Directory)\%(Filename).h + + ..\..\..\src\Include\config.h;%(Outputs) + Generation of config.h + copy %(FullPath) %(RootDir)%(Directory)\%(Filename).h + + ..\..\..\src\Include\config.h;%(Outputs) + Generation of config.h + copy %(FullPath) %(RootDir)%(Directory)\%(Filename).h + + ..\..\..\src\Include\config.h;%(Outputs) + + + true + true + + + true + true + + + + + true + true + + + true + true + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/FlightGear/FlightGear.vcxproj.filters b/projects/VC100/FlightGear/FlightGear.vcxproj.filters new file mode 100644 index 000000000..04d9c33ff --- /dev/null +++ b/projects/VC100/FlightGear/FlightGear.vcxproj.filters @@ -0,0 +1,2912 @@ + + + + + {5b5a7035-1789-4175-be3c-5ba77c37de44} + + + {8efb426e-e23e-42d6-9e6e-406c51e3a65c} + + + {7d7c9038-3ad4-4e1f-b67d-d27baa06f8e8} + + + {a2116df7-5e2f-40d8-a56f-ef96cdebd6c6} + + + {6ed1f548-d273-46c6-a0bb-b9ee2303f481} + + + {eacbd83d-0087-44ce-a78f-73d5498b2af1} + + + {d8c4cb07-9e19-43f0-a85a-dcf30b2545c7} + + + {183efdbf-00a8-427a-98da-dec58255128e} + + + {411dbaca-baf6-4170-b100-71a554209935} + + + {9436baf4-76e7-4226-a161-60eab79eb34b} + + + {2487fd19-c144-45be-aea7-289d221345b5} + + + {d371bccf-2c19-4079-b535-d031216e8490} + + + {27550555-bc98-408b-b4b0-4ebd297b6a3d} + + + {b3b2ce93-c999-472a-bfa6-06c1143c7fae} + + + {cb4d76a1-7275-4cd6-a305-63636b13ade9} + + + {ff59ef83-e9a1-46ac-8391-e268a9df0dfc} + + + {fabb1c71-61fb-4a57-88da-26945141c440} + + + {940c9533-0978-40ef-8d39-961d0ad89b4e} + + + {c9754169-5e10-4035-9544-6294c31d9709} + + + {131a31a9-d8bd-4a93-8cce-4798aa9c9bc9} + + + {0c65f02c-7bae-4389-bf94-5e2c67ba0e68} + + + {81173da0-37ce-43a2-85a6-0a5efcbfed91} + + + {bae088e3-d112-4668-b653-beb723426c96} + + + {6b8abb03-12fe-470a-a3d6-69f2b99cb082} + + + {56f378cc-a098-4fc1-b6db-708df701363c} + + + {10afb571-0a80-4493-9d07-71dbb3e128fb} + + + {5f18d822-922b-4bc5-a197-1f9c749d3aca} + + + {da1bf6b6-517a-4d9b-8de2-b43a126426a8} + + + {3a8fdd5f-359c-4867-b542-c680216b835b} + + + {5ecfbcb6-4b64-419f-8e53-f0cf299087bf} + + + {4d06a2fc-202e-44ed-bf26-22bbef505bc5} + + + {1965f1ef-8cc9-40d6-876b-6f1787bd300d} + + + {175c5293-cb40-47ec-bceb-f234bedfd31c} + + + {bed96b77-e07c-42c9-956a-df71af33a794} + + + {0a02d14a-7bb7-4564-a1b9-7a8f5ccc9cbd} + + + {044334ac-08b1-409d-acd5-b950b9d57ced} + + + {22009ac9-4ac5-4518-afd8-0b237abe6d00} + + + {9a55973a-7b5a-4fbd-9873-93012209f7e0} + + + {8cae8c55-248a-4be4-a389-24f651d7b9ea} + + + {8f862bbd-b18e-4576-989c-a9463482781a} + + + + + Lib_Aircraft + + + Lib_Aircraft + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_Autopilot + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit\build_in + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models\atmosphere + + + Lib_JSBSim\models\atmosphere + + + Lib_JSBSim\models\atmosphere + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\initialization + + + Lib_JSBSim\initialization + + + Lib_JSBSim\initialization + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_Flight + + + Lib_Flight + + + Lib_Flight + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Time + + + Lib_Time + + + Lib_Multiplayer + + + Lib_Multiplayer + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Model + + + Lib_Model + + + Lib_Model + + + Lib_Model + + + Lib_UFO + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Instrumentation\Lib_HUD + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_ExternalNet + + + ExternalPipe + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_Traffic + + + Lib_Traffic + + + Lib_Traffic + + + Lib_SP + + + Lib_SP + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_ATC + + + Lib_JSBSim\math + + + Lib_Flight + + + Lib_ATC + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Flight + + + Lib_Environment + + + Lib_ATC + + + Lib_Time + + + + + Lib_Aircraft + + + Lib_Aircraft + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_Airports + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_ATCDCL + + + Lib_Autopilot + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit + + + Lib_Cockpit\build_in + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\math + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models + + + Lib_JSBSim\models\atmosphere + + + Lib_JSBSim\models\atmosphere + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\flight_control + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\models\propulsion + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\input_output + + + Lib_JSBSim\initialization + + + Lib_JSBSim\initialization + + + Lib_JSBSim\initialization + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_LaRCsim + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_UIUCModel + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_YASim + + + Lib_Flight + + + Lib_Flight + + + Lib_Flight + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_GUI + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + Lib_Input + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + main + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Navaids + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Network + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Scenery + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Sound + + + Lib_Time + + + Lib_Time + + + Lib_Multiplayer + + + Lib_Multiplayer + + + Lib_Multiplayer + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Environment + + + Lib_Model + + + Lib_Model + + + Lib_Model + + + Lib_Model + + + Lib_UFO + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation + + + Lib_Instrumentation\Lib_HUD + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_Systems + + + Lib_ExternalNet + + + ExternalPipe + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_AIModel + + + Lib_Traffic + + + Lib_Traffic + + + Lib_Traffic + + + Lib_SP + + + Lib_SP + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_KLN89 + + + Lib_ATC + + + Lib_JSBSim\math + + + Lib_Flight + + + Lib_ATC + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Autopilot + + + Lib_Flight + + + Lib_Environment + + + Lib_ATC + + + Lib_Time + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/VC100/GPSsmooth/GPSsmooth.vcxproj b/projects/VC100/GPSsmooth/GPSsmooth.vcxproj new file mode 100644 index 000000000..01e9faee7 --- /dev/null +++ b/projects/VC100/GPSsmooth/GPSsmooth.vcxproj @@ -0,0 +1,208 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {AE9CE7E4-8F21-4C34-82DD-4D0371C210DA} + GPSsmooth + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)GPSsmooth.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)GPSsmooth.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/GPSsmooth/GPSsmooth.vcxproj.filters b/projects/VC100/GPSsmooth/GPSsmooth.vcxproj.filters new file mode 100644 index 000000000..8c91450e0 --- /dev/null +++ b/projects/VC100/GPSsmooth/GPSsmooth.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj b/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj new file mode 100644 index 000000000..4c52c0bac --- /dev/null +++ b/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj @@ -0,0 +1,211 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {92010FAB-17A3-4891-AE6D-507214FEA508} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)MIDGsmooth.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)MIDGsmooth.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj.filters b/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj.filters new file mode 100644 index 000000000..78a176a0a --- /dev/null +++ b/projects/VC100/MIDGsmooth/MIDGsmooth.vcxproj.filters @@ -0,0 +1,30 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC100/UGsmooth/UGsmooth.vcxproj b/projects/VC100/UGsmooth/UGsmooth.vcxproj new file mode 100644 index 000000000..44d5a52d7 --- /dev/null +++ b/projects/VC100/UGsmooth/UGsmooth.vcxproj @@ -0,0 +1,216 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {EEEEB798-BFFD-425F-86F9-03C6FE6B8B99} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)UGsmooth.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;net_d.lib;ul_d.lib;ws2_32.lib;winmm.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)UGsmooth.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + sg.lib;net.lib;ul.lib;ws2_32.lib;winmm.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/UGsmooth/UGsmooth.vcxproj.filters b/projects/VC100/UGsmooth/UGsmooth.vcxproj.filters new file mode 100644 index 000000000..a335f818e --- /dev/null +++ b/projects/VC100/UGsmooth/UGsmooth.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC100/fgadmin.rc b/projects/VC100/fgadmin.rc new file mode 100644 index 000000000..a25aa7813 --- /dev/null +++ b/projects/VC100/fgadmin.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON "flightgear.ico" diff --git a/projects/VC100/fgadmin/fgadmin.vcxproj b/projects/VC100/fgadmin/fgadmin.vcxproj new file mode 100644 index 000000000..c7c59e4ec --- /dev/null +++ b/projects/VC100/fgadmin/fgadmin.vcxproj @@ -0,0 +1,229 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {7004E589-7EA0-4AFD-B432-3D5E00B55049} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;HAVE_ZLIB;NOMINMAX;_USE_MATH_DEFINES;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + fltkd.lib;ul_d.lib;comctl32.lib;wsock32.lib;zlibd.lib;sg_d.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgadmin.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;HAVE_ZLIB;NOMINMAX;_USE_MATH_DEFINES;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + fltkd.lib;ul_d.lib;comctl32.lib;wsock32.lib;zlibd.lib;sg_d.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgadmin.pdb + Console + false + + + MachineX64 + + + + + MaxSpeed + AnySuitable + true + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;HAVE_ZLIB;NOMINMAX;_USE_MATH_DEFINES;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + + + Level3 + + + + + fltk.lib;ul.lib;sg.lib;comctl32.lib;wsock32.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + false + Windows + true + true + false + + + MachineX86 + + + + + X64 + + + MaxSpeed + OnlyExplicitInline + true + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;HAVE_ZLIB;NOMINMAX;_USE_MATH_DEFINES;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + MultiThreadedDLL + true + + + Level3 + + + + + fltk.lib;ul.lib;sg.lib;comctl32.lib;wsock32.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + false + Windows + true + true + false + + + MachineX64 + + + + + + + + + + + + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/fgadmin/fgadmin.vcxproj.filters b/projects/VC100/fgadmin/fgadmin.vcxproj.filters new file mode 100644 index 000000000..dfbf2a092 --- /dev/null +++ b/projects/VC100/fgadmin/fgadmin.vcxproj.filters @@ -0,0 +1,47 @@ + + + + + {563ffc76-1709-4474-b936-8c8b1ef2cf9e} + cpp;c;cxx;def;odl;idl;hpj;bat;asm + + + {1fb342bf-ece0-497c-9a9b-8bfb0b461604} + h;hpp;hxx;hm;inl;inc + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + + + + + + + \ No newline at end of file diff --git a/projects/VC100/fgjs/fgjs.vcxproj b/projects/VC100/fgjs/fgjs.vcxproj new file mode 100644 index 000000000..f9b1b2e4f --- /dev/null +++ b/projects/VC100/fgjs/fgjs.vcxproj @@ -0,0 +1,215 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {6749547A-6493-4754-8E0E-49FB3137C4CA} + fgjs + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;js_d.lib;ul_d.lib;zlibd.lib;winmm.lib;ws2_32.lib;OpenThreadsd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgjs.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;js_d.lib;ul_d.lib;zlibd.lib;winmm.lib;ws2_32.lib;OpenThreadsd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgjs.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;js.lib;ul.lib;zlib.lib;winmm.lib;ws2_32.lib;OpenThreads.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + + + X64 + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + sg.lib;js.lib;ul.lib;zlib.lib;winmm.lib;ws2_32.lib;OpenThreads.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/fgjs/fgjs.vcxproj.filters b/projects/VC100/fgjs/fgjs.vcxproj.filters new file mode 100644 index 000000000..038014706 --- /dev/null +++ b/projects/VC100/fgjs/fgjs.vcxproj.filters @@ -0,0 +1,36 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC100/fgviewer/fgviewer.vcxproj b/projects/VC100/fgviewer/fgviewer.vcxproj new file mode 100644 index 000000000..4c37c4d30 --- /dev/null +++ b/projects/VC100/fgviewer/fgviewer.vcxproj @@ -0,0 +1,207 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {0F13A557-EC52-481D-ADFB-9209C068FCEB} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\boost_1_43_0;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + opengl32.lib;osgd.lib;osgDBd.lib;osgViewerd.lib;osgGAd.lib;openthreadsd.lib;osgParticled.lib;osgUtild.lib;osgTextd.lib;ul_d.lib;sg_d.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgviewer.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\boost_1_43_0;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + opengl32.lib;osgd.lib;osgDBd.lib;osgViewerd.lib;osgGAd.lib;openthreadsd.lib;osgParticled.lib;osgUtild.lib;osgTextd.lib;ul_d.lib;sg_d.lib;zlibd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)fgviewer.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\boost_1_43_0;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + opengl32.lib;osg.lib;osgDB.lib;osgViewer.lib;osgGA.lib;openthreads.lib;osgParticle.lib;osgUtil.lib;osgText.lib;ul.lib;sg.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\boost_1_43_0;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + opengl32.lib;osg.lib;osgDB.lib;osgViewer.lib;osgGA.lib;openthreads.lib;osgParticle.lib;osgUtil.lib;osgText.lib;ul.lib;sg.lib;zlib.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/fgviewer/fgviewer.vcxproj.filters b/projects/VC100/fgviewer/fgviewer.vcxproj.filters new file mode 100644 index 000000000..fe8015b61 --- /dev/null +++ b/projects/VC100/fgviewer/fgviewer.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + \ No newline at end of file diff --git a/projects/VC100/flightgear.ico b/projects/VC100/flightgear.ico new file mode 100644 index 000000000..e041319f6 Binary files /dev/null and b/projects/VC100/flightgear.ico differ diff --git a/projects/VC100/flightgear.rc b/projects/VC100/flightgear.rc new file mode 100644 index 000000000..32cb5ae37 --- /dev/null +++ b/projects/VC100/flightgear.rc @@ -0,0 +1 @@ +FLIGHTGEAR ICON "flightgear.ico" diff --git a/projects/VC100/flightgear64.ico b/projects/VC100/flightgear64.ico new file mode 100644 index 000000000..4f262054d Binary files /dev/null and b/projects/VC100/flightgear64.ico differ diff --git a/projects/VC100/flightgear64.rc b/projects/VC100/flightgear64.rc new file mode 100644 index 000000000..0a929ebcb --- /dev/null +++ b/projects/VC100/flightgear64.rc @@ -0,0 +1 @@ +FLIGHTGEAR ICON "flightgear64.ico" diff --git a/projects/VC100/metar/metar.vcxproj b/projects/VC100/metar/metar.vcxproj new file mode 100644 index 000000000..d40361f04 --- /dev/null +++ b/projects/VC100/metar/metar.vcxproj @@ -0,0 +1,203 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {FC424099-5D77-4BC2-A93F-2EE59F816B51} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + sg_d.lib;ul_d.lib;net_d.lib;ws2_32.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)metar.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + sg_d.lib;ul_d.lib;net_d.lib;ws2_32.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)metar.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\..\SimGear;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;ul.lib;net.lib;ws2_32.lib;%(AdditionalDependencies) + ..\..\..\..\plib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\..\SimGear;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + + + sg.lib;ul.lib;net.lib;ws2_32.lib;%(AdditionalDependencies) + ..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/metar/metar.vcxproj.filters b/projects/VC100/metar/metar.vcxproj.filters new file mode 100644 index 000000000..927f4f99b --- /dev/null +++ b/projects/VC100/metar/metar.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + \ No newline at end of file diff --git a/projects/VC100/terrasync/terrasync.vcxproj b/projects/VC100/terrasync/terrasync.vcxproj new file mode 100644 index 000000000..2edb4903e --- /dev/null +++ b/projects/VC100/terrasync/terrasync.vcxproj @@ -0,0 +1,207 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {874D3F55-6048-4068-A7C2-7FA6AF1F30EA} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;HAVE_SVN_CLIENT_H;HAVE_LIBSVN_CLIENT_1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + ul_d.lib;sg_d.lib;net_d.lib;ws2_32.lib;libsvn_client-1.lib;libsvn_diff-1.lib;libsvn_delta-1.lib;libsvn_ra-1.lib;libsvn_subr-1.lib;libsvn_wc-1.lib;libapr-1.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)terrasync.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;HAVE_SVN_CLIENT_H;HAVE_LIBSVN_CLIENT_1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + ul_d.lib;sg_d.lib;net_d.lib;ws2_32.lib;libsvn_client-1.lib;libsvn_diff-1.lib;libsvn_delta-1.lib;libsvn_ra-1.lib;libsvn_subr-1.lib;libsvn_wc-1.lib;libapr-1.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)terrasync.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;HAVE_SVN_CLIENT_H;HAVE_LIBSVN_CLIENT_1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + ul.lib;sg.lib;net.lib;ws2_32.lib;libsvn_client-1.lib;libsvn_diff-1.lib;libsvn_delta-1.lib;libsvn_ra-1.lib;libsvn_subr-1.lib;libsvn_wc-1.lib;libapr-1.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;HAVE_SVN_CLIENT_H;HAVE_LIBSVN_CLIENT_1;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + ul.lib;sg.lib;net.lib;ws2_32.lib;libsvn_client-1.lib;libsvn_diff-1.lib;libsvn_delta-1.lib;libsvn_ra-1.lib;libsvn_subr-1.lib;libsvn_wc-1.lib;libapr-1.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/terrasync/terrasync.vcxproj.filters b/projects/VC100/terrasync/terrasync.vcxproj.filters new file mode 100644 index 000000000..f63c8e6b8 --- /dev/null +++ b/projects/VC100/terrasync/terrasync.vcxproj.filters @@ -0,0 +1,22 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + \ No newline at end of file diff --git a/projects/VC100/xmlgrep/xmlgrep.vcxproj b/projects/VC100/xmlgrep/xmlgrep.vcxproj new file mode 100644 index 000000000..f2894ce6f --- /dev/null +++ b/projects/VC100/xmlgrep/xmlgrep.vcxproj @@ -0,0 +1,193 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {1F40CF41-9836-4488-BAAF-560623665C12} + xmlgrep + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + true + $(OutDir)xmlgrep.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + + + Level3 + EditAndContinue + + + true + $(OutDir)xmlgrep.pdb + Console + false + + + MachineX64 + + + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + AnySuitable + + + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + MultiThreadedDLL + + + Level3 + ProgramDatabase + + + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/projects/VC100/xmlgrep/xmlgrep.vcxproj.filters b/projects/VC100/xmlgrep/xmlgrep.vcxproj.filters new file mode 100644 index 000000000..9bf80bae5 --- /dev/null +++ b/projects/VC100/xmlgrep/xmlgrep.vcxproj.filters @@ -0,0 +1,36 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC100/yasim/yasim.vcxproj b/projects/VC100/yasim/yasim.vcxproj new file mode 100644 index 000000000..cb3477d7b --- /dev/null +++ b/projects/VC100/yasim/yasim.vcxproj @@ -0,0 +1,261 @@ + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + {800CB1FF-C398-4B81-B3D6-8BBD9E0897D2} + Win32Proj + + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + Application + MultiByte + + + + + + + + + + + + + + + + + + + + + + + <_ProjectFileVersion>10.0.30319.1 + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + true + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + $(SolutionDir)$(Platform)\$(Configuration)\ + $(Platform)\$(Configuration)\ + false + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + AllRules.ruleset + + + + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;ul_d.lib;OpenThreadsd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)yasim.pdb + Console + false + + + MachineX86 + + + + + X64 + + + Disabled + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;_DEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + true + EnableFastChecks + MultiThreadedDebugDLL + true + + + Level3 + EditAndContinue + + + sg_d.lib;ul_d.lib;OpenThreadsd.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + $(OutDir)yasim.pdb + Console + false + + + MachineX64 + + + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + AnySuitable + + + sg.lib;ul.lib;OpenThreads.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100\OpenSceneGraph\lib;..\..\..\..\3rdParty\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX86 + + + + + X64 + + + ..\..\..\src;..\..\..\..\SimGear;..\..\..\..\install\msvc100-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_43_0;%(AdditionalIncludeDirectories) + WIN32;NDEBUG;_CONSOLE;NOMINMAX;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + true + + + Level3 + ProgramDatabase + + + sg.lib;ul.lib;OpenThreads.lib;%(AdditionalDependencies) + ..\..\..\..\install\msvc100-64\OpenSceneGraph\lib;..\..\..\..\3rdParty.x64\lib;%(AdditionalLibraryDirectories) + true + Console + true + true + false + + + MachineX64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {22540cd3-d3ca-4c86-a773-80aeee3acded} + + + + + + \ No newline at end of file diff --git a/projects/VC100/yasim/yasim.vcxproj.filters b/projects/VC100/yasim/yasim.vcxproj.filters new file mode 100644 index 000000000..02bac020e --- /dev/null +++ b/projects/VC100/yasim/yasim.vcxproj.filters @@ -0,0 +1,180 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + \ No newline at end of file diff --git a/projects/VC90/.gitignore b/projects/VC90/.gitignore new file mode 100644 index 000000000..d0e66af1f --- /dev/null +++ b/projects/VC90/.gitignore @@ -0,0 +1,5 @@ +FlightGear.ncb +FlightGear.suo +*.sln.cache +Win32 +x64 diff --git a/projects/VC90/FlightGear/.gitignore b/projects/VC90/FlightGear/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/FlightGear/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/FlightGear/FlightGear.vcproj b/projects/VC90/FlightGear/FlightGear.vcproj index bb6d3f382..eacb7a081 100644 --- a/projects/VC90/FlightGear/FlightGear.vcproj +++ b/projects/VC90/FlightGear/FlightGear.vcproj @@ -48,7 +48,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\..\..\src;..\..\..\src\include;..\..\..\..\SimGear;..\..\..\src\FDM\JSBSim;..\..\..\..\install\msvc90\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_39_0" - PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;ENABLE_ATCDCL" + PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS" StringPooling="true" BasicRuntimeChecks="0" RuntimeLibrary="3" @@ -137,7 +137,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="..\..\..\src;..\..\..\src\include;..\..\..\..\SimGear;..\..\..\src\FDM\JSBSim;..\..\..\..\install\msvc90-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_39_0" - PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE;ENABLE_ATCDCL" + PreprocessorDefinitions="_DEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE" StringPooling="true" BasicRuntimeChecks="0" RuntimeLibrary="3" @@ -225,7 +225,7 @@ Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\..\..\src;..\..\..\src\include;..\..\..\src\FDM\JSBSim;..\..\..\..\SimGear;..\..\..\..\install\msvc90\OpenSceneGraph\include;..\..\..\..\3rdParty\include;..\..\..\..\boost_1_39_0" - PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;ENABLE_ATCDCL" + PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS" StringPooling="true" RuntimeLibrary="2" EnableFunctionLevelLinking="true" @@ -313,7 +313,7 @@ Name="VCCLCompilerTool" InlineFunctionExpansion="1" AdditionalIncludeDirectories="..\..\..\src;..\..\..\src\include;..\..\..\src\FDM\JSBSim;..\..\..\..\SimGear;..\..\..\..\install\msvc90-64\OpenSceneGraph\include;..\..\..\..\3rdParty.x64\include;..\..\..\..\boost_1_39_0" - PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE;ENABLE_ATCDCL" + PreprocessorDefinitions="NDEBUG;WIN32;_CONSOLE;HAVE_CONFIG_H;FGFS;ENABLE_AUDIO_SUPPORT;_FG_NDEBUG;ENABLE_THREADS=1;FG_ENABLE_MULTIPASS_CLOUDS;ENABLE_SP_FMDS;_USE_MATH_DEFINES;FG_JPEG_SERVER;_CRT_SECURE_NO_WARNINGS;_CRT_NONSTDC_NO_WARNINGS;PU_USE_NATIVE" StringPooling="true" RuntimeLibrary="2" EnableFunctionLevelLinking="true" @@ -377,14 +377,6 @@ - - - - @@ -524,173 +516,1399 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + @@ -2541,6 +3759,14 @@ + + + + @@ -2549,6 +3775,14 @@ RelativePath="..\..\..\src\FDM\flight.hxx" > + + + + @@ -2613,6 +3847,14 @@ RelativePath="..\..\..\src\GUI\layout.hxx" > + + + + @@ -2645,10 +3887,14 @@ RelativePath="..\..\..\src\GUI\SafeTexFont.hxx" > - - - - + + + + @@ -3365,6 +4611,14 @@ RelativePath="..\..\..\src\Environment\environment_mgr.hxx" > + + + + @@ -4245,6 +5499,22 @@ + + + + + + + + diff --git a/projects/VC90/GPSsmooth/.gitignore b/projects/VC90/GPSsmooth/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/GPSsmooth/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/MIDGsmooth/.gitignore b/projects/VC90/MIDGsmooth/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/MIDGsmooth/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/UGsmooth/.gitignore b/projects/VC90/UGsmooth/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/UGsmooth/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/fgadmin/.gitignore b/projects/VC90/fgadmin/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/fgadmin/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/fgjs/.gitignore b/projects/VC90/fgjs/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/fgjs/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/fgviewer/.gitignore b/projects/VC90/fgviewer/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/fgviewer/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/metar/.gitignore b/projects/VC90/metar/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/metar/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/metar/metar.vcproj b/projects/VC90/metar/metar.vcproj index a3d11428a..fc1afafd8 100644 --- a/projects/VC90/metar/metar.vcproj +++ b/projects/VC90/metar/metar.vcproj @@ -223,7 +223,7 @@ Name="VCLinkerTool" AdditionalDependencies="sg.lib ul.lib net.lib ws2_32.lib" LinkIncremental="1" - AdditionalLibraryDirectories="..\..\..\..\plib" + AdditionalLibraryDirectories="..\..\..\..\3rdParty\lib" GenerateDebugInformation="true" SubSystem="1" OptimizeReferences="2" diff --git a/projects/VC90/terrasync/.gitignore b/projects/VC90/terrasync/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/terrasync/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/xmlgrep/.gitignore b/projects/VC90/xmlgrep/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/xmlgrep/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/projects/VC90/yasim/.gitignore b/projects/VC90/yasim/.gitignore new file mode 100644 index 000000000..8a9d35c88 --- /dev/null +++ b/projects/VC90/yasim/.gitignore @@ -0,0 +1 @@ +*.user diff --git a/src/AIModel/AIAircraft.cxx b/src/AIModel/AIAircraft.cxx index 0a8c1d546..92f458427 100644 --- a/src/AIModel/AIAircraft.cxx +++ b/src/AIModel/AIAircraft.cxx @@ -629,7 +629,12 @@ bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) { // << dist_to_go << ": Lead distance " // << lead_dist << " " << curr->name // << " Ground target speed " << groundTargetSpeed << endl; - + // if (trafficRef) { + // if (trafficRef->getCallSign() == "Transavia7584") { + // cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " " + // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << curr->name << endl; + // } + // } return dist_to_go < lead_dist; } diff --git a/src/AIModel/AIBallistic.cxx b/src/AIModel/AIBallistic.cxx index 5e3b15509..42e3f22c5 100644 --- a/src/AIModel/AIBallistic.cxx +++ b/src/AIModel/AIBallistic.cxx @@ -61,10 +61,12 @@ FGAIBallistic::FGAIBallistic(object_type ot) : _slave_load_to_ac(false), _contents_lb(0), _report_collision(false), + _report_expiry(false), _report_impact(false), _external_force(false), _impact_report_node(fgGetNode("/ai/models/model-impact", true)), - _old_height(0) + _old_height(0), + _elapsed_time(0) { no_roll = false; @@ -80,7 +82,8 @@ void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) { FGAIBase::readFromScenario(scFileNode); - //setPath(scFileNode->getStringValue("model", "Models/Geometry/rocket.ac")); + //setPath(scFileNode->getStringValue("model", "Models/Geometry/rocket.ac")); + setRandom(scFileNode->getBoolValue("random", false)); setAzimuth(scFileNode->getDoubleValue("azimuth", 0.0)); setElevation(scFileNode->getDoubleValue("elevation", 0)); setDragArea(scFileNode->getDoubleValue("eda", 0.007)); @@ -93,10 +96,11 @@ void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) { setCd(scFileNode->getDoubleValue("cd", 0.029)); //setMass(scFileNode->getDoubleValue("mass", 0.007)); setWeight(scFileNode->getDoubleValue("weight", 0.25)); - setStabilisation(scFileNode->getBoolValue("aero-stabilized", false)); + setStabilisation(scFileNode->getBoolValue("aero-stabilised", false)); setNoRoll(scFileNode->getBoolValue("no-roll", false)); - setRandom(scFileNode->getBoolValue("random", false)); setImpact(scFileNode->getBoolValue("impact", false)); + setExpiry(scFileNode->getBoolValue("expiry", false)); + setCollision(scFileNode->getBoolValue("collision", false)); setImpactReportNode(scFileNode->getStringValue("impact-reports")); setName(scFileNode->getStringValue("name", "Rocket")); setFuseRange(scFileNode->getDoubleValue("fuse-range", 0.0)); @@ -104,7 +108,7 @@ void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) { setSubID(scFileNode->getIntValue("SubID", 0)); setExternalForce(scFileNode->getBoolValue("external-force", false)); setForcePath(scFileNode->getStringValue("force-path", "")); - setForceStabilisation(scFileNode->getBoolValue("force-stabilized", false)); + setForceStabilisation(scFileNode->getBoolValue("force-stabilised", false)); setXoffset(scFileNode->getDoubleValue("x-offset", 0.0)); setYoffset(scFileNode->getDoubleValue("y-offset", 0.0)); setZoffset(scFileNode->getDoubleValue("z-offset", 0.0)); @@ -116,7 +120,6 @@ void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) { setSlaved(scFileNode->getBoolValue("slaved", false)); setSlavedLoad(scFileNode->getBoolValue("slaved-load", false)); setContentsNode(scFileNode->getStringValue("contents")); - setRandom(scFileNode->getBoolValue("random", false)); } bool FGAIBallistic::init(bool search_in_AI_path) { @@ -124,6 +127,16 @@ bool FGAIBallistic::init(bool search_in_AI_path) { _impact_reported = false; _collision_reported = false; + _expiry_reported = false; + + _impact_lat = 0; + _impact_lon = 0; + _impact_elev = 0; + _impact_hdg = 0; + _impact_pitch = 0; + _impact_roll = 0; + _impact_speed = 0; + invisible = false; _elapsed_time += (sg_random() * 100); @@ -131,6 +144,8 @@ bool FGAIBallistic::init(bool search_in_AI_path) { props->setStringValue("material/name", ""); props->setStringValue("name", _name.c_str()); props->setStringValue("submodels/path", _submodel.c_str()); + props->setStringValue("force/path", _force_path.c_str()); + //props->setStringValue("vector/path", _vector_path.c_str()); // start with high value so that animations don't trigger yet _ht_agl_ft = 1e10; @@ -167,7 +182,7 @@ void FGAIBallistic::bind() { if(_external_force){ props->tie("controls/force_stabilized", SGRawValuePointer(&_force_stabilised)); - props->tie("position/global-x", + props->tie("position/global-x", SGRawValueMethods(*this, &FGAIBase::_getCartPosX, 0)); props->tie("position/global-y", SGRawValueMethods(*this, &FGAIBase::_getCartPosY, 0)); @@ -181,7 +196,7 @@ void FGAIBallistic::bind() { SGRawValuePointer(&hs)); props->tie("position/altitude-ft", SGRawValueMethods(*this, &FGAIBase::_getAltitude, &FGAIBase::_setAltitude)); - props->tie("position/latitude-deg", + props->tie("position/latitude-deg", SGRawValueMethods(*this, &FGAIBase::_getLatitude, &FGAIBase::_setLatitude)); props->tie("position/longitude-deg", SGRawValueMethods(*this, &FGAIBase::_getLongitude, &FGAIBase::_setLongitude)); @@ -263,7 +278,13 @@ void FGAIBallistic::update(double dt) { } void FGAIBallistic::setAzimuth(double az) { - hdg = _azimuth = az; + + if (_random) + hdg = _azimuth = (az - 5 ) + (10 * sg_random()); + else + hdg = _azimuth = az; + + //cout << _name << " init hdg " << hdg << " random " << _random << endl; } void FGAIBallistic::setElevation(double el) { @@ -291,7 +312,12 @@ void FGAIBallistic::setDragArea(double a) { } void FGAIBallistic::setLife(double seconds) { - life = seconds; + + if (_random){ + life = seconds * _randomness + (seconds * (1 -_randomness) * sg_random()); + //cout << "life " << life << endl; + } else + life = seconds; } void FGAIBallistic::setBuoyancy(double fpss) { @@ -321,6 +347,11 @@ void FGAIBallistic::setMass(double m) { void FGAIBallistic::setWeight(double w) { _weight_lb = w; } + +void FGAIBallistic::setRandomness(double r) { + _randomness = r; +} + void FGAIBallistic::setRandom(bool r) { _random = r; } @@ -333,6 +364,11 @@ void FGAIBallistic::setCollision(bool c) { _report_collision = c; } +void FGAIBallistic::setExpiry(bool e) { + _report_expiry = e; + //cout << "_report_expiry " << _report_expiry << endl; +} + void FGAIBallistic::setExternalForce(bool f) { _external_force = f; } @@ -391,20 +427,20 @@ void FGAIBallistic::setContentsNode(const string& path) { bool FGAIBallistic::getSlaved() const { return _slave_to_ac; -} +} double FGAIBallistic::getMass() const { return _mass; } double FGAIBallistic::getContents() { - if(_contents_node) + if(_contents_node) _contents_lb = _contents_node->getChild("level-lbs",0,1)->getDoubleValue(); return _contents_lb; } void FGAIBallistic::setContents(double c) { - if(_contents_node) + if(_contents_node) _contents_lb = _contents_node->getChild("level-gal_us",0,1)->setDoubleValue(c); } @@ -441,8 +477,8 @@ bool FGAIBallistic::getHtAGL(){ props->setStringValue("material/name", names[0].c_str()); else props->setStringValue("material/name", ""); - /*cout << "material " << mat_name - << " solid " << _solid + /*cout << "material " << mat_name + << " solid " << _solid << " load " << _load_resistance << " frictionFactor " << frictionFactor << endl;*/ @@ -455,11 +491,11 @@ bool FGAIBallistic::getHtAGL(){ } double FGAIBallistic::getRecip(double az){ - // calculate the reciprocal of the input azimuth + // calculate the reciprocal of the input azimuth if(az - 180 < 0){ return az + 180; } else { - return az - 180; + return az - 180; } } @@ -479,17 +515,17 @@ void FGAIBallistic::setHt(double h, double dt, double coeff){ } void FGAIBallistic::setHdg(double az, double dt, double coeff){ - double recip = getRecip(hdg); - double c = dt / (coeff + dt); - //we need to ensure that we turn the short way to the new hdg - if (az < recip && az < hdg && hdg > 180) { - hdg = ((az + 360) * c) + (hdg * (1 - c)); - } else if (az > recip && az > hdg && hdg <= 180){ - hdg = ((az - 360) * c) + (hdg * (1 - c)); - } else { - hdg = (az * c) + (hdg * (1 - c)); - } - } + double recip = getRecip(hdg); + double c = dt / (coeff + dt); + //we need to ensure that we turn the short way to the new hdg + if (az < recip && az < hdg && hdg > 180) { + hdg = ((az + 360) * c) + (hdg * (1 - c)); + } else if (az > recip && az > hdg && hdg <= 180){ + hdg = ((az - 360) * c) + (hdg * (1 - c)); + } else { + hdg = (az * c) + (hdg * (1 - c)); + } +} double FGAIBallistic::getTgtXOffset() const { return _tgt_x_offset; @@ -497,7 +533,7 @@ double FGAIBallistic::getTgtXOffset() const { double FGAIBallistic::getTgtYOffset() const { return _tgt_y_offset; -} +} double FGAIBallistic::getTgtZOffset() const { return _tgt_z_offset; @@ -528,7 +564,7 @@ void FGAIBallistic::slaveToAC(double dt){ //update the mass (slugs) _mass = (_weight_lb + getContents()) / slugs_to_lbs; - /*cout <<"_mass "<<_mass <<" " << getContents() + /*cout <<"_mass "<<_mass <<" " << getContents() <<" " << getContents() / slugs_to_lbs << endl;*/ } @@ -536,15 +572,22 @@ void FGAIBallistic::Run(double dt) { _life_timer += dt; // if life = -1 the object does not die - if (_life_timer > life && life != -1) - setDie(true); + if (_life_timer > life && life != -1){ + + if (_report_expiry && !_expiry_reported){ + //cout<<"AIBallistic: expiry"<< endl; + handle_expiry(); + } else + setDie(true); + + } //set the contents in the appropriate tank or other property in the parent to zero setContents(0); - //randomise Cd by +- 5% + //randomise Cd by +- 10% if (_random) - _Cd = _Cd * 0.95 + (0.05 * sg_random()); + _Cd = _Cd * 0.90 + (0.10 * sg_random()); // Adjust Cd by Mach number. The equations are based on curves // for a conventional shell/bullet (no boat-tail). @@ -617,17 +660,18 @@ void FGAIBallistic::Run(double dt) { double friction_force_speed_east_deg_sec = 0; double force_elevation_deg = 0; - if (_external_force) { + if (_external_force) { + SGPropertyNode *n = fgGetNode(_force_path.c_str(), true); double force_lbs = n->getChild("force-lb", 0, true)->getDoubleValue(); force_elevation_deg = n->getChild("force-elevation-deg", 0, true)->getDoubleValue(); double force_azimuth_deg = n->getChild("force-azimuth-deg", 0, true)->getDoubleValue(); - + //resolve force into vertical and horizontal components: double v_force_lbs = force_lbs * sin( force_elevation_deg * SG_DEGREES_TO_RADIANS ); h_force_lbs = force_lbs * cos( force_elevation_deg * SG_DEGREES_TO_RADIANS ); - //ground interaction + //ground interaction if (getHtAGL()){ double deadzone = 0.1; @@ -639,7 +683,7 @@ void FGAIBallistic::Run(double dt) { normal_force_lbs = 0; pos.setElevationFt(0 + _ground_offset); - if (vs < 0) + if (vs < 0) vs = -vs * 0.5; // calculate friction @@ -648,7 +692,7 @@ void FGAIBallistic::Run(double dt) { static_friction_force_lbs = mu * normal_force_lbs * _frictionFactor; - //adjust horizontal force. We assume that a speed of <= 5 fps is static + //adjust horizontal force. We assume that a speed of <= 5 fps is static if (h_force_lbs <= static_friction_force_lbs && hs <= 5){ h_force_lbs = hs = 0; speed_north_fps = speed_east_fps = 0; @@ -694,9 +738,9 @@ void FGAIBallistic::Run(double dt) { double wind_speed_from_east_deg_sec = _wind_from_east / ft_per_deg_lon; //recombine the horizontal velocity components - hs = sqrt(((speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps) + hs = sqrt(((speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps) * (speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps)) - + ((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps) + + ((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps) * (speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps))); if (hs <= 0.00001) @@ -727,10 +771,10 @@ void FGAIBallistic::Run(double dt) { } } else { pos.setLatitudeDeg( pos.getLatitudeDeg() - + (speed_north_deg_sec - wind_speed_from_north_deg_sec + + (speed_north_deg_sec - wind_speed_from_north_deg_sec + force_speed_north_deg_sec + friction_force_speed_north_deg_sec) * dt ); pos.setLongitudeDeg( pos.getLongitudeDeg() - + (speed_east_deg_sec - wind_speed_from_east_deg_sec + + (speed_east_deg_sec - wind_speed_from_east_deg_sec + force_speed_east_deg_sec + friction_force_speed_east_deg_sec) * dt ); pos.setElevationFt(pos.getElevationFt() + vs * dt); } @@ -743,7 +787,7 @@ void FGAIBallistic::Run(double dt) { // recalculate elevation and azimuth (velocity vectors) _elevation = atan2( vs, hs ) * SG_RADIANS_TO_DEGREES; - _azimuth = atan2((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps), + _azimuth = atan2((speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps), (speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps)) * SG_RADIANS_TO_DEGREES; @@ -751,14 +795,19 @@ void FGAIBallistic::Run(double dt) { if (_azimuth < 0) _azimuth += 360; + //cout << "_azimuth " << _azimuth << " hdg "<< hdg << endl; + if (_aero_stabilised) { // we simulate rotational moment of inertia by using a filter + //cout<< "_aero_stabilised "<< endl; const double coeff = 0.9; // we assume a symetrical MI about the pitch and yaw axis setPch(_elevation, dt, coeff); setHdg(_azimuth, dt, coeff); } else if (_force_stabilised) { // we simulate rotational moment of inertia by using a filter - const double coeff = 0.9; + //cout<< "_force_stabilised "<< endl; + + const double coeff = 0.9; double ratio = h_force_lbs/(_mass * slugs_to_lbs); if (ratio > 1) ratio = 1; @@ -794,7 +843,7 @@ double FGAIBallistic::_getTime() const { void FGAIBallistic::handle_impact() { // try terrain intersection - if(!getHtAGL()) + if(!getHtAGL()) return; if (_ht_agl_ft <= 0) { @@ -809,6 +858,20 @@ void FGAIBallistic::handle_impact() { } } +void FGAIBallistic::handle_expiry() { + + SG_LOG(SG_GENERAL, SG_DEBUG, "AIBallistic: handle_expiry " << pos.getElevationM()); + + report_impact(pos.getElevationM()); + _expiry_reported = true; + + //if (life == -1){ + // invisible = true; + //} else if (_subID == 0) // kill the AIObject if there is no subsubmodel + // setDie(true); + +} + void FGAIBallistic::handle_collision() { const FGAIBase *object = manager->calcCollision(pos.getElevationFt(), @@ -832,10 +895,13 @@ void FGAIBallistic::report_impact(double elevation, const FGAIBase *object) _impact_roll = roll; SGPropertyNode *n = props->getNode("impact", true); - if (object) + if (object) { n->setStringValue("type", object->getTypeString()); - else + n->setStringValue("callsign", object->_callsign); + } else { n->setStringValue("type", "terrain"); + n->setStringValue("callsign", ""); + } n->setDoubleValue("longitude-deg", _impact_lon); n->setDoubleValue("latitude-deg", _impact_lat); @@ -857,7 +923,7 @@ SGVec3d FGAIBallistic::getCartHitchPos() const{ // convert geodetic positions to geocentered SGVec3d cartuserPos = getCartUserPos(); - SGVec3d cartPos = getCartPos(); + //SGVec3d cartPos = getCartPos(); // Transform to the right coordinate frame, configuration is done in // the x-forward, y-right, z-up coordinates (feet), computation @@ -895,7 +961,7 @@ void FGAIBallistic::setHitchPos(){ } double FGAIBallistic::getDistanceLoadToHitch() const { - //calculate the distance load to hitch + //calculate the distance load to hitch SGVec3d carthitchPos = getCartHitchPos(); SGVec3d cartPos = getCartPos(); @@ -967,7 +1033,7 @@ double FGAIBallistic::getBearingLoadToHitch() const { } double FGAIBallistic::getRelBrgHitchToUser() const { - //calculate the relative bearing + //calculate the relative bearing double az1, az2, distance; geo_inverse_wgs_84(hitchpos, userpos, &az1, &az2, &distance); @@ -1019,11 +1085,11 @@ void FGAIBallistic::formateToAC(double dt){ setHitchPos(); setHitchVelocity(dt); - // elapsed time has a random initialisation so that each + // elapsed time has a random initialisation so that each // wingman moves differently _elapsed_time += dt; - // we derive a sine based factor to give us smoothly + // we derive a sine based factor to give us smoothly // varying error between -1 and 1 double factor = sin(SGMiscd::deg2rad(_elapsed_time * 10)); double r_angle = 5 * factor; diff --git a/src/AIModel/AIBallistic.hxx b/src/AIModel/AIBallistic.hxx index 859bcd109..09efbd6e1 100644 --- a/src/AIModel/AIBallistic.hxx +++ b/src/AIModel/AIBallistic.hxx @@ -68,8 +68,10 @@ public: void setWeight( double w ); void setNoRoll( bool nr ); void setRandom( bool r ); + void setRandomness( double r ); void setName(const string&); void setCollision(bool c); + void setExpiry(bool e); void setImpact(bool i); void setImpactReportNode(const string&); void setContentsNode(const string&); @@ -150,7 +152,8 @@ private: bool _wind; // if true, local wind will be applied to object double _Cd; // drag coefficient double _mass; // slugs - bool _random; // modifier for Cd + bool _random; // modifier for Cd, life, az + double _randomness; // dimension for _random, only applies to life at present double _load_resistance; // ground load resistanc N/m^2 double _frictionFactor; // dimensionless modifier for Coefficient of Friction bool _solid; // if true ground is solid for FDMs @@ -164,6 +167,7 @@ private: bool _report_collision; // if true a collision point with AI Objects is calculated bool _report_impact; // if true an impact point on the terrain is calculated bool _external_force; // if true then apply external force + bool _report_expiry; SGPropertyNode_ptr _impact_report_node; // report node for impact and collision SGPropertyNode_ptr _contents_node; // report node for impact and collision @@ -181,6 +185,7 @@ private: const SGMaterial* _material; void handle_collision(); + void handle_expiry(); void handle_impact(); void report_impact(double elevation, const FGAIBase *target = 0); void slaveToAC(double dt); @@ -192,13 +197,13 @@ private: double getDistanceLoadToHitch() const; double getElevLoadToHitch() const; double getBearingLoadToHitch() const; + double getRecip(double az); double getMass() const; double hs; double _ground_offset; double _load_offset; - double _force; double _old_height; SGVec3d _oldcarthitchPos; diff --git a/src/AIModel/AIBase.cxx b/src/AIModel/AIBase.cxx index de107a682..d143296a1 100644 --- a/src/AIModel/AIBase.cxx +++ b/src/AIModel/AIBase.cxx @@ -81,6 +81,8 @@ FGAIBase::FGAIBase(object_type ot) : delete_me = false; _impact_reported = false; _collision_reported = false; + _expiry_reported = false; + _subID = 0; _x_offset = 0; @@ -579,6 +581,10 @@ bool FGAIBase::_getCollisionData() { return _collision_reported; } +bool FGAIBase::_getExpiryData() { + return _expiry_reported; +} + bool FGAIBase::_getImpactData() { return _impact_reported; } diff --git a/src/AIModel/AIBase.hxx b/src/AIModel/AIBase.hxx index 1ab3a640e..e47f778d0 100644 --- a/src/AIModel/AIBase.hxx +++ b/src/AIModel/AIBase.hxx @@ -40,7 +40,7 @@ class SGMaterial; class FGAIManager; class FGAIFlightPlan; -class FGAIBase : public osg::Referenced { +class FGAIBase : public SGReferenced { public: enum object_type { otNull = 0, otAircraft, otShip, otCarrier, otBallistic, @@ -177,6 +177,7 @@ protected: bool _impact_reported; bool _collision_reported; + bool _expiry_reported; double _impact_lat; double _impact_lon; @@ -246,6 +247,7 @@ public: bool _getImpact(); bool _getImpactData(); bool _getCollisionData(); + bool _getExpiryData(); SGPropertyNode* _getProps() const; diff --git a/src/AIModel/AICarrier.cxx b/src/AIModel/AICarrier.cxx index ff2a42014..b6487519d 100644 --- a/src/AIModel/AICarrier.cxx +++ b/src/AIModel/AICarrier.cxx @@ -57,6 +57,7 @@ void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) { setMaxLong(scFileNode->getDoubleValue("max-long", 0)); setMinLong(scFileNode->getDoubleValue("min-long", 0)); setMPControl(scFileNode->getBoolValue("mp-control", false)); + setAIControl(scFileNode->getBoolValue("ai-control", false)); SGPropertyNode* flols = scFileNode->getChild("flols-pos"); if (flols) { @@ -121,6 +122,10 @@ void FGAICarrier::setMPControl(bool c) { MPControl = c; } +void FGAICarrier::setAIControl(bool c) { + AIControl = c; +} + void FGAICarrier::update(double dt) { // Now update the position and heading. This will compute new hdg and // roll values required for the rotation speed computation. @@ -134,8 +139,8 @@ void FGAICarrier::update(double dt) { TurnToLaunch(); } else if(turn_to_recovery_hdg ){ TurnToRecover(); - } else if(OutsideBox() || returning ) {// check that the carrier is inside - ReturnToBox(); // the operating box, + } else if(OutsideBox() || returning ) {// check that the carrier is inside + ReturnToBox(); // the operating box, } else { TurnToBase(); } @@ -168,10 +173,10 @@ void FGAICarrier::update(double dt) { eyeWrtCarrier = ec2body.transform(eyeWrtCarrier); // the eyepoints vector wrt the flols position SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off; - + // the distance from the eyepoint to the flols dist = norm(eyeWrtFlols); - + // now the angle, positive angles are upwards if (fabs(dist) < SGLimits::min()) { angle = 0; @@ -180,7 +185,7 @@ void FGAICarrier::update(double dt) { sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle)); angle = SGMiscd::rad2deg(asin(sAngle)); } - + // set the value of source if ( angle <= 4.35 && angle > 4.01 ) source = 1; @@ -436,12 +441,12 @@ void FGAICarrier::TurnToRecover(){ if (wind_speed_kts < 3){ tgt_heading = base_course + 60; } else if (rel_wind < -9 && rel_wind >= -180){ - tgt_heading = wind_from_deg; + tgt_heading = wind_from_deg; } else if (rel_wind > -7 && rel_wind < 45){ tgt_heading = wind_from_deg + 60; } else if (rel_wind >=45 && rel_wind < 180){ tgt_heading = wind_from_deg + 45; - } else + } else tgt_heading = hdg; SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0); diff --git a/src/AIModel/AICarrier.hxx b/src/AIModel/AICarrier.hxx index 9df40db41..da3380502 100644 --- a/src/AIModel/AICarrier.hxx +++ b/src/AIModel/AICarrier.hxx @@ -58,6 +58,7 @@ public: void setMaxLong( double deg ); void setMinLong( double deg ); void setMPControl( bool c ); + void setAIControl( bool c ); void TurnToLaunch(); void TurnToRecover(); void TurnToBase(); diff --git a/src/AIModel/AIFlightPlan.cxx b/src/AIModel/AIFlightPlan.cxx index 381f9e944..60952d799 100644 --- a/src/AIModel/AIFlightPlan.cxx +++ b/src/AIModel/AIFlightPlan.cxx @@ -175,20 +175,12 @@ FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac, if (wpt->name == "END") wpt->finished = true; else wpt->finished = false; waypoints.push_back(wpt); - } - } - catch (const sg_exception &) { - SG_LOG(SG_GENERAL, SG_WARN, - "Error reading AI flight plan: "); - cerr << "Errno = " << errno << endl; - if (errno == ENOENT) - { - SG_LOG(SG_GENERAL, SG_WARN, "Reason: No such file or directory"); - } - } + } // of node loop + } catch (const sg_exception &e) { + SG_LOG(SG_GENERAL, SG_WARN, "Error reading AI flight plan: " << + e.getMessage() << " from " << e.getOrigin()); } - else - { + } else { // cout << path.str() << endl; // cout << "Trying to create this plan dynamically" << endl; // cout << "Route from " << dep->id << " to " << arr->id << endl; @@ -405,7 +397,7 @@ void FGAIFlightPlan::setLeadDistance(double speed, double bearing, return; } if (speed < 25) { - turn_radius = ((360/30)*15) / (2*M_PI); + turn_radius = ((360/30)*fabs(speed)) / (2*M_PI); } else turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank @@ -419,9 +411,16 @@ void FGAIFlightPlan::setLeadDistance(double speed, double bearing, //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2); - // if ((errno == EDOM) || (errno == ERANGE) || lead_distance < 1.0) - // { - // } + if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) { + // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound + // << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle << ". Turn radius = " << turn_radius << endl; + lead_distance = 3 * turn_radius; + return; + } + if ((leadInAngle > 90) && (current->on_ground == true)) { + lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2); + return; + } } void FGAIFlightPlan::setLeadDistance(double distance_ft){ diff --git a/src/AIModel/AIFlightPlan.hxx b/src/AIModel/AIFlightPlan.hxx index 2d3b2ef9d..c70028dd3 100644 --- a/src/AIModel/AIFlightPlan.hxx +++ b/src/AIModel/AIFlightPlan.hxx @@ -149,7 +149,7 @@ private: void createClimb(FGAIAircraft *, bool, FGAirport *, double, double, const string&); void createCruise(FGAIAircraft *, bool, FGAirport*, FGAirport*, double, double, double, double, const string&); void createDecent(FGAIAircraft *, FGAirport *, const string&); - void createLanding(FGAIAircraft *, FGAirport *); + void createLanding(FGAIAircraft *, FGAirport *, const string&); void createParking(FGAIAircraft *, FGAirport *, double radius); void deleteWaypoints(); void resetWaypoints(); diff --git a/src/AIModel/AIFlightPlanCreate.cxx b/src/AIModel/AIFlightPlanCreate.cxx index 64df906f5..d2cd7a81e 100644 --- a/src/AIModel/AIFlightPlanCreate.cxx +++ b/src/AIModel/AIFlightPlanCreate.cxx @@ -75,7 +75,7 @@ void FGAIFlightPlan::create(FGAIAircraft *ac, FGAirport *dep, FGAirport *arr, in createDecent(ac, arr, fltType); break; case 7: - createLanding(ac, arr); + createLanding(ac, arr, fltType); break; case 8: createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline); @@ -366,23 +366,36 @@ void FGAIFlightPlan::createLandingTaxi(FGAIAircraft *ac, FGAirport *apt, /******************************************************************* * CreateTakeOff - * initialize the Aircraft at the parking location + * A note on units: + * - Speed -> knots -> nm/hour + * - distance along runway =-> meters + * - accel / decel -> is given as knots/hour, but this is highly questionable: + * for a jet_transport performance class, a accel / decel rate of 5 / 2 is + * given respectively. According to performance data.cxx, a value of kts / second seems + * more likely however. + * ******************************************************************/ void FGAIFlightPlan::createTakeOff(FGAIAircraft *ac, bool firstFlight, FGAirport *apt, double speed, const string &fltType) { double accel = ac->getPerformance()->acceleration(); double vTaxi = ac->getPerformance()->vTaxi(); double vRotate = ac->getPerformance()->vRotate(); -// double vTakeoff = ac->getPerformance()->vTakeoff(); + double vTakeoff = ac->getPerformance()->vTakeoff(); double vClimb = ac->getPerformance()->vClimb(); + + double accelMetric = (accel * SG_NM_TO_METER) / 3600; + double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600; + double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600; + double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600; + double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600; // Acceleration = dV / dT // Acceleration X dT = dV // dT = dT / Acceleration //d = (Vf^2 - Vo^2) / (2*a) -// double accelTime = (vRotate - vTaxi) / accel; + //double accelTime = (vRotate - vTaxi) / accel; //cerr << "Using " << accelTime << " as total acceleration time" << endl; - double accelDistance = (vRotate*vRotate - vTaxi*vTaxi) / (2*accel); - //cerr << "Using " << accelDistance << " " << accel << " " << vRotate << endl; + double accelDistance = (vRotateMetric*vRotateMetric - vTaxiMetric*vTaxiMetric) / (2*accelMetric); + cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl; waypoint *wpt; // Get the current active runway, based on code from David Luff // This should actually be unified and extended to include @@ -400,14 +413,20 @@ void FGAIFlightPlan::createTakeOff(FGAIAircraft *ac, bool firstFlight, FGAirport double airportElev = apt->getElevation(); // Acceleration point, 105 meters into the runway, SGGeod accelPoint = rwy->pointOnCenterline(105.0); - wpt = createOnGround(ac, "accel", accelPoint, airportElev, vClimb); + wpt = createOnGround(ac, "accel", accelPoint, airportElev, vRotate); + waypoints.push_back(wpt); + + + accelDistance = (vTakeoffMetric*vTakeoffMetric - vTaxiMetric*vTaxiMetric) / (2*accelMetric); + cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl; + accelPoint = rwy->pointOnCenterline(105.0+accelDistance); + wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff); waypoints.push_back(wpt); - //Start Climbing to 3000 ft. Let's do this - // at the center of the runway for now: - SGGeod rotate = rwy->pointOnCenterline(105.0+accelDistance); - wpt = cloneWithPos(ac, wpt, "SOC", rotate); - wpt->altitude = airportElev+1000; + accelDistance = ((vTakeoffMetric*1.1)*(vTakeoffMetric*1.1) - vTaxiMetric*vTaxiMetric) / (2*accelMetric); + cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl; + accelPoint = rwy->pointOnCenterline(105.0+accelDistance); + wpt = createOnGround(ac, "rotate", accelPoint, airportElev+1000, vTakeoff*1.1); wpt->on_ground = false; waypoints.push_back(wpt); @@ -471,7 +490,7 @@ void FGAIFlightPlan::createDecent(FGAIAircraft *ac, FGAirport *apt, const string { // Ten thousand ft. Slowing down to 240 kts waypoint *wpt; -double vDecent = ac->getPerformance()->vDescent(); + double vDecent = ac->getPerformance()->vDescent(); double vApproach = ac->getPerformance()->vApproach(); //Beginning of Decent @@ -499,13 +518,31 @@ double vDecent = ac->getPerformance()->vDescent(); * CreateLanding * initialize the Aircraft at the parking location ******************************************************************/ -void FGAIFlightPlan::createLanding(FGAIAircraft *ac, FGAirport *apt) +void FGAIFlightPlan::createLanding(FGAIAircraft *ac, FGAirport *apt, const string &fltType) { double vTouchdown = ac->getPerformance()->vTouchdown(); double vTaxi = ac->getPerformance()->vTaxi(); + string rwyClass = getRunwayClassFromTrafficType(fltType); + double heading = ac->getTrafficRef()->getCourse(); + apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway, heading); + rwy = apt->getRunwayByIdent(activeRunway); + + waypoint *wpt; double aptElev = apt->getElevation(); + + SGGeod coord; + char buffer[12]; + for (int i = 1; i < 10; i++) { + snprintf(buffer, 12, "wpt%d", i); + coord = rwy->pointOnCenterline(rwy->lengthM() * (i/10.0)); + wpt = createOnGround(ac, buffer, coord, aptElev, (vTouchdown/i)); + wpt->crossat = apt->getElevation(); + waypoints.push_back(wpt); + } + + /* //Runway Threshold wpt = createOnGround(ac, "Threshold", rwy->threshold(), aptElev, vTouchdown); wpt->crossat = apt->getElevation(); @@ -519,6 +556,7 @@ void FGAIFlightPlan::createLanding(FGAIAircraft *ac, FGAirport *apt) wpt = createOnGround(ac, "Roll Out", rollOut, aptElev, vTaxi); wpt->crossat = apt->getElevation(); waypoints.push_back(wpt); + */ } /******************************************************************* diff --git a/src/AIModel/AIFlightPlanCreateCruise.cxx b/src/AIModel/AIFlightPlanCreateCruise.cxx index d20a2134b..13df4b607 100644 --- a/src/AIModel/AIFlightPlanCreateCruise.cxx +++ b/src/AIModel/AIFlightPlanCreateCruise.cxx @@ -38,7 +38,6 @@ #include "AIAircraft.hxx" #include "performancedata.hxx" - using std::iostream; void FGAIFlightPlan::evaluateRoutePart(double deplat, @@ -55,28 +54,18 @@ void FGAIFlightPlan::evaluateRoutePart(double deplat, SGGeoc arr(SGGeoc::fromDegM(arrlon, arrlat, 100.0)); SGVec3d a = SGVec3d::fromGeoc(dep); - SGVec3d b = SGVec3d::fromGeoc(arr); - SGVec3d _cross = cross(b, a); + SGVec3d nb = normalize(SGVec3d::fromGeoc(arr)); + SGVec3d na = normalize(a); + + SGVec3d _cross = cross(nb, na); - double angle = sgACos(dot(a, b)); + double angle = acos(dot(na, nb)); + const double angleStep = 0.05 * SG_DEGREES_TO_RADIANS; tmpNode = 0; - for (double ang = 0.0; ang < angle; ang += 0.05) - { - sgdVec3 newPos; - sgdMat4 matrix; - //cerr << "Angle = " << ang << endl; - sgdMakeRotMat4(matrix, ang, _cross.data()); - for(int j = 0; j < 3; j++) - { - newPos[j] =0.0; - for (int k = 0; k<3; k++) - { - newPos[j] += matrix[j][k]*a[k]; - } - } - - //cerr << "1"<< endl; - SGGeod geod = SGGeod::fromCart(SGVec3d(newPos[0], newPos[1], newPos[2])); + for (double ang = 0.0; ang < angle; ang += angleStep) + { + SGQuatd q = SGQuatd::fromAngleAxis(ang, _cross); + SGGeod geod = SGGeod::fromCart(q.transform(a)); prevNode = tmpNode; tmpNode = globals->get_airwaynet()->findNearestNode(geod); diff --git a/src/AIModel/AIManager.cxx b/src/AIModel/AIManager.cxx index ed4f4a534..315920ab5 100644 --- a/src/AIModel/AIManager.cxx +++ b/src/AIModel/AIManager.cxx @@ -18,6 +18,8 @@ // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +#include + #include #include #include @@ -381,7 +383,7 @@ FGAIManager::getStartPosition(const string& id, const string& pid, std::string pnumber = scEntry->getStringValue("pennant-number"); std::string name = scEntry->getStringValue("name"); if (type == "carrier" && (pnumber == id || name == id)) { - osg::ref_ptr carrier = new FGAICarrier; + SGSharedPtr carrier = new FGAICarrier; carrier->readFromScenario(scEntry); if (carrier->getParkPosition(pid, geodPos, hdng, uvw)) { diff --git a/src/AIModel/AIManager.hxx b/src/AIModel/AIManager.hxx index 3f6dd9c2f..8f582801a 100644 --- a/src/AIModel/AIManager.hxx +++ b/src/AIModel/AIManager.hxx @@ -46,7 +46,7 @@ class FGAIManager : public SGSubsystem public: // A list of pointers to AI objects - typedef list > ai_list_type; + typedef list > ai_list_type; typedef ai_list_type::iterator ai_list_iterator; typedef ai_list_type::const_iterator ai_list_const_iterator; diff --git a/src/AIModel/AIMultiplayer.cxx b/src/AIModel/AIMultiplayer.cxx index ab9cc5c3c..d2fb505c0 100644 --- a/src/AIModel/AIMultiplayer.cxx +++ b/src/AIModel/AIMultiplayer.cxx @@ -72,6 +72,9 @@ void FGAIMultiplayer::bind() { props->tie("refuel/contact", SGRawValuePointer(&contact)); props->setBoolValue("tanker",isTanker); + props->tie("controls/invisible", + SGRawValuePointer(&invisible)); + #define AIMPROProp(type, name) \ SGRawValueMethods(*this, &FGAIMultiplayer::get##name) @@ -97,6 +100,7 @@ void FGAIMultiplayer::unbind() { //props->untie("callsign"); props->untie("controls/allow-extrapolation"); props->untie("controls/lag-adjust-system-speed"); + props->untie("controls/invisible"); props->untie("refuel/contact"); } diff --git a/src/AIModel/AIShip.cxx b/src/AIModel/AIShip.cxx index b0e0eb65f..41f09550e 100644 --- a/src/AIModel/AIShip.cxx +++ b/src/AIModel/AIShip.cxx @@ -52,6 +52,7 @@ _next_run(0), _lead_angle(0), _xtrack_error(0), _tunnel(false), +_initial_tunnel(false), _curr_alt(0), _prev_alt(0), _until_time(""), diff --git a/src/AIModel/submodel.cxx b/src/AIModel/submodel.cxx index 7b946f0b8..0958923c1 100644 --- a/src/AIModel/submodel.cxx +++ b/src/AIModel/submodel.cxx @@ -37,6 +37,7 @@ FGSubmodelMgr::FGSubmodelMgr() string contents_node; contrail_altitude = 30000; _count = 0; + _found_sub = true; } FGSubmodelMgr::~FGSubmodelMgr() @@ -82,7 +83,9 @@ void FGSubmodelMgr::init() void FGSubmodelMgr::postinit() { // postinit, so that the AI list is populated loadAI(); - loadSubmodels(); + + while (_found_sub) + loadSubmodels(); //TODO reload submodels if an MP ac joins } @@ -106,6 +109,7 @@ void FGSubmodelMgr::update(double dt) _impact = false; _hit = false; + _expiry = false; // check if the submodel hit an object or terrain sm_list = ai->get_ai_list(); @@ -115,14 +119,18 @@ void FGSubmodelMgr::update(double dt) for (; sm_list_itr != end; ++sm_list_itr) { _impact = (*sm_list_itr)->_getImpactData(); _hit = (*sm_list_itr)->_getCollisionData(); + _expiry = (*sm_list_itr)->_getExpiryData(); int parent_subID = (*sm_list_itr)->_getSubID(); + //SG_LOG(SG_GENERAL, SG_DEBUG, "Submodel: Impact " << _impact << " hit! " // << _hit <<" parent_subID " << parent_subID); + if ( parent_subID == 0) // this entry in the list has no associated submodel continue; // so we can continue - if (_impact || _hit) { - //SG_LOG(SG_GENERAL, SG_DEBUG, "Submodel: Impact " << _impact << " hit! " << _hit ); + if (_impact || _hit || _expiry) { + // SG_LOG(SG_GENERAL, SG_ALERT, "Submodel: Impact " << _impact << " hit! " << _hit + //<< " exipiry :-( " << _expiry ); submodel_iterator = submodels.begin(); @@ -139,9 +147,11 @@ void FGSubmodelMgr::update(double dt) _parent_roll = (*sm_list_itr)->_getImpactRoll(); _parent_speed = (*sm_list_itr)->_getImpactSpeed(); (*submodel_iterator)->first_time = true; + //cout << "Impact: parent SubID = child_ID elev " << _parent_elev << endl; - if (release(*submodel_iterator, dt)) + if (release(*submodel_iterator, dt)) (*sm_list_itr)->setDie(true); + } ++submodel_iterator; @@ -169,64 +179,26 @@ void FGSubmodelMgr::update(double dt) if ((*submodel_iterator)->trigger_node != 0) { _trigger_node = (*submodel_iterator)->trigger_node; trigger = _trigger_node->getBoolValue(); - //cout << "trigger node found " << trigger << endl; + //cout << (*submodel_iterator)->name << "trigger node found " << trigger << endl; } else { trigger = true; //cout << (*submodel_iterator)->name << "trigger node not found " << trigger << endl; } - if (trigger) { - int id = (*submodel_iterator)->id; - string name = (*submodel_iterator)->name; - // don't release submodels from AI Objects if they are - // too far away to be seen. id 0 is not an AI model, - // so we can skip the whole process - sm_list_iterator sm_list_itr = sm_list.begin(); - sm_list_iterator end = sm_list.end(); - - while (sm_list_itr != end) { - in_range = true; - - if (id == 0) { - //SG_LOG(SG_GENERAL, SG_DEBUG, - // "Submodels: continuing: " << id << " name " << name ); - ++sm_list_itr; - continue; - } - - int parent_id = (*submodel_iterator)->id; - - if (parent_id == id) { - double parent_lat = (*sm_list_itr)->_getLatitude(); - double parent_lon = (*sm_list_itr)->_getLongitude(); - string parent_name = (*sm_list_itr)->_getName(); - double own_lat = _user_lat_node->getDoubleValue(); - double own_lon = _user_lon_node->getDoubleValue(); - double range_nm = getRange(parent_lat, parent_lon, own_lat, own_lon); - //cout << "parent name " << parent_name << ", "<< parent_id << ", "<< parent_lat << ", " << parent_lon << endl; - //cout << "own name " << own_lat << ", " << own_lon << " range " << range_nm << endl; - - if (range_nm > 15) { - //SG_LOG(SG_GENERAL, SG_DEBUG, - // "Submodels: skipping release, out of range: " << id); - in_range = false; - } - } - - ++sm_list_itr; - } // end while - - /*SG_LOG(SG_GENERAL, SG_DEBUG, - "Submodels end: " << (*submodel_iterator)->id - << " name " << (*submodel_iterator)->name - << " count " << (*submodel_iterator)->count - << " in range " << in_range);*/ + if (trigger && (*submodel_iterator)->count != 0) { - if ((*submodel_iterator)->count != 0 && in_range) - release(*submodel_iterator, dt); + int id = (*submodel_iterator)->id; + string name = (*submodel_iterator)->name; + + /*SG_LOG(SG_GENERAL, SG_DEBUG, + "Submodels end: " << (*submodel_iterator)->id + << " name " << (*submodel_iterator)->name + << " count " << (*submodel_iterator)->count + << " in range " << in_range);*/ - } else - (*submodel_iterator)->first_time = true; + release(*submodel_iterator, dt); + } else + (*submodel_iterator)->first_time = true; ++submodel_iterator; } // end while @@ -247,9 +219,11 @@ bool FGSubmodelMgr::release(submodel *sm, double dt) sm->timer += dt; if (sm->timer < sm->delay) { - //cout << "not yet: timer" << sm->timer << " delay " << sm->delay<< endl; + //cout << "not yet: timer " << sm->timer << " delay " << sm->delay << endl; return false; } + + //cout << "released timer: " << sm->timer << " delay " << sm->delay << endl; sm->timer = 0.0; @@ -262,9 +236,12 @@ bool FGSubmodelMgr::release(submodel *sm, double dt) FGAIBallistic* ballist = new FGAIBallistic; ballist->setPath(sm->model.c_str()); - ballist->setLatitude(IC.lat); - ballist->setLongitude(IC.lon); - ballist->setAltitude(IC.alt); + ballist->setName(sm->name); + ballist->setRandom(sm->random); + ballist->setRandomness(sm->randomness); + ballist->setLatitude(offsetpos.getLatitudeDeg()); + ballist->setLongitude(offsetpos.getLongitudeDeg()); + ballist->setAltitude(offsetpos.getElevationFt()); ballist->setAzimuth(IC.azimuth); ballist->setElevation(IC.elevation); ballist->setRoll(IC.roll); @@ -279,8 +256,8 @@ bool FGSubmodelMgr::release(submodel *sm, double dt) ballist->setCd(sm->cd); ballist->setStabilisation(sm->aero_stabilised); ballist->setNoRoll(sm->no_roll); - ballist->setName(sm->name); ballist->setCollision(sm->collision); + ballist->setExpiry(sm->expiry); ballist->setImpact(sm->impact); ballist->setImpactReportNode(sm->impact_report); ballist->setFuseRange(sm->fuse_range); @@ -293,7 +270,6 @@ bool FGSubmodelMgr::release(submodel *sm, double dt) if (sm->count > 0) sm->count--; - return true; } @@ -338,16 +314,11 @@ void FGSubmodelMgr::transform(submodel *sm) //cout << " name " << name << " id " << id << " sub id" << sub_id << endl; - if (_impact || _hit) { + // set the Initial Conditions for the types of submodel parent + + if (_impact || _hit || _expiry) { // set the data for a submodel tied to a submodel _count++; - //cout << "Submodels: release sub sub " << _count<< endl; - //cout << " id " << sm->id - // << " lat " << _parent_lat - // << " lon " << _parent_lon - // << " elev " << _parent_elev - // << " name " << sm->name - // << endl; IC.lat = _parent_lat; IC.lon = _parent_lon; @@ -362,10 +333,7 @@ void FGSubmodelMgr::transform(submodel *sm) } else if (id == 0) { //set the data for a submodel tied to the main model - /*cout << "Submodels: release main sub " << endl; - cout << " name " << sm->name - << " id" << sm->id - << endl;*/ + IC.lat = _user_lat_node->getDoubleValue(); IC.lon = _user_lon_node->getDoubleValue(); IC.alt = _user_alt_node->getDoubleValue(); @@ -413,12 +381,22 @@ void FGSubmodelMgr::transform(submodel *sm) cout << "speed north " << IC.speed_north_fps << endl ; cout << "parent speed fps in" << IC.speed << "sm speed in " << sm->speed << endl ;*/ + // Set the Initial Conditions that are common to all types of parent IC.wind_from_east = _user_wind_from_east_node->getDoubleValue(); IC.wind_from_north = _user_wind_from_north_node->getDoubleValue(); - in[0] = sm->x_offset; - in[1] = sm->y_offset; - in[2] = sm->z_offset; + userpos.setLatitudeDeg(IC.lat); + userpos.setLongitudeDeg(IC.lon); + userpos.setElevationFt(IC.alt); + + _x_offset = sm->x_offset; + _y_offset = sm->y_offset; + _z_offset = sm->z_offset; + + setOffsetPos(); + + //IC.elevation += sm->pitch_offset; + //IC.azimuth += sm->yaw_offset ; // pre-process the trig functions cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS); @@ -428,43 +406,9 @@ void FGSubmodelMgr::transform(submodel *sm) cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS); sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS); - // set up the transform matrix - trans[0][0] = cosRy * cosRz; - trans[0][1] = -1 * cosRx * sinRz + sinRx * sinRy * cosRz ; - trans[0][2] = sinRx * sinRz + cosRx * sinRy * cosRz; - - trans[1][0] = cosRy * sinRz; - trans[1][1] = cosRx * cosRz + sinRx * sinRy * sinRz; - trans[1][2] = -1 * sinRx * cosRx + cosRx * sinRy * sinRz; - - trans[2][0] = -1 * sinRy; - trans[2][1] = sinRx * cosRy; - trans[2][2] = cosRx * cosRy; - - - // multiply the input and transform matrices - out[0] = in[0] * trans[0][0] + in[1] * trans[0][1] + in[2] * trans[0][2]; - out[1] = in[0] * trans[1][0] + in[1] * trans[1][1] + in[2] * trans[1][2]; - out[2] = in[0] * trans[2][0] + in[1] * trans[2][1] + in[2] * trans[2][2]; - - // convert ft to degrees of latitude - out[0] = out[0] / (366468.96 - 3717.12 * cos(IC.lat * SG_DEGREES_TO_RADIANS)); - - // convert ft to degrees of longitude - out[1] = out[1] / (365228.16 * cos(IC.lat * SG_DEGREES_TO_RADIANS)); - - // set submodel initial position - IC.lat += out[0]; - IC.lon += out[1]; - IC.alt += out[2]; - - // get aircraft velocity vector angles in XZ and XY planes - //double alpha = _user_alpha_node->getDoubleValue(); - //double velXZ = IC.elevation - alpha * cosRx; - //double velXY = IC.azimuth - (IC.elevation - alpha * sinRx); // Get submodel initial velocity vector angles in XZ and XY planes. - // This needs to be fixed. This vector should be added to aircraft's vector. + // This vector should be added to aircraft's vector. IC.elevation += (sm->yaw_offset * sinRx) + (sm->pitch_offset * cosRx); IC.azimuth += (sm->yaw_offset * cosRx) - (sm->pitch_offset * sinRx); @@ -487,7 +431,7 @@ void FGSubmodelMgr::transform(submodel *sm) // if speeds are low this calculation can become unreliable if (IC.speed > 1) { - IC.azimuth = atan2(IC.total_speed_east , IC.total_speed_north) * SG_RADIANS_TO_DEGREES; + //IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES; // cout << "azimuth1 " << IC.azimuth<aero_stabilised = entry_node->getBoolValue("aero-stabilised", true); sm->no_roll = entry_node->getBoolValue("no-roll", false); sm->collision = entry_node->getBoolValue("collision", false); + sm->expiry = entry_node->getBoolValue("expiry", false); sm->impact = entry_node->getBoolValue("impact", false); sm->impact_report = entry_node->getStringValue("impact-reports"); sm->fuse_range = entry_node->getDoubleValue("fuse-range", 0.0); @@ -604,6 +540,10 @@ void FGSubmodelMgr::setData(int id, string& path, bool serviceable) sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false); sm->ext_force = entry_node->getBoolValue("external-force", false); sm->force_path = entry_node->getStringValue("force-path", ""); + sm->random = entry_node->getBoolValue("random", false); + sm->randomness = entry_node->getDoubleValue("randomness", 0.5); + + //cout << "sm->contents_node " << sm->contents_node << endl; if (sm->contents_node != 0) sm->contents = sm->contents_node->getDoubleValue(); @@ -626,11 +566,13 @@ void FGSubmodelMgr::setData(int id, string& path, bool serviceable) sm->sub_id = 0; sm->prop = fgGetNode("/ai/submodels/submodel", index, true); + sm->prop->tie("delay", SGRawValuePointer(&(sm->delay))); sm->prop->tie("count", SGRawValuePointer(&(sm->count))); sm->prop->tie("repeat", SGRawValuePointer(&(sm->repeat))); sm->prop->tie("id", SGRawValuePointer(&(sm->id))); sm->prop->tie("sub-id", SGRawValuePointer(&(sm->sub_id))); sm->prop->tie("serviceable", SGRawValuePointer(&(sm->serviceable))); + sm->prop->tie("random", SGRawValuePointer(&(sm->random))); string name = sm->name; sm->prop->setStringValue("name", name.c_str()); @@ -640,7 +582,7 @@ void FGSubmodelMgr::setData(int id, string& path, bool serviceable) string force_path = sm->force_path; sm->prop->setStringValue("force_path", force_path.c_str()); - //cout << "set force_path " << force_path << endl; + //cout << "set force_path Sub " << force_path << endl; if (sm->contents_node != 0) sm->prop->tie("contents-lbs", SGRawValuePointer(&(sm->contents))); @@ -698,14 +640,18 @@ void FGSubmodelMgr::setSubData(int id, string& path, bool serviceable) sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true); sm->no_roll = entry_node->getBoolValue("no-roll", false); sm->collision = entry_node->getBoolValue("collision", false); + sm->expiry = entry_node->getBoolValue("expiry", false); sm->impact = entry_node->getBoolValue("impact", false); sm->impact_report = entry_node->getStringValue("impact-reports"); sm->fuse_range = entry_node->getDoubleValue("fuse-range", 0.0); sm->contents_node = fgGetNode(entry_node->getStringValue("contents", "none"), false); sm->speed_node = fgGetNode(entry_node->getStringValue("speed-node", "none"), false); sm->submodel = entry_node->getStringValue("submodel-path", ""); + sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false); sm->ext_force = entry_node->getBoolValue("external-force", false); sm->force_path = entry_node->getStringValue("force-path", ""); + sm->random = entry_node->getBoolValue("random", false); + sm->randomness = entry_node->getDoubleValue("randomness", 0.5); //cout << "sm->contents_node " << sm->contents_node << endl; if (sm->contents_node != 0) @@ -734,16 +680,17 @@ void FGSubmodelMgr::setSubData(int id, string& path, bool serviceable) sm->prop->tie("id", SGRawValuePointer(&(sm->id))); sm->prop->tie("sub-id", SGRawValuePointer(&(sm->sub_id))); sm->prop->tie("serviceable", SGRawValuePointer(&(sm->serviceable))); + sm->prop->tie("random", SGRawValuePointer(&(sm->random))); string name = sm->name; sm->prop->setStringValue("name", name.c_str()); string submodel = sm->submodel; sm->prop->setStringValue("submodel", submodel.c_str()); - // cout << " set submodel path " << submodel<< endl; + // cout << " set submodel path AI" << submodel<< endl; string force_path = sm->force_path; sm->prop->setStringValue("force_path", force_path.c_str()); - //cout << "set force_path " << force_path << endl; + //cout << "set force_path AI" << force_path << endl; if (sm->contents_node != 0) sm->prop->tie("contents-lbs", SGRawValuePointer(&(sm->contents))); @@ -757,31 +704,38 @@ void FGSubmodelMgr::loadSubmodels() { SG_LOG(SG_GENERAL, SG_DEBUG, "Submodels: Loading sub submodels"); - submodel_iterator = submodels.begin(); + _found_sub = false; - while (submodel_iterator != submodels.end()) { - string submodel = (*submodel_iterator)->submodel; - if (!submodel.empty()) { - //int id = (*submodel_iterator)->id; - bool serviceable = true; - //SG_LOG(SG_GENERAL, SG_DEBUG, "found path sub sub " - // << submodel - // << " index " << index - // << "name " << (*submodel_iterator)->name); - - (*submodel_iterator)->sub_id = index; - setSubData(index, submodel, serviceable); - } + submodel_iterator = submodels.begin(); - ++submodel_iterator; - } + while (submodel_iterator != submodels.end()) { + string submodel = (*submodel_iterator)->submodel; + if (!submodel.empty()) { + //int id = (*submodel_iterator)->id; + bool serviceable = true; + //SG_LOG(SG_GENERAL, SG_DEBUG, "found path sub sub " + // << submodel + // << " index " << index + // << "name " << (*submodel_iterator)->name); + + if ((*submodel_iterator)->sub_id == 0){ + (*submodel_iterator)->sub_id = index; + _found_sub = true; + setSubData(index, submodel, serviceable); + } + } + + ++submodel_iterator; + } // end while subsubmodel_iterator = subsubmodels.begin(); while (subsubmodel_iterator != subsubmodels.end()) { submodels.push_back(*subsubmodel_iterator); ++subsubmodel_iterator; - } + } // end while + + subsubmodels.clear(); //submodel_iterator = submodels.begin(); @@ -796,4 +750,44 @@ void FGSubmodelMgr::loadSubmodels() //} } +SGVec3d FGSubmodelMgr::getCartOffsetPos() const{ + + // convert geodetic positions to geocentered + SGVec3d cartuserPos = SGVec3d::fromGeod(userpos); + + // Transform to the right coordinate frame, configuration is done in + // the x-forward, y-right, z-up coordinates (feet), computation + // in the simulation usual body x-forward, y-right, z-down coordinates + // (meters) ) + + SGVec3d _off(_x_offset * SG_FEET_TO_METER, + _y_offset * SG_FEET_TO_METER, + -_z_offset * SG_FEET_TO_METER); + + // Transform the user position to the horizontal local coordinate system. + SGQuatd hlTrans = SGQuatd::fromLonLat(userpos); + + // and postrotate the orientation of the user model wrt the horizontal + // local frame + hlTrans *= SGQuatd::fromYawPitchRollDeg( + IC.azimuth, + IC.elevation, + IC.roll); + + // The offset converted to the usual body fixed coordinate system + // rotated to the earth-fixed coordinates axis + SGVec3d off = hlTrans.backTransform(_off); + + // Add the position offset of the user model to get the geocentered position + SGVec3d offsetPos = cartuserPos + off; + + return offsetPos; +} + +void FGSubmodelMgr::setOffsetPos(){ + // convert the offset geocentered position to geodetic + SGVec3d cartoffsetPos = getCartOffsetPos(); + + SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos); +} // end of submodel.cxx diff --git a/src/AIModel/submodel.hxx b/src/AIModel/submodel.hxx index 7ca046f9d..cd645f64e 100644 --- a/src/AIModel/submodel.hxx +++ b/src/AIModel/submodel.hxx @@ -53,6 +53,7 @@ public: double drag_area; double life; double buoyancy; + double randomness; bool wind; bool first_time; double cd; @@ -62,7 +63,9 @@ public: int id; bool no_roll; bool serviceable; + bool random; bool collision; + bool expiry; bool impact; string impact_report; double fuse_range; @@ -141,6 +144,10 @@ private: double _parent_pitch; double _parent_roll; double _parent_speed; + double _x_offset; + double _y_offset; + double _z_offset; + static const double lbs_to_slugs; //conversion factor @@ -148,6 +155,8 @@ private: bool _impact; bool _hit; + bool _expiry; + bool _found_sub; SGPropertyNode_ptr _serviceable_node; SGPropertyNode_ptr _user_lat_node; @@ -174,7 +183,7 @@ private: IC_struct IC; // A list of pointers to AI objects - typedef list > sm_list_type; + typedef list > sm_list_type; typedef sm_list_type::iterator sm_list_iterator; typedef sm_list_type::const_iterator sm_list_const_iterator; @@ -190,9 +199,13 @@ private: bool release(submodel *, double dt); - double getRange(double lat, double lon, double lat2, double lon2) const; int _count; + + SGGeod userpos; + SGGeod offsetpos; + SGVec3d getCartOffsetPos() const; + void setOffsetPos(); }; diff --git a/src/ATC/Makefile.am b/src/ATC/Makefile.am index 35756c958..8748cef1e 100644 --- a/src/ATC/Makefile.am +++ b/src/ATC/Makefile.am @@ -2,6 +2,7 @@ noinst_LIBRARIES = libATC.a libATC_a_SOURCES = \ atcutils.cxx atcutils.hxx \ + atis.cxx atis.hxx \ trafficcontrol.cxx trafficcontrol.hxx INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src diff --git a/src/ATC/atcutils.cxx b/src/ATC/atcutils.cxx index 12747c480..94e4ec63b 100644 --- a/src/ATC/atcutils.cxx +++ b/src/ATC/atcutils.cxx @@ -69,8 +69,8 @@ bool FGCommList::init( const SGPath& path ) { LoadComms(temp); temp = path; temp.append( "ATC/default.approach" ); - LoadComms(temp); - return true;*/ + LoadComms(temp);*/ + return true; } @@ -107,9 +107,8 @@ bool FGCommList::LoadComms(const SGPath& path) { fin >> skipcomment; } - fin.close(); + fin.close();*/ return true; -*/ } @@ -160,13 +159,14 @@ bool FGCommList::FindByFreq(const SGGeod& aPos, double freq, return false; } */ + return false; } int FGCommList::FindByPos(const SGGeod& aPos, double range, comm_list_type* stations, atc_type tp) { -/* // number of relevant stations found within range int found = 0; +/* stations->erase(stations->begin(), stations->end()); // get bucket number for plane position @@ -203,8 +203,8 @@ int FGCommList::FindByPos(const SGGeod& aPos, double range, comm_list_type* stat } } } - return found; */ + return found; } @@ -248,15 +248,15 @@ double FGCommList::FindClosest(const SGGeod& aPos, ATCData& ad, atc_type tp, dou } range *= 10; } - return(-9999.0); */ + return(-9999.0); } // Find by Airport code. // This is basically a wrapper for a call to the airport database to get the airport // position followed by a call to FindByPos(...) -bool FGCommList::FindByCode( const string& ICAO, ATCData& ad, atc_type tp ) { +bool FGCommList::FindByCode( const std::string& ICAO, ATCData& ad, atc_type tp ) { /* const FGAirport *a = fgFindAirportID( ICAO); if ( a) { @@ -277,15 +277,15 @@ bool FGCommList::FindByCode( const string& ICAO, ATCData& ad, atc_type tp ) { } } } - return false; */ + return false; } // TODO - this function should move somewhere else eventually! // Return an appropriate sequence number for an ATIS transmission. // Return sequence number + 2600 if sequence is unchanged since // last time. -int FGCommList::GetAtisSequence( const string& apt_id, +int FGCommList::GetAtisSequence( const std::string& apt_id, const double tstamp, const int interval, const int special) { /* @@ -312,6 +312,7 @@ int FGCommList::GetAtisSequence( const string& apt_id, // << " Delta: " << delta << endl; return(tran.sequence + (delta ? 0 : LTRS*1000)); */ + return 2600; } /***************************************************************************** * FGKln89AlignedProjection @@ -369,4 +370,4 @@ SGGeod FGKln89AlignedProjection::ConvertFromLocal(const SGVec3d& pt) { return SGGeod::fromRadM(_origin.getLongitudeRad()+delta_lon, _origin.getLatitudeRad()+delta_lat, pt.z()); } -#endif // #ENABLE_ATCDCL \ No newline at end of file +#endif // #ENABLE_ATCDCL diff --git a/src/ATC/atcutils.hxx b/src/ATC/atcutils.hxx index e26d204b0..d2d2366a0 100644 --- a/src/ATC/atcutils.hxx +++ b/src/ATC/atcutils.hxx @@ -52,7 +52,8 @@ #if !ENABLE_ATCDCL class SGPath; -class ATCData; + + // Possible types of ATC type that the radios may be tuned to. // INVALID implies not tuned in to anything. @@ -67,6 +68,18 @@ enum atc_type { INVALID /* must be last element; see ATC_NUM_TYPES */ }; +struct ATCData { + ATCData() : type(INVALID), cart(0, 0, 0), freq(0), range(0) {} + atc_type type; + SGGeod geod; + SGVec3d cart; + unsigned short int freq; + unsigned short int range; + std::string ident; + std::string name; +}; + + // A list of ATC stations typedef std::list < ATCData > comm_list_type; diff --git a/src/ATC/atis.cxx b/src/ATC/atis.cxx new file mode 100644 index 000000000..02394167b --- /dev/null +++ b/src/ATC/atis.cxx @@ -0,0 +1,46 @@ +/****************************************************************************** + * atis.cxx + * Written by Durk Talsma, started August 1, 2010. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * + **************************************************************************/ + + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include +#include "atis.hxx" + +FGAtisManager::FGAtisManager() { + +} + +FGAtisManager::~FGAtisManager() { + +} + +void FGAtisManager::init() { + SGSubsystem::init(); +} + +void FGAtisManager::update ( double time ) { + //cerr << "ATIS code is running at time: " << time << endl; +} diff --git a/src/ATC/atis.hxx b/src/ATC/atis.hxx new file mode 100644 index 000000000..12fc4fd07 --- /dev/null +++ b/src/ATC/atis.hxx @@ -0,0 +1,39 @@ +/* -*- Mode: C++ -*- ***************************************************** + * atic.hxx + * Written by Durk Talsma. Started August 1, 2010; based on earlier work + * by David C. Luff + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * + **************************************************************************/ + +#ifndef _ATIS_HXX_ +#define _ATIS_HXX_ + +#include + +class FGAtisManager : public SGSubsystem +{ +private: + +public: + FGAtisManager(); + ~FGAtisManager(); + void init(); + void update(double time); +}; + +#endif // _ATIS_HXX_ \ No newline at end of file diff --git a/src/ATC/trafficcontrol.cxx b/src/ATC/trafficcontrol.cxx index 98b2ab46e..c7d20bdb5 100644 --- a/src/ATC/trafficcontrol.cxx +++ b/src/ATC/trafficcontrol.cxx @@ -38,15 +38,16 @@ FGTrafficRecord::FGTrafficRecord() : id(0), waitsForId(0), currentPos(0), leg(0), + frequencyId(0), state(0), + allowTransmission(true), latitude(0), longitude(0), heading(0), speed(0), altitude(0), - radius(0), - frequencyId(0), - allowTransmission(true) { + radius(0) +{ } void FGTrafficRecord::setPositionAndIntentions(int pos, FGAIFlightPlan *route) @@ -65,7 +66,6 @@ void FGTrafficRecord::setPositionAndIntentions(int pos, FGAIFlightPlan *route) } intentions.erase(i); } else { - //int legNr, routeNr; //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint(); int size = route->getNrOfWayPoints(); //cerr << "Setting pos" << pos << " "; @@ -510,7 +510,7 @@ void FGATCController::transmit(FGTrafficRecord *rec, AtcMsgId msgId, AtcMsgDir m double onBoardRadioFreq1 = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz"); int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5); int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5); - //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << endl; + //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl; // Display ATC message only when one of the radios is tuned // the relevant frequency. diff --git a/src/ATCDCL/AIEntity.cxx b/src/ATCDCL/AIEntity.cxx deleted file mode 100644 index 0d3d764fd..000000000 --- a/src/ATCDCL/AIEntity.cxx +++ /dev/null @@ -1,74 +0,0 @@ -// FGAIEntity - abstract base class an artificial intelligence entity -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -/***************************************************************** -* -* WARNING - Curt has some ideas about AI traffic so anything in here -* may get rewritten or scrapped. Contact Curt http://www.flightgear.org/~curt -* before spending any time or effort on this code!!! -* -******************************************************************/ - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include
-#include -#include -#include -#include -#include - -#include "AIEntity.hxx" - -FGAIEntity::FGAIEntity() : - _ground_elevation_m(0) -{ -} - -FGAIEntity::~FGAIEntity() { - globals->get_scenery()->get_scene_graph()->removeChild(_aip.getSceneGraph()); -} - -void FGAIEntity::SetModel(osg::Node* model) { - _aip.init(model); - _aip.setVisible(false); - globals->get_scenery()->get_scene_graph()->addChild(_aip.getSceneGraph()); -} - -void FGAIEntity::Update(double dt) { -} - -const string &FGAIEntity::GetCallsign() { - static string s = ""; - return(s); -} - -void FGAIEntity::RegisterTransmission(int code) { -} - -// Run the internal calculations -//void FGAIEntity::Update() { -void FGAIEntity::Transform() { - _aip.setPosition(_pos); - _aip.setOrientation(_roll, _pitch, _hdg); - _aip.update(); -} diff --git a/src/ATCDCL/AIEntity.hxx b/src/ATCDCL/AIEntity.hxx deleted file mode 100644 index 5254c8099..000000000 --- a/src/ATCDCL/AIEntity.hxx +++ /dev/null @@ -1,71 +0,0 @@ -// FGAIEntity - abstract base class an artificial intelligence entity -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifndef _FG_AIEntity_HXX -#define _FG_AIEntity_HXX - -#include -#include - -/***************************************************************** -* -* FGAIEntity - this class implements the minimum requirement -* for any AI entity - a position, an orientation, an associated -* 3D model, and the ability to be moved. It does nothing useful -* and all AI entities are expected to be derived from it. -* -******************************************************************/ -class FGAIEntity { - -public: - - FGAIEntity(); - virtual ~FGAIEntity(); - - // Set the 3D model to use (Must be called) - void SetModel(osg::Node* model); - - // Run the internal calculations - virtual void Update(double dt)=0; - - // Send a transmission *TO* the AIEntity. - // FIXME int code is a hack - eventually this will receive Alexander's coded messages. - virtual void RegisterTransmission(int code)=0; - - const SGGeod& getPos() const - { return _pos; } - - virtual const string& GetCallsign()=0; - -protected: - - SGGeod _pos; // Geodetic position - double _hdg; //True heading in degrees - double _roll; //degrees - double _pitch; //degrees - - SGModelPlacement _aip; - double _ground_elevation_m; - - void Transform(); -}; - -#endif // _FG_AIEntity_HXX - diff --git a/src/ATCDCL/AIGAVFRTraffic.cxx b/src/ATCDCL/AIGAVFRTraffic.cxx deleted file mode 100644 index 93a1f80cb..000000000 --- a/src/ATCDCL/AIGAVFRTraffic.cxx +++ /dev/null @@ -1,465 +0,0 @@ -// FGAILocalTraffic - AIEntity derived class with enough logic to -// fly and interact with the traffic pattern. -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include -#include -#include
-#include -#include - -using std::string; - -#include "ATC.hxx" -#include "ATCmgr.hxx" -#include "AILocalTraffic.hxx" -#include "AIGAVFRTraffic.hxx" -#include "ATCutils.hxx" -#include "tower.hxx" - -// extern from Airports/simple.cxx -extern SGGeod fgGetAirportPos( const std::string& id ); - -FGAIGAVFRTraffic::FGAIGAVFRTraffic() { - ATC = globals->get_ATC_mgr(); - _towerContactedIncoming = false; - _clearedStraightIn = false; - _clearedDownwindEntry = false; - _incoming = false; - _straightIn = false; - _downwindEntry = false; - _climbout = false; - _local = false; - _established = false; - _e45 = false; - _entering = false; - _turning = false; - _cruise_climb_ias = 90.0; - _cruise_ias = 110.0; - patternDirection = -1.0; - - // TESTING - REMOVE OR COMMENT OUT BEFORE COMMIT!!! - //_towerContactPrinted = false; -} - -FGAIGAVFRTraffic::~FGAIGAVFRTraffic() { -} - -// We should never need to Init FGAIGAVFRTraffic in the pattern since that implies arrivel -// and we can just use an FGAILocalTraffic instance for that instead. - -// Init en-route to destID at point pt. -// TODO - no idea what to do if pt is above planes ceiling due mountains!! -bool FGAIGAVFRTraffic::Init(const SGGeod& pt, const string& destID, const string& callsign) { - FGAILocalTraffic::Init(callsign, destID, EN_ROUTE); - // TODO FIXME - to get up and running we're going to ignore elev and get FGAIMgr to - // pass in known good values for the test location. Need to fix this!!! (or at least canonically decide who has responsibility for setting elev). - _enroute = true; - _destID = destID; - _pos = pt; - _destPos = fgGetAirportPos(destID); // TODO - check if we are within the tower catchment area already. - _cruise_alt = (_destPos.getElevationM() + 2500.0) * SG_FEET_TO_METER; // TODO look at terrain elevation as well - _pos.setElevationM(_cruise_alt); - // initially set waypoint as airport location - _wp = _destPos; - // Set the initial track - track = GetHeadingFromTo(_pos, _wp); - // And set the plane to keep following it. - SetTrack(GetHeadingFromTo(_pos, _wp)); - _roll = 0.0; - _pitch = 0.0; - slope = 0.0; - // TODO - set climbout if altitude is below normal cruising altitude? - //Transform(); - // Assume it's OK to set the plane visible - _aip.setVisible(true); - //cout << "Setting visible true\n"; - Transform(); - return(true); -} - -// Init at srcID to fly to destID -bool FGAIGAVFRTraffic::Init(const string& srcID, const string& destID, const string& callsign, OperatingState state) { - _enroute = false; - FGAILocalTraffic::Init(callsign, srcID, PARKED); - return(true); -} - -void FGAIGAVFRTraffic::Update(double dt) { - if(_enroute) { - //cout << "_enroute\n"; - //cout << "e" << flush; - FlyPlane(dt); - //cout << "f" << flush; - Transform(); - //cout << "g" << flush; - FGAIPlane::Update(dt); - //cout << "h" << flush; - responseCounter += dt; - - // we shouldn't really need this since there's a LOD of 10K on the whole plane anyway I think. - // There are two _aip.setVisible statements set when _local = true that can be removed if the below is removed. - if(dclGetHorizontalSeparation(_pos, SGGeod::fromDegM(fgGetDouble("/position/longitude-deg"), fgGetDouble("/position/latitude-deg"), 0.0)) > 8000) _aip.setVisible(false); - else _aip.setVisible(true); - - } else if(_local) { - //cout << "L"; - //cout << "_local\n"; - FGAILocalTraffic::Update(dt); - } -} - -void FGAIGAVFRTraffic::FlyPlane(double dt) { - if(_climbout) { - // Check whether to level off - if(_pos.getElevationM() >= _cruise_alt) { - slope = 0.0; - _pitch = 0.0; - IAS = _cruise_ias; // FIXME - use smooth transistion to new speed and attitude. - _climbout = false; - } else { - slope = 4.0; - _pitch = 5.0; - IAS = _cruise_climb_ias; - } - } else { - // TESTING - /* - if(dclGetHorizontalSeparation(_destPos, _pos) / 1600.0 < 8.1) { - if(!_towerContactPrinted) { - if(airportID == "KSQL") { - cout << "****************************************************************\n"; - cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"; - cout << "****************************************************************\n"; - } - _towerContactPrinted = true; - } - } - */ - - // if distance to destination is less than 6 - 9 miles contact tower - // and prepare to become _incoming after response. - // Possibly check whether to start descent before this? - //cout << "." << flush; - //cout << "sep = " << dclGetHorizontalSeparation(_destPos, _pos) / 1600.0 << '\n'; - if(dclGetHorizontalSeparation(_destPos, _pos) / 1600.0 < 8.0) { - //cout << "-" << flush; - if(!_towerContactedIncoming) { - //cout << "_" << flush; - GetAirportDetails(airportID); - //cout << "L" << flush; - if(_controlled) { - freq = (double)tower->get_freq() / 100.0; - tuned_station = tower; - } else { - freq = 122.8; // TODO - need to get the correct CTAF/Unicom frequency if no tower - tuned_station = NULL; - } - //cout << "freq = " << freq << endl; - GetRwyDetails(airportID); - //"@AP Tower @CS @MI miles @CD of the airport for full stop with ATIS" - // At the bare minimum we ought to make sure it goes the right way at dual parallel rwy airports! - if(rwy.rwyID.size() == 3) { - patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1); - } - if(_controlled) { - pending_transmission = tower->get_name(); - pending_transmission += " Tower "; - } else { - pending_transmission = "Traffic "; - // TODO - find some way of getting uncontrolled airport name - } - pending_transmission += plane.callsign; - //char buf[10]; - int dist_miles = (int)dclGetHorizontalSeparation(_pos, _destPos) / 1600; - //sprintf(buf, " %i ", dist_miles); - pending_transmission += " "; - pending_transmission += ConvertNumToSpokenDigits(dist_miles); - if(dist_miles > 1) pending_transmission += " miles "; - else pending_transmission += " mile "; - pending_transmission += GetCompassDirection(GetHeadingFromTo(_destPos, _pos)); - pending_transmission += " of the airport for full stop with ATIS"; - //cout << pending_transmission << endl; - Transmit(14); // 14 is the callback code, NOT the timeout! - responseCounter = 0; - _towerContactedIncoming = true; - } else { - //cout << "?" << flush; - if(_clearedStraightIn && responseCounter > 5.5) { - //cout << "5 " << flush; - _clearedStraightIn = false; - _straightIn = true; - _incoming = true; - _wp = GetPatternApproachPos(); - //_hdg = GetHeadingFromTo(_pos, _wp); // TODO - turn properly! - SetTrack(GetHeadingFromTo(_pos, _wp)); - slope = atan((_wp.getElevationM() - _pos.getElevationM()) / dclGetHorizontalSeparation(_wp, _pos)) * DCL_RADIANS_TO_DEGREES; - double thesh_offset = 0.0; - SGVec3d opos = ortho.ConvertToLocal(_pos); - double angToApt = atan((_pos.getElevationM() - fgGetAirportElev(airportID)) / (opos.y() - thesh_offset)) * DCL_RADIANS_TO_DEGREES; - //cout << "angToApt = " << angToApt << ' '; - slope = (angToApt > -5.0 ? 0.0 : angToApt); - //cout << "slope = " << slope << '\n'; - pending_transmission = "Straight-in "; - pending_transmission += ConvertRwyNumToSpokenString(rwy.rwyID); - pending_transmission += " "; - pending_transmission += plane.callsign; - //cout << pending_transmission << '\n'; - ConditionalTransmit(4); - } else if(_clearedDownwindEntry && responseCounter > 5.5) { - //cout << "6" << flush; - _clearedDownwindEntry = false; - _downwindEntry = true; - _incoming = true; - _wp = GetPatternApproachPos(); - SetTrack(GetHeadingFromTo(_pos, _wp)); - slope = atan((_wp.getElevationM() - _pos.getElevationM()) / dclGetHorizontalSeparation(_wp, _pos)) * DCL_RADIANS_TO_DEGREES; - //cout << "slope = " << slope << '\n'; - pending_transmission = "Report "; - pending_transmission += (patternDirection == 1 ? "right downwind " : "left downwind "); - pending_transmission += ConvertRwyNumToSpokenString(rwy.rwyID); - pending_transmission += " "; - pending_transmission += plane.callsign; - //cout << pending_transmission << '\n'; - ConditionalTransmit(4); - } - } - if(_pos.getElevationM() < (fgGetAirportElev(airportID) + (1000.0 * SG_FEET_TO_METER))) slope = 0.0; - } - } - if(_incoming) { - //cout << "i" << '\n'; - SGVec3d orthopos = ortho.ConvertToLocal(_pos); - // TODO - Check whether to start descent - // become _local after the 3 mile report. - if(_pos.getElevationM() < (fgGetAirportElev(airportID) + (1000.0 * SG_FEET_TO_METER))) slope = 0.0; - // TODO - work out why I needed to add the above line to stop the plane going underground!!! - // (Although it's worth leaving it in as a robustness check anyway). - if(_straightIn) { - //cout << "A " << flush; - if(fabs(orthopos.x()) < 10.0 && !_established) { - SetTrack(rwy.hdg); - _established = true; - //cout << "Established at " << orthopos << '\n'; - } - double thesh_offset = 30.0; - //cout << "orthopos.y = " << orthopos.y() << " alt = " << _pos.getElevationM() - fgGetAirportElev(airportID) << '\n'; - if(_established && (orthopos.y() > -5400.0)) { - slope = atan((_pos.getElevationM() - fgGetAirportElev(airportID)) / (orthopos.y() - thesh_offset)) * DCL_RADIANS_TO_DEGREES; - //cout << "slope0 = " << slope << '\n'; - } - //cout << "slope1 = " << slope << '\n'; - if(slope > -5.5) slope = 0.0; // ie we're too low. - //cout << "slope2 = " << slope << '\n'; - slope += 0.001; // To avoid yo-yoing with the above. - //if(_established && (orthopos.y() > -5400.0)) slope = -5.5; - if(_established && (orthopos.y() > -4800.0)) { - pending_transmission = "3 mile final Runway "; - pending_transmission += ConvertRwyNumToSpokenString(rwy.rwyID); - pending_transmission += " "; - pending_transmission += plane.callsign; - //cout << pending_transmission << '\n'; - ConditionalTransmit(35); - _local = true; - _aip.setVisible(true); // HACK - _enroute = false; - StraightInEntry(true); - } - } else if(_downwindEntry) { - //cout << "B" << flush; - if(_entering) { - //cout << "C" << flush; - if(_turning) { - if(fabs(_hdg - (rwy.hdg + 180)) < 2.0) { // TODO - use track instead of _hdg? - //cout << "Going Local...\n"; - leg = DOWNWIND; - _local = true; - _aip.setVisible(true); // HACK - _enroute = false; - _entering = false; - _turning = false; - DownwindEntry(); - } - } - if(fabs(orthopos.x() - (patternDirection == 1 ? 1000 : -1000)) < (_e45 ? 175 : 550)) { // Caution - hardwired turn clearances. - //cout << "_turning...\n"; - _turning = true; - SetTrack(rwy.hdg + 180.0); - } // TODO - need to check for other traffic in the pattern and enter much more integilently than that!!! - } else { - //cout << "D" << flush; - //cout << '\n' << dclGetHorizontalSeparation(_wp, _pos) << '\n'; - //cout << ortho.ConvertToLocal(GetPos()); - //cout << ortho.ConvertToLocal(_wp); - if(dclGetHorizontalSeparation(_wp, _pos) < 100.0) { - pending_transmission = "2 miles out for "; - pending_transmission += (patternDirection == 1 ? "right " : "left "); - pending_transmission += "downwind Runway "; - pending_transmission += ConvertRwyNumToSpokenString(rwy.rwyID); - pending_transmission += " "; - pending_transmission += plane.callsign; - //cout << pending_transmission << '\n'; - // TODO - are we at pattern altitude?? - slope = 0.0; - ConditionalTransmit(30); - if(_e45) { - SetTrack(patternDirection == 1 ? rwy.hdg - 135.0 : rwy.hdg + 135.0); - } else { - SetTrack(patternDirection == 1 ? rwy.hdg + 90.0 : rwy.hdg - 90.0); - } - //if(_hdg < 0.0) _hdg += 360.0; - _entering = true; - } else { - SetTrack(GetHeadingFromTo(_pos, _wp)); - } - } - } - } else { - // !_incoming - slope = 0.0; - } - // FIXME - lots of hackery in the next six lines!!!! - double crab = 0.0; // This is a placeholder for when we take wind into account. - _hdg = track + crab; - double vel = _cruise_ias; - double dist = vel * 0.514444 * dt; - _pos = dclUpdatePosition(_pos, track, slope, dist); -} - -void FGAIGAVFRTraffic::RegisterTransmission(int code) { - switch(code) { - case 1: // taxi request cleared - FGAILocalTraffic::RegisterTransmission(code); - break; - case 2: // contact tower - FGAILocalTraffic::RegisterTransmission(code); - break; - case 3: // Cleared to line up - FGAILocalTraffic::RegisterTransmission(code); - break; - case 4: // cleared to take-off - FGAILocalTraffic::RegisterTransmission(code); - break; - case 5: // contact ground - FGAILocalTraffic::RegisterTransmission(code); - break; - case 6: // taxi to the GA parking - FGAILocalTraffic::RegisterTransmission(code); - break; - case 7: // Cleared to land - FGAILocalTraffic::RegisterTransmission(code); - break; - case 13: // Go around! - FGAILocalTraffic::RegisterTransmission(code); - break; - case 14: // VFR approach for straight-in - responseCounter = 0; - _clearedStraightIn = true; - break; - case 15: // VFR approach for downwind entry - responseCounter = 0; - _clearedDownwindEntry = true; - break; - default: - SG_LOG(SG_ATC, SG_WARN, "FGAIGAVFRTraffic::RegisterTransmission(...) called with unknown code " << code); - FGAILocalTraffic::RegisterTransmission(code); - break; - } -} - -// Callback handler -// TODO - Really should enumerate these coded values. -void FGAIGAVFRTraffic::ProcessCallback(int code) { - // 1 - Request Departure from ground - // 2 - Report at hold short - // 10 - report crosswind - // 11 - report downwind - // 12 - report base - // 13 - report final - // 14 - Contact Tower for VFR arrival - // 99 - Remove self - if(code < 14) { - FGAILocalTraffic::ProcessCallback(code); - } else if(code == 14) { - if(_controlled) { - tower->VFRArrivalContact(plane, this, FULL_STOP); - } - // TODO else possibly announce arrival intentions at uncontrolled airport? - } else if(code == 99) { - // Might handle this different in future - hence separated from the other codes to pass to AILocalTraffic. - FGAILocalTraffic::ProcessCallback(code); - } -} - -// Return an appropriate altitude to fly at based on the desired altitude and direction -// whilst respecting the quadrangle rule. -int FGAIGAVFRTraffic::GetQuadrangleAltitude(int dir, int des_alt) { - return(8888); - // TODO - implement me! -} - -// Calculates the position needed to set up for either pattern entry or straight in approach. -// Currently returns one of three positions dependent on initial position wrt threshold of active rwy. -// 1/ A few miles out on extended centreline for straight-in. -// 2/ At an appropriate point on circuit side of rwy for a 45deg entry to downwind. -// 3/ At and appropriate point on non-circuit side of rwy at take-off end for perpendicular entry to circuit overflying end-of-rwy. -SGGeod FGAIGAVFRTraffic::GetPatternApproachPos() { - //cout << "\n\n"; - //cout << "Calculating pattern approach pos for " << plane.callsign << '\n'; - SGVec3d orthopos = ortho.ConvertToLocal(_pos); - SGVec3d tmp; - //cout << "patternDirection = " << patternDirection << '\n'; - if(orthopos.y() >= -1000.0) { // Note that this has to be set the same as the calculation in tower.cxx - at the moment approach type is not transmitted properly between the two. - //cout << "orthopos.x = " << orthopos.x() << '\n'; - if((orthopos.x() * patternDirection) > 0.0) { // 45 deg entry - tmp.x() = 2000 * patternDirection; - tmp.y() = (rwy.end2ortho.y() / 2.0) + 2000; - tmp.z() = (fgGetAirportElev(airportID) + (1000 * SG_FEET_TO_METER)); - _e45 = true; - //cout << "45 deg entry... "; - } else { - tmp.x() = (1000 * patternDirection * -1); - tmp.y() = (rwy.end2ortho.y()); - tmp.z() = (fgGetAirportElev(airportID) + (1000 * SG_FEET_TO_METER)); - _e45 = false; - //cout << "90 deg entry... "; - } - } else { - tmp.x() = 0; - tmp.y() = -5400; - tmp.z() = ((5400.0 / 6.0) + fgGetAirportElev(airportID) + 10.0); - //cout << "Straight in... "; - } - //cout << "Waypoint is " << tmp << '\n'; - //cout << ortho.ConvertFromLocal(tmp) << '\n'; - //cout << '\n'; - //exit(-1); - return ortho.ConvertFromLocal(tmp); -} - -//FGAIGAVFRTraffic:: - -//FGAIGAVFRTraffic:: - -//FGAIGAVFRTraffic:: diff --git a/src/ATCDCL/AIGAVFRTraffic.hxx b/src/ATCDCL/AIGAVFRTraffic.hxx deleted file mode 100644 index fda97cf39..000000000 --- a/src/ATCDCL/AIGAVFRTraffic.hxx +++ /dev/null @@ -1,124 +0,0 @@ -// FGAILocalTraffic - AIEntity derived class with enough logic to -// fly and interact with the traffic pattern. -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifndef _FG_AIGAVFRTraffic_HXX -#define _FG_AIGAVFRTraffic_HXX - -#include -#include
- -#include "AILocalTraffic.hxx" - -#include -using std::string; - -class FGAIGAVFRTraffic : public FGAILocalTraffic { - -public: - - FGAIGAVFRTraffic(); - ~FGAIGAVFRTraffic(); - - // Init en-route to destID at point pt. (lat, lon, elev) (elev in meters, lat and lon in degrees). - bool Init(const SGGeod& pt, const string& destID, const string& callsign); - // Init at srcID to fly to destID - bool Init(const string& srcID, const string& destID, const string& callsign, OperatingState state = PARKED); - - // Run the internal calculations - void Update(double dt); - - // Return what type of landing we're doing on this circuit - //LandingType GetLandingOption(); - - void RegisterTransmission(int code); - - // Process callbacks sent by base class - // (These codes are not related to the codes above) - void ProcessCallback(int code); - -protected: - - // Do what is necessary to land and parkup at home airport - void ReturnToBase(double dt); - - //void GetRwyDetails(string id); - - -private: - FGATCMgr* ATC; - // This is purely for synactic convienience to avoid writing globals->get_ATC_mgr()-> all through the code! - - // High-level stuff - OperatingState operatingState; - bool touchAndGo; //True if circuits should be flown touch and go, false for full stop - - // Performance characteristics of the plane in knots and ft/min - some of this might get moved out into FGAIPlane - double best_rate_of_climb_speed; - double best_rate_of_climb; - double nominal_climb_speed; - double nominal_climb_rate; - double nominal_cruise_speed; - double nominal_circuit_speed; - double nominal_descent_rate; - double nominal_approach_speed; - double nominal_final_speed; - double stall_speed_landing_config; - - // environment - some of this might get moved into FGAIPlane - SGPropertyNode_ptr wind_from_hdg; //degrees - SGPropertyNode_ptr wind_speed_knots; //knots - - atc_type changeFreqType; // the service we need to change to - - void CalculateSoD(double base_leg_pos, double downwind_leg_pos, bool pattern_direction); - - // GA VFR specific - bool _towerContactedIncoming; - bool _straightIn; - bool _clearedStraightIn; - bool _downwindEntry; - bool _clearedDownwindEntry; - SGGeod _wp; // Next waypoint (ie. the one we're currently heading for) - bool _enroute; - string _destID; - bool _climbout; - double _cruise_alt; - double _cruise_ias; - double _cruise_climb_ias; - SGGeod _destPos; - bool _local; - bool _incoming; - bool _established; - bool _e45; - bool _entering; - bool _turning; - - int GetQuadrangleAltitude(int dir, int des_alt); - - SGGeod GetPatternApproachPos(); - - void FlyPlane(double dt); - - // HACK for testing - remove or comment out before CVS commit!!! - //bool _towerContactPrinted; -}; - -#endif // _FG_AILocalTraffic_HXX diff --git a/src/ATCDCL/AILocalTraffic.cxx b/src/ATCDCL/AILocalTraffic.cxx deleted file mode 100644 index 8a66eda6e..000000000 --- a/src/ATCDCL/AILocalTraffic.cxx +++ /dev/null @@ -1,1543 +0,0 @@ -// FGAILocalTraffic - AIEntity derived class with enough logic to -// fly and interact with the traffic pattern. -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -/*========================================================== - -TODO list. - -Should get pattern direction from tower. - -Need to continually monitor and adjust deviation from glideslope -during descent to avoid occasionally landing short or long. - -============================================================*/ - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include -#include
-#include
-#include -#include -#include -#include -#include -#include - -using std::string; - -#include "ATCmgr.hxx" -#include "AILocalTraffic.hxx" -#include "ATCutils.hxx" -#include "AIMgr.hxx" - -FGAILocalTraffic::FGAILocalTraffic() { - ATC = globals->get_ATC_mgr(); - - // TODO - unhardwire this - plane.type = GA_SINGLE; - - _roll = 0.0; - _pitch = 0.0; - _hdg = 270.0; - - //Hardwire initialisation for now - a lot of this should be read in from config eventually - Vr = 70.0; - best_rate_of_climb_speed = 70.0; - //best_rate_of_climb; - //nominal_climb_speed; - //nominal_climb_rate; - //nominal_circuit_speed; - //min_circuit_speed; - //max_circuit_speed; - nominal_descent_rate = 500.0; - nominal_final_speed = 65.0; - //nominal_approach_speed; - //stall_speed_landing_config; - nominalTaxiSpeed = 7.5; - taxiTurnRadius = 8.0; - wheelOffset = 1.45; // Warning - hardwired to the C172 - we need to read this in from file. - elevInitGood = false; - // Init the property nodes - wind_from_hdg = fgGetNode("/environment/wind-from-heading-deg", true); - wind_speed_knots = fgGetNode("/environment/wind-speed-kt", true); - circuitsToFly = 0; - liningUp = false; - taxiRequestPending = false; - taxiRequestCleared = false; - holdingShort = false; - clearedToLineUp = false; - clearedToTakeOff = false; - _clearedToLand = false; - reportReadyForDeparture = false; - contactTower = false; - contactGround = false; - _taxiToGA = false; - _removeSelf = false; - - descending = false; - targetDescentRate = 0.0; - goAround = false; - goAroundCalled = false; - - transmitted = false; - - freeTaxi = false; - _savedSlope = 0.0; - - _controlled = false; - - _invisible = false; -} - -FGAILocalTraffic::~FGAILocalTraffic() { -} - -void FGAILocalTraffic::GetAirportDetails(const string& id) { - AirportATC a; - if(ATC->GetAirportATCDetails(airportID, &a)) { - if(a.tower_freq) { // Has a tower - TODO - check the opening hours!!! - tower = (FGTower*)ATC->GetATCPointer(airportID, TOWER); - if(tower == NULL) { - // Something has gone wrong - abort or carry on with un-towered operation? - SG_LOG(SG_ATC, SG_ALERT, "ERROR - can't get a tower pointer from tower control for " << airportID << " in FGAILocalTraffic::GetAirportDetails() :-("); - _controlled = false; - } else { - _controlled = true; - } - if(tower) { - ground = tower->GetGroundPtr(); - if(ground == NULL) { - // Something has gone wrong :-( - SG_LOG(SG_ATC, SG_ALERT, "ERROR - can't get a ground pointer from tower control in FGAILocalTraffic::GetAirportDetails() :-("); - } - } - } else { - _controlled = false; - // TODO - Check CTAF, unicom etc - } - } else { - SG_LOG(SG_ATC, SG_ALERT, "Unable to find airport details in for " << airportID << " in FGAILocalTraffic::GetAirportDetails() :-("); - _controlled = false; - } - // Get the airport elevation - aptElev = fgGetAirportElev(airportID.c_str()); - //cout << "Airport elev in AILocalTraffic = " << aptElev << '\n'; - // WARNING - we use this elev for the whole airport - some assumptions in the code - // might fall down with very slopey airports. -} - -// Get details of the active runway -// It is assumed that by the time this is called the tower control and airport code will have been set up. -void FGAILocalTraffic::GetRwyDetails(const string& id) { - //cout << "GetRwyDetails called" << endl; - - const FGAirport* apt = fgFindAirportID(id); - assert(apt); - FGRunway* runway(apt->getActiveRunwayForUsage()); - - double hdg = runway->headingDeg(); - double other_way = hdg - 180.0; - while(other_way <= 0.0) { - other_way += 360.0; - } - - // move to the +l end/center of the runway - //cout << "Runway center is at " << runway._lon << ", " << runway._lat << '\n'; - double tshlon = 0.0, tshlat = 0.0, tshr; - double tolon = 0.0, tolat = 0.0, tor; - rwy.length = runway->lengthM(); - rwy.width = runway->widthM(); - geo_direct_wgs_84 ( aptElev, runway->latitude(), runway->longitude(), other_way, - rwy.length / 2.0 - 25.0, &tshlat, &tshlon, &tshr ); - geo_direct_wgs_84 ( aptElev, runway->latitude(), runway->longitude(), hdg, - rwy.length / 2.0 - 25.0, &tolat, &tolon, &tor ); - // Note - 25 meters in from the runway end is a bit of a hack to put the plane ahead of the user. - // now copy what we need out of runway into rwy - rwy.threshold_pos = SGGeod::fromDegM(tshlon, tshlat, aptElev); - SGGeod takeoff_end = SGGeod::fromDegM(tolon, tolat, aptElev); - //cout << "Threshold position = " << tshlon << ", " << tshlat << ", " << aptElev << '\n'; - //cout << "Takeoff position = " << tolon << ", " << tolat << ", " << aptElev << '\n'; - rwy.hdg = hdg; - // Set the projection for the local area - //cout << "Initing ortho for airport " << id << '\n'; - ortho.Init(rwy.threshold_pos, rwy.hdg); - rwy.end1ortho = ortho.ConvertToLocal(rwy.threshold_pos); // should come out as zero - rwy.end2ortho = ortho.ConvertToLocal(takeoff_end); -} - - -/* -There are two possible scenarios during initialisation: -The first is that the user is flying towards the airport, and hence the traffic -could be initialised anywhere, as long as the AI planes are consistent with -each other. -The second is that the user has started the sim at or close to the airport, and -hence the traffic must be initialised with respect to the user as well as each other. -To a certain extent it's FGAIMgr that has to worry about this, but we need to provide -sufficient initialisation functionality within the plane classes to allow the manager -to initially position them where and how required. -*/ -bool FGAILocalTraffic::Init(const string& callsign, const string& ICAO, OperatingState initialState, PatternLeg initialLeg) { - //cout << "FGAILocalTraffic.Init(...) called" << endl; - airportID = ICAO; - - plane.callsign = callsign; - - if(initialState == EN_ROUTE) return(true); - - // Get the ATC pointers and airport elev - GetAirportDetails(airportID); - - // Get the active runway details (and copy them into rwy) - GetRwyDetails(airportID); - //cout << "Runway is " << rwy.rwyID << '\n'; - - // FIXME TODO - pattern direction is still hardwired - patternDirection = -1; // Left - // At the bare minimum we ought to make sure it goes the right way at dual parallel rwy airports! - if(rwy.rwyID.size() == 3) { - patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1); - } - - if(_controlled) { - if((initialState == PARKED) || (initialState == TAXIING)) { - freq = (double)ground->get_freq() / 100.0; - } else { - freq = (double)tower->get_freq() / 100.0; - } - } else { - freq = 122.8; - // TODO - find the proper freq if CTAF or unicom or after-hours. - } - - //cout << "In Init(), initialState = " << initialState << endl; - operatingState = initialState; - SGVec3d orthopos; - switch(operatingState) { - case PARKED: - tuned_station = ground; - ourGate = ground->GetGateNode(); - if(ourGate == NULL) { - // Implies no available gates - what shall we do? - // For now just vanish the plane - possibly we can make this more elegant in the future - SG_LOG(SG_ATC, SG_ALERT, "No gate found by FGAILocalTraffic whilst attempting Init at " << airportID << '\n'); - return(false); - } - _pitch = 0.0; - _roll = 0.0; - vel = 0.0; - slope = 0.0; - _pos = ourGate->pos; - _pos.setElevationM(aptElev); - _hdg = ourGate->heading; - Transform(); - - // Now we've set the position we can do the ground elev - elevInitGood = false; - inAir = false; - DoGroundElev(); - - break; - case TAXIING: - //tuned_station = ground; - // FIXME - implement this case properly - // For now we'll assume that the plane should start at the hold short in this case - // and that we're working without ground network elements. Ie. an airport with no facility file. - if(_controlled) { - tuned_station = tower; - } else { - tuned_station = NULL; - } - freeTaxi = true; - // Set a position and orientation in an approximate place for hold short. - //cout << "rwy.width = " << rwy.width << '\n'; - orthopos = SGVec3d((rwy.width / 2.0 + 10.0) * -1.0, 0.0, 0.0); - // TODO - set the x pos to be +ve if a RH parallel rwy. - _pos = ortho.ConvertFromLocal(orthopos); - _pos.setElevationM(aptElev); - _hdg = rwy.hdg + 90.0; - // TODO - reset the heading if RH rwy. - _pitch = 0.0; - _roll = 0.0; - vel = 0.0; - slope = 0.0; - elevInitGood = false; - inAir = false; - Transform(); - DoGroundElev(); - //Transform(); - - responseCounter = 0.0; - contactTower = false; - changeFreq = true; - holdingShort = true; - clearedToLineUp = false; - changeFreqType = TOWER; - - break; - case IN_PATTERN: - // For now we'll always start the in_pattern case on the threshold ready to take-off - // since we've got the implementation for this case already. - // TODO - implement proper generic in_pattern startup. - - // 18/10/03 - adding the ability to start on downwind (mainly to speed testing of the go-around code!!) - - //cout << "Starting in pattern...\n"; - - if(_controlled) { - tuned_station = tower; - } else { - tuned_station = NULL; - } - - circuitsToFly = 0; // ie just fly this circuit and then stop - touchAndGo = false; - - if(initialLeg == DOWNWIND) { - _pos = ortho.ConvertFromLocal(SGVec3d(1000*patternDirection, 800, 0.0)); - _pos.setElevationM(rwy.threshold_pos.getElevationM() + 1000 * SG_FEET_TO_METER); - _hdg = rwy.hdg + 180.0; - leg = DOWNWIND; - elevInitGood = false; - inAir = true; - SetTrack(rwy.hdg - (180 * patternDirection)); - slope = 0.0; - _pitch = 0.0; - _roll = 0.0; - IAS = 90.0; - descending = false; - _aip.setVisible(true); - if(_controlled) { - tower->RegisterAIPlane(plane, this, CIRCUIT, DOWNWIND); - } - Transform(); - } else { - // Default to initial position on threshold for now - _pos = rwy.threshold_pos; - _hdg = rwy.hdg; - - // Now we've set the position we can do the ground elev - // This might not always be necessary if we implement in-air start - elevInitGood = false; - inAir = false; - - _pitch = 0.0; - _roll = 0.0; - leg = TAKEOFF_ROLL; - vel = 0.0; - slope = 0.0; - - Transform(); - DoGroundElev(); - } - - operatingState = IN_PATTERN; - - break; - case EN_ROUTE: - // This implies we're being init'd by AIGAVFRTraffic - simple return now - return(true); - default: - SG_LOG(SG_ATC, SG_ALERT, "Attempt to set unknown operating state in FGAILocalTraffic.Init(...)\n"); - return(false); - } - - - return(true); -} - - -// Set up downwind state - this is designed to be called from derived classes who are already tuned to tower -void FGAILocalTraffic::DownwindEntry() { - circuitsToFly = 0; // ie just fly this circuit and then stop - touchAndGo = false; - operatingState = IN_PATTERN; - leg = DOWNWIND; - elevInitGood = false; - inAir = true; - SetTrack(rwy.hdg - (180 * patternDirection)); - slope = 0.0; - _pitch = 0.0; - _roll = 0.0; - IAS = 90.0; - descending = false; -} - -void FGAILocalTraffic::StraightInEntry(bool des) { - //cout << "************ STRAIGHT-IN ********************\n"; - circuitsToFly = 0; // ie just fly this circuit and then stop - touchAndGo = false; - operatingState = IN_PATTERN; - leg = FINAL; - elevInitGood = false; - inAir = true; - SetTrack(rwy.hdg); - transmitted = true; // TODO - fix this hack. - // TODO - set up the next 5 properly for a descent! - slope = -5.5; - _pitch = 0.0; - _roll = 0.0; - IAS = 90.0; - descending = des; -} - - -// Return what type of landing we're doing on this circuit -LandingType FGAILocalTraffic::GetLandingOption() { - //cout << "circuitsToFly = " << circuitsToFly << '\n'; - if(circuitsToFly) { - return(touchAndGo ? TOUCH_AND_GO : STOP_AND_GO); - } else { - return(FULL_STOP); - } -} - - -// Commands to do something from higher level logic -void FGAILocalTraffic::FlyCircuits(int numCircuits, bool tag) { - //cout << "FlyCircuits called" << endl; - - switch(operatingState) { - case IN_PATTERN: - circuitsToFly += numCircuits; - return; - break; - case TAXIING: - // HACK - assume that we're taxiing out for now - circuitsToFly += numCircuits; - touchAndGo = tag; - break; - case PARKED: - circuitsToFly = numCircuits; // Note that one too many circuits gets flown because we only test and decrement circuitsToFly after landing - // thus flying one too many circuits. TODO - Need to sort this out better! - touchAndGo = tag; - break; - case EN_ROUTE: - break; - } -} - -// Run the internal calculations -void FGAILocalTraffic::Update(double dt) { - //cout << "U" << flush; - - // we shouldn't really need this since there's a LOD of 10K on the whole plane anyway I think. - // At the moment though I need to to avoid DList overflows - the whole plane LOD obviously isn't getting picked up. - if(!_invisible) { - if(dclGetHorizontalSeparation(_pos, SGGeod::fromDegM(fgGetDouble("/position/longitude-deg"), fgGetDouble("/position/latitude-deg"), 0.0)) > 8000) _aip.setVisible(false); - else _aip.setVisible(true); - } else { - _aip.setVisible(false); - } - - //double responseTime = 10.0; // seconds - this should get more sophisticated at some point - responseCounter += dt; - if((contactTower) && (responseCounter >= 8.0)) { - // Acknowledge request before changing frequency so it gets rendered if the user is on the same freq - string trns = "Tower "; - double f = globals->get_ATC_mgr()->GetFrequency(airportID, TOWER) / 100.0; - char buf[10]; - sprintf(buf, "%.2f", f); - trns += buf; - trns += " "; - trns += plane.callsign; - pending_transmission = trns; - ConditionalTransmit(30.0); - responseCounter = 0.0; - contactTower = false; - changeFreq = true; - changeFreqType = TOWER; - } - - if((contactGround) && (responseCounter >= 8.0)) { - // Acknowledge request before changing frequency so it gets rendered if the user is on the same freq - string trns = "Ground "; - double f = globals->get_ATC_mgr()->GetFrequency(airportID, GROUND) / 100.0; - char buf[10]; - sprintf(buf, "%.2f", f); - trns += buf; - trns += " "; - trns += "Good Day"; - pending_transmission = trns; - ConditionalTransmit(5.0); - responseCounter = 0.0; - contactGround = false; - changeFreq = true; - changeFreqType = GROUND; - } - - if((_taxiToGA) && (responseCounter >= 8.0)) { - // Acknowledge request before changing frequency so it gets rendered if the user is on the same freq - string trns = "GA Parking, Thank you and Good Day"; - //double f = globals->get_ATC_mgr()->GetFrequency(airportID, GROUND) / 100.0; - pending_transmission = trns; - ConditionalTransmit(5.0, 99); - _taxiToGA = false; - if(_controlled) { - tower->DeregisterAIPlane(plane.callsign); - } - // NOTE - we can't delete this instance yet since then the frequency won't get release when the message display finishes. - } - - if((_removeSelf) && (responseCounter >= 8.0)) { - _removeSelf = false; - // MEGA HACK - check if we are at a simple airport or not first instead of simply hardwiring KEMT as the only non-simple airport. - // TODO FIXME TODO FIXME !!!!!!! - if(airportID != "KEMT") globals->get_AI_mgr()->ScheduleRemoval(plane.callsign); - } - - if((changeFreq) && (responseCounter > 8.0)) { - switch(changeFreqType) { - case TOWER: - if(!tower) { - SG_LOG(SG_ATC, SG_ALERT, "ERROR: Trying to change frequency to tower in FGAILocalTraffic, but tower is NULL!!!"); - break; - } - tuned_station = tower; - freq = (double)tower->get_freq() / 100.0; - //Transmit("DING!"); - // Contact the tower, even if only virtually - pending_transmission = plane.callsign; - pending_transmission += " at hold short for runway "; - pending_transmission += ConvertRwyNumToSpokenString(rwy.rwyID); - pending_transmission += " traffic pattern "; - if(circuitsToFly) { - pending_transmission += ConvertNumToSpokenDigits(circuitsToFly + 1); - pending_transmission += " circuits touch and go"; - } else { - pending_transmission += " one circuit to full stop"; - } - Transmit(2); - break; - case GROUND: - if(!tower) { - SG_LOG(SG_ATC, SG_ALERT, "ERROR: Trying to change frequency to ground in FGAILocalTraffic, but tower is NULL!!!"); - break; - } - if(!ground) { - SG_LOG(SG_ATC, SG_ALERT, "ERROR: Trying to change frequency to ground in FGAILocalTraffic, but ground is NULL!!!"); - break; - } - tower->DeregisterAIPlane(plane.callsign); - tuned_station = ground; - freq = (double)ground->get_freq() / 100.0; - break; - // And to avoid compiler warnings... - case APPROACH: break; - case ATIS: break; - case AWOS: break; - case ENROUTE: break; - case DEPARTURE: break; - case INVALID: break; - } - changeFreq = false; - } - - //cout << "," << flush; - - switch(operatingState) { - case IN_PATTERN: - //cout << "In IN_PATTERN\n"; - if(!inAir) { - DoGroundElev(); - if(!elevInitGood) { - if(_ground_elevation_m > -9990.0) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - //cout << "TAKEOFF_ROLL, POS = " << pos.lon() << ", " << pos.lat() << ", " << pos.elev() << '\n'; - //Transform(); - _aip.setVisible(true); - //cout << "Making plane visible!\n"; - elevInitGood = true; - } - } - } - FlyTrafficPattern(dt); - Transform(); - break; - case TAXIING: - //cout << "In TAXIING\n"; - //cout << "*" << flush; - if(!elevInitGood) { - //DoGroundElev(); - if(_ground_elevation_m > -9990.0) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - //Transform(); - _aip.setVisible(true); - //Transform(); - //cout << "Making plane visible!\n"; - elevInitGood = true; - } - } - DoGroundElev(); - //cout << "~" << flush; - if(!((holdingShort) && (!clearedToLineUp))) { - //cout << "|" << flush; - Taxi(dt); - } - //cout << ";" << flush; - if((clearedToTakeOff) && (responseCounter >= 8.0)) { - // possible assumption that we're at the hold short here - may not always hold - // TODO - sort out the case where we're cleared to line-up first and then cleared to take-off on the rwy. - taxiState = TD_LINING_UP; - //cout << "A" << endl; - path = ground->GetPath(holdShortNode, rwy.rwyID); - //cout << "B" << endl; - if(!path.size()) { // Assume no facility file so we'll just taxi to a point on the runway near the threshold - //cout << "C" << endl; - node* np = new node; - np->struct_type = NODE; - np->pos = ortho.ConvertFromLocal(SGVec3d(0.0, 10.0, 0.0)); - path.push_back(np); - } else { - //cout << "D" << endl; - } - /* - cout << "path returned was:" << endl; - for(unsigned int i=0; istruct_type) { - case NODE: - cout << "NODE " << ((node*)(path[i]))->nodeID << endl; - break; - case ARC: - cout << "ARC\n"; - break; - } - } - */ - clearedToTakeOff = false; // We *are* still cleared - this simply stops the response recurring!! - holdingShort = false; - string trns = "Cleared for take-off "; - trns += plane.callsign; - pending_transmission = trns; - Transmit(); - StartTaxi(); - } - //cout << "^" << flush; - Transform(); - break; - case PARKED: - //cout << "In PARKED\n"; - if(!elevInitGood) { - DoGroundElev(); - if(_ground_elevation_m > -9990.0) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - //Transform(); - _aip.setVisible(true); - //Transform(); - //cout << "Making plane visible!\n"; - elevInitGood = true; - } - } - - if(circuitsToFly) { - if((taxiRequestPending) && (taxiRequestCleared)) { - //cout << "&" << flush; - // Get the active runway details (in case they've changed since init) - GetRwyDetails(airportID); - - // Get the takeoff node for the active runway, get a path to it and start taxiing - path = ground->GetPathToHoldShort(ourGate, rwy.rwyID); - if(path.size() < 2) { - // something has gone wrong - SG_LOG(SG_ATC, SG_ALERT, "Invalid path from gate to theshold in FGAILocalTraffic::FlyCircuits\n"); - return; - } - /* - cout << "path returned was:\n"; - for(unsigned int i=0; istruct_type) { - case NODE: - cout << "NODE " << ((node*)(path[i]))->nodeID << endl; - break; - case ARC: - cout << "ARC\n"; - break; - } - } - */ - path.erase(path.begin()); // pop the gate - we're here already! - taxiState = TD_OUTBOUND; - taxiRequestPending = false; - holdShortNode = (node*)(*(path.begin() + path.size())); - StartTaxi(); - } else if(!taxiRequestPending) { - //cout << "(" << flush; - // Do some communication - // airport name + tower + airplane callsign + location + request taxi for + operation type + ? - string trns = ""; - if(_controlled) { - trns += tower->get_name(); - trns += " tower "; - } else { - trns += "Traffic "; - // TODO - get the airport name somehow if uncontrolled - } - trns += plane.callsign; - trns += " on apron parking request taxi for traffic pattern"; - //cout << "trns = " << trns << endl; - pending_transmission = trns; - Transmit(1); - taxiRequestCleared = false; - taxiRequestPending = true; - } - } - - //cout << "!" << flush; - - // Maybe the below should be set when we get to the threshold and prepare for TO? - // FIXME TODO - pattern direction is still hardwired - patternDirection = -1; // Left - // At the bare minimum we ought to make sure it goes the right way at dual parallel rwy airports! - if(rwy.rwyID.size() == 3) { - patternDirection = (rwy.rwyID.substr(2,1) == "R" ? 1 : -1); - } - // Do nothing - Transform(); - //cout << ")" << flush; - break; - default: - break; - } - //cout << "I " << flush; - - //cout << "Update _pos = " << _pos << ", vis = " << _aip.getVisible() << '\n'; - - // Convienience output for AI debugging using the property logger - //fgSetDouble("/AI/Local1/ortho-x", (ortho.ConvertToLocal(_pos)).x()); - //fgSetDouble("/AI/Local1/ortho-y", (ortho.ConvertToLocal(_pos)).y()); - //fgSetDouble("/AI/Local1/elev", _pos.elev() * SG_METER_TO_FEET); - - // And finally, call parent. - FGAIPlane::Update(dt); -} - -void FGAILocalTraffic::RegisterTransmission(int code) { - switch(code) { - case 1: // taxi request cleared - taxiRequestCleared = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " cleared to taxi..."); - break; - case 2: // contact tower - responseCounter = 0; - contactTower = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " told to contact tower..."); - break; - case 3: // Cleared to line up - responseCounter = 0; - clearedToLineUp = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " cleared to line-up..."); - break; - case 4: // cleared to take-off - responseCounter = 0; - clearedToTakeOff = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " cleared to take-off..."); - break; - case 5: // contact ground - responseCounter = 0; - contactGround = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " told to contact ground..."); - break; - // case 6 is a temporary mega-hack for controlled airports without separate ground control - case 6: // taxi to the GA parking - responseCounter = 0; - _taxiToGA = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " told to taxi to the GA parking..."); - break; - case 7: // Cleared to land (also implies cleared for the option - _clearedToLand = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " cleared to land..."); - break; - case 13: // Go around! - responseCounter = 0; - goAround = true; - _clearedToLand = false; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " told to go-around!!"); - break; - default: - break; - } -} - -// Fly a traffic pattern -// FIXME - far too much of the mechanics of turning, rolling, accellerating, descending etc is in here. -// Move it out to FGAIPlane and have FlyTrafficPattern just specify what to do, not the implementation. -void FGAILocalTraffic::FlyTrafficPattern(double dt) { - // Need to differentiate between in-air (IAS governed) and on-ground (vel governed) - // Take-off is an interesting case - we are on the ground but takeoff speed is IAS governed. - - // WIND - // Wind has two effects - a mechanical one in that IAS translates to a different vel, and the hdg != track, - // but also a piloting effect, in that the AI must be able to descend at a different rate in order to hit the threshold. - - //cout << "dt = " << dt << '\n'; - double dist = 0; - // ack - I can't remember how long a rate 1 turn is meant to take. - double turn_time = 60.0; // seconds - TODO - check this guess - double turn_circumference; - double turn_radius; - SGVec3d orthopos = ortho.ConvertToLocal(_pos); // ortho position of the plane - //cout << "runway elev = " << rwy.threshold_pos.getElevationM() << ' ' << rwy.threshold_pos.getElevationM() * SG_METER_TO_FEET << '\n'; - //cout << "elev = " << _pos.elev() << ' ' << _pos.elev() * SG_METER_TO_FEET << '\n'; - - // HACK FOR TESTING - REMOVE - //cout << "Calling ExitRunway..." << endl; - //ExitRunway(orthopos); - //return; - // END HACK - - //wind - double wind_from = wind_from_hdg->getDoubleValue(); - double wind_speed = wind_speed_knots->getDoubleValue(); - - double dveldt; - - switch(leg) { - case TAKEOFF_ROLL: - //inAir = false; - track = rwy.hdg; - if(vel < 80.0) { - double dveldt = 5.0; - vel += dveldt * dt; - } - if(_ground_elevation_m > -9990.0) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - } - IAS = vel + (cos((_hdg - wind_from) * DCL_DEGREES_TO_RADIANS) * wind_speed); - if(IAS >= 70) { - leg = CLIMBOUT; - SetTrack(rwy.hdg); // Hands over control of turning to AIPlane - _pitch = 10.0; - IAS = best_rate_of_climb_speed; - //slope = 7.0; - slope = 6.0; // Reduced it slightly since it's climbing a lot steeper than I can in the JSBSim C172. - inAir = true; - } - break; - case CLIMBOUT: - // Turn to crosswind if above 700ft AND if other traffic allows - // (decided in FGTower and accessed through GetCrosswindConstraint(...)). - // According to AIM, traffic should climb to within 300ft of pattern altitude before commencing crosswind turn. - // TODO - At hot 'n high airports this may be 500ft AGL though - need to make this a variable. - if((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET > 700) { - double cc = 0.0; - if(_controlled && tower->GetCrosswindConstraint(cc)) { - if(orthopos.y() > cc) { - //cout << "Turning to crosswind, distance from threshold = " << orthopos.y() << '\n'; - leg = TURN1; - } - } else if(orthopos.y() > 1500.0) { // Added this constraint as a hack to prevent turning too early when going around. - // TODO - We should be doing it as a distance from takeoff end, not theshold end though. - //cout << "Turning to crosswind, distance from threshold = " << orthopos.y() << '\n'; - leg = TURN1; - } - } - // Need to check for levelling off in case we can't turn crosswind as soon - // as we would like due to other traffic. - if((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET > 1000) { - slope = 0.0; - _pitch = 0.0; - IAS = 80.0; // FIXME - use smooth transistion to new speed and attitude. - } - if(goAround && !goAroundCalled) { - if(responseCounter > 5.5) { - pending_transmission = plane.callsign; - pending_transmission += " going around"; - Transmit(); - goAroundCalled = true; - } - } - break; - case TURN1: - SetTrack(rwy.hdg + (90.0 * patternDirection)); - if((track < (rwy.hdg - 89.0)) || (track > (rwy.hdg + 89.0))) { - leg = CROSSWIND; - } - break; - case CROSSWIND: - goAround = false; - if((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET > 1000) { - slope = 0.0; - _pitch = 0.0; - IAS = 80.0; // FIXME - use smooth transistion to new speed - } - // turn 1000m out for now, taking other traffic into accout - if(fabs(orthopos.x()) > 900) { - double dd = 0.0; - if(_controlled && tower->GetDownwindConstraint(dd)) { - if(fabs(orthopos.x()) > fabs(dd)) { - //cout << "Turning to downwind, distance from centerline = " << fabs(orthopos.x()) << '\n'; - leg = TURN2; - } - } else { - //cout << "Turning to downwind, distance from centerline = " << fabs(orthopos.x()) << '\n'; - leg = TURN2; - } - } - break; - case TURN2: - SetTrack(rwy.hdg - (180 * patternDirection)); - // just in case we didn't make height on crosswind - if((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET > 1000) { - slope = 0.0; - _pitch = 0.0; - IAS = 80.0; // FIXME - use smooth transistion to new speed - } - if((track < (rwy.hdg - 179.0)) || (track > (rwy.hdg + 179.0))) { - leg = DOWNWIND; - transmitted = false; - } - break; - case DOWNWIND: - // just in case we didn't make height on crosswind - if(((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET > 995) && ((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET < 1015)) { - slope = 0.0; - _pitch = 0.0; - IAS = 90.0; // FIXME - use smooth transistion to new speed - } - if((_pos.getElevationM() - rwy.threshold_pos.getElevationM()) * SG_METER_TO_FEET >= 1015) { - slope = -1.0; - _pitch = -1.0; - IAS = 90.0; // FIXME - use smooth transistion to new speed - } - if((orthopos.y() < 0) && (!transmitted)) { - TransmitPatternPositionReport(); - transmitted = true; - } - if((orthopos.y() < -100) && (!descending)) { - //cout << "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDdddd\n"; - // Maybe we should think about when to start descending. - // For now we're assuming that we aim to follow the same glidepath regardless of wind. - double d1; - double d2; - CalculateSoD(((_controlled && tower->GetBaseConstraint(d1)) ? d1 : -1000.0), ((_controlled && tower->GetDownwindConstraint(d2)) ? d2 : 1000.0 * patternDirection), (patternDirection ? true : false)); - if(SoD.leg == DOWNWIND) { - descending = (orthopos.y() < SoD.y ? true : false); - } - - } - if(descending) { - slope = -5.5; // FIXME - calculate to descent at 500fpm and hit the desired point on the runway (taking wind into account as well!!) - _pitch = -3.0; - IAS = 85.0; - } - - // Try and arrange to turn nicely onto base - turn_circumference = IAS * 0.514444 * turn_time; - //Hmmm - this is an interesting one - ground vs airspeed in relation to turn radius - //We'll leave it as a hack with IAS for now but it needs revisiting. - turn_radius = turn_circumference / (2.0 * DCL_PI); - if(orthopos.y() < -1000.0 + turn_radius) { - //if(orthopos.y() < -980) { - double bb = 0.0; - if(_controlled && tower->GetBaseConstraint(bb)) { - if(fabs(orthopos.y()) > fabs(bb)) { - //cout << "Turning to base, distance from threshold = " << fabs(orthopos.y()) << '\n'; - leg = TURN3; - transmitted = false; - IAS = 80.0; - } - } else { - //cout << "Turning to base, distance from threshold = " << fabs(orthopos.y()) << '\n'; - leg = TURN3; - transmitted = false; - IAS = 80.0; - } - } - break; - case TURN3: - SetTrack(rwy.hdg - (90 * patternDirection)); - if(fabs(rwy.hdg - track) < 91.0) { - leg = BASE; - } - break; - case BASE: - if(!transmitted) { - // Base report should only be transmitted at uncontrolled airport - not towered. - if(!_controlled) TransmitPatternPositionReport(); - transmitted = true; - } - - if(!descending) { - double d1; - // Make downwind leg position artifically large to avoid any chance of SoD being returned as - // on downwind when we are already on base. - CalculateSoD(((_controlled && tower->GetBaseConstraint(d1)) ? d1 : -1000.0), (10000.0 * patternDirection), (patternDirection ? true : false)); - if(SoD.leg == BASE) { - descending = (fabs(orthopos.y()) < fabs(SoD.y) ? true : false); - } - - } - if(descending) { - slope = -5.5; // FIXME - calculate to descent at 500fpm and hit the threshold (taking wind into account as well!!) - _pitch = -4.0; - IAS = 70.0; - } - - // Try and arrange to turn nicely onto final - turn_circumference = IAS * 0.514444 * turn_time; - //Hmmm - this is an interesting one - ground vs airspeed in relation to turn radius - //We'll leave it as a hack with IAS for now but it needs revisiting. - turn_radius = turn_circumference / (2.0 * DCL_PI); - if(fabs(orthopos.x()) < (turn_radius + 50)) { - leg = TURN4; - transmitted = false; - //roll = -20; - } - break; - case TURN4: - SetTrack(rwy.hdg); - if(fabs(track - rwy.hdg) < 0.6) { - leg = FINAL; - vel = nominal_final_speed; - } - break; - case FINAL: - if(goAround && responseCounter > 2.0) { - leg = CLIMBOUT; - _pitch = 8.0; - IAS = best_rate_of_climb_speed; - slope = 5.0; // A bit less steep than the initial climbout. - inAir = true; - goAroundCalled = false; - descending = false; - break; - } - LevelWings(); - if(!transmitted) { - if((!_controlled) || (!_clearedToLand)) TransmitPatternPositionReport(); - transmitted = true; - } - if(!descending) { - // Make base leg position artifically large to avoid any chance of SoD being returned as - // on base or downwind when we are already on final. - CalculateSoD(-10000.0, (1000.0 * patternDirection), (patternDirection ? true : false)); - if(SoD.leg == FINAL) { - descending = (fabs(orthopos.y()) < fabs(SoD.y) ? true : false); - } - - } - if(descending) { - if(orthopos.y() < -50.0) { - double thesh_offset = 30.0; - slope = atan((_pos.getElevationM() - fgGetAirportElev(airportID)) / (orthopos.y() - thesh_offset)) * DCL_RADIANS_TO_DEGREES; - //cout << "slope = " << slope << ", elev = " << _pos.elev() << ", apt_elev = " << fgGetAirportElev(airportID) << ", op.y = " << orthopos.y() << '\n'; - if(slope < -10.0) slope = -10.0; - _savedSlope = slope; - _pitch = -4.0; - IAS = 70.0; - } else { - if(_pos.getElevationM() < (rwy.threshold_pos.getElevationM()+10.0+wheelOffset)) { - if(_ground_elevation_m > -9990.0) { - if(_pos.getElevationM() < (_ground_elevation_m + wheelOffset + 1.0)) { - slope = -2.0; - _pitch = 1.0; - IAS = 55.0; - } else if(_pos.getElevationM() < (_ground_elevation_m + wheelOffset + 5.0)) { - slope = -4.0; - _pitch = -2.0; - IAS = 60.0; - } else { - slope = _savedSlope; - _pitch = -3.0; - IAS = 65.0; - } - } else { - // Elev not determined - slope = _savedSlope; - _pitch = -3.0; - IAS = 65.0; - } - } else { - slope = _savedSlope; - _pitch = -3.0; - IAS = 65.0; - } - } - } - // Try and track the extended centreline - SetTrack(rwy.hdg - (0.2 * orthopos.x())); - //cout << "orthopos.x() = " << orthopos.x() << " hdg = " << hdg << '\n'; - if(_pos.getElevationM() < (rwy.threshold_pos.getElevationM()+20.0+wheelOffset)) { - DoGroundElev(); // Need to call it here expicitly on final since it's only called - // for us in update(...) when the inAir flag is false. - } - if(_pos.getElevationM() < (rwy.threshold_pos.getElevationM()+10.0+wheelOffset)) { - //slope = -1.0; - //_pitch = 1.0; - if(_ground_elevation_m > -9990.0) { - if((_ground_elevation_m + wheelOffset) > _pos.getElevationM()) { - slope = 0.0; - _pitch = 0.0; - leg = LANDING_ROLL; - inAir = false; - LevelWings(); - ClearTrack(); // Take over explicit track handling since AIPlane currently always banks when changing course - } - } // else need a fallback position based on arpt elev in case ground elev determination fails? - } else { - // TODO - } - break; - case LANDING_ROLL: - //inAir = false; - descending = false; - if(_ground_elevation_m > -9990.0) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - } - track = rwy.hdg; - dveldt = -5.0; - vel += dveldt * dt; - // FIXME - differentiate between touch and go and full stops - if(vel <= 15.0) { - //cout << "Vel <= 15.0, circuitsToFly = " << circuitsToFly << endl; - if(circuitsToFly <= 0) { - //cout << "Calling ExitRunway..." << endl; - ExitRunway(orthopos); - return; - } else { - //cout << "Taking off again..." << endl; - leg = TAKEOFF_ROLL; - --circuitsToFly; - } - } - break; - case LEG_UNKNOWN: - break; - } - - if(inAir) { - // calculate ground speed and crab from the wind triangle - double wind_angle = GetAngleDiff_deg(wind_from + 180, track); - double wind_side = (wind_angle < 0) ? -1.0 : 1.0; - - double sine_of_crab = wind_speed / IAS * sin(fabs(wind_angle) * DCL_DEGREES_TO_RADIANS); - if (sine_of_crab >= 1.0) { - // The crosswind component is greater than the IAS, - // we can't keep the aircraft on track. - // Assume increased IAS such that it cancels lateral speed. - // This is unrealistic, but not sure how the rest of the sim - // would react to the aircraft going off course. - // Should be a rare case anyway. - crab = wind_side * 90.0; - } else { - crab = asin(sine_of_crab) * DCL_RADIANS_TO_DEGREES * wind_side; - } - vel = cos(wind_angle * DCL_DEGREES_TO_RADIANS) * wind_speed - + cos(crab * DCL_DEGREES_TO_RADIANS) * IAS; - } else { // on the ground - crab dosen't apply - crab = 0.0; - } - - //cout << "X " << orthopos.x() << " Y " << orthopos.y() << " SLOPE " << slope << " elev " << _pos.elev() * SG_METER_TO_FEET << '\n'; - - _hdg = track + crab; - dclBoundHeading(_hdg); - dist = vel * 0.514444 * dt; - _pos = dclUpdatePosition(_pos, track, slope, dist); -} - -// Pattern direction is true for right, false for left -void FGAILocalTraffic::CalculateSoD(double base_leg_pos, double downwind_leg_pos, bool pattern_direction) { - // For now we'll ignore wind and hardwire the glide angle. - double ga = 5.5; //degrees - double pa = 1000.0 * SG_FEET_TO_METER; // pattern altitude in meters - // FIXME - get glideslope angle and pattern altitude agl from airport details if available - - // For convienience, we'll have +ve versions of the input distances - double blp = fabs(base_leg_pos); - double dlp = fabs(downwind_leg_pos); - - //double turn_allowance = 150.0; // Approximate distance in meters that a 90deg corner is shortened by turned in a light plane. - - double stod = pa / tan(ga * DCL_DEGREES_TO_RADIANS); // distance in meters from touchdown point to start descent - //cout << "Descent to start = " << stod << " meters out\n"; - if(stod < blp) { // Start descending on final - SoD.leg = FINAL; - SoD.y = stod * -1.0; - SoD.x = 0.0; - } else if(stod < (blp + dlp)) { // Start descending on base leg - SoD.leg = BASE; - SoD.y = blp * -1.0; - SoD.x = (pattern_direction ? (stod - dlp) : (stod - dlp) * -1.0); - } else { // Start descending on downwind leg - SoD.leg = DOWNWIND; - SoD.x = (pattern_direction ? dlp : dlp * -1.0); - SoD.y = (blp - (stod - (blp + dlp))) * -1.0; - } -} - -void FGAILocalTraffic::TransmitPatternPositionReport(void) { - // airport name + "traffic" + airplane callsign + pattern direction + pattern leg + rwy + ? - string trns; - int code = 0; - const string& apt_name = _controlled ? tower->get_name() : airportID; - - trns += apt_name; - trns += " Traffic "; - trns += plane.callsign; - if(patternDirection == 1) { - trns += " right "; - } else { - trns += " left "; - } - - // We could probably get rid of this whole switch statement and just pass a string containing the leg from the FlyPattern function. - switch(leg) { // We'll assume that transmissions in turns are intended for next leg - do pilots ever call out that they are in the turn? - case TURN1: - // Fall through to CROSSWIND - case CROSSWIND: // I don't think this case will be used here but it can't hurt to leave it in - trns += "crosswind "; - break; - case TURN2: - // Fall through to DOWNWIND - case DOWNWIND: - trns += "downwind "; - code = 11; - break; - case TURN3: - // Fall through to BASE - case BASE: - trns += "base "; - break; - case TURN4: - // Fall through to FINAL - case FINAL: // maybe this should include long/short final if appropriate? - trns += "final "; - code = 13; - break; - default: // Hopefully this won't be used - trns += "pattern "; - break; - } - trns += ConvertRwyNumToSpokenString(rwy.rwyID); - - trns += ' '; - - // And add the airport name again - trns += apt_name; - - pending_transmission = trns; - ConditionalTransmit(60.0, code); // Assume a report of this leg will be invalid if we can't transmit within a minute. -} - -// Callback handler -// TODO - Really should enumerate these coded values. -void FGAILocalTraffic::ProcessCallback(int code) { - // 1 - Request Departure from ground - // 2 - Report at hold short - // 3 - Report runway vacated - // 10 - report crosswind - // 11 - report downwind - // 12 - report base - // 13 - report final - if(code == 1) { - ground->RequestDeparture(plane, this); - } else if(code == 2) { - tower->ContactAtHoldShort(plane, this, CIRCUIT); - } else if(code == 3) { - tower->ReportRunwayVacated(plane.callsign); - } else if(code == 11) { - tower->ReportDownwind(plane.callsign); - } else if(code == 13) { - tower->ReportFinal(plane.callsign); - } else if(code == 99) { // Flag this instance for deletion - responseCounter = 0; - _removeSelf = true; - SG_LOG(SG_ATC, SG_INFO, "AI local traffic " << plane.callsign << " delete instance callback called."); - } -} - -void FGAILocalTraffic::ExitRunway(const SGVec3d& orthopos) { - //cout << "In ExitRunway" << endl; - //cout << "Runway ID is " << rwy.ID << endl; - - _clearedToLand = false; - - node_array_type exitNodes = ground->GetExits(rwy.rwyID); //I suppose we ought to have some fallback for rwy with no defined exits? - /* - cout << "Node ID's of exits are "; - for(unsigned int i=0; inodeID << ' '; - } - cout << endl; - */ - if(exitNodes.size()) { - //Find the next exit from orthopos.y - double d; - double dist = 100000; //ie. longer than any runway in existance - double backdist = 100000; - node_array_iterator nItr = exitNodes.begin(); - node* rwyExit = *(exitNodes.begin()); - //int gateID; //This might want to be more persistant at some point - while(nItr != exitNodes.end()) { - d = ortho.ConvertToLocal((*nItr)->pos).y() - ortho.ConvertToLocal(_pos).y(); //FIXME - consider making orthopos a class variable - if(d > 0.0) { - if(d < dist) { - dist = d; - rwyExit = *nItr; - } - } else { - if(fabs(d) < backdist) { - backdist = d; - //TODO - need some logic here that if we don't get a forward exit we turn round and store the backwards one - } - } - ++nItr; - } - ourGate = ground->GetGateNode(); - if(ourGate == NULL) { - // Implies no available gates - what shall we do? - // For now just vanish the plane - possibly we can make this more elegant in the future - SG_LOG(SG_ATC, SG_ALERT, "No gate found by FGAILocalTraffic whilst landing at " << airportID << '\n'); - //_aip.setVisible(false); - //cout << "Setting visible false\n"; - operatingState = PARKED; - return; - } - path = ground->GetPath(rwyExit, ourGate); - /* - cout << "path returned was:" << endl; - for(unsigned int i=0; istruct_type) { - case NODE: - cout << "NODE " << ((node*)(path[i]))->nodeID << endl; - break; - case ARC: - cout << "ARC\n"; - break; - } - } - */ - taxiState = TD_INBOUND; - StartTaxi(); - } else { - // Something must have gone wrong with the ground network file - or there is only a rwy here and no exits defined - SG_LOG(SG_ATC, SG_INFO, "No exits found by FGAILocalTraffic from runway " << rwy.rwyID << " at " << airportID << '\n'); - //if(airportID == "KRHV") cout << "No exits found by " << plane.callsign << " from runway " << rwy.rwyID << " at " << airportID << '\n'; - // What shall we do - just remove the plane from sight? - _aip.setVisible(false); - _invisible = true; - //cout << "Setting visible false\n"; - //tower->ReportRunwayVacated(plane.callsign); - string trns = "Clear of the runway "; - trns += plane.callsign; - pending_transmission = trns; - Transmit(3); - operatingState = PARKED; - } -} - -// Set the class variable nextTaxiNode to the next node in the path -// and update taxiPathPos, the class variable path iterator position -// TODO - maybe should return error codes to the calling function if we fail here -void FGAILocalTraffic::GetNextTaxiNode() { - //cout << "GetNextTaxiNode called " << endl; - //cout << "taxiPathPos = " << taxiPathPos << endl; - ground_network_path_iterator pathItr = path.begin() + taxiPathPos; - if(pathItr == path.end()) { - SG_LOG(SG_ATC, SG_ALERT, "ERROR IN AILocalTraffic::GetNextTaxiNode - no more nodes in path\n"); - } else { - if((*pathItr)->struct_type == NODE) { - //cout << "ITS A NODE" << endl; - //*pathItr = new node; - nextTaxiNode = (node*)*pathItr; - ++taxiPathPos; - //delete pathItr; - } else { - //cout << "ITS NOT A NODE" << endl; - //The first item in found must have been an arc - //Assume for now that it was straight - pathItr++; - taxiPathPos++; - if(pathItr == path.end()) { - SG_LOG(SG_ATC, SG_ALERT, "ERROR IN AILocalTraffic::GetNextTaxiNode - path ended with an arc\n"); - } else if((*pathItr)->struct_type == NODE) { - nextTaxiNode = (node*)*pathItr; - ++taxiPathPos; - } else { - //OOPS - two non-nodes in a row - that shouldn't happen ATM - SG_LOG(SG_ATC, SG_ALERT, "ERROR IN AILocalTraffic::GetNextTaxiNode - two non-nodes in sequence\n"); - } - } - } -} - -// StartTaxi - set up the taxiing state - call only at the start of taxiing -void FGAILocalTraffic::StartTaxi() { - //cout << "StartTaxi called" << endl; - operatingState = TAXIING; - - taxiPathPos = 0; - - //Set the desired heading - //Assume we are aiming for first node on path - //Eventually we may need to consider the fact that we might start on a curved arc and - //not be able to head directly for the first node. - GetNextTaxiNode(); // sets the class variable nextTaxiNode to the next taxi node! - desiredTaxiHeading = GetHeadingFromTo(_pos, nextTaxiNode->pos); - //cout << "First taxi heading is " << desiredTaxiHeading << endl; -} - -// speed in knots, headings in degrees, radius in meters. -static double TaxiTurnTowardsHeading(double current_hdg, double desired_hdg, double speed, double radius, double dt) { - // wrap heading - this prevents a logic bug where the plane would just go round in circles!! - while(current_hdg < 0.0) { - current_hdg += 360.0; - } - while(current_hdg > 360.0) { - current_hdg -= 360.0; - } - if(fabs(current_hdg - desired_hdg) > 0.1) { - // Which is the quickest direction to turn onto heading? - if(desired_hdg > current_hdg) { - if((desired_hdg - current_hdg) <= 180) { - // turn right - current_hdg += ((speed * 0.514444 * dt) / (radius * DCL_PI)) * 180.0; - // TODO - check that increments are less than the delta that we check for the right direction - // Probably need to reduce convergence speed as convergence is reached - } else { - current_hdg -= ((speed * 0.514444 * dt) / (radius * DCL_PI)) * 180.0; - } - } else { - if((current_hdg - desired_hdg) <= 180) { - // turn left - current_hdg -= ((speed * 0.514444 * dt) / (radius * DCL_PI)) * 180.0; - // TODO - check that increments are less than the delta that we check for the right direction - // Probably need to reduce convergence speed as convergence is reached - } else { - current_hdg += ((speed * 0.514444 * dt) / (radius * DCL_PI)) * 180.0; - } - } - } - return(current_hdg); -} - -void FGAILocalTraffic::Taxi(double dt) { - //cout << "Taxi called" << endl; - // Logic - if we are further away from next point than turn radius then head for it - // If we have reached turning point then get next point and turn onto that heading - // Look out for the finish!! - - desiredTaxiHeading = GetHeadingFromTo(_pos, nextTaxiNode->pos); - - bool lastNode = (taxiPathPos == path.size() ? true : false); - if(lastNode) { - //cout << "LAST NODE\n"; - } - - // HACK ALERT! - for now we will taxi at constant speed for straights and turns - - // Remember that hdg is always equal to track when taxiing so we don't have to consider them both - double dist_to_go = dclGetHorizontalSeparation(_pos, nextTaxiNode->pos); // we may be able to do this more cheaply using orthopos - //cout << "dist_to_go = " << dist_to_go << endl; - if((nextTaxiNode->type == GATE) && (dist_to_go <= 0.1)) { - // This might be more robust to outward paths starting with a gate if we check for either - // last node or TD_INBOUND ? - // park up - operatingState = PARKED; - } else if(((dist_to_go > taxiTurnRadius) || (nextTaxiNode->type == GATE)) && (!liningUp)){ - // if the turn radius is r, and speed is s, then in a time dt we turn through - // ((s.dt)/(PI.r)) x 180 degrees - // or alternatively (s.dt)/r radians - //cout << "hdg = " << hdg << " desired taxi heading = " << desiredTaxiHeading << '\n'; - _hdg = TaxiTurnTowardsHeading(_hdg, desiredTaxiHeading, nominalTaxiSpeed, taxiTurnRadius, dt); - double vel = nominalTaxiSpeed; - //cout << "vel = " << vel << endl; - double dist = vel * 0.514444 * dt; - //cout << "dist = " << dist << endl; - double track = _hdg; - //cout << "track = " << track << endl; - double slope = 0.0; - _pos = dclUpdatePosition(_pos, track, slope, dist); - //cout << "Updated position...\n"; - if(_ground_elevation_m > -9990) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - } // else don't change the elev until we get a valid ground elev again! - } else if(lastNode) { - if(taxiState == TD_LINING_UP) { - if((!liningUp) && (dist_to_go <= taxiTurnRadius)) { - liningUp = true; - } - if(liningUp) { - _hdg = TaxiTurnTowardsHeading(_hdg, rwy.hdg, nominalTaxiSpeed, taxiTurnRadius, dt); - double vel = nominalTaxiSpeed; - //cout << "vel = " << vel << endl; - double dist = vel * 0.514444 * dt; - //cout << "dist = " << dist << endl; - double track = _hdg; - //cout << "track = " << track << endl; - double slope = 0.0; - _pos = dclUpdatePosition(_pos, track, slope, dist); - //cout << "Updated position...\n"; - if(_ground_elevation_m > -9990) { - _pos.setElevationM(_ground_elevation_m + wheelOffset); - } // else don't change the elev until we get a valid ground elev again! - if(fabs(_hdg - rwy.hdg) <= 1.0) { - operatingState = IN_PATTERN; - leg = TAKEOFF_ROLL; - inAir = false; - liningUp = false; - } - } - } else if(taxiState == TD_OUTBOUND) { - // Pause awaiting further instructions - // and for now assume we've reached the hold-short node - holdingShort = true; - } // else at the moment assume TD_INBOUND always ends in a gate in which case we can ignore it - } else { - // Time to turn (we've already checked it's not the end we're heading for). - // set the target node to be the next node which will prompt automatically turning onto - // the right heading in the stuff above, with the usual provisos applied. - GetNextTaxiNode(); - // For now why not just recursively call this function? - Taxi(dt); - } -} - - -// Warning - ground elev determination is CPU intensive -// Either this function or the logic of how often it is called -// will almost certainly change. -void FGAILocalTraffic::DoGroundElev() { - // Only do the proper hitlist stuff if we are within visible range of the viewer. - double visibility_meters = fgGetDouble("/environment/visibility-m"); - FGViewer* vw = globals->get_current_view(); - if(dclGetHorizontalSeparation(_pos, SGGeod::fromGeodM(vw->getPosition(), 0.0)) > visibility_meters) { - _ground_elevation_m = aptElev; - return; - } - - // FIXME: make shure the pos.lat/pos.lon values are in degrees ... - double range = 500.0; - if (!globals->get_tile_mgr()->scenery_available(_aip.getPosition(), range)) { - // Try to shedule tiles for that position. - globals->get_tile_mgr()->update( _aip.getPosition(), range ); - } - - // FIXME: make shure the pos.lat/pos.lon values are in degrees ... - double alt; - if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(_aip.getPosition(), 20000), alt, 0, _aip.getSceneGraph())) - _ground_elevation_m = alt; -} - diff --git a/src/ATCDCL/AILocalTraffic.hxx b/src/ATCDCL/AILocalTraffic.hxx deleted file mode 100644 index c62a9456e..000000000 --- a/src/ATCDCL/AILocalTraffic.hxx +++ /dev/null @@ -1,233 +0,0 @@ -// FGAILocalTraffic - AIEntity derived class with enough logic to -// fly and interact with the traffic pattern. -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifndef _FG_AILocalTraffic_HXX -#define _FG_AILocalTraffic_HXX - -#include -#include
- -#include "AIPlane.hxx" -#include "ATCProjection.hxx" -#include "ground.hxx" - -class FGGround; -class FGTower; -struct Gate; - -#include -using std::string; - -enum TaxiState { - TD_INBOUND, - TD_OUTBOUND, - TD_NONE, - TD_LINING_UP -}; - -enum OperatingState { - IN_PATTERN, - TAXIING, - PARKED, - EN_ROUTE -}; - -struct StartOfDescent { - PatternLeg leg; - double x; // Runway aligned orthopos - double y; // ditto -}; - -class FGAILocalTraffic : public FGAIPlane { - -public: - - // At the moment we expect the expanded short form callsign - eventually we will just want the reg + type. - FGAILocalTraffic(); - ~FGAILocalTraffic(); - - // Initialise - bool Init(const string& callsign, const string& ICAO, OperatingState initialState = PARKED, PatternLeg initialLeg = DOWNWIND); - - // Run the internal calculations - void Update(double dt); - - // Go out and practice circuits - void FlyCircuits(int numCircuits, bool tag); - - // Return what type of landing we're doing on this circuit - LandingType GetLandingOption(); - - // TODO - this will get more complex and moved into the main class - // body eventually since the position approved to taxi to will have - // to be passed. - inline void ApproveTaxiRequest() {taxiRequestCleared = true;} - - inline void DenyTaxiRequest() {taxiRequestCleared = false;} - - void RegisterTransmission(int code); - - // Process callbacks sent by base class - // (These codes are not related to the codes above) - void ProcessCallback(int code); - - // This is a hack and will probably go eventually - inline bool AtHoldShort() {return holdingShort;} - -protected: - - // Attempt to enter the traffic pattern in a reasonably intelligent manner - void EnterTrafficPattern(double dt); - - // Set up the internal state to be consistent for a downwind entry. - void DownwindEntry(); - - // Ditto for straight-in - void StraightInEntry(bool des = false); - - // Do what is necessary to land and parkup at home airport - void ReturnToBase(double dt); - - // Airport/runway/pattern details - string airportID; // The ICAO code of the airport that we're operating around - double aptElev; // Airport elevation - FGGround* ground; // A pointer to the ground control. - FGTower* tower; // A pointer to the tower control. - bool _controlled; // Set true if we find tower control working for the airport, false otherwise. - RunwayDetails rwy; - double patternDirection; // 1 for right, -1 for left (This is double because we multiply/divide turn rates - // with it to get RH/LH turns - DON'T convert it to int under ANY circumstances!! - double glideAngle; // Assumed to be visual glidepath angle for FGAILocalTraffic - can be found at www.airnav.com - // Its conceivable that patternDirection and glidePath could be moved into the RunwayDetails structure. - - // Its possible that this might be moved out to the ground/airport class at some point. - FGATCAlignedProjection ortho; // Orthogonal mapping of the local area with the threshold at the origin - // and the runway aligned with the y axis. - - void GetAirportDetails(const string& id); - - void GetRwyDetails(const string& id); - - double responseCounter; // timer in seconds to allow response to requests to be a little while after them - // Will almost certainly get moved to FGAIPlane. - -private: - FGATCMgr* ATC; - // This is purely for synactic convienience to avoid writing globals->get_ATC_mgr()-> all through the code! - - // High-level stuff - OperatingState operatingState; - int circuitsToFly; //Number of circuits still to do in this session NOT INCLUDING THE CURRENT ONE - bool touchAndGo; //True if circuits should be flown touch and go, false for full stop - bool transmitted; // Set true when a position report for the current leg has been transmitted. - - // Performance characteristics of the plane in knots and ft/min - some of this might get moved out into FGAIPlane - double Vr; - double best_rate_of_climb_speed; - double best_rate_of_climb; - double nominal_climb_speed; - double nominal_climb_rate; - double nominal_circuit_speed; - double min_circuit_speed; - double max_circuit_speed; - double nominal_descent_rate; - double nominal_approach_speed; - double nominal_final_speed; - double stall_speed_landing_config; - double nominal_taxi_speed; - - // Physical/rendering stuff - double wheelOffset; // Height above ground at which we need to render the plane whilst taxiing - bool elevInitGood; // We have had at least one good elev reading - bool inAir; // True when off the ground - - // environment - some of this might get moved into FGAIPlane - SGPropertyNode_ptr wind_from_hdg; //degrees - SGPropertyNode_ptr wind_speed_knots; //knots - - // Pattern details that (may) change - int numInPattern; // Number of planes in the pattern (this might get more complicated if high performance GA aircraft fly a higher pattern eventually) - int numAhead; // More importantly - how many of them are ahead of us? - double distToNext; // And even more importantly, how near are we getting to the one immediately ahead? - //PatternLeg leg; // Our current position in the pattern - now moved to FGAIPlane - StartOfDescent SoD; // Start of descent calculated wrt wind, pattern size & altitude, glideslope etc - bool descending; // We're in the coming down phase of the pattern - double targetDescentRate; // m/s - - // Taxiing details - // At the moment this assumes that all taxiing in is to gates (a loose term that includes - // any permitted parking spot) and that all taxiing out is to runways. - bool parked; - bool taxiing; - bool taxiRequestPending; - bool taxiRequestCleared; - TaxiState taxiState; - double desiredTaxiHeading; - double taxiTurnRadius; - double nominalTaxiSpeed; - Gate* ourGate; - ground_network_path_type path; // a path through the ground network for the plane to taxi - unsigned int taxiPathPos; // position of iterator in taxi path when applicable - node* nextTaxiNode; // next node in taxi path - node* holdShortNode; - //Runway out_dest; //FIXME - implement this - bool holdingShort; - bool reportReadyForDeparture; // set true when ATC has requested that the plane report when ready for departure - bool clearedToLineUp; - bool clearedToTakeOff; - bool _clearedToLand; // also implies cleared for the option. - bool liningUp; // Set true when the turn onto the runway heading is commenced when taxiing out - bool goAround; // Set true if need to go-around - bool goAroundCalled; // Set true during go-around only after we have called our go-around on the radio - bool contactTower; // we have been told to contact tower - bool contactGround; // we have been told to contact ground - bool changeFreq; // true when we need to change frequency - bool _taxiToGA; // Temporary mega-hack indicating we are to taxi to the GA parking and disconnect from tower control. - bool _removeSelf; // Indicates that we wish to remove this instance. The use of a variable is a hack to allow time for messages to purge before removal, due to the fagility of the current dialog system. - atc_type changeFreqType; // the service we need to change to - bool freeTaxi; // False if the airport has a facilities file with a logical taxi network defined, true if we need to calculate our own taxiing points. - - // Hack for getting close to the runway when atan can go pear-shaped - double _savedSlope; - - void FlyTrafficPattern(double dt); - - // TODO - need to add something to define what option we are flying - Touch and go / Stop and go / Landing properly / others? - - void TransmitPatternPositionReport(); - - void CalculateSoD(double base_leg_pos, double downwind_leg_pos, bool pattern_direction); - - void ExitRunway(const SGVec3d& orthopos); - - void StartTaxi(); - - void Taxi(double dt); - - void GetNextTaxiNode(); - - void DoGroundElev(); - - // Set when the plane should be invisible *regardless of distance from user*. - bool _invisible; -}; - -#endif // _FG_AILocalTraffic_HXX diff --git a/src/ATCDCL/AIMgr.cxx b/src/ATCDCL/AIMgr.cxx deleted file mode 100644 index 8b6c448bc..000000000 --- a/src/ATCDCL/AIMgr.cxx +++ /dev/null @@ -1,604 +0,0 @@ -// AIMgr.cxx - implementation of FGAIMgr -// - a global management class for FlightGear generated AI traffic -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include - -#include
-#include
-#include -#include -#include -#include - -#ifdef _MSC_VER -# include -#else -# include // for directory reading -# include // for directory reading -#endif - -#include -#include - -#include "AIMgr.hxx" -#include "AILocalTraffic.hxx" -#include "AIGAVFRTraffic.hxx" -#include "ATCutils.hxx" -#include "commlist.hxx" - -using std::list; -using std::cout; - -using namespace simgear; - -// extern from Airports/simple.cxx -extern SGGeod fgGetAirportPos( const std::string& id ); - -FGAIMgr::FGAIMgr() { - ATC = globals->get_ATC_mgr(); - initDone = false; - ai_callsigns_used["GFS"] = 1; // so we don't inadvertently use this - // TODO - use the proper user callsign when it becomes user settable. - removalList.clear(); - activated.clear(); - _havePiperModel = true; -} - -FGAIMgr::~FGAIMgr() { - for (ai_list_itr = ai_list.begin(); ai_list_itr != ai_list.end(); ai_list_itr++) { - delete (*ai_list_itr); - } -} - -void FGAIMgr::init() { - //cout << "AIMgr::init called..." << endl; - - // Pointers to user's position - lon_node = fgGetNode("/position/longitude-deg", true); - lat_node = fgGetNode("/position/latitude-deg", true); - elev_node = fgGetNode("/position/altitude-ft", true); - - // Load up models at the start to avoid pausing later - // Hack alert - Hardwired paths!! - string planepath = "Aircraft/c172p/Models/c172p.xml"; - bool _loadedDefaultOK = true; - try { - _defaultModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props()); - } catch(sg_exception&) { - _loadedDefaultOK = false; - } - - if(!_loadedDefaultOK ) { - // Just load the same 3D model as the default user plane - that's *bound* to exist! - // TODO - implement robust determination of availability of GA AI aircraft models - planepath = "Aircraft/c172p/Models/c172p.ac"; - _defaultModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props()); - } - - planepath = "Aircraft/pa28-161/Models/pa28-161.ac"; - try { - _piperModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props()); - } catch(sg_exception&) { - _havePiperModel = false; - } - - // go through the $FG_ROOT/ATC directory and find all *.taxi files - SGPath path(globals->get_fg_root()); - path.append("ATC/"); - string dir = path.dir(); - string ext; - string file, f_ident; - int pos; - - ulDir *d; - struct ulDirEnt *de; - - if ( (d = ulOpenDir( dir.c_str() )) == NULL ) { - SG_LOG(SG_ATC, SG_WARN, "cannot open directory " << dir); - } else { - // load all .taxi files - while ( (de = ulReadDir(d)) != NULL ) { - file = de->d_name; - pos = file.find("."); - ext = file.substr(pos + 1); - if(ext == "taxi") { - f_ident = file.substr(0, pos); - const FGAirport *a = fgFindAirportID( f_ident); - if(a){ - SGBucket sgb(a->getLongitude(), a->getLatitude()); - int idx = sgb.gen_index(); - if(facilities.find(idx) != facilities.end()) { - facilities[idx]->push_back(f_ident); - } else { - ID_list_type* apts = new ID_list_type; - apts->push_back(f_ident); - facilities[idx] = apts; - } - SG_LOG(SG_ATC, SG_BULK, "Mapping " << f_ident << " to bucket " << idx); - } - } - } - ulCloseDir(d); - } - - // See if are in range at startup and activate if necessary - SearchByPos(15.0); - - initDone = true; -} - -void FGAIMgr::bind() { -} - -void FGAIMgr::unbind() { -} - -void FGAIMgr::update(double dt) { - if(!initDone) { - init(); - SG_LOG(SG_ATC, SG_WARN, "Warning - AIMgr::update(...) called before AIMgr::init()"); - } - - //cout << activated.size() << '\n'; - - SGGeod userPos = SGGeod::fromDegM(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue()); - - // TODO - make these class variables!! - static int i = 0; - static int j = 0; - - // Don't update any planes for first 50 runs through - this avoids some possible initialisation anomalies - // Might not need it now we have fade-in though? - if(i < 50) { - ++i; - return; - } - - if(j == 215) { - SearchByPos(25.0); - j = 0; - } else if(j == 200) { - // Go through the list of activated airports and remove those out of range - //cout << "The following airports have been activated by the AI system:\n"; - ai_activated_map_iterator apt_itr = activated.begin(); - while(apt_itr != activated.end()) { - //cout << "FIRST IS " << (*apt_itr).first << '\n'; - if(dclGetHorizontalSeparation(userPos, fgGetAirportPos((*apt_itr).first)) > (35.0 * 1600.0)) { - // Then get rid of it and make sure the iterator is left pointing to the next one! - string s = (*apt_itr).first; - if(traffic.find(s) != traffic.end()) { - //cout << "s = " << s << ", traffic[s].size() = " << traffic[s].size() << '\n'; - if(!traffic[s].empty()) { - apt_itr++; - } else { - //cout << "Erasing " << (*apt_itr).first << " and traffic" << '\n'; - activated.erase(apt_itr); - apt_itr = activated.upper_bound(s); - traffic.erase(s); - } - } else { - //cout << "Erasing " << (*apt_itr).first << ' ' << (*apt_itr).second << '\n'; - activated.erase(apt_itr); - apt_itr = activated.upper_bound(s); - } - } else { - apt_itr++; - } - } - } else if(j == 180) { - // Go through the list of activated airports and do the random airplane generation - ai_traffic_map_iterator it = traffic.begin(); - while(it != traffic.end()) { - string s = (*it).first; - //cout << "s = " << s << " size = " << (*it).second.size() << '\n'; - // Only generate extra traffic if within a certain distance of the user, - // TODO - maybe take users's tuned freq into account as well. - double d = dclGetHorizontalSeparation(userPos, fgGetAirportPos(s)); - if(d < (15.0 * 1600.0)) { - double cd = 0.0; - bool gen = false; - //cout << "Size of list is " << (*it).second.size() << " at " << s << '\n'; - if((*it).second.size()) { - FGAIEntity* e = *((*it).second.rbegin()); // Get the last airplane currently scheduled to arrive at this airport. - cd = dclGetHorizontalSeparation(e->getPos(), fgGetAirportPos(s)); - if(cd < (d < 5000 ? 10000 : d + 5000)) { - gen = true; - } - } else { - gen = true; - cd = 0.0; - } - if(gen) { - //cout << "Generating extra traffic at airport " << s << ", at least " << cd << " meters out\n"; - //GenerateSimpleAirportTraffic(s, cd); - GenerateSimpleAirportTraffic(s, cd + 3000.0); // The random seems a bit wierd - traffic could get far too bunched without the +3000. - // TODO - make the anti-random constant variable depending on the ai-traffic level. - } - } - ++it; - } - } - - ++j; - - //cout << "Size of AI list is " << ai_list.size() << '\n'; - - // TODO - need to add a check of if any activated airports have gone out of range - - string rs; // plane to be removed, if one. - if(removalList.size()) { - rs = *(removalList.begin()); - removalList.pop_front(); - } else { - rs = ""; - } - - // Traverse the list of active planes and run all their update methods - // TODO - spread the load - not all planes should need updating every frame. - // Note that this will require dt to be calculated for each plane though - // since they rely on it to calculate distance travelled. - ai_list_itr = ai_list.begin(); - while(ai_list_itr != ai_list.end()) { - FGAIEntity *e = *ai_list_itr; - if(rs.size() && e->GetCallsign() == rs) { - //cout << "Removing " << rs << " from ai_list\n"; - ai_list_itr = ai_list.erase(ai_list_itr); - delete e; - // This is a hack - we should deref this plane from the airport count! - } else { - e->Update(dt); - ++ai_list_itr; - } - } - - //cout << "Size of AI list is " << ai_list.size() << '\n'; -} - -void FGAIMgr::ScheduleRemoval(const string& s) { - //cout << "Scheduling removal of plane " << s << " from AIMgr\n"; - removalList.push_back(s); -} - -// Activate AI traffic at an airport -void FGAIMgr::ActivateAirport(const string& ident) { - ATC->AIRegisterAirport(ident); - // TODO - need to start the traffic more randomly - FGAILocalTraffic* local_traffic = new FGAILocalTraffic; - local_traffic->SetModel(_defaultModel.get()); // currently hardwired to cessna. - //local_traffic->Init(ident, IN_PATTERN, TAKEOFF_ROLL); - local_traffic->Init(GenerateShortForm(GenerateUniqueCallsign()), ident); - local_traffic->FlyCircuits(1, true); // Fly 2 circuits with touch & go in between - ai_list.push_back(local_traffic); - traffic[ident].push_back(local_traffic); - //cout << "******** ACTIVATING AIRPORT, ident = " << ident << '\n'; - activated[ident] = 1; -} - -// Hack - Generate AI traffic at an airport with no facilities file -void FGAIMgr::GenerateSimpleAirportTraffic(const string& ident, double min_dist) { - // Ugly hack - don't let VFR Cessnas operate at a hardwired list of major airports - // This will go eventually once airport .xml files specify the traffic profile - if(ident == "KSFO" || ident == "KDFW" || ident == "EGLL" || ident == "KORD" || ident == "KJFK" - || ident == "KMSP" || ident == "KLAX" || ident == "KBOS" || ident == "KEDW" - || ident == "KSEA" || ident == "EHAM") { - return; - } - - /* - // TODO - check for military airports - this should be in the current data. - // UGGH - there's no point at the moment - everything is labelled civil in basic.dat! - FGAirport a = fgFindAirportID(ident, &a); - if(a) { - cout << "CODE IS " << a.code << '\n'; - } else { - // UG - can't find the airport! - return; - } - */ - - SGGeod aptpos = fgGetAirportPos(ident); // TODO - check for elev of -9999 - //cout << "ident = " << ident << ", elev = " << aptpos.getElevationM() << '\n'; - - // Operate from airports at 3000ft and below only to avoid the default cloud layers and since we don't degrade AI performance with altitude. - if(aptpos.getElevationM() > 3000) { - //cout << "High alt airports not yet supported - returning\n"; - return; - } - - // Rough hack for plane type - make 70% of the planes cessnas, the rest pipers. - bool cessna = true; - - // Get the time and only operate VFR in the (approximate) daytime. - struct tm *t = globals->get_time_params()->getGmt(); - int loc_time = t->tm_hour + int(aptpos.getLongitudeDeg() / (360.0 / 24.0)); - while (loc_time < 0) - loc_time += 24; - while (loc_time >= 24) - loc_time -= 24; - - //cout << "loc_time = " << loc_time << '\n'; - if(loc_time < 7 || loc_time > 19) return; - - // Check that the visibility is OK for IFR operation. - double visibility; - FGEnvironment stationweather = - ((FGEnvironmentMgr *)globals->get_subsystem("environment")) - ->getEnvironment(aptpos.getLatitudeDeg(), aptpos.getLongitudeDeg(), aptpos.getElevationM()); // TODO - check whether this should take ft or m for elev. - visibility = stationweather.get_visibility_m(); - // Technically we can do VFR down to 1 mile (1600m) but that's pretty murky! - //cout << "vis = " << visibility << '\n'; - if(visibility < 3000) return; - - ATC->AIRegisterAirport(ident); - - // Next - get the distance from user to the airport. - SGGeod userpos = SGGeod::fromDegM(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue()); - double d = dclGetHorizontalSeparation(userpos, aptpos); // in meters - - int lev = fgGetInt("/sim/ai-traffic/level"); - if(lev < 1) - return; - if (lev > 3) - lev = 3; - if(visibility < 6000) lev = 1; - //cout << "level = " << lev << '\n'; - - // Next - generate any local / circuit traffic - - /* - // --------------------------- THIS BLOCK IS JUST FOR TESTING - COMMENT OUT BEFORE RELEASE --------------- - // Finally - generate VFR approaching traffic - //if(d > 2000) { - if(ident == "KPOC") { - double ad = 2000.0; - double avd = 3000.0; // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day! - //while(ad < (d < 10000 ? 12000 : d + 2000)) { - for(int i=0; i<8; ++i) { - double dd = sg_random() * avd; - // put a minimum spacing in for now since I don't think tower will cope otherwise! - if(dd < 1500) dd = 1500; - //ad += dd; - ad += dd; - double dir = int(sg_random() * 36); - if(dir == 36) dir--; - dir *= 10; - //dir = 180; - if(sg_random() < 0.3) cessna = false; - else cessna = true; - string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-")); - FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic(); - t->SetModel(cessna ? _defaultModel : _piperModel); - //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n"; - SGGeod tpos = dclUpdatePosition(aptpos, dir, 6.0, ad); - if(tpos.getElevationM() > (aptpos.getElevationM() + 3000.0)) tpos.setElevationM(aptpos.getElevationM() + 3000.0); - t->Init(tpos, ident, s); - ai_list.push_back(t); - } - } - activated[ident] = 1; - return; - //--------------------------------------------------------------------------------------------------- - */ - - double ad; // Minimum distance out of first arriving plane in meters. - double mind; // Minimum spacing of traffic in meters - double avd; // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day! - // Finally - generate VFR approaching traffic - //if(d > 2000) { - if(1) { - if(lev == 3) { - ad = 5000.0; - mind = 2000.0; - avd = 6000.0; - } else if(lev == 2) { - ad = 8000.0; - mind = 4000.0; - avd = 10000.0; - } else { - ad = 9000.0; // Start the first aircraft at least 9K out for now. - mind = 6000.0; - avd = 15000.0; - } - /* - // Check if there is already arriving traffic at this airport - cout << "BING A " << ident << '\n'; - if(traffic.find(ident) != traffic.end()) { - cout << "BING B " << ident << '\n'; - ai_list_type lst = traffic[ident]; - cout << "BING C " << ident << '\n'; - if(lst.size()) { - cout << "BING D " << ident << '\n'; - double cd = dclGetHorizontalSeparation(aptpos, (*lst.rbegin())->GetPos()); - cout << "ident = " << ident << ", cd = " << cd << '\n'; - if(cd > ad) ad = cd; - } - } - */ - if(min_dist != 0) ad = min_dist; - //cout << "ident = " << ident << ", ad = " << ad << '\n'; - while(ad < (d < 5000 ? 15000 : d + 10000)) { - double dd = mind + (sg_random() * (avd - mind)); - ad += dd; - double dir = int(sg_random() * 36); - if(dir == 36) dir--; - dir *= 10; - - if(sg_random() < 0.3) cessna = false; - else cessna = true; - string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-")); - FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic(); - t->SetModel(cessna ? _defaultModel.get() : (_havePiperModel ? _piperModel.get() : _defaultModel.get())); - //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n"; - SGGeod tpos = dclUpdatePosition(aptpos, dir, 6.0, ad); - if(tpos.getElevationM() > (aptpos.getElevationM() + 3000.0)) tpos.setElevationM(aptpos.getElevationM() + 3000.0); // FEET yuk :-( - t->Init(tpos, ident, s); - ai_list.push_back(t); - traffic[ident].push_back(t); - } - } -} - -/* -// Generate a VFR arrival at airport apt, at least distance d (meters) out. -void FGAIMgr::GenerateVFRArrival(const string& apt, double d) { -} -*/ - -// Search for valid airports in the vicinity of the user and activate them if necessary -void FGAIMgr::SearchByPos(double range) { - //cout << "In SearchByPos(...)" << endl; - - // get bucket number for plane position - _userAircraftPos = SGGeod::fromDegFt(lon_node->getDoubleValue(), - lat_node->getDoubleValue(), elev_node->getDoubleValue()); - SGBucket buck(_userAircraftPos); - - // get neigboring buckets - int bx = (int)( range*SG_NM_TO_METER / buck.get_width_m() / 2); - //cout << "bx = " << bx << endl; - int by = (int)( range*SG_NM_TO_METER / buck.get_height_m() / 2 ); - //cout << "by = " << by << endl; - - // Search for airports with facitities files -------------------------- - // loop over bucket range - for ( int i=-bx; i<=bx; i++) { - //cout << "i loop\n"; - for ( int j=-by; j<=by; j++) { - //cout << "j loop\n"; - buck = sgBucketOffset(_userAircraftPos.getLongitudeDeg(), _userAircraftPos.getLatitudeDeg(), i, j); - long int bucket = buck.gen_index(); - //cout << "bucket is " << bucket << endl; - if(facilities.find(bucket) != facilities.end()) { - ID_list_type* apts = facilities[bucket]; - ID_list_iterator current = apts->begin(); - ID_list_iterator last = apts->end(); - - //cout << "Size of apts is " << apts->size() << endl; - - //double rlon = lon * SGD_DEGREES_TO_RADIANS; - //double rlat = lat * SGD_DEGREES_TO_RADIANS; - for(; current != last; ++current) { - //cout << "Found " << *current << endl;; - if(activated.find(*current) == activated.end()) { - //cout << "Activating " << *current << endl; - //FGAirport a; - //if(dclFindAirportID(*current, &a)) { - // // We can do something here based on distance from the user if we wish. - //} - //string s = *current; - //cout << "s = " << s << '\n'; - ActivateAirport(*current); - //ActivateSimpleAirport(*current); // TODO - put this back to ActivateAirport when that code is done. - //cout << "Activation done" << endl; - } else { - //cout << *current << " already activated" << endl; - } - } - } - } - } - //------------------------------------------------------------- - - // Search for any towered airports in the vicinity ------------ - comm_list_type towered; - comm_list_iterator twd_itr; - - int num_twd = current_commlist->FindByPos(_userAircraftPos, range, &towered, TOWER); - if (num_twd != 0) { - double closest = 1000000; - string s = ""; - for(twd_itr = towered.begin(); twd_itr != towered.end(); twd_itr++) { - // Only activate the closest airport not already activated each time. - if(activated.find(twd_itr->ident) == activated.end()) { - double sep = dclGetHorizontalSeparation(_userAircraftPos, fgGetAirportPos(twd_itr->ident)); - if(sep < closest) { - closest = sep; - s = twd_itr->ident; - } - - } - } - if(s.size()) { - // TODO - find out why empty strings come through here when all in-range airports done. - GenerateSimpleAirportTraffic(s); - //cout << "**************ACTIVATING SIMPLE AIRPORT, ident = " << s << '\n'; - activated[s] = 1; - } - } -} - -string FGAIMgr::GenerateCallsign() { - // For now we'll just generate US callsigns until we can regionally identify airports. - string s = "N"; - // Add 3 to 5 numbers and make up to 5 with letters. - //sg_srandom_time(); - double d = sg_random(); - int n = int(d * 3); - if(n == 3) --n; - //cout << "First n, n = " << n << '\n'; - int j = 3 + n; - //cout << "j = " << j << '\n'; - for(int i=0; i0; --i) { - char c = callsign[callsign.size() - i]; - //cout << c << '\n'; - string tmp = ""; - tmp += c; - if(isalpha(c)) s += GetPhoneticLetter(c); - else s += ConvertNumToSpokenDigits(tmp); - if(i > 1) s += '-'; - } - return(s); -} diff --git a/src/ATCDCL/AIMgr.hxx b/src/ATCDCL/AIMgr.hxx deleted file mode 100644 index 8d87c5c98..000000000 --- a/src/ATCDCL/AIMgr.hxx +++ /dev/null @@ -1,136 +0,0 @@ -// AIMgr.hxx - definition of FGAIMgr -// - a global management class for FlightGear generated AI traffic -// -// Written by David Luff, started March 2002. -// -// Copyright (C) 2002 David C Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifndef _FG_AIMGR_HXX -#define _FG_AIMGR_HXX - -#include - -#include
- -#include - -#include "ATCmgr.hxx" -#include "AIEntity.hxx" - -using std::list; - - -class FGAIMgr : public SGSubsystem -{ - -private: - FGATCMgr* ATC; - // This is purely for synactic convienience to avoid writing globals->get_ATC_mgr()-> all through the code! - - // A list of pointers to all currently active AI stuff - typedef list ai_list_type; - typedef ai_list_type::iterator ai_list_iterator; - typedef ai_list_type::const_iterator ai_list_const_iterator; - - // Everything put in this list should be created dynamically - // on the heap and ***DELETED WHEN REMOVED!!!!!*** - ai_list_type ai_list; - ai_list_iterator ai_list_itr; - // Any member function of FGATCMgr is permitted to leave this iterator pointing - // at any point in or at the end of the list. - // Hence any new access must explicitly first check for atc_list.end() before dereferencing. - - // A list of airport or airplane ID's - typedef list < string > ID_list_type; - typedef ID_list_type::iterator ID_list_iterator; - - // Temporary storage of ID of planes scheduled for removeal - ID_list_type removalList; - - // A map of airport-IDs that have taxiway network files against bucket number - typedef map < int, ID_list_type* > ai_apt_map_type; - typedef ai_apt_map_type::iterator ai_apt_map_iterator; - ai_apt_map_type facilities; - - // A map of airport ID's that we've activated AI traffic at - typedef map < string, int > ai_activated_map_type; - typedef ai_activated_map_type::iterator ai_activated_map_iterator; - ai_activated_map_type activated; - - // AI traffic lists mapped by airport - typedef map < string, ai_list_type > ai_traffic_map_type; - typedef ai_traffic_map_type::iterator ai_traffic_map_iterator; - ai_traffic_map_type traffic; - - // A map of callsigns that we have used (eg CFGFS or N0546D - the code will generate Cessna-four-six-delta from this later) - typedef map < string, int > ai_callsigns_map_type; - typedef ai_callsigns_map_type::iterator ai_callsigns_map_iterator; - ai_callsigns_map_type ai_callsigns_used; - - SGGeod _userAircraftPos; - - // Pointers to current users position - SGPropertyNode_ptr lon_node; - SGPropertyNode_ptr lat_node; - SGPropertyNode_ptr elev_node; -public: - - FGAIMgr(); - ~FGAIMgr(); - - void init(); - - void bind(); - - void unbind(); - - void update(double dt); - - // Signal that it is OK to remove a plane of callsign s - // (To be called by the plane itself). - void ScheduleRemoval(const string& s); - -private: - - osg::ref_ptr _defaultModel; // Cessna 172! - osg::ref_ptr _piperModel; // pa28-161 - - bool initDone; // Hack - guard against update getting called before init - - // Remove a class from the ai_list and delete it from memory - //void RemoveFromList(const char* id, atc_type tp); - - // Activate AI traffic at an airport - void ActivateAirport(const string& ident); - - // Hack - Generate AI traffic at an airport with no facilities file, with the first plane being at least min_dist out. - void GenerateSimpleAirportTraffic(const string& ident, double min_dist = 0.0); - - // Search for valid airports in the vicinity of the user and activate them if necessary - void SearchByPos(double range); - - string GenerateCallsign(); - - string GenerateUniqueCallsign(); - - string GenerateShortForm(const string& callsign, const string& plane_str = "Cessna-", bool local = false); - - // TODO - implement a proper robust system for registering and loading AI GA aircraft models - bool _havePiperModel; -}; - -#endif // _FG_AIMGR_HXX diff --git a/src/ATCDCL/AIPlane.cxx b/src/ATCDCL/AIPlane.cxx deleted file mode 100644 index 8fd67d13a..000000000 --- a/src/ATCDCL/AIPlane.cxx +++ /dev/null @@ -1,275 +0,0 @@ -// FGAIPlane - abstract base class for an AI plane -// -// Written by David Luff, started 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#include
-#include
-#include -#include -#include -#include -using std::string; - - -#include "AIPlane.hxx" - -FGAIPlane::FGAIPlane() { - leg = LEG_UNKNOWN; - tuned_station = NULL; - pending_transmission = ""; - _timeout = 0; - _pending = false; - _callback_code = 0; - _transmit = false; - _transmitting = false; - voice = false; - playing = false; - voiceOK = false; - vPtr = NULL; - track = 0.0; - _tgtTrack = 0.0; - _trackSet = false; - _tgtRoll = 0.0; - _rollSuspended = false; - - if ( !_sgr ) { - SGSoundMgr *smgr = globals->get_soundmgr(); - _sgr = smgr->find("atc", true); - _sgr->tie_to_listener(); - } -} - -FGAIPlane::~FGAIPlane() { -} - -void FGAIPlane::Update(double dt) { - if(_pending) { - if(tuned_station) { - if(tuned_station->GetFreqClear()) { - //cout << "TUNED STATION FREQ CLEAR\n"; - tuned_station->SetFreqInUse(); - _pending = false; - _transmit = true; - _transmitting = false; - } else { - if(_timeout > 0.0) { // allows count down to be avoided by initially setting it to zero - _timeout -= dt; - if(_timeout <= 0.0) { - _timeout = 0.0; - _pending = false; - // timed out - don't render. - if(_callback_code == 99) { - // MEGA-HACK - 99 is the remove self callback - currently this *does* need to be run even if the transmission isn't made. - ProcessCallback(_callback_code); - } - } - } - } - } else { - // Not tuned to ATC - Just go ahead and transmit - //cout << "NOT TUNED TO ATC\n"; - _pending = false; - _transmit = true; - _transmitting = false; - } - } - - // This turns on rendering if on the same freq as the user - // TODO - turn it off if user switches to another freq - keep track of where in message we are etc. - if(_transmit) { - //cout << "transmit\n"; - double user_freq0 = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz"); - double user_freq1 = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz"); - _counter = 0.0; - _max_count = 5.0; // FIXME - hardwired length of message - need to calculate it! - - //cout << "Transmission = " << pending_transmission << '\n'; - - // The radios dialog seems to set slightly imprecise freqs, eg 118.099998 - // The eplison stuff below is a work-around - double eps0 = fabs(freq - user_freq0); - double eps1 = fabs(freq - user_freq1); - if(eps0 < 0.002 || eps1 < 0.002) { - //cout << "Transmitting..." << endl; - // we are on the same frequency, so check distance to the user plane - if(1) { - // For now assume in range !!! - // TODO - implement range checking - // TODO - at the moment the volume is always set off comm1 - float volume = fgGetFloat("/instrumentation/comm[0]/volume"); - Render(plane.callsign, volume, false); - } - } - // Run the callback regardless of whether on same freq as user or not. - if(_callback_code) { - ProcessCallback(_callback_code); - } - _transmit = false; - _transmitting = true; - } else if(_transmitting) { - if(_counter >= _max_count) { - NoRender(plane.callsign); - _transmitting = false; - // For now we'll let ATC decide whether to respond - //if(tuned_station) tuned_station->SetResponseReqd(plane.callsign); - //if(tuned_station->get_ident() == "KRHV") cout << "Notifying transmission finished" << endl; - if(tuned_station) tuned_station->NotifyTransmissionFinished(plane.callsign); - } - _counter += dt; - } - - // Fly the plane if necessary - if(_trackSet) { - while((_tgtTrack - track) > 180.0) track += 360.0; - while((track - _tgtTrack) > 180.0) track -= 360.0; - double turn_time = 60.0; - track += (360.0 / turn_time) * dt * (_tgtTrack > track ? 1.0 : -1.0); - // TODO - bank a bit less for small turns. - Bank(25.0 * (_tgtTrack > track ? 1.0 : -1.0)); - if(fabs(track - _tgtTrack) < 2.0) { // TODO - might need to optimise the delta there - it's on the large (safe) side atm. - track = _tgtTrack; - LevelWings(); - } - } - - if(!_rollSuspended) { - if(fabs(_roll - _tgtRoll) > 0.6) { - // This *should* bank us smoothly to any angle - _roll -= ((_roll - _tgtRoll)/fabs(_roll - _tgtRoll)); - } else { - _roll = _tgtRoll; - } - } -} - -void FGAIPlane::Transmit(int callback_code) { - SG_LOG(SG_ATC, SG_INFO, "Transmit called for plane " << plane.callsign << ", msg = " << pending_transmission); - _pending = true; - _callback_code = callback_code; - _timeout = 0.0; -} - -void FGAIPlane::ConditionalTransmit(double timeout, int callback_code) { - SG_LOG(SG_ATC, SG_INFO, "Timed transmit called for plane " << plane.callsign << ", msg = " << pending_transmission); - _pending = true; - _callback_code = callback_code; - _timeout = timeout; -} - -void FGAIPlane::ImmediateTransmit(int callback_code) { - // TODO - at the moment the volume is always set off comm1 - float volume = fgGetFloat("/instrumentation/comm[0]/volume"); - - Render(plane.callsign, volume, false); - if(callback_code) { - ProcessCallback(callback_code); - } -} - -// Derived classes should override this. -void FGAIPlane::ProcessCallback(int code) { -} - -// Render a transmission -// Outputs the transmission either on screen or as audio depending on user preference -// The refname is a string to identify this sample to the sound manager -// The repeating flag indicates whether the message should be repeated continuously or played once. -void FGAIPlane::Render(const string& refname, const float volume, bool repeating) { - fgSetString("/sim/messages/ai-plane", pending_transmission.c_str()); -#ifdef ENABLE_AUDIO_SUPPORT - voice = (voiceOK && fgGetBool("/sim/sound/voice")); - if(voice) { - size_t len; - void* buf = vPtr->WriteMessage(pending_transmission, &len); - if(voice && (volume > 0.05)) { - SGSoundSample* simple = new SGSoundSample(&buf, len, 8000 ); - simple->set_volume(volume); - _sgr->add(simple, refname); - _sgr->play(refname, repeating); - } - } -#endif // ENABLE_AUDIO_SUPPORT - if(!voice) { - // first rip the underscores and the pause hints out of the string - these are for the convienience of the voice parser - for(unsigned int i = 0; i < pending_transmission.length(); ++i) { - if((pending_transmission.substr(i,1) == "_") || (pending_transmission.substr(i,1) == "/")) { - pending_transmission[i] = ' '; - } - } - } - playing = true; -} - - -// Cease rendering a transmission. -void FGAIPlane::NoRender(const string& refname) { - if(playing) { - if(voice) { -#ifdef ENABLE_AUDIO_SUPPORT - _sgr->stop(refname); - _sgr->remove(refname); -#endif - } - playing = false; - } -} - -/* - -*/ - -void FGAIPlane::RegisterTransmission(int code) { -} - - -// Return what type of landing we're doing on this circuit -LandingType FGAIPlane::GetLandingOption() { - return(FULL_STOP); -} - - -ostream& operator << (ostream& os, PatternLeg pl) { - switch(pl) { - case(TAKEOFF_ROLL): return(os << "TAKEOFF ROLL"); - case(CLIMBOUT): return(os << "CLIMBOUT"); - case(TURN1): return(os << "TURN1"); - case(CROSSWIND): return(os << "CROSSWIND"); - case(TURN2): return(os << "TURN2"); - case(DOWNWIND): return(os << "DOWNWIND"); - case(TURN3): return(os << "TURN3"); - case(BASE): return(os << "BASE"); - case(TURN4): return(os << "TURN4"); - case(FINAL): return(os << "FINAL"); - case(LANDING_ROLL): return(os << "LANDING ROLL"); - case(LEG_UNKNOWN): return(os << "UNKNOWN"); - } - return(os << "ERROR - Unknown switch in PatternLeg operator << "); -} - - -ostream& operator << (ostream& os, LandingType lt) { - switch(lt) { - case(FULL_STOP): return(os << "FULL STOP"); - case(STOP_AND_GO): return(os << "STOP AND GO"); - case(TOUCH_AND_GO): return(os << "TOUCH AND GO"); - case(AIP_LT_UNKNOWN): return(os << "UNKNOWN"); - } - return(os << "ERROR - Unknown switch in LandingType operator << "); -} - diff --git a/src/ATCDCL/AIPlane.hxx b/src/ATCDCL/AIPlane.hxx deleted file mode 100644 index 53158f929..000000000 --- a/src/ATCDCL/AIPlane.hxx +++ /dev/null @@ -1,167 +0,0 @@ -// FGAIPlane - abstract base class for an AI plane -// -// Written by David Luff, started 2002. -// -// Copyright (C) 2002 David C. Luff - david.luff@nottingham.ac.uk -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -#ifndef _FG_AI_PLANE_HXX -#define _FG_AI_PLANE_HXX - -#include "AIEntity.hxx" -#include "ATC.hxx" - -class SGSampleGroup; - -enum PatternLeg { - TAKEOFF_ROLL, - CLIMBOUT, - TURN1, - CROSSWIND, - TURN2, - DOWNWIND, - TURN3, - BASE, - TURN4, - FINAL, - LANDING_ROLL, - LEG_UNKNOWN -}; - -ostream& operator << (ostream& os, PatternLeg pl); - -enum LandingType { - FULL_STOP, - STOP_AND_GO, - TOUCH_AND_GO, - AIP_LT_UNKNOWN -}; - -ostream& operator << (ostream& os, LandingType lt); - -/***************************************************************** -* -* FGAIPlane - this class is derived from FGAIEntity and adds the -* practical requirement for an AI plane - the ability to send radio -* communication, and simple performance details for the actual AI -* implementation to use. The AI implementation is expected to be -* in derived classes - this class does nothing useful on its own. -* -******************************************************************/ -class FGAIPlane : public FGAIEntity { - -public: - - FGAIPlane(); - virtual ~FGAIPlane(); - - // Run the internal calculations - void Update(double dt); - - // Send a transmission *TO* the AIPlane. - // FIXME int code is a hack - eventually this will receive Alexander's coded messages. - virtual void RegisterTransmission(int code); - - // Return the current pattern leg the plane is flying. - inline PatternLeg GetLeg() {return leg;} - - // Return what type of landing we're doing on this circuit - virtual LandingType GetLandingOption(); - - // Return the callsign - inline const string& GetCallsign() {return plane.callsign;} - -protected: - PlaneRec plane; - - double mag_hdg; // degrees - the heading that the physical aircraft is *pointing* - double track; // track that the physical aircraft is *following* - degrees relative to *true* north - double crab; // Difference between heading and track due to wind. - double mag_var; // degrees - double IAS; // Indicated airspeed in knots - double vel; // velocity along track in knots - double vel_si; // velocity along track in m/s - double slope; // Actual slope that the plane is flying (degrees) - +ve is uphill - double AoA; // degrees - difference between slope and pitch - // We'll assume that the plane doesn't yaw or slip - the track/heading difference is to allow for wind - - double freq; // The comm frequency that we're operating on - - // We need some way for this class to display its radio transmissions if on the - // same frequency and in the vicinity of the user's aircraft - // This may need to be done independently of ATC eg CTAF - // Make radio transmission - this simply sends the transmission for physical rendering if the users - // aircraft is on the same frequency and in range. It is up to the derived classes to let ATC know - // what is going on. - string pending_transmission; // derived classes set this string before calling Transmit(...) - FGATC* tuned_station; // and this if they are tuned to ATC - - // Transmit a message when channel becomes free of other dialog - void Transmit(int callback_code = 0); - - // Transmit a message if channel becomes free within timeout (seconds). timeout of zero implies no limit - void ConditionalTransmit(double timeout, int callback_code = 0); - - // Transmit regardless of other dialog on the channel eg emergency - void ImmediateTransmit(int callback_code = 0); - - inline void SetTrack(double t) { _tgtTrack = t; _trackSet = true; } - inline void ClearTrack() { _trackSet = false; } - - inline void Bank(double r) { _tgtRoll = r; } - inline void LevelWings(void) { _tgtRoll = 0.0; } - - virtual void ProcessCallback(int code); - - PatternLeg leg; - -private: - bool _pending; - double _timeout; - int _callback_code; // A callback code to be notified and processed by the derived classes - // A value of zero indicates no callback required - bool _transmit; // we are to transmit - bool _transmitting; // we are transmitting - double _counter; - double _max_count; - - // Render a transmission (in string pending_transmission) - // Outputs the transmission either on screen or as audio depending on user preference - // The refname is a string to identify this sample to the sound manager - // The repeating flag indicates whether the message should be repeated continuously or played once. - void Render(const string& refname, const float volume, bool repeating); - - // Cease rendering a transmission. - // Requires the sound manager refname if audio, else "". - void NoRender(const string& refname); - - // Rendering related stuff - bool voice; // Flag - true if we are using voice - bool playing; // Indicates a message in progress - bool voiceOK; // Flag - true if at least one voice has loaded OK - FGATCVoice* vPtr; - - // Navigation - double _tgtTrack; // Track to be following if _trackSet is true - bool _trackSet; // Set true if tgtTrack is to be followed - double _tgtRoll; - bool _rollSuspended; // Set true when a derived class has suspended AIPlane's roll control - - SGSharedPtr _sgr; -}; - -#endif // _FG_AI_PLANE_HXX - diff --git a/src/ATCDCL/ATC.hxx b/src/ATCDCL/ATC.hxx index e2751460e..e5ddcd0a9 100644 --- a/src/ATCDCL/ATC.hxx +++ b/src/ATCDCL/ATC.hxx @@ -65,6 +65,8 @@ enum plane_type { // PlaneRec - a structure holding ATC-centric details of planes under control // This might move or change eventually struct PlaneRec { + PlaneRec() : type(UNKNOWN), squawkcode(0) {} + PlaneRec(const std::string& s) : type(UNKNOWN), callsign(s), squawkcode(0) {} plane_type type; std::string callsign; int squawkcode; @@ -87,6 +89,7 @@ const int ATC_NUM_TYPES = 1 + INVALID; // DCL - new experimental ATC data store struct ATCData { + ATCData() : type(INVALID), cart(0, 0, 0), freq(0), range(0) {} atc_type type; SGGeod geod; SGVec3d cart; @@ -99,6 +102,7 @@ struct ATCData { // perhaps we could use an FGRunway instead of this. // That wouldn't cache the orthopos though. struct RunwayDetails { + RunwayDetails() : end1ortho(0, 0, 0), end2ortho(0, 0, 0), hdg(0), length(-1), width(-1) {} SGGeod threshold_pos; SGVec3d end1ortho; // ortho projection end1 (the threshold ATM) SGVec3d end2ortho; // ortho projection end2 (the take off end in the current hardwired scheme) diff --git a/src/ATCDCL/ATCmgr.cxx b/src/ATCDCL/ATCmgr.cxx index 19053adef..fe0375015 100644 --- a/src/ATCDCL/ATCmgr.cxx +++ b/src/ATCDCL/ATCmgr.cxx @@ -178,45 +178,6 @@ unsigned short int FGATCMgr::GetFrequency(const string& ident, const atc_type& t return(ok ? test.freq : 0); } - -// Register the fact that the AI system wants to activate an airport -// Might need more sophistication in this in the future - eg registration by aircraft call-sign. -bool FGATCMgr::AIRegisterAirport(const string& ident) { - SG_LOG(SG_ATC, SG_BULK, "AI registered airport " << ident << " with the ATC system"); - //cout << "AI registered airport " << ident << " with the ATC system" << '\n'; - if(airport_atc_map.find(ident) != airport_atc_map.end()) { - airport_atc_map[ident]->set_by_AI = true; - airport_atc_map[ident]->numAI++; - return(true); - } else { - const FGAirport *ap = fgFindAirportID(ident); - if (ap) { - //cout << "ident = " << ident << '\n'; - AirportATC *a = new AirportATC; - // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway! - a->geod = ap->geod(); - a->atis_freq = GetFrequency(ident, ATIS) - || GetFrequency(ident, AWOS); - //cout << "ATIS freq = " << a->atis_freq << '\n'; - a->atis_active = false; - a->tower_freq = GetFrequency(ident, TOWER); - //cout << "Tower freq = " << a->tower_freq << '\n'; - a->tower_active = false; - a->ground_freq = GetFrequency(ident, GROUND); - //cout << "Ground freq = " << a->ground_freq << '\n'; - a->ground_active = false; - // TODO - some airports will have a tower/ground frequency but be inactive overnight. - a->set_by_AI = true; - a->numAI = 1; - airport_atc_map[ident] = a; - return(true); - } else { - SG_LOG(SG_ATC, SG_ALERT, "ERROR - can't find airport " << ident << " in AIRegisterAirport(...)"); - } - } - return(false); -} - // Register the fact that the comm radio is tuned to an airport // Channel is zero based bool FGATCMgr::CommRegisterAirport(const string& ident, int chan, const atc_type& tp) { @@ -273,8 +234,7 @@ typedef map MSI; void FGATCMgr::ZapOtherService(const string ncunit, const string svc_name){ for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) { - //cout << "Zapping " << navcomm - // << "[" << unit << "]" << " otherthan: " << svc_name << endl; + if (svc->first != svc_name) { MSI &actv = svc->second->active_on; // OK, we have found some OTHER service; @@ -286,7 +246,9 @@ void FGATCMgr::ZapOtherService(const string ncunit, const string svc_name){ //cout << "Eradicating service: '" << svc->first << "'" << endl; svc->second->SetNoDisplay(); svc->second->Update(0); // one last update - delete svc->second; + SG_LOG(SG_GENERAL, SG_INFO, "would have erased ATC service:" << svc->second->get_name()<< "/" + << svc->second->get_ident()); + // delete svc->second; atc_list->erase(svc); // ALL pointers into the ATC list are now invalid, // so let's reset them: diff --git a/src/ATCDCL/ATCmgr.hxx b/src/ATCDCL/ATCmgr.hxx index 13349490d..c21d0c5f3 100644 --- a/src/ATCDCL/ATCmgr.hxx +++ b/src/ATCDCL/ATCmgr.hxx @@ -156,9 +156,6 @@ public: // Returns zero if not found unsigned short int GetFrequency(const string& ident, const atc_type& tp); - // Register the fact that the AI system wants to activate an airport - bool AIRegisterAirport(const string& ident); - // Register the fact that the comm radio is tuned to an airport bool CommRegisterAirport(const string& ident, int chan, const atc_type& tp); diff --git a/src/ATCDCL/Makefile.am b/src/ATCDCL/Makefile.am index a7c199283..eecca04f2 100644 --- a/src/ATCDCL/Makefile.am +++ b/src/ATCDCL/Makefile.am @@ -12,11 +12,6 @@ libATCDCL_a_SOURCES = \ ATCmgr.hxx ATCmgr.cxx \ ATCutils.hxx ATCutils.cxx \ ATCProjection.hxx ATCProjection.cxx \ - AIMgr.hxx AIMgr.cxx \ - AIEntity.hxx AIEntity.cxx \ - AIPlane.hxx AIPlane.cxx \ - AILocalTraffic.hxx AILocalTraffic.cxx \ - AIGAVFRTraffic.hxx AIGAVFRTraffic.cxx \ transmission.hxx transmission.cxx \ transmissionlist.hxx transmissionlist.cxx diff --git a/src/ATCDCL/atis.cxx b/src/ATCDCL/atis.cxx index 67c108f4b..0747903de 100644 --- a/src/ATCDCL/atis.cxx +++ b/src/ATCDCL/atis.cxx @@ -63,10 +63,9 @@ using boost::ref; using boost::tie; FGATIS::FGATIS() : - transmission(""), - trans_ident(""), old_volume(0), atis_failed(false), + msg_OK(0), attention(0), _prev_display(0), refname("atis") diff --git a/src/ATCDCL/ground.cxx b/src/ATCDCL/ground.cxx index 08a320613..f345852b0 100644 --- a/src/ATCDCL/ground.cxx +++ b/src/ATCDCL/ground.cxx @@ -36,7 +36,6 @@ #include "ground.hxx" #include "ATCutils.hxx" -#include "AILocalTraffic.hxx" #include "ATCmgr.hxx" using std::ifstream; @@ -290,64 +289,6 @@ void FGGround::Init() { } void FGGround::Update(double dt) { - // Each time step, what do we need to do? - // We need to go through the list of outstanding requests and acknowedgements - // and process at least one of them. - // We need to go through the list of planes under our control and check if - // any need to be addressed. - // We need to check for planes not under our control coming within our - // control area and address if necessary. - - // Lets take the example of a plane which has just contacted ground - // following landing - presumably requesting where to go? - // First we need to establish the position of the plane within the logical network. - // Next we need to decide where its going. - - if(ground_traffic.size()) { - if(ground_traffic_itr == ground_traffic.end()) { - ground_traffic_itr = ground_traffic.begin(); - } - - //Process(*ground_traffic_itr); - GroundRec* g = *ground_traffic_itr; - if(g->taxiRequestOutstanding) { - double responseTime = 10.0; // seconds - this should get more sophisticated at some point - if(g->clearanceCounter > responseTime) { - // DO CLEARANCE - // TODO - move the mechanics of making up the transmission out of the main Update(...) routine. - string trns = ""; - trns += g->plane.callsign; - trns += " taxi holding point runway "; // TODO - add the holding point name - // eg " taxi holding point G2 runway " - trns += ConvertRwyNumToSpokenString(activeRwy); - if(_display) { - fgSetString("/sim/messages/ground", trns.c_str()); - } - g->planePtr->RegisterTransmission(1); // cleared to taxi - g->clearanceCounter = 0.0; - g->taxiRequestOutstanding = false; - } else { - g->clearanceCounter += (dt * ground_traffic.size()); - } - } else if(((FGAILocalTraffic*)(g->planePtr))->AtHoldShort()) { // That's a hack - eventually we should monitor actual position - // HACK ALERT - the automatic cast to AILocalTraffic has to go once we have other sorts working!!!!! FIXME TODO - // NOTE - we don't need to do the contact tower bit unless we have separate tower and ground - string trns = g->plane.callsign; - trns += " contact Tower "; - double f = globals->get_ATC_mgr()->GetFrequency(ident, TOWER) / 100.0; - char buf[10]; - sprintf(buf, "%.2f", f); - trns += buf; - if(_display) { - fgSetString("/sim/messages/ground", trns.c_str()); - } - g->planePtr->RegisterTransmission(2); // contact tower - delete *ground_traffic_itr; - ground_traffic.erase(ground_traffic_itr); - ground_traffic_itr = ground_traffic.begin(); - } - ++ground_traffic_itr; - } // Call the base class update for the response time handling. FGATC::Update(dt); @@ -362,7 +303,11 @@ void FGGround::DoRwyDetails() { //cout << "GetRwyDetails called" << endl; const FGAirport* apt = fgFindAirportID(ident); - assert(apt); + if (!apt) { + SG_LOG(SG_ATC, SG_WARN, "FGGround::DoRwyDetails: unknown ICAO:" << ident); + return; + } + FGRunway* runway = apt->getActiveRunwayForUsage(); activeRwy = runway->ident(); @@ -653,68 +598,3 @@ node_array_type FGGround::GetExits(const string& rwyID) { // FIXME - get a 07L or similar in here and we're stuffed!!! return(runways[atoi(rwyID.c_str())].exits); } - -void FGGround::RequestDeparture(const PlaneRec& plane, FGAIEntity* requestee) { - // For now we'll just automatically clear all planes to the runway hold. - // This communication needs to be delayed 20 sec or so from receiving the request. - // Even if display=false we still need to start the timer in case display=true when communication starts. - // We also need to bear in mind we also might have other outstanding communications, although for now we'll punt that issue! - // FIXME - sort the above! - - // HACK - assume that anything requesting departure is new for now - FIXME LATER - GroundRec* g = new GroundRec; - g->plane = plane; - g->planePtr = requestee; - g->taxiRequestOutstanding = true; - g->clearanceCounter = 0; - g->cleared = false; - g->incoming = false; - // TODO - need to handle the next 3 as well - //node* destination; - //node* last_clearance; - - ground_traffic.push_back(g); -} - -#if 0 -void FGGround::NewArrival(plane_rec plane) { - // What are we going to do here? - // We need to start a new ground_rec and add the plane_rec to it - // We need to decide what gate we are going to clear it to. - // Then we need to add clearing it to that gate to the pending transmissions queue? - or simply transmit? - // Probably simply transmit for now and think about a transmission queue later if we need one. - // We might need one though in order to add a little delay for response time. - ground_rec* g = new ground_rec; - g->plane_rec = plane; - g->current_pos = ConvertWGS84ToXY(plane.pos); - g->node = GetNode(g->current_pos); // TODO - might need to sort out node/arc here - AssignGate(g); - g->cleared = false; - ground_traffic.push_back(g); - NextClearance(g); -} - -void FGGround::NewContact(plane_rec plane) { - // This is a bit of a convienience function at the moment and is likely to change. - if(at a gate or apron) - NewDeparture(plane); - else - NewArrival(plane); -} - -void FGGround::NextClearance(ground_rec &g) { - // Need to work out where we can clear g to. - // Assume the pilot doesn't need progressive instructions - // We *should* already have a gate or holding point assigned by the time we get here - // but it wouldn't do any harm to check. - - // For now though we will hardwire it to clear to the final destination. -} - -void FGGround::AssignGate(ground_rec &g) { - // We'll cheat for now - since we only have the user's aircraft and a couple of airports implemented - // we'll hardwire the gate! - // In the long run the logic of which gate or area to send the plane to could be somewhat non-trivial. -} -#endif //0 - diff --git a/src/ATCDCL/ground.hxx b/src/ATCDCL/ground.hxx index 257ffdad8..345787475 100644 --- a/src/ATCDCL/ground.hxx +++ b/src/ATCDCL/ground.hxx @@ -34,7 +34,6 @@ #include -class FGAIEntity; class FGATCMgr; ////////////////////////////////////////////////////// @@ -176,9 +175,7 @@ typedef shortest_path_map_type::iterator shortest_path_map_iterator; // Planes active within the ground network. // A more specialist plane rec to include ground information -struct GroundRec { - FGAIEntity* planePtr; // This might move to the planeRec eventually - +struct GroundRec { PlaneRec plane; node* destination; node* last_clearance; @@ -211,19 +208,6 @@ public: void Update(double dt); inline const std::string& get_trans_ident() { return trans_ident; } - - // Contact ground control on arrival, assumed to request any gate - //void NewArrival(plane_rec plane); - - // Contact ground control on departure, assumed to request currently active runway. - void RequestDeparture(const PlaneRec& plane, FGAIEntity* requestee); - - // Contact ground control when the calling routine doesn't know if arrival - // or departure is appropriate. - //void NewContact(plane_rec plane); - - // Make a request of ground control. - //void Request(ground_request request); // Randomly fill some of the available gates and GA parking spots with planes void PopulateGates(); diff --git a/src/ATCDCL/tower.cxx b/src/ATCDCL/tower.cxx index fa54b15cf..f765fa4ee 100644 --- a/src/ATCDCL/tower.cxx +++ b/src/ATCDCL/tower.cxx @@ -42,11 +42,11 @@ #include #include "tower.hxx" +#include "ground.hxx" #include "ATCmgr.hxx" #include "ATCutils.hxx" #include "ATCDialog.hxx" #include "commlist.hxx" -#include "AILocalTraffic.hxx" using std::cout; @@ -54,7 +54,6 @@ using std::cout; // TowerPlaneRec TowerPlaneRec::TowerPlaneRec() : - planePtr(NULL), eta(0), dist_out(0), clearedToLand(false), @@ -86,7 +85,6 @@ TowerPlaneRec::TowerPlaneRec() : } TowerPlaneRec::TowerPlaneRec(const PlaneRec& p) : - planePtr(NULL), eta(0), dist_out(0), clearedToLand(false), @@ -118,7 +116,6 @@ TowerPlaneRec::TowerPlaneRec(const PlaneRec& p) : } TowerPlaneRec::TowerPlaneRec(const SGGeod& pt) : - planePtr(NULL), eta(0), dist_out(0), clearedToLand(false), @@ -151,7 +148,6 @@ TowerPlaneRec::TowerPlaneRec(const SGGeod& pt) : } TowerPlaneRec::TowerPlaneRec(const PlaneRec& p, const SGGeod& pt) : - planePtr(NULL), eta(0), dist_out(0), clearedToLand(false), @@ -345,7 +341,6 @@ void FGTower::Init() { t->landingType = AIP_LT_UNKNOWN; t->leg = TAKEOFF_ROLL; t->isUser = true; - t->planePtr = NULL; t->clearedToTakeOff = false; rwyList.push_back(t); rwyListItr = rwyList.begin(); @@ -508,8 +503,6 @@ void FGTower::Respond() { t->opType = STRAIGHT_IN; if(t->isUser) { current_atcdialog->add_entry(ident, "@CS @MI mile final runway @RW@GR", "Report Final", TOWER, (int)USER_REPORT_3_MILE_FINAL); - } else { - t->planePtr->RegisterTransmission(14); } } else { // For now we'll just request reporting downwind. @@ -523,8 +516,6 @@ void FGTower::Respond() { // leave it in the app list until it gets into pattern though. if(t->isUser) { current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND); - } else { - t->planePtr->RegisterTransmission(15); } } trns += ConvertRwyNumToSpokenString(activeRwy); @@ -635,8 +626,6 @@ void FGTower::Respond() { // or put rwy vacated at the top since that'll be more common? current_atcdialog->add_entry(ident, "@CS Going Around", "Report going around", TOWER, USER_REPORT_GOING_AROUND); current_atcdialog->add_entry(ident, "@CS Clear of the runway", "Report runway vacated", TOWER, USER_REPORT_RWY_VACATED); - } else { - t->planePtr->RegisterTransmission(7); } } else if(t->eta < 20) { // Do nothing - we'll be telling it to go around in less than 10 seconds if the @@ -650,8 +639,6 @@ void FGTower::Respond() { t->opType = CIRCUIT; if(t->isUser) { current_atcdialog->add_entry(ident, "@AP Tower, @CS Downwind @RW", "Report Downwind", TOWER, (int)USER_REPORT_DOWNWIND); - } else { - t->planePtr->RegisterTransmission(15); } t->clearedToLand = false; } @@ -705,7 +692,6 @@ void FGTower::ProcessDownwindReport(TowerPlaneRec* t) { if((i == 1) && rwyList.empty() && (t->nextOnRwy) && (!cf)) { // Unfortunately nextOnRwy currently doesn't handle circuit/straight-in ordering properly at present, hence the cf check below. trns += "Cleared to land"; // TODO - clear for the option if appropriate t->clearedToLand = true; - if(!t->isUser) t->planePtr->RegisterTransmission(7); } else if((i+a) > 1) { //First set tt to point to the correct preceding plane - final or circuit if(tc && tf) { @@ -728,8 +714,6 @@ void FGTower::ProcessDownwindReport(TowerPlaneRec* t) { PatternLeg leg; if(tt->isUser) { leg = tt->leg; - } else { - leg = tt->planePtr->GetLeg(); } if(leg == FINAL) { trns += " on final"; @@ -777,11 +761,9 @@ void FGTower::ProcessRunwayVacatedReport(TowerPlaneRec* t) { sprintf(buf, "%.2f", f); trns += buf; trns += " Good Day"; - if(!t->isUser) t->planePtr->RegisterTransmission(5); } else { // Cop-out!! trns += " cleared for taxi to general aviation parking"; - if(!t->isUser) t->planePtr->RegisterTransmission(6); // TODO - this is a mega-hack!! } //cout << "trns = " << trns << '\n'; if(_display) { @@ -806,7 +788,6 @@ void FGTower::ClearHoldingPlane(TowerPlaneRec* t) { //if(timeSinceLastDeparture <= 60.0 && departed == true) { trns += " line up runway " + ConvertRwyNumToSpokenString(activeRwy); t->clearedToLineUp = true; - t->planePtr->RegisterTransmission(3); // cleared to line-up //} else if(arriving plane < some threshold away) { } else if(GetTrafficETA(2) < 150.0 && (timeSinceLastDeparture > 60.0 || departed == false)) { // Hack - hardwired time trns += " cleared immediate take-off"; @@ -884,7 +865,6 @@ void FGTower::ClearHoldingPlane(TowerPlaneRec* t) { SG_LOG(SG_ATC, SG_WARN, "Warning: Departing traffic cleared for *immediate* take-off despite no arriving traffic in FGTower"); } t->clearedToTakeOff = true; - t->planePtr->RegisterTransmission(4); // cleared to take-off - TODO differentiate between immediate and normal take-off departed = false; timeSinceLastDeparture = 0.0; } else { @@ -892,7 +872,6 @@ void FGTower::ClearHoldingPlane(TowerPlaneRec* t) { trns += " cleared for take-off"; // TODO - add traffic is... ? t->clearedToTakeOff = true; - t->planePtr->RegisterTransmission(4); // cleared to take-off departed = false; timeSinceLastDeparture = 0.0; } @@ -968,10 +947,6 @@ void FGTower::CheckCircuitList(double dt) { t->pos.setLatitudeDeg(user_lat_node->getDoubleValue()); t->pos.setElevationM(user_elev_node->getDoubleValue()); //cout << ident << ' ' << circuitList.size() << ' ' << t->plane.callsign << " " << t->leg << " eta " << t->eta << '\n'; - } else { - t->pos = t->planePtr->getPos(); // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this. - t->landingType = t->planePtr->GetLandingOption(); - //cout << "AI plane landing option is " << t->landingType << '\n'; } SGVec3d tortho = ortho.ConvertToLocal(t->pos); if(t->isUser) { @@ -1059,8 +1034,6 @@ void FGTower::CheckCircuitList(double dt) { t->leg = LANDING_ROLL; } } - } else { - t->leg = t->planePtr->GetLeg(); } // Set the constraints IF this is the first plane in the circuit @@ -1151,10 +1124,6 @@ void FGTower::CheckCircuitList(double dt) { // Assume it complies!!! t->opType = CIRCUIT; t->leg = CLIMBOUT; - if(t->planePtr) { - //cout << "Registering Go-around transmission with AI plane\n"; - t->planePtr->RegisterTransmission(13); - } } } else if(!t->clearedToLand) { // The whip through the appList is a hack since currently t->nextOnRwy doesn't always work @@ -1173,9 +1142,6 @@ void FGTower::CheckCircuitList(double dt) { Transmit(); //if(t->isUser) cout << "Transmitting cleared to Land!!!\n"; t->clearedToLand = true; - if(!t->isUser) { - t->planePtr->RegisterTransmission(7); - } } } else { //if(t->isUser) cout << "Not next\n"; @@ -1219,8 +1185,6 @@ void FGTower::CheckRunwayList(double dt) { t->pos.setLongitudeDeg(user_lon_node->getDoubleValue()); t->pos.setLatitudeDeg(user_lat_node->getDoubleValue()); t->pos.setElevationM(user_elev_node->getDoubleValue()); - } else { - t->pos = t->planePtr->getPos(); // We should probably only set the pos's on one walk through the traffic list in the update function, to save a few CPU should we end up duplicating this. } bool on_rwy = OnActiveRunway(t->pos); if(!on_rwy) { @@ -1283,8 +1247,6 @@ void FGTower::CheckApproachList(double dt) { t->pos.setLongitudeDeg(user_lon_node->getDoubleValue()); t->pos.setLatitudeDeg(user_lat_node->getDoubleValue()); t->pos.setElevationM(user_elev_node->getDoubleValue()); - } else { - // TODO - set/update the position if it's an AI plane } doThresholdETACalc(); // We need this here because planes in the lists are not guaranteed to *always* have the correct ETA //cout << "eta is " << t->eta << ", rwy is " << (rwyList.size() ? "occupied " : "clear ") << '\n'; @@ -1313,12 +1275,7 @@ void FGTower::CheckApproachList(double dt) { // Assume it complies!!! t->opType = CIRCUIT; t->leg = CLIMBOUT; - if(!t->isUser) { - if(t->planePtr) { - //cout << "Registering Go-around transmission with AI plane\n"; - t->planePtr->RegisterTransmission(13); - } - } else { + if(t->isUser) { // TODO - add Go-around ack to comm options, // remove report rwy vacated. (possibly). } @@ -1358,9 +1315,6 @@ void FGTower::CheckApproachList(double dt) { Transmit(); //if(t->isUser) cout << "Transmitting cleared to Land!!!\n"; t->clearedToLand = true; - if(!t->isUser) { - t->planePtr->RegisterTransmission(7); - } } } else { //if(t->isUser) cout << "Not next\n"; @@ -1369,15 +1323,7 @@ void FGTower::CheckApproachList(double dt) { // Check for landing... bool landed = false; - if(!t->isUser) { - if(t->planePtr) { - if(t->planePtr->GetLeg() == LANDING_ROLL) { - landed = true; - } - } else { - SG_LOG(SG_ATC, SG_ALERT, "WARNING - not user and null planePtr in CheckApproachList!"); - } - } else { // user + if(t->isUser) { if(OnActiveRunway(t->pos)) { landed = true; } @@ -1417,9 +1363,10 @@ void FGTower::CheckDepartureList(double dt) { //cout << "Dep list, checking " << t->plane.callsign; double distout; // meters - if(t->isUser) distout = dclGetHorizontalSeparation(_geod, - SGGeod::fromDegM(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())); - else distout = dclGetHorizontalSeparation(_geod, t->planePtr->getPos()); + if(t->isUser) { + distout = dclGetHorizontalSeparation(_geod, + SGGeod::fromDegM(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), user_elev_node->getDoubleValue())); + } //cout << " distout = " << distout << '\n'; if(t->isUser && !(t->clearedToTakeOff)) { // HACK - we use clearedToTakeOff to check if ATC already contacted with plane (and cleared take-off) or not if(!OnAnyRunway(SGGeod::fromDegM(user_lon_node->getDoubleValue(), user_lat_node->getDoubleValue(), 0.0), false)) { @@ -1437,9 +1384,6 @@ void FGTower::CheckDepartureList(double dt) { RemoveAllUserDialogOptions(); //cout << "ADD A\n"; current_atcdialog->add_entry(ident, "@AP Tower, @CS @MI miles @CD of the airport for full stop@AT", "Contact tower for VFR arrival (full stop)", TOWER, (int)USER_REQUEST_VFR_ARRIVAL_FULL_STOP); - } else { - // Send a clear-of-airspace signal - // TODO - implement this once we actually have departing AI traffic (currently all circuits or arrivals). } RemovePlane(t->plane.callsign); } else { @@ -1505,7 +1449,11 @@ void FGTower::DoRwyDetails() { // Based on the airport-id and wind get the active runway const FGAirport* apt = fgFindAirportID(ident); - assert(apt); + if (!apt) { + SG_LOG(SG_ATC, SG_WARN, "FGTower::DoRwyDetails: unknown ICAO:" << ident); + return; + } + FGRunway* runway = apt->getActiveRunwayForUsage(); activeRwy = runway->ident(); @@ -1943,16 +1891,12 @@ void FGTower::doThresholdETACalc() { // Do the approach list first for(twrItr = appList.begin(); twrItr != appList.end(); twrItr++) { TowerPlaneRec* tpr = *twrItr; - if(!(tpr->isUser)) tpr->pos = tpr->planePtr->getPos(); - //cout << "APP: "; CalcETA(tpr); } // Then the circuit list //cout << "Circuit list size is " << circuitList.size() << '\n'; for(twrItr = circuitList.begin(); twrItr != circuitList.end(); twrItr++) { TowerPlaneRec* tpr = *twrItr; - if(!(tpr->isUser)) tpr->pos = tpr->planePtr->getPos(); - //cout << "CIRC: "; CalcETA(tpr); } //cout << "Done doThresholdETCCalc" << endl; @@ -2031,65 +1975,6 @@ double FGTower::GetTrafficETA(unsigned int list_pos, bool printout) { //cout << "ETA returned = " << tpr->eta << '\n'; return(tpr->eta); } - - -void FGTower::ContactAtHoldShort(const PlaneRec& plane, FGAIPlane* requestee, tower_traffic_type operation) { - // HACK - assume that anything contacting at hold short is new for now - FIXME LATER - TowerPlaneRec* t = new TowerPlaneRec; - t->plane = plane; - t->planePtr = requestee; - t->holdShortReported = true; - t->clearedToLineUp = false; - t->clearedToTakeOff = false; - t->opType = operation; - t->pos = requestee->getPos(); - - //cout << "Hold Short reported by " << plane.callsign << '\n'; - SG_LOG(SG_ATC, SG_BULK, "Hold Short reported by " << plane.callsign); - -/* - bool next = AddToTrafficList(t, true); - if(next) { - double teta = GetTrafficETA(2); - if(teta < 150.0) { - t->clearanceCounter = 7.0; // This reduces the delay before response to 3 secs if an immediate takeoff is reqd - //cout << "Reducing response time to request due imminent traffic\n"; - } - } else { - } -*/ - // TODO - possibly add the reduced interval to clearance when immediate back in under the new scheme - - holdList.push_back(t); - - responseReqd = true; -} - -// Register the presence of an AI plane at a point where contact would already have been made in real life -// CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns. -void FGTower::RegisterAIPlane(const PlaneRec& plane, FGAIPlane* ai, const tower_traffic_type& op, const PatternLeg& lg) { - // At the moment this is only going to be tested with inserting an AI plane on downwind - TowerPlaneRec* t = new TowerPlaneRec; - t->plane = plane; - t->planePtr = ai; - t->opType = op; - t->leg = lg; - t->pos = ai->getPos(); - - CalcETA(t); - - if(op == CIRCUIT && lg != LEG_UNKNOWN) { - AddToCircuitList(t); - } else { - // FLAG A WARNING - } - - doThresholdUseOrder(); -} - -void FGTower::DeregisterAIPlane(const string& id) { - RemovePlane(id); -} // Contact tower for VFR approach // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo" @@ -2147,33 +2032,6 @@ void FGTower::VFRArrivalContact(const string& ID, const LandingType& opt) { current_atcdialog->remove_entry(ident, USER_REQUEST_VFR_ARRIVAL_TOUCH_AND_GO, TOWER); } -// landingType defaults to AIP_LT_UNKNOWN -void FGTower::VFRArrivalContact(const PlaneRec& plane, FGAIPlane* requestee, const LandingType& lt) { - //cout << "VFRArrivalContact called for plane " << plane.callsign << " at " << ident << '\n'; - // Possible hack - assume this plane is new for now - TODO - should check really - TowerPlaneRec* t = new TowerPlaneRec; - t->plane = plane; - t->planePtr = requestee; - t->landingType = lt; - t->pos = requestee->getPos(); - - //cout << "Hold Short reported by " << plane.callsign << '\n'; - SG_LOG(SG_ATC, SG_BULK, "VFR arrival contact made by " << plane.callsign); - //cout << "VFR arrival contact made by " << plane.callsign << '\n'; - - // HACK - to get up and running I'm going to assume a staight-in final for now. - t->opType = STRAIGHT_IN; - - t->vfrArrivalReported = true; - responseReqd = true; - - //cout << "Before adding, appList.size = " << appList.size() << " at " << ident << '\n'; - appList.push_back(t); // Not necessarily permanent - appListItr = appList.begin(); - //cout << "After adding, appList.size = " << appList.size() << " at " << ident << '\n'; - AddToTrafficList(t); -} - void FGTower::RequestDepartureClearance(const string& ID) { //cout << "Request Departure Clearance called...\n"; } @@ -2384,9 +2242,6 @@ void FGTower::ReportDownwind(const string& ID) { t->pos.setLongitudeDeg(user_lon_node->getDoubleValue()); t->pos.setLatitudeDeg(user_lat_node->getDoubleValue()); t->pos.setElevationM(user_elev_node->getDoubleValue()); - } else { - // ASSERT(t->planePtr != NULL); - t->pos = t->planePtr->getPos(); } CalcETA(t); AddToCircuitList(t); @@ -2413,9 +2268,6 @@ void FGTower::ReportGoingAround(const string& ID) { t->pos.setLongitudeDeg(user_lon_node->getDoubleValue()); t->pos.setLatitudeDeg(user_lat_node->getDoubleValue()); t->pos.setElevationM(user_elev_node->getDoubleValue()); - } else { - // ASSERT(t->planePtr != NULL); - t->pos = t->planePtr->getPos(); } CalcETA(t); AddToCircuitList(t); @@ -2655,3 +2507,32 @@ ostream& operator << (ostream& os, tower_traffic_type ttt) { return(os << "ERROR - Unknown switch in tower_traffic_type operator << "); } +ostream& operator << (ostream& os, PatternLeg pl) { + switch(pl) { + case(TAKEOFF_ROLL): return(os << "TAKEOFF ROLL"); + case(CLIMBOUT): return(os << "CLIMBOUT"); + case(TURN1): return(os << "TURN1"); + case(CROSSWIND): return(os << "CROSSWIND"); + case(TURN2): return(os << "TURN2"); + case(DOWNWIND): return(os << "DOWNWIND"); + case(TURN3): return(os << "TURN3"); + case(BASE): return(os << "BASE"); + case(TURN4): return(os << "TURN4"); + case(FINAL): return(os << "FINAL"); + case(LANDING_ROLL): return(os << "LANDING ROLL"); + case(LEG_UNKNOWN): return(os << "UNKNOWN"); + } + return(os << "ERROR - Unknown switch in PatternLeg operator << "); +} + + +ostream& operator << (ostream& os, LandingType lt) { + switch(lt) { + case(FULL_STOP): return(os << "FULL STOP"); + case(STOP_AND_GO): return(os << "STOP AND GO"); + case(TOUCH_AND_GO): return(os << "TOUCH AND GO"); + case(AIP_LT_UNKNOWN): return(os << "UNKNOWN"); + } + return(os << "ERROR - Unknown switch in LandingType operator << "); +} + diff --git a/src/ATCDCL/tower.hxx b/src/ATCDCL/tower.hxx index a09536993..fa7115c0d 100644 --- a/src/ATCDCL/tower.hxx +++ b/src/ATCDCL/tower.hxx @@ -31,7 +31,6 @@ #include "ATC.hxx" #include "ATCProjection.hxx" -#include "AIPlane.hxx" class FGATCMgr; class FGGround; @@ -49,6 +48,32 @@ enum tower_traffic_type { ostream& operator << (ostream& os, tower_traffic_type ttt); +enum PatternLeg { + TAKEOFF_ROLL, + CLIMBOUT, + TURN1, + CROSSWIND, + TURN2, + DOWNWIND, + TURN3, + BASE, + TURN4, + FINAL, + LANDING_ROLL, + LEG_UNKNOWN +}; + +ostream& operator << (ostream& os, PatternLeg pl); + +enum LandingType { + FULL_STOP, + STOP_AND_GO, + TOUCH_AND_GO, + AIP_LT_UNKNOWN +}; + +ostream& operator << (ostream& os, LandingType lt); + enum tower_callback_type { USER_REQUEST_VFR_DEPARTURE = 1, USER_REQUEST_VFR_ARRIVAL = 2, @@ -74,7 +99,6 @@ public: TowerPlaneRec(const SGGeod& pt); TowerPlaneRec(const PlaneRec& p, const SGGeod& pt); - FGAIPlane* planePtr; // This might move to the planeRec eventually PlaneRec plane; SGGeod pos; @@ -136,8 +160,6 @@ public: // eg "Cessna Charlie Foxtrot Golf Foxtrot Sierra eight miles South of the airport for full stop with Bravo" // This function probably only called via user interaction - AI planes will have an overloaded function taking a planerec. void VFRArrivalContact(const std::string& ID, const LandingType& opt = AIP_LT_UNKNOWN); - // For the AI planes... - void VFRArrivalContact(const PlaneRec& plane, FGAIPlane* requestee, const LandingType& lt = AIP_LT_UNKNOWN); void RequestDepartureClearance(const std::string& ID); void RequestTakeOffClearance(const std::string& ID); @@ -151,16 +173,6 @@ public: void ReportDownwind(const std::string& ID); void ReportGoingAround(const std::string& ID); - // Contact tower when at a hold short for departure - for now we'll assume plane - maybe vehicles might want to cross runway eventually? - void ContactAtHoldShort(const PlaneRec& plane, FGAIPlane* requestee, tower_traffic_type operation); - - // Register the presence of an AI plane at a point where contact would already have been made in real life - // CAUTION - currently it is assumed that this plane's callsign is unique - it is up to AIMgr to generate unique callsigns. - void RegisterAIPlane(const PlaneRec& plane, FGAIPlane* ai, const tower_traffic_type& op, const PatternLeg& lg = LEG_UNKNOWN); - - // Deregister and remove an AI plane. - void DeregisterAIPlane(const std::string& id); - // Public interface to the active runway - this will get more complex // in the future and consider multi-runway use, airplane weight etc. inline const std::string& GetActiveRunway() const { return activeRwy; } diff --git a/src/ATCDCL/transmission.cxx b/src/ATCDCL/transmission.cxx index 9f77af939..5c1d01572 100644 --- a/src/ATCDCL/transmission.cxx +++ b/src/ATCDCL/transmission.cxx @@ -25,6 +25,8 @@ #include "transmission.hxx" +#include + #include #include diff --git a/src/Aircraft/Makefile.am b/src/Aircraft/Makefile.am index 25dcd510d..02b586a9f 100644 --- a/src/Aircraft/Makefile.am +++ b/src/Aircraft/Makefile.am @@ -1,7 +1,6 @@ noinst_LIBRARIES = libAircraft.a libAircraft_a_SOURCES = \ - aircraft.cxx aircraft.hxx \ controls.cxx controls.hxx \ replay.cxx replay.hxx diff --git a/src/Aircraft/aircraft.cxx b/src/Aircraft/aircraft.cxx deleted file mode 100644 index ba760a33b..000000000 --- a/src/Aircraft/aircraft.cxx +++ /dev/null @@ -1,242 +0,0 @@ -// aircraft.cxx -- various aircraft routines -// -// Written by Curtis Olson, started May 1997. -// -// Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ - -#ifdef HAVE_CONFIG_H -# include "config.h" -#endif - -#include -#include // strdup - -#include - -#include -#include -#include -#include -#include -#include - -#include
-#include
-#include
-#include
-#include -#include -#include -#include - -#include "aircraft.hxx" - - -// This is a record containing all the info for the aircraft currently -// being operated -fgAIRCRAFT current_aircraft; - - -// Initialize an Aircraft structure -void fgAircraftInit( void ) { - SG_LOG( SG_AIRCRAFT, SG_INFO, "Initializing Aircraft structure" ); - - current_aircraft.fdm_state = cur_fdm_state; - current_aircraft.controls = globals->get_controls(); -} - - -// Display various parameters to stdout -void fgAircraftOutputCurrent(fgAIRCRAFT *a) { - FGInterface *f; - - f = a->fdm_state; - - SG_LOG( SG_FLIGHT, SG_DEBUG, - "Pos = (" - << (f->get_Longitude() * 3600.0 * SGD_RADIANS_TO_DEGREES) << "," - << (f->get_Latitude() * 3600.0 * SGD_RADIANS_TO_DEGREES) << "," - << f->get_Altitude() - << ") (Phi,Theta,Psi)=(" - << f->get_Phi() << "," - << f->get_Theta() << "," - << f->get_Psi() << ")" ); - - SG_LOG( SG_FLIGHT, SG_DEBUG, - "Kts = " << f->get_V_equiv_kts() - << " Elev = " << globals->get_controls()->get_elevator() - << " Aileron = " << globals->get_controls()->get_aileron() - << " Rudder = " << globals->get_controls()->get_rudder() - << " Power = " << globals->get_controls()->get_throttle( 0 ) ); -} - - -// Show available aircraft types -void fgReadAircraft(void) { - - // SGPropertyNode *aircraft_types = fgGetNode("/sim/aircraft-types", true); - - SGPath path( globals->get_fg_root() ); - path.append("Aircraft"); - - ulDirEnt* dire; - ulDir *dirp; - - dirp = ulOpenDir(path.c_str()); - if (dirp == NULL) { - SG_LOG( SG_AIRCRAFT, SG_ALERT, "Unable to open aircraft directory." ); - ulCloseDir(dirp); - return; - } - - while ((dire = ulReadDir(dirp)) != NULL) { - char *ptr; - - if ((ptr = strstr(dire->d_name, "-set.xml")) && strlen(ptr) == 8) { - - *ptr = '\0'; -#if 0 - SGPath afile = path; - afile.append(dire->d_name); - - SGPropertyNode root; - try { - readProperties(afile.str(), &root); - } catch (...) { - continue; - } - - SGPropertyNode *node = root.getNode("sim"); - if (node) { - SGPropertyNode *desc = node->getNode("description"); - - if (desc) { - SGPropertyNode *aircraft = - aircraft_types->getChild(dire->d_name, 0, true); - - aircraft->setStringValue(strdup(desc->getStringValue())); - } - } -#endif - } - } - - ulCloseDir(dirp); - - globals->get_commands()->addCommand("load-aircraft", fgLoadAircraft); -} - -bool -fgLoadAircraft (const SGPropertyNode * arg) -{ - static const SGPropertyNode *master_freeze - = fgGetNode("/sim/freeze/master"); - - bool freeze = master_freeze->getBoolValue(); - if ( !freeze ) { - fgSetBool("/sim/freeze/master", true); - } - - // TODO: - // remove electrical system - cur_fdm_state->unbind(); - - // Save the selected aircraft model since restoreInitialState - // will obverwrite it. - // - string aircraft = fgGetString("/sim/aircraft", ""); - globals->restoreInitialState(); - - fgSetString("/sim/aircraft", aircraft.c_str()); - fgSetString("/sim/panel/path", "Aircraft/c172p/Panels/c172-vfr-panel.xml"); - - if ( aircraft.size() > 0 ) { - SGPath aircraft_path(globals->get_fg_root()); - aircraft_path.append("Aircraft"); - aircraft_path.append(aircraft); - aircraft_path.concat("-set.xml"); - SG_LOG(SG_INPUT, SG_INFO, "Reading default aircraft: " << aircraft - << " from " << aircraft_path.str()); - try { - readProperties(aircraft_path.str(), globals->get_props()); - } catch (const sg_exception &e) { - string message = "Error reading default aircraft: "; - message += e.getFormattedMessage(); - SG_LOG(SG_INPUT, SG_ALERT, message); - exit(2); - } - } else { - SG_LOG(SG_INPUT, SG_ALERT, "No default aircraft specified"); - } - - // Initialize the (new) 2D panel. - // - string panel_path = fgGetString("/sim/panel/path", - "Aircraft/c172p/Panels/c172-vfr-panel.xml"); - - FGPanel *panel = fgReadPanel(panel_path); - if (panel == 0) { - SG_LOG( SG_INPUT, SG_ALERT, - "Error reading new panel from " << panel_path ); - } else { - SG_LOG( SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path ); - globals->get_current_panel()->unbind(); - delete globals->get_current_panel(); - globals->set_current_panel( panel ); - globals->get_current_panel()->init(); - globals->get_current_panel()->bind(); - globals->get_current_panel()->update(0); - } - - // Load the new 3D model - // - globals->get_aircraft_model()->unbind(); - delete globals->get_aircraft_model(); - globals->set_aircraft_model(new FGAircraftModel); - globals->get_aircraft_model()->init(); - globals->get_aircraft_model()->bind(); - - // TODO: - // load new electrical system - // - - // update our position based on current presets - fgInitPosition(); - - // Update the HUD - fgHUDInit(¤t_aircraft); - - SGTime *t = globals->get_time_params(); - delete t; - t = fgInitTime(); - globals->set_time_params( t ); - - globals->get_viewmgr()->reinit(); - globals->get_controls()->reset_all(); - globals->get_aircraft_model()->reinit(); - globals->get_subsystem("xml-autopilot")->reinit(); - - fgReInitSubsystems(); - - if ( !freeze ) { - fgSetBool("/sim/freeze/master", false); - } - - return true; -} diff --git a/src/Aircraft/aircraft.hxx b/src/Aircraft/aircraft.hxx deleted file mode 100644 index 95763b017..000000000 --- a/src/Aircraft/aircraft.hxx +++ /dev/null @@ -1,58 +0,0 @@ -//************************************************************************* -// aircraft.hxx -- define shared aircraft parameters -// -// Written by Curtis Olson, started May 1997. -// -// Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ -//*************************************************************************/ - - -#ifndef _AIRCRAFT_HXX -#define _AIRCRAFT_HXX - -class FGInterface; -class FGControls; -class SGPropertyNode; - -// Define a structure containing all the parameters for an aircraft -typedef struct{ - FGInterface *fdm_state; - FGControls *controls; -} fgAIRCRAFT ; - - -// current_aircraft contains all the parameters of the aircraft -// currently being operated. -extern fgAIRCRAFT current_aircraft; - - -// Initialize an Aircraft structure -void fgAircraftInit( void ); - - -// Display various parameters to stdout -void fgAircraftOutputCurrent(fgAIRCRAFT *a); - - -// Read the list of available aircraft into to property tree -void fgReadAircraft(void); -bool fgLoadAircraft (const SGPropertyNode * arg); - -#endif // _AIRCRAFT_HXX - diff --git a/src/Aircraft/replay.cxx b/src/Aircraft/replay.cxx index 21c4a1d44..aa976adcb 100644 --- a/src/Aircraft/replay.cxx +++ b/src/Aircraft/replay.cxx @@ -26,7 +26,6 @@ #include -#include #include
#include #include @@ -164,9 +163,10 @@ void FGReplay::update( double dt ) { //FGProps2NetFDM( &f, false ); // sanity check, don't collect data if FDM data isn't good - if ( !cur_fdm_state->get_inited() ) { + if (!fgGetBool("/sim/fdm-initialized", false)) { return; } + //FGNetCtrls c; //FGProps2NetCtrls( &c, false, false ); //stamp("point_04ba"); diff --git a/src/Airports/.gitignore b/src/Airports/.gitignore new file mode 100644 index 000000000..a11fbd261 --- /dev/null +++ b/src/Airports/.gitignore @@ -0,0 +1 @@ +calc_loc diff --git a/src/Airports/dynamics.cxx b/src/Airports/dynamics.cxx index a323d809c..f45341e5e 100644 --- a/src/Airports/dynamics.cxx +++ b/src/Airports/dynamics.cxx @@ -432,6 +432,12 @@ string FGAirportDynamics::chooseRwyByHeading(stringVec rwys, double rwyHeading, headingError; string runway; for (stringVecIterator i = rwys.begin(); i != rwys.end(); i++) { + if (!_ap->hasRunwayWithIdent(*i)) { + SG_LOG(SG_ATC, SG_WARN, "chooseRwyByHeading: runway " << *i << + " not found at " << _ap->ident()); + continue; + } + FGRunway *rwy = _ap->getRunwayByIdent((*i)); rwyHeading = rwy->headingDeg(); headingError = fabs(heading - rwyHeading); diff --git a/src/Airports/pavement.cxx b/src/Airports/pavement.cxx index 7e5f60763..4f06a9a1d 100755 --- a/src/Airports/pavement.cxx +++ b/src/Airports/pavement.cxx @@ -25,8 +25,9 @@ #include "pavement.hxx" FGPavement::FGPavement(const std::string& aIdent, const SGGeod& aPos) : - FGPositioned(PAVEMENT, aIdent, aPos, false) + FGPositioned(PAVEMENT, aIdent, aPos) { + init(false); // FGPositioned::init } void FGPavement::addNode(const SGGeod &aPos, bool aClose) diff --git a/src/Airports/runwaybase.cxx b/src/Airports/runwaybase.cxx index fd82406ad..1131e22a0 100644 --- a/src/Airports/runwaybase.cxx +++ b/src/Airports/runwaybase.cxx @@ -51,12 +51,14 @@ FGRunwayBase::FGRunwayBase(Type aTy, const string& aIdent, const double width, const int surface_code, bool index) : - FGPositioned(aTy, aIdent, aGeod, index) + FGPositioned(aTy, aIdent, aGeod) { _heading = heading; _length = length; _width = width; _surface_code = surface_code; + + init(index); } SGGeod FGRunwayBase::pointOnCenterline(double aOffset) const diff --git a/src/Airports/runwayprefs.cxx b/src/Airports/runwayprefs.cxx index 8337d31f9..b47c6bc77 100644 --- a/src/Airports/runwayprefs.cxx +++ b/src/Airports/runwayprefs.cxx @@ -26,6 +26,7 @@ #endif #include +#include #include diff --git a/src/Airports/runways.cxx b/src/Airports/runways.cxx index 3eb853823..27caa4f6d 100644 --- a/src/Airports/runways.cxx +++ b/src/Airports/runways.cxx @@ -27,6 +27,7 @@ #include // sprintf() #include // atoi() +#include #include diff --git a/src/Airports/simple.cxx b/src/Airports/simple.cxx index af16923b3..a418bd414 100644 --- a/src/Airports/simple.cxx +++ b/src/Airports/simple.cxx @@ -30,6 +30,8 @@ #include "simple.hxx" +#include + #include #include #include @@ -61,6 +63,7 @@ FGAirport::FGAirport(const string &id, const SGGeod& location, const SGGeod& tow mRunwaysLoaded(false), mTaxiwaysLoaded(true) { + init(true); // init FGPositioned } diff --git a/src/Autopilot/Makefile.am b/src/Autopilot/Makefile.am index 7ba3b5bb6..fdd591884 100644 --- a/src/Autopilot/Makefile.am +++ b/src/Autopilot/Makefile.am @@ -2,7 +2,17 @@ noinst_LIBRARIES = libAutopilot.a libAutopilot_a_SOURCES = \ route_mgr.cxx route_mgr.hxx \ - xmlauto.cxx xmlauto.hxx \ - autobrake.cxx autobrake.hxx + autopilotgroup.cxx autopilotgroup.hxx \ + autopilot.cxx autopilot.hxx \ + inputvalue.cxx inputvalue.hxx \ + component.cxx component.hxx \ + analogcomponent.cxx analogcomponent.hxx \ + pidcontroller.cxx pidcontroller.hxx \ + pisimplecontroller.cxx pisimplecontroller.hxx \ + predictor.cxx predictor.hxx \ + digitalfilter.cxx digitalfilter.hxx \ + digitalcomponent.cxx digitalcomponent.hxx \ + logic.cxx logic.hxx \ + flipflop.cxx flipflop.hxx INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src diff --git a/src/Autopilot/analogcomponent.cxx b/src/Autopilot/analogcomponent.cxx new file mode 100644 index 000000000..d32717d22 --- /dev/null +++ b/src/Autopilot/analogcomponent.cxx @@ -0,0 +1,113 @@ +// analogcomponent.cxx - Base class for analog autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#include "analogcomponent.hxx" +#include
+ +using namespace FGXMLAutopilot; + +AnalogComponent::AnalogComponent() : + Component(), + _feedback_if_disabled(false), + _passive_mode( fgGetNode("/autopilot/locks/passive-mode", true) ) +{ +} + +double AnalogComponent::clamp( double value ) const +{ + //If this is a periodical value, normalize it into our domain + // before clamping + if( _periodical ) + value = _periodical->normalize( value ); + + // clamp, if either min or max is defined + if( _minInput.size() + _maxInput.size() > 0 ) { + double d = _maxInput.get_value(); + if( value > d ) value = d; + d = _minInput.get_value(); + if( value < d ) value = d; + } + return value; +} + +bool AnalogComponent::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + SG_LOG( SG_AUTOPILOT, SG_BULK, "AnalogComponent::configure(" << nodeName << ")" << endl ); + if( Component::configure( nodeName, configNode ) ) + return true; + + if ( nodeName == "feedback-if-disabled" ) { + _feedback_if_disabled = configNode->getBoolValue(); + return true; + } + + if ( nodeName == "output" ) { + // grab all and childs + int found = 0; + // backwards compatibility: allow elements + SGPropertyNode_ptr prop; + for( int i = 0; (prop = configNode->getChild("prop", i)) != NULL; i++ ) { + SGPropertyNode *tmp = fgGetNode( prop->getStringValue(), true ); + _output_list.push_back( tmp ); + found++; + } + for( int i = 0; (prop = configNode->getChild("property", i)) != NULL; i++ ) { + SGPropertyNode *tmp = fgGetNode( prop->getStringValue(), true ); + _output_list.push_back( tmp ); + found++; + } + + // no elements, text node of is property name + if( found == 0 ) + _output_list.push_back( fgGetNode(configNode->getStringValue(), true ) ); + + return true; + } + + if( nodeName == "input" ) { + _valueInput.push_back( new InputValue( configNode ) ); + return true; + } + + if( nodeName == "reference" ) { + _referenceInput.push_back( new InputValue( configNode ) ); + return true; + } + + if( nodeName == "min" || nodeName == "u_min" ) { + _minInput.push_back( new InputValue( configNode ) ); + return true; + } + + if( nodeName == "max" || nodeName == "u_max" ) { + _maxInput.push_back( new InputValue( configNode ) ); + return true; + } + + if( nodeName == "period" ) { + _periodical = new PeriodicalValue( configNode ); + return true; + } + + SG_LOG( SG_AUTOPILOT, SG_BULK, "AnalogComponent::configure(" << nodeName << ") [unhandled]" << endl ); + return false; +} diff --git a/src/Autopilot/analogcomponent.hxx b/src/Autopilot/analogcomponent.hxx new file mode 100644 index 000000000..ccbd099b6 --- /dev/null +++ b/src/Autopilot/analogcomponent.hxx @@ -0,0 +1,148 @@ +// analogcomponent.hxx - Base class for analog autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __ANALOGCOMPONENT_HXX +#define __ANALOGCOMPONENT_HXX 1 + +#include "inputvalue.hxx" +#include "component.hxx" + +namespace FGXMLAutopilot { + +/** + * @brief Base class for analog autopilot components + * + * Each analog component has + *
    + *
  • one value input
  • + *
  • one reference input
  • + *
  • one minimum clamp input
  • + *
  • one maximum clamp input
  • + *
  • an optional periodical definition
  • + *
+ */ +class AnalogComponent : public Component { + +private: + /** + * @brief a flag signalling that the output property value shall be fed back + * to the active input property if this component is disabled. This flag + * reflects the <feedback-if-disabled> boolean property. + */ + bool _feedback_if_disabled; + +protected: + /** + * @brief the value input + */ + InputValueList _valueInput; + + /** + * @brief the reference input + */ + InputValueList _referenceInput; + + /** + * @brief the minimum output clamp input + */ + InputValueList _minInput; + + /** + * @brief the maximum output clamp input + */ + InputValueList _maxInput; + + /** + * @brief the configuration for periodical outputs + */ + PeriodicalValue_ptr _periodical; + + /** + * @brief A constructor for an analog component. Call configure() to + * configure this component from a property node + */ + AnalogComponent(); + + /** + * @brief This method configures this analog component from a property node. Gets + * called multiple times from the base class configure method for every + config node. + * @param nodeName the name of the configuration node provided in configNode + * @param configNode the configuration node itself + * @return true if the node was handled, false otherwise. + */ + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + + /** + * @brief clamp the given value if <min> and/or <max> inputs were given + * @param the value to clamp + * @return the clamped value + */ + double clamp( double value ) const; + + /** + * @brief overideable method being called from the update() method if this component + * is disabled. Analog components feed back it's output value to the active + input value if disabled and feedback-if-disabled is true + */ + virtual void disabled( double dt ); + + /** + * @brief return the current double value of the output property + * @return the current value of the output property + * If no output property is configured, a value of zero will be returned. + * If more than one output property is configured, the value of the first output property + * is returned. The current value of the output property will be clamped to the configured + * values of <min> and/or <max>. + */ + inline double get_output_value() const { + return _output_list.size() == 0 ? 0.0 : clamp(_output_list[0]->getDoubleValue()); + } + + simgear::PropertyList _output_list; + SGPropertyNode_ptr _passive_mode; + + inline void set_output_value( double value ) { + // passive_ignore == true means that we go through all the + // motions, but drive the outputs. This is analogous to + // running the autopilot with the "servos" off. This is + // helpful for things like flight directors which position + // their vbars from the autopilot computations. + if ( _honor_passive && _passive_mode->getBoolValue() ) return; + value = clamp( value ); + for( simgear::PropertyList::iterator it = _output_list.begin(); + it != _output_list.end(); ++it) + (*it)->setDoubleValue( value ); + } +}; + +inline void AnalogComponent::disabled( double dt ) +{ + if( _feedback_if_disabled && _output_list.size() > 0 ) { + InputValue * input; + if( (input = _valueInput.get_active() ) != NULL ) + input->set_value( _output_list[0]->getDoubleValue() ); + } +} + +} +#endif // ANALOGCOMPONENT_HXX diff --git a/src/Autopilot/autobrake.cxx b/src/Autopilot/autobrake.cxx deleted file mode 100644 index ec1fcfc0e..000000000 --- a/src/Autopilot/autobrake.cxx +++ /dev/null @@ -1,349 +0,0 @@ -// autobrake.cxx - generic, configurable autobrake system -// -// Written by James Turner, started September 2009. -// -// Copyright (C) 2009 Curtis L. Olson -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ - -#include "autobrake.hxx" - -#include
- -FGAutoBrake::FGAutoBrake() : - _lastGroundspeedKts(0.0), - _step(0), - _rto(false), - _armed(false), - _rtoArmed(false), - _engaged(false), - _targetDecel(0.0), - _fcsBrakeControl(0.0), - _leftBrakeOutput(0.0), - _rightBrakeOutput(0.0) -{ - // default config, close to Boeing 747-400 / 777 values - _configNumSteps = 4; - _configRTOStep = -1; - _configDisengageStep = 0; - _configMaxDecel = 11; // ft-sec-sec - _configRTODecel = 11; // ft-sec-sec - _configRTOSpeed = 85; // kts -} - -FGAutoBrake::~FGAutoBrake() -{ -} - -void FGAutoBrake::init() -{ - _root = fgGetNode("/autopilot/autobrake", true); - - _root->tie("armed", SGRawValueMethods - (*this, &FGAutoBrake::getArmed, &FGAutoBrake::setArmed)); - - _root->tie("step", SGRawValueMethods - (*this, &FGAutoBrake::getStep, &FGAutoBrake::setStep)); - - _root->tie("rto", SGRawValueMethods - (*this, &FGAutoBrake::getRTO, &FGAutoBrake::setRTO)); - - _engineControlsNode = fgGetNode("/controls/engines"); - - // brake position nodes - _brakeInputs[0] = fgGetNode("/controls/gear/brake-left"); - _brakeInputs[1] = fgGetNode("/controls/gear/brake-right"); - _brakeInputs[2] = fgGetNode("/controls/gear/copilot-brake-left"); - _brakeInputs[3] = fgGetNode("/controls/gear/copilot-brake-right"); - - // config - SGPropertyNode_ptr config = _root->getChild("config", 0, true); - config->tie("num-steps", SGRawValuePointer(&_configNumSteps)); - config->tie("rto-step", SGRawValuePointer(&_configRTOStep)); - config->tie("disengage-step", SGRawValuePointer(&_configDisengageStep)); - config->tie("rto-decel-fts-sec", SGRawValuePointer(&_configRTODecel)); - config->tie("max-decel-fts-sec", SGRawValuePointer(&_configMaxDecel)); - config->tie("rto-engage-kts", SGRawValuePointer(&_configRTOSpeed)); - - - // outputs - _root->tie("target-decel-fts-sec", - SGRawValueMethods(*this, &FGAutoBrake::getTargetDecel)); - _root->tie("actual-decel-fts-sec", - SGRawValueMethods(*this, &FGAutoBrake::getActualDecel)); - _root->tie("fcs-brake", SGRawValuePointer(&_fcsBrakeControl)); - _root->tie("brake-left-output", SGRawValuePointer(&_leftBrakeOutput)); - _root->tie("brake-right-output", SGRawValuePointer(&_rightBrakeOutput)); - - _root->tie("engaged", SGRawValueMethods(*this, &FGAutoBrake::getEngaged)); -} - -void FGAutoBrake::postinit() -{ - _weightOnWheelsNode = fgGetNode("/gear/gear/wow"); - _groundspeedNode = fgGetNode("/velocities/groundspeed-kt"); - if (!_weightOnWheelsNode) { - return; // don't crash if we're using an acft (UFO, ATC, with no WoW flag) - } - - _lastWoW = _weightOnWheelsNode->getBoolValue(); -} - - -void FGAutoBrake::bind() -{ -} - -void FGAutoBrake::unbind() -{ -} - -void FGAutoBrake::update(double dt) -{ - _leftBrakeInput = SGMiscd::max(_brakeInputs[0]->getDoubleValue(), - _brakeInputs[2]->getDoubleValue()); - _rightBrakeInput = SGMiscd::max(_brakeInputs[1]->getDoubleValue(), - _brakeInputs[3]->getDoubleValue()); - - // various FDMs don't supply sufficent information for us to work, - // so just be passive in those cases. - if (!_weightOnWheelsNode || !_groundspeedNode || !_engineControlsNode) { - // pass the values straight through - _leftBrakeOutput = _leftBrakeInput; - _rightBrakeOutput = _rightBrakeInput; - return; - } - - if (dt <= 0.0) { - return; // paused - } - - double gs = _groundspeedNode->getDoubleValue(); - _actualDecel = (_lastGroundspeedKts - gs) / dt; - _lastGroundspeedKts = gs; - - if (!_armed || (_step == 0)) { - // even if we're off or disarmed, the physical valve system must pass - // pilot control values through. - _leftBrakeOutput = _leftBrakeInput; - _rightBrakeOutput = _rightBrakeInput; - return; - } - - if (_engaged) { - updateEngaged(dt); - } else { - bool e = shouldEngage(); - if (e) { - engage(); - updateEngaged(dt); - } - } - - // sum pilot inpiuts with auto-brake FCS input - _leftBrakeOutput = SGMiscd::max(_leftBrakeInput, _fcsBrakeControl); - _rightBrakeOutput = SGMiscd::max(_rightBrakeInput, _fcsBrakeControl); - - _lastWoW = _weightOnWheelsNode->getBoolValue(); -} - -void FGAutoBrake::engage() -{ - SG_LOG(SG_AUTOPILOT, SG_INFO, "FGAutoBrake: engaging"); - _engaged = true; -} - -void FGAutoBrake::updateEngaged(double dt) -{ - // check for pilot braking input cancelling engage - const double BRAKE_INPUT_THRESHOLD = 0.02; // 2% application triggers - if ((_leftBrakeInput > BRAKE_INPUT_THRESHOLD) || (_rightBrakeInput > BRAKE_INPUT_THRESHOLD)) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "auto-brake, detected pilot brake input, disengaing"); - disengage(); - return; - } - - if (!throttlesAtIdle()) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "auto-brake, throttles not at idle, disengaing"); - disengage(); - return; - } - - // update the target deceleration; note step can be changed while engaged - if (_rto) { - _targetDecel = _configRTODecel; - } else { - double f = (double) _step / _configNumSteps; - _targetDecel = _configMaxDecel * f; - } -} - -bool FGAutoBrake::shouldEngage() -{ - if (_rto) { - return shouldEngageRTO(); - } - - if (_lastWoW || !_weightOnWheelsNode->getBoolValue()) { - return false; - } - - - if (!throttlesAtIdle()) { - return false; - } - - SG_LOG(SG_AUTOPILOT, SG_INFO, "Autobrake, should enage"); - return true; -} - -bool FGAutoBrake::shouldEngageRTO() -{ - double speed = _groundspeedNode->getDoubleValue(); - - if (_rtoArmed) { - if (speed < _configRTOSpeed) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "FGAutoBrake: RTO armed, but speed is now below arming speed"); - _rtoArmed = false; - return false; - } - - if (!_weightOnWheelsNode->getBoolValue()) { - if (airborne()) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "FGAutoBrake: RTO, airbone, disengaging"); - _rtoArmed = false; - _armed = false; - _step = _configDisengageStep; - } - - return false; - } - - if (throttlesAtIdle()) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "FGAutoBrake: RTO, throttles at idle, will engage"); - return true; - } else { - return false; - } - } else { - // RTO arming case - if (speed > _configRTOSpeed) { - SG_LOG(SG_AUTOPILOT, SG_INFO, "Autobrake RTO: passed " << _configRTOSpeed << " knots, arming RTO mode"); - _rtoArmed = true; - } - } - - return false; -} - -void FGAutoBrake::disengage() -{ - if (!_engaged) { - return; - } - - SG_LOG(SG_AUTOPILOT, SG_INFO, "FGAutoBrake: disengage"); - _engaged = false; - _fcsBrakeControl = 0.0; - _armed = false; - _rtoArmed = false; - _targetDecel = 0.0; - _step = _configDisengageStep; -} - -bool FGAutoBrake::airborne() const -{ - return !_weightOnWheelsNode->getBoolValue(); -} - -bool FGAutoBrake::throttlesAtIdle() const -{ - SGPropertyNode_ptr e; - const double IDLE_THROTTLE = 0.05; // 5% margin for idle setting - - for (int index=0; (e = _engineControlsNode->getChild("engine", index)) != NULL; ++index) { - if ((e->getDoubleValue("throttle") > IDLE_THROTTLE) && !e->getBoolValue("reverser")) { - return false; - } - } // of engines iteration - - return true; -} - -void FGAutoBrake::setArmed(bool aArmed) -{ - if (aArmed == _armed) { - return; - } - - disengage(); - _armed = aArmed; -} - -void FGAutoBrake::setRTO(bool aRTO) -{ - if (aRTO) { - // ensure we meet RTO selection criteria: - if (!_weightOnWheelsNode->getBoolValue()) { - // some systems combine RTO with a standard step, selecting RTO if on - // the ground. Handle that case by setting _rto = false, and letting - // setStep() do the rest of the work as normal. - if ((_configRTOStep > 0) && (_configRTOStep <= _configNumSteps)) { - // RTO is combined with a normal step, select that - } else { - SG_LOG(SG_AUTOPILOT, SG_WARN, "auto-brake: cannot select RTO mode, no weight on wheels"); - } - - _rto = false; - return; - } - - _rtoArmed = false; - _rto = true; - _step = _configRTOStep; - setArmed(true); - SG_LOG(SG_AUTOPILOT, SG_INFO, "RTO mode set"); - } else { - _rto = false; - _rtoArmed = false; - // and if we're enaged? - disengage(); - } -} - -void FGAutoBrake::setStep(int aStep) -{ - if (aStep == _step) { - return; - } - - SG_LOG(SG_AUTOPILOT, SG_INFO, "Autobrake step now=" << aStep); - _step = aStep; - bool validStep = false; - - if (aStep == _configRTOStep) { - setRTO(true); - validStep = true; - } else { - _rto = false; - validStep = (_step > 0) && (_step <= _configNumSteps); - } - - setArmed(validStep); // selecting a valid step arms the system -} - - diff --git a/src/Autopilot/autobrake.hxx b/src/Autopilot/autobrake.hxx deleted file mode 100644 index 2a6845c66..000000000 --- a/src/Autopilot/autobrake.hxx +++ /dev/null @@ -1,108 +0,0 @@ -// autobrake.hxx - generic, configurable autobrake system -// -// Written by James Turner, started September 2009. -// -// Copyright (C) 2009 Curtis L. Olson -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ - -#ifndef FG_INSTR_AUTOBRAKE_HXX -#define FG_INSTR_AUTOBRAKE_HXX - -#include -#include - -// forward decls - -class FGAutoBrake : public SGSubsystem -{ -public: - FGAutoBrake(); - virtual ~FGAutoBrake(); - - virtual void init (); - virtual void postinit (); - virtual void bind (); - virtual void unbind (); - virtual void update (double dt); - -private: - - void engage(); - void disengage(); - - void updateEngaged(double dt); - - bool shouldEngage(); - bool shouldEngageRTO(); - - /** - * Helper to determine if all throttles are at idle - * (or have reverse thrust engaged) - */ - bool throttlesAtIdle() const; - - /** - * Helper to determine if we're airbone, i.e weight off all wheels - */ - bool airborne() const; - -// accessors, mostly for SGRawValueMethods use - void setArmed(bool aArmed); - bool getArmed() const { return _armed; } - - void setRTO(bool aRTO); - bool getRTO() const { return _rto; } - - void setStep(int aStep); - int getStep() const { return _step; } - - bool getEngaged() const { return _engaged;} - double getTargetDecel() const { return _targetDecel; } - double getActualDecel() const { return _actualDecel; } - -// members - double _lastGroundspeedKts; - int _step; - bool _rto; // true if in Rejected TakeOff mode - bool _armed; - bool _rtoArmed; ///< true if we have met arming criteria for RTO mode - bool _engaged; ///< true if auto-braking is currently active - double _targetDecel; // target deceleration ft-sec^2 - double _actualDecel; // measured current deceleration in ft-sec^2 - double _fcsBrakeControl; - bool _lastWoW; - double _leftBrakeInput; // summed pilot and co-pilot left brake input - double _rightBrakeInput; // summed pilot and co-pilot right brake input - double _leftBrakeOutput; - double _rightBrakeOutput; - - SGPropertyNode_ptr _root; - SGPropertyNode_ptr _brakeInputs[4]; - SGPropertyNode_ptr _weightOnWheelsNode; - SGPropertyNode_ptr _engineControlsNode; - SGPropertyNode_ptr _groundspeedNode; - - int _configNumSteps; - int _configRTOStep; - int _configDisengageStep; - double _configMaxDecel; ///< deceleration (in ft-sec^2) corresponding to step=numSteps - double _configRTODecel; ///< deceleration (in ft-sec^2) to use in RTO mode - double _configRTOSpeed; ///< speed (in kts) for RTO mode to arm -}; - -#endif // of FG_INSTR_AUTOBRAKE_HXX diff --git a/src/Autopilot/autopilot.cxx b/src/Autopilot/autopilot.cxx new file mode 100644 index 000000000..e8bb91b02 --- /dev/null +++ b/src/Autopilot/autopilot.cxx @@ -0,0 +1,114 @@ +// autopilot.cxx - an even more flexible, generic way to build autopilots +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "functor.hxx" +#include "predictor.hxx" +#include "digitalfilter.hxx" +#include "pisimplecontroller.hxx" +#include "pidcontroller.hxx" +#include "autopilot.hxx" +#include "logic.hxx" +#include "flipflop.hxx" + +#include "Main/fg_props.hxx" + +using namespace FGXMLAutopilot; + +Autopilot::Autopilot( SGPropertyNode_ptr rootNode, SGPropertyNode_ptr configNode ) : + _name("unnamed autopilot"), + _serviceable(true), + _rootNode(rootNode) +{ + map *> componentForge; + componentForge["pid-controller"] = new CreateAndConfigureFunctor(); + componentForge["pi-simple-controller"] = new CreateAndConfigureFunctor(); + componentForge["predict-simple"] = new CreateAndConfigureFunctor(); + componentForge["filter"] = new CreateAndConfigureFunctor(); + componentForge["logic"] = new CreateAndConfigureFunctor(); + componentForge["flipflop"] = new CreateAndConfigureFunctor(); + + if( configNode == NULL ) configNode = rootNode; + + int count = configNode->nChildren(); + for ( int i = 0; i < count; ++i ) { + SGPropertyNode_ptr node = configNode->getChild(i); + string childName = node->getName(); + if( componentForge.count(childName) == 0 ) { + SG_LOG( SG_AUTOPILOT, SG_BULK, "unhandled element <" << childName << ">" << endl ); + continue; + } + + Component * component = (*componentForge[childName])(node); + if( component->get_name().length() == 0 ) { + ostringstream buf; + buf << "unnamed_component_" << i; + component->set_name( buf.str() ); + } + + SG_LOG( SG_AUTOPILOT, SG_INFO, "adding autopilot component \"" << childName << "\" as \"" << component->get_name() << "\"" ); + add_component(component); + } +} + +Autopilot::~Autopilot() +{ +} + +void Autopilot::bind() +{ + fgTie( _rootNode->getNode("serviceable", true)->getPath().c_str(), this, + &Autopilot::is_serviceable, &Autopilot::set_serviceable ); +} + +void Autopilot::unbind() +{ + _rootNode->untie( "serviceable" ); +} + +void Autopilot::add_component( Component * component ) +{ + if( component == NULL ) return; + + // check for duplicate name + std::string name = component->get_name(); + for( unsigned i = 0; get_subsystem( name.c_str() ) != NULL; i++ ) { + ostringstream buf; + buf << component->get_name() << "_" << i; + name = buf.str(); + } + if( name != component->get_name() ) + SG_LOG( SG_ALL, SG_WARN, "Duplicate autopilot component " << component->get_name() << ", renamed to " << name ); + + set_subsystem( name.c_str(), component ); +} + +void Autopilot::update( double dt ) +{ + if( !_serviceable || dt <= SGLimitsd::min() ) + return; + SGSubsystemGroup::update( dt ); +} diff --git a/src/Autopilot/autopilot.hxx b/src/Autopilot/autopilot.hxx new file mode 100644 index 000000000..56bb6c32e --- /dev/null +++ b/src/Autopilot/autopilot.hxx @@ -0,0 +1,69 @@ +// autopilot.hxx - an even more flexible, generic way to build autopilots +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __AUTOPILOT_HXX +#define __AUTOPILOT_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "component.hxx" + +#include +#include + +namespace FGXMLAutopilot { + +/** + * @brief A SGSubsystemGroup implementation to serve as a collection + * of Components + */ +class Autopilot : public SGSubsystemGroup +{ +public: + Autopilot( SGPropertyNode_ptr rootNode, SGPropertyNode_ptr configNode = NULL ); + ~Autopilot(); + + void bind(); + void unbind(); + void update( double dt ); + + void set_serviceable( bool value ) { _serviceable = value; } + bool is_serviceable() const { return _serviceable; } + + std::string get_name() const { return _name; } + void set_name( std::string & name ) { _name = name; } + + void add_component( Component * component ); + +protected: + +private: + std::string _name; + bool _serviceable; + SGPropertyNode_ptr _rootNode; +}; + +} + +#endif // __AUTOPILOT_HXX 1 diff --git a/src/Autopilot/autopilotgroup.cxx b/src/Autopilot/autopilotgroup.cxx new file mode 100644 index 000000000..347a39e0e --- /dev/null +++ b/src/Autopilot/autopilotgroup.cxx @@ -0,0 +1,146 @@ +// autopilotgroup.cxx - an even more flexible, generic way to build autopilots +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "autopilot.hxx" +#include "autopilotgroup.hxx" + +#include +#include + +#include +#include +#include
+ + +using simgear::PropertyList; + +class FGXMLAutopilotGroupImplementation : public FGXMLAutopilotGroup +{ +public: + void init(); + void reinit(); + void update( double dt ); +private: + void initFrom( SGPropertyNode_ptr rootNode, const char * childName ); + vector _autopilotNames; + +}; + +void FGXMLAutopilotGroupImplementation::update( double dt ) +{ + // update all configured autopilots + SGSubsystemGroup::update( dt ); +} + +void FGXMLAutopilotGroupImplementation::reinit() +{ + SGSubsystemGroup::unbind(); + + for( vector::size_type i = 0; i < _autopilotNames.size(); i++ ) { + FGXMLAutopilot::Autopilot * ap = (FGXMLAutopilot::Autopilot*)get_subsystem( _autopilotNames[i] ); + if( ap == NULL ) continue; // ? + remove_subsystem( _autopilotNames[i] ); + delete ap; + } + _autopilotNames.clear(); + init(); +} + +void FGXMLAutopilotGroupImplementation::init() +{ + static const char * nodeNames[] = { + "autopilot", + "property-rule" + }; + for( unsigned i = 0; i < sizeof(nodeNames)/sizeof(nodeNames[0]); i++ ) + initFrom( fgGetNode( "/sim/systems" ), nodeNames[i] ); + + SGSubsystemGroup::bind(); + SGSubsystemGroup::init(); +} + +void FGXMLAutopilotGroupImplementation::initFrom( SGPropertyNode_ptr rootNode, const char * childName ) +{ + if( rootNode == NULL ) + return; + + PropertyList autopilotNodes = rootNode->getChildren(childName); + for( PropertyList::size_type i = 0; i < autopilotNodes.size(); i++ ) { + SGPropertyNode_ptr pathNode = autopilotNodes[i]->getNode( "path" ); + if( pathNode == NULL ) { + SG_LOG( SG_ALL, SG_WARN, "No configuration file specified for this property-rule!"); + continue; + } + + string apName; + SGPropertyNode_ptr nameNode = autopilotNodes[i]->getNode( "name" ); + if( nameNode != NULL ) { + apName = nameNode->getStringValue(); + } else { + std::ostringstream buf; + buf << "unnamed_autopilot_" << i; + apName = buf.str(); + } + + { + // check for duplicate names + string name = apName; + for( unsigned i = 0; get_subsystem( apName.c_str() ) != NULL; i++ ) { + ostringstream buf; + buf << name << "_" << i; + apName = buf.str(); + } + if( apName != name ) + SG_LOG( SG_ALL, SG_WARN, "Duplicate property-rule configuration name " << name << ", renamed to " << apName ); + } + + SGPath config = globals->resolve_maybe_aircraft_path(pathNode->getStringValue()); + + SG_LOG( SG_ALL, SG_INFO, "Reading property-rule configuration from " << config.str() ); + + try { + SGPropertyNode_ptr root = new SGPropertyNode(); + readProperties( config.str(), root ); + + SG_LOG( SG_AUTOPILOT, SG_INFO, "adding property-rule subsystem " << apName ); + FGXMLAutopilot::Autopilot * ap = new FGXMLAutopilot::Autopilot( autopilotNodes[i], root ); + ap->set_name( apName ); + set_subsystem( apName, ap ); + _autopilotNames.push_back( apName ); + + } catch (const sg_exception& e) { + SG_LOG( SG_AUTOPILOT, SG_ALERT, "Failed to load property-rule configuration: " + << config.str() << ":" << e.getMessage() ); + continue; + } + } +} + +FGXMLAutopilotGroup * FGXMLAutopilotGroup::createInstance() +{ + return new FGXMLAutopilotGroupImplementation(); +} diff --git a/src/Autopilot/autopilotgroup.hxx b/src/Autopilot/autopilotgroup.hxx new file mode 100644 index 000000000..1ccb0be76 --- /dev/null +++ b/src/Autopilot/autopilotgroup.hxx @@ -0,0 +1,41 @@ +// autopilotgroup.hxx - an even more flexible, generic way to build autopilots +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#ifndef _XMLAUTO_HXX +#define _XMLAUTO_HXX 1 + + +/** + * @brief Model an autopilot system by implementing a SGSubsystemGroup + * + */ +class FGXMLAutopilotGroup : public SGSubsystemGroup +{ +public: + static FGXMLAutopilotGroup * createInstance(); +protected: + FGXMLAutopilotGroup() : SGSubsystemGroup() {} + +}; + +#endif // _XMLAUTO_HXX diff --git a/src/Autopilot/component.cxx b/src/Autopilot/component.cxx new file mode 100644 index 000000000..bdf6ecc21 --- /dev/null +++ b/src/Autopilot/component.cxx @@ -0,0 +1,130 @@ +// component.cxx - Base class for autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#include "component.hxx" +#include
+#include + +using namespace FGXMLAutopilot; + +Component::Component() : + _enable_value(NULL), + _enabled(false), + _debug(false), + _honor_passive(false) +{ +} + +Component::~Component() +{ + delete _enable_value; +} + +bool Component::configure( SGPropertyNode_ptr configNode ) +{ + for (int i = 0; i < configNode->nChildren(); ++i ) { + SGPropertyNode_ptr prop; + + SGPropertyNode_ptr child = configNode->getChild(i); + string cname(child->getName()); + + if( configure( cname, child ) ) + continue; + + } // for configNode->nChildren() + + return true; +} + +bool Component::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + SG_LOG( SG_AUTOPILOT, SG_BULK, "Component::configure(" << nodeName << ")" << endl ); + + if ( nodeName == "name" ) { + _name = configNode->getStringValue(); + return true; + } + + if ( nodeName == "debug" ) { + _debug = configNode->getBoolValue(); + return true; + } + + if ( nodeName == "enable" ) { + SGPropertyNode_ptr prop; + + if( (prop = configNode->getChild("condition")) != NULL ) { + _condition = sgReadCondition(fgGetNode("/"), prop); + return true; + } + if ( (prop = configNode->getChild( "property" )) != NULL ) { + _enable_prop = fgGetNode( prop->getStringValue(), true ); + } + + if ( (prop = configNode->getChild( "prop" )) != NULL ) { + _enable_prop = fgGetNode( prop->getStringValue(), true ); + } + + if ( (prop = configNode->getChild( "value" )) != NULL ) { + delete _enable_value; + _enable_value = new string(prop->getStringValue()); + } + + if ( (prop = configNode->getChild( "honor-passive" )) != NULL ) { + _honor_passive = prop->getBoolValue(); + } + + return true; + } // enable + + SG_LOG( SG_AUTOPILOT, SG_BULK, "Component::configure(" << nodeName << ") [unhandled]" << endl ); + return false; +} + +bool Component::isPropertyEnabled() +{ + if( _condition ) + return _condition->test(); + + if( _enable_prop ) { + if( _enable_value ) { + return *_enable_value == _enable_prop->getStringValue(); + } else { + return _enable_prop->getBoolValue(); + } + } + return true; +} + +void Component::update( double dt ) +{ + bool firstTime = false; + if( isPropertyEnabled() ) { + firstTime = !_enabled; + _enabled = true; + } else { + _enabled = false; + } + + if( _enabled ) update( firstTime, dt ); + else disabled( dt ); +} diff --git a/src/Autopilot/component.hxx b/src/Autopilot/component.hxx new file mode 100644 index 000000000..3f8d60352 --- /dev/null +++ b/src/Autopilot/component.hxx @@ -0,0 +1,140 @@ +// component.hxx - Base class for autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __COMPONENT_HXX +#define __COMPONENT_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include + +namespace FGXMLAutopilot { + +/** + * @brief Base class for other autopilot components + */ +class Component : public SGSubsystem { + +private: + + SGSharedPtr _condition; + SGPropertyNode_ptr _enable_prop; + std::string * _enable_value; + std::string _name; + bool _enabled; + +protected: + + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + + + /** + * @brief the implementation of the update() method of the SGSubsystem + */ + virtual void update( double dt ); + + /** + * @brief pure virtual function to be implemented by the derived classes. Gets called from + * the update method if it's not disabled with the firstTime parameter set to true if this + * is the first call after being enabled + * @param firstTime set to true if this is the first update call since this component has + been enabled. Set to false for every subsequent call. + * @param dt the elapsed time since the last call + */ + virtual void update( bool firstTime, double dt ) = 0; + + /** + * @brief overideable method being called from the update() method if this component + * is disabled. It's a noop by default. + */ + virtual void disabled( double dt ) {} + + /** + * @brief debug flag, true if this component should generate some useful output + * on every iteration + */ + bool _debug; + + + /** + * @brief a (historic) flag signalling the derived class that it should compute it's internal + * state but shall not set the output properties if /autopilot/locks/passive-mode is true. + */ + bool _honor_passive; + +public: + + /** + * @brief A constructor for an empty Component. + */ + Component(); + + /** + * virtual destructor to clean up resources + */ + virtual ~Component(); + + /** + * @brief configure this component from a property node. Iterates through all nodes found + * as childs under configNode and calls configure of the derived class for each child. + * @param configNode the property node containing the configuration + */ + bool configure( SGPropertyNode_ptr configNode ); + + /** + * @brief getter for the name property + * @return the name of the component + */ + inline const std::string& get_name() const { return _name; } + + /** + * @brief setter for the name property + * @param name the name of the component + */ + inline void set_name( const std::string & name ) { _name = name; } + + /** + * @brief check if this component is enabled as configured in the + * <enable> section + * @return true if the enable-condition is true. + * + * If a <condition> is defined, this condition is evaluated, + * <prop> and <value> tags are ignored. + * + * If a <prop> is defined and no <value> is defined, the property + * named in the <prop><prop> tags is evaluated as boolean. + * + * If a <prop> is defined and a <value> is defined, the property named + * in <prop></prop> is compared (as a string) to the value defined in + * <value></value> + * + * Returns true, if neither <condition> nor <prop> exists + */ + bool isPropertyEnabled(); +}; + + +} +#endif // COMPONENT_HXX diff --git a/src/Autopilot/digitalcomponent.cxx b/src/Autopilot/digitalcomponent.cxx new file mode 100644 index 000000000..8fed619fb --- /dev/null +++ b/src/Autopilot/digitalcomponent.cxx @@ -0,0 +1,109 @@ +// digitalcomponent.cxx - Base class for digital autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "digitalcomponent.hxx" +#include
+ +using namespace FGXMLAutopilot; + +DigitalComponent::DigitalComponent() : + _inverted(false) +{ +} + +bool DigitalComponent::InputMap::get_value( const std::string & name ) const +{ + // can't use map::operator[] here since it's not const + const_iterator __i = lower_bound( name ); + if (__i == end() || key_comp()(name, (*__i).first)) + return false; // does not exist, return false + + return (*__i).second->test(); +} + +/* + + Foo + + ... + + + + Bar + /foo/bar + true + + /some/property +*/ +bool DigitalComponent::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if( Component::configure( nodeName, configNode ) ) + return true; + + if (nodeName == "input") { + SGPropertyNode_ptr nameNode = configNode->getNode("name"); + string name; + if( nameNode != NULL ) { + name = nameNode->getStringValue(); + } else { + std::ostringstream buf; + buf << "Input" << _input.size(); + name = buf.str(); + } + _input[name] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "output") { + SGPropertyNode_ptr n = configNode->getNode("name"); + string name; + if( n != NULL ) { + name = n->getStringValue(); + } else { + std::ostringstream buf; + buf << "Output" << _output.size(); + name = buf.str(); + } + + DigitalOutput_ptr o = new DigitalOutput(); + _output[name] = o; + + if( (n = configNode->getNode("inverted")) != NULL ) + o->setInverted( n->getBoolValue() ); + + if( (n = configNode->getNode("property")) != NULL ) + o->setProperty( fgGetNode( n->getStringValue(), true ) ); + + if( configNode->nChildren() == 0 ) + o->setProperty( fgGetNode( configNode->getStringValue(), true ) ); + + return true; + } + + if (nodeName == "inverted") { + _inverted = configNode->getBoolValue(); + return true; + } + + return false; +} diff --git a/src/Autopilot/digitalcomponent.hxx b/src/Autopilot/digitalcomponent.hxx new file mode 100644 index 000000000..606dd5f8b --- /dev/null +++ b/src/Autopilot/digitalcomponent.hxx @@ -0,0 +1,130 @@ +// digitalcomponent.hxx - Base class for digital autopilot components +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __DIGITALCOMPONENT_HXX +#define __DIGITALCOMPONENT_HXX 1 + +#include "component.hxx" + +namespace FGXMLAutopilot { + +/** + * @brief Models a digital output bound to a property. May be an inverted output. + */ +class DigitalOutput : public SGReferenced { + +private: + bool _inverted; + SGPropertyNode_ptr _node; + +protected: + +public: + /** + * @brief Constructs an empty, noninverting output + */ + DigitalOutput(); + + inline void setProperty( SGPropertyNode_ptr node ); + + inline void setInverted( bool value ) { _inverted = value; } + inline bool isInverted() const { return _inverted; } + + bool getValue() const; + void setValue( bool value ); +}; + +inline DigitalOutput::DigitalOutput() : _inverted(false) +{ +} + +inline void DigitalOutput::setProperty( SGPropertyNode_ptr node ) +{ + _node->setBoolValue( (_node = node)->getBoolValue() ); +} + +inline bool DigitalOutput::getValue() const +{ + if( _node == NULL ) return false; + bool nodeState = _node->getBoolValue(); + return _inverted ? !nodeState : nodeState; +} + +inline void DigitalOutput::setValue( bool value ) +{ + if( _node == NULL ) return; + _node->setBoolValue( _inverted ? !value : value ); +} + +typedef SGSharedPtr DigitalOutput_ptr; + +/** + * @brief Base class for digital autopilot components + * + * Each digital component has (at least) + *
    + *
  • one value input
  • + *
  • any number of output properties
  • + *
+ */ +class DigitalComponent : public Component { +public: + DigitalComponent(); + + class InputMap : public std::map > { + public: + bool get_value( const std::string & name ) const; + }; + + +// typedef std::map > InputMap; + typedef std::map OutputMap; +protected: + + /** + * @brief Named input "pins" + */ + InputMap _input; + + /** + * @brief Named output "pins" + */ + OutputMap _output; + + /** + * @brief Global "inverted" flag for the outputs + */ + bool _inverted; + + /** + * @brief Over-rideable hook method to allow derived classes to refine top-level + * node parsing. + * @param aName + * @param aNode + * @return true if the node was handled, false otherwise. + */ + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); +}; + +} +#endif // DIGITALCOMPONENT_HXX + diff --git a/src/Autopilot/digitalfilter.cxx b/src/Autopilot/digitalfilter.cxx new file mode 100644 index 000000000..9edf53b82 --- /dev/null +++ b/src/Autopilot/digitalfilter.cxx @@ -0,0 +1,358 @@ +// digitalfilter.cxx - a selection of digital filters +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "digitalfilter.hxx" +#include "functor.hxx" +#include + +namespace FGXMLAutopilot { + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ +class GainFilterImplementation : public DigitalFilterImplementation { +protected: + InputValueList _gainInput; + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); +public: + GainFilterImplementation() : _gainInput(1.0) {} + double compute( double dt, double input ); +}; + +class ReciprocalFilterImplementation : public GainFilterImplementation { +public: + double compute( double dt, double input ); +}; + +class DerivativeFilterImplementation : public GainFilterImplementation { + InputValueList _TfInput; + double _input_1; + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); +public: + DerivativeFilterImplementation(); + double compute( double dt, double input ); +}; + +class ExponentialFilterImplementation : public GainFilterImplementation { +protected: + InputValueList _TfInput; + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + bool _isSecondOrder; + double output_1, output_2; +public: + ExponentialFilterImplementation(); + double compute( double dt, double input ); + virtual void initialize( double output ); +}; + +class MovingAverageFilterImplementation : public DigitalFilterImplementation { +protected: + InputValueList _samplesInput; + double _output_1; + std::deque _inputQueue; + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); +public: + MovingAverageFilterImplementation(); + double compute( double dt, double input ); + virtual void initialize( double output ); +}; + +class NoiseSpikeFilterImplementation : public DigitalFilterImplementation { +protected: + double _output_1; + InputValueList _rateOfChangeInput; + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); +public: + NoiseSpikeFilterImplementation(); + double compute( double dt, double input ); + virtual void initialize( double output ); +}; + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +} // namespace FGXMLAutopilot + +using namespace FGXMLAutopilot; + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +bool DigitalFilterImplementation::configure( SGPropertyNode_ptr configNode ) +{ + for (int i = 0; i < configNode->nChildren(); ++i ) { + SGPropertyNode_ptr prop; + + SGPropertyNode_ptr child = configNode->getChild(i); + string cname(child->getName()); + + if( configure( cname, child ) ) + continue; + + } // for configNode->nChildren() + + return true; +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +double GainFilterImplementation::compute( double dt, double input ) +{ + return _gainInput.get_value() * input; +} + +bool GainFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if (nodeName == "gain" ) { + _gainInput.push_back( new InputValue( configNode, 1 ) ); + return true; + } + + return false; +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +double ReciprocalFilterImplementation::compute( double dt, double input ) +{ + if( input >= -SGLimitsd::min() || input <= SGLimitsd::min() ) + return SGLimitsd::max(); + + return _gainInput.get_value() / input; + +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +DerivativeFilterImplementation::DerivativeFilterImplementation() : + _input_1(0.0) +{ +} + +bool DerivativeFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if( GainFilterImplementation::configure( nodeName, configNode ) ) + return true; + + if (nodeName == "filter-time" ) { + _TfInput.push_back( new InputValue( configNode, 1 ) ); + return true; + } + + return false; +} + +double DerivativeFilterImplementation::compute( double dt, double input ) +{ + double output = (input - _input_1) * _TfInput.get_value() * _gainInput.get_value() / dt; + _input_1 = input; + return output; + +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +MovingAverageFilterImplementation::MovingAverageFilterImplementation() : + _output_1(0.0) +{ +} + +void MovingAverageFilterImplementation::initialize( double output ) +{ + _output_1 = output; +} + +double MovingAverageFilterImplementation::compute( double dt, double input ) +{ + std::deque::size_type samples = _samplesInput.get_value(); + _inputQueue.resize(samples+1, 0.0); + + double output_0 = _output_1 + (input - _inputQueue.back()) / samples; + + _output_1 = output_0; + _inputQueue.push_front(input); + return output_0; +} + +bool MovingAverageFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if (nodeName == "samples" ) { + _samplesInput.push_back( new InputValue( configNode, 1 ) ); + return true; + } + + return false; +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +NoiseSpikeFilterImplementation::NoiseSpikeFilterImplementation() : + _output_1(0.0) +{ +} + +void NoiseSpikeFilterImplementation::initialize( double output ) +{ + _output_1 = output; +} + +double NoiseSpikeFilterImplementation::compute( double dt, double input ) +{ + double maxChange = _rateOfChangeInput.get_value() * dt; + + double output_0 = _output_1; + + if (_output_1 - input > maxChange) { + output_0 = _output_1 - maxChange; + } else if( _output_1 - input < -maxChange ) { + output_0 = _output_1 + maxChange; + } else if (fabs(input - _output_1) <= maxChange) { + output_0 = input; + } + _output_1 = output_0; + return output_0; +} + +bool NoiseSpikeFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if (nodeName == "max-rate-of-change" ) { + _rateOfChangeInput.push_back( new InputValue( configNode, 1 ) ); + return true; + } + + return false; +} + +/* --------------------------------------------------------------------------------- */ +/* --------------------------------------------------------------------------------- */ + +ExponentialFilterImplementation::ExponentialFilterImplementation() + : _isSecondOrder(false), + output_1(0.0), + output_2(0.0) +{ +} + +void ExponentialFilterImplementation::initialize( double output ) +{ + output_1 = output_2 = output; +} + +double ExponentialFilterImplementation::compute( double dt, double input ) +{ + input = GainFilterImplementation::compute( dt, input ); + + double output_0; + double alpha = 1 / ((_TfInput.get_value()/dt) + 1); + + if(_isSecondOrder) { + output_0 = alpha * alpha * input + + 2 * (1 - alpha) * output_1 - + (1 - alpha) * (1 - alpha) * output_2; + } else { + output_0 = alpha * input + (1 - alpha) * output_1; + } + output_2 = output_1; + return (output_1 = output_0); +} + +bool ExponentialFilterImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if( GainFilterImplementation::configure( nodeName, configNode ) ) + return true; + + if (nodeName == "filter-time" ) { + _TfInput.push_back( new InputValue( configNode, 1 ) ); + return true; + } + + if (nodeName == "type" ) { + string type(configNode->getStringValue()); + _isSecondOrder = type == "double-exponential"; + } + + return false; +} + +/* --------------------------------------------------------------------------------- */ +/* Digital Filter Component Implementation */ +/* --------------------------------------------------------------------------------- */ + +DigitalFilter::DigitalFilter() : + AnalogComponent() +{ +} + +static map *> componentForge; + +bool DigitalFilter::configure(const string& nodeName, SGPropertyNode_ptr configNode) +{ + if( componentForge.empty() ) { + componentForge["gain"] = new CreateAndConfigureFunctor(); + componentForge["exponential"] = new CreateAndConfigureFunctor(); + componentForge["double-exponential"] = new CreateAndConfigureFunctor(); + componentForge["moving-average"] = new CreateAndConfigureFunctor(); + componentForge["noise-spike"] = new CreateAndConfigureFunctor(); + componentForge["reciprocal"] = new CreateAndConfigureFunctor(); + componentForge["derivative"] = new CreateAndConfigureFunctor(); + } + + SG_LOG( SG_AUTOPILOT, SG_BULK, "DigitalFilter::configure(" << nodeName << ")" << endl ); + if( AnalogComponent::configure( nodeName, configNode ) ) + return true; + + if (nodeName == "type" ) { + string type( configNode->getStringValue() ); + if( componentForge.count(type) == 0 ) { + SG_LOG( SG_AUTOPILOT, SG_BULK, "unhandled filter type <" << type << ">" << endl ); + return true; + } + _implementation = (*componentForge[type])( configNode->getParent() ); + return true; + } + + SG_LOG( SG_AUTOPILOT, SG_BULK, "DigitalFilter::configure(" << nodeName << ") [unhandled]" << endl ); + return false; // not handled by us, let the base class try +} + +void DigitalFilter::update( bool firstTime, double dt) +{ + if( _implementation == NULL ) return; + + if( firstTime ) + _implementation->initialize( get_output_value() ); + + double input = _valueInput.get_value() - _referenceInput.get_value(); + double output = _implementation->compute( dt, input ); + + set_output_value( output ); + + if(_debug) { + cout << "input:" << input + << "\toutput:" << output << endl; + } +} diff --git a/src/Autopilot/digitalfilter.hxx b/src/Autopilot/digitalfilter.hxx new file mode 100644 index 000000000..4bc37a904 --- /dev/null +++ b/src/Autopilot/digitalfilter.hxx @@ -0,0 +1,72 @@ +// digitalfilter.hxx - a selection of digital filters +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __DIGITALFILTER_HXX +#define __DIGITALFILTER_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "analogcomponent.hxx" + +namespace FGXMLAutopilot { + +/** + * + * + */ +class DigitalFilterImplementation : public SGReferenced { +protected: + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode) = 0; +public: + virtual void initialize( double output ) {} + virtual double compute( double dt, double input ) = 0; + bool configure( SGPropertyNode_ptr configNode ); +}; + +/** + * brief@ DigitalFilter - a selection of digital filters + * + */ +class DigitalFilter : public AnalogComponent +{ +private: + SGSharedPtr _implementation; + +protected: + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode); + void update( bool firstTime, double dt); + + InputValueList _Tf; + InputValueList _samples; + InputValueList _rateOfChange; + InputValueList _gain; + +public: + DigitalFilter(); + ~DigitalFilter() {} + +}; + +} // namespace FGXMLAutopilot +#endif diff --git a/src/Autopilot/flipflop.cxx b/src/Autopilot/flipflop.cxx new file mode 100644 index 000000000..076b2db48 --- /dev/null +++ b/src/Autopilot/flipflop.cxx @@ -0,0 +1,469 @@ +// flipflop.hxx - implementation of multiple flip flop types +// +// Written by Torsten Dreyer +// +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "flipflop.hxx" +#include "functor.hxx" +#include "inputvalue.hxx" +#include
+ +namespace FGXMLAutopilot { + +/** + * @brief Flip flop implementation for a RS flip flop with dominant RESET + * + * RS (reset-set) flip flops act as a fundamental latch. It has two input lines, + * S (set) and R (reset). Activating the set input sets the output while activating + * the reset input resets the output. If both inputs are activated, the output + * is deactivated, too. This is why the RESET line is called dominant. Use a + * SRFlipFlopImplementation for a dominant SET line. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Logictable
SRQ
falsefalseunchanged
falsetruefalse
truefalsetrue
truetruefalse
+ */ +class RSFlipFlopImplementation : public FlipFlopImplementation { +protected: + bool _rIsDominant; +public: + RSFlipFlopImplementation( bool rIsDominant = true ) : _rIsDominant( rIsDominant ) {} + virtual bool getState( double dt, DigitalComponent::InputMap input, bool & q ); +}; + +/** + * @brief Flip flop implementation for a RS flip flop with dominant SET + * + * SR (set-reset) flip flops act as a fundamental latch. It has two input lines, + * S (set) and R (reset). Activating the set input sets the output while activating + * the reset input resets the output. If both inputs are activated, the output + * is activated, too. This is why the SET line is called dominant. Use a + * RSFlipFlopImplementation for a dominant RESET line. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Logictable
SRQ
falsefalseunchanged
falsetruefalse
truefalsetrue
truetruetrue
+ */ +class SRFlipFlopImplementation : public RSFlipFlopImplementation { +public: + SRFlipFlopImplementation() : RSFlipFlopImplementation( false ) {} +}; + +/** + * @brief Base class for clocked flip flop implementation + * + * A clocked flip flop computes it's output on the raising edge (false/true transition) + * of the clock input. If such a transition is detected, the onRaisingEdge method is called + * by this implementation. All clocked flip flops inherit from the RS flip flop and may + * be set or reset by the respective set/reset lines. Note that the RS implementation + * ignores the clock, The output is set immediately, regardless of the state of the clock + * input. The "clock" input is mandatory for clocked flip flops. + * + */ +class ClockedFlipFlopImplementation : public RSFlipFlopImplementation { +private: + /** + * @brief the previous state of the clock input + */ + bool _clock; +protected: + + /** + * @brief pure virtual function to be implemented from the implementing class, gets called + * from the update method if the raising edge of the clock input was detected. + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool onRaisingEdge( DigitalComponent::InputMap input, bool & q ) = 0; +public: + + /** + * @brief constructor for a ClockedFlipFlopImplementation + * @param rIsDominant boolean flag to signal if RESET shall be dominant (true) or SET shall be dominant (false) + */ + ClockedFlipFlopImplementation( bool rIsDominant = true ) : RSFlipFlopImplementation( rIsDominant ), _clock(false) {} + + /** + * @brief evaluates the output state from the input lines. + * This method basically waits for a raising edge and calls onRaisingEdge + * @param dt the elapsed time in seconds from since the last call + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool getState( double dt, DigitalComponent::InputMap input, bool & q ); +}; + +/** + * @brief Implements a JK flip flop as a clocked flip flop + * + * The JK flip flop has five input lines: R, S, clock, J and K. The R and S lines work as described + * in the RS flip flop. Setting the J line to true sets the output to true on the next raising + * edge of the clock line. Setting the K line to true sets the output to false on the next raising + * edge of the clock line. If both, J and K are true, the output is toggled at with every raising + * edge of the clock line. + * + * Undefined inputs default to false. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Logictable
SRJKclockQ (previous)Q
falsefalsefalsefalseanyanyunchanged
truefalseanyanyanyanytrue
anytrueanyanyanyanyfalse
falsefalsetruefalse^anytrue
falsefalsefalsetrue^anyfalse
falsefalsetruetrue^falsetrue
falsefalsetruetrue^truefalse
+ */ +class JKFlipFlopImplementation : public ClockedFlipFlopImplementation { +public: + /** + * @brief constructor for a JKFlipFlopImplementation + * @param rIsDominant boolean flag to signal if RESET shall be dominant (true) or SET shall be dominant (false) + */ + JKFlipFlopImplementation( bool rIsDominant = true ) : ClockedFlipFlopImplementation ( rIsDominant ) {} + + /** + * @brief compute the output state according to the logic table on the raising edge of the clock + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool onRaisingEdge( DigitalComponent::InputMap input, bool & q ); +}; + +/** + * @brief Implements a D (delay) flip flop. + * + */ +class DFlipFlopImplementation : public ClockedFlipFlopImplementation { +public: + /** + * @brief constructor for a DFlipFlopImplementation + * @param rIsDominant boolean flag to signal if RESET shall be dominant (true) or SET shall be dominant (false) + */ + DFlipFlopImplementation( bool rIsDominant = true ) : ClockedFlipFlopImplementation ( rIsDominant ) {} + + /** + * @brief compute the output state according to the logic table on the raising edge of the clock + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool onRaisingEdge( DigitalComponent::InputMap input, bool & q ) { + q = input.get_value("D"); + return true; + } +}; + +/** + * @brief Implements a T (toggle) flip flop. + * + */ +class TFlipFlopImplementation : public ClockedFlipFlopImplementation { +public: + /** + * @brief constructor for a TFlipFlopImplementation + * @param rIsDominant boolean flag to signal if RESET shall be dominant (true) or SET shall be dominant (false) + */ + TFlipFlopImplementation( bool rIsDominant = true ) : ClockedFlipFlopImplementation ( rIsDominant ) {} + + /** + * @brief compute the output state according to the logic table on the raising edge of the clock + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool onRaisingEdge( DigitalComponent::InputMap input, bool & q ) { + q = !q; + return true; + } +}; + +/** + * @brief Implements a monostable flip flop + * + * The stable output state is false. + * + */ +class MonoFlopImplementation : public JKFlipFlopImplementation { +protected: + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + InputValueList _time; + double _t; +public: + /** + * @brief constructor for a MonoFlopImplementation + * @param rIsDominant boolean flag to signal if RESET shall be dominant (true) or SET shall be dominant (false) + */ + MonoFlopImplementation( bool rIsDominant = true ) : JKFlipFlopImplementation( rIsDominant ) {} + /** + * @brief evaluates the output state from the input lines and returns to the stable state + * after expiry of the internal timer + * @param dt the elapsed time in seconds from since the last call + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool getState( double dt, DigitalComponent::InputMap input, bool & q ); +}; + +} // namespace + +using namespace FGXMLAutopilot; + +bool MonoFlopImplementation::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if( JKFlipFlopImplementation::configure( nodeName, configNode ) ) + return true; + + if (nodeName == "time") { + _time.push_back( new InputValue( configNode ) ); + return true; + } + + return false; +} + +bool MonoFlopImplementation::getState( double dt, DigitalComponent::InputMap input, bool & q ) +{ + if( JKFlipFlopImplementation::getState( dt, input, q ) ) { + _t = q ? _time.get_value() : 0; + return true; + } + + _t -= dt; + if( _t <= 0.0 ) { + q = 0; + return true; + } + + return false; +} + + +bool RSFlipFlopImplementation::getState( double dt, DigitalComponent::InputMap input, bool & q ) +{ + bool s = input.get_value("S"); + bool r = input.get_value("R"); + + // s == false && q == false: no change, keep state + if( s || r ) { + if( _rIsDominant ) { // RS: reset is dominant + if( s ) q = true; // set + if( r ) q = false; // reset + } else { // SR: set is dominant + if( r ) q = false; // reset + if( s ) q = true; // set + } + return true; // signal state changed + } + return false; // signal state unchagned +} + +bool ClockedFlipFlopImplementation::getState( double dt, DigitalComponent::InputMap input, bool & q ) +{ + bool c = input.get_value("clock"); + bool raisingEdge = c && !_clock; + + _clock = c; + + if( RSFlipFlopImplementation::getState( dt, input, q ) ) + return true; + + + if( !raisingEdge ) return false; //signal no change + return onRaisingEdge( input, q ); +} + +bool JKFlipFlopImplementation::onRaisingEdge( DigitalComponent::InputMap input, bool & q ) +{ + bool j = input.get_value("J"); + bool k = input.get_value("K"); + + // j == false && k == false: no change, keep state + if( (j || k) ) { + if( j && k ) { + q = !q; // toggle + } else { + if( j ) q = true; // set + if( k ) q = false; // reset + } + return true; // signal state changed + } + + return false; // signal no change +} + +bool FlipFlopImplementation::configure( SGPropertyNode_ptr configNode ) +{ + for (int i = 0; i < configNode->nChildren(); ++i ) { + SGPropertyNode_ptr prop; + + SGPropertyNode_ptr child = configNode->getChild(i); + string cname(child->getName()); + + if( configure( cname, child ) ) + continue; + + } // for configNode->nChildren() + + return true; +} + + +static map *> componentForge; + +bool FlipFlop::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + if( componentForge.empty() ) { + componentForge["RS"] = new CreateAndConfigureFunctor(); + componentForge["SR"] = new CreateAndConfigureFunctor(); + componentForge["JK"] = new CreateAndConfigureFunctor(); + componentForge["D"] = new CreateAndConfigureFunctor(); + componentForge["T"] = new CreateAndConfigureFunctor(); + componentForge["monostable"] = new CreateAndConfigureFunctor(); + } + + if( DigitalComponent::configure( nodeName, configNode ) ) + return true; + + if( nodeName == "type" ) { + string type(configNode->getStringValue()); + if( componentForge.count(type) == 0 ) { + SG_LOG( SG_AUTOPILOT, SG_BULK, "unhandled flip-flop type <" << type << ">" << endl ); + return true; + } + _implementation = (*componentForge[type])( configNode->getParent() ); + return true; + } + + if (nodeName == "set"||nodeName == "S") { + _input["S"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "reset" || nodeName == "R" ) { + _input["R"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "J") { + _input["J"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "K") { + _input["K"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "D") { + _input["D"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + if (nodeName == "clock") { + _input["clock"] = sgReadCondition( fgGetNode("/"), configNode ); + return true; + } + + return false; +} + +void FlipFlop::update( bool firstTime, double dt ) +{ + if( _implementation == NULL ) { + SG_LOG( SG_AUTOPILOT, SG_ALERT, "No flip-flop implementation for " << get_name() << endl ); + return; + } + + bool q0, q; + + q0 = q = get_output(); + + if( _implementation->getState( dt, _input, q ) && q0 != q ) { + set_output( q ); + + if(_debug) { + cout << "updating flip-flop \"" << get_name() << "\"" << endl; + cout << "prev. Output:" << q0 << endl; + for( InputMap::const_iterator it = _input.begin(); it != _input.end(); it++ ) + cout << "Input \"" << (*it).first << "\":" << (*it).second->test() << endl; + cout << "new Output:" << q << endl; + } + } +} + + diff --git a/src/Autopilot/flipflop.hxx b/src/Autopilot/flipflop.hxx new file mode 100644 index 000000000..dfdb38252 --- /dev/null +++ b/src/Autopilot/flipflop.hxx @@ -0,0 +1,92 @@ +// flipflop.hxx - implementation of multiple flip flop types +// +// Written by Torsten Dreyer +// +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __FLIPFLOPCOMPONENT_HXX +#define __FLIPFLOPCOMPONENT_HXX 1 + +#include "logic.hxx" + +namespace FGXMLAutopilot { + +/** + * @brief Interface for a flip flop implementation. Can be configured from a property node and + * returns a state depending on input lines. + */ +class FlipFlopImplementation : public SGReferenced { +protected: + /** + * @brief configure this component from a property node. Iterates through all nodes found + * as childs under configNode and calls configure of the derived class for each child. + * @param configNode the property node containing the configuration + */ + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) { return false; } +public: + /** + * @brief evaluates the output state from the input lines + * @param dt the elapsed time in seconds from since the last call + * @param input a map of named input lines + * @param q a reference to a boolean variable to receive the output state + * @return true if the state has changed, false otherwise + */ + virtual bool getState( double dt, DigitalComponent::InputMap input, bool & q ) { return false; } + + /** + * @brief configure this component from a property node. Iterates through all nodes found + * as childs under configNode and calls configure of the derived class for each child. + * @param configNode the property node containing the configuration + */ + bool configure( SGPropertyNode_ptr configNode ); +}; + +/** + * @brief A simple flipflop implementation + */ +class FlipFlop : public Logic { +public: +protected: + /** + * @brief Over-rideable hook method to allow derived classes to refine top-level + * node parsing. + * @param aName + * @param aNode + * @return true if the node was handled, false otherwise. + */ + virtual bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + + /** + * @brief Implementation of the pure virtual function of the Component class. Gets called from + * the update method if it's not disabled with the firstTime parameter set to true if this + * is the first call after being enabled + * @param firstTime set to true if this is the first update call since this component has + been enabled. Set to false for every subsequent call. + * @param dt the elapsed time since the last call + */ + void update( bool firstTime, double dt ); + +private: + /** + * @brief Pointer to the actual flip flop implementation + */ + SGSharedPtr _implementation; + +}; + +} +#endif // FLIPFLOPCOMPONENT_HXX diff --git a/src/Autopilot/functor.hxx b/src/Autopilot/functor.hxx new file mode 100644 index 000000000..b68b683c3 --- /dev/null +++ b/src/Autopilot/functor.hxx @@ -0,0 +1,50 @@ +// functor.hxx - a utility to create object based on names +// +// Written by Torsten Dreyer +// +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __FUNCTOR_HXX +#define __FUNCTOR_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +namespace FGXMLAutopilot { + +template class FunctorBase { +public: + virtual TBase * operator()( SGPropertyNode_ptr configNode ) = 0; +}; + +template class CreateAndConfigureFunctor : + public FunctorBase, + SGReferenced { +public: + virtual TBase * operator()( SGPropertyNode_ptr configNode ) { + TBase * base = new TClass(); + base->configure( configNode ); + return base; + } +}; + +} + +#endif // __FUNCTOR_HXX 1 diff --git a/src/Autopilot/inputvalue.cxx b/src/Autopilot/inputvalue.cxx new file mode 100644 index 000000000..fb80263c1 --- /dev/null +++ b/src/Autopilot/inputvalue.cxx @@ -0,0 +1,202 @@ +// inputvalue.hxx - provide input to autopilot components +// +// Written by Torsten Dreyer +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "inputvalue.hxx" +#include
+using namespace FGXMLAutopilot; + +PeriodicalValue::PeriodicalValue( SGPropertyNode_ptr root ) +{ + SGPropertyNode_ptr minNode = root->getChild( "min" ); + SGPropertyNode_ptr maxNode = root->getChild( "max" ); + if( minNode == NULL || maxNode == NULL ) { + SG_LOG(SG_AUTOPILOT, SG_ALERT, "periodical defined, but no and/or tag. Period ignored." ); + } else { + minPeriod = new InputValue( minNode ); + maxPeriod = new InputValue( maxNode ); + } +} + +double PeriodicalValue::normalize( double value ) +{ + if( !(minPeriod && maxPeriod )) return value; + + double p1 = minPeriod->get_value(); + double p2 = maxPeriod->get_value(); + + double min = std::min(p1,p2); + double max = std::max(p1,p2); + double phase = fabs(max - min); + + if( phase > SGLimitsd::min() ) { + while( value < min ) value += phase; + while( value >= max ) value -= phase; + } else { + value = min; // phase is zero + } + + return value; +} + +InputValue::InputValue( SGPropertyNode_ptr node, double value, double offset, double scale) : + _value(0.0), + _abs(false) +{ + parse( node, value, offset, scale ); +} + + +void InputValue::parse( SGPropertyNode_ptr node, double aValue, double aOffset, double aScale ) +{ + _value = aValue; + _property = NULL; + _offset = NULL; + _scale = NULL; + _min = NULL; + _max = NULL; + _periodical = NULL; + + if( node == NULL ) + return; + + SGPropertyNode * n; + + if( (n = node->getChild("condition")) != NULL ) { + _condition = sgReadCondition(fgGetNode("/"), n); + } + + if( (n = node->getChild( "scale" )) != NULL ) { + _scale = new InputValue( n, aScale ); + } + + if( (n = node->getChild( "offset" )) != NULL ) { + _offset = new InputValue( n, aOffset ); + } + + if( (n = node->getChild( "max" )) != NULL ) { + _max = new InputValue( n ); + } + + if( (n = node->getChild( "min" )) != NULL ) { + _min = new InputValue( n ); + } + + if( (n = node->getChild( "abs" )) != NULL ) { + _abs = n->getBoolValue(); + } + + if( (n = node->getChild( "period" )) != NULL ) { + _periodical = new PeriodicalValue( n ); + } + + SGPropertyNode *valueNode = node->getChild( "value" ); + if ( valueNode != NULL ) { + _value = valueNode->getDoubleValue(); + } + + if ((n = node->getChild("expression")) != NULL) { + _expression = SGReadDoubleExpression(fgGetNode("/"), n->getChild(0)); + return; + } + + n = node->getChild( "property" ); + // if no element, check for element for backwards + // compatibility + if( n == NULL ) + n = node->getChild( "prop" ); + + if ( n != NULL ) { + _property = fgGetNode( n->getStringValue(), true ); + if ( valueNode != NULL ) { + // initialize property with given value + // if both and exist + double s = get_scale(); + if( s != 0 ) + _property->setDoubleValue( (_value - get_offset())/s ); + else + _property->setDoubleValue( 0 ); // if scale is zero, value*scale is zero + } + + return; + } // of have a or + + + if (valueNode == NULL) { + // no , or element, use text node + const char * textnode = node->getStringValue(); + char * endp = NULL; + // try to convert to a double value. If the textnode does not start with a number + // endp will point to the beginning of the string. We assume this should be + // a property name + _value = strtod( textnode, &endp ); + if( endp == textnode ) { + _property = fgGetNode( textnode, true ); + } + } +} + +void InputValue::set_value( double aValue ) +{ + if (!_property) + return; + + double s = get_scale(); + if( s != 0 ) + _property->setDoubleValue( (aValue - get_offset())/s ); + else + _property->setDoubleValue( 0 ); // if scale is zero, value*scale is zero +} + +double InputValue::get_value() const +{ + double value = _value; + + if (_expression) { + // compute the expression value + value = _expression->getValue(NULL); + } else if( _property != NULL ) { + value = _property->getDoubleValue(); + } + + if( _scale ) + value *= _scale->get_value(); + + if( _offset ) + value += _offset->get_value(); + + if( _min ) { + double m = _min->get_value(); + if( value < m ) + value = m; + } + + if( _max ) { + double m = _max->get_value(); + if( value > m ) + value = m; + } + + if( _periodical ) { + value = _periodical->normalize( value ); + } + + return _abs ? fabs(value) : value; +} + diff --git a/src/Autopilot/inputvalue.hxx b/src/Autopilot/inputvalue.hxx new file mode 100644 index 000000000..bdf0b6382 --- /dev/null +++ b/src/Autopilot/inputvalue.hxx @@ -0,0 +1,127 @@ +// inputvalue.hxx - provide input to autopilot components +// +// Written by Torsten Dreyer +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#ifndef _INPUTVALUE_HXX +#define _INPUTVALUE_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + + +#include + +namespace FGXMLAutopilot { + +typedef SGSharedPtr InputValue_ptr; +typedef SGSharedPtr PeriodicalValue_ptr; + +/** + * @brief Model a periodical value like angular values + * + * Most common use for periodical values are angular values. + * If y = f(x) = f(x + n*period), this is a periodical function + */ +class PeriodicalValue : public SGReferenced { +private: + InputValue_ptr minPeriod; // The minimum value of the period + InputValue_ptr maxPeriod; // The maximum value of the period +public: + PeriodicalValue( SGPropertyNode_ptr node ); + double normalize( double value ); +}; + +/** + * @brief A input value for analog autopilot components + * + * Input values may be constants, property values, transformed with a scale + * and/or offset, clamped to min/max values, be periodical, bound to + * conditions or evaluated from expressions. + */ +class InputValue : public SGReferenced { +private: + double _value; // The value as a constant or initializer for the property + bool _abs; // return absolute value + SGPropertyNode_ptr _property; // The name of the property containing the value + InputValue_ptr _offset; // A fixed offset, defaults to zero + InputValue_ptr _scale; // A constant scaling factor defaults to one + InputValue_ptr _min; // A minimum clip defaults to no clipping + InputValue_ptr _max; // A maximum clip defaults to no clipping + PeriodicalValue_ptr _periodical; // + SGSharedPtr _condition; + SGSharedPtr _expression; ///< expression to generate the value + +public: + InputValue( SGPropertyNode_ptr node = NULL, double value = 0.0, double offset = 0.0, double scale = 1.0 ); + + void parse( SGPropertyNode_ptr, double value = 0.0, double offset = 0.0, double scale = 1.0 ); + + /* get the value of this input, apply scale and offset and clipping */ + double get_value() const; + + /* set the input value after applying offset and scale */ + void set_value( double value ); + + inline double get_scale() const { + return _scale == NULL ? 1.0 : _scale->get_value(); + } + + inline double get_offset() const { + return _offset == NULL ? 0.0 : _offset->get_value(); + } + + inline bool is_enabled() const { + return _condition == NULL ? true : _condition->test(); + } + +}; + +/** + * @brief A chained list of InputValues + * + * Many compoments support InputValueLists as input. Each InputValue may be bound to + * a condition. This list supports the get_value() function to retrieve the value + * of the first InputValue in this list that has a condition evaluating to true. + */ +class InputValueList : public std::vector { + public: + InputValueList( double def = 0.0 ) : _def(def) { } + + InputValue_ptr get_active() const { + for (const_iterator it = begin(); it != end(); ++it) { + if( (*it)->is_enabled() ) + return *it; + } + return NULL; + } + + double get_value() const { + InputValue_ptr input = get_active(); + return input == NULL ? _def : input->get_value(); + } + private: + + double _def; + +}; + +} + +#endif diff --git a/src/Autopilot/logic.cxx b/src/Autopilot/logic.cxx new file mode 100644 index 000000000..83270427d --- /dev/null +++ b/src/Autopilot/logic.cxx @@ -0,0 +1,63 @@ +// logic.cxx - Base class for logic components +// +// Written by Torsten Dreyer +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +// for some obscure reason, MSVC needs this to compile +#ifdef _MSC_VER +#ifndef HAVE_CONFIG_H +# include +#endif +#include +#endif + +#include "logic.hxx" + +using namespace FGXMLAutopilot; + +bool Logic::get_input() const +{ + // return state of first configured condition + InputMap::const_iterator it = _input.begin(); + if( it == _input.end() ) return false; // no inputs? + return (*it).second->test(); +} + +void Logic::set_output( bool value ) +{ + // respect global inverted flag + if( _inverted ) value = !value; + + // set all outputs to the given value + for( OutputMap::iterator it = _output.begin(); it != _output.end(); it++ ) + (*it).second->setValue( value ); +} + +bool Logic::get_output() const +{ + OutputMap::const_iterator it = _output.begin(); + bool q = it != _output.end() ? (*it).second->getValue() : false; + return _inverted ? !q : q; +} + +void Logic::update( bool firstTime, double dt ) +{ + set_output( get_input() ); +} + diff --git a/src/Autopilot/logic.hxx b/src/Autopilot/logic.hxx new file mode 100644 index 000000000..44add3a43 --- /dev/null +++ b/src/Autopilot/logic.hxx @@ -0,0 +1,46 @@ +// logic.hxx - Base class for logic components +// +// Written by Torsten Dreyer +// +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __LOGICCOMPONENT_HXX +#define __LOGICCOMPONENT_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "digitalcomponent.hxx" + +namespace FGXMLAutopilot { + +/** + * @brief A simple logic class writing <condition> to a property + */ +class Logic : public DigitalComponent { +public: + bool get_input() const; + void set_output( bool value ); + bool get_output() const; +protected: + void update( bool firstTime, double dt ); +}; + +} +#endif // LOGICCOMPONENT_HXX + diff --git a/src/Autopilot/pidcontroller.cxx b/src/Autopilot/pidcontroller.cxx new file mode 100644 index 000000000..1ad027460 --- /dev/null +++ b/src/Autopilot/pidcontroller.cxx @@ -0,0 +1,246 @@ +// pidcontroller.cxx - implementation of PID controller +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "pidcontroller.hxx" + +using namespace FGXMLAutopilot; + +PIDController::PIDController(): + AnalogComponent(), + alpha( 0.1 ), + beta( 1.0 ), + gamma( 0.0 ), + ep_n_1( 0.0 ), + edf_n_1( 0.0 ), + edf_n_2( 0.0 ), + u_n_1( 0.0 ), + desiredTs( 0.0 ), + elapsedTime( 0.0 ) +{ +} + +/* + * Roy Vegard Ovesen: + * + * Ok! Here is the PID controller algorithm that I would like to see + * implemented: + * + * delta_u_n = Kp * [ (ep_n - ep_n-1) + ((Ts/Ti)*e_n) + * + (Td/Ts)*(edf_n - 2*edf_n-1 + edf_n-2) ] + * + * u_n = u_n-1 + delta_u_n + * + * where: + * + * delta_u : The incremental output + * Kp : Proportional gain + * ep : Proportional error with reference weighing + * ep = beta * r - y + * where: + * beta : Weighing factor + * r : Reference (setpoint) + * y : Process value, measured + * e : Error + * e = r - y + * Ts : Sampling interval + * Ti : Integrator time + * Td : Derivator time + * edf : Derivate error with reference weighing and filtering + * edf_n = edf_n-1 / ((Ts/Tf) + 1) + ed_n * (Ts/Tf) / ((Ts/Tf) + 1) + * where: + * Tf : Filter time + * Tf = alpha * Td , where alpha usually is set to 0.1 + * ed : Unfiltered derivate error with reference weighing + * ed = gamma * r - y + * where: + * gamma : Weighing factor + * + * u : absolute output + * + * Index n means the n'th value. + * + * + * Inputs: + * enabled , + * y_n , r_n , beta=1 , gamma=0 , alpha=0.1 , + * Kp , Ti , Td , Ts (is the sampling time available?) + * u_min , u_max + * + * Output: + * u_n + */ + +void PIDController::update( bool firstTime, double dt ) +{ + double edf_n = 0.0; + double delta_u_n = 0.0; // incremental output + double u_n = 0.0; // absolute output + + double u_min = _minInput.get_value(); + double u_max = _maxInput.get_value(); + + elapsedTime += dt; + if( elapsedTime <= desiredTs ) { + // do nothing if time step is not positive (i.e. no time has + // elapsed) + return; + } + double Ts = elapsedTime; // sampling interval (sec) + elapsedTime = 0.0; + + if( firstTime ) { + // first time being enabled, seed u_n with current + // property tree value + ep_n_1 = 0.0; + edf_n_2 = edf_n_1 = edf_n = 0.0; + u_n = get_output_value(); + u_n_1 = u_n; + } + + if( Ts > SGLimitsd::min()) { + if( _debug ) cout << "Updating " << get_name() + << " Ts " << Ts << endl; + + double y_n = _valueInput.get_value(); + double r_n = _referenceInput.get_value(); + + if ( _debug ) cout << " input = " << y_n << " ref = " << r_n << endl; + + // Calculates proportional error: + double ep_n = beta * r_n - y_n; + if ( _debug ) cout << " ep_n = " << ep_n; + if ( _debug ) cout << " ep_n_1 = " << ep_n_1; + + // Calculates error: + double e_n = r_n - y_n; + if ( _debug ) cout << " e_n = " << e_n; + + double td = Td.get_value(); + if ( td > 0.0 ) { // do we need to calcluate derivative error? + + // Calculates derivate error: + double ed_n = gamma * r_n - y_n; + if ( _debug ) cout << " ed_n = " << ed_n; + + // Calculates filter time: + double Tf = alpha * td; + if ( _debug ) cout << " Tf = " << Tf; + + // Filters the derivate error: + edf_n = edf_n_1 / (Ts/Tf + 1) + + ed_n * (Ts/Tf) / (Ts/Tf + 1); + if ( _debug ) cout << " edf_n = " << edf_n; + } else { + edf_n_2 = edf_n_1 = edf_n = 0.0; + } + + // Calculates the incremental output: + double ti = Ti.get_value(); + if ( ti > 0.0 ) { + delta_u_n = Kp.get_value() * ( (ep_n - ep_n_1) + + ((Ts/ti) * e_n) + + ((td/Ts) * (edf_n - 2*edf_n_1 + edf_n_2)) ); + + if ( _debug ) { + cout << " delta_u_n = " << delta_u_n << endl; + cout << "P:" << Kp.get_value() * (ep_n - ep_n_1) + << " I:" << Kp.get_value() * ((Ts/ti) * e_n) + << " D:" << Kp.get_value() * ((td/Ts) * (edf_n - 2*edf_n_1 + edf_n_2)) + << endl; + } + } + + // Integrator anti-windup logic: + if ( delta_u_n > (u_max - u_n_1) ) { + delta_u_n = u_max - u_n_1; + if ( _debug ) cout << " max saturation " << endl; + } else if ( delta_u_n < (u_min - u_n_1) ) { + delta_u_n = u_min - u_n_1; + if ( _debug ) cout << " min saturation " << endl; + } + + // Calculates absolute output: + u_n = u_n_1 + delta_u_n; + if ( _debug ) cout << " output = " << u_n << endl; + + // Updates indexed values; + u_n_1 = u_n; + ep_n_1 = ep_n; + edf_n_2 = edf_n_1; + edf_n_1 = edf_n; + + set_output_value( u_n ); + } +} + +bool PIDController::configure( const std::string & nodeName, SGPropertyNode_ptr configNode ) +{ + SG_LOG( SG_AUTOPILOT, SG_BULK, "PIDController::configure(" << nodeName << ")" << endl ); + + if( AnalogComponent::configure( nodeName, configNode ) ) + return true; + + if( nodeName == "config" ) { + Component::configure( configNode ); + return true; + } + + if (nodeName == "Ts") { + desiredTs = configNode->getDoubleValue(); + return true; + } + + if (nodeName == "Kp") { + Kp.push_back( new InputValue(configNode) ); + return true; + } + + if (nodeName == "Ti") { + Ti.push_back( new InputValue(configNode) ); + return true; + } + + if (nodeName == "Td") { + Td.push_back( new InputValue(configNode) ); + return true; + } + + if (nodeName == "beta") { + beta = configNode->getDoubleValue(); + return true; + } + + if (nodeName == "alpha") { + alpha = configNode->getDoubleValue(); + return true; + } + + if (nodeName == "gamma") { + gamma = configNode->getDoubleValue(); + return true; + } + + SG_LOG( SG_AUTOPILOT, SG_BULK, "PIDController::configure(" << nodeName << ") [unhandled]" << endl ); + return false; +} + diff --git a/src/Autopilot/pidcontroller.hxx b/src/Autopilot/pidcontroller.hxx new file mode 100644 index 000000000..da69a7389 --- /dev/null +++ b/src/Autopilot/pidcontroller.hxx @@ -0,0 +1,74 @@ +// pidcontroller.hxx - implementation of PID controller +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __PIDCONTROLLER_HXX +#define __PIDCONTROLLER_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "analogcomponent.hxx" + +#include +#include + +namespace FGXMLAutopilot { + +/** + * Roy Ovesen's PID controller + */ +class PIDController : public AnalogComponent { + +private: + // Configuration values + InputValueList Kp; // proportional gain + InputValueList Ti; // Integrator time (sec) + InputValueList Td; // Derivator time (sec) + + double alpha; // low pass filter weighing factor (usually 0.1) + double beta; // process value weighing factor for + // calculating proportional error + // (usually 1.0) + double gamma; // process value weighing factor for + // calculating derivative error + // (usually 0.0) + + // Previous state tracking values + double ep_n_1; // ep[n-1] (prop error) + double edf_n_1; // edf[n-1] (derivative error) + double edf_n_2; // edf[n-2] (derivative error) + double u_n_1; // u[n-1] (output) + double desiredTs; // desired sampling interval (sec) + double elapsedTime; // elapsed time (sec) + +protected: + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode); +public: + PIDController(); + ~PIDController() {} + + void update( bool firstTime, double dt ); +}; + +} +#endif // __PIDCONTROLLER_HXX diff --git a/src/Autopilot/pisimplecontroller.cxx b/src/Autopilot/pisimplecontroller.cxx new file mode 100644 index 000000000..b19633adf --- /dev/null +++ b/src/Autopilot/pisimplecontroller.cxx @@ -0,0 +1,88 @@ +// pisimplecontroller.cxx - implementation of a simple PI controller +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "pisimplecontroller.hxx" + +using namespace FGXMLAutopilot; + +PISimpleController::PISimpleController() : + AnalogComponent(), + _int_sum( 0.0 ) +{ +} + +bool PISimpleController::configure( const string& nodeName, SGPropertyNode_ptr configNode) +{ + if( AnalogComponent::configure( nodeName, configNode ) ) + return true; + + if( nodeName == "config" ) { + Component::configure( configNode ); + return true; + } + + if (nodeName == "Kp") { + _Kp.push_back( new InputValue(configNode) ); + return true; + } + + if (nodeName == "Ki") { + _Ki.push_back( new InputValue(configNode) ); + return true; + } + + return false; +} + +void PISimpleController::update( bool firstTime, double dt ) +{ + if ( firstTime ) { + // we have just been enabled, zero out int_sum + _int_sum = 0.0; + } + + if ( _debug ) cout << "Updating " << get_name() << endl; + double y_n = _valueInput.get_value(); + double r_n = _referenceInput.get_value(); + + double error = r_n - y_n; + if ( _debug ) cout << "input = " << y_n + << " reference = " << r_n + << " error = " << error + << endl; + + double prop_comp = clamp(error * _Kp.get_value()); + _int_sum += error * _Ki.get_value() * dt; + + + double output = prop_comp + _int_sum; + double clamped_output = clamp( output ); + if( output != clamped_output ) // anti-windup + _int_sum = clamped_output - prop_comp; + + if ( _debug ) cout << "prop_comp = " << prop_comp + << " int_sum = " << _int_sum << endl; + + set_output_value( clamped_output ); + if ( _debug ) cout << "output = " << clamped_output << endl; +} diff --git a/src/Autopilot/pisimplecontroller.hxx b/src/Autopilot/pisimplecontroller.hxx new file mode 100644 index 000000000..06dcb01a2 --- /dev/null +++ b/src/Autopilot/pisimplecontroller.hxx @@ -0,0 +1,64 @@ +// pisimplecontroller.hxx - implementation of a simple PI controller +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __PISIMPLECONTROLLER_HXX +#define __PISIMPLECONTROLLER_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "analogcomponent.hxx" + +#include +#include + +namespace FGXMLAutopilot { + +/** + * A simplistic P [ + I ] PI controller + */ +class PISimpleController : public AnalogComponent { + +private: + + // proportional component data + InputValueList _Kp; + + // integral component data + InputValueList _Ki; + double _int_sum; + +protected: + bool configure( const std::string & nodeName, SGPropertyNode_ptr configNode ); + +public: + + PISimpleController(); + ~PISimpleController() {} + + void update( bool firstTime, double dt ); +}; + +} + +#endif diff --git a/src/Autopilot/predictor.cxx b/src/Autopilot/predictor.cxx new file mode 100644 index 000000000..fe16d14db --- /dev/null +++ b/src/Autopilot/predictor.cxx @@ -0,0 +1,81 @@ +// predictor.cxx - predict future values +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// + +#include "predictor.hxx" + +#ifdef SG_BULK +#undef SG_BULK +#endif +#define SG_BULK SG_ALERT +#ifdef SG_INFO +#undef SG_INFO +#endif +#define SG_INFO SG_ALERT + +using namespace FGXMLAutopilot; + +Predictor::Predictor () : + AnalogComponent(), + _average(0.0) +{ +} + +bool Predictor::configure(const string& nodeName, SGPropertyNode* configNode) +{ + SG_LOG( SG_AUTOPILOT, SG_BULK, "Predictor::configure(" << nodeName << ")" << endl ); + if (nodeName == "seconds") { + _seconds.push_back( new InputValue( configNode, 0 ) ); + return true; + } + + if (nodeName == "filter-gain") { + _filter_gain.push_back( new InputValue( configNode, 0 ) ); + return true; + } + + SG_LOG( SG_AUTOPILOT, SG_BULK, "Predictor::configure(" << nodeName << ") [unhandled]" << endl ); + return false; +} + +void Predictor::update( bool firstTime, double dt ) +{ + double ivalue = _valueInput.get_value(); + + if ( firstTime ) { + _last_value = ivalue; + } + + double current = (ivalue - _last_value)/dt; // calculate current error change (per second) + _average = dt < 1.0 ? ((1.0 - dt) * _average + current * dt) : current; + + // calculate output with filter gain adjustment + double output = ivalue + + (1.0 - _filter_gain.get_value()) * (_average * _seconds.get_value()) + + _filter_gain.get_value() * (current * _seconds.get_value()); + output = clamp( output ); + set_output_value( output ); + + _last_value = ivalue; +} + + diff --git a/src/Autopilot/predictor.hxx b/src/Autopilot/predictor.hxx new file mode 100644 index 000000000..5418b337f --- /dev/null +++ b/src/Autopilot/predictor.hxx @@ -0,0 +1,67 @@ +// predictor.hxx - predict future values +// +// Written by Torsten Dreyer +// Based heavily on work created by Curtis Olson, started January 2004. +// +// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt +// Copyright (C) 2010 Torsten Dreyer - Torsten (at) t3r (dot) de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef __PREDICTOR_HXX +#define __PREDICTOR_HXX 1 + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "analogcomponent.hxx" + +#include + +namespace FGXMLAutopilot { + +/** + * @brief Simple moving average filter converts input value to predicted value "seconds". + * + * Smoothing as described by Curt Olson: + * gain would be valid in the range of 0 - 1.0 + * 1.0 would mean no filtering. + * 0.0 would mean no input. + * 0.5 would mean (1 part past value + 1 part current value) / 2 + * 0.1 would mean (9 parts past value + 1 part current value) / 10 + * 0.25 would mean (3 parts past value + 1 part current value) / 4 + */ +class Predictor : public AnalogComponent { + +private: + double _last_value; + double _average; + InputValueList _seconds; + InputValueList _filter_gain; + +protected: + bool configure(const std::string& nodeName, SGPropertyNode* configNode ); + +public: + Predictor(); + ~Predictor() {} + + void update( bool firstTime, double dt ); +}; + +} // namespace FGXMLAutopilot + +#endif diff --git a/src/Autopilot/route_mgr.cxx b/src/Autopilot/route_mgr.cxx index 967ca992a..07059cc16 100644 --- a/src/Autopilot/route_mgr.cxx +++ b/src/Autopilot/route_mgr.cxx @@ -51,20 +51,8 @@ #include "Airports/simple.hxx" #include "Airports/runways.hxx" -#include "FDM/flight.hxx" // for getting ground speed - #define RM "/autopilot/route-manager/" -static double get_ground_speed() { - // starts in ft/s so we convert to kts - static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up"); - - double ft_s = cur_fdm_state->get_V_ground_speed() - * speedup_node->getIntValue(); - double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM; - return kts; -} - FGRouteMgr::FGRouteMgr() : _route( new SGRoute ), input(fgGetNode( RM "input", true )), @@ -212,7 +200,7 @@ void FGRouteMgr::update( double dt ) { return; } - double groundSpeed = get_ground_speed(); + double groundSpeed = fgGetDouble("/velocities/groundspeed-kt", 0.0); if (airborne->getBoolValue()) { time_t now = time(NULL); elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime)); @@ -265,14 +253,14 @@ void FGRouteMgr::update( double dt ) { void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance) { - double speed = get_ground_speed(); + double speed =fgGetDouble("/velocities/groundspeed-kt", 0.0); if (speed < 1.0) { aProp->setStringValue("--:--"); return; } char eta_str[64]; - double eta = aDistance * SG_METER_TO_NM / get_ground_speed(); + double eta = aDistance * SG_METER_TO_NM / speed; if ( eta >= 100.0 ) { eta = 99.999; // clamp } diff --git a/src/Autopilot/xmlauto.cxx b/src/Autopilot/xmlauto.cxx deleted file mode 100644 index fe51f37b1..000000000 --- a/src/Autopilot/xmlauto.cxx +++ /dev/null @@ -1,1136 +0,0 @@ -// xmlauto.cxx - a more flexible, generic way to build autopilots -// -// Written by Curtis Olson, started January 2004. -// -// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include - -#include -#include -#include -#include - -#include
-#include
-#include
- -#include "xmlauto.hxx" - -using std::cout; -using std::endl; - -using simgear::PropertyList; - -FGPeriodicalValue::FGPeriodicalValue( SGPropertyNode_ptr root ) -{ - SGPropertyNode_ptr minNode = root->getChild( "min" ); - SGPropertyNode_ptr maxNode = root->getChild( "max" ); - if( minNode == NULL || maxNode == NULL ) { - SG_LOG(SG_AUTOPILOT, SG_ALERT, "periodical defined, but no and/or tag. Period ignored." ); - } else { - minPeriod = new FGXMLAutoInput( minNode ); - maxPeriod = new FGXMLAutoInput( maxNode ); - } -} - -double FGPeriodicalValue::normalize( double value ) -{ - if( !(minPeriod && maxPeriod )) return value; - - double p1 = minPeriod->get_value(); - double p2 = maxPeriod->get_value(); - - double min = std::min(p1,p2); - double max = std::max(p1,p2); - double phase = fabs(max - min); - - if( phase > SGLimitsd::min() ) { - while( value < min ) value += phase; - while( value >= max ) value -= phase; - } else { - value = min; // phase is zero - } - - return value; -} - -FGXMLAutoInput::FGXMLAutoInput( SGPropertyNode_ptr node, double value, double offset, double scale) : - value(0.0), - abs(false), - _condition(NULL) -{ - parse( node, value, offset, scale ); -} - - -void FGXMLAutoInput::parse( SGPropertyNode_ptr node, double aValue, double aOffset, double aScale ) -{ - value = aValue; - property = NULL; - offset = NULL; - scale = NULL; - min = NULL; - max = NULL; - periodical = NULL; - - if( node == NULL ) - return; - - SGPropertyNode * n; - - if( (n = node->getChild("condition")) != NULL ) { - _condition = sgReadCondition(fgGetNode("/"), n); - } - - if( (n = node->getChild( "scale" )) != NULL ) { - scale = new FGXMLAutoInput( n, aScale ); - } - - if( (n = node->getChild( "offset" )) != NULL ) { - offset = new FGXMLAutoInput( n, aOffset ); - } - - if( (n = node->getChild( "max" )) != NULL ) { - max = new FGXMLAutoInput( n ); - } - - if( (n = node->getChild( "min" )) != NULL ) { - min = new FGXMLAutoInput( n ); - } - - if( (n = node->getChild( "abs" )) != NULL ) { - abs = n->getBoolValue(); - } - - if( (n = node->getChild( "period" )) != NULL ) { - periodical = new FGPeriodicalValue( n ); - } - - SGPropertyNode *valueNode = node->getChild( "value" ); - if ( valueNode != NULL ) { - value = valueNode->getDoubleValue(); - } - - n = node->getChild( "property" ); - // if no element, check for element for backwards - // compatibility - if( n == NULL ) - n = node->getChild( "prop" ); - - if ( n != NULL ) { - property = fgGetNode( n->getStringValue(), true ); - if ( valueNode != NULL ) { - // initialize property with given value - // if both and exist - double s = get_scale(); - if( s != 0 ) - property->setDoubleValue( (value - get_offset())/s ); - else - property->setDoubleValue( 0 ); // if scale is zero, value*scale is zero - } - } - - if ( n == NULL && valueNode == NULL ) { - // no element and no element, use text node - const char * textnode = node->getStringValue(); - char * endp = NULL; - // try to convert to a double value. If the textnode does not start with a number - // endp will point to the beginning of the string. We assume this should be - // a property name - value = strtod( textnode, &endp ); - if( endp == textnode ) { - property = fgGetNode( textnode, true ); - } - } -} - -void FGXMLAutoInput::set_value( double aValue ) -{ - double s = get_scale(); - if( s != 0 ) - property->setDoubleValue( (aValue - get_offset())/s ); - else - property->setDoubleValue( 0 ); // if scale is zero, value*scale is zero -} - -double FGXMLAutoInput::get_value() -{ - if( property != NULL ) - value = property->getDoubleValue(); - - if( scale ) - value *= scale->get_value(); - - if( offset ) - value += offset->get_value(); - - if( min ) { - double m = min->get_value(); - if( value < m ) - value = m; - } - - if( max ) { - double m = max->get_value(); - if( value > m ) - value = m; - } - - if( periodical ) { - value = periodical->normalize( value ); - } - - return abs ? fabs(value) : value; -} - -FGXMLAutoComponent::FGXMLAutoComponent() : - _condition( NULL ), - enable_prop( NULL ), - enable_value( NULL ), - passive_mode( fgGetNode("/autopilot/locks/passive-mode", true) ), - honor_passive( false ), - name(""), - feedback_if_disabled( false ), - debug(false), - enabled( false ) -{ -} - -FGXMLAutoComponent::~FGXMLAutoComponent() -{ - delete enable_value; -} - -void FGXMLAutoComponent::parseNode(SGPropertyNode* aNode) -{ - SGPropertyNode *prop; - for (int i = 0; i < aNode->nChildren(); ++i ) { - SGPropertyNode *child = aNode->getChild(i); - string cname(child->getName()); - - if (parseNodeHook(cname, child)) { - // derived class handled it, fine - } else if ( cname == "name" ) { - name = child->getStringValue(); - } else if ( cname == "feedback-if-disabled" ) { - feedback_if_disabled = child->getBoolValue(); - } else if ( cname == "debug" ) { - debug = child->getBoolValue(); - } else if ( cname == "enable" ) { - if( (prop = child->getChild("condition")) != NULL ) { - _condition = sgReadCondition(fgGetNode("/"), prop); - } else { - if ( (prop = child->getChild( "prop" )) != NULL ) { - enable_prop = fgGetNode( prop->getStringValue(), true ); - } - - if ( (prop = child->getChild( "value" )) != NULL ) { - delete enable_value; - enable_value = new string(prop->getStringValue()); - } - } - if ( (prop = child->getChild( "honor-passive" )) != NULL ) { - honor_passive = prop->getBoolValue(); - } - } else if ( cname == "input" ) { - valueInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "reference" ) { - referenceInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "output" ) { - // grab all and childs - int found = 0; - // backwards compatibility: allow elements - for( int i = 0; (prop = child->getChild("prop", i)) != NULL; i++ ) { - SGPropertyNode *tmp = fgGetNode( prop->getStringValue(), true ); - output_list.push_back( tmp ); - found++; - } - for( int i = 0; (prop = child->getChild("property", i)) != NULL; i++ ) { - SGPropertyNode *tmp = fgGetNode( prop->getStringValue(), true ); - output_list.push_back( tmp ); - found++; - } - - // no elements, text node of is property name - if( found == 0 ) - output_list.push_back( fgGetNode(child->getStringValue(), true ) ); - } else if ( cname == "config" ) { - parseConfig(child); - } else if ( cname == "min" ) { - uminInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "u_min" ) { - uminInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "max" ) { - umaxInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "u_max" ) { - umaxInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "period" ) { - periodical = new FGPeriodicalValue( child ); - } else { - SG_LOG(SG_AUTOPILOT, SG_ALERT, "malformed autopilot definition - unrecognized node:" - << cname << " in section " << name); - throw sg_io_exception("XMLAuto: unrecognized component node:" + cname, "Section=" + name); - } - } // of top-level iteration -} - -void FGXMLAutoComponent::parseConfig(SGPropertyNode* aConfig) -{ - for (int i = 0; i < aConfig->nChildren(); ++i ) { - SGPropertyNode *child = aConfig->getChild(i); - string cname(child->getName()); - - if (parseConfigHook(cname, child)) { - // derived class handled it, fine - } else if ( cname == "min" ) { - uminInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "u_min" ) { - uminInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "max" ) { - umaxInput.push_back( new FGXMLAutoInput( child ) ); - } else if ( cname == "u_max" ) { - umaxInput.push_back( new FGXMLAutoInput( child ) ); - } else { - SG_LOG(SG_AUTOPILOT, SG_ALERT, "malformed autopilot definition - unrecognized config node:" - << cname << " in section " << name); - throw sg_io_exception("XMLAuto: unrecognized config node:" + cname, "Section=" + name); - } - } // of config iteration -} - -bool FGXMLAutoComponent::parseNodeHook(const string& aName, SGPropertyNode* aNode) -{ - return false; -} - -bool FGXMLAutoComponent::parseConfigHook(const string& aName, SGPropertyNode* aNode) -{ - return false; -} - -bool FGXMLAutoComponent::isPropertyEnabled() -{ - if( _condition ) - return _condition->test(); - - if( enable_prop ) { - if( enable_value ) { - return *enable_value == enable_prop->getStringValue(); - } else { - return enable_prop->getBoolValue(); - } - } - return true; -} - -void FGXMLAutoComponent::do_feedback_if_disabled() -{ - if( output_list.size() > 0 ) { - FGXMLAutoInput * input = valueInput.get_active(); - if( input != NULL ) - input->set_value( output_list[0]->getDoubleValue() ); - } -} - -double FGXMLAutoComponent::clamp( double value ) -{ - //If this is a periodical value, normalize it into our domain - // before clamping - if( periodical ) - value = periodical->normalize( value ); - - // clamp, if either min or max is defined - if( uminInput.size() + umaxInput.size() > 0 ) { - double d = umaxInput.get_value( 0.0 ); - if( value > d ) value = d; - d = uminInput.get_value( 0.0 ); - if( value < d ) value = d; - } - return value; -} - -FGPIDController::FGPIDController( SGPropertyNode *node ): - FGXMLAutoComponent(), - alpha( 0.1 ), - beta( 1.0 ), - gamma( 0.0 ), - ep_n_1( 0.0 ), - edf_n_1( 0.0 ), - edf_n_2( 0.0 ), - u_n_1( 0.0 ), - desiredTs( 0.0 ), - elapsedTime( 0.0 ) -{ - parseNode(node); -} - -bool FGPIDController::parseConfigHook(const string& aName, SGPropertyNode* aNode) -{ - if (aName == "Ts") { - desiredTs = aNode->getDoubleValue(); - } else if (aName == "Kp") { - Kp.push_back( new FGXMLAutoInput(aNode) ); - } else if (aName == "Ti") { - Ti.push_back( new FGXMLAutoInput(aNode) ); - } else if (aName == "Td") { - Td.push_back( new FGXMLAutoInput(aNode) ); - } else if (aName == "beta") { - beta = aNode->getDoubleValue(); - } else if (aName == "alpha") { - alpha = aNode->getDoubleValue(); - } else if (aName == "gamma") { - gamma = aNode->getDoubleValue(); - } else { - // unhandled by us, let the base class try it - return false; - } - - return true; -} - -/* - * Roy Vegard Ovesen: - * - * Ok! Here is the PID controller algorithm that I would like to see - * implemented: - * - * delta_u_n = Kp * [ (ep_n - ep_n-1) + ((Ts/Ti)*e_n) - * + (Td/Ts)*(edf_n - 2*edf_n-1 + edf_n-2) ] - * - * u_n = u_n-1 + delta_u_n - * - * where: - * - * delta_u : The incremental output - * Kp : Proportional gain - * ep : Proportional error with reference weighing - * ep = beta * r - y - * where: - * beta : Weighing factor - * r : Reference (setpoint) - * y : Process value, measured - * e : Error - * e = r - y - * Ts : Sampling interval - * Ti : Integrator time - * Td : Derivator time - * edf : Derivate error with reference weighing and filtering - * edf_n = edf_n-1 / ((Ts/Tf) + 1) + ed_n * (Ts/Tf) / ((Ts/Tf) + 1) - * where: - * Tf : Filter time - * Tf = alpha * Td , where alpha usually is set to 0.1 - * ed : Unfiltered derivate error with reference weighing - * ed = gamma * r - y - * where: - * gamma : Weighing factor - * - * u : absolute output - * - * Index n means the n'th value. - * - * - * Inputs: - * enabled , - * y_n , r_n , beta=1 , gamma=0 , alpha=0.1 , - * Kp , Ti , Td , Ts (is the sampling time available?) - * u_min , u_max - * - * Output: - * u_n - */ - -void FGPIDController::update( double dt ) { - double e_n; // error - double edf_n; - double delta_u_n = 0.0; // incremental output - double u_n = 0.0; // absolute output - double Ts; // sampling interval (sec) - - double u_min = uminInput.get_value(); - double u_max = umaxInput.get_value(); - - elapsedTime += dt; - if ( elapsedTime <= desiredTs ) { - // do nothing if time step is not positive (i.e. no time has - // elapsed) - return; - } - Ts = elapsedTime; - elapsedTime = 0.0; - - if ( isPropertyEnabled() ) { - if ( !enabled ) { - // first time being enabled, seed u_n with current - // property tree value - u_n = get_output_value(); - u_n_1 = u_n; - } - enabled = true; - } else { - enabled = false; - do_feedback(); - } - - if ( enabled && Ts > 0.0) { - if ( debug ) cout << "Updating " << get_name() - << " Ts " << Ts << endl; - - double y_n = valueInput.get_value(); - double r_n = referenceInput.get_value(); - - if ( debug ) cout << " input = " << y_n << " ref = " << r_n << endl; - - // Calculates proportional error: - double ep_n = beta * r_n - y_n; - if ( debug ) cout << " ep_n = " << ep_n; - if ( debug ) cout << " ep_n_1 = " << ep_n_1; - - // Calculates error: - e_n = r_n - y_n; - if ( debug ) cout << " e_n = " << e_n; - - double td = Td.get_value(); - if ( td > 0.0 ) { // do we need to calcluate derivative error? - - // Calculates derivate error: - double ed_n = gamma * r_n - y_n; - if ( debug ) cout << " ed_n = " << ed_n; - - // Calculates filter time: - double Tf = alpha * td; - if ( debug ) cout << " Tf = " << Tf; - - // Filters the derivate error: - edf_n = edf_n_1 / (Ts/Tf + 1) - + ed_n * (Ts/Tf) / (Ts/Tf + 1); - if ( debug ) cout << " edf_n = " << edf_n; - } else { - edf_n_2 = edf_n_1 = edf_n = 0.0; - } - - // Calculates the incremental output: - double ti = Ti.get_value(); - if ( ti > 0.0 ) { - delta_u_n = Kp.get_value() * ( (ep_n - ep_n_1) - + ((Ts/ti) * e_n) - + ((td/Ts) * (edf_n - 2*edf_n_1 + edf_n_2)) ); - - if ( debug ) { - cout << " delta_u_n = " << delta_u_n << endl; - cout << "P:" << Kp.get_value() * (ep_n - ep_n_1) - << " I:" << Kp.get_value() * ((Ts/ti) * e_n) - << " D:" << Kp.get_value() * ((td/Ts) * (edf_n - 2*edf_n_1 + edf_n_2)) - << endl; - } - } - - // Integrator anti-windup logic: - if ( delta_u_n > (u_max - u_n_1) ) { - delta_u_n = u_max - u_n_1; - if ( debug ) cout << " max saturation " << endl; - } else if ( delta_u_n < (u_min - u_n_1) ) { - delta_u_n = u_min - u_n_1; - if ( debug ) cout << " min saturation " << endl; - } - - // Calculates absolute output: - u_n = u_n_1 + delta_u_n; - if ( debug ) cout << " output = " << u_n << endl; - - // Updates indexed values; - u_n_1 = u_n; - ep_n_1 = ep_n; - edf_n_2 = edf_n_1; - edf_n_1 = edf_n; - - set_output_value( u_n ); - } else if ( !enabled ) { - ep_n_1 = 0.0; - edf_n_2 = edf_n_1 = edf_n = 0.0; - } -} - - -FGPISimpleController::FGPISimpleController( SGPropertyNode *node ): - FGXMLAutoComponent(), - int_sum( 0.0 ) -{ - parseNode(node); -} - -bool FGPISimpleController::parseConfigHook(const string& aName, SGPropertyNode* aNode) -{ - if (aName == "Kp") { - Kp.push_back( new FGXMLAutoInput(aNode) ); - } else if (aName == "Ki") { - Ki.push_back( new FGXMLAutoInput(aNode) ); - } else { - // unhandled by us, let the base class try it - return false; - } - - return true; -} - -void FGPISimpleController::update( double dt ) { - - if ( isPropertyEnabled() ) { - if ( !enabled ) { - // we have just been enabled, zero out int_sum - int_sum = 0.0; - } - enabled = true; - } else { - enabled = false; - do_feedback(); - } - - if ( enabled ) { - if ( debug ) cout << "Updating " << get_name() << endl; - double y_n = valueInput.get_value(); - double r_n = referenceInput.get_value(); - - double error = r_n - y_n; - if ( debug ) cout << "input = " << y_n - << " reference = " << r_n - << " error = " << error - << endl; - - double prop_comp = clamp(error * Kp.get_value()); - int_sum += error * Ki.get_value() * dt; - - - double output = prop_comp + int_sum; - double clamped_output = clamp( output ); - if( output != clamped_output ) // anti-windup - int_sum = clamped_output - prop_comp; - - if ( debug ) cout << "prop_comp = " << prop_comp - << " int_sum = " << int_sum << endl; - - set_output_value( clamped_output ); - if ( debug ) cout << "output = " << clamped_output << endl; - } -} - - -FGPredictor::FGPredictor ( SGPropertyNode *node ): - FGXMLAutoComponent(), - average(0.0) -{ - parseNode(node); -} - -bool FGPredictor::parseNodeHook(const string& aName, SGPropertyNode* aNode) -{ - if (aName == "seconds") { - seconds.push_back( new FGXMLAutoInput( aNode, 0 ) ); - } else if (aName == "filter-gain") { - filter_gain.push_back( new FGXMLAutoInput( aNode, 0 ) ); - } else { - return false; - } - - return true; -} - -void FGPredictor::update( double dt ) { - /* - Simple moving average filter converts input value to predicted value "seconds". - - Smoothing as described by Curt Olson: - gain would be valid in the range of 0 - 1.0 - 1.0 would mean no filtering. - 0.0 would mean no input. - 0.5 would mean (1 part past value + 1 part current value) / 2 - 0.1 would mean (9 parts past value + 1 part current value) / 10 - 0.25 would mean (3 parts past value + 1 part current value) / 4 - - */ - - double ivalue = valueInput.get_value(); - - if ( isPropertyEnabled() ) { - if ( !enabled ) { - // first time being enabled - last_value = ivalue; - } - enabled = true; - } else { - enabled = false; - do_feedback(); - } - - if ( enabled ) { - - if ( dt > 0.0 ) { - double current = (ivalue - last_value)/dt; // calculate current error change (per second) - average = dt < 1.0 ? ((1.0 - dt) * average + current * dt) : current; - - // calculate output with filter gain adjustment - double output = ivalue + - (1.0 - filter_gain.get_value()) * (average * seconds.get_value()) + - filter_gain.get_value() * (current * seconds.get_value()); - output = clamp( output ); - set_output_value( output ); - } - last_value = ivalue; - } -} - - -FGDigitalFilter::FGDigitalFilter(SGPropertyNode *node): - FGXMLAutoComponent(), - filterType(none) -{ - parseNode(node); - - output.resize(2, 0.0); - input.resize(samplesInput.get_value() + 1, 0.0); -} - - -bool FGDigitalFilter::parseNodeHook(const string& aName, SGPropertyNode* aNode) -{ - if (aName == "type" ) { - string val(aNode->getStringValue()); - if ( val == "exponential" ) { - filterType = exponential; - } else if (val == "double-exponential") { - filterType = doubleExponential; - } else if (val == "moving-average") { - filterType = movingAverage; - } else if (val == "noise-spike") { - filterType = noiseSpike; - } else if (val == "gain") { - filterType = gain; - } else if (val == "reciprocal") { - filterType = reciprocal; - } else if (val == "differential") { - filterType = differential; - // use a constant of two samples for current and previous input value - samplesInput.push_back( new FGXMLAutoInput(NULL, 2.0 ) ); - } - } else if (aName == "filter-time" ) { - TfInput.push_back( new FGXMLAutoInput( aNode, 1.0 ) ); - if( filterType == none ) filterType = exponential; - } else if (aName == "samples" ) { - samplesInput.push_back( new FGXMLAutoInput( aNode, 1 ) ); - if( filterType == none ) filterType = movingAverage; - } else if (aName == "max-rate-of-change" ) { - rateOfChangeInput.push_back( new FGXMLAutoInput( aNode, 1 ) ); - if( filterType == none ) filterType = noiseSpike; - } else if (aName == "gain" ) { - gainInput.push_back( new FGXMLAutoInput( aNode, 1 ) ); - if( filterType == none ) filterType = gain; - } else { - return false; // not handled by us, let the base class try - } - - return true; -} - -void FGDigitalFilter::update(double dt) -{ - if ( isPropertyEnabled() ) { - - input.push_front(valueInput.get_value()-referenceInput.get_value()); - input.resize(samplesInput.get_value() + 1, 0.0); - - if ( !enabled ) { - // first time being enabled, initialize output to the - // value of the output property to avoid bumping. - output.push_front(get_output_value()); - } - - enabled = true; - } else { - enabled = false; - do_feedback(); - } - - if ( !enabled || dt < SGLimitsd::min() ) - return; - - /* - * Exponential filter - * - * Output[n] = alpha*Input[n] + (1-alpha)*Output[n-1] - * - */ - if( debug ) cout << "Updating " << get_name() - << " dt " << dt << endl; - - if (filterType == exponential) - { - double alpha = 1 / ((TfInput.get_value()/dt) + 1); - output.push_front(alpha * input[0] + - (1 - alpha) * output[0]); - } - else if (filterType == doubleExponential) - { - double alpha = 1 / ((TfInput.get_value()/dt) + 1); - output.push_front(alpha * alpha * input[0] + - 2 * (1 - alpha) * output[0] - - (1 - alpha) * (1 - alpha) * output[1]); - } - else if (filterType == movingAverage) - { - output.push_front(output[0] + - (input[0] - input.back()) / samplesInput.get_value()); - } - else if (filterType == noiseSpike) - { - double maxChange = rateOfChangeInput.get_value() * dt; - - if ((output[0] - input[0]) > maxChange) - { - output.push_front(output[0] - maxChange); - } - else if ((output[0] - input[0]) < -maxChange) - { - output.push_front(output[0] + maxChange); - } - else if (fabs(input[0] - output[0]) <= maxChange) - { - output.push_front(input[0]); - } - } - else if (filterType == gain) - { - output[0] = gainInput.get_value() * input[0]; - } - else if (filterType == reciprocal) - { - if (input[0] != 0.0) { - output[0] = gainInput.get_value() / input[0]; - } - } - else if (filterType == differential) - { - if( dt > SGLimitsd::min() ) { - output[0] = (input[0]-input[1]) * TfInput.get_value() / dt; - } - } - - output[0] = clamp(output[0]) ; - set_output_value( output[0] ); - - output.resize(2); - - if (debug) - { - cout << "input:" << input[0] - << "\toutput:" << output[0] << endl; - } -} - -FGXMLAutoLogic::FGXMLAutoLogic(SGPropertyNode * node ) : - FGXMLAutoComponent(), - inverted(false) -{ - parseNode(node); -} - -bool FGXMLAutoLogic::parseNodeHook(const std::string& aName, SGPropertyNode* aNode) -{ - if (aName == "input") { - input = sgReadCondition( fgGetNode("/"), aNode ); - } else if (aName == "inverted") { - inverted = aNode->getBoolValue(); - } else { - return false; - } - - return true; -} - -void FGXMLAutoLogic::update(double dt) -{ - if ( isPropertyEnabled() ) { - if ( !enabled ) { - // we have just been enabled - } - enabled = true; - } else { - enabled = false; - do_feedback(); - } - - if ( !enabled || dt < SGLimitsd::min() ) - return; - - if( input == NULL ) { - if ( debug ) cout << "No input for " << get_name() << endl; - return; - } - - bool i = input->test(); - - if ( debug ) cout << "Updating " << get_name() << ": " << (inverted ? !i : i) << endl; - - set_output_value( i ); -} - - -FGXMLAutopilotGroup::FGXMLAutopilotGroup() : - SGSubsystemGroup() -#ifdef XMLAUTO_USEHELPER - ,average(0.0), // average/filtered prediction - v_last(0.0), // last velocity - last_static_pressure(0.0), - vel(fgGetNode( "/velocities/airspeed-kt", true )), - // Estimate speed in 5,10 seconds - lookahead5(fgGetNode( "/autopilot/internal/lookahead-5-sec-airspeed-kt", true )), - lookahead10(fgGetNode( "/autopilot/internal/lookahead-10-sec-airspeed-kt", true )), - bug(fgGetNode( "/autopilot/settings/heading-bug-deg", true )), - mag_hdg(fgGetNode( "/orientation/heading-magnetic-deg", true )), - bug_error(fgGetNode( "/autopilot/internal/heading-bug-error-deg", true )), - fdm_bug_error(fgGetNode( "/autopilot/internal/fdm-heading-bug-error-deg", true )), - target_true(fgGetNode( "/autopilot/settings/true-heading-deg", true )), - true_hdg(fgGetNode( "/orientation/heading-deg", true )), - true_error(fgGetNode( "/autopilot/internal/true-heading-error-deg", true )), - target_nav1(fgGetNode( "/instrumentation/nav[0]/radials/target-auto-hdg-deg", true )), - true_nav1(fgGetNode( "/autopilot/internal/nav1-heading-error-deg", true )), - true_track_nav1(fgGetNode( "/autopilot/internal/nav1-track-error-deg", true )), - nav1_course_error(fgGetNode( "/autopilot/internal/nav1-course-error", true )), - nav1_selected_course(fgGetNode( "/instrumentation/nav[0]/radials/selected-deg", true )), - vs_fps(fgGetNode( "/velocities/vertical-speed-fps", true )), - vs_fpm(fgGetNode( "/autopilot/internal/vert-speed-fpm", true )), - static_pressure(fgGetNode( "/systems/static[0]/pressure-inhg", true )), - pressure_rate(fgGetNode( "/autopilot/internal/pressure-rate", true )), - track(fgGetNode( "/orientation/track-deg", true )) -#endif -{ -} - -void FGXMLAutopilotGroup::update( double dt ) -{ - // update all configured autopilots - SGSubsystemGroup::update( dt ); -#ifdef XMLAUTO_USEHELPER - // update helper values - double v = vel->getDoubleValue(); - double a = 0.0; - if ( dt > 0.0 ) { - a = (v - v_last) / dt; - - if ( dt < 1.0 ) { - average = (1.0 - dt) * average + dt * a; - } else { - average = a; - } - - lookahead5->setDoubleValue( v + average * 5.0 ); - lookahead10->setDoubleValue( v + average * 10.0 ); - v_last = v; - } - - // Calculate heading bug error normalized to +/- 180.0 - double diff = bug->getDoubleValue() - mag_hdg->getDoubleValue(); - SG_NORMALIZE_RANGE(diff, -180.0, 180.0); - bug_error->setDoubleValue( diff ); - - fdm_bug_error->setDoubleValue( diff ); - - // Calculate true heading error normalized to +/- 180.0 - diff = target_true->getDoubleValue() - true_hdg->getDoubleValue(); - SG_NORMALIZE_RANGE(diff, -180.0, 180.0); - true_error->setDoubleValue( diff ); - - // Calculate nav1 target heading error normalized to +/- 180.0 - diff = target_nav1->getDoubleValue() - true_hdg->getDoubleValue(); - SG_NORMALIZE_RANGE(diff, -180.0, 180.0); - true_nav1->setDoubleValue( diff ); - - // Calculate true groundtrack - diff = target_nav1->getDoubleValue() - track->getDoubleValue(); - SG_NORMALIZE_RANGE(diff, -180.0, 180.0); - true_track_nav1->setDoubleValue( diff ); - - // Calculate nav1 selected course error normalized to +/- 180.0 - diff = nav1_selected_course->getDoubleValue() - mag_hdg->getDoubleValue(); - SG_NORMALIZE_RANGE( diff, -180.0, 180.0 ); - nav1_course_error->setDoubleValue( diff ); - - // Calculate vertical speed in fpm - vs_fpm->setDoubleValue( vs_fps->getDoubleValue() * 60.0 ); - - - // Calculate static port pressure rate in [inhg/s]. - // Used to determine vertical speed. - if ( dt > 0.0 ) { - double current_static_pressure = static_pressure->getDoubleValue(); - double current_pressure_rate = - ( current_static_pressure - last_static_pressure ) / dt; - - pressure_rate->setDoubleValue(current_pressure_rate); - last_static_pressure = current_static_pressure; - } -#endif -} - -void FGXMLAutopilotGroup::reinit() -{ - for( vector::size_type i = 0; i < _autopilotNames.size(); i++ ) { - FGXMLAutopilot * ap = (FGXMLAutopilot*)get_subsystem( _autopilotNames[i] ); - if( ap == NULL ) continue; // ? - remove_subsystem( _autopilotNames[i] ); - delete ap; - } - _autopilotNames.clear(); - init(); -} - -void FGXMLAutopilotGroup::init() -{ - PropertyList autopilotNodes = fgGetNode( "/sim/systems", true )->getChildren("autopilot"); - if( autopilotNodes.size() == 0 ) { - SG_LOG( SG_ALL, SG_WARN, "No autopilot configuration specified for this model!"); - return; - } - - for( PropertyList::size_type i = 0; i < autopilotNodes.size(); i++ ) { - SGPropertyNode_ptr pathNode = autopilotNodes[i]->getNode( "path" ); - if( pathNode == NULL ) { - SG_LOG( SG_ALL, SG_WARN, "No autopilot configuration file specified for this autopilot!"); - continue; - } - - string apName; - SGPropertyNode_ptr nameNode = autopilotNodes[i]->getNode( "name" ); - if( nameNode != NULL ) { - apName = nameNode->getStringValue(); - } else { - std::ostringstream buf; - buf << "unnamed_autopilot_" << i; - apName = buf.str(); - } - - if( get_subsystem( apName.c_str() ) != NULL ) { - SG_LOG( SG_ALL, SG_ALERT, "Duplicate autopilot configuration name " << apName << " ignored" ); - continue; - } - - SGPath config( globals->get_fg_root() ); - config.append( pathNode->getStringValue() ); - - SG_LOG( SG_ALL, SG_INFO, "Reading autopilot configuration from " << config.str() ); - // FGXMLAutopilot - FGXMLAutopilot * ap = new FGXMLAutopilot; - try { - SGPropertyNode_ptr root = new SGPropertyNode(); - readProperties( config.str(), root ); - - - if ( ! ap->build( root ) ) { - SG_LOG( SG_ALL, SG_ALERT, - "Detected an internal inconsistency in the autopilot configuration." << endl << " See earlier errors for details." ); - delete ap; - continue; - } - } catch (const sg_exception& e) { - SG_LOG( SG_AUTOPILOT, SG_ALERT, "Failed to load autopilot configuration: " - << config.str() << ":" << e.getMessage() ); - delete ap; - continue; - } - - SG_LOG( SG_AUTOPILOT, SG_INFO, "adding autopilot subsystem " << apName ); - set_subsystem( apName, ap ); - _autopilotNames.push_back( apName ); - } - - SGSubsystemGroup::init(); -} - -FGXMLAutopilot::FGXMLAutopilot() { -} - - -FGXMLAutopilot::~FGXMLAutopilot() { -} - - -/* read all /sim/systems/autopilot[n]/path properties, try to read the file specified therein - * and configure/add the digital filters specified in that file - */ -void FGXMLAutopilot::init() -{ -} - - -void FGXMLAutopilot::reinit() { - components.clear(); - init(); -} - - -void FGXMLAutopilot::bind() { -} - -void FGXMLAutopilot::unbind() { -} - -bool FGXMLAutopilot::build( SGPropertyNode_ptr config_props ) { - SGPropertyNode *node; - int i; - - int count = config_props->nChildren(); - for ( i = 0; i < count; ++i ) { - node = config_props->getChild(i); - string name = node->getName(); - // cout << name << endl; - SG_LOG( SG_AUTOPILOT, SG_BULK, "adding autopilot component " << name ); - if ( name == "pid-controller" ) { - components.push_back( new FGPIDController( node ) ); - } else if ( name == "pi-simple-controller" ) { - components.push_back( new FGPISimpleController( node ) ); - } else if ( name == "predict-simple" ) { - components.push_back( new FGPredictor( node ) ); - } else if ( name == "filter" ) { - components.push_back( new FGDigitalFilter( node ) ); - } else if ( name == "logic" ) { - components.push_back( new FGXMLAutoLogic( node ) ); - } else { - SG_LOG( SG_AUTOPILOT, SG_WARN, "Unknown top level autopilot section: " << name ); -// return false; - } - } - - return true; -} - -/* - * Update the list of autopilot components - */ - -void FGXMLAutopilot::update( double dt ) -{ - unsigned int i; - for ( i = 0; i < components.size(); ++i ) { - components[i]->update( dt ); - } -} - diff --git a/src/Autopilot/xmlauto.hxx b/src/Autopilot/xmlauto.hxx deleted file mode 100644 index a29d49e23..000000000 --- a/src/Autopilot/xmlauto.hxx +++ /dev/null @@ -1,483 +0,0 @@ -// xmlauto.hxx - a more flexible, generic way to build autopilots -// -// Written by Curtis Olson, started January 2004. -// -// Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as -// published by the Free Software Foundation; either version 2 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -// -// $Id$ - - -#ifndef _XMLAUTO_HXX -#define _XMLAUTO_HXX 1 - -/* -Torsten Dreyer: -I'd like to deprecate the so called autopilot helper function -(which is now part of the AutopilotGroup::update() method). -Every property calculated within this helper can be calculated -using filters defined in an external autopilot definition file. -The complete set of calculations may be extracted into a separate -configuration file. The current implementation is able to hande -multiple config files and autopilots. The helper doubles code -and writes properties used only by a few aircraft. -*/ -// FIXME: this should go into config.h and/or configure -// or removed along with the "helper" one day. -#define XMLAUTO_USEHELPER - -#include - -#include -#include -#include - -#include -#include -#include - -typedef SGSharedPtr FGXMLAutoInput_ptr; -typedef SGSharedPtr FGPeriodicalValue_ptr; - -class FGPeriodicalValue : public SGReferenced { -private: - FGXMLAutoInput_ptr minPeriod; // The minimum value of the period - FGXMLAutoInput_ptr maxPeriod; // The maximum value of the period -public: - FGPeriodicalValue( SGPropertyNode_ptr node ); - double normalize( double value ); -}; - -class FGXMLAutoInput : public SGReferenced { -private: - double value; // The value as a constant or initializer for the property - bool abs; // return absolute value - SGPropertyNode_ptr property; // The name of the property containing the value - FGXMLAutoInput_ptr offset; // A fixed offset, defaults to zero - FGXMLAutoInput_ptr scale; // A constant scaling factor defaults to one - FGXMLAutoInput_ptr min; // A minimum clip defaults to no clipping - FGXMLAutoInput_ptr max; // A maximum clip defaults to no clipping - FGPeriodicalValue_ptr periodical; // - SGSharedPtr _condition; - -public: - FGXMLAutoInput( SGPropertyNode_ptr node = NULL, double value = 0.0, double offset = 0.0, double scale = 1.0 ); - - void parse( SGPropertyNode_ptr, double value = 0.0, double offset = 0.0, double scale = 1.0 ); - - /* get the value of this input, apply scale and offset and clipping */ - double get_value(); - - /* set the input value after applying offset and scale */ - void set_value( double value ); - - inline double get_scale() { - return scale == NULL ? 1.0 : scale->get_value(); - } - - inline double get_offset() { - return offset == NULL ? 0.0 : offset->get_value(); - } - - inline bool is_enabled() { - return _condition == NULL ? true : _condition->test(); - } - -}; - -class FGXMLAutoInputList : public std::vector { - public: - FGXMLAutoInput_ptr get_active() { - for (iterator it = begin(); it != end(); ++it) { - if( (*it)->is_enabled() ) - return *it; - } - return NULL; - } - - double get_value( double def = 0.0 ) { - FGXMLAutoInput_ptr input = get_active(); - return input == NULL ? def : input->get_value(); - } - -}; - -/** - * Base class for other autopilot components - */ - -class FGXMLAutoComponent : public SGReferenced { - -private: - simgear::PropertyList output_list; - - SGSharedPtr _condition; - SGPropertyNode_ptr enable_prop; - std::string * enable_value; - - SGPropertyNode_ptr passive_mode; - bool honor_passive; - - std::string name; - - /* Feed back output property to input property if - this filter is disabled. This is for multi-stage - filter where one filter sits behind a pid-controller - to provide changes of the overall output to the pid- - controller. - feedback is disabled by default. - */ - bool feedback_if_disabled; - void do_feedback_if_disabled(); - -protected: - FGXMLAutoComponent(); - - /* - * Parse a component specification read from a property-list. - * Calls the hook methods below to allow derived classes to - * specialise parsing bevaiour. - */ - void parseNode(SGPropertyNode* aNode); - - /** - * Helper to parse the config section - */ - void parseConfig(SGPropertyNode* aConfig); - - /* - * Over-rideable hook method to allow derived classes to refine top-level - * node parsing. Return true if the node was handled, false otherwise. - */ - virtual bool parseNodeHook(const std::string& aName, SGPropertyNode* aNode); - - /** - * Over-rideable hook method to allow derived classes to refine config - * node parsing. Return true if the node was handled, false otherwise. - */ - virtual bool parseConfigHook(const std::string& aName, SGPropertyNode* aNode); - - FGXMLAutoInputList valueInput; - FGXMLAutoInputList referenceInput; - FGXMLAutoInputList uminInput; - FGXMLAutoInputList umaxInput; - FGPeriodicalValue_ptr periodical; - // debug flag - bool debug; - bool enabled; - - - inline void do_feedback() { - if( feedback_if_disabled ) do_feedback_if_disabled(); - } - -public: - - virtual ~FGXMLAutoComponent(); - - virtual void update (double dt)=0; - - inline const std::string& get_name() { return name; } - - double clamp( double value ); - - inline void set_output_value( double value ) { - // passive_ignore == true means that we go through all the - // motions, but drive the outputs. This is analogous to - // running the autopilot with the "servos" off. This is - // helpful for things like flight directors which position - // their vbars from the autopilot computations. - if ( honor_passive && passive_mode->getBoolValue() ) return; - for( simgear::PropertyList::iterator it = output_list.begin(); - it != output_list.end(); ++it) - (*it)->setDoubleValue( clamp( value ) ); - } - - inline void set_output_value( bool value ) { - // passive_ignore == true means that we go through all the - // motions, but drive the outputs. This is analogous to - // running the autopilot with the "servos" off. This is - // helpful for things like flight directors which position - // their vbars from the autopilot computations. - if ( honor_passive && passive_mode->getBoolValue() ) return; - for( simgear::PropertyList::iterator it = output_list.begin(); - it != output_list.end(); ++it) - (*it)->setBoolValue( value ); // don't use clamp here, bool is clamped anyway - } - - inline double get_output_value() { - return output_list.size() == 0 ? 0.0 : clamp(output_list[0]->getDoubleValue()); - } - - /* - Returns true if the enable-condition is true. - - If a is defined, this condition is evaluated, - and tags are ignored. - - If a is defined and no is defined, the property - named in the tags is evaluated as boolean. - - If a is defined a a is defined, the property named - in is compared (as a string) to the value defined in - - - Returns true, if neither nor exists - - Examples: - Using a tag - - - - - This is ignored - This is also ignored - - - Using a single boolean property - - /some/property/that/is/evaluated/as/boolean - - - Using == - This is the old style behaviour - - /only/true/if/this/equals/true - true - - */ - bool isPropertyEnabled(); -}; - -typedef SGSharedPtr FGXMLAutoComponent_ptr; - - -/** - * Roy Ovesen's PID controller - */ - -class FGPIDController : public FGXMLAutoComponent { - -private: - - - // Configuration values - FGXMLAutoInputList Kp; // proportional gain - FGXMLAutoInputList Ti; // Integrator time (sec) - FGXMLAutoInputList Td; // Derivator time (sec) - - double alpha; // low pass filter weighing factor (usually 0.1) - double beta; // process value weighing factor for - // calculating proportional error - // (usually 1.0) - double gamma; // process value weighing factor for - // calculating derivative error - // (usually 0.0) - - // Previous state tracking values - double ep_n_1; // ep[n-1] (prop error) - double edf_n_1; // edf[n-1] (derivative error) - double edf_n_2; // edf[n-2] (derivative error) - double u_n_1; // u[n-1] (output) - double desiredTs; // desired sampling interval (sec) - double elapsedTime; // elapsed time (sec) - - -protected: - bool parseConfigHook(const std::string& aName, SGPropertyNode* aNode); - -public: - - FGPIDController( SGPropertyNode *node ); - FGPIDController( SGPropertyNode *node, bool old ); - ~FGPIDController() {} - - void update( double dt ); -}; - - -/** - * A simplistic P [ + I ] PID controller - */ - -class FGPISimpleController : public FGXMLAutoComponent { - -private: - - // proportional component data - FGXMLAutoInputList Kp; - - // integral component data - FGXMLAutoInputList Ki; - double int_sum; - -protected: - bool parseConfigHook(const std::string& aName, SGPropertyNode* aNode); - -public: - - FGPISimpleController( SGPropertyNode *node ); - ~FGPISimpleController() {} - - void update( double dt ); -}; - - -/** - * Predictor - calculates value in x seconds future. - */ - -class FGPredictor : public FGXMLAutoComponent { - -private: - double last_value; - double average; - FGXMLAutoInputList seconds; - FGXMLAutoInputList filter_gain; - -protected: - bool parseNodeHook(const std::string& aName, SGPropertyNode* aNode); - -public: - FGPredictor( SGPropertyNode *node ); - ~FGPredictor() {} - - void update( double dt ); -}; - - -/** - * FGDigitalFilter - a selection of digital filters - * - * Exponential filter - * Double exponential filter - * Moving average filter - * Noise spike filter - * - * All these filters are low-pass filters. - * - */ - -class FGDigitalFilter : public FGXMLAutoComponent -{ -private: - FGXMLAutoInputList samplesInput; // Number of input samples to average - FGXMLAutoInputList rateOfChangeInput; // The maximum allowable rate of change [1/s] - FGXMLAutoInputList gainInput; // - FGXMLAutoInputList TfInput; // Filter time [s] - - std::deque output; - std::deque input; - enum filterTypes { exponential, doubleExponential, movingAverage, - noiseSpike, gain, reciprocal, differential, none }; - filterTypes filterType; - -protected: - bool parseNodeHook(const std::string& aName, SGPropertyNode* aNode); - -public: - FGDigitalFilter(SGPropertyNode *node); - ~FGDigitalFilter() {} - - void update(double dt); -}; - -class FGXMLAutoLogic : public FGXMLAutoComponent -{ -private: - SGSharedPtr input; - bool inverted; - -protected: - bool parseNodeHook(const std::string& aName, SGPropertyNode* aNode); - -public: - FGXMLAutoLogic(SGPropertyNode * node ); - ~FGXMLAutoLogic() {} - - void update(double dt); -}; - -/** - * Model an autopilot system. - * - */ - -class FGXMLAutopilotGroup : public SGSubsystemGroup -{ -public: - FGXMLAutopilotGroup(); - void init(); - void reinit(); - void update( double dt ); -private: - std::vector _autopilotNames; - -#ifdef XMLAUTO_USEHELPER - double average; - double v_last; - double last_static_pressure; - - SGPropertyNode_ptr vel; - SGPropertyNode_ptr lookahead5; - SGPropertyNode_ptr lookahead10; - SGPropertyNode_ptr bug; - SGPropertyNode_ptr mag_hdg; - SGPropertyNode_ptr bug_error; - SGPropertyNode_ptr fdm_bug_error; - SGPropertyNode_ptr target_true; - SGPropertyNode_ptr true_hdg; - SGPropertyNode_ptr true_error; - SGPropertyNode_ptr target_nav1; - SGPropertyNode_ptr true_nav1; - SGPropertyNode_ptr true_track_nav1; - SGPropertyNode_ptr nav1_course_error; - SGPropertyNode_ptr nav1_selected_course; - SGPropertyNode_ptr vs_fps; - SGPropertyNode_ptr vs_fpm; - SGPropertyNode_ptr static_pressure; - SGPropertyNode_ptr pressure_rate; - SGPropertyNode_ptr track; -#endif -}; - -class FGXMLAutopilot : public SGSubsystem -{ - -public: - - FGXMLAutopilot(); - ~FGXMLAutopilot(); - - void init(); - void reinit(); - void bind(); - void unbind(); - void update( double dt ); - - - bool build( SGPropertyNode_ptr ); -protected: - typedef std::vector comp_list; - -private: - bool serviceable; - comp_list components; - -}; - - -#endif // _XMLAUTO_HXX diff --git a/src/Cockpit/cockpit.cxx b/src/Cockpit/cockpit.cxx index 0414a0f6a..a2f542cbc 100644 --- a/src/Cockpit/cockpit.cxx +++ b/src/Cockpit/cockpit.cxx @@ -26,6 +26,7 @@ #endif #include +#include #include #include @@ -36,11 +37,8 @@ #include #include -#include #include -#ifdef ENABLE_SP_FDM -#include -#endif + #include
#include
#include
@@ -51,7 +49,6 @@ #include "cockpit.hxx" #include "hud.hxx" - // The following routines obtain information concerntin the aircraft's // current state and return it to calling instrument display routines. // They should eventually be member functions of the aircraft. @@ -59,14 +56,14 @@ float get_latitude( void ) { - return current_aircraft.fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES; + return fgGetDouble("/position/latitude-deg"); } float get_lat_min( void ) { double a, d; - a = current_aircraft.fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES; + a = fgGetDouble("/position/latitude-deg"); if (a < 0.0) { a = -a; } @@ -79,7 +76,7 @@ float get_lat_min( void ) float get_longitude( void ) { - return current_aircraft.fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES; + return fgGetDouble("/position/longitude-deg"); } @@ -99,7 +96,7 @@ get_formated_gmt_time( void ) float get_long_min( void ) { double a, d; - a = current_aircraft.fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES; + a = fgGetDouble("/position/longitude-deg"); if (a < 0.0) { a = -a; } @@ -139,7 +136,7 @@ float get_speed( void ) { static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up"); - float speed = current_aircraft.fdm_state->get_V_calibrated_kts() + float speed = fgGetDouble("/velocities/airspeed-kt") * speedup_node->getIntValue(); return speed; @@ -147,27 +144,27 @@ float get_speed( void ) float get_mach(void) { - return current_aircraft.fdm_state->get_Mach_number(); + return fgGetDouble("/velocities/mach"); } float get_aoa( void ) { - return current_aircraft.fdm_state->get_Alpha() * SGD_RADIANS_TO_DEGREES; + return fgGetDouble("/orientation/alpha-deg"); } float get_roll( void ) { - return current_aircraft.fdm_state->get_Phi(); + return fgGetDouble("/orientation/roll-deg") * SG_DEGREES_TO_RADIANS; } float get_pitch( void ) { - return current_aircraft.fdm_state->get_Theta(); + return fgGetDouble("/orientation/pitch-deg") * SG_DEGREES_TO_RADIANS; } float get_heading( void ) { - return current_aircraft.fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES; + return fgGetDouble("/orientation/heading-deg"); } float get_altitude( void ) @@ -175,16 +172,11 @@ float get_altitude( void ) static const SGPropertyNode *startup_units_node = fgGetNode("/sim/startup/units"); - float altitude; - if ( !strcmp(startup_units_node->getStringValue(), "feet") ) { - altitude = current_aircraft.fdm_state->get_Altitude(); + return fgGetDouble("/position/altitude-ft"); } else { - altitude = (current_aircraft.fdm_state->get_Altitude() - * SG_FEET_TO_METER); + return fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER; } - - return altitude; } float get_agl( void ) @@ -192,22 +184,16 @@ float get_agl( void ) static const SGPropertyNode *startup_units_node = fgGetNode("/sim/startup/units"); - float agl; - if ( !strcmp(startup_units_node->getStringValue(), "feet") ) { - agl = (current_aircraft.fdm_state->get_Altitude() - - current_aircraft.fdm_state->get_Runway_altitude()); + return fgGetDouble("/position/altitude-agl-ft"); } else { - agl = (current_aircraft.fdm_state->get_Altitude() - - current_aircraft.fdm_state->get_Runway_altitude()) * SG_FEET_TO_METER; + return fgGetDouble("/position/altitude-agl-ft") * SG_FEET_TO_METER; } - - return agl; } float get_sideslip( void ) { - return current_aircraft.fdm_state->get_Beta(); + return fgGetDouble("/orientation/side-slip-rad"); } float get_frame_rate( void ) @@ -246,11 +232,11 @@ float get_climb_rate( void ) static const SGPropertyNode *startup_units_node = fgGetNode("/sim/startup/units"); - float climb_rate; + float climb_rate = fgGetDouble("/velocities/vertical-speed-fps", 0.0); if ( !strcmp(startup_units_node->getStringValue(), "feet") ) { - climb_rate = current_aircraft.fdm_state->get_Climb_Rate() * 60.0; + climb_rate *= 60.0; } else { - climb_rate = current_aircraft.fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60.0; + climb_rate *= SG_FEET_TO_METER * 60.0; } return climb_rate; @@ -259,15 +245,9 @@ float get_climb_rate( void ) float get_view_direction( void ) { - double view_off = SGD_2PI - globals->get_current_view()->getHeadingOffset_deg() * SGD_DEGREES_TO_RADIANS; - double view = ( current_aircraft.fdm_state->get_Psi() + view_off) - * SGD_RADIANS_TO_DEGREES; - - if (view > 360.) - view -= 360.; - else if (view<0.) - view += 360.; - + double view_off = 360.0 - globals->get_current_view()->getHeadingOffset_deg(); + double view = fgGetDouble("/orientation/heading-deg") + view_off; + SG_NORMALIZE_RANGE(view, 0.0, 360.0); return view; } @@ -280,240 +260,108 @@ float get_dme( void ) return dme_node->getFloatValue(); } -// $$$ begin - added, VS Renganathan 13 Oct 2K -// #ifdef FIGHTER_HUD -float get_Vx ( void ) -{ - // Curt dont comment this and return zero. - Ranga - // Please remove comments from get_V_..() function in flight.hxx - float Vxx = current_aircraft.fdm_state->get_V_north_rel_ground(); - return Vxx; -} - -float get_Vy ( void ) -{ - // Curt dont comment this and return zero. - Ranga - // Please remove comments from get_V_..() function in flight.hxx - float Vyy = current_aircraft.fdm_state->get_V_east_rel_ground(); - return Vyy; -} - -float get_Vz ( void ) -{ - // Curt dont comment this and return zero. - Ranga - // Please remove comments from get_V_..() function in flight.hxx - float Vzz = current_aircraft.fdm_state->get_V_down_rel_ground(); - return Vzz; -} - float get_Ax ( void ) { - float Ax = current_aircraft.fdm_state->get_V_dot_north(); - return Ax; -} - -float get_Ay ( void ) -{ - float Ay = current_aircraft.fdm_state->get_V_dot_east(); - return Ay; -} - -float get_Az ( void ) -{ - float Az = current_aircraft.fdm_state->get_V_dot_down(); - return Az; + return fgGetDouble("/accelerations/ned/north-accel-fps_sec", 0.0); } float get_anzg ( void ) { - float anzg = current_aircraft.fdm_state->get_N_Z_cg(); - return anzg; + return fgGetDouble("/accelerations/n-z-cg-fps_sec", 0.0); } #ifdef ENABLE_SP_FDM -int get_iaux1 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(1); -} - -int get_iaux2 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(2); -} - -int get_iaux3 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(3); -} - -int get_iaux4 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(4); -} - -int get_iaux5 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(5); -} - -int get_iaux6 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(6); -} - -int get_iaux7 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(7); -} - -int get_iaux8 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(8); -} - -int get_iaux9 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(9); -} - -int get_iaux10 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(10); -} - -int get_iaux11 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(11); -} - -int get_iaux12 (void) -{ - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_iaux(12); -} - float get_aux1 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(1); + return fgGetDouble("/fdm-ada/ship-lat", 0.0); } float get_aux2 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(2); + return fgGetDouble("/fdm-ada/ship-lon", 0.0); } float get_aux3 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(3); + return fgGetDouble("/fdm-ada/ship-alt", 0.0); } float get_aux4 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(4); + return fgGetDouble("/fdm-ada/skijump-dist", 0.0); } float get_aux5 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(5); + return fgGetDouble("/fdm-ada/aux5", 0.0); } float get_aux6 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(6); + return fgGetDouble("/fdm-ada/aux6", 0.0); } float get_aux7 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(7); + return fgGetDouble("/fdm-ada/aux7", 0.0); } float get_aux8 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_daux(8); -} + return fgGetDouble("/fdm-ada/aux8", 0.0);} float get_aux9 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(1); -} + return fgGetDouble("/fdm-ada/aux9", 0.0);} float get_aux10 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(2); + return fgGetDouble("/fdm-ada/aux10", 0.0); } float get_aux11 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(3); + return fgGetDouble("/fdm-ada/aux11", 0.0); } float get_aux12 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(4); + return fgGetDouble("/fdm-ada/aux12", 0.0); } float get_aux13 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(5); + return fgGetDouble("/fdm-ada/aux13", 0.0); } float get_aux14 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(6); + return fgGetDouble("/fdm-ada/aux14", 0.0); } float get_aux15 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(7); + return fgGetDouble("/fdm-ada/aux15", 0.0); } float get_aux16 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(8); + return fgGetDouble("/fdm-ada/aux16", 0.0); } float get_aux17 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(9); + return fgGetDouble("/fdm-ada/aux17", 0.0); } float get_aux18 (void) { - FGADA *fdm = (FGADA *)current_aircraft.fdm_state; - return fdm->get_faux(10); + return fgGetDouble("/fdm-ada/aux18", 0.0); } #endif -bool fgCockpitInit( fgAIRCRAFT *cur_aircraft ) +bool fgCockpitInit() { SG_LOG( SG_COCKPIT, SG_INFO, "Initializing cockpit subsystem" ); @@ -529,7 +377,7 @@ bool fgCockpitInit( fgAIRCRAFT *cur_aircraft ) // HI_Head is now a null pointer so we can generate a new list from the // current aircraft. - fgHUDInit( cur_aircraft ); + fgHUDInit(); return true; } diff --git a/src/Cockpit/cockpit.hxx b/src/Cockpit/cockpit.hxx index 9c7a5c9d2..91c415514 100644 --- a/src/Cockpit/cockpit.hxx +++ b/src/Cockpit/cockpit.hxx @@ -33,10 +33,7 @@ #include -#include -#include "panel.hxx" - -bool fgCockpitInit( fgAIRCRAFT *cur_aircraft ); +bool fgCockpitInit(); void fgCockpitUpdate( osg::State* ); #endif /* _COCKPIT_HXX */ diff --git a/src/Cockpit/hud.cxx b/src/Cockpit/hud.cxx index b06a1917b..57c2264e8 100644 --- a/src/Cockpit/hud.cxx +++ b/src/Cockpit/hud.cxx @@ -42,8 +42,6 @@ #include -#include -//#include #include // FGFontCache #include
#include @@ -230,7 +228,7 @@ int readHud( istream &input ) // display for a Piper Cub doesn't show the speed range of a North American // mustange and the engine readouts of a B36! // -int fgHUDInit( fgAIRCRAFT * /* current_aircraft */ ) +int fgHUDInit() { HUD_style = 1; @@ -282,7 +280,7 @@ int fgHUDInit( fgAIRCRAFT * /* current_aircraft */ ) } -int fgHUDInit2( fgAIRCRAFT * /* current_aircraft */ ) +int fgHUDInit2() { HUD_style = 2; diff --git a/src/Cockpit/hud.hxx b/src/Cockpit/hud.hxx index 3774767b6..bec30f553 100644 --- a/src/Cockpit/hud.hxx +++ b/src/Cockpit/hud.hxx @@ -54,7 +54,6 @@ namespace osg { #include #include -#include #include #include #include @@ -134,46 +133,6 @@ extern float get_mach( void ); extern char *coord_format_lat(float); extern char *coord_format_lon(float); -// $$$ begin - added, VS Renganathan, 13 Oct 2K -extern float get_anzg (void); -extern float get_Vx (void); -extern float get_Vy (void); -extern float get_Vz (void); -extern float get_Ax (void); -extern float get_Ay (void); -extern float get_Az (void); -extern int get_iaux1 (void); -extern int get_iaux2 (void); -extern int get_iaux3 (void); -extern int get_iaux4 (void); -extern int get_iaux5 (void); -extern int get_iaux6 (void); -extern int get_iaux7 (void); -extern int get_iaux8 (void); -extern int get_iaux9 (void); -extern int get_iaux10 (void); -extern int get_iaux11 (void); -extern int get_iaux12 (void); -extern float get_aux1(void); -extern float get_aux2(void); -extern float get_aux3(void); -extern float get_aux4(void); -extern float get_aux5 (void); -extern float get_aux6 (void); -extern float get_aux7 (void); -extern float get_aux8(void); -extern float get_aux9(void); -extern float get_aux10(void); -extern float get_aux11(void); -extern float get_aux12(void); -extern float get_aux13(void); -extern float get_aux14(void); -extern float get_aux15(void); -extern float get_aux16(void); -extern float get_aux17(void); -extern float get_aux18(void); -// $$$ end - added, VS Renganathan, 13 Oct 2K - extern char *get_formated_gmt_time( void ); enum hudinstype{ HUDno_instr, @@ -734,8 +693,8 @@ public: }; -extern int fgHUDInit( fgAIRCRAFT * /* current_aircraft */ ); -extern int fgHUDInit2( fgAIRCRAFT * /* current_aircraft */ ); +extern int fgHUDInit(); +extern int fgHUDInit2(); extern void fgUpdateHUD( osg::State* ); extern void fgUpdateHUD( osg::State*, GLfloat x_start, GLfloat y_start, GLfloat x_end, GLfloat y_end ); diff --git a/src/Cockpit/hud_labl.cxx b/src/Cockpit/hud_labl.cxx index 95d69142a..8927b113e 100644 --- a/src/Cockpit/hud_labl.cxx +++ b/src/Cockpit/hud_labl.cxx @@ -114,7 +114,7 @@ void instr_label::draw(void) } } else { - snprintf(label_buffer, sizeof( label_buffer) -1, format_buffer.c_str()); + snprintf(label_buffer, sizeof( label_buffer)-1, format_buffer.c_str(), 0); } lenstr = getStringWidth(label_buffer); diff --git a/src/Cockpit/hud_ladr.cxx b/src/Cockpit/hud_ladr.cxx index 34b58d0eb..d56315b06 100644 --- a/src/Cockpit/hud_ladr.cxx +++ b/src/Cockpit/hud_ladr.cxx @@ -96,11 +96,11 @@ void HudLadder::draw(void) #ifdef ENABLE_SP_FDM int lgear, wown, wowm, ilcanclaw, ihook; - ilcanclaw = get_iaux2(); - lgear = get_iaux3(); - wown = get_iaux4(); - wowm = get_iaux5(); - ihook = get_iaux6(); + ilcanclaw = fgGetInt("/fdm-ada/iaux2", 0); + lgear = fgGetInt("/fdm-ada/iaux3", 0); + wown = fgGetInt("/fdm-ada/iaux4", 0); + wowm = fgGetInt("/fdm-ada/iaux5", 0);; + ihook = fgGetInt("/fdm-ada/iaux6", 0); #endif float pitch_value = current_ch1() * SGD_RADIANS_TO_DEGREES; @@ -159,12 +159,12 @@ void HudLadder::draw(void) //**************************************************************** //velocity vector reticle - computations if (velocity_vector) { - Vxx = get_Vx(); - Vyy = get_Vy(); - Vzz = get_Vz(); - Axx = get_Ax(); - Ayy = get_Ay(); - Azz = get_Az(); + Vxx = fgGetDouble("/velocities/north-relground-fps", 0.0); + Vyy = fgGetDouble("/velocities/east-relground-fps", 0.0); + Vzz = fgGetDouble("/velocities/down-relground-fps", 0.0); + Axx = fgGetDouble("/accelerations/ned/north-accel-fps_sec", 0.0); + Ayy = fgGetDouble("/accelerations/ned/east-accel-fps_sec", 0.0); + Azz = fgGetDouble("/accelerations/ned/down-accel-fps_sec", 0.0); psi = get_heading(); if (psi > 180.0) @@ -597,8 +597,8 @@ void HudLadder::draw(void) fromwp_lon = get_longitude() * SGD_DEGREES_TO_RADIANS; fromwp_lat = get_latitude() * SGD_DEGREES_TO_RADIANS; - towp_lon = get_aux2() * SGD_DEGREES_TO_RADIANS; - towp_lat = get_aux1() * SGD_DEGREES_TO_RADIANS; + towp_lon = fgGetDouble("/fdm-ada/ship-lon", 0.0) * SGD_DEGREES_TO_RADIANS; + towp_lat = fgGetDouble("/fdm-ada/ship-lat", 0.0) * SGD_DEGREES_TO_RADIANS; dist = acos(sin(fromwp_lat) * sin(towp_lat) + cos(fromwp_lat) * cos(towp_lat) * cos(fabs(fromwp_lon - towp_lon))); diff --git a/src/Cockpit/hud_rwy.cxx b/src/Cockpit/hud_rwy.cxx index 0f7866619..2be152523 100644 --- a/src/Cockpit/hud_rwy.cxx +++ b/src/Cockpit/hud_rwy.cxx @@ -27,7 +27,6 @@ #include #include
#include -#include #include #include #include @@ -185,7 +184,7 @@ FGRunway* runway_instr::get_active_runway() void runway_instr::get_rwy_points(sgdVec3 *points3d) { - double alt = current_aircraft.fdm_state->get_Runway_altitude() * SG_FEET_TO_METER; + double alt = runway->geod().getElevationM(); double length = runway->lengthM() * 0.5; double width = runway->widthM() * 0.5; double frontLat = 0.0, frontLon = 0.0, backLat = 0.0, backLon = 0.0, az = 0.0, tempLat = 0.0, tempLon = 0.0; diff --git a/src/Cockpit/panel.cxx b/src/Cockpit/panel.cxx index be2f12570..9c39626ee 100644 --- a/src/Cockpit/panel.cxx +++ b/src/Cockpit/panel.cxx @@ -122,11 +122,7 @@ FGTextureManager::createTexture (const string &relativePath, bool staticTexture) { osg::Texture2D* texture = _textureMap[relativePath].get(); if (texture == 0) { - SG_LOG( SG_COCKPIT, SG_DEBUG, - "Texture " << relativePath << " does not yet exist" ); - SGPath tpath(globals->get_fg_root()); - tpath.append(relativePath); - + SGPath tpath = globals->resolve_aircraft_path(relativePath); texture = SGLoadTexture2D(staticTexture, tpath); _textureMap[relativePath] = texture; diff --git a/src/Cockpit/panel_io.cxx b/src/Cockpit/panel_io.cxx index 7ef58b6e1..ecd6efd89 100644 --- a/src/Cockpit/panel_io.cxx +++ b/src/Cockpit/panel_io.cxx @@ -839,10 +839,9 @@ fgReadPanel (istream &input) FGPanel * fgReadPanel (const string &relative_path) { - SGPath path(globals->get_fg_root()); - path.append(relative_path); + SGPath path = globals->resolve_aircraft_path(relative_path); SGPropertyNode root; - + try { readProperties(path.str(), &root); } catch (const sg_exception &e) { diff --git a/src/Environment/Makefile.am b/src/Environment/Makefile.am index a39d0ec3c..6c7ee1f51 100644 --- a/src/Environment/Makefile.am +++ b/src/Environment/Makefile.am @@ -12,6 +12,7 @@ libEnvironment_a_SOURCES = \ fgwind.cxx fgwind.hxx \ atmosphere.cxx atmosphere.hxx \ precipitation_mgr.cxx precipitation_mgr.hxx \ - ridge_lift.cxx ridge_lift.hxx + ridge_lift.cxx ridge_lift.hxx \ + ephemeris.cxx ephemeris.hxx INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src diff --git a/src/Environment/environment.cxx b/src/Environment/environment.cxx index 9a5755e3d..30354ffd9 100644 --- a/src/Environment/environment.cxx +++ b/src/Environment/environment.cxx @@ -211,20 +211,32 @@ FGEnvironment::read (const SGPropertyNode * node) maybe_copy_value(this, node, "visibility-m", &FGEnvironment::set_visibility_m); + maybe_copy_value(this, node, "elevation-ft", + &FGEnvironment::set_elevation_ft); + if (!maybe_copy_value(this, node, "temperature-sea-level-degc", - &FGEnvironment::set_temperature_sea_level_degc)) - maybe_copy_value(this, node, "temperature-degc", - &FGEnvironment::set_temperature_degc); + &FGEnvironment::set_temperature_sea_level_degc)) { + if( maybe_copy_value(this, node, "temperature-degc", + &FGEnvironment::set_temperature_degc)) { + _recalc_sl_temperature(); + } + } if (!maybe_copy_value(this, node, "dewpoint-sea-level-degc", - &FGEnvironment::set_dewpoint_sea_level_degc)) - maybe_copy_value(this, node, "dewpoint-degc", - &FGEnvironment::set_dewpoint_degc); + &FGEnvironment::set_dewpoint_sea_level_degc)) { + if( maybe_copy_value(this, node, "dewpoint-degc", + &FGEnvironment::set_dewpoint_degc)) { + _recalc_sl_dewpoint(); + } + } if (!maybe_copy_value(this, node, "pressure-sea-level-inhg", - &FGEnvironment::set_pressure_sea_level_inhg)) - maybe_copy_value(this, node, "pressure-inhg", - &FGEnvironment::set_pressure_inhg); + &FGEnvironment::set_pressure_sea_level_inhg)) { + if( maybe_copy_value(this, node, "pressure-inhg", + &FGEnvironment::set_pressure_inhg)) { + _recalc_sl_pressure(); + } + } maybe_copy_value(this, node, "wind-from-heading-deg", &FGEnvironment::set_wind_from_heading_deg); @@ -232,9 +244,6 @@ FGEnvironment::read (const SGPropertyNode * node) maybe_copy_value(this, node, "wind-speed-kt", &FGEnvironment::set_wind_speed_kt); - maybe_copy_value(this, node, "elevation-ft", - &FGEnvironment::set_elevation_ft); - maybe_copy_value(this, node, "turbulence/magnitude-norm", &FGEnvironment::set_turbulence_magnitude_norm); @@ -652,7 +661,7 @@ FGEnvironment::_recalc_sl_temperature () } #endif - if (elevation_ft >= ISA_def[1].height) { + if (elevation_ft * atmodel::foot >= ISA_def[1].height) { SG_LOG(SG_GENERAL, SG_ALERT, "recalc_sl_temperature: " << "valid only in troposphere, not " << elevation_ft); return; diff --git a/src/Environment/environment_ctrl.cxx b/src/Environment/environment_ctrl.cxx index 6efcbde3e..0cc434e69 100644 --- a/src/Environment/environment_ctrl.cxx +++ b/src/Environment/environment_ctrl.cxx @@ -25,6 +25,7 @@ #endif #include +#include #include #include @@ -132,7 +133,11 @@ void FGInterpolateEnvironmentCtrl::init () { read_table( boundary_n, _boundary_table); - read_table( aloft_n, _aloft_table); + // pass in a pointer to the environment of the last bondary layer as + // a starting point + read_table( aloft_n, _aloft_table, + _boundary_table.size() > 0 ? + &(*(_boundary_table.end()-1))->environment : NULL ); } void @@ -142,7 +147,7 @@ FGInterpolateEnvironmentCtrl::reinit () } void -FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node, vector &table) +FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node, vector &table, FGEnvironment * parent ) { double last_altitude_ft = 0.0; double sort_required = false; @@ -163,8 +168,11 @@ FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node, vectorenvironment.copy( *parent ); if (i > 0) b->environment.copy(table[i-1]->environment); + b->environment.read(child); b->altitude_ft = b->environment.get_elevation_ft(); @@ -183,6 +191,14 @@ FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node, vector::size_type n = 1; n < table.size(); n++ ) { + if( fabs(table[n]->altitude_ft - table[n-1]->altitude_ft ) < 1 ) { + SG_LOG( SG_GENERAL, SG_ALERT, "Removing duplicate altitude entry in environment config for altitude " << table[n]->altitude_ft ); + table.erase( table.begin() + n ); + } + } } void @@ -196,7 +212,7 @@ FGInterpolateEnvironmentCtrl::update (double delta_time_sec) int length = _boundary_table.size(); if (length > 0) { - // boundary table + // boundary table double boundary_limit = _boundary_table[length-1]->altitude_ft; if (boundary_limit >= altitude_agl_ft) { do_interpolate(_boundary_table, altitude_agl_ft, _environment); @@ -204,16 +220,16 @@ FGInterpolateEnvironmentCtrl::update (double delta_time_sec) } else if ((boundary_limit + boundary_transition) >= altitude_agl_ft) { //TODO: this is 500ft above the top altitude of boundary layer //shouldn't this be +/-250 ft off of the top altitude? - // both tables + // both tables do_interpolate(_boundary_table, altitude_agl_ft, &env1); do_interpolate(_aloft_table, altitude_ft, &env2); - double fraction = - (altitude_agl_ft - boundary_limit) / boundary_transition; + double fraction = boundary_transition > SGLimitsd::min() ? + (altitude_agl_ft - boundary_limit) / boundary_transition : 1.0; interpolate(&env1, &env2, fraction, _environment); return; } } - // aloft table + // aloft table do_interpolate(_aloft_table, altitude_ft, _environment); } @@ -224,31 +240,26 @@ FGInterpolateEnvironmentCtrl::do_interpolate (vector &table, double al if (length == 0) return; - // Boundary conditions + // Boundary conditions if ((length == 1) || (table[0]->altitude_ft >= altitude_ft)) { - environment->copy(table[0]->environment); + environment->copy(table[0]->environment); // below bottom of table return; } else if (table[length-1]->altitude_ft <= altitude_ft) { - environment->copy(table[length-1]->environment); + environment->copy(table[length-1]->environment); // above top of table return; - } - // Search the interpolation table - for (int i = 0; i < length - 1; i++) { - if ((i == length - 1) || (table[i]->altitude_ft <= altitude_ft)) { - FGEnvironment * env1 = &(table[i]->environment); - FGEnvironment * env2 = &(table[i+1]->environment); - double fraction; - if (table[i]->altitude_ft == table[i+1]->altitude_ft) - fraction = 1.0; - else - fraction = - ((altitude_ft - table[i]->altitude_ft) / - (table[i+1]->altitude_ft - table[i]->altitude_ft)); - interpolate(env1, env2, fraction, environment); - - return; - } - } + } + + // Search the interpolation table + int layer; + for ( layer = 1; // can't be below bottom layer, handled above + layer < length && table[layer]->altitude_ft <= altitude_ft; + layer++); + FGEnvironment * env1 = &(table[layer-1]->environment); + FGEnvironment * env2 = &(table[layer]->environment); + // two layers of same altitude were sorted out in read_table + double fraction = ((altitude_ft - table[layer-1]->altitude_ft) / + (table[layer]->altitude_ft - table[layer-1]->altitude_ft)); + interpolate(env1, env2, fraction, environment); } bool @@ -747,7 +758,7 @@ void FGMetarCtrl::set_metar( const char * metar_string ) m = new FGMetar( metar_string ); } catch( sg_io_exception ) { - fprintf( stderr, "can't get metar: %s\n", metar_string ); + SG_LOG( SG_GENERAL, SG_WARN, "Can't get metar: " << metar_string ); metar_valid = false; return; } diff --git a/src/Environment/environment_ctrl.hxx b/src/Environment/environment_ctrl.hxx index aec1442cb..1f81c0259 100644 --- a/src/Environment/environment_ctrl.hxx +++ b/src/Environment/environment_ctrl.hxx @@ -101,7 +101,7 @@ private: static bool lessThan(bucket *a, bucket *b); }; - void read_table (const SGPropertyNode * node, std::vector &table); + void read_table (const SGPropertyNode * node, std::vector &table, FGEnvironment * parent = NULL ); void do_interpolate (std::vector &table, double altitude_ft, FGEnvironment * environment); diff --git a/src/Environment/environment_mgr.cxx b/src/Environment/environment_mgr.cxx index acf20b861..775e4a32a 100644 --- a/src/Environment/environment_mgr.cxx +++ b/src/Environment/environment_mgr.cxx @@ -24,6 +24,8 @@ # include #endif +#include + #include #include #include @@ -32,7 +34,6 @@ #include
#include
-#include #include #include "environment.hxx" @@ -40,6 +41,7 @@ #include "environment_ctrl.hxx" #include "fgclouds.hxx" #include "precipitation_mgr.hxx" +#include "ridge_lift.hxx" class SGSky; extern SGSky *thesky; @@ -64,10 +66,18 @@ FGEnvironmentMgr::FGEnvironmentMgr () _precipitationManager = new FGPrecipitationMgr; set_subsystem("precipitation", _precipitationManager); + + set_subsystem("ridgelift", new FGRidgeLift); } FGEnvironmentMgr::~FGEnvironmentMgr () { + SGSubsystem * subsys; + + subsys = get_subsystem( "ridgelift" ); + remove_subsystem( "ridgelift" ); + delete subsys; + remove_subsystem("precipitation"); delete _precipitationManager; @@ -90,7 +100,7 @@ FGEnvironmentMgr::init () { SG_LOG( SG_GENERAL, SG_INFO, "Initializing environment subsystem"); SGSubsystemGroup::init(); - _update_fdm(); + //_update_fdm(); } void @@ -98,7 +108,7 @@ FGEnvironmentMgr::reinit () { SG_LOG( SG_GENERAL, SG_INFO, "Reinitializing environment subsystem"); SGSubsystemGroup::reinit(); - _update_fdm(); + //_update_fdm(); } void @@ -290,20 +300,25 @@ void FGEnvironmentMgr::update (double dt) { SGSubsystemGroup::update(dt); - - // FIXME: the FDMs should update themselves - current_aircraft.fdm_state - ->set_Velocities_Local_Airmass(_environment->get_wind_from_north_fps(), - _environment->get_wind_from_east_fps(), - _environment->get_wind_from_down_fps()); + _environment->set_elevation_ft(fgGetDouble("/position/altitude-ft")); _environment->set_local_weather_lift_fps(fgGetDouble("/local-weather/current/thermal-lift")); - osg::Vec3 windVec(-_environment->get_wind_from_north_fps(), + osg::Vec3 windVec(_environment->get_wind_from_north_fps(), -_environment->get_wind_from_east_fps(), - _environment->get_wind_from_down_fps()); - simgear::Particles::setWindVector(windVec * SG_FEET_TO_METER); + 0); + // SG_LOG(SG_GENERAL, SG_ALERT, "-_environment->get_wind_from_north_mps() " << + //_environment->get_wind_from_north_fps() * SG_FEET_TO_METER + //<< " -_environment->get_wind_from_east_mps() " + //<< -_environment->get_wind_from_east_fps() * SG_FEET_TO_METER + //); + + // simgear::Particles::setWindVector(windVec * SG_FEET_TO_METER); + simgear::Particles::setWindFrom( _environment->get_wind_from_heading_deg(), + _environment->get_wind_speed_kt() ); + //double wind_true_deg = _environment->get_wind_from_heading_deg(); + //simgear::Particles::setWindFrom( wind_true_deg, + // _environment->get_wind_speed_kt() ); - _update_fdm(); } FGEnvironment @@ -335,27 +350,6 @@ FGEnvironmentMgr::getEnvironment(const SGGeod& aPos) const } -void -FGEnvironmentMgr::_update_fdm () const -{ - // - // Pass atmosphere on to FDM - // FIXME: have FDMs read properties directly. - // - if (fgGetBool("/environment/params/control-fdm-atmosphere")) { - // convert from Rankine to Celsius - cur_fdm_state - ->set_Static_temperature((9.0/5.0) - * (_environment->get_temperature_degc() + 273.15)); - // convert from inHG to PSF - cur_fdm_state - ->set_Static_pressure(_environment->get_pressure_inhg() * 70.726566); - // keep in slugs/ft^3 - cur_fdm_state - ->set_Density(_environment->get_density_slugft3()); - } -} - double FGEnvironmentMgr::get_cloud_layer_span_m (int index) const { diff --git a/src/Environment/environment_mgr.hxx b/src/Environment/environment_mgr.hxx index ffd753463..490340c4a 100644 --- a/src/Environment/environment_mgr.hxx +++ b/src/Environment/environment_mgr.hxx @@ -76,8 +76,6 @@ public: virtual FGEnvironment getEnvironment(const SGGeod& aPos) const; private: - void _update_fdm () const; - double get_cloud_layer_span_m (int index) const; void set_cloud_layer_span_m (int index, double span_m); double get_cloud_layer_elevation_ft (int index) const; diff --git a/src/Environment/ephemeris.cxx b/src/Environment/ephemeris.cxx new file mode 100644 index 000000000..874617fd2 --- /dev/null +++ b/src/Environment/ephemeris.cxx @@ -0,0 +1,85 @@ +// ephemeris.cxx -- wrap SGEphemeris code in a subsystem +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#include + +#include +#include + +#include
+#include
+ +Ephemeris::Ephemeris() : + _impl(NULL), + _latProp(NULL) +{ +} + +Ephemeris::~Ephemeris() +{ + delete _impl; +} + +void Ephemeris::init() +{ + if (_impl) { + return; + } + + SGPath ephem_data_path(globals->get_fg_root()); + ephem_data_path.append("Astro"); + _impl = new SGEphemeris(ephem_data_path.c_str()); + globals->set_ephem(_impl); + + _latProp = fgGetNode("/position/latitude-deg", true); + update(0.0); +} + +void Ephemeris::postinit() +{ + +} + +static void tieStar(const char* prop, Star* s, double (Star::*getter)() const) +{ + fgGetNode(prop, true)->tie(SGRawValueMethods(*s, getter, NULL)); +} + +void Ephemeris::bind() +{ + tieStar("/ephemeris/sun/xs", _impl->get_sun(), &Star::getxs); + tieStar("/ephemeris/sun/ys", _impl->get_sun(), &Star::getys); + tieStar("/ephemeris/sun/ze", _impl->get_sun(), &Star::getze); + tieStar("/ephemeris/sun/ye", _impl->get_sun(), &Star::getye); + + tieStar("/ephemeris/sun/lat-deg", _impl->get_sun(), &Star::getLat); +} + +void Ephemeris::unbind() +{ +} + +void Ephemeris::update(double) +{ + SGTime* st = globals->get_time_params(); + _impl->update(st->getMjd(), st->getLst(), _latProp->getDoubleValue()); +} diff --git a/src/Environment/ephemeris.hxx b/src/Environment/ephemeris.hxx new file mode 100644 index 000000000..766cff734 --- /dev/null +++ b/src/Environment/ephemeris.hxx @@ -0,0 +1,53 @@ +// ephemeris.hxx -- wrap SGEphemeris code in a subsystem +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#ifndef FG_ENVIRONMENT_EPHEMERIS_HXX +#define FG_ENVIRONMENT_EPHEMERIS_HXX + +#include + +class SGEphemeris; +class SGPropertyNode; + +/** + * Wrap SGEphemeris in a susbsytem/property interface + */ +class Ephemeris : public SGSubsystem +{ +public: + + Ephemeris(); + ~Ephemeris(); + + virtual void bind(); + virtual void unbind(); + virtual void update(double dt); + virtual void init(); + virtual void postinit(); + +private: + SGEphemeris* _impl; + SGPropertyNode* _latProp; +}; + +#endif // of FG_ENVIRONMENT_EPHEMERIS_HXX + diff --git a/src/Environment/fgclouds.cxx b/src/Environment/fgclouds.cxx index 606a4973e..208fa402b 100644 --- a/src/Environment/fgclouds.cxx +++ b/src/Environment/fgclouds.cxx @@ -24,6 +24,7 @@ # include "config.h" #endif +#include #include
#include @@ -100,8 +101,7 @@ double FGClouds::buildCloud(SGPropertyNode *cloud_def_root, SGPropertyNode *box_ double y = sg_random() * SGCloudField::fieldSize - (SGCloudField::fieldSize / 2.0); double z = grid_z_rand * (sg_random() - 0.5); - sgVec3 pos={x,y,z}; - + SGVec3f pos(x,y,z); for(int i = 0; i < box_def->nChildren() ; i++) { SGPropertyNode *abox = box_def->getChild(i); diff --git a/src/Environment/terrainsampler.cxx b/src/Environment/terrainsampler.cxx new file mode 100644 index 000000000..276c8ffb1 --- /dev/null +++ b/src/Environment/terrainsampler.cxx @@ -0,0 +1,402 @@ +// terrainsampler.cxx -- +// +// Written by Torsten Dreyer, started July 2010 +// Based on local weather implementation in nasal from +// Thorsten Renk +// +// Copyright (C) 2010 Curtis Olson +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifdef HAVE_CONFIG_H +# include +#endif + +#include
+#include +#include +#include + +#include "terrainsampler.hxx" +using simgear::PropertyList; + +#include "tiedpropertylist.hxx" + +namespace Environment { +/** + * @brief Class for presampling the terrain roughness + */ +class AreaSampler : public SGSubsystem { +public: + AreaSampler( SGPropertyNode_ptr rootNode ); + virtual ~AreaSampler(); + void update( double dt ); + void bind(); + void unbind(); + void init(); + void reinit(); + + int getElevationHistogramStep() const { return _elevationHistogramStep; } + void setElevationHistograpStep( int value ) { + _elevationHistogramStep = value > 0 ? value : 500; + _elevationHistogramCount = _elevationHistogramMax / _elevationHistogramStep; + } + + int getElevationHistogramMax() const { return _elevationHistogramMax; } + void setElevationHistograpMax( int value ) { + _elevationHistogramMax = value > 0 ? value : 10000; + _elevationHistogramCount = _elevationHistogramMax / _elevationHistogramStep; + } + + int getElevationHistogramCount() const { return _elevationHistogramCount; } + +private: + void analyse(); + + SGPropertyNode_ptr _rootNode; + + bool _enabled; + bool _useAircraftPosition; + double _heading_deg; + double _speed_kt; + int _radius; + double _max_computation_time_norm; + int _max_samples; // keep xx samples in queue for analysis + double _reuse_samples_norm; + double _recalc_distance_norm; + int _elevationHistogramMax; + int _elevationHistogramStep; + int _elevationHistogramCount; + SGGeod _inputPosition; + + double _altOffset; + double _altMedian; + double _altMin; + double _altLayered; + double _altMean; + SGGeod _outputPosition; + + SGPropertyNode_ptr _signalNode; + SGPropertyNode_ptr _positionLatitudeNode; + SGPropertyNode_ptr _positionLongitudeNode; + + deque _elevations; + TiedPropertyList _tiedProperties; +}; + +AreaSampler::AreaSampler( SGPropertyNode_ptr rootNode ) : + _rootNode(rootNode), + _enabled(true), + _useAircraftPosition(false), + _heading_deg(0.0), + _speed_kt(0.0), + _radius(40000.0), + _max_computation_time_norm(0.1), + _max_samples(1000), + _reuse_samples_norm(0.8), + _recalc_distance_norm(0.1), + _elevationHistogramMax(10000), + _elevationHistogramStep(500), + _elevationHistogramCount(_elevationHistogramMax/_elevationHistogramStep), + _altOffset(0), + _altMedian(0), + _altMin(0), + _altLayered(0), + _altMean(0), + _signalNode(rootNode->getNode("output/valid", true )), + _positionLatitudeNode(fgGetNode( "/position/latitude-deg", true )), + _positionLongitudeNode(fgGetNode( "/position/longitude-deg", true )) +{ + _inputPosition.setElevationM( SG_MAX_ELEVATION_M ); +} + +AreaSampler::~AreaSampler() +{ +} + + +void AreaSampler::bind() +{ + _tiedProperties.setRoot( _rootNode ); + _tiedProperties.Tie( "enabled", &_enabled ); + + _tiedProperties.setRoot( _rootNode->getNode( "input", true ) ); + _tiedProperties.Tie( "use-aircraft-position", &_useAircraftPosition ); + _tiedProperties.Tie( "latitude-deg", &_inputPosition, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg ); + _tiedProperties.Tie( "longitude-deg", &_inputPosition, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg ); + _tiedProperties.Tie( "heading-deg", &_heading_deg ); + _tiedProperties.Tie( "speed-kt", &_speed_kt ); + _tiedProperties.Tie( "radius-m", &_radius ); + _tiedProperties.Tie( "max-computation-time-norm", &_max_computation_time_norm ); + _tiedProperties.Tie( "max-samples", &_max_samples ); + _tiedProperties.Tie( "reuse-samples-norm", &_reuse_samples_norm ); + _tiedProperties.Tie( "recalc-distance-norm", &_recalc_distance_norm ); + _tiedProperties.Tie( "elevation-histogram-max-ft", this, &AreaSampler::getElevationHistogramMax, &AreaSampler::setElevationHistograpMax ); + _tiedProperties.Tie( "elevation-histogram-step-ft", this, &AreaSampler::getElevationHistogramStep, &AreaSampler::setElevationHistograpStep ); + _tiedProperties.Tie( "elevation-histogram-count", this, &AreaSampler::getElevationHistogramCount ); + + _tiedProperties.setRoot( _rootNode->getNode( "output", true ) ); + _tiedProperties.Tie( "alt-offset-ft", &_altOffset ); + _tiedProperties.Tie( "alt-median-ft", &_altMedian ); + _tiedProperties.Tie( "alt-min-ft", &_altMin ); + _tiedProperties.Tie( "alt-layered-ft", &_altLayered ); + _tiedProperties.Tie( "alt-mean-ft", &_altMean ); + _tiedProperties.Tie( "longitude-deg", &_outputPosition, &SGGeod::getLongitudeDeg ); + _tiedProperties.Tie( "latitude-deg", &_outputPosition, &SGGeod::getLatitudeDeg ); + +} + +void AreaSampler::unbind() +{ + _tiedProperties.Untie(); +} + +void AreaSampler::init() +{ + _signalNode->setBoolValue(false); + _elevations.clear(); + _altOffset = 0.0; + _altMedian = 0.0; + _altMin = 0.0; + _altLayered = 0.0; + _altMean = 0.0; +} + +void AreaSampler::reinit() +{ + init(); +} + +void AreaSampler::update( double dt ) +{ + // if not enabled or time has stalled, do nothing + if( !(_enabled && dt > SGLimitsd::min()) ) + return; + + // get the aircraft's position if requested + if( _useAircraftPosition && _speed_kt < 0.5 ) { + _inputPosition = SGGeod::fromDegM( + _positionLongitudeNode->getDoubleValue(), + _positionLatitudeNode->getDoubleValue(), + SG_MAX_ELEVATION_M ); + } + + // need geocentric coordinates + SGGeoc center = SGGeoc::fromGeod( _inputPosition ); + + // if a speed is set, move the input position + if( _speed_kt >= 0.5 ) { + double distance_m = _speed_kt * dt * SG_NM_TO_METER; + center = center.advanceRadM( _heading_deg * SG_DEGREES_TO_RADIANS, distance_m ); + _inputPosition = SGGeod::fromGeoc( center ); + } + + if( _signalNode->getBoolValue() ) { + // if we had finished the iteration and moved more than 10% of the radius + // of the sampling area, drop the oldest samples and continue sampling + if( SGGeoc::distanceM( center, SGGeoc::fromGeod(_outputPosition ) ) >= _recalc_distance_norm * _radius ) { + _elevations.resize( _max_samples * _reuse_samples_norm ); + _signalNode->setBoolValue( false ); + } + } + + if( _signalNode->getBoolValue() ) + return; // nothing to do. + + FGScenery * scenery = globals->get_scenery(); + + SGTimeStamp start = SGTimeStamp::now(); + while( (SGTimeStamp::now() - start).toSecs() < dt * _max_computation_time_norm ) { + // sample until we used up all our configured time + double distance = sg_random(); + distance = _radius * (1-distance*distance); + double course = sg_random() * 2.0 * SG_PI; + SGGeod probe = SGGeod::fromGeoc(center.advanceRadM( course, distance )); + double elevation_m = 0.0; + + if (scenery->get_elevation_m( probe, elevation_m, NULL )) + _elevations.push_front(elevation_m *= SG_METER_TO_FEET); + + if( _elevations.size() >= (deque::size_type)_max_samples ) { + // sampling complete? + analyse(); + _outputPosition = _inputPosition; + _signalNode->setBoolValue( true ); + break; + } + } +} + +void AreaSampler::analyse() +{ + double sum; + + vector histogram(_elevationHistogramCount,0); + + for( deque::size_type i = 0; i < _elevations.size(); i++ ) { + int idx = SGMisc::clip( (int)(_elevations[i]/_elevationHistogramStep), 0, histogram.size()-1 ); + histogram[idx]++; + } + + _altMedian = 0.0; + sum = 0.0; + for( vector::size_type i = 0; i < histogram.size(); i++ ) { + sum += histogram[i]; + if( sum > 0.5 * _elevations.size() ) { + _altMedian = i * _elevationHistogramStep; + break; + } + } + + _altOffset = 0.0; + sum = 0.0; + for( vector::size_type i = 0; i < histogram.size(); i++ ) { + sum += histogram[i]; + if( sum > 0.3 * _elevations.size() ) { + _altOffset = i * _elevationHistogramStep; + break; + } + } + + _altMean = 0.0; + for( vector::size_type i = 0; i < histogram.size(); i++ ) { + _altMean += histogram[i] * i; + } + _altMean *= _elevationHistogramStep; + if( _elevations.size() != 0.0 ) _altMean /= _elevations.size(); + + _altMin = 0.0; + for( vector::size_type i = 0; i < histogram.size(); i++ ) { + if( histogram[i] > 0 ) { + _altMin = i * _elevationHistogramStep; + break; + } + } + + double alt_low_min = 0.0; + double n_max = 0.0; + sum = 0.0; + for( vector::size_type i = 0; i < histogram.size()-1; i++ ) { + sum += histogram[i]; + if( histogram[i] > n_max ) n_max = histogram[i]; + if( n_max > histogram[i+1] && sum > 0.3*_elevations.size()) { + alt_low_min = i * _elevationHistogramStep; + break; + } + } + + _altLayered = 0.5 * (_altMin + _altOffset); + +#if 0 +append(alt_50_array, alt_med); +#endif +} + +/* --------------------- End of AreaSampler implementation ------------- */ + +/* --------------------- TerrainSamplerImplementation -------------------------- */ + +class TerrainSamplerImplementation : public TerrainSampler +{ +public: + TerrainSamplerImplementation ( SGPropertyNode_ptr rootNode ); + virtual ~TerrainSamplerImplementation (); + + virtual void init (); + virtual void postinit(); + virtual void reinit (); + virtual void bind(); + virtual void unbind(); + virtual void update (double delta_time_sec); +private: + inline string areaSubsystemName( unsigned i ) { + ostringstream name; + name << "area" << i; + return name.str(); + } + + SGPropertyNode_ptr _rootNode; + bool _enabled; + TiedPropertyList _tiedProperties; +}; + +TerrainSamplerImplementation::TerrainSamplerImplementation( SGPropertyNode_ptr rootNode ) : + _rootNode( rootNode ), + _enabled(true) +{ +} + +TerrainSamplerImplementation::~TerrainSamplerImplementation() +{ +} + +void TerrainSamplerImplementation::init() +{ + PropertyList areaNodes = _rootNode->getChildren( "area" ); + + for( PropertyList::size_type i = 0; i < areaNodes.size(); i++ ) + set_subsystem( areaSubsystemName(i), new AreaSampler( areaNodes[i] ) ); + + SGSubsystemGroup::init(); +} + +void TerrainSamplerImplementation::postinit() +{ + SGSubsystemGroup::bind();// +} + +void TerrainSamplerImplementation::reinit() +{ + for( unsigned i = 0;; i++ ) { + string subsystemName = areaSubsystemName(i); + SGSubsystem * subsys = get_subsystem( subsystemName ); + if( subsys == NULL ) + break; + remove_subsystem( subsystemName ); + } + + init(); +} + +void TerrainSamplerImplementation::bind() +{ + SGSubsystemGroup::bind(); + _tiedProperties.Tie( _rootNode->getNode("enabled",true), &_enabled ); +} + +void TerrainSamplerImplementation::unbind() +{ + _tiedProperties.Untie(); + SGSubsystemGroup::unbind(); +} + +void TerrainSamplerImplementation::update( double dt ) +{ + if( !(_enabled && dt > SGLimitsd::min()) ) + return; + SGSubsystemGroup::update(dt); +} + +/* ----------------------------------------------------------------------- */ + +/* implementation of the TerrainSampler factory to hide the implementation + details */ +TerrainSampler * TerrainSampler::createInstance( SGPropertyNode_ptr rootNode ) +{ + return new TerrainSamplerImplementation( rootNode ); +} + +} // namespace + diff --git a/src/Environment/terrainsampler.hxx b/src/Environment/terrainsampler.hxx new file mode 100644 index 000000000..e9fa3c319 --- /dev/null +++ b/src/Environment/terrainsampler.hxx @@ -0,0 +1,36 @@ +// terrainsampler.hxx -- +// +// Written by Torsten Dreyer, started July 2010 +// Based on local weather implementation in nasal from +// Thorsten Renk +// +// Copyright (C) 2010 Curtis Olson +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +#ifndef _TERRAIN_SAMPLER_HXX +#define _TERRAIN_SAMPLER_HXX + +#include + +namespace Environment { +class TerrainSampler : public SGSubsystemGroup +{ +public: + static TerrainSampler * createInstance( SGPropertyNode_ptr rootNode ); +}; + +} // namespace +#endif diff --git a/src/Environment/tiedpropertylist.hxx b/src/Environment/tiedpropertylist.hxx new file mode 100644 index 000000000..dbb9cc45a --- /dev/null +++ b/src/Environment/tiedpropertylist.hxx @@ -0,0 +1,80 @@ +#ifndef __TIEDPROPERTYLIST_HXX +#define __TIEDPROPERTYLIST_HXX +#include +using simgear::PropertyList; + +// Maybe this goes into SimGear's props.hxx later? +class TiedPropertyList : PropertyList { +public: + TiedPropertyList() {} + TiedPropertyList( SGPropertyNode_ptr root ) { _root = root; } + + void setRoot( SGPropertyNode_ptr root ) { _root = root; } + SGPropertyNode_ptr getRoot() const { return _root; } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, const SGRawValue &rawValue, bool useDefault = true ) { + bool success = node->tie( rawValue, useDefault ); + if( success ) { + SG_LOG( SG_ALL, SG_INFO, "Tied " << node->getPath() ); + push_back( node ); + } else { +#if PROPS_STANDALONE + cerr << "Failed to tie property " << node->getPath() << endl; +#else + SG_LOG(SG_GENERAL, SG_WARN, "Failed to tie property " << node->getPath() ); +#endif + } + return node; + } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, V * value, bool useDefault = true ) { + return Tie( node, SGRawValuePointer(value), useDefault ); + } + + template SGPropertyNode_ptr Tie( const char * relative_path, V * value, bool useDefault = true ) { + return Tie( _root->getNode(relative_path,true), SGRawValuePointer(value), useDefault ); + } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, V (*getter)(), void (*setter)(V) = 0, bool useDefault = true ) { + return Tie(node, SGRawValueFunctions(getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( const char * relative_path, V (*getter)(), void (*setter)(V) = 0, bool useDefault = true ) { + return Tie(_root->getNode(relative_path, true), SGRawValueFunctions(getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, int index, V (*getter)(int), void (*setter)(int, V) = 0, bool useDefault = true) { + return Tie( node, SGRawValueFunctionsIndexed(index, getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( const char * relative_path, int index, V (*getter)(int), void (*setter)(int, V) = 0, bool useDefault = true) { + return Tie( _root->getNode( relative_path, true ), SGRawValueFunctionsIndexed(index, getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, T * obj, V (T::*getter)() const, void (T::*setter)(V) = 0, bool useDefault = true) { + return Tie( node, SGRawValueMethods(*obj, getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( const char * relative_path, T * obj, V (T::*getter)() const, void (T::*setter)(V) = 0, bool useDefault = true) { + return Tie( _root->getNode( relative_path, true), SGRawValueMethods(*obj, getter, setter), useDefault ); + } + + template SGPropertyNode_ptr Tie( SGPropertyNode_ptr node, T * obj, int index, V (T::*getter)(int) const, void (T::*setter)(int, V) = 0, bool useDefault = true) { + return Tie( node, SGRawValueMethodsIndexed(*obj, index, getter, setter), useDefault); + } + + template SGPropertyNode_ptr Tie( const char * relative_path, T * obj, int index, V (T::*getter)(int) const, void (T::*setter)(int, V) = 0, bool useDefault = true) { + return Tie( _root->getNode( relative_path, true ), SGRawValueMethodsIndexed(*obj, index, getter, setter), useDefault); + } + + void Untie() { + while( size() > 0 ) { + SG_LOG( SG_ALL, SG_INFO, "untie of " << back()->getPath() ); + back()->untie(); + pop_back(); + } + } +private: + SGPropertyNode_ptr _root; +}; +#endif diff --git a/src/FDM/ExternalPipe/ExternalPipe.cxx b/src/FDM/ExternalPipe/ExternalPipe.cxx index 2be480971..abe656960 100644 --- a/src/FDM/ExternalPipe/ExternalPipe.cxx +++ b/src/FDM/ExternalPipe/ExternalPipe.cxx @@ -31,6 +31,7 @@ # include // unlink() #endif +#include #include // FILE*, fopen(), fread(), fwrite(), et. al. #include // for cout, endl @@ -428,47 +429,48 @@ void FGExternalPipe::update_binary( double dt ) { // Process remote FDM "set" commands -static void process_set_command( const string_list &tokens ) { + +void FGExternalPipe::process_set_command( const string_list &tokens ) { if ( tokens[1] == "geodetic_position" ) { double lat_rad = atof( tokens[2].c_str() ); double lon_rad = atof( tokens[3].c_str() ); double alt_m = atof( tokens[4].c_str() ); - cur_fdm_state->_updateGeodeticPosition( lat_rad, lon_rad, + _updateGeodeticPosition( lat_rad, lon_rad, alt_m * SG_METER_TO_FEET ); - double agl_m = alt_m - cur_fdm_state->get_Runway_altitude_m(); - cur_fdm_state->_set_Altitude_AGL( agl_m * SG_METER_TO_FEET ); + double agl_m = alt_m - get_Runway_altitude_m(); + _set_Altitude_AGL( agl_m * SG_METER_TO_FEET ); } else if ( tokens[1] == "euler_angles" ) { double phi_rad = atof( tokens[2].c_str() ); double theta_rad = atof( tokens[3].c_str() ); double psi_rad = atof( tokens[4].c_str() ); - cur_fdm_state->_set_Euler_Angles( phi_rad, theta_rad, psi_rad ); + _set_Euler_Angles( phi_rad, theta_rad, psi_rad ); } else if ( tokens[1] == "euler_rates" ) { double phidot = atof( tokens[2].c_str() ); double thetadot = atof( tokens[3].c_str() ); double psidot = atof( tokens[4].c_str() ); - cur_fdm_state->_set_Euler_Rates( phidot, thetadot, psidot ); + _set_Euler_Rates( phidot, thetadot, psidot ); } else if ( tokens[1] == "ned" ) { double north_fps = atof( tokens[2].c_str() ); double east_fps = atof( tokens[3].c_str() ); double down_fps = atof( tokens[4].c_str() ); - cur_fdm_state->_set_Velocities_Local( north_fps, east_fps, down_fps ); + _set_Velocities_Local( north_fps, east_fps, down_fps ); } else if ( tokens[1] == "alpha" ) { - cur_fdm_state->_set_Alpha( atof(tokens[2].c_str()) ); + _set_Alpha( atof(tokens[2].c_str()) ); } else if ( tokens[1] == "beta" ) { - cur_fdm_state->_set_Beta( atof(tokens[2].c_str()) ); + _set_Beta( atof(tokens[2].c_str()) ); #if 0 - cur_fdm_state->_set_V_calibrated_kts( net->vcas ); - cur_fdm_state->_set_Climb_Rate( net->climb_rate ); - cur_fdm_state->_set_Velocities_Local( net->v_north, + _set_V_calibrated_kts( net->vcas ); + _set_Climb_Rate( net->climb_rate ); + _set_Velocities_Local( net->v_north, net->v_east, net->v_down ); - cur_fdm_state->_set_Velocities_Wind_Body( net->v_wind_body_north, + _set_Velocities_Wind_Body( net->v_wind_body_north, net->v_wind_body_east, net->v_wind_body_down ); - cur_fdm_state->_set_Accels_Pilot_Body( net->A_X_pilot, + _set_Accels_Pilot_Body( net->A_X_pilot, net->A_Y_pilot, net->A_Z_pilot ); #endif diff --git a/src/FDM/ExternalPipe/ExternalPipe.hxx b/src/FDM/ExternalPipe/ExternalPipe.hxx index d5e03967b..866967c12 100644 --- a/src/FDM/ExternalPipe/ExternalPipe.hxx +++ b/src/FDM/ExternalPipe/ExternalPipe.hxx @@ -62,6 +62,7 @@ private: void update_binary( double dt ); void update_property( double dt ); + void process_set_command( const string_list &tokens ); public: // Constructor diff --git a/src/FDM/JSBSim/FGFDMExec.cpp b/src/FDM/JSBSim/FGFDMExec.cpp index 685122381..5226a3e37 100644 --- a/src/FDM/JSBSim/FGFDMExec.cpp +++ b/src/FDM/JSBSim/FGFDMExec.cpp @@ -42,7 +42,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGFDMExec.h" -#include "FGState.h" #include "models/FGAtmosphere.h" #include "models/atmosphere/FGMSIS.h" #include "models/atmosphere/FGMars.h" @@ -72,7 +71,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFDMExec.cpp,v 1.79 2010/07/25 13:52:20 jberndt Exp $"; static const char *IdHdr = ID_FDMEXEC; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -111,7 +110,6 @@ FGFDMExec::FGFDMExec(FGPropertyManager* root) : Root(root) Frame = 0; Error = 0; GroundCallback = 0; - State = 0; Atmosphere = 0; FCS = 0; Propulsion = 0; @@ -129,11 +127,17 @@ FGFDMExec::FGFDMExec(FGPropertyManager* root) : Root(root) Trim = 0; Script = 0; + RootDir = ""; + modelLoaded = false; IsChild = false; holding = false; Terminate = false; + sim_time = 0.0; + dT = 1.0/120.0; // a default timestep size. This is needed for when JSBSim is + // run in standalone mode with no initialization file. + IdFDM = FDMctr; // The main (parent) JSBSim instance is always the "zeroth" FDMctr++; // instance. "child" instances are loaded last. @@ -169,6 +173,9 @@ FGFDMExec::FGFDMExec(FGPropertyManager* root) : Root(root) instance->Tie("simulation/do_simple_trim", this, (iPMF)0, &FGFDMExec::DoTrim); instance->Tie("simulation/reset", this, (iPMF)0, &FGFDMExec::ResetToInitialConditions); instance->Tie("simulation/terminate", (int *)&Terminate); + instance->Tie("simulation/sim-time-sec", this, &FGFDMExec::GetSimTime); + instance->Tie("simulation/jsbsim-debug", this, &FGFDMExec::GetDebugLevel, &FGFDMExec::SetDebugLevel); + Constructing = false; } @@ -217,15 +224,11 @@ bool FGFDMExec::Allocate(void) Auxiliary = new FGAuxiliary(this); Input = new FGInput(this); - State = new FGState(this); // This must be done here, as the FGState - // class needs valid pointers to the above - // model classes - // Schedule a model. The second arg (the integer) is the pass number. For // instance, the atmosphere model could get executed every fifth pass it is called. Schedule(Input, 1); - Schedule(Atmosphere, 30); + Schedule(Atmosphere, 1); Schedule(FCS, 1); Schedule(Propulsion, 1); Schedule(MassBalance, 1); @@ -267,7 +270,6 @@ bool FGFDMExec::DeAllocate(void) delete Aircraft; delete Propagate; delete Auxiliary; - delete State; delete Script; for (unsigned i=0; iIntegrationSuspended()) success = Script->RunScript(); + if (Script != 0 && !IntegrationSuspended()) success = Script->RunScript(); vector ::iterator it; for (it = Models.begin(); it != Models.end(); ++it) (*it)->Run(); Frame++; - if (!Holding()) State->IncrTime(); + if (!Holding()) IncrTime(); if (Terminate) success = false; return (success); @@ -341,14 +342,49 @@ bool FGFDMExec::Run(void) bool FGFDMExec::RunIC(void) { - State->SuspendIntegration(); - State->Initialize(IC); + SuspendIntegration(); // saves the integration rate, dt, then sets it to 0.0. + Initialize(IC); Run(); - State->ResumeIntegration(); + ResumeIntegration(); // Restores the integration rate to what it was. return true; } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGFDMExec::Initialize(FGInitialCondition *FGIC) +{ + Propagate->SetInitialState( FGIC ); + + Atmosphere->Run(); + Atmosphere->SetWindNED( FGIC->GetWindNFpsIC(), + FGIC->GetWindEFpsIC(), + FGIC->GetWindDFpsIC() ); + + FGColumnVector3 vAeroUVW; + vAeroUVW = Propagate->GetUVW() + Propagate->GetTl2b()*Atmosphere->GetTotalWindNED(); + + double alpha, beta; + if (vAeroUVW(eW) != 0.0) + alpha = vAeroUVW(eU)*vAeroUVW(eU) > 0.0 ? atan2(vAeroUVW(eW), vAeroUVW(eU)) : 0.0; + else + alpha = 0.0; + if (vAeroUVW(eV) != 0.0) + 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; + else + beta = 0.0; + + Auxiliary->SetAB(alpha, beta); + + double Vt = vAeroUVW.Magnitude(); + Auxiliary->SetVt(Vt); + + Auxiliary->SetMach(Vt/Atmosphere->GetSoundSpeed()); + + double qbar = 0.5*Vt*Vt*Atmosphere->GetDensity(); + Auxiliary->Setqbar(qbar); +} + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // A private, internal function call for Tie-ing to a property, so it needs an @@ -388,20 +424,6 @@ void FGFDMExec::SetGroundCallback(FGGroundCallback* p) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -double FGFDMExec::GetSimTime(void) -{ - return (State->Getsim_time()); -} - -//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -double FGFDMExec::GetDeltaT(void) -{ - return (State->Getdt()); -} - -//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - vector FGFDMExec::EnumerateFDMs(void) { vector FDMList; @@ -417,12 +439,12 @@ vector FGFDMExec::EnumerateFDMs(void) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -bool FGFDMExec::LoadScript(string script) +bool FGFDMExec::LoadScript(string script, double deltaT) { bool result; Script = new FGScript(this); - result = Script->LoadScript(script); + result = Script->LoadScript(RootDir + script, deltaT); return result; } @@ -432,9 +454,9 @@ bool FGFDMExec::LoadScript(string script) bool FGFDMExec::LoadModel(string AircraftPath, string EnginePath, string SystemsPath, string model, bool addModelToPath) { - FGFDMExec::AircraftPath = AircraftPath; - FGFDMExec::EnginePath = EnginePath; - FGFDMExec::SystemsPath = SystemsPath; + FGFDMExec::AircraftPath = RootDir + AircraftPath; + FGFDMExec::EnginePath = RootDir + EnginePath; + FGFDMExec::SystemsPath = RootDir + SystemsPath; return LoadModel(model, addModelToPath); } @@ -445,7 +467,6 @@ bool FGFDMExec::LoadModel(string model, bool addModelToPath) { string token; string aircraftCfgFileName; - string separator = "/"; Element* element = 0L; bool result = false; // initialize result to false, indicating input file not yet read @@ -458,8 +479,8 @@ bool FGFDMExec::LoadModel(string model, bool addModelToPath) } FullAircraftPath = AircraftPath; - if (addModelToPath) FullAircraftPath += separator + model; - aircraftCfgFileName = FullAircraftPath + separator + model + ".xml"; + if (addModelToPath) FullAircraftPath += "/" + model; + aircraftCfgFileName = FullAircraftPath + "/" + model + ".xml"; if (modelLoaded) { DeAllocate(); @@ -645,6 +666,9 @@ bool FGFDMExec::LoadModel(string model, bool addModelToPath) modelLoaded = true; if (debug_lvl > 0) { + MassBalance->Run(); // Update all mass properties for the report. + MassBalance->GetMassPropertiesReport(); + cout << endl << fgblue << highint << "End of vehicle configuration loading." << endl << "-------------------------------------------------------------------------------" @@ -893,15 +917,17 @@ bool FGFDMExec::SetOutputDirectives(string fname) bool result; FGOutput* Output = new FGOutput(this); - Output->SetDirectivesFile(fname); + Output->SetDirectivesFile(RootDir + fname); Output->InitModel(); - Schedule(Output, 1); + Schedule(Output, 1); result = Output->Load(0); - Outputs.push_back(Output); - typedef int (FGOutput::*iOPMF)(void) const; - string outputProp = CreateIndexedPropertyName("simulation/output",Outputs.size()-1); - instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate); + if (result) { + Outputs.push_back(Output); + typedef int (FGOutput::*iOPMF)(void) const; + string outputProp = CreateIndexedPropertyName("simulation/output",Outputs.size()-1); + instance->Tie(outputProp+"/log_rate_hz", Output, (iOPMF)0, &FGOutput::SetRate); + } return result; } @@ -918,11 +944,11 @@ void FGFDMExec::DoTrim(int mode) cerr << endl << "Illegal trimming mode!" << endl << endl; return; } - saved_time = State->Getsim_time(); + saved_time = sim_time; FGTrim trim(this, (JSBSim::TrimMode)mode); if ( !trim.DoTrim() ) cerr << endl << "Trim Failed" << endl << endl; trim.Report(); - State->Setsim_time(saved_time); + sim_time = saved_time; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -936,7 +962,7 @@ void FGFDMExec::DoTrimAnalysis(int mode) cerr << endl << "Illegal trimming mode!" << endl << endl; return; } - saved_time = State->Getsim_time(); + saved_time = sim_time; FGTrimAnalysis trimAnalysis(this, (JSBSim::TrimAnalysisMode)mode); @@ -950,7 +976,7 @@ void FGFDMExec::DoTrimAnalysis(int mode) if ( !result ) cerr << endl << "Trim Failed" << endl << endl; trimAnalysis.Report(); - State->Setsim_time(saved_time); + Setsim_time(saved_time); EnableOutput(); cout << "\nOutput: " << GetOutputFileName() << endl; @@ -1025,7 +1051,7 @@ void FGFDMExec::Debug(int from) if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects if (from == 2) { cout << "================== Frame: " << Frame << " Time: " - << State->Getsim_time() << " dt: " << State->Getdt() << endl; + << sim_time << " dt: " << dT << endl; } } if (debug_lvl & 8 ) { // Runtime state variables diff --git a/src/FDM/JSBSim/FGFDMExec.h b/src/FDM/JSBSim/FGFDMExec.h index c1fbbb8ef..8c91cb2c9 100644 --- a/src/FDM/JSBSim/FGFDMExec.h +++ b/src/FDM/JSBSim/FGFDMExec.h @@ -60,7 +60,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FDMEXEC "$Id$" +#define ID_FDMEXEC "$Id: FGFDMExec.h,v 1.52 2010/07/04 13:50:21 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -169,7 +169,7 @@ CLASS DOCUMENTATION property actually maps toa function call of DoTrim(). @author Jon S. Berndt - @version $Revision$ + @version $Revision: 1.52 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -270,23 +270,23 @@ public: /** Loads a script @param Script the full path name and file name for the script to be loaded. @return true if successfully loadsd; false otherwise. */ - bool LoadScript(string Script); + bool LoadScript(string Script, double deltaT); /** Sets the path to the engine config file directories. @param path path to the directory under which engine config files are kept, for instance "engine" */ - bool SetEnginePath(string path) { EnginePath = path; return true; } + bool SetEnginePath(string path) { EnginePath = RootDir + path; return true; } /** Sets the path to the aircraft config file directories. @param path path to the aircraft directory. For instance: "aircraft". Under aircraft, then, would be directories for various modeled aircraft such as C172/, x15/, etc. */ - bool SetAircraftPath(string path) { AircraftPath = path; return true; } + bool SetAircraftPath(string path) { AircraftPath = RootDir + path; return true; } /** Sets the path to the systems config file directories. @param path path to the directory under which systems config files are kept, for instance "systems" */ - bool SetSystemsPath(string path) { SystemsPath = path; return true; } + bool SetSystemsPath(string path) { SystemsPath = RootDir + path; return true; } /// @name Top-level executive State and Model retrieval mechanism //@{ @@ -318,8 +318,6 @@ public: inline FGInput* GetInput(void) {return Input;} /// Returns the FGGroundCallback pointer. inline FGGroundCallback* GetGroundCallback(void) {return GroundCallback;} - /// Returns the FGState pointer. - inline FGState* GetState(void) {return State;} /// Retrieves the script object inline FGScript* GetScript(void) {return Script;} // Returns a pointer to the FGInitialCondition object @@ -351,19 +349,19 @@ public: /// Returns the model name. string GetModelName(void) { return modelName; } - +/* /// Returns the current time. double GetSimTime(void); /// Returns the current frame time (delta T). double GetDeltaT(void); - +*/ /// Returns a pointer to the property manager object. FGPropertyManager* GetPropertyManager(void); /// Returns a vector of strings representing the names of all loaded models (future) vector EnumerateFDMs(void); /// Gets the number of child FDMs. - int GetFDMCount(void) {return ChildFDMList.size();} + int GetFDMCount(void) {return (int)ChildFDMList.size();} /// Gets a particular child FDM. childData* GetChildFDM(int i) {return ChildFDMList[i];} /// Marks this instance of the Exec object as a "child" object. @@ -454,6 +452,8 @@ public: // Print the contents of the property catalog for the loaded aircraft. void PrintPropertyCatalog(void); + vector& GetPropertyCatalog(void) {return PropertyCatalog;} + /// Use the MSIS atmosphere model. void UseAtmosphereMSIS(void); @@ -465,12 +465,61 @@ public: void SetTrimMode(int mode){ ta_mode = mode; } int GetTrimMode(void) const { return ta_mode; } + /// Returns the cumulative simulation time in seconds. + double GetSimTime(void) const { return sim_time; } + + /// Returns the simulation delta T. + double GetDeltaT(void) {return dT;} + + /// Suspends the simulation and sets the delta T to zero. + void SuspendIntegration(void) {saved_dT = dT; dT = 0.0;} + + /// Resumes the simulation by resetting delta T to the correct value. + void ResumeIntegration(void) {dT = saved_dT;} + + /** Returns the simulation suspension state. + @return true if suspended, false if executing */ + bool IntegrationSuspended(void) {return dT == 0.0;} + + /** Sets the current sim time. + @param cur_time the current time + @return the current simulation time. */ + double Setsim_time(double cur_time) { + sim_time = cur_time; + return sim_time; + } + + /** Sets the integration time step for the simulation executive. + @param delta_t the time step in seconds. */ + void Setdt(double delta_t) { dT = delta_t; } + + /** Sets the root directory where JSBSim starts looking for its system directories. + @param rootDir the string containing the root directory. */ + void SetRootDir(string rootDir) {RootDir = rootDir;} + + /** Retrieves teh Root Directory. + @return the string representing the root (base) JSBSim directory. */ + string GetRootDir(void) const {return RootDir;} + + /** Increments the simulation time. + @return the new simulation time. */ + double IncrTime(void) { + sim_time += dT; + return sim_time; + } + + /** Retrieves the current debug level setting. */ + int GetDebugLevel(void) const {return debug_lvl;}; + private: static unsigned int FDMctr; int Error; unsigned int Frame; unsigned int IdFDM; unsigned short Terminate; + double dT; + double saved_dT; + double sim_time; bool holding; bool Constructing; bool modelLoaded; @@ -482,6 +531,7 @@ private: string SystemsPath; string CFGVersion; string Release; + string RootDir; bool trim_status; int ta_mode; @@ -489,7 +539,6 @@ private: static FGPropertyManager *master; FGGroundCallback* GroundCallback; - FGState* State; FGAtmosphere* Atmosphere; FGFCS* FCS; FGPropulsion* Propulsion; @@ -521,6 +570,7 @@ private: void ResetToInitialConditions(int mode); bool Allocate(void); bool DeAllocate(void); + void Initialize(FGInitialCondition *FGIC); void Debug(int from); }; diff --git a/src/FDM/JSBSim/FGJSBBase.cpp b/src/FDM/JSBSim/FGJSBBase.cpp index f07a4f081..a361a37d2 100644 --- a/src/FDM/JSBSim/FGJSBBase.cpp +++ b/src/FDM/JSBSim/FGJSBBase.cpp @@ -44,7 +44,7 @@ INCLUDES namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGJSBBase.cpp,v 1.29 2010/03/18 13:19:21 jberndt Exp $"; static const char *IdHdr = ID_JSBBASE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -77,8 +77,8 @@ CLASS IMPLEMENTATION char FGJSBBase::fgdef[6] = {'\0' }; #endif -const double FGJSBBase::radtodeg = 57.29578; -const double FGJSBBase::degtorad = 1.745329E-2; +const double FGJSBBase::radtodeg = 57.295779513082320876798154814105; +const double FGJSBBase::degtorad = 0.017453292519943295769236907684886; const double FGJSBBase::hptoftlbssec = 550.0; const double FGJSBBase::psftoinhg = 0.014138; const double FGJSBBase::psftopa = 47.88; diff --git a/src/FDM/JSBSim/FGJSBBase.h b/src/FDM/JSBSim/FGJSBBase.h index d4ceb2c97..2049a3cad 100644 --- a/src/FDM/JSBSim/FGJSBBase.h +++ b/src/FDM/JSBSim/FGJSBBase.h @@ -63,7 +63,7 @@ namespace std DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_JSBBASE "$Id$" +#define ID_JSBBASE "$Id: FGJSBBase.h,v 1.30 2010/07/01 23:13:19 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -79,7 +79,7 @@ CLASS DOCUMENTATION * This class provides universal constants, utility functions, messaging * functions, and enumerated constants to JSBSim. @author Jon S. Berndt - @version $Id$ + @version $Id: FGJSBBase.h,v 1.30 2010/07/01 23:13:19 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -310,7 +310,7 @@ protected: static std::queue Messages; - void Debug(int from) {}; + void Debug(int) {}; static unsigned int messageId; diff --git a/src/FDM/JSBSim/FGState.cpp b/src/FDM/JSBSim/FGState.cpp index 372d01e79..08e38a690 100644 --- a/src/FDM/JSBSim/FGState.cpp +++ b/src/FDM/JSBSim/FGState.cpp @@ -45,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGState.cpp,v 1.15 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_STATE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/FGState.h b/src/FDM/JSBSim/FGState.h index 9fd627eba..220f042fd 100644 --- a/src/FDM/JSBSim/FGState.h +++ b/src/FDM/JSBSim/FGState.h @@ -62,7 +62,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_STATE "$Id$" +#define ID_STATE "$Id: FGState.h,v 1.15 2009/10/02 10:30:07 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -78,7 +78,7 @@ CLASS DOCUMENTATION

Properties

@property sim-time-sec (read only) cumulative simulation in seconds. @author Jon S. Berndt - @version $Revision$ + @version $Revision: 1.15 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/JSBSim.cxx b/src/FDM/JSBSim/JSBSim.cxx index 15daa8e22..a915539cc 100644 --- a/src/FDM/JSBSim/JSBSim.cxx +++ b/src/FDM/JSBSim/JSBSim.cxx @@ -5,20 +5,20 @@ // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org // // This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License as +// modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// General Public License for more details. +// Lesser General Public License for more details. // -// You should have received a copy of the GNU General Public License +// You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // -// $Id$ +// $Id: JSBSim.cxx,v 1.62 2010/07/14 05:50:40 ehofman Exp $ #ifdef HAVE_CONFIG_H @@ -38,7 +38,6 @@ #include -#include #include #include
#include
@@ -46,7 +45,6 @@ #include "JSBSim.hxx" #include #include -#include #include #include #include @@ -59,6 +57,8 @@ #include #include #include +#include +#include #include #include #include @@ -103,7 +103,7 @@ public: double contact[3], normal[3], vel[3], agl = 0; mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal, vel, &agl); - n = FGColumnVector3( -normal[0], -normal[1], -normal[2] ); + n = FGColumnVector3( normal[0], normal[1], normal[2] ); v = FGColumnVector3( vel[0], vel[1], vel[2] ); cont = FGColumnVector3( contact[0], contact[1], contact[2] ); return agl; @@ -148,7 +148,6 @@ FGJSBsim::FGJSBsim( double dt ) // Register ground callback. fdmex->SetGroundCallback( new FGFSGroundCallback(this) ); - State = fdmex->GetState(); Atmosphere = fdmex->GetAtmosphere(); FCS = fdmex->GetFCS(); MassBalance = fdmex->GetMassBalance(); @@ -171,7 +170,13 @@ FGJSBsim::FGJSBsim( double dt ) SGPath systems_path( fgGetString("/sim/aircraft-dir") ); systems_path.append( "Systems" ); - State->Setdt( dt ); +// deprecate sim-time-sec for simulation/sim-time-sec +// remove alias with increased configuration file version number (2.1 or later) + SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec"); + fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node ); +// end of sim-time-sec deprecation patch + + fdmex->Setdt( dt ); result = fdmex->LoadModel( aircraft_path.str(), engine_path.str(), @@ -301,8 +306,6 @@ FGJSBsim::~FGJSBsim(void) void FGJSBsim::init() { - double tmp; - SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" ); // Explicitly call the superclass's @@ -333,6 +336,21 @@ void FGJSBsim::init() << ", " << fdmex->GetAtmosphere()->GetPressure() << ", " << fdmex->GetAtmosphere()->GetDensity() ); +// deprecate egt_degf for egt-degf to have consistent naming +// TODO: raise log-level to ALERT in summer 2010, +// remove alias in fall 2010, +// remove this code in winter 2010 + for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) { + SGPropertyNode * node = fgGetNode("engines/engine", i, true); + SGPropertyNode * egtn = node->getNode( "egt_degf" ); + if( egtn != NULL ) { + SG_LOG(SG_FLIGHT,SG_WARN, + "Aircraft uses deprecated node egt_degf. Please upgrade to egt-degf"); + node->getNode("egt-degf", true)->alias( egtn ); + } + } +// end of egt_degf deprecation patch + if (fgGetBool("/sim/presets/running")) { for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) { SGPropertyNode * node = fgGetNode("engines/engine", i, true); @@ -442,7 +460,7 @@ void FGJSBsim::update( double dt ) cart = FGLocation(lon, lat, alt+slr); } double cart_pos[3] = { cart(1), cart(2), cart(3) }; - double t0 = State->Getsim_time(); + double t0 = fdmex->GetSimTime(); bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos, groundCacheRadius ); if (!cache_ok) { @@ -470,7 +488,7 @@ void FGJSBsim::update( double dt ) if ( needTrim ) { if ( startup_trim->getBoolValue() ) { double contact[3], d[3], agl; - get_agl_ft(State->Getsim_time(), cart_pos, SG_METER_TO_FEET*2, contact, + get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact, d, d, &agl); double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1] + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC(); @@ -489,7 +507,7 @@ void FGJSBsim::update( double dt ) for ( i=0; i < multiloop; i++ ) { fdmex->Run(); - update_external_forces(State->Getsim_time() + i * State->Getdt()); + update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT()); } FGJSBBase::Message* msg; @@ -784,7 +802,7 @@ bool FGJSBsim::copy_from_JSBsim() FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i); node->setDoubleValue("n1", eng->GetN1()); node->setDoubleValue("n2", eng->GetN2()); - node->setDoubleValue("egt_degf", 32 + eng->GetEGT()*9/5); + node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5); node->setBoolValue("augmentation", eng->GetAugmentation()); node->setBoolValue("water-injection", eng->GetInjection()); node->setBoolValue("ignition", eng->GetIgnition()); @@ -828,6 +846,8 @@ bool FGJSBsim::copy_from_JSBsim() node->setDoubleValue("rpm", eng->getRPM()); } // end FGElectric code block break; + case FGEngine::etUnknown: + break; } { // FGEngine code block @@ -899,7 +919,7 @@ bool FGJSBsim::copy_from_JSBsim() // force a sim crashed if crashed (altitude AGL < 0) if (get_Altitude_AGL() < -100.0) { - State->SuspendIntegration(); + fdmex->SuspendIntegration(); crashed = true; } @@ -987,7 +1007,7 @@ void FGJSBsim::set_Altitude(double alt) _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET ); fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET ); SG_LOG(SG_FLIGHT, SG_INFO, - "Terrain elevation: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET ); + "Terrain elevation: " << FGInterface::get_Runway_altitude() * SG_METER_TO_FEET ); fgic->SetLatitudeRadIC( lat_geoc ); fgic->SetAltitudeASLFtIC(alt); needTrim=true; @@ -1149,9 +1169,6 @@ void FGJSBsim::do_trim(void) } else { trimmed->setBoolValue(true); } -// if (FGJSBBase::debug_lvl > 0) -// State->ReportState(); - delete fgtrim; pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() ); @@ -1268,7 +1285,6 @@ void FGJSBsim::update_external_forces(double t_off) FGColumnVector3 hook_tip_body = hook_root_body; hook_tip_body(1) -= hook_length * cos_fi; hook_tip_body(3) += hook_length * sin_fi; - bool hook_tip_valid = true; double contact[3]; double ground_normal[3]; diff --git a/src/FDM/JSBSim/JSBSim.hxx b/src/FDM/JSBSim/JSBSim.hxx index d6f5f1b8c..38c952bd2 100644 --- a/src/FDM/JSBSim/JSBSim.hxx +++ b/src/FDM/JSBSim/JSBSim.hxx @@ -8,16 +8,16 @@ ------ Copyright (C) 1999 - 2000 Curtis L. Olson (curt@flightgear.org) ------ This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License as + modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - General Public License for more details. + Lesser General Public License for more details. - You should have received a copy of the GNU General Public License + You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. @@ -38,7 +38,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #undef MAX_ENGINES -#include #include "math/FGColumnVector3.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -87,7 +86,7 @@ CLASS DOCUMENTATION documentation for main for direction on running JSBSim apart from FlightGear. @author Curtis L. Olson (original) @author Tony Peden (Maintained and refined) - @version $Id$ + @version $Id: JSBSim.hxx,v 1.13 2010/07/07 20:46:36 andgi Exp $ @see main in file JSBSim.cpp (use main() wrapper for standalone usage) */ diff --git a/src/FDM/JSBSim/initialization/FGInitialCondition.cpp b/src/FDM/JSBSim/initialization/FGInitialCondition.cpp index 7eb3f7f66..2d8f8a673 100644 --- a/src/FDM/JSBSim/initialization/FGInitialCondition.cpp +++ b/src/FDM/JSBSim/initialization/FGInitialCondition.cpp @@ -56,12 +56,13 @@ INCLUDES #include #include #include +#include "input_output/string_utilities.h" using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGInitialCondition.cpp,v 1.40 2010/06/02 04:05:13 jberndt Exp $"; static const char *IdHdr = ID_INITIALCONDITION; //****************************************************************************** @@ -704,23 +705,22 @@ double FGInitialCondition::calcVcas(double Mach) { double psl=fdmex->GetAtmosphere()->GetPressureSL(); double rhosl=fdmex->GetAtmosphere()->GetDensitySL(); double pt,A,B,D,vcas; - if(Mach < 0) Mach=0; - if(Mach < 1) //calculate total pressure assuming isentropic flow + + if (Mach < 0) Mach=0; + if (Mach < 1) //calculate total pressure assuming isentropic flow pt=p*pow((1 + 0.2*Mach*Mach),3.5); else { // shock in front of pitot tube, we'll assume its normal and use // the Rayleigh Pitot Tube Formula, i.e. the ratio of total - // pressure behind the shock to the static pressure in front - - - //the normal shock assumption should not be a bad one -- most supersonic - //aircraft place the pitot probe out front so that it is the forward - //most point on the aircraft. The real shock would, of course, take - //on something like the shape of a rounded-off cone but, here again, - //the assumption should be good since the opening of the pitot probe - //is very small and, therefore, the effects of the shock curvature - //should be small as well. AFAIK, this approach is fairly well accepted - //within the aerospace community + // pressure behind the shock to the static pressure in front of + // the normal shock assumption should not be a bad one -- most supersonic + // aircraft place the pitot probe out front so that it is the forward + // most point on the aircraft. The real shock would, of course, take + // on something like the shape of a rounded-off cone but, here again, + // the assumption should be good since the opening of the pitot probe + // is very small and, therefore, the effects of the shock curvature + // should be small as well. AFAIK, this approach is fairly well accepted + // within the aerospace community B = 5.76*Mach*Mach/(5.6*Mach*Mach - 0.8); @@ -842,8 +842,6 @@ double FGInitialCondition::GetWindDirDegIC(void) const { bool FGInitialCondition::Load(string rstfile, bool useStoredPath) { - int n; - string sep = "/"; if( useStoredPath ) { init_file_name = fdmex->GetFullAircraftPath() + sep + rstfile + ".xml"; @@ -864,6 +862,26 @@ bool FGInitialCondition::Load(string rstfile, bool useStoredPath) exit(-1); } + double version = document->GetAttributeValueAsNumber("version"); + if (version == HUGE_VAL) { + return Load_v1(); // Default to the old version + } else if (version >= 3.0) { + cerr << "Only initialization file formats 1 and 2 are currently supported" << endl; + exit (-1); + } else if (version >= 2.0) { + return Load_v2(); + } else if (version >= 1.0) { + return Load_v1(); + } + +} + +//****************************************************************************** + +bool FGInitialCondition::Load_v1(void) +{ + int n; + if (document->FindElement("latitude")) SetLatitudeDegIC(document->FindElementValueAsNumberConvertTo("latitude", "DEG")); if (document->FindElement("longitude")) @@ -941,6 +959,249 @@ bool FGInitialCondition::Load(string rstfile, bool useStoredPath) //****************************************************************************** +bool FGInitialCondition::Load_v2(void) +{ + int n; + FGColumnVector3 vLoc, vOrient; + bool result = true; + FGInertial* Inertial = fdmex->GetInertial(); + FGPropagate* Propagate = fdmex->GetPropagate(); + + if (document->FindElement("earth_position_angle")) { + double epa = document->FindElementValueAsNumberConvertTo("earth_position_angle", "RAD"); + Inertial->SetEarthPositionAngle(epa); + } + + // Initialize vehicle position + // + // Allowable frames: + // - ECI (Earth Centered Inertial) + // - ECEF (Earth Centered, Earth Fixed) + + Element* position = document->FindElement("position"); + if (position) { + vLoc = position->FindElementTripletConvertTo("FT"); + string frame = position->GetAttributeValue("frame"); + frame = to_lower(frame); + if (frame == "eci") { + // Need to transform vLoc to ECEF for storage and use in FGLocation. + vLoc = Propagate->GetTi2ec()*vLoc; + } else if (frame == "ecef") { + // Move vLoc query until after lat/lon/alt query to eliminate spurious warning msgs. + if (vLoc.Magnitude() == 0.0) { + Propagate->SetLatitudeDeg(position->FindElementValueAsNumberConvertTo("latitude", "DEG")); + Propagate->SetLongitudeDeg(position->FindElementValueAsNumberConvertTo("longitude", "DEG")); + if (position->FindElement("radius")) { + radius_to_vehicle = position->FindElementValueAsNumberConvertTo("radius", "FT"); + SetAltitudeASLFtIC(radius_to_vehicle - sea_level_radius); + } else if (position->FindElement("altitudeAGL")) { + SetAltitudeAGLFtIC(position->FindElementValueAsNumberConvertTo("altitudeAGL", "FT")); + } else if (position->FindElement("altitudeMSL")) { + SetAltitudeASLFtIC(position->FindElementValueAsNumberConvertTo("altitudeMSL", "FT")); + } else { + cerr << endl << " No altitude or radius initial condition is given." << endl; + result = false; + } + } + } else { + cerr << endl << " Neither ECI nor ECEF frame is specified for initial position." << endl; + result = false; + } + } else { + cerr << endl << " Initial position not specified in this initialization file." << endl; + result = false; + } + + // End of position initialization + + // Initialize vehicle orientation + // Allowable frames + // - ECI (Earth Centered Inertial) + // - ECEF (Earth Centered, Earth Fixed) + // - Local + // + // Need to convert the provided orientation to an ECI orientation, using + // the given orientation and knowledge of the Earth position angle. + // This could be done using matrices (where in the subscript "b/a", + // it is meant "b with respect to a", and where b=body frame, + // i=inertial frame, and e=ecef frame) as: + // + // C_b/i = C_b/e * C_e/i + // + // Using quaternions (note reverse ordering compared to matrix representation): + // + // Q_b/i = Q_e/i * Q_b/e + // + // Use the specific matrices as needed. The above example of course is for the whole + // body to inertial orientation. + // The new orientation angles can be extracted from the matrix or the quaternion. + // ToDo: Do we need to deal with normalization of the quaternions here? + + Element* orientation_el = document->FindElement("orientation"); + if (orientation_el) { + string frame = orientation_el->GetAttributeValue("frame"); + frame = to_lower(frame); + vOrient = orientation_el->FindElementTripletConvertTo("RAD"); + FGQuaternion QuatI2Body; + if (frame == "eci") { + + QuatI2Body = FGQuaternion(vOrient); + + } else if (frame == "ecef") { + + // In this case we are given the Euler angles representing the orientation of + // the body with respect to the ECEF system, represented by the C_b/e Matrix. + // We want the body orientation with respect to the inertial system: + // + // C_b/i = C_b/e * C_e/i + // + // Using quaternions (note reverse ordering compared to matrix representation): + // + // Q_b/i = Q_e/i * Q_b/e + + FGQuaternion QuatEC2Body(vOrient); // Store relationship of Body frame wrt ECEF frame, Q_b/e + FGQuaternion QuatI2EC = Propagate->GetTi2ec(); // Get Q_e/i from matrix + QuatI2Body = QuatI2EC * QuatEC2Body; // Q_b/i = Q_e/i * Q_b/e + + } else if (frame == "local") { + + // In this case, we are supplying the Euler angles for the vehicle with + // respect to the local (NED frame), also called the navigation frame. + // This is the most common way of initializing the orientation of + // aircraft. The matrix representation is: + // + // C_b/i = C_b/n * C_n/e * C_e/i + // + // Or, using quaternions (note reverse ordering compared to matrix representation): + // + // Q_b/i = Q_e/i * Q_n/e * Q_b/n + + FGQuaternion QuatLocal2Body = FGQuaternion(vOrient); // Store relationship of Body frame wrt local (NED) frame, Q_b/n + FGQuaternion QuatEC2Local = Propagate->GetTec2l(); // Get Q_n/e from matrix + FGQuaternion QuatI2EC = Propagate->GetTi2ec(); // Get Q_e/i from matrix + QuatI2Body = QuatI2EC * QuatEC2Local * QuatLocal2Body; // Q_b/i = Q_e/i * Q_n/e * Q_b/n + + } else { + + cerr << endl << fgred << " Orientation frame type: \"" << frame + << "\" is not supported!" << reset << endl << endl; + result = false; + + } + + Propagate->SetInertialOrientation(QuatI2Body); + } + + // Initialize vehicle velocity + // Allowable frames + // - ECI (Earth Centered Inertial) + // - ECEF (Earth Centered, Earth Fixed) + // - Local + // - Body + // The vehicle will be defaulted to (0,0,0) in the Body frame if nothing is provided. + + Element* velocity_el = document->FindElement("velocity"); + FGColumnVector3 vInertialVelocity; + FGColumnVector3 vInitVelocity = FGColumnVector3(0.0, 0.0, 0.0); + if (velocity_el) { + + string frame = velocity_el->GetAttributeValue("frame"); + frame = to_lower(frame); + FGColumnVector3 vInitVelocity = velocity_el->FindElementTripletConvertTo("FT/SEC"); + FGColumnVector3 omega_cross_r = Inertial->omega() * Propagate->GetInertialPosition(); + + if (frame == "eci") { + vInertialVelocity = vInitVelocity; + } else if (frame == "ecef") { + FGMatrix33 mTec2i = Propagate->GetTec2i(); // Get C_i/e + vInertialVelocity = mTec2i * vInitVelocity + omega_cross_r; + } else if (frame == "local") { + FGMatrix33 mTl2i = Propagate->GetTl2i(); + vInertialVelocity = mTl2i * vInitVelocity + omega_cross_r; + } else if (frame == "body") { + FGMatrix33 mTb2i = Propagate->GetTb2i(); + vInertialVelocity = mTb2i * vInitVelocity + omega_cross_r; + } else { + + cerr << endl << fgred << " Velocity frame type: \"" << frame + << "\" is not supported!" << reset << endl << endl; + result = false; + + } + + } else { + + FGMatrix33 mTb2i = Propagate->GetTb2i(); + vInertialVelocity = mTb2i * vInitVelocity + (Inertial->omega() * Propagate->GetInertialPosition()); + + } + + Propagate->SetInertialVelocity(vInertialVelocity); + + // Allowable frames + // - ECI (Earth Centered Inertial) + // - ECEF (Earth Centered, Earth Fixed) + // - Body + + FGColumnVector3 vInertialRate; + Element* attrate_el = document->FindElement("attitude_rate"); + if (attrate_el) { + + string frame = attrate_el->GetAttributeValue("frame"); + frame = to_lower(frame); + FGColumnVector3 vAttRate = attrate_el->FindElementTripletConvertTo("RAD/SEC"); + + if (frame == "eci") { + vInertialRate = vAttRate; + } else if (frame == "ecef") { +// vInertialRate = vAttRate + Inertial->omega(); + } else if (frame == "body") { + //Todo: determine local frame rate + FGMatrix33 mTb2l = Propagate->GetTb2l(); +// vInertialRate = mTb2l*vAttRate + Inertial->omega(); + } else if (!frame.empty()) { // misspelling of frame + + cerr << endl << fgred << " Attitude rate frame type: \"" << frame + << "\" is not supported!" << reset << endl << endl; + result = false; + + } else if (frame.empty()) { + + } + + } else { // Body frame attitude rate assumed 0 relative to local. +/* + //Todo: determine local frame rate + + FGMatrix33 mTi2l = Propagate->GetTi2l(); + vVel = mTi2l * vInertialVelocity; + + // Compute the local frame ECEF velocity + vVel = Tb2l * VState.vUVW; + + FGColumnVector3 vOmegaLocal = FGColumnVector3( + radInv*vVel(eEast), + -radInv*vVel(eNorth), + -radInv*vVel(eEast)*VState.vLocation.GetTanLatitude() ); +*/ + } + + // Check to see if any engines are specified to be initialized in a running state + FGPropulsion* propulsion = fdmex->GetPropulsion(); + Element* running_elements = document->FindElement("running"); + while (running_elements) { + n = int(running_elements->GetDataAsNumber()); + propulsion->InitRunning(n); + running_elements = document->FindNextElement("running"); + } + + // fdmex->RunIC(); + + return result; +} + +//****************************************************************************** + void FGInitialCondition::bind(void){ PropertyManager->Tie("ic/vc-kts", this, &FGInitialCondition::GetVcalibratedKtsIC, diff --git a/src/FDM/JSBSim/initialization/FGInitialCondition.h b/src/FDM/JSBSim/initialization/FGInitialCondition.h index 898acc3fd..b5c8c2819 100644 --- a/src/FDM/JSBSim/initialization/FGInitialCondition.h +++ b/src/FDM/JSBSim/initialization/FGInitialCondition.h @@ -56,7 +56,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_INITIALCONDITION "$Id$" +#define ID_INITIALCONDITION "$Id: FGInitialCondition.h,v 1.20 2010/02/15 03:22:57 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -202,7 +202,7 @@ CLASS DOCUMENTATION @property ic/r-rad_sec (read/write) Yaw rate initial condition in radians/second @author Tony Peden - @version "$Id$" + @version "$Id: FGInitialCondition.h,v 1.20 2010/02/15 03:22:57 jberndt Exp $" */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -647,6 +647,9 @@ private: FGFDMExec *fdmex; FGPropertyManager *PropertyManager; + bool Load_v1(void); + bool Load_v2(void); + bool Constructing; bool getAlpha(void); bool getTheta(void); diff --git a/src/FDM/JSBSim/initialization/FGTrim.cpp b/src/FDM/JSBSim/initialization/FGTrim.cpp index 2f425b769..6b0cd81c0 100644 --- a/src/FDM/JSBSim/initialization/FGTrim.cpp +++ b/src/FDM/JSBSim/initialization/FGTrim.cpp @@ -51,6 +51,8 @@ INCLUDES #include "models/FGGroundReactions.h" #include "models/FGInertial.h" #include "models/FGAerodynamics.h" +#include "models/FGPropulsion.h" +#include "models/propulsion/FGEngine.h" #include "math/FGColumnVector3.h" #if _MSC_VER @@ -61,7 +63,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGTrim.cpp,v 1.13 2010/04/23 17:23:40 dpculp Exp $"; static const char *IdHdr = ID_TRIM; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -239,6 +241,8 @@ bool FGTrim::DoTrim(void) { fdmex->DisableOutput(); + setEngineTrimMode(true); + fgic->SetPRadpsIC(0.0); fgic->SetQRadpsIC(0.0); fgic->SetRRadpsIC(0.0); @@ -354,6 +358,7 @@ bool FGTrim::DoTrim(void) { for(i=0;i < fdmex->GetGroundReactions()->GetNumGearUnits();i++){ fdmex->GetGroundReactions()->GetGearUnit(i)->SetReport(true); } + setEngineTrimMode(false); fdmex->EnableOutput(); return !trim_failed; } @@ -620,6 +625,15 @@ void FGTrim::setDebug(void) { //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +void FGTrim::setEngineTrimMode(bool mode) { + FGPropulsion* prop = fdmex->GetPropulsion(); + for (unsigned int i=0; iGetNumEngines(); i++) { + prop->GetEngine(i)->SetTrimMode(mode); + } +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + void FGTrim::SetMode(TrimMode tt) { ClearStates(); mode=tt; diff --git a/src/FDM/JSBSim/initialization/FGTrim.h b/src/FDM/JSBSim/initialization/FGTrim.h index 420f3fda2..0d6e3092c 100644 --- a/src/FDM/JSBSim/initialization/FGTrim.h +++ b/src/FDM/JSBSim/initialization/FGTrim.h @@ -60,7 +60,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_TRIM "$Id$" +#define ID_TRIM "$Id: FGTrim.h,v 1.7 2010/04/23 17:23:40 dpculp Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -120,7 +120,7 @@ CLASS DOCUMENTATION @endcode @author Tony Peden - @version "$Id$" + @version "$Id: FGTrim.h,v 1.7 2010/04/23 17:23:40 dpculp Exp $" */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -176,7 +176,7 @@ private: void setupTurn(void); void updateRates(void); - + void setEngineTrimMode(bool mode); void setDebug(void); public: diff --git a/src/FDM/JSBSim/initialization/FGTrimAxis.cpp b/src/FDM/JSBSim/initialization/FGTrimAxis.cpp index 186b9b1df..e0378793f 100644 --- a/src/FDM/JSBSim/initialization/FGTrimAxis.cpp +++ b/src/FDM/JSBSim/initialization/FGTrimAxis.cpp @@ -55,7 +55,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGTrimAxis.cpp,v 1.10 2010/07/08 11:36:28 jberndt Exp $"; static const char *IdHdr = ID_TRIMAXIS; /*****************************************************************************/ @@ -434,6 +434,10 @@ void FGTrimAxis::setThrottlesPct(void) { /*****************************************************************************/ void FGTrimAxis::AxisReport(void) { + // Save original cout format characteristics + std::ios_base::fmtflags originalFormat = cout.flags(); + std::streamsize originalPrecision = cout.precision(); + std::streamsize originalWidth = cout.width(); cout << " " << setw(20) << GetControlName() << ": "; cout << setw(6) << setprecision(2) << GetControl()*control_convert << ' '; cout << setw(5) << GetStateName() << ": "; @@ -444,6 +448,10 @@ void FGTrimAxis::AxisReport(void) { cout << " Passed" << endl; else cout << " Failed" << endl; + // Restore original cout format characteristics + cout.flags(originalFormat); + cout.precision(originalPrecision); + cout.width(originalWidth); } /*****************************************************************************/ diff --git a/src/FDM/JSBSim/initialization/FGTrimAxis.h b/src/FDM/JSBSim/initialization/FGTrimAxis.h index ac3d45f8f..9fc7cebb9 100644 --- a/src/FDM/JSBSim/initialization/FGTrimAxis.h +++ b/src/FDM/JSBSim/initialization/FGTrimAxis.h @@ -48,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_TRIMAXIS "$Id$" +#define ID_TRIMAXIS "$Id: FGTrimAxis.h,v 1.4 2006/10/01 22:47:47 jberndt Exp $" #define DEFAULT_TOLERANCE 0.001 diff --git a/src/FDM/JSBSim/input_output/FGGroundCallback.cpp b/src/FDM/JSBSim/input_output/FGGroundCallback.cpp index d1484115c..bf1cfb1b5 100644 --- a/src/FDM/JSBSim/input_output/FGGroundCallback.cpp +++ b/src/FDM/JSBSim/input_output/FGGroundCallback.cpp @@ -71,10 +71,11 @@ double FGGroundCallback::GetAGLevel(double t, const FGLocation& loc, FGColumnVector3& vel) const { vel = FGColumnVector3(0.0, 0.0, 0.0); - normal = (-1/FGColumnVector3(loc).Magnitude())*FGColumnVector3(loc); - double radius = loc.GetRadius(); - double agl = GetAltitude(loc); - contact = ((radius-agl)/radius)*FGColumnVector3(loc); + normal = FGColumnVector3(loc).Normalize(); + double loc_radius = loc.GetRadius(); // Get the radius of the given location + // (e.g. the CG) + double agl = loc_radius - mReferenceRadius; + contact = (mReferenceRadius/loc_radius)*FGColumnVector3(loc); return agl; } diff --git a/src/FDM/JSBSim/input_output/FGGroundCallback.h b/src/FDM/JSBSim/input_output/FGGroundCallback.h index 4def8c1ca..63955a4d0 100644 --- a/src/FDM/JSBSim/input_output/FGGroundCallback.h +++ b/src/FDM/JSBSim/input_output/FGGroundCallback.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_GROUNDCALLBACK "$Id$" +#define ID_GROUNDCALLBACK "$Id: FGGroundCallback.h,v 1.8 2009/10/02 10:30:09 jberndt Exp $" namespace JSBSim { @@ -59,7 +59,7 @@ CLASS DOCUMENTATION ball formed earth. @author Mathias Froehlich - @version $Id$ + @version $Id: FGGroundCallback.h,v 1.8 2009/10/02 10:30:09 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/input_output/FGPropertyManager.cpp b/src/FDM/JSBSim/input_output/FGPropertyManager.cpp index 991badb90..11e566965 100755 --- a/src/FDM/JSBSim/input_output/FGPropertyManager.cpp +++ b/src/FDM/JSBSim/input_output/FGPropertyManager.cpp @@ -74,7 +74,7 @@ FGPropertyManager::GetNode (const string &path, bool create) { SGPropertyNode* node=this->getNode(path.c_str(), create); if (node == 0 && !suppress_warning) { - cout << "FGPropertyManager::GetNode() No node found for " << path << endl; + cerr << "FGPropertyManager::GetNode() No node found for " << path << endl; } return (FGPropertyManager*)node; } @@ -152,6 +152,19 @@ string FGPropertyManager::GetFullyQualifiedName(void) { } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +string FGPropertyManager::GetRelativeName( const string &path ) +{ + string temp_string = GetFullyQualifiedName(); + size_t len = path.length(); + if ( (len > 0) && (temp_string.substr(0,len) == path) ) { + temp_string = temp_string.erase(0,len); + } + return temp_string; +} + + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -243,8 +256,8 @@ void FGPropertyManager::SetArchivable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) - cout << - "Attempt to set archive flag for non-existant property " + cerr << + "Attempt to set archive flag for non-existent property " << name << endl; else node->setAttribute(SGPropertyNode::ARCHIVE, state); @@ -256,7 +269,7 @@ void FGPropertyManager::SetReadable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) - cout << + cerr << "Attempt to set read flag for non-existant property " << name << endl; else @@ -269,7 +282,7 @@ void FGPropertyManager::SetWritable (const string &name, bool state ) { SGPropertyNode * node = getNode(name.c_str()); if (node == 0) - cout << + cerr << "Attempt to set write flag for non-existant property " << name << endl; else @@ -281,7 +294,7 @@ void FGPropertyManager::SetWritable (const string &name, bool state ) void FGPropertyManager::Untie (const string &name) { if (!untie(name.c_str())) - cout << "Failed to untie property " << name << endl; + cerr << "Failed to untie property " << name << endl; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -289,7 +302,7 @@ void FGPropertyManager::Untie (const string &name) void FGPropertyManager::Tie (const string &name, bool *pointer, bool useDefault) { if (!tie(name.c_str(), SGRawValuePointer(pointer), useDefault)) - cout << "Failed to tie property " << name << " to a pointer" << endl; + cerr << "Failed to tie property " << name << " to a pointer" << endl; else if (debug_lvl & 0x20) cout << name << endl; } @@ -300,7 +313,7 @@ void FGPropertyManager::Tie (const string &name, int *pointer, bool useDefault ) { if (!tie(name.c_str(), SGRawValuePointer(pointer), useDefault)) - cout << "Failed to tie property " << name << " to a pointer" << endl; + cerr << "Failed to tie property " << name << " to a pointer" << endl; else if (debug_lvl & 0x20) cout << name << endl; } @@ -311,7 +324,7 @@ void FGPropertyManager::Tie (const string &name, long *pointer, bool useDefault ) { if (!tie(name.c_str(), SGRawValuePointer(pointer), useDefault)) - cout << "Failed to tie property " << name << " to a pointer" << endl; + cerr << "Failed to tie property " << name << " to a pointer" << endl; else if (debug_lvl & 0x20) cout << name << endl; } @@ -322,7 +335,7 @@ void FGPropertyManager::Tie (const string &name, float *pointer, bool useDefault ) { if (!tie(name.c_str(), SGRawValuePointer(pointer), useDefault)) - cout << "Failed to tie property " << name << " to a pointer" << endl; + cerr << "Failed to tie property " << name << " to a pointer" << endl; else if (debug_lvl & 0x20) cout << name << endl; } @@ -332,7 +345,7 @@ void FGPropertyManager::Tie (const string &name, float *pointer, void FGPropertyManager::Tie (const string &name, double *pointer, bool useDefault) { if (!tie(name.c_str(), SGRawValuePointer(pointer), useDefault)) - cout << "Failed to tie property " << name << " to a pointer" << endl; + cerr << "Failed to tie property " << name << " to a pointer" << endl; else if (debug_lvl & 0x20) cout << name << endl; } diff --git a/src/FDM/JSBSim/input_output/FGPropertyManager.h b/src/FDM/JSBSim/input_output/FGPropertyManager.h index 2db5408e3..c29b5a412 100644 --- a/src/FDM/JSBSim/input_output/FGPropertyManager.h +++ b/src/FDM/JSBSim/input_output/FGPropertyManager.h @@ -53,7 +53,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PROPERTYMANAGER "$Id$" +#define ID_PROPERTYMANAGER "$Id: FGPropertyManager.h,v 1.17 2010/07/08 11:36:28 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -129,6 +129,15 @@ class FGPropertyManager : public SGPropertyNode, public FGJSBBase */ std::string GetFullyQualifiedName(void); + /** + * Get the qualified name of a node relative to given base path, + * otherwise the fully qualified name. + * This function is very slow, so is probably useful for debugging only. + * + * @param path The path to strip off, if found. + */ + std::string GetRelativeName( const std::string &path = "/fdm/jsbsim/" ); + /** * Get a bool value for a property. * diff --git a/src/FDM/JSBSim/input_output/FGScript.cpp b/src/FDM/JSBSim/input_output/FGScript.cpp index dde76de95..bd940bb4c 100755 --- a/src/FDM/JSBSim/input_output/FGScript.cpp +++ b/src/FDM/JSBSim/input_output/FGScript.cpp @@ -42,17 +42,19 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGScript.h" +#include "input_output/FGXMLElement.h" #include "input_output/FGXMLParse.h" #include "initialization/FGTrim.h" #include #include +#include using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGScript.cpp,v 1.41 2010/07/08 11:36:28 jberndt Exp $"; static const char *IdHdr = ID_FGSCRIPT; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -67,8 +69,8 @@ CLASS IMPLEMENTATION FGScript::FGScript(FGFDMExec* fgex) : FDMExec(fgex) { - State = FDMExec->GetState(); PropertyManager=FDMExec->GetPropertyManager(); + Debug(0); } @@ -89,7 +91,7 @@ FGScript::~FGScript() //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -bool FGScript::LoadScript( string script ) +bool FGScript::LoadScript(string script, double deltaT) { string aircraft="", initialize="", comparison = "", prop_name=""; string notifyPropertyName=""; @@ -135,10 +137,18 @@ bool FGScript::LoadScript( string script ) // Set sim timing StartTime = run_element->GetAttributeValueAsNumber("start"); - State->Setsim_time(StartTime); + FDMExec->Setsim_time(StartTime); EndTime = run_element->GetAttributeValueAsNumber("end"); - dt = run_element->GetAttributeValueAsNumber("dt"); - State->Setdt(dt); + + if (deltaT == 0.0) + dt = run_element->GetAttributeValueAsNumber("dt"); + else { + dt = deltaT; + cout << endl << "Overriding simulation step size from the command line. New step size is: " + << deltaT << " seconds (" << 1/deltaT << " Hz)" << endl << endl; + } + + FDMExec->Setdt(dt); // read aircraft and initialization files @@ -175,7 +185,7 @@ bool FGScript::LoadScript( string script ) if (output_file.empty()) { cerr << "No logging directives file was specified." << endl; } else { - FDMExec->SetOutputDirectives(output_file); + if (!FDMExec->SetOutputDirectives(output_file)) return false; } } @@ -226,7 +236,12 @@ bool FGScript::LoadScript( string script ) // Process the conditions condition_element = event_element->FindElement("condition"); if (condition_element != 0) { - newCondition = new FGCondition(condition_element, PropertyManager); + try { + newCondition = new FGCondition(condition_element, PropertyManager); + } catch(string str) { + cout << endl << fgred << str << reset << endl << endl; + return false; + } newEvent->Condition = newCondition; } else { cerr << "No condition specified in script event " << newEvent->Name << endl; @@ -320,7 +335,7 @@ bool FGScript::RunScript(void) unsigned i, j; unsigned event_ctr = 0; - double currentTime = State->Getsim_time(); + double currentTime = FDMExec->GetSimTime(); double newSetValue = 0; if (currentTime > EndTime) return false; //Script done! @@ -409,7 +424,7 @@ bool FGScript::RunScript(void) cout << endl << " Event " << event_ctr << " (" << Events[ev_ctr].Name << ")" << " executed at time: " << currentTime << endl; for (j=0; jGetName() + cout << " " << Events[ev_ctr].NotifyProperties[j]->GetRelativeName() << " = " << Events[ev_ctr].NotifyProperties[j]->getDoubleValue() << endl; } cout << endl; @@ -453,7 +468,8 @@ void FGScript::Debug(int from) cout << endl; cout << "Script: \"" << ScriptName << "\"" << endl; cout << " begins at " << StartTime << " seconds and runs to " << EndTime - << " seconds with dt = " << State->Getdt() << endl; + << " seconds with dt = " << setprecision(6) << FDMExec->GetDeltaT() << " (" << + ceil(1.0/FDMExec->GetDeltaT()) << " Hz)" << endl; cout << endl; for (unsigned int i=0; iPrintCondition(); - cout << endl << " Actions taken:" << endl << " {"; + cout << endl << " Actions taken"; + if (Events[i].Delay > 0.0) + cout << " (after a delay of " << Events[i].Delay << " secs)"; + cout << ":" << endl << " {"; for (unsigned j=0; jGetName() + cout << endl << " set " << Events[i].SetParam[j]->GetRelativeName("/fdm/jsbsim/") << " to function value"; } else { if (Events[i].SetParam[j] == 0) { @@ -496,7 +515,7 @@ void FGScript::Debug(int from) << reset << endl; exit(-1); } - cout << endl << " set " << Events[i].SetParam[j]->GetName() + cout << endl << " set " << Events[i].SetParam[j]->GetRelativeName("/fdm/jsbsim/") << " to " << Events[i].SetValue[j]; } @@ -529,8 +548,21 @@ void FGScript::Debug(int from) if (Events[i].Action[j] == FG_RAMP || Events[i].Action[j] == FG_EXP) cout << " with time constant " << Events[i].TC[j] << ")"; } - cout << endl << " }" << endl << endl; - + cout << endl << " }" << endl; + + // Print notifications + if (Events[i].Notify) { + if (Events[i].NotifyProperties.size() > 0) { + cout << " Notifications" << ":" << endl << " {" << endl; + for (unsigned j=0; jGetRelativeName("/fdm/jsbsim/") + << endl; + } + cout << " }" << endl; + } + } + cout << endl; } } } diff --git a/src/FDM/JSBSim/input_output/FGScript.h b/src/FDM/JSBSim/input_output/FGScript.h index 4dc5c8cf9..9f8d3ef8e 100644 --- a/src/FDM/JSBSim/input_output/FGScript.h +++ b/src/FDM/JSBSim/input_output/FGScript.h @@ -38,7 +38,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGJSBBase.h" -#include "FGState.h" #include "FGFDMExec.h" #include "math/FGFunction.h" #include "math/FGCondition.h" @@ -49,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FGSCRIPT "$Id$" +#define ID_FGSCRIPT "$Id: FGScript.h,v 1.18 2010/04/11 13:44:42 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -158,7 +157,7 @@ CLASS DOCUMENTATION comes the "run" section, where the conditions are described in "event" clauses.

@author Jon S. Berndt - @version "$Id$" + @version "$Id: FGScript.h,v 1.18 2010/04/11 13:44:42 jberndt Exp $" */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -175,10 +174,13 @@ public: ~FGScript(); /** Loads a script to drive JSBSim (usually in standalone mode). - The language is the Script Directives for JSBSim. + The language is the Script Directives for JSBSim. If a simulation step size + has been supplied on the command line, it will be override the script- + specified simulation step size. @param script the filename (including path name, if any) for the script. + @param deltaT a simulation step size from the command line @return true if successful */ - bool LoadScript( string script ); + bool LoadScript(string script, double deltaT); /** This function is called each pass through the executive Run() method IF scripting is enabled. @@ -259,7 +261,6 @@ private: vector local_properties; FGFDMExec* FDMExec; - FGState* State; FGPropertyManager* PropertyManager; void Debug(int from); }; diff --git a/src/FDM/JSBSim/input_output/FGXMLElement.cpp b/src/FDM/JSBSim/input_output/FGXMLElement.cpp index df541fa3a..0c3e91063 100755 --- a/src/FDM/JSBSim/input_output/FGXMLElement.cpp +++ b/src/FDM/JSBSim/input_output/FGXMLElement.cpp @@ -42,7 +42,7 @@ FORWARD DECLARATIONS namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGXMLElement.cpp,v 1.29 2010/03/18 13:18:31 jberndt Exp $"; static const char *IdHdr = ID_XMLELEMENT; bool Element::converterIsInitialized = false; @@ -114,7 +114,10 @@ Element::Element(const string& nm) convert["KTS"]["FT/SEC"] = 1.68781; convert["FT/SEC"]["KTS"] = 1.0/convert["KTS"]["FT/SEC"]; convert["M/S"]["FT/S"] = 3.2808399; + convert["M/SEC"]["FT/SEC"] = 3.2808399; convert["FT/S"]["M/S"] = 1.0/convert["M/S"]["FT/S"]; + convert["M/SEC"]["FT/SEC"] = 3.2808399; + convert["FT/SEC"]["M/SEC"] = 1.0/convert["M/SEC"]["FT/SEC"]; // Torque convert["FT*LBS"]["N*M"] = 1.35581795; convert["N*M"]["FT*LBS"] = 1/convert["FT*LBS"]["N*M"]; @@ -185,6 +188,7 @@ Element::Element(const string& nm) convert["FT/SEC"]["FT/SEC"] = 1.00; convert["KTS"]["KTS"] = 1.00; convert["M/S"]["M/S"] = 1.0; + convert["M/SEC"]["M/SEC"] = 1.0; // Torque convert["FT*LBS"]["FT*LBS"] = 1.00; convert["N*M"]["N*M"] = 1.00; diff --git a/src/FDM/JSBSim/input_output/FGXMLElement.h b/src/FDM/JSBSim/input_output/FGXMLElement.h index 75add86b7..21af97275 100755 --- a/src/FDM/JSBSim/input_output/FGXMLElement.h +++ b/src/FDM/JSBSim/input_output/FGXMLElement.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_XMLELEMENT "$Id$" +#define ID_XMLELEMENT "$Id: FGXMLElement.h,v 1.16 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -136,7 +136,7 @@ CLASS DOCUMENTATION - GAL = gallon (U.S. liquid) @author Jon S. Berndt - @version $Id$ + @version $Id: FGXMLElement.h,v 1.16 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/input_output/FGXMLFileRead.h b/src/FDM/JSBSim/input_output/FGXMLFileRead.h index 204c40138..d7366db7c 100755 --- a/src/FDM/JSBSim/input_output/FGXMLFileRead.h +++ b/src/FDM/JSBSim/input_output/FGXMLFileRead.h @@ -43,7 +43,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_XMLFILEREAD "$Id$" +#define ID_XMLFILEREAD "$Id: FGXMLFileRead.h,v 1.5 2009/11/28 20:12:47 andgi Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/input_output/FGXMLParse.cpp b/src/FDM/JSBSim/input_output/FGXMLParse.cpp index 7eefba94f..90fe0e7b9 100755 --- a/src/FDM/JSBSim/input_output/FGXMLParse.cpp +++ b/src/FDM/JSBSim/input_output/FGXMLParse.cpp @@ -40,7 +40,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGXMLParse.cpp,v 1.10 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_XMLPARSE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/input_output/FGXMLParse.h b/src/FDM/JSBSim/input_output/FGXMLParse.h index 5fdd92b06..350e3e6a7 100755 --- a/src/FDM/JSBSim/input_output/FGXMLParse.h +++ b/src/FDM/JSBSim/input_output/FGXMLParse.h @@ -40,7 +40,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_XMLPARSE "$Id$" +#define ID_XMLPARSE "$Id: FGXMLParse.h,v 1.7 2009/10/24 22:59:30 jberndt Exp $" #define VALID_CHARS """`!@#$%^&*()_+`1234567890-={}[];':,.<>/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -57,7 +57,7 @@ CLASS DOCUMENTATION /** Encapsulates an XML parser based on the EasyXML parser from the SimGear library. @author Jon S. Berndt - @version $Id$ + @version $Id: FGXMLParse.h,v 1.7 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/input_output/FGfdmSocket.cpp b/src/FDM/JSBSim/input_output/FGfdmSocket.cpp index 85cb88c4f..d1edb6739 100644 --- a/src/FDM/JSBSim/input_output/FGfdmSocket.cpp +++ b/src/FDM/JSBSim/input_output/FGfdmSocket.cpp @@ -52,7 +52,7 @@ using std::string; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGfdmSocket.cpp,v 1.27 2010/05/13 03:07:59 jberndt Exp $"; static const char *IdHdr = ID_FDMSOCKET; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -77,7 +77,9 @@ FGfdmSocket::FGfdmSocket(const string& address, int port, int protocol) cout << "Could not get host net address by name..." << endl; } } else { - if ((host = gethostbyaddr(address.c_str(), address.size(), PF_INET)) == NULL) { + unsigned int ip; + ip = inet_addr(address.c_str()); + if ((host = gethostbyaddr((char*)&ip, address.size(), PF_INET)) == NULL) { cout << "Could not get host net address by number..." << endl; } } diff --git a/src/FDM/JSBSim/input_output/FGfdmSocket.h b/src/FDM/JSBSim/input_output/FGfdmSocket.h index 46b41ad56..4c9e34b3c 100644 --- a/src/FDM/JSBSim/input_output/FGfdmSocket.h +++ b/src/FDM/JSBSim/input_output/FGfdmSocket.h @@ -51,6 +51,7 @@ INCLUDES #include #include #include + #include #include #include #include @@ -64,7 +65,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FDMSOCKET "$Id$" +#define ID_FDMSOCKET "$Id: FGfdmSocket.h,v 1.19 2010/05/13 03:07:59 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/input_output/string_utilities.h b/src/FDM/JSBSim/input_output/string_utilities.h index bc3a152a9..f2dc22090 100644 --- a/src/FDM/JSBSim/input_output/string_utilities.h +++ b/src/FDM/JSBSim/input_output/string_utilities.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_STRINGUTILS "$Id$" +#define ID_STRINGUTILS "$Id: string_utilities.h,v 1.13 2010/07/07 11:59:48 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -64,18 +64,19 @@ CLASS DECLARATION extern std::string& trim_left(std::string& str); extern std::string& trim_right(std::string& str); extern std::string& trim(std::string& str); + extern std::string& trim_all_space(std::string& str); extern std::string& to_upper(std::string& str); extern std::string& to_lower(std::string& str); extern bool is_number(const std::string& str); std::vector split(std::string str, char d); #else - #include + #include using namespace std; string& trim_left(string& str) { - while (str.size() && !isgraph(str[0])) { + while (str.size() && isspace((unsigned char)str[0])) { str = str.erase(0,1); } return str; @@ -83,7 +84,7 @@ CLASS DECLARATION string& trim_right(string& str) { - while (str.size() && !isgraph(str[str.size()-1])) { + while (str.size() && isspace((unsigned char)str[str.size()-1])) { str = str.erase(str.size()-1,1); } return str; @@ -96,6 +97,17 @@ CLASS DECLARATION return str = trim_left(temp_str); } + string& trim_all_space(string& str) + { + for (size_t i=0; iGetNode(property1, true); + TestParam1 = PropertyManager->GetNode(property1, false); + if (!TestParam1) { + cerr << fgred << " In condition: " << test << ". Unknown property " + << property1 << " referenced." << endl + << "Creating property. Check usage." << reset << endl; + TestParam1 = PropertyManager->GetNode(property1, true); + } Comparison = mComparison[conditional]; + if (Comparison == ecUndef) { + throw("Comparison operator: \""+conditional+"\" does not exist. Please check the conditional."); + } if (is_number(property2)) { TestValue = atof(property2.c_str()); } else { - TestParam2 = PropertyManager->GetNode(property2, true); + TestParam2 = PropertyManager->GetNode(property2, false); + if (!TestParam2) { + cerr << fgred << " In condition: " << test << ". Unknown property " + << property2 << " referenced." << endl + << "Creating property. Check usage." << reset << endl; + TestParam2 = PropertyManager->GetNode(property2, true); + } } } @@ -252,9 +267,12 @@ void FGCondition::PrintCondition(void ) } else { if (TestParam2 != 0L) - cout << " " << TestParam1->GetName() << " " << conditional << " " << TestParam2->GetName(); + cout << " " << TestParam1->GetRelativeName() << " " + << conditional << " " + << TestParam2->GetRelativeName(); else - cout << " " << TestParam1->GetName() << " " << conditional << " " << TestValue; + cout << " " << TestParam1->GetRelativeName() << " " + << conditional << " " << TestValue; } } diff --git a/src/FDM/JSBSim/math/FGCondition.h b/src/FDM/JSBSim/math/FGCondition.h index 6272a8371..2cd75bdfb 100644 --- a/src/FDM/JSBSim/math/FGCondition.h +++ b/src/FDM/JSBSim/math/FGCondition.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_CONDITION "$Id$" +#define ID_CONDITION "$Id: FGCondition.h,v 1.5 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/math/FGFunction.cpp b/src/FDM/JSBSim/math/FGFunction.cpp index e45e6d9aa..183654e2e 100755 --- a/src/FDM/JSBSim/math/FGFunction.cpp +++ b/src/FDM/JSBSim/math/FGFunction.cpp @@ -43,7 +43,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFunction.cpp,v 1.32 2010/03/18 13:21:24 jberndt Exp $"; static const char *IdHdr = ID_FUNCTION; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -265,7 +265,10 @@ double FGFunction::GetValue(void) const } break; case eQuotient: - temp /= Parameters[1]->GetValue(); + if (Parameters[1]->GetValue() != 0.0) + temp /= Parameters[1]->GetValue(); + else + temp = HUGE_VAL; break; case ePow: temp = pow(temp,Parameters[1]->GetValue()); diff --git a/src/FDM/JSBSim/math/FGFunction.h b/src/FDM/JSBSim/math/FGFunction.h index d122ffe20..91a811f9a 100755 --- a/src/FDM/JSBSim/math/FGFunction.h +++ b/src/FDM/JSBSim/math/FGFunction.h @@ -42,7 +42,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FUNCTION "$Id$" +#define ID_FUNCTION "$Id: FGFunction.h,v 1.21 2009/11/18 04:49:02 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/math/FGLocation.cpp b/src/FDM/JSBSim/math/FGLocation.cpp index 42619b93f..f3c4d88bc 100644 --- a/src/FDM/JSBSim/math/FGLocation.cpp +++ b/src/FDM/JSBSim/math/FGLocation.cpp @@ -45,7 +45,7 @@ INCLUDES namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGLocation.cpp,v 1.21 2010/07/02 01:48:12 jberndt Exp $"; static const char *IdHdr = ID_LOCATION; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -64,6 +64,19 @@ FGLocation::FGLocation(void) e = 1.0; eps2 = -1.0; f = 1.0; + epa = 0.0; + + mLon = mLat = mRadius = mGeodLat = GeodeticAltitude = 0.0; + +// initial_longitude = 0.0; + + mTl2ec.InitMatrix(); + mTec2l.InitMatrix(); + mTi2ec.InitMatrix(); + mTec2i.InitMatrix(); + mTi2l.InitMatrix(); + mTl2i.InitMatrix(); + mECLoc.InitMatrix(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -76,7 +89,7 @@ FGLocation::FGLocation(double lon, double lat, double radius) double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); - initial_longitude = lon; + a = 0.0; b = 0.0; a2 = 0.0; @@ -85,9 +98,15 @@ FGLocation::FGLocation(double lon, double lat, double radius) e = 1.0; eps2 = -1.0; f = 1.0; + epa = 0.0; mECLoc = FGColumnVector3( radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat ); + mLon = mLat = mRadius = mGeodLat = GeodeticAltitude = 0.0; + +// initial_longitude = 0.0 + + ComputeDerived(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -159,7 +178,7 @@ void FGLocation::SetPosition(double lon, double lat, double radius) double cosLat = cos(lat); double sinLon = sin(lon); double cosLon = cos(lon); - initial_longitude = lon; +// initial_longitude = lon; mECLoc = FGColumnVector3( radius*cosLat*cosLon, radius*cosLat*sinLon, radius*sinLat ); @@ -176,7 +195,7 @@ void FGLocation::SetPositionGeodetic(double lon, double lat, double height) mLon = lon; GeodeticAltitude = height; - initial_longitude = mLon; +// initial_longitude = mLon; double RN = a / sqrt(1.0 - e2*sin(mGeodLat)*sin(mGeodLat)); @@ -204,25 +223,23 @@ void FGLocation::SetEllipse(double semimajor, double semiminor) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Compute the ECEF to ECI transformation matrix using Stevens and Lewis "Aircraft -// Control and Simulation", second edition, eqn. 1.4-12, pg. 39 +// Control and Simulation", second edition, eqn. 1.4-12, pg. 39. In Stevens and Lewis +// notation, this is C_i/e, a transformation from ECEF to ECI. -const FGMatrix33& FGLocation::GetTec2i(double epa) +const FGMatrix33& FGLocation::GetTec2i(void) { - double mu = epa - initial_longitude; - mTec2i = FGMatrix33( cos(mu), -sin(mu), 0.0, - sin(mu), cos(mu), 0.0, - 0.0, 0.0, 1.0 ); return mTec2i; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// This is given in Stevens and Lewis "Aircraft +// Control and Simulation", second edition, eqn. 1.4-12, pg. 39 +// The notation in Stevens and Lewis is: C_e/i. This represents a transformation +// from ECI to ECEF - and the orientation of the ECEF frame relative to the ECI +// frame. -const FGMatrix33& FGLocation::GetTi2ec(double epa) +const FGMatrix33& FGLocation::GetTi2ec(void) { - double mu = epa - initial_longitude; - mTi2ec = FGMatrix33( cos(mu), sin(mu), 0.0, - -sin(mu), cos(mu), 0.0, - 0.0, 0.0, 1.0 ); return mTi2ec; } @@ -235,7 +252,8 @@ void FGLocation::ComputeDerivedUnconditional(void) const // The distance of the location to the Z-axis, which is the axis // through the poles. - double rxy = sqrt(mECLoc(eX)*mECLoc(eX) + mECLoc(eY)*mECLoc(eY)); + double r02 = mECLoc(eX)*mECLoc(eX) + mECLoc(eY)*mECLoc(eY); + double rxy = sqrt(r02); // Compute the sin/cos values of the longitude double sinLon, cosLon; @@ -270,23 +288,42 @@ void FGLocation::ComputeDerivedUnconditional(void) const // Compute the transform matrices from and to the earth centered frame. // See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, - // Eqn. 1.4-13, page 40. + // Eqn. 1.4-13, page 40. In Stevens and Lewis notation, this is C_n/e - the + // orientation of the navigation (local) frame relative to the ECEF frame, + // and a transformation from ECEF to nav (local) frame. + mTec2l = FGMatrix33( -cosLon*sinLat, -sinLon*sinLat, cosLat, -sinLon , cosLon , 0.0 , -cosLon*cosLat, -sinLon*cosLat, -sinLat ); + // In Stevens and Lewis notation, this is C_e/n - the + // orientation of the ECEF frame relative to the nav (local) frame, + // and a transformation from nav (local) to ECEF frame. + mTl2ec = mTec2l.Transposed(); - + + // Calculate the inertial to ECEF and transpose matrices + double cos_epa = cos(epa); + double sin_epa = sin(epa); + mTi2ec = FGMatrix33( cos_epa, sin_epa, 0.0, + -sin_epa, cos_epa, 0.0, + 0.0, 0.0, 1.0 ); + mTec2i = mTi2ec.Transposed(); + + // Now calculate the local (or nav, or ned) frame to inertial transform matrix, + // and the inverse. + mTl2i = mTec2i * mTl2ec; + mTi2l = mTl2i.Transposed(); + // Calculate the geodetic latitude base on AIAA Journal of Guidance and Control paper, // "Improved Method for Calculating Exact Geodetic Latitude and Altitude", and // "Improved Method for Calculating Exact Geodetic Latitude and Altitude, Revisited", // author: I. Sofair if (a != 0.0 && b != 0.0) { - double c, p, q, s, t, u, v, w, z, p2, u2, r02, r0; + double c, p, q, s, t, u, v, w, z, p2, u2, r0; double Ne, P, Q0, Q, signz0, sqrt_q; p = fabs(mECLoc(eZ))/eps2; - r02 = mECLoc(eX)*mECLoc(eX) + mECLoc(eY)*mECLoc(eY); s = r02/(e2*eps2); p2 = p*p; q = p2 - b2 + s; @@ -306,7 +343,7 @@ void FGLocation::ComputeDerivedUnconditional(void) const z = signz0*sqrt_q*(w+sqrt(sqrt(t*t+v)-u*w-0.5*t-0.25)); Ne = a*sqrt(1+eps2*z*z/b2); mGeodLat = asin((eps2+1.0)*(z/Ne)); - r0 = sqrt(r02); + r0 = rxy; GeodeticAltitude = r0*cos(mGeodLat) + mECLoc(eZ)*sin(mGeodLat) - a2/Ne; } } diff --git a/src/FDM/JSBSim/math/FGLocation.h b/src/FDM/JSBSim/math/FGLocation.h index b61ffa966..2112557de 100644 --- a/src/FDM/JSBSim/math/FGLocation.h +++ b/src/FDM/JSBSim/math/FGLocation.h @@ -48,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_LOCATION "$Id$" +#define ID_LOCATION "$Id: FGLocation.h,v 1.23 2010/08/04 07:28:21 ehofman Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -60,79 +60,89 @@ namespace JSBSim { CLASS DOCUMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -/** Holds an arbitrary location in the earth centered reference frame. - This coordinate frame has its center in the middle of the earth. - Its x-axis points from the center of the earth towards a location - with zero latitude and longitude on the earths surface. The y-axis - points from the center of the earth towards a location with zero - latitude and 90deg longitude on the earths surface. The z-axis - points from the earths center to the geographic north pole. - - This class provides access functions to set and get the location as - either the simple x, y and z values in ft or longitude/latitude and - the radial distance of the location from the earth center. - - It is common to associate a parent frame with a location. This - frame is usually called the local horizontal frame or simply the local - frame. This frame has its x/y plane parallel to the surface of the earth - (with the assumption of a spherical earth). The x-axis points - towards north, the y-axis points towards east and the z-axis - points to the center of the earth. - - Since this frame is determined by the location, this class also - provides the rotation matrices required to transform from the - earth centered frame to the local horizontal frame and back. There - are also conversion functions for conversion of position vectors - given in the one frame to positions in the other frame. - - The earth centered reference frame is *NOT* an inertial frame - since it rotates with the earth. - - The coordinates in the earth centered frame are the master values. - All other values are computed from these master values and are - cached as long as the location is changed by access through a - non-const member function. Values are cached to improve performance. - It is best practice to work with a natural set of master values. - Other parameters that are derived from these master values are calculated - only when needed, and IF they are needed and calculated, then they are - cached (stored and remembered) so they do not need to be re-calculated - until the master values they are derived from are themselves changed - (and become stale). - - Accuracy and round off: - - Given that we model a vehicle near the earth, the earths surface - radius is about 2*10^7, ft and that we use double values for the - representation of the location, we have an accuracy of about - 1e-16*2e7ft/1=2e-9ft left. This should be sufficient for our needs. - Note that this is the same relative accuracy we would have when we - compute directly with lon/lat/radius. For the radius value this - is clear. For the lon/lat pair this is easy to see. Take for - example KSFO located at about 37.61deg north 122.35deg west, which - corresponds to 0.65642rad north and 2.13541rad west. Both values - are of magnitude of about 1. But 1ft corresponds to about - 1/(2e7*2*pi)=7.9577e-09rad. So the left accuracy with this - representation is also about 1*1e-16/7.9577e-09=1.2566e-08 which - is of the same magnitude as the representation chosen here. - - The advantage of this representation is that it is a linear space - without singularities. The singularities are the north and south - pole and most notably the non-steady jump at -pi to pi. It is - harder to track this jump correctly especially when we need to - work with error norms and derivatives of the equations of motion - within the time-stepping code. Also, the rate of change is of the - same magnitude for all components in this representation which is - an advantage for numerical stability in implicit time-stepping too. - - Note: The latitude is a GEOCENTRIC value. FlightGear - converts latitude to a geodetic value and uses that. In order to get best - matching relative to a map, geocentric latitude must be converted to geodetic. +/** FGLocation holds an arbitrary location in the Earth centered Earth fixed + reference frame (ECEF). This coordinate frame has its center in the middle + of the earth. The X-axis points from the center of the Earth towards a + location with zero latitude and longitude on the Earth surface. The Y-axis + points from the center of the Earth towards a location with zero latitude + and 90 deg East longitude on the Earth surface. The Z-axis points from the + Earth center to the geographic north pole. + + This class provides access functions to set and get the location as either + the simple X, Y and Z values in ft or longitude/latitude and the radial + distance of the location from the Earth center. + + It is common to associate a parent frame with a location. This frame is + usually called the local horizontal frame or simply the local frame. It is + also called the NED frame (North, East, Down), as well as the Navigation + frame. This frame has its X/Y plane parallel to the surface of the Earth + (with the assumption of a spherical Earth). The X-axis points towards north, + the Y-axis points east and the Z-axis points to the center of the Earth. + + Since the local frame is determined by the location (and NOT by the + orientation of the vehicle IN any frame), this class also provides the + rotation matrices required to transform from the Earth centered (ECEF) frame + to the local horizontal frame and back. This class also "owns" the + transformations that go from the inertial frame (Earth-centered Inertial, or + ECI) to and from the ECEF frame, as well as to and from the local frame. + Again, this is because the ECI, ECEF, and local frames do not involve the + actual orientation of the vehicle - only the location on the Earth surface, + and the angular difference between the ECI and ECEF frames. There are + conversion functions for conversion of position vectors given in the one + frame to positions in the other frame. + + The Earth centered reference frame is NOT an inertial frame since it rotates + with the Earth. + + The coordinates in the Earth centered frame are the master values. All other + values are computed from these master values and are cached as long as the + location is changed by access through a non-const member function. Values + are cached to improve performance. It is best practice to work with a + natural set of master values. Other parameters that are derived from these + master values are calculated only when needed, and IF they are needed and + calculated, then they are cached (stored and remembered) so they do not need + to be re-calculated until the master values they are derived from are + themselves changed (and become stale). + + Accuracy and round off + + Given, + + -that we model a vehicle near the Earth + -that the Earth surface radius is about 2*10^7, ft + -that we use double values for the representation of the location + + we have an accuracy of about + + 1e-16*2e7ft/1 = 2e-9 ft + + left. This should be sufficient for our needs. Note that this is the same + relative accuracy we would have when we compute directly with + lon/lat/radius. For the radius value this is clear. For the lon/lat pair + this is easy to see. Take for example KSFO located at about 37.61 deg north + 122.35 deg west, which corresponds to 0.65642 rad north and 2.13541 rad + west. Both values are of magnitude of about 1. But 1 ft corresponds to about + 1/(2e7*2*pi) = 7.9577e-09 rad. So the left accuracy with this representation + is also about 1*1e-16/7.9577e-09 = 1.2566e-08 which is of the same magnitude + as the representation chosen here. + + The advantage of this representation is that it is a linear space without + singularities. The singularities are the north and south pole and most + notably the non-steady jump at -pi to pi. It is harder to track this jump + correctly especially when we need to work with error norms and derivatives + of the equations of motion within the time-stepping code. Also, the rate of + change is of the same magnitude for all components in this representation + which is an advantage for numerical stability in implicit time-stepping. + + Note: The latitude is a GEOCENTRIC value. FlightGear converts latitude to a + geodetic value and uses that. In order to get best matching relative to a + map, geocentric latitude must be converted to geodetic. @see Stevens and Lewis, "Aircraft Control and Simulation", Second edition @see W. C. Durham "Aircraft Dynamics & Control", section 2.2 @author Mathias Froehlich - @version $Id$ + @version $Id: FGLocation.h,v 1.23 2010/08/04 07:28:21 ehofman Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -244,6 +254,13 @@ public: and semiminor axis lengths */ void SetEllipse(double semimajor, double semiminor); + /** Sets the Earth position angle. + This is the relative orientation of the ECEF frame with respect to the + Inertial frame. + @param EPA Earth fixed frame (ECEF) rotation offset about the axis with + respect to the Inertial (ECI) frame in radians. */ + void SetEarthPositionAngle(double EPA) {epa = EPA; mCacheValid = false; ComputeDerived();} + /** Get the longitude. @return the longitude in rad of the location represented with this class instance. The returned values are in the range between @@ -309,6 +326,7 @@ public: @return the distance of the location represented with this class instance to the center of the earth in ft. The radius value is always positive. */ + //double GetRadius() const { return mECLoc.Magnitude(); } // may not work with FlightGear double GetRadius() const { ComputeDerived(); return mRadius; } /** Transform matrix from local horizontal to earth centered frame. @@ -324,12 +342,16 @@ public: /** Transform matrix from inertial to earth centered frame. Returns a const reference to the rotation matrix of the transform from the inertial frame to the earth centered frame (ECI to ECEF). */ - const FGMatrix33& GetTi2ec(double epa); + const FGMatrix33& GetTi2ec(void); /** Transform matrix from the earth centered to inertial frame. Returns a const reference to the rotation matrix of the transform from the earth centered frame to the inertial frame (ECEF to ECI). */ - const FGMatrix33& GetTec2i(double epa); + const FGMatrix33& GetTec2i(void); + + const FGMatrix33& GetTi2l(void) const {return mTi2l;} + + const FGMatrix33& GetTl2i(void) const {return mTl2i;} /** Conversion from Local frame coordinates to a location in the earth centered and fixed frame. @@ -354,14 +376,14 @@ public: Return the value of the matrix entry at the given index. Indices are counted starting with 1. Note that the index given in the argument is unchecked. */ - double operator()(unsigned int idx) const { return Entry(idx); } + double operator()(unsigned int idx) const { return mECLoc.Entry(idx); } /** Write access the entries of the vector. @param idx the component index. @return a reference to the vector entry at the given index. Indices are counted starting with 1. Note that the index given in the argument is unchecked. */ - double& operator()(unsigned int idx) { return Entry(idx); } + double& operator()(unsigned int idx) { mCacheValid = false; return mECLoc.Entry(idx); } /** Read access the entries of the vector. @param idx the component index. @@ -385,6 +407,12 @@ public: mCacheValid = false; return mECLoc.Entry(idx); } + /** Sets this location via the supplied vector. + The location can be set by an Earth-centered, Earth-fixed (ECEF) frame + position vector. The cache is marked as invalid, so any future requests + for selected important data will cause the parameters to be calculated. + @param v the ECEF column vector in feet. + @return a reference to the FGLocation object. */ const FGLocation& operator=(const FGColumnVector3& v) { mECLoc(eX) = v(eX); @@ -395,6 +423,9 @@ public: return *this; } + /** Sets this location via the supplied location object. + @param v A location object reference. + @return a reference to the FGLocation object. */ const FGLocation& operator=(const FGLocation& l) { mECLoc = l.mECLoc; @@ -422,31 +453,47 @@ public: return *this; } + + /** This operator returns true if the ECEF location vectors for the two + location objects are equal. */ bool operator==(const FGLocation& l) const { return mECLoc == l.mECLoc; } + + /** This operator returns true if the ECEF location vectors for the two + location objects are not equal. */ bool operator!=(const FGLocation& l) const { return ! operator==(l); } + + /** This operator adds the ECEF position vectors. + The supplied vector (right side) is added to the ECEF position vector + on the left side of the equality, and a pointer to this object is + returned. */ const FGLocation& operator+=(const FGLocation &l) { mCacheValid = false; mECLoc += l.mECLoc; return *this; } + const FGLocation& operator-=(const FGLocation &l) { mCacheValid = false; mECLoc -= l.mECLoc; return *this; } + const FGLocation& operator*=(double scalar) { mCacheValid = false; mECLoc *= scalar; return *this; } + const FGLocation& operator/=(double scalar) { return operator*=(1.0/scalar); } + FGLocation operator+(const FGLocation& l) const { return FGLocation(mECLoc + l.mECLoc); } + FGLocation operator-(const FGLocation& l) const { return FGLocation(mECLoc - l.mECLoc); } @@ -500,7 +547,11 @@ private: mutable FGMatrix33 mTec2l; mutable FGMatrix33 mTi2ec; mutable FGMatrix33 mTec2i; - + mutable FGMatrix33 mTi2l; + mutable FGMatrix33 mTl2i; + + double epa; + /* Terms for geodetic latitude calculation. Values are from WGS84 model */ double a; // Earth semimajor axis in feet (6,378,137.0 meters) double b; // Earth semiminor axis in feet (6,356,752.3142 meters) diff --git a/src/FDM/JSBSim/math/FGMatrix33.cpp b/src/FDM/JSBSim/math/FGMatrix33.cpp index 5eccfdfce..379b37004 100644 --- a/src/FDM/JSBSim/math/FGMatrix33.cpp +++ b/src/FDM/JSBSim/math/FGMatrix33.cpp @@ -48,7 +48,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGMatrix33.cpp,v 1.10 2010/07/01 23:13:19 jberndt Exp $"; static const char *IdHdr = ID_MATRIX33; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -70,20 +70,94 @@ FGMatrix33::FGMatrix33(void) string FGMatrix33::Dump(const string& delimiter) const { ostringstream buffer; - buffer << std::setw(18) << std::setprecision(16) << Entry(1,1) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(1,2) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(1,3) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(2,1) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(2,2) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(2,3) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(3,1) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(3,2) << delimiter; - buffer << std::setw(18) << std::setprecision(16) << Entry(3,3); + buffer << setw(12) << setprecision(10) << data[0] << delimiter; + buffer << setw(12) << setprecision(10) << data[3] << delimiter; + buffer << setw(12) << setprecision(10) << data[6] << delimiter; + buffer << setw(12) << setprecision(10) << data[1] << delimiter; + buffer << setw(12) << setprecision(10) << data[4] << delimiter; + buffer << setw(12) << setprecision(10) << data[7] << delimiter; + buffer << setw(12) << setprecision(10) << data[2] << delimiter; + buffer << setw(12) << setprecision(10) << data[5] << delimiter; + buffer << setw(12) << setprecision(10) << data[8]; return buffer.str(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +string FGMatrix33::Dump(const string& delimiter, const string& prefix) const +{ + ostringstream buffer; + + buffer << prefix << right << fixed << setw(9) << setprecision(6) << data[0] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[3] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[6] << endl; + + buffer << prefix << right << fixed << setw(9) << setprecision(6) << data[1] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[4] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[7] << endl; + + buffer << prefix << right << fixed << setw(9) << setprecision(6) << data[2] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[5] << delimiter; + buffer << right << fixed << setw(9) << setprecision(6) << data[8]; + + buffer << setw(0) << left; + + return buffer.str(); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FGQuaternion FGMatrix33::GetQuaternion(void) +{ + FGQuaternion Q; + + double tempQ[4]; + int idx; + + tempQ[0] = 1.0 + data[0] + data[4] + data[8]; + tempQ[1] = 1.0 + data[0] - data[4] - data[8]; + tempQ[2] = 1.0 - data[0] + data[4] - data[8]; + tempQ[3] = 1.0 - data[0] - data[4] + data[8]; + + // Find largest of the above + idx = 0; + for (int i=1; i<4; i++) if (tempQ[i] > tempQ[idx]) idx = i; + + switch(idx) { + case 0: + Q(1) = 0.50*sqrt(tempQ[0]); + Q(2) = 0.25*(data[7] - data[5])/Q(1); + Q(3) = 0.25*(data[2] - data[6])/Q(1); + Q(4) = 0.25*(data[3] - data[1])/Q(1); + break; + case 1: + Q(2) = 0.50*sqrt(tempQ[1]); + Q(1) = 0.25*(data[7] - data[5])/Q(2); + Q(3) = 0.25*(data[3] + data[1])/Q(2); + Q(4) = 0.25*(data[2] + data[6])/Q(2); + break; + case 2: + Q(3) = 0.50*sqrt(tempQ[2]); + Q(1) = 0.25*(data[2] - data[6])/Q(3); + Q(2) = 0.25*(data[3] + data[1])/Q(3); + Q(4) = 0.25*(data[7] + data[5])/Q(3); + break; + case 3: + Q(4) = 0.50*sqrt(tempQ[3]); + Q(1) = 0.25*(data[3] - data[1])/Q(4); + Q(2) = 0.25*(data[6] + data[2])/Q(4); + Q(3) = 0.25*(data[7] + data[5])/Q(4); + break; + default: + //error + break; + } + + return (Q); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + ostream& operator<<(ostream& os, const FGMatrix33& M) { for (unsigned int i=1; i<=M.Rows(); i++) { @@ -112,9 +186,9 @@ istream& operator>>(istream& is, FGMatrix33& M) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% double FGMatrix33::Determinant(void) const { - return Entry(1,1)*Entry(2,2)*Entry(3,3) + Entry(1,2)*Entry(2,3)*Entry(3,1) - + Entry(1,3)*Entry(2,1)*Entry(3,2) - Entry(1,3)*Entry(2,2)*Entry(3,1) - - Entry(1,2)*Entry(2,1)*Entry(3,3) - Entry(2,3)*Entry(3,2)*Entry(1,1); + return data[0]*data[4]*data[8] + data[3]*data[7]*data[2] + + data[6]*data[1]*data[5] - data[6]*data[4]*data[2] + - data[3]*data[1]*data[8] - data[7]*data[5]*data[0]; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -123,21 +197,28 @@ FGMatrix33 FGMatrix33::Inverse(void) const { // Compute the inverse of a general matrix using Cramers rule. // I guess googling for cramers rule gives tons of references // for this. :) - double rdet = 1.0/Determinant(); - - double i11 = rdet*(Entry(2,2)*Entry(3,3)-Entry(2,3)*Entry(3,2)); - double i21 = rdet*(Entry(2,3)*Entry(3,1)-Entry(2,1)*Entry(3,3)); - double i31 = rdet*(Entry(2,1)*Entry(3,2)-Entry(2,2)*Entry(3,1)); - double i12 = rdet*(Entry(1,3)*Entry(3,2)-Entry(1,2)*Entry(3,3)); - double i22 = rdet*(Entry(1,1)*Entry(3,3)-Entry(1,3)*Entry(3,1)); - double i32 = rdet*(Entry(1,2)*Entry(3,1)-Entry(1,1)*Entry(3,2)); - double i13 = rdet*(Entry(1,2)*Entry(2,3)-Entry(1,3)*Entry(2,2)); - double i23 = rdet*(Entry(1,3)*Entry(2,1)-Entry(1,1)*Entry(2,3)); - double i33 = rdet*(Entry(1,1)*Entry(2,2)-Entry(1,2)*Entry(2,1)); - - return FGMatrix33( i11, i12, i13, - i21, i22, i23, - i31, i32, i33 ); + + if (Determinant() != 0.0) { + double rdet = 1.0/Determinant(); + + double i11 = rdet*(data[4]*data[8]-data[7]*data[5]); + double i21 = rdet*(data[7]*data[2]-data[1]*data[8]); + double i31 = rdet*(data[1]*data[5]-data[4]*data[2]); + double i12 = rdet*(data[6]*data[5]-data[3]*data[8]); + double i22 = rdet*(data[0]*data[8]-data[6]*data[2]); + double i32 = rdet*(data[3]*data[2]-data[0]*data[5]); + double i13 = rdet*(data[3]*data[7]-data[6]*data[4]); + double i23 = rdet*(data[6]*data[1]-data[0]*data[7]); + double i33 = rdet*(data[0]*data[4]-data[3]*data[1]); + + return FGMatrix33( i11, i12, i13, + i21, i22, i23, + i31, i32, i33 ); + } else { + return FGMatrix33( 0, 0, 0, + 0, 0, 0, + 0, 0, 0 ); + } } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -154,15 +235,15 @@ void FGMatrix33::InitMatrix(void) FGMatrix33 FGMatrix33::operator-(const FGMatrix33& M) const { - return FGMatrix33( Entry(1,1) - M(1,1), - Entry(1,2) - M(1,2), - Entry(1,3) - M(1,3), - Entry(2,1) - M(2,1), - Entry(2,2) - M(2,2), - Entry(2,3) - M(2,3), - Entry(3,1) - M(3,1), - Entry(3,2) - M(3,2), - Entry(3,3) - M(3,3) ); + return FGMatrix33( data[0] - M.data[0], + data[3] - M.data[3], + data[6] - M.data[6], + data[1] - M.data[1], + data[4] - M.data[4], + data[7] - M.data[7], + data[2] - M.data[2], + data[5] - M.data[5], + data[8] - M.data[8] ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -186,30 +267,30 @@ FGMatrix33& FGMatrix33::operator-=(const FGMatrix33 &M) FGMatrix33 FGMatrix33::operator+(const FGMatrix33& M) const { - return FGMatrix33( Entry(1,1) + M(1,1), - Entry(1,2) + M(1,2), - Entry(1,3) + M(1,3), - Entry(2,1) + M(2,1), - Entry(2,2) + M(2,2), - Entry(2,3) + M(2,3), - Entry(3,1) + M(3,1), - Entry(3,2) + M(3,2), - Entry(3,3) + M(3,3) ); + return FGMatrix33( data[0] + M.data[0], + data[3] + M.data[3], + data[6] + M.data[6], + data[1] + M.data[1], + data[4] + M.data[4], + data[7] + M.data[7], + data[2] + M.data[2], + data[5] + M.data[5], + data[8] + M.data[8] ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGMatrix33& FGMatrix33::operator+=(const FGMatrix33 &M) { - Entry(1,1) += M(1,1); - Entry(1,2) += M(1,2); - Entry(1,3) += M(1,3); - Entry(2,1) += M(2,1); - Entry(2,2) += M(2,2); - Entry(2,3) += M(2,3); - Entry(3,1) += M(3,1); - Entry(3,2) += M(3,2); - Entry(3,3) += M(3,3); + data[0] += M.data[0]; + data[3] += M.data[3]; + data[6] += M.data[6]; + data[1] += M.data[1]; + data[4] += M.data[4]; + data[7] += M.data[7]; + data[2] += M.data[2]; + data[5] += M.data[5]; + data[8] += M.data[8]; return *this; } @@ -218,19 +299,19 @@ FGMatrix33& FGMatrix33::operator+=(const FGMatrix33 &M) FGMatrix33 FGMatrix33::operator*(const double scalar) const { - return FGMatrix33( scalar * Entry(1,1), - scalar * Entry(1,2), - scalar * Entry(1,3), - scalar * Entry(2,1), - scalar * Entry(2,2), - scalar * Entry(2,3), - scalar * Entry(3,1), - scalar * Entry(3,2), - scalar * Entry(3,3) ); + return FGMatrix33( scalar * data[0], + scalar * data[3], + scalar * data[6], + scalar * data[1], + scalar * data[4], + scalar * data[7], + scalar * data[2], + scalar * data[5], + scalar * data[8] ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - +/* FGMatrix33 operator*(double scalar, FGMatrix33 &M) { return FGMatrix33( scalar * M(1,1), @@ -243,20 +324,20 @@ FGMatrix33 operator*(double scalar, FGMatrix33 &M) scalar * M(3,2), scalar * M(3,3) ); } - +*/ //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGMatrix33& FGMatrix33::operator*=(const double scalar) { - Entry(1,1) *= scalar; - Entry(1,2) *= scalar; - Entry(1,3) *= scalar; - Entry(2,1) *= scalar; - Entry(2,2) *= scalar; - Entry(2,3) *= scalar; - Entry(3,1) *= scalar; - Entry(3,2) *= scalar; - Entry(3,3) *= scalar; + data[0] *= scalar; + data[3] *= scalar; + data[6] *= scalar; + data[1] *= scalar; + data[4] *= scalar; + data[7] *= scalar; + data[2] *= scalar; + data[5] *= scalar; + data[8] *= scalar; return *this; } @@ -265,18 +346,17 @@ FGMatrix33& FGMatrix33::operator*=(const double scalar) FGMatrix33 FGMatrix33::operator*(const FGMatrix33& M) const { - // FIXME: Make compiler friendlier FGMatrix33 Product; - Product(1,1) = Entry(1,1)*M(1,1) + Entry(1,2)*M(2,1) + Entry(1,3)*M(3,1); - Product(1,2) = Entry(1,1)*M(1,2) + Entry(1,2)*M(2,2) + Entry(1,3)*M(3,2); - Product(1,3) = Entry(1,1)*M(1,3) + Entry(1,2)*M(2,3) + Entry(1,3)*M(3,3); - Product(2,1) = Entry(2,1)*M(1,1) + Entry(2,2)*M(2,1) + Entry(2,3)*M(3,1); - Product(2,2) = Entry(2,1)*M(1,2) + Entry(2,2)*M(2,2) + Entry(2,3)*M(3,2); - Product(2,3) = Entry(2,1)*M(1,3) + Entry(2,2)*M(2,3) + Entry(2,3)*M(3,3); - Product(3,1) = Entry(3,1)*M(1,1) + Entry(3,2)*M(2,1) + Entry(3,3)*M(3,1); - Product(3,2) = Entry(3,1)*M(1,2) + Entry(3,2)*M(2,2) + Entry(3,3)*M(3,2); - Product(3,3) = Entry(3,1)*M(1,3) + Entry(3,2)*M(2,3) + Entry(3,3)*M(3,3); + Product.data[0] = data[0]*M.data[0] + data[3]*M.data[1] + data[6]*M.data[2]; + Product.data[3] = data[0]*M.data[3] + data[3]*M.data[4] + data[6]*M.data[5]; + Product.data[6] = data[0]*M.data[6] + data[3]*M.data[7] + data[6]*M.data[8]; + Product.data[1] = data[1]*M.data[0] + data[4]*M.data[1] + data[7]*M.data[2]; + Product.data[4] = data[1]*M.data[3] + data[4]*M.data[4] + data[7]*M.data[5]; + Product.data[7] = data[1]*M.data[6] + data[4]*M.data[7] + data[7]*M.data[8]; + Product.data[2] = data[2]*M.data[0] + data[5]*M.data[1] + data[8]*M.data[2]; + Product.data[5] = data[2]*M.data[3] + data[5]*M.data[4] + data[8]*M.data[5]; + Product.data[8] = data[2]*M.data[6] + data[5]*M.data[7] + data[8]*M.data[8]; return Product; } @@ -288,20 +368,20 @@ FGMatrix33& FGMatrix33::operator*=(const FGMatrix33& M) // FIXME: Make compiler friendlier double a,b,c; - a = Entry(1,1); b=Entry(1,2); c=Entry(1,3); - Entry(1,1) = a*M(1,1) + b*M(2,1) + c*M(3,1); - Entry(1,2) = a*M(1,2) + b*M(2,2) + c*M(3,2); - Entry(1,3) = a*M(1,3) + b*M(2,3) + c*M(3,3); + a = data[0]; b=data[3]; c=data[6]; + data[0] = a*M.data[0] + b*M.data[1] + c*M.data[2]; + data[3] = a*M.data[3] + b*M.data[4] + c*M.data[5]; + data[6] = a*M.data[6] + b*M.data[7] + c*M.data[8]; - a = Entry(2,1); b=Entry(2,2); c=Entry(2,3); - Entry(2,1) = a*M(1,1) + b*M(2,1) + c*M(3,1); - Entry(2,2) = a*M(1,2) + b*M(2,2) + c*M(3,2); - Entry(2,3) = a*M(1,3) + b*M(2,3) + c*M(3,3); + a = data[1]; b=data[4]; c=data[7]; + data[1] = a*M.data[0] + b*M.data[1] + c*M.data[2]; + data[4] = a*M.data[3] + b*M.data[4] + c*M.data[5]; + data[7] = a*M.data[6] + b*M.data[7] + c*M.data[8]; - a = Entry(3,1); b=Entry(3,2); c=Entry(3,3); - Entry(3,1) = a*M(1,1) + b*M(2,1) + c*M(3,1); - Entry(3,2) = a*M(1,2) + b*M(2,2) + c*M(3,2); - Entry(3,3) = a*M(1,3) + b*M(2,3) + c*M(3,3); + a = data[2]; b=data[5]; c=data[8]; + data[2] = a*M.data[0] + b*M.data[1] + c*M.data[2]; + data[5] = a*M.data[3] + b*M.data[4] + c*M.data[5]; + data[8] = a*M.data[6] + b*M.data[7] + c*M.data[8]; return *this; } @@ -314,15 +394,15 @@ FGMatrix33 FGMatrix33::operator/(const double scalar) const if ( scalar != 0 ) { double tmp = 1.0/scalar; - Quot(1,1) = Entry(1,1) * tmp; - Quot(1,2) = Entry(1,2) * tmp; - Quot(1,3) = Entry(1,3) * tmp; - Quot(2,1) = Entry(2,1) * tmp; - Quot(2,2) = Entry(2,2) * tmp; - Quot(2,3) = Entry(2,3) * tmp; - Quot(3,1) = Entry(3,1) * tmp; - Quot(3,2) = Entry(3,2) * tmp; - Quot(3,3) = Entry(3,3) * tmp; + Quot.data[0] = data[0] * tmp; + Quot.data[3] = data[3] * tmp; + Quot.data[6] = data[6] * tmp; + Quot.data[1] = data[1] * tmp; + Quot.data[4] = data[4] * tmp; + Quot.data[7] = data[7] * tmp; + Quot.data[2] = data[2] * tmp; + Quot.data[5] = data[5] * tmp; + Quot.data[8] = data[8] * tmp; } else { MatrixException mE; mE.Message = "Attempt to divide by zero in method FGMatrix33::operator/(const double scalar)"; @@ -337,15 +417,15 @@ FGMatrix33& FGMatrix33::operator/=(const double scalar) { if ( scalar != 0 ) { double tmp = 1.0/scalar; - Entry(1,1) *= tmp; - Entry(1,2) *= tmp; - Entry(1,3) *= tmp; - Entry(2,1) *= tmp; - Entry(2,2) *= tmp; - Entry(2,3) *= tmp; - Entry(3,1) *= tmp; - Entry(3,2) *= tmp; - Entry(3,3) *= tmp; + data[0] *= tmp; + data[3] *= tmp; + data[6] *= tmp; + data[1] *= tmp; + data[4] *= tmp; + data[7] *= tmp; + data[2] *= tmp; + data[5] *= tmp; + data[8] *= tmp; } else { MatrixException mE; mE.Message = "Attempt to divide by zero in method FGMatrix33::operator/=(const double scalar)"; @@ -358,29 +438,40 @@ FGMatrix33& FGMatrix33::operator/=(const double scalar) void FGMatrix33::T(void) { - for (unsigned int i=1; i<=3; i++) { - for (unsigned int j=i+1; j<=3; j++) { - double tmp = Entry(i,j); - Entry(i,j) = Entry(j,i); - Entry(j,i) = tmp; - } - } + double tmp; + + tmp = data[3]; + data[3] = data[1]; + data[1] = tmp; + + tmp = data[6]; + data[6] = data[2]; + data[2] = tmp; + + tmp = data[7]; + data[7] = data[5]; + data[5] = tmp; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -FGColumnVector3 FGMatrix33::operator*(const FGColumnVector3& v) const { - double tmp1 = v(1)*Entry(1,1); - double tmp2 = v(1)*Entry(2,1); - double tmp3 = v(1)*Entry(3,1); +FGColumnVector3 FGMatrix33::operator*(const FGColumnVector3& v) const +{ + double v1 = v(1); + double v2 = v(2); + double v3 = v(3); + + double tmp1 = v1*data[0]; //[(col-1)*eRows+row-1] + double tmp2 = v1*data[1]; + double tmp3 = v1*data[2]; - tmp1 += v(2)*Entry(1,2); - tmp2 += v(2)*Entry(2,2); - tmp3 += v(2)*Entry(3,2); + tmp1 += v2*data[3]; + tmp2 += v2*data[4]; + tmp3 += v2*data[5]; - tmp1 += v(3)*Entry(1,3); - tmp2 += v(3)*Entry(2,3); - tmp3 += v(3)*Entry(3,3); + tmp1 += v3*data[6]; + tmp2 += v3*data[7]; + tmp3 += v3*data[8]; return FGColumnVector3( tmp1, tmp2, tmp3 ); } diff --git a/src/FDM/JSBSim/math/FGMatrix33.h b/src/FDM/JSBSim/math/FGMatrix33.h index d07687ea9..7af43031b 100644 --- a/src/FDM/JSBSim/math/FGMatrix33.h +++ b/src/FDM/JSBSim/math/FGMatrix33.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MATRIX33 "$Id$" +#define ID_MATRIX33 "$Id: FGMatrix33.h,v 1.11 2010/06/30 03:13:40 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -59,6 +59,7 @@ FORWARD DECLARATIONS namespace JSBSim { class FGColumnVector3; +class FGQuaternion; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS DOCUMENTATION @@ -111,17 +112,17 @@ public: Create copy of the matrix given in the argument. */ FGMatrix33(const FGMatrix33& M) { - Entry(1,1) = M.Entry(1,1); - Entry(2,1) = M.Entry(2,1); - Entry(3,1) = M.Entry(3,1); - Entry(1,2) = M.Entry(1,2); - Entry(2,2) = M.Entry(2,2); - Entry(3,2) = M.Entry(3,2); - Entry(1,3) = M.Entry(1,3); - Entry(2,3) = M.Entry(2,3); - Entry(3,3) = M.Entry(3,3); - - Debug(0); + data[0] = M.data[0]; + data[1] = M.data[1]; + data[2] = M.data[2]; + data[3] = M.data[3]; + data[4] = M.data[4]; + data[5] = M.data[5]; + data[6] = M.data[6]; + data[7] = M.data[7]; + data[8] = M.data[8]; + +// Debug(0); } /** Initialization by given values. @@ -141,28 +142,34 @@ public: FGMatrix33(double m11, double m12, double m13, double m21, double m22, double m23, double m31, double m32, double m33) { - Entry(1,1) = m11; - Entry(2,1) = m21; - Entry(3,1) = m31; - Entry(1,2) = m12; - Entry(2,2) = m22; - Entry(3,2) = m32; - Entry(1,3) = m13; - Entry(2,3) = m23; - Entry(3,3) = m33; - - Debug(0); + data[0] = m11; + data[1] = m21; + data[2] = m31; + data[3] = m12; + data[4] = m22; + data[5] = m32; + data[6] = m13; + data[7] = m23; + data[8] = m33; + + // Debug(0); } /** Destructor. */ - ~FGMatrix33(void) { Debug(1); } + ~FGMatrix33(void) { /* Debug(1); */ } /** Prints the contents of the matrix. @param delimeter the item separator (tab or comma) @return a string with the delimeter-separated contents of the matrix */ std::string Dump(const std::string& delimeter) const; + /** Prints the contents of the matrix. + @param delimeter the item separator (tab or comma, etc.) + @param prefix an additional prefix that is used to indent the 3X3 matrix printout + @return a string with the delimeter-separated contents of the matrix */ + std::string Dump(const std::string& delimiter, const std::string& prefix) const; + /** Read access the entries of the matrix. @param row Row index. @param col Column index. @@ -171,7 +178,7 @@ public: column indices. Indices are counted starting with 1. */ double operator()(unsigned int row, unsigned int col) const { - return Entry(row, col); + return data[(col-1)*eRows+row-1]; } /** Write access the entries of the matrix. @@ -184,7 +191,7 @@ public: column indices. Indices are counted starting with 1. */ double& operator()(unsigned int row, unsigned int col) { - return Entry(row, col); + return data[(col-1)*eRows+row-1]; } /** Read access the entries of the matrix. @@ -237,9 +244,9 @@ public: @return the transposed matrix. */ FGMatrix33 Transposed(void) const { - return FGMatrix33( Entry(1,1), Entry(2,1), Entry(3,1), - Entry(1,2), Entry(2,2), Entry(3,2), - Entry(1,3), Entry(2,3), Entry(3,3) ); + return FGMatrix33( data[0], data[1], data[2], + data[3], data[4], data[5], + data[6], data[7], data[8] ); } /** Transposes this matrix. @@ -258,17 +265,21 @@ public: void InitMatrix(double m11, double m12, double m13, double m21, double m22, double m23, double m31, double m32, double m33) { - Entry(1,1) = m11; - Entry(2,1) = m21; - Entry(3,1) = m31; - Entry(1,2) = m12; - Entry(2,2) = m22; - Entry(3,2) = m32; - Entry(1,3) = m13; - Entry(2,3) = m23; - Entry(3,3) = m33; + data[0] = m11; + data[1] = m21; + data[2] = m31; + data[3] = m12; + data[4] = m22; + data[5] = m32; + data[6] = m13; + data[7] = m23; + data[8] = m33; } + /** Returns the quaternion associated with this direction cosine (rotation) matrix. + */ + FGQuaternion GetQuaternion(void); + /** Determinant of the matrix. @return the determinant of the matrix. */ @@ -458,4 +469,6 @@ std::istream& operator>>(std::istream& is, FGMatrix33& M); } // namespace JSBSim +#include "FGQuaternion.h" + #endif diff --git a/src/FDM/JSBSim/math/FGParameter.h b/src/FDM/JSBSim/math/FGParameter.h index f1f42a8ed..85b43b1af 100755 --- a/src/FDM/JSBSim/math/FGParameter.h +++ b/src/FDM/JSBSim/math/FGParameter.h @@ -40,7 +40,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PARAMETER "$Id$" +#define ID_PARAMETER "$Id: FGParameter.h,v 1.5 2009/08/30 03:51:28 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/math/FGPropertyValue.cpp b/src/FDM/JSBSim/math/FGPropertyValue.cpp index 111b078c8..66f89b89a 100755 --- a/src/FDM/JSBSim/math/FGPropertyValue.cpp +++ b/src/FDM/JSBSim/math/FGPropertyValue.cpp @@ -32,7 +32,7 @@ INCLUDES namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPropertyValue.cpp,v 1.4 2009/08/30 03:51:28 jberndt Exp $"; static const char *IdHdr = ID_PROPERTYVALUE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/math/FGPropertyValue.h b/src/FDM/JSBSim/math/FGPropertyValue.h index 82803f558..3466c66ba 100755 --- a/src/FDM/JSBSim/math/FGPropertyValue.h +++ b/src/FDM/JSBSim/math/FGPropertyValue.h @@ -41,7 +41,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PROPERTYVALUE "$Id$" +#define ID_PROPERTYVALUE "$Id: FGPropertyValue.h,v 1.6 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/math/FGQuaternion.cpp b/src/FDM/JSBSim/math/FGQuaternion.cpp index 74b63d888..07868cfa0 100644 --- a/src/FDM/JSBSim/math/FGQuaternion.cpp +++ b/src/FDM/JSBSim/math/FGQuaternion.cpp @@ -40,6 +40,7 @@ SENTRY #include #include +#include #include using std::cerr; using std::cout; @@ -56,18 +57,18 @@ using std::endl; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGQuaternion.cpp,v 1.16 2010/06/30 03:13:40 jberndt Exp $"; static const char *IdHdr = ID_QUATERNION; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Initialize from q -FGQuaternion::FGQuaternion(const FGQuaternion& q) - : mCacheValid(q.mCacheValid) { - Entry(1) = q(1); - Entry(2) = q(2); - Entry(3) = q(3); - Entry(4) = q(4); +FGQuaternion::FGQuaternion(const FGQuaternion& q) : mCacheValid(q.mCacheValid) +{ + data[0] = q(1); + data[1] = q(2); + data[2] = q(3); + data[3] = q(4); if (mCacheValid) { mT = q.mT; mTInv = q.mTInv; @@ -80,8 +81,36 @@ FGQuaternion::FGQuaternion(const FGQuaternion& q) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Initialize with the three euler angles -FGQuaternion::FGQuaternion(double phi, double tht, double psi) - : mCacheValid(false) { +FGQuaternion::FGQuaternion(double phi, double tht, double psi): mCacheValid(false) +{ + InitializeFromEulerAngles(phi, tht, psi); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +FGQuaternion::FGQuaternion(FGColumnVector3 vOrient): mCacheValid(false) +{ + double phi = vOrient(ePhi); + double tht = vOrient(eTht); + double psi = vOrient(ePsi); + + InitializeFromEulerAngles(phi, tht, psi); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// +// This function computes the quaternion that describes the relationship of the +// body frame with respect to another frame, such as the ECI or ECEF frames. The +// Euler angles used represent a 3-2-1 (psi, theta, phi) rotation sequence from +// the reference frame to the body frame. See "Quaternions and Rotation +// Sequences", Jack B. Kuipers, sections 9.2 and 7.6. + +void FGQuaternion::InitializeFromEulerAngles(double phi, double tht, double psi) +{ + mEulerAngles(ePhi) = phi; + mEulerAngles(eTht) = tht; + mEulerAngles(ePsi) = psi; + double thtd2 = 0.5*tht; double psid2 = 0.5*psi; double phid2 = 0.5*phi; @@ -99,10 +128,27 @@ FGQuaternion::FGQuaternion(double phi, double tht, double psi) double Sphid2Sthtd2 = Sphid2*Sthtd2; double Sphid2Cthtd2 = Sphid2*Cthtd2; - Entry(1) = Cphid2Cthtd2*Cpsid2 + Sphid2Sthtd2*Spsid2; - Entry(2) = Sphid2Cthtd2*Cpsid2 - Cphid2Sthtd2*Spsid2; - Entry(3) = Cphid2Sthtd2*Cpsid2 + Sphid2Cthtd2*Spsid2; - Entry(4) = Cphid2Cthtd2*Spsid2 - Sphid2Sthtd2*Cpsid2; + data[0] = Cphid2Cthtd2*Cpsid2 + Sphid2Sthtd2*Spsid2; + data[1] = Sphid2Cthtd2*Cpsid2 - Cphid2Sthtd2*Spsid2; + data[2] = Cphid2Sthtd2*Cpsid2 + Sphid2Cthtd2*Spsid2; + data[3] = Cphid2Cthtd2*Spsid2 - Sphid2Sthtd2*Cpsid2; + + Normalize(); +} +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// Initialize with a direction cosine (rotation) matrix + +FGQuaternion::FGQuaternion(const FGMatrix33& m) : mCacheValid(false) +{ + data[0] = 0.50*sqrt(1.0 + m(1,1) + m(2,2) + m(3,3)); + double t = 0.25/data[0]; + data[1] = t*(m(2,3) - m(3,2)); + data[2] = t*(m(3,1) - m(1,3)); + data[3] = t*(m(1,2) - m(2,1)); + + ComputeDerivedUnconditional(); + + Normalize(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -111,37 +157,32 @@ FGQuaternion::FGQuaternion(double phi, double tht, double psi) angular velocities PQR. See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, Equation 1.3-36. + Also see Jack Kuipers, "Quaternions and Rotation Sequences", Equation 11.12. */ -FGQuaternion FGQuaternion::GetQDot(const FGColumnVector3& PQR) const { - double norm = Magnitude(); - if (norm == 0.0) - return FGQuaternion::zero(); - double rnorm = 1.0/norm; - - FGQuaternion QDot; - QDot(1) = -0.5*(Entry(2)*PQR(eP) + Entry(3)*PQR(eQ) + Entry(4)*PQR(eR)); - QDot(2) = 0.5*(Entry(1)*PQR(eP) + Entry(3)*PQR(eR) - Entry(4)*PQR(eQ)); - QDot(3) = 0.5*(Entry(1)*PQR(eQ) + Entry(4)*PQR(eP) - Entry(2)*PQR(eR)); - QDot(4) = 0.5*(Entry(1)*PQR(eR) + Entry(2)*PQR(eQ) - Entry(3)*PQR(eP)); - return rnorm*QDot; +FGQuaternion FGQuaternion::GetQDot(const FGColumnVector3& PQR) +{ + return FGQuaternion( + -0.5*( data[1]*PQR(eP) + data[2]*PQR(eQ) + data[3]*PQR(eR)), + 0.5*( data[0]*PQR(eP) - data[3]*PQR(eQ) + data[2]*PQR(eR)), + 0.5*( data[3]*PQR(eP) + data[0]*PQR(eQ) - data[1]*PQR(eR)), + 0.5*(-data[2]*PQR(eP) + data[1]*PQR(eQ) + data[0]*PQR(eR)) + ); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGQuaternion::Normalize() { - // Note: this does not touch the cache - // since it does not change the orientation ... - + // Note: this does not touch the cache since it does not change the orientation double norm = Magnitude(); - if (norm == 0.0) - return; - + if (norm == 0.0 || fabs(norm - 1.000) < 1e-10) return; + double rnorm = 1.0/norm; - Entry(1) *= rnorm; - Entry(2) *= rnorm; - Entry(3) *= rnorm; - Entry(4) *= rnorm; + + data[0] *= rnorm; + data[1] *= rnorm; + data[2] *= rnorm; + data[3] *= rnorm; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -150,45 +191,42 @@ void FGQuaternion::Normalize() void FGQuaternion::ComputeDerivedUnconditional(void) const { mCacheValid = true; - - // First normalize the 4-vector - double norm = Magnitude(); - if (norm == 0.0) - return; - double rnorm = 1.0/norm; - double q1 = rnorm*Entry(1); - double q2 = rnorm*Entry(2); - double q3 = rnorm*Entry(3); - double q4 = rnorm*Entry(4); + double q0 = data[0]; // use some aliases/shorthand for the quat elements. + double q1 = data[1]; + double q2 = data[2]; + double q3 = data[3]; // Now compute the transformation matrix. + double q0q0 = q0*q0; double q1q1 = q1*q1; double q2q2 = q2*q2; double q3q3 = q3*q3; - double q4q4 = q4*q4; + double q0q1 = q0*q1; + double q0q2 = q0*q2; + double q0q3 = q0*q3; double q1q2 = q1*q2; double q1q3 = q1*q3; - double q1q4 = q1*q4; double q2q3 = q2*q3; - double q2q4 = q2*q4; - double q3q4 = q3*q4; - mT(1,1) = q1q1 + q2q2 - q3q3 - q4q4; - mT(1,2) = 2.0*(q2q3 + q1q4); - mT(1,3) = 2.0*(q2q4 - q1q3); - mT(2,1) = 2.0*(q2q3 - q1q4); - mT(2,2) = q1q1 - q2q2 + q3q3 - q4q4; - mT(2,3) = 2.0*(q3q4 + q1q2); - mT(3,1) = 2.0*(q2q4 + q1q3); - mT(3,2) = 2.0*(q3q4 - q1q2); - mT(3,3) = q1q1 - q2q2 - q3q3 + q4q4; - // Since this is an orthogonal matrix, the inverse is simply - // the transpose. + mT(1,1) = q0q0 + q1q1 - q2q2 - q3q3; // This is found from Eqn. 1.3-32 in + mT(1,2) = 2.0*(q1q2 + q0q3); // Stevens and Lewis + mT(1,3) = 2.0*(q1q3 - q0q2); + mT(2,1) = 2.0*(q1q2 - q0q3); + mT(2,2) = q0q0 - q1q1 + q2q2 - q3q3; + mT(2,3) = 2.0*(q2q3 + q0q1); + mT(3,1) = 2.0*(q1q3 + q0q2); + mT(3,2) = 2.0*(q2q3 - q0q1); + mT(3,3) = q0q0 - q1q1 - q2q2 + q3q3; + + // Since this is an orthogonal matrix, the inverse is simply the transpose. + mTInv = mT; mTInv.T(); // Compute the Euler-angles + // Also see Jack Kuipers, "Quaternions and Rotation Sequences", section 7.8.. + if (mT(3,3) == 0.0) mEulerAngles(ePhi) = 0.5*M_PI; else @@ -218,6 +256,55 @@ void FGQuaternion::ComputeDerivedUnconditional(void) const mEulerCosines(ePhi) = cos(mEulerAngles(ePhi)); mEulerCosines(eTht) = cos(mEulerAngles(eTht)); mEulerCosines(ePsi) = cos(mEulerAngles(ePsi)); + +// Debug(2); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// The bitmasked value choices are as follows: +// unset: In this case (the default) JSBSim would only print +// out the normally expected messages, essentially echoing +// the config files as they are read. If the environment +// variable is not set, debug_lvl is set to 1 internally +// 0: This requests JSBSim not to output any messages +// whatsoever. +// 1: This value explicity requests the normal JSBSim +// startup messages +// 2: This value asks for a message to be printed out when +// a class is instantiated +// 4: When this value is set, a message is displayed when a +// FGModel object executes its Run() method +// 8: When this value is set, various runtime state variables +// are printed out periodically +// 16: When set various parameters are sanity checked and +// a message is printed out when they go out of bounds + +void FGQuaternion::Debug(int from) const +{ + if (debug_lvl <= 0) return; + + if (debug_lvl & 1) { // Standard console startup message output + } + if (debug_lvl & 2 ) { // Instantiation/Destruction notification + if (from == 0) cout << "Instantiated: FGQuaternion" << endl; + if (from == 1) cout << "Destroyed: FGQuaternion" << endl; + } + if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects + } + if (debug_lvl & 8 ) { // Runtime state variables + } + if (debug_lvl & 16) { // Sanity checking + if (!EqualToRoundoff(Magnitude(), 1.0)) { + cout << "Quaternion magnitude differs from 1.0 !" << endl; + cout << "\tdelta from 1.0: " << std::scientific << Magnitude()-1.0 << endl; + } + } + if (debug_lvl & 64) { + if (from == 0) { // Constructor + cout << IdSrc << endl; + cout << IdHdr << endl; + } + } } } // namespace JSBSim diff --git a/src/FDM/JSBSim/math/FGQuaternion.h b/src/FDM/JSBSim/math/FGQuaternion.h index 73c0e009a..104a52f39 100644 --- a/src/FDM/JSBSim/math/FGQuaternion.h +++ b/src/FDM/JSBSim/math/FGQuaternion.h @@ -41,18 +41,18 @@ SENTRY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGJSBBase.h" -#include "FGMatrix33.h" #include "FGColumnVector3.h" -#include "input_output/FGPropertyManager.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_QUATERNION "$Id$" +#define ID_QUATERNION "$Id: FGQuaternion.h,v 1.17 2010/06/30 03:13:40 jberndt Exp $" namespace JSBSim { +class FGMatrix33; + /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS DOCUMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ @@ -88,14 +88,13 @@ namespace JSBSim { CLASS DECLARATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -class FGQuaternion - : virtual FGJSBBase { +class FGQuaternion : virtual FGJSBBase { public: /** Default initializer. Default initializer, initializes the class with the identity rotation. */ FGQuaternion() : mCacheValid(false) { - Entry(1) = 1.0; - Entry(2) = Entry(3) = Entry(4) = 0.0; + data[0] = 1.0; + data[1] = data[2] = data[3] = 0.0; } /** Copy constructor. @@ -110,6 +109,11 @@ public: @param psi The euler Z axis (heading) angle in radians */ FGQuaternion(double phi, double tht, double psi); + /** Initializer by euler angle vector. + Initialize the quaternion with the euler angle vector. + @param vOrient The euler axis angle vector in radians (phi, tht, psi) */ + FGQuaternion(FGColumnVector3 vOrient); + /** Initializer by one euler angle. Initialize the quaternion with the single euler angle where its index is given in the first argument. @@ -117,43 +121,50 @@ public: @param angle The euler angle in radians */ FGQuaternion(int idx, double angle) : mCacheValid(false) { + double angle2 = 0.5*angle; double Sangle2 = sin(angle2); double Cangle2 = cos(angle2); if (idx == ePhi) { - Entry(1) = Cangle2; - Entry(2) = Sangle2; - Entry(3) = 0.0; - Entry(4) = 0.0; + data[0] = Cangle2; + data[1] = Sangle2; + data[2] = 0.0; + data[3] = 0.0; } else if (idx == eTht) { - Entry(1) = Cangle2; - Entry(2) = 0.0; - Entry(3) = Sangle2; - Entry(4) = 0.0; + data[0] = Cangle2; + data[1] = 0.0; + data[2] = Sangle2; + data[3] = 0.0; } else { - Entry(1) = Cangle2; - Entry(2) = 0.0; - Entry(3) = 0.0; - Entry(4) = Sangle2; + data[0] = Cangle2; + data[1] = 0.0; + data[2] = 0.0; + data[3] = Sangle2; } } + /** Initializer by matrix. + Initialize the quaternion with the matrix representing a transform from one frame + to another using the standard aerospace sequence, Yaw-Pitch-Roll (3-2-1). + @param m the rotation matrix */ + FGQuaternion(const FGMatrix33& m); + /// Destructor. ~FGQuaternion() {} /** Quaternion derivative for given angular rates. Computes the quaternion derivative which results from the given angular velocities - @param PQR a constant reference to the body rate vector + @param PQR a constant reference to a rotation rate vector @return the quaternion derivative @see Stevens and Lewis, "Aircraft Control and Simulation", Second Edition, Equation 1.3-36. */ - FGQuaternion GetQDot(const FGColumnVector3& PQR) const; + FGQuaternion GetQDot(const FGColumnVector3& PQR); /** Transformation matrix. @return a reference to the transformation/rotation matrix @@ -220,7 +231,7 @@ public: Note that the index given in the argument is unchecked. */ - double operator()(unsigned int idx) const { return Entry(idx); } + double operator()(unsigned int idx) const { return data[idx-1]; } /** Write access the entries of the vector. @@ -231,7 +242,7 @@ public: Note that the index given in the argument is unchecked. */ - double& operator()(unsigned int idx) { return Entry(idx); } + double& operator()(unsigned int idx) { mCacheValid = false; return data[idx-1]; } /** Read access the entries of the vector. @@ -246,7 +257,7 @@ public: Note that the index given in the argument is unchecked. */ - double Entry(unsigned int idx) const { return mData[idx-1]; } + double Entry(unsigned int idx) const { return data[idx-1]; } /** Write access the entries of the vector. @@ -261,7 +272,10 @@ public: Note that the index given in the argument is unchecked. */ - double& Entry(unsigned int idx) { mCacheValid = false; return mData[idx-1]; } + double& Entry(unsigned int idx) { + mCacheValid = false; + return data[idx-1]; + } /** Assignment operator "=". Assign the value of q to the current object. Cached values are @@ -270,10 +284,11 @@ public: @return reference to a quaternion object */ const FGQuaternion& operator=(const FGQuaternion& q) { // Copy the master values ... - Entry(1) = q(1); - Entry(2) = q(2); - Entry(3) = q(3); - Entry(4) = q(4); + data[0] = q(1); + data[1] = q(2); + data[2] = q(3); + data[3] = q(4); + ComputeDerived(); // .. and copy the derived values if they are valid mCacheValid = q.mCacheValid; if (mCacheValid) { @@ -286,12 +301,15 @@ public: return *this; } + /// Conversion from Quat to Matrix + operator FGMatrix33() const { return GetT(); } + /** Comparison operator "==". @param q a quaternion reference @return true if both quaternions represent the same rotation. */ bool operator==(const FGQuaternion& q) const { - return Entry(1) == q(1) && Entry(2) == q(2) - && Entry(3) == q(3) && Entry(4) == q(4); + return data[0] == q(1) && data[1] == q(2) + && data[2] == q(3) && data[3] == q(4); } /** Comparison operator "!=". @@ -300,10 +318,10 @@ public: bool operator!=(const FGQuaternion& q) const { return ! operator==(q); } const FGQuaternion& operator+=(const FGQuaternion& q) { // Copy the master values ... - Entry(1) += q(1); - Entry(2) += q(2); - Entry(3) += q(3); - Entry(4) += q(4); + data[0] += q(1); + data[1] += q(2); + data[2] += q(3); + data[3] += q(4); mCacheValid = false; return *this; } @@ -313,10 +331,10 @@ public: @return a quaternion reference representing Q, where Q = Q - q. */ const FGQuaternion& operator-=(const FGQuaternion& q) { // Copy the master values ... - Entry(1) -= q(1); - Entry(2) -= q(2); - Entry(3) -= q(3); - Entry(4) -= q(4); + data[0] -= q(1); + data[1] -= q(2); + data[2] -= q(3); + data[3] -= q(4); mCacheValid = false; return *this; } @@ -325,10 +343,10 @@ public: @param scalar a multiplicative value. @return a quaternion reference representing Q, where Q = Q * scalar. */ const FGQuaternion& operator*=(double scalar) { - Entry(1) *= scalar; - Entry(2) *= scalar; - Entry(3) *= scalar; - Entry(4) *= scalar; + data[0] *= scalar; + data[1] *= scalar; + data[2] *= scalar; + data[3] *= scalar; mCacheValid = false; return *this; } @@ -344,16 +362,16 @@ public: @param q a quaternion to be summed. @return a quaternion representing Q, where Q = Q + q. */ FGQuaternion operator+(const FGQuaternion& q) const { - return FGQuaternion(Entry(1)+q(1), Entry(2)+q(2), - Entry(3)+q(3), Entry(4)+q(4)); + return FGQuaternion(data[0]+q(1), data[1]+q(2), + data[2]+q(3), data[3]+q(4)); } /** Arithmetic operator "-". @param q a quaternion to be subtracted. @return a quaternion representing Q, where Q = Q - q. */ FGQuaternion operator-(const FGQuaternion& q) const { - return FGQuaternion(Entry(1)-q(1), Entry(2)-q(2), - Entry(3)-q(3), Entry(4)-q(4)); + return FGQuaternion(data[0]-q(1), data[1]-q(2), + data[2]-q(3), data[3]-q(4)); } /** Arithmetic operator "*". @@ -361,10 +379,10 @@ public: @param q a quaternion to be multiplied. @return a quaternion representing Q, where Q = Q * q. */ FGQuaternion operator*(const FGQuaternion& q) const { - return FGQuaternion(Entry(1)*q(1)-Entry(2)*q(2)-Entry(3)*q(3)-Entry(4)*q(4), - Entry(1)*q(2)+Entry(2)*q(1)+Entry(3)*q(4)-Entry(4)*q(3), - Entry(1)*q(3)-Entry(2)*q(4)+Entry(3)*q(1)+Entry(4)*q(2), - Entry(1)*q(4)+Entry(2)*q(3)-Entry(3)*q(2)+Entry(4)*q(1)); + return FGQuaternion(data[0]*q(1)-data[1]*q(2)-data[2]*q(3)-data[3]*q(4), + data[0]*q(2)+data[1]*q(1)+data[2]*q(4)-data[3]*q(3), + data[0]*q(3)-data[1]*q(4)+data[2]*q(1)+data[3]*q(2), + data[0]*q(4)+data[1]*q(3)-data[2]*q(2)+data[3]*q(1)); } /** Arithmetic operator "*=". @@ -372,14 +390,14 @@ public: @param q a quaternion to be multiplied. @return a quaternion reference representing Q, where Q = Q * q. */ const FGQuaternion& operator*=(const FGQuaternion& q) { - double q0 = Entry(1)*q(1)-Entry(2)*q(2)-Entry(3)*q(3)-Entry(4)*q(4); - double q1 = Entry(1)*q(2)+Entry(2)*q(1)+Entry(3)*q(4)-Entry(4)*q(3); - double q2 = Entry(1)*q(3)-Entry(2)*q(4)+Entry(3)*q(1)+Entry(4)*q(2); - double q3 = Entry(1)*q(4)+Entry(2)*q(3)-Entry(3)*q(2)+Entry(4)*q(1); - Entry(1) = q0; - Entry(2) = q1; - Entry(3) = q2; - Entry(4) = q3; + double q0 = data[0]*q(1)-data[1]*q(2)-data[2]*q(3)-data[3]*q(4); + double q1 = data[0]*q(2)+data[1]*q(1)+data[2]*q(4)-data[3]*q(3); + double q2 = data[0]*q(3)-data[1]*q(4)+data[2]*q(1)+data[3]*q(2); + double q3 = data[0]*q(4)+data[1]*q(3)-data[2]*q(2)+data[3]*q(1); + data[0] = q0; + data[1] = q1; + data[2] = q2; + data[3] = q3; mCacheValid = false; return *this; } @@ -391,12 +409,12 @@ public: the identity orientation. */ FGQuaternion Inverse(void) const { - double norm = Magnitude(); + double norm = SqrMagnitude(); if (norm == 0.0) return *this; double rNorm = 1.0/norm; - return FGQuaternion( Entry(1)*rNorm, -Entry(2)*rNorm, - -Entry(3)*rNorm, -Entry(4)*rNorm ); + return FGQuaternion( data[0]*rNorm, -data[1]*rNorm, + -data[2]*rNorm, -data[3]*rNorm ); } /** Conjugate of the quaternion. @@ -405,7 +423,7 @@ public: to the inverse iff the quaternion is normalized. */ FGQuaternion Conjugate(void) const { - return FGQuaternion( Entry(1), -Entry(2), -Entry(3), -Entry(4) ); + return FGQuaternion( data[0], -data[1], -data[2], -data[3] ); } friend FGQuaternion operator*(double, const FGQuaternion&); @@ -421,11 +439,11 @@ public: Compute and return the square of the euclidean norm of this vector. */ double SqrMagnitude(void) const { - return Entry(1)*Entry(1)+Entry(2)*Entry(2) - +Entry(3)*Entry(3)+Entry(4)*Entry(4); + return data[0]*data[0] + data[1]*data[1] + + data[2]*data[2] + data[3]*data[3]; } - /** Normialze. + /** Normalize. Normalize the vector to have the Magnitude() == 1.0. If the vector is equal to zero it is left untouched. @@ -439,7 +457,7 @@ public: private: /** Copying by assigning the vector valued components. */ FGQuaternion(double q1, double q2, double q3, double q4) : mCacheValid(false) - { Entry(1) = q1; Entry(2) = q2; Entry(3) = q3; Entry(4) = q4; } + { data[0] = q1; data[1] = q2; data[2] = q3; data[3] = q4; } /** Computation of derived values. This function recomputes the derived values like euler angles and @@ -450,16 +468,15 @@ private: This function checks if the derived values like euler angles and transformation matrices are already computed. If so, it returns. If they need to be computed the real worker routine - \ref FGQuaternion::ComputeDerivedUnconditional(void) const - is called. - This function is inlined to avoid function calls in the fast path. */ + FGQuaternion::ComputeDerivedUnconditional(void) const + is called. */ void ComputeDerived(void) const { if (!mCacheValid) ComputeDerivedUnconditional(); } /** The quaternion values itself. This is the master copy. */ - double mData[4]; + double data[4]; /** A data validity flag. This class implements caching of the derived values like the @@ -479,6 +496,10 @@ private: /** The cached sines and cosines of the euler angles. */ mutable FGColumnVector3 mEulerSines; mutable FGColumnVector3 mEulerCosines; + + void Debug(int from) const; + + void InitializeFromEulerAngles(double phi, double tht, double psi); }; /** Scalar multiplication. @@ -494,4 +515,6 @@ inline FGQuaternion operator*(double scalar, const FGQuaternion& q) { } // namespace JSBSim +#include "FGMatrix33.h" + #endif diff --git a/src/FDM/JSBSim/math/FGRealValue.cpp b/src/FDM/JSBSim/math/FGRealValue.cpp index 9d3deec3b..a30f9fcce 100755 --- a/src/FDM/JSBSim/math/FGRealValue.cpp +++ b/src/FDM/JSBSim/math/FGRealValue.cpp @@ -32,7 +32,7 @@ INCLUDES namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGRealValue.cpp,v 1.4 2009/08/30 03:51:28 jberndt Exp $"; static const char *IdHdr = ID_REALVALUE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/math/FGRealValue.h b/src/FDM/JSBSim/math/FGRealValue.h index 626770c26..277c595c1 100755 --- a/src/FDM/JSBSim/math/FGRealValue.h +++ b/src/FDM/JSBSim/math/FGRealValue.h @@ -40,7 +40,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_REALVALUE "$Id$" +#define ID_REALVALUE "$Id: FGRealValue.h,v 1.4 2009/08/30 03:51:28 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/math/FGRungeKutta.cpp b/src/FDM/JSBSim/math/FGRungeKutta.cpp new file mode 100644 index 000000000..bc3dabc07 --- /dev/null +++ b/src/FDM/JSBSim/math/FGRungeKutta.cpp @@ -0,0 +1,230 @@ +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + Header: FGRungeKutta.cpp + Author: Thomas Kreitler + Date started: 04/9/2010 + + ------------- Copyright (C) ------------- + + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA. + + Further information about the GNU Lesser General Public License can also be found on + the world wide web at http://www.gnu.org. + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + INCLUDES +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +#include +#include +#include + +#include "FGRungeKutta.h" + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + DEFINITIONS + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +using std::cout; +using std::endl; + +namespace JSBSim { + +static const char *IdSrc = "$Id: FGRungeKutta.cpp,v 1.1 2010/06/02 04:05:13 jberndt Exp $"; +static const char *IdHdr = ID_RUNGEKUTTA; + +const double FGRungeKutta::RealLimit = 1e30; + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +CLASS IMPLEMENTATION +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +FGRungeKutta::~FGRungeKutta() { }; + +int FGRungeKutta::init(double x_start, double x_end, int intervals) +{ + x0 = x_start; + x1 = x_end; + h = (x_end - x_start)/intervals; + safer_x1 = x1 - h*1e-6; // avoid 'intervals*h < x1' + h05 = h*0.5; + err = 0.0; + + if (x0>=x1) { + status &= eFaultyInit; + } + return status; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +/* + Make sure that a numerical result is within +/-RealLimit. + This is a hapless try to be portable. + (There will be at least one architecture/compiler combination + where this will fail.) +*/ + +bool FGRungeKutta::sane_val(double x) +{ + // assuming +/- inf behave as expected and 'nan' comparisons yield to false + if ( x < RealLimit && x > -RealLimit ) return true; + return false; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +double FGRungeKutta::evolve(double y_0, FGRungeKuttaProblem *pf) +{ + double x = x0; + double y = y_0; + pfo = pf; + + iterations = 0; + + if (!trace_values) { + while (xpFunc(x , y ); + k2 = pfo->pFunc(x + h05, y + h05*k1); + k3 = pfo->pFunc(x + h05, y + h05*k2); + k4 = pfo->pFunc(x + h , y + h *k3); + + y += h/6.0 * ( k1 + 2.0*k2 + 2.0*k3 + k4 ); + + return y; +} + + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +CLASS IMPLEMENTATION +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +// Butcher tableau +const double FGRKFehlberg::A2[] = { 0.0, 1.0/4.0 }; +const double FGRKFehlberg::A3[] = { 0.0, 3.0/32.0, 9.0/32.0 }; +const double FGRKFehlberg::A4[] = { 0.0, 1932.0/2197.0, -7200.0/2197.0, 7296.0/2197.0 }; +const double FGRKFehlberg::A5[] = { 0.0, 439.0/216.0, -8.0, 3680.0/513.0, -845.0/4104.0 }; +const double FGRKFehlberg::A6[] = { 0.0, -8.0/27.0, 2.0, -3544.0/2565.0, 1859.0/4104.0, -11.0/40.0 }; + +const double FGRKFehlberg::C[] = { 0.0, 0.0, 1.0/4.0, 3.0/8.0, 12.0/13.0, 1.0, 1.0/2.0 }; + +const double FGRKFehlberg::B[] = { 0.0, 16.0/135.0, 0.0, 6656.0/12825.0, 28561.0/56430.0, -9.0/50.0, 2.0/55.0 }; +const double FGRKFehlberg::Bs[] = { 0.0, 25.0/216.0, 0.0, 1408.0/2565.0, 2197.0/4104.0, -1.0/5.0, 0.0 }; + +// use this if truncation is an issue +// const double Ee[] = { 0.0, 1.0/360.0, 0.0, -128.0/4275.0, -2197.0/75240.0, 1.0/50.0, 2.0/55.0 }; + +FGRKFehlberg::~FGRKFehlberg() { }; + +double FGRKFehlberg::approximate(double x, double y) +{ + + double k1,k2,k3,k4,k5,k6, as; + + double y4_val; + double y5_val; + double abs_err; + double est_step; + int done = 0; + + + while (!done) { + + err = h*h*h*h*h; // h might change + + k1 = pfo->pFunc(x , y ); + + as = h*A2[1]*k1; + k2 = pfo->pFunc(x + C[2]*h , y + as ); + + as = h*(A3[1]*k1 + A3[2]*k2); + k3 = pfo->pFunc(x + C[3]*h , y + as ); + + as = h*(A4[1]*k1 + A4[2]*k2 + A4[3]*k3); + k4 = pfo->pFunc(x + C[4]*h , y + as ); + + as = h*(A5[1]*k1 + A5[2]*k2 + A5[3]*k3 + A5[4]*k4); + k5 = pfo->pFunc(x + C[5]*h , y + as ); + + as = h*(A6[1]*k1 + A6[2]*k2 + A6[3]*k3 + A6[4]*k4 + A6[5]*k5); + k6 = pfo->pFunc(x + C[6]*h , y + as ); + + /* B[2]*k2 and Bs[2]*k2 are zero */ + y5_val = y + h * ( B[1]*k1 + B[3]*k3 + B[4]*k4 + B[5]*k5 + B[6]*k6); + y4_val = y + h * (Bs[1]*k1 + Bs[3]*k3 + Bs[4]*k4 + Bs[5]*k5); + + abs_err = fabs(y4_val-y5_val); + // same in green + // abs_err = h * (Ee[1] * k1 + Ee[3] * k3 + Ee[4] * k4 + Ee[5] * k5 + Ee[6] * k6); + + // estimate step size + if (abs_err > epsilon) { + est_step = sqrt(sqrt(epsilon*h/abs_err)); + } else { + est_step=2.0*h; // cheat + } + + // check if a smaller step size is proposed + + if (shrink_avail>0 && est_stepGetNode(property_string); if (node == 0) { - cerr << "IndependenVar property, " << property_string - << " in Table definition is not defined." << endl; - abort(); + throw("IndependenVar property, " + property_string + " in Table definition is not defined."); } lookup_axis = axisElement->GetAttributeValue("lookup"); @@ -177,6 +175,8 @@ FGTable::FGTable(FGPropertyManager* propMan, Element* el) : PropertyManager(prop lookupProperty[eColumn] = node; } else if (lookup_axis == string("table")) { lookupProperty[eTable] = node; + } else if (!lookup_axis.empty()) { + throw("Lookup table axis specification not understood: " + lookup_axis); } else { // assumed single dimension table; row lookup lookupProperty[eRow] = node; } diff --git a/src/FDM/JSBSim/math/FGTable.h b/src/FDM/JSBSim/math/FGTable.h index 1b0d22e16..e96cf07fe 100644 --- a/src/FDM/JSBSim/math/FGTable.h +++ b/src/FDM/JSBSim/math/FGTable.h @@ -47,7 +47,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_TABLE "$Id$" +#define ID_TABLE "$Id: FGTable.h,v 1.11 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -233,7 +233,7 @@ combustion_efficiency = Lookup_Combustion_Efficiency->GetValue(equivalence_ratio @endcode @author Jon S. Berndt -@version $Id$ +@version $Id: FGTable.h,v 1.11 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/math/Makefile.am b/src/FDM/JSBSim/math/Makefile.am index ce92ff6eb..5ae295ede 100644 --- a/src/FDM/JSBSim/math/Makefile.am +++ b/src/FDM/JSBSim/math/Makefile.am @@ -2,10 +2,10 @@ noinst_LIBRARIES = libMath.a libMath_a_SOURCES = FGColumnVector3.cpp FGFunction.cpp FGLocation.cpp FGMatrix33.cpp \ FGPropertyValue.cpp FGQuaternion.cpp FGRealValue.cpp FGTable.cpp \ - FGCondition.cpp + FGCondition.cpp FGRungeKutta.cpp noinst_HEADERS = FGColumnVector3.h FGFunction.h FGLocation.h FGMatrix33.h \ FGParameter.h FGPropertyValue.h FGQuaternion.h FGRealValue.h FGTable.h \ - FGCondition.h + FGCondition.h FGRungeKutta.h INCLUDES = -I$(top_srcdir)/src/FDM/JSBSim diff --git a/src/FDM/JSBSim/models/FGAerodynamics.cpp b/src/FDM/JSBSim/models/FGAerodynamics.cpp index a793cce2f..d8c66df20 100644 --- a/src/FDM/JSBSim/models/FGAerodynamics.cpp +++ b/src/FDM/JSBSim/models/FGAerodynamics.cpp @@ -52,7 +52,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGAerodynamics.cpp,v 1.31 2009/11/28 14:30:11 andgi Exp $"; static const char *IdHdr = ID_AERODYNAMICS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGAerodynamics.h b/src/FDM/JSBSim/models/FGAerodynamics.h index 8c26e5277..0f966d845 100644 --- a/src/FDM/JSBSim/models/FGAerodynamics.h +++ b/src/FDM/JSBSim/models/FGAerodynamics.h @@ -52,7 +52,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_AERODYNAMICS "$Id$" +#define ID_AERODYNAMICS "$Id: FGAerodynamics.h,v 1.20 2009/11/12 13:08:11 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -109,7 +109,7 @@ CLASS DOCUMENTATION Systems may NOT be combined, or a load error will occur. @author Jon S. Berndt, Tony Peden - @version $Revision$ + @version $Revision: 1.20 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -214,7 +214,6 @@ private: typedef std::map AxisIndex; AxisIndex AxisIdx; FGFunction* AeroRPShift; - std::vector variables; typedef vector CoeffArray; CoeffArray* Coeff; FGColumnVector3 vFnative; diff --git a/src/FDM/JSBSim/models/FGAircraft.cpp b/src/FDM/JSBSim/models/FGAircraft.cpp index 75f9fba59..d292316d6 100644 --- a/src/FDM/JSBSim/models/FGAircraft.cpp +++ b/src/FDM/JSBSim/models/FGAircraft.cpp @@ -68,7 +68,7 @@ DEFINITIONS GLOBAL DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGAircraft.cpp,v 1.27 2010/07/27 23:18:19 jberndt Exp $"; static const char *IdHdr = ID_AIRCRAFT; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -123,6 +123,9 @@ bool FGAircraft::Run(void) vForces += GroundReactions->GetForces(); vForces += ExternalReactions->GetForces(); vForces += BuoyantForces->GetForces(); + } else { + const FGMatrix33& mTl2b = Propagate->GetTl2b(); + vForces = mTl2b * FGColumnVector3(0,0,-MassBalance->GetWeight()); } vMoments.InitMatrix(); @@ -136,10 +139,10 @@ bool FGAircraft::Run(void) vBodyAccel = vForces/MassBalance->GetMass(); - vNcg = vBodyAccel/Inertial->gravity(); + vNcg = vBodyAccel/Inertial->SLgravity(); vNwcg = Aerodynamics->GetTb2w() * vNcg; - vNwcg(3) = -1*vNwcg(3) + 1; + vNwcg(3) = 1.0 - vNwcg(3); RunPostFunctions(); diff --git a/src/FDM/JSBSim/models/FGAircraft.h b/src/FDM/JSBSim/models/FGAircraft.h index a66665c06..a03656895 100644 --- a/src/FDM/JSBSim/models/FGAircraft.h +++ b/src/FDM/JSBSim/models/FGAircraft.h @@ -49,7 +49,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_AIRCRAFT "$Id$" +#define ID_AIRCRAFT "$Id: FGAircraft.h,v 1.15 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -90,7 +90,7 @@ CLASS DOCUMENTATION @endcode @author Jon S. Berndt - @version $Id$ + @version $Id: FGAircraft.h,v 1.15 2009/10/24 22:59:30 jberndt Exp $ @see Cooke, Zyda, Pratt, and McGhee, "NPSNET: Flight Simulation Dynamic Modeling Using Quaternions", Presence, Vol. 1, No. 4, pp. 404-420 Naval Postgraduate School, January 1994 diff --git a/src/FDM/JSBSim/models/FGAtmosphere.cpp b/src/FDM/JSBSim/models/FGAtmosphere.cpp index 8acb17c1b..2db1c65d9 100644 --- a/src/FDM/JSBSim/models/FGAtmosphere.cpp +++ b/src/FDM/JSBSim/models/FGAtmosphere.cpp @@ -48,11 +48,11 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGAtmosphere.h" -#include "FGState.h" -#include "FGFDMExec.h" #include "FGAircraft.h" #include "FGPropagate.h" #include "FGInertial.h" +#include "FGAuxiliary.h" +#include "FGFDMExec.h" #include "input_output/FGPropertyManager.h" #include #include @@ -61,7 +61,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGAtmosphere.cpp,v 1.35 2010/08/11 11:51:33 jberndt Exp $"; static const char *IdHdr = ID_ATMOSPHERE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -277,7 +277,9 @@ void FGAtmosphere::Calculate(double altitude) void FGAtmosphere::CalculateDerived(void) { T_dev = (*temperature) - GetTemperature(h); - density_altitude = h + T_dev * 66.7; + + if (T_dev == 0.0) density_altitude = h; + else density_altitude = 518.4/0.00357 * (1.0 - pow(GetDensityRatio(),0.235)); if (turbType != ttNone) Turbulence(); @@ -383,7 +385,7 @@ void FGAtmosphere::SetWindPsi(double dir) void FGAtmosphere::Turbulence(void) { - double DeltaT = rate*State->Getdt(); + double DeltaT = rate*FDMExec->GetDeltaT(); switch (turbType) { case ttStandard: { diff --git a/src/FDM/JSBSim/models/FGAtmosphere.h b/src/FDM/JSBSim/models/FGAtmosphere.h index 2a7443e5d..84d3f072a 100644 --- a/src/FDM/JSBSim/models/FGAtmosphere.h +++ b/src/FDM/JSBSim/models/FGAtmosphere.h @@ -49,7 +49,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ATMOSPHERE "$Id$" +#define ID_ATMOSPHERE "$Id: FGAtmosphere.h,v 1.22 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -63,7 +63,7 @@ CLASS DOCUMENTATION /** Models the 1976 Standard Atmosphere. @author Tony Peden, Jon Berndt - @version $Id$ + @version $Id: FGAtmosphere.h,v 1.22 2009/10/02 10:30:09 jberndt Exp $ @see Anderson, John D. "Introduction to Flight, Third Edition", McGraw-Hill, 1989, ISBN 0-07-001641-0 */ diff --git a/src/FDM/JSBSim/models/FGAuxiliary.cpp b/src/FDM/JSBSim/models/FGAuxiliary.cpp index 815a1b400..ededdc1cc 100755 --- a/src/FDM/JSBSim/models/FGAuxiliary.cpp +++ b/src/FDM/JSBSim/models/FGAuxiliary.cpp @@ -4,7 +4,7 @@ Author: Tony Peden, Jon Berndt Date started: 01/26/99 Purpose: Calculates additional parameters needed by the visual system, etc. - Called by: FGSimExec + Called by: FGFDMExec ------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) ------------- @@ -59,7 +59,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGAuxiliary.cpp,v 1.42 2010/07/27 23:18:19 jberndt Exp $"; static const char *IdHdr = ID_AUXILIARY; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -167,22 +167,10 @@ bool FGAuxiliary::Run() vEulerRates(ePhi) = vPQR(eP) + vEulerRates(ePsi)*sTht; } -// 12/16/2005, JSB: For ground handling purposes, at this time, let's ramp -// in the effects of wind from 10 fps to 30 fps when there is weight on the -// landing gear wheels. - - if (GroundReactions->GetWOW() && vUVW(eU) < 10) { - vAeroPQR = vPQR; - vAeroUVW = vUVW; - } else if (GroundReactions->GetWOW() && vUVW(eU) < 30) { - double factor = (vUVW(eU) - 10.0)/20.0; - vAeroPQR = vPQR - factor*Atmosphere->GetTurbPQR(); - vAeroUVW = vUVW - factor*Propagate->GetTl2b()*Atmosphere->GetTotalWindNED(); - } else { - FGColumnVector3 wind = Propagate->GetTl2b()*Atmosphere->GetTotalWindNED(); - vAeroPQR = vPQR - Atmosphere->GetTurbPQR(); - vAeroUVW = vUVW - wind; - } +// Combine the wind speed with aircraft speed to obtain wind relative speed + FGColumnVector3 wind = Propagate->GetTl2b()*Atmosphere->GetTotalWindNED(); + vAeroPQR = vPQR - Atmosphere->GetTurbPQR(); + vAeroUVW = vUVW - wind; Vt = vAeroUVW.Magnitude(); if ( Vt > 0.05) { @@ -249,15 +237,16 @@ bool FGAuxiliary::Run() vPilotAccel.InitMatrix(); if ( Vt > 1.0 ) { - vAircraftAccel = Aerodynamics->GetForces() - + Propulsion->GetForces() - + GroundReactions->GetForces() - + ExternalReactions->GetForces() - + BuoyantForces->GetForces(); + // Use the "+=" operator to avoid the creation of temporary objects. + vAircraftAccel = Aerodynamics->GetForces(); + vAircraftAccel += Propulsion->GetForces(); + vAircraftAccel += GroundReactions->GetForces(); + vAircraftAccel += ExternalReactions->GetForces(); + vAircraftAccel += BuoyantForces->GetForces(); vAircraftAccel /= MassBalance->GetMass(); // Nz is Acceleration in "g's", along normal axis (-Z body axis) - Nz = -vAircraftAccel(eZ)/Inertial->gravity(); + Nz = -vAircraftAccel(eZ)/Inertial->SLgravity(); vToEyePt = MassBalance->StructuralToBody(Aircraft->GetXYZep()); vPilotAccel = vAircraftAccel + Propagate->GetPQRdot() * vToEyePt; vPilotAccel += vPQR * (vPQR * vToEyePt); @@ -268,15 +257,15 @@ bool FGAuxiliary::Run() // any jitter that could be introduced by the landing gear. Theoretically, // this branch could be eliminated, with a penalty of having a short // transient at startup (lasting only a fraction of a second). - vPilotAccel = Propagate->GetTl2b() * FGColumnVector3( 0.0, 0.0, -Inertial->gravity() ); - Nz = -vPilotAccel(eZ)/Inertial->gravity(); + vPilotAccel = Propagate->GetTl2b() * FGColumnVector3( 0.0, 0.0, -Inertial->SLgravity() ); + Nz = -vPilotAccel(eZ)/Inertial->SLgravity(); } - vPilotAccelN = vPilotAccel/Inertial->gravity(); + vPilotAccelN = vPilotAccel/Inertial->SLgravity(); // VRP computation const FGLocation& vLocation = Propagate->GetLocation(); - FGColumnVector3 vrpStructural = Aircraft->GetXYZvrp(); + FGColumnVector3& vrpStructural = Aircraft->GetXYZvrp(); FGColumnVector3 vrpBody = MassBalance->StructuralToBody( vrpStructural ); FGColumnVector3 vrpLocal = Propagate->GetTb2l() * vrpBody; vLocationVRP = vLocation.LocalToLocation( vrpLocal ); diff --git a/src/FDM/JSBSim/models/FGAuxiliary.h b/src/FDM/JSBSim/models/FGAuxiliary.h index e3baa4911..d86cc5f11 100644 --- a/src/FDM/JSBSim/models/FGAuxiliary.h +++ b/src/FDM/JSBSim/models/FGAuxiliary.h @@ -48,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_AUXILIARY "$Id$" +#define ID_AUXILIARY "$Id: FGAuxiliary.h,v 1.17 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -100,7 +100,7 @@ CLASS DOCUMENTATION The radius R is calculated below in the vector vToEyePt. @author Tony Peden, Jon Berndt - @version $Id$ + @version $Id: FGAuxiliary.h,v 1.17 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGBuoyantForces.cpp b/src/FDM/JSBSim/models/FGBuoyantForces.cpp index 49d9cb2e5..64c97ebfb 100644 --- a/src/FDM/JSBSim/models/FGBuoyantForces.cpp +++ b/src/FDM/JSBSim/models/FGBuoyantForces.cpp @@ -5,7 +5,7 @@ Date started: 01/21/08 Purpose: Encapsulates the buoyant forces - ------------- Copyright (C) 2008 - 2009 Anders Gidenstam ------------- + ------------- Copyright (C) 2008 - 2010 Anders Gidenstam ------------- ------------- Copyright (C) 2008 Jon S. Berndt (jon@jsbsim.org) ------------- This program is free software; you can redistribute it and/or modify it under @@ -38,14 +38,14 @@ INCLUDES #include "FGBuoyantForces.h" #include "FGMassBalance.h" -#include "input_output/FGPropertyManager.h" // Need? +#include "input_output/FGPropertyManager.h" #include using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGBuoyantForces.cpp,v 1.12 2010/05/07 18:59:55 andgi Exp $"; static const char *IdHdr = ID_BUOYANTFORCES; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -63,8 +63,6 @@ FGBuoyantForces::FGBuoyantForces(FGFDMExec* FDMExec) : FGModel(FDMExec) gasCellJ.InitMatrix(); - bind(); - Debug(0); } @@ -141,6 +139,10 @@ bool FGBuoyantForces::Load(Element *element) FGModel::PostLoad(element); + if (!NoneDefined) { + bind(); + } + return true; } @@ -258,6 +260,19 @@ string FGBuoyantForces::GetBuoyancyValues(string delimeter) void FGBuoyantForces::bind(void) { + typedef double (FGBuoyantForces::*PMF)(int) const; + PropertyManager->Tie("moments/l-buoyancy-lbsft", this, eL, + (PMF)&FGBuoyantForces::GetMoments); + PropertyManager->Tie("moments/m-buoyancy-lbsft", this, eM, + (PMF)&FGBuoyantForces::GetMoments); + PropertyManager->Tie("moments/n-buoyancy-lbsft", this, eN, + (PMF)&FGBuoyantForces::GetMoments); + PropertyManager->Tie("forces/fbx-buoyancy-lbs", this, eX, + (PMF)&FGBuoyantForces::GetForces); + PropertyManager->Tie("forces/fby-buoyancy-lbs", this, eY, + (PMF)&FGBuoyantForces::GetForces); + PropertyManager->Tie("forces/fbz-buoyancy-lbs", this, eZ, + (PMF)&FGBuoyantForces::GetForces); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGBuoyantForces.h b/src/FDM/JSBSim/models/FGBuoyantForces.h index ec664b3ab..c27566d37 100644 --- a/src/FDM/JSBSim/models/FGBuoyantForces.h +++ b/src/FDM/JSBSim/models/FGBuoyantForces.h @@ -4,7 +4,7 @@ Author: Anders Gidenstam, Jon S. Berndt Date started: 01/21/08 - ------------- Copyright (C) 2008 Anders Gidenstam ------------- + ------------- Copyright (C) 2008 - 2010 Anders Gidenstam ------------- ------------- Copyright (C) 2008 Jon S. Berndt (jon@jsbsim.org) ------------- This program is free software; you can redistribute it and/or modify it under @@ -51,7 +51,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_BUOYANTFORCES "$Id$" +#define ID_BUOYANTFORCES "$Id: FGBuoyantForces.h,v 1.11 2010/05/07 20:38:34 andgi Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -96,7 +96,7 @@ CLASS DOCUMENTATION See FGGasCell for the full configuration file format for gas cells. @author Anders Gidenstam, Jon S. Berndt - @version $Id$ + @version $Id: FGBuoyantForces.h,v 1.11 2010/05/07 20:38:34 andgi Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -130,10 +130,18 @@ public: @return a force vector. */ const FGColumnVector3& GetForces(void) const {return vTotalForces;} + /** Gets a component of the total Buoyant force vector. + @return a component of the force vector. */ + double GetForces(int idx) const {return vTotalForces(idx);} + /** Gets the total Buoyancy moment vector. @return a moment vector. */ const FGColumnVector3& GetMoments(void) const {return vTotalMoments;} + /** Gets a component of the total Buoyancy moment vector. + @return a component of the moment vector. */ + double GetMoments(int idx) const {return vTotalMoments(idx);} + /** Gets the total gas mass. The gas mass is part of the aircraft's inertia. @return mass in slugs. */ diff --git a/src/FDM/JSBSim/models/FGExternalForce.cpp b/src/FDM/JSBSim/models/FGExternalForce.cpp index fa1d35d22..12ade79e7 100755 --- a/src/FDM/JSBSim/models/FGExternalForce.cpp +++ b/src/FDM/JSBSim/models/FGExternalForce.cpp @@ -60,7 +60,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGExternalForce.cpp,v 1.10 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_EXTERNALFORCE; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGExternalForce.h b/src/FDM/JSBSim/models/FGExternalForce.h index d4a90db83..f1a6a41ac 100755 --- a/src/FDM/JSBSim/models/FGExternalForce.h +++ b/src/FDM/JSBSim/models/FGExternalForce.h @@ -51,7 +51,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_EXTERNALFORCE "$Id$" +#define ID_EXTERNALFORCE "$Id: FGExternalForce.h,v 1.8 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/FGExternalReactions.cpp b/src/FDM/JSBSim/models/FGExternalReactions.cpp index a9b6ee275..7df087c1e 100755 --- a/src/FDM/JSBSim/models/FGExternalReactions.cpp +++ b/src/FDM/JSBSim/models/FGExternalReactions.cpp @@ -53,7 +53,7 @@ DEFINITIONS GLOBAL DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGExternalReactions.cpp,v 1.8 2009/11/12 13:08:11 jberndt Exp $"; static const char *IdHdr = ID_EXTERNALREACTIONS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGExternalReactions.h b/src/FDM/JSBSim/models/FGExternalReactions.h index c6f65fe10..10ad35d07 100755 --- a/src/FDM/JSBSim/models/FGExternalReactions.h +++ b/src/FDM/JSBSim/models/FGExternalReactions.h @@ -46,7 +46,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_EXTERNALREACTIONS "$Id$" +#define ID_EXTERNALREACTIONS "$Id: FGExternalReactions.h,v 1.9 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/FGFCS.cpp b/src/FDM/JSBSim/models/FGFCS.cpp index 477890295..4d71ca97d 100644 --- a/src/FDM/JSBSim/models/FGFCS.cpp +++ b/src/FDM/JSBSim/models/FGFCS.cpp @@ -63,7 +63,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFCS.cpp,v 1.69 2010/08/10 12:39:07 jberndt Exp $"; static const char *IdHdr = ID_FCS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -533,19 +533,17 @@ bool FGFCS::Load(Element* el, SystemType systype) Components=0; - string separator = "/"; - // ToDo: The handling of name and file attributes could be improved, here, // considering that a name can be in the external file, as well. name = el->GetAttributeValue("name"); - if (name.empty()) { + if (name.empty() || !el->GetAttributeValue("file").empty()) { fname = el->GetAttributeValue("file"); if (systype == stSystem) { file = FindSystemFullPathname(fname); } else { - file = FDMExec->GetFullAircraftPath() + separator + fname + ".xml"; + file = FDMExec->GetFullAircraftPath() + "/" + fname + ".xml"; } if (fname.empty()) { cerr << "FCS, Autopilot, or system does not appear to be defined inline nor in a file" << endl; @@ -692,49 +690,55 @@ double FGFCS::GetBrake(FGLGear::BrakeGroup bg) //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -string FGFCS::FindSystemFullPathname(const string& system_filename) +string FGFCS::FindSystemFullPathname(const string& sysfilename) { string fullpath, localpath; + string system_filename = sysfilename; string systemPath = FDMExec->GetSystemsPath(); string aircraftPath = FDMExec->GetFullAircraftPath(); ifstream system_file; - string separator = "/"; + fullpath = systemPath + "/"; + localpath = aircraftPath + "/Systems/"; - fullpath = systemPath + separator; - localpath = aircraftPath + separator + "Systems" + separator; + if (system_filename.length() <=4 || system_filename.substr(system_filename.length()-4, 4) != ".xml") { + system_filename.append(".xml"); + } - system_file.open(string(fullpath + system_filename + ".xml").c_str()); + system_file.open(string(localpath + system_filename).c_str()); if ( !system_file.is_open()) { - system_file.open(string(localpath + system_filename + ".xml").c_str()); + system_file.open(string(fullpath + system_filename).c_str()); if ( !system_file.is_open()) { cerr << " Could not open system file: " << system_filename << " in path " << fullpath << " or " << localpath << endl; return string(""); } else { - return string(localpath + system_filename + ".xml"); + return string(fullpath + system_filename); } } - return string(fullpath + system_filename + ".xml"); + return string(localpath + system_filename); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -ifstream* FGFCS::FindSystemFile(const string& system_filename) +ifstream* FGFCS::FindSystemFile(const string& sysfilename) { string fullpath, localpath; + string system_filename = sysfilename; string systemPath = FDMExec->GetSystemsPath(); string aircraftPath = FDMExec->GetFullAircraftPath(); ifstream* system_file = new ifstream(); - string separator = "/"; + fullpath = systemPath + "/"; + localpath = aircraftPath + "/Systems/"; - fullpath = systemPath + separator; - localpath = aircraftPath + separator + "Systems" + separator; + if (system_filename.substr(system_filename.length()-4, 4) != ".xml") { + system_filename.append(".xml"); + } - system_file->open(string(fullpath + system_filename + ".xml").c_str()); + system_file->open(string(localpath + system_filename).c_str()); if ( !system_file->is_open()) { - system_file->open(string(localpath + system_filename + ".xml").c_str()); + system_file->open(string(fullpath + system_filename).c_str()); if ( !system_file->is_open()) { cerr << " Could not open system file: " << system_filename << " in path " << fullpath << " or " << localpath << endl; diff --git a/src/FDM/JSBSim/models/FGFCS.h b/src/FDM/JSBSim/models/FGFCS.h index b00c037a9..6e10de9c4 100644 --- a/src/FDM/JSBSim/models/FGFCS.h +++ b/src/FDM/JSBSim/models/FGFCS.h @@ -51,7 +51,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FCS "$Id$" +#define ID_FCS "$Id: FGFCS.h,v 1.28 2010/01/18 13:12:25 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -168,7 +168,7 @@ CLASS DOCUMENTATION @property gear/tailhook-pos-norm @author Jon S. Berndt - @version $Revision$ + @version $Revision: 1.28 $ @see FGActuator @see FGDeadBand @see FGFCSFunction @@ -407,12 +407,12 @@ public: /** Sets the throttle command for the specified engine @param engine engine ID number - @param cmd throttle command in percent (0 - 100)*/ + @param cmd normalized throttle command (0.0 - 1.0)*/ void SetThrottleCmd(int engine, double cmd); /** Sets the mixture command for the specified engine @param engine engine ID number - @param cmd mixture command in percent (0 - 100)*/ + @param cmd normalized mixture command (0.0 - 1.0)*/ void SetMixtureCmd(int engine, double cmd); /** Set the gear extend/retract command, defaults to down @@ -462,12 +462,12 @@ public: /** Sets the actual throttle setting for the specified engine @param engine engine ID number - @param cmd throttle setting in percent (0 - 100)*/ + @param cmd normalized throttle setting (0.0 - 1.0)*/ void SetThrottlePos(int engine, double cmd); /** Sets the actual mixture setting for the specified engine @param engine engine ID number - @param cmd mixture setting in percent (0 - 100)*/ + @param cmd normalized mixture setting (0.0 - 1.0)*/ void SetMixturePos(int engine, double cmd); /** Sets the steering position diff --git a/src/FDM/JSBSim/models/FGGasCell.cpp b/src/FDM/JSBSim/models/FGGasCell.cpp index 73c5091dd..8edabcd9a 100644 --- a/src/FDM/JSBSim/models/FGGasCell.cpp +++ b/src/FDM/JSBSim/models/FGGasCell.cpp @@ -53,7 +53,7 @@ using std::max; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGGasCell.cpp,v 1.12 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_GASCELL; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGGasCell.h b/src/FDM/JSBSim/models/FGGasCell.h index 0aae911b1..de34fb670 100644 --- a/src/FDM/JSBSim/models/FGGasCell.h +++ b/src/FDM/JSBSim/models/FGGasCell.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_GASCELL "$Id$" +#define ID_GASCELL "$Id: FGGasCell.h,v 1.10 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/FGGroundReactions.cpp b/src/FDM/JSBSim/models/FGGroundReactions.cpp index c8afc723b..fdbfa254f 100644 --- a/src/FDM/JSBSim/models/FGGroundReactions.cpp +++ b/src/FDM/JSBSim/models/FGGroundReactions.cpp @@ -46,13 +46,52 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGGroundReactions.cpp,v 1.29 2010/07/30 11:50:01 jberndt Exp $"; static const char *IdHdr = ID_GROUNDREACTIONS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -CLASS IMPLEMENTATION +CLASS IMPLEMENTATION for MultiplierIterator (See below for FGGroundReactions) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ +MultiplierIterator::MultiplierIterator(FGGroundReactions* GndReactions) +: GroundReactions(GndReactions), + multiplier(NULL), + gearNum(0), + entry(0) +{ + for (int i=0; i < GroundReactions->GetNumGearUnits(); i++) { + FGLGear* gear = GroundReactions->GetGearUnit(i); + + if (!gear->GetWOW()) continue; + + gearNum = i; + multiplier = gear->GetMultiplierEntry(0); + break; + } +} + +MultiplierIterator& MultiplierIterator::operator++() +{ + for (int i=gearNum; i < GroundReactions->GetNumGearUnits(); i++) { + FGLGear* gear = GroundReactions->GetGearUnit(i); + + if (!gear->GetWOW()) continue; + + multiplier = gear->GetMultiplierEntry(++entry); + if (multiplier) { + gearNum = i; + break; + } + else + entry = -1; + } + + return *this; +} + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +CLASS IMPLEMENTATION +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ FGGroundReactions::FGGroundReactions(FGFDMExec* fgex) : FGModel(fgex) { @@ -123,6 +162,20 @@ bool FGGroundReactions::GetWOW(void) return result; } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// This function must be called after friction forces are resolved in order to +// include them in the ground reactions total force and moment. +void FGGroundReactions::UpdateForcesAndMoments(void) +{ + vForces.InitMatrix(); + vMoments.InitMatrix(); + + for (unsigned int i=0; iUpdateForces(); + vMoments += lGear[i]->GetMoments(); + } +} + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% bool FGGroundReactions::Load(Element* el) diff --git a/src/FDM/JSBSim/models/FGGroundReactions.h b/src/FDM/JSBSim/models/FGGroundReactions.h index a5785d6ca..5c5ea682c 100644 --- a/src/FDM/JSBSim/models/FGGroundReactions.h +++ b/src/FDM/JSBSim/models/FGGroundReactions.h @@ -45,7 +45,7 @@ INCLUDES #include "math/FGColumnVector3.h" #include "input_output/FGXMLElement.h" -#define ID_GROUNDREACTIONS "$Id$" +#define ID_GROUNDREACTIONS "$Id: FGGroundReactions.h,v 1.17 2010/07/30 11:50:01 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -78,6 +78,19 @@ CLASS DOCUMENTATION CLASS DECLARATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ +class MultiplierIterator +{ +public: + MultiplierIterator(FGGroundReactions* GndReactions); + MultiplierIterator& operator++(); + FGPropagate::LagrangeMultiplier* operator*() { return multiplier; } +private: + FGGroundReactions* GroundReactions; + FGPropagate::LagrangeMultiplier* multiplier; + int gearNum; + int entry; +}; + class FGGroundReactions : public FGModel { public: @@ -94,6 +107,7 @@ public: string GetGroundReactionStrings(string delimeter); string GetGroundReactionValues(string delimeter); bool GetWOW(void); + void UpdateForcesAndMoments(void); int GetNumGearUnits(void) const { return (int)lGear.size(); } diff --git a/src/FDM/JSBSim/models/FGInertial.cpp b/src/FDM/JSBSim/models/FGInertial.cpp index 4ff657a51..ab2670eb9 100644 --- a/src/FDM/JSBSim/models/FGInertial.cpp +++ b/src/FDM/JSBSim/models/FGInertial.cpp @@ -38,7 +38,6 @@ INCLUDES #include "FGInertial.h" #include "FGFDMExec.h" #include "FGPropagate.h" -#include "FGState.h" #include "FGMassBalance.h" #include @@ -46,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGInertial.cpp,v 1.18 2010/03/28 05:57:00 jberndt Exp $"; static const char *IdHdr = ID_INERTIAL; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -119,7 +118,7 @@ bool FGInertial::Run(void) // Gravitation accel double r = Propagate->GetRadius(); gAccel = GetGAccel(r); - earthPosAngle += State->Getdt()*RotationRate; + earthPosAngle += FDMExec->GetDeltaT()*RotationRate; RunPostFunctions(); @@ -133,6 +132,34 @@ double FGInertial::GetGAccel(double r) const return GM/(r*r); } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// +// Calculate the WGS84 gravitation value in ECEF frame. Pass in the ECEF position +// via the position parameter. The J2Gravity value returned is in ECEF frame, +// and therefore may need to be expressed (transformed) in another frame, +// depending on how it is used. See Stevens and Lewis eqn. 1.4-16. + +FGColumnVector3 FGInertial::GetGravityJ2(FGColumnVector3 position) const +{ + FGColumnVector3 J2Gravity; + + // Gravitation accel + double r = position.Magnitude(); + double lat = Propagate->GetLatitude(); + double sinLat = sin(lat); + + double preCommon = 1.5*J2*(a/r)*(a/r); + double xy = 1.0 - 5.0*(sinLat*sinLat); + double z = 3.0 - 5.0*(sinLat*sinLat); + double GMOverr2 = GM/(r*r); + + J2Gravity(1) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eX)/r); + J2Gravity(2) = -GMOverr2 * ((1.0 + (preCommon * xy)) * position(eY)/r); + J2Gravity(3) = -GMOverr2 * ((1.0 + (preCommon * z)) * position(eZ)/r); + + return J2Gravity; +} + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGInertial::bind(void) diff --git a/src/FDM/JSBSim/models/FGInertial.h b/src/FDM/JSBSim/models/FGInertial.h index cf4579236..f4db378a2 100644 --- a/src/FDM/JSBSim/models/FGInertial.h +++ b/src/FDM/JSBSim/models/FGInertial.h @@ -47,7 +47,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_INERTIAL "$Id$" +#define ID_INERTIAL "$Id: FGInertial.h,v 1.15 2010/01/27 04:01:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -82,10 +82,13 @@ public: double GetEarthPositionAngle(void) const { return earthPosAngle; } double GetEarthPositionAngleDeg(void) const { return earthPosAngle*radtodeg;} double GetGAccel(double r) const; + FGColumnVector3 GetGravityJ2(FGColumnVector3 position) const; double GetRefRadius(void) const {return RadiusReference;} double GetSemimajor(void) const {return a;} double GetSemiminor(void) const {return b;} + void SetEarthPositionAngle(double epa) {earthPosAngle = epa;} + private: double gAccel; double gAccelReference; diff --git a/src/FDM/JSBSim/models/FGInput.cpp b/src/FDM/JSBSim/models/FGInput.cpp index dd124efa0..c8cc13b83 100755 --- a/src/FDM/JSBSim/models/FGInput.cpp +++ b/src/FDM/JSBSim/models/FGInput.cpp @@ -39,7 +39,7 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGInput.h" -#include "FGState.h" +#include "FGAircraft.h" #include "FGFDMExec.h" #include "input_output/FGfdmSocket.h" @@ -53,7 +53,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGInput.cpp,v 1.19 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_INPUT; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -192,7 +192,7 @@ bool FGInput::Run(void) info << "JSBSim version: " << JSBSim_version << endl; info << "Config File version: " << needed_cfg_version << endl; info << "Aircraft simulated: " << Aircraft->GetAircraftName() << endl; - info << "Simulation time: " << setw(8) << setprecision(3) << State->Getsim_time() << endl; + info << "Simulation time: " << setw(8) << setprecision(3) << FDMExec->GetSimTime() << endl; socket->Reply(info.str()); } else if (command == "help") { // HELP diff --git a/src/FDM/JSBSim/models/FGInput.h b/src/FDM/JSBSim/models/FGInput.h index 58aa9ebdb..b86a428c6 100755 --- a/src/FDM/JSBSim/models/FGInput.h +++ b/src/FDM/JSBSim/models/FGInput.h @@ -46,7 +46,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_INPUT "$Id$" +#define ID_INPUT "$Id: FGInput.h,v 1.8 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/FGLGear.cpp b/src/FDM/JSBSim/models/FGLGear.cpp index b0c448b41..569b76ee4 100644 --- a/src/FDM/JSBSim/models/FGLGear.cpp +++ b/src/FDM/JSBSim/models/FGLGear.cpp @@ -41,7 +41,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGLGear.h" -#include "FGState.h" #include "FGGroundReactions.h" #include "FGFCS.h" #include "FGAuxiliary.h" @@ -62,7 +61,7 @@ DEFINITIONS GLOBAL DATA %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGLGear.cpp,v 1.76 2010/07/30 11:50:01 jberndt Exp $"; static const char *IdHdr = ID_LGEAR; // Body To Structural (body frame is rotated 180 deg about Y and lengths are given in @@ -76,7 +75,8 @@ CLASS IMPLEMENTATION FGLGear::FGLGear(Element* el, FGFDMExec* fdmex, int number) : FGForce(fdmex), GearNumber(number), - SteerAngle(0.0) + SteerAngle(0.0), + Castered(false) { Element *force_table=0; Element *dampCoeff=0; @@ -202,7 +202,7 @@ FGLGear::FGLGear(Element* el, FGFDMExec* fdmex, int number) : if (sSteerType == "STEERABLE") eSteerType = stSteer; else if (sSteerType == "FIXED" ) eSteerType = stFixed; - else if (sSteerType == "CASTERED" ) eSteerType = stCaster; + else if (sSteerType == "CASTERED" ) {eSteerType = stCaster; Castered = true;} else if (sSteerType.empty() ) {eSteerType = stFixed; sSteerType = "FIXED (defaulted)";} else { @@ -210,50 +210,11 @@ FGLGear::FGLGear(Element* el, FGFDMExec* fdmex, int number) : << sSteerType << " is undefined." << endl; } - RFRV = 0.7; // Rolling force relaxation velocity, default value - SFRV = 0.7; // Side force relaxation velocity, default value - - Element* relax_vel = el->FindElement("relaxation_velocity"); - if (relax_vel) { - if (relax_vel->FindElement("rolling")) { - RFRV = relax_vel->FindElementValueAsNumberConvertTo("rolling", "FT/SEC"); - } - if (relax_vel->FindElement("side")) { - SFRV = relax_vel->FindElementValueAsNumberConvertTo("side", "FT/SEC"); - } - } - - State = fdmex->GetState(); - Aircraft = fdmex->GetAircraft(); - Propagate = fdmex->GetPropagate(); - Auxiliary = fdmex->GetAuxiliary(); - FCS = fdmex->GetFCS(); - MassBalance = fdmex->GetMassBalance(); - - LongForceLagFilterCoeff = 1/State->Getdt(); // default longitudinal force filter coefficient - LatForceLagFilterCoeff = 1/State->Getdt(); // default lateral force filter coefficient - - Element* force_lag_filter_elem = el->FindElement("force_lag_filter"); - if (force_lag_filter_elem) { - if (force_lag_filter_elem->FindElement("rolling")) { - LongForceLagFilterCoeff = force_lag_filter_elem->FindElementValueAsNumber("rolling"); - } - if (force_lag_filter_elem->FindElement("side")) { - LatForceLagFilterCoeff = force_lag_filter_elem->FindElementValueAsNumber("side"); - } - } - - LongForceFilter = Filter(LongForceLagFilterCoeff, State->Getdt()); - LatForceFilter = Filter(LatForceLagFilterCoeff, State->Getdt()); - - WheelSlipLagFilterCoeff = 1/State->Getdt(); - - Element *wheel_slip_angle_lag_elem = el->FindElement("wheel_slip_filter"); - if (wheel_slip_angle_lag_elem) { - WheelSlipLagFilterCoeff = wheel_slip_angle_lag_elem->GetDataAsNumber(); - } - - WheelSlipFilter = Filter(WheelSlipLagFilterCoeff, State->Getdt()); + Auxiliary = fdmex->GetAuxiliary(); + Propagate = fdmex->GetPropagate(); + FCS = fdmex->GetFCS(); + MassBalance = fdmex->GetMassBalance(); + GroundReactions = fdmex->GetGroundReactions(); GearUp = false; GearDown = true; @@ -292,6 +253,11 @@ FGLGear::FGLGear(Element* el, FGFDMExec* fdmex, int number) : Peak = staticFCoeff; Curvature = 1.03; + // Initialize Lagrange multipliers + LMultiplier[ftRoll].value = 0.; + LMultiplier[ftSide].value = 0.; + LMultiplier[ftRoll].value = 0.; + Debug(0); } @@ -307,36 +273,36 @@ FGLGear::~FGLGear() FGColumnVector3& FGLGear::GetBodyForces(void) { - double t = fdmex->GetState()->Getsim_time(); - dT = State->Getdt()*fdmex->GetGroundReactions()->GetRate(); + double t = fdmex->GetSimTime(); + dT = fdmex->GetDeltaT()*GroundReactions->GetRate(); vFn.InitMatrix(); if (isRetractable) ComputeRetractionState(); if (GearDown) { - double verticalZProj = 0.; - vWhlBodyVec = MassBalance->StructuralToBody(vXYZn); // Get wheel in body frame vLocalGear = Propagate->GetTb2l() * vWhlBodyVec; // Get local frame wheel location gearLoc = Propagate->GetLocation().LocalToLocation(vLocalGear); - // Compute the height of the theoretical location of the wheel (if strut is not compressed) with - // respect to the ground level + // Compute the height of the theoretical location of the wheel (if strut is + // not compressed) with respect to the ground level double height = fdmex->GetGroundCallback()->GetAGLevel(t, gearLoc, contact, normal, cvel); - vGroundNormal = -1. * Propagate->GetTec2b() * normal; + vGroundNormal = Propagate->GetTec2b() * normal; + + // The height returned above is the AGL and is expressed in the Z direction + // of the ECEF coordinate frame. We now need to transform this height in + // actual compression of the strut (BOGEY) of in the normal direction to the + // ground (STRUCTURE) + double normalZ = (Propagate->GetTec2l()*normal)(eZ); + double LGearProj = -(mTGear.Transposed() * vGroundNormal)(eZ); - // The height returned above is the AGL and is expressed in the Z direction of the local - // coordinate frame. We now need to transform this height in actual compression of the strut (BOGEY) - // of in the normal direction to the ground (STRUCTURE) switch (eContactType) { case ctBOGEY: - verticalZProj = (Propagate->GetTb2l()*mTGear*FGColumnVector3(0.,0.,1.))(eZ); - compressLength = verticalZProj > 0.0 ? -height / verticalZProj : 0.0; + compressLength = LGearProj > 0.0 ? height * normalZ / LGearProj : 0.0; break; case ctSTRUCTURE: - verticalZProj = (Propagate->GetTec2l()*normal)(eZ); - compressLength = fabs(verticalZProj) > 0.0 ? -height / verticalZProj : 0.0; + compressLength = height * normalZ / DotProduct(normal, normal); break; } @@ -344,13 +310,22 @@ FGColumnVector3& FGLGear::GetBodyForces(void) WOW = true; - // [The next equation should really use the vector to the contact patch of - // the tire including the strut compression and not the original vWhlBodyVec.] + // The following equations use the vector to the tire contact patch + // including the strut compression. + FGColumnVector3 vWhlDisplVec; + + switch(eContactType) { + case ctBOGEY: + vWhlDisplVec = mTGear * FGColumnVector3(0., 0., -compressLength); + break; + case ctSTRUCTURE: + vWhlDisplVec = compressLength * vGroundNormal; + break; + } - FGColumnVector3 vWhlDisplVec = mTGear * FGColumnVector3(0., 0., compressLength); - FGColumnVector3 vWhlContactVec = vWhlBodyVec - vWhlDisplVec; - vActingXYZn = vXYZn - Tb2s * vWhlDisplVec; - FGColumnVector3 vBodyWhlVel = Propagate->GetPQR() * vWhlContactVec; + FGColumnVector3 vWhlContactVec = vWhlBodyVec + vWhlDisplVec; + vActingXYZn = vXYZn + Tb2s * vWhlDisplVec; + FGColumnVector3 vBodyWhlVel = Propagate->GetPQR() * vWhlContactVec; vBodyWhlVel += Propagate->GetUVW() - Propagate->GetTec2b() * cvel; vWhlVelVec = mTGear.Transposed() * vBodyWhlVel; @@ -361,47 +336,22 @@ FGColumnVector3& FGLGear::GetBodyForces(void) vLocalWhlVel = Transform().Transposed() * vBodyWhlVel; - switch (eContactType) { - case ctBOGEY: - // Compression speed along the strut - compressSpeed = -vWhlVelVec(eZ); - case ctSTRUCTURE: - // Compression speed along the ground normal - compressSpeed = -vLocalWhlVel(eX); - } + compressSpeed = -vLocalWhlVel(eX); + if (eContactType == ctBOGEY) + compressSpeed /= LGearProj; ComputeVerticalStrutForce(); - // Compute the forces in the wheel ground plane. + // Compute the friction coefficients in the wheel ground plane. if (eContactType == ctBOGEY) { ComputeSlipAngle(); ComputeBrakeForceCoefficient(); ComputeSideForceCoefficient(); - double sign = vLocalWhlVel(eY)>0?1.0:(vLocalWhlVel(eY)<0?-1.0:0.0); - vFn(eY) = - ((1.0 - TirePressureNorm) * 30 + vFn(eX) * BrakeFCoeff) * sign; - vFn(eZ) = vFn(eX) * FCoeff; - } - else if (eContactType == ctSTRUCTURE) { - FGColumnVector3 vSlipVec = vLocalWhlVel; - vSlipVec(eX) = 0.; - vSlipVec.Normalize(); - vFn -= staticFCoeff * vFn(eX) * vSlipVec; } - // Lag and attenuate the XY-plane forces dependent on velocity. This code - // uses a lag filter, C/(s + C) where "C" is the filter coefficient. When - // "C" is chosen at the frame rate (in Hz), the jittering is significantly - // reduced. This is because the jitter is present *at* the execution rate. - // If a coefficient is set to something equal to or less than zero, the - // filter is bypassed. - - if (LongForceLagFilterCoeff > 0) vFn(eY) = LongForceFilter.execute(vFn(eY)); - if (LatForceLagFilterCoeff > 0) vFn(eZ) = LatForceFilter.execute(vFn(eZ)); - - if ((fabs(vLocalWhlVel(eY)) <= RFRV) && RFRV > 0) vFn(eY) *= fabs(vLocalWhlVel(eY))/RFRV; - if ((fabs(vLocalWhlVel(eZ)) <= SFRV) && SFRV > 0) vFn(eZ) *= fabs(vLocalWhlVel(eZ))/SFRV; - - // End section for attenuating gear jitter + // Prepare the Jacobians and the Lagrange multipliers for later friction + // forces calculations. + ComputeJacobian(vWhlContactVec); } else { // Gear is NOT compressed @@ -492,14 +442,13 @@ void FGLGear::ComputeRetractionState(void) } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// Calculate tire slip angle. void FGLGear::ComputeSlipAngle(void) { - // Calculate tire slip angle. - WheelSlip = -atan2(vLocalWhlVel(eZ), fabs(vLocalWhlVel(eY)))*radtodeg; - - // Filter the wheel slip angle - if (WheelSlipLagFilterCoeff > 0) WheelSlip = WheelSlipFilter.execute(WheelSlip); +// Check that the speed is non-null otherwise use the current angle + if (vLocalWhlVel.Magnitude(eY,eZ) > 1E-3) + WheelSlip = -atan2(vLocalWhlVel(eZ), fabs(vLocalWhlVel(eY)))*radtodeg; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -516,7 +465,13 @@ void FGLGear::ComputeSteeringAngle(void) SteerAngle = 0.0; break; case stCaster: - SteerAngle = atan2(vWhlVelVec(eY), fabs(vWhlVelVec(eX))); + if (!Castered) + SteerAngle = degtorad * FCS->GetSteerPosDeg(GearNumber); + else { + // Check that the speed is non-null otherwise use the current angle + if (vWhlVelVec.Magnitude(eX,eY) > 0.1) + SteerAngle = atan2(vWhlVelVec(eY), fabs(vWhlVelVec(eX))); + } break; default: cerr << "Improper steering type membership detected for this gear." << endl; @@ -571,20 +526,18 @@ void FGLGear::InitializeReporting(void) void FGLGear::ReportTakeoffOrLanding(void) { - double deltaT = State->Getdt()*fdmex->GetGroundReactions()->GetRate(); - if (FirstContact) - LandingDistanceTraveled += Auxiliary->GetVground()*deltaT; + LandingDistanceTraveled += Auxiliary->GetVground()*dT; if (StartedGroundRun) { - TakeoffDistanceTraveled50ft += Auxiliary->GetVground()*deltaT; - if (WOW) TakeoffDistanceTraveled += Auxiliary->GetVground()*deltaT; + TakeoffDistanceTraveled50ft += Auxiliary->GetVground()*dT; + if (WOW) TakeoffDistanceTraveled += Auxiliary->GetVground()*dT; } if ( ReportEnable && Auxiliary->GetVground() <= 0.05 && !LandingReported - && fdmex->GetGroundReactions()->GetWOW()) + && GroundReactions->GetWOW()) { if (debug_lvl > 0) Report(erLand); } @@ -592,7 +545,7 @@ void FGLGear::ReportTakeoffOrLanding(void) if ( ReportEnable && !TakeoffReported && (Propagate->GetDistanceAGL() - vLocalGear(eZ)) > 50.0 - && !fdmex->GetGroundReactions()->GetWOW()) + && !GroundReactions->GetWOW()) { if (debug_lvl > 0) Report(erTakeoff); } @@ -608,10 +561,10 @@ void FGLGear::CrashDetect(void) if ( (compressLength > 500.0 || vFn.Magnitude() > 100000000.0 || GetMoments().Magnitude() > 5000000000.0 || - SinkRate > 1.4666*30 ) && !State->IntegrationSuspended()) + SinkRate > 1.4666*30 ) && !fdmex->IntegrationSuspended()) { PutMessage("Crash Detected: Simulation FREEZE."); - State->SuspendIntegration(); + fdmex->SuspendIntegration(); } } @@ -733,6 +686,99 @@ double FGLGear::GetGearUnitPos(void) return GearPos; } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// Compute the jacobian entries for the friction forces resolution later +// in FGPropagate + +void FGLGear::ComputeJacobian(const FGColumnVector3& vWhlContactVec) +{ + // When the point of contact is moving, dynamic friction is used + // This type of friction is limited to ctSTRUCTURE elements because their + // friction coefficient is the same in every directions + if ((eContactType == ctSTRUCTURE) && (vLocalWhlVel.Magnitude(eY,eZ) > 1E-3)) { + FGColumnVector3 velocityDirection = vLocalWhlVel; + + StaticFriction = false; + + velocityDirection(eX) = 0.; + velocityDirection.Normalize(); + + LMultiplier[ftDynamic].ForceJacobian = Transform()*velocityDirection; + LMultiplier[ftDynamic].MomentJacobian = vWhlContactVec * LMultiplier[ftDynamic].ForceJacobian; + LMultiplier[ftDynamic].Max = 0.; + LMultiplier[ftDynamic].Min = -fabs(dynamicFCoeff * vFn(eX)); + LMultiplier[ftDynamic].value = Constrain(LMultiplier[ftDynamic].Min, LMultiplier[ftDynamic].value, LMultiplier[ftDynamic].Max); + } + else { + // Static friction is used for ctSTRUCTURE when the contact point is not moving. + // It is always used for ctBOGEY elements because the friction coefficients + // of a tyre depend on the direction of the movement (roll & side directions). + // This cannot be handled properly by the so-called "dynamic friction". + StaticFriction = true; + + LMultiplier[ftRoll].ForceJacobian = Transform()*FGColumnVector3(0.,1.,0.); + LMultiplier[ftSide].ForceJacobian = Transform()*FGColumnVector3(0.,0.,1.); + LMultiplier[ftRoll].MomentJacobian = vWhlContactVec * LMultiplier[ftRoll].ForceJacobian; + LMultiplier[ftSide].MomentJacobian = vWhlContactVec * LMultiplier[ftSide].ForceJacobian; + + switch(eContactType) { + case ctBOGEY: + LMultiplier[ftRoll].Max = fabs(BrakeFCoeff * vFn(eX)); + LMultiplier[ftSide].Max = fabs(FCoeff * vFn(eX)); + break; + case ctSTRUCTURE: + LMultiplier[ftRoll].Max = fabs(staticFCoeff * vFn(eX)); + LMultiplier[ftSide].Max = fabs(staticFCoeff * vFn(eX)); + break; + } + + LMultiplier[ftRoll].Min = -LMultiplier[ftRoll].Max; + LMultiplier[ftSide].Min = -LMultiplier[ftSide].Max; + LMultiplier[ftRoll].value = Constrain(LMultiplier[ftRoll].Min, LMultiplier[ftRoll].value, LMultiplier[ftRoll].Max); + LMultiplier[ftSide].value = Constrain(LMultiplier[ftSide].Min, LMultiplier[ftSide].value, LMultiplier[ftSide].Max); + } +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// This function is used by the MultiplierIterator class to enumerate the +// Lagrange multipliers of a landing gear. This allows to encapsulate the storage +// of the multipliers in FGLGear without exposing it. From an outside point of +// view, each FGLGear instance has a number of Lagrange multipliers which can be +// accessed through this routine without knowing the exact constraint which they +// model. + +FGPropagate::LagrangeMultiplier* FGLGear::GetMultiplierEntry(int entry) +{ + switch(entry) { + case 0: + if (StaticFriction) + return &LMultiplier[ftRoll]; + else + return &LMultiplier[ftDynamic]; + case 1: + if (StaticFriction) + return &LMultiplier[ftSide]; + default: + return NULL; + } +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// This routine is called after the Lagrange multiplier has been computed. The +// friction forces of the landing gear are then updated accordingly. +FGColumnVector3& FGLGear::UpdateForces(void) +{ + if (StaticFriction) { + vFn(eY) = LMultiplier[ftRoll].value; + vFn(eZ) = LMultiplier[ftSide].value; + } + else + vFn += LMultiplier[ftDynamic].value * (Transform ().Transposed() * LMultiplier[ftDynamic].ForceJacobian); + + // Return the updated force in the body frame + return FGForce::GetBodyForces(); +} + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGLGear::bind(void) @@ -760,8 +806,10 @@ void FGLGear::bind(void) fdmex->GetPropertyManager()->Tie( property_name.c_str(), &staticFCoeff ); if (eSteerType == stCaster) { - property_name = base_property_name + "/steering-angle-rad"; - fdmex->GetPropertyManager()->Tie( property_name.c_str(), &SteerAngle ); + property_name = base_property_name + "/steering-angle-deg"; + fdmex->GetPropertyManager()->Tie( property_name.c_str(), this, &FGLGear::GetSteerAngleDeg ); + property_name = base_property_name + "/castered"; + fdmex->GetPropertyManager()->Tie( property_name.c_str(), &Castered); } } @@ -780,7 +828,7 @@ void FGLGear::Report(ReportType repType) switch(repType) { case erLand: cout << endl << "Touchdown report for " << name << " (WOW at time: " - << fdmex->GetState()->Getsim_time() << " seconds)" << endl; + << fdmex->GetSimTime() << " seconds)" << endl; cout << " Sink rate at contact: " << SinkRate << " fps, " << SinkRate*0.3048 << " mps" << endl; cout << " Contact ground speed: " << GroundSpeed*.5925 << " knots, " @@ -795,16 +843,16 @@ void FGLGear::Report(ReportType repType) break; case erTakeoff: cout << endl << "Takeoff report for " << name << " (Liftoff at time: " - << fdmex->GetState()->Getsim_time() << " seconds)" << endl; + << fdmex->GetSimTime() << " seconds)" << endl; cout << " Distance traveled: " << TakeoffDistanceTraveled << " ft, " << TakeoffDistanceTraveled*0.3048 << " meters" << endl; cout << " Distance traveled (over 50'): " << TakeoffDistanceTraveled50ft << " ft, " << TakeoffDistanceTraveled50ft*0.3048 << " meters" << endl; - cout << " [Altitude (ASL): " << fdmex->GetPropagate()->GetAltitudeASL() << " ft. / " - << fdmex->GetPropagate()->GetAltitudeASLmeters() << " m | Temperature: " + cout << " [Altitude (ASL): " << Propagate->GetAltitudeASL() << " ft. / " + << Propagate->GetAltitudeASLmeters() << " m | Temperature: " << fdmex->GetAtmosphere()->GetTemperature() - 459.67 << " F / " << RankineToCelsius(fdmex->GetAtmosphere()->GetTemperature()) << " C]" << endl; - cout << " [Velocity (KCAS): " << fdmex->GetAuxiliary()->GetVcalibratedKTS() << "]" << endl; + cout << " [Velocity (KCAS): " << Auxiliary->GetVcalibratedKTS() << "]" << endl; TakeoffReported = true; break; case erNone: @@ -859,9 +907,6 @@ void FGLGear::Debug(int from) cout << " Grouping: " << sBrakeGroup << endl; cout << " Max Steer Angle: " << maxSteerAngle << endl; cout << " Retractable: " << isRetractable << endl; - cout << " Relaxation Velocities:" << endl; - cout << " Rolling: " << RFRV << endl; - cout << " Side: " << SFRV << endl; } } } diff --git a/src/FDM/JSBSim/models/FGLGear.h b/src/FDM/JSBSim/models/FGLGear.h index 9b86b6879..2190f8b9c 100644 --- a/src/FDM/JSBSim/models/FGLGear.h +++ b/src/FDM/JSBSim/models/FGLGear.h @@ -39,6 +39,7 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "models/propulsion/FGForce.h" +#include "models/FGPropagate.h" #include "math/FGColumnVector3.h" #include @@ -46,7 +47,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_LGEAR "$Id$" +#define ID_LGEAR "$Id: FGLGear.h,v 1.40 2010/07/30 11:50:01 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -84,7 +85,6 @@ CLASS DOCUMENTATION

Operational Properties

  1. Name
  2. -
  3. Steerability attribute {one of STEERABLE | FIXED | CASTERED}
  4. Brake Group Membership {one of LEFT | CENTER | RIGHT | NOSE | TAIL | NONE}
  5. Max Steer Angle, in degrees

@@ -178,19 +178,10 @@ CLASS DOCUMENTATION {0 | 1}
- - {number} - {number} - - - {number} - {number} - - {number} @endcode @author Jon S. Berndt - @version $Id$ + @version $Id: FGLGear.h,v 1.40 2010/07/30 11:50:01 jberndt Exp $ @see Richard E. McFarland, "A Standard Kinematic Model for Flight Simulation at NASA-Ames", NASA CR-2497, January 1975 @see Barnes W. McCormick, "Aerodynamics, Aeronautics, and Flight Mechanics", @@ -216,6 +207,8 @@ public: enum ReportType {erNone=0, erTakeoff, erLand}; /// Damping types enum DampType {dtLinear=0, dtSquare}; + /// Friction types + enum FrictionType {ftRoll=0, ftSide, ftDynamic}; /** Constructor @param el a pointer to the XML element that contains the CONTACT info. @param Executive a pointer to the parent executive object @@ -289,6 +282,10 @@ public: double GetWheelVel(int axis) const { return vWhlVelVec(axis);} bool IsBogey(void) const { return (eContactType == ctBOGEY);} double GetGearUnitPos(void); + double GetSteerAngleDeg(void) const { return radtodeg*SteerAngle; } + FGPropagate::LagrangeMultiplier* GetMultiplierEntry(int entry); + void SetLagrangeMultiplier(double lambda, int entry); + FGColumnVector3& UpdateForces(void); void bind(void); @@ -337,6 +334,8 @@ private: bool isRetractable; bool GearUp, GearDown; bool Servicable; + bool Castered; + bool StaticFriction; std::string name; std::string sSteerType; std::string sBrakeGroup; @@ -349,22 +348,14 @@ private: DampType eDampType; DampType eDampTypeRebound; double maxSteerAngle; - double RFRV; // Rolling force relaxation velocity - double SFRV; // Side force relaxation velocity - double LongForceLagFilterCoeff; // Longitudinal Force Lag Filter Coefficient - double LatForceLagFilterCoeff; // Lateral Force Lag Filter Coefficient - double WheelSlipLagFilterCoeff; // Wheel slip angle lag filter coefficient - - Filter LongForceFilter; - Filter LatForceFilter; - Filter WheelSlipFilter; - - FGState* State; - FGAircraft* Aircraft; - FGPropagate* Propagate; - FGAuxiliary* Auxiliary; - FGFCS* FCS; - FGMassBalance* MassBalance; + + FGPropagate::LagrangeMultiplier LMultiplier[3]; + + FGAuxiliary* Auxiliary; + FGPropagate* Propagate; + FGFCS* FCS; + FGMassBalance* MassBalance; + FGGroundReactions* GroundReactions; void ComputeRetractionState(void); void ComputeBrakeForceCoefficient(void); @@ -373,6 +364,7 @@ private: void ComputeSideForceCoefficient(void); void ComputeVerticalStrutForce(void); void ComputeGroundCoordSys(void); + void ComputeJacobian(const FGColumnVector3& vWhlContactVec); void CrashDetect(void); void InitializeReporting(void); void ResetReporting(void); diff --git a/src/FDM/JSBSim/models/FGMassBalance.cpp b/src/FDM/JSBSim/models/FGMassBalance.cpp index 7b6752a3e..9e485c1a6 100644 --- a/src/FDM/JSBSim/models/FGMassBalance.cpp +++ b/src/FDM/JSBSim/models/FGMassBalance.cpp @@ -40,16 +40,18 @@ INCLUDES #include "FGMassBalance.h" #include "FGPropulsion.h" +#include "propulsion/FGTank.h" #include "FGBuoyantForces.h" #include "input_output/FGPropertyManager.h" #include +#include #include using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGMassBalance.cpp,v 1.32 2010/08/12 04:07:11 jberndt Exp $"; static const char *IdHdr = ID_MASSBALANCE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -124,7 +126,9 @@ bool FGMassBalance::Load(Element* el) SetAircraftBaseInertias(FGMatrix33( bixx, -bixy, bixz, -bixy, biyy, -biyz, bixz, -biyz, bizz )); - EmptyWeight = el->FindElementValueAsNumberConvertTo("emptywt", "LBS"); + if (el->FindElement("emptywt")) { + EmptyWeight = el->FindElementValueAsNumberConvertTo("emptywt", "LBS"); + } element = el->FindElement("location"); while (element) { @@ -241,6 +245,7 @@ bool FGMassBalance::Run(void) void FGMassBalance::AddPointMass(Element* el) { + double radius=0, length=0; Element* loc_element = el->FindElement("location"); string pointmass_name = el->GetAttributeValue("name"); if (!loc_element) { @@ -251,8 +256,40 @@ void FGMassBalance::AddPointMass(Element* el) double w = el->FindElementValueAsNumberConvertTo("weight", "LBS"); FGColumnVector3 vXYZ = loc_element->FindElementTripletConvertTo("IN"); - PointMasses.push_back(new PointMass(w, vXYZ)); - PointMasses.back()->bind(PropertyManager, PointMasses.size()-1); + PointMass *pm = new PointMass(w, vXYZ); + pm->SetName(pointmass_name); + + Element* form_element = el->FindElement("form"); + if (form_element) { + string shape = form_element->GetAttributeValue("shape"); + Element* radius_element = form_element->FindElement("radius"); + Element* length_element = form_element->FindElement("length"); + if (radius_element) radius = form_element->FindElementValueAsNumberConvertTo("radius", "FT"); + if (length_element) length = form_element->FindElementValueAsNumberConvertTo("length", "FT"); + if (shape == "tube") { + pm->SetPointMassShapeType(PointMass::esTube); + pm->SetRadius(radius); + pm->SetLength(length); + pm->CalculateShapeInertia(); + } else if (shape == "cylinder") { + pm->SetPointMassShapeType(PointMass::esCylinder); + pm->SetRadius(radius); + pm->SetLength(length); + pm->CalculateShapeInertia(); + } else if (shape == "sphere") { + pm->SetPointMassShapeType(PointMass::esSphere); + pm->SetRadius(radius); + pm->CalculateShapeInertia(); + } else if (shape == "ball") { + pm->SetPointMassShapeType(PointMass::esBall); + pm->SetRadius(radius); + pm->CalculateShapeInertia(); + } else { + } + } + + pm->bind(PropertyManager, PointMasses.size()); + PointMasses.push_back(pm); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -290,8 +327,10 @@ FGMatrix33& FGMassBalance::CalculatePMInertias(void) pmJ = FGMatrix33(); - for (unsigned int i=0; iWeight, PointMasses[i]->Location ); + pmJ += PointMasses[i]->GetPointMassInertia(); + } return pmJ; } @@ -339,7 +378,7 @@ void FGMassBalance::bind(void) PropertyManager->Tie("inertia/weight-lbs", this, &FGMassBalance::GetWeight); PropertyManager->Tie("inertia/empty-weight-lbs", this, - &FGMassBalance::GetWeight, &FGMassBalance::SetEmptyWeight); + &FGMassBalance::GetEmptyWeight); PropertyManager->Tie("inertia/cg-x-in", this,1, (PMF)&FGMassBalance::GetXYZcg); PropertyManager->Tie("inertia/cg-y-in", this,2, @@ -349,7 +388,9 @@ void FGMassBalance::bind(void) } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - +// +// This function binds properties for each pointmass object created. +// void FGMassBalance::PointMass::bind(FGPropertyManager* PropertyManager, int num) { string tmp = CreateIndexedPropertyName("inertia/pointmass-weight-lbs", num); PropertyManager->Tie( tmp.c_str(), this, &PointMass::GetPointMassWeight, @@ -366,6 +407,63 @@ void FGMassBalance::PointMass::bind(FGPropertyManager* PropertyManager, int num) &PointMass::SetPointMassLocation); } +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGMassBalance::GetMassPropertiesReport(void) const +{ + cout << endl << fgblue << highint + << " Mass Properties Report (English units: lbf, in, slug-ft^2)" + << reset << endl; + cout << " " << underon << " Weight CG-X CG-Y" + << " CG-Z Ixx Iyy Izz" << underoff << endl; + cout.precision(1); + cout << highint << setw(34) << left << " Base Vehicle " << normint + << right << setw(10) << EmptyWeight << setw(8) << vbaseXYZcg(eX) << setw(8) + << vbaseXYZcg(eY) << setw(8) << vbaseXYZcg(eZ) << setw(12) << baseJ(1,1) + << setw(12) << baseJ(2,2) << setw(12) << baseJ(3,3) << endl; + + for (unsigned int i=0;iGetPointMassWeight(); + cout << highint << left << setw(4) << i << setw(30) << pm->GetName() << normint + << right << setw(10) << pmweight << setw(8) << pm->GetLocation()(eX) + << setw(8) << pm->GetLocation()(eY) << setw(8) << pm->GetLocation()(eZ) + << setw(12) << pm->GetPointMassMoI(1,1) << setw(12) << pm->GetPointMassMoI(2,2) + << setw(12) << pm->GetPointMassMoI(3,3) << endl; + } + + for (unsigned int i=0;iGetNumTanks() ;i++) { + FGTank* tank = Propulsion->GetTank(i); + string tankname=""; + if (tank->GetType() == FGTank::ttFUEL && tank->GetGrainType() != FGTank::gtUNKNOWN) { + tankname = "Solid Fuel"; + } else if (tank->GetType() == FGTank::ttFUEL) { + tankname = "Fuel"; + } else if (tank->GetType() == FGTank::ttOXIDIZER) { + tankname = "Oxidizer"; + } else { + tankname = "(Unknown tank type)"; + } + cout << highint << left << setw(4) << i << setw(30) << tankname << normint + << right << setw(10) << tank->GetContents() << setw(8) << tank->GetXYZ(eX) + << setw(8) << tank->GetXYZ(eY) << setw(8) << tank->GetXYZ(eZ) + << setw(12) << "*" << setw(12) << "*" + << setw(12) << "*" << endl; + } + + cout << underon << setw(104) << " " << underoff << endl; + cout << highint << left << setw(30) << " Total: " << right << setw(14) << Weight + << setw(8) << vXYZcg(eX) + << setw(8) << vXYZcg(eY) + << setw(8) << vXYZcg(eZ) + << setw(12) << mJ(1,1) + << setw(12) << mJ(2,2) + << setw(12) << mJ(3,3) + << normint << endl; + + cout.setf(ios_base::fixed); +} + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print @@ -398,7 +496,7 @@ void FGMassBalance::Debug(int from) cout << " baseIxy: " << baseJ(1,2) << " slug-ft2" << endl; cout << " baseIxz: " << baseJ(1,3) << " slug-ft2" << endl; cout << " baseIyz: " << baseJ(2,3) << " slug-ft2" << endl; - cout << " EmptyWeight: " << EmptyWeight << " lbm" << endl; + cout << " Empty Weight: " << EmptyWeight << " lbm" << endl; cout << " CG (x, y, z): " << vbaseXYZcg << endl; // ToDo: Need to add point mass outputs here for (unsigned int i=0; i +#include /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MASSBALANCE "$Id$" +#define ID_MASSBALANCE "$Id: FGMassBalance.h,v 1.21 2010/08/12 04:07:11 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONSS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ +using std::string; + namespace JSBSim { /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -62,7 +65,11 @@ CLASS DOCUMENTATION /** Models weight, balance and moment of inertia information. Maintains a vector of point masses. Sums the contribution of all, and provides this to FGPropagate. - Loads the \ section of the aircraft configuration file. + Loads the \ section of the aircraft configuration file. There + can be any number of . Each can also have a shape which - if + present - causes an associated moment of inertia to be calculated based on + the shape. Note that a cylinder is solid, a tube is hollow, a ball is solid + and a sphere is hollow.

Configuration File Format:

@code @@ -74,20 +81,24 @@ CLASS DOCUMENTATION {number} {number} {number} - + {number} {number} {number} - + [ +
+ {number} + {number} +
{number} - + {number} {number} {number}
- ... other point masses ... + ... other point masses ...]
@endcode */ @@ -109,9 +120,10 @@ public: double GetMass(void) const {return Mass;} double GetWeight(void) const {return Weight;} - FGColumnVector3& GetXYZcg(void) {return vXYZcg;} + double GetEmptyWeight(void) const {return EmptyWeight;} + const FGColumnVector3& GetXYZcg(void) const {return vXYZcg;} double GetXYZcg(int axis) const {return vXYZcg(axis);} - FGColumnVector3& GetDeltaXYZcg(void) {return vDeltaXYZcg;} + const FGColumnVector3& GetDeltaXYZcg(void) const {return vDeltaXYZcg;} double GetDeltaXYZcg(int axis) const {return vDeltaXYZcg(axis);} /** Computes the inertia contribution of a pointmass. @@ -158,6 +170,7 @@ public: FGMatrix33& GetJ(void) {return mJ;} FGMatrix33& GetJinv(void) {return mJinv;} void SetAircraftBaseInertias(FGMatrix33 BaseJ) {baseJ = BaseJ;} + void GetMassPropertiesReport(void) const; private: double Weight; @@ -177,17 +190,66 @@ private: FGColumnVector3 PointMassCG; FGMatrix33& CalculatePMInertias(void); + + /** The PointMass structure encapsulates a point mass object, moments of inertia + mass, location, etc. */ struct PointMass { PointMass(double w, FGColumnVector3& vXYZ) { Weight = w; Location = vXYZ; + mPMInertia.InitMatrix(); + Radius = 0.0; + Length = 0.0; } + + void CalculateShapeInertia(void) { + switch(eShapeType) { + case esTube: + mPMInertia(1,1) = (Weight/(slugtolb))*Radius*Radius; // mr^2 + mPMInertia(2,2) = (Weight/(slugtolb*12))*(6*Radius*Radius + Length*Length); + mPMInertia(3,3) = mPMInertia(2,2); + break; + case esCylinder: + mPMInertia(1,1) = (Weight/(slugtolb*2))*Radius*Radius; // 0.5*mr^2 + mPMInertia(2,2) = (Weight/(slugtolb*12))*(3*Radius*Radius + Length*Length); + mPMInertia(3,3) = mPMInertia(2,2); + break; + case esSphere: + mPMInertia(1,1) = (Weight/(slugtolb*3))*Radius*Radius*2; // (2mr^2)/3 + mPMInertia(2,2) = mPMInertia(1,1); + mPMInertia(3,3) = mPMInertia(1,1); + case esBall: + mPMInertia(1,1) = (Weight/(slugtolb*5))*Radius*Radius*2; // (2mr^2)/5 + mPMInertia(2,2) = mPMInertia(1,1); + mPMInertia(3,3) = mPMInertia(1,1); + break; + default: + break; + } + } + + enum esShape {esUnspecified, esTube, esCylinder, esSphere, esBall} eShapeType; FGColumnVector3 Location; - double Weight; + double Weight; /// Weight in pounds. + double Radius; /// Radius in feet. + double Length; /// Length in feet. + string Name; + FGMatrix33 mPMInertia; + double GetPointMassLocation(int axis) const {return Location(axis);} + double GetPointMassWeight(void) const {return Weight;} + esShape GetShapeType(void) {return eShapeType;} + FGColumnVector3 GetLocation(void) {return Location;} + FGMatrix33 GetPointMassInertia(void) {return mPMInertia;} + string GetName(void) {return Name;} + void SetPointMassLocation(int axis, double value) {Location(axis) = value;} void SetPointMassWeight(double wt) {Weight = wt;} - double GetPointMassWeight(void) const {return Weight;} + void SetPointMassShapeType(esShape st) {eShapeType = st;} + void SetRadius(double r) {Radius = r;} + void SetLength(double l) {Length = l;} + void SetName(string name) {Name = name;} + double GetPointMassMoI(int r, int c) {return mPMInertia(r,c);} void bind(FGPropertyManager* PropertyManager, int num); }; diff --git a/src/FDM/JSBSim/models/FGModel.cpp b/src/FDM/JSBSim/models/FGModel.cpp index 2e2b8357e..cd9a7eabb 100644 --- a/src/FDM/JSBSim/models/FGModel.cpp +++ b/src/FDM/JSBSim/models/FGModel.cpp @@ -39,7 +39,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGModel.h" -#include "FGState.h" #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGFCS.h" @@ -58,7 +57,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGModel.cpp,v 1.14 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_MODEL; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -74,7 +73,6 @@ FGModel::FGModel(FGFDMExec* fdmex) FDMExec = fdmex; NextModel = 0L; - State = 0; Atmosphere = 0; FCS = 0; Propulsion = 0; @@ -115,7 +113,6 @@ FGModel::~FGModel() bool FGModel::InitModel(void) { - State = FDMExec->GetState(); Atmosphere = FDMExec->GetAtmosphere(); FCS = FDMExec->GetFCS(); Propulsion = FDMExec->GetPropulsion(); @@ -129,8 +126,7 @@ bool FGModel::InitModel(void) Propagate = FDMExec->GetPropagate(); Auxiliary = FDMExec->GetAuxiliary(); - if (!State || - !Atmosphere || + if (!Atmosphere || !FCS || !Propulsion || !MassBalance || diff --git a/src/FDM/JSBSim/models/FGModel.h b/src/FDM/JSBSim/models/FGModel.h index 5907328f9..5f3ac9489 100644 --- a/src/FDM/JSBSim/models/FGModel.h +++ b/src/FDM/JSBSim/models/FGModel.h @@ -48,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MODEL "$Id$" +#define ID_MODEL "$Id: FGModel.h,v 1.14 2009/11/12 13:08:11 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/FGOutput.cpp b/src/FDM/JSBSim/models/FGOutput.cpp index e358ce028..a974915f4 100644 --- a/src/FDM/JSBSim/models/FGOutput.cpp +++ b/src/FDM/JSBSim/models/FGOutput.cpp @@ -40,7 +40,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGOutput.h" -#include "FGState.h" #include "FGFDMExec.h" #include "FGAtmosphere.h" #include "FGFCS.h" @@ -53,6 +52,7 @@ INCLUDES #include "FGPropagate.h" #include "FGAuxiliary.h" #include "FGInertial.h" +#include "FGPropulsion.h" #include "models/propulsion/FGEngine.h" #include "models/propulsion/FGTank.h" #include "models/propulsion/FGPiston.h" @@ -77,7 +77,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGOutput.cpp,v 1.48 2010/04/12 12:25:19 jberndt Exp $"; static const char *IdHdr = ID_OUTPUT; // (stolen from FGFS native_fdm.cxx) @@ -187,7 +187,7 @@ bool FGOutput::Run(void) { if (FGModel::Run()) return true; - if (enabled && !State->IntegrationSuspended()&& !FDMExec->Holding()) { + if (enabled && !FDMExec->IntegrationSuspended()&& !FDMExec->Holding()) { RunPreFunctions(); if (Type == otSocket) { SocketOutput(); @@ -267,7 +267,8 @@ void FGOutput::DelimitedOutput(const string& fname) if (SubSystems & ssRates) { outstream << delimeter; outstream << "P (deg/s)" + delimeter + "Q (deg/s)" + delimeter + "R (deg/s)" + delimeter; - outstream << "P dot (deg/s^2)" + delimeter + "Q dot (deg/s^2)" + delimeter + "R dot (deg/s^2)"; + outstream << "P dot (deg/s^2)" + delimeter + "Q dot (deg/s^2)" + delimeter + "R dot (deg/s^2)" + delimeter; + outstream << "P_{inertial} (deg/s)" + delimeter + "Q_{inertial} (deg/s)" + delimeter + "R_{inertial} (deg/s)"; } if (SubSystems & ssVelocities) { outstream << delimeter; @@ -277,6 +278,7 @@ void FGOutput::DelimitedOutput(const string& fname) outstream << "V_{Inertial} (ft/s)" + delimeter; outstream << "UBody" + delimeter + "VBody" + delimeter + "WBody" + delimeter; outstream << "Aero V_{X Body} (ft/s)" + delimeter + "Aero V_{Y Body} (ft/s)" + delimeter + "Aero V_{Z Body} (ft/s)" + delimeter; + outstream << "V_{X_{inertial}} (ft/s)" + delimeter + "V_{Y_{inertial}} (ft/s)" + delimeter + "V_{Z_{inertial}} (ft/s)" + delimeter; outstream << "V_{North} (ft/s)" + delimeter + "V_{East} (ft/s)" + delimeter + "V_{Down} (ft/s)"; } if (SubSystems & ssForces) { @@ -334,8 +336,9 @@ void FGOutput::DelimitedOutput(const string& fname) outstream << "Beta (deg)" + delimeter; outstream << "Latitude (deg)" + delimeter; outstream << "Longitude (deg)" + delimeter; - outstream << "ECEF X (ft)" + delimeter + "ECEF Y (ft)" + delimeter + "ECEF Z (ft)" + delimeter; - outstream << "EPA (deg)" + delimeter; + outstream << "X_{ECI} (ft)" + delimeter + "Y_{ECI} (ft)" + delimeter + "Z_{ECI} (ft)" + delimeter; + outstream << "X_{ECEF} (ft)" + delimeter + "Y_{ECEF} (ft)" + delimeter + "Z_{ECEF} (ft)" + delimeter; + outstream << "Earth Position Angle (deg)" + delimeter; outstream << "Distance AGL (ft)" + delimeter; outstream << "Terrain Elevation (ft)"; } @@ -365,7 +368,7 @@ void FGOutput::DelimitedOutput(const string& fname) dFirstPass = false; } - outstream << State->Getsim_time(); + outstream << FDMExec->GetSimTime(); if (SubSystems & ssSimulation) { } if (SubSystems & ssAerosurfaces) { @@ -383,7 +386,8 @@ void FGOutput::DelimitedOutput(const string& fname) if (SubSystems & ssRates) { outstream << delimeter; outstream << (radtodeg*Propagate->GetPQR()).Dump(delimeter) << delimeter; - outstream << (radtodeg*Propagate->GetPQRdot()).Dump(delimeter); + outstream << (radtodeg*Propagate->GetPQRdot()).Dump(delimeter) << delimeter; + outstream << (radtodeg*Propagate->GetPQRi()).Dump(delimeter); } if (SubSystems & ssVelocities) { outstream << delimeter; @@ -393,6 +397,7 @@ void FGOutput::DelimitedOutput(const string& fname) outstream << Propagate->GetInertialVelocityMagnitude() << delimeter; outstream << setprecision(12) << Propagate->GetUVW().Dump(delimeter) << delimeter; outstream << Auxiliary->GetAeroUVW().Dump(delimeter) << delimeter; + outstream << Propagate->GetInertialVelocity().Dump(delimeter) << delimeter; outstream << Propagate->GetVel().Dump(delimeter); outstream.precision(10); } @@ -445,6 +450,7 @@ void FGOutput::DelimitedOutput(const string& fname) outstream << Propagate->GetLocation().GetLatitudeDeg() << delimeter; outstream << Propagate->GetLocation().GetLongitudeDeg() << delimeter; outstream.precision(18); + outstream << ((FGColumnVector3)Propagate->GetInertialPosition()).Dump(delimeter) << delimeter; outstream << ((FGColumnVector3)Propagate->GetLocation()).Dump(delimeter) << delimeter; outstream.precision(14); outstream << Inertial->GetEarthPositionAngleDeg() << delimeter; @@ -817,7 +823,7 @@ void FGOutput::SocketOutput(void) } socket->Clear(); - socket->Append(State->Getsim_time()); + socket->Append(FDMExec->GetSimTime()); if (SubSystems & ssAerosurfaces) { socket->Append(FCS->GetDaCmd()); @@ -952,13 +958,15 @@ bool FGOutput::Load(Element* element) output_file_name = DirectivesFile; // one found in the config file. document = LoadXMLDocument(output_file_name); } else if (!element->GetAttributeValue("file").empty()) { - output_file_name = element->GetAttributeValue("file"); + output_file_name = FDMExec->GetRootDir() + element->GetAttributeValue("file"); document = LoadXMLDocument(output_file_name); } else { document = element; } - name = document->GetAttributeValue("name"); + if (!document) return false; + + name = FDMExec->GetRootDir() + document->GetAttributeValue("name"); type = document->GetAttributeValue("type"); SetType(type); if (!document->GetAttributeValue("port").empty() && type == string("SOCKET")) { @@ -1035,7 +1043,7 @@ void FGOutput::SetRate(int rtHz) { rtHz = rtHz>1000?1000:(rtHz<0?0:rtHz); if (rtHz > 0) { - rate = (int)(0.5 + 1.0/(State->Getdt()*rtHz)); + rate = (int)(0.5 + 1.0/(FDMExec->GetDeltaT()*rtHz)); Enable(); } else { rate = 1; @@ -1085,7 +1093,7 @@ void FGOutput::Debug(int from) } switch (Type) { case otCSV: - cout << scratch << " in CSV format output at rate " << 1/(State->Getdt()*rate) << " Hz" << endl; + cout << scratch << " in CSV format output at rate " << 1/(FDMExec->GetDeltaT()*rate) << " Hz" << endl; break; case otNone: default: diff --git a/src/FDM/JSBSim/models/FGOutput.h b/src/FDM/JSBSim/models/FGOutput.h index cd1ca6e30..f1cfef7d0 100644 --- a/src/FDM/JSBSim/models/FGOutput.h +++ b/src/FDM/JSBSim/models/FGOutput.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_OUTPUT "$Id$" +#define ID_OUTPUT "$Id: FGOutput.h,v 1.17 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -123,7 +123,7 @@ CLASS DOCUMENTATION propulsion ON|OFF NOTE that Time is always output with the data. - @version $Id$ + @version $Id: FGOutput.h,v 1.17 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/FGPropagate.cpp b/src/FDM/JSBSim/models/FGPropagate.cpp index 9bd502898..ebb83211b 100644 --- a/src/FDM/JSBSim/models/FGPropagate.cpp +++ b/src/FDM/JSBSim/models/FGPropagate.cpp @@ -48,6 +48,7 @@ COMMENTS, REFERENCES, and NOTES Wiley & Sons, 1979 ISBN 0-471-03032-5 [5] Bernard Etkin, "Dynamics of Flight, Stability and Control", Wiley & Sons, 1982 ISBN 0-471-08936-2 +[6] Erin Catto, "Iterative Dynamics with Temporal Coherence", February 22, 2005 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES @@ -56,10 +57,11 @@ INCLUDES #include #include #include +#include #include "FGPropagate.h" +#include "FGGroundReactions.h" #include "FGFDMExec.h" -#include "FGState.h" #include "FGAircraft.h" #include "FGMassBalance.h" #include "FGInertial.h" @@ -69,7 +71,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPropagate.cpp,v 1.60 2010/08/12 19:11:22 andgi Exp $"; static const char *IdHdr = ID_PROPAGATE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -80,30 +82,23 @@ FGPropagate::FGPropagate(FGFDMExec* fdmex) : FGModel(fdmex) { Debug(0); Name = "FGPropagate"; - - last2_vPQRdot.InitMatrix(); - last_vPQRdot.InitMatrix(); + gravType = gtWGS84; + vPQRdot.InitMatrix(); - - last2_vQtrndot = FGQuaternion(0,0,0); - last_vQtrndot = FGQuaternion(0,0,0); vQtrndot = FGQuaternion(0,0,0); - - last2_vUVWdot.InitMatrix(); - last_vUVWdot.InitMatrix(); vUVWdot.InitMatrix(); - - last2_vLocationDot.InitMatrix(); - last_vLocationDot.InitMatrix(); - vLocationDot.InitMatrix(); - - vOmegaLocal.InitMatrix(); + vInertialVelocity.InitMatrix(); integrator_rotational_rate = eAdamsBashforth2; integrator_translational_rate = eTrapezoidal; integrator_rotational_position = eAdamsBashforth2; integrator_translational_position = eTrapezoidal; + VState.dqPQRdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqUVWdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqInertialVelocity.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqQtrndot.resize(4, FGQuaternion(0.0,0.0,0.0)); + bind(); Debug(0); } @@ -126,25 +121,17 @@ bool FGPropagate::InitModel(void) VState.vLocation.SetRadius( LocalTerrainRadius + 4.0 ); VState.vLocation.SetEllipse(Inertial->GetSemimajor(), Inertial->GetSemiminor()); - vOmega = FGColumnVector3( 0.0, 0.0, Inertial->omega() ); // Earth rotation vector + vOmegaEarth = FGColumnVector3( 0.0, 0.0, Inertial->omega() ); // Earth rotation vector - last2_vPQRdot.InitMatrix(); - last_vPQRdot.InitMatrix(); vPQRdot.InitMatrix(); - - last2_vQtrndot = FGQuaternion(0,0,0); - last_vQtrndot = FGQuaternion(0,0,0); vQtrndot = FGQuaternion(0,0,0); - - last2_vUVWdot.InitMatrix(); - last_vUVWdot.InitMatrix(); vUVWdot.InitMatrix(); - - last2_vLocationDot.InitMatrix(); - last_vLocationDot.InitMatrix(); - vLocationDot.InitMatrix(); + vInertialVelocity.InitMatrix(); - vOmegaLocal.InitMatrix(); + VState.dqPQRdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqUVWdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqInertialVelocity.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqQtrndot.resize(4, FGColumnVector3(0.0,0.0,0.0)); integrator_rotational_rate = eAdamsBashforth2; integrator_translational_rate = eTrapezoidal; @@ -161,51 +148,93 @@ void FGPropagate::SetInitialState(const FGInitialCondition *FGIC) SetSeaLevelRadius(FGIC->GetSeaLevelRadiusFtIC()); SetTerrainElevation(FGIC->GetTerrainElevationFtIC()); + VehicleRadius = GetRadius(); + radInv = 1.0/VehicleRadius; + + // Initialize the State Vector elements and the transformation matrices + // Set the position lat/lon/radius VState.vLocation.SetPosition( FGIC->GetLongitudeRadIC(), - FGIC->GetLatitudeRadIC(), - FGIC->GetAltitudeASLFtIC() + FGIC->GetSeaLevelRadiusFtIC() ); + FGIC->GetLatitudeRadIC(), + FGIC->GetAltitudeASLFtIC() + FGIC->GetSeaLevelRadiusFtIC() ); - VehicleRadius = GetRadius(); - radInv = 1.0/VehicleRadius; + VState.vLocation.SetEarthPositionAngle(Inertial->GetEarthPositionAngle()); + + Ti2ec = GetTi2ec(); // ECI to ECEF transform + Tec2i = Ti2ec.Transposed(); // ECEF to ECI frame transform + + Tl2ec = GetTl2ec(); // local to ECEF transform + Tec2l = Tl2ec.Transposed(); // ECEF to local frame transform - // Set the Orientation from the euler angles - VState.vQtrn = FGQuaternion( FGIC->GetPhiRadIC(), - FGIC->GetThetaRadIC(), - FGIC->GetPsiRadIC() ); + Ti2l = GetTi2l(); + Tl2i = Ti2l.Transposed(); + + // Set the orientation from the euler angles (is normalized within the + // constructor). The Euler angles represent the orientation of the body + // frame relative to the local frame. + VState.qAttitudeLocal = FGQuaternion( FGIC->GetPhiRadIC(), + FGIC->GetThetaRadIC(), + FGIC->GetPsiRadIC() ); + + VState.qAttitudeECI = Ti2l.GetQuaternion()*VState.qAttitudeLocal; + + Ti2b = GetTi2b(); // ECI to body frame transform + Tb2i = Ti2b.Transposed(); // body to ECI frame transform + + Tl2b = VState.qAttitudeLocal; // local to body frame transform + Tb2l = Tl2b.Transposed(); // body to local frame transform + + Tec2b = Tl2b * Tec2l; // ECEF to body frame transform + Tb2ec = Tec2b.Transposed(); // body to ECEF frame tranform // Set the velocities in the instantaneus body frame VState.vUVW = FGColumnVector3( FGIC->GetUBodyFpsIC(), - FGIC->GetVBodyFpsIC(), - FGIC->GetWBodyFpsIC() ); + FGIC->GetVBodyFpsIC(), + FGIC->GetWBodyFpsIC() ); - // Set the angular velocities in the instantaneus body frame. - VState.vPQR = FGColumnVector3( FGIC->GetPRadpsIC(), - FGIC->GetQRadpsIC(), - FGIC->GetRRadpsIC() ); + VState.vInertialPosition = Tec2i * VState.vLocation; // Compute the local frame ECEF velocity - vVel = GetTb2l()*VState.vUVW; + vVel = Tb2l * VState.vUVW; - // Finally, make sure that the quaternion stays normalized. - VState.vQtrn.Normalize(); + // Refer to Stevens and Lewis, 1.5-14a, pg. 49. + // This is the rotation rate of the "Local" frame, expressed in the local frame. - // Recompute the LocalTerrainRadius. - RecomputeLocalTerrainRadius(); + FGColumnVector3 vOmegaLocal = FGColumnVector3( + radInv*vVel(eEast), + -radInv*vVel(eNorth), + -radInv*vVel(eEast)*VState.vLocation.GetTanLatitude() ); - // These local copies of the transformation matrices are for use for - // initial conditions only. + // Set the angular velocities of the body frame relative to the ECEF frame, + // expressed in the body frame. Effectively, this is: + // w_b/e = w_b/l + w_l/e + VState.vPQR = FGColumnVector3( FGIC->GetPRadpsIC(), + FGIC->GetQRadpsIC(), + FGIC->GetRRadpsIC() ) + Tl2b*vOmegaLocal; + + VState.vPQRi = VState.vPQR + Ti2b * vOmegaEarth; + + // Make an initial run and set past values + CalculatePQRdot(); // Angular rate derivative + CalculateUVWdot(); // Translational rate derivative + ResolveFrictionForces(0.); // Update rate derivatives with friction forces + CalculateQuatdot(); // Angular orientation derivative + CalculateInertialVelocity(); // Translational position derivative + + // Initialize past values deques + VState.dqPQRdot.clear(); + VState.dqUVWdot.clear(); + VState.dqInertialVelocity.clear(); + VState.dqQtrndot.clear(); + for (int i=0; i<4; i++) { + VState.dqPQRdot.push_front(vPQRdot); + VState.dqUVWdot.push_front(vUVWdot); + VState.dqInertialVelocity.push_front(VState.vInertialVelocity); + VState.dqQtrndot.push_front(vQtrndot); + } - Tl2b = GetTl2b(); // local to body frame transform - Tb2l = Tl2b.Transposed(); // body to local frame transform - Tl2ec = GetTl2ec(); // local to ECEF transform - Tec2l = Tl2ec.Transposed(); // ECEF to local frame transform - Tec2b = Tl2b * Tec2l; // ECEF to body frame transform - Tb2ec = Tec2b.Transposed(); // body to ECEF frame tranform - Ti2ec = GetTi2ec(); // ECI to ECEF transform - Tec2i = Ti2ec.Transposed(); // ECEF to ECI frame transform - Ti2b = Tec2b*Ti2ec; // ECI to body frame transform - Tb2i = Ti2b.Transposed(); // body to ECI frame transform + // Recompute the LocalTerrainRadius. + RecomputeLocalTerrainRadius(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -233,120 +262,60 @@ bool FGPropagate::Run(void) if (FGModel::Run()) return true; // Fast return if we have nothing to do ... if (FDMExec->Holding()) return false; + double dt = FDMExec->GetDeltaT()*rate; // The 'stepsize' + RunPreFunctions(); + // Calculate state derivatives + CalculatePQRdot(); // Angular rate derivative + CalculateUVWdot(); // Translational rate derivative + ResolveFrictionForces(dt); // Update rate derivatives with friction forces + CalculateQuatdot(); // Angular orientation derivative + CalculateInertialVelocity(); // Translational position derivative + + // Propagate rotational / translational velocity, angular /translational position, respectively. + Integrate(VState.vPQRi, vPQRdot, VState.dqPQRdot, dt, integrator_rotational_rate); + Integrate(VState.vUVW, vUVWdot, VState.dqUVWdot, dt, integrator_translational_rate); + Integrate(VState.qAttitudeECI, vQtrndot, VState.dqQtrndot, dt, integrator_rotational_position); + Integrate(VState.vInertialPosition, VState.vInertialVelocity, VState.dqInertialVelocity, dt, integrator_translational_position); + + VState.qAttitudeECI.Normalize(); // Normalize the ECI Attitude quaternion + + VState.vLocation.SetEarthPositionAngle(Inertial->GetEarthPositionAngle()); // Update the Earth position angle (EPA) + + // Update the "Location-based" transformation matrices from the vLocation vector. + + Ti2ec = GetTi2ec(); // ECI to ECEF transform + Tec2i = Ti2ec.Transposed(); // ECEF to ECI frame transform + Tl2ec = GetTl2ec(); // local to ECEF transform + Tec2l = Tl2ec.Transposed(); // ECEF to local frame transform + Ti2l = GetTi2l(); + Tl2i = Ti2l.Transposed(); + + // Update the "Orientation-based" transformation matrices from the orientation quaternion + + Ti2b = GetTi2b(); // ECI to body frame transform + Tb2i = Ti2b.Transposed(); // body to ECI frame transform + Tl2b = Ti2b*Tl2i; // local to body frame transform + Tb2l = Tl2b.Transposed(); // body to local frame transform + Tec2b = Tl2b * Tec2l; // ECEF to body frame transform + Tb2ec = Tec2b.Transposed(); // body to ECEF frame tranform + + // Set auxililary state variables + VState.vLocation = Ti2ec*VState.vInertialPosition; RecomputeLocalTerrainRadius(); - // Calculate current aircraft radius from center of planet - - VehicleRadius = GetRadius(); + VehicleRadius = GetRadius(); // Calculate current aircraft radius from center of planet radInv = 1.0/VehicleRadius; - // These local copies of the transformation matrices are for use this - // pass through Run() only. + VState.vPQR = VState.vPQRi - Ti2b * vOmegaEarth; - Tl2b = GetTl2b(); // local to body frame transform - Tb2l = Tl2b.Transposed(); // body to local frame transform - Tl2ec = GetTl2ec(); // local to ECEF transform - Tec2l = Tl2ec.Transposed(); // ECEF to local frame transform - Tec2b = Tl2b * Tec2l; // ECEF to body frame transform - Tb2ec = Tec2b.Transposed(); // body to ECEF frame tranform - Ti2ec = GetTi2ec(); // ECI to ECEF transform - Tec2i = Ti2ec.Transposed(); // ECEF to ECI frame transform - Ti2b = Tec2b*Ti2ec; // ECI to body frame transform - Tb2i = Ti2b.Transposed(); // body to ECI frame transform + VState.qAttitudeLocal = Tl2b.GetQuaternion(); // Compute vehicle velocity wrt ECEF frame, expressed in Local horizontal frame. vVel = Tb2l * VState.vUVW; - // Inertial angular velocity measured in the body frame. - vPQRi = VState.vPQR + Tec2b*vOmega; - - // Calculate state derivatives - CalculatePQRdot(); // Angular rate derivative - CalculateUVWdot(); // Translational rate derivative - CalculateQuatdot(); // Angular orientation derivative - CalculateLocationdot(); // Translational position derivative - - // Integrate to propagate the state - - double dt = State->Getdt()*rate; // The 'stepsize' - - // Propagate rotational velocity - - switch(integrator_rotational_rate) { - case eRectEuler: VState.vPQR += dt*vPQRdot; - break; - case eTrapezoidal: VState.vPQR += 0.5*dt*(vPQRdot + last_vPQRdot); - break; - case eAdamsBashforth2: VState.vPQR += dt*(1.5*vPQRdot - 0.5*last_vPQRdot); - break; - case eAdamsBashforth3: VState.vPQR += (1/12.0)*dt*(23.0*vPQRdot - 16.0*last_vPQRdot + 5.0*last2_vPQRdot); - break; - case eNone: // do nothing, freeze angular rate - break; - } - - // Propagate translational velocity - - switch(integrator_translational_rate) { - case eRectEuler: VState.vUVW += dt*vUVWdot; - break; - case eTrapezoidal: VState.vUVW += 0.5*dt*(vUVWdot + last_vUVWdot); - break; - case eAdamsBashforth2: VState.vUVW += dt*(1.5*vUVWdot - 0.5*last_vUVWdot); - break; - case eAdamsBashforth3: VState.vUVW += (1/12.0)*dt*(23.0*vUVWdot - 16.0*last_vUVWdot + 5.0*last2_vUVWdot); - break; - case eNone: // do nothing, freeze translational rate - break; - } - - // Propagate angular position - - switch(integrator_rotational_position) { - case eRectEuler: VState.vQtrn += dt*vQtrndot; - break; - case eTrapezoidal: VState.vQtrn += 0.5*dt*(vQtrndot + last_vQtrndot); - break; - case eAdamsBashforth2: VState.vQtrn += dt*(1.5*vQtrndot - 0.5*last_vQtrndot); - break; - case eAdamsBashforth3: VState.vQtrn += (1/12.0)*dt*(23.0*vQtrndot - 16.0*last_vQtrndot + 5.0*last2_vQtrndot); - break; - case eNone: // do nothing, freeze angular position - break; - } - - // Propagate translational position - - switch(integrator_translational_position) { - case eRectEuler: VState.vLocation += dt*vLocationDot; - break; - case eTrapezoidal: VState.vLocation += 0.5*dt*(vLocationDot + last_vLocationDot); - break; - case eAdamsBashforth2: VState.vLocation += dt*(1.5*vLocationDot - 0.5*last_vLocationDot); - break; - case eAdamsBashforth3: VState.vLocation += (1/12.0)*dt*(23.0*vLocationDot - 16.0*last_vLocationDot + 5.0*last2_vLocationDot); - break; - case eNone: // do nothing, freeze translational position - break; - } - - // Set past values - - last2_vPQRdot = last_vPQRdot; - last_vPQRdot = vPQRdot; - - last2_vUVWdot = last_vUVWdot; - last_vUVWdot = vUVWdot; - - last2_vQtrndot = last_vQtrndot; - last_vQtrndot = vQtrndot; - - last2_vLocationDot = last_vLocationDot; - last_vLocationDot = vLocationDot; - - RunPreFunctions(); + RunPostFunctions(); Debug(2); return false; @@ -361,7 +330,7 @@ bool FGPropagate::Run(void) // J is the inertia matrix // Jinv is the inverse inertia matrix // vMoments is the moment vector in the body frame -// vPQRi is the total inertial angular velocity of the vehicle +// VState.vPQRi is the total inertial angular velocity of the vehicle // expressed in the body frame. // Reference: See Stevens and Lewis, "Aircraft Control and Simulation", // Second edition (2004), eqn 1.5-16e (page 50) @@ -376,7 +345,7 @@ void FGPropagate::CalculatePQRdot(void) // moments and the total inertial angular velocity expressed in the body // frame. - vPQRdot = Jinv*(vMoments - vPQRi*(J*vPQRi)); + vPQRdot = Jinv*(vMoments - VState.vPQRi*(J*VState.vPQRi)); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -388,72 +357,255 @@ void FGPropagate::CalculatePQRdot(void) void FGPropagate::CalculateQuatdot(void) { - vOmegaLocal.InitMatrix( radInv*vVel(eEast), - -radInv*vVel(eNorth), - -radInv*vVel(eEast)*VState.vLocation.GetTanLatitude() ); - // Compute quaternion orientation derivative on current body rates - vQtrndot = VState.vQtrn.GetQDot( VState.vPQR - Tl2b*vOmegaLocal); + vQtrndot = VState.qAttitudeECI.GetQDot( VState.vPQRi); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // This set of calculations results in the body frame accelerations being // computed. +// Compute body frame accelerations based on the current body forces. +// Include centripetal and coriolis accelerations. +// vOmegaEarth is the Earth angular rate - expressed in the inertial frame - +// so it has to be transformed to the body frame. More completely, +// vOmegaEarth is the rate of the ECEF frame relative to the Inertial +// frame (ECI), expressed in the Inertial frame. +// vForces is the total force on the vehicle in the body frame. +// VState.vPQR is the vehicle body rate relative to the ECEF frame, expressed +// in the body frame. +// VState.vUVW is the vehicle velocity relative to the ECEF frame, expressed +// in the body frame. // Reference: See Stevens and Lewis, "Aircraft Control and Simulation", -// Second edition (2004), eqn 1.5-16d (page 50) +// Second edition (2004), eqns 1.5-13 (pg 48) and 1.5-16d (page 50) void FGPropagate::CalculateUVWdot(void) { double mass = MassBalance->GetMass(); // mass const FGColumnVector3& vForces = Aircraft->GetForces(); // current forces - const FGColumnVector3 vGravAccel( 0.0, 0.0, Inertial->GetGAccel(VehicleRadius) ); - - // Begin to compute body frame accelerations based on the current body forces - vUVWdot = vForces/mass - VState.vPQR * VState.vUVW; + vUVWdot = vForces/mass - (VState.vPQR + 2.0*(Ti2b *vOmegaEarth)) * VState.vUVW; - // Include Coriolis acceleration. - vUVWdot -= 2.0 * (Ti2b *vOmega) * VState.vUVW; + // Include Centripetal acceleration. + vUVWdot -= Ti2b * (vOmegaEarth*(vOmegaEarth*VState.vInertialPosition)); - // Include Centrifugal acceleration. - if (!GroundReactions->GetWOW()) { - vUVWdot -= Ti2b*(vOmega*(vOmega*(Tec2i*VState.vLocation))); + // Include Gravitation accel + switch (gravType) { + case gtStandard: + vGravAccel = Tl2b * FGColumnVector3( 0.0, 0.0, Inertial->GetGAccel(VehicleRadius) ); + break; + case gtWGS84: + vGravAccel = Tec2b * Inertial->GetGravityJ2(VState.vLocation); + break; } - // Include Gravitation accel - FGColumnVector3 gravAccel = Tl2b*vGravAccel; - vUVWdot += gravAccel; + vUVWdot += vGravAccel; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -void FGPropagate::CalculateLocationdot(void) -{ - // Transform the vehicle velocity relative to the ECEF frame, expressed - // in the body frame, to be expressed in the ECEF frame. - vLocationDot = Tb2ec * VState.vUVW; - - // Now, transform the velocity vector of the body relative to the origin (Earth + // Transform the velocity vector of the body relative to the origin (Earth // center) to be expressed in the inertial frame, and add the vehicle velocity - // contribution due to the rotation of the planet. The above velocity is only - // relative to the rotating ECEF frame. + // contribution due to the rotation of the planet. // Reference: See Stevens and Lewis, "Aircraft Control and Simulation", // Second edition (2004), eqn 1.5-16c (page 50) - vInertialVelocity = Tec2i * vLocationDot + (vOmega * (Tec2i * VState.vLocation)); +void FGPropagate::CalculateInertialVelocity(void) +{ + VState.vInertialVelocity = Tb2i * VState.vUVW + (vOmegaEarth * VState.vInertialPosition); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGPropagate::Integrate( FGColumnVector3& Integrand, + FGColumnVector3& Val, + deque & ValDot, + double dt, + eIntegrateType integration_type) +{ + ValDot.push_front(Val); + ValDot.pop_back(); + + switch(integration_type) { + case eRectEuler: Integrand += dt*ValDot[0]; + break; + case eTrapezoidal: Integrand += 0.5*dt*(ValDot[0] + ValDot[1]); + break; + case eAdamsBashforth2: Integrand += dt*(1.5*ValDot[0] - 0.5*ValDot[1]); + break; + case eAdamsBashforth3: Integrand += (1/12.0)*dt*(23.0*ValDot[0] - 16.0*ValDot[1] + 5.0*ValDot[2]); + break; + case eAdamsBashforth4: Integrand += (1/24.0)*dt*(55.0*ValDot[0] - 59.0*ValDot[1] + 37.0*ValDot[2] - 9.0*ValDot[3]); + break; + case eNone: // do nothing, freeze translational rate + break; + } +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGPropagate::Integrate( FGQuaternion& Integrand, + FGQuaternion& Val, + deque & ValDot, + double dt, + eIntegrateType integration_type) +{ + ValDot.push_front(Val); + ValDot.pop_back(); + + switch(integration_type) { + case eRectEuler: Integrand += dt*ValDot[0]; + break; + case eTrapezoidal: Integrand += 0.5*dt*(ValDot[0] + ValDot[1]); + break; + case eAdamsBashforth2: Integrand += dt*(1.5*ValDot[0] - 0.5*ValDot[1]); + break; + case eAdamsBashforth3: Integrand += (1/12.0)*dt*(23.0*ValDot[0] - 16.0*ValDot[1] + 5.0*ValDot[2]); + break; + case eAdamsBashforth4: Integrand += (1/24.0)*dt*(55.0*ValDot[0] - 59.0*ValDot[1] + 37.0*ValDot[2] - 9.0*ValDot[3]); + break; + case eNone: // do nothing, freeze rotational rate + break; + } +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// Resolves the contact forces just before integrating the EOM. +// This routine is using Lagrange multipliers and the projected Gauss-Seidel +// (PGS) method. +// Reference: See Erin Catto, "Iterative Dynamics with Temporal Coherence", +// February 22, 2005 +// In JSBSim there is only one rigid body (the aircraft) and there can be +// multiple points of contact between the aircraft and the ground. As a +// consequence our matrix J*M^-1*J^T is not sparse and the algorithm described +// in Catto's paper has been adapted accordingly. + +void FGPropagate::ResolveFrictionForces(double dt) +{ + const double invMass = 1.0 / MassBalance->GetMass(); + const FGMatrix33& Jinv = MassBalance->GetJinv(); + vector JacF, JacM; + FGColumnVector3 vdot, wdot; + FGColumnVector3 Fc, Mc; + int n = 0, i; + + // Compiles data from the ground reactions to build up the jacobian matrix + for (MultiplierIterator it=MultiplierIterator(GroundReactions); *it; ++it, n++) { + JacF.push_back((*it)->ForceJacobian); + JacM.push_back((*it)->MomentJacobian); + } + + // If no gears are in contact with the ground then return + if (!n) return; + + vector a(n*n); // Will contain J*M^-1*J^T + vector eta(n); + vector lambda(n); + vector lambdaMin(n); + vector lambdaMax(n); + + // Initializes the Lagrange multipliers + i = 0; + for (MultiplierIterator it=MultiplierIterator(GroundReactions); *it; ++it, i++) { + lambda[i] = (*it)->value; + lambdaMax[i] = (*it)->Max; + lambdaMin[i] = (*it)->Min; + } + + vdot = vUVWdot; + wdot = vPQRdot; + + if (dt > 0.) { + // First compute the ground velocity below the aircraft center of gravity + FGLocation contact; + FGColumnVector3 normal, cvel; + + // Instruct the algorithm to zero out the relative movement between the + // aircraft and the ground. + vdot += (VState.vUVW - Tec2b * cvel) / dt; + wdot += VState.vPQR / dt; + } + + // Assemble the linear system of equations + for (i=0; i < n; i++) { + for (int j=0; j < i; j++) + a[i*n+j] = a[j*n+i]; // Takes advantage of the symmetry of J^T*M^-1*J + for (int j=i; j < n; j++) + a[i*n+j] = DotProduct(JacF[i],invMass*JacF[j])+DotProduct(JacM[i],Jinv*JacM[j]); + } + + // Prepare the linear system for the Gauss-Seidel algorithm : + // divide every line of 'a' and eta by a[i,i]. This is in order to save + // a division computation at each iteration of Gauss-Seidel. + for (i=0; i < n; i++) { + double d = 1.0 / a[i*n+i]; + + eta[i] = -(DotProduct(JacF[i],vdot)+DotProduct(JacM[i],wdot))*d; + for (int j=0; j < n; j++) + a[i*n+j] *= d; + } + + // Resolve the Lagrange multipliers with the projected Gauss-Seidel method + for (int iter=0; iter < 50; iter++) { + double norm = 0.; + + for (i=0; i < n; i++) { + double lambda0 = lambda[i]; + double dlambda = eta[i]; + + for (int j=0; j < n; j++) + dlambda -= a[i*n+j]*lambda[j]; + + lambda[i] = Constrain(lambdaMin[i], lambda0+dlambda, lambdaMax[i]); + dlambda = lambda[i] - lambda0; + + norm += fabs(dlambda); + } + + if (norm < 1E-5) break; + } + + // Calculate the total friction forces and moments + + Fc.InitMatrix(); + Mc.InitMatrix(); + + for (i=0; i< n; i++) { + Fc += lambda[i]*JacF[i]; + Mc += lambda[i]*JacM[i]; + } + + vUVWdot += invMass * Fc; + vPQRdot += Jinv * Mc; + + // Save the value of the Lagrange multipliers to accelerate the convergence + // of the Gauss-Seidel algorithm at next iteration. + i = 0; + for (MultiplierIterator it=MultiplierIterator(GroundReactions); *it; ++it) + (*it)->value = lambda[i++]; + + GroundReactions->UpdateForcesAndMoments(); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGPropagate::SetInertialOrientation(FGQuaternion Qi) { + VState.qAttitudeECI = Qi; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +void FGPropagate::SetInertialVelocity(FGColumnVector3 Vi) { + VState.vInertialVelocity = Vi; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGPropagate::RecomputeLocalTerrainRadius(void) { - double t = State->Getsim_time(); + double t = FDMExec->GetSimTime(); // Get the LocalTerrain radius. - FGLocation contactloc; - FGColumnVector3 dv; FDMExec->GetGroundCallback()->GetAGLevel(t, VState.vLocation, contactloc, dv, dv); - LocalTerrainRadius = contactloc.GetRadius(); + LocalTerrainRadius = contactloc.GetRadius(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -472,17 +624,19 @@ double FGPropagate::GetTerrainElevation(void) const } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - +//Todo: when should this be called - when should the new EPA be used to +// calculate the transformation matrix, so that the matrix is not a step +// ahead of the sim and the associated calculations? const FGMatrix33& FGPropagate::GetTi2ec(void) { - return VState.vLocation.GetTi2ec(Inertial->GetEarthPositionAngle()); + return VState.vLocation.GetTi2ec(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% const FGMatrix33& FGPropagate::GetTec2i(void) { - return VState.vLocation.GetTec2i(Inertial->GetEarthPositionAngle()); + return VState.vLocation.GetTec2i(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -518,7 +672,7 @@ void FGPropagate::SetDistanceAGL(double tt) void FGPropagate::bind(void) { typedef double (FGPropagate::*PMF)(int) const; -// typedef double (FGPropagate::*dPMF)() const; + PropertyManager->Tie("velocities/h-dot-fps", this, &FGPropagate::Gethdot); PropertyManager->Tie("velocities/v-north-fps", this, eNorth, (PMF)&FGPropagate::GetVel); @@ -572,10 +726,11 @@ void FGPropagate::bind(void) PropertyManager->Tie("attitude/pitch-rad", this, (int)eTht, (PMF)&FGPropagate::GetEuler); PropertyManager->Tie("attitude/heading-true-rad", this, (int)ePsi, (PMF)&FGPropagate::GetEuler); - PropertyManager->Tie("simulation/integrator/rate/rotational", &integrator_rotational_rate); - PropertyManager->Tie("simulation/integrator/rate/translational", &integrator_translational_rate); - PropertyManager->Tie("simulation/integrator/position/rotational", &integrator_rotational_position); - PropertyManager->Tie("simulation/integrator/position/translational", &integrator_translational_position); + PropertyManager->Tie("simulation/integrator/rate/rotational", (int*)&integrator_rotational_rate); + PropertyManager->Tie("simulation/integrator/rate/translational", (int*)&integrator_translational_rate); + PropertyManager->Tie("simulation/integrator/position/rotational", (int*)&integrator_rotational_position); + PropertyManager->Tie("simulation/integrator/position/translational", (int*)&integrator_translational_position); + PropertyManager->Tie("simulation/gravity-model", &gravType); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -612,7 +767,96 @@ void FGPropagate::Debug(int from) } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } - if (debug_lvl & 8 ) { // Runtime state variables + if (debug_lvl & 8 && from == 2) { // Runtime state variables + cout << endl << fgblue << highint << left + << " Propagation Report (English units: ft, degrees) at simulation time " << FDMExec->GetSimTime() << " seconds" + << reset << endl; + cout << endl; + cout << highint << " Earth Position Angle (deg): " << setw(8) << setprecision(3) << reset + << Inertial->GetEarthPositionAngleDeg() << endl; + cout << endl; + cout << highint << " Body velocity (ft/sec): " << setw(8) << setprecision(3) << reset << VState.vUVW << endl; + cout << highint << " Local velocity (ft/sec): " << setw(8) << setprecision(3) << reset << vVel << endl; + cout << highint << " Inertial velocity (ft/sec): " << setw(8) << setprecision(3) << reset << VState.vInertialVelocity << endl; + cout << highint << " Inertial Position (ft): " << setw(10) << setprecision(3) << reset << VState.vInertialPosition << endl; + cout << highint << " Latitude (deg): " << setw(8) << setprecision(3) << reset << VState.vLocation.GetLatitudeDeg() << endl; + cout << highint << " Longitude (deg): " << setw(8) << setprecision(3) << reset << VState.vLocation.GetLongitudeDeg() << endl; + cout << highint << " Altitude ASL (ft): " << setw(8) << setprecision(3) << reset << GetAltitudeASL() << endl; + cout << highint << " Acceleration (NED, ft/sec^2): " << setw(8) << setprecision(3) << reset << Tb2l*GetUVWdot() << endl; + cout << endl; + cout << highint << " Matrix ECEF to Body (Orientation of Body with respect to ECEF): " + << reset << endl << Tec2b.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tec2b.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Body to ECEF (Orientation of ECEF with respect to Body):" + << reset << endl << Tb2ec.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tb2ec.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Local to Body (Orientation of Body with respect to Local):" + << reset << endl << Tl2b.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tl2b.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Body to Local (Orientation of Local with respect to Body):" + << reset << endl << Tb2l.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tb2l.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Local to ECEF (Orientation of ECEF with respect to Local):" + << reset << endl << Tl2ec.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tl2ec.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix ECEF to Local (Orientation of Local with respect to ECEF):" + << reset << endl << Tec2l.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tec2l.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix ECEF to Inertial (Orientation of Inertial with respect to ECEF):" + << reset << endl << Tec2i.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tec2i.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Inertial to ECEF (Orientation of ECEF with respect to Inertial):" + << reset << endl << Ti2ec.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Ti2ec.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Inertial to Body (Orientation of Body with respect to Inertial):" + << reset << endl << Ti2b.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Ti2b.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Body to Inertial (Orientation of Inertial with respect to Body):" + << reset << endl << Tb2i.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tb2i.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Inertial to Local (Orientation of Local with respect to Inertial):" + << reset << endl << Ti2l.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Ti2l.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << highint << " Matrix Local to Inertial (Orientation of Inertial with respect to Local):" + << reset << endl << Tl2i.Dump("\t", " ") << endl; + cout << highint << " Associated Euler angles (deg): " << setw(8) + << setprecision(3) << reset << (Tl2i.GetQuaternion().GetEuler()*radtodeg) + << endl << endl; + + cout << setprecision(6); // reset the output stream } if (debug_lvl & 16) { // Sanity checking if (from == 2) { // State sanity checking diff --git a/src/FDM/JSBSim/models/FGPropagate.h b/src/FDM/JSBSim/models/FGPropagate.h index c84005318..404946791 100644 --- a/src/FDM/JSBSim/models/FGPropagate.h +++ b/src/FDM/JSBSim/models/FGPropagate.h @@ -43,12 +43,13 @@ INCLUDES #include "math/FGLocation.h" #include "math/FGQuaternion.h" #include "math/FGMatrix33.h" +#include /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PROPAGATE "$Id$" +#define ID_PROPAGATE "$Id: FGPropagate.h,v 1.43 2010/07/25 15:35:11 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -56,6 +57,7 @@ FORWARD DECLARATIONS namespace JSBSim { +using std::deque; class FGInitialCondition; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -66,6 +68,16 @@ CLASS DOCUMENTATION The Equations of Motion (EOM) for JSBSim are integrated to propagate the state of the vehicle given the forces and moments that act on it. The integration accounts for a rotating Earth. + + The general execution of this model follows this process: + + -Calculate the angular accelerations + -Calculate the translational accelerations + -Calculate the angular rate + -Calculate the translational velocity + + -Integrate accelerations and rates + Integration of rotational and translation position and rate can be customized as needed or frozen by the selection of no integrator. The selection of which integrator to use is done through the setting of @@ -86,10 +98,11 @@ CLASS DOCUMENTATION 2: Trapezoidal 3: Adams Bashforth 2 4: Adams Bashforth 3 + 5: Adams Bashforth 4 @endcode @author Jon S. Berndt, Mathias Froehlich - @version $Id$ + @version $Id: FGPropagate.h,v 1.43 2010/07/25 15:35:11 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -106,17 +119,38 @@ public: fixed (ECEF) frame. units ft */ FGLocation vLocation; + /** The velocity vector of the vehicle with respect to the ECEF frame, expressed in the body system. units ft/sec */ FGColumnVector3 vUVW; + /** The angular velocity vector for the vehicle relative to the ECEF frame, expressed in the body frame. units rad/sec */ FGColumnVector3 vPQR; + + /** The angular velocity vector for the vehicle body frame relative to the + ECI frame, expressed in the body frame. + units rad/sec */ + FGColumnVector3 vPQRi; + /** The current orientation of the vehicle, that is, the orientation of the - body frame relative to the local, vehilce-carried, NED frame. */ - FGQuaternion vQtrn; + body frame relative to the local, NED frame. */ + FGQuaternion qAttitudeLocal; + + /** The current orientation of the vehicle, that is, the orientation of the + body frame relative to the inertial (ECI) frame. */ + FGQuaternion qAttitudeECI; + + FGColumnVector3 vInertialVelocity; + + FGColumnVector3 vInertialPosition; + + deque dqPQRdot; + deque dqUVWdot; + deque dqInertialVelocity; + deque dqQtrndot; }; /** Constructor. @@ -133,7 +167,10 @@ public: ~FGPropagate(); /// These define the indices use to select the various integrators. - enum eIntegrateType {eNone = 0, eRectEuler, eTrapezoidal, eAdamsBashforth2, eAdamsBashforth3}; + enum eIntegrateType {eNone = 0, eRectEuler, eTrapezoidal, eAdamsBashforth2, eAdamsBashforth3, eAdamsBashforth4}; + + /// These define the indices use to select the gravitation models. + enum eGravType {gtStandard, gtWGS84}; /** Initializes the FGPropagate class after instantiation and prior to first execution. The base class FGModel::InitModel is called first, initializing pointers to the @@ -144,6 +181,8 @@ public: @return false if no error */ bool Run(void); + const FGQuaternion& GetQuaterniondot(void) const {return vQtrndot;} + /** Retrieves the velocity vector. The vector returned is represented by an FGColumnVector reference. The vector for the velocity in Local frame is organized (Vnorth, Veast, Vdown). The vector @@ -207,9 +246,9 @@ public: in FGJSBBase. The relevant enumerators for the vector returned by this call are, eP=1, eQ=2, eR=3. units rad/sec - @return The body frame angular rates in rad/sec. + @return The body frame inertial angular rates in rad/sec. */ - const FGColumnVector3& GetPQRi(void) const {return vPQRi;} + const FGColumnVector3& GetPQRi(void) const {return VState.vPQRi;} /** Retrieves the body axis angular acceleration vector. Retrieves the body axis angular acceleration vector in rad/sec^2. The @@ -241,7 +280,7 @@ public: angle about the Y axis, and the third item is the angle about the Z axis (Phi, Theta, Psi). */ - const FGColumnVector3& GetEuler(void) const { return VState.vQtrn.GetEuler(); } + const FGColumnVector3& GetEuler(void) const { return VState.qAttitudeLocal.GetEuler(); } /** Retrieves a body frame velocity component. Retrieves a body frame velocity component. The velocity returned is @@ -284,7 +323,15 @@ public: /** Retrieves the total inertial velocity in ft/sec. */ - double GetInertialVelocityMagnitude(void) const { return vInertialVelocity.Magnitude(); } + double GetInertialVelocityMagnitude(void) const { return VState.vInertialVelocity.Magnitude(); } + + /** Retrieves the inertial velocity vector in ft/sec. + */ + const FGColumnVector3& GetInertialVelocity(void) const { return VState.vInertialVelocity; } + + /** Retrieves the inertial position vector. + */ + const FGColumnVector3& GetInertialPosition(void) const { return VState.vInertialPosition; } /** Returns the current altitude above sea level. This function returns the altitude above sea level. @@ -324,7 +371,7 @@ public: @param axis the index of the angular velocity component desired (1-based). @return The body frame angular velocity component. */ - double GetPQRi(int axis) const {return vPQRi(axis);} + double GetPQRi(int axis) const {return VState.vPQRi(axis);} /** Retrieves a body frame angular acceleration component. Retrieves a body frame angular acceleration component. The angular @@ -350,7 +397,7 @@ public: units radians @return An Euler angle. */ - double GetEuler(int axis) const { return VState.vQtrn.GetEuler(axis); } + double GetEuler(int axis) const { return VState.qAttitudeLocal.GetEuler(axis); } /** Retrieves the cosine of a vehicle Euler angle component. Retrieves the cosine of an Euler angle (Phi, Theta, or Psi) from the @@ -362,7 +409,7 @@ public: units none @return The cosine of an Euler angle. */ - double GetCosEuler(int idx) const { return VState.vQtrn.GetCosEuler(idx); } + double GetCosEuler(int idx) const { return VState.qAttitudeLocal.GetCosEuler(idx); } /** Retrieves the sine of a vehicle Euler angle component. Retrieves the sine of an Euler angle (Phi, Theta, or Psi) from the @@ -374,7 +421,7 @@ public: units none @return The sine of an Euler angle. */ - double GetSinEuler(int idx) const { return VState.vQtrn.GetSinEuler(idx); } + double GetSinEuler(int idx) const { return VState.qAttitudeLocal.GetSinEuler(idx); } /** Returns the current altitude rate. Returns the current altitude rate (rate of climb). @@ -414,13 +461,13 @@ public: The quaternion class, being the means by which the orientation of the vehicle is stored, manages the local-to-body transformation matrix. @return a reference to the local-to-body transformation matrix. */ - const FGMatrix33& GetTl2b(void) const { return VState.vQtrn.GetT(); } + const FGMatrix33& GetTl2b(void) const { return VState.qAttitudeLocal.GetT(); } /** Retrieves the body-to-local transformation matrix. The quaternion class, being the means by which the orientation of the vehicle is stored, manages the body-to-local transformation matrix. @return a reference to the body-to-local matrix. */ - const FGMatrix33& GetTb2l(void) const { return VState.vQtrn.GetTInv(); } + const FGMatrix33& GetTb2l(void) const { return VState.qAttitudeLocal.GetTInv(); } /** Retrieves the ECEF-to-body transformation matrix. @return a reference to the ECEF-to-body transformation matrix. */ @@ -430,6 +477,14 @@ public: @return a reference to the body-to-ECEF matrix. */ const FGMatrix33& GetTb2ec(void) const { return Tb2ec; } + /** Retrieves the ECI-to-body transformation matrix. + @return a reference to the ECI-to-body transformation matrix. */ + const FGMatrix33& GetTi2b(void) const { return VState.qAttitudeECI.GetT(); } + + /** Retrieves the body-to-ECI transformation matrix. + @return a reference to the body-to-ECI matrix. */ + const FGMatrix33& GetTb2i(void) const { return VState.qAttitudeECI.GetTInv(); } + /** Retrieves the ECEF-to-ECI transformation matrix. @return a reference to the ECEF-to-ECI transformation matrix. */ const FGMatrix33& GetTec2i(void); @@ -450,16 +505,33 @@ public: @return a reference to the local-to-ECEF matrix. */ const FGMatrix33& GetTl2ec(void) const { return VState.vLocation.GetTl2ec(); } + /** Retrieves the local-to-inertial transformation matrix. + @return a reference to the local-to-inertial transformation matrix. */ + const FGMatrix33& GetTl2i(void) { return VState.vLocation.GetTl2i(); } + + /** Retrieves the inertial-to-local transformation matrix. + @return a reference to the inertial-to-local matrix. */ + const FGMatrix33& GetTi2l(void) { return VState.vLocation.GetTi2l(); } + VehicleState* GetVState(void) { return &VState; } void SetVState(VehicleState* vstate) { VState.vLocation = vstate->vLocation; VState.vUVW = vstate->vUVW; VState.vPQR = vstate->vPQR; - VState.vQtrn = vstate->vQtrn; // ... mmh + VState.qAttitudeLocal = vstate->qAttitudeLocal; + VState.qAttitudeECI = vstate->qAttitudeECI; + + VState.dqPQRdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqUVWdot.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqInertialVelocity.resize(4, FGColumnVector3(0.0,0.0,0.0)); + VState.dqQtrndot.resize(4, FGColumnVector3(0.0,0.0,0.0)); } - const FGQuaternion GetQuaternion(void) const { return VState.vQtrn; } + void SetInertialOrientation(FGQuaternion Qi); + void SetInertialVelocity(FGColumnVector3 Vi); + + const FGQuaternion GetQuaternion(void) const { return VState.qAttitudeLocal; } void SetPQR(unsigned int i, double val) { if ((i>=1) && (i<=3) ) @@ -492,10 +564,13 @@ public: VState.vLocation -= vDeltaXYZEC; } - void CalculatePQRdot(void); - void CalculateQuatdot(void); - void CalculateLocationdot(void); - void CalculateUVWdot(void); + struct LagrangeMultiplier { + FGColumnVector3 ForceJacobian; + FGColumnVector3 MomentJacobian; + double Min; + double Max; + double value; + }; private: @@ -504,16 +579,14 @@ private: struct VehicleState VState; FGColumnVector3 vVel; + FGColumnVector3 vPQRdot; + FGColumnVector3 vUVWdot; FGColumnVector3 vInertialVelocity; - FGColumnVector3 vPQRdot, last_vPQRdot, last2_vPQRdot; - FGColumnVector3 vUVWdot, last_vUVWdot, last2_vUVWdot; - FGColumnVector3 vLocationDot, last_vLocationDot, last2_vLocationDot; FGColumnVector3 vLocation; FGColumnVector3 vDeltaXYZEC; - FGColumnVector3 vPQRi; // Inertial frame angular velocity - FGColumnVector3 vOmega; // The Earth angular velocity vector - FGColumnVector3 vOmegaLocal; // The local frame angular velocity vector - FGQuaternion vQtrndot, last_vQtrndot, last2_vQtrndot; + FGColumnVector3 vGravAccel; + FGColumnVector3 vOmegaEarth; // The Earth angular velocity vector + FGQuaternion vQtrndot; FGMatrix33 Tec2b; FGMatrix33 Tb2ec; FGMatrix33 Tl2b; // local to body frame matrix copy for immediate local use @@ -524,13 +597,37 @@ private: FGMatrix33 Ti2ec; // ECI to ECEF frame matrix copy for immediate local use FGMatrix33 Ti2b; // ECI to body frame rotation matrix FGMatrix33 Tb2i; // body to ECI frame rotation matrix + FGMatrix33 Ti2l; + FGMatrix33 Tl2i; + FGLocation contactloc; + FGColumnVector3 dv; double LocalTerrainRadius, SeaLevelRadius, VehicleRadius; double radInv; - int integrator_rotational_rate; - int integrator_translational_rate; - int integrator_rotational_position; - int integrator_translational_position; + eIntegrateType integrator_rotational_rate; + eIntegrateType integrator_translational_rate; + eIntegrateType integrator_rotational_position; + eIntegrateType integrator_translational_position; + int gravType; + + void CalculatePQRdot(void); + void CalculateQuatdot(void); + void CalculateInertialVelocity(void); + void CalculateUVWdot(void); + + void Integrate( FGColumnVector3& Integrand, + FGColumnVector3& Val, + deque & ValDot, + double dt, + eIntegrateType integration_type); + + void Integrate( FGQuaternion& Integrand, + FGQuaternion& Val, + deque & ValDot, + double dt, + eIntegrateType integration_type); + + void ResolveFrictionForces(double dt); void bind(void); void Debug(int from); diff --git a/src/FDM/JSBSim/models/FGPropulsion.cpp b/src/FDM/JSBSim/models/FGPropulsion.cpp index e71dfeaf0..bd3b09f0a 100644 --- a/src/FDM/JSBSim/models/FGPropulsion.cpp +++ b/src/FDM/JSBSim/models/FGPropulsion.cpp @@ -45,7 +45,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGPropulsion.h" -#include "FGState.h" #include "models/FGFCS.h" #include "models/FGMassBalance.h" #include "models/propulsion/FGThruster.h" @@ -66,7 +65,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPropulsion.cpp,v 1.39 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_PROPULSION; extern short debug_lvl; @@ -149,7 +148,7 @@ bool FGPropulsion::Run(void) RunPreFunctions(); - double dt = State->Getdt(); + double dt = FDMExec->GetDeltaT(); vForces.InitMatrix(); vMoments.InitMatrix(); diff --git a/src/FDM/JSBSim/models/FGPropulsion.h b/src/FDM/JSBSim/models/FGPropulsion.h index ce62a60ea..ff3502c95 100644 --- a/src/FDM/JSBSim/models/FGPropulsion.h +++ b/src/FDM/JSBSim/models/FGPropulsion.h @@ -49,7 +49,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PROPULSION "$Id$" +#define ID_PROPULSION "$Id: FGPropulsion.h,v 1.25 2010/01/02 17:58:01 andgi Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -91,7 +91,7 @@ CLASS DOCUMENTATION @endcode @author Jon S. Berndt - @version $Id$ + @version $Id: FGPropulsion.h,v 1.25 2010/01/02 17:58:01 andgi Exp $ @see FGEngine FGTank @@ -132,8 +132,8 @@ public: @return the address of the specific engine, or zero if no such engine is available */ inline FGEngine* GetEngine(unsigned int index) { - if (index <= Engines.size()-1) return Engines[index]; - else return 0L; } + if (index < Engines.size()) return Engines[index]; + else return 0L; } /// Retrieves the number of tanks defined for the aircraft. inline unsigned int GetNumTanks(void) const {return (unsigned int)Tanks.size();} @@ -143,8 +143,8 @@ public: @return the address of the specific tank, or zero if no such tank is available */ inline FGTank* GetTank(unsigned int index) { - if (index <= Tanks.size()-1) return Tanks[index]; - else return 0L; } + if (index < Tanks.size()) return Tanks[index]; + else return 0L; } /** Returns the number of fuel tanks currently actively supplying fuel */ inline int GetnumSelectedFuelTanks(void) const {return numSelectedFuelTanks;} diff --git a/src/FDM/JSBSim/models/atmosphere/FGMSIS.cpp b/src/FDM/JSBSim/models/atmosphere/FGMSIS.cpp index bd2a0abb8..390a11449 100755 --- a/src/FDM/JSBSim/models/atmosphere/FGMSIS.cpp +++ b/src/FDM/JSBSim/models/atmosphere/FGMSIS.cpp @@ -58,7 +58,7 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGMSIS.h" -#include "FGState.h" +#include "models/FGAuxiliary.h" #include /* maths functions */ #include // for cout, endl @@ -66,7 +66,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGMSIS.cpp,v 1.13 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_MSIS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/atmosphere/FGMSIS.h b/src/FDM/JSBSim/models/atmosphere/FGMSIS.h index 1765388a7..5761b1921 100755 --- a/src/FDM/JSBSim/models/atmosphere/FGMSIS.h +++ b/src/FDM/JSBSim/models/atmosphere/FGMSIS.h @@ -41,12 +41,13 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "models/FGAtmosphere.h" +#include "FGFDMExec.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MSIS "$Id$" +#define ID_MSIS "$Id: FGMSIS.h,v 1.7 2010/02/25 05:21:36 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -74,7 +75,7 @@ CLASS DOCUMENTATION and check http://www.brodo.de/english/pub/nrlmsise/index.html for updated releases of this package. @author David Culp - @version $Id$ + @version $Id: FGMSIS.h,v 1.7 2010/02/25 05:21:36 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/atmosphere/FGMars.cpp b/src/FDM/JSBSim/models/atmosphere/FGMars.cpp index 7bebc7d34..93c388f5f 100755 --- a/src/FDM/JSBSim/models/atmosphere/FGMars.cpp +++ b/src/FDM/JSBSim/models/atmosphere/FGMars.cpp @@ -42,14 +42,13 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGMars.h" -#include "FGState.h" #include using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGMars.cpp,v 1.10 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_MARS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/atmosphere/FGMars.h b/src/FDM/JSBSim/models/atmosphere/FGMars.h index 5f4bba350..e98634ecf 100755 --- a/src/FDM/JSBSim/models/atmosphere/FGMars.h +++ b/src/FDM/JSBSim/models/atmosphere/FGMars.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MARS "$Id$" +#define ID_MARS "$Id: FGMars.h,v 1.8 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -58,7 +58,7 @@ CLASS DOCUMENTATION /** Models the Martian atmosphere. @author Jon Berndt - @version $Id$ + @version $Id: FGMars.h,v 1.8 2009/10/02 10:30:09 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGAccelerometer.cpp b/src/FDM/JSBSim/models/flight_control/FGAccelerometer.cpp index 1148c81b6..30c2f2244 100755 --- a/src/FDM/JSBSim/models/flight_control/FGAccelerometer.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGAccelerometer.cpp @@ -45,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGAccelerometer.cpp,v 1.8 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_ACCELEROMETER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGAccelerometer.h b/src/FDM/JSBSim/models/flight_control/FGAccelerometer.h index d552fe434..5616ed55b 100755 --- a/src/FDM/JSBSim/models/flight_control/FGAccelerometer.h +++ b/src/FDM/JSBSim/models/flight_control/FGAccelerometer.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ACCELEROMETER "$Id$" +#define ID_ACCELEROMETER "$Id: FGAccelerometer.h,v 1.4 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -110,7 +110,7 @@ even varying all the way from 0.95 to 1.05 in adjacent frames - whatever the del time. @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.4 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGActuator.cpp b/src/FDM/JSBSim/models/flight_control/FGActuator.cpp old mode 100755 new mode 100644 index ae2aa38b7..4c58bebfd --- a/src/FDM/JSBSim/models/flight_control/FGActuator.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGActuator.cpp @@ -43,7 +43,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGActuator.cpp,v 1.14 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_ACTUATOR; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGActuator.h b/src/FDM/JSBSim/models/flight_control/FGActuator.h old mode 100755 new mode 100644 index ecfb3bf8a..7a7866e6d --- a/src/FDM/JSBSim/models/flight_control/FGActuator.h +++ b/src/FDM/JSBSim/models/flight_control/FGActuator.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ACTUATOR "$Id$" +#define ID_ACTUATOR "$Id: FGActuator.h,v 1.11 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -111,7 +111,7 @@ Example: @endcode @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.11 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGDeadBand.cpp b/src/FDM/JSBSim/models/flight_control/FGDeadBand.cpp index 3d0689d38..0158b6356 100644 --- a/src/FDM/JSBSim/models/flight_control/FGDeadBand.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGDeadBand.cpp @@ -46,7 +46,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGDeadBand.cpp,v 1.9 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_DEADBAND; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGDeadBand.h b/src/FDM/JSBSim/models/flight_control/FGDeadBand.h index 9dd4a39a3..80464769f 100644 --- a/src/FDM/JSBSim/models/flight_control/FGDeadBand.h +++ b/src/FDM/JSBSim/models/flight_control/FGDeadBand.h @@ -43,7 +43,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_DEADBAND "$Id$" +#define ID_DEADBAND "$Id: FGDeadBand.h,v 1.9 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -80,7 +80,7 @@ CLASS DOCUMENTATION produce no output. For example, say that the width value is 2.0. If the input is between -1.0 and +1.0, the output will be zero. @author Jon S. Berndt - @version $Id$ + @version $Id: FGDeadBand.h,v 1.9 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGFCSComponent.cpp b/src/FDM/JSBSim/models/flight_control/FGFCSComponent.cpp index d1f454555..8e713589f 100644 --- a/src/FDM/JSBSim/models/flight_control/FGFCSComponent.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGFCSComponent.cpp @@ -47,7 +47,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFCSComponent.cpp,v 1.27 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_FCSCOMPONENT; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGFCSComponent.h b/src/FDM/JSBSim/models/flight_control/FGFCSComponent.h index b1fc2c6c5..27186fb6d 100644 --- a/src/FDM/JSBSim/models/flight_control/FGFCSComponent.h +++ b/src/FDM/JSBSim/models/flight_control/FGFCSComponent.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FCSCOMPONENT "$Id$" +#define ID_FCSCOMPONENT "$Id: FGFCSComponent.h,v 1.16 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -80,7 +80,7 @@ CLASS DOCUMENTATION - FGActuator @author Jon S. Berndt - @version $Id$ + @version $Id: FGFCSComponent.h,v 1.16 2009/10/24 22:59:30 jberndt Exp $ @see Documentation for the FGFCS class, and for the configuration file class */ diff --git a/src/FDM/JSBSim/models/flight_control/FGFCSFunction.cpp b/src/FDM/JSBSim/models/flight_control/FGFCSFunction.cpp index d8a91572e..c6a352f3b 100755 --- a/src/FDM/JSBSim/models/flight_control/FGFCSFunction.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGFCSFunction.cpp @@ -45,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFCSFunction.cpp,v 1.9 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_FCSFUNCTION; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGFCSFunction.h b/src/FDM/JSBSim/models/flight_control/FGFCSFunction.h index fe731e8c3..d6524edf2 100755 --- a/src/FDM/JSBSim/models/flight_control/FGFCSFunction.h +++ b/src/FDM/JSBSim/models/flight_control/FGFCSFunction.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FCSFUNCTION "$Id$" +#define ID_FCSFUNCTION "$Id: FGFCSFunction.h,v 1.7 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -105,7 +105,7 @@ a function (from an aero specification): @endcode - @version $Id$ + @version $Id: FGFCSFunction.h,v 1.7 2009/10/02 10:30:09 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGFilter.cpp b/src/FDM/JSBSim/models/flight_control/FGFilter.cpp index f0ca49064..2aab6e2b8 100644 --- a/src/FDM/JSBSim/models/flight_control/FGFilter.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGFilter.cpp @@ -48,7 +48,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGFilter.cpp,v 1.15 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_FILTER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGFilter.h b/src/FDM/JSBSim/models/flight_control/FGFilter.h index 7aeafc202..efb03541c 100644 --- a/src/FDM/JSBSim/models/flight_control/FGFilter.h +++ b/src/FDM/JSBSim/models/flight_control/FGFilter.h @@ -43,7 +43,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FILTER "$Id$" +#define ID_FILTER "$Id: FGFilter.h,v 1.12 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -228,7 +228,7 @@ is so that the last component in a "string" can copy its value to the appropriat output, such as the elevator, or speedbrake, etc. @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.12 $ */ diff --git a/src/FDM/JSBSim/models/flight_control/FGGain.cpp b/src/FDM/JSBSim/models/flight_control/FGGain.cpp index 0ecb8c645..e52cd37e6 100644 --- a/src/FDM/JSBSim/models/flight_control/FGGain.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGGain.cpp @@ -47,7 +47,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGGain.cpp,v 1.20 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_GAIN; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGGain.h b/src/FDM/JSBSim/models/flight_control/FGGain.h index 525c4e449..5383cab20 100644 --- a/src/FDM/JSBSim/models/flight_control/FGGain.h +++ b/src/FDM/JSBSim/models/flight_control/FGGain.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_GAIN "$Id$" +#define ID_GAIN "$Id: FGGain.h,v 1.14 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -208,7 +208,7 @@ CLASS DOCUMENTATION @endcode @author Jon S. Berndt - @version $Revision$ + @version $Revision: 1.14 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGGradient.cpp b/src/FDM/JSBSim/models/flight_control/FGGradient.cpp index 2325dec1e..9046e4975 100644 --- a/src/FDM/JSBSim/models/flight_control/FGGradient.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGGradient.cpp @@ -44,7 +44,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGGradient.cpp,v 1.4 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_GRADIENT; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGGradient.h b/src/FDM/JSBSim/models/flight_control/FGGradient.h index ce7dac4f8..06d3e843f 100644 --- a/src/FDM/JSBSim/models/flight_control/FGGradient.h +++ b/src/FDM/JSBSim/models/flight_control/FGGradient.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_GRADIENT "$Id$" +#define ID_GRADIENT "$Id: FGGradient.h,v 1.5 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/flight_control/FGGyro.cpp b/src/FDM/JSBSim/models/flight_control/FGGyro.cpp index 740c01e3a..dffb3c9da 100755 --- a/src/FDM/JSBSim/models/flight_control/FGGyro.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGGyro.cpp @@ -44,7 +44,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGGyro.cpp,v 1.5 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_GYRO; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGGyro.h b/src/FDM/JSBSim/models/flight_control/FGGyro.h index af10851bf..2dcc9fb21 100755 --- a/src/FDM/JSBSim/models/flight_control/FGGyro.h +++ b/src/FDM/JSBSim/models/flight_control/FGGyro.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_GYRO "$Id$" +#define ID_GYRO "$Id: FGGyro.h,v 1.5 2009/12/11 06:03:06 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -70,7 +70,6 @@ Syntax: @code - property number number @@ -86,8 +85,8 @@ Syntax: Example: @code - - aero/qbar + + X 0.5 2 @@ -99,9 +98,6 @@ Example: @endcode -The only required element in the gyro definition is the input element. In that -case, no degradation would be modeled, and the output would simply be the input. - For noise, if the type is PERCENT, then the value supplied is understood to be a percentage variance. That is, if the number given is 0.05, the the variance is understood to be +/-0.05 percent maximum variance. So, the actual value for the gyro @@ -110,7 +106,7 @@ even varying all the way from 0.95 to 1.05 in adjacent frames - whatever the del time. @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.5 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGKinemat.cpp b/src/FDM/JSBSim/models/flight_control/FGKinemat.cpp index 931c1740c..525fcee37 100644 --- a/src/FDM/JSBSim/models/flight_control/FGKinemat.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGKinemat.cpp @@ -46,7 +46,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGKinemat.cpp,v 1.10 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_FLAPS; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGKinemat.h b/src/FDM/JSBSim/models/flight_control/FGKinemat.h index 8dcc73bb8..93ae1ce76 100644 --- a/src/FDM/JSBSim/models/flight_control/FGKinemat.h +++ b/src/FDM/JSBSim/models/flight_control/FGKinemat.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FLAPS "$Id$" +#define ID_FLAPS "$Id: FGKinemat.h,v 1.10 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/JSBSim/models/flight_control/FGMagnetometer.cpp b/src/FDM/JSBSim/models/flight_control/FGMagnetometer.cpp index 368d3524e..3c04e68fa 100755 --- a/src/FDM/JSBSim/models/flight_control/FGMagnetometer.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGMagnetometer.cpp @@ -47,7 +47,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGMagnetometer.cpp,v 1.5 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_MAGNETOMETER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGMagnetometer.h b/src/FDM/JSBSim/models/flight_control/FGMagnetometer.h index e806fb622..c7a850ab3 100755 --- a/src/FDM/JSBSim/models/flight_control/FGMagnetometer.h +++ b/src/FDM/JSBSim/models/flight_control/FGMagnetometer.h @@ -50,7 +50,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_MAGNETOMETER "$Id$" +#define ID_MAGNETOMETER "$Id: FGMagnetometer.h,v 1.4 2009/12/11 06:03:06 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -70,8 +70,13 @@ Syntax: @code - property + {X|Y|Z} number + + number + number + number + number number @@ -87,8 +92,8 @@ Syntax: Example: @code - - aero/qbar + + X 0.5 2 @@ -101,8 +106,9 @@ Example: @endcode -The only required element in the magnetometer definition is the input element. In that -case, no degradation would be modeled, and the output would simply be the input. +The only required element in the magnetometer definition is the axis element. In +the default case, no degradation would be modeled, and the output would simply be +the input. For noise, if the type is PERCENT, then the value supplied is understood to be a percentage variance. That is, if the number given is 0.05, the the variance is @@ -112,7 +118,7 @@ even varying all the way from 0.95 to 1.05 in adjacent frames - whatever the del time. @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.4 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGPID.cpp b/src/FDM/JSBSim/models/flight_control/FGPID.cpp index 3dda266f2..ac265b8ff 100755 --- a/src/FDM/JSBSim/models/flight_control/FGPID.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGPID.cpp @@ -44,7 +44,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPID.cpp,v 1.16 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_PID; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGPID.h b/src/FDM/JSBSim/models/flight_control/FGPID.h index adad3606c..a573dc321 100755 --- a/src/FDM/JSBSim/models/flight_control/FGPID.h +++ b/src/FDM/JSBSim/models/flight_control/FGPID.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PID "$Id$" +#define ID_PID "$Id: FGPID.h,v 1.12 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -83,7 +83,7 @@ CLASS DOCUMENTATION @author Jon S. Berndt - @version $Revision$ + @version $Revision: 1.12 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSensor.cpp b/src/FDM/JSBSim/models/flight_control/FGSensor.cpp index 1ca89b6ba..1f46dc954 100755 --- a/src/FDM/JSBSim/models/flight_control/FGSensor.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGSensor.cpp @@ -46,7 +46,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGSensor.cpp,v 1.20 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_SENSOR; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSensor.h b/src/FDM/JSBSim/models/flight_control/FGSensor.h index 136099536..bcc18dbe5 100755 --- a/src/FDM/JSBSim/models/flight_control/FGSensor.h +++ b/src/FDM/JSBSim/models/flight_control/FGSensor.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_SENSOR "$Id$" +#define ID_SENSOR "$Id: FGSensor.h,v 1.19 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -107,7 +107,7 @@ time. The delay element can specify a frame delay. The integer number provided i the number of frames to delay the output signal. @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.19 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSensorOrientation.h b/src/FDM/JSBSim/models/flight_control/FGSensorOrientation.h index 4f6d52f3e..4defe4f7a 100755 --- a/src/FDM/JSBSim/models/flight_control/FGSensorOrientation.h +++ b/src/FDM/JSBSim/models/flight_control/FGSensorOrientation.h @@ -48,7 +48,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_SensorOrientation "$Id$" +#define ID_SensorOrientation "$Id: FGSensorOrientation.h,v 1.3 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -65,7 +65,7 @@ CLASS DOCUMENTATION Syntax: @author Jon S. Berndt -@version $Revision$ +@version $Revision: 1.3 $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSummer.cpp b/src/FDM/JSBSim/models/flight_control/FGSummer.cpp index e77ee7208..40e675351 100644 --- a/src/FDM/JSBSim/models/flight_control/FGSummer.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGSummer.cpp @@ -45,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGSummer.cpp,v 1.7 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_SUMMER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSummer.h b/src/FDM/JSBSim/models/flight_control/FGSummer.h index e37642855..12a198d01 100644 --- a/src/FDM/JSBSim/models/flight_control/FGSummer.h +++ b/src/FDM/JSBSim/models/flight_control/FGSummer.h @@ -43,7 +43,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_SUMMER "$Id$" +#define ID_SUMMER "$Id: FGSummer.h,v 1.9 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -99,7 +99,7 @@ CLASS DOCUMENTATION @author Jon S. Berndt - @version $Id$ + @version $Id: FGSummer.h,v 1.9 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSwitch.cpp b/src/FDM/JSBSim/models/flight_control/FGSwitch.cpp index c29c72277..4e68ea7ff 100644 --- a/src/FDM/JSBSim/models/flight_control/FGSwitch.cpp +++ b/src/FDM/JSBSim/models/flight_control/FGSwitch.cpp @@ -69,7 +69,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGSwitch.cpp,v 1.19 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_SWITCH; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/flight_control/FGSwitch.h b/src/FDM/JSBSim/models/flight_control/FGSwitch.h index a68c2c4a5..a230aef7e 100644 --- a/src/FDM/JSBSim/models/flight_control/FGSwitch.h +++ b/src/FDM/JSBSim/models/flight_control/FGSwitch.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_SWITCH "$Id$" +#define ID_SWITCH "$Id: FGSwitch.h,v 1.13 2009/10/02 10:30:09 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -124,7 +124,7 @@ ap/attitude_hold takes the value 1), the value of the switch component will be whatever value fcs/roll-ap-error-summer is. @author Jon S. Berndt -@version $Id$ +@version $Id: FGSwitch.h,v 1.13 2009/10/02 10:30:09 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGElectric.cpp b/src/FDM/JSBSim/models/propulsion/FGElectric.cpp index 1ab17c7b6..b1459ebad 100644 --- a/src/FDM/JSBSim/models/propulsion/FGElectric.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGElectric.cpp @@ -40,7 +40,6 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGElectric.h" -#include "FGState.h" #include "models/FGPropulsion.h" #include "models/propulsion/FGThruster.h" @@ -51,7 +50,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGElectric.cpp,v 1.8 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_ELECTRIC; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -67,7 +66,7 @@ FGElectric::FGElectric(FGFDMExec* exec, Element *el, int engine_number) PowerWatts = 745.7; hptowatts = 745.7; - dt = State->Getdt(); + dt = FDMExec->GetDeltaT(); if (el->FindElement("power")) PowerWatts = el->FindElementValueAsNumberConvertTo("power","WATTS"); diff --git a/src/FDM/JSBSim/models/propulsion/FGElectric.h b/src/FDM/JSBSim/models/propulsion/FGElectric.h index da4a575bb..7bcdb406f 100644 --- a/src/FDM/JSBSim/models/propulsion/FGElectric.h +++ b/src/FDM/JSBSim/models/propulsion/FGElectric.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ELECTRIC "$Id$"; +#define ID_ELECTRIC "$Id: FGElectric.h,v 1.8 2009/10/24 22:59:30 jberndt Exp $"; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -65,7 +65,7 @@ CLASS DOCUMENTATION there is no battery model available, so this motor does not consume any energy. There is no internal friction. @author David Culp - @version "$Id$" + @version "$Id: FGElectric.h,v 1.8 2009/10/24 22:59:30 jberndt Exp $" */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGEngine.cpp b/src/FDM/JSBSim/models/propulsion/FGEngine.cpp index b95837b04..abaf368e2 100644 --- a/src/FDM/JSBSim/models/propulsion/FGEngine.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGEngine.cpp @@ -41,7 +41,7 @@ INCLUDES #include "FGTank.h" #include "FGPropeller.h" #include "FGNozzle.h" -#include "FGState.h" +#include "FGRotor.h" #include "models/FGPropulsion.h" #include "input_output/FGXMLParse.h" #include "math/FGColumnVector3.h" @@ -54,7 +54,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGEngine.cpp,v 1.38 2010/06/02 04:05:13 jberndt Exp $"; static const char *IdHdr = ID_ENGINE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -80,7 +80,6 @@ FGEngine::FGEngine(FGFDMExec* exec, Element* engine_element, int engine_number) ResetToIC(); // initialize dynamic terms FDMExec = exec; - State = FDMExec->GetState(); Atmosphere = FDMExec->GetAtmosphere(); FCS = FDMExec->GetFCS(); Propulsion = FDMExec->GetPropulsion(); @@ -124,8 +123,13 @@ FGEngine::FGEngine(FGFDMExec* exec, Element* engine_element, int engine_number) while (local_element) { int tankID = (int)local_element->GetDataAsNumber(); FGTank* tank = Propulsion->GetTank(tankID); - AddFeedTank( tankID , tank->GetPriority()); - FuelDensity = tank->GetDensity(); + if (tank) { + AddFeedTank(tankID, tank->GetPriority()); + FuelDensity = tank->GetDensity(); + } else { + cerr << "Feed tank " << tankID << + " specified in engine definition does not exist." << endl; + } local_element = engine_element->GetParent()->FindNextElement("feed"); } } else { @@ -168,6 +172,7 @@ void FGEngine::ResetToIC(void) TrimMode = false; FuelFlow_gph = 0.0; FuelFlow_pph = 0.0; + FuelFlowRate = 0.0; FuelFreeze = false; } @@ -234,7 +239,7 @@ void FGEngine::ConsumeFuel(void) double FGEngine::CalcFuelNeed(void) { - double dT = State->Getdt()*Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT()*Propulsion->GetRate(); FuelFlowRate = SLFuelFlowMax*PctPower; FuelExpended = FuelFlowRate*dT; return FuelExpended; @@ -317,11 +322,13 @@ bool FGEngine::LoadThruster(Element *thruster_element) Thruster = new FGPropeller(FDMExec, document, EngineNumber); } else if (thrType == "nozzle") { Thruster = new FGNozzle(FDMExec, document, EngineNumber); + } else if (thrType == "rotor") { + Thruster = new FGRotor(FDMExec, document, EngineNumber); } else if (thrType == "direct") { Thruster = new FGThruster( FDMExec, document, EngineNumber); } - Thruster->SetdeltaT(State->Getdt() * Propulsion->GetRate()); + Thruster->SetdeltaT(FDMExec->GetDeltaT() * Propulsion->GetRate()); Debug(2); return true; diff --git a/src/FDM/JSBSim/models/propulsion/FGEngine.h b/src/FDM/JSBSim/models/propulsion/FGEngine.h index c758d3bc7..8a3f51a8e 100644 --- a/src/FDM/JSBSim/models/propulsion/FGEngine.h +++ b/src/FDM/JSBSim/models/propulsion/FGEngine.h @@ -45,6 +45,8 @@ INCLUDES #include "FGJSBBase.h" #include "input_output/FGXMLFileRead.h" +#include "input_output/FGXMLElement.h" +#include "models/FGFCS.h" #include "math/FGColumnVector3.h" #include #include @@ -53,7 +55,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ENGINE "$Id$" +#define ID_ENGINE "$Id: FGEngine.h,v 1.20 2010/02/25 05:21:36 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -62,9 +64,7 @@ FORWARD DECLARATIONS namespace JSBSim { class FGFDMExec; -class FGState; class FGAtmosphere; -class FGFCS; class FGAircraft; class FGPropagate; class FGPropulsion; @@ -118,7 +118,7 @@ CLASS DOCUMENTATION documentation for engine and thruster classes. @author Jon S. Berndt - @version $Id$ + @version $Id: FGEngine.h,v 1.20 2010/02/25 05:21:36 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -228,7 +228,6 @@ protected: double FuelDensity; FGFDMExec* FDMExec; - FGState* State; FGAtmosphere* Atmosphere; FGFCS* FCS; FGPropulsion* Propulsion; diff --git a/src/FDM/JSBSim/models/propulsion/FGForce.cpp b/src/FDM/JSBSim/models/propulsion/FGForce.cpp index ff7532916..0180d18e4 100644 --- a/src/FDM/JSBSim/models/propulsion/FGForce.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGForce.cpp @@ -53,7 +53,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGForce.cpp,v 1.14 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_FORCE; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGForce.h b/src/FDM/JSBSim/models/propulsion/FGForce.h index eb2f59506..9ec0d3064 100644 --- a/src/FDM/JSBSim/models/propulsion/FGForce.h +++ b/src/FDM/JSBSim/models/propulsion/FGForce.h @@ -66,7 +66,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_FORCE "$Id$" +#define ID_FORCE "$Id: FGForce.h,v 1.13 2009/10/05 04:48:03 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -215,7 +215,7 @@ and vMn, the moments, can be made directly. Otherwise, the usage is similar.


@author Tony Peden - @version $Id$ + @version $Id: FGForce.h,v 1.13 2009/10/05 04:48:03 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGNozzle.cpp b/src/FDM/JSBSim/models/propulsion/FGNozzle.cpp index fdbd1533f..f1d0fb12e 100644 --- a/src/FDM/JSBSim/models/propulsion/FGNozzle.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGNozzle.cpp @@ -47,7 +47,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGNozzle.cpp,v 1.13 2009/10/26 03:49:58 jberndt Exp $"; static const char *IdHdr = ID_NOZZLE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGNozzle.h b/src/FDM/JSBSim/models/propulsion/FGNozzle.h index 4b5dc40a5..d2945ba7b 100644 --- a/src/FDM/JSBSim/models/propulsion/FGNozzle.h +++ b/src/FDM/JSBSim/models/propulsion/FGNozzle.h @@ -44,7 +44,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_NOZZLE "$Id$"; +#define ID_NOZZLE "$Id: FGNozzle.h,v 1.8 2009/10/26 03:49:58 jberndt Exp $"; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -75,7 +75,7 @@ CLASS DOCUMENTATION All parameters MUST be specified. @author Jon S. Berndt - @version $Id$ + @version $Id: FGNozzle.h,v 1.8 2009/10/26 03:49:58 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGPiston.cpp b/src/FDM/JSBSim/models/propulsion/FGPiston.cpp index 7f484e6b9..77dcf245a 100644 --- a/src/FDM/JSBSim/models/propulsion/FGPiston.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGPiston.cpp @@ -43,8 +43,8 @@ INCLUDES #include #include "FGPiston.h" -#include "FGState.h" #include "models/FGAtmosphere.h" +#include "models/FGAuxiliary.h" #include "models/FGPropulsion.h" #include "FGPropeller.h" #include @@ -53,7 +53,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPiston.cpp,v 1.52 2010/06/05 12:12:34 jberndt Exp $"; static const char *IdHdr = ID_PISTON; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -74,7 +74,7 @@ FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number) // Defaults and initializations Type = etPiston; - dt = State->Getdt(); + dt = FDMExec->GetDeltaT(); // These items are read from the configuration file // Defaults are from a Lycoming O-360, more or less @@ -96,6 +96,9 @@ FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number) Z_airbox = -999; Ram_Air_Factor = 1; PeakMeanPistonSpeed_fps = 100; + FMEPDynamic= 18400; + FMEPStatic = 46500; + // These are internal program variables @@ -201,6 +204,10 @@ FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number) Z_airbox = el->FindElementValueAsNumber("air-intake-impedance-factor"); if (el->FindElement("ram-air-factor")) Ram_Air_Factor = el->FindElementValueAsNumber("ram-air-factor"); + if (el->FindElement("dynamic-fmep")) + FMEPDynamic= el->FindElementValueAsNumberConvertTo("dynamic-fmep","PA"); + if (el->FindElement("static-fmep")) + FMEPStatic = el->FindElementValueAsNumberConvertTo("static-fmep","PA"); if (el->FindElement("peak-piston-speed")) PeakMeanPistonSpeed_fps = el->FindElementValueAsNumber("peak-piston-speed"); if (el->FindElement("numboostspeeds")) { // Turbo- and super-charging parameters @@ -244,8 +251,8 @@ FGPiston::FGPiston(FGFDMExec* exec, Element* el, int engine_number) // Create IFSC to match the engine if not provided if (ISFC < 0) { double pmep = 29.92 - MaxManifoldPressure_inHg; - pmep *= inhgtopa; - double fmep = (18400 * RatedMeanPistonSpeed_fps * fttom + 46500); + pmep *= inhgtopa * volumetric_efficiency; + double fmep = (FMEPDynamic * RatedMeanPistonSpeed_fps * fttom + FMEPStatic); double hp_loss = ((pmep + fmep) * displacement_SI * MaxRPM)/(Cycles*22371); ISFC = ( 1.1*Displacement * MaxRPM * volumetric_efficiency *(MaxManifoldPressure_inHg / 29.92) ) / (9411 * (MaxHP+hp_loss)); // cout <<"FMEP: "<< fmep <<" PMEP: "<< pmep << " hp_loss: " < 0.0) ConsumeFuel(); Throttle = FCS->GetThrottlePos(EngineNumber); - // calculate the throttle plate angle. 1 unit is approx pi/2 radians. - ThrottleAngle = MinThrottle+((MaxThrottle-MinThrottle)*Throttle ); Mixture = FCS->GetMixturePos(EngineNumber); // @@ -435,7 +441,7 @@ double FGPiston::Calculate(void) double FGPiston::CalcFuelNeed(void) { - double dT = State->Getdt() * Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT() * Propulsion->GetRate(); FuelExpended = FuelFlowRate * dT; return FuelExpended; } @@ -444,9 +450,13 @@ double FGPiston::CalcFuelNeed(void) int FGPiston::InitRunning(void) { Magnetos=3; - //Thruster->SetRPM( 1.1*IdleRPM/Thruster->GetGearRatio() ); - Thruster->SetRPM( 1000 ); + p_amb = Atmosphere->GetPressure() * psftopa; + double mix= p_amb / (101325.0*1.3); + FCS->SetMixturePos(EngineNumber, mix); + Thruster->SetRPM( 2.*IdleRPM/Thruster->GetGearRatio() ); + //Thruster->SetRPM( 1000 ); Running=true; +// cout <<"Set Running in FGPiston. RPM:" << Thruster->GetRPM()*Thruster->GetGearRatio() <<" Pressure:"< 0) { + } if(BoostSpeed > 0) { // Check if we need to change to a lower boost speed if(p_amb > BoostSwitchPressure[BoostSpeed - 1] + BoostSwitchHysteresis) { BoostSpeed--; @@ -559,7 +568,7 @@ void FGPiston::doBoostControl(void) * from the throttle position, turbo/supercharger boost control * system, engine speed and local ambient air density. * - * Inputs: p_amb, Throttle, ThrottleAngle, + * Inputs: p_amb, Throttle, * MeanPistonSpeed_fps, dt * * Outputs: MAP, ManifoldPressure_inHg, TMAP @@ -567,7 +576,7 @@ void FGPiston::doBoostControl(void) void FGPiston::doMAP(void) { - double Zt =(1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence + double Zt = (1-Throttle)*(1-Throttle)*Z_throttle; // throttle impedence double Ze= MeanPistonSpeed_fps > 0 ? PeakMeanPistonSpeed_fps/MeanPistonSpeed_fps : 999999; // engine impedence double map_coefficient = Ze/(Ze+Z_airbox+Zt); @@ -579,7 +588,7 @@ void FGPiston::doMAP(void) // Find the mean effective pressure required to achieve this manifold pressure // Fixme: determine the HP consumed by the supercharger - PMEP = TMAP - p_amb; // Fixme: p_amb should be exhaust manifold pressure + PMEP = (TMAP - p_amb) * volumetric_efficiency; // Fixme: p_amb should be exhaust manifold pressure if (Boosted) { // If takeoff boost is fitted, we currently assume the following throttle map: @@ -618,7 +627,7 @@ void FGPiston::doMAP(void) * (used in CHT calculation for air-cooled engines). * * Inputs: p_amb, R_air, T_amb, MAP, Displacement, - * RPM, volumetric_efficiency, ThrottleAngle + * RPM, volumetric_efficiency, * * TODO: Model inlet manifold air temperature. * @@ -627,9 +636,10 @@ void FGPiston::doMAP(void) void FGPiston::doAirFlow(void) { - double gamma = 1.1; // specific heat constants + double gamma = 1.3; // specific heat constants // loss of volumentric efficiency due to difference between MAP and exhaust pressure - double ve =((gamma-1)/gamma)+( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1)); +// Eq 6-10 from The Internal Combustion Engine - Charles Taylor Vol 1 + double ve =((gamma-1)/gamma) +( CompressionRatio -(p_amb/MAP))/(gamma*( CompressionRatio - 1)); rho_air = p_amb / (R_air * T_amb); double swept_volume = (displacement_SI * (RPM/60)) / 2; @@ -665,15 +675,11 @@ void FGPiston::doFuelFlow(void) /** * Calculate the power produced by the engine. * - * Currently, the JSBSim propellor model does not allow the - * engine to produce enough RPMs to get up to a high horsepower. - * When tested with sufficient RPM, it has no trouble reaching - * 200HP. - * - * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb, + * Inputs: ManifoldPressure_inHg, p_amb, RPM, T_amb, ISFC, * Mixture_Efficiency_Correlation, Cycles, MaxHP, PMEP, + * MeanPistonSpeed_fps * - * Outputs: PctPower, HP + * Outputs: PctPower, HP, FMEP, IndicatedHorsePower */ void FGPiston::doEnginePower(void) @@ -686,9 +692,8 @@ void FGPiston::doEnginePower(void) ME = Mixture_Efficiency_Correlation->GetValue(m_dot_fuel/m_dot_air); percent_RPM = RPM/MaxRPM; -// Guestimate engine friction as a percentage of rated HP + a percentage of rpm + a percentage of Indicted HP -// friction = 1 - (percent_RPM * percent_RPM * percent_RPM/10); - FMEP = (-18400 * MeanPistonSpeed_fps * fttom - 46500); +// Guestimate engine friction losses from Figure 4.4 of "Engines: An Introduction", John Lumley + FMEP = (-FMEPDynamic * MeanPistonSpeed_fps * fttom - FMEPStatic); power = 1; @@ -770,7 +775,7 @@ void FGPiston::doCHT(void) double h2 = -3.95; double h3 = -140.0; // -0.05 * 2800 (default maxrpm) - double arbitary_area = 1.0; + double arbitary_area = Displacement/360.0; double CpCylinderHead = 800.0; double MassCylinderHead = 8.0; @@ -813,8 +818,8 @@ void FGPiston::doOilTemperature(void) if (OilPressure_psi > 5.0 ) { time_constant = 5000 / OilPressure_psi; // Guess at a time constant for circulated oil. // The higher the pressure the faster it reaches - // target temperature. Oil pressure should be about - // 60 PSI yielding a TC of about 80. + // target temperature. Oil pressure should be about + // 60 PSI yielding a TC of about 80. } else { time_constant = 1000; // Time constant for engine-off; reflects the fact // that oil is no longer getting circulated @@ -919,12 +924,13 @@ void FGPiston::Debug(int from) cout << " Cycles: " << Cycles << endl; cout << " IdleRPM: " << IdleRPM << endl; cout << " MaxRPM: " << MaxRPM << endl; - cout << " MaxThrottle: " << MaxThrottle << endl; - cout << " MinThrottle: " << MinThrottle << endl; + cout << " Throttle Constant: " << Z_throttle << endl; cout << " ISFC: " << ISFC << endl; cout << " Volumetric Efficiency: " << volumetric_efficiency << endl; cout << " PeakMeanPistonSpeed_fps: " << PeakMeanPistonSpeed_fps << endl; cout << " Intake Impedance Factor: " << Z_airbox << endl; + cout << " Dynamic FMEP Factor: " << FMEPDynamic << endl; + cout << " Static FMEP Factor: " << FMEPStatic << endl; cout << endl; cout << " Combustion Efficiency table:" << endl; diff --git a/src/FDM/JSBSim/models/propulsion/FGPiston.h b/src/FDM/JSBSim/models/propulsion/FGPiston.h index 2bfb1971a..a008e6a73 100644 --- a/src/FDM/JSBSim/models/propulsion/FGPiston.h +++ b/src/FDM/JSBSim/models/propulsion/FGPiston.h @@ -41,13 +41,12 @@ INCLUDES #include "FGEngine.h" #include "math/FGTable.h" -#include "input_output/FGXMLElement.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PISTON "$Id$"; +#define ID_PISTON "$Id: FGPiston.h,v 1.23 2010/02/25 05:21:36 jberndt Exp $"; #define FG_MAX_BOOST_SPEEDS 3 /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -66,7 +65,7 @@ CLASS DOCUMENTATION @code - {number} + {number} {number} {number} {number} @@ -82,6 +81,8 @@ CLASS DOCUMENTATION {number} {number} {number} + {number} + {number} {number} {0 | 1} {0 | 1} @@ -180,7 +181,7 @@ CLASS DOCUMENTATION @author Dave Luff (engine operational code) @author David Megginson (initial porting and additional code) @author Ron Jensen (additional engine code) - @version $Id$ + @version $Id: FGPiston.h,v 1.23 2010/02/25 05:21:36 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -216,7 +217,6 @@ public: double getRPM(void) {return RPM;} protected: - double ThrottleAngle; private: int crank_counter; @@ -224,9 +224,8 @@ private: double IndicatedHorsePower; double PMEP; double FMEP; - double SpeedSlope; - double SpeedIntercept; - double AltitudeSlope; + double FMEPDynamic; + double FMEPStatic; double PowerAvailable; // timestep diff --git a/src/FDM/JSBSim/models/propulsion/FGPropeller.cpp b/src/FDM/JSBSim/models/propulsion/FGPropeller.cpp index fb1be8ac1..8204bb9d2 100644 --- a/src/FDM/JSBSim/models/propulsion/FGPropeller.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGPropeller.cpp @@ -48,7 +48,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGPropeller.cpp,v 1.30 2010/05/02 15:10:07 jberndt Exp $"; static const char *IdHdr = ID_PROPELLER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -76,6 +76,9 @@ FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) Reverse_coef = 0.0; GearRatio = 1.0; CtFactor = CpFactor = 1.0; + ConstantSpeed = 0; + cThrust = cPower = CtMach = CpMach = 0; + Vinduced = 0.0; if (prop_element->FindElement("ixx")) Ixx = prop_element->FindElementValueAsNumberConvertTo("ixx", "SLUG*FT2"); @@ -91,8 +94,12 @@ FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) MaxPitch = prop_element->FindElementValueAsNumber("maxpitch"); if (prop_element->FindElement("minrpm")) MinRPM = prop_element->FindElementValueAsNumber("minrpm"); - if (prop_element->FindElement("maxrpm")) + if (prop_element->FindElement("maxrpm")) { MaxRPM = prop_element->FindElementValueAsNumber("maxrpm"); + ConstantSpeed = 1; + } + if (prop_element->FindElement("constspeed")) + ConstantSpeed = (int)prop_element->FindElementValueAsNumber("constspeed"); if (prop_element->FindElement("reversepitch")) ReversePitch = prop_element->FindElementValueAsNumber("reversepitch"); for (int i=0; i<2; i++) { @@ -102,6 +109,10 @@ FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) cThrust = new FGTable(PropertyManager, table_element); } else if (name == "C_POWER") { cPower = new FGTable(PropertyManager, table_element); + } else if (name == "CT_MACH") { + CtMach = new FGTable(PropertyManager, table_element); + } else if (name == "CP_MACH") { + CpMach = new FGTable(PropertyManager, table_element); } else { cerr << "Unknown table type: " << name << " in propeller definition." << endl; } @@ -129,6 +140,7 @@ FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) vTorque.InitMatrix(); D4 = Diameter*Diameter*Diameter*Diameter; D5 = D4*Diameter; + Pitch = MinPitch; string property_name, base_property_name; base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNum); @@ -140,6 +152,14 @@ FGPropeller::FGPropeller(FGFDMExec* exec, Element* prop_element, int num) PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetThrustCoefficient ); property_name = base_property_name + "/propeller-rpm"; PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetRPM ); + property_name = base_property_name + "/helical-tip-Mach"; + PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetHelicalTipMach ); + property_name = base_property_name + "/constant-speed-mode"; + PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetConstantSpeed, + &FGPropeller::SetConstantSpeed ); + property_name = base_property_name + "/prop-induced-velocity_fps"; + PropertyManager->Tie( property_name.c_str(), this, &FGPropeller::GetInducedVelocity, + &FGPropeller::SetInducedVelocity ); Debug(0); } @@ -150,6 +170,8 @@ FGPropeller::~FGPropeller() { delete cThrust; delete cPower; + delete CtMach; + delete CpMach; Debug(1); } @@ -176,13 +198,27 @@ double FGPropeller::Calculate(double PowerAvailable) double rho = fdmex->GetAtmosphere()->GetDensity(); double RPS = RPM/60.0; - if (RPS > 0.00) J = Vel / (Diameter * RPS); // Calculate J normally - else J = 1000.0; // Set J to a high number + // Calculate helical tip Mach + double Area = 0.25*Diameter*Diameter*M_PI; + double Vtip = RPS * Diameter * M_PI; + HelicalTipMach = sqrt(Vtip*Vtip + Vel*Vel) / + fdmex->GetAtmosphere()->GetSoundSpeed(); + + if (RPS > 0.0) J = Vel / (Diameter * RPS); // Calculate J normally + else J = Vel / Diameter; - if (MaxPitch == MinPitch) ThrustCoeff = cThrust->GetValue(J); - else ThrustCoeff = cThrust->GetValue(J, Pitch); + if (MaxPitch == MinPitch) { // Fixed pitch prop + ThrustCoeff = cThrust->GetValue(J); + } else { // Variable pitch prop + ThrustCoeff = cThrust->GetValue(J, Pitch); + } + + // Apply optional scaling factor to Ct (default value = 1) ThrustCoeff *= CtFactor; + // Apply optional Mach effects from CT_MACH table + if (CtMach) ThrustCoeff *= CtMach->GetValue(HelicalTipMach); + if (P_Factor > 0.0001) { alpha = fdmex->GetAuxiliary()->Getalpha(); beta = fdmex->GetAuxiliary()->Getbeta(); @@ -191,6 +227,11 @@ double FGPropeller::Calculate(double PowerAvailable) } Thrust = ThrustCoeff*RPS*RPS*D4*rho; + + // From B. W. McCormick, "Aerodynamics, Aeronautics, and Flight Mechanics" + // first edition, eqn. 6.15 (propeller analysis chapter). + Vinduced = 0.5 * (-Vel + sqrt(Vel*Vel + 2.0*Thrust/(rho*Area))); + omega = RPS*2.0*M_PI; vFn(1) = Thrust; @@ -203,12 +244,12 @@ double FGPropeller::Calculate(double PowerAvailable) vH(eY) = 0.0; vH(eZ) = 0.0; - if (omega > 0.0) ExcessTorque = GearRatio * PowerAvailable / omega; - else ExcessTorque = GearRatio * PowerAvailable / 1.0; + if (omega > 0.0) ExcessTorque = PowerAvailable / omega; + else ExcessTorque = PowerAvailable / 1.0; RPM = (RPS + ((ExcessTorque / Ixx) / (2.0 * M_PI)) * deltaT) * 60.0; - if (RPM < 1.0) RPM = 0; // Engine friction stops rotation arbitrarily at 1 RPM. + if (RPM < 0.0) RPM = 0.0; // Engine won't turn backwards // Transform Torque and momentum first, as PQR is used in this // equation and cannot be transformed itself. @@ -223,19 +264,23 @@ double FGPropeller::GetPowerRequired(void) { double cPReq, J; double rho = fdmex->GetAtmosphere()->GetDensity(); + double Vel = fdmex->GetAuxiliary()->GetAeroUVW(eU); double RPS = RPM / 60.0; - if (RPS != 0) J = fdmex->GetAuxiliary()->GetAeroUVW(eU) / (Diameter * RPS); - else J = 1000.0; // Set J to a high number + if (RPS != 0.0) J = Vel / (Diameter * RPS); + else J = Vel / Diameter; - if (MaxPitch == MinPitch) { // Fixed pitch prop - Pitch = MinPitch; + if (MaxPitch == MinPitch) { // Fixed pitch prop cPReq = cPower->GetValue(J); + } else { // Variable pitch prop - if (MaxRPM != MinRPM) { // fixed-speed prop + if (ConstantSpeed != 0) { // Constant Speed Mode // do normal calculation when propeller is neither feathered nor reversed + // Note: This method of feathering and reversing was added to support the + // turboprop model. It's left here for backward compatablity, but + // now feathering and reversing should be done in Manual Pitch Mode. if (!Feathered) { if (!Reversed) { @@ -267,19 +312,29 @@ double FGPropeller::GetPowerRequired(void) Pitch += (MaxPitch - Pitch) / 300; // just a guess (about 5 sec to fully feathered) } - } else { // Variable Speed Prop - Pitch = MinPitch + (MaxPitch - MinPitch) * Advance; + } else { // Manual Pitch Mode, pitch is controlled externally + } + cPReq = cPower->GetValue(J, Pitch); } + + // Apply optional scaling factor to Cp (default value = 1) cPReq *= CpFactor; - if (RPS > 0) { + // Apply optional Mach effects from CP_MACH table + if (CpMach) cPReq *= CpMach->GetValue(HelicalTipMach); + + if (RPS > 0.1) { PowerRequired = cPReq*RPS*RPS*RPS*D5*rho; vTorque(eX) = -Sense*PowerRequired / (RPS*2.0*M_PI); } else { - PowerRequired = 0.0; - vTorque(eX) = 0.0; + // For a stationary prop we have to estimate torque first. + double CL = (90.0 - Pitch) / 20.0; + if (CL > 1.5) CL = 1.5; + double BladeArea = Diameter * Diameter / 32.0 * numBlades; + vTorque(eX) = -Sense*BladeArea*Diameter*Vel*Vel*rho*0.19*CL; + PowerRequired = vTorque(eX)*0.2*M_PI; } return PowerRequired; diff --git a/src/FDM/JSBSim/models/propulsion/FGPropeller.h b/src/FDM/JSBSim/models/propulsion/FGPropeller.h index 500e67985..ea7953e1e 100644 --- a/src/FDM/JSBSim/models/propulsion/FGPropeller.h +++ b/src/FDM/JSBSim/models/propulsion/FGPropeller.h @@ -45,7 +45,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_PROPELLER "$Id$" +#define ID_PROPELLER "$Id: FGPropeller.h,v 1.16 2010/04/09 12:44:06 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -71,6 +71,7 @@ CLASS DOCUMENTATION {number} {number} {number} + {number} {number} {1 | -1} {number} @@ -89,6 +90,19 @@ CLASS DOCUMENTATION + + + {numbers} + +
+ + + + {numbers} + +
+ + @endcode @@ -102,6 +116,7 @@ CLASS DOCUMENTATION \ - Maximum blade pitch angle. \ - Minimum rpm target for constant speed propeller. \ - Maximum rpm target for constant speed propeller. + \ - 1 = constant speed mode, 0 = manual pitch mode. \ - Blade pitch angle for reverse. \ - Direction of rotation (1=clockwise as viewed from cockpit, -1=anti-clockwise as viewed from cockpit). @@ -111,7 +126,10 @@ CLASS DOCUMENTATION Two tables are needed. One for coefficient of thrust (Ct) and one for - coefficient of power (Cp). + coefficient of power (Cp). + + Two tables are optional. They apply a factor to Ct and Cp based on the + helical tip Mach.
Several references were helpful, here:
    @@ -123,7 +141,7 @@ CLASS DOCUMENTATION
  • Various NACA Technical Notes and Reports
@author Jon S. Berndt - @version $Id$ + @version $Id: FGPropeller.h,v 1.16 2010/04/09 12:44:06 jberndt Exp $ @see FGEngine @see FGThruster */ @@ -169,6 +187,9 @@ public: /// Sets the P-Factor constant void SetPFactor(double pf) {P_Factor = pf;} + /// Sets propeller into constant speed mode, or manual pitch mode + void SetConstantSpeed(int mode) {ConstantSpeed = mode;} + /// Sets coefficient of thrust multiplier void SetCtFactor(double ctf) {CtFactor = ctf;} @@ -204,6 +225,11 @@ public: /// Retrieves propeller power table FGTable* GetCPowerTable(void) const { return cPower; } + /// Retrieves propeller thrust Mach effects factor + FGTable* GetCtMachTable(void) const { return CtMach; } + /// Retrieves propeller power Mach effects factor + FGTable* GetCpMachTable(void) const { return CpMach; } + /// Retrieves the Torque in foot-pounds (Don't you love the English system?) double GetTorque(void) { return vTorque(eX); } @@ -233,6 +259,10 @@ public: void SetFeather (bool f) { Feathered = f; } bool GetFeather (void) { return Feathered; } double GetThrustCoefficient(void) const {return ThrustCoeff;} + double GetHelicalTipMach(void) const {return HelicalTipMach;} + int GetConstantSpeed(void) const {return ConstantSpeed;} + void SetInducedVelocity(double Vi) {Vinduced = Vi;} + double GetInducedVelocity(void) const {return Vinduced;} private: int numBlades; @@ -251,14 +281,19 @@ private: double ExcessTorque; double D4; double D5; + double HelicalTipMach; + double Vinduced; FGColumnVector3 vTorque; FGTable *cThrust; FGTable *cPower; + FGTable *CtMach; + FGTable *CpMach; double CtFactor; double CpFactor; + int ConstantSpeed; void Debug(int from); double ReversePitch; // Pitch, when fully reversed - bool Reversed; // true, when propeller is reversed + bool Reversed; // true, when propeller is reversed double Reverse_coef; // 0 - 1 defines AdvancePitch (0=MIN_PITCH 1=REVERSE_PITCH) bool Feathered; // true, if feather command }; diff --git a/src/FDM/JSBSim/models/propulsion/FGRocket.cpp b/src/FDM/JSBSim/models/propulsion/FGRocket.cpp index 85b0fd57f..52ab88cb2 100644 --- a/src/FDM/JSBSim/models/propulsion/FGRocket.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGRocket.cpp @@ -41,7 +41,6 @@ INCLUDES #include #include #include "FGRocket.h" -#include "FGState.h" #include "models/FGPropulsion.h" #include "FGThruster.h" #include "FGTank.h" @@ -50,7 +49,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGRocket.cpp,v 1.19 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_ROCKET; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -66,9 +65,9 @@ FGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number) previousFuelNeedPerTank = 0.0; previousOxiNeedPerTank = 0.0; PropellantFlowRate = 0.0; - FuelFlowRate = 0.0; - OxidizerFlowRate = 0.0; - SLOxiFlowMax = 0.0; + FuelFlowRate = FuelExpended = 0.0; + OxidizerFlowRate = OxidizerExpended = 0.0; + SLOxiFlowMax = SLFuelFlowMax = 0.0; BuildupTime = 0.0; It = 0.0; ThrustVariation = 0.0; @@ -127,7 +126,7 @@ FGRocket::~FGRocket(void) double FGRocket::Calculate(void) { - double dT = State->Getdt()*Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT()*Propulsion->GetRate(); double thrust; if (!Flameout && !Starved) ConsumeFuel(); @@ -157,7 +156,7 @@ double FGRocket::Calculate(void) VacThrust *= sin((BurnTime/BuildupTime)*M_PI/2.0); // VacThrust *= (1-cos((BurnTime/BuildupTime)*M_PI))/2.0; // 1 - cos approach } - BurnTime += State->Getdt(); // Increment burn time + BurnTime += FDMExec->GetDeltaT(); // Increment burn time } else { VacThrust = 0.0; } @@ -210,14 +209,16 @@ void FGRocket::ConsumeFuel(void) // a solid rocket is being modeled. for (i=0; iGetTank(SourceTanks[i]); + Tank = Propulsion->GetTank(i); switch(Tank->GetType()) { case FGTank::ttFUEL: - if (Tank->GetContents() > 0.0 && Tank->GetSelected()) ++TanksWithFuel; + if (Tank->GetContents() > 0.0 && Tank->GetSelected() && SourceTanks[i] > 0) ++TanksWithFuel; break; case FGTank::ttOXIDIZER: - haveOxTanks = true; - if (Tank->GetContents() > 0.0 && Tank->GetSelected()) ++TanksWithOxidizer; + if (Tank->GetContents() > 0.0 && Tank->GetSelected() && SourceTanks[i] > 0) { + haveOxTanks = true; + ++TanksWithOxidizer; + } break; } } @@ -232,12 +233,15 @@ void FGRocket::ConsumeFuel(void) // Expend fuel from the engine's tanks if the tank is selected as a source // for this engine. - double fuelNeedPerTank = CalcFuelNeed()/TanksWithFuel; - double oxiNeedPerTank = CalcOxidizerNeed()/TanksWithOxidizer; + double fuelNeedPerTank = 0; + double oxiNeedPerTank = 0; + + if (TanksWithFuel > 0) fuelNeedPerTank = CalcFuelNeed()/TanksWithFuel; + if (TanksWithOxidizer > 0) oxiNeedPerTank = CalcOxidizerNeed()/TanksWithOxidizer; for (i=0; iGetTank(SourceTanks[i]); - if ( ! Tank->GetSelected()) continue; // If this tank is not selected as a source, skip it. + Tank = Propulsion->GetTank(i); + if ( ! Tank->GetSelected() || SourceTanks[i] == 0) continue; // If this tank is not selected as a source, skip it. switch(Tank->GetType()) { case FGTank::ttFUEL: Fshortage += Tank->Drain(2.0*fuelNeedPerTank - previousFuelNeedPerTank); @@ -263,7 +267,7 @@ void FGRocket::ConsumeFuel(void) double FGRocket::CalcFuelNeed(void) { - double dT = State->Getdt()*Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT()*Propulsion->GetRate(); if (ThrustTable != 0L) { // Thrust table given - infers solid fuel FuelFlowRate = VacThrust/Isp; // This calculates wdot (weight flow rate in lbs/sec) @@ -280,7 +284,7 @@ double FGRocket::CalcFuelNeed(void) double FGRocket::CalcOxidizerNeed(void) { - double dT = State->Getdt()*Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT()*Propulsion->GetRate(); OxidizerFlowRate = SLOxiFlowMax*PctPower; OxidizerExpended = OxidizerFlowRate*dT; return OxidizerExpended; @@ -367,7 +371,8 @@ void FGRocket::Debug(int from) cout << " Minimum Throttle = " << MinThrottle << endl; cout << " Fuel Flow (max) = " << SLFuelFlowMax << endl; cout << " Oxidizer Flow (max) = " << SLOxiFlowMax << endl; - cout << " Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl; + if (SLFuelFlowMax > 0) + cout << " Mixture ratio = " << SLOxiFlowMax/SLFuelFlowMax << endl; } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification diff --git a/src/FDM/JSBSim/models/propulsion/FGRocket.h b/src/FDM/JSBSim/models/propulsion/FGRocket.h index 4ff539572..8692a5c1a 100644 --- a/src/FDM/JSBSim/models/propulsion/FGRocket.h +++ b/src/FDM/JSBSim/models/propulsion/FGRocket.h @@ -46,7 +46,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ROCKET "$Id$" +#define ID_ROCKET "$Id: FGRocket.h,v 1.12 2009/11/08 02:24:17 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -118,7 +118,7 @@ for the rocket engine to be throttle up to 1. At that time, the solid rocket fuel begins burning and thrust is provided. @author Jon S. Berndt - $Id$ + $Id: FGRocket.h,v 1.12 2009/11/08 02:24:17 jberndt Exp $ @see FGNozzle, FGThruster, FGForce, diff --git a/src/FDM/JSBSim/models/propulsion/FGRotor.cpp b/src/FDM/JSBSim/models/propulsion/FGRotor.cpp index 6ef33e7c0..b1c1661d0 100644 --- a/src/FDM/JSBSim/models/propulsion/FGRotor.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGRotor.cpp @@ -5,7 +5,7 @@ Date started: 08/24/00 Purpose: Encapsulates the rotor object - ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) ------------- + ------------- Copyright (C) 2000 Jon S. Berndt (jsb@hal-pc.org) ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software @@ -30,32 +30,733 @@ FUNCTIONAL DESCRIPTION HISTORY -------------------------------------------------------------------------------- 08/24/00 JSB Created +01/01/10 T.Kreitler test implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#include "FGRotor.h" #include +#include + +#include "FGRotor.h" + +#include "models/FGPropagate.h" +#include "models/FGAtmosphere.h" +#include "models/FGAuxiliary.h" +#include "models/FGMassBalance.h" + +#include "input_output/FGXMLElement.h" + +#include "math/FGRungeKutta.h" using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGRotor.cpp,v 1.9 2010/06/05 12:12:34 jberndt Exp $"; static const char *IdHdr = ID_ROTOR; +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +MISC +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +static int dump_req; // debug schwafel flag + +static inline double sqr(double x) { return x*x; } + /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CLASS IMPLEMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ +// starting with 'inner' rotor, FGRotor constructor is further down + +FGRotor::rotor::~rotor() { } + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// hmm, not a real alternative to a pretty long initializer list + +void FGRotor::rotor::zero() { + FGColumnVector3 zero_vec(0.0, 0.0, 0.0); + + flags = 0; + parent = NULL ; + + reports = 0; + + // configuration + Radius = 0.0 ; + BladeNum = 0 ; + RelDistance_xhub = 0.0 ; + RelShift_yhub = 0.0 ; + RelHeight_zhub = 0.0 ; + NominalRPM = 0.0 ; + MinRPM = 0.0 ; + BladeChord = 0.0 ; + LiftCurveSlope = 0.0 ; + BladeFlappingMoment = 0.0 ; + BladeTwist = 0.0 ; + BladeMassMoment = 0.0 ; + TipLossB = 0.0 ; + PolarMoment = 0.0 ; + InflowLag = 0.0 ; + ShaftTilt = 0.0 ; + HingeOffset = 0.0 ; + HingeOffset_hover = 0.0 ; + CantAngleD3 = 0.0 ; + + theta_shaft = 0.0 ; + phi_shaft = 0.0 ; + + // derived parameters + LockNumberByRho = 0.0 ; + solidity = 0.0 ; + RpmRatio = 0.0 ; -FGRotor::FGRotor(FGFDMExec *FDMExec, Element* rotor_element, int num) - : FGThruster(FDMExec, rotor_element, num) + for (int i=0; i<5; i++) R[i] = 0.0; + for (int i=0; i<6; i++) B[i] = 0.0; + + BodyToShaft.InitMatrix(); + ShaftToBody.InitMatrix(); + + // dynamic values + ActualRPM = 0.0 ; + Omega = 0.0 ; + beta_orient = 0.0 ; + a0 = 0.0 ; + a_1 = b_1 = a_dw = 0.0 ; + a1s = b1s = 0.0 ; + H_drag = J_side = 0.0 ; + + Torque = 0.0 ; + Thrust = 0.0 ; + Ct = 0.0 ; + lambda = 0.0 ; + mu = 0.0 ; + nu = 0.0 ; + v_induced = 0.0 ; + + force = zero_vec ; + moment = zero_vec ; + +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// 5in1: value-fetch-convert-default-return function + +double FGRotor::rotor::cnf_elem( const string& ename, double default_val, + const string& unit, bool tell) { - Debug(0); + + Element *e = NULL; + double val=default_val; + + std::string pname = "*No parent element*"; + + if (parent) { + e = parent->FindElement(ename); + pname = parent->GetName(); + } + + if (e) { + if (unit.empty()) { + // val = e->FindElementValueAsNumber(ename); + // yields to: Attempting to get single data value from multiple lines + val = parent->FindElementValueAsNumber(ename); + } else { + // val = e->FindElementValueAsNumberConvertTo(ename,unit); + // yields to: Attempting to get non-existent element diameter + crash, why ? + val = parent->FindElementValueAsNumberConvertTo(ename,unit); + } + } else { + if (tell) { + cerr << pname << ": missing element '" << ename <<"' using estimated value: " << default_val << endl; + } + } + + return val; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +double FGRotor::rotor::cnf_elem(const string& ename, double default_val, bool tell) +{ + return cnf_elem(ename, default_val, "", tell); +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// 1. read configuration and try to fill holes, ymmv +// 2. calculate derived parameters and transforms +void FGRotor::rotor::configure(int f, const rotor *xmain) +{ + + double estimate; + const bool yell = true; + const bool silent = false; + + flags = f; + + estimate = (xmain) ? 2.0 * xmain->Radius * 0.2 : 42.0; + Radius = 0.5 * cnf_elem("diameter", estimate, "FT", yell); + + estimate = (xmain) ? xmain->BladeNum : 2.0; + estimate = Constrain(1.0,estimate,4.0); + BladeNum = (int) cnf_elem("numblades", estimate, yell); + + estimate = (xmain) ? - xmain->Radius * 1.05 - Radius : - 0.025 * Radius ; + RelDistance_xhub = cnf_elem("xhub", estimate, "FT", yell); + + RelShift_yhub = cnf_elem("yhub", 0.0, "FT", silent); + + estimate = - 0.1 * Radius - 4.0; + RelHeight_zhub = cnf_elem("zhub", estimate, "FT", yell); + + // make sure that v_tip (omega*r) is below 0.7mach ~ 750ft/s + estimate = (750.0/Radius)/(2.0*M_PI) * 60.0; // 7160/Radius + NominalRPM = cnf_elem("nominalrpm", estimate, yell); + + MinRPM = cnf_elem("minrpm", 1.0, silent); + MinRPM = Constrain(1.0, MinRPM, NominalRPM-1.0); + + estimate = (xmain) ? 0.12 : 0.07; // guess solidity + estimate = estimate * M_PI*Radius/BladeNum; + BladeChord = cnf_elem("chord", estimate, "FT", yell); + + LiftCurveSlope = cnf_elem("liftcurveslope", 6.0, yell); // "1/RAD" + + estimate = sqr(BladeChord) * sqr(Radius) * 0.57; + BladeFlappingMoment = cnf_elem("flappingmoment", estimate, "SLUG*FT2", yell); + BladeFlappingMoment = Constrain(0.1, BladeFlappingMoment, 1e9); + + BladeTwist = cnf_elem("twist", -0.17, "RAD", yell); + + estimate = sqr(BladeChord) * BladeChord * 15.66; // might be really wrong! + BladeMassMoment = cnf_elem("massmoment", estimate, yell); // slug-ft + BladeMassMoment = Constrain(0.1, BladeMassMoment, 1e9); + + TipLossB = cnf_elem("tiplossfactor", 0.98, silent); + + estimate = 1.1 * BladeFlappingMoment * BladeNum; + PolarMoment = cnf_elem("polarmoment", estimate, "SLUG*FT2", silent); + PolarMoment = Constrain(0.1, PolarMoment, 1e9); + + InflowLag = cnf_elem("inflowlag", 0.2, silent); // fixme, depends on size + + estimate = (xmain) ? 0.0 : -0.06; + ShaftTilt = cnf_elem("shafttilt", estimate, "RAD", silent); + + // ignore differences between teeter/hingeless/fully-articulated constructions + estimate = 0.05 * Radius; + HingeOffset = cnf_elem("hingeoffset", estimate, "FT", (xmain) ? silent : yell); + + CantAngleD3 = cnf_elem("cantangle", 0.0, "RAD", silent); + + // derived parameters + + // precalc often used powers + R[0]=1.0; R[1]=Radius; R[2]=R[1]*R[1]; R[3]=R[2]*R[1]; R[4]=R[3]*R[1]; + B[0]=1.0; B[1]=TipLossB; B[2]=B[1]*B[1]; B[3]=B[2]*B[1]; B[4]=B[3]*B[1]; B[5]=B[4]*B[1]; + + LockNumberByRho = LiftCurveSlope * BladeChord * R[4] / BladeFlappingMoment; + solidity = BladeNum * BladeChord / (M_PI * Radius); + + // use simple orientations at the moment + if (flags & eTail) { // axis parallel to Y_body + theta_shaft = 0.0; // no tilt + phi_shaft = 0.5*M_PI; + + // opposite direction if main rotor is spinning CW + if (xmain && (xmain->flags & eRotCW) ) { + phi_shaft = -phi_shaft; + } + } else { // more or less upright + theta_shaft = ShaftTilt; + phi_shaft = 0.0; + } + + // setup Shaft-Body transforms, see /SH79/ eqn(17,18) + double st = sin(theta_shaft); + double ct = cos(theta_shaft); + double sp = sin(phi_shaft); + double cp = cos(phi_shaft); + + ShaftToBody.InitMatrix( ct, st*sp, st*cp, + 0.0, cp, -sp, + -st, ct*sp, ct*cp ); + + BodyToShaft = ShaftToBody.Inverse(); + + // misc defaults + nu = 0.001; // help the flow solver by providing some moving molecules + + return; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// calculate control-axes components of total airspeed at the hub. +// sets rotor orientation angle (beta) as side effect. /SH79/ eqn(19-22) + +FGColumnVector3 FGRotor::rotor::hub_vel_body2ca( const FGColumnVector3 &uvw, + const FGColumnVector3 &pqr, + double a_ic, double b_ic) +{ + + FGColumnVector3 v_r, v_shaft, v_w; + FGColumnVector3 pos(RelDistance_xhub,0.0,RelHeight_zhub); + + v_r = uvw + pqr*pos; + v_shaft = BodyToShaft * v_r; + + beta_orient = atan2(v_shaft(eV),v_shaft(eU)); + + v_w(eU) = v_shaft(eU)*cos(beta_orient) + v_shaft(eV)*sin(beta_orient); + v_w(eV) = 0.0; + v_w(eW) = v_shaft(eW) - b_ic*v_shaft(eU) - a_ic*v_shaft(eV); + + return v_w; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// express fuselage angular velocity in control axes /SH79/ eqn(30,31) + +FGColumnVector3 FGRotor::rotor::fus_angvel_body2ca( const FGColumnVector3 &pqr) +{ + FGColumnVector3 av_s_fus, av_w_fus; + + av_s_fus = BodyToShaft * pqr; + + av_w_fus(eP)= av_s_fus(eP)*cos(beta_orient) + av_s_fus(eQ)*sin(beta_orient); + av_w_fus(eQ)= - av_s_fus(eP)*sin(beta_orient) + av_s_fus(eQ)*cos(beta_orient); + av_w_fus(eR)= av_s_fus(eR); + + return av_w_fus; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// problem function passed to rk solver + + double FGRotor::rotor::dnuFunction::pFunc(double x, double nu) { + double d_nu; + d_nu = k_sat * (ct_lambda * (k_wor - nu) + k_theta) / + (2.0 * sqrt( mu2 + sqr(k_wor - nu)) ); + d_nu = d_nu * k_flowscale - nu; + return d_nu; + }; + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + + // merge params to keep the equation short + void FGRotor::rotor::dnuFunction::update_params(rotor *r, double ct_t01, double fs, double w) { + k_sat = 0.5* r->solidity * r->LiftCurveSlope; + ct_lambda = 1.0/2.0*r->B[2] + 1.0/4.0 * r->mu*r->mu; + k_wor = w/(r->Omega*r->Radius); + k_theta = ct_t01; + mu2 = r->mu * r->mu; + k_flowscale = fs; + }; + + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// Calculate rotor thrust and inflow-ratio (lambda), this is achieved by +// approximating a solution for the differential equation: +// +// dnu/dt = 1/tau ( Ct / (2*sqrt(mu^2+lambda^2)) - nu ) , /SH79/ eqn(26). +// +// Propper calculation of the inflow-ratio (lambda) is vital for the +// following calculations. Simple implementations (i.e. Newton-Raphson w/o +// checking) tend to oscillate or overshoot in the low speed region, +// therefore a more expensive solver is used. +// +// The flow_scale parameter is used to approximate a reduction of inflow +// if the helicopter is close to the ground, yielding to higher thrust, +// see /TA77/ eqn(10a). Doing the ground effect calculation here seems +// more favorable then to code it in the fdm_config. + +void FGRotor::rotor::calc_flow_and_thrust( + double dt, double rho, double theta_0, + double Uw, double Ww, double flow_scale) +{ + + double ct_over_sigma = 0.0; + double ct_l, ct_t0, ct_t1; + double nu_ret = 0.0; + + mu = Uw/(Omega*Radius); // /SH79/ eqn(24) + + ct_t0 = (1.0/3.0*B[3] + 1.0/2.0 * TipLossB*mu*mu - 4.0/(9.0*M_PI) * mu*mu*mu )*theta_0; + ct_t1 = (1.0/4.0*B[4] + 1.0/4.0 * B[2]*mu*mu)*BladeTwist; + + // merge params together + flowEquation.update_params(this, ct_t0+ct_t1, flow_scale, Ww); + + nu_ret = rk.evolve(nu, &flowEquation); + + if (rk.getStatus() != FGRungeKutta::eNoError) { // never observed so far + cerr << "# IEHHHH [" << flags << "]: Solver Error - resetting!" << endl; + rk.clearStatus(); + nu_ret = nu; // use old value and keep fingers crossed. + } + + // keep an eye on the solver, but be quiet after a hundred messages + if (reports < 100 && rk.getIterations()>6) { + cerr << "# LOOK [" << flags << "]: Solver took " + << rk.getIterations() << " rounds." << endl; + reports++; + if (reports==100) { + cerr << "# stopped babbling after 100 notifications." << endl; + } + } + + // now from nu to lambda, Ct, and Thrust + + nu = nu_ret; + lambda = Ww/(Omega*Radius) - nu; // /SH79/ eqn(25) + + ct_l = (1.0/2.0*B[2] + 1.0/4.0 * mu*mu)*lambda; + ct_over_sigma = (LiftCurveSlope/2.0)*(ct_l + ct_t0 + ct_t1); // /SH79/ eqn(27) + + Thrust = BladeNum*BladeChord*Radius*rho*sqr(Omega*Radius) * ct_over_sigma; + + Ct = ct_over_sigma * solidity; + v_induced = nu * (Omega*Radius); + + if (dump_req && (flags & eMain) ) { + printf("# mu %f : nu %f lambda %f vi %f\n", mu, nu, lambda, v_induced); + } + +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// this is the most arcane part in the calculation chain the +// constants used should be reverted to more general parameters. +// otoh: it works also for smaller rotors, sigh! +// See /SH79/ eqn(36), and /BA41/ for a richer set of equations. + +void FGRotor::rotor::calc_torque(double rho, double theta_0) +{ + double Qa0; + double cq_s_m[5], cq_over_sigma; + double l,m,t075; // shortcuts + + t075 = theta_0 + 0.75 * BladeTwist; + + m = mu; + l = lambda; + + cq_s_m[0] = 0.00109 - 0.0036*l - 0.0027*t075 - 1.10*sqr(l) - 0.545*l*t075 + 0.122*sqr(t075); + cq_s_m[2] = ( 0.00109 - 0.0027*t075 - 3.13*sqr(l) - 6.35*l*t075 - 1.93*sqr(t075) ) * sqr(m); + cq_s_m[3] = - 0.133*l*t075 * sqr(m)*m; + cq_s_m[4] = ( - 0.976*sqr(l) - 6.38*l*t075 - 5.26*sqr(t075) ) * sqr(m)*sqr(m); + + cq_over_sigma = cq_s_m[0] + cq_s_m[2] + cq_s_m[3] + cq_s_m[4]; + // guess an a (LiftCurveSlope) is included in eqn above, so check if there is a large + // influence when a_'other-model'/ a_'ch54' diverts from 1.0. + + Qa0 = BladeNum * BladeChord * R[2] * rho * sqr(Omega*Radius); + +// TODO: figure out how to handle negative cq_over_sigma/torque + + Torque = Qa0 * cq_over_sigma; + + return; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// The coning angle doesn't apply for teetering rotors, but calculating +// doesn't hurt. /SH79/ eqn(29) + +void FGRotor::rotor::calc_coning_angle(double rho, double theta_0) +{ + double lock_gamma = LockNumberByRho * rho; + + double a0_l = (1.0/6.0 * B[3] + 0.04 * mu*mu*mu) * lambda; + double a0_t0 = (1.0/8.0 * B[4] + 1.0/8.0 * B[2]*mu*mu) * theta_0; + double a0_t1 = (1.0/10.0 * B[5] + 1.0/12.0 * B[3]*mu*mu) * BladeTwist; + a0 = lock_gamma * ( a0_l + a0_t0 + a0_t1); + return; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// Flapping angles relative to control axes /SH79/ eqn(32) + +void FGRotor::rotor::calc_flapping_angles( double rho, double theta_0, + const FGColumnVector3 &pqr_fus_w) +{ + double lock_gamma = LockNumberByRho * rho; + + double mu2_2B2 = sqr(mu)/(2.0*B[2]); + double t075 = theta_0 + 0.75 * BladeTwist; // common approximation for rectangular blades + + a_1 = 1.0/(1.0 - mu2_2B2) * ( + (2.0*lambda + (8.0/3.0)*t075)*mu + + pqr_fus_w(eP)/Omega + - 16.0 * pqr_fus_w(eQ)/(B[4]*lock_gamma*Omega) + ); + + b_1 = 1.0/(1.0 + mu2_2B2) * ( + (4.0/3.0)*mu*a0 + - pqr_fus_w(eQ)/Omega + - 16.0 * pqr_fus_w(eP)/(B[4]*lock_gamma*Omega) + ); + + // used in force calc + a_dw = 1.0/(1.0 - mu2_2B2) * ( + (2.0*lambda + (8.0/3.0)*t075)*mu + - 24.0 * pqr_fus_w(eQ)/(B[4]*lock_gamma*Omega) + * ( 1.0 - ( 0.29 * t075 / (Ct/solidity) ) ) + ); + + return; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// /SH79/ eqn(38,39) + +void FGRotor::rotor::calc_drag_and_side_forces(double rho, double theta_0) +{ + double cy_over_sigma ; + double t075 = theta_0 + 0.75 * BladeTwist; + + H_drag = Thrust * a_dw; + + cy_over_sigma = ( + 0.75*b_1*lambda - 1.5*a0*mu*lambda + 0.25*a_1*b_1*mu + - a0*a_1*sqr(mu) + (1.0/6.0)*a0*a_1 + - (0.75*mu*a0 - (1.0/3.0)*b_1 - 0.5*sqr(mu)*b_1)*t075 + ); + cy_over_sigma *= LiftCurveSlope/2.0; + + J_side = BladeNum * BladeChord * Radius * rho * sqr(Omega*Radius) * cy_over_sigma; + + return; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// transform rotor forces from control axes to shaft axes, and express +// in body axes /SH79/ eqn(40,41) + +FGColumnVector3 FGRotor::rotor::body_forces(double a_ic, double b_ic) +{ + FGColumnVector3 F_s( + - H_drag*cos(beta_orient) - J_side*sin(beta_orient) + Thrust*b_ic, + - H_drag*sin(beta_orient) + J_side*cos(beta_orient) + Thrust*a_ic, + - Thrust); + + if (dump_req && (flags & eMain) ) { + printf("# abß: % f % f % f\n", a_ic, b_ic, beta_orient ); + printf("# HJT: % .2f % .2f % .2f\n", H_drag, J_side, Thrust ); + printf("# F_s: % .2f % .2f % .2f\n", F_s(1), F_s(2), F_s(3) ); + FGColumnVector3 F_h; + F_h = ShaftToBody * F_s; + printf("# F_h: % .2f % .2f % .2f\n", F_h(1), F_h(2), F_h(3) ); + } + + return ShaftToBody * F_s; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// rotational sense is handled here +// still a todo: how to get propper values for 'BladeMassMoment' +// here might be a good place to tweak hovering stability, check /AM50/. + +FGColumnVector3 FGRotor::rotor::body_moments(FGColumnVector3 F_h, double a_ic, double b_ic) +{ + FGColumnVector3 M_s, M_hub, M_h; + + FGColumnVector3 h_pos(RelDistance_xhub, 0.0, RelHeight_zhub); + + // vermutlich ein biege moment, bzw.widerstands moment ~ d^3 + double M_w_tilde = 0.0 ; + double mf = 0.0 ; + + M_w_tilde = BladeMassMoment; + + // cyclic flapping relative to shaft axes /SH79/ eqn(43) + a1s = a_1*cos(beta_orient) + b_1*sin(beta_orient) - b_ic; + b1s = b_1*cos(beta_orient) - a_1*sin(beta_orient) + a_ic; + + // mind this: no HingeOffset, no additional pitch/roll moments + mf = 0.5 * (HingeOffset+HingeOffset_hover) * BladeNum * Omega*Omega * M_w_tilde; + M_s(eL) = mf*b1s; + M_s(eM) = mf*a1s; + M_s(eN) = Torque; + + if (flags & eRotCW) { + M_s(eN) = -M_s(eN); + } + + if (flags & eCoaxial) { + M_s(eN) = 0.0; + } + + M_hub = ShaftToBody * M_s; + + M_h = M_hub + (h_pos * F_h); + + return M_h; } + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// Constructor + +FGRotor::FGRotor(FGFDMExec *exec, Element* rotor_element, int num) + : FGThruster(exec, rotor_element, num) +{ + + FGColumnVector3 location, orientation; + Element *thruster_element; + + PropertyManager = fdmex->GetPropertyManager(); + dt = fdmex->GetDeltaT(); + + /* apply defaults */ + + rho = 0.002356; // just a sane value + + RPM = 0.0; + Sense = 1.0; + tailRotorPresent = false; + + effective_tail_col = 0.001; // just a sane value + + prop_inflow_ratio_lambda = 0.0; + prop_advance_ratio_mu = 0.0; + prop_inflow_ratio_induced_nu = 0.0; + prop_mr_torque = 0.0; + prop_thrust_coefficient = 0.0; + prop_coning_angle = 0.0; + + prop_theta_downwash = prop_phi_downwash = 0.0; + + hover_threshold = 0.0; + hover_scale = 0.0; + + mr.zero(); + tr.zero(); + + // debug stuff + prop_DumpFlag = 0; + + /* configure */ + + Type = ttRotor; + SetTransformType(FGForce::tCustom); + + // get data from parent and 'mount' the rotor system + + thruster_element = rotor_element->GetParent()->FindElement("sense"); + if (thruster_element) { + Sense = thruster_element->GetDataAsNumber() >= 0.0 ? 1.0: -1.0; + } + + thruster_element = rotor_element->GetParent()->FindElement("location"); + if (thruster_element) location = thruster_element->FindElementTripletConvertTo("IN"); + else cerr << "No thruster location found." << endl; + + thruster_element = rotor_element->GetParent()->FindElement("orient"); + if (thruster_element) orientation = thruster_element->FindElementTripletConvertTo("RAD"); + else cerr << "No thruster orientation found." << endl; + + SetLocation(location); + SetAnglesToBody(orientation); + + // get main rotor parameters + mr.parent = rotor_element; + + int flags = eMain; + + string a_val=""; + a_val = rotor_element->GetAttributeValue("variant"); + if ( a_val == "coaxial" ) { + flags += eCoaxial; + cerr << "# found 'coaxial' variant" << endl; + } + + if (Sense<0.0) { + flags += eRotCW; + } + + mr.configure(flags); + + mr.rk.init(0,dt,6); + + // get tail rotor parameters + tr.parent=rotor_element->FindElement("tailrotor"); + if (tr.parent) { + tailRotorPresent = true; + } else { + tailRotorPresent = false; + cerr << "# No tailrotor found, assuming a single rotor." << endl; + } + + if (tailRotorPresent) { + int flags = eTail; + if (Sense<0.0) { + flags += eRotCW; + } + tr.configure(flags, &mr); + tr.rk.init(0,dt,6); + tr.RpmRatio = tr.NominalRPM/mr.NominalRPM; // 'connect' + } + + /* remaining parameters */ + + // ground effect + double c_ground_effect = 0.0; // uh1 ~ 0.28 , larger values increase the effect + ground_effect_exp = 0.0; + ground_effect_shift = 0.0; + + if (rotor_element->FindElement("cgroundeffect")) + c_ground_effect = rotor_element->FindElementValueAsNumber("cgroundeffect"); + + if (rotor_element->FindElement("groundeffectshift")) + ground_effect_shift = rotor_element->FindElementValueAsNumberConvertTo("groundeffectshift","FT"); + + // prepare calculations, see /TA77/ + if (c_ground_effect > 1e-5) { + ground_effect_exp = 1.0 / ( 2.0*mr.Radius * c_ground_effect ); + } else { + ground_effect_exp = 0.0; // disable + } + + // smooth out jumps in hagl reported, otherwise the ground effect + // calculation would cause jumps too. 1Hz seems sufficient. + damp_hagl = Filter(1.0,dt); + + + // misc, experimental + if (rotor_element->FindElement("hoverthreshold")) + hover_threshold = rotor_element->FindElementValueAsNumberConvertTo("hoverthreshold", "FT/SEC"); + + if (rotor_element->FindElement("hoverscale")) + hover_scale = rotor_element->FindElementValueAsNumber("hoverscale"); + + // enable import-export + bind(); + + // unused right now + prop_rotorbrake->setDoubleValue(0.0); + prop_freewheel_factor->setDoubleValue(1.0); + + Debug(0); + +} // Constructor + //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGRotor::~FGRotor() @@ -65,23 +766,295 @@ FGRotor::~FGRotor() //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +// mea-culpa - the connection to the engine might be wrong, but the calling +// convention appears to be 'variable' too. +// piston call: +// return Thruster->Calculate((Eng_HP * hptoftlbssec)-Thruster->GetPowerRequired()); +// turbine call: +// Thrust = Thruster->Calculate(Thrust); // allow thruster to modify thrust (i.e. reversing) +// +// Here 'Calculate' takes thrust and estimates the power provided. + double FGRotor::Calculate(double PowerAvailable) { - return 0.0; + // controls + double A_IC; // lateral (roll) control in radians + double B_IC; // longitudinal (pitch) control in radians + double theta_col; // main rotor collective pitch in radians + double tail_col; // tail rotor collective in radians + + // state + double h_agl_ft = 0.0; + double Vt ; + + FGColumnVector3 UVW_h; + FGColumnVector3 PQR_h; + + /* total vehicle velocity including wind effects in feet per second. */ + Vt = fdmex->GetAuxiliary()->GetVt(); + + dt = fdmex->GetDeltaT(); // might be variable ? + + dump_req = prop_DumpFlag; + prop_DumpFlag = 0; + + // fetch often used values + rho = fdmex->GetAtmosphere()->GetDensity(); // slugs/ft^3. + + UVW_h = fdmex->GetAuxiliary()->GetAeroUVW(); + PQR_h = fdmex->GetAuxiliary()->GetAeroPQR(); + + // handle present RPM now, calc omega values. + + if (RPM < mr.MinRPM) { // kludge, otherwise calculations go bananas + RPM = mr.MinRPM; + } + + mr.ActualRPM = RPM; + mr.Omega = (RPM/60.0)*2.0*M_PI; + + if (tailRotorPresent) { + tr.ActualRPM = RPM*tr.RpmRatio; + tr.Omega = (RPM*tr.RpmRatio/60.0)*2.0*M_PI; + } + + // read control inputs + + A_IC = prop_lateral_ctrl->getDoubleValue(); + B_IC = prop_longitudinal_ctrl->getDoubleValue(); + theta_col = prop_collective_ctrl->getDoubleValue(); + tail_col = 0.0; + if (tailRotorPresent) { + tail_col = prop_antitorque_ctrl->getDoubleValue(); + } + + + FGColumnVector3 vHub_ca = mr.hub_vel_body2ca(UVW_h,PQR_h,A_IC,B_IC); + FGColumnVector3 avFus_ca = mr.fus_angvel_body2ca(PQR_h); + + + h_agl_ft = fdmex->GetPropagate()->GetDistanceAGL(); + + double filtered_hagl; + filtered_hagl = damp_hagl.execute( h_agl_ft + ground_effect_shift ); + + // gnuplot> plot [-1:50] 1 - exp((-x/44)/.28) + double ge_factor = 1.0; + if (ground_effect_exp > 1e-5) { + ge_factor -= exp(-filtered_hagl*ground_effect_exp); + } + // clamp + if (ge_factor<0.5) ge_factor=0.5; + + if (dump_req) { + printf("# GE h: %.3f (%.3f) f: %f\n", filtered_hagl, h_agl_ft + ground_effect_shift, ge_factor); + } + + + // EXPERIMENTAL: modify rotor for hover, see rotor::body_moments for the consequences + if (hover_threshold > 1e-5 && Vt < hover_threshold) { + double scale = 1.0 - Vt/hover_threshold; + mr.HingeOffset_hover = scale*hover_scale*mr.Radius; + } else { + mr.HingeOffset_hover = 0.0; + } + + // all set, start calculations + + /* MAIN ROTOR */ + + mr.calc_flow_and_thrust(dt, rho, theta_col, vHub_ca(eU), vHub_ca(eW), ge_factor); + + prop_inflow_ratio_lambda = mr.lambda; + prop_advance_ratio_mu = mr.mu; + prop_inflow_ratio_induced_nu = mr.nu; + prop_thrust_coefficient = mr.Ct; + + mr.calc_coning_angle(rho, theta_col); + prop_coning_angle = mr.a0; + + mr.calc_torque(rho, theta_col); + prop_mr_torque = mr.Torque; + + mr.calc_flapping_angles(rho, theta_col, avFus_ca); + mr.calc_drag_and_side_forces(rho, theta_col); + + FGColumnVector3 F_h_mr = mr.body_forces(A_IC,B_IC); + FGColumnVector3 M_h_mr = mr.body_moments(F_h_mr, A_IC, B_IC); + + // export downwash angles + // theta: positive for downwash moving from +z_h towards +x_h + // phi: positive for downwash moving from +z_h towards -y_h + + prop_theta_downwash = atan2( - UVW_h(eU), mr.v_induced - UVW_h(eW)); + prop_phi_downwash = atan2( UVW_h(eV), mr.v_induced - UVW_h(eW)); + + mr.force(eX) = F_h_mr(1); + mr.force(eY) = F_h_mr(2); + mr.force(eZ) = F_h_mr(3); + + mr.moment(eL) = M_h_mr(1); + mr.moment(eM) = M_h_mr(2); + mr.moment(eN) = M_h_mr(3); + + /* TAIL ROTOR */ + + FGColumnVector3 F_h_tr(0.0, 0.0, 0.0); + FGColumnVector3 M_h_tr(0.0, 0.0, 0.0); + + if (tailRotorPresent) { + FGColumnVector3 vHub_ca_tr = tr.hub_vel_body2ca(UVW_h,PQR_h); + FGColumnVector3 avFus_ca_tr = tr.fus_angvel_body2ca(PQR_h); + + tr.calc_flow_and_thrust(dt, rho, tail_col, vHub_ca_tr(eU), vHub_ca_tr(eW)); + tr.calc_coning_angle(rho, tail_col); + + // test code for cantered tail rotor, see if it has a notable effect. /SH79/ eqn(47) + if (fabs(tr.CantAngleD3)>1e-5) { + double tan_d3 = tan(tr.CantAngleD3); + double d_t0t; + double ca_dt = dt/12.0; + for (int i = 0; i<12; i++) { + d_t0t = 1/0.1*(tail_col - tr.a0 * tan_d3 - effective_tail_col); + effective_tail_col += d_t0t*ca_dt; + } + } else { + effective_tail_col = tail_col; + } + + tr.calc_torque(rho, effective_tail_col); + tr.calc_flapping_angles(rho, effective_tail_col, avFus_ca_tr); + tr.calc_drag_and_side_forces(rho, effective_tail_col); + + F_h_tr = tr.body_forces(); + M_h_tr = tr.body_moments(F_h_tr); + } + + tr.force(eX) = F_h_tr(1) ; + tr.force(eY) = F_h_tr(2) ; + tr.force(eZ) = F_h_tr(3) ; + tr.moment(eL) = M_h_tr(1) ; + tr.moment(eM) = M_h_tr(2) ; + tr.moment(eN) = M_h_tr(3) ; + +/* + TODO: + check negative mr.Torque conditions + freewheel factor: assure [0..1] just multiply with available power + rotorbrake: just steal from available power + +*/ + + // calculate new RPM, assuming a stiff connection between engine and rotor. + + double engine_hp = PowerAvailable/2.24; // 'undo' force via the estimation factor used in aeromatic + double engine_torque = 550.0*engine_hp/mr.Omega; + double Omega_dot = (engine_torque - mr.Torque) / mr.PolarMoment; + + RPM += ( Omega_dot * dt )/(2.0*M_PI) * 60.0; + + if (0 && dump_req) { + printf("# SENSE : % d % d\n", mr.flags & eRotCW ? -1 : 1, tr.flags & eRotCW ? -1 : 1); + printf("# vi : % f % f\n", mr.v_induced, tr.v_induced); + printf("# a0 a1 b1 : % f % f % f\n", mr.a0, mr.a_1, mr.b_1 ); + printf("# m forces : % f % f % f\n", mr.force(eX), mr.force(eY), mr.force(eZ) ); + printf("# m moments : % f % f % f\n", mr.moment(eL), mr.moment(eM), mr.moment(eN) ); + printf("# t forces : % f % f % f\n", tr.force(eX), tr.force(eY), tr.force(eZ) ); + printf("# t moments : % f % f % f\n", tr.moment(eL), tr.moment(eM), tr.moment(eN) ); + } + + // finally set vFn & vMn + vFn = mr.force + tr.force; + vMn = mr.moment + tr.moment; + + // and just lie here + Thrust = 0.0; + + // return unmodified thrust to the turbine. + // :TK: As far as I can see the return value is unused. + return PowerAvailable; + +} // Calculate + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// FGThruster does return 0.0 (the implicit direct thruster) +// piston CALL: return Thruster->Calculate((Eng_HP * hptoftlbssec)-Thruster->GetPowerRequired()); + +double FGRotor::GetPowerRequired(void) +{ + PowerRequired = 0.0; + return PowerRequired; +} + +//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +bool FGRotor::bind(void) { + + string property_name, base_property_name; + base_property_name = CreateIndexedPropertyName("propulsion/engine", EngineNum); + + PropertyManager->Tie( base_property_name + "/rotor-rpm", this, &FGRotor::GetRPM ); + PropertyManager->Tie( base_property_name + "/thrust-mr-lbs", &mr.Thrust ); + PropertyManager->Tie( base_property_name + "/vi-mr-fps", &mr.v_induced ); + PropertyManager->Tie( base_property_name + "/a0-mr-rad", &mr.a0 ); + PropertyManager->Tie( base_property_name + "/a1-mr-rad", &mr.a1s ); // s means shaft axes + PropertyManager->Tie( base_property_name + "/b1-mr-rad", &mr.b1s ); + PropertyManager->Tie( base_property_name + "/thrust-tr-lbs", &tr.Thrust ); + PropertyManager->Tie( base_property_name + "/vi-tr-fps", &tr.v_induced ); + + // lambda + PropertyManager->Tie( base_property_name + "/inflow-ratio", &prop_inflow_ratio_lambda ); + // mu + PropertyManager->Tie( base_property_name + "/advance-ratio", &prop_advance_ratio_mu ); + // nu + PropertyManager->Tie( base_property_name + "/induced-inflow-ratio", &prop_inflow_ratio_induced_nu ); + + PropertyManager->Tie( base_property_name + "/torque-mr-lbsft", &prop_mr_torque ); + PropertyManager->Tie( base_property_name + "/thrust-coefficient", &prop_thrust_coefficient ); + PropertyManager->Tie( base_property_name + "/main-rotor-rpm", &mr.ActualRPM ); + PropertyManager->Tie( base_property_name + "/tail-rotor-rpm", &tr.ActualRPM ); + + // position of the downwash + PropertyManager->Tie( base_property_name + "/theta-downwash-rad", &prop_theta_downwash ); + PropertyManager->Tie( base_property_name + "/phi-downwash-rad", &prop_phi_downwash ); + + // nodes to use via getValue + prop_collective_ctrl = PropertyManager->GetNode(base_property_name + "/collective-ctrl-rad",true); + prop_lateral_ctrl = PropertyManager->GetNode(base_property_name + "/lateral-ctrl-rad",true); + prop_longitudinal_ctrl = PropertyManager->GetNode(base_property_name + "/longitudinal-ctrl-rad",true); + prop_antitorque_ctrl = PropertyManager->GetNode(base_property_name + "/antitorque-ctrl-rad",true); + + prop_rotorbrake = PropertyManager->GetNode(base_property_name + "/rotorbrake-hp", true); + prop_freewheel_factor = PropertyManager->GetNode(base_property_name + "/freewheel-factor", true); + + PropertyManager->Tie( base_property_name + "/dump-flag", &prop_DumpFlag ); + + return true; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGRotor::GetThrusterLabels(int id, string delimeter) { - return ""; + + std::ostringstream buf; + + buf << Name << " RPM (engine " << id << ")"; + + return buf.str(); + } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% string FGRotor::GetThrusterValues(int id, string delimeter) { - return ""; + std::ostringstream buf; + + buf << RPM; + + return buf.str(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -109,7 +1082,7 @@ void FGRotor::Debug(int from) if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor - + cout << "\n Rotor Name: " << Name << endl; } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification @@ -129,4 +1102,6 @@ void FGRotor::Debug(int from) } } } -} + +} // namespace JSBSim + diff --git a/src/FDM/JSBSim/models/propulsion/FGRotor.h b/src/FDM/JSBSim/models/propulsion/FGRotor.h index 6188f40d9..0663fba46 100644 --- a/src/FDM/JSBSim/models/propulsion/FGRotor.h +++ b/src/FDM/JSBSim/models/propulsion/FGRotor.h @@ -1,10 +1,10 @@ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Header: FGRotor.h - Author: Jon S. Berndt + Author: T. Kreitler Date started: 08/24/00 - ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) ------------- + ------------- Copyright (C) 2010 T. Kreitler ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software @@ -25,7 +25,7 @@ HISTORY -------------------------------------------------------------------------------- -08/24/00 JSB Created +01/01/10 T.Kreitler test implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SENTRY @@ -39,12 +39,14 @@ INCLUDES %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ #include "FGThruster.h" +#include "math/FGTable.h" +#include "math/FGRungeKutta.h" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_ROTOR "$Id$" +#define ID_ROTOR "$Id: FGRotor.h,v 1.6 2010/06/02 04:05:13 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -56,7 +58,145 @@ namespace JSBSim { CLASS DOCUMENTATION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -/** Models a rotor (such as for a helicopter); NOT YET IMPLEMENTED. +/** Models a rotor system. The default configuration consists of main and + tail rotor. A practical way to define the positions is to start with an + imaginary gear-box near the cg of the vehicle. + + In this case the location in the thruster definition should be + approximately equal to the cg defined in the fdm_config/mass_balance + section. If the default orientation (roll=pitch=yaw=0) is used the + positions of the rotor hubs are now defined relative to the location + of the thruster (i.e. the cg-centered body coordinate system). + + +

Configuration File Format:

+@code + + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + {number} + + {number} + {number} + + +// LENGTH means any of the supported units, same for ANGLE and MOMENT. +// Xunit-attributes are a hint for currently unsupported units, so +// values must be provided accordingly. + +@endcode + +

Configuration Parameters:

+ + Brief description and the symbol frequently found in the literature. + +
+    \           - Rotor disk diameter (R).
+    \          - Number of blades (b).
+    \               - Relative height in body coordinate system, thus usually negative.
+    \               - Relative distance in body coordinate system, close to zero 
+                             for main rotor, and usually negative for the tail rotor. 
+    \         - RPM at which the rotor usally operates. 
+    \             - Lowest RPM generated by the code, optional.
+    \              - Blade chord, (c).
+    \     - Slope of curve of section lift against section angle of attack,
+                             per rad (a).
+    \     - Flapping moment of inertia (I_b).
+    \              - Blade twist from root to tip, (theta_1).
+    \         - Blade mass moment. (Biege/Widerstands-moment)
+    \      - Tip-loss factor. The Blade fraction that produces lift.
+                              Value usually ranges between 0.95 - 1.0, optional (B).
+    \        - Moment of inertia for the whole rotor disk, optional.
+    \          - Rotor inflow time constant, sec.
+    \          - Orientation of the rotor shaft, negative angles define
+                              a 'forward' tilt. Used by main rotor, optional.
+    \        - Rotor flapping-hinge offset (e).
+    
+    Experimental properties
+    
+    \          - Flapping hinge cantangle used by tail rotor, optional.
+    \      - Parameter for exponent in ground effect approximation. Value should
+                              be in the range 0.2 - 0.35, 0.0 disables, optional.
+    \  - Further adjustment of ground effect. 
+
+
+ +

Notes:

+ + The behavior of the rotor is controlled/influenced by 5 inputs.
    +
  • The power provided by the engine. This is handled by the regular engine controls.
  • +
  • The collective control input. This is read from the fdm property + propulsion/engine[x]/collective-ctrl-rad.
  • +
  • The lateral cyclic input. Read from + propulsion/engine[x]/lateral-ctrl-rad.
  • +
  • The longitudinal cyclic input. Read from + propulsion/engine[x]/longitudinal-ctrl-rad.
  • +
  • The tail collective (aka antitorque, aka pedal) control input. Read from + propulsion/engine[x]/antitorque-ctrl-rad.
  • + +
+ + In order to keep the rotor speed constant, use of a RPM-Governor system is encouraged. + + It is possible to use different orientation/locations for the rotor system, but then xhub + and zhub are no longer aligned to the body frame and need proper recalculation. + + To model a standalone main rotor just omit the element. If you provide + a plain element all tail rotor parameters are estimated. + + The 'sense' parameter from the thruster is interpreted as follows, sense=1 means + counter clockwise rotation of the main rotor, as viewed from above. This is as a far + as I know more popular than clockwise rotation, which is defined by setting sense to + -1 (to be honest, I'm just 99.9% sure that the orientation is handled properly). + + Concerning coaxial designs: By providing the 'variant' attribute with value 'coaxial' + a Kamov-style rotor is modeled - i.e. the rotor produces no torque. + + +

References:

+ +
+
/SH79/
Shaugnessy, J. D., Deaux, Thomas N., and Yenni, Kenneth R., + "Development and Validation of a Piloted Simulation of a + Helicopter and External Sling Load", NASA TP-1285, 1979.
+
/BA41/
Bailey,F.J.,Jr., "A Simplified Theoretical Method of Determining + the Characteristics of a Lifting Rotor in Forward Flight", NACA Rep.716, 1941.
+
/AM50/
Amer, Kenneth B.,"Theory of Helicopter Damping in Pitch or Roll and a + Comparison With Flight Measurements", NACA TN-2136, 1950.
+
/TA77/
Talbot, Peter D., Corliss, Lloyd D., "A Mathematical Force and Moment + Model of a UH-1H Helicopter for Flight Dynamics Simulations", NASA TM-73,254, 1977.
+
+ + @author Thomas Kreitler + @version $Id: FGRotor.h,v 1.6 2010/06/02 04:05:13 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -65,18 +205,197 @@ CLASS DECLARATION class FGRotor : public FGThruster { + enum eRotorFlags {eNone=0, eMain=1, eTail=2, eCoaxial=4, eRotCW=8} ; + struct rotor { + + virtual ~rotor(); + void zero(); + void configure(int f, const rotor *xmain = NULL); + + // assist in parameter retrieval + double cnf_elem(const string& ename, double default_val=0.0, const string& unit = "", bool tell=false); + double cnf_elem(const string& ename, double default_val=0.0, bool tell=false); + + // rotor dynamics + void calc_flow_and_thrust(double dt, double rho, double theta_0, double Uw, double Ww, double flow_scale = 1.0); + + void calc_torque(double rho, double theta_0); + void calc_coning_angle(double rho, double theta_0); + void calc_flapping_angles(double rho, double theta_0, const FGColumnVector3 &pqr_fus_w); + void calc_drag_and_side_forces(double rho, double theta_0); + + // transformations + FGColumnVector3 hub_vel_body2ca( const FGColumnVector3 &uvw, const FGColumnVector3 &pqr, + double a_ic = 0.0 , double b_ic = 0.0 ); + FGColumnVector3 fus_angvel_body2ca( const FGColumnVector3 &pqr); + + FGColumnVector3 body_forces(double a_ic = 0.0 , double b_ic = 0.0 ); + FGColumnVector3 body_moments(FGColumnVector3 F_h, double a_ic = 0.0 , double b_ic = 0.0 ); + + // bookkeeping + int flags ; + Element *parent ; + + // used in flow calculation + // FGRK4 rk ; // use this after checking + FGRKFehlberg rk ; + int reports ; + + // configuration parameters + double Radius ; + int BladeNum ; + double RelDistance_xhub ; + double RelShift_yhub ; + double RelHeight_zhub ; + double NominalRPM ; + double MinRPM ; + double BladeChord ; + double LiftCurveSlope ; + double BladeFlappingMoment ; + double BladeTwist ; + double BladeMassMoment ; + double TipLossB ; + double PolarMoment ; + double InflowLag ; + double ShaftTilt ; + double HingeOffset ; + double HingeOffset_hover ; + double CantAngleD3 ; + + double theta_shaft ; + double phi_shaft ; + + // derived parameters + double LockNumberByRho ; + double solidity ; // aka sigma + double RpmRatio ; // main_to_tail, hmm + double R[5] ; // Radius powers + double B[6] ; // TipLossB powers + + FGMatrix33 BodyToShaft ; // [S]T, see /SH79/ eqn(17,18) + FGMatrix33 ShaftToBody ; // [S] + + // dynamic values + double ActualRPM ; + double Omega ; // must be > 0 + double beta_orient ; + double a0 ; // coning angle (rad) + double a_1, b_1, a_dw ; + double a1s, b1s ; // cyclic flapping relative to shaft axes, /SH79/ eqn(43) + double H_drag, J_side ; + + double Torque ; + double Thrust ; + double Ct ; + double lambda ; // inflow ratio + double mu ; // tip-speed ratio + double nu ; // induced inflow ratio + double v_induced ; // always positive [ft/s] + + // results + FGColumnVector3 force ; + FGColumnVector3 moment ; + + + // declare the problem function + class dnuFunction : public FGRungeKuttaProblem { + public: + void update_params(rotor *r, double ct_t01, double fs, double w); + private: + double pFunc(double x, double y); + // some shortcuts + double k_sat, ct_lambda, k_wor, k_theta, mu2, k_flowscale; + } flowEquation; + + + }; + + public: - /// Constructor - FGRotor(FGFDMExec *FDMExec, Element* rotor_element, int num); + /** Constructor + @param exec pointer to executive structure + @param rotor_element pointer to XML element in the config file + @param num the number of this rotor */ + FGRotor(FGFDMExec *exec, Element* rotor_element, int num); + /// Destructor ~FGRotor(); + void SetRPM(double rpm) {RPM = rpm;} + + /** Calculates forces and moments created by the rotor(s) and updates + vFn,vMn state variables. RPM changes are handled inside, too. + The RPM change is based on estimating the torque provided by the engine. + + @param PowerAvailable here this is the thrust (not power) provided by a turbine + @return PowerAvailable */ double Calculate(double); + + double GetRPM(void) const { return RPM; } + double GetDiameter(void) { return mr.Radius*2.0; } + + // Stubs. Right now this rotor-to-engine interface is just a hack. + double GetTorque(void) { return 0.0; /* return mr.Torque;*/ } + double GetPowerRequired(void); + + // Stubs. Only main rotor RPM is returned string GetThrusterLabels(int id, string delimeter); string GetThrusterValues(int id, string delimeter); private: + + bool bind(void); + + double RPM; + double Sense; // default is counter clockwise rotation of the main rotor (viewed from above) + bool tailRotorPresent; + void Debug(int from); + + FGPropertyManager* PropertyManager; + + rotor mr; + rotor tr; + + Filter damp_hagl; + + double rho; + + double effective_tail_col; // /SH79/ eqn(47) + + double ground_effect_exp; + double ground_effect_shift; + + double hover_threshold; + double hover_scale; + + // fdm imported controls + FGPropertyManager* prop_collective_ctrl; + FGPropertyManager* prop_lateral_ctrl; + FGPropertyManager* prop_longitudinal_ctrl; + FGPropertyManager* prop_antitorque_ctrl; + + FGPropertyManager* prop_freewheel_factor; + FGPropertyManager* prop_rotorbrake; + + // fdm export ... + double prop_inflow_ratio_lambda; + double prop_advance_ratio_mu; + double prop_inflow_ratio_induced_nu; + double prop_mr_torque; + double prop_coning_angle; + + double prop_theta_downwash; + double prop_phi_downwash; + + double prop_thrust_coefficient; + double prop_lift_coefficient; + + double dt; // deltaT doesn't do the thing + + // devel/debug stuff + int prop_DumpFlag; // causes 1-time dump on stdout + }; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGTank.cpp b/src/FDM/JSBSim/models/propulsion/FGTank.cpp index f05831b73..c9d38dab8 100644 --- a/src/FDM/JSBSim/models/propulsion/FGTank.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGTank.cpp @@ -48,7 +48,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGTank.cpp,v 1.28 2010/01/24 19:26:04 jberndt Exp $"; static const char *IdHdr = ID_TANK; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -66,6 +66,7 @@ FGTank::FGTank(FGFDMExec* exec, Element* el, int tank_number) InitialTemperature = Temperature = -9999.0; Ixx = Iyy = Izz = 0.0; Radius = Contents = Standpipe = Length = InnerRadius = 0.0; + InitialStandpipe = 0.0; Capacity = 0.00001; Priority = InitialPriority = 1; PropertyManager = Exec->GetPropertyManager(); diff --git a/src/FDM/JSBSim/models/propulsion/FGTank.h b/src/FDM/JSBSim/models/propulsion/FGTank.h index 55930543f..12e7e5fc9 100644 --- a/src/FDM/JSBSim/models/propulsion/FGTank.h +++ b/src/FDM/JSBSim/models/propulsion/FGTank.h @@ -52,7 +52,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_TANK "$Id$" +#define ID_TANK "$Id: FGTank.h,v 1.21 2010/02/05 05:53:00 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -195,6 +195,9 @@ public: /// Destructor ~FGTank(); + enum TankType {ttUNKNOWN, ttFUEL, ttOXIDIZER}; + enum GrainType {gtUNKNOWN, gtCYLINDRICAL, gtENDBURNING}; + /** Removes fuel from the tank. This function removes fuel from a tank. If the tank empties, it is deselected. @@ -275,6 +278,8 @@ public: const FGColumnVector3 GetXYZ(void); const double GetXYZ(int idx); + const GrainType GetGrainType(void) {return grainType;} + double Fill(double amount); void SetContents(double amount); void SetContentsGallons(double gallons); @@ -282,9 +287,6 @@ public: void SetStandpipe(double amount) { Standpipe = amount; } void SetSelected(bool sel) { sel==true ? SetPriority(1):SetPriority(0); } - enum TankType {ttUNKNOWN, ttFUEL, ttOXIDIZER}; - enum GrainType {gtUNKNOWN, gtCYLINDRICAL, gtENDBURNING}; - private: TankType Type; GrainType grainType; diff --git a/src/FDM/JSBSim/models/propulsion/FGThruster.cpp b/src/FDM/JSBSim/models/propulsion/FGThruster.cpp index 32a508ee1..064177a2b 100644 --- a/src/FDM/JSBSim/models/propulsion/FGThruster.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGThruster.cpp @@ -45,7 +45,7 @@ using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGThruster.cpp,v 1.12 2009/10/24 22:59:30 jberndt Exp $"; static const char *IdHdr = ID_THRUSTER; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGThruster.h b/src/FDM/JSBSim/models/propulsion/FGThruster.h index 886b678dc..118005f5a 100644 --- a/src/FDM/JSBSim/models/propulsion/FGThruster.h +++ b/src/FDM/JSBSim/models/propulsion/FGThruster.h @@ -46,7 +46,7 @@ INCLUDES DEFINITIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ -#define ID_THRUSTER "$Id$" +#define ID_THRUSTER "$Id: FGThruster.h,v 1.15 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -74,7 +74,7 @@ CLASS DOCUMENTATION 1.57 (pi/2) results in no thrust at all. @author Jon Berndt - @version $Id$ + @version $Id: FGThruster.h,v 1.15 2009/10/24 22:59:30 jberndt Exp $ */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGTurbine.cpp b/src/FDM/JSBSim/models/propulsion/FGTurbine.cpp index b690d72f0..c61667b4b 100644 --- a/src/FDM/JSBSim/models/propulsion/FGTurbine.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGTurbine.cpp @@ -42,15 +42,16 @@ INCLUDES #include #include #include "FGTurbine.h" -#include "FGState.h" -#include "models/FGPropulsion.h" #include "FGThruster.h" +#include "models/FGPropulsion.h" +#include "models/FGAuxiliary.h" +#include "models/FGAtmosphere.h" using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGTurbine.cpp,v 1.27 2010/05/24 11:26:37 jberndt Exp $"; static const char *IdHdr = ID_TURBINE; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -118,7 +119,7 @@ double FGTurbine::Calculate(void) TAT = (Auxiliary->GetTotalTemperature() - 491.69) * 0.5555556; double qbar = Auxiliary->Getqbar(); - dt = State->Getdt() * Propulsion->GetRate(); + dt = FDMExec->GetDeltaT() * Propulsion->GetRate(); ThrottlePos = FCS->GetThrottlePos(EngineNumber); if (ThrottlePos > 1.0) { AugmentCmd = ThrottlePos - 1.0; @@ -145,7 +146,7 @@ double FGTurbine::Calculate(void) if (!Running && Cutoff && Starter) { if (phase == tpOff) phase = tpSpinUp; - } + } // start if ((Starter == true) || (qbar > 30.0)) { @@ -223,7 +224,7 @@ double FGTurbine::Run() if (!Augmentation) { correctedTSFC = TSFC * sqrt(T/389.7) * (0.84 + (1-N2norm)*(1-N2norm)); - FuelFlow_pph = Seek(&FuelFlow_pph, thrust * correctedTSFC, 1000.0, 100000); + FuelFlow_pph = Seek(&FuelFlow_pph, thrust * correctedTSFC, 1000.0, 10000.0); if (FuelFlow_pph < IdleFF) FuelFlow_pph = IdleFF; NozzlePosition = Seek(&NozzlePosition, 1.0 - N2norm, 0.8, 0.8); thrust = thrust * (1.0 - BleedDemand); @@ -388,7 +389,7 @@ double FGTurbine::Trim() double FGTurbine::CalcFuelNeed(void) { - double dT = State->Getdt() * Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT() * Propulsion->GetRate(); FuelFlowRate = FuelFlow_pph / 3600.0; // Calculates flow in lbs/sec from lbs/hr FuelExpended = FuelFlowRate * dT; // Calculates fuel expended in this time step return FuelExpended; @@ -539,12 +540,12 @@ void FGTurbine::bindmodel() //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% int FGTurbine::InitRunning(void) { - State->SuspendIntegration(); + FDMExec->SuspendIntegration(); Cutoff=false; Running=true; N2=IdleN2; Calculate(); - State->ResumeIntegration(); + FDMExec->ResumeIntegration(); return phase==tpRun; } diff --git a/src/FDM/JSBSim/models/propulsion/FGTurbine.h b/src/FDM/JSBSim/models/propulsion/FGTurbine.h index 9eebc335d..1fff92c67 100644 --- a/src/FDM/JSBSim/models/propulsion/FGTurbine.h +++ b/src/FDM/JSBSim/models/propulsion/FGTurbine.h @@ -42,7 +42,7 @@ INCLUDES #include "FGEngine.h" -#define ID_TURBINE "$Id$" +#define ID_TURBINE "$Id: FGTurbine.h,v 1.18 2009/10/24 22:59:30 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS @@ -146,7 +146,7 @@ CLASS DOCUMENTATION /engine/direct.xml @author David P. Culp - @version "$Id$" + @version "$Id: FGTurbine.h,v 1.18 2009/10/24 22:59:30 jberndt Exp $" */ /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% diff --git a/src/FDM/JSBSim/models/propulsion/FGTurboProp.cpp b/src/FDM/JSBSim/models/propulsion/FGTurboProp.cpp index 9ebef96df..f384877fc 100755 --- a/src/FDM/JSBSim/models/propulsion/FGTurboProp.cpp +++ b/src/FDM/JSBSim/models/propulsion/FGTurboProp.cpp @@ -44,16 +44,15 @@ INCLUDES #include #include #include "FGTurboProp.h" - #include "FGPropeller.h" -#include "FGState.h" +#include "models/FGPropulsion.h" #include "models/FGAuxiliary.h" using namespace std; namespace JSBSim { -static const char *IdSrc = "$Id$"; +static const char *IdSrc = "$Id: FGTurboProp.cpp,v 1.16 2010/02/25 05:21:36 jberndt Exp $"; static const char *IdHdr = ID_TURBOPROP; /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -162,7 +161,7 @@ bool FGTurboProp::Load(FGFDMExec* exec, Element *el) double FGTurboProp::Calculate(void) { TAT = (Auxiliary->GetTotalTemperature() - 491.69) * 0.5555556; - dt = State->Getdt() * Propulsion->GetRate(); + dt = FDMExec->GetDeltaT() * Propulsion->GetRate(); ThrottleCmd = FCS->GetThrottleCmd(EngineNumber); @@ -406,7 +405,7 @@ double FGTurboProp::Start(void) double FGTurboProp::CalcFuelNeed(void) { - double dT = State->Getdt() * Propulsion->GetRate(); + double dT = FDMExec->GetDeltaT() * Propulsion->GetRate(); FuelFlowRate = FuelFlow_pph / 3600.0; FuelExpended = FuelFlowRate * dT; return FuelExpended; @@ -505,12 +504,12 @@ string FGTurboProp::GetEngineValues(const string& delimiter) int FGTurboProp::InitRunning(void) { - State->SuspendIntegration(); + FDMExec->SuspendIntegration(); Cutoff=false; Running=true; N2=16.0; Calculate(); - State->ResumeIntegration(); + FDMExec->ResumeIntegration(); return phase==tpRun; } diff --git a/src/FDM/JSBSim/models/propulsion/FGTurboProp.h b/src/FDM/JSBSim/models/propulsion/FGTurboProp.h index cb10f85b9..66febb191 100755 --- a/src/FDM/JSBSim/models/propulsion/FGTurboProp.h +++ b/src/FDM/JSBSim/models/propulsion/FGTurboProp.h @@ -46,7 +46,7 @@ INCLUDES #include "input_output/FGXMLElement.h" #include "math/FGTable.h" -#define ID_TURBOPROP "$Id$" +#define ID_TURBOPROP "$Id: FGTurboProp.h,v 1.11 2009/10/26 03:48:42 jberndt Exp $" /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FORWARD DECLARATIONS diff --git a/src/FDM/LaRCsim/LaRCsim.cxx b/src/FDM/LaRCsim/LaRCsim.cxx index 611849dff..850532f34 100644 --- a/src/FDM/LaRCsim/LaRCsim.cxx +++ b/src/FDM/LaRCsim/LaRCsim.cxx @@ -31,7 +31,6 @@ #include #include -#include #include #include #include diff --git a/src/FDM/Makefile.am b/src/FDM/Makefile.am index 04e9ff8f4..e1e764c82 100644 --- a/src/FDM/Makefile.am +++ b/src/FDM/Makefile.am @@ -11,8 +11,10 @@ noinst_LIBRARIES = libFlight.a libFlight_a_SOURCES = \ flight.cxx flight.hxx \ + fdm_shell.cxx fdm_shell.hxx \ + flightProperties.cxx flightProperties.hxx \ groundcache.cxx groundcache.hxx \ UFO.cxx UFO.hxx \ NullFDM.cxx NullFDM.hxx -INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src +INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src -I$(top_srcdir)/src/FDM/JSBSim diff --git a/src/FDM/SP/ADA.cxx b/src/FDM/SP/ADA.cxx index 9aaa468fa..7585b428a 100644 --- a/src/FDM/SP/ADA.cxx +++ b/src/FDM/SP/ADA.cxx @@ -22,6 +22,8 @@ # include #endif +#include + #include #include #include @@ -261,14 +263,15 @@ bool FGADA::copy_from_FGADA() { _set_Velocities_Local( V_north, V_east, V_down ); //same as UVW_local in fps //Positions and attitude for ship - _set_daux(1,sixdof_to_visuals.aux1);//ship lat - _set_daux(2,sixdof_to_visuals.aux2);//ship lon - _set_daux(3,sixdof_to_visuals.aux3);//ship alt+heave - _set_daux(4,sixdof_to_visuals.aux4);//distance of a/c from ski-jump exit - _set_faux(1,sixdof_to_visuals.aux9);//ship pitch - _set_faux(2,sixdof_to_visuals.aux10);//ship roll - _set_faux(3,sixdof_to_visuals.aux11);//ship yaw - _set_iaux(1,sixdof_to_visuals.iaux1);//flag for drawing ship + + fgSetDouble("/fdm-ada/ship-lat", sixdof_to_visuals.aux1); + fgSetDouble("/fdm-ada/ship-lon", sixdof_to_visuals.aux2); + fgSetDouble("/fdm-ada/ship-alt", sixdof_to_visuals.aux3); + fgSetDouble("/fdm-ada/skijump-dist", sixdof_to_visuals.aux4); + fgSetDouble("/fdm-ada/ship-pitch", sixdof_to_visuals.aux9); // faux1 + fgSetDouble("/fdm-ada/ship-roll", sixdof_to_visuals.aux10); // faux2 + fgSetDouble("/fdm-ada/ship-yaw", sixdof_to_visuals.aux11); // faux3 + fgSetInt("/fdm-ada/draw-ship", sixdof_to_visuals.iaux1); // controls globals->get_controls()->set_throttle(0,throttle/131.0); @@ -284,30 +287,30 @@ bool FGADA::copy_from_FGADA() { _set_Mach_number( Machno); _set_Climb_Rate( W_local*SG_METER_TO_FEET ); //pressure alt in feet for lca(navy) - _set_iaux(2,sixdof_to_visuals.iaux2);//control law mode switch posn - _set_iaux(3,sixdof_to_visuals.iaux3);//ldg gear posn - _set_iaux(4,sixdof_to_visuals.iaux4);// wow nose status - _set_iaux(5,sixdof_to_visuals.iaux5);// wow main status - _set_iaux(6,sixdof_to_visuals.iaux6);// arrester hook posn - _set_iaux(7,sixdof_to_visuals.iaux7); - _set_iaux(8,sixdof_to_visuals.iaux8); - _set_iaux(9,sixdof_to_visuals.iaux9); - _set_iaux(10,sixdof_to_visuals.iaux10); - _set_iaux(11,sixdof_to_visuals.iaux11); - _set_iaux(12,sixdof_to_visuals.iaux12); - - _set_daux(5,sixdof_to_visuals.aux5); - _set_daux(6,sixdof_to_visuals.aux6); - _set_daux(7,sixdof_to_visuals.aux7); - _set_daux(8,sixdof_to_visuals.aux8); - - _set_faux(4,sixdof_to_visuals.aux12); - _set_faux(5,sixdof_to_visuals.aux13); - _set_faux(6,sixdof_to_visuals.aux14); - _set_faux(7,sixdof_to_visuals.aux15); - _set_faux(8,sixdof_to_visuals.aux16); - _set_faux(9,sixdof_to_visuals.aux17); - _set_faux(10,sixdof_to_visuals.aux18); + fgSetInt("/fdm-ada/iaux2", sixdof_to_visuals.iaux2); //control law mode switch posn + fgSetInt("/fdm-ada/iaux3", sixdof_to_visuals.iaux3); //ldg gear posn + fgSetInt("/fdm-ada/iaux4", sixdof_to_visuals.iaux4); // wow nose status + fgSetInt("/fdm-ada/iaux5", sixdof_to_visuals.iaux5); // wow main status + fgSetInt("/fdm-ada/iaux6", sixdof_to_visuals.iaux6); // arrester hook posn + fgSetInt("/fdm-ada/iaux7", sixdof_to_visuals.iaux7); + fgSetInt("/fdm-ada/iaux8", sixdof_to_visuals.iaux8); + fgSetInt("/fdm-ada/iaux9", sixdof_to_visuals.iaux9); + fgSetInt("/fdm-ada/iaux10", sixdof_to_visuals.iaux10); + fgSetInt("/fdm-ada/iaux11", sixdof_to_visuals.iaux11); + fgSetInt("/fdm-ada/iaux12", sixdof_to_visuals.iaux12); + + fgSetDouble("/fdm-ada/aux5", sixdof_to_visuals.aux5); + fgSetDouble("/fdm-ada/aux6", sixdof_to_visuals.aux6); + fgSetDouble("/fdm-ada/aux7", sixdof_to_visuals.aux7); + fgSetDouble("/fdm-ada/aux8", sixdof_to_visuals.aux8); + + fgSetDouble("/fdm-ada/aux12", sixdof_to_visuals.aux12); + fgSetDouble("/fdm-ada/aux13", sixdof_to_visuals.aux13); + fgSetDouble("/fdm-ada/aux14", sixdof_to_visuals.aux14); + fgSetDouble("/fdm-ada/aux15", sixdof_to_visuals.aux15); + fgSetDouble("/fdm-ada/aux16", sixdof_to_visuals.aux16); + fgSetDouble("/fdm-ada/aux17", sixdof_to_visuals.aux17); + fgSetDouble("/fdm-ada/aux18", sixdof_to_visuals.aux18); // Angular rates _set_Omega_Body( P_body, Q_body, R_body ); diff --git a/src/FDM/SP/BalloonSim.cpp b/src/FDM/SP/BalloonSim.cpp index 264d49b37..add046cac 100644 --- a/src/FDM/SP/BalloonSim.cpp +++ b/src/FDM/SP/BalloonSim.cpp @@ -48,8 +48,6 @@ HISTORY #include -#include - #include "BalloonSim.h" /****************************************************************************/ diff --git a/src/FDM/SP/MagicCarpet.cxx b/src/FDM/SP/MagicCarpet.cxx index 44bffd0ef..822c1aa89 100644 --- a/src/FDM/SP/MagicCarpet.cxx +++ b/src/FDM/SP/MagicCarpet.cxx @@ -115,4 +115,5 @@ void FGMagicCarpet::update( double dt ) { _update_ground_elev_at_pos(); _set_Sea_level_radius( sl_radius * SG_METER_TO_FEET); _set_Altitude( get_Altitude() + climb ); + _set_Altitude_AGL( get_Altitude() - get_Runway_altitude() ); } diff --git a/src/FDM/UIUCModel/uiuc_gear.cpp b/src/FDM/UIUCModel/uiuc_gear.cpp index da120d29f..31a87d0b9 100644 --- a/src/FDM/UIUCModel/uiuc_gear.cpp +++ b/src/FDM/UIUCModel/uiuc_gear.cpp @@ -67,7 +67,6 @@ #include #include -#include #include
#include "uiuc_gear.h" diff --git a/src/FDM/UIUCModel/uiuc_recorder.cpp b/src/FDM/UIUCModel/uiuc_recorder.cpp index 97e93b59c..3264ad184 100644 --- a/src/FDM/UIUCModel/uiuc_recorder.cpp +++ b/src/FDM/UIUCModel/uiuc_recorder.cpp @@ -94,7 +94,6 @@ #include #include -#include #include
#include "uiuc_recorder.h" diff --git a/src/FDM/UIUCModel/uiuc_wrapper.cpp b/src/FDM/UIUCModel/uiuc_wrapper.cpp index c11cbc97e..47897560e 100644 --- a/src/FDM/UIUCModel/uiuc_wrapper.cpp +++ b/src/FDM/UIUCModel/uiuc_wrapper.cpp @@ -83,10 +83,10 @@ #endif #include +#include #include #include -#include #include
#include "uiuc_aircraft.h" diff --git a/src/FDM/YASim/.gitignore b/src/FDM/YASim/.gitignore new file mode 100644 index 000000000..3608c84f7 --- /dev/null +++ b/src/FDM/YASim/.gitignore @@ -0,0 +1,2 @@ +proptest +yasim diff --git a/src/FDM/fdm_shell.cxx b/src/FDM/fdm_shell.cxx new file mode 100644 index 000000000..a4cfad309 --- /dev/null +++ b/src/FDM/fdm_shell.cxx @@ -0,0 +1,266 @@ +// fdm_shell.cxx -- encapsulate FDM implementations as well-behaved subsystems +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +#include +#include +#include +#include
+#include
+#include + +// all the FDMs, since we are the factory method +#if ENABLE_SP_FDM +#include +#include +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +/* + * Evil global variable required by Network/FGNative, + * see that class for more information + */ +FGInterface* evil_global_fdm_state = NULL; + +FDMShell::FDMShell() : + _impl(NULL), + _dataLogging(false) +{ +} + +FDMShell::~FDMShell() +{ + delete _impl; +} + +void FDMShell::init() +{ + _props = globals->get_props(); + fgSetBool("/sim/fdm-initialized", false); + createImplementation(); +} + +void FDMShell::reinit() +{ + if (_impl) { + fgSetBool("/sim/fdm-initialized", false); + evil_global_fdm_state = NULL; + _impl->unbind(); + delete _impl; + _impl = NULL; + } + + init(); +} + +void FDMShell::bind() +{ + if (_impl && _impl->get_inited()) { + if (_impl->get_bound()) { + throw sg_exception("FDMShell::bind of bound FGInterface impl"); + } + + _impl->bind(); + } +} + +void FDMShell::unbind() +{ + if( _impl ) _impl->unbind(); +} + +void FDMShell::update(double dt) +{ + if (!_impl) { + return; + } + + if (!_impl->get_inited()) { + // Check for scenery around the aircraft. + double lon = fgGetDouble("/sim/presets/longitude-deg"); + double lat = fgGetDouble("/sim/presets/latitude-deg"); + + double range = 1000.0; // in metres + SGGeod geod = SGGeod::fromDeg(lon, lat); + if (globals->get_scenery()->scenery_available(geod, range)) { + SG_LOG(SG_FLIGHT, SG_INFO, "Scenery loaded, will init FDM"); + _impl->init(); + if (_impl->get_bound()) { + _impl->unbind(); + } + _impl->bind(); + + evil_global_fdm_state = _impl; + fgSetBool("/sim/fdm-initialized", true); + fgSetBool("/sim/signals/fdm-initialized", true); + } + } + + if (!_impl->get_inited()) { + return; // still waiting + } + +// pull environmental data in, since the FDMs are lazy + _impl->set_Velocities_Local_Airmass( + _props->getDoubleValue("environment/wind-from-north-fps", 0.0), + _props->getDoubleValue("environment/wind-from-east-fps", 0.0), + _props->getDoubleValue("environment/wind-from-down-fps", 0.0)); + + if (_props->getBoolValue("environment/params/control-fdm-atmosphere")) { + // convert from Rankine to Celsius + double tempDegC = _props->getDoubleValue("environment/temperature-degc"); + _impl->set_Static_temperature((9.0/5.0) * (tempDegC + 273.15)); + + // convert from inHG to PSF + double pressureInHg = _props->getDoubleValue("environment/pressure-inhg"); + _impl->set_Static_pressure(pressureInHg * 70.726566); + // keep in slugs/ft^3 + _impl->set_Density(_props->getDoubleValue("environment/density-slugft3")); + } + + bool doLog = _props->getBoolValue("/sim/temp/fdm-data-logging", false); + if (doLog != _dataLogging) { + _dataLogging = doLog; + _impl->ToggleDataLogging(doLog); + } + +// FIXME - replay manager should handle most of this + int replayState = fgGetInt("/sim/freeze/replay-state", 0); + if (replayState == 0) { + _impl->update(dt); // normal code path + } else if (replayState == 1) { + // should be inside FGReplay! + SGPropertyNode* replay_time = fgGetNode("/sim/replay/time", true); + FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" )); + r->replay( replay_time->getDoubleValue() ); + replay_time->setDoubleValue( replay_time->getDoubleValue() + + ( dt + * fgGetInt("/sim/speed-up") ) ); + + } else if (replayState == 2) { + // paused replay, no-op + } else { + throw sg_range_exception("unknown FGReplay state"); + } +} + +void FDMShell::createImplementation() +{ + assert(!_impl); + + double dt = 1.0 / fgGetInt("/sim/model-hz"); + string model = fgGetString("/sim/flight-model"); + + if ( model == "larcsim" ) { + _impl = new FGLaRCsim( dt ); + } else if ( model == "jsb" ) { + _impl = new FGJSBsim( dt ); +#if ENABLE_SP_FDM + } else if ( model == "ada" ) { + _impl = new FGADA( dt ); + } else if ( model == "acms" ) { + _impl = new FGACMS( dt ); + } else if ( model == "balloon" ) { + _impl = new FGBalloonSim( dt ); + } else if ( model == "magic" ) { + _impl = new FGMagicCarpet( dt ); +#endif + } else if ( model == "ufo" ) { + _impl = new FGUFO( dt ); + } else if ( model == "external" ) { + // external is a synonym for "--fdm=null" and is + // maintained here for backwards compatibility + _impl = new FGNullFDM( dt ); + } else if ( model.find("network") == 0 ) { + string host = "localhost"; + int port1 = 5501; + int port2 = 5502; + int port3 = 5503; + string net_options = model.substr(8); + string::size_type begin, end; + begin = 0; + // host + end = net_options.find( ",", begin ); + if ( end != string::npos ) { + host = net_options.substr(begin, end - begin); + begin = end + 1; + } + // port1 + end = net_options.find( ",", begin ); + if ( end != string::npos ) { + port1 = atoi( net_options.substr(begin, end - begin).c_str() ); + begin = end + 1; + } + // port2 + end = net_options.find( ",", begin ); + if ( end != string::npos ) { + port2 = atoi( net_options.substr(begin, end - begin).c_str() ); + begin = end + 1; + } + // port3 + end = net_options.find( ",", begin ); + if ( end != string::npos ) { + port3 = atoi( net_options.substr(begin, end - begin).c_str() ); + begin = end + 1; + } + _impl = new FGExternalNet( dt, host, port1, port2, port3 ); + } else if ( model.find("pipe") == 0 ) { + // /* old */ string pipe_path = model.substr(5); + // /* old */ _impl = new FGExternalPipe( dt, pipe_path ); + string pipe_path = ""; + string pipe_protocol = ""; + string pipe_options = model.substr(5); + string::size_type begin, end; + begin = 0; + // pipe file path + end = pipe_options.find( ",", begin ); + if ( end != string::npos ) { + pipe_path = pipe_options.substr(begin, end - begin); + begin = end + 1; + } + // protocol (last option) + pipe_protocol = pipe_options.substr(begin); + _impl = new FGExternalPipe( dt, pipe_path, pipe_protocol ); + } else if ( model == "null" ) { + _impl = new FGNullFDM( dt ); + } else if ( model == "yasim" ) { + _impl = new YASim( dt ); + } else { + throw sg_exception(string("Unrecognized flight model '") + model + + "', cannot init flight dynamics model."); + } + +} + diff --git a/src/FDM/fdm_shell.hxx b/src/FDM/fdm_shell.hxx new file mode 100644 index 000000000..be0b1f859 --- /dev/null +++ b/src/FDM/fdm_shell.hxx @@ -0,0 +1,62 @@ +// fdm_shell.hxx -- encapsulate FDM implementations as well-behaved subsystems +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#ifndef FG_FDM_SHELL_HXX +#define FG_FDM_SHELL_HXX + +#include + +// forward decls +class FGInterface; + +/** + * Wrap an FDM implementation in a subsystem with standard semantics + * Notably, deal with the various cases in which update() should not + * be called, such as replay or before scenery has loaded + * + * This class also provides the factory method which creates the + * specific FDM class (createImplementation) + */ +class FDMShell : public SGSubsystem +{ +public: + FDMShell(); + ~FDMShell(); + + virtual void init(); + virtual void reinit(); + + virtual void bind(); + virtual void unbind(); + + virtual void update(double dt); + +private: + + void createImplementation(); + + FGInterface* _impl; + SGPropertyNode* _props; // root property tree for this FDM instance + bool _dataLogging; +}; + +#endif // of FG_FDM_SHELL_HXX diff --git a/src/FDM/flight.cxx b/src/FDM/flight.cxx index 10ce9948a..5676e688b 100644 --- a/src/FDM/flight.cxx +++ b/src/FDM/flight.cxx @@ -44,8 +44,6 @@ static inline void assign(double* ptr, const SGVec3d& vec) ptr[2] = vec[2]; } -FGInterface *cur_fdm_state = 0; - // Constructor FGInterface::FGInterface() { @@ -253,7 +251,7 @@ FGInterface::bind () false); fgSetArchivable("/position/altitude-ft"); fgTie("/position/altitude-agl-ft", this, - &FGInterface::get_Altitude_AGL); // read-only + &FGInterface::get_Altitude_AGL, &FGInterface::set_AltitudeAGL); fgSetArchivable("/position/ground-elev-ft"); fgTie("/position/ground-elev-ft", this, &FGInterface::get_Runway_altitude); // read-only @@ -264,7 +262,8 @@ FGInterface::bind () &FGInterface::get_Runway_altitude_m); // read-only fgSetArchivable("/position/sea-level-radius-ft"); fgTie("/position/sea-level-radius-ft", this, - &FGInterface::get_Sea_level_radius); // read-only + &FGInterface::get_Sea_level_radius, + &FGInterface::_set_Sea_level_radius); // Orientation fgTie("/orientation/roll-deg", this, @@ -285,12 +284,16 @@ FGInterface::bind () // Body-axis "euler rates" (rotation speed, but in a funny // representation). fgTie("/orientation/roll-rate-degps", this, - &FGInterface::get_Phi_dot_degps); + &FGInterface::get_Phi_dot_degps, &FGInterface::set_Phi_dot_degps); fgTie("/orientation/pitch-rate-degps", this, - &FGInterface::get_Theta_dot_degps); + &FGInterface::get_Theta_dot_degps, &FGInterface::set_Theta_dot_degps); fgTie("/orientation/yaw-rate-degps", this, - &FGInterface::get_Psi_dot_degps); + &FGInterface::get_Psi_dot_degps, &FGInterface::set_Psi_dot_degps); + fgTie("/orientation/p-body", this, &FGInterface::get_P_body); + fgTie("/orientation/q-body", this, &FGInterface::get_Q_body); + fgTie("/orientation/r-body", this, &FGInterface::get_R_body); + // Ground speed knots fgTie("/velocities/groundspeed-kt", this, &FGInterface::get_V_ground_speed_kt); @@ -301,6 +304,9 @@ FGInterface::bind () &FGInterface::set_V_calibrated_kts, false); + fgTie("/velocities/equivalent-kt", this, + &FGInterface::get_V_equiv_kts); + // Mach number fgTie("/velocities/mach", this, &FGInterface::get_Mach_number, @@ -325,11 +331,19 @@ FGInterface::bind () // LaRCSim are fixed (LaRCSim adds the // earth's rotation to the east velocity). fgTie("/velocities/speed-north-fps", this, - &FGInterface::get_V_north); + &FGInterface::get_V_north, &FGInterface::set_V_north); fgTie("/velocities/speed-east-fps", this, - &FGInterface::get_V_east); + &FGInterface::get_V_east, &FGInterface::set_V_east); fgTie("/velocities/speed-down-fps", this, - &FGInterface::get_V_down); + &FGInterface::get_V_down, &FGInterface::set_V_down); + + fgTie("/velocities/north-relground-fps", this, + &FGInterface::get_V_north_rel_ground); + fgTie("/velocities/east-relground-fps", this, + &FGInterface::get_V_east_rel_ground); + fgTie("/velocities/down-relground-fps", this, + &FGInterface::get_V_down_rel_ground); + // Relative wind // FIXME: temporarily archivable, until @@ -358,11 +372,11 @@ FGInterface::bind () &FGInterface::get_Gamma_vert_rad, &FGInterface::set_Gamma_vert_rad ); fgTie("/orientation/side-slip-rad", this, - &FGInterface::get_Beta); // read-only + &FGInterface::get_Beta, &FGInterface::_set_Beta); fgTie("/orientation/side-slip-deg", this, &FGInterface::get_Beta_deg); // read-only fgTie("/orientation/alpha-deg", this, - &FGInterface::get_Alpha_deg); // read-only + &FGInterface::get_Alpha_deg, &FGInterface::set_Alpha_deg); // read-only fgTie("/accelerations/nlf", this, &FGInterface::get_Nlf); // read-only @@ -376,11 +390,13 @@ FGInterface::bind () // Pilot accelerations fgTie("/accelerations/pilot/x-accel-fps_sec", - this, &FGInterface::get_A_X_pilot); + this, &FGInterface::get_A_X_pilot, &FGInterface::set_A_X_pilot); fgTie("/accelerations/pilot/y-accel-fps_sec", - this, &FGInterface::get_A_Y_pilot); + this, &FGInterface::get_A_Y_pilot, &FGInterface::set_A_Y_pilot); fgTie("/accelerations/pilot/z-accel-fps_sec", - this, &FGInterface::get_A_Z_pilot); + this, &FGInterface::get_A_Z_pilot, &FGInterface::set_A_Z_pilot); + + fgTie("/accelerations/n-z-cg-fps_sec", this, &FGInterface::get_N_Z_cg); } @@ -394,6 +410,10 @@ FGInterface::bind () void FGInterface::unbind () { + if (!bound) { + return; + } + bound = false; fgUntie("/position/latitude-deg"); @@ -411,15 +431,22 @@ FGInterface::unbind () fgUntie("/orientation/roll-rate-degps"); fgUntie("/orientation/pitch-rate-degps"); fgUntie("/orientation/yaw-rate-degps"); + fgUntie("/orientation/p-body"); + fgUntie("/orientation/q-body"); + fgUntie("/orientation/r-body"); fgUntie("/orientation/side-slip-rad"); fgUntie("/orientation/side-slip-deg"); fgUntie("/orientation/alpha-deg"); fgUntie("/velocities/airspeed-kt"); fgUntie("/velocities/groundspeed-kt"); + fgUntie("/velocities/equivalent-kt"); fgUntie("/velocities/mach"); fgUntie("/velocities/speed-north-fps"); fgUntie("/velocities/speed-east-fps"); fgUntie("/velocities/speed-down-fps"); + fgUntie("/velocities/north-relground-fps"); + fgUntie("/velocities/east-relground-fps"); + fgUntie("/velocities/down-relground-fps"); fgUntie("/velocities/uBody-fps"); fgUntie("/velocities/vBody-fps"); fgUntie("/velocities/wBody-fps"); @@ -432,6 +459,7 @@ FGInterface::unbind () fgUntie("/accelerations/ned/north-accel-fps_sec"); fgUntie("/accelerations/ned/east-accel-fps_sec"); fgUntie("/accelerations/ned/down-accel-fps_sec"); + fgUntie("/accelerations/n-z-cg-fps_sec"); } /** @@ -893,6 +921,3 @@ FGInterface::release_wire(void) ground_cache.release_wire(); } -void fgToggleFDMdataLogging(void) { - cur_fdm_state->ToggleDataLogging(); -} diff --git a/src/FDM/flight.hxx b/src/FDM/flight.hxx index 222df3b54..6965d3098 100644 --- a/src/FDM/flight.hxx +++ b/src/FDM/flight.hxx @@ -187,13 +187,18 @@ private: double altitude_agl; double track; - double daux[16]; // auxilliary doubles - float faux[16]; // auxilliary floats - int iaux[16]; // auxilliary ints - // the ground cache object itself. FGGroundCache ground_cache; + void set_A_X_pilot(double x) + { _set_Accels_Pilot_Body(x, a_pilot_body_v[1], a_pilot_body_v[2]); } + + void set_A_Y_pilot(double y) + { _set_Accels_Pilot_Body(a_pilot_body_v[0], y, a_pilot_body_v[2]); } + + void set_A_Z_pilot(double z) + { _set_Accels_Pilot_Body(a_pilot_body_v[0], a_pilot_body_v[1], z); } + protected: int _calc_multiloop (double dt); @@ -284,6 +289,22 @@ public: euler_rates_v[1] = theta; euler_rates_v[2] = psi; } + + void set_Phi_dot_degps(double x) + { + euler_rates_v[0] = x * SG_DEGREES_TO_RADIANS; + } + + void set_Theta_dot_degps(double x) + { + euler_rates_v[1] = x * SG_DEGREES_TO_RADIANS; + } + + void set_Psi_dot_degps(double x) + { + euler_rates_v[2] = x * SG_DEGREES_TO_RADIANS; + } + inline void _set_Geocentric_Rates( double lat, double lon, double rad ) { geocentric_rates_v[0] = lat; geocentric_rates_v[1] = lon; @@ -328,6 +349,9 @@ public: inline void _set_T_Local_to_Body( int i, int j, double value) { } inline void _set_Alpha( double a ) { alpha = a; } inline void _set_Beta( double b ) { beta = b; } + + inline void set_Alpha_deg( double a ) { alpha = a * SG_DEGREES_TO_RADIANS; } + inline void _set_Gamma_vert_rad( double gv ) { gamma_vert_rad = gv; } inline void _set_Density( double d ) { density = d; } inline void _set_Mach_number( double m ) { mach_number = m; } @@ -339,10 +363,6 @@ public: inline void _set_Runway_altitude( double alt ) { runway_altitude = alt; } inline void _set_Climb_Rate(double rate) { climb_rate = rate; } - inline void _set_daux( int n, double value ) { daux[n] = value; } - inline void _set_faux( int n, float value ) { faux[n] = value; } - inline void _set_iaux( int n, int value ) { iaux[n] = value; } - public: FGInterface(); @@ -623,11 +643,6 @@ public: inline double get_Climb_Rate() const { return climb_rate; } - // Auxilliary variables - inline double get_daux( int n ) const { return daux[n]; } - inline float get_faux( int n ) const { return faux[n]; } - inline int get_iaux( int n ) const { return iaux[n]; } - // Note that currently this is the "same" value runway altitude... inline double get_ground_elev_ft() const { return runway_altitude; } @@ -712,10 +727,4 @@ public: void release_wire(void); }; -extern FGInterface * cur_fdm_state; - -// Toggle data logging on/off -void fgToggleFDMdataLogging(void); - - #endif // _FLIGHT_HXX diff --git a/src/FDM/flightProperties.cxx b/src/FDM/flightProperties.cxx new file mode 100644 index 000000000..aa4d3cc24 --- /dev/null +++ b/src/FDM/flightProperties.cxx @@ -0,0 +1,311 @@ +// flightProperties.cxx -- expose FDM properties via helper methods +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#include + +#include +#include + +#include
+ +FlightProperties::FlightProperties(SGPropertyNode* root) : + _root(root) +{ + if (!_root) { + _root = globals->get_props(); + } +} + +FlightProperties::~FlightProperties() +{ +} + +double FlightProperties::get_V_north() const +{ + return _root->getDoubleValue("velocities/speed-north-fps", 0.0); +} + +double FlightProperties::get_V_east() const +{ + return _root->getDoubleValue("velocities/speed-east-fps", 0.0); +} + +double FlightProperties::get_V_down() const +{ + return _root->getDoubleValue("velocities/speed-down-fps", 0.0); +} + +double FlightProperties::get_uBody () const +{ + return _root->getDoubleValue("velocities/uBody-fps", 0.0); +} + +double FlightProperties::get_vBody () const +{ + return _root->getDoubleValue("velocities/vBody-fps", 0.0); +} + +double FlightProperties::get_wBody () const +{ + return _root->getDoubleValue("velocities/wBody-fps", 0.0); +} + +double FlightProperties::get_A_X_pilot() const +{ + return _root->getDoubleValue("accelerations/pilot/x-accel-fps_sec", 0.0); +} + +double FlightProperties::get_A_Y_pilot() const +{ + return _root->getDoubleValue("/accelerations/pilot/y-accel-fps_sec", 0.0); +} + +double FlightProperties::get_A_Z_pilot() const +{ + return _root->getDoubleValue("/accelerations/pilot/z-accel-fps_sec", 0.0); +} + +SGGeod FlightProperties::getPosition() const +{ + return SGGeod::fromDegFt(get_Longitude_deg(), get_Latitude_deg(), get_Altitude()); +} + +double FlightProperties::get_Latitude() const +{ + return get_Latitude_deg() * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Longitude() const +{ + return get_Longitude_deg() * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Altitude() const +{ + return _root->getDoubleValue("position/altitude-ft"); +} + +double FlightProperties::get_Altitude_AGL(void) const +{ + return _root->getDoubleValue("position/altitude-agl-ft"); +} + +double FlightProperties::get_Latitude_deg () const +{ + return _root->getDoubleValue("position/latitude-deg"); +} + +double FlightProperties::get_Longitude_deg () const +{ + return _root->getDoubleValue("position/longitude-deg"); +} + +double FlightProperties::get_Track(void) const +{ + return _root->getDoubleValue("orientation/track-deg"); +} + +double FlightProperties::get_Phi_deg() const +{ + return _root->getDoubleValue("orientation/roll-deg"); +} + +double FlightProperties::get_Theta_deg() const +{ + return _root->getDoubleValue("orientation/pitch-deg"); +} + +double FlightProperties::get_Psi_deg() const +{ + return _root->getDoubleValue("orientation/heading-deg"); +} + +double FlightProperties::get_Phi_dot() const +{ + return get_Phi_dot_degps() * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Theta_dot() const +{ + return get_Theta_dot_degps() * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Psi_dot() const +{ + return get_Psi_dot_degps() * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Alpha() const +{ + return _root->getDoubleValue("orientation/alpha-deg") * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Beta() const +{ + return _root->getDoubleValue("orientation/beta-deg") * SG_DEGREES_TO_RADIANS; +} + +double FlightProperties::get_Phi_dot_degps() const +{ + return _root->getDoubleValue("orientation/roll-rate-degps"); +} + +double FlightProperties::get_Theta_dot_degps() const +{ + return _root->getDoubleValue("orientation/pitch-rate-degps"); +} + +double FlightProperties::get_Psi_dot_degps() const +{ + return _root->getDoubleValue("orientation/yaw-rate-degps"); +} + +double FlightProperties::get_Total_temperature() const +{ + return 0.0; +} + +double FlightProperties::get_Total_pressure() const +{ + return 0.0; +} + +double FlightProperties::get_Dynamic_pressure() const +{ + return 0.0; +} + +void FlightProperties::set_Longitude(double l) +{ + _root->setDoubleValue("position/longitude-deg", l * SG_RADIANS_TO_DEGREES); +} + +void FlightProperties::set_Latitude(double l) +{ + _root->setDoubleValue("position/latitude-deg", l * SG_RADIANS_TO_DEGREES); +} + +void FlightProperties::set_Altitude(double ft) +{ + _root->setDoubleValue("position/altitude-ft", ft); +} + +void FlightProperties::set_Euler_Angles(double phi, double theta, double psi) +{ + _root->setDoubleValue("orientation/roll-deg", phi * SG_RADIANS_TO_DEGREES); + _root->setDoubleValue("orientation/pitch-deg", theta * SG_RADIANS_TO_DEGREES); + _root->setDoubleValue("orientation/heading-deg", psi * SG_RADIANS_TO_DEGREES); +} + +void FlightProperties::set_V_calibrated_kts(double kts) +{ + _root->setDoubleValue("velocities/airspeed-kt", kts); +} + +void FlightProperties::set_Climb_Rate(double fps) +{ + _root->setDoubleValue("velocities/vertical-speed-fps", fps); +} + +double FlightProperties::get_V_ground_speed() const +{ + const double KNOTS_TO_FTS = (SG_NM_TO_METER * SG_METER_TO_FEET)/ 3600.0; + return _root->getDoubleValue("velocities/groundspeed-kt") * KNOTS_TO_FTS; +} + +double FlightProperties::get_V_calibrated_kts() const +{ + return _root->getDoubleValue("velocities/airspeed-kt"); +} + +double FlightProperties::get_V_equiv_kts() const +{ + return _root->getDoubleValue("velocities/equivalent-kt"); +} + +double FlightProperties::get_Climb_Rate() const +{ + return _root->getDoubleValue("velocities/vertical-speed-fps"); +} + +double FlightProperties::get_Runway_altitude_m() const +{ + return _root->getDoubleValue("environment/ground-elevation-m"); +} + +void FlightProperties::set_Accels_Pilot_Body(double x, double y, double z) +{ + _root->setDoubleValue("accelerations/pilot/x-accel-fps_sec", x); + _root->setDoubleValue("accelerations/pilot/y-accel-fps_sec", y); + _root->setDoubleValue("accelerations/pilot/z-accel-fps_sec", z); +} + +void FlightProperties::set_Velocities_Local(double x, double y, double z) +{ + _root->setDoubleValue("velocities/speed-north-fps", x); + _root->setDoubleValue("velocities/speed-east-fps", y); + _root->setDoubleValue("velocities/speed-down-fps", z); +} + +void FlightProperties::set_Velocities_Wind_Body(double x, double y, double z) +{ + _root->setDoubleValue("velocities/vBody-fps", x); + _root->setDoubleValue("velocities/uBody-fps", y); + _root->setDoubleValue("velocities/wBody-fps", z); +} + +void FlightProperties::set_Euler_Rates(double x, double y, double z) +{ + _root->setDoubleValue("orientation/roll-rate-degps", x * SG_RADIANS_TO_DEGREES); + _root->setDoubleValue("orientation/pitch-rate-degps", y * SG_RADIANS_TO_DEGREES); + _root->setDoubleValue("orientation/yaw-rate-degps", z * SG_RADIANS_TO_DEGREES); +} + +void FlightProperties::set_Alpha(double a) +{ + _root->setDoubleValue("orientation/alpha-deg", a * SG_RADIANS_TO_DEGREES); +} + +void FlightProperties::set_Beta(double b) +{ + _root->setDoubleValue("orientation/side-slip-rad", b); +} + +void FlightProperties::set_Altitude_AGL(double ft) +{ + _root->setDoubleValue("position/altitude-agl-ft", ft); +} + +double FlightProperties::get_P_body() const +{ + return _root->getDoubleValue("orientation/p-body", 0.0); +} + +double FlightProperties::get_Q_body() const +{ + return _root->getDoubleValue("orientation/q-body", 0.0); +} + +double FlightProperties::get_R_body() const +{ + return _root->getDoubleValue("orientation/r-body", 0.0); +} diff --git a/src/FDM/flightProperties.hxx b/src/FDM/flightProperties.hxx new file mode 100644 index 000000000..62a082e12 --- /dev/null +++ b/src/FDM/flightProperties.hxx @@ -0,0 +1,128 @@ +// flightProperties.hxx -- expose FDM properties via helper methods +// +// Written by James Turner, started June 2010. +// +// Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 2 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +// +// $Id$ + +#ifndef FG_FLIGHT_PROPERTIES_HXX +#define FG_FLIGHT_PROPERTIES_HXX + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include // for SGVec3d +#include + +// forward decls +class SGPropertyNode; +class SGGeoc; +class SGGeod; + +/** + * Encapsulate the FDM properties in some getter/setter helpers. + * This class intentionally mimics portions of + * @FGInterface, to permit easy migration of code outside the FDMs, + * to use properties instead of global variables. + */ +class FlightProperties +{ +public: + FlightProperties(SGPropertyNode* aRoot = NULL); + ~FlightProperties(); + + double get_V_north() const; + double get_V_east() const; + double get_V_down() const; + double get_uBody () const; + double get_vBody () const; + double get_wBody () const; + + double get_A_X_pilot() const; + double get_A_Y_pilot() const; + double get_A_Z_pilot() const; + + double get_P_body() const; + double get_Q_body() const; + double get_R_body() const; + + SGGeod getPosition() const; + + double get_Latitude() const; + double get_Longitude() const; + double get_Altitude() const; + + double get_Altitude_AGL(void) const; + double get_Track(void) const; + + double get_Latitude_deg () const; + double get_Longitude_deg () const; + + double get_Phi_deg() const; + double get_Theta_deg() const; + double get_Psi_deg() const; + + double get_Phi() const { return SGMiscd::deg2rad(get_Phi_deg()); } + double get_Theta() const { return SGMiscd::deg2rad(get_Theta_deg()); } + double get_Psi() const { return SGMiscd::deg2rad(get_Psi_deg()); } + + double get_Phi_dot() const; + double get_Theta_dot() const; + double get_Psi_dot() const; + double get_Alpha() const; + double get_Beta() const; + + double get_Phi_dot_degps() const; + double get_Theta_dot_degps() const; + double get_Psi_dot_degps() const; + + double get_V_ground_speed() const; // in feet/s + double get_V_equiv_kts() const; + double get_V_calibrated_kts() const; + double get_Climb_Rate() const; + double get_Runway_altitude_m() const; + + double get_Total_temperature() const; + double get_Total_pressure() const; + double get_Dynamic_pressure() const; + + void set_Longitude(double l); // radians + void set_Latitude(double l); // radians + void set_Altitude(double ft); // feet + + void set_Euler_Angles(double phi, double theta, double psi); + void set_Euler_Rates(double x, double y, double z); + + void set_Alpha(double a); + void set_Beta(double b); + + void set_Altitude_AGL(double ft); + + void set_V_calibrated_kts(double kts); + void set_Climb_Rate(double fps); + + void set_Velocities_Local(double x, double y, double z); + void set_Velocities_Wind_Body(double x, double y, double z); + void set_Accels_Pilot_Body(double x, double y, double z); +private: + SGPropertyNode* _root; +}; + +#endif // of FG_FLIGHT_PROPERTIES_HXX diff --git a/src/GUI/.gitignore b/src/GUI/.gitignore new file mode 100644 index 000000000..f3cd5f6cf --- /dev/null +++ b/src/GUI/.gitignore @@ -0,0 +1 @@ +layout-test diff --git a/src/GUI/dialog.hxx b/src/GUI/dialog.hxx index e08dbe75a..090ef2bbc 100644 --- a/src/GUI/dialog.hxx +++ b/src/GUI/dialog.hxx @@ -161,7 +161,7 @@ private: bool _needsRelayout; // Nasal module. - string _module; + std::string _module; SGPropertyNode_ptr _nasal_close; // PUI provides no way for userdata to be deleted automatically @@ -173,7 +173,7 @@ private: PropertyObject (const char * name, puObject * object, SGPropertyNode_ptr node); - string name; + std::string name; puObject * object; SGPropertyNode_ptr node; }; diff --git a/src/GUI/gui.h b/src/GUI/gui.h index 2563251d8..4ea7b588d 100644 --- a/src/GUI/gui.h +++ b/src/GUI/gui.h @@ -55,15 +55,12 @@ extern fntTexFont *guiFntHandle; extern int gui_menu_on; // from gui_funcs.cxx -extern void reInit(void); extern void fgDumpSnapShotWrapper(); #ifdef TR_HIRES_SNAP extern void fgHiResDumpWrapper(); extern void fgHiResDump(); #endif -#if defined( _WIN32 ) && !defined(__MINGW32__) -extern void printScreen(); -#endif + extern void helpCb(); typedef struct { diff --git a/src/GUI/gui_funcs.cxx b/src/GUI/gui_funcs.cxx index 52eb06662..ff6971549 100644 --- a/src/GUI/gui_funcs.cxx +++ b/src/GUI/gui_funcs.cxx @@ -53,11 +53,8 @@ #ifdef _WIN32 # include -# if !defined(__MINGW32__) -# include -# include -# endif #endif + #include "gui.h" using std::string; @@ -75,9 +72,6 @@ const __fg_gui_fn_t __fg_gui_fn[] = { {"dumpHiResSnapShot", fgHiResDumpWrapper}, #endif {"dumpSnapShot", fgDumpSnapShotWrapper}, -#if defined( _WIN32 ) && !defined(__MINGW32__) - {"printScreen", printScreen}, -#endif // Help {"helpCb", helpCb}, @@ -403,61 +397,6 @@ void fgHiResDump() } #endif // #if defined( TR_HIRES_SNAP) - -#if defined( _WIN32 ) && !defined(__MINGW32__) - -void rotateView( double roll, double pitch, double yaw ) -{ - // rotate view -} - -GlBitmap *b1 = NULL; -GLubyte *hiResScreenCapture( int multiplier ) -{ - float oldfov = fgGetDouble("/sim/current-view/field-of-view"); - float fov = oldfov / multiplier; - FGViewer *v = globals->get_current_view(); - fgSetDouble("/sim/current-view/field-of-view", fov); -// globals->get_renderer()->init(); - int cur_width = fgGetInt("/sim/startup/xsize"); - int cur_height = fgGetInt("/sim/startup/ysize"); - delete( b1 ); - // New empty (mostly) bitmap - b1 = new GlBitmap( GL_RGB, 1, 1, (unsigned char *)"123" ); - int x,y; - for ( y = 0; y < multiplier; y++ ) { - for ( x = 0; x < multiplier; x++ ) { - globals->get_renderer()->resize( cur_width, cur_height ); - // pan to tile - rotateView( 0, (y*fov)-((multiplier-1)*fov/2), (x*fov)-((multiplier-1)*fov/2) ); - globals->get_renderer()->update( false ); - // restore view - GlBitmap b2; - b1->copyBitmap( &b2, cur_width*x, cur_height*y ); - } - } - fgSetDouble("/sim/current-view/field-of-view", oldfov); - return b1->getBitmap(); -} -#endif - -#if defined( _WIN32 ) && !defined(__MINGW32__) -// win32 print screen function -void printScreen () { - int mouse = fgGetMouseCursor(); - fgSetMouseCursor(MOUSE_CURSOR_NONE); - - CGlPrinter p( CGlPrinter::PRINT_BITMAP ); - int cur_width = fgGetInt("/sim/startup/xsize"); - int cur_height = fgGetInt("/sim/startup/ysize"); - p.Begin( "FlightGear", cur_width*3, cur_height*3 ); - p.End( hiResScreenCapture(3) ); - - fgSetMouseCursor(mouse); -} -#endif // #ifdef _WIN32 - - void fgDumpSnapShotWrapper () { fgDumpSnapShot(); } diff --git a/src/GUI/menubar.cxx b/src/GUI/menubar.cxx index 89246a5ed..5675b14e4 100644 --- a/src/GUI/menubar.cxx +++ b/src/GUI/menubar.cxx @@ -36,16 +36,6 @@ do_hires_snapshot_dialog (const SGPropertyNode * arg) } #endif // TR_HIRES_SNAP -#if defined( _WIN32 ) && !defined(__MINGW32__) -extern void printScreen (); -static bool -do_print_dialog (const SGPropertyNode * arg) -{ - printScreen(); - return true; -} -#endif - extern void helpCb (); static bool do_help_dialog (const SGPropertyNode * arg) @@ -60,9 +50,6 @@ static struct { } deprecated_dialogs [] = { #if defined(TR_HIRES_SNAP) { "old-hires-snapshot-dialog", do_hires_snapshot_dialog }, -#endif -#if defined( _WIN32 ) && !defined(__MINGW32__) - { "old-print-dialog", do_print_dialog }, #endif { "old-help-dialog", do_help_dialog }, { 0, 0 } diff --git a/src/Include/.gitignore b/src/Include/.gitignore new file mode 100644 index 000000000..e76f66334 --- /dev/null +++ b/src/Include/.gitignore @@ -0,0 +1,4 @@ +config.h +config.h.* +stamp-h1 +version.h diff --git a/src/Include/config.h-msvc6.in b/src/Include/config.h-msvc6.in deleted file mode 100644 index 4ddcd9193..000000000 --- a/src/Include/config.h-msvc6.in +++ /dev/null @@ -1,198 +0,0 @@ - -/* Special single config.h for MSVC6 build - Geoff McLane - 23 July, 2003 */ - -/* Define to enable plib joystick support */ -#ifndef ENABLE_PLIB_JOYSTICK -#define ENABLE_PLIB_JOYSTICK -#endif // #ifndef ENABLE_PLIB_JOYSTICK - -/* Define to enable threaded tile paging */ -#undef ENABLE_THREADS - -/* Define so that JSBSim compiles in 'library' mode */ -#define FGFS 1 - -/* Define to build with jpeg screen shot server */ -#undef FG_JPEG_SERVER - -/* Define for no logging output */ -#undef FG_NDEBUG - -/* Define to build with Oliver's networking */ -#undef FG_NETWORK_OLK - -/* Define to enable plib joystick name support */ -#define FG_PLIB_JOYSTICK_GETNAME - -/* Define to build with Christian Mayer's weather code */ -#undef FG_WEATHERCM - -/* Define if the X Window System is missing or not being used. */ -#define X_DISPLAY_MISSING 1 - -/* Define if the CONSOLE output has no ANSI driver (eg no "esc [ ..." seqs.) */ -#define NO_ANSI_DRIVER - -/* Define to empty if the keyword does not work. */ -/* #undef const */ - -/* Define if you don't have vprintf but do have _doprnt. */ -/* #undef HAVE_DOPRNT */ - -/* Define if you have the vprintf function. */ -#define HAVE_VPRINTF 1 - -/* Define to package name - not used? */ -#define PACKAGE "FlightGear" - -/* Define to package version - use in main.cxx */ -#define FLIGHTGEAR_VERSION "MSVC6-WIN32-@VERSION@" - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define to `unsigned' if doesn't define. */ -/* #undef size_t */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #undef TIME_WITH_SYS_TIME */ - -/* Define if your declares struct tm. */ -#define TM_IN_SYS_TIME 1 - -/* Define to version number */ -#define VERSION "@VERSION@" - -/* Define if compiling on a Winbloze (95, NT, etc.) platform */ -#define WIN32 1 - -/* Define if you have the GetLocalTime function. */ -#define HAVE_GETLOCALTIME 1 - -/* Define if you have the ftime function. */ -#define HAVE_FTIME 1 - -/* Define if you have the getitimer function. */ -/* #define HAVE_GETITIMER 1 */ - -/* Define if you have the getrusage function. */ -/* #define HAVE_GETRUSAGE 1 */ - -/* Define if you have the gettimeofday function. */ -/* #define HAVE_GETTIMEOFDAY 1 */ - -/* Define if you have the mktime function. */ -#define HAVE_MKTIME 1 - -/* Define if you have the rand function. */ -#define HAVE_RAND 1 - -/* Define if you have the random function. */ -/* #define HAVE_RANDOM 1 */ - -/* Define if you have the rint function. */ -/* #define HAVE_RINT 1 */ - -/* Define if you have the setitimer function. */ -/* #define HAVE_SETITIMER 1 */ - -/* Define if you have the signal function. */ -#define HAVE_SIGNAL 1 - -/* Define if you have the strstr function. */ -#define HAVE_STRSTR 1 - -/* Define if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the header file. */ -#define HAVE_GETOPT_H 1 - -/* Define if you have the header file. */ -#define HAVE_MALLOC_H 1 - -/* Define if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_SYS_TIME_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_SYS_TIMEB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_UNISTD_H 1 */ - -/* Define if you have the header file. */ -/* #define HAVE_VALUES_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_WINBASE_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the GL library (-lGL). */ -#define HAVE_LIBGL 1 - -/* Define if you have the GLU library (-lGLU). */ -#define HAVE_LIBGLU 1 - -/* Define if you have the GLcore library (-lGLcore). */ -/* #undef HAVE_LIBGLCORE */ - -/* Define if you have the ICE library (-lICE). */ -/* #define HAVE_LIBICE 1 */ - -/* Define if you have the MesaGL library (-lMesaGL). */ -/* #undef HAVE_LIBMESAGL */ - -/* Define if you have the MesaGLU library (-lMesaGLU). */ -/* #undef HAVE_LIBMESAGLU */ - -/* Define if you have the SM library (-lSM). */ -/* #define HAVE_LIBSM 1 */ - -/* Define if you have the X11 library (-lX11). */ -/* #define HAVE_LIBX11 1 */ - -/* Define if you have the Xext library (-lXext). */ -/* #define HAVE_LIBXEXT 1 */ - -/* Define if you have the Xi library (-lXi). */ -/* #define HAVE_LIBXI 1 */ - -/* Define if you have the Xmu library (-lXmu). */ -/* #define HAVE_LIBXMU 1 */ - -/* Define if you have the Xt library (-lXt). */ -/* #define HAVE_LIBXT 1 */ - -/* Define if you have the glut library (-lglut). */ -#define HAVE_LIBGLUT 1 - -/* Define if you have the m library (-lm). */ -#define HAVE_LIBM 1 - -/* Define if you have the socket library (-lsocket). */ -/* #undef HAVE_LIBSOCKET */ - -/* Define if you have the header file. */ -#define HAVE_MEMORY_H 1 - -#define HAVE_MEMCPY 1 - -#define NOMINMAX 1 - -#ifndef ENABLE_AUDIO_SUPPORT -#define ENABLE_AUDIO_SUPPORT -#endif - -#ifndef FG_GLUT_H -#define FG_GLUT_H -#endif // #ifndef FG_GLUT_H - -// eof - config.h-msvc6 - single flightgear config.h file diff --git a/src/Include/config.h-msvc71 b/src/Include/config.h-msvc71 old mode 100755 new mode 100644 index 0e2c75d62..0e7fc3835 --- a/src/Include/config.h-msvc71 +++ b/src/Include/config.h-msvc71 @@ -163,8 +163,6 @@ #define NOMINMAX 1 -#define HAVE_CULLSETTINGS_CLEAR_MASK 1 - #ifndef ENABLE_AUDIO_SUPPORT #define ENABLE_AUDIO_SUPPORT #endif diff --git a/src/Include/config.h-msvc71.in b/src/Include/config.h-msvc71.in deleted file mode 100755 index d67dcacbb..000000000 --- a/src/Include/config.h-msvc71.in +++ /dev/null @@ -1,172 +0,0 @@ -/* Special single config.h for MSVC71 build - F. Bouvier - 06 Jan, 2007 */ - -/* Define if the X Window System is missing or not being used. */ -#define X_DISPLAY_MISSING 1 - -/* Define if the CONSOLE output has no ANSI driver (eg no "esc [ ..." seqs.) */ -#define NO_ANSI_DRIVER - -/* Define to empty if the keyword does not work. */ -/* #undef const */ - -/* Define if you don't have vprintf but do have _doprnt. */ -/* #undef HAVE_DOPRNT */ - -/* Define if you have the vprintf function. */ -#define HAVE_VPRINTF 1 - -/* Define to package name - not used? */ -#define PACKAGE "FlightGear" - -/* Define to package version - use in main.cxx */ -#define FLIGHTGEAR_VERSION "MSVC7.1-WIN32-@VERSION@" - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define to `unsigned' if doesn't define. */ -/* #undef size_t */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #undef TIME_WITH_SYS_TIME */ - -/* Define if your declares struct tm. */ -#define TM_IN_SYS_TIME 1 - -/* Define to version number */ -#define VERSION "@VERSION@" -#ifndef FG_VERSION /* allow override */ -#define FG_VERSION 7 -#endif /* FG_VERSION */ - -/* Define if compiling on a Winbloze (95, NT, etc.) platform */ -#define WIN32 1 - -/* Define if you have the GetLocalTime function. */ -#define HAVE_GETLOCALTIME 1 - -/* Define if you have the ftime function. */ -#define HAVE_FTIME 1 - -/* Define if you have the getitimer function. */ -/* #define HAVE_GETITIMER 1 */ - -/* Define if you have the getrusage function. */ -/* #define HAVE_GETRUSAGE 1 */ - -/* Define if you have the gettimeofday function. */ -/* #define HAVE_GETTIMEOFDAY 1 */ - -/* Define if you have the mktime function. */ -#define HAVE_MKTIME 1 - -/* Define if you have the rand function. */ -#define HAVE_RAND 1 - -/* Define if you have the random function. */ -/* #define HAVE_RANDOM 1 */ - -/* Define if you have the rint function. */ -/* #define HAVE_RINT 1 */ - -/* Define if you have the setitimer function. */ -/* #define HAVE_SETITIMER 1 */ - -/* Define if you have the signal function. */ -#define HAVE_SIGNAL 1 - -/* Define if you have the strstr function. */ -#define HAVE_STRSTR 1 - -/* Define if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the header file. */ -#define HAVE_GETOPT_H 1 - -/* Define if you have the header file. */ -#define HAVE_MALLOC_H 1 - -/* Define if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_SYS_TIME_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_SYS_TIMEB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_UNISTD_H 1 */ - -/* Define if you have the header file. */ -/* #define HAVE_VALUES_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_WINBASE_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the GL library (-lGL). */ -#define HAVE_LIBGL 1 - -/* Define if you have the GLU library (-lGLU). */ -#define HAVE_LIBGLU 1 - -/* Define if you have the GLcore library (-lGLcore). */ -/* #undef HAVE_LIBGLCORE */ - -/* Define if you have the ICE library (-lICE). */ -/* #define HAVE_LIBICE 1 */ - -/* Define if you have the MesaGL library (-lMesaGL). */ -/* #undef HAVE_LIBMESAGL */ - -/* Define if you have the MesaGLU library (-lMesaGLU). */ -/* #undef HAVE_LIBMESAGLU */ - -/* Define if you have the SM library (-lSM). */ -/* #define HAVE_LIBSM 1 */ - -/* Define if you have the X11 library (-lX11). */ -/* #define HAVE_LIBX11 1 */ - -/* Define if you have the Xext library (-lXext). */ -/* #define HAVE_LIBXEXT 1 */ - -/* Define if you have the Xi library (-lXi). */ -/* #define HAVE_LIBXI 1 */ - -/* Define if you have the Xmu library (-lXmu). */ -/* #define HAVE_LIBXMU 1 */ - -/* Define if you have the Xt library (-lXt). */ -/* #define HAVE_LIBXT 1 */ - -/* Define if you have the glut library (-lglut). */ -#define HAVE_LIBGLUT 1 - -/* Define if you have the m library (-lm). */ -#define HAVE_LIBM 1 - -/* Define if you have the socket library (-lsocket). */ -/* #undef HAVE_LIBSOCKET */ - -/* Define if you have the header file. */ -#define HAVE_MEMORY_H 1 - -#define HAVE_MEMCPY 1 - -#define NOMINMAX 1 - -#ifndef ENABLE_AUDIO_SUPPORT -#define ENABLE_AUDIO_SUPPORT -#endif - -#define FG_GLUT_H - -// eof - config.h-msvc71 - single flightgear config.h file diff --git a/src/Include/config.h-msvc8 b/src/Include/config.h-msvc8 old mode 100755 new mode 100644 diff --git a/src/Include/config.h-msvc8.in b/src/Include/config.h-msvc8.in deleted file mode 100644 index cc630a070..000000000 --- a/src/Include/config.h-msvc8.in +++ /dev/null @@ -1,202 +0,0 @@ - -/* Special single config.h for MSVC6 build - Geoff McLane - 23 July, 2003 */ - -/* Define to enable plib joystick support */ -#ifndef ENABLE_PLIB_JOYSTICK -#define ENABLE_PLIB_JOYSTICK -#endif // #ifndef ENABLE_PLIB_JOYSTICK - -/* Define to enable threaded tile paging */ -#define ENABLE_THREADS 1 -#define ENABLE_AUDIO_SUPPORT 1 - -/* Define so that JSBSim compiles in 'library' mode */ -#define FGFS 1 - -/* Define to build with jpeg screen shot server */ -#undef FG_JPEG_SERVER - -/* Define to build with multiplayer support */ -#define FG_MPLAYER_AS 1 - -/* Define for no logging output */ -#undef FG_NDEBUG - -/* Define to build with Oliver's networking */ -#undef FG_NETWORK_OLK - -/* Define to enable plib joystick name support */ -#define FG_PLIB_JOYSTICK_GETNAME - -/* Define to build with Christian Mayer's weather code */ -#undef FG_WEATHERCM - -/* Define if the X Window System is missing or not being used. */ -#define X_DISPLAY_MISSING 1 - -/* Define if the CONSOLE output has no ANSI driver (eg no "esc [ ..." seqs.) */ -#define NO_ANSI_DRIVER - -/* Define to empty if the keyword does not work. */ -/* #undef const */ - -/* Define if you don't have vprintf but do have _doprnt. */ -/* #undef HAVE_DOPRNT */ - -/* Define if you have the vprintf function. */ -#define HAVE_VPRINTF 1 - -/* Define to package name - not used? */ -#define PACKAGE "FlightGear" - -/* Define to package version - use in main.cxx */ -#define FLIGHTGEAR_VERSION "MSVC8-WIN32-@VERSION@" - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define to `unsigned' if doesn't define. */ -/* #undef size_t */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #undef TIME_WITH_SYS_TIME */ - -/* Define if your declares struct tm. */ -#define TM_IN_SYS_TIME 1 - -/* Define to version number */ -#define VERSION "@VERSION@" - -/* Define if compiling on a Winbloze (95, NT, etc.) platform */ -#define WIN32 1 - -/* Define if you have the GetLocalTime function. */ -#define HAVE_GETLOCALTIME 1 - -/* Define if you have the ftime function. */ -#define HAVE_FTIME 1 - -/* Define if you have the getitimer function. */ -/* #define HAVE_GETITIMER 1 */ - -/* Define if you have the getrusage function. */ -/* #define HAVE_GETRUSAGE 1 */ - -/* Define if you have the gettimeofday function. */ -/* #define HAVE_GETTIMEOFDAY 1 */ - -/* Define if you have the mktime function. */ -#define HAVE_MKTIME 1 - -/* Define if you have the rand function. */ -#define HAVE_RAND 1 - -/* Define if you have the random function. */ -/* #define HAVE_RANDOM 1 */ - -/* Define if you have the rint function. */ -/* #define HAVE_RINT 1 */ - -/* Define if you have the setitimer function. */ -/* #define HAVE_SETITIMER 1 */ - -/* Define if you have the signal function. */ -#define HAVE_SIGNAL 1 - -/* Define if you have the strstr function. */ -#define HAVE_STRSTR 1 - -/* Define if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the header file. */ -#define HAVE_GETOPT_H 1 - -/* Define if you have the header file. */ -#define HAVE_MALLOC_H 1 - -/* Define if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_SYS_TIME_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_SYS_TIMEB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_UNISTD_H 1 */ - -/* Define if you have the header file. */ -/* #define HAVE_VALUES_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_WINBASE_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the GL library (-lGL). */ -#define HAVE_LIBGL 1 - -/* Define if you have the GLU library (-lGLU). */ -#define HAVE_LIBGLU 1 - -/* Define if you have the GLcore library (-lGLcore). */ -/* #undef HAVE_LIBGLCORE */ - -/* Define if you have the ICE library (-lICE). */ -/* #define HAVE_LIBICE 1 */ - -/* Define if you have the MesaGL library (-lMesaGL). */ -/* #undef HAVE_LIBMESAGL */ - -/* Define if you have the MesaGLU library (-lMesaGLU). */ -/* #undef HAVE_LIBMESAGLU */ - -/* Define if you have the SM library (-lSM). */ -/* #define HAVE_LIBSM 1 */ - -/* Define if you have the X11 library (-lX11). */ -/* #define HAVE_LIBX11 1 */ - -/* Define if you have the Xext library (-lXext). */ -/* #define HAVE_LIBXEXT 1 */ - -/* Define if you have the Xi library (-lXi). */ -/* #define HAVE_LIBXI 1 */ - -/* Define if you have the Xmu library (-lXmu). */ -/* #define HAVE_LIBXMU 1 */ - -/* Define if you have the Xt library (-lXt). */ -/* #define HAVE_LIBXT 1 */ - -/* Define if you have the glut library (-lglut). */ -#define HAVE_LIBGLUT 1 - -/* Define if you have the m library (-lm). */ -#define HAVE_LIBM 1 - -/* Define if you have the socket library (-lsocket). */ -/* #undef HAVE_LIBSOCKET */ - -/* Define if you have the header file. */ -#define HAVE_MEMORY_H 1 - -#define HAVE_MEMCPY 1 -#define NOMINMAX 1 - - -#ifndef ENABLE_AUDIO_SUPPORT -#define ENABLE_AUDIO_SUPPORT -#endif - -#ifndef FG_GLUT_H -#define FG_GLUT_H -#endif // #ifndef FG_GLUT_H - -// eof - config.h-msvc6 - single flightgear config.h file diff --git a/src/Include/config.h-msvc90 b/src/Include/config.h-msvc90 old mode 100755 new mode 100644 diff --git a/src/Include/config.h-msvc90.in b/src/Include/config.h-msvc90.in deleted file mode 100644 index 52695b032..000000000 --- a/src/Include/config.h-msvc90.in +++ /dev/null @@ -1,174 +0,0 @@ -/* Special single config.h for MSVC90 build - F. Bouvier - 17 Jan, 2010 */ - -/* Define if the X Window System is missing or not being used. */ -#define X_DISPLAY_MISSING 1 - -/* Define if the CONSOLE output has no ANSI driver (eg no "esc [ ..." seqs.) */ -#define NO_ANSI_DRIVER - -/* Define to empty if the keyword does not work. */ -/* #undef const */ - -/* Define if you don't have vprintf but do have _doprnt. */ -/* #undef HAVE_DOPRNT */ - -/* Define if you have the vprintf function. */ -#define HAVE_VPRINTF 1 - -/* Define to package name - not used? */ -#define PACKAGE "FlightGear" - -/* Define to package version - use in main.cxx */ -#define FLIGHTGEAR_VERSION "MSVC9.0-WIN32-@VERSION@" - -/* Define as the return type of signal handlers (int or void). */ -#define RETSIGTYPE void - -/* Define to `unsigned' if doesn't define. */ -/* #undef size_t */ - -/* Define if you have the ANSI C header files. */ -#define STDC_HEADERS 1 - -/* Define if you can safely include both and . */ -/* #undef TIME_WITH_SYS_TIME */ - -/* Define if your declares struct tm. */ -#define TM_IN_SYS_TIME 1 - -/* Define to version number */ -#define VERSION "@VERSION@" -#ifndef FG_VERSION /* allow override */ -#define FG_VERSION 7 -#endif /* FG_VERSION */ - -/* Define if compiling on a Winbloze (95, NT, etc.) platform */ -#define WIN32 1 - -/* Define if you have the GetLocalTime function. */ -#define HAVE_GETLOCALTIME 1 - -/* Define if you have the ftime function. */ -#define HAVE_FTIME 1 - -/* Define if you have the getitimer function. */ -/* #define HAVE_GETITIMER 1 */ - -/* Define if you have the getrusage function. */ -/* #define HAVE_GETRUSAGE 1 */ - -/* Define if you have the gettimeofday function. */ -/* #define HAVE_GETTIMEOFDAY 1 */ - -/* Define if you have the mktime function. */ -#define HAVE_MKTIME 1 - -/* Define if you have the rand function. */ -#define HAVE_RAND 1 - -/* Define if you have the random function. */ -/* #define HAVE_RANDOM 1 */ - -/* Define if you have the rint function. */ -/* #define HAVE_RINT 1 */ - -/* Define if you have the setitimer function. */ -/* #define HAVE_SETITIMER 1 */ - -/* Define if you have the signal function. */ -#define HAVE_SIGNAL 1 - -/* Define if you have the strstr function. */ -#define HAVE_STRSTR 1 - -/* Define if you have the header file. */ -#define HAVE_FCNTL_H 1 - -/* Define if you have the header file. */ -#define HAVE_GETOPT_H 1 - -/* Define if you have the header file. */ -#define HAVE_MALLOC_H 1 - -/* Define if you have the header file. */ -#define HAVE_STDLIB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_SYS_TIME_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_SYS_TIMEB_H 1 - -/* Define if you have the header file. */ -/* #define HAVE_UNISTD_H 1 */ - -/* Define if you have the header file. */ -/* #define HAVE_VALUES_H 1 */ - -/* Define if you have the header file. */ -#define HAVE_WINBASE_H 1 - -/* Define if you have the header file. */ -#define HAVE_WINDOWS_H 1 - -/* Define if you have the GL library (-lGL). */ -#define HAVE_LIBGL 1 - -/* Define if you have the GLU library (-lGLU). */ -#define HAVE_LIBGLU 1 - -/* Define if you have the GLcore library (-lGLcore). */ -/* #undef HAVE_LIBGLCORE */ - -/* Define if you have the ICE library (-lICE). */ -/* #define HAVE_LIBICE 1 */ - -/* Define if you have the MesaGL library (-lMesaGL). */ -/* #undef HAVE_LIBMESAGL */ - -/* Define if you have the MesaGLU library (-lMesaGLU). */ -/* #undef HAVE_LIBMESAGLU */ - -/* Define if you have the SM library (-lSM). */ -/* #define HAVE_LIBSM 1 */ - -/* Define if you have the X11 library (-lX11). */ -/* #define HAVE_LIBX11 1 */ - -/* Define if you have the Xext library (-lXext). */ -/* #define HAVE_LIBXEXT 1 */ - -/* Define if you have the Xi library (-lXi). */ -/* #define HAVE_LIBXI 1 */ - -/* Define if you have the Xmu library (-lXmu). */ -/* #define HAVE_LIBXMU 1 */ - -/* Define if you have the Xt library (-lXt). */ -/* #define HAVE_LIBXT 1 */ - -/* Define if you have the glut library (-lglut). */ -#define HAVE_LIBGLUT 1 - -/* Define if you have the m library (-lm). */ -#define HAVE_LIBM 1 - -/* Define if you have the socket library (-lsocket). */ -/* #undef HAVE_LIBSOCKET */ - -/* Define if you have the header file. */ -#define HAVE_MEMORY_H 1 - -#define HAVE_MEMCPY 1 - -#define NOMINMAX 1 - -#define HAVE_CULLSETTINGS_CLEAR_MASK 1 - -#ifndef ENABLE_AUDIO_SUPPORT -#define ENABLE_AUDIO_SUPPORT -#endif - -#define FG_GLUT_H - -// eof - config.h-msvc90 - single flightgear config.h file diff --git a/src/Include/general.hxx b/src/Include/general.hxx index 0db2b8829..c72f8031e 100644 --- a/src/Include/general.hxx +++ b/src/Include/general.hxx @@ -56,10 +56,11 @@ class FGGeneral { #endif public: - + inline char* get_glVendor() { return glVendor; } inline void set_glVendor( char *str ) { glVendor = str; } inline char* get_glRenderer() const { return glRenderer; } inline void set_glRenderer( char *str ) { glRenderer = str; } + inline char* get_glVersion() { return glVersion; } inline void set_glVersion( char *str ) { glVersion = str; } inline void set_glMaxTexSize( int i ) { glMaxTexSize = i; } inline int get_glMaxTexSize() const { return glMaxTexSize; } diff --git a/src/Input/.gitignore b/src/Input/.gitignore new file mode 100644 index 000000000..2abe61b50 --- /dev/null +++ b/src/Input/.gitignore @@ -0,0 +1,2 @@ +fgjs +js_demo diff --git a/src/Input/FGButton.cxx b/src/Input/FGButton.cxx index cb03aeac4..63a679d79 100644 --- a/src/Input/FGButton.cxx +++ b/src/Input/FGButton.cxx @@ -45,7 +45,7 @@ FGButton::~FGButton () } -void FGButton::init( const SGPropertyNode * node, const string name, string & module ) +void FGButton::init( const SGPropertyNode * node, const std::string name, std::string & module ) { if (node == 0) { SG_LOG(SG_INPUT, SG_DEBUG, "No bindings for button " << name); diff --git a/src/Input/FGButton.hxx b/src/Input/FGButton.hxx index 6ab5347a0..675f969d2 100644 --- a/src/Input/FGButton.hxx +++ b/src/Input/FGButton.hxx @@ -32,7 +32,7 @@ class FGButton : public FGCommonInput { public: FGButton(); virtual ~FGButton(); - void init( const SGPropertyNode * node, const string name, string & module ); + void init( const SGPropertyNode * node, const std::string name, std::string & module ); void update( int modifiers, bool pressed, int x = -1, int y = -1); bool is_repeatable; float interval_sec; diff --git a/src/Input/FGCommonInput.hxx b/src/Input/FGCommonInput.hxx index 575ab5402..046ce8264 100644 --- a/src/Input/FGCommonInput.hxx +++ b/src/Input/FGCommonInput.hxx @@ -39,14 +39,14 @@ class FGCommonInput { public: - typedef vector > binding_list_t; + typedef std::vector > binding_list_t; /* read all "binding" nodes directly under the specified base node and fill the vector of SGBinding supplied in binding_list. Reads all the mod-xxx bindings and add the corresponding SGBindings. */ - static void read_bindings (const SGPropertyNode * base, binding_list_t * binding_list, int modifiers, const string & module ); + static void read_bindings (const SGPropertyNode * base, binding_list_t * binding_list, int modifiers, const std::string & module ); }; #endif diff --git a/src/Input/FGDeviceConfigurationMap.hxx b/src/Input/FGDeviceConfigurationMap.hxx index 27a3a8a14..e89addc96 100644 --- a/src/Input/FGDeviceConfigurationMap.hxx +++ b/src/Input/FGDeviceConfigurationMap.hxx @@ -33,9 +33,8 @@ #include #include -using std::map; -class FGDeviceConfigurationMap : public map { +class FGDeviceConfigurationMap : public std::map { public: FGDeviceConfigurationMap ( const char * relative_path, SGPropertyNode_ptr base, const char * childname ); virtual ~FGDeviceConfigurationMap(); diff --git a/src/Input/FGMouseInput.cxx b/src/Input/FGMouseInput.cxx index c0b7e3f87..16bb7883e 100644 --- a/src/Input/FGMouseInput.cxx +++ b/src/Input/FGMouseInput.cxx @@ -25,7 +25,7 @@ #include "FGMouseInput.hxx" -void ActivePickCallbacks::init( int b, const osgGA::GUIEventAdapter* ea ) +void ActivePickCallbacks::init( int b, const osgGA::GUIEventAdapter* ea ) { // Get the list of hit callbacks. Take the first callback that // accepts the mouse button press and ignore the rest of them @@ -44,7 +44,7 @@ void ActivePickCallbacks::init( int b, const osgGA::GUIEventAdapter* ea ) } } -void ActivePickCallbacks::update( double dt ) +void ActivePickCallbacks::update( double dt ) { // handle repeatable mouse press events for( iterator mi = begin(); mi != end(); ++mi ) { @@ -202,6 +202,7 @@ FGMouseInput::mouse::mouse () save_y(-1), nModes(1), current_mode(0), + timeout(0), modes(NULL) { } diff --git a/src/Instrumentation/HUD/HUD_label.cxx b/src/Instrumentation/HUD/HUD_label.cxx index 98a6a1df0..5cf2bcb57 100644 --- a/src/Instrumentation/HUD/HUD_label.cxx +++ b/src/Instrumentation/HUD/HUD_label.cxx @@ -144,7 +144,7 @@ void HUD::Label::draw(void) char buf[BUFSIZE+1]; buf[ BUFSIZE] = '\0'; // Be sure to terminate properly if (_mode == NONE) - snprintf(buf, BUFSIZE, _format.c_str()); + snprintf(buf, BUFSIZE, _format.c_str(), 0); else if (_mode == STRING) snprintf(buf, BUFSIZE, _format.c_str(), _input.getStringValue()); else if (_mode == INT) diff --git a/src/Instrumentation/HUD/HUD_ladder.cxx b/src/Instrumentation/HUD/HUD_ladder.cxx index 75b2e3afc..478ffa1b1 100644 --- a/src/Instrumentation/HUD/HUD_ladder.cxx +++ b/src/Instrumentation/HUD/HUD_ladder.cxx @@ -24,11 +24,10 @@ #endif #include -#include +#include #include
#include "HUD.hxx" - // FIXME static float get__heading() { return fgGetFloat("/orientation/heading-deg") * M_PI / 180.0; } static float get__throttleval() { return fgGetFloat("/controls/engines/engine/throttle"); } @@ -424,12 +423,11 @@ void HUD::Ladder::draw(void) // however the horizon line should always stay on the horizon. We // project the alpha/beta offset onto the horizon line to get the // result we want. - sgdVec3 p1; // result - sgdVec3 p; sgdSetVec3(p, vel_x, vel_y, 0.0); - sgdVec3 p0; sgdSetVec3(p0, 0.0, 0.0, 0.0); - sgdVec3 d; sgdSetVec3(d, cos(roll_value), sin(roll_value), 0.0); - sgdClosestPointToLine(p1, p, p0, d); - glTranslatef(p1[0], p1[1], 0); + + SGVec3d d(cos(roll_value), sin(roll_value), 0.0); + SGRayd r(SGVec3d::zeros(), d); + SGVec3d p = r.getClosestPointTo(SGVec3d(vel_x, vel_y, 0.0)); + glTranslatef(p[0], p[1], 0); } } else { // ladder position is fixed relative to the center of the screen. diff --git a/src/Instrumentation/HUD/HUD_runway.cxx b/src/Instrumentation/HUD/HUD_runway.cxx index 8eb443c36..450f118a3 100644 --- a/src/Instrumentation/HUD/HUD_runway.cxx +++ b/src/Instrumentation/HUD/HUD_runway.cxx @@ -29,7 +29,6 @@ #include
#include -#include #include #include #include @@ -180,7 +179,7 @@ FGRunway* HUD::Runway::get_active_runway() void HUD::Runway::get_rwy_points(sgdVec3 *_points3d) { - double alt = current_aircraft.fdm_state->get_Runway_altitude() * SG_FEET_TO_METER; + double alt = _runway->geod().getElevationM(); double length = _runway->lengthM() * 0.5; double width = _runway->widthM() * 0.5; double frontLat = 0.0, frontLon = 0.0, backLat = 0.0, backLon = 0.0, az = 0.0, tempLat = 0.0, tempLon = 0.0; diff --git a/src/Instrumentation/KLN89/kln89_page_apt.cxx b/src/Instrumentation/KLN89/kln89_page_apt.cxx index 96cceea0d..e15b1a45e 100644 --- a/src/Instrumentation/KLN89/kln89_page_apt.cxx +++ b/src/Instrumentation/KLN89/kln89_page_apt.cxx @@ -26,7 +26,14 @@ #endif #include "kln89_page_apt.hxx" -#include + +#include + +#if ENABLE_ATCDCL +# include +#else + #include +#endif #include
#include #include diff --git a/src/Instrumentation/dclgps.cxx b/src/Instrumentation/dclgps.cxx index d3da8e828..018e943c4 100644 --- a/src/Instrumentation/dclgps.cxx +++ b/src/Instrumentation/dclgps.cxx @@ -1102,7 +1102,8 @@ FGPositioned* DCLGPS::FindTypedFirstById(const string& id, FGPositioned::Type ty if (exact) { FGPositioned::List matches = - FGPositioned::findAllWithIdentSortedByRange(id, SGGeod::fromRad(_lon, _lat), &filter); + FGPositioned::findAllWithIdent(id, &filter); + FGPositioned::sortByRange(matches, SGGeod::fromRad(_lon, _lat)); multi = (matches.size() > 1); return matches.empty() ? NULL : matches.front().ptr(); } diff --git a/src/Instrumentation/gps.cxx b/src/Instrumentation/gps.cxx index 1ddb87e08..71e3becbd 100644 --- a/src/Instrumentation/gps.cxx +++ b/src/Instrumentation/gps.cxx @@ -11,6 +11,7 @@ #include #include +#include #include "Main/fg_props.hxx" #include "Main/globals.hxx" // for get_subsystem @@ -144,10 +145,10 @@ public: DeprecatedPropListener(SGPropertyNode* gps) { _parents.insert(gps); - SGPropertyNode* wp = gps->getChild("wp"); + SGPropertyNode* wp = gps->getChild("wp", 0, true); _parents.insert(wp); - _parents.insert(wp->getChild("wp", 0)); - _parents.insert(wp->getChild("wp", 1)); + _parents.insert(wp->getChild("wp", 0, true)); + _parents.insert(wp->getChild("wp", 1, true)); std::set::iterator it; for (it = _parents.begin(); it != _parents.end(); ++it) { @@ -331,7 +332,7 @@ GPS::bind() tie(_gpsNode, "desired-course-deg", SGRawValueMethods (*this, &GPS::getDesiredCourse, NULL)); - _desiredCourseNode = _gpsNode->getChild("desired-course-deg"); + _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true); tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", "indicated-latitude-deg", "indicated-altitude-ft"); @@ -1382,9 +1383,6 @@ void GPS::setScratchFromRouteWaypoint(int aIndex) _scratchValid = true; _scratchNode->setDoubleValue("course", wp.get_track()); _scratchNode->setIntValue("index", aIndex); - - int lastResult = _routeMgr->size() - 1; - _searchHasNext = (_searchResultIndex < lastResult); } void GPS::loadNearest() @@ -1409,17 +1407,14 @@ void GPS::loadNearest() _searchResults = FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get()); - _searchResultsCached = true; _searchResultIndex = 0; _searchIsRoute = false; - _searchHasNext = false; if (_searchResults.empty()) { SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all"); return; } - _searchHasNext = (_searchResults.size() > 1); setScratchFromCachedSearchResult(); } @@ -1476,66 +1471,47 @@ void GPS::search() } _searchExact = _scratchNode->getBoolValue("exact", true); - _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true); _searchResultIndex = 0; _searchIsRoute = false; - _searchHasNext = false; - - if (_searchExact && _searchOrderByRange) { - // immediate mode search, get all the results now and cache them - auto_ptr f(createFilter(_searchType)); - if (_searchNames) { - _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get()); - } else { - _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get()); - } - - _searchResultsCached = true; - - if (_searchResults.empty()) { - clearScratch(); - return; - } - - _searchHasNext = (_searchResults.size() > 1); - setScratchFromCachedSearchResult(); - } else { - // iterative search, look up result zero - _searchResultsCached = false; - performSearch(); - } -} -void GPS::performSearch() -{ auto_ptr f(createFilter(_searchType)); - clearScratch(); - - FGPositionedRef r; if (_searchNames) { - if (_searchOrderByRange) { - r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext); - } else { - r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext); - } + _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get()); } else { - if (_searchOrderByRange) { - r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext); - } else { - r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext); - } + _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get()); + } + + bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true); + if (orderByRange) { + FGPositioned::sortByRange(_searchResults, _indicated_pos); } - if (!r) { + if (_searchResults.empty()) { + clearScratch(); return; } - setScratchFromPositioned(r.get(), _searchResultIndex); + setScratchFromCachedSearchResult(); +} + +bool GPS::getScratchHasNext() const +{ + int lastResult; + if (_searchIsRoute) { + lastResult = _routeMgr->size() - 1; + } else { + lastResult = (int) _searchResults.size() - 1; + } + + if (lastResult < 0) { // search array might be empty + return false; + } + + return (_searchResultIndex < lastResult); } void GPS::setScratchFromCachedSearchResult() { - assert(_searchResultsCached); int index = _searchResultIndex; if ((index < 0) || (index >= (int) _searchResults.size())) { @@ -1544,9 +1520,6 @@ void GPS::setScratchFromCachedSearchResult() } setScratchFromPositioned(_searchResults[index], index); - - int lastResult = (int) _searchResults.size() - 1; - _searchHasNext = (_searchResultIndex < lastResult); } void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex) @@ -1564,9 +1537,7 @@ void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex) } _scratchValid = true; - if (_searchResultsCached) { - _scratchNode->setIntValue("result-count", _searchResults.size()); - } + _scratchNode->setIntValue("result-count", _searchResults.size()); switch (aPos->type()) { case FGPositioned::VOR: @@ -1650,20 +1621,17 @@ void GPS::selectLegMode() void GPS::nextResult() { - if (!_searchHasNext) { + if (!getScratchHasNext()) { return; } clearScratch(); if (_searchIsRoute) { setScratchFromRouteWaypoint(++_searchResultIndex); - } else if (_searchResultsCached) { - ++_searchResultIndex; - setScratchFromCachedSearchResult(); } else { ++_searchResultIndex; - performSearch(); - } // of iterative search case + setScratchFromCachedSearchResult(); + } } void GPS::previousResult() @@ -1677,10 +1645,8 @@ void GPS::previousResult() if (_searchIsRoute) { setScratchFromRouteWaypoint(_searchResultIndex); - } else if (_searchResultsCached) { - setScratchFromCachedSearchResult(); } else { - performSearch(); + setScratchFromCachedSearchResult(); } } @@ -1699,14 +1665,15 @@ void GPS::defineWaypoint() // check for duplicate idents FGPositioned::TypeFilter f(FGPositioned::WAYPOINT); - FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f); + FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f); if (!dups.empty()) { SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum"); } SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident); FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos); - _searchResultsCached = false; + _searchResults.clear(); + _searchResults.push_back(wpt); setScratchFromPositioned(wpt.get(), -1); } diff --git a/src/Instrumentation/gps.hxx b/src/Instrumentation/gps.hxx index f1a1b4396..d6c3a7069 100644 --- a/src/Instrumentation/gps.hxx +++ b/src/Instrumentation/gps.hxx @@ -7,6 +7,8 @@ #ifndef __INSTRUMENTS_GPS_HXX #define __INSTRUMENTS_GPS_HXX 1 +#include + #include #include #include @@ -262,7 +264,7 @@ private: double getScratchDistance() const; double getScratchMagBearing() const; double getScratchTrueBearing() const; - bool getScratchHasNext() const { return _searchHasNext; } + bool getScratchHasNext() const; double getSelectedCourse() const { return _selectedCourse; } void setSelectedCourse(double crs); @@ -392,8 +394,6 @@ private: std::string _searchQuery; FGPositioned::Type _searchType; bool _searchExact; - bool _searchOrderByRange; - bool _searchResultsCached; FGPositioned::List _searchResults; bool _searchIsRoute; ///< set if 'search' is actually the current route bool _searchHasNext; ///< is there a result after this one? diff --git a/src/Instrumentation/groundradar.cxx b/src/Instrumentation/groundradar.cxx index 56c7d0902..ffa2e1fc9 100644 --- a/src/Instrumentation/groundradar.cxx +++ b/src/Instrumentation/groundradar.cxx @@ -20,6 +20,8 @@ # include "config.h" #endif +#include + #include #include #include diff --git a/src/Instrumentation/instrument_mgr.cxx b/src/Instrumentation/instrument_mgr.cxx index 6bfecbb27..2e3f21e3f 100644 --- a/src/Instrumentation/instrument_mgr.cxx +++ b/src/Instrumentation/instrument_mgr.cxx @@ -56,46 +56,68 @@ FGInstrumentMgr::FGInstrumentMgr () : { set_subsystem("od_gauge", new FGODGauge); set_subsystem("hud", new HUD); +} - SGPropertyNode_ptr config_props = new SGPropertyNode; - - SGPropertyNode *path_n = fgGetNode("/sim/instrumentation/path"); - - if (path_n) { - SGPath config( globals->get_fg_root() ); - config.append( path_n->getStringValue() ); - - SG_LOG( SG_ALL, SG_INFO, "Reading instruments from " - << config.str() ); - try { - readProperties( config.str(), config_props ); +FGInstrumentMgr::~FGInstrumentMgr () +{ +} - if ( !build(config_props) ) { - throw sg_error( +void FGInstrumentMgr::init() +{ + SGPropertyNode_ptr config_props = new SGPropertyNode; + SGPropertyNode* path_n = fgGetNode("/sim/instrumentation/path"); + if (!path_n) { + SG_LOG(SG_COCKPIT, SG_WARN, "No instrumentation model specified for this model!"); + return; + } + + SGPath config = globals->resolve_aircraft_path(path_n->getStringValue()); + SG_LOG( SG_COCKPIT, SG_INFO, "Reading instruments from " << config.str() ); + + try { + readProperties( config.str(), config_props ); + if (!build(config_props)) { + throw sg_error( "Detected an internal inconsistency in the instrumentation\n" "system specification file. See earlier errors for details."); - } - } catch (const sg_exception&) { - SG_LOG( SG_ALL, SG_ALERT, "Failed to load instrumentation system model: " - << config.str() ); - } - - } else { - SG_LOG( SG_ALL, SG_WARN, - "No instrumentation model specified for this model!"); - } - - if (!_explicitGps) { - SG_LOG(SG_INSTR, SG_INFO, "creating default GPS instrument"); - SGPropertyNode_ptr nd(new SGPropertyNode); - nd->setStringValue("name", "gps"); - nd->setIntValue("number", 0); - set_subsystem("gps[0]", new GPS(nd)); } + } catch (const sg_exception&) { + SG_LOG(SG_COCKPIT, SG_ALERT, "Failed to load instrumentation system model: " + << config.str() ); + } + + + if (!_explicitGps) { + SG_LOG(SG_INSTR, SG_INFO, "creating default GPS instrument"); + SGPropertyNode_ptr nd(new SGPropertyNode); + nd->setStringValue("name", "gps"); + nd->setIntValue("number", 0); + _instruments.push_back("gps[0]"); + set_subsystem("gps[0]", new GPS(nd)); + } + + // bind() created instruments before init. + for (unsigned int i=0; i<_instruments.size(); ++i) { + const std::string& nm(_instruments[i]); + SGSubsystem* instr = get_subsystem(nm); + instr->bind(); + } + + SGSubsystemGroup::init(); } -FGInstrumentMgr::~FGInstrumentMgr () -{ +void FGInstrumentMgr::reinit() +{ +// delete all our instrument + for (unsigned int i=0; i<_instruments.size(); ++i) { + const std::string& nm(_instruments[i]); + SGSubsystem* instr = get_subsystem(nm); + instr->unbind(); + remove_subsystem(nm); + delete instr; + } + + init(); } bool FGInstrumentMgr::build (SGPropertyNode* config_props) @@ -111,7 +133,7 @@ bool FGInstrumentMgr::build (SGPropertyNode* config_props) if (index > 0) subsystemname << '['<< index << ']'; string id = subsystemname.str(); - + _instruments.push_back(id); if ( name == "adf" ) { set_subsystem( id, new ADF( node ), 0.15 ); diff --git a/src/Instrumentation/instrument_mgr.hxx b/src/Instrumentation/instrument_mgr.hxx index b5856ef97..d7c9b2a07 100644 --- a/src/Instrumentation/instrument_mgr.hxx +++ b/src/Instrumentation/instrument_mgr.hxx @@ -31,10 +31,15 @@ public: FGInstrumentMgr (); virtual ~FGInstrumentMgr (); - bool build (SGPropertyNode* config_props); - + + virtual void init(); + virtual void reinit(); private: + bool build (SGPropertyNode* config_props); + bool _explicitGps; + + std::vector _instruments; }; #endif // __INSTRUMENT_MGR_HXX diff --git a/src/Instrumentation/kr_87.cxx b/src/Instrumentation/kr_87.cxx index 41928a097..30c0cbe66 100644 --- a/src/Instrumentation/kr_87.cxx +++ b/src/Instrumentation/kr_87.cxx @@ -32,7 +32,6 @@ #include #include -#include #include #include "kr_87.hxx" diff --git a/src/Instrumentation/kt_70.cxx b/src/Instrumentation/kt_70.cxx index 99787b71f..ec48bf84d 100644 --- a/src/Instrumentation/kt_70.cxx +++ b/src/Instrumentation/kt_70.cxx @@ -32,8 +32,6 @@ #include #include -#include - #include "kt_70.hxx" diff --git a/src/Instrumentation/marker_beacon.cxx b/src/Instrumentation/marker_beacon.cxx index c9f7c9a34..f7945722d 100644 --- a/src/Instrumentation/marker_beacon.cxx +++ b/src/Instrumentation/marker_beacon.cxx @@ -31,7 +31,6 @@ #include #include -#include #include #include "marker_beacon.hxx" diff --git a/src/Instrumentation/mk_viii.cxx b/src/Instrumentation/mk_viii.cxx index a3073136a..12f3ef050 100755 --- a/src/Instrumentation/mk_viii.cxx +++ b/src/Instrumentation/mk_viii.cxx @@ -182,6 +182,8 @@ MK_VIII::PropertiesHandler::init () mk_node(altimeter_serviceable) = fgGetNode("/instrumentation/altimeter/serviceable", true); mk_node(altitude) = fgGetNode("/position/altitude-ft", true); mk_node(altitude_agl) = fgGetNode("/position/altitude-agl-ft", true); + mk_node(altitude_gear_agl) = fgGetNode("/position/gear-agl-ft", true); + mk_node(orientation_roll) = fgGetNode("/orientation/roll-deg", true); mk_node(asi_serviceable) = fgGetNode("/instrumentation/airspeed-indicator/serviceable", true); mk_node(asi_speed) = fgGetNode("/instrumentation/airspeed-indicator/indicated-speed-kt", true); mk_node(autopilot_heading_lock) = fgGetNode("/autopilot/locks/heading", true); @@ -712,7 +714,10 @@ MK_VIII::ConfigurationModule::read_options_select_group_1 (int value) bool MK_VIII::ConfigurationModule::read_radio_altitude_input_select (int value) { - // unimplemented + if (value >= 0 && value <= 2) + mk->io_handler.conf.use_gear_altitude = true; + else + mk->io_handler.conf.use_gear_altitude = false; return (value >= 0 && value <= 4) || (value >= 251 && value <= 255); } @@ -732,7 +737,10 @@ MK_VIII::ConfigurationModule::read_navigation_input_select (int value) bool MK_VIII::ConfigurationModule::read_attitude_input_select (int value) { - // unimplemented + if (value == 2) + mk->io_handler.conf.use_attitude_indicator=true; + else + mk->io_handler.conf.use_attitude_indicator=false; return (value >= 0 && value <= 6) || value == 253 || value == 255; } @@ -1144,9 +1152,13 @@ MK_VIII::IOHandler::update_inputs () mk_ainput(barometric_altitude_rate).set(mk_node(vs)->getDoubleValue() * 60); if (mk_ainput_feed(radio_altitude)) { + double agl; + if (conf.use_gear_altitude) + agl = mk_node(altitude_gear_agl)->getDoubleValue(); + else + agl = mk_node(altitude_agl)->getDoubleValue(); // Some flight models may return negative values when on the // ground or after a crash; do not allow them. - double agl = mk_node(altitude_agl)->getDoubleValue(); mk_ainput(radio_altitude).set(SG_MAX2(0.0, agl)); } if (mk_ainput_feed(glideslope_deviation)) @@ -1164,11 +1176,20 @@ MK_VIII::IOHandler::update_inputs () } if (mk_ainput_feed(roll_angle)) { + if (conf.use_attitude_indicator) + { + // read data from attitude indicator instrument (requires vacuum system to work) if (mk_node(ai_serviceable)->getBoolValue() && ! mk_node(ai_caged)->getBoolValue()) mk_ainput(roll_angle).set(mk_node(ai_roll)->getDoubleValue()); else mk_ainput(roll_angle).unset(); } + else + { + // use simulator source + mk_ainput(roll_angle).set(mk_node(orientation_roll)->getDoubleValue()); + } + } if (mk_ainput_feed(localizer_deviation)) { if (mk_node(nav0_serviceable)->getBoolValue() @@ -2624,6 +2645,8 @@ MK_VIII::SelfTestHandler::stop () button_pressed = false; state = STATE_NONE; + // reset self-test handler position + current=0; } } @@ -2933,7 +2956,7 @@ MK_VIII::AlertHandler::update () // set new state - old_alerts = alerts; + old_alerts = voice_alerts; repeated_alerts = 0; altitude_callout_voice = NULL; } @@ -3764,6 +3787,7 @@ MK_VIII::Mode4Handler::update_ab () } mk_unset_alerts(mk_alert(MODE4_TOO_LOW_FLAPS) | mk_alert(MODE4_TOO_LOW_GEAR)); + ab_bias=0.0; } void @@ -3789,6 +3813,7 @@ MK_VIII::Mode4Handler::update_ab_expanded () } mk_unset_alerts(mk_alert(MODE4AB_TOO_LOW_TERRAIN)); + ab_expanded_bias=0.0; } void @@ -3805,7 +3830,10 @@ MK_VIII::Mode4Handler::update_c () && mk_data(radio_altitude).get() < mk_data(terrain_clearance).get()) handle_alert(mk_alert(MODE4C_TOO_LOW_TERRAIN), mk_data(terrain_clearance).get(), &c_bias); else + { mk_unset_alerts(mk_alert(MODE4C_TOO_LOW_TERRAIN)); + c_bias=0.0; + } } void diff --git a/src/Instrumentation/mk_viii.hxx b/src/Instrumentation/mk_viii.hxx index 7d33b1ca8..fe9f564fa 100755 --- a/src/Instrumentation/mk_viii.hxx +++ b/src/Instrumentation/mk_viii.hxx @@ -200,6 +200,8 @@ class MK_VIII : public SGSubsystem SGPropertyNode_ptr altimeter_serviceable; SGPropertyNode_ptr altitude; SGPropertyNode_ptr altitude_agl; + SGPropertyNode_ptr altitude_gear_agl; + SGPropertyNode_ptr orientation_roll; SGPropertyNode_ptr asi_serviceable; SGPropertyNode_ptr asi_speed; SGPropertyNode_ptr autopilot_heading_lock; @@ -479,6 +481,8 @@ public: bool alternate_steep_approach; bool use_internal_gps; bool localizer_enabled; + bool use_gear_altitude; + bool use_attitude_indicator; } conf; struct _s_input_feeders @@ -1358,7 +1362,7 @@ private: } conf; inline Mode4Handler (MK_VIII *device) - : mk(device) {} + : mk(device),ab_bias(0.0),ab_expanded_bias(0.0),c_bias(0.0) {} double get_upper_agl (const EnvelopesConfiguration *c); void update (); @@ -1402,7 +1406,7 @@ private: public: inline Mode5Handler (MK_VIII *device) - : mk(device) {} + : mk(device), soft_bias(0.0) {} void update (); }; diff --git a/src/Instrumentation/navradio.cxx b/src/Instrumentation/navradio.cxx index cdf617530..0970cae5a 100644 --- a/src/Instrumentation/navradio.cxx +++ b/src/Instrumentation/navradio.cxx @@ -28,15 +28,16 @@ #include "navradio.hxx" #include +#include #include #include -#include #include #include #include #include #include +#include #include @@ -878,12 +879,12 @@ void FGNavRadio::search() } _navaid = nav; - char identBuffer[5] = " "; + string identBuffer(4, ' '); if (nav) { _dme = globals->get_dmelist()->findByFreq(freq, pos); nav_id_node->setStringValue(nav->get_ident()); - strncpy(identBuffer, nav->ident().c_str(), 5); + identBuffer = simgear::strutils::rpad( nav->ident(), 4, ' ' ); effective_range = adjustNavRange(nav->get_elev_ft(), pos.getElevationM(), nav->get_range()); loc_node->setBoolValue(nav->type() != FGPositioned::VOR); diff --git a/src/Instrumentation/od_gauge.cxx b/src/Instrumentation/od_gauge.cxx index e5eed1efc..707030ef6 100644 --- a/src/Instrumentation/od_gauge.cxx +++ b/src/Instrumentation/od_gauge.cxx @@ -38,7 +38,6 @@ #include #include -#include #include #include
diff --git a/src/Main/.gitignore b/src/Main/.gitignore new file mode 100644 index 000000000..5ffcb24f2 --- /dev/null +++ b/src/Main/.gitignore @@ -0,0 +1,4 @@ +fgfs +metar +runfgfs +runfgfs.bat diff --git a/src/Main/Makefile.am b/src/Main/Makefile.am index e0798d6d4..bafc88324 100644 --- a/src/Main/Makefile.am +++ b/src/Main/Makefile.am @@ -86,7 +86,8 @@ fgfs_LDADD = \ $(ATCDCL_LIBS) \ $(top_builddir)/src/Cockpit/libCockpit.a \ $(top_builddir)/src/Cockpit/built_in/libBuilt_in.a \ - $(top_builddir)/src/FDM/libFlight.a \ + $(top_builddir)/src/Network/libNetwork.a \ + $(top_builddir)/src/FDM/libFlight.a \ $(top_builddir)/src/FDM/ExternalNet/libExternalNet.a \ $(top_builddir)/src/FDM/ExternalPipe/libExternalPipe.a \ $(JSBSIM_LIBS) \ @@ -101,7 +102,6 @@ fgfs_LDADD = \ $(top_builddir)/src/Instrumentation/libInstrumentation.a \ $(top_builddir)/src/Instrumentation/HUD/libHUD.a \ $(top_builddir)/src/Model/libModel.a \ - $(top_builddir)/src/Network/libNetwork.a \ $(top_builddir)/src/Navaids/libNavaids.a \ $(top_builddir)/src/Scenery/libScenery.a \ $(top_builddir)/src/Scripting/libScripting.a \ @@ -138,4 +138,4 @@ metar_LDADD = \ metar_LDFLAGS = $(metar_PLIB_FW) -INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src -I$(top_srcdir)/src/FDM/JSBSim +INCLUDES = -I$(top_srcdir) -I$(top_srcdir)/src diff --git a/src/Main/WindowBuilder.cxx b/src/Main/WindowBuilder.cxx index 79fff968f..d1c90618f 100644 --- a/src/Main/WindowBuilder.cxx +++ b/src/Main/WindowBuilder.cxx @@ -60,6 +60,10 @@ WindowBuilder::makeDefaultTraits(bool stencil) GraphicsContext::Traits* traits = new osg::GraphicsContext::Traits; traits->readDISPLAY(); + if (traits->displayNum < 0) + traits->displayNum = 0; + if (traits->screenNum < 0) + traits->screenNum = 0; int cbits = (bpp <= 16) ? 5 : 8; int zbits = (bpp <= 16) ? 16 : 24; traits->red = traits->green = traits->blue = cbits; @@ -148,7 +152,7 @@ GraphicsWindow* WindowBuilder::buildWindow(const SGPropertyNode* winNode) string windowName; if (winNode->hasChild("window-name")) windowName = winNode->getStringValue("window-name"); - else if (winNode->hasChild("name")) + else if (winNode->hasChild("name")) windowName = winNode->getStringValue("name"); GraphicsWindow* result = 0; if (!windowName.empty()) { diff --git a/src/Main/bootstrap.cxx b/src/Main/bootstrap.cxx index 877712d35..8a360206e 100644 --- a/src/Main/bootstrap.cxx +++ b/src/Main/bootstrap.cxx @@ -57,8 +57,14 @@ using std::endl; #include "fg_os.hxx" +#ifdef _MSC_VER +char homepath[256] = ""; +char * homedir = homepath; +char *hostname = ::getenv( "COMPUTERNAME" ); +#else char *homedir = ::getenv( "HOME" ); char *hostname = ::getenv( "HOSTNAME" ); +#endif bool free_hostname = false; // foreward declaration. @@ -163,6 +169,14 @@ int _bootstrap_OSInit; // Main entry point; catch any exceptions that have made it this far. int main ( int argc, char **argv ) { +#if _MSC_VER + // Windows has no $HOME aka %HOME%, so we have to construct the full path. + // make sure it fits into the buffer. Max. path length is 255, but who knows + // what's in these environment variables? + homepath[sizeof(homepath)-1] = 0; + strncpy( homepath, ::getenv("APPDATA"), sizeof(homepath)-1 ); + strncat( homepath, "\\flightgear.org", sizeof(homepath)-strlen(homepath)-1 ); +#endif #ifdef PTW32_STATIC_LIB // Initialise static pthread win32 lib diff --git a/src/Main/fg_commands.cxx b/src/Main/fg_commands.cxx index 6131e4795..ddeab463b 100644 --- a/src/Main/fg_commands.cxx +++ b/src/Main/fg_commands.cxx @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -36,7 +37,6 @@ #include #include #include