[Orxonox-commit 3215] r7908 - in code/forks/sandbox_light: . bin cmake cmake/tools data doc/api doc/api/images src src/external src/external/ogremath src/external/ogremath/GLX src/external/ogremath/OSX src/external/ogremath/WIN32 src/libraries src/libraries/core src/libraries/util src/orxonox
rgrieder at orxonox.net
rgrieder at orxonox.net
Thu Feb 17 05:47:23 CET 2011
Author: rgrieder
Date: 2011-02-17 05:47:22 +0100 (Thu, 17 Feb 2011)
New Revision: 7908
Added:
code/forks/sandbox_light/src/external/ogremath/
code/forks/sandbox_light/src/external/ogremath/CMakeLists.txt
code/forks/sandbox_light/src/external/ogremath/GLX/
code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimer.cpp
code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimerImp.h
code/forks/sandbox_light/src/external/ogremath/OSX/
code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimer.cpp
code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimerImp.h
code/forks/sandbox_light/src/external/ogremath/OgreBitwise.h
code/forks/sandbox_light/src/external/ogremath/OgreColourValue.cpp
code/forks/sandbox_light/src/external/ogremath/OgreColourValue.h
code/forks/sandbox_light/src/external/ogremath/OgreConfig.h
code/forks/sandbox_light/src/external/ogremath/OgreMath.cpp
code/forks/sandbox_light/src/external/ogremath/OgreMath.h
code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.cpp
code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.h
code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.cpp
code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.h
code/forks/sandbox_light/src/external/ogremath/OgrePlane.cpp
code/forks/sandbox_light/src/external/ogremath/OgrePlane.h
code/forks/sandbox_light/src/external/ogremath/OgrePlatform.h
code/forks/sandbox_light/src/external/ogremath/OgrePrerequisites.h
code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.cpp
code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.h
code/forks/sandbox_light/src/external/ogremath/OgreTimer.h
code/forks/sandbox_light/src/external/ogremath/OgreVector2.cpp
code/forks/sandbox_light/src/external/ogremath/OgreVector2.h
code/forks/sandbox_light/src/external/ogremath/OgreVector3.cpp
code/forks/sandbox_light/src/external/ogremath/OgreVector3.h
code/forks/sandbox_light/src/external/ogremath/OgreVector4.cpp
code/forks/sandbox_light/src/external/ogremath/OgreVector4.h
code/forks/sandbox_light/src/external/ogremath/WIN32/
code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimer.cpp
code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimerImp.h
code/forks/sandbox_light/src/external/ogremath/asm_math.h
Removed:
code/forks/sandbox_light/README
code/forks/sandbox_light/bin/client1.bat.in
code/forks/sandbox_light/bin/client1.in
code/forks/sandbox_light/bin/client2.bat.in
code/forks/sandbox_light/bin/client2.in
code/forks/sandbox_light/bin/dedicated.bat.in
code/forks/sandbox_light/bin/dedicated.in
code/forks/sandbox_light/bin/dedicatedClient.bat.in
code/forks/sandbox_light/bin/dedicatedClient.in
code/forks/sandbox_light/bin/masterserver.bat.in
code/forks/sandbox_light/bin/masterserver.in
code/forks/sandbox_light/bin/server.bat.in
code/forks/sandbox_light/bin/server.in
code/forks/sandbox_light/bin/standalone.bat.in
code/forks/sandbox_light/bin/standalone.in
code/forks/sandbox_light/cmake/tools/CheckOGREPlugins.cmake
code/forks/sandbox_light/cmake/tools/FindALUT.cmake
code/forks/sandbox_light/cmake/tools/FindCEGUI.cmake
code/forks/sandbox_light/cmake/tools/FindDirectX.cmake
code/forks/sandbox_light/cmake/tools/FindENet.cmake
code/forks/sandbox_light/cmake/tools/FindLua.cmake
code/forks/sandbox_light/cmake/tools/FindOGRE.cmake
code/forks/sandbox_light/cmake/tools/FindOgg.cmake
code/forks/sandbox_light/cmake/tools/FindVorbis.cmake
code/forks/sandbox_light/cmake/tools/GenerateToluaBindings.cmake
code/forks/sandbox_light/data/DataInstallScript.cmake
code/forks/sandbox_light/data/DefaultResources.oxr
code/forks/sandbox_light/data/defaultConfig/
code/forks/sandbox_light/data/gui/
code/forks/sandbox_light/data/levels/
code/forks/sandbox_light/data/lua/
code/forks/sandbox_light/data/overlays/
code/forks/sandbox_light/data/particle/
code/forks/sandbox_light/data/tcl/
code/forks/sandbox_light/doc/api/images/orxonox.jpg
code/forks/sandbox_light/doc/api/images/pickupmodule.png
code/forks/sandbox_light/doc/api/images/questsystem.png
code/forks/sandbox_light/src/external/bullet/
code/forks/sandbox_light/src/external/ceguilua/
code/forks/sandbox_light/src/external/cpptcl/
code/forks/sandbox_light/src/external/enet/
code/forks/sandbox_light/src/external/ogreceguirenderer/
code/forks/sandbox_light/src/external/ois/
code/forks/sandbox_light/src/external/tinyxml/
code/forks/sandbox_light/src/external/tolua/
code/forks/sandbox_light/src/libraries/core/BaseObject.cc
code/forks/sandbox_light/src/libraries/core/BaseObject.h
code/forks/sandbox_light/src/libraries/core/ClassFactory.h
code/forks/sandbox_light/src/libraries/core/ClassTreeMask.cc
code/forks/sandbox_light/src/libraries/core/ClassTreeMask.h
code/forks/sandbox_light/src/libraries/core/ConfigFileManager.cc
code/forks/sandbox_light/src/libraries/core/ConfigFileManager.h
code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.cc
code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.h
code/forks/sandbox_light/src/libraries/core/ConfigValueIncludes.h
code/forks/sandbox_light/src/libraries/core/CoreIncludes.h
code/forks/sandbox_light/src/libraries/core/CorePrecompiledHeaders.h
code/forks/sandbox_light/src/libraries/core/DynLib.cc
code/forks/sandbox_light/src/libraries/core/DynLib.h
code/forks/sandbox_light/src/libraries/core/DynLibManager.cc
code/forks/sandbox_light/src/libraries/core/DynLibManager.h
code/forks/sandbox_light/src/libraries/core/Event.cc
code/forks/sandbox_light/src/libraries/core/Event.h
code/forks/sandbox_light/src/libraries/core/EventIncludes.h
code/forks/sandbox_light/src/libraries/core/GUIManager.cc
code/forks/sandbox_light/src/libraries/core/GUIManager.h
code/forks/sandbox_light/src/libraries/core/Game.cc
code/forks/sandbox_light/src/libraries/core/Game.h
code/forks/sandbox_light/src/libraries/core/GameMode.cc
code/forks/sandbox_light/src/libraries/core/GameMode.h
code/forks/sandbox_light/src/libraries/core/GameState.cc
code/forks/sandbox_light/src/libraries/core/GameState.h
code/forks/sandbox_light/src/libraries/core/GraphicsManager.cc
code/forks/sandbox_light/src/libraries/core/GraphicsManager.h
code/forks/sandbox_light/src/libraries/core/Identifier.cc
code/forks/sandbox_light/src/libraries/core/Identifier.h
code/forks/sandbox_light/src/libraries/core/Iterator.h
code/forks/sandbox_light/src/libraries/core/Language.cc
code/forks/sandbox_light/src/libraries/core/Language.h
code/forks/sandbox_light/src/libraries/core/Loader.cc
code/forks/sandbox_light/src/libraries/core/Loader.h
code/forks/sandbox_light/src/libraries/core/LuaState.cc
code/forks/sandbox_light/src/libraries/core/LuaState.h
code/forks/sandbox_light/src/libraries/core/MemoryArchive.cc
code/forks/sandbox_light/src/libraries/core/MemoryArchive.h
code/forks/sandbox_light/src/libraries/core/MetaObjectList.cc
code/forks/sandbox_light/src/libraries/core/MetaObjectList.h
code/forks/sandbox_light/src/libraries/core/Namespace.cc
code/forks/sandbox_light/src/libraries/core/Namespace.h
code/forks/sandbox_light/src/libraries/core/NamespaceNode.cc
code/forks/sandbox_light/src/libraries/core/NamespaceNode.h
code/forks/sandbox_light/src/libraries/core/ObjectList.h
code/forks/sandbox_light/src/libraries/core/ObjectListBase.cc
code/forks/sandbox_light/src/libraries/core/ObjectListBase.h
code/forks/sandbox_light/src/libraries/core/ObjectListIterator.h
code/forks/sandbox_light/src/libraries/core/OrxonoxClass.cc
code/forks/sandbox_light/src/libraries/core/OrxonoxClass.h
code/forks/sandbox_light/src/libraries/core/Resource.cc
code/forks/sandbox_light/src/libraries/core/Resource.h
code/forks/sandbox_light/src/libraries/core/SmartPtr.h
code/forks/sandbox_light/src/libraries/core/SubclassIdentifier.h
code/forks/sandbox_light/src/libraries/core/Super.h
code/forks/sandbox_light/src/libraries/core/Template.cc
code/forks/sandbox_light/src/libraries/core/Template.h
code/forks/sandbox_light/src/libraries/core/Thread.cc
code/forks/sandbox_light/src/libraries/core/Thread.h
code/forks/sandbox_light/src/libraries/core/ThreadPool.cc
code/forks/sandbox_light/src/libraries/core/ThreadPool.h
code/forks/sandbox_light/src/libraries/core/ToluaInterface.h
code/forks/sandbox_light/src/libraries/core/WeakPtr.h
code/forks/sandbox_light/src/libraries/core/WindowEventListener.cc
code/forks/sandbox_light/src/libraries/core/WindowEventListener.h
code/forks/sandbox_light/src/libraries/core/XMLFile.h
code/forks/sandbox_light/src/libraries/core/XMLNameListener.cc
code/forks/sandbox_light/src/libraries/core/XMLNameListener.h
code/forks/sandbox_light/src/libraries/core/XMLPort.cc
code/forks/sandbox_light/src/libraries/core/XMLPort.h
code/forks/sandbox_light/src/libraries/core/command/
code/forks/sandbox_light/src/libraries/core/input/
code/forks/sandbox_light/src/libraries/network/
code/forks/sandbox_light/src/libraries/tools/
code/forks/sandbox_light/src/libraries/util/Clipboard.cc
code/forks/sandbox_light/src/libraries/util/Clipboard.h
code/forks/sandbox_light/src/libraries/util/DisplayStringConversions.h
code/forks/sandbox_light/src/libraries/util/ExprParser.cc
code/forks/sandbox_light/src/libraries/util/ExprParser.h
code/forks/sandbox_light/src/libraries/util/Scope.cc
code/forks/sandbox_light/src/libraries/util/Scope.h
code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.cc
code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.h
code/forks/sandbox_light/src/libraries/util/Serialise.h
code/forks/sandbox_light/src/modules/
code/forks/sandbox_light/src/orxonox/CameraManager.cc
code/forks/sandbox_light/src/orxonox/CameraManager.h
code/forks/sandbox_light/src/orxonox/ChatHistory.cc
code/forks/sandbox_light/src/orxonox/ChatHistory.h
code/forks/sandbox_light/src/orxonox/ChatInputHandler.cc
code/forks/sandbox_light/src/orxonox/ChatInputHandler.h
code/forks/sandbox_light/src/orxonox/Level.cc
code/forks/sandbox_light/src/orxonox/Level.h
code/forks/sandbox_light/src/orxonox/LevelInfo.cc
code/forks/sandbox_light/src/orxonox/LevelInfo.h
code/forks/sandbox_light/src/orxonox/LevelManager.cc
code/forks/sandbox_light/src/orxonox/LevelManager.h
code/forks/sandbox_light/src/orxonox/MoodManager.cc
code/forks/sandbox_light/src/orxonox/MoodManager.h
code/forks/sandbox_light/src/orxonox/PawnManager.cc
code/forks/sandbox_light/src/orxonox/PawnManager.h
code/forks/sandbox_light/src/orxonox/PlayerManager.cc
code/forks/sandbox_light/src/orxonox/PlayerManager.h
code/forks/sandbox_light/src/orxonox/Radar.cc
code/forks/sandbox_light/src/orxonox/Radar.h
code/forks/sandbox_light/src/orxonox/Scene.cc
code/forks/sandbox_light/src/orxonox/Scene.h
code/forks/sandbox_light/src/orxonox/Test.cc
code/forks/sandbox_light/src/orxonox/Test.h
code/forks/sandbox_light/src/orxonox/collisionshapes/
code/forks/sandbox_light/src/orxonox/controllers/
code/forks/sandbox_light/src/orxonox/gamestates/
code/forks/sandbox_light/src/orxonox/gametypes/
code/forks/sandbox_light/src/orxonox/graphics/
code/forks/sandbox_light/src/orxonox/infos/
code/forks/sandbox_light/src/orxonox/interfaces/
code/forks/sandbox_light/src/orxonox/items/
code/forks/sandbox_light/src/orxonox/overlays/
code/forks/sandbox_light/src/orxonox/pickup/
code/forks/sandbox_light/src/orxonox/sound/
code/forks/sandbox_light/src/orxonox/weaponsystem/
code/forks/sandbox_light/src/orxonox/worldentities/
Modified:
code/forks/sandbox_light/CMakeLists.txt
code/forks/sandbox_light/INSTALL
code/forks/sandbox_light/bin/CMakeLists.txt
code/forks/sandbox_light/cmake/InstallConfig.cmake
code/forks/sandbox_light/cmake/LibraryConfig.cmake
code/forks/sandbox_light/cmake/LibraryConfigTardis.cmake
code/forks/sandbox_light/cmake/PackageConfig.cmake
code/forks/sandbox_light/cmake/PackageConfigMSVC.cmake
code/forks/sandbox_light/cmake/PackageConfigMinGW.cmake
code/forks/sandbox_light/cmake/tools/TargetUtilities.cmake
code/forks/sandbox_light/data/CMakeLists.txt
code/forks/sandbox_light/doc/api/Groups.dox
code/forks/sandbox_light/doc/api/main.dox
code/forks/sandbox_light/src/CMakeLists.txt
code/forks/sandbox_light/src/SpecialConfig.h.in
code/forks/sandbox_light/src/external/CMakeLists.txt
code/forks/sandbox_light/src/libraries/CMakeLists.txt
code/forks/sandbox_light/src/libraries/core/CMakeLists.txt
code/forks/sandbox_light/src/libraries/core/Core.cc
code/forks/sandbox_light/src/libraries/core/Core.h
code/forks/sandbox_light/src/libraries/core/CorePrereqs.h
code/forks/sandbox_light/src/libraries/core/PathConfig.cc
code/forks/sandbox_light/src/libraries/core/PathConfig.h
code/forks/sandbox_light/src/libraries/util/CMakeLists.txt
code/forks/sandbox_light/src/libraries/util/Clock.cc
code/forks/sandbox_light/src/libraries/util/Exception.cc
code/forks/sandbox_light/src/libraries/util/Math.cc
code/forks/sandbox_light/src/libraries/util/Math.h
code/forks/sandbox_light/src/libraries/util/MultiType.h
code/forks/sandbox_light/src/libraries/util/MultiTypeValue.h
code/forks/sandbox_light/src/libraries/util/UtilPrereqs.h
code/forks/sandbox_light/src/orxonox/CMakeLists.txt
code/forks/sandbox_light/src/orxonox/Main.cc
code/forks/sandbox_light/src/orxonox/OrxonoxPrecompiledHeaders.h
code/forks/sandbox_light/src/orxonox/OrxonoxPrereqs.h
Log:
Stripped down trunk to form a new light sandbox.
Modified: code/forks/sandbox_light/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -51,7 +51,6 @@
SET(DEFAULT_RUNTIME_PATH bin)
SET(DEFAULT_LIBRARY_PATH lib)
SET(DEFAULT_ARCHIVE_PATH lib/static)
-SET(DEFAULT_MODULE_PATH lib/modules)
SET(DEFAULT_DOC_PATH doc)
SET(DEFAULT_DATA_PATH data)
SET(DEFAULT_CONFIG_PATH config)
@@ -61,15 +60,11 @@
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_RUNTIME_PATH})
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_LIBRARY_PATH})
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_ARCHIVE_PATH})
-SET(CMAKE_MODULE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_MODULE_PATH})
SET(CMAKE_DOC_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_DOC_PATH})
# Data directories are only inputs, no delclaration here
SET(CMAKE_CONFIG_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_CONFIG_PATH})
SET(CMAKE_LOG_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${DEFAULT_LOG_PATH})
-# Set the extension of the dynamic modules
-SET(ORXONOX_MODULE_EXTENSION ".module")
-
# Sets where to find the external libraries like OgreMain.dll at runtime
# On Unix you should not have to change this at all.
# This only applies to development runs in the build tree
Modified: code/forks/sandbox_light/INSTALL
===================================================================
--- code/forks/sandbox_light/INSTALL 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/INSTALL 2011-02-17 04:47:22 UTC (rev 7908)
@@ -8,19 +8,7 @@
In order to compile Orxonox you will need the following libraries:
(for windows there are already precompiled packages on the website)
-OGRE 3D Graphics Engine 1.4 - 1.7
-CEGUI (Crazy Eddie's GUI System) 0.5 - 0.6
Boost libraries 1.35 -
-ENet (Network library) 1.1 - 1.2
-Lua (scripting language) 5.0 - 5.1
-Tcl (shell script language) 8.4 - 8.5
-OpenAL (audio) (no version requirements specified yet)
-ALUT (audio) (no version requirements specified yet)
-LibOgg (no version requirements specified yet)
-LibVorbis (no version requirements specified yet)
-ZLib (compression) (no version requirements specified yet)
-OGRE supports both OpenGL and DirectX9 rendering. You will also need OGRE for the dedicated server!
-
Further information about installing and running this application can be found on
http://www.orxonox.net/wiki/Running
Deleted: code/forks/sandbox_light/README
===================================================================
--- code/forks/sandbox_light/README 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/README 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,20 +0,0 @@
-Hi there,
-
-We are proud to present you Orxonox - the most ferious 3D space shooter ever to exist.
-
-This game is free, if you have paid for this, get your money back! The source code of this game is licensed under the GPL (GNU General Public License).
-The game content is licensed under the Creative Commons Attribution-Sharealike 3.0 license. For more information read LICENSE in the same folder you found this file.
-
-For directions to install this game, please check out the file INSTALL or http://www.orxonox.net/wiki/Running
-
-This application uses the Ogre Graphics Engine (http://www.ogre3d.org), if you haven't already downloaded a precompiled version of Ogre with this package. Visit our webpage to get your Orxonox compatible version of the Ogre libraries.
-
-This is an open source game. If you want to contribute check out http://www.orxonox.net/wiki/development to find more information how you could help us making the game better. We are always looking for programmers and content designers, who like to contribute.
-
-We hope you have fun playing the game. Check out http://www.orxonox.net for news and newer versions of the game.
-
-Please contact us in our forum ( http://forum.orxonox.net ) or check out our contact page ( http://www.orxonox.net/wiki/about#Contact ). We hope to hear from you and are looking forward to your feedback.
-
-
-Cheers,
-The Orxonox Development Team
Modified: code/forks/sandbox_light/bin/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/bin/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -25,7 +25,7 @@
#
# Create run scripts for Windows to manually add the DLL path when executing
-SET(RUN_SCRIPTS run standalone client1 client2 server dedicated dedicatedClient masterserver)
+SET(RUN_SCRIPTS run)
IF(WIN32)
FOREACH(_script ${RUN_SCRIPTS})
LIST(REMOVE_ITEM RUN_SCRIPTS ${_script})
Deleted: code/forks/sandbox_light/bin/client1.bat.in
===================================================================
--- code/forks/sandbox_light/bin/client1.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/client1.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --client --writingPathSuffix client1
-pause
Deleted: code/forks/sandbox_light/bin/client1.in
===================================================================
--- code/forks/sandbox_light/bin/client1.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/client1.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --client --writingPathSuffix client1 $@
Deleted: code/forks/sandbox_light/bin/client2.bat.in
===================================================================
--- code/forks/sandbox_light/bin/client2.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/client2.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --client --writingPathSuffix client2
-pause
Deleted: code/forks/sandbox_light/bin/client2.in
===================================================================
--- code/forks/sandbox_light/bin/client2.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/client2.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --client --writingPathSuffix client2 $@
Deleted: code/forks/sandbox_light/bin/dedicated.bat.in
===================================================================
--- code/forks/sandbox_light/bin/dedicated.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/dedicated.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --dedicated --writingPathSuffix dedicated
-pause
Deleted: code/forks/sandbox_light/bin/dedicated.in
===================================================================
--- code/forks/sandbox_light/bin/dedicated.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/dedicated.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --dedicated --writingPathSuffix dedicated $@
Deleted: code/forks/sandbox_light/bin/dedicatedClient.bat.in
===================================================================
--- code/forks/sandbox_light/bin/dedicatedClient.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/dedicatedClient.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --dedicatedClient --writingPathSuffix dedicatedClient
-pause
Deleted: code/forks/sandbox_light/bin/dedicatedClient.in
===================================================================
--- code/forks/sandbox_light/bin/dedicatedClient.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/dedicatedClient.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --dedicatedClient --writingPathSuffix dedicatedClient $@
Deleted: code/forks/sandbox_light/bin/masterserver.bat.in
===================================================================
--- code/forks/sandbox_light/bin/masterserver.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/masterserver.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --masterserver --writingPathSuffix masterserver
-pause
Deleted: code/forks/sandbox_light/bin/masterserver.in
===================================================================
--- code/forks/sandbox_light/bin/masterserver.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/masterserver.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --masterserver --writingPathSuffix masterserver $@
Deleted: code/forks/sandbox_light/bin/server.bat.in
===================================================================
--- code/forks/sandbox_light/bin/server.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/server.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --server --writingPathSuffix server
-pause
Deleted: code/forks/sandbox_light/bin/server.in
===================================================================
--- code/forks/sandbox_light/bin/server.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/server.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --server --writingPathSuffix server $@
Deleted: code/forks/sandbox_light/bin/standalone.bat.in
===================================================================
--- code/forks/sandbox_light/bin/standalone.bat.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/standalone.bat.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-title @PROJECT_NAME@
-path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
- at CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --standalone --writingPathSuffix standalone
-pause
Deleted: code/forks/sandbox_light/bin/standalone.in
===================================================================
--- code/forks/sandbox_light/bin/standalone.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/bin/standalone.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,4 +0,0 @@
-#!/bin/sh
-# convenience script for starting orxonox on Linux
-
-exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --standalone --writingPathSuffix standalone $@
Modified: code/forks/sandbox_light/cmake/InstallConfig.cmake
===================================================================
--- code/forks/sandbox_light/cmake/InstallConfig.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/InstallConfig.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -42,7 +42,6 @@
SET(RUNTIME_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_RUNTIME_PATH})
SET(LIBRARY_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_LIBRARY_PATH})
SET(ARCHIVE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_ARCHIVE_PATH})
-SET(MODULE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_MODULE_PATH})
SET(DOC_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_DOC_PATH})
SET(DATA_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_DATA_PATH})
SET(CONFIG_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/${DEFAULT_CONFIG_PATH})
@@ -54,7 +53,6 @@
SET(RUNTIME_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/games)
SET(LIBRARY_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/lib/games/orxonox)
SET(ARCHIVE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/lib/games/orxonox/static)
- SET(MODULE_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/lib/games/orxonox/modules)
SET(DOC_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/share/doc/orxonox)
SET(DATA_INSTALL_DIRECTORY ${CMAKE_INSTALL_PREFIX}/share/games/orxonox)
ENDIF()
Modified: code/forks/sandbox_light/cmake/LibraryConfig.cmake
===================================================================
--- code/forks/sandbox_light/cmake/LibraryConfig.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/LibraryConfig.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -92,71 +92,11 @@
############### Library finding #################
# Performs the search and sets the variables #
-FIND_PACKAGE(OGRE 1.4 REQUIRED)
-#FIND_PACKAGE(ENet 1.1 REQUIRED)
-FIND_PACKAGE(Ogg REQUIRED)
-FIND_PACKAGE(Vorbis REQUIRED)
-FIND_PACKAGE(ALUT REQUIRED)
-FIND_PACKAGE(ZLIB REQUIRED)
-IF(POCO_REQUIRED)
- FIND_PACKAGE(POCO REQUIRED)
-ENDIF()
+#FIND_PACKAGE(POCO REQUIRED)
IF(WIN32)
FIND_PACKAGE(DbgHelp)
- FIND_PACKAGE(DirectX REQUIRED)
ENDIF()
-##### CEGUI #####
-# We make use of the CEGUI script module called CEGUILua.
-# However there is a small issue with that: We use Tolua, a C++ binding
-# generator ourselves. And we also have to use our bindings in the same
-# lua state is CEGUILua's. Unfortunately this implies that both lua runtime
-# version are equal or else you get segmentation faults.
-# In order to match the Lua versions we decided to ship CEGUILua in our
-# repository, mainly because there is no way to determine which version of
-# Lua CEGUILua was linked against (you'd have to specify yourself) and secondly
-# because we can then choose the Lua version. Future plans might involve only
-# accepting Lua 5.1.
-
-# Insert all internally supported CEGUILua versions here
-SET(CEGUILUA_INTERNAL_SUPPORT 0.5.0 0.6.0 0.6.1 0.6.2)
-OPTION(CEGUILUA_USE_EXTERNAL_LIBRARY "Force the use of external CEGUILua library" OFF)
-FIND_PACKAGE(CEGUI 0.5 REQUIRED)
-
-##### Lua #####
-IF(CEGUILUA_USE_EXTERNAL_LIBRARY)
- COMPARE_VERSION_STRINGS(${CEGUI_VERSION} "0.6" _version_comparison)
- IF(version_comparison LESS 0)
- SET(LUA_VERSION_REQUEST 5.0)
- ELSE()
- SET(LUA_VERSION_REQUEST 5.1)
- ENDIF()
-ELSE()
- SET(LUA_VERSION_REQUEST 5)
-ENDIF()
-FIND_PACKAGE(Lua ${LUA_VERSION_REQUEST} EXACT REQUIRED)
-
-##### OpenAL #####
-FIND_PACKAGE(OpenAL REQUIRED)
-# Also use parent include dir (without AL/) for ALUT
-IF(OPENAL_INCLUDE_DIR MATCHES "/AL$")
- GET_FILENAME_COMPONENT(ALT_OPENAL_INCLUDE_DIR ${OPENAL_INCLUDE_DIR} PATH)
-ENDIF()
-SET(OPENAL_INCLUDE_DIRS ${OPENAL_INCLUDE_DIR} ${ALT_OPENAL_INCLUDE_DIR})
-# Notfiy user
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenAL DEFAULT_MSG OPENAL_LIBRARY OPENAL_INCLUDE_DIR)
-# Hide variables created by the script
-MARK_AS_ADVANCED(OPENAL_INCLUDE_DIR OPENAL_LIBRARY)
-
-##### Tcl #####
-# We only require Tcl, so avoid confusing user about other Tcl stuff by
-# applying a little workaround
-SET(Tclsh_FIND_QUIETLY TRUE)
-FIND_PACKAGE(TCL QUIET)
-# Display messages separately
-SET(TCL_FIND_QUIETLY FALSE)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(TCL DEFAULT_MSG TCL_LIBRARY TCL_INCLUDE_PATH)
-
##### Boost #####
# Expand the next statement if newer boost versions than 1.36.1 are released
SET(Boost_ADDITIONAL_VERSIONS 1.37 1.37.0 1.38 1.38.0 1.39 1.39.0 1.40 1.40.0
@@ -175,41 +115,8 @@
# Note: Default option in the libraries vary, but our default option is dynamic
IF(WIN32)
OPTION(LINK_BOOST_DYNAMIC "Link Boost dynamically on Windows" TRUE)
- OPTION(LINK_CEGUI_DYNAMIC "Link CEGUI dynamicylly on Windows" TRUE)
- #OPTION(LINK_ENET_DYNAMIC "Link ENet dynamically on Windows" TRUE)
- OPTION(LINK_OGRE_DYNAMIC "Link OGRE dynamically on Windows" TRUE)
- OPTION(LINK_TCL_DYNAMIC "Link TCL dynamically on Windows" TRUE)
- OPTION(LINK_ZLIB_DYNAMIC "Link ZLib dynamically on Windows" TRUE)
- COMPARE_VERSION_STRINGS("${LUA_VERSION}" "5.1" _version_comparison)
- IF(_version_comparison LESS 0)
- OPTION(LINK_LUA_DYNAMIC "Link Lua dynamically on Windows" FALSE)
- ELSE(_version_comparison LESS 0)
- OPTION(LINK_LUA_DYNAMIC "Link Lua dynamically on Windows" TRUE)
- ENDIF(_version_comparison LESS 0)
IF(DEPENDENCY_PACKAGE_ENABLE)
- MARK_AS_ADVANCED(
- LINK_BOOST_DYNAMIC LINK_CEGUI_DYNAMIC #LINK_ENET_DYNAMIC
- LINK_OGRE_DYNAMIC LINK_TCL_DYNAMIC LINK_ZLIB_DYNAMIC
- LINK_LUA_DYNAMIC
- )
+ MARK_AS_ADVANCED(LINK_BOOST_DYNAMIC)
ENDIF()
ENDIF(WIN32)
-
-
-################# OGRE Plugins ##################
-
-# More plugins: Plugin_BSPSceneManager, Plugin_OctreeSceneManager
-SET(OGRE_PLUGINS_INT Plugin_ParticleFX)
-IF(WIN32)
- # CG program manager is probably DirectX related (not available under unix)
- LIST(APPEND OGRE_PLUGINS_INT Plugin_CgProgramManager)
-ENDIF(WIN32)
-SET(OGRE_PLUGINS ${OGRE_PLUGINS_INT} CACHE STRING
- "Specify which OGRE plugins to load. Existance check is performed.")
-
-# Check the plugins and determine the plugin folder
-# You can give a hint by setting the environment variable ENV{OGRE_PLUGIN_DIR}
-INCLUDE(CheckOGREPlugins)
-CHECK_OGRE_PLUGINS(${OGRE_PLUGINS})
-
Modified: code/forks/sandbox_light/cmake/LibraryConfigTardis.cmake
===================================================================
--- code/forks/sandbox_light/cmake/LibraryConfigTardis.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/LibraryConfigTardis.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -71,13 +71,4 @@
LIST(APPEND CMAKE_INCLUDE_PATH "/usr/pack/ogre-1.6.1-sd")
LIST(APPEND CMAKE_LIBRARY_PATH "/usr/pack/ogre-1.6.1-sd/i686-debian-linux5.0")
- #SET(ENV{CEGUIDIR} "/usr/pack/cegui-0.6.2-sd;/usr/pack/cegui-0.6.2-sd/i686-debian-linux5.0")
- #SET(ENV{ENETDIR} "/usr/pack/enet-1.2-sd;/usr/pack/enet-1.2-sd/i686-debian-linux4.0")
- #SET(ENV{ALUTDIR} "/usr/pack/openal-0.0.8-cl;/usr/pack/openal-0.0.8-cl/i686-debian-linux3.1")
- #SET(ENV{OGGDIR} "/usr/pack/oggvorbis-1.0-ds;/usr/pack/oggvorbis-1.0-ds/i686-debian-linux3.0")
- #SET(ENV{VORBISDIR} "/usr/pack/oggvorbis-1.0-ds;/usr/pack/oggvorbis-1.0-ds/i686-debian-linux3.0")
- #SET(ENV{LUA_DIR} "/usr/pack/lua-5.1.4-sd;/usr/pack/lua-5.1.4-sd/i686-debian-linux4.0")
- #SET(ENV{OGRE_HOME} "/usr/pack/ogre-1.4.9-sd;/usr/pack/ogre-1.4.9-sd/i686-debian-linux4.0")
- #SET(ENV{OPENALDIR} "/usr/pack/openal-0.0.8-cl;/usr/pack/openal-0.0.8-cl/i686-debian-linux3.1")
- #SET(TCL_INCLUDE_PATH "/usr/pack/tcltk-8.4.9.linux-mo/include")
ENDIF(TARDIS)
Modified: code/forks/sandbox_light/cmake/PackageConfig.cmake
===================================================================
--- code/forks/sandbox_light/cmake/PackageConfig.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/PackageConfig.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -77,30 +77,12 @@
ENDIF()
# Include paths and other special treatments
-SET(ENV{ALUTDIR} ${DEP_INCLUDE_DIR}/freealut)
SET(ENV{BOOST_ROOT} ${DEP_INCLUDE_DIR}/boost)
-SET(ENV{CEGUIDIR} ${DEP_INCLUDE_DIR}/cegui)
SET(ENV{DBGHELP_DIR} ${DEP_INCLUDE_DIR}/dbghelp)
-SET(ENV{DXSDK_DIR} ${DEP_INCLUDE_DIR}/directx)
-#SET(ENV{ENETDIR} ${DEP_INCLUDE_DIR}/enet)
-SET(ENV{LUA_DIR} ${DEP_INCLUDE_DIR}/lua)
-SET(ENV{OGGDIR} ${DEP_INCLUDE_DIR}/libogg)
-SET(ENV{VORBISDIR} ${DEP_INCLUDE_DIR}/libvorbis)
-SET(ENV{OGRE_HOME} ${DEP_INCLUDE_DIR}/ogre)
-SET(ENV{OGRE_PLUGIN_DIR} ${DEP_BINARY_DIR})
-SET(ENV{OPENALDIR} ${DEP_INCLUDE_DIR}/openal)
SET(ENV{POCODIR} ${DEP_INCLUDE_DIR}/poco)
-LIST(APPEND CMAKE_INCLUDE_PATH ${DEP_INCLUDE_DIR}/tcl/include)
-LIST(APPEND CMAKE_INCLUDE_PATH ${DEP_INCLUDE_DIR}/zlib/include)
### INSTALL ###
-# Tcl script library
-INSTALL(
- DIRECTORY ${DEP_LIBRARY_DIR}/tcl/
- DESTINATION lib/tcl
-)
-
# On Windows, DLLs have to be in the executable folder, install them
IF(WIN32 AND DEP_BINARY_DIR)
## DEBUG
Modified: code/forks/sandbox_light/cmake/PackageConfigMSVC.cmake
===================================================================
--- code/forks/sandbox_light/cmake/PackageConfigMSVC.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/PackageConfigMSVC.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -53,7 +53,6 @@
# Certain find scripts don't behave as ecpected to we have
# to specify the libraries ourselves.
- SET(TCL_LIBRARY ${DEP_LIBRARY_DIR}/tcl85.lib CACHE FILEPATH "")
- SET(ZLIB_LIBRARY ${DEP_LIBRARY_DIR}/zdll.lib CACHE FILEPATH "")
+ #SET(ZLIB_LIBRARY ${DEP_LIBRARY_DIR}/zdll.lib CACHE FILEPATH "")
ENDIF(MSVC)
Modified: code/forks/sandbox_light/cmake/PackageConfigMinGW.cmake
===================================================================
--- code/forks/sandbox_light/cmake/PackageConfigMinGW.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/PackageConfigMinGW.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -46,7 +46,6 @@
# Certain find scripts don't behave as ecpected to we have
# to specify the libraries ourselves.
- SET(TCL_LIBRARY ${DEP_BINARY_DIR}/tcl85.dll CACHE FILEPATH "")
- SET(ZLIB_LIBRARY ${DEP_BINARY_DIR}/zlib1.dll CACHE FILEPATH "")
+ #SET(ZLIB_LIBRARY ${DEP_BINARY_DIR}/zlib1.dll CACHE FILEPATH "")
ENDIF(MINGW)
Deleted: code/forks/sandbox_light/cmake/tools/CheckOGREPlugins.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/CheckOGREPlugins.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/CheckOGREPlugins.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,120 +0,0 @@
- #
- # ORXONOX - the hottest 3D action shooter ever to exist
- # > www.orxonox.net <
- #
- # 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.
- #
- #
- # Author:
- # Reto Grieder
- # Description:
- # Function that checks each OGRE plugin for existance. Also looks for debug
- # versions and sets them accordingly.
- # All the plugins specified as function arguments have to be found or the
- # script will issue a fatal error. Additionally, all release plugins have
- # to be found in the same folder. Analogously for debug plugins.
- # Output:
- # OGRE_PLUGINS_FOLDER_DEBUG Folder with the debug plugins
- # OGRE_PLUGINS_FOLDER_RELEASE Folder with the release plugins
- # OGRE_PLUGINS_DEBUG Names of the debug plugins without extension
- # OGRE_PLUGINS_RELEASE Names of the release plugins without ext.
- # Note:
- # You must not specify render systems as input. That will be taken care of
- # automatically.
- #
-
-FUNCTION(CHECK_OGRE_PLUGINS)
-
- SET(OGRE_PLUGINS ${ARGN})
-
- IF(WIN32)
- # On Windows we need only *.dll, not *.lib. Especially the MSVC generator doesn't look for *.dll
- SET(CMAKE_FIND_LIBRARY_SUFFIXES .dll)
- ENDIF(WIN32)
- # Do not prefix "lib" on any platform
- SET(CMAKE_FIND_LIBRARY_PREFIXES "")
-
- SET(OGRE_RENDER_SYSTEMS RenderSystem_GL RenderSystem_Direct3D9)
- SET(OGRE_RENDER_SYSTEM_FOUND FALSE)
- FOREACH(_plugin ${OGRE_PLUGINS} ${OGRE_RENDER_SYSTEMS})
- FIND_LIBRARY(OGRE_PLUGIN_${_plugin}_OPTIMIZED
- NAMES ${_plugin}
- PATHS $ENV{OGRE_HOME} $ENV{OGRE_PLUGIN_DIR}
- PATH_SUFFIXES bin/Release bin/release Release release lib lib/OGRE bin
- )
- FIND_LIBRARY(OGRE_PLUGIN_${_plugin}_DEBUG
- NAMES ${_plugin}d ${_plugin}_d ${_plugin}
- PATHS $ENV{OGRE_HOME} $ENV{OGRE_PLUGIN_DIR}
- PATH_SUFFIXES bin/Debug bin/debug Debug debug lib lib/OGRE bin
- )
- # We only need at least one render system. Check at the end.
- IF(NOT ${_plugin} MATCHES "RenderSystem")
- IF(NOT OGRE_PLUGIN_${_plugin}_OPTIMIZED)
- MESSAGE(FATAL_ERROR "Could not find OGRE plugin named ${_plugin}")
- ENDIF()
- ELSEIF(OGRE_PLUGIN_${_plugin}_OPTIMIZED)
- SET(OGRE_RENDER_SYSTEM_FOUND TRUE)
- ENDIF()
-
- IF(OGRE_PLUGIN_${_plugin}_OPTIMIZED)
- # If debug version is not available, release will do as well
- IF(OGRE_PLUGIN_${_plugin}_DEBUG STREQUAL OGRE_PLUGIN_${_plugin}_OPTIMIZED)
- # In this case the library finder didn't find real debug versions
- SET(OGRE_PLUGIN_${_plugin}_DEBUG "OGRE_PLUGIN_${_plugin}_DEBUG-NOTFOUND" CACHE STRING "" FORCE)
- ENDIF()
- MARK_AS_ADVANCED(OGRE_PLUGIN_${_plugin}_OPTIMIZED OGRE_PLUGIN_${_plugin}_DEBUG)
-
- ### Set variables to configure orxonox.ini correctly afterwards in bin/ ###
- # Check and set the folders
- GET_FILENAME_COMPONENT(_plugins_folder ${OGRE_PLUGIN_${_plugin}_OPTIMIZED} PATH)
- IF(OGRE_PLUGINS_FOLDER_RELEASE AND NOT OGRE_PLUGINS_FOLDER_RELEASE STREQUAL _plugins_folder)
- MESSAGE(FATAL_ERROR "Ogre release plugins have to be in the same folder!")
- ENDIF()
- SET(OGRE_PLUGINS_FOLDER_RELEASE ${_plugins_folder})
- IF(OGRE_PLUGIN_${_plugin}_DEBUG)
- GET_FILENAME_COMPONENT(_plugins_folder ${OGRE_PLUGIN_${_plugin}_DEBUG} PATH)
- ENDIF()
- IF(OGRE_PLUGINS_FOLDER_DEBUG AND NOT OGRE_PLUGINS_FOLDER_DEBUG STREQUAL _plugins_folder)
- MESSAGE(FATAL_ERROR "Ogre debug plugins have to be in the same folder!")
- ENDIF()
- SET(OGRE_PLUGINS_FOLDER_DEBUG ${_plugins_folder})
-
- # Create a list with the plugins for release and debug configurations
- LIST(APPEND OGRE_PLUGINS_RELEASE ${_plugin})
- # Determine debug postfix ("d" or "_d" or none)
- IF(OGRE_PLUGIN_${_plugin}_DEBUG MATCHES "_d\\.|_d$")
- LIST(APPEND OGRE_PLUGINS_DEBUG "${_plugin}_d")
- ELSEIF(OGRE_PLUGIN_${_plugin}_DEBUG MATCHES "d\\.|d$")
- LIST(APPEND OGRE_PLUGINS_DEBUG "${_plugin}d")
- ELSE()
- LIST(APPEND OGRE_PLUGINS_DEBUG "${_plugin}")
- ENDIF()
- ENDIF(OGRE_PLUGIN_${_plugin}_OPTIMIZED)
- ENDFOREACH(_plugin)
- IF(NOT OGRE_RENDER_SYSTEM_FOUND)
- MESSAGE(FATAL_ERROR "Could not find an OGRE render system plugin")
- ENDIF()
-
- # List has to be comma separated for orxonox.ini
- STRING(REPLACE ";" ", " OGRE_PLUGINS_RELEASE "${OGRE_PLUGINS_RELEASE}")
- STRING(REPLACE ";" ", " OGRE_PLUGINS_DEBUG "${OGRE_PLUGINS_DEBUG}")
-
- # Set variables outside function scope
- SET(OGRE_PLUGINS_FOLDER_DEBUG ${OGRE_PLUGINS_FOLDER_DEBUG} PARENT_SCOPE)
- SET(OGRE_PLUGINS_FOLDER_RELEASE ${OGRE_PLUGINS_FOLDER_RELEASE} PARENT_SCOPE)
- SET(OGRE_PLUGINS_RELEASE ${OGRE_PLUGINS_RELEASE} PARENT_SCOPE)
- SET(OGRE_PLUGINS_DEBUG ${OGRE_PLUGINS_DEBUG} PARENT_SCOPE)
-
-ENDFUNCTION(CHECK_OGRE_PLUGINS)
Deleted: code/forks/sandbox_light/cmake/tools/FindALUT.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindALUT.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindALUT.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,80 +0,0 @@
-# - Locate FreeAlut
-# This module defines
-# ALUT_LIBRARY
-# ALUT_FOUND, if false, do not try to link against Alut
-# ALUT_INCLUDE_DIR, where to find the headers
-#
-# $ALUTDIR is an environment variable that would
-# correspond to the ./configure --prefix=$ALUTDIR
-# used in building Alut.
-#
-# Created by Eric Wing. This was influenced by the FindSDL.cmake module.
-# On OSX, this will prefer the Framework version (if found) over others.
-# People will have to manually change the cache values of
-# ALUT_LIBRARY to override this selection.
-# Tiger will include OpenAL as part of the System.
-# But for now, we have to look around.
-# Other (Unix) systems should be able to utilize the non-framework paths.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Some simplifications by Adrian Friedli and Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(FindPackageHandleStandardArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(ALUT_INCLUDE_DIR AL/alut.h
- PATHS
- $ENV{ALUTDIR}
- ~/Library/Frameworks/OpenAL.framework
- /Library/Frameworks/OpenAL.framework
- /System/Library/Frameworks/OpenAL.framework # Tiger
- PATH_SUFFIXES include include/OpenAL include/AL Headers
-)
-
-# I'm not sure if I should do a special casing for Apple. It is
-# unlikely that other Unix systems will find the framework path.
-# But if they do ([Next|Open|GNU]Step?),
-# do they want the -framework option also?
-IF(${ALUT_INCLUDE_DIR} MATCHES ".framework")
-
- STRING(REGEX REPLACE "(.*)/.*\\.framework/.*" "\\1" ALUT_FRAMEWORK_PATH_TMP ${ALUT_INCLUDE_DIR})
- IF("${ALUT_FRAMEWORK_PATH_TMP}" STREQUAL "/Library/Frameworks"
- OR "${ALUT_FRAMEWORK_PATH_TMP}" STREQUAL "/System/Library/Frameworks"
- )
- # String is in default search path, don't need to use -F
- SET (ALUT_LIBRARY_OPTIMIZED "-framework OpenAL" CACHE STRING "OpenAL framework for OSX")
- ELSE()
- # String is not /Library/Frameworks, need to use -F
- SET(ALUT_LIBRARY_OPTIMIZED "-F${ALUT_FRAMEWORK_PATH_TMP} -framework OpenAL" CACHE STRING "OpenAL framework for OSX")
- ENDIF()
- # Clear the temp variable so nobody can see it
- SET(ALUT_FRAMEWORK_PATH_TMP "" CACHE INTERNAL "")
-
-ELSE()
- FIND_LIBRARY(ALUT_LIBRARY_OPTIMIZED
- NAMES alut
- PATHS $ENV{ALUTDIR}
- PATH_SUFFIXES lib libs
- )
- FIND_LIBRARY(ALUT_LIBRARY_DEBUG
- NAMES alutd alut_d alutD alut_D
- PATHS $ENV{ALUTDIR}
- PATH_SUFFIXES lib libs
- )
-ENDIF()
-
-# Handle the REQUIRED argument and set ALUT_FOUND
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(ALUT DEFAULT_MSG
- ALUT_LIBRARY_OPTIMIZED
- ALUT_INCLUDE_DIR
-)
-
-# Collect optimized and debug libraries
-HANDLE_LIBRARY_TYPES(ALUT)
-
-MARK_AS_ADVANCED(
- ALUT_INCLUDE_DIR
- ALUT_LIBRARY_OPTIMIZED
- ALUT_LIBRARY_DEBUG
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindCEGUI.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindCEGUI.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindCEGUI.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,103 +0,0 @@
-# Find CEGUI includes and library
-#
-# This module defines
-# CEGUI_INCLUDE_DIR
-# CEGUI_LIBRARY, the library to link against to use CEGUI.
-# CEGUI_FOUND, If false, do not try to use CEGUI
-# CEGUI_VERSION, the version as string "x.y.z"
-# CEGUILUA_LIBRARY, Script module library
-# CEGUILUA_USE_INTERNAL_LIBRARY, True if CEGUILUA_LIBRARY was not defined here
-#
-# Input:
-# ENV{CEGUIDIR}, CEGUI path, optional
-# FIND CEGUILUA_INTERNAL_SUPPORT, List of all CEGUILua version supported
-# in the source repository
-# CEGUILUA_USE_EXTERNAL_LIBRARY, Force finding of CEGUILua
-#
-# Created by Matt Williams to find OGRE libraries
-# Copyright © 2007, Matt Williams
-#
-# Modified by Nicolas Schlumberger to find CEGUI libraries
-# and make it run on the Tardis-Infrastucture of the ETH Zurich
-# Copyright 2007, Nicolas Schlumberger
-#
-# Redistribution and use is allowed according to the terms of the BSD license.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Lots of simplifications by Adrian Friedli and Reto Grieder
-# Version checking and CEGUILua finding by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(DetermineVersion)
-INCLUDE(FindPackageHandleAdvancedArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(CEGUI_INCLUDE_DIR CEGUI.h
- PATHS $ENV{CEGUIDIR}
- PATH_SUFFIXES include include/CEGUI CEGUI.framework/Headers
-)
-FIND_LIBRARY(CEGUI_LIBRARY_OPTIMIZED
- NAMES CEGUIBase CEGUI
- PATHS $ENV{CEGUIDIR}
- PATH_SUFFIXES lib bin
-)
-FIND_LIBRARY(CEGUI_LIBRARY_DEBUG
- NAMES
- CEGUIBased CEGUIBase_d CEGUIBaseD CEGUIBase_D
- CEGUId CEGUI_d CEGUID CEGUI_D
- PATHS $ENV{CEGUIDIR}
- PATH_SUFFIXES lib bin
-)
-
-# Inspect CEGUIVersion.h for the version number
-DETERMINE_VERSION(CEGUI ${CEGUI_INCLUDE_DIR}/CEGUIVersion.h)
-
-# Handle the REQUIRED argument and set CEGUI_FOUND
-# Also checks the version requirements if given
-FIND_PACKAGE_HANDLE_ADVANCED_ARGS(CEGUI DEFAULT_MSG "${CEGUI_VERSION}"
- CEGUI_LIBRARY_OPTIMIZED
- CEGUI_INCLUDE_DIR
-)
-
-# Collect optimized and debug libraries
-HANDLE_LIBRARY_TYPES(CEGUI)
-
-MARK_AS_ADVANCED(
- CEGUI_INCLUDE_DIR
- CEGUI_LIBRARY_OPTIMIZED
- CEGUI_LIBRARY_DEBUG
-)
-
-LIST(FIND CEGUILUA_INTERNAL_SUPPORT "${CEGUI_VERSION}" _find_result)
-IF(CEGUILUA_USE_EXTERNAL_LIBRARY OR _find_result EQUAL -1)
- # Also try to find the CEGUILua libraries.
- # There would already be libraries in src/ for versions 0.5 and 0.6
- FIND_LIBRARY(CEGUILUA_LIBRARY_OPTIMIZED
- NAMES CEGUILua
- PATHS $ENV{CEGUIDIR}
- PATH_SUFFIXES lib bin
- )
- FIND_LIBRARY(CEGUILUA_LIBRARY_DEBUG
- NAMES CEGUILuad CEGUILua_d
- PATHS $ENV{CEGUIDIR}
- PATH_SUFFIXES lib bin
- )
-
- SET(CEGUILua_FIND_REQUIRED ${CEGUI_FIND_REQUIRED})
- # Handle the REQUIRED argument and set CEGUILUA_FOUND
- FIND_PACKAGE_HANDLE_STANDARD_ARGS(CEGUILua DEFAULT_MSG
- CEGUILUA_LIBRARY_OPTIMIZED
- )
-
- # Collect optimized and debug libraries
- HANDLE_LIBRARY_TYPES(CEGUILUA)
-
- MARK_AS_ADVANCED(
- CEGUILUA_LIBRARY_OPTIMIZED
- CEGUILUA_LIBRARY_DEBUG
- )
-
-ELSE(CEGUILUA_USE_EXTERNAL_LIBRARY OR _find_result EQUAL -1)
- SET(CEGUILUA_USE_INTERNAL_LIBRARY TRUE)
-ENDIF(CEGUILUA_USE_EXTERNAL_LIBRARY OR _find_result EQUAL -1)
-
Deleted: code/forks/sandbox_light/cmake/tools/FindDirectX.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindDirectX.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindDirectX.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,53 +0,0 @@
-# Find script for DirectX on Windows
-# Specifically designed to find dxguid and dinput8 for OIS
-# Once loaded this will define
-# DIRECTX_FOUND - system has DirectX
-# DIRECTX_INCLUDE_DIR - include directory for DirectX
-# DIRECTX_LIBRARIES - libraries for DirectX
-#
-# Set ENV{DXSD_DIR} if that has not been done the SDK installation.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Simplifications and CMake 2.6.0 bugfix by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(FindPackageHandleStandardArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(DIRECTX_INCLUDE_DIR dinput.h
- PATHS $ENV{DXSDK_DIR}
- PATH_SUFFIXES include
-)
-FIND_LIBRARY(DIRECTX_LIBRARY_input dinput8
- PATHS $ENV{DXSDK_DIR}
- PATH_SUFFIXES lib Lib lib/x86 Lib/x86
- NO_DEFAULT_PATH # Or else CMake 2.6.0 will find the dll in system32 on windows
-)
-FIND_LIBRARY(DIRECTX_LIBRARY_input dinput8
- PATHS $ENV{DXSDK_DIR}
- PATH_SUFFIXES lib Lib lib/x86 Lib/x86
-)
-FIND_LIBRARY(DIRECTX_LIBRARY_guid dxguid
- PATHS $ENV{DXSDK_DIR}
- PATH_SUFFIXES lib Lib lib/x86 Lib/x86
- NO_DEFAULT_PATH # Or else CMake 2.6.0 will find the dll in system32 on windows
-)
-FIND_LIBRARY(DIRECTX_LIBRARY_guid dxguid
- PATHS $ENV{DXSDK_DIR}
- PATH_SUFFIXES lib Lib lib/x86 Lib/x86
-)
-
-# Handle the REQUIRED argument and set DIRECTX_FOUND
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(DirectX DEFAULT_MSG
- DIRECTX_LIBRARY_input
- DIRECTX_LIBRARY_guid
- DIRECTX_INCLUDE_DIR
-)
-
-SET(DIRECTX_LIBRARIES ${DIRECTX_LIBRARY_input} ${DIRECTX_LIBRARY_guid})
-
-MARK_AS_ADVANCED(
- DIRECTX_INCLUDE_DIR
- DIRECTX_LIBRARY_input
- DIRECTX_LIBRARY_guid
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindENet.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindENet.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindENet.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,80 +0,0 @@
-# - Try to find enet
-# Once done this will define
-#
-# ENET_FOUND - system has enet
-# ENet_INCLUDE_DIR - the enet include directory
-# ENet_LIBRARY - the library needed to link against enet
-#
-# $ENETDIR is an environment variable used for finding enet.
-#
-# Borrowed from The Mana World
-# http://themanaworld.org/
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Lots of simplifications by Adrian Friedli and Reto Grieder
-# Version checking by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(FindPackageHandleAdvancedArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(ENET_INCLUDE_DIR enet/enet.h
- PATHS $ENV{ENETDIR}
- PATH_SUFFIXES include
-)
-FIND_LIBRARY(ENET_LIBRARY_OPTIMIZED
- NAMES enet
- PATHS $ENV{ENETDIR}
- PATH_SUFFIXES lib
-)
-FIND_LIBRARY(ENET_LIBRARY_DEBUG
- NAMES enetd enet_d enet_D
- PATHS $ENV{ENETDIR}
- PATH_SUFFIXES lib
-)
-
-# Only works for 1.2.2 and higher, otherwise see below
-DETERMINE_VERSION(ENET ${ENET_INCLUDE_DIR}/enet/enet.h)
-IF(${ENET_VERSION} STREQUAL "0.0.0")
- # Try to determine the version. Note that enet only stores the major
- # version in the header file. So we check for existing functions.
- # Hence the this script only distinguishes between 1.0, 1.1 and 1.2
- FILE(STRINGS ${ENET_INCLUDE_DIR}/enet/enet.h _enet_header REGEX "ENET_")
- IF(_enet_header MATCHES "ENET_VERSION[ \t]*=[ \t]*1")
- IF(_enet_header MATCHES "enet_socket_set_option")
- SET(ENET_VERSION 1.2)
- ELSEIF(_enet_header MATCHES "enet_peer_disconnect_later")
- SET(ENET_VERSION 1.1)
- ELSE()
- SET(ENET_VERSION 1.0)
- ENDIF()
- ELSE()
- SET(ENET_VERSION 0) # Script doesn't support versions below 1.0
- ENDIF()
-ENDIF()
-
-# Handle the REQUIRED argument and set ENET_FOUND
-# Also check the the version requirements
-FIND_PACKAGE_HANDLE_ADVANCED_ARGS(ENet DEFAULT_MSG ${ENET_VERSION}
- ENET_LIBRARY_OPTIMIZED
- ENET_INCLUDE_DIR
-)
-
-COMPARE_VERSION_STRINGS(${ENET_VERSION} 1.2 _comparison TRUE)
-IF(${_comparison} EQUAL 1)
- MESSAGE(STATUS "Warning: Using ENet version 1.3, which is not protocol compatible with 1.1 and 1.2.")
-ENDIF()
-
-# Collect optimized and debug libraries
-IF(NOT LINK_ENET_DYNAMIC AND WIN32)
- # ENet is linked statically, hence we need to add some windows dependencies
- HANDLE_LIBRARY_TYPES(ENET ws2_32 winmm)
-ELSE()
- HANDLE_LIBRARY_TYPES(ENET)
-ENDIF()
-
-MARK_AS_ADVANCED(
- ENET_INCLUDE_DIR
- ENET_LIBRARY_OPTIMIZED
- ENET_LIBRARY_DEBUG
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindLua.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindLua.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindLua.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,184 +0,0 @@
- #
- # ORXONOX - the hottest 3D action shooter ever to exist
- # > www.orxonox.net <
- #
- # 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.
- #
- #
- # Author:
- # Reto Grieder
- # Description:
- # Finds either Lua 5.0 or Lua 5.1 on the system. The script regards the
- # VERSION, EXACT, REQUIRED and QUIET arguments. A note about the EXACT
- # argument: EXACT 5 will match all Lua 5 versions.
- # When the search was successful, the following variables are set:
- # LUA_INCLUDE_DIR, LUA_LIBRARIES, LUA_VERSION, LUA_FOUND
- #
-
-INCLUDE(CompareVersionStrings)
-INCLUDE(FindPackageHandleAdvancedArgs)
-INCLUDE(HandleLibraryTypes)
-
-# Macro that determines Lua version. Should work for versions 2.2 and above (current release: 5.1.4)
-FUNCTION(DETERMINE_LUA_VERSION _file _varname)
- IF(EXISTS ${_file})
- FILE(STRINGS ${_file} _file_content REGEX "LUA_VERSION|LUA_RELEASE")
- ELSE()
- SET(${_varname} "0" PARENT_SCOPE)
- RETURN()
- ENDIF()
- STRING(REGEX REPLACE "^.*LUA_RELEASE[ \t]+\"Lua[ \t]+([.0-9]+)\".*$" "\\1" ${_varname} "${_file_content}")
- IF(${_varname} STREQUAL "${_file_content}")
- # At most version 5.1.0
- STRING(REGEX REPLACE "^.*LUA_VERSION[ \t]+\"Lua[ \t]+([.0-9]+)\".*$" "\\1" ${_varname} "${_file_content}")
- IF(${_varname} STREQUAL "${_file_content}")
- MESSAGE(FATAL_ERROR "Could not determine Lua version which means this script has a bug")
- ENDIF()
- IF(${_varname} MATCHES "^[0-9]+\\.[0-9]+$")
- SET(${_varname} "${${_varname}}.0") # E.g. "3.2" is "3.2.0" actually
- ENDIF()
- ENDIF()
- SET(${_varname} "${${_varname}}" PARENT_SCOPE)
-ENDFUNCTION(DETERMINE_LUA_VERSION)
-
-
-# Find Lua 5.1
-FIND_PATH(LUA_5.1_INCLUDE_DIR lua.h
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES include/lua51 include/lua5.1 include/lua include
-)
-IF(LUA_5.1_INCLUDE_DIR)
- DETERMINE_LUA_VERSION(${LUA_5.1_INCLUDE_DIR}/lua.h LUA_5.1_VERSION)
- COMPARE_VERSION_STRINGS("${LUA_5.1_VERSION}" "5.1" _version_compare TRUE)
- IF(NOT _version_compare EQUAL 0)
- # Incorrect version found, abort search
- SET(LUA_5.1_INCLUDE_DIR "LUA_5.1_INCLUDE_DIR-NOTFOUND" CACHE PATH "" FORCE)
- ELSE()
- FIND_LIBRARY(LUA_5.1_LIBRARY_OPTIMIZED
- NAMES lua51 lua5.1 lua
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- FIND_LIBRARY(LUA_5.1_LIBRARY_DEBUG
- NAMES lua51d lua51_d lua5.1d lua5.1_d luad lua_d
- lua51D lua51_D lua5.1D lua5.1_D luad lua_D
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- HANDLE_LIBRARY_TYPES(LUA_5.1)
- SET(LUA_5.1_LIBRARIES ${LUA_5.1_LIBRARY})
- IF(LUA_5.1_LIBRARIES)
- SET(LUA_5.1_FOUND TRUE)
- ENDIF()
- ENDIF(NOT _version_compare EQUAL 0)
-ENDIF(LUA_5.1_INCLUDE_DIR)
-
-
-# Find Lua 5.0
-FIND_PATH(LUA_5.0_INCLUDE_DIR lua.h
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES include/lua50 include/lua5.0 include/lua5 include/lua include
-)
-IF(LUA_5.0_INCLUDE_DIR)
- DETERMINE_LUA_VERSION(${LUA_5.0_INCLUDE_DIR}/lua.h LUA_5.0_VERSION)
- COMPARE_VERSION_STRINGS("${LUA_5.0_VERSION}" "5.0" _version_compare TRUE)
- IF(NOT _version_compare EQUAL 0)
- # Incorrect version found, abourt search
- SET(LUA_5.0_INCLUDE_DIR "LUA_5.0_INCLUDE_DIR-NOTFOUND" CACHE PATH "" FORCE)
- ELSE()
- FIND_LIBRARY(LUA_5.0_LUA_LIBRARY_OPTIMIZED
- NAMES lua50 lua5.0 lua5 lua
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- FIND_LIBRARY(LUA_5.0_LUA_LIBRARY_DEBUG
- NAMES lua50d lua50_d lua5.0d lua5.0_d lua5d lua5_d luad lua_d
- lua50D lua50_D lua5.0D lua5.0_D lua5d lua5_D luaD lua_D
- PATHS $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- HANDLE_LIBRARY_TYPES(LUA_5.0_LUA)
-
- # In an OS X framework, lualib is usually included as part of the framework
- # (like GLU in OpenGL.framework)
- IF(${LUA_5.0_LUA_LIBRARY} MATCHES "framework")
- SET(LUA_5.0_LIBRARIES ${LUA_5.0_LUA_LIBRARY})
- ELSE()
- FIND_LIBRARY(LUA_5.0_LUALIB_LIBRARY_OPTIMIZED
- NAMES lualib50 lualib5.0 lualib5 lualib
- PATHS $ENV{LUALIB_DIR} $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- FIND_LIBRARY(LUA_5.0_LUALIB_LIBRARY_DEBUG
- NAMES lualib50d lualib50_d lualib5.0d lualib5.0_d
- lualib5d lualib5_d lualibd lualib_d
- lualib50D lualib50_D lualib5.0D lualib5.0_D
- lualib5D lualib5_D lualibD lualib_D
- PATHS $ENV{LUALIB_DIR} $ENV{LUA_DIR}
- PATH_SUFFIXES lib64 lib
- )
- HANDLE_LIBRARY_TYPES(LUA_5.0_LUALIB)
- # Both libraries are required for Lua 5.0 to be found
- IF(LUA_5.0_LUA_LIBRARY AND LUA_5.0_LUALIB_LIBRARY)
- SET(LUA_5.0_LIBRARIES ${LUA_5.0_LUA_LIBRARY} ${LUA_5.0_LUALIB_LIBRARY})
- ENDIF()
- ENDIF(${LUA_5.0_LUA_LIBRARY} MATCHES "framework")
-
- IF(LUA_5.0_LIBRARIES)
- SET(LUA_5.0_FOUND TRUE)
- ENDIF()
- ENDIF(NOT _version_compare EQUAL 0)
-ENDIF(LUA_5.0_INCLUDE_DIR)
-
-# Pick the right version
-IF(Lua_FIND_VERSION_EXACT AND NOT Lua_FIND_VERSION MATCHES "^[0-9]*$")
- STRING(REGEX REPLACE "^([0-9]+\\.[0-9]+)(\\..*)?$" "\\1" LUA_VERSION_SELECTION ${Lua_FIND_VERSION})
-ELSE()
- IF(LUA_5.1_FOUND) # Prefer version 5.1 if found
- SET(LUA_VERSION_SELECTION "5.1")
- ELSEIF(LUA_5.0_FOUND)
- SET(LUA_VERSION_SELECTION "5.0")
- ENDIF()
-ENDIF()
-
-SET(LUA_INCLUDE_DIR "${LUA_${LUA_VERSION_SELECTION}_INCLUDE_DIR}")
-SET(LUA_LIBRARIES "${LUA_${LUA_VERSION_SELECTION}_LIBRARIES}")
-SET(LUA_VERSION_LONG "${LUA_${LUA_VERSION_SELECTION}_VERSION}")
-SET(LUA_VERSION "${LUA_VERSION_SELECTION}")
-
-FIND_PACKAGE_HANDLE_ADVANCED_ARGS(Lua DEFAULT_MSG "${LUA_VERSION_LONG}"
- LUA_LIBRARIES
- LUA_INCLUDE_DIR
-)
-
-# Include the math library for Unix only
-IF(LUA_FOUND)
- IF(UNIX AND NOT APPLE)
- FIND_LIBRARY(UNIX_MATH_LIBRARY m)
- SET(LUA_LIBRARIES ${LUA_LIBRARIES} ${UNIX_MATH_LIBRARY})
- ENDIF()
-ENDIF(LUA_FOUND)
-
-MARK_AS_ADVANCED(
- LUA_5.0_INCLUDE_DIR
- LUA_5.0_LUA_LIBRARY_OPTIMIZED
- LUA_5.0_LUA_LIBRARY_DEBUG
- LUA_5.0_LUALIB_LIBRARY_OPTIMIZED
- LUA_5.0_LUALIB_LIBRARY_DEBUG
- LUA_5.1_INCLUDE_DIR
- LUA_5.1_LIBRARY_OPTIMIZED
- LUA_5.1_LIBRARY_DEBUG
- UNIX_MATH_LIBRARY
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindOGRE.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindOGRE.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindOGRE.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,55 +0,0 @@
-# Find OGRE includes and library
-#
-# This module defines
-# OGRE_INCLUDE_DIR
-# OGRE_LIBRARY, the library to link against to use OGRE.
-# OGRE_FOUND, If false, do not try to use OGRE
-#
-# Copyright © 2007, Matt Williams
-# Modified by Nicolas Schlumberger to make it work on the Tardis-Infrastucture
-# of the ETH Zurich (removed later on)
-#
-# Redistribution and use is allowed according to the terms of the BSD license.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Lots of simplifications by Adrian Friedli
-# Version checking by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(DetermineVersion)
-INCLUDE(FindPackageHandleAdvancedArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(OGRE_INCLUDE_DIR Ogre.h
- PATHS $ENV{OGRE_HOME}
- PATH_SUFFIXES include include/OGRE Ogre.framework/Headers
-)
-FIND_LIBRARY(OGRE_LIBRARY_OPTIMIZED
- NAMES OgreMain Ogre
- PATHS $ENV{OGRE_HOME}
- PATH_SUFFIXES lib bin/Release bin/release Release release
-)
-FIND_LIBRARY(OGRE_LIBRARY_DEBUG
- NAMES OgreMaind OgreMain_d OgreMainD OgreMain_D Ogred Ogre_d OgreD Ogre_d
- PATHS $ENV{OGRE_HOME}
- PATH_SUFFIXES lib bin/Debug bin/debug Debug debug Versions/A
-)
-
-# Inspect OgrePrerquisites.h for the version number
-DETERMINE_VERSION(OGRE ${OGRE_INCLUDE_DIR}/OgrePrerequisites.h)
-
-# Handle the REQUIRED argument and set OGRE_FOUND
-# Also check the version requirements
-FIND_PACKAGE_HANDLE_ADVANCED_ARGS(OGRE DEFAULT_MSG ${OGRE_VERSION}
- OGRE_LIBRARY_OPTIMIZED
- OGRE_INCLUDE_DIR
-)
-
-# Collect optimized and debug libraries
-HANDLE_LIBRARY_TYPES(OGRE)
-
-MARK_AS_ADVANCED(
- OGRE_INCLUDE_DIR
- OGRE_LIBRARY_OPTIMIZED
- OGRE_LIBRARY_DEBUG
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindOgg.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindOgg.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindOgg.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,47 +0,0 @@
-# - Try to find ogg
-# Once done this will define
-#
-# OGG_FOUND - system has ogg
-# OGG_INCLUDE_DIR
-# OGG_LIBRARY
-#
-# $OGGDIR is an environment variable used
-# for finding ogg.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Most of all rewritten by Adrian Friedli
-# Debug versions and simplifications by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(FindPackageHandleStandardArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(OGG_INCLUDE_DIR ogg/ogg.h
- PATHS $ENV{OGGDIR}
- PATH_SUFFIXES include
-)
-FIND_LIBRARY(OGG_LIBRARY_OPTIMIZED
- NAMES ogg
- PATHS $ENV{OGGDIR}
- PATH_SUFFIXES lib
-)
-FIND_LIBRARY(OGG_LIBRARY_DEBUG
- NAMES oggd ogg_d oggD ogg_D
- PATHS $ENV{OGGDIR}
- PATH_SUFFIXES lib
-)
-
-# Handle the REQUIRED argument and set OGG_FOUND
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(Ogg DEFAULT_MSG
- OGG_LIBRARY_OPTIMIZED
- OGG_INCLUDE_DIR
-)
-
-# Collect optimized and debug libraries
-HANDLE_LIBRARY_TYPES(OGG)
-
-MARK_AS_ADVANCED(
- OGG_INCLUDE_DIR
- OGG_LIBRARY_OPTIMIZED
- OGG_LIBRARY_DEBUG
-)
Deleted: code/forks/sandbox_light/cmake/tools/FindVorbis.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/FindVorbis.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/FindVorbis.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,62 +0,0 @@
-# - Try to find ogg/vorbis
-# Once done this will define
-#
-# VORBIS_FOUND - system has vorbis
-# VORBIS_INCLUDE_DIR
-# VORBIS_LIBRARIES - vorbis and vorbisfile libraries
-#
-# $VORBISDIR is an environment variable used
-# for finding vorbis.
-#
-# Several changes and additions by Fabian 'x3n' Landau
-# Most of all rewritten by Adrian Friedli
-# Debug versions and simplifications by Reto Grieder
-# > www.orxonox.net <
-
-INCLUDE(FindPackageHandleStandardArgs)
-INCLUDE(HandleLibraryTypes)
-
-FIND_PATH(VORBIS_INCLUDE_DIR vorbis/codec.h
- PATHS $ENV{VORBISDIR}
- PATH_SUFFIXES include
-)
-FIND_LIBRARY(VORBIS_LIBRARY_OPTIMIZED
- NAMES vorbis
- PATHS $ENV{VORBISDIR}
- PATH_SUFFIXES lib
-)
-FIND_LIBRARY(VORBIS_LIBRARY_DEBUG
- NAMES vorbisd vorbis_d vorbisD vorbis_D
- PATHS $ENV{VORBISDIR}
- PATH_SUFFIXES lib
-)
-FIND_LIBRARY(VORBISFILE_LIBRARY_OPTIMIZED
- NAMES vorbisfile
- PATHS $ENV{VORBISDIR}
- PATH_SUFFIXES lib
-)
-FIND_LIBRARY(VORBISFILE_LIBRARY_DEBUG
- NAMES vorbisfiled vorbisfile_d vorbisfileD vorbisfile_D
- PATHS $ENV{VORBISDIR}
- PATH_SUFFIXES lib
-)
-
-# Handle the REQUIRED argument and set VORBIS_FOUND
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(Vorbis DEFAULT_MSG
- VORBIS_LIBRARY_OPTIMIZED
- VORBISFILE_LIBRARY_OPTIMIZED
- VORBIS_INCLUDE_DIR
-)
-
-# Collect optimized and debug libraries
-HANDLE_LIBRARY_TYPES(VORBIS)
-HANDLE_LIBRARY_TYPES(VORBISFILE)
-SET(VORBIS_LIBRARIES ${VORBIS_LIBRARY} ${VORBISFILE_LIBRARY})
-
-MARK_AS_ADVANCED(
- VORBIS_INCLUDE_DIR
- VORBIS_LIBRARY_OPTIMIZED
- VORBIS_LIBRARY_DEBUG
- VORBISFILE_LIBRARY_OPTIMIZED
- VORBISFILE_LIBRARY_DEBUG
-)
Deleted: code/forks/sandbox_light/cmake/tools/GenerateToluaBindings.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/GenerateToluaBindings.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/GenerateToluaBindings.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,80 +0,0 @@
- #
- # ORXONOX - the hottest 3D action shooter ever to exist
- # > www.orxonox.net <
- #
- # 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.
- #
- #
- # Author:
- # Adrian Friedli
- # Description:
- # Sets the CMake options that will generate Tolua++ bindings.
- # Parameters:
- # _tolua_package - Name of the package, e.g. "Core"
- # _target_source_files - Variable name of the target source files, the
- # script will add the generated files to this list.
- # ARGN - The header files in the style "INTPUTFILES Foo.h Bar.h"
- # Global Variables: (need to be set before)
- # TOLUA_PARSER_SOURCE - Lua file with the parser source code
- # TOLUA_PARSER_DEPENDENCIES - All the dependent lua files
- # RUNTIME_LIBRARY_DIRECTORY - Working directory
- #
-
-FUNCTION(GENERATE_TOLUA_BINDINGS _tolua_package _target_source_files)
- SET(_tolua_inputfiles ${ARGN})
- LIST(REMOVE_ITEM _tolua_inputfiles "INPUTFILES")
-
- SET(_tolua_pkgfile "${CMAKE_CURRENT_BINARY_DIR}/tolua.pkg")
- SET(_tolua_cxxfile "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/ToluaBind${_tolua_package}.cc")
- SET(_tolua_hfile "${CMAKE_BINARY_DIR}/src/toluabind/${CMAKE_CFG_INTDIR}/ToluaBind${_tolua_package}.h")
-
- SET(${_target_source_files}
- ${${_target_source_files}}
- ${_tolua_cxxfile}
- ${_tolua_hfile}
- PARENT_SCOPE
- )
-
- # Disable annoying GCC warnings
- IF(CMAKE_COMPILER_IS_GNU)
- SET_SOURCE_FILES_PROPERTIES(${_tolua_cxxfile} PROPERTIES COMPILE_FLAGS "-w")
- ENDIF()
-
- # Tolua binding speedup if required
- IF(ORXONOX_RELEASE)
- SET_SOURCE_FILES_PROPERTIES(${_tolua_cxxfile} PROPERTIES COMPILE_FLAGS "-DTOLUA_RELEASE")
- ENDIF()
-
- # Create temporary package file and implicit dependencies
- FILE(REMOVE ${_tolua_pkgfile})
- FOREACH(_tolua_inputfile ${_tolua_inputfiles})
- FILE(APPEND ${_tolua_pkgfile} "\$cfile \"${_tolua_inputfile}\"\n")
- LIST(APPEND _implicit_dependencies CXX ${_tolua_inputfile})
- ENDFOREACH(_tolua_inputfile)
-
- ADD_CUSTOM_COMMAND(
- OUTPUT ${_tolua_cxxfile} ${_tolua_hfile}
- COMMAND toluaapp_orxonox -n ${_tolua_package}
- -w ${CMAKE_CURRENT_SOURCE_DIR}
- -o ${_tolua_cxxfile}
- -H ${_tolua_hfile}
- -s ${TOLUA_PARSER_SOURCE}
- ${_tolua_pkgfile}
- DEPENDS ${TOLUA_PARSER_DEPENDENCIES}
- IMPLICIT_DEPENDS ${_implicit_dependencies}
- WORKING_DIRECTORY ${RUNTIME_LIBRARY_DIRECTORY}
- COMMENT "Generating tolua bind files for package ${_tolua_package}"
- )
-ENDFUNCTION(GENERATE_TOLUA_BINDINGS)
Modified: code/forks/sandbox_light/cmake/tools/TargetUtilities.cmake
===================================================================
--- code/forks/sandbox_light/cmake/tools/TargetUtilities.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/cmake/tools/TargetUtilities.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -33,7 +33,6 @@
# ORXONOX_EXTERNAL: Specify this for third party libraries
# NO_DLL_INTERFACE: Link statically with MSVC
# NO_SOURCE_GROUPS: Don't create msvc source groups
- # MODULE: For dynamic module libraries (libraries only)
# WIN32: Inherited from ADD_EXECUTABLE (executables only)
# PCH_NO_DEFAULT: Do not make precompiled header files default if
# specified with PCH_FILE
@@ -45,7 +44,6 @@
# VERSION: Set version to the binary
# SOURCE_FILES: Source files for the target
# DEFINE_SYMBOL: Sets the DEFINE_SYMBOL target property
- # TOLUA_FILES: Files with tolua interface
# PCH_FILE: Precompiled header file
# PCH_EXCLUDE: Source files to be excluded from PCH support
# OUTPUT_NAME: If you want a different name than the target name
@@ -59,7 +57,6 @@
INCLUDE(CMakeDependentOption)
INCLUDE(CapitaliseName)
-INCLUDE(GenerateToluaBindings)
INCLUDE(ParseMacroArguments)
INCLUDE(SourceFileUtilities)
IF(PCH_COMPILER_SUPPORT)
@@ -84,7 +81,7 @@
NO_DLL_INTERFACE NO_SOURCE_GROUPS PCH_NO_DEFAULT
NO_INSTALL NO_VERSION ${_additional_switches})
SET(_list_names LINK_LIBRARIES VERSION SOURCE_FILES
- DEFINE_SYMBOL TOLUA_FILES PCH_FILE
+ DEFINE_SYMBOL PCH_FILE
PCH_EXCLUDE OUTPUT_NAME)
PARSE_MACRO_ARGUMENTS("${_switches}" "${_list_names}" ${ARGN})
@@ -164,12 +161,6 @@
# Remove potential duplicates
LIST(REMOVE_DUPLICATES _${_target_name}_files)
- # TOLUA_FILES
- IF(_arg_TOLUA_FILES)
- GENERATE_TOLUA_BINDINGS(${_target_name_capitalised} _${_target_name}_files
- INPUTFILES ${_arg_TOLUA_FILES})
- ENDIF()
-
# First part (pre target) of precompiled header files
IF(PCH_COMPILER_SUPPORT AND _arg_PCH_FILE)
# Provide convenient option to control PCH
@@ -257,17 +248,6 @@
SET_TARGET_PROPERTIES(${_target_name} PROPERTIES COMPILE_FLAGS "${_compile_flags} -Zm1000")
ENDIF()
- # Configure modules
- IF (_arg_MODULE)
- SET_TARGET_PROPERTIES(${_target_name} PROPERTIES
- RUNTIME_OUTPUT_DIRECTORY ${CMAKE_MODULE_OUTPUT_DIRECTORY} # Windows
- LIBRARY_OUTPUT_DIRECTORY ${CMAKE_MODULE_OUTPUT_DIRECTORY} # Unix
- )
- ADD_MODULE(${_target_name})
- # Ensure that the main program depends on the module
- SET(ORXONOX_MODULES ${ORXONOX_MODULES} ${_target_name} CACHE STRING "" FORCE)
- ENDIF()
-
# Static library flags are not globally available
IF(ORXONOX_STATIC_LINKER_FLAGS)
SET_TARGET_PROPERTIES(${_target_name} PROPERTIES STATIC_LIBRARY_FLAGS ${ORXONOX_STATIC_LINKER_FLAGS})
@@ -305,52 +285,10 @@
# Install all targets except for static ones (executables also have SHARED in _link_mode)
IF(${_link_mode} STREQUAL "SHARED" AND NOT _arg_NO_INSTALL)
- IF(_arg_MODULE)
- INSTALL(TARGETS ${_target_name}
- RUNTIME DESTINATION ${MODULE_INSTALL_DIRECTORY}
- LIBRARY DESTINATION ${MODULE_INSTALL_DIRECTORY}
- )
- ELSE()
- INSTALL(TARGETS ${_target_name}
- RUNTIME DESTINATION ${RUNTIME_INSTALL_DIRECTORY}
- LIBRARY DESTINATION ${LIBRARY_INSTALL_DIRECTORY}
- )
- ENDIF()
+ INSTALL(TARGETS ${_target_name}
+ RUNTIME DESTINATION ${RUNTIME_INSTALL_DIRECTORY}
+ LIBRARY DESTINATION ${LIBRARY_INSTALL_DIRECTORY}
+ )
ENDIF()
ENDMACRO(TU_ADD_TARGET)
-
-
-# Creates a helper file with name <name_of_the_library>${ORXONOX_MODULE_EXTENSION}
-# This helps finding dynamically loadable modules at runtime
-
-FUNCTION(ADD_MODULE _target)
- # We use the properties to get the name because the librarys name may differ from
- # the target name (for example orxonox <-> liborxonox)
-
- GET_TARGET_PROPERTY(_target_loc ${_target} LOCATION)
- GET_FILENAME_COMPONENT(_target_name ${_target_loc} NAME_WE)
-
- IF(CMAKE_CONFIGURATION_TYPES)
- FOREACH(_config ${CMAKE_CONFIGURATION_TYPES})
- SET(_module_filename ${CMAKE_MODULE_OUTPUT_DIRECTORY}/${_config}/${_target_name}${ORXONOX_MODULE_EXTENSION})
-
- FILE(WRITE ${_module_filename})
-
- INSTALL(
- FILES ${_module_filename}
- DESTINATION ${MODULE_INSTALL_DIRECTORY}
- CONFIGURATIONS ${_config}
- )
- ENDFOREACH()
- ELSE()
- SET(_module_filename ${CMAKE_MODULE_OUTPUT_DIRECTORY}/${_target_name}${ORXONOX_MODULE_EXTENSION})
-
- FILE(WRITE ${_module_filename})
-
- INSTALL(
- FILES ${_module_filename}
- DESTINATION ${MODULE_INSTALL_DIRECTORY}
- )
- ENDIF()
-ENDFUNCTION(ADD_MODULE)
Modified: code/forks/sandbox_light/data/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/data/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/data/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -28,39 +28,3 @@
# is called EXTERNAL_DATA
SET(DATA_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
SET(DATA_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PARENT_SCOPE)
-
-# Specify data directory
-GET_FILENAME_COMPONENT(_search_path_1 ${CMAKE_SOURCE_DIR}/../data_extern ABSOLUTE)
-FIND_PATH(EXTERNAL_DATA_DIRECTORY resources.oxr
- PATHS
- ${CMAKE_SOURCE_DIR}/data_extern
- ${_search_path_1}
- NO_CMAKE_PATH NO_CMAKE_ENVIRONMENT_PATH NO_SYSTEM_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH
-)
-
-IF(NOT EXTERNAL_DATA_DIRECTORY)
- MESSAGE(STATUS "Warning: External data directory not found. If you want to compile while downloading the data files, you will have to recompile about four files afterwards and relink everything.")
- MESSAGE(STATUS "You can specify your own folder with the EXTERNAL_DATA_DIRECTORY variable. Default location for the path is orxonox_root/data_extern")
- # Temporary override to the default location.
- SET(EXTERNAL_DATA_DIRECTORY ${CMAKE_SOURCE_DIR}/data_extern)
-ENDIF()
-
-
-################ Installation #################
-
-# Internal directory
-INSTALL(
- DIRECTORY ${DATA_DIRECTORY}/
- DESTINATION ${DATA_INSTALL_DIRECTORY}
- REGEX "\\.svn$|_svn$|CMakeLists.txt|InstallScript.cmake" EXCLUDE
-)
-# External directory
-INSTALL(
- DIRECTORY ${EXTERNAL_DATA_DIRECTORY}/
- DESTINATION ${DATA_INSTALL_DIRECTORY}
- REGEX "\\.svn$|_svn$|resources\\.oxr|AUTHORS|LICENSE" EXCLUDE
-)
-# Configure the install scripts (variables not available during installation)
-CONFIGURE_FILE(DataInstallScript.cmake ${CMAKE_CURRENT_BINARY_DIR}/DataInstallScript.cmake @ONLY)
-# Join both resources.oxr files
-INSTALL(SCRIPT ${CMAKE_CURRENT_BINARY_DIR}/DataInstallScript.cmake)
Deleted: code/forks/sandbox_light/data/DataInstallScript.cmake
===================================================================
--- code/forks/sandbox_light/data/DataInstallScript.cmake 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/data/DataInstallScript.cmake 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,37 +0,0 @@
- #
- # ORXONOX - the hottest 3D action shooter ever to exist
- # > www.orxonox.net <
- #
- # 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.
- #
- #
- # Author:
- # Reto Grieder
- # Description:
- # Joins both resources.oxr files together
- # Caution:
- # Variables are declared with @...@ because they don't exist anymore
- # during the installation. But we still require variables (_external_file)
- # so we can only replace @...@ but not ${...}
- #
-
-# Write some comment
-FILE(APPEND $ENV{DESTDIR}/@DATA_INSTALL_DIRECTORY@/DefaultResources.oxr "\n\n\n <!-- ---------------------------------------- -->")
-FILE(APPEND $ENV{DESTDIR}/@DATA_INSTALL_DIRECTORY@/DefaultResources.oxr "\n <!-- Content from the external data directory -->")
-FILE(APPEND $ENV{DESTDIR}/@DATA_INSTALL_DIRECTORY@/DefaultResources.oxr "\n <!-- ---------------------------------------- -->\n\n")
-
-# Append the external file
-FILE(READ @EXTERNAL_DATA_DIRECTORY@/resources.oxr _external_file)
-FILE(APPEND $ENV{DESTDIR}/@DATA_INSTALL_DIRECTORY@/DefaultResources.oxr ${_external_file})
Deleted: code/forks/sandbox_light/data/DefaultResources.oxr
===================================================================
--- code/forks/sandbox_light/data/DefaultResources.oxr 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/data/DefaultResources.oxr 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,12 +0,0 @@
-<ResourceCollection resourceGroup = "General" >
- <ResourceLocation path = "levels" recursive=true/>
- <ResourceLocation path = "lua" />
- <ResourceLocation path = "overlays" />
- <ResourceLocation path = "particle" />
- <ResourceLocation path = "tcl" />
-
- <ResourceLocation path = "gui/configs" />
- <ResourceLocation path = "gui/layouts" />
- <ResourceLocation path = "gui/schemes" />
- <ResourceLocation path = "gui/scripts" />
-</ResourceCollection>
Modified: code/forks/sandbox_light/doc/api/Groups.dox
===================================================================
--- code/forks/sandbox_light/doc/api/Groups.dox 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/doc/api/Groups.dox 2011-02-17 04:47:22 UTC (rev 7908)
@@ -43,16 +43,6 @@
*/
/**
- @defgroup Class Class management
- @ingroup Core
-*/
-
-/**
- @defgroup Object Object management
- @ingroup Core
-*/
-
-/**
@defgroup Command Command
@ingroup Core
*/
@@ -63,639 +53,6 @@
*/
/**
- @defgroup Input Input
- @ingroup Core
-*/
-
-/**
@defgroup Management Management
@ingroup Core
*/
-
-/**
- @defgroup XML XML
- @ingroup Core
-*/
-
-/**
- @defgroup Network Network
-
- The network library is used to connect clients and server, to synchronize objects and variables, and
- to transmit network function calls. It contains the central @ref orxonox::Server "Server" and
- @ref orxonox::Client "Client" classes as well as several functions and macros for
- @ref orxonox::Synchronisable "synchronisable" classes.
-*/
-
-/**
- @defgroup Tools Tools
-
- The tools are a bunch of utilities that belong to the Orxonox library, but are independent of other
- features.
-*/
-
-/**
- @defgroup Orxonox Orxonox
-
- The Orxonox library contains the central and most important classes of the game. Managers, interfaces,
- base-classes, and more are located in Orxonox. More specialized classes that inherit of the base-classes
- in Orxonox are often sourced out to the modules.
-*/
-
-/**
- @defgroup Modules Modules
-
- The modules are libraries that depend on the Orxonox library and that are loaded dynamically on runtime
- (in contrast to statically loaded libraries like util and core). Each module contains some classes that
- are usually connected to each other, but they are independent of other modules. However modules can still
- link to other modules, but only in a hierarchical order, no circular dependencies.
-*/
-
-/**
- @defgroup Designtools Designtools
- @ingroup Modules
-*/
-
-/**
- @defgroup Notifications Notifications
- @ingroup Modules
-
- @ref orxonox::Notification "Notifications" are short messages, that can be sent from anywhere in Orxonox and then are displayed on the screen to inform the user about some occurence he has to know about. Such an occurence could be, that he just shot and killed his Archnemesis Overlord3, that he just got a new Pickup or that he received a Quest and needs to have a look at the Quest-Menu.
-
- @section NotificationsUsage Usage
- Let's very briefly talk about what you have to do to either send @ref orxonox::Notification "Notifications" from some part of Orxonox or display Notifications on your screen.
-
- @subsection NotifictionsSending Sending notifications
- Sending a new @ref orxonox::Notification "Notification" from (almost) anywhere in Orxonox is fairly easy.
- You first have to decide on a message, it shouldn't be too long but be long enough to get your point accross.
- Then you have to decide on a sender. The sender is a string by which the different @ref orxonox::NotificationQueue "NotificationQueues" (the entities that display the @ref orxonox::Notification "Notifications") can decide whether they should display the @ref orxonox::Notification "Notification" or not. So the sender is some string that identifies a group of @ref orxonox::Notification "Notifications" that have something in common or some entity that is sending them. For example: All @ref orxonox::Notification "Notifications" sent by any part of the Questsystem have "questsystem" as sender and thus we could create a @ref orxonox::NotificationQueue "NotificationQueue" that only displays @ref orxonox::Notification "Notifications" from the Questsystem, but more to that later.
- And lastly you have to decide to whom you want to send this @ref orxonox::Notification "Notification". You have to get the clientId of the intended recipient (e.g. trough a @ref orxonox::PlayerInfo "PlayerInfo") or you only send the @ref orxonox::Notification "Notification" locally, either by setting the clientId to Host::getPlayerID() or by setting the variable 'isLocal' to true, and setting clientId to what ever you want, since it will be ignored.
- Once you have decided all that you can send the Notification by calling:
- @code
- NotificationManager::sendNotification(message, clientId, sender, isLocal); // isLocal = false can be ommitted since that is the default value.
- @endcode
-
- @subsection NotificationsDisplay Displaying notifications
- Displaying @ref orxonox::Notification "Notifications" is even easier, all you need to do is to load the NotificationLayer in the level, where you want @ref orxonox::Notification "Notifications" displayed. You can either do this manually by executing the following command in the console:
- @code
- showGUI NotificationLayer false true
- @endcode
- Or automatically, by adding a @ref orxonox::Script "Script" to the levelfile that does it for you:
- @code
- <Script code="showGUI NotificationLayer false true" needsGraphics="true" />
- @endcode
-
- If you want to change the way the @ref orxonox::Notification "Notifications" are displayed, you can enter the (at this point rather rudimentary) edit mode and add new @ref orxonox::NotificationQueue "NotificationQueues" or change position and properties of the existing ones, by executing the following command in the console:
- @code
- enterEditMode
- @endcode
-
- @section NotificationsTechincalDetails Technical details
- The Notifications module has three major parts that interact with each other. First there is the @ref orxonox::NotificationQueue "NotificationQueue", this is the entity that (logically, not effectively) displays @ref orxonox::Notification "Notifications" according to some rules, then there is the NotificationLayer, which is the GUI which (actually) displays @ref orxonox::Notification "Notifications" by visualizing the @ref orxonox::NotificationQueue "NotificationQueues" and as a result also the @ref orxonox::Notification "Notifications", that are displayed by the respective @ref orxonox::NotificationQueue "NotificationQueues" and lastly there is the @ref orxonox::NotificationManager "NotificationManager", which connects these two.
-
- @subsection NotificationQueue NotificationQueue
- The @ref orxonox::NotificationQueue "NotificationQueue" is the entity, that (as said earlier) logically displays @ref orxonox::Notification "Notifications". Furthermore a @ref orxonox::NotificationQueue "NotificationQueue" displays only a subset of all the @ref orxonox::Notification "Notifications". The parameters that reduce the range of displayed @ref orxonox::Notification "Notifications" are:
- - @b senders The senders, the set of targets of a @ref orxonox::NotificationQueue "NotificationQueue" is the set of senders a @ref orxonox::NotificationQueue "NotificationQueue" displays @ref orxonox::Notification "Notifications" from. E.g. If one would set the senders to "questsystem" then only @ref orxonox::Notification "Notifications" from the Questsystem would be displayed in that particular queue. If you set senders to "all" then all Notifications will be displayed. Different senders can be concatinated with commas.
- - @b size The size specifies how many @ref orxonox::Notification "Notifications" are displayed at the most, if there are more @ref orxonox::Notification "Notifications" that could be displayed, then only the most recent are displayed.
- - @b displayTime The display time specifies how long a @ref orxonox::Notification "Notification" is displayed at the most.
-
- @subsection NotificationLayer NotificationLayer
- The NotificationLayer is a GUI sheet, that displays all the @ref orxonox::NotificationQueue "NotificationQueues" and their @ref orxonox::Notification "Notifications". In its normal mode of operation it is transparent to input, meaning that it only functions as a means of displaying, however if switched to edit mode the NotificationLayer no longer is transparent to input and allows for the adding, removal and modification of @ref orxonox::NotificationQueue "NotificationQueues". For every @ref orxonox::NotificationQueue "NotificationQueue" there is the equivalent representation in the NotificationLayer. So @ref orxonox::NotificationQueue "NotificationQueues" are not each represented by a GUI sheet, but thely all belong to one and the same GUI sheet, the NotificationLayer.
-
- @subsection NotificationManager NotificationManager
- The @ref orxonox::NotificationManager "NotificationManager" is (hence the name) the managing entity in this setting. It is responsible for the registering and unregistering of @ref orxonox::NotificationListener "NotificationListeners" (which the @ref orxonox::NotificationQueue "NotificationQueue" is) and also informs them about changes related to @ref orxonox::Notification "Notifications". It is also responsible for the creation and destruction of @ref orxonox::NotificationQueue "NotificationQueues" through the NotificationLayer and is also the point of approach for the NotificationLayer to get information it needs to display the queues. Finally the @ref orxonox::NotificationManager "NotificationManager" is responsible for sending (and in the process creating) @ref orxonox::Notification "Notifications" and is a means for the @ref orxonox::NotificationQueue "NotificationQueues" to get the information they need about @ref orxonox::Notification "Notifications".
-
- @subsection Notification Notification
- The @ref orxonox::Notification "Notification" class is more or less a data structure that groups the notification message and the sender, and possibly other future parameters, together to form a comprehensive structure that we call Notification.
-
- Additionally there is another important class of objects belonging to the Notifications module. The @ref orxonox::NotificationDispatcher "NotificationDispatchers".
-
- @subsection NotificationDispatcher NotificationDispatcher
- @ref orxonox::NotificationDispatcher "NotificationDispatchers" are entities that are instantiated in a level file (through XML) and that dispatch (or send) a specific @ref orxonox::Notification "Notification" upon having received a triggering event.
-
- @defgroup NotificationDispatchers Dispatchers
- @ingroup Notifications
-
- @ref orxonox::NotificationDispatcher "NotificationDispatchers" are entities that are instantiated in a level file (through XML) and that dispatch (or send) a specific @ref orxonox::Notification "Notification" upon having received a triggering event.
-
- At this point there are two @ref orxonox::NotificationDispatcher "NotificationDispatchers", the @ref orxonox::SimpleNotification "SimpleNotification", which just displays a specified message, and the @ref orxonox::CommandNotification "CommandNotification" which displays a message with a binding for a specified command in it.
-*/
-
-/**
- @defgroup Objects Objects
- @ingroup Modules
-
- @defgroup Collisionshapes Collisionshapes
- @ingroup Objects
-
- @defgroup Eventsystem Eventsystem
- @ingroup Objects
-
- @defgroup Triggers Triggers
- @ingroup Objects
-
- Triggers are objects which react to certain events. They can be combined and used as simple overlay logic in levels.
-
- @defgroup NormalTrigger Trigger
- @ingroup Triggers
-
- @defgroup MultiTrigger MultiTrigger
- @ingroup Triggers
-
- @ref orxonox::MultiTrigger "MultiTriggers" are (as they are @ref orxonox::TriggerBase "Triggers") objects which react to certain events. They offer all the functionality that the common @ref orxonox::Trigger "Triggers" do with one significant difference. The common @ref orxonox::Trigger "Trigger" has just one state, it can either be <em>triggered</em> or <em>not triggered</em>, it doesn't discriminate between who's triggering (or not triggering) it. A @ref orxonox::MultiTrigger "MultiTrigger", on the other hand, has a distinct state (<em>triggered</em> or <em>not triggered</em>) for each entity that is defined as being able to trigger said @ref orxonox::MultiTrigger "MultiTrigger".
-
- This difference becomes significant, when, for example, you want a @ref orxonox::DistanceTrigger "DistanceTrigger" to trigger a @ref orxonox::QuestEffectBeacon "QuestEffectBeacon" to hand out a @ref orxonox::Quest "Quest" to any @ref orxonox::Pawn "Pawn" that enters its range. With a simple @ref orxonox::DistanceTrigger "DistanceTrigger" (as opposed to the more complex @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger") the first @ref orxonox::Pawn "Pawn" to be in range would trigger it an receive the @ref orxonox::Quest "Quest", however if a second @ref orxonox::Pawn "Pawn" would enter the range, while the first @ref orxonox::Pawn "Pawn" still is in the range nothing would happen and even after the first @ref orxonox::Pawn "Pawn" left nothing would happen, since the whole time the @ref orxonox::DistanceTrigger "DistanceTrigger" would just be triggered. In contrast with a @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" the first @ref orxonox::Pawn "Pawn" would enter the range and the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" would have the state <em>triggered</em> for this exact @ref orxonox::Pawn "Pawn" (but for none else) and thus the @ref orxonox::Pawn "Pawn" would receive the @ref orxonox::Quest "Quest" and when the second @ref orxonox::Pawn "Pawn" enters the range the state of the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" for that second @ref orxonox::Pawn "Pawn" would change to <em>triggered</em> and it would receive the @ref orxonox::Quest "Quest" as well.
-
- @section WhenToUseMultiTriggers When to use MultiTriggers
- Consequentially you would use @ref orxonox::MultiTrigger "MultiTriggers" (instead of common @ref orxonox::Trigger "Triggers"), when it is important that the trigger has different states for each triggering entity and when that fact is essential in the concept of the object that reacts to the triggering. However you should not just use @ref orxonox::MultiTrigger "MultiTrigger" instead of @ref orxonox::Trigger "Trigger", when in doubt, because @ref orxonox::MultiTrigger "MultiTrigger" produces significantly more overhead than @ref orxonox::Trigger "Trigger" due to the added complexity.
-
- @section HowToUseMultiTriggers How to use MultiTriggers
- ...
-
- @section MultiTriggerTechnicalDetails Technical Details
- A common @ref orxonox::Trigger "Trigger" is an object that can either be <em>active</em> or <em>inactive</em>, with a specified behavior how to switch between the two. A @ref orxonox::MultiTrigger "MultiTrigger" generalizes that behavior for multiple objects triggering the trigger. A @ref orxonox::MultiTrigger "MultiTrigger" can be <em>active</em> or <em>inactive</em> for any object triggering it, with the state for each object being completely independent of the state for all other objects. Each time a switch occurs an @ref orxonox::Event "Event" is fired, with a @ref orxonox::MultiTriggerContainer "MultiTriggerContainer" as the originator, containing a pointer to the @ref orxonox::MultiTrigger "MultiTrigger" that caused the @ref orxonox::Event "Event" and a pointer to the object that caused the trigger to change it's activity. This way the entity that reacts to the @ref orxonox::MultiTrigger "MultiTrigger" triggering receives the information it needs about the entity that triggered the @ref orxonox::MultiTrigger "MultiTrigger".
-
- Also, just as with all triggers, @ref orxonox::MultiTrigger "MultiTriggers" can be nested (event with triggers other than @ref orxonox::MultiTrigger "MultiTriggers").
- @code
- <MultiTrigger switch="true" delay="2">
- <DistanceMultiTrigger position="100,0,0" distance="80" />
- <EventTrigger ... />
- </Trigger>
- @endcode
-
- @ref orxonox::MultiTrigger "MultiTriggers" also allow for additional complexity which can be added through the choice of the parameters (some of which are also present in the common @ref orxonox::Trigger "Trigger") explained (briefly) below.
- But first it is important to understand a small implementational detail. There is a distinction between the @ref orxonox::MultiTrigger "MultiTrigger" being triggered (there is the state <em>triggered</em> for that) and the @ref orxonox::MultiTrigger "MultiTrigger" being active (for that is the state <em>activity</em>). From the outside only the <em>activity</em> is visible (and has above been referred to as <em>triggered</em> for the sake of comprehensibility). The state <em>triggered</em> tells us whether the trigger is actually triggered, but it could pretend (for some reason, some of which we will see shortly) to be <em>triggered</em> to the outside, while it in fact isn't (but it would then be <em>active</em>). The standard behavior is, that the <em>activity</em> changes, when the @ref orxonox::MultiTrigger "MultiTrigger" transits from being triggered to not being triggered or the other way around. So to the inside a @ref orxonox::MultiTrigger "MultiTrigger" being <em>active</em> is synonymous to the @ref orxonox::MultiTrigger "MultiTrigger" being <em>triggered</em> to the outside.
-
- The parameters of the @ref orxonox::MultiTrigger "MultiTrigger" are:
- - @b delay The delay is the time in seconds, that the trigger waits until it reacts (i.e. changes it's state) to the triggering condition being fulfilled. Internally this is handled by a state queue coupled with a counter, for each state that is delayed. The state becomes <em>active</em> when the counter runs out. This allows the @ref orxonox::MultiTrigger "MultiTrigger" to work even if the delay changes at runtime. However if the delay changes it only affects newly arriving states not the ones already in the queue. The default is <code>0</code>.
- - @b switch Switch is a boolean, if <code>true</code> the @ref orxonox::MultiTrigger "MultiTrigger" is in <em>switch-mode</em>, meaning, that the <em>activity</em> changes only when the trigger is triggered, not when it is un-triggered (Just like a light switch does). This means, that in <em>switch-mode</em> the <em>activity</em> only changes, when the trigger changes from not being triggered to being triggered but not the other way around. The default is <code>false</code>.
- - @b stayActive Stay active is also a boolean, if <code>true</code> the @ref orxonox::MultiTrigger "MultiTrigger" stays active after it has been activated as many times as specified by the parameter <em>activations</em>. In essence this means, that after the last time it is activated it cannot be deactivated. The default is <code>false</code>.
- - @b activations Activations is the number of times the @ref orxonox::MultiTrigger "MultiTrigger" can be activated until the trigger can't be triggered anymore. The default is <code>-1</code>, which denotes infinity.
- - @b invert Invert is a boolean, if <code>true</code> the @ref orxonox::MultiTrigger "MultiTrigger" is in <em>invert-mode</em>, meaning, that if the triggering condition is fulfilled the @ref orxonox::MultiTrigger "MultiTrigger" will have the state <em>not triggered</em> and and if the condition is not fulfilled it will have the state <em>triggered</em>. In short it inverts the behavior of the @ref orxonox::MultiTrigger "MultiTrigger". The default is <code>false</code>.
- - @b simultaneousTriggerers The number of simultaneous triggerers limits the number of objects that are allowed to trigger the @ref orxonox::MultiTrigger "MultiTrigger" at the same time. Or more precisely, the number of distinct objects the @ref orxonox::MultiTrigger "MultiTrigger" has positive <em>triggered</em> states for, at each point in time. The default is <code>-1</code>, which denotes infinity.
- - @b mode The mode describes how the @ref orxonox::MultiTrigger "MultiTrigger" acts in relation to all the triggers (its children), that are appended to it. There are 3 modes: <em>and</em>, meaning that the @ref orxonox::MultiTrigger "MultiTrigger" can only be triggered if all the appended triggers are active. <em>or</em>, meaning that the @ref orxonox::MultiTrigger "MultiTrigger" can only be triggered if at least one of the appended triggers is active. And <em>xor</em>, meaning that the @ref orxonox::MultiTrigger "MultiTrigger" can only be triggered if one and only one appended trigger is active. Note, that I wrote 'can only be active', that implies, that there is an additional condition to the <em>activity</em> of the @ref orxonox::MultiTrigger "MultiTrigger" and that is the fulfillment of the triggering condition (the @ref orxonox::MultiTrigger "MultiTrigger" class itself doesn't have one, but all derived classes should). Also bear in mind, that the <em>activity</em> of a @ref orxonox::MultiTrigger "MultiTrigger" is still coupled to the object that triggered it. The default is <em>and</em>.
- - @b broadcast Broadcast is a boolean, if <code>true</code> the @ref orxonox::MultiTrigger "MultiTrigger" is in <em>broadcast-mode</em>, meaning, that all trigger events that are caused by no originator (originator is <code>NULL</code>) are broadcast as having come from every possible originator, or more precisely as having come from all objects that are specified targets of this @ref orxonox::MultiTrigger "MultiTrigger". The default is <code>false</code>.
- - @b target The target describes the kind of objects that are allowed to trigger this @ref orxonox::MultiTrigger "MultiTrigger". The parameter has to be set to the class name of the class that is allowed to trigger the @ref orxonox::MultiTrigger "MultiTrigger". The default is <code>Pawn</code>.
-
- @subsection Sub-typesOfMultiTriggers Sub-types of MultiTriggers
-
- @subsubsection EventMultiTrigger EventMultiTrigger
- An @ref orxonox::EventMultiTrigger "EventMultiTrigger" can either be used to broadcast an @ref orxonox::Event "Event" that does not come from a @ref orxonox::MultiTrigger "MultiTrigger" to all entities that are targets of the @ref orxonox::EventMultiTrigger "EventMultiTrigger" or, more in line with its prototype the @ref orxonox::EventTrigger "EventTrigger", to be triggered for an entity when an @ref orxonox::Event "Event" that was caused by an entity of the same type is captured.
-
- A common usage could look like this:
- @code
- <EventMultiTrigger invert="true" delay="1">
- <events>
- <trigger>
- <MultiTrigger ... />
- <Trigger ... />
- </trigger>
- </events>
- </EventMultiTrigger>
- @endcode
-
- @subsubsection DistanceMultiTrigger DistanceMultiTrigger
- A @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" is the MultiTrigger equivalent of the @ref orxonox::DistanceTrigger "DistanceTrigger" and works just the same way. It triggers (now separately for each object triggering it, since it's a @ref orxonox::MultiTrigger "MultiTrigger") whenever an object that is a target of the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" is in the specified range.
-
- Two additional parameters can be specified for the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" are the <em>distance</em>, which defines the maximum distance at which an object still triggers the @ref orxonox:: "DistanceMultiTrigger", and the <em>targetname</em>. Setting the <em>targename</em> puts the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" in <em>single-target mode</em>. In this mode the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" can only be triggered by objects that have a @ref orxonox::DistanceTriggerBeacon "DistanceTriggerBeacon" with the name specified by <em>targetname</em> directly attached. For the <em>single-target mode</em> to work the target of the @ref orxonox::DistanceMultiTrigger "DistanceMultiTrigger" has to be set to <code>DistanceTriggerBeacon</code>.
-
- A common usage (without @ref orxonox::DistanceTriggerBeacon "DistanceTriggerBeacon") would look like this:
- @code
- <DistanceMultiTrigger position="0,0,0" switch="true" target="Pawn" distance="20" />
- @endcode
-
- With @ref orxonox::DistanceTriggerBeacon "DistanceTriggerBeacon" it would look like this:
- @code
- <DistanceMultiTrigger position="0,0,0" target="DistanceMultiTrigger" targetname="beacon1" distance="30" />
- @endcode
-*/
-
-/**
- @defgroup Overlays Overlays
- @ingroup Modules
-*/
-
-/**
- @defgroup Pickup Pickup
- @ingroup Modules
-
- The Pickup module adds a special type of object to Orxonox, the so-called @ref orxonox::Pickupable "Pickupables". @ref orxonox::Pickupable "Pickupables" are objects that can be picked up (by virtually any entity, but commonly by the @ref orxonox::Pawn "Pawn") and have some kind of effect on the entity that picked the @ref orxonox::Pickupable "Pickupable" up.
-
- @section IncludingPickups Including pickups in a level
- @ref orxonox::Pickupable "Pickupables" are designed so that they can be included in levels fairly easily, while also ensuring, that the pickup itself (its game-logic component) and how it is represented (e.g. in the PickupInventory (the GUI that displays @ref orxonox::Pickupable "Pickupables") or in the game) are neatly seperated.
- To be able to use @ref orxonox::Pickupable "Pickupables" in a level one must understand some basic concepts.
- - @ref orxonox::Pickupable "Pickupables" are entities which (by itself) have no physical (or graphical) dimension. The simply represent the effect they will have on a @ref orxonox::PickupCarrier "PickupCarrier" (the entity that can pick up @ref orxonox::Pickupable "Pickupables", @ref orxonox::Pawn "Pawn" for example inherits from @ref orxonox::PickupSpawner "PickupSpawner" and thus is able to pick up and carry @ref orxonox::Pickupable "Pickupables"), when used and the mechanism that leads to that.
- - The physical (or graphical) dimension of a pickup is called a @ref orxonox::PickupRepresentation "PickupRepresentation".
- - The @ref orxonox::PickupRepresentation "PickupRepresentation" of a @ref orxonox::Pickupable "Pickupable" and the @ref orxonox::Pickupable "Pickupable" itself are linked to each other, in such a way that a @ref orxonox::PickupRepresentation "PickupRepresentation" can only represent one type of @ref orxonox::Pickupable "Pickupable".
- - A type of @ref orxonox::Pickupable "Pickupable" is a specific pickup class (inheriting from @ref orxonox::Pickupable "Pickupable") with specific values for all its relevant parameters. This means, that a pickup of the same class with the same values for all parameters except for one is a different type of pickup and will therefore have a different @ref orxonox::PickupRepresentation "PickupRepresentation". Which parameters are the ones relevant to destinguish between two types of pickups can be defined in the class description of the specific pickup.
- - The entity that actually gives a @ref orxonox::Pickupable "Pickupable" to a @ref orxonox::PickupCarrier "PickupCarrier" is called a @ref orxonox::PickupSpawner "PickupSpawner". A @ref orxonox::PickupSpawner "PickupSpawner" creates (based on some parameters) @ref orxonox::Pickupable "Pickupables" which then is picked up by the @ref orxonox::PickupCarrier "PickupCarrier", that caused the @ref orxonox::PickupSpawner "PickupSpawner" to spawn a new pickup. How the spawner looks in the game is defined by the @ref orxonox::PickupRepresentation "PickupRepresentation" of the @ref orxonox::Pickupable "Pickupable" it spawns.
-
- @subsection UsingPredifinedPickups Using predefined pickups
- There is a file called <code>pickupRepresentationTemplates.oxt</code> in <code>levels/templates</code>, which holds the templates for the @ref orxonox::PickupRepresentation "PickupRepresentations" and also templates for @ref orxonox::Pickupable "Pickupables". The templates for the @ref orxonox::PickupRepresentation "PickupRepresentations" define the @ref orxonox::StaticEntity "StaticEntities" that are attached to the @ref orxonox::PickupSpawner "PickupSpawners" to make them look like the @ref orxonox::Pickupable "Pickupable" they are spawning. The templates for the @ref orxonox::Pickupable "Pickupables" can be added just for ease of use.
- If you want to use pickups you will have to include this file in your level file, somewhere above the Level-tag.
- @code
- <?lua
- include("templates/pickupRepresentationTemplates.oxt")
- ?>
- ...
- <Level>
- ...
- @endcode
- There is another file called <code>pickups.oxi</code> in <code>level/includes</code> which creates all @ref orxonox::PickupRepresentation "PickupRepresentations" needed for the @ref orxonox::Pickupable "Pickupable" supplied by the <code>pickupRepresentationTemplates.oxt</code> file. This file will have to be included as well. It has to be somewhere after the opening Scene-tag and your first use of a pickup.
- @code
- <Scene>
- ...
- <?lua
- include("includes/pickups.oxi")
- ?>
- @endcode
- After that all the predefined pickups specified in those two files can be used just by creating a @ref orxonox::PickupSpawner "PickupSpawner" for them in the respective level.
- For example:
- @code
- <PickupSpawner position="-100,0,-100" respawnTime="30" maxSpawnedItems="10">
- <pickup>
- <HealthPickup
- health = 10
- healthType = "limited"
- activationType = "immediate"
- durationType = "once"
- />
- </pickup>
- </PickupSpawner>
- @endcode
- Please be aware, that the @ref orxonox::Pickupable "Pickupable" specified for the @ref orxonox::PickupSpawner "PickupSpawner", has to be exactly the same (including all parameters) to the one specified in the <code>pickups.oxi</code> file.
- To make things simpler, one could just use the templates specified in the <code>pickupRepresentationTemplates.oxt</code> file. Which, following the previous example, would look like this:
- @code
- <PickupSpawner position="-100,0,-100" respawnTime="30" maxSpawnedItems="10">
- <pickup>
- <HealthPickup template="smallhealthpickup" />
- </pickup>
- </PickupSpawner>
- @endcode
-
- @subsection UnsingNon-PredefinedPickups Using non-predefined pickups
- To include a type of pickup (which, as we remember, is the class of the @ref orxonox::Pickupable "Pickupable" with specific values for all the relevant parameters) in a level file, you can just create a new @ref orxonox::PickupSpawner "PickupSpawner" and specify the @ref orxonox::Pickupable "Pickupable".
- @code
- <PickupSpawner position="-100,0,-100" respawnTime="30" maxSpawnedItems="10">
- <pickup>
- <HealthPickup
- health = 33
- healthType = "limited"
- activationType = "immediate"
- durationType = "once"
- />
- </pickup>
- </PickupSpawner>
- @endcode
- As can be seen in the <code>pickupRepresentationTemplates.oxt</code> file and the <code>pickups.oxi</code> file there is no @ref orxonox::PickupRepresentation "PickupRepresentation" defined for this type of pickup. Thus the default representation will be used.
-
- To create an appropriate @ref orxonox::PickupRepresentation "PickupRepresentation" for the inserted pickup above, you can just create a @ref orxonox::PickupRepresentation "PickupRepresentation" within the scene (Within the Scene-tags).
- @code
- <PickupRepresentation
- name = "My new health pickup"
- description = "This is an awesome new health pickup."
- spawnerTemplate = "mediumhealthpickupRepresentation"
- inventoryRepresentation = "MediumHealth"
- >
- <pickup>
- <HealthPickup
- health = 33
- healthType = "limited"
- activationType = "immediate"
- durationType = "once"
- />
- </pickup>
- </PickupRepresentation>
- @endcode
- Notice, that the type of pickup specified for the @ref orxonox::PickupRepresentation "PickupRepresentation", naturally, needs to be the same (this is the way they can be connected). Also, we just used an existing <em>spawnerTemplate</em>, to make things simpler.
-
- The next step is to create a <em>spawnerRepresentation</em> uniquely for our new type of pickup. Lets call it <code>newhealthpickupRepresentation</code>. Thus the parameter <em>spawnerTemplate</em> of the @ref orxonox::PickupRepresentation "PickupRepresentation" has to be changed to that value.
- @code
- spawnerTemplate = "newhealthpickupRepresentation"
- @endcode
- The <em>spawnerTemplate</em> defines how the @ref orxonox::PickupSpawner "PickupSpawner" is displayed in a level.
- In our example case it could look like this:
- @code
- <Template name=newhealthpickupRepresentation>
- <PickupRepresentation>
- <spawner-representation>
- <StaticEntity>
- <attached>
- -- Here you can put all the objects which define the look of the spawner. --
- </attached>
- </StaticEntity>
- </spawner-representation>
- </PickupRepresentation>
- </Template>
- @endcode
- Please refer to the <code>pickupRepresentationTemplates.oxt</code> for more examples.
-
- The @ref orxonox::PickupRepresentation "PickupRepresentation" also needs another parameter the <em>inventoryRepresentation</em>. This parameter defined how the @ref orxonox::Pickupable "Pickupable" is displayed in the PickupInventory (a menu to browse the currently equipped pickups).
- @code
- inventoryRepresentation = "MediumHealth"
- @endcode
- This is the name of an image defined in the PickupInventory imageset (<code>PickupInventory.imageset</code>), which can be found in <code>data_extern/gui/imagesets</code>.
-
- This is all that has to be done. Now you have a new pickup type with an appropriate @ref orxonox::PickupRepresentation "PickupRepresentation" for your use. If you feel that your pickup is useful in general, please don't hesitate to create a template for the pickup and add your pickup to the <code>pickupRepresentationTemplates.oxt</code> file and the <code>pickups.oxi</code> file, so that anyone who wants to use it can do so quite easily.
-
- There is also an additional way to create new types of pickups to be used in a level (without having to do any coding). There is a @ref orxonox::Pickupable "Pickupable" called the @ref orxonox::PickupCollection "PickupCollection", which is just a collection (hence the name) of @ref orxonox::Pickupable "Pickupables" (more precisely of @ref orxonox::CollectiblePickup "CollectiblePickups"), behaving as if it was just one @ref orxonox::Pickupable "Pickupable".
- A @ref orxonox::PickupCollection "PickupCollection" can be created as follows:
- @code
- <PickupCollection>
- <pickupables>
- -- some pickups you want to have in your collection, e.g. --
- <HealthPickup template=smallhealthpickup />
- <HealthPickup health=50 healthRate=5 durationType=continuous activationType=immediate healthType=limited />
- </pickupables>
- </PickupCollection>
- @endcode
- Of which types of pickups a collection is made up is entirely up to the one creating the @ref orxonox::PickupCollection "PickupCollection", they can be mixed freely.
-
- @section CreatingAPickup Creating a new pickup
- Things have been fairly straightforward so far. Creating a @ref orxonox::Pickupable "Pickupable" form scratch isn't as easy. Therefore I'm just going to supply you with a recipe, or a set of steps you have to take, without which your pickup won't work and point out some common pitfalls.
-
- @subsection CreatingAPickupClass Creating the class
- For a new @ref orxonox::Pickupable "Pickupable" you need to create a new class in <code>>modules/pickup/items</code>. Your class needs to be derived from another pickup class, normally this would either be @ref orxonox::Pickupable "Pickupable", @ref orxonox::CollectiblePickup "CollectiblePickup" or @ref orxonox::Pickup "Pickup". @ref orxonox::Pickupable "Pickupable" is (as mentioned earlier) the base class of all things that can be picked up, thus of all pickups. @ref orxonox::CollectiblePickup "CollectiblePickup" is a (directly) derived class of @ref orxonox::Pickupable "Pickupable" and provides the additional functionality of enabling your pickup to be used in a @ref orxonox::PickupCollection "PickupCollection". However you are probably going to want to derive your class form @ref orxonox::Pickup "Pickup", because it is a @ref orxonox::CollectiblePickup "CollectiblePickup" and provides some useful methods. So have a look at @ref orxonox::Pickup "Pickup".
- Once you have created your new pickup class you have to insert it in the <code>PickupPrereqs.h</code> file in the <code>modules/pickup</code> folder and in the <code>CMakeList.txt</code> file in the <code>modules/pickup/items</code> folder. Also have a look at other pickups to make sure you include all the necessary files in your class.
-
- @subsection ChoosingTheCarriers Coosing the carriers
- You also have to choose the entities that are allowed to pick your pickup up. After you have chosen the entity that carries your pickup, you need to do the following.
- - The enity that carries your pickup needs to be derived from the @ref orxonox::PickupCarrier "PickupCarrier" interface. And you need to implement the @ref orxonox::PickupCarrier "PickupCarriers'" virtual functions <code>getCarrierChildren()</code> and <code>getCarrierParent()</code>. These tow methods are needed, because all pickups are initially picked up by a @ref orxonox::Pawn "Pawn" and then handed down to the entity that effectively carries them. With the above mentioned two function just that is accomplished. A hierarchical structure is established with one parent and a set of children, where the @ref orxonox::Pawn "Pawn" is the root node of this hierarchical structure, the only entity with no parent.
- - Once you have done that you will also want to specify in your pickup which carriers can pick it up, this is done via the <code>addTarget()</code> function. So you have to make sure the target is added whenever one of your pickups is created (so, most conveniently somewhere in the constructor), with the following command.
- @code
- this->addTarget(ClassIdentifier<MyCarrierClass>::getIdentifier());
- @endcode
-
- @subsection CreatingTheInnerWorkings Creating the inner workings of your pickup
- Now that we have the skeleton of a pickup and we have defined which carriers are allowed to pick our pickup up we are going to take a look at all the methods we can (or sometimes have to) overload from @ref orxonox::Pickupable "Pickupable", for our pickup to work properly. But first I will introduce some more concepts to make the need for these methods more obvious.
- - Since one pickup class can by itself be many pickup types, we need a way to find out whether a particular instance of a pickup is of the same type as another instance of a pickup. To that end the @ref orxonox::PickupIdentifier "PickupIdentifier" was created. The @ref orxonox::PickupIdentifier "PickupIdentifier" accounts for the type of class your pickup is of and also for the parameters (and their values) that distinguish different types of pickups of the same class. Much of the functionality of the pickup module relies on this identifier being correct, thus it is very important to initialize it correctly. (We will see, how that is done in a short while.)
- - Every @ref orxonox::Pickupable "Pickupable" has at least two states which are very important. The first is, whether the @ref orxonox::Pickupable "Pickupable" is currently in use or not and the second is whether the pickup is currently picked up or not.
-
- Let's have a look at the important methods.
- - <b>changedUsed()</b> The <code>changedUsed()</code> method is called whenever the state of the @ref orxonox::Pickupable "Pickupable" transits from being used to not being used or the other way around. Which means this method is probably the most important method you have at your fingertips, since it enables you to apply the effect of your pickup when it gets used and remove the effect as soon as it is no longer in use.
- - <b>changedPickedUp()</b> The <code>changedPickedUp()</code> method is called whenever the state of the @ref orxonox::Pickupable "Pickupable" changes from being picked up to not being picked up or the other way around. For example if you want your pickup to be used as soon as it is picked up, this is the method you have to overload to achieve that behavior (or just let your pickup be derived from @ref orxonox::Pickup "Pickup", which implements exactly that behavior, if the <em>activationType</em> is set to <em>immediate</em>). You don't have to concern yourself with destroying the pickup or creating a spawner when it changes to not picked up, since that is already implemented with the @ref orxonox::Pickupable "Pickupable" and @ref orxonox::PickupCarrier "PickupCarrier" classes. If you want a different behavior, however, once again, this is the method.
- - <b>changedCarrier()</b> The <code>changedCarrier()</code> method is called whenever the carrier of the @ref orxonox::Pickupable "Pickupable" changes. And by that I don't mean the class that is allowed to carry the pickup, but the object that actually carries (or carried) the pickup. Please do not overload this class to implement behavior for picked up -> not picked up transitions, use <code>changedPickedUp()</code> for that. For most pickup classes this method doesn't need to be overloaded. Where it is used, however is in the @ref orxonox::PickupCollection "PickupCollection" class, where the new carrier needed to be communicated to all pickups the collection consists of, whenever the carrier was changed.
-
- Please be aware, that these three methods are methods registered with @ref Super.h "Super", meaning, that whenever overloading them, don't forget to call <code>SUPER(MyClass, myMethod);</code>.
- Also when implementing the above methods you should think of what should happen in unexpected situations, e.g. when your pickup is unused manually and set to used again.
- Additionally you should use the <code>destroy()</code> method of Pickupable instead of the method provided by @ref orxonox::OrxonoxClass "OrxonoxClass", meaning <code>Pickupable::destroy()</code> instead of plain <code>destroy()</code>.
-
- - <b>clone()</b> The <code>clone()</code> method creates a new pickup of the same type as the pickup it is cloned from. So the cloned pickup is not exactly the same, as it doesn't necessarily completely reflect the status of the pickup it is cloned from, but it reflects all the parameters and their values, that distinguish different types of this pickup class. It needs to be implemented by every pickup class. And it is best if this is done in a very specific way. Below is shown how:
- @code
- void MyPickup::clone(OrxonoxClass*& item)
- {
- if(item == NULL)
- item = new MyPickup(this);
-
- SUPER(MyPickup, clone, item);
-
- MyPickup* pickup = dynamic_cast<MyPickup*>(item);
- // Here you should set all the important parameters (that distinguish the different types of this pickup), e.g.
- pickup->setSomeParameter(this->getSomeParameter());
- // You must also initialize the identifier of the new pickup, this is normally done in a member function called in
- pickup->initializeIdentifier();
- }
- @endcode
- - <b>initializeIdentifier()</b> The <code>initializeIdentifier()</code> method initializes (or more simply put, creates) the @ref orxonox::PickupIdentifier "PickupIdentifier" of the instance of your pickup. Since the important values of the parameters are not yet available in the constructor of your pickup this <code>initializeIdentifier()</code> method must be called as soon as they are available, which normally is in the <code>XMLPort()</code> method, and the <code>clone()</code> method, as seen above. In the <code>initializeIdentifier()</code> method you need to register each parameter that is important for the type of your pickup to its identifier, this is normally done as follows:
- @code
- void Pickup::initializeIdentifier(void)
- {
- // If the get method returns a string.
- std::string val1 = this->getSomeParameter();
- std::string type1 = "someParameter";
- this->pickupIdentifier_->addParameter(type1, val1);
- // If the get method doesn't return a string
- std::stringstream stream;
- stream << this->getSomeOtherParameter();
- std::string type2 = "someOtherParameter";
- std::string val2 = stream.str();
- this->pickupIdentifier_->addParameter(type2, val2);
- }
- @endcode
-
- Be aware, this only works for parameters that are simple enough, meaning with pointers for example it will, naturally, not work, and other ways must be found (this is for example done in @ref orxonox::PickupCollection "PickupCollection" with a derived class of the @ref orxonox::PickupIdentifier "PickupIdentifier", the @ref orxonox::PickupCollectionIdentifier "PickupCollectionIdentifier") or in the @ref orxonox::DronePickup "DronePickup" class by using a @ref orxonox::Template "Template".
- - <b>createSpawner()</b> The <code>createSpawner()</code> method needs to be implemented by any pickup directly inheriting from @ref orxonox::Pickupable "Pickupable" (or directly from @ref orxonox::CollectiblePickup "CollectiblePickup"), so if you inherit from @ref orxonox::Pickup "Pickup", you don't need to implement this. It is used to create a @ref orxonox::PickupSpawner "PickupSpawner", when the pickup is dropped. A standard implementation would look like this.
- @code
- bool MyPickup::createSpawner(void)
- {
- new DroppedPickup(this, this, this->getCarrier());
- return true;
- }
- @endcode
-
- @section PickupTechnicalDetails Technical details
-
- @image html pickupmodule.png
-
- @defgroup PickupItems Items
- @ingroup Pickup
-
- The actual pickups can be found here.
-*/
-
-/**
- @defgroup Pong Pong
- @ingroup Modules
-*/
-
-/**
- @defgroup Questsystem Questsystem
- @ingroup Modules
-
- The Questsystem is a module that enhances Orxonox with @ref orxonox::Quest "Quests". @ref orxonox::Quest "Quests" are objects that challenge the player that receives such an object to fulfill some specific task (e.g. Rescue a princess, fetch some rare metal alloy, destroy the evil pirates den, ...). Upon having fulfilled that task the player can be rewarded with some kind of reward. Quests can be hierarchically structured, meaning that to fulfill some @ref orxonox::Quest "Quest" you first have to fulfill all (or some, depending on the quest) sub-quests.
-
- @section QuestsystemTechnicalDetails Technical details
- The Questsystem essentially consists of the @ref orxonox::Quest "Quest" entity which is the quest itself (and sub- or helper-entities, such as @ref orxonox::QuestHint "QuestHint" (hints for quests) or @ref orxonox::QuestDescription "QuestDescription" (descriptions for quests and hints, to separate content from function)), the @ref orxonox::QuestEffect "QuestEffect" and @ref orxonox::QuestListener "QuestListener" entities which are the only tools for quests to have any influence on the game world. By enabling quests to have @ref orxonox::QuestEffect "QuestEffects" they are able to (for example) fail or complete other quests, activate hints, give rewards or even add a quest to a player. @ref orxonox::QuestListener "QuestListeners" on the other hand can be used by any object to react to a status change of a quest. The @ref orxonox::QuestEffectBeacon "QuestEffectBeacon" is the physical entity which finally makes quests available for the player in the game, by being able to invoke a @ref orxonox::QuestEffect "QuestEffect" on a player (under some conditions).
- @image html questsystem.png
-
- @section CreatingQuests Creating Quests
-
- @subsection CreatingTheQuestHierarchy Creating the Quest-Hierarchy
- To start you have to create a Quest-Hierarchy in the XML-Levelfile by hierarchically nesting your quests. There are two types of Quests you can use, the LocalQuest and the GlobalQuest.
-
- @subsubsection LocalQuest LocalQuest
- A @ref orxonox::LocalQuest "LocalQuest" is a @ref orxonox::Quest "Quest" which has different states for each player, that means each @ref orxonox::LocalQuest "LocalQuest" can be obtained and completed (or failed) by each player in parallel. A questId is some string that uniquely identifies the quest, this can either be a name or, to ensure uniqueness, you can use a GUID generator (<a href="http://www.google.com/search?q=guid+generator">google</a> or you can use this <a href="http://www.famkruithof.net/uuid/uuidgen">generator</a>). The advantage of GUID is, that you can be quite sure that your id is unique, the drawback is, that it provides less overview and can be quite confusing when looking at the level file. So make your own choice.
-
- Creating a @ref orxonox::LocalQuest "LocalQuest" in XML goes as follows:
- @code
- <LocalQuest id="questId">
- <QuestDescription title="Title" description="Description." /> //The description of the quest.
- <subquests>
- <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
- ...
- <Quest id="questIdn" />
- </subquests>
- <hints>
- <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
- ...
- <QuestHint id="hintIdn" />
- </hints>
- <fail-effects>
- <QuestEffect /> //A list of QuestEffects, invoked when the Quest is failed, see QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </fail-effects>
- <complete-effects>
- <QuestEffect /> //A list of QuestEffects, invoked when the Quest is completed, see QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </complete-effects>
- </LocalQuest>
- @endcode
-
- @subsubsection GlobalQuest GlobalQuest
- @ref orxonox::GlobalQuest "GlobalQuests" are different, they can be obtained by every player but the changes made to the @ref orxonox::Quest "Quest" (e.g. completion of the quest) affect all owners of the quest. A short example: There are 3 Players, A, B and C. Player A obtains the quest, a while later player B obtains the quest and completes it. Since it is a @ref orxonox::GlobalQuest "GlobalQuest" it is completed for all players having obtained the Quest which means it is also completed for player A. Player C though, never having obtained the quest, can now never complete it.
-
- Creating a @ref orxonox::GlobalQuest "GlobalQuest" in XML goes as follows:
- @code
- <GlobalQuest id="questId">
- <QuestDescription title="Title" description="Description." /> //The description of the quest.
- <subquests>
- <Quest id ="questId1" /> //A list of n subquest, be aware, each of the <Quest /> tags must have a description and so on and so forth as well.
- ...
- <Quest id="questIdn" />
- </subquests>
- <hints>
- <QuestHint id="hintId1" /> //A list of n QuestHints, see QuestHint for the full XML representation of those.
- ...
- <QuestHint id="hintIdn" />
- </hints>
- <fail-effects>
- <QuestEffect /> //A list of QuestEffects, invoked on all players possessing this quest, when the Quest is failed, see QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </fail-effects>
- <complete-effects>
- <QuestEffect /> //A list of QuestEffects, invoked on all players possessing this quest, when the Quest is completed, see QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </complete-effects>
- <reward-effects>
- <QuestEffect /> //A list of QuestEffects, invoked on the player completing this quest. See QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </reward-effects>
- </GlobalQuest>
- @endcode
-
- As you may see that another difference between a @ref orxonox::GlobalQuest "GlobalQuest" and a @ref orxonox::LocalQuest "LocalQuest" is, that with a @ref orxonox::GlobalQuest "GlobalQuest" having @ref orxonox::AddReward "RewardEffects", the RewardEffects are only executed on the player completing the quest. Additionally @ref orxonox::CompleteQuest "CompleteEffects" are executed on all players having obtained the quest before it was completed, when it is completed., while with a @ref orxonox::LocalQuest "LocalQuest" each player that completes a quest, completes it for himself alone, but also gets the reward, regardless whether another player completed the quest before him.
-
- @subsubsection QuestHint QuestHint
- @ref orxonox::QuestHint "QuestHints" can be used to give a player useful information for @ref orxonox::Quest "Quests" he is working on completing. @ref orxonox::QuestHint "QuestHints" cannot have any side effects, but also have an identifier which follows the same form as in the @ref orxonox::Quest "Quests".
-
- Creating a @ref orxonox::QuestHint "QuestHint" in XML goes as follows:
- @code
- <QuestHint id="hintId">
- <QuestDesctription title="" description="" />
- </QuestHint>
- @endcode
-
- @subsubsection QuestDescription QuestDescription
- Each @ref orxonox::Quest "Quest" (and also each @ref orxonox::QuestHint "QuestHint") must have a @ref orxonox::QuestDescription "QuestDescription" consisting of a title and description, and for @ref orxonox::Quest "Quests" also messages for the event the quest is either failed or completed. Of course these are (as is the title and the description) optional.
-
- Creating a @ref orxonox::QuestDescription "QuestDescription" in XML goes as follows:
- @code
- <QuestDescription title="Title" description="Description Text" failMessage="You fail." completeMessage="You win!" />
- @endcode
-
- @subsection CreatingSideEffects Creating side effects
- @ref orxonox::Quest "Quests" can have side effects, in fact that is mostly what they are about. This means that they can have an influence on the game world. @ref orxonox::Quest "Quests" do that through two distinct devices, @ref orxonox::QuestEffect "QuestEffects" (active) and @ref orxonox::QuestListener "QuestListeners" (passive).
-
- @subsubsection QuestEffect QuestEffect
- A @ref orxonox::QuestEffect "QuestEffect" is the first (and probably most important) device for @ref orxonox::Quest "Quests" to have side effects. There are two entities that can have @ref orxonox::QuestEffect "QuestEffects": @ref orxonox::Quest "Quests" and @ref orxonox::QuestEffectBeacon "QuestEffectBeacons" (which will be explained later on). @ref orxonox::QuestEffect "QuestEffects", for example, can start a @ref orxonox::Quest "Quest" for a player, complete/fail @ref orxonox::Quest "Quests" for a player, add a @ref orxonox::QuestHint "QuestHint" or a @ref orxonox::Rewardable "Reward" to a player, and potentially much, much more.
-
- These @ref orxonox::QuestEffect "QuestEffects" are implemented so far, but feel free to <a href="http://www.orxonox.net/wiki/DamianFrick">contact me</a> if you have suggestions for new @ref orxonox::QuestEffect "QuestEffects" or if you need help implementing a new one yourself.
-
- @paragraph AddQuest AddQuest
- This @ref orxonox::QuestEffect "QuestEffect" adds (respectively starts) a @ref orxonox::Quest "Quest" (identified by the given questId) to the player.
- @code
- <AddQuest questId="id" /> //Where id identifies the Quest that should be added.
- @endcode
-
- @paragraph FailQuest FailQuest
- This @ref orxonox::QuestEffect "QuestEffect" fails a @ref orxonox::Quest "Quest" (identified by the given questId) for the player.
- @code
- <FailQuest questId="id" /> //Where id identifies the Quest that should be added.
- @endcode
-
- @paragraph CompleteQuest CompleteQuest
- This @ref orxonox::QuestEffect "QuestEffect" completes a @ref orxonox::Quest "Quest" (identified by the given questId) for the player.
- @code
- <CompleteQuest questId="id" /> //Where id identifies the Quest that should be added.
- @endcode
-
- @paragraph AddQuestHint AddQuestHint
- This @ref orxonox::QuestEffect "QuestEffect" adds a @ref orxonox::QuestHint "QuestHint" to a @ref orxonox::Quest "Quest" (identified by the given questId) of a player.
- @code
- <AddQuestHint hintId="id" /> //Where id identifies the QuestHint that should be added.
- @endcode
-
- @paragraph AddReward AddReward
- This @ref orxonox::QuestEffect "QuestEffect" adds a @ref orxonox::Rewardable "Rewardable" (@ref orxonox::Rewardable "Rewardable" is an Interface which can be implemented by an object that its creator thinks should be able to be rewarded a player for completing (or failing for that matter) a @ref orxonox::Quest "Quest") to the player. @ref Pickup Pickups for example wold be good @ref orxonox::Rewardable "Rewardables".
- @code
- <AddReward>
- <Rewardable /> //A list of Rewardable objects to be rewarded the player, see the specific Rewardables for their respective XML representations.
- ...
- <Rewardable />
- </AddReward>
- @endcode
-
- @subsubsection QuestListener QuestListener
- The @ref orxonox::QuestListener "QuestListener" is the second device you can use to create side effects. As opposed to @ref orxonox::QuestEffect "QuestEffects" (that are executed (or invoked) either as a result of failing or completing a Quest or by a @ref orxonox::QuestEffectBeacon "QuestEffectBeacon"), @ref orxonox::QuestListener "QuestListeners" are passive, meaning that they relay information regarding status changes of @ref orxonox::Quest "Quests" rather than enforcing status changes. @ref orxonox::QuestListener "QuestListeners" have a certain mode (all, start, complete or fail) and a @ref orxonox::Quest "Quest" which they belong to (resp. to which they react). You then can use @ref orxonox::QuestListener "QuestListeners" to make basically any object aware of when the status of the given @ref orxonox::Quest "Quest" changes (the way you defined through the mode) and take any action you may think of.
-
- Here is an example of the usage of @ref orxonox::QuestListener "QuestListeners" in XML:
- @code
- <BaseObject> // The object that should react to the status change of a Quest.
- <events>
- <function> // Where function is the method of the object that schould be executed. Normally this would be visibility or activity.
- <QuestListener questId="someQuestId" mode="someMode" /> // Where someQuestId is the identifier for the Quest the QuestListener is reacting to, and someMode is the kind of status change the QUestListener reacts to (all, start, complete or fail).
- </function>
- </events>
- </BaseObject>
- @endcode
-
- I hope this example has made the usage of @ref orxonox::QuestListener "QuestListeners" a little clearer. The @ref orxonox::QuestListener "QuestListener" actually reacts exactly as any @ref orxonox::Trigger "Trigger" or @ref orxonox::EventListener "EventListener" would (although the @ref orxonox::QuestListener "QuestListener" is really neighter the one nor the other) which means you can use it in exactly the same way you would use one of the above, it just reacts to a different thing. Namely to the change in a @ref orxonox::Quest "Quests" status.
-
- @subsection PuttingTheQuestsInTheGameWorld Putting the Quests in the game world
- As of now we know how to create @ref orxonox::Quest "Quests" and @ref orxonox::QuestHint "QuestHints", we have a way for quests to add new quests, or even complete/fail other quests. We also have a way of reacting to a status change in a @ref orxonox::Quest "Quest". In short we know how quests can be created, how they can influence other quests and how we can react to changes in quests. But our @ref orxonox::Quest "Quests" have no ties (well, not really at least) to the game world as of yet, meaning, that the game world cannot influence quests. For this we have @ref orxonox::QuestEffectBeacon "QuestEffectBeacons".
-
- @subsubsection QuestEffectBeacon QuestEffectBeacon
- The @ref orxonox::QuestEffectBeacon "QuestEffectBeacon" is a @ref orxonox::StaticEntity "StaticEntity" and has the ability to (when triggered trough some circumstance) invoke a specified list of @ref orxonox::QuestEffect "QuestEffects" on the player triggering the @ref orxonox::QuestEffectBeacon "QuestEffectBeacon".
-
- Creating a @ref orxonox::QuestEffectBeacon "QuestEffectBeacon" in XML goes as follows:
- @code
- <QuestEffectBeacon times=n> //Where 'n' is either a number >= 0, which means the QuestEffectBeacon can be executed n times. Or n = -1, which means the QuestEffectBeacon can be executed an infinite number of times.
- <effects>
- <QuestEffect /> //A list of QuestEffects, invoked when the QuestEffectBeacon is executed, see QuestEffect for the full XML representation.
- ...
- <QuestEffect />
- </effects>
- <events>
- <execute>
- <EventListener event=eventIdString />
- </execute>
- </events>
- <attached>
- <PlayerTrigger name=eventIdString /> //A PlayerTrigger triggering the execution of the QuestEffectBeacon.
- </attached>
- </QuestEffectBeacon>
- @endcode
-
- The @ref orxonox::QuestEffectBeacon "QuestEffectBeacon" can only be executed a defined number of times (where -1 times stands for an infinite number of times) and the @ref orxonox::QuestEffect "QuestEffects" are invoked whenever the method 'execute' is called, which is (indirectly through an @ref orxonox::EventListener "EventListener", because I wanted to attach the @ref orxonox::PlayerTrigger "PlayerTrigger" so that its position is always relative to the @ref orxonox::QuestEffectBeacon "QuestEffectBeacons" position) done by the @ref orxonox::PlayerTrigger "PlayerTrigger".
-
- A @ref orxonox::PlayerTrigger "PlayerTrigger" is a special sort of @ref orxonox::Trigger "Trigger" that knows the player that triggered it and therefore can be asked who that was. This allows the @ref orxonox::QuestEffect "QuestEffects" to be executed on the right player.
-
- @section SampleQuest Sample quest
- To get your head around all of this and see some of the things mentioned here in action you might want to check out the "The Tale of Princess Aeryn"-Quest (Levelfile: princessAeryn.oxw) in the level-folder.
-*/
-
-/**
- @defgroup QuestEffects Effects
- @ingroup Questsystem
-
- A @ref orxonox::QuestEffect "QuestEffect" is a device for @ref orxonox::Quest "Quests" to have side effects. There are two entities that can have @ref orxonox::QuestEffect "QuestEffects": @ref orxonox::Quest "Quests" and \ref orxonox::QuestEffectBeacon "QuestEffectBeacons". @ref orxonox::QuestEffect "QuestEffects", for example, can start a @ref orxonox::Quest "Quest" for a player, complete/fail @ref orxonox::Quest "Quests" for a player, add a @ref orxonox::QuestHint "QuestHint" or a @ref orxonox::Rewardable "Reward" to a player, and potentially much, much more.
-*/
-
-/**
- @defgroup Weapons Weapons
- @ingroup Modules
-*/
Deleted: code/forks/sandbox_light/doc/api/images/orxonox.jpg
===================================================================
(Binary files differ)
Deleted: code/forks/sandbox_light/doc/api/images/pickupmodule.png
===================================================================
(Binary files differ)
Deleted: code/forks/sandbox_light/doc/api/images/questsystem.png
===================================================================
(Binary files differ)
Modified: code/forks/sandbox_light/doc/api/main.dox
===================================================================
--- code/forks/sandbox_light/doc/api/main.dox 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/doc/api/main.dox 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,8 +1,6 @@
/**
@mainpage
- @image html orxonox.jpg
-
This is the documentation of Orxonox. It contains descriptions of our classes and functions and
explains their usage with several examples and background information. Because Orxonox is so big,
we can't document all of our code - sorry for that! But we do your best to document the most
Modified: code/forks/sandbox_light/src/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -37,19 +37,11 @@
# If no defines are specified, these libs get linked statically
ADD_COMPILER_FLAGS("-DBOOST_ALL_DYN_LINK" WIN32 LINK_BOOST_DYNAMIC)
-#ADD_COMPILER_FLAGS("-DENET_DLL" WIN32 LINK_ENET_DYNAMIC)
-ADD_COMPILER_FLAGS("-DLUA_BUILD_AS_DLL" WIN32 LINK_LUA_DYNAMIC)
-ADD_COMPILER_FLAGS("-DZLIB_DLL" WIN32 LINK_ZLIB_DYNAMIC)
# If no defines are specified, these libs get linked dynamically
-ADD_COMPILER_FLAGS("-DCEGUI_STATIC" WIN32 NOT LINK_CEGUI_DYNAMIC)
-ADD_COMPILER_FLAGS("-DOGRE_STATIC_LIB" WIN32 NOT LINK_OGRE_DYNAMIC)
-ADD_COMPILER_FLAGS("-DSTATIC_BUILD" WIN32 NOT LINK_TCL_DYNAMIC)
+#ADD_COMPILER_FLAGS("-DSTATIC_BUILD" WIN32 NOT LINK_TCL_DYNAMIC)
######### Library Behaviour (external) ##########
-# Use TinyXML++
-ADD_COMPILER_FLAGS("-DTIXML_USE_TICPP")
-
# Default linking for externals is SHARED
SET(ORXONOX_EXTERNAL_LINK_MODE SHARED CACHE STRING "Link mode for external libraries that we build ourselves. Note: on Windows, some libraries cannot be linked shared.")
@@ -58,66 +50,34 @@
ELSE()
SET(_external_shared_link FALSE)
ENDIF()
-# If no defines are specified, these libs get linked dynamically
-ADD_COMPILER_FLAGS("-DCEGUILUA_STATIC" WIN32 NOT _external_shared_link)
-ADD_COMPILER_FLAGS("-DENET_DLL" WIN32 _external_shared_link)
-ADD_COMPILER_FLAGS("-DOGRE_GUIRENDERER_STATIC_LIB" WIN32 NOT _external_shared_link)
-ADD_COMPILER_FLAGS("-DOIS_STATIC_LIB" WIN32 NOT _external_shared_link)
-ADD_COMPILER_FLAGS("-DTOLUA_STATIC_BUILD" WIN32 NOT _external_shared_link)
############## Include Directories ##############
# Set the search paths for include files
INCLUDE_DIRECTORIES(
# External
- ${OGRE_INCLUDE_DIR}
- ${CEGUI_INCLUDE_DIR}
- #${ENET_INCLUDE_DIR}
${Boost_INCLUDE_DIRS}
${POCO_INCLUDE_DIR}
- ${OPENAL_INCLUDE_DIRS}
- ${ALUT_INCLUDE_DIR}
- ${VORBIS_INCLUDE_DIR}
- ${OGG_INCLUDE_DIR}
- ${LUA_INCLUDE_DIR}
- ${TCL_INCLUDE_PATH}
- ${DIRECTX_INCLUDE_DIR}
- ${ZLIB_INCLUDE_DIR}
# All includes in "externals" should be prefixed with the path
# relative to "external" to avoid conflicts
${CMAKE_CURRENT_SOURCE_DIR}/external
# Include directories needed even if only included by Orxonox
- ${CMAKE_CURRENT_SOURCE_DIR}/external/bullet
- ${CMAKE_CURRENT_SOURCE_DIR}/external/ois
+ #${CMAKE_CURRENT_SOURCE_DIR}/external/ois
# OrxonoxConfig.h
${CMAKE_CURRENT_BINARY_DIR}
)
-IF(CEGUILUA_USE_INTERNAL_LIBRARY)
- INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/external/ceguilua/ceguilua-${CEGUI_VERSION})
-ENDIF()
-
IF (DBGHELP_FOUND)
INCLUDE_DIRECTORIES(${DBGHELP_INCLUDE_DIR})
ENDIF()
-################### Tolua Bind ##################
-
-# Create directory because the tolua application doesn't work otherwise
-IF(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/toluabind/${CMAKE_CFG_INTDIR})
- FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/toluabind/${CMAKE_CFG_INTDIR})
-ENDIF()
-
-INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR}/toluabind/${CMAKE_CFG_INTDIR})
-
################ Sub Directories ################
ADD_SUBDIRECTORY(external)
ADD_SUBDIRECTORY(libraries)
ADD_SUBDIRECTORY(orxonox)
-ADD_SUBDIRECTORY(modules)
################## Executable ###################
@@ -140,8 +100,6 @@
Orxonox.cc
OUTPUT_NAME orxonox
)
-# Main executable should depend on all modules
-ADD_DEPENDENCIES(orxonox-main ${ORXONOX_MODULES})
# Get name to configure the run scripts
GET_TARGET_PROPERTY(_exec_loc orxonox-main LOCATION)
Modified: code/forks/sandbox_light/src/SpecialConfig.h.in
===================================================================
--- code/forks/sandbox_light/src/SpecialConfig.h.in 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/SpecialConfig.h.in 2011-02-17 04:47:22 UTC (rev 7908)
@@ -41,8 +41,6 @@
#include "OrxonoxConfig.h"
-#cmakedefine CEGUILUA_USE_INTERNAL_LIBRARY ///< Set whether we must suffix "ceguilua/" for the CEGUILua.h include
-
#cmakedefine DEPENDENCY_PACKAGE_ENABLE ///< Defined if a precompiled depdency package was used. We then copy all libraries too when installing.
#cmakedefine INSTALL_COPYABLE ///< Orxonox either gets installed to the system or just into a folder. The latter uses relative paths.
@@ -60,7 +58,6 @@
const char defaultRuntimePath[] = "@DEFAULT_RUNTIME_PATH@";
const char defaultLibraryPath[] = "@DEFAULT_LIBRARY_PATH@";
const char defaultArchivePath[] = "@DEFAULT_ARCHIVE_PATH@";
- const char defaultModulePath[] = "@DEFAULT_MODULE_PATH@";
const char defaultDocPath[] = "@DEFAULT_DOC_PATH@";
const char defaultDataPath[] = "@DEFAULT_DATA_PATH@";
const char defaultConfigPath[] = "@DEFAULT_CONFIG_PATH@";
@@ -69,18 +66,14 @@
#ifndef INSTALL_COPYABLE
// INSTALLATION PATHS
const char dataInstallDirectory[] = "@DATA_INSTALL_DIRECTORY@";
- const char moduleInstallDirectory[] = "@MODULE_INSTALL_DIRECTORY@";
#endif
// DEVELOPMENT RUN PATHS
const char dataDevDirectory[] = "@DATA_DIRECTORY@";
- const char externalDataDevDirectory[] = "@EXTERNAL_DATA_DIRECTORY@";
#ifdef CMAKE_CONFIGURATION_TYPES
- const char moduleDevDirectory[] = "@CMAKE_MODULE_OUTPUT_DIRECTORY@/" CMAKE_INTDIR;
const char configDevDirectory[] = "@CMAKE_CONFIG_OUTPUT_DIRECTORY@/" CMAKE_INTDIR;
const char logDevDirectory[] = "@CMAKE_LOG_OUTPUT_DIRECTORY@/" CMAKE_INTDIR;
#else
- const char moduleDevDirectory[] = "@CMAKE_MODULE_OUTPUT_DIRECTORY@";
const char configDevDirectory[] = "@CMAKE_CONFIG_OUTPUT_DIRECTORY@";
const char logDevDirectory[] = "@CMAKE_LOG_OUTPUT_DIRECTORY@";
#endif
@@ -89,25 +82,6 @@
const char dependencyLibraryDirectory[] = "@DEP_LIBRARY_DIR@";
#endif
- // Module extension
- const char moduleExtension[] = "@ORXONOX_MODULE_EXTENSION@";
-
- // OGRE PLUGINS
-#ifdef NDEBUG
- const char ogrePlugins[] = "@OGRE_PLUGINS_RELEASE@";
-# ifdef DEPENDENCY_PACKAGE_ENABLE
- const char ogrePluginsDirectory[] = ".";
-# else
- const char ogrePluginsDirectory[] = "@OGRE_PLUGINS_FOLDER_RELEASE@";
-# endif
-#else
- const char ogrePlugins[] = "@OGRE_PLUGINS_DEBUG@";
-# ifdef DEPENDENCY_PACKAGE_ENABLE
- const char ogrePluginsDirectory[] = ".";
-# else
- const char ogrePluginsDirectory[] = "@OGRE_PLUGINS_FOLDER_DEBUG@";
-# endif
-#endif
} }
#endif /* _SpecialConfig_H__ */
Modified: code/forks/sandbox_light/src/external/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/external/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/external/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -19,22 +19,5 @@
################ Sub Directories ################
-ADD_SUBDIRECTORY(tolua)
-
-# Include CEGUILua if not requested otherwise
-IF(CEGUILUA_USE_INTERNAL_LIBRARY)
- IF(NOT IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ceguilua/ceguilua-${CEGUI_VERSION})
- MESSAGE(FATAL_ERROR "CEGUILua version not found in src folder. Update list of supported versions in LibraryConfig.cmake!")
- ENDIF()
-
- ADD_SUBDIRECTORY(ceguilua)
- SET(CEGUILUA_LIBRARY ${CEGUILUA_LIBRARY} PARENT_SCOPE)
-ENDIF()
-
-ADD_SUBDIRECTORY(bullet)
-ADD_SUBDIRECTORY(cpptcl)
-ADD_SUBDIRECTORY(enet)
ADD_SUBDIRECTORY(loki)
-ADD_SUBDIRECTORY(ogreceguirenderer)
-ADD_SUBDIRECTORY(ois)
-ADD_SUBDIRECTORY(tinyxml)
+ADD_SUBDIRECTORY(ogremath)
Added: code/forks/sandbox_light/src/external/ogremath/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/CMakeLists.txt (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,49 @@
+ #
+ # ORXONOX - the hottest 3D action shooter ever to exist
+ # > www.orxonox.net <
+ #
+ # 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.
+ #
+
+SET_SOURCE_FILES(OGREMATH_SRC_FILES
+COMPILATION_BEGIN OgreCompilation.cc
+ OgreColourValue.cpp
+ OgreMath.cpp
+ OgreMatrix3.cpp
+ OgreMatrix4.cpp
+ OgrePlane.cpp
+ OgreQuaternion.cpp
+ OgreVector2.cpp
+ OgreVector3.cpp
+ OgreVector4.cpp
+COMPILATION_END
+)
+
+IF(WIN32)
+ ADD_SOURCE_FILES(OGREMATH_SRC_FILES WIN32/OgreTimer.cpp)
+ELSEIF(APPLE)
+ ADD_SOURCE_FILES(OGREMATH_SRC_FILES OSX/OgreTimer.cpp)
+ELSEIF(UNIX)
+ ADD_SOURCE_FILES(OGREMATH_SRC_FILES GLX/OgreTimer.cpp)
+ENDIF()
+
+ORXONOX_ADD_LIBRARY(ogremath_orxonox
+ ORXONOX_EXTERNAL
+ FIND_HEADER_FILES
+ DEFINE_SYMBOL
+ "OGRE_NONCLIENT_BUILD"
+ SOURCE_FILES
+ ${OGREMATH_SRC_FILES}
+)
Property changes on: code/forks/sandbox_light/src/external/ogremath/CMakeLists.txt
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimer.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimer.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimer.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,80 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "ogremath/OgreTimer.h"
+#include <sys/time.h>
+
+using namespace Ogre;
+
+//--------------------------------------------------------------------------------//
+Timer::Timer()
+{
+ reset();
+}
+
+//--------------------------------------------------------------------------------//
+Timer::~Timer()
+{
+}
+
+//--------------------------------------------------------------------------------//
+void Timer::reset()
+{
+ zeroClock = clock();
+ gettimeofday(&start, NULL);
+}
+
+//--------------------------------------------------------------------------------//
+unsigned long Timer::getMilliseconds()
+{
+ struct timeval now;
+ gettimeofday(&now, NULL);
+ return (now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000;
+}
+
+//--------------------------------------------------------------------------------//
+unsigned long Timer::getMicroseconds()
+{
+ struct timeval now;
+ gettimeofday(&now, NULL);
+ return (now.tv_sec-start.tv_sec)*1000000+(now.tv_usec-start.tv_usec);
+}
+
+//-- Common Across All Timers ----------------------------------------------------//
+unsigned long Timer::getMillisecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000.0)) ;
+}
+
+//-- Common Across All Timers ----------------------------------------------------//
+unsigned long Timer::getMicrosecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000000.0)) ;
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimer.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimerImp.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimerImp.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimerImp.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,79 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __GLXTimer_H__
+#define __GLXTimer_H__
+
+#include "ogremath/OgrePrerequisites.h"
+
+namespace Ogre
+{
+ /** Timer class */
+ class _OgreExport Timer
+ {
+ private:
+ struct timeval start;
+ clock_t zeroClock;
+ public:
+ Timer();
+ ~Timer();
+
+ /** Method for setting a specific option of the Timer. These options are usually
+ specific for a certain implementation of the Timer class, and may (and probably
+ will) not exist across different implementations. reset() must be called after
+ all setOption() calls.
+ @param
+ strKey The name of the option to set
+ @param
+ pValue A pointer to the value - the size should be calculated by the timer
+ based on the key
+ @return
+ On success, true is returned.
+ @par
+ On failure, false is returned.
+ */
+ bool setOption( const String& strKey, const void* pValue ) { return false; }
+
+ /** Resets timer */
+ void reset();
+
+ /** Returns milliseconds since initialisation or last reset */
+ unsigned long getMilliseconds();
+
+ /** Returns microseconds since initialisation or last reset */
+ unsigned long getMicroseconds();
+
+ /** Returns milliseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMillisecondsCPU();
+
+ /** Returns microseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMicrosecondsCPU();
+ };
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/GLX/OgreTimerImp.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimer.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimer.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimer.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,80 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "ogremath/OgreTimer.h"
+#include <sys/time.h>
+
+using namespace Ogre;
+
+//--------------------------------------------------------------------------------//
+Timer::Timer()
+{
+ reset();
+}
+
+//--------------------------------------------------------------------------------//
+Timer::~Timer()
+{
+}
+
+//--------------------------------------------------------------------------------//
+void Timer::reset()
+{
+ zeroClock = clock();
+ gettimeofday(&start, NULL);
+}
+
+//--------------------------------------------------------------------------------//
+unsigned long Timer::getMilliseconds()
+{
+ struct timeval now;
+ gettimeofday(&now, NULL);
+ return (now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000;
+}
+
+//--------------------------------------------------------------------------------//
+unsigned long Timer::getMicroseconds()
+{
+ struct timeval now;
+ gettimeofday(&now, NULL);
+ return (now.tv_sec-start.tv_sec)*1000000+(now.tv_usec-start.tv_usec);
+}
+
+//-- Common Across All Timers ----------------------------------------------------//
+unsigned long Timer::getMillisecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000.0)) ;
+}
+
+//-- Common Across All Timers ----------------------------------------------------//
+unsigned long Timer::getMicrosecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000000.0)) ;
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimer.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimerImp.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimerImp.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimerImp.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,79 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+#ifndef __OSXTimer_H__
+#define __OSXTimer_H__
+
+#include <ogremath/OgrePrerequisites.h>
+
+namespace Ogre
+{
+ /** Timer class */
+ class Timer
+ {
+ private:
+ struct timeval start;
+ clock_t zeroClock;
+ public:
+ Timer();
+ ~Timer();
+
+ /** Method for setting a specific option of the Timer. These options are usually
+ specific for a certain implementation of the Timer class, and may (and probably
+ will) not exist across different implementations. reset() must be called after
+ all setOption() calls.
+ @param
+ strKey The name of the option to set
+ @param
+ pValue A pointer to the value - the size should be calculated by the timer
+ based on the key
+ @return
+ On success, true is returned.
+ @par
+ On failure, false is returned.
+ */
+ bool setOption( const String& strKey, const void* pValue ) { return false; }
+
+ /** Resets timer */
+ void reset();
+
+ /** Returns milliseconds since initialisation or last reset */
+ unsigned long getMilliseconds();
+
+ /** Returns microseconds since initialisation or last reset */
+ unsigned long getMicroseconds();
+
+ /** Returns milliseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMillisecondsCPU();
+
+ /** Returns microseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMicrosecondsCPU();
+ };
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OSX/OgreTimerImp.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreBitwise.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreBitwise.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreBitwise.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,323 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef _Bitwise_H__
+#define _Bitwise_H__
+
+#include "OgrePrerequisites.h"
+
+namespace Ogre {
+
+ /** Class for manipulating bit patterns.
+ */
+ class Bitwise {
+ public:
+ /** Returns the most significant bit set in a value.
+ */
+ static FORCEINLINE unsigned int mostSignificantBitSet(unsigned int value)
+ {
+ unsigned int result = 0;
+ while (value != 0) {
+ ++result;
+ value >>= 1;
+ }
+ return result-1;
+ }
+ /** Returns the closest power-of-two number greater or equal to value.
+ @note 0 and 1 are powers of two, so
+ firstPO2From(0)==0 and firstPO2From(1)==1.
+ */
+ static FORCEINLINE uint32 firstPO2From(uint32 n)
+ {
+ --n;
+ n |= n >> 16;
+ n |= n >> 8;
+ n |= n >> 4;
+ n |= n >> 2;
+ n |= n >> 1;
+ ++n;
+ return n;
+ }
+ /** Determines whether the number is power-of-two or not.
+ @note 0 and 1 are tread as power of two.
+ */
+ template<typename T>
+ static FORCEINLINE bool isPO2(T n)
+ {
+ return (n & (n-1)) == 0;
+ }
+ /** Returns the number of bits a pattern must be shifted right by to
+ remove right-hand zeros.
+ */
+ template<typename T>
+ static FORCEINLINE unsigned int getBitShift(T mask)
+ {
+ if (mask == 0)
+ return 0;
+
+ unsigned int result = 0;
+ while ((mask & 1) == 0) {
+ ++result;
+ mask >>= 1;
+ }
+ return result;
+ }
+
+ /** Takes a value with a given src bit mask, and produces another
+ value with a desired bit mask.
+ @remarks
+ This routine is useful for colour conversion.
+ */
+ template<typename SrcT, typename DestT>
+ static inline DestT convertBitPattern(SrcT srcValue, SrcT srcBitMask, DestT destBitMask)
+ {
+ // Mask off irrelevant source value bits (if any)
+ srcValue = srcValue & srcBitMask;
+
+ // Shift source down to bottom of DWORD
+ const unsigned int srcBitShift = getBitShift(srcBitMask);
+ srcValue >>= srcBitShift;
+
+ // Get max value possible in source from srcMask
+ const SrcT srcMax = srcBitMask >> srcBitShift;
+
+ // Get max available in dest
+ const unsigned int destBitShift = getBitShift(destBitMask);
+ const DestT destMax = destBitMask >> destBitShift;
+
+ // Scale source value into destination, and shift back
+ DestT destValue = (srcValue * destMax) / srcMax;
+ return (destValue << destBitShift);
+ }
+
+ /**
+ * Convert N bit colour channel value to P bits. It fills P bits with the
+ * bit pattern repeated. (this is /((1<<n)-1) in fixed point)
+ */
+ static inline unsigned int fixedToFixed(uint32 value, unsigned int n, unsigned int p)
+ {
+ if(n > p)
+ {
+ // Less bits required than available; this is easy
+ value >>= n-p;
+ }
+ else if(n < p)
+ {
+ // More bits required than are there, do the fill
+ // Use old fashioned division, probably better than a loop
+ if(value == 0)
+ value = 0;
+ else if(value == (static_cast<unsigned int>(1)<<n)-1)
+ value = (1<<p)-1;
+ else value = value*(1<<p)/((1<<n)-1);
+ }
+ return value;
+ }
+
+ /**
+ * Convert floating point colour channel value between 0.0 and 1.0 (otherwise clamped)
+ * to integer of a certain number of bits. Works for any value of bits between 0 and 31.
+ */
+ static inline unsigned int floatToFixed(const float value, const unsigned int bits)
+ {
+ if(value <= 0.0f) return 0;
+ else if (value >= 1.0f) return (1<<bits)-1;
+ else return (unsigned int)(value * (1<<bits));
+ }
+
+ /**
+ * Fixed point to float
+ */
+ static inline float fixedToFloat(unsigned value, unsigned int bits)
+ {
+ return (float)value/(float)((1<<bits)-1);
+ }
+
+ /**
+ * Write a n*8 bits integer value to memory in native endian.
+ */
+ static inline void intWrite(void *dest, const int n, const unsigned int value)
+ {
+ switch(n) {
+ case 1:
+ ((uint8*)dest)[0] = (uint8)value;
+ break;
+ case 2:
+ ((uint16*)dest)[0] = (uint16)value;
+ break;
+ case 3:
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ ((uint8*)dest)[0] = (uint8)((value >> 16) & 0xFF);
+ ((uint8*)dest)[1] = (uint8)((value >> 8) & 0xFF);
+ ((uint8*)dest)[2] = (uint8)(value & 0xFF);
+#else
+ ((uint8*)dest)[2] = (uint8)((value >> 16) & 0xFF);
+ ((uint8*)dest)[1] = (uint8)((value >> 8) & 0xFF);
+ ((uint8*)dest)[0] = (uint8)(value & 0xFF);
+#endif
+ break;
+ case 4:
+ ((uint32*)dest)[0] = (uint32)value;
+ break;
+ }
+ }
+ /**
+ * Read a n*8 bits integer value to memory in native endian.
+ */
+ static inline unsigned int intRead(const void *src, int n) {
+ switch(n) {
+ case 1:
+ return ((uint8*)src)[0];
+ case 2:
+ return ((uint16*)src)[0];
+ case 3:
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ return ((uint32)((uint8*)src)[0]<<16)|
+ ((uint32)((uint8*)src)[1]<<8)|
+ ((uint32)((uint8*)src)[2]);
+#else
+ return ((uint32)((uint8*)src)[0])|
+ ((uint32)((uint8*)src)[1]<<8)|
+ ((uint32)((uint8*)src)[2]<<16);
+#endif
+ case 4:
+ return ((uint32*)src)[0];
+ }
+ return 0; // ?
+ }
+
+ /** Convert a float32 to a float16 (NV_half_float)
+ Courtesy of OpenEXR
+ */
+ static inline uint16 floatToHalf(float i)
+ {
+ union { float f; uint32 i; } v;
+ v.f = i;
+ return floatToHalfI(v.i);
+ }
+ /** Converts float in uint32 format to a a half in uint16 format
+ */
+ static inline uint16 floatToHalfI(uint32 i)
+ {
+ register int s = (i >> 16) & 0x00008000;
+ register int e = ((i >> 23) & 0x000000ff) - (127 - 15);
+ register int m = i & 0x007fffff;
+
+ if (e <= 0)
+ {
+ if (e < -10)
+ {
+ return 0;
+ }
+ m = (m | 0x00800000) >> (1 - e);
+
+ return s | (m >> 13);
+ }
+ else if (e == 0xff - (127 - 15))
+ {
+ if (m == 0) // Inf
+ {
+ return s | 0x7c00;
+ }
+ else // NAN
+ {
+ m >>= 13;
+ return s | 0x7c00 | m | (m == 0);
+ }
+ }
+ else
+ {
+ if (e > 30) // Overflow
+ {
+ return s | 0x7c00;
+ }
+
+ return s | (e << 10) | (m >> 13);
+ }
+ }
+
+ /**
+ * Convert a float16 (NV_half_float) to a float32
+ * Courtesy of OpenEXR
+ */
+ static inline float halfToFloat(uint16 y)
+ {
+ union { float f; uint32 i; } v;
+ v.i = halfToFloatI(y);
+ return v.f;
+ }
+ /** Converts a half in uint16 format to a float
+ in uint32 format
+ */
+ static inline uint32 halfToFloatI(uint16 y)
+ {
+ register int s = (y >> 15) & 0x00000001;
+ register int e = (y >> 10) & 0x0000001f;
+ register int m = y & 0x000003ff;
+
+ if (e == 0)
+ {
+ if (m == 0) // Plus or minus zero
+ {
+ return s << 31;
+ }
+ else // Denormalized number -- renormalize it
+ {
+ while (!(m & 0x00000400))
+ {
+ m <<= 1;
+ e -= 1;
+ }
+
+ e += 1;
+ m &= ~0x00000400;
+ }
+ }
+ else if (e == 31)
+ {
+ if (m == 0) // Inf
+ {
+ return (s << 31) | 0x7f800000;
+ }
+ else // NaN
+ {
+ return (s << 31) | 0x7f800000 | (m << 13);
+ }
+ }
+
+ e = e + (127 - 15);
+ m = m << 13;
+
+ return (s << 31) | (e << 23) | m;
+ }
+
+
+ };
+}
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreBitwise.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreColourValue.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreColourValue.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreColourValue.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,406 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgreColourValue.h"
+#include "OgreMath.h"
+
+namespace Ogre {
+
+ const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0);
+ const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0);
+ const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0);
+ const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0);
+ const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0);
+ const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0);
+
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ ABGR ColourValue::getAsABGR(void) const
+#else
+ RGBA ColourValue::getAsRGBA(void) const
+#endif
+ {
+ uint8 val8;
+ uint32 val32 = 0;
+
+ // Convert to 32bit pattern
+ // (RGBA = 8888)
+
+ // Red
+ val8 = static_cast<uint8>(r * 255);
+ val32 = val8 << 24;
+
+ // Green
+ val8 = static_cast<uint8>(g * 255);
+ val32 += val8 << 16;
+
+ // Blue
+ val8 = static_cast<uint8>(b * 255);
+ val32 += val8 << 8;
+
+ // Alpha
+ val8 = static_cast<uint8>(a * 255);
+ val32 += val8;
+
+ return val32;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ BGRA ColourValue::getAsBGRA(void) const
+#else
+ ARGB ColourValue::getAsARGB(void) const
+#endif
+ {
+ uint8 val8;
+ uint32 val32 = 0;
+
+ // Convert to 32bit pattern
+ // (ARGB = 8888)
+
+ // Alpha
+ val8 = static_cast<uint8>(a * 255);
+ val32 = val8 << 24;
+
+ // Red
+ val8 = static_cast<uint8>(r * 255);
+ val32 += val8 << 16;
+
+ // Green
+ val8 = static_cast<uint8>(g * 255);
+ val32 += val8 << 8;
+
+ // Blue
+ val8 = static_cast<uint8>(b * 255);
+ val32 += val8;
+
+
+ return val32;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ ARGB ColourValue::getAsARGB(void) const
+#else
+ BGRA ColourValue::getAsBGRA(void) const
+#endif
+ {
+ uint8 val8;
+ uint32 val32 = 0;
+
+ // Convert to 32bit pattern
+ // (ARGB = 8888)
+
+ // Blue
+ val8 = static_cast<uint8>(b * 255);
+ val32 = val8 << 24;
+
+ // Green
+ val8 = static_cast<uint8>(g * 255);
+ val32 += val8 << 16;
+
+ // Red
+ val8 = static_cast<uint8>(r * 255);
+ val32 += val8 << 8;
+
+ // Alpha
+ val8 = static_cast<uint8>(a * 255);
+ val32 += val8;
+
+
+ return val32;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ RGBA ColourValue::getAsRGBA(void) const
+#else
+ ABGR ColourValue::getAsABGR(void) const
+#endif
+ {
+ uint8 val8;
+ uint32 val32 = 0;
+
+ // Convert to 32bit pattern
+ // (ABRG = 8888)
+
+ // Alpha
+ val8 = static_cast<uint8>(a * 255);
+ val32 = val8 << 24;
+
+ // Blue
+ val8 = static_cast<uint8>(b * 255);
+ val32 += val8 << 16;
+
+ // Green
+ val8 = static_cast<uint8>(g * 255);
+ val32 += val8 << 8;
+
+ // Red
+ val8 = static_cast<uint8>(r * 255);
+ val32 += val8;
+
+
+ return val32;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ void ColourValue::setAsABGR(const ABGR val)
+#else
+ void ColourValue::setAsRGBA(const RGBA val)
+#endif
+ {
+ uint32 val32 = val;
+
+ // Convert from 32bit pattern
+ // (RGBA = 8888)
+
+ // Red
+ r = ((val32 >> 24) & 0xFF) / 255.0f;
+
+ // Green
+ g = ((val32 >> 16) & 0xFF) / 255.0f;
+
+ // Blue
+ b = ((val32 >> 8) & 0xFF) / 255.0f;
+
+ // Alpha
+ a = (val32 & 0xFF) / 255.0f;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ void ColourValue::setAsBGRA(const BGRA val)
+#else
+ void ColourValue::setAsARGB(const ARGB val)
+#endif
+ {
+ uint32 val32 = val;
+
+ // Convert from 32bit pattern
+ // (ARGB = 8888)
+
+ // Alpha
+ a = ((val32 >> 24) & 0xFF) / 255.0f;
+
+ // Red
+ r = ((val32 >> 16) & 0xFF) / 255.0f;
+
+ // Green
+ g = ((val32 >> 8) & 0xFF) / 255.0f;
+
+ // Blue
+ b = (val32 & 0xFF) / 255.0f;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ void ColourValue::setAsARGB(const ARGB val)
+#else
+ void ColourValue::setAsBGRA(const BGRA val)
+#endif
+ {
+ uint32 val32 = val;
+
+ // Convert from 32bit pattern
+ // (ARGB = 8888)
+
+ // Blue
+ b = ((val32 >> 24) & 0xFF) / 255.0f;
+
+ // Green
+ g = ((val32 >> 16) & 0xFF) / 255.0f;
+
+ // Red
+ r = ((val32 >> 8) & 0xFF) / 255.0f;
+
+ // Alpha
+ a = (val32 & 0xFF) / 255.0f;
+ }
+ //---------------------------------------------------------------------
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+ void ColourValue::setAsRGBA(const RGBA val)
+#else
+ void ColourValue::setAsABGR(const ABGR val)
+#endif
+ {
+ uint32 val32 = val;
+
+ // Convert from 32bit pattern
+ // (ABGR = 8888)
+
+ // Alpha
+ a = ((val32 >> 24) & 0xFF) / 255.0f;
+
+ // Blue
+ b = ((val32 >> 16) & 0xFF) / 255.0f;
+
+ // Green
+ g = ((val32 >> 8) & 0xFF) / 255.0f;
+
+ // Red
+ r = (val32 & 0xFF) / 255.0f;
+ }
+ //---------------------------------------------------------------------
+ bool ColourValue::operator==(const ColourValue& rhs) const
+ {
+ return (r == rhs.r &&
+ g == rhs.g &&
+ b == rhs.b &&
+ a == rhs.a);
+ }
+ //---------------------------------------------------------------------
+ bool ColourValue::operator!=(const ColourValue& rhs) const
+ {
+ return !(*this == rhs);
+ }
+ //---------------------------------------------------------------------
+ void ColourValue::setHSB(Real hue, Real saturation, Real brightness)
+ {
+ // wrap hue
+ if (hue > 1.0f)
+ {
+ hue -= (int)hue;
+ }
+ else if (hue < 0.0f)
+ {
+ hue += (int)hue + 1;
+ }
+ // clamp saturation / brightness
+ saturation = std::min(saturation, (Real)1.0);
+ saturation = std::max(saturation, (Real)0.0);
+ brightness = std::min(brightness, (Real)1.0);
+ brightness = std::max(brightness, (Real)0.0);
+
+ if (brightness == 0.0f)
+ {
+ // early exit, this has to be black
+ r = g = b = 0.0f;
+ return;
+ }
+
+ if (saturation == 0.0f)
+ {
+ // early exit, this has to be grey
+
+ r = g = b = brightness;
+ return;
+ }
+
+
+ Real hueDomain = hue * 6.0f;
+ if (hueDomain >= 6.0f)
+ {
+ // wrap around, and allow mathematical errors
+ hueDomain = 0.0f;
+ }
+ unsigned short domain = (unsigned short)hueDomain;
+ Real f1 = brightness * (1 - saturation);
+ Real f2 = brightness * (1 - saturation * (hueDomain - domain));
+ Real f3 = brightness * (1 - saturation * (1 - (hueDomain - domain)));
+
+ switch (domain)
+ {
+ case 0:
+ // red domain; green ascends
+ r = brightness;
+ g = f3;
+ b = f1;
+ break;
+ case 1:
+ // yellow domain; red descends
+ r = f2;
+ g = brightness;
+ b = f1;
+ break;
+ case 2:
+ // green domain; blue ascends
+ r = f1;
+ g = brightness;
+ b = f3;
+ break;
+ case 3:
+ // cyan domain; green descends
+ r = f1;
+ g = f2;
+ b = brightness;
+ break;
+ case 4:
+ // blue domain; red ascends
+ r = f3;
+ g = f1;
+ b = brightness;
+ break;
+ case 5:
+ // magenta domain; blue descends
+ r = brightness;
+ g = f1;
+ b = f2;
+ break;
+ }
+
+
+ }
+ //---------------------------------------------------------------------
+ void ColourValue::getHSB(Real* hue, Real* saturation, Real* brightness) const
+ {
+
+ Real vMin = std::min(r, std::min(g, b));
+ Real vMax = std::max(r, std::max(g, b));
+ Real delta = vMax - vMin;
+
+ *brightness = vMax;
+
+ if (Math::RealEqual(delta, 0.0f, 1e-6))
+ {
+ // grey
+ *hue = 0;
+ *saturation = 0;
+ }
+ else
+ {
+ // a colour
+ *saturation = delta / vMax;
+
+ Real deltaR = (((vMax - r) / 6.0f) + (delta / 2.0f)) / delta;
+ Real deltaG = (((vMax - g) / 6.0f) + (delta / 2.0f)) / delta;
+ Real deltaB = (((vMax - b) / 6.0f) + (delta / 2.0f)) / delta;
+
+ if (Math::RealEqual(r, vMax))
+ *hue = deltaB - deltaG;
+ else if (Math::RealEqual(g, vMax))
+ *hue = 0.3333333f + deltaR - deltaB;
+ else if (Math::RealEqual(b, vMax))
+ *hue = 0.6666667f + deltaG - deltaR;
+
+ if (*hue < 0.0f)
+ *hue += 1.0f;
+ if (*hue > 1.0f)
+ *hue -= 1.0f;
+ }
+
+
+ }
+
+}
+
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreColourValue.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreColourValue.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreColourValue.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreColourValue.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,330 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef _COLOURVALUE_H__
+#define _COLOURVALUE_H__
+
+#include "OgrePrerequisites.h"
+
+#include <cassert>
+#include <ostream>
+
+namespace Ogre {
+
+ typedef uint32 RGBA;
+ typedef uint32 ARGB;
+ typedef uint32 ABGR;
+ typedef uint32 BGRA;
+
+ /** Class representing colour.
+ @remarks
+ Colour is represented as 4 components, each of which is a
+ floating-point value from 0.0 to 1.0.
+ @par
+ The 3 'normal' colour components are red, green and blue, a higher
+ number indicating greater amounts of that component in the colour.
+ The forth component is the 'alpha' value, which represents
+ transparency. In this case, 0.0 is completely transparent and 1.0 is
+ fully opaque.
+ */
+ class _OgreExport ColourValue
+ {
+ public:
+ static const ColourValue ZERO;
+ static const ColourValue Black;
+ static const ColourValue White;
+ static const ColourValue Red;
+ static const ColourValue Green;
+ static const ColourValue Blue;
+
+ explicit ColourValue( float red = 1.0f,
+ float green = 1.0f,
+ float blue = 1.0f,
+ float alpha = 1.0f ) : r(red), g(green), b(blue), a(alpha)
+ { }
+
+ bool operator==(const ColourValue& rhs) const;
+ bool operator!=(const ColourValue& rhs) const;
+
+ float r,g,b,a;
+
+ /** Retrieves colour as RGBA.
+ */
+ RGBA getAsRGBA(void) const;
+
+ /** Retrieves colour as ARGB.
+ */
+ ARGB getAsARGB(void) const;
+
+ /** Retrieves colour as BGRA.
+ */
+ BGRA getAsBGRA(void) const;
+
+ /** Retrieves colours as ABGR */
+ ABGR getAsABGR(void) const;
+
+ /** Sets colour as RGBA.
+ */
+ void setAsRGBA(const RGBA val);
+
+ /** Sets colour as ARGB.
+ */
+ void setAsARGB(const ARGB val);
+
+ /** Sets colour as BGRA.
+ */
+ void setAsBGRA(const BGRA val);
+
+ /** Sets colour as ABGR.
+ */
+ void setAsABGR(const ABGR val);
+
+ /** Clamps colour value to the range [0, 1].
+ */
+ void saturate(void)
+ {
+ if (r < 0)
+ r = 0;
+ else if (r > 1)
+ r = 1;
+
+ if (g < 0)
+ g = 0;
+ else if (g > 1)
+ g = 1;
+
+ if (b < 0)
+ b = 0;
+ else if (b > 1)
+ b = 1;
+
+ if (a < 0)
+ a = 0;
+ else if (a > 1)
+ a = 1;
+ }
+
+ /** As saturate, except that this colour value is unaffected and
+ the saturated colour value is returned as a copy. */
+ ColourValue saturateCopy(void) const
+ {
+ ColourValue ret = *this;
+ ret.saturate();
+ return ret;
+ }
+
+ /// Array accessor operator
+ inline float operator [] ( const size_t i ) const
+ {
+ assert( i < 4 );
+
+ return *(&r+i);
+ }
+
+ /// Array accessor operator
+ inline float& operator [] ( const size_t i )
+ {
+ assert( i < 4 );
+
+ return *(&r+i);
+ }
+
+ /// Pointer accessor for direct copying
+ inline float* ptr()
+ {
+ return &r;
+ }
+ /// Pointer accessor for direct copying
+ inline const float* ptr() const
+ {
+ return &r;
+ }
+
+
+ // arithmetic operations
+ inline ColourValue operator + ( const ColourValue& rkVector ) const
+ {
+ ColourValue kSum;
+
+ kSum.r = r + rkVector.r;
+ kSum.g = g + rkVector.g;
+ kSum.b = b + rkVector.b;
+ kSum.a = a + rkVector.a;
+
+ return kSum;
+ }
+
+ inline ColourValue operator - ( const ColourValue& rkVector ) const
+ {
+ ColourValue kDiff;
+
+ kDiff.r = r - rkVector.r;
+ kDiff.g = g - rkVector.g;
+ kDiff.b = b - rkVector.b;
+ kDiff.a = a - rkVector.a;
+
+ return kDiff;
+ }
+
+ inline ColourValue operator * (const float fScalar ) const
+ {
+ ColourValue kProd;
+
+ kProd.r = fScalar*r;
+ kProd.g = fScalar*g;
+ kProd.b = fScalar*b;
+ kProd.a = fScalar*a;
+
+ return kProd;
+ }
+
+ inline ColourValue operator * ( const ColourValue& rhs) const
+ {
+ ColourValue kProd;
+
+ kProd.r = rhs.r * r;
+ kProd.g = rhs.g * g;
+ kProd.b = rhs.b * b;
+ kProd.a = rhs.a * a;
+
+ return kProd;
+ }
+
+ inline ColourValue operator / ( const ColourValue& rhs) const
+ {
+ ColourValue kProd;
+
+ kProd.r = rhs.r / r;
+ kProd.g = rhs.g / g;
+ kProd.b = rhs.b / b;
+ kProd.a = rhs.a / a;
+
+ return kProd;
+ }
+
+ inline ColourValue operator / (const float fScalar ) const
+ {
+ assert( fScalar != 0.0 );
+
+ ColourValue kDiv;
+
+ float fInv = 1.0 / fScalar;
+ kDiv.r = r * fInv;
+ kDiv.g = g * fInv;
+ kDiv.b = b * fInv;
+ kDiv.a = a * fInv;
+
+ return kDiv;
+ }
+
+ inline friend ColourValue operator * (const float fScalar, const ColourValue& rkVector )
+ {
+ ColourValue kProd;
+
+ kProd.r = fScalar * rkVector.r;
+ kProd.g = fScalar * rkVector.g;
+ kProd.b = fScalar * rkVector.b;
+ kProd.a = fScalar * rkVector.a;
+
+ return kProd;
+ }
+
+ // arithmetic updates
+ inline ColourValue& operator += ( const ColourValue& rkVector )
+ {
+ r += rkVector.r;
+ g += rkVector.g;
+ b += rkVector.b;
+ a += rkVector.a;
+
+ return *this;
+ }
+
+ inline ColourValue& operator -= ( const ColourValue& rkVector )
+ {
+ r -= rkVector.r;
+ g -= rkVector.g;
+ b -= rkVector.b;
+ a -= rkVector.a;
+
+ return *this;
+ }
+
+ inline ColourValue& operator *= (const float fScalar )
+ {
+ r *= fScalar;
+ g *= fScalar;
+ b *= fScalar;
+ a *= fScalar;
+ return *this;
+ }
+
+ inline ColourValue& operator /= (const float fScalar )
+ {
+ assert( fScalar != 0.0 );
+
+ float fInv = 1.0 / fScalar;
+
+ r *= fInv;
+ g *= fInv;
+ b *= fInv;
+ a *= fInv;
+
+ return *this;
+ }
+
+ /** Set a colour value from Hue, Saturation and Brightness.
+ @param hue Hue value, scaled to the [0,1] range as opposed to the 0-360
+ @param saturation Saturation level, [0,1]
+ @param brightness Brightness level, [0,1]
+ */
+ void setHSB(Real hue, Real saturation, Real brightness);
+
+ /** Convert the current colour to Hue, Saturation and Brightness values.
+ @param hue Output hue value, scaled to the [0,1] range as opposed to the 0-360
+ @param saturation Output saturation level, [0,1]
+ @param brightness Output brightness level, [0,1]
+ */
+ void getHSB(Real* hue, Real* saturation, Real* brightness) const;
+
+
+
+ /** Function for writing to a stream.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const ColourValue& c )
+ {
+ o << "ColourValue(" << c.r << ", " << c.g << ", " << c.b << ", " << c.a << ")";
+ return o;
+ }
+
+ };
+
+} // namespace
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreColourValue.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreConfig.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreConfig.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreConfig.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,162 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Config_H_
+#define __Config_H_
+
+// Read configuration options; some systems use an auto-generated config.h,
+// other use a manually generated config.h; in any case just define
+// HAVE_CONFIG_H to include the custom config.h file.
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/** If set to 1, profiling code will be included in the application. When you
+ are deploying your application you will probably want to set this to 0 */
+#define OGRE_PROFILING 0
+
+/** There are three modes for handling asserts in OGRE:
+0 - STANDARD - Standard asserts in debug builds, nothing in release builds
+1 - RELEASE_EXCEPTIONS - Standard asserts in debug builds, exceptions in release builds
+2 - EXCEPTIONS - Exceptions in debug builds, exceptions in release builds
+*/
+#define OGRE_ASSERT_MODE 0
+
+/** If set to >0, OGRE will always 'think' that the graphics card only has the
+ number of texture units specified. Very useful for testing multipass fallback.
+*/
+#define OGRE_PRETEND_TEXTURE_UNITS 0
+
+/** If set to 1, Real is typedef'ed to double. Otherwise, Real is typedef'ed
+ to float. Setting this allows you to perform mathematical operations in the
+ CPU (Quaternion, Vector3 etc) with more precision, but bear in mind that the
+ GPU still operates in single-precision mode.
+*/
+#ifndef OGRE_DOUBLE_PRECISION
+#define OGRE_DOUBLE_PRECISION 0
+#endif
+
+/** Define number of texture coordinate sets allowed per vertex.
+*/
+#define OGRE_MAX_TEXTURE_COORD_SETS 6
+
+/** Define max number of texture layers allowed per pass on any card.
+*/
+#define OGRE_MAX_TEXTURE_LAYERS 16
+
+/** Define max number of lights allowed per pass.
+*/
+#define OGRE_MAX_SIMULTANEOUS_LIGHTS 8
+
+/** Define max number of blending weights allowed per vertex.
+*/
+#define OGRE_MAX_BLEND_WEIGHTS 4
+
+/** Define this if you want to link OGRE as a static lib (preferably as a project file)
+*/
+//#define OGRE_STATIC_LIB
+
+
+// define the memory allocator configuration to use
+#define OGRE_MEMORY_ALLOCATOR_STD 1
+#define OGRE_MEMORY_ALLOCATOR_NED 2 // you need to have nedmalloc on your path for this
+#define OGRE_MEMORY_ALLOCATOR_USER 3
+
+#ifndef OGRE_MEMORY_ALLOCATOR
+# define OGRE_MEMORY_ALLOCATOR OGRE_MEMORY_ALLOCATOR_NED
+#endif
+
+// enable or disable the memory tracker, recording the memory allocations & tracking leaks
+// default is to disable since it's expensive, but you can enable if needed per build target
+
+#ifndef OGRE_MEMORY_TRACKER_DEBUG_MODE
+# define OGRE_MEMORY_TRACKER_DEBUG_MODE 0
+#endif
+
+#ifndef OGRE_MEMORY_TRACKER_RELEASE_MODE
+# define OGRE_MEMORY_TRACKER_RELEASE_MODE 0
+#endif
+/** Define max number of multiple render targets (MRTs) to render to at once.
+*/
+#define OGRE_MAX_MULTIPLE_RENDER_TARGETS 8
+
+/** Support for multithreading, there are 3 options
+
+OGRE_THREAD_SUPPORT = 0
+ No support for threading.
+OGRE_THREAD_SUPPORT = 1
+ Thread support for background loading, by both loading and constructing resources
+ in a background thread. Resource management and SharedPtr handling becomes
+ thread-safe, and resources may be completely loaded in the background.
+ The places where threading is available are clearly
+ marked, you should assume state is NOT thread safe unless otherwise
+ stated in relation to this flag.
+OGRE_THREAD_SUPPORT = 2
+ Thread support for background resource preparation. This means that resource
+ data can streamed into memory in the background, but the final resource
+ construction (including RenderSystem dependencies) is still done in the primary
+ thread. Has a lower synchronisation primitive overhead than full threading
+ while still allowing the major blocking aspects of resource management (I/O)
+ to be done in the background.
+*/
+#ifndef OGRE_THREAD_SUPPORT
+#define OGRE_THREAD_SUPPORT 0
+#endif
+#if OGRE_THREAD_SUPPORT != 0 && OGRE_THREAD_SUPPORT != 1 && OGRE_THREAD_SUPPORT != 2
+#define OGRE_THREAD_SUPPORT 1
+#endif
+
+/** Disables use of the FreeImage image library for loading images.
+WARNING: Use only when you want to provide your own image loading code via codecs.
+*/
+#ifndef OGRE_NO_FREEIMAGE
+#define OGRE_NO_FREEIMAGE 0
+#endif
+
+/** Disables use of the DevIL image library for loading images.
+By default DevIL is disabled in Eihort in favour of FreeImage, but you may re-enable
+it if you choose
+*/
+#ifndef OGRE_NO_DEVIL
+#define OGRE_NO_DEVIL 1
+#endif
+
+/** Disables use of the internal image codec for loading DDS files.
+WARNING: Use only when you want to provide your own image loading code via codecs.
+*/
+#ifndef OGRE_NO_DDS_CODEC
+#define OGRE_NO_DDS_CODEC 0
+#endif
+
+/** Enables the use of the new script compilers when Ogre compiles resource scripts.
+*/
+#ifndef OGRE_USE_NEW_COMPILERS
+#define OGRE_USE_NEW_COMPILERS 1
+#endif
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreConfig.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMath.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMath.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMath.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,449 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+#include "OgreMath.h"
+#include "asm_math.h"
+#include "OgreVector2.h"
+#include "OgreVector3.h"
+#include "OgreVector4.h"
+#include "OgreMatrix4.h"
+
+
+namespace Ogre
+{
+
+ const Real Math::POS_INFINITY = std::numeric_limits<Real>::infinity();
+ const Real Math::NEG_INFINITY = -std::numeric_limits<Real>::infinity();
+ const Real Math::PI = Real( 4.0 * atan( 1.0 ) );
+ const Real Math::TWO_PI = Real( 2.0 * PI );
+ const Real Math::HALF_PI = Real( 0.5 * PI );
+ const Real Math::fDeg2Rad = PI / Real(180.0);
+ const Real Math::fRad2Deg = Real(180.0) / PI;
+
+ int Math::mTrigTableSize;
+ Math::AngleUnit Math::msAngleUnit;
+
+ Real Math::mTrigTableFactor;
+ Real *Math::mSinTable = NULL;
+ Real *Math::mTanTable = NULL;
+
+ //-----------------------------------------------------------------------
+ Math::Math( unsigned int trigTableSize )
+ {
+ msAngleUnit = AU_DEGREE;
+
+ mTrigTableSize = trigTableSize;
+ mTrigTableFactor = mTrigTableSize / Math::TWO_PI;
+
+ mSinTable = static_cast<Real*>(malloc(mTrigTableSize * sizeof(Real)));
+ mTanTable = static_cast<Real*>(malloc(mTrigTableSize * sizeof(Real)));
+
+ buildTrigTables();
+ }
+
+ //-----------------------------------------------------------------------
+ Math::~Math()
+ {
+ free(mSinTable);
+ free(mTanTable);
+ }
+
+ //-----------------------------------------------------------------------
+ void Math::buildTrigTables(void)
+ {
+ // Build trig lookup tables
+ // Could get away with building only PI sized Sin table but simpler this
+ // way. Who cares, it'll ony use an extra 8k of memory anyway and I like
+ // simplicity.
+ Real angle;
+ for (int i = 0; i < mTrigTableSize; ++i)
+ {
+ angle = Math::TWO_PI * i / mTrigTableSize;
+ mSinTable[i] = sin(angle);
+ mTanTable[i] = tan(angle);
+ }
+ }
+ //-----------------------------------------------------------------------
+ Real Math::SinTable (Real fValue)
+ {
+ // Convert range to index values, wrap if required
+ int idx;
+ if (fValue >= 0)
+ {
+ idx = int(fValue * mTrigTableFactor) % mTrigTableSize;
+ }
+ else
+ {
+ idx = mTrigTableSize - (int(-fValue * mTrigTableFactor) % mTrigTableSize) - 1;
+ }
+
+ return mSinTable[idx];
+ }
+ //-----------------------------------------------------------------------
+ Real Math::TanTable (Real fValue)
+ {
+ // Convert range to index values, wrap if required
+ int idx = int(fValue *= mTrigTableFactor) % mTrigTableSize;
+ return mTanTable[idx];
+ }
+ //-----------------------------------------------------------------------
+ int Math::ISign (int iValue)
+ {
+ return ( iValue > 0 ? +1 : ( iValue < 0 ? -1 : 0 ) );
+ }
+ //-----------------------------------------------------------------------
+ Radian Math::ACos (Real fValue)
+ {
+ if ( -1.0 < fValue )
+ {
+ if ( fValue < 1.0 )
+ return Radian(acos(fValue));
+ else
+ return Radian(0.0);
+ }
+ else
+ {
+ return Radian(PI);
+ }
+ }
+ //-----------------------------------------------------------------------
+ Radian Math::ASin (Real fValue)
+ {
+ if ( -1.0 < fValue )
+ {
+ if ( fValue < 1.0 )
+ return Radian(asin(fValue));
+ else
+ return Radian(HALF_PI);
+ }
+ else
+ {
+ return Radian(-HALF_PI);
+ }
+ }
+ //-----------------------------------------------------------------------
+ Real Math::Sign (Real fValue)
+ {
+ if ( fValue > 0.0 )
+ return 1.0;
+
+ if ( fValue < 0.0 )
+ return -1.0;
+
+ return 0.0;
+ }
+ //-----------------------------------------------------------------------
+ Real Math::InvSqrt(Real fValue)
+ {
+ return Real(asm_rsq(fValue));
+ }
+ //-----------------------------------------------------------------------
+ Real Math::UnitRandom ()
+ {
+ return asm_rand() / asm_rand_max();
+ }
+
+ //-----------------------------------------------------------------------
+ Real Math::RangeRandom (Real fLow, Real fHigh)
+ {
+ return (fHigh-fLow)*UnitRandom() + fLow;
+ }
+
+ //-----------------------------------------------------------------------
+ Real Math::SymmetricRandom ()
+ {
+ return 2.0f * UnitRandom() - 1.0f;
+ }
+
+ //-----------------------------------------------------------------------
+ void Math::setAngleUnit(Math::AngleUnit unit)
+ {
+ msAngleUnit = unit;
+ }
+ //-----------------------------------------------------------------------
+ Math::AngleUnit Math::getAngleUnit(void)
+ {
+ return msAngleUnit;
+ }
+ //-----------------------------------------------------------------------
+ Real Math::AngleUnitsToRadians(Real angleunits)
+ {
+ if (msAngleUnit == AU_DEGREE)
+ return angleunits * fDeg2Rad;
+ else
+ return angleunits;
+ }
+
+ //-----------------------------------------------------------------------
+ Real Math::RadiansToAngleUnits(Real radians)
+ {
+ if (msAngleUnit == AU_DEGREE)
+ return radians * fRad2Deg;
+ else
+ return radians;
+ }
+
+ //-----------------------------------------------------------------------
+ Real Math::AngleUnitsToDegrees(Real angleunits)
+ {
+ if (msAngleUnit == AU_RADIAN)
+ return angleunits * fRad2Deg;
+ else
+ return angleunits;
+ }
+
+ //-----------------------------------------------------------------------
+ Real Math::DegreesToAngleUnits(Real degrees)
+ {
+ if (msAngleUnit == AU_RADIAN)
+ return degrees * fDeg2Rad;
+ else
+ return degrees;
+ }
+
+ //-----------------------------------------------------------------------
+ bool Math::pointInTri2D(const Vector2& p, const Vector2& a,
+ const Vector2& b, const Vector2& c)
+ {
+ // Winding must be consistent from all edges for point to be inside
+ Vector2 v1, v2;
+ Real dot[3];
+ bool zeroDot[3];
+
+ v1 = b - a;
+ v2 = p - a;
+
+ // Note we don't care about normalisation here since sign is all we need
+ // It means we don't have to worry about magnitude of cross products either
+ dot[0] = v1.crossProduct(v2);
+ zeroDot[0] = Math::RealEqual(dot[0], 0.0f, 1e-3);
+
+
+ v1 = c - b;
+ v2 = p - b;
+
+ dot[1] = v1.crossProduct(v2);
+ zeroDot[1] = Math::RealEqual(dot[1], 0.0f, 1e-3);
+
+ // Compare signs (ignore colinear / coincident points)
+ if(!zeroDot[0] && !zeroDot[1]
+ && Math::Sign(dot[0]) != Math::Sign(dot[1]))
+ {
+ return false;
+ }
+
+ v1 = a - c;
+ v2 = p - c;
+
+ dot[2] = v1.crossProduct(v2);
+ zeroDot[2] = Math::RealEqual(dot[2], 0.0f, 1e-3);
+ // Compare signs (ignore colinear / coincident points)
+ if((!zeroDot[0] && !zeroDot[2]
+ && Math::Sign(dot[0]) != Math::Sign(dot[2])) ||
+ (!zeroDot[1] && !zeroDot[2]
+ && Math::Sign(dot[1]) != Math::Sign(dot[2])))
+ {
+ return false;
+ }
+
+
+ return true;
+ }
+ //-----------------------------------------------------------------------
+ bool Math::pointInTri3D(const Vector3& p, const Vector3& a,
+ const Vector3& b, const Vector3& c, const Vector3& normal)
+ {
+ // Winding must be consistent from all edges for point to be inside
+ Vector3 v1, v2;
+ Real dot[3];
+ bool zeroDot[3];
+
+ v1 = b - a;
+ v2 = p - a;
+
+ // Note we don't care about normalisation here since sign is all we need
+ // It means we don't have to worry about magnitude of cross products either
+ dot[0] = v1.crossProduct(v2).dotProduct(normal);
+ zeroDot[0] = Math::RealEqual(dot[0], 0.0f, 1e-3);
+
+
+ v1 = c - b;
+ v2 = p - b;
+
+ dot[1] = v1.crossProduct(v2).dotProduct(normal);
+ zeroDot[1] = Math::RealEqual(dot[1], 0.0f, 1e-3);
+
+ // Compare signs (ignore colinear / coincident points)
+ if(!zeroDot[0] && !zeroDot[1]
+ && Math::Sign(dot[0]) != Math::Sign(dot[1]))
+ {
+ return false;
+ }
+
+ v1 = a - c;
+ v2 = p - c;
+
+ dot[2] = v1.crossProduct(v2).dotProduct(normal);
+ zeroDot[2] = Math::RealEqual(dot[2], 0.0f, 1e-3);
+ // Compare signs (ignore colinear / coincident points)
+ if((!zeroDot[0] && !zeroDot[2]
+ && Math::Sign(dot[0]) != Math::Sign(dot[2])) ||
+ (!zeroDot[1] && !zeroDot[2]
+ && Math::Sign(dot[1]) != Math::Sign(dot[2])))
+ {
+ return false;
+ }
+
+
+ return true;
+ }
+ //-----------------------------------------------------------------------
+ bool Math::RealEqual( Real a, Real b, Real tolerance )
+ {
+ if (fabs(b-a) <= tolerance)
+ return true;
+ else
+ return false;
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Math::calculateTangentSpaceVector(
+ const Vector3& position1, const Vector3& position2, const Vector3& position3,
+ Real u1, Real v1, Real u2, Real v2, Real u3, Real v3)
+ {
+ //side0 is the vector along one side of the triangle of vertices passed in,
+ //and side1 is the vector along another side. Taking the cross product of these returns the normal.
+ Vector3 side0 = position1 - position2;
+ Vector3 side1 = position3 - position1;
+ //Calculate face normal
+ Vector3 normal = side1.crossProduct(side0);
+ normal.normalise();
+ //Now we use a formula to calculate the tangent.
+ Real deltaV0 = v1 - v2;
+ Real deltaV1 = v3 - v1;
+ Vector3 tangent = deltaV1 * side0 - deltaV0 * side1;
+ tangent.normalise();
+ //Calculate binormal
+ Real deltaU0 = u1 - u2;
+ Real deltaU1 = u3 - u1;
+ Vector3 binormal = deltaU1 * side0 - deltaU0 * side1;
+ binormal.normalise();
+ //Now, we take the cross product of the tangents to get a vector which
+ //should point in the same direction as our normal calculated above.
+ //If it points in the opposite direction (the dot product between the normals is less than zero),
+ //then we need to reverse the s and t tangents.
+ //This is because the triangle has been mirrored when going from tangent space to object space.
+ //reverse tangents if necessary
+ Vector3 tangentCross = tangent.crossProduct(binormal);
+ if (tangentCross.dotProduct(normal) < 0.0f)
+ {
+ tangent = -tangent;
+ binormal = -binormal;
+ }
+
+ return tangent;
+
+ }
+ //-----------------------------------------------------------------------
+ Vector4 Math::calculateFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3)
+ {
+ Vector3 normal = calculateBasicFaceNormal(v1, v2, v3);
+ // Now set up the w (distance of tri from origin
+ return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1)));
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Math::calculateBasicFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3)
+ {
+ Vector3 normal = (v2 - v1).crossProduct(v3 - v1);
+ normal.normalise();
+ return normal;
+ }
+ //-----------------------------------------------------------------------
+ Vector4 Math::calculateFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3)
+ {
+ Vector3 normal = calculateBasicFaceNormalWithoutNormalize(v1, v2, v3);
+ // Now set up the w (distance of tri from origin)
+ return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1)));
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Math::calculateBasicFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3)
+ {
+ Vector3 normal = (v2 - v1).crossProduct(v3 - v1);
+ return normal;
+ }
+ //-----------------------------------------------------------------------
+ Real Math::gaussianDistribution(Real x, Real offset, Real scale)
+ {
+ Real nom = Math::Exp(
+ -Math::Sqr(x - offset) / (2 * Math::Sqr(scale)));
+ Real denom = scale * Math::Sqrt(2 * Math::PI);
+
+ return nom / denom;
+
+ }
+ //---------------------------------------------------------------------
+ Matrix4 Math::makeViewMatrix(const Vector3& position, const Quaternion& orientation,
+ const Matrix4* reflectMatrix)
+ {
+ Matrix4 viewMatrix;
+
+ // View matrix is:
+ //
+ // [ Lx Uy Dz Tx ]
+ // [ Lx Uy Dz Ty ]
+ // [ Lx Uy Dz Tz ]
+ // [ 0 0 0 1 ]
+ //
+ // Where T = -(Transposed(Rot) * Pos)
+
+ // This is most efficiently done using 3x3 Matrices
+ Matrix3 rot;
+ orientation.ToRotationMatrix(rot);
+
+ // Make the translation relative to new axes
+ Matrix3 rotT = rot.Transpose();
+ Vector3 trans = -rotT * position;
+
+ // Make final matrix
+ viewMatrix = Matrix4::IDENTITY;
+ viewMatrix = rotT; // fills upper 3x3
+ viewMatrix[0][3] = trans.x;
+ viewMatrix[1][3] = trans.y;
+ viewMatrix[2][3] = trans.z;
+
+ // Deal with reflections
+ if (reflectMatrix)
+ {
+ viewMatrix = viewMatrix * (*reflectMatrix);
+ }
+
+ return viewMatrix;
+
+ }
+
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMath.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMath.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMath.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMath.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,510 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Math_H__
+#define __Math_H__
+
+#include "OgrePrerequisites.h"
+
+#include <cassert>
+#include <cmath>
+#include <vector>
+#include <utility>
+#include <list>
+#include <limits>
+
+namespace Ogre
+{
+ /** Wrapper class which indicates a given angle value is in Radians.
+ @remarks
+ Radian values are interchangeable with Degree values, and conversions
+ will be done automatically between them.
+ */
+ class Radian
+ {
+ Real mRad;
+
+ public:
+ explicit Radian ( Real r=0 ) : mRad(r) {}
+ Radian ( const Degree& d );
+ Radian& operator = ( const Real& f ) { mRad = f; return *this; }
+ Radian& operator = ( const Radian& r ) { mRad = r.mRad; return *this; }
+ Radian& operator = ( const Degree& d );
+
+ Real valueDegrees() const; // see bottom of this file
+ Real valueRadians() const { return mRad; }
+ Real valueAngleUnits() const;
+
+ const Radian& operator + () const { return *this; }
+ Radian operator + ( const Radian& r ) const { return Radian ( mRad + r.mRad ); }
+ Radian operator + ( const Degree& d ) const;
+ Radian& operator += ( const Radian& r ) { mRad += r.mRad; return *this; }
+ Radian& operator += ( const Degree& d );
+ Radian operator - () const { return Radian(-mRad); }
+ Radian operator - ( const Radian& r ) const { return Radian ( mRad - r.mRad ); }
+ Radian operator - ( const Degree& d ) const;
+ Radian& operator -= ( const Radian& r ) { mRad -= r.mRad; return *this; }
+ Radian& operator -= ( const Degree& d );
+ Radian operator * ( Real f ) const { return Radian ( mRad * f ); }
+ Radian operator * ( const Radian& f ) const { return Radian ( mRad * f.mRad ); }
+ Radian& operator *= ( Real f ) { mRad *= f; return *this; }
+ Radian operator / ( Real f ) const { return Radian ( mRad / f ); }
+ Radian& operator /= ( Real f ) { mRad /= f; return *this; }
+
+ bool operator < ( const Radian& r ) const { return mRad < r.mRad; }
+ bool operator <= ( const Radian& r ) const { return mRad <= r.mRad; }
+ bool operator == ( const Radian& r ) const { return mRad == r.mRad; }
+ bool operator != ( const Radian& r ) const { return mRad != r.mRad; }
+ bool operator >= ( const Radian& r ) const { return mRad >= r.mRad; }
+ bool operator > ( const Radian& r ) const { return mRad > r.mRad; }
+ };
+
+ /** Wrapper class which indicates a given angle value is in Degrees.
+ @remarks
+ Degree values are interchangeable with Radian values, and conversions
+ will be done automatically between them.
+ */
+ class Degree
+ {
+ Real mDeg; // if you get an error here - make sure to define/typedef 'Real' first
+
+ public:
+ explicit Degree ( Real d=0 ) : mDeg(d) {}
+ Degree ( const Radian& r ) : mDeg(r.valueDegrees()) {}
+ Degree& operator = ( const Real& f ) { mDeg = f; return *this; }
+ Degree& operator = ( const Degree& d ) { mDeg = d.mDeg; return *this; }
+ Degree& operator = ( const Radian& r ) { mDeg = r.valueDegrees(); return *this; }
+
+ Real valueDegrees() const { return mDeg; }
+ Real valueRadians() const; // see bottom of this file
+ Real valueAngleUnits() const;
+
+ const Degree& operator + () const { return *this; }
+ Degree operator + ( const Degree& d ) const { return Degree ( mDeg + d.mDeg ); }
+ Degree operator + ( const Radian& r ) const { return Degree ( mDeg + r.valueDegrees() ); }
+ Degree& operator += ( const Degree& d ) { mDeg += d.mDeg; return *this; }
+ Degree& operator += ( const Radian& r ) { mDeg += r.valueDegrees(); return *this; }
+ Degree operator - () const { return Degree(-mDeg); }
+ Degree operator - ( const Degree& d ) const { return Degree ( mDeg - d.mDeg ); }
+ Degree operator - ( const Radian& r ) const { return Degree ( mDeg - r.valueDegrees() ); }
+ Degree& operator -= ( const Degree& d ) { mDeg -= d.mDeg; return *this; }
+ Degree& operator -= ( const Radian& r ) { mDeg -= r.valueDegrees(); return *this; }
+ Degree operator * ( Real f ) const { return Degree ( mDeg * f ); }
+ Degree operator * ( const Degree& f ) const { return Degree ( mDeg * f.mDeg ); }
+ Degree& operator *= ( Real f ) { mDeg *= f; return *this; }
+ Degree operator / ( Real f ) const { return Degree ( mDeg / f ); }
+ Degree& operator /= ( Real f ) { mDeg /= f; return *this; }
+
+ bool operator < ( const Degree& d ) const { return mDeg < d.mDeg; }
+ bool operator <= ( const Degree& d ) const { return mDeg <= d.mDeg; }
+ bool operator == ( const Degree& d ) const { return mDeg == d.mDeg; }
+ bool operator != ( const Degree& d ) const { return mDeg != d.mDeg; }
+ bool operator >= ( const Degree& d ) const { return mDeg >= d.mDeg; }
+ bool operator > ( const Degree& d ) const { return mDeg > d.mDeg; }
+ };
+
+ /** Wrapper class which identifies a value as the currently default angle
+ type, as defined by Math::setAngleUnit.
+ @remarks
+ Angle values will be automatically converted between radians and degrees,
+ as appropriate.
+ */
+ class Angle
+ {
+ Real mAngle;
+ public:
+ explicit Angle ( Real angle ) : mAngle(angle) {}
+ operator Radian() const;
+ operator Degree() const;
+ };
+
+ // these functions could not be defined within the class definition of class
+ // Radian because they required class Degree to be defined
+ inline Radian::Radian ( const Degree& d ) : mRad(d.valueRadians()) {
+ }
+ inline Radian& Radian::operator = ( const Degree& d ) {
+ mRad = d.valueRadians(); return *this;
+ }
+ inline Radian Radian::operator + ( const Degree& d ) const {
+ return Radian ( mRad + d.valueRadians() );
+ }
+ inline Radian& Radian::operator += ( const Degree& d ) {
+ mRad += d.valueRadians();
+ return *this;
+ }
+ inline Radian Radian::operator - ( const Degree& d ) const {
+ return Radian ( mRad - d.valueRadians() );
+ }
+ inline Radian& Radian::operator -= ( const Degree& d ) {
+ mRad -= d.valueRadians();
+ return *this;
+ }
+
+ /** Class to provide access to common mathematical functions.
+ @remarks
+ Most of the maths functions are aliased versions of the C runtime
+ library functions. They are aliased here to provide future
+ optimisation opportunities, either from faster RTLs or custom
+ math approximations.
+ @note
+ <br>This is based on MgcMath.h from
+ <a href="http://www.geometrictools.com/">Wild Magic</a>.
+ */
+ class _OgreExport Math
+ {
+ public:
+ /** The angular units used by the API. This functionality is now deprecated in favor
+ of discreet angular unit types ( see Degree and Radian above ). The only place
+ this functionality is actually still used is when parsing files. Search for
+ usage of the Angle class for those instances
+ */
+ enum AngleUnit
+ {
+ AU_DEGREE,
+ AU_RADIAN
+ };
+
+ protected:
+ // angle units used by the api
+ static AngleUnit msAngleUnit;
+
+ /// Size of the trig tables as determined by constructor.
+ static int mTrigTableSize;
+
+ /// Radian -> index factor value ( mTrigTableSize / 2 * PI )
+ static Real mTrigTableFactor;
+ static Real* mSinTable;
+ static Real* mTanTable;
+
+ /** Private function to build trig tables.
+ */
+ void buildTrigTables();
+
+ static Real SinTable (Real fValue);
+ static Real TanTable (Real fValue);
+ public:
+ /** Default constructor.
+ @param
+ trigTableSize Optional parameter to set the size of the
+ tables used to implement Sin, Cos, Tan
+ */
+ Math(unsigned int trigTableSize = 4096);
+
+ /** Default destructor.
+ */
+ ~Math();
+
+ static inline int IAbs (int iValue) { return ( iValue >= 0 ? iValue : -iValue ); }
+ static inline int ICeil (float fValue) { return int(ceil(fValue)); }
+ static inline int IFloor (float fValue) { return int(floor(fValue)); }
+ static int ISign (int iValue);
+
+ static inline Real Abs (Real fValue) { return Real(fabs(fValue)); }
+ static inline Degree Abs (const Degree& dValue) { return Degree(fabs(dValue.valueDegrees())); }
+ static inline Radian Abs (const Radian& rValue) { return Radian(fabs(rValue.valueRadians())); }
+ static Radian ACos (Real fValue);
+ static Radian ASin (Real fValue);
+ static inline Radian ATan (Real fValue) { return Radian(atan(fValue)); }
+ static inline Radian ATan2 (Real fY, Real fX) { return Radian(atan2(fY,fX)); }
+ static inline Real Ceil (Real fValue) { return Real(ceil(fValue)); }
+
+ /** Cosine function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Cos (const Radian& fValue, bool useTables = false) {
+ return (!useTables) ? Real(cos(fValue.valueRadians())) : SinTable(fValue.valueRadians() + HALF_PI);
+ }
+ /** Cosine function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Cos (Real fValue, bool useTables = false) {
+ return (!useTables) ? Real(cos(fValue)) : SinTable(fValue + HALF_PI);
+ }
+
+ static inline Real Exp (Real fValue) { return Real(exp(fValue)); }
+
+ static inline Real Floor (Real fValue) { return Real(floor(fValue)); }
+
+ static inline Real Log (Real fValue) { return Real(log(fValue)); }
+
+ static inline Real Pow (Real fBase, Real fExponent) { return Real(pow(fBase,fExponent)); }
+
+ static Real Sign (Real fValue);
+ static inline Radian Sign ( const Radian& rValue )
+ {
+ return Radian(Sign(rValue.valueRadians()));
+ }
+ static inline Degree Sign ( const Degree& dValue )
+ {
+ return Degree(Sign(dValue.valueDegrees()));
+ }
+
+ /** Sine function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Sin (const Radian& fValue, bool useTables = false) {
+ return (!useTables) ? Real(sin(fValue.valueRadians())) : SinTable(fValue.valueRadians());
+ }
+ /** Sine function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Sin (Real fValue, bool useTables = false) {
+ return (!useTables) ? Real(sin(fValue)) : SinTable(fValue);
+ }
+
+ static inline Real Sqr (Real fValue) { return fValue*fValue; }
+
+ static inline Real Sqrt (Real fValue) { return Real(sqrt(fValue)); }
+
+ static inline Radian Sqrt (const Radian& fValue) { return Radian(sqrt(fValue.valueRadians())); }
+
+ static inline Degree Sqrt (const Degree& fValue) { return Degree(sqrt(fValue.valueDegrees())); }
+
+ /** Inverse square root i.e. 1 / Sqrt(x), good for vector
+ normalisation.
+ */
+ static Real InvSqrt(Real fValue);
+
+ static Real UnitRandom (); // in [0,1]
+
+ static Real RangeRandom (Real fLow, Real fHigh); // in [fLow,fHigh]
+
+ static Real SymmetricRandom (); // in [-1,1]
+
+ /** Tangent function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Tan (const Radian& fValue, bool useTables = false) {
+ return (!useTables) ? Real(tan(fValue.valueRadians())) : TanTable(fValue.valueRadians());
+ }
+ /** Tangent function.
+ @param
+ fValue Angle in radians
+ @param
+ useTables If true, uses lookup tables rather than
+ calculation - faster but less accurate.
+ */
+ static inline Real Tan (Real fValue, bool useTables = false) {
+ return (!useTables) ? Real(tan(fValue)) : TanTable(fValue);
+ }
+
+ static inline Real DegreesToRadians(Real degrees) { return degrees * fDeg2Rad; }
+ static inline Real RadiansToDegrees(Real radians) { return radians * fRad2Deg; }
+
+ /** These functions used to set the assumed angle units (radians or degrees)
+ expected when using the Angle type.
+ @par
+ You can set this directly after creating a new Root, and also before/after resource creation,
+ depending on whether you want the change to affect resource files.
+ */
+ static void setAngleUnit(AngleUnit unit);
+ /** Get the unit being used for angles. */
+ static AngleUnit getAngleUnit(void);
+
+ /** Convert from the current AngleUnit to radians. */
+ static Real AngleUnitsToRadians(Real units);
+ /** Convert from radians to the current AngleUnit . */
+ static Real RadiansToAngleUnits(Real radians);
+ /** Convert from the current AngleUnit to degrees. */
+ static Real AngleUnitsToDegrees(Real units);
+ /** Convert from degrees to the current AngleUnit. */
+ static Real DegreesToAngleUnits(Real degrees);
+
+ /** Checks whether a given point is inside a triangle, in a
+ 2-dimensional (Cartesian) space.
+ @remarks
+ The vertices of the triangle must be given in either
+ trigonometrical (anticlockwise) or inverse trigonometrical
+ (clockwise) order.
+ @param
+ p The point.
+ @param
+ a The triangle's first vertex.
+ @param
+ b The triangle's second vertex.
+ @param
+ c The triangle's third vertex.
+ @returns
+ If the point resides in the triangle, <b>true</b> is
+ returned.
+ @par
+ If the point is outside the triangle, <b>false</b> is
+ returned.
+ */
+ static bool pointInTri2D(const Vector2& p, const Vector2& a,
+ const Vector2& b, const Vector2& c);
+
+ /** Checks whether a given 3D point is inside a triangle.
+ @remarks
+ The vertices of the triangle must be given in either
+ trigonometrical (anticlockwise) or inverse trigonometrical
+ (clockwise) order, and the point must be guaranteed to be in the
+ same plane as the triangle
+ @param
+ p The point.
+ @param
+ a The triangle's first vertex.
+ @param
+ b The triangle's second vertex.
+ @param
+ c The triangle's third vertex.
+ @param
+ normal The triangle plane's normal (passed in rather than calculated
+ on demand since the caller may already have it)
+ @returns
+ If the point resides in the triangle, <b>true</b> is
+ returned.
+ @par
+ If the point is outside the triangle, <b>false</b> is
+ returned.
+ */
+ static bool pointInTri3D(const Vector3& p, const Vector3& a,
+ const Vector3& b, const Vector3& c, const Vector3& normal);
+
+ /** Compare 2 reals, using tolerance for inaccuracies.
+ */
+ static bool RealEqual(Real a, Real b,
+ Real tolerance = std::numeric_limits<Real>::epsilon());
+
+ /** Calculates the tangent space vector for a given set of positions / texture coords. */
+ static Vector3 calculateTangentSpaceVector(
+ const Vector3& position1, const Vector3& position2, const Vector3& position3,
+ Real u1, Real v1, Real u2, Real v2, Real u3, Real v3);
+
+ /** Calculate a face normal, including the w component which is the offset from the origin. */
+ static Vector4 calculateFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3);
+ /** Calculate a face normal, no w-information. */
+ static Vector3 calculateBasicFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3);
+ /** Calculate a face normal without normalize, including the w component which is the offset from the origin. */
+ static Vector4 calculateFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3);
+ /** Calculate a face normal without normalize, no w-information. */
+ static Vector3 calculateBasicFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3);
+
+ /** Generates a value based on the Gaussian (normal) distribution function
+ with the given offset and scale parameters.
+ */
+ static Real gaussianDistribution(Real x, Real offset = 0.0f, Real scale = 1.0f);
+
+ /** Clamp a value within an inclusive range. */
+ template <typename T>
+ static T Clamp(T val, T minval, T maxval)
+ {
+ assert (minval < maxval && "Invalid clamp range");
+ return std::max(std::min(val, maxval), minval);
+ }
+
+ static Matrix4 makeViewMatrix(const Vector3& position, const Quaternion& orientation,
+ const Matrix4* reflectMatrix = 0);
+
+
+
+ static const Real POS_INFINITY;
+ static const Real NEG_INFINITY;
+ static const Real PI;
+ static const Real TWO_PI;
+ static const Real HALF_PI;
+ static const Real fDeg2Rad;
+ static const Real fRad2Deg;
+
+ };
+
+ // these functions must be defined down here, because they rely on the
+ // angle unit conversion functions in class Math:
+
+ inline Real Radian::valueDegrees() const
+ {
+ return Math::RadiansToDegrees ( mRad );
+ }
+
+ inline Real Radian::valueAngleUnits() const
+ {
+ return Math::RadiansToAngleUnits ( mRad );
+ }
+
+ inline Real Degree::valueRadians() const
+ {
+ return Math::DegreesToRadians ( mDeg );
+ }
+
+ inline Real Degree::valueAngleUnits() const
+ {
+ return Math::DegreesToAngleUnits ( mDeg );
+ }
+
+ inline Angle::operator Radian() const
+ {
+ return Radian(Math::AngleUnitsToRadians(mAngle));
+ }
+
+ inline Angle::operator Degree() const
+ {
+ return Degree(Math::AngleUnitsToDegrees(mAngle));
+ }
+
+ inline Radian operator * ( Real a, const Radian& b )
+ {
+ return Radian ( a * b.valueRadians() );
+ }
+
+ inline Radian operator / ( Real a, const Radian& b )
+ {
+ return Radian ( a / b.valueRadians() );
+ }
+
+ inline Degree operator * ( Real a, const Degree& b )
+ {
+ return Degree ( a * b.valueDegrees() );
+ }
+
+ inline Degree operator / ( Real a, const Degree& b )
+ {
+ return Degree ( a / b.valueDegrees() );
+ }
+
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMath.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,1511 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgreMatrix3.h"
+
+#include "OgreMath.h"
+
+// Adapted from Matrix math by Wild Magic http://www.geometrictools.com/
+
+namespace Ogre
+{
+ const Real Matrix3::EPSILON = 1e-06;
+ const Matrix3 Matrix3::ZERO(0,0,0,0,0,0,0,0,0);
+ const Matrix3 Matrix3::IDENTITY(1,0,0,0,1,0,0,0,1);
+ const Real Matrix3::ms_fSvdEpsilon = 1e-04;
+ const unsigned int Matrix3::ms_iSvdMaxIterations = 32;
+
+ //-----------------------------------------------------------------------
+ Vector3 Matrix3::GetColumn (size_t iCol) const
+ {
+ assert( 0 <= iCol && iCol < 3 );
+ return Vector3(m[0][iCol],m[1][iCol],
+ m[2][iCol]);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::SetColumn(size_t iCol, const Vector3& vec)
+ {
+ assert( 0 <= iCol && iCol < 3 );
+ m[0][iCol] = vec.x;
+ m[1][iCol] = vec.y;
+ m[2][iCol] = vec.z;
+
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromAxes(const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis)
+ {
+ SetColumn(0,xAxis);
+ SetColumn(1,yAxis);
+ SetColumn(2,zAxis);
+
+ }
+
+ //-----------------------------------------------------------------------
+ bool Matrix3::operator== (const Matrix3& rkMatrix) const
+ {
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ if ( m[iRow][iCol] != rkMatrix.m[iRow][iCol] )
+ return false;
+ }
+ }
+
+ return true;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::operator+ (const Matrix3& rkMatrix) const
+ {
+ Matrix3 kSum;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ kSum.m[iRow][iCol] = m[iRow][iCol] +
+ rkMatrix.m[iRow][iCol];
+ }
+ }
+ return kSum;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::operator- (const Matrix3& rkMatrix) const
+ {
+ Matrix3 kDiff;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ kDiff.m[iRow][iCol] = m[iRow][iCol] -
+ rkMatrix.m[iRow][iCol];
+ }
+ }
+ return kDiff;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::operator* (const Matrix3& rkMatrix) const
+ {
+ Matrix3 kProd;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ kProd.m[iRow][iCol] =
+ m[iRow][0]*rkMatrix.m[0][iCol] +
+ m[iRow][1]*rkMatrix.m[1][iCol] +
+ m[iRow][2]*rkMatrix.m[2][iCol];
+ }
+ }
+ return kProd;
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Matrix3::operator* (const Vector3& rkPoint) const
+ {
+ Vector3 kProd;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ kProd[iRow] =
+ m[iRow][0]*rkPoint[0] +
+ m[iRow][1]*rkPoint[1] +
+ m[iRow][2]*rkPoint[2];
+ }
+ return kProd;
+ }
+ //-----------------------------------------------------------------------
+ Vector3 operator* (const Vector3& rkPoint, const Matrix3& rkMatrix)
+ {
+ Vector3 kProd;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ kProd[iRow] =
+ rkPoint[0]*rkMatrix.m[0][iRow] +
+ rkPoint[1]*rkMatrix.m[1][iRow] +
+ rkPoint[2]*rkMatrix.m[2][iRow];
+ }
+ return kProd;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::operator- () const
+ {
+ Matrix3 kNeg;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ kNeg[iRow][iCol] = -m[iRow][iCol];
+ }
+ return kNeg;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::operator* (Real fScalar) const
+ {
+ Matrix3 kProd;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ kProd[iRow][iCol] = fScalar*m[iRow][iCol];
+ }
+ return kProd;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 operator* (Real fScalar, const Matrix3& rkMatrix)
+ {
+ Matrix3 kProd;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ kProd[iRow][iCol] = fScalar*rkMatrix.m[iRow][iCol];
+ }
+ return kProd;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::Transpose () const
+ {
+ Matrix3 kTranspose;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ kTranspose[iRow][iCol] = m[iCol][iRow];
+ }
+ return kTranspose;
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::Inverse (Matrix3& rkInverse, Real fTolerance) const
+ {
+ // Invert a 3x3 using cofactors. This is about 8 times faster than
+ // the Numerical Recipes code which uses Gaussian elimination.
+
+ rkInverse[0][0] = m[1][1]*m[2][2] -
+ m[1][2]*m[2][1];
+ rkInverse[0][1] = m[0][2]*m[2][1] -
+ m[0][1]*m[2][2];
+ rkInverse[0][2] = m[0][1]*m[1][2] -
+ m[0][2]*m[1][1];
+ rkInverse[1][0] = m[1][2]*m[2][0] -
+ m[1][0]*m[2][2];
+ rkInverse[1][1] = m[0][0]*m[2][2] -
+ m[0][2]*m[2][0];
+ rkInverse[1][2] = m[0][2]*m[1][0] -
+ m[0][0]*m[1][2];
+ rkInverse[2][0] = m[1][0]*m[2][1] -
+ m[1][1]*m[2][0];
+ rkInverse[2][1] = m[0][1]*m[2][0] -
+ m[0][0]*m[2][1];
+ rkInverse[2][2] = m[0][0]*m[1][1] -
+ m[0][1]*m[1][0];
+
+ Real fDet =
+ m[0][0]*rkInverse[0][0] +
+ m[0][1]*rkInverse[1][0]+
+ m[0][2]*rkInverse[2][0];
+
+ if ( Math::Abs(fDet) <= fTolerance )
+ return false;
+
+ Real fInvDet = 1.0/fDet;
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ rkInverse[iRow][iCol] *= fInvDet;
+ }
+
+ return true;
+ }
+ //-----------------------------------------------------------------------
+ Matrix3 Matrix3::Inverse (Real fTolerance) const
+ {
+ Matrix3 kInverse = Matrix3::ZERO;
+ Inverse(kInverse,fTolerance);
+ return kInverse;
+ }
+ //-----------------------------------------------------------------------
+ Real Matrix3::Determinant () const
+ {
+ Real fCofactor00 = m[1][1]*m[2][2] -
+ m[1][2]*m[2][1];
+ Real fCofactor10 = m[1][2]*m[2][0] -
+ m[1][0]*m[2][2];
+ Real fCofactor20 = m[1][0]*m[2][1] -
+ m[1][1]*m[2][0];
+
+ Real fDet =
+ m[0][0]*fCofactor00 +
+ m[0][1]*fCofactor10 +
+ m[0][2]*fCofactor20;
+
+ return fDet;
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::Bidiagonalize (Matrix3& kA, Matrix3& kL,
+ Matrix3& kR)
+ {
+ Real afV[3], afW[3];
+ Real fLength, fSign, fT1, fInvT1, fT2;
+ bool bIdentity;
+
+ // map first column to (*,0,0)
+ fLength = Math::Sqrt(kA[0][0]*kA[0][0] + kA[1][0]*kA[1][0] +
+ kA[2][0]*kA[2][0]);
+ if ( fLength > 0.0 )
+ {
+ fSign = (kA[0][0] > 0.0 ? 1.0 : -1.0);
+ fT1 = kA[0][0] + fSign*fLength;
+ fInvT1 = 1.0/fT1;
+ afV[1] = kA[1][0]*fInvT1;
+ afV[2] = kA[2][0]*fInvT1;
+
+ fT2 = -2.0/(1.0+afV[1]*afV[1]+afV[2]*afV[2]);
+ afW[0] = fT2*(kA[0][0]+kA[1][0]*afV[1]+kA[2][0]*afV[2]);
+ afW[1] = fT2*(kA[0][1]+kA[1][1]*afV[1]+kA[2][1]*afV[2]);
+ afW[2] = fT2*(kA[0][2]+kA[1][2]*afV[1]+kA[2][2]*afV[2]);
+ kA[0][0] += afW[0];
+ kA[0][1] += afW[1];
+ kA[0][2] += afW[2];
+ kA[1][1] += afV[1]*afW[1];
+ kA[1][2] += afV[1]*afW[2];
+ kA[2][1] += afV[2]*afW[1];
+ kA[2][2] += afV[2]*afW[2];
+
+ kL[0][0] = 1.0+fT2;
+ kL[0][1] = kL[1][0] = fT2*afV[1];
+ kL[0][2] = kL[2][0] = fT2*afV[2];
+ kL[1][1] = 1.0+fT2*afV[1]*afV[1];
+ kL[1][2] = kL[2][1] = fT2*afV[1]*afV[2];
+ kL[2][2] = 1.0+fT2*afV[2]*afV[2];
+ bIdentity = false;
+ }
+ else
+ {
+ kL = Matrix3::IDENTITY;
+ bIdentity = true;
+ }
+
+ // map first row to (*,*,0)
+ fLength = Math::Sqrt(kA[0][1]*kA[0][1]+kA[0][2]*kA[0][2]);
+ if ( fLength > 0.0 )
+ {
+ fSign = (kA[0][1] > 0.0 ? 1.0 : -1.0);
+ fT1 = kA[0][1] + fSign*fLength;
+ afV[2] = kA[0][2]/fT1;
+
+ fT2 = -2.0/(1.0+afV[2]*afV[2]);
+ afW[0] = fT2*(kA[0][1]+kA[0][2]*afV[2]);
+ afW[1] = fT2*(kA[1][1]+kA[1][2]*afV[2]);
+ afW[2] = fT2*(kA[2][1]+kA[2][2]*afV[2]);
+ kA[0][1] += afW[0];
+ kA[1][1] += afW[1];
+ kA[1][2] += afW[1]*afV[2];
+ kA[2][1] += afW[2];
+ kA[2][2] += afW[2]*afV[2];
+
+ kR[0][0] = 1.0;
+ kR[0][1] = kR[1][0] = 0.0;
+ kR[0][2] = kR[2][0] = 0.0;
+ kR[1][1] = 1.0+fT2;
+ kR[1][2] = kR[2][1] = fT2*afV[2];
+ kR[2][2] = 1.0+fT2*afV[2]*afV[2];
+ }
+ else
+ {
+ kR = Matrix3::IDENTITY;
+ }
+
+ // map second column to (*,*,0)
+ fLength = Math::Sqrt(kA[1][1]*kA[1][1]+kA[2][1]*kA[2][1]);
+ if ( fLength > 0.0 )
+ {
+ fSign = (kA[1][1] > 0.0 ? 1.0 : -1.0);
+ fT1 = kA[1][1] + fSign*fLength;
+ afV[2] = kA[2][1]/fT1;
+
+ fT2 = -2.0/(1.0+afV[2]*afV[2]);
+ afW[1] = fT2*(kA[1][1]+kA[2][1]*afV[2]);
+ afW[2] = fT2*(kA[1][2]+kA[2][2]*afV[2]);
+ kA[1][1] += afW[1];
+ kA[1][2] += afW[2];
+ kA[2][2] += afV[2]*afW[2];
+
+ Real fA = 1.0+fT2;
+ Real fB = fT2*afV[2];
+ Real fC = 1.0+fB*afV[2];
+
+ if ( bIdentity )
+ {
+ kL[0][0] = 1.0;
+ kL[0][1] = kL[1][0] = 0.0;
+ kL[0][2] = kL[2][0] = 0.0;
+ kL[1][1] = fA;
+ kL[1][2] = kL[2][1] = fB;
+ kL[2][2] = fC;
+ }
+ else
+ {
+ for (int iRow = 0; iRow < 3; iRow++)
+ {
+ Real fTmp0 = kL[iRow][1];
+ Real fTmp1 = kL[iRow][2];
+ kL[iRow][1] = fA*fTmp0+fB*fTmp1;
+ kL[iRow][2] = fB*fTmp0+fC*fTmp1;
+ }
+ }
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::GolubKahanStep (Matrix3& kA, Matrix3& kL,
+ Matrix3& kR)
+ {
+ Real fT11 = kA[0][1]*kA[0][1]+kA[1][1]*kA[1][1];
+ Real fT22 = kA[1][2]*kA[1][2]+kA[2][2]*kA[2][2];
+ Real fT12 = kA[1][1]*kA[1][2];
+ Real fTrace = fT11+fT22;
+ Real fDiff = fT11-fT22;
+ Real fDiscr = Math::Sqrt(fDiff*fDiff+4.0*fT12*fT12);
+ Real fRoot1 = 0.5*(fTrace+fDiscr);
+ Real fRoot2 = 0.5*(fTrace-fDiscr);
+
+ // adjust right
+ Real fY = kA[0][0] - (Math::Abs(fRoot1-fT22) <=
+ Math::Abs(fRoot2-fT22) ? fRoot1 : fRoot2);
+ Real fZ = kA[0][1];
+ Real fInvLength = Math::InvSqrt(fY*fY+fZ*fZ);
+ Real fSin = fZ*fInvLength;
+ Real fCos = -fY*fInvLength;
+
+ Real fTmp0 = kA[0][0];
+ Real fTmp1 = kA[0][1];
+ kA[0][0] = fCos*fTmp0-fSin*fTmp1;
+ kA[0][1] = fSin*fTmp0+fCos*fTmp1;
+ kA[1][0] = -fSin*kA[1][1];
+ kA[1][1] *= fCos;
+
+ size_t iRow;
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ fTmp0 = kR[0][iRow];
+ fTmp1 = kR[1][iRow];
+ kR[0][iRow] = fCos*fTmp0-fSin*fTmp1;
+ kR[1][iRow] = fSin*fTmp0+fCos*fTmp1;
+ }
+
+ // adjust left
+ fY = kA[0][0];
+ fZ = kA[1][0];
+ fInvLength = Math::InvSqrt(fY*fY+fZ*fZ);
+ fSin = fZ*fInvLength;
+ fCos = -fY*fInvLength;
+
+ kA[0][0] = fCos*kA[0][0]-fSin*kA[1][0];
+ fTmp0 = kA[0][1];
+ fTmp1 = kA[1][1];
+ kA[0][1] = fCos*fTmp0-fSin*fTmp1;
+ kA[1][1] = fSin*fTmp0+fCos*fTmp1;
+ kA[0][2] = -fSin*kA[1][2];
+ kA[1][2] *= fCos;
+
+ size_t iCol;
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ fTmp0 = kL[iCol][0];
+ fTmp1 = kL[iCol][1];
+ kL[iCol][0] = fCos*fTmp0-fSin*fTmp1;
+ kL[iCol][1] = fSin*fTmp0+fCos*fTmp1;
+ }
+
+ // adjust right
+ fY = kA[0][1];
+ fZ = kA[0][2];
+ fInvLength = Math::InvSqrt(fY*fY+fZ*fZ);
+ fSin = fZ*fInvLength;
+ fCos = -fY*fInvLength;
+
+ kA[0][1] = fCos*kA[0][1]-fSin*kA[0][2];
+ fTmp0 = kA[1][1];
+ fTmp1 = kA[1][2];
+ kA[1][1] = fCos*fTmp0-fSin*fTmp1;
+ kA[1][2] = fSin*fTmp0+fCos*fTmp1;
+ kA[2][1] = -fSin*kA[2][2];
+ kA[2][2] *= fCos;
+
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ fTmp0 = kR[1][iRow];
+ fTmp1 = kR[2][iRow];
+ kR[1][iRow] = fCos*fTmp0-fSin*fTmp1;
+ kR[2][iRow] = fSin*fTmp0+fCos*fTmp1;
+ }
+
+ // adjust left
+ fY = kA[1][1];
+ fZ = kA[2][1];
+ fInvLength = Math::InvSqrt(fY*fY+fZ*fZ);
+ fSin = fZ*fInvLength;
+ fCos = -fY*fInvLength;
+
+ kA[1][1] = fCos*kA[1][1]-fSin*kA[2][1];
+ fTmp0 = kA[1][2];
+ fTmp1 = kA[2][2];
+ kA[1][2] = fCos*fTmp0-fSin*fTmp1;
+ kA[2][2] = fSin*fTmp0+fCos*fTmp1;
+
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ fTmp0 = kL[iCol][1];
+ fTmp1 = kL[iCol][2];
+ kL[iCol][1] = fCos*fTmp0-fSin*fTmp1;
+ kL[iCol][2] = fSin*fTmp0+fCos*fTmp1;
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::SingularValueDecomposition (Matrix3& kL, Vector3& kS,
+ Matrix3& kR) const
+ {
+ // temas: currently unused
+ //const int iMax = 16;
+ size_t iRow, iCol;
+
+ Matrix3 kA = *this;
+ Bidiagonalize(kA,kL,kR);
+
+ for (unsigned int i = 0; i < ms_iSvdMaxIterations; i++)
+ {
+ Real fTmp, fTmp0, fTmp1;
+ Real fSin0, fCos0, fTan0;
+ Real fSin1, fCos1, fTan1;
+
+ bool bTest1 = (Math::Abs(kA[0][1]) <=
+ ms_fSvdEpsilon*(Math::Abs(kA[0][0])+Math::Abs(kA[1][1])));
+ bool bTest2 = (Math::Abs(kA[1][2]) <=
+ ms_fSvdEpsilon*(Math::Abs(kA[1][1])+Math::Abs(kA[2][2])));
+ if ( bTest1 )
+ {
+ if ( bTest2 )
+ {
+ kS[0] = kA[0][0];
+ kS[1] = kA[1][1];
+ kS[2] = kA[2][2];
+ break;
+ }
+ else
+ {
+ // 2x2 closed form factorization
+ fTmp = (kA[1][1]*kA[1][1] - kA[2][2]*kA[2][2] +
+ kA[1][2]*kA[1][2])/(kA[1][2]*kA[2][2]);
+ fTan0 = 0.5*(fTmp+Math::Sqrt(fTmp*fTmp + 4.0));
+ fCos0 = Math::InvSqrt(1.0+fTan0*fTan0);
+ fSin0 = fTan0*fCos0;
+
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ fTmp0 = kL[iCol][1];
+ fTmp1 = kL[iCol][2];
+ kL[iCol][1] = fCos0*fTmp0-fSin0*fTmp1;
+ kL[iCol][2] = fSin0*fTmp0+fCos0*fTmp1;
+ }
+
+ fTan1 = (kA[1][2]-kA[2][2]*fTan0)/kA[1][1];
+ fCos1 = Math::InvSqrt(1.0+fTan1*fTan1);
+ fSin1 = -fTan1*fCos1;
+
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ fTmp0 = kR[1][iRow];
+ fTmp1 = kR[2][iRow];
+ kR[1][iRow] = fCos1*fTmp0-fSin1*fTmp1;
+ kR[2][iRow] = fSin1*fTmp0+fCos1*fTmp1;
+ }
+
+ kS[0] = kA[0][0];
+ kS[1] = fCos0*fCos1*kA[1][1] -
+ fSin1*(fCos0*kA[1][2]-fSin0*kA[2][2]);
+ kS[2] = fSin0*fSin1*kA[1][1] +
+ fCos1*(fSin0*kA[1][2]+fCos0*kA[2][2]);
+ break;
+ }
+ }
+ else
+ {
+ if ( bTest2 )
+ {
+ // 2x2 closed form factorization
+ fTmp = (kA[0][0]*kA[0][0] + kA[1][1]*kA[1][1] -
+ kA[0][1]*kA[0][1])/(kA[0][1]*kA[1][1]);
+ fTan0 = 0.5*(-fTmp+Math::Sqrt(fTmp*fTmp + 4.0));
+ fCos0 = Math::InvSqrt(1.0+fTan0*fTan0);
+ fSin0 = fTan0*fCos0;
+
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ fTmp0 = kL[iCol][0];
+ fTmp1 = kL[iCol][1];
+ kL[iCol][0] = fCos0*fTmp0-fSin0*fTmp1;
+ kL[iCol][1] = fSin0*fTmp0+fCos0*fTmp1;
+ }
+
+ fTan1 = (kA[0][1]-kA[1][1]*fTan0)/kA[0][0];
+ fCos1 = Math::InvSqrt(1.0+fTan1*fTan1);
+ fSin1 = -fTan1*fCos1;
+
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ fTmp0 = kR[0][iRow];
+ fTmp1 = kR[1][iRow];
+ kR[0][iRow] = fCos1*fTmp0-fSin1*fTmp1;
+ kR[1][iRow] = fSin1*fTmp0+fCos1*fTmp1;
+ }
+
+ kS[0] = fCos0*fCos1*kA[0][0] -
+ fSin1*(fCos0*kA[0][1]-fSin0*kA[1][1]);
+ kS[1] = fSin0*fSin1*kA[0][0] +
+ fCos1*(fSin0*kA[0][1]+fCos0*kA[1][1]);
+ kS[2] = kA[2][2];
+ break;
+ }
+ else
+ {
+ GolubKahanStep(kA,kL,kR);
+ }
+ }
+ }
+
+ // positize diagonal
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ if ( kS[iRow] < 0.0 )
+ {
+ kS[iRow] = -kS[iRow];
+ for (iCol = 0; iCol < 3; iCol++)
+ kR[iRow][iCol] = -kR[iRow][iCol];
+ }
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::SingularValueComposition (const Matrix3& kL,
+ const Vector3& kS, const Matrix3& kR)
+ {
+ size_t iRow, iCol;
+ Matrix3 kTmp;
+
+ // product S*R
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ for (iCol = 0; iCol < 3; iCol++)
+ kTmp[iRow][iCol] = kS[iRow]*kR[iRow][iCol];
+ }
+
+ // product L*S*R
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ m[iRow][iCol] = 0.0;
+ for (int iMid = 0; iMid < 3; iMid++)
+ m[iRow][iCol] += kL[iRow][iMid]*kTmp[iMid][iCol];
+ }
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::Orthonormalize ()
+ {
+ // Algorithm uses Gram-Schmidt orthogonalization. If 'this' matrix is
+ // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2],
+ //
+ // q0 = m0/|m0|
+ // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0|
+ // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1|
+ //
+ // where |V| indicates length of vector V and A*B indicates dot
+ // product of vectors A and B.
+
+ // compute q0
+ Real fInvLength = Math::InvSqrt(m[0][0]*m[0][0]
+ + m[1][0]*m[1][0] +
+ m[2][0]*m[2][0]);
+
+ m[0][0] *= fInvLength;
+ m[1][0] *= fInvLength;
+ m[2][0] *= fInvLength;
+
+ // compute q1
+ Real fDot0 =
+ m[0][0]*m[0][1] +
+ m[1][0]*m[1][1] +
+ m[2][0]*m[2][1];
+
+ m[0][1] -= fDot0*m[0][0];
+ m[1][1] -= fDot0*m[1][0];
+ m[2][1] -= fDot0*m[2][0];
+
+ fInvLength = Math::InvSqrt(m[0][1]*m[0][1] +
+ m[1][1]*m[1][1] +
+ m[2][1]*m[2][1]);
+
+ m[0][1] *= fInvLength;
+ m[1][1] *= fInvLength;
+ m[2][1] *= fInvLength;
+
+ // compute q2
+ Real fDot1 =
+ m[0][1]*m[0][2] +
+ m[1][1]*m[1][2] +
+ m[2][1]*m[2][2];
+
+ fDot0 =
+ m[0][0]*m[0][2] +
+ m[1][0]*m[1][2] +
+ m[2][0]*m[2][2];
+
+ m[0][2] -= fDot0*m[0][0] + fDot1*m[0][1];
+ m[1][2] -= fDot0*m[1][0] + fDot1*m[1][1];
+ m[2][2] -= fDot0*m[2][0] + fDot1*m[2][1];
+
+ fInvLength = Math::InvSqrt(m[0][2]*m[0][2] +
+ m[1][2]*m[1][2] +
+ m[2][2]*m[2][2]);
+
+ m[0][2] *= fInvLength;
+ m[1][2] *= fInvLength;
+ m[2][2] *= fInvLength;
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::QDUDecomposition (Matrix3& kQ,
+ Vector3& kD, Vector3& kU) const
+ {
+ // Factor M = QR = QDU where Q is orthogonal, D is diagonal,
+ // and U is upper triangular with ones on its diagonal. Algorithm uses
+ // Gram-Schmidt orthogonalization (the QR algorithm).
+ //
+ // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then
+ //
+ // q0 = m0/|m0|
+ // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0|
+ // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1|
+ //
+ // where |V| indicates length of vector V and A*B indicates dot
+ // product of vectors A and B. The matrix R has entries
+ //
+ // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2
+ // r10 = 0 r11 = q1*m1 r12 = q1*m2
+ // r20 = 0 r21 = 0 r22 = q2*m2
+ //
+ // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00,
+ // u02 = r02/r00, and u12 = r12/r11.
+
+ // Q = rotation
+ // D = scaling
+ // U = shear
+
+ // D stores the three diagonal entries r00, r11, r22
+ // U stores the entries U[0] = u01, U[1] = u02, U[2] = u12
+
+ // build orthogonal matrix Q
+ Real fInvLength = Math::InvSqrt(m[0][0]*m[0][0]
+ + m[1][0]*m[1][0] +
+ m[2][0]*m[2][0]);
+ kQ[0][0] = m[0][0]*fInvLength;
+ kQ[1][0] = m[1][0]*fInvLength;
+ kQ[2][0] = m[2][0]*fInvLength;
+
+ Real fDot = kQ[0][0]*m[0][1] + kQ[1][0]*m[1][1] +
+ kQ[2][0]*m[2][1];
+ kQ[0][1] = m[0][1]-fDot*kQ[0][0];
+ kQ[1][1] = m[1][1]-fDot*kQ[1][0];
+ kQ[2][1] = m[2][1]-fDot*kQ[2][0];
+ fInvLength = Math::InvSqrt(kQ[0][1]*kQ[0][1] + kQ[1][1]*kQ[1][1] +
+ kQ[2][1]*kQ[2][1]);
+ kQ[0][1] *= fInvLength;
+ kQ[1][1] *= fInvLength;
+ kQ[2][1] *= fInvLength;
+
+ fDot = kQ[0][0]*m[0][2] + kQ[1][0]*m[1][2] +
+ kQ[2][0]*m[2][2];
+ kQ[0][2] = m[0][2]-fDot*kQ[0][0];
+ kQ[1][2] = m[1][2]-fDot*kQ[1][0];
+ kQ[2][2] = m[2][2]-fDot*kQ[2][0];
+ fDot = kQ[0][1]*m[0][2] + kQ[1][1]*m[1][2] +
+ kQ[2][1]*m[2][2];
+ kQ[0][2] -= fDot*kQ[0][1];
+ kQ[1][2] -= fDot*kQ[1][1];
+ kQ[2][2] -= fDot*kQ[2][1];
+ fInvLength = Math::InvSqrt(kQ[0][2]*kQ[0][2] + kQ[1][2]*kQ[1][2] +
+ kQ[2][2]*kQ[2][2]);
+ kQ[0][2] *= fInvLength;
+ kQ[1][2] *= fInvLength;
+ kQ[2][2] *= fInvLength;
+
+ // guarantee that orthogonal matrix has determinant 1 (no reflections)
+ Real fDet = kQ[0][0]*kQ[1][1]*kQ[2][2] + kQ[0][1]*kQ[1][2]*kQ[2][0] +
+ kQ[0][2]*kQ[1][0]*kQ[2][1] - kQ[0][2]*kQ[1][1]*kQ[2][0] -
+ kQ[0][1]*kQ[1][0]*kQ[2][2] - kQ[0][0]*kQ[1][2]*kQ[2][1];
+
+ if ( fDet < 0.0 )
+ {
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ kQ[iRow][iCol] = -kQ[iRow][iCol];
+ }
+
+ // build "right" matrix R
+ Matrix3 kR;
+ kR[0][0] = kQ[0][0]*m[0][0] + kQ[1][0]*m[1][0] +
+ kQ[2][0]*m[2][0];
+ kR[0][1] = kQ[0][0]*m[0][1] + kQ[1][0]*m[1][1] +
+ kQ[2][0]*m[2][1];
+ kR[1][1] = kQ[0][1]*m[0][1] + kQ[1][1]*m[1][1] +
+ kQ[2][1]*m[2][1];
+ kR[0][2] = kQ[0][0]*m[0][2] + kQ[1][0]*m[1][2] +
+ kQ[2][0]*m[2][2];
+ kR[1][2] = kQ[0][1]*m[0][2] + kQ[1][1]*m[1][2] +
+ kQ[2][1]*m[2][2];
+ kR[2][2] = kQ[0][2]*m[0][2] + kQ[1][2]*m[1][2] +
+ kQ[2][2]*m[2][2];
+
+ // the scaling component
+ kD[0] = kR[0][0];
+ kD[1] = kR[1][1];
+ kD[2] = kR[2][2];
+
+ // the shear component
+ Real fInvD0 = 1.0/kD[0];
+ kU[0] = kR[0][1]*fInvD0;
+ kU[1] = kR[0][2]*fInvD0;
+ kU[2] = kR[1][2]/kD[1];
+ }
+ //-----------------------------------------------------------------------
+ Real Matrix3::MaxCubicRoot (Real afCoeff[3])
+ {
+ // Spectral norm is for A^T*A, so characteristic polynomial
+ // P(x) = c[0]+c[1]*x+c[2]*x^2+x^3 has three positive real roots.
+ // This yields the assertions c[0] < 0 and c[2]*c[2] >= 3*c[1].
+
+ // quick out for uniform scale (triple root)
+ const Real fOneThird = 1.0/3.0;
+ const Real fEpsilon = 1e-06;
+ Real fDiscr = afCoeff[2]*afCoeff[2] - 3.0*afCoeff[1];
+ if ( fDiscr <= fEpsilon )
+ return -fOneThird*afCoeff[2];
+
+ // Compute an upper bound on roots of P(x). This assumes that A^T*A
+ // has been scaled by its largest entry.
+ Real fX = 1.0;
+ Real fPoly = afCoeff[0]+fX*(afCoeff[1]+fX*(afCoeff[2]+fX));
+ if ( fPoly < 0.0 )
+ {
+ // uses a matrix norm to find an upper bound on maximum root
+ fX = Math::Abs(afCoeff[0]);
+ Real fTmp = 1.0+Math::Abs(afCoeff[1]);
+ if ( fTmp > fX )
+ fX = fTmp;
+ fTmp = 1.0+Math::Abs(afCoeff[2]);
+ if ( fTmp > fX )
+ fX = fTmp;
+ }
+
+ // Newton's method to find root
+ Real fTwoC2 = 2.0*afCoeff[2];
+ for (int i = 0; i < 16; i++)
+ {
+ fPoly = afCoeff[0]+fX*(afCoeff[1]+fX*(afCoeff[2]+fX));
+ if ( Math::Abs(fPoly) <= fEpsilon )
+ return fX;
+
+ Real fDeriv = afCoeff[1]+fX*(fTwoC2+3.0*fX);
+ fX -= fPoly/fDeriv;
+ }
+
+ return fX;
+ }
+ //-----------------------------------------------------------------------
+ Real Matrix3::SpectralNorm () const
+ {
+ Matrix3 kP;
+ size_t iRow, iCol;
+ Real fPmax = 0.0;
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ for (iCol = 0; iCol < 3; iCol++)
+ {
+ kP[iRow][iCol] = 0.0;
+ for (int iMid = 0; iMid < 3; iMid++)
+ {
+ kP[iRow][iCol] +=
+ m[iMid][iRow]*m[iMid][iCol];
+ }
+ if ( kP[iRow][iCol] > fPmax )
+ fPmax = kP[iRow][iCol];
+ }
+ }
+
+ Real fInvPmax = 1.0/fPmax;
+ for (iRow = 0; iRow < 3; iRow++)
+ {
+ for (iCol = 0; iCol < 3; iCol++)
+ kP[iRow][iCol] *= fInvPmax;
+ }
+
+ Real afCoeff[3];
+ afCoeff[0] = -(kP[0][0]*(kP[1][1]*kP[2][2]-kP[1][2]*kP[2][1]) +
+ kP[0][1]*(kP[2][0]*kP[1][2]-kP[1][0]*kP[2][2]) +
+ kP[0][2]*(kP[1][0]*kP[2][1]-kP[2][0]*kP[1][1]));
+ afCoeff[1] = kP[0][0]*kP[1][1]-kP[0][1]*kP[1][0] +
+ kP[0][0]*kP[2][2]-kP[0][2]*kP[2][0] +
+ kP[1][1]*kP[2][2]-kP[1][2]*kP[2][1];
+ afCoeff[2] = -(kP[0][0]+kP[1][1]+kP[2][2]);
+
+ Real fRoot = MaxCubicRoot(afCoeff);
+ Real fNorm = Math::Sqrt(fPmax*fRoot);
+ return fNorm;
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::ToAxisAngle (Vector3& rkAxis, Radian& rfRadians) const
+ {
+ // Let (x,y,z) be the unit-length axis and let A be an angle of rotation.
+ // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where
+ // I is the identity and
+ //
+ // +- -+
+ // P = | 0 -z +y |
+ // | +z 0 -x |
+ // | -y +x 0 |
+ // +- -+
+ //
+ // If A > 0, R represents a counterclockwise rotation about the axis in
+ // the sense of looking from the tip of the axis vector towards the
+ // origin. Some algebra will show that
+ //
+ // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P
+ //
+ // In the event that A = pi, R-R^t = 0 which prevents us from extracting
+ // the axis through P. Instead note that R = I+2*P^2 when A = pi, so
+ // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and
+ // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi,
+ // it does not matter which sign you choose on the square roots.
+
+ Real fTrace = m[0][0] + m[1][1] + m[2][2];
+ Real fCos = 0.5*(fTrace-1.0);
+ rfRadians = Math::ACos(fCos); // in [0,PI]
+
+ if ( rfRadians > Radian(0.0) )
+ {
+ if ( rfRadians < Radian(Math::PI) )
+ {
+ rkAxis.x = m[2][1]-m[1][2];
+ rkAxis.y = m[0][2]-m[2][0];
+ rkAxis.z = m[1][0]-m[0][1];
+ rkAxis.normalise();
+ }
+ else
+ {
+ // angle is PI
+ float fHalfInverse;
+ if ( m[0][0] >= m[1][1] )
+ {
+ // r00 >= r11
+ if ( m[0][0] >= m[2][2] )
+ {
+ // r00 is maximum diagonal term
+ rkAxis.x = 0.5*Math::Sqrt(m[0][0] -
+ m[1][1] - m[2][2] + 1.0);
+ fHalfInverse = 0.5/rkAxis.x;
+ rkAxis.y = fHalfInverse*m[0][1];
+ rkAxis.z = fHalfInverse*m[0][2];
+ }
+ else
+ {
+ // r22 is maximum diagonal term
+ rkAxis.z = 0.5*Math::Sqrt(m[2][2] -
+ m[0][0] - m[1][1] + 1.0);
+ fHalfInverse = 0.5/rkAxis.z;
+ rkAxis.x = fHalfInverse*m[0][2];
+ rkAxis.y = fHalfInverse*m[1][2];
+ }
+ }
+ else
+ {
+ // r11 > r00
+ if ( m[1][1] >= m[2][2] )
+ {
+ // r11 is maximum diagonal term
+ rkAxis.y = 0.5*Math::Sqrt(m[1][1] -
+ m[0][0] - m[2][2] + 1.0);
+ fHalfInverse = 0.5/rkAxis.y;
+ rkAxis.x = fHalfInverse*m[0][1];
+ rkAxis.z = fHalfInverse*m[1][2];
+ }
+ else
+ {
+ // r22 is maximum diagonal term
+ rkAxis.z = 0.5*Math::Sqrt(m[2][2] -
+ m[0][0] - m[1][1] + 1.0);
+ fHalfInverse = 0.5/rkAxis.z;
+ rkAxis.x = fHalfInverse*m[0][2];
+ rkAxis.y = fHalfInverse*m[1][2];
+ }
+ }
+ }
+ }
+ else
+ {
+ // The angle is 0 and the matrix is the identity. Any axis will
+ // work, so just use the x-axis.
+ rkAxis.x = 1.0;
+ rkAxis.y = 0.0;
+ rkAxis.z = 0.0;
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromAxisAngle (const Vector3& rkAxis, const Radian& fRadians)
+ {
+ Real fCos = Math::Cos(fRadians);
+ Real fSin = Math::Sin(fRadians);
+ Real fOneMinusCos = 1.0-fCos;
+ Real fX2 = rkAxis.x*rkAxis.x;
+ Real fY2 = rkAxis.y*rkAxis.y;
+ Real fZ2 = rkAxis.z*rkAxis.z;
+ Real fXYM = rkAxis.x*rkAxis.y*fOneMinusCos;
+ Real fXZM = rkAxis.x*rkAxis.z*fOneMinusCos;
+ Real fYZM = rkAxis.y*rkAxis.z*fOneMinusCos;
+ Real fXSin = rkAxis.x*fSin;
+ Real fYSin = rkAxis.y*fSin;
+ Real fZSin = rkAxis.z*fSin;
+
+ m[0][0] = fX2*fOneMinusCos+fCos;
+ m[0][1] = fXYM-fZSin;
+ m[0][2] = fXZM+fYSin;
+ m[1][0] = fXYM+fZSin;
+ m[1][1] = fY2*fOneMinusCos+fCos;
+ m[1][2] = fYZM-fXSin;
+ m[2][0] = fXZM-fYSin;
+ m[2][1] = fYZM+fXSin;
+ m[2][2] = fZ2*fOneMinusCos+fCos;
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesXYZ (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz -cy*sz sy
+ // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
+ // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
+
+ rfPAngle = Radian(Math::ASin(m[0][2]));
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(-m[1][2],m[2][2]);
+ rfRAngle = Math::ATan2(-m[0][1],m[0][0]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(m[1][0],m[1][1]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(m[1][0],m[1][1]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesXZY (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz -sz cz*sy
+ // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz
+ // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz
+
+ rfPAngle = Math::ASin(-m[0][1]);
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(m[2][1],m[1][1]);
+ rfRAngle = Math::ATan2(m[0][2],m[0][0]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(-m[2][0],m[2][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(-m[2][0],m[2][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesYXZ (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy
+ // cx*sz cx*cz -sx
+ // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy
+
+ rfPAngle = Math::ASin(-m[1][2]);
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(m[0][2],m[2][2]);
+ rfRAngle = Math::ATan2(m[1][0],m[1][1]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(-m[0][1],m[0][0]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(-m[0][1],m[0][0]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesYZX (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz
+ // sz cx*cz -cz*sx
+ // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz
+
+ rfPAngle = Math::ASin(m[1][0]);
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(-m[2][0],m[0][0]);
+ rfRAngle = Math::ATan2(-m[1][2],m[1][1]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(m[2][1],m[2][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(m[2][1],m[2][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesZXY (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz
+ // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz
+ // -cx*sy sx cx*cy
+
+ rfPAngle = Math::ASin(m[2][1]);
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(-m[0][1],m[1][1]);
+ rfRAngle = Math::ATan2(-m[2][0],m[2][2]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(m[0][2],m[0][0]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(m[0][2],m[0][0]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::ToEulerAnglesZYX (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const
+ {
+ // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz
+ // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz
+ // -sy cy*sx cx*cy
+
+ rfPAngle = Math::ASin(-m[2][0]);
+ if ( rfPAngle < Radian(Math::HALF_PI) )
+ {
+ if ( rfPAngle > Radian(-Math::HALF_PI) )
+ {
+ rfYAngle = Math::ATan2(m[1][0],m[0][0]);
+ rfRAngle = Math::ATan2(m[2][1],m[2][2]);
+ return true;
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRmY = Math::ATan2(-m[0][1],m[0][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = rfRAngle - fRmY;
+ return false;
+ }
+ }
+ else
+ {
+ // WARNING. Not a unique solution.
+ Radian fRpY = Math::ATan2(-m[0][1],m[0][2]);
+ rfRAngle = Radian(0.0); // any angle works
+ rfYAngle = fRpY - rfRAngle;
+ return false;
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesXYZ (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ *this = kXMat*(kYMat*kZMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesXZY (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ *this = kXMat*(kZMat*kYMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesYXZ (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ *this = kYMat*(kXMat*kZMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesYZX (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ *this = kYMat*(kZMat*kXMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesZXY (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ *this = kZMat*(kXMat*kYMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::FromEulerAnglesZYX (const Radian& fYAngle, const Radian& fPAngle,
+ const Radian& fRAngle)
+ {
+ Real fCos, fSin;
+
+ fCos = Math::Cos(fYAngle);
+ fSin = Math::Sin(fYAngle);
+ Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0);
+
+ fCos = Math::Cos(fPAngle);
+ fSin = Math::Sin(fPAngle);
+ Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos);
+
+ fCos = Math::Cos(fRAngle);
+ fSin = Math::Sin(fRAngle);
+ Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos);
+
+ *this = kZMat*(kYMat*kXMat);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::Tridiagonal (Real afDiag[3], Real afSubDiag[3])
+ {
+ // Householder reduction T = Q^t M Q
+ // Input:
+ // mat, symmetric 3x3 matrix M
+ // Output:
+ // mat, orthogonal matrix Q
+ // diag, diagonal entries of T
+ // subd, subdiagonal entries of T (T is symmetric)
+
+ Real fA = m[0][0];
+ Real fB = m[0][1];
+ Real fC = m[0][2];
+ Real fD = m[1][1];
+ Real fE = m[1][2];
+ Real fF = m[2][2];
+
+ afDiag[0] = fA;
+ afSubDiag[2] = 0.0;
+ if ( Math::Abs(fC) >= EPSILON )
+ {
+ Real fLength = Math::Sqrt(fB*fB+fC*fC);
+ Real fInvLength = 1.0/fLength;
+ fB *= fInvLength;
+ fC *= fInvLength;
+ Real fQ = 2.0*fB*fE+fC*(fF-fD);
+ afDiag[1] = fD+fC*fQ;
+ afDiag[2] = fF-fC*fQ;
+ afSubDiag[0] = fLength;
+ afSubDiag[1] = fE-fB*fQ;
+ m[0][0] = 1.0;
+ m[0][1] = 0.0;
+ m[0][2] = 0.0;
+ m[1][0] = 0.0;
+ m[1][1] = fB;
+ m[1][2] = fC;
+ m[2][0] = 0.0;
+ m[2][1] = fC;
+ m[2][2] = -fB;
+ }
+ else
+ {
+ afDiag[1] = fD;
+ afDiag[2] = fF;
+ afSubDiag[0] = fB;
+ afSubDiag[1] = fE;
+ m[0][0] = 1.0;
+ m[0][1] = 0.0;
+ m[0][2] = 0.0;
+ m[1][0] = 0.0;
+ m[1][1] = 1.0;
+ m[1][2] = 0.0;
+ m[2][0] = 0.0;
+ m[2][1] = 0.0;
+ m[2][2] = 1.0;
+ }
+ }
+ //-----------------------------------------------------------------------
+ bool Matrix3::QLAlgorithm (Real afDiag[3], Real afSubDiag[3])
+ {
+ // QL iteration with implicit shifting to reduce matrix from tridiagonal
+ // to diagonal
+
+ for (int i0 = 0; i0 < 3; i0++)
+ {
+ const unsigned int iMaxIter = 32;
+ unsigned int iIter;
+ for (iIter = 0; iIter < iMaxIter; iIter++)
+ {
+ int i1;
+ for (i1 = i0; i1 <= 1; i1++)
+ {
+ Real fSum = Math::Abs(afDiag[i1]) +
+ Math::Abs(afDiag[i1+1]);
+ if ( Math::Abs(afSubDiag[i1]) + fSum == fSum )
+ break;
+ }
+ if ( i1 == i0 )
+ break;
+
+ Real fTmp0 = (afDiag[i0+1]-afDiag[i0])/(2.0*afSubDiag[i0]);
+ Real fTmp1 = Math::Sqrt(fTmp0*fTmp0+1.0);
+ if ( fTmp0 < 0.0 )
+ fTmp0 = afDiag[i1]-afDiag[i0]+afSubDiag[i0]/(fTmp0-fTmp1);
+ else
+ fTmp0 = afDiag[i1]-afDiag[i0]+afSubDiag[i0]/(fTmp0+fTmp1);
+ Real fSin = 1.0;
+ Real fCos = 1.0;
+ Real fTmp2 = 0.0;
+ for (int i2 = i1-1; i2 >= i0; i2--)
+ {
+ Real fTmp3 = fSin*afSubDiag[i2];
+ Real fTmp4 = fCos*afSubDiag[i2];
+ if ( Math::Abs(fTmp3) >= Math::Abs(fTmp0) )
+ {
+ fCos = fTmp0/fTmp3;
+ fTmp1 = Math::Sqrt(fCos*fCos+1.0);
+ afSubDiag[i2+1] = fTmp3*fTmp1;
+ fSin = 1.0/fTmp1;
+ fCos *= fSin;
+ }
+ else
+ {
+ fSin = fTmp3/fTmp0;
+ fTmp1 = Math::Sqrt(fSin*fSin+1.0);
+ afSubDiag[i2+1] = fTmp0*fTmp1;
+ fCos = 1.0/fTmp1;
+ fSin *= fCos;
+ }
+ fTmp0 = afDiag[i2+1]-fTmp2;
+ fTmp1 = (afDiag[i2]-fTmp0)*fSin+2.0*fTmp4*fCos;
+ fTmp2 = fSin*fTmp1;
+ afDiag[i2+1] = fTmp0+fTmp2;
+ fTmp0 = fCos*fTmp1-fTmp4;
+
+ for (int iRow = 0; iRow < 3; iRow++)
+ {
+ fTmp3 = m[iRow][i2+1];
+ m[iRow][i2+1] = fSin*m[iRow][i2] +
+ fCos*fTmp3;
+ m[iRow][i2] = fCos*m[iRow][i2] -
+ fSin*fTmp3;
+ }
+ }
+ afDiag[i0] -= fTmp2;
+ afSubDiag[i0] = fTmp0;
+ afSubDiag[i1] = 0.0;
+ }
+
+ if ( iIter == iMaxIter )
+ {
+ // should not get here under normal circumstances
+ return false;
+ }
+ }
+
+ return true;
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::EigenSolveSymmetric (Real afEigenvalue[3],
+ Vector3 akEigenvector[3]) const
+ {
+ Matrix3 kMatrix = *this;
+ Real afSubDiag[3];
+ kMatrix.Tridiagonal(afEigenvalue,afSubDiag);
+ kMatrix.QLAlgorithm(afEigenvalue,afSubDiag);
+
+ for (size_t i = 0; i < 3; i++)
+ {
+ akEigenvector[i][0] = kMatrix[0][i];
+ akEigenvector[i][1] = kMatrix[1][i];
+ akEigenvector[i][2] = kMatrix[2][i];
+ }
+
+ // make eigenvectors form a right--handed system
+ Vector3 kCross = akEigenvector[1].crossProduct(akEigenvector[2]);
+ Real fDet = akEigenvector[0].dotProduct(kCross);
+ if ( fDet < 0.0 )
+ {
+ akEigenvector[2][0] = - akEigenvector[2][0];
+ akEigenvector[2][1] = - akEigenvector[2][1];
+ akEigenvector[2][2] = - akEigenvector[2][2];
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Matrix3::TensorProduct (const Vector3& rkU, const Vector3& rkV,
+ Matrix3& rkProduct)
+ {
+ for (size_t iRow = 0; iRow < 3; iRow++)
+ {
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ rkProduct[iRow][iCol] = rkU[iRow]*rkV[iCol];
+ }
+ }
+ //-----------------------------------------------------------------------
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,241 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Matrix3_H__
+#define __Matrix3_H__
+
+#include "OgrePrerequisites.h"
+
+#include "OgreVector3.h"
+#include <ostream>
+
+// NB All code adapted from Wild Magic 0.2 Matrix math (free source code)
+// http://www.geometrictools.com/
+
+// NOTE. The (x,y,z) coordinate system is assumed to be right-handed.
+// Coordinate axis rotation matrices are of the form
+// RX = 1 0 0
+// 0 cos(t) -sin(t)
+// 0 sin(t) cos(t)
+// where t > 0 indicates a counterclockwise rotation in the yz-plane
+// RY = cos(t) 0 sin(t)
+// 0 1 0
+// -sin(t) 0 cos(t)
+// where t > 0 indicates a counterclockwise rotation in the zx-plane
+// RZ = cos(t) -sin(t) 0
+// sin(t) cos(t) 0
+// 0 0 1
+// where t > 0 indicates a counterclockwise rotation in the xy-plane.
+
+namespace Ogre
+{
+ /** A 3x3 matrix which can represent rotations around axes.
+ @note
+ <b>All the code is adapted from the Wild Magic 0.2 Matrix
+ library (http://www.geometrictools.com/).</b>
+ @par
+ The coordinate system is assumed to be <b>right-handed</b>.
+ */
+ class _OgreExport Matrix3
+ {
+ public:
+ /** Default constructor.
+ @note
+ It does <b>NOT</b> initialize the matrix for efficiency.
+ */
+ inline Matrix3 () {};
+ inline explicit Matrix3 (const Real arr[3][3])
+ {
+ memcpy(m,arr,9*sizeof(Real));
+ }
+ inline Matrix3 (const Matrix3& rkMatrix)
+ {
+ memcpy(m,rkMatrix.m,9*sizeof(Real));
+ }
+ Matrix3 (Real fEntry00, Real fEntry01, Real fEntry02,
+ Real fEntry10, Real fEntry11, Real fEntry12,
+ Real fEntry20, Real fEntry21, Real fEntry22)
+ {
+ m[0][0] = fEntry00;
+ m[0][1] = fEntry01;
+ m[0][2] = fEntry02;
+ m[1][0] = fEntry10;
+ m[1][1] = fEntry11;
+ m[1][2] = fEntry12;
+ m[2][0] = fEntry20;
+ m[2][1] = fEntry21;
+ m[2][2] = fEntry22;
+ }
+
+ // member access, allows use of construct mat[r][c]
+ inline Real* operator[] (size_t iRow) const
+ {
+ return (Real*)m[iRow];
+ }
+ /*inline operator Real* ()
+ {
+ return (Real*)m[0];
+ }*/
+ Vector3 GetColumn (size_t iCol) const;
+ void SetColumn(size_t iCol, const Vector3& vec);
+ void FromAxes(const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis);
+
+ // assignment and comparison
+ inline Matrix3& operator= (const Matrix3& rkMatrix)
+ {
+ memcpy(m,rkMatrix.m,9*sizeof(Real));
+ return *this;
+ }
+ bool operator== (const Matrix3& rkMatrix) const;
+ inline bool operator!= (const Matrix3& rkMatrix) const
+ {
+ return !operator==(rkMatrix);
+ }
+
+ // arithmetic operations
+ Matrix3 operator+ (const Matrix3& rkMatrix) const;
+ Matrix3 operator- (const Matrix3& rkMatrix) const;
+ Matrix3 operator* (const Matrix3& rkMatrix) const;
+ Matrix3 operator- () const;
+
+ // matrix * vector [3x3 * 3x1 = 3x1]
+ Vector3 operator* (const Vector3& rkVector) const;
+
+ // vector * matrix [1x3 * 3x3 = 1x3]
+ _OgreExport friend Vector3 operator* (const Vector3& rkVector,
+ const Matrix3& rkMatrix);
+
+ // matrix * scalar
+ Matrix3 operator* (Real fScalar) const;
+
+ // scalar * matrix
+ _OgreExport friend Matrix3 operator* (Real fScalar, const Matrix3& rkMatrix);
+
+ // utilities
+ Matrix3 Transpose () const;
+ bool Inverse (Matrix3& rkInverse, Real fTolerance = 1e-06) const;
+ Matrix3 Inverse (Real fTolerance = 1e-06) const;
+ Real Determinant () const;
+
+ // singular value decomposition
+ void SingularValueDecomposition (Matrix3& rkL, Vector3& rkS,
+ Matrix3& rkR) const;
+ void SingularValueComposition (const Matrix3& rkL,
+ const Vector3& rkS, const Matrix3& rkR);
+
+ // Gram-Schmidt orthonormalization (applied to columns of rotation matrix)
+ void Orthonormalize ();
+
+ // orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12)
+ void QDUDecomposition (Matrix3& rkQ, Vector3& rkD,
+ Vector3& rkU) const;
+
+ Real SpectralNorm () const;
+
+ // matrix must be orthonormal
+ void ToAxisAngle (Vector3& rkAxis, Radian& rfAngle) const;
+ inline void ToAxisAngle (Vector3& rkAxis, Degree& rfAngle) const {
+ Radian r;
+ ToAxisAngle ( rkAxis, r );
+ rfAngle = r;
+ }
+ void FromAxisAngle (const Vector3& rkAxis, const Radian& fRadians);
+
+ // The matrix must be orthonormal. The decomposition is yaw*pitch*roll
+ // where yaw is rotation about the Up vector, pitch is rotation about the
+ // Right axis, and roll is rotation about the Direction axis.
+ bool ToEulerAnglesXYZ (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ bool ToEulerAnglesXZY (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ bool ToEulerAnglesYXZ (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ bool ToEulerAnglesYZX (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ bool ToEulerAnglesZXY (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ bool ToEulerAnglesZYX (Radian& rfYAngle, Radian& rfPAngle,
+ Radian& rfRAngle) const;
+ void FromEulerAnglesXYZ (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ void FromEulerAnglesXZY (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ void FromEulerAnglesYXZ (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ void FromEulerAnglesYZX (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ void FromEulerAnglesZXY (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ void FromEulerAnglesZYX (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle);
+ // eigensolver, matrix must be symmetric
+ void EigenSolveSymmetric (Real afEigenvalue[3],
+ Vector3 akEigenvector[3]) const;
+
+ static void TensorProduct (const Vector3& rkU, const Vector3& rkV,
+ Matrix3& rkProduct);
+
+ /** Determines if this matrix involves a scaling. */
+ inline bool hasScale() const
+ {
+ // check magnitude of column vectors (==local axes)
+ Real t = m[0][0] * m[0][0] + m[1][0] * m[1][0] + m[2][0] * m[2][0];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+ t = m[0][1] * m[0][1] + m[1][1] * m[1][1] + m[2][1] * m[2][1];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+ t = m[0][2] * m[0][2] + m[1][2] * m[1][2] + m[2][2] * m[2][2];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+
+ return false;
+ }
+
+
+ static const Real EPSILON;
+ static const Matrix3 ZERO;
+ static const Matrix3 IDENTITY;
+
+ protected:
+ // support for eigensolver
+ void Tridiagonal (Real afDiag[3], Real afSubDiag[3]);
+ bool QLAlgorithm (Real afDiag[3], Real afSubDiag[3]);
+
+ // support for singular value decomposition
+ static const Real ms_fSvdEpsilon;
+ static const unsigned int ms_iSvdMaxIterations;
+ static void Bidiagonalize (Matrix3& kA, Matrix3& kL,
+ Matrix3& kR);
+ static void GolubKahanStep (Matrix3& kA, Matrix3& kL,
+ Matrix3& kR);
+
+ // support for spectral norm
+ static Real MaxCubicRoot (Real afCoeff[3]);
+
+ Real m[3][3];
+
+ // for faster access
+ friend class Matrix4;
+ };
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMatrix3.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,252 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgreMatrix4.h"
+
+#include "OgreVector3.h"
+#include "OgreMatrix3.h"
+
+namespace Ogre
+{
+
+ const Matrix4 Matrix4::ZERO(
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0,
+ 0, 0, 0, 0 );
+
+ const Matrix4 Matrix4::IDENTITY(
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1 );
+
+ const Matrix4 Matrix4::CLIPSPACE2DTOIMAGESPACE(
+ 0.5, 0, 0, 0.5,
+ 0, -0.5, 0, 0.5,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1);
+
+ //-----------------------------------------------------------------------
+ inline static Real
+ MINOR(const Matrix4& m, const size_t r0, const size_t r1, const size_t r2,
+ const size_t c0, const size_t c1, const size_t c2)
+ {
+ return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) -
+ m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) +
+ m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]);
+ }
+ //-----------------------------------------------------------------------
+ Matrix4 Matrix4::adjoint() const
+ {
+ return Matrix4( MINOR(*this, 1, 2, 3, 1, 2, 3),
+ -MINOR(*this, 0, 2, 3, 1, 2, 3),
+ MINOR(*this, 0, 1, 3, 1, 2, 3),
+ -MINOR(*this, 0, 1, 2, 1, 2, 3),
+
+ -MINOR(*this, 1, 2, 3, 0, 2, 3),
+ MINOR(*this, 0, 2, 3, 0, 2, 3),
+ -MINOR(*this, 0, 1, 3, 0, 2, 3),
+ MINOR(*this, 0, 1, 2, 0, 2, 3),
+
+ MINOR(*this, 1, 2, 3, 0, 1, 3),
+ -MINOR(*this, 0, 2, 3, 0, 1, 3),
+ MINOR(*this, 0, 1, 3, 0, 1, 3),
+ -MINOR(*this, 0, 1, 2, 0, 1, 3),
+
+ -MINOR(*this, 1, 2, 3, 0, 1, 2),
+ MINOR(*this, 0, 2, 3, 0, 1, 2),
+ -MINOR(*this, 0, 1, 3, 0, 1, 2),
+ MINOR(*this, 0, 1, 2, 0, 1, 2));
+ }
+ //-----------------------------------------------------------------------
+ Real Matrix4::determinant() const
+ {
+ return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) -
+ m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) +
+ m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) -
+ m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2);
+ }
+ //-----------------------------------------------------------------------
+ Matrix4 Matrix4::inverse() const
+ {
+ Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2], m03 = m[0][3];
+ Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2], m13 = m[1][3];
+ Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2], m23 = m[2][3];
+ Real m30 = m[3][0], m31 = m[3][1], m32 = m[3][2], m33 = m[3][3];
+
+ Real v0 = m20 * m31 - m21 * m30;
+ Real v1 = m20 * m32 - m22 * m30;
+ Real v2 = m20 * m33 - m23 * m30;
+ Real v3 = m21 * m32 - m22 * m31;
+ Real v4 = m21 * m33 - m23 * m31;
+ Real v5 = m22 * m33 - m23 * m32;
+
+ Real t00 = + (v5 * m11 - v4 * m12 + v3 * m13);
+ Real t10 = - (v5 * m10 - v2 * m12 + v1 * m13);
+ Real t20 = + (v4 * m10 - v2 * m11 + v0 * m13);
+ Real t30 = - (v3 * m10 - v1 * m11 + v0 * m12);
+
+ Real invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03);
+
+ Real d00 = t00 * invDet;
+ Real d10 = t10 * invDet;
+ Real d20 = t20 * invDet;
+ Real d30 = t30 * invDet;
+
+ Real d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
+ Real d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
+ Real d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
+ Real d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
+
+ v0 = m10 * m31 - m11 * m30;
+ v1 = m10 * m32 - m12 * m30;
+ v2 = m10 * m33 - m13 * m30;
+ v3 = m11 * m32 - m12 * m31;
+ v4 = m11 * m33 - m13 * m31;
+ v5 = m12 * m33 - m13 * m32;
+
+ Real d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
+ Real d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
+ Real d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
+ Real d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
+
+ v0 = m21 * m10 - m20 * m11;
+ v1 = m22 * m10 - m20 * m12;
+ v2 = m23 * m10 - m20 * m13;
+ v3 = m22 * m11 - m21 * m12;
+ v4 = m23 * m11 - m21 * m13;
+ v5 = m23 * m12 - m22 * m13;
+
+ Real d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
+ Real d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
+ Real d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
+ Real d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
+
+ return Matrix4(
+ d00, d01, d02, d03,
+ d10, d11, d12, d13,
+ d20, d21, d22, d23,
+ d30, d31, d32, d33);
+ }
+ //-----------------------------------------------------------------------
+ Matrix4 Matrix4::inverseAffine(void) const
+ {
+ assert(isAffine());
+
+ Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2];
+ Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2];
+
+ Real t00 = m22 * m11 - m21 * m12;
+ Real t10 = m20 * m12 - m22 * m10;
+ Real t20 = m21 * m10 - m20 * m11;
+
+ Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2];
+
+ Real invDet = 1 / (m00 * t00 + m01 * t10 + m02 * t20);
+
+ t00 *= invDet; t10 *= invDet; t20 *= invDet;
+
+ m00 *= invDet; m01 *= invDet; m02 *= invDet;
+
+ Real r00 = t00;
+ Real r01 = m02 * m21 - m01 * m22;
+ Real r02 = m01 * m12 - m02 * m11;
+
+ Real r10 = t10;
+ Real r11 = m00 * m22 - m02 * m20;
+ Real r12 = m02 * m10 - m00 * m12;
+
+ Real r20 = t20;
+ Real r21 = m01 * m20 - m00 * m21;
+ Real r22 = m00 * m11 - m01 * m10;
+
+ Real m03 = m[0][3], m13 = m[1][3], m23 = m[2][3];
+
+ Real r03 = - (r00 * m03 + r01 * m13 + r02 * m23);
+ Real r13 = - (r10 * m03 + r11 * m13 + r12 * m23);
+ Real r23 = - (r20 * m03 + r21 * m13 + r22 * m23);
+
+ return Matrix4(
+ r00, r01, r02, r03,
+ r10, r11, r12, r13,
+ r20, r21, r22, r23,
+ 0, 0, 0, 1);
+ }
+ //-----------------------------------------------------------------------
+ void Matrix4::makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
+ {
+ // Ordering:
+ // 1. Scale
+ // 2. Rotate
+ // 3. Translate
+
+ Matrix3 rot3x3, scale3x3;
+ orientation.ToRotationMatrix(rot3x3);
+ scale3x3 = Matrix3::ZERO;
+ scale3x3[0][0] = scale.x;
+ scale3x3[1][1] = scale.y;
+ scale3x3[2][2] = scale.z;
+
+ // Set up final matrix with scale, rotation and translation
+ *this = rot3x3 * scale3x3;
+ this->setTrans(position);
+
+ // No projection term
+ m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
+ }
+ //-----------------------------------------------------------------------
+ void Matrix4::makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation)
+ {
+ // Invert the parameters
+ Vector3 invTranslate = -position;
+ Vector3 invScale(1 / scale.x, 1 / scale.y, 1 / scale.z);
+ Quaternion invRot = orientation.Inverse();
+
+ // Because we're inverting, order is translation, rotation, scale
+ // So make translation relative to scale & rotation
+ invTranslate *= invScale; // scale
+ invTranslate = invRot * invTranslate; // rotate
+
+ // Next, make a 3x3 rotation matrix and apply inverse scale
+ Matrix3 rot3x3, scale3x3;
+ invRot.ToRotationMatrix(rot3x3);
+ scale3x3 = Matrix3::ZERO;
+ scale3x3[0][0] = invScale.x;
+ scale3x3[1][1] = invScale.y;
+ scale3x3[2][2] = invScale.z;
+
+ // Set up final matrix with scale, rotation and translation
+ *this = scale3x3 * rot3x3;
+ this->setTrans(invTranslate);
+
+ // No projection term
+ m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1;
+ }
+
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,614 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Matrix4__
+#define __Matrix4__
+
+// Precompiler options
+#include "OgrePrerequisites.h"
+
+#include "OgreVector3.h"
+#include "OgreMatrix3.h"
+#include "OgreVector4.h"
+#include <ostream>
+
+namespace Ogre
+{
+ /** Class encapsulating a standard 4x4 homogeneous matrix.
+ @remarks
+ OGRE uses column vectors when applying matrix multiplications,
+ This means a vector is represented as a single column, 4-row
+ matrix. This has the effect that the transformations implemented
+ by the matrices happens right-to-left e.g. if vector V is to be
+ transformed by M1 then M2 then M3, the calculation would be
+ M3 * M2 * M1 * V. The order that matrices are concatenated is
+ vital since matrix multiplication is not cummatative, i.e. you
+ can get a different result if you concatenate in the wrong order.
+ @par
+ The use of column vectors and right-to-left ordering is the
+ standard in most mathematical texts, and id the same as used in
+ OpenGL. It is, however, the opposite of Direct3D, which has
+ inexplicably chosen to differ from the accepted standard and uses
+ row vectors and left-to-right matrix multiplication.
+ @par
+ OGRE deals with the differences between D3D and OpenGL etc.
+ internally when operating through different render systems. OGRE
+ users only need to conform to standard maths conventions, i.e.
+ right-to-left matrix multiplication, (OGRE transposes matrices it
+ passes to D3D to compensate).
+ @par
+ The generic form M * V which shows the layout of the matrix
+ entries is shown below:
+ <pre>
+ [ m[0][0] m[0][1] m[0][2] m[0][3] ] {x}
+ | m[1][0] m[1][1] m[1][2] m[1][3] | * {y}
+ | m[2][0] m[2][1] m[2][2] m[2][3] | {z}
+ [ m[3][0] m[3][1] m[3][2] m[3][3] ] {1}
+ </pre>
+ */
+ class _OgreExport Matrix4
+ {
+ protected:
+ /// The matrix entries, indexed by [row][col].
+ union {
+ Real m[4][4];
+ Real _m[16];
+ };
+ public:
+ /** Default constructor.
+ @note
+ It does <b>NOT</b> initialize the matrix for efficiency.
+ */
+ inline Matrix4()
+ {
+ }
+
+ inline Matrix4(
+ Real m00, Real m01, Real m02, Real m03,
+ Real m10, Real m11, Real m12, Real m13,
+ Real m20, Real m21, Real m22, Real m23,
+ Real m30, Real m31, Real m32, Real m33 )
+ {
+ m[0][0] = m00;
+ m[0][1] = m01;
+ m[0][2] = m02;
+ m[0][3] = m03;
+ m[1][0] = m10;
+ m[1][1] = m11;
+ m[1][2] = m12;
+ m[1][3] = m13;
+ m[2][0] = m20;
+ m[2][1] = m21;
+ m[2][2] = m22;
+ m[2][3] = m23;
+ m[3][0] = m30;
+ m[3][1] = m31;
+ m[3][2] = m32;
+ m[3][3] = m33;
+ }
+
+ /** Creates a standard 4x4 transformation matrix with a zero translation part from a rotation/scaling 3x3 matrix.
+ */
+
+ inline Matrix4(const Matrix3& m3x3)
+ {
+ operator=(IDENTITY);
+ operator=(m3x3);
+ }
+
+ /** Creates a standard 4x4 transformation matrix with a zero translation part from a rotation/scaling Quaternion.
+ */
+
+ inline Matrix4(const Quaternion& rot)
+ {
+ Matrix3 m3x3;
+ rot.ToRotationMatrix(m3x3);
+ operator=(IDENTITY);
+ operator=(m3x3);
+ }
+
+
+ inline Real* operator [] ( size_t iRow )
+ {
+ assert( iRow < 4 );
+ return m[iRow];
+ }
+
+ inline const Real *const operator [] ( size_t iRow ) const
+ {
+ assert( iRow < 4 );
+ return m[iRow];
+ }
+
+ inline Matrix4 concatenate(const Matrix4 &m2) const
+ {
+ Matrix4 r;
+ r.m[0][0] = m[0][0] * m2.m[0][0] + m[0][1] * m2.m[1][0] + m[0][2] * m2.m[2][0] + m[0][3] * m2.m[3][0];
+ r.m[0][1] = m[0][0] * m2.m[0][1] + m[0][1] * m2.m[1][1] + m[0][2] * m2.m[2][1] + m[0][3] * m2.m[3][1];
+ r.m[0][2] = m[0][0] * m2.m[0][2] + m[0][1] * m2.m[1][2] + m[0][2] * m2.m[2][2] + m[0][3] * m2.m[3][2];
+ r.m[0][3] = m[0][0] * m2.m[0][3] + m[0][1] * m2.m[1][3] + m[0][2] * m2.m[2][3] + m[0][3] * m2.m[3][3];
+
+ r.m[1][0] = m[1][0] * m2.m[0][0] + m[1][1] * m2.m[1][0] + m[1][2] * m2.m[2][0] + m[1][3] * m2.m[3][0];
+ r.m[1][1] = m[1][0] * m2.m[0][1] + m[1][1] * m2.m[1][1] + m[1][2] * m2.m[2][1] + m[1][3] * m2.m[3][1];
+ r.m[1][2] = m[1][0] * m2.m[0][2] + m[1][1] * m2.m[1][2] + m[1][2] * m2.m[2][2] + m[1][3] * m2.m[3][2];
+ r.m[1][3] = m[1][0] * m2.m[0][3] + m[1][1] * m2.m[1][3] + m[1][2] * m2.m[2][3] + m[1][3] * m2.m[3][3];
+
+ r.m[2][0] = m[2][0] * m2.m[0][0] + m[2][1] * m2.m[1][0] + m[2][2] * m2.m[2][0] + m[2][3] * m2.m[3][0];
+ r.m[2][1] = m[2][0] * m2.m[0][1] + m[2][1] * m2.m[1][1] + m[2][2] * m2.m[2][1] + m[2][3] * m2.m[3][1];
+ r.m[2][2] = m[2][0] * m2.m[0][2] + m[2][1] * m2.m[1][2] + m[2][2] * m2.m[2][2] + m[2][3] * m2.m[3][2];
+ r.m[2][3] = m[2][0] * m2.m[0][3] + m[2][1] * m2.m[1][3] + m[2][2] * m2.m[2][3] + m[2][3] * m2.m[3][3];
+
+ r.m[3][0] = m[3][0] * m2.m[0][0] + m[3][1] * m2.m[1][0] + m[3][2] * m2.m[2][0] + m[3][3] * m2.m[3][0];
+ r.m[3][1] = m[3][0] * m2.m[0][1] + m[3][1] * m2.m[1][1] + m[3][2] * m2.m[2][1] + m[3][3] * m2.m[3][1];
+ r.m[3][2] = m[3][0] * m2.m[0][2] + m[3][1] * m2.m[1][2] + m[3][2] * m2.m[2][2] + m[3][3] * m2.m[3][2];
+ r.m[3][3] = m[3][0] * m2.m[0][3] + m[3][1] * m2.m[1][3] + m[3][2] * m2.m[2][3] + m[3][3] * m2.m[3][3];
+
+ return r;
+ }
+
+ /** Matrix concatenation using '*'.
+ */
+ inline Matrix4 operator * ( const Matrix4 &m2 ) const
+ {
+ return concatenate( m2 );
+ }
+
+ /** Vector transformation using '*'.
+ @remarks
+ Transforms the given 3-D vector by the matrix, projecting the
+ result back into <i>w</i> = 1.
+ @note
+ This means that the initial <i>w</i> is considered to be 1.0,
+ and then all the tree elements of the resulting 3-D vector are
+ divided by the resulting <i>w</i>.
+ */
+ inline Vector3 operator * ( const Vector3 &v ) const
+ {
+ Vector3 r;
+
+ Real fInvW = 1.0 / ( m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] );
+
+ r.x = ( m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] ) * fInvW;
+ r.y = ( m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] ) * fInvW;
+ r.z = ( m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] ) * fInvW;
+
+ return r;
+ }
+ inline Vector4 operator * (const Vector4& v) const
+ {
+ return Vector4(
+ m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w,
+ m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w,
+ m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w,
+ m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] * v.w
+ );
+ }
+
+
+ /** Matrix addition.
+ */
+ inline Matrix4 operator + ( const Matrix4 &m2 ) const
+ {
+ Matrix4 r;
+
+ r.m[0][0] = m[0][0] + m2.m[0][0];
+ r.m[0][1] = m[0][1] + m2.m[0][1];
+ r.m[0][2] = m[0][2] + m2.m[0][2];
+ r.m[0][3] = m[0][3] + m2.m[0][3];
+
+ r.m[1][0] = m[1][0] + m2.m[1][0];
+ r.m[1][1] = m[1][1] + m2.m[1][1];
+ r.m[1][2] = m[1][2] + m2.m[1][2];
+ r.m[1][3] = m[1][3] + m2.m[1][3];
+
+ r.m[2][0] = m[2][0] + m2.m[2][0];
+ r.m[2][1] = m[2][1] + m2.m[2][1];
+ r.m[2][2] = m[2][2] + m2.m[2][2];
+ r.m[2][3] = m[2][3] + m2.m[2][3];
+
+ r.m[3][0] = m[3][0] + m2.m[3][0];
+ r.m[3][1] = m[3][1] + m2.m[3][1];
+ r.m[3][2] = m[3][2] + m2.m[3][2];
+ r.m[3][3] = m[3][3] + m2.m[3][3];
+
+ return r;
+ }
+
+ /** Matrix subtraction.
+ */
+ inline Matrix4 operator - ( const Matrix4 &m2 ) const
+ {
+ Matrix4 r;
+ r.m[0][0] = m[0][0] - m2.m[0][0];
+ r.m[0][1] = m[0][1] - m2.m[0][1];
+ r.m[0][2] = m[0][2] - m2.m[0][2];
+ r.m[0][3] = m[0][3] - m2.m[0][3];
+
+ r.m[1][0] = m[1][0] - m2.m[1][0];
+ r.m[1][1] = m[1][1] - m2.m[1][1];
+ r.m[1][2] = m[1][2] - m2.m[1][2];
+ r.m[1][3] = m[1][3] - m2.m[1][3];
+
+ r.m[2][0] = m[2][0] - m2.m[2][0];
+ r.m[2][1] = m[2][1] - m2.m[2][1];
+ r.m[2][2] = m[2][2] - m2.m[2][2];
+ r.m[2][3] = m[2][3] - m2.m[2][3];
+
+ r.m[3][0] = m[3][0] - m2.m[3][0];
+ r.m[3][1] = m[3][1] - m2.m[3][1];
+ r.m[3][2] = m[3][2] - m2.m[3][2];
+ r.m[3][3] = m[3][3] - m2.m[3][3];
+
+ return r;
+ }
+
+ /** Tests 2 matrices for equality.
+ */
+ inline bool operator == ( const Matrix4& m2 ) const
+ {
+ if(
+ m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] ||
+ m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] ||
+ m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] ||
+ m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3] )
+ return false;
+ return true;
+ }
+
+ /** Tests 2 matrices for inequality.
+ */
+ inline bool operator != ( const Matrix4& m2 ) const
+ {
+ if(
+ m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] ||
+ m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] ||
+ m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] ||
+ m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3] )
+ return true;
+ return false;
+ }
+
+ /** Assignment from 3x3 matrix.
+ */
+ inline void operator = ( const Matrix3& mat3 )
+ {
+ m[0][0] = mat3.m[0][0]; m[0][1] = mat3.m[0][1]; m[0][2] = mat3.m[0][2];
+ m[1][0] = mat3.m[1][0]; m[1][1] = mat3.m[1][1]; m[1][2] = mat3.m[1][2];
+ m[2][0] = mat3.m[2][0]; m[2][1] = mat3.m[2][1]; m[2][2] = mat3.m[2][2];
+ }
+
+ inline Matrix4 transpose(void) const
+ {
+ return Matrix4(m[0][0], m[1][0], m[2][0], m[3][0],
+ m[0][1], m[1][1], m[2][1], m[3][1],
+ m[0][2], m[1][2], m[2][2], m[3][2],
+ m[0][3], m[1][3], m[2][3], m[3][3]);
+ }
+
+ /*
+ -----------------------------------------------------------------------
+ Translation Transformation
+ -----------------------------------------------------------------------
+ */
+ /** Sets the translation transformation part of the matrix.
+ */
+ inline void setTrans( const Vector3& v )
+ {
+ m[0][3] = v.x;
+ m[1][3] = v.y;
+ m[2][3] = v.z;
+ }
+
+ /** Extracts the translation transformation part of the matrix.
+ */
+ inline Vector3 getTrans() const
+ {
+ return Vector3(m[0][3], m[1][3], m[2][3]);
+ }
+
+
+ /** Builds a translation matrix
+ */
+ inline void makeTrans( const Vector3& v )
+ {
+ m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = v.x;
+ m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0; m[1][3] = v.y;
+ m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0; m[2][3] = v.z;
+ m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1.0;
+ }
+
+ inline void makeTrans( Real tx, Real ty, Real tz )
+ {
+ m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = tx;
+ m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0; m[1][3] = ty;
+ m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0; m[2][3] = tz;
+ m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1.0;
+ }
+
+ /** Gets a translation matrix.
+ */
+ inline static Matrix4 getTrans( const Vector3& v )
+ {
+ Matrix4 r;
+
+ r.m[0][0] = 1.0; r.m[0][1] = 0.0; r.m[0][2] = 0.0; r.m[0][3] = v.x;
+ r.m[1][0] = 0.0; r.m[1][1] = 1.0; r.m[1][2] = 0.0; r.m[1][3] = v.y;
+ r.m[2][0] = 0.0; r.m[2][1] = 0.0; r.m[2][2] = 1.0; r.m[2][3] = v.z;
+ r.m[3][0] = 0.0; r.m[3][1] = 0.0; r.m[3][2] = 0.0; r.m[3][3] = 1.0;
+
+ return r;
+ }
+
+ /** Gets a translation matrix - variation for not using a vector.
+ */
+ inline static Matrix4 getTrans( Real t_x, Real t_y, Real t_z )
+ {
+ Matrix4 r;
+
+ r.m[0][0] = 1.0; r.m[0][1] = 0.0; r.m[0][2] = 0.0; r.m[0][3] = t_x;
+ r.m[1][0] = 0.0; r.m[1][1] = 1.0; r.m[1][2] = 0.0; r.m[1][3] = t_y;
+ r.m[2][0] = 0.0; r.m[2][1] = 0.0; r.m[2][2] = 1.0; r.m[2][3] = t_z;
+ r.m[3][0] = 0.0; r.m[3][1] = 0.0; r.m[3][2] = 0.0; r.m[3][3] = 1.0;
+
+ return r;
+ }
+
+ /*
+ -----------------------------------------------------------------------
+ Scale Transformation
+ -----------------------------------------------------------------------
+ */
+ /** Sets the scale part of the matrix.
+ */
+ inline void setScale( const Vector3& v )
+ {
+ m[0][0] = v.x;
+ m[1][1] = v.y;
+ m[2][2] = v.z;
+ }
+
+ /** Gets a scale matrix.
+ */
+ inline static Matrix4 getScale( const Vector3& v )
+ {
+ Matrix4 r;
+ r.m[0][0] = v.x; r.m[0][1] = 0.0; r.m[0][2] = 0.0; r.m[0][3] = 0.0;
+ r.m[1][0] = 0.0; r.m[1][1] = v.y; r.m[1][2] = 0.0; r.m[1][3] = 0.0;
+ r.m[2][0] = 0.0; r.m[2][1] = 0.0; r.m[2][2] = v.z; r.m[2][3] = 0.0;
+ r.m[3][0] = 0.0; r.m[3][1] = 0.0; r.m[3][2] = 0.0; r.m[3][3] = 1.0;
+
+ return r;
+ }
+
+ /** Gets a scale matrix - variation for not using a vector.
+ */
+ inline static Matrix4 getScale( Real s_x, Real s_y, Real s_z )
+ {
+ Matrix4 r;
+ r.m[0][0] = s_x; r.m[0][1] = 0.0; r.m[0][2] = 0.0; r.m[0][3] = 0.0;
+ r.m[1][0] = 0.0; r.m[1][1] = s_y; r.m[1][2] = 0.0; r.m[1][3] = 0.0;
+ r.m[2][0] = 0.0; r.m[2][1] = 0.0; r.m[2][2] = s_z; r.m[2][3] = 0.0;
+ r.m[3][0] = 0.0; r.m[3][1] = 0.0; r.m[3][2] = 0.0; r.m[3][3] = 1.0;
+
+ return r;
+ }
+
+ /** Extracts the rotation / scaling part of the Matrix as a 3x3 matrix.
+ @param m3x3 Destination Matrix3
+ */
+ inline void extract3x3Matrix(Matrix3& m3x3) const
+ {
+ m3x3.m[0][0] = m[0][0];
+ m3x3.m[0][1] = m[0][1];
+ m3x3.m[0][2] = m[0][2];
+ m3x3.m[1][0] = m[1][0];
+ m3x3.m[1][1] = m[1][1];
+ m3x3.m[1][2] = m[1][2];
+ m3x3.m[2][0] = m[2][0];
+ m3x3.m[2][1] = m[2][1];
+ m3x3.m[2][2] = m[2][2];
+
+ }
+
+ /** Determines if this matrix involves a scaling. */
+ inline bool hasScale() const
+ {
+ // check magnitude of column vectors (==local axes)
+ Real t = m[0][0] * m[0][0] + m[1][0] * m[1][0] + m[2][0] * m[2][0];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+ t = m[0][1] * m[0][1] + m[1][1] * m[1][1] + m[2][1] * m[2][1];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+ t = m[0][2] * m[0][2] + m[1][2] * m[1][2] + m[2][2] * m[2][2];
+ if (!Math::RealEqual(t, 1.0, 1e-04))
+ return true;
+
+ return false;
+ }
+
+ /** Determines if this matrix involves a negative scaling. */
+ inline bool hasNegativeScale() const
+ {
+ return determinant() < 0;
+ }
+
+ /** Extracts the rotation / scaling part as a quaternion from the Matrix.
+ */
+ inline Quaternion extractQuaternion() const
+ {
+ Matrix3 m3x3;
+ extract3x3Matrix(m3x3);
+ return Quaternion(m3x3);
+ }
+
+ static const Matrix4 ZERO;
+ static const Matrix4 IDENTITY;
+ /** Useful little matrix which takes 2D clipspace {-1, 1} to {0,1}
+ and inverts the Y. */
+ static const Matrix4 CLIPSPACE2DTOIMAGESPACE;
+
+ inline Matrix4 operator*(Real scalar) const
+ {
+ return Matrix4(
+ scalar*m[0][0], scalar*m[0][1], scalar*m[0][2], scalar*m[0][3],
+ scalar*m[1][0], scalar*m[1][1], scalar*m[1][2], scalar*m[1][3],
+ scalar*m[2][0], scalar*m[2][1], scalar*m[2][2], scalar*m[2][3],
+ scalar*m[3][0], scalar*m[3][1], scalar*m[3][2], scalar*m[3][3]);
+ }
+
+ /** Function for writing to a stream.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const Matrix4& m )
+ {
+ o << "Matrix4(";
+ for (size_t i = 0; i < 4; ++i)
+ {
+ o << " row" << (unsigned)i << "{";
+ for(size_t j = 0; j < 4; ++j)
+ {
+ o << m[i][j] << " ";
+ }
+ o << "}";
+ }
+ o << ")";
+ return o;
+ }
+
+ Matrix4 adjoint() const;
+ Real determinant() const;
+ Matrix4 inverse() const;
+
+ /** Building a Matrix4 from orientation / scale / position.
+ @remarks
+ Transform is performed in the order scale, rotate, translation, i.e. translation is independent
+ of orientation axes, scale does not affect size of translation, rotation and scaling are always
+ centered on the origin.
+ */
+ void makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation);
+
+ /** Building an inverse Matrix4 from orientation / scale / position.
+ @remarks
+ As makeTransform except it build the inverse given the same data as makeTransform, so
+ performing -translation, -rotate, 1/scale in that order.
+ */
+ void makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation);
+
+ /** Check whether or not the matrix is affine matrix.
+ @remarks
+ An affine matrix is a 4x4 matrix with row 3 equal to (0, 0, 0, 1),
+ e.g. no projective coefficients.
+ */
+ inline bool isAffine(void) const
+ {
+ return m[3][0] == 0 && m[3][1] == 0 && m[3][2] == 0 && m[3][3] == 1;
+ }
+
+ /** Returns the inverse of the affine matrix.
+ @note
+ The matrix must be an affine matrix. @see Matrix4::isAffine.
+ */
+ Matrix4 inverseAffine(void) const;
+
+ /** Concatenate two affine matrix.
+ @note
+ The matrices must be affine matrix. @see Matrix4::isAffine.
+ */
+ inline Matrix4 concatenateAffine(const Matrix4 &m2) const
+ {
+ assert(isAffine() && m2.isAffine());
+
+ return Matrix4(
+ m[0][0] * m2.m[0][0] + m[0][1] * m2.m[1][0] + m[0][2] * m2.m[2][0],
+ m[0][0] * m2.m[0][1] + m[0][1] * m2.m[1][1] + m[0][2] * m2.m[2][1],
+ m[0][0] * m2.m[0][2] + m[0][1] * m2.m[1][2] + m[0][2] * m2.m[2][2],
+ m[0][0] * m2.m[0][3] + m[0][1] * m2.m[1][3] + m[0][2] * m2.m[2][3] + m[0][3],
+
+ m[1][0] * m2.m[0][0] + m[1][1] * m2.m[1][0] + m[1][2] * m2.m[2][0],
+ m[1][0] * m2.m[0][1] + m[1][1] * m2.m[1][1] + m[1][2] * m2.m[2][1],
+ m[1][0] * m2.m[0][2] + m[1][1] * m2.m[1][2] + m[1][2] * m2.m[2][2],
+ m[1][0] * m2.m[0][3] + m[1][1] * m2.m[1][3] + m[1][2] * m2.m[2][3] + m[1][3],
+
+ m[2][0] * m2.m[0][0] + m[2][1] * m2.m[1][0] + m[2][2] * m2.m[2][0],
+ m[2][0] * m2.m[0][1] + m[2][1] * m2.m[1][1] + m[2][2] * m2.m[2][1],
+ m[2][0] * m2.m[0][2] + m[2][1] * m2.m[1][2] + m[2][2] * m2.m[2][2],
+ m[2][0] * m2.m[0][3] + m[2][1] * m2.m[1][3] + m[2][2] * m2.m[2][3] + m[2][3],
+
+ 0, 0, 0, 1);
+ }
+
+ /** 3-D Vector transformation specially for affine matrix.
+ @remarks
+ Transforms the given 3-D vector by the matrix, projecting the
+ result back into <i>w</i> = 1.
+ @note
+ The matrix must be an affine matrix. @see Matrix4::isAffine.
+ */
+ inline Vector3 transformAffine(const Vector3& v) const
+ {
+ assert(isAffine());
+
+ return Vector3(
+ m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3],
+ m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3],
+ m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]);
+ }
+
+ /** 4-D Vector transformation specially for affine matrix.
+ @note
+ The matrix must be an affine matrix. @see Matrix4::isAffine.
+ */
+ inline Vector4 transformAffine(const Vector4& v) const
+ {
+ assert(isAffine());
+
+ return Vector4(
+ m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w,
+ m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w,
+ m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w,
+ v.w);
+ }
+ };
+
+ /* Removed from Vector4 and made a non-member here because otherwise
+ OgreMatrix4.h and OgreVector4.h have to try to include and inline each
+ other, which frankly doesn't work ;)
+ */
+ inline Vector4 operator * (const Vector4& v, const Matrix4& mat)
+ {
+ return Vector4(
+ v.x*mat[0][0] + v.y*mat[1][0] + v.z*mat[2][0] + v.w*mat[3][0],
+ v.x*mat[0][1] + v.y*mat[1][1] + v.z*mat[2][1] + v.w*mat[3][1],
+ v.x*mat[0][2] + v.y*mat[1][2] + v.z*mat[2][2] + v.w*mat[3][2],
+ v.x*mat[0][3] + v.y*mat[1][3] + v.z*mat[2][3] + v.w*mat[3][3]
+ );
+ }
+
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreMatrix4.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgrePlane.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgrePlane.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgrePlane.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,159 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+(Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgrePlane.h"
+#include "OgreMatrix3.h"
+
+namespace Ogre {
+ //-----------------------------------------------------------------------
+ Plane::Plane ()
+ {
+ normal = Vector3::ZERO;
+ d = 0.0;
+ }
+ //-----------------------------------------------------------------------
+ Plane::Plane (const Plane& rhs)
+ {
+ normal = rhs.normal;
+ d = rhs.d;
+ }
+ //-----------------------------------------------------------------------
+ Plane::Plane (const Vector3& rkNormal, Real fConstant)
+ {
+ normal = rkNormal;
+ d = -fConstant;
+ }
+ //---------------------------------------------------------------------
+ Plane::Plane (Real a, Real b, Real c, Real _d)
+ : normal(a, b, c), d(_d)
+ {
+ }
+ //-----------------------------------------------------------------------
+ Plane::Plane (const Vector3& rkNormal, const Vector3& rkPoint)
+ {
+ redefine(rkNormal, rkPoint);
+ }
+ //-----------------------------------------------------------------------
+ Plane::Plane (const Vector3& rkPoint0, const Vector3& rkPoint1,
+ const Vector3& rkPoint2)
+ {
+ redefine(rkPoint0, rkPoint1, rkPoint2);
+ }
+ //-----------------------------------------------------------------------
+ Real Plane::getDistance (const Vector3& rkPoint) const
+ {
+ return normal.dotProduct(rkPoint) + d;
+ }
+ //-----------------------------------------------------------------------
+ Plane::Side Plane::getSide (const Vector3& rkPoint) const
+ {
+ Real fDistance = getDistance(rkPoint);
+
+ if ( fDistance < 0.0 )
+ return Plane::NEGATIVE_SIDE;
+
+ if ( fDistance > 0.0 )
+ return Plane::POSITIVE_SIDE;
+
+ return Plane::NO_SIDE;
+ }
+
+
+ //-----------------------------------------------------------------------
+ Plane::Side Plane::getSide (const Vector3& centre, const Vector3& halfSize) const
+ {
+ // Calculate the distance between box centre and the plane
+ Real dist = getDistance(centre);
+
+ // Calculate the maximise allows absolute distance for
+ // the distance between box centre and plane
+ Real maxAbsDist = normal.absDotProduct(halfSize);
+
+ if (dist < -maxAbsDist)
+ return Plane::NEGATIVE_SIDE;
+
+ if (dist > +maxAbsDist)
+ return Plane::POSITIVE_SIDE;
+
+ return Plane::BOTH_SIDE;
+ }
+ //-----------------------------------------------------------------------
+ void Plane::redefine(const Vector3& rkPoint0, const Vector3& rkPoint1,
+ const Vector3& rkPoint2)
+ {
+ Vector3 kEdge1 = rkPoint1 - rkPoint0;
+ Vector3 kEdge2 = rkPoint2 - rkPoint0;
+ normal = kEdge1.crossProduct(kEdge2);
+ normal.normalise();
+ d = -normal.dotProduct(rkPoint0);
+ }
+ //-----------------------------------------------------------------------
+ void Plane::redefine(const Vector3& rkNormal, const Vector3& rkPoint)
+ {
+ normal = rkNormal;
+ d = -rkNormal.dotProduct(rkPoint);
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Plane::projectVector(const Vector3& p) const
+ {
+ // We know plane normal is unit length, so use simple method
+ Matrix3 xform;
+ xform[0][0] = 1.0f - normal.x * normal.x;
+ xform[0][1] = -normal.x * normal.y;
+ xform[0][2] = -normal.x * normal.z;
+ xform[1][0] = -normal.y * normal.x;
+ xform[1][1] = 1.0f - normal.y * normal.y;
+ xform[1][2] = -normal.y * normal.z;
+ xform[2][0] = -normal.z * normal.x;
+ xform[2][1] = -normal.z * normal.y;
+ xform[2][2] = 1.0f - normal.z * normal.z;
+ return xform * p;
+
+ }
+ //-----------------------------------------------------------------------
+ Real Plane::normalise(void)
+ {
+ Real fLength = normal.length();
+
+ // Will also work for zero-sized vectors, but will change nothing
+ if (fLength > 1e-08f)
+ {
+ Real fInvLength = 1.0f / fLength;
+ normal *= fInvLength;
+ d *= fInvLength;
+ }
+
+ return fLength;
+ }
+ //-----------------------------------------------------------------------
+ std::ostream& operator<< (std::ostream& o, const Plane& p)
+ {
+ o << "Plane(normal=" << p.normal << ", d=" << p.d << ")";
+ return o;
+ }
+} // namespace Ogre
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgrePlane.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgrePlane.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgrePlane.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgrePlane.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,156 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+// Original free version by:
+// Magic Software, Inc.
+// http://www.geometrictools.com/
+// Copyright (c) 2000, All Rights Reserved
+
+#ifndef __Plane_H__
+#define __Plane_H__
+
+#include "OgrePrerequisites.h"
+
+#include "OgreVector3.h"
+
+namespace Ogre {
+
+ /** Defines a plane in 3D space.
+ @remarks
+ A plane is defined in 3D space by the equation
+ Ax + By + Cz + D = 0
+ @par
+ This equates to a vector (the normal of the plane, whose x, y
+ and z components equate to the coefficients A, B and C
+ respectively), and a constant (D) which is the distance along
+ the normal you have to go to move the plane back to the origin.
+ */
+ class _OgreExport Plane
+ {
+ public:
+ /** Default constructor - sets everything to 0.
+ */
+ Plane ();
+ Plane (const Plane& rhs);
+ /** Construct a plane through a normal, and a distance to move the plane along the normal.*/
+ Plane (const Vector3& rkNormal, Real fConstant);
+ /** Construct a plane using the 4 constants directly **/
+ Plane (Real a, Real b, Real c, Real d);
+ Plane (const Vector3& rkNormal, const Vector3& rkPoint);
+ Plane (const Vector3& rkPoint0, const Vector3& rkPoint1,
+ const Vector3& rkPoint2);
+
+ /** The "positive side" of the plane is the half space to which the
+ plane normal points. The "negative side" is the other half
+ space. The flag "no side" indicates the plane itself.
+ */
+ enum Side
+ {
+ NO_SIDE,
+ POSITIVE_SIDE,
+ NEGATIVE_SIDE,
+ BOTH_SIDE
+ };
+
+ Side getSide (const Vector3& rkPoint) const;
+
+ /**
+ returns the side where the aligneBox is. the flag BOTH_SIDE indicates an intersecting box.
+ one corner ON the plane is sufficient to consider the box and the plane intersecting.
+ */
+ Side getSide (const AxisAlignedBox& rkBox) const;
+
+ /** Returns which side of the plane that the given box lies on.
+ The box is defined as centre/half-size pairs for effectively.
+ @param centre The centre of the box.
+ @param halfSize The half-size of the box.
+ @returns
+ POSITIVE_SIDE if the box complete lies on the "positive side" of the plane,
+ NEGATIVE_SIDE if the box complete lies on the "negative side" of the plane,
+ and BOTH_SIDE if the box intersects the plane.
+ */
+ Side getSide (const Vector3& centre, const Vector3& halfSize) const;
+
+ /** This is a pseudodistance. The sign of the return value is
+ positive if the point is on the positive side of the plane,
+ negative if the point is on the negative side, and zero if the
+ point is on the plane.
+ @par
+ The absolute value of the return value is the true distance only
+ when the plane normal is a unit length vector.
+ */
+ Real getDistance (const Vector3& rkPoint) const;
+
+ /** Redefine this plane based on 3 points. */
+ void redefine(const Vector3& rkPoint0, const Vector3& rkPoint1,
+ const Vector3& rkPoint2);
+
+ /** Redefine this plane based on a normal and a point. */
+ void redefine(const Vector3& rkNormal, const Vector3& rkPoint);
+
+ /** Project a vector onto the plane.
+ @remarks This gives you the element of the input vector that is perpendicular
+ to the normal of the plane. You can get the element which is parallel
+ to the normal of the plane by subtracting the result of this method
+ from the original vector, since parallel + perpendicular = original.
+ @param v The input vector
+ */
+ Vector3 projectVector(const Vector3& v) const;
+
+ /** Normalises the plane.
+ @remarks
+ This method normalises the plane's normal and the length scale of d
+ is as well.
+ @note
+ This function will not crash for zero-sized vectors, but there
+ will be no changes made to their components.
+ @returns The previous length of the plane's normal.
+ */
+ Real normalise(void);
+
+ Vector3 normal;
+ Real d;
+
+ /// Comparison operator
+ bool operator==(const Plane& rhs) const
+ {
+ return (rhs.d == d && rhs.normal == normal);
+ }
+ bool operator!=(const Plane& rhs) const
+ {
+ return (rhs.d != d && rhs.normal != normal);
+ }
+
+ _OgreExport friend std::ostream& operator<< (std::ostream& o, const Plane& p);
+ };
+
+ typedef std::vector<Plane> PlaneList;
+
+} // namespace Ogre
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgrePlane.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgrePlatform.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgrePlatform.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgrePlatform.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,226 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Platform_H_
+#define __Platform_H_
+
+#include "OgreConfig.h"
+
+namespace Ogre {
+/* Initial platform/compiler-related stuff to set.
+*/
+#define OGRE_PLATFORM_WIN32 1
+#define OGRE_PLATFORM_LINUX 2
+#define OGRE_PLATFORM_APPLE 3
+
+#define OGRE_COMPILER_MSVC 1
+#define OGRE_COMPILER_GNUC 2
+#define OGRE_COMPILER_BORL 3
+
+#define OGRE_ENDIAN_LITTLE 1
+#define OGRE_ENDIAN_BIG 2
+
+#define OGRE_ARCHITECTURE_32 1
+#define OGRE_ARCHITECTURE_64 2
+
+/* Finds the compiler type and version.
+*/
+#if defined( _MSC_VER )
+# define OGRE_COMPILER OGRE_COMPILER_MSVC
+# define OGRE_COMP_VER _MSC_VER
+
+#elif defined( __GNUC__ )
+# define OGRE_COMPILER OGRE_COMPILER_GNUC
+# define OGRE_COMP_VER (((__GNUC__)*100) + \
+ (__GNUC_MINOR__*10) + \
+ __GNUC_PATCHLEVEL__)
+
+#elif defined( __BORLANDC__ )
+# define OGRE_COMPILER OGRE_COMPILER_BORL
+# define OGRE_COMP_VER __BCPLUSPLUS__
+# define __FUNCTION__ __FUNC__
+#else
+# pragma error "No known compiler. Abort! Abort!"
+
+#endif
+
+/* See if we can use __forceinline or if we need to use __inline instead */
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC
+# if OGRE_COMP_VER >= 1200
+# define FORCEINLINE __forceinline
+# endif
+#elif defined(__MINGW32__)
+# if !defined(FORCEINLINE)
+# define FORCEINLINE __inline
+# endif
+#else
+# define FORCEINLINE __inline
+#endif
+
+/* Finds the current platform */
+
+#if defined( __WIN32__ ) || defined( _WIN32 )
+# define OGRE_PLATFORM OGRE_PLATFORM_WIN32
+
+#elif defined( __APPLE_CC__)
+# define OGRE_PLATFORM OGRE_PLATFORM_APPLE
+
+#else
+# define OGRE_PLATFORM OGRE_PLATFORM_LINUX
+#endif
+
+ /* Find the arch type */
+#if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || defined(__alpha__) || defined(__ia64__) || defined(__s390__) || defined(__s390x__)
+# define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_64
+#else
+# define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_32
+#endif
+
+// For generating compiler warnings - should work on any compiler
+// As a side note, if you start your message with 'Warning: ', the MSVC
+// IDE actually does catch a warning :)
+#define OGRE_QUOTE_INPLACE(x) # x
+#define OGRE_QUOTE(x) OGRE_QUOTE_INPLACE(x)
+#define OGRE_WARN( x ) message( __FILE__ "(" QUOTE( __LINE__ ) ") : " x "\n" )
+
+//----------------------------------------------------------------------------
+// Windows Settings
+#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
+
+// If we're not including this from a client build, specify that the stuff
+// should get exported. Otherwise, import it.
+# if defined( OGRE_STATIC_LIB )
+ // Linux compilers don't have symbol import/export directives.
+# define _OgreExport
+# define _OgrePrivate
+# else
+# if defined( OGRE_NONCLIENT_BUILD )
+# define _OgreExport __declspec( dllexport )
+# else
+# if defined( __MINGW32__ )
+# define _OgreExport
+# else
+# define _OgreExport __declspec( dllimport )
+# endif
+# endif
+# define _OgrePrivate
+# endif
+// Win32 compilers use _DEBUG for specifying debug builds.
+# ifdef _DEBUG
+# define OGRE_DEBUG_MODE 1
+# else
+# define OGRE_DEBUG_MODE 0
+# endif
+
+// Disable unicode support on MingW at the moment, poorly supported in stdlibc++
+// STLPORT fixes this though so allow if found
+// MinGW C++ Toolkit supports unicode and sets the define __MINGW32_TOOLKIT_UNICODE__ in _mingw.h
+#if defined( __MINGW32__ ) && !defined(_STLPORT_VERSION)
+# include<_mingw.h>
+# if defined(__MINGW32_TOOLBOX_UNICODE__)
+# define OGRE_UNICODE_SUPPORT 1
+# else
+# define OGRE_UNICODE_SUPPORT 0
+# endif
+#else
+# define OGRE_UNICODE_SUPPORT 1
+#endif
+
+#endif
+//----------------------------------------------------------------------------
+
+//----------------------------------------------------------------------------
+// Linux/Apple Settings
+#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
+
+// Enable GCC symbol visibility
+# if defined( OGRE_GCC_VISIBILITY )
+# define _OgreExport __attribute__ ((visibility("default")))
+# define _OgrePrivate __attribute__ ((visibility("hidden")))
+# else
+# define _OgreExport
+# define _OgrePrivate
+# endif
+
+// A quick define to overcome different names for the same function
+# define stricmp strcasecmp
+
+// Unlike the Win32 compilers, Linux compilers seem to use DEBUG for when
+// specifying a debug build.
+// (??? this is wrong, on Linux debug builds aren't marked in any way unless
+// you mark it yourself any way you like it -- zap ???)
+# ifdef DEBUG
+# define OGRE_DEBUG_MODE 1
+# else
+# define OGRE_DEBUG_MODE 0
+# endif
+
+#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
+ #define OGRE_PLATFORM_LIB "OgrePlatform.bundle"
+#else
+ //OGRE_PLATFORM_LINUX
+ #define OGRE_PLATFORM_LIB "libOgrePlatform.so"
+#endif
+
+// Always enable unicode support for the moment
+// Perhaps disable in old versions of gcc if necessary
+#define OGRE_UNICODE_SUPPORT 1
+
+#endif
+
+//For apple, we always have a custom config.h file
+#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
+# include "config.h"
+#endif
+
+//----------------------------------------------------------------------------
+
+//----------------------------------------------------------------------------
+// Endian Settings
+// check for BIG_ENDIAN config flag, set OGRE_ENDIAN correctly
+#ifdef OGRE_CONFIG_BIG_ENDIAN
+# define OGRE_ENDIAN OGRE_ENDIAN_BIG
+#else
+# define OGRE_ENDIAN OGRE_ENDIAN_LITTLE
+#endif
+
+// Integer formats of fixed bit width
+typedef unsigned int uint32;
+typedef unsigned short uint16;
+typedef unsigned char uint8;
+// define uint64 type
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC
+ typedef unsigned __int64 uint64;
+#else
+ typedef unsigned long long uint64;
+#endif
+
+
+}
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgrePlatform.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgrePrerequisites.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgrePrerequisites.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgrePrerequisites.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,407 @@
+/*-------------------------------------------------------------------------
+This source file is a part of OGRE
+(Object-oriented Graphics Rendering Engine)
+
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+This library is free software; you can redistribute it and/or modify it
+under the terms of the GNU Lesser General Public License (LGPL) as
+published by the Free Software Foundation; either version 2.1 of the
+License, or (at your option) any later version.
+
+This library 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 library; if not, write to the Free Software Foundation,
+Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or go to
+http://www.gnu.org/copyleft/lesser.txt
+-------------------------------------------------------------------------*/
+#ifndef __OgrePrerequisites_H__
+#define __OgrePrerequisites_H__
+
+// Platform-specific stuff
+#include "OgrePlatform.h"
+
+// Needed for OGRE_WCHAR_T_STRINGS below
+#include <string>
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC
+// Turn off warnings generated by long std templates
+// This warns about truncation to 255 characters in debug/browse info
+# pragma warning (disable : 4786)
+
+// Turn off warnings generated by long std templates
+// This warns about truncation to 255 characters in debug/browse info
+# pragma warning (disable : 4503)
+
+// disable: "conversion from 'double' to 'float', possible loss of data
+# pragma warning (disable : 4244)
+
+// disable: "truncation from 'double' to 'float'
+# pragma warning (disable : 4305)
+
+// disable: "<type> needs to have dll-interface to be used by clients'
+// Happens on STL member variables which are not public therefore is ok
+# pragma warning (disable : 4251)
+
+// disable: "non dll-interface class used as base for dll-interface class"
+// Happens when deriving from Singleton because bug in compiler ignores
+// template export
+# pragma warning (disable : 4275)
+
+// disable: "C++ Exception Specification ignored"
+// This is because MSVC 6 did not implement all the C++ exception
+// specifications in the ANSI C++ draft.
+# pragma warning( disable : 4290 )
+
+// disable: "no suitable definition provided for explicit template
+// instantiation request" Occurs in VC7 for no justifiable reason on all
+// #includes of Singleton
+# pragma warning( disable: 4661)
+
+// disable: deprecation warnings when using CRT calls in VC8
+// These show up on all C runtime lib code in VC8, disable since they clutter
+// the warnings with things we may not be able to do anything about (e.g.
+// generated code from nvparse etc). I doubt very much that these calls
+// will ever be actually removed from VC anyway, it would break too much code.
+# pragma warning( disable: 4996)
+
+// disable: "conditional expression constant", always occurs on
+// OGRE_MUTEX_CONDITIONAL when no threading enabled
+# pragma warning (disable : 201)
+
+#endif
+
+// configure memory tracking
+#if OGRE_DEBUG_MODE
+# if OGRE_MEMORY_TRACKER_DEBUG_MODE
+# define OGRE_MEMORY_TRACKER 1
+# else
+# define OGRE_MEMORY_TRACKER 0
+# endif
+#else
+# if OGRE_MEMORY_TRACKER_RELEASE_MODE
+# define OGRE_MEMORY_TRACKER 1
+# else
+# define OGRE_MEMORY_TRACKER 0
+# endif
+#endif
+
+
+
+
+namespace Ogre {
+ // Define ogre version
+ #define OGRE_VERSION_MAJOR 1
+ #define OGRE_VERSION_MINOR 6
+ #define OGRE_VERSION_PATCH 1
+ #define OGRE_VERSION_SUFFIX ""
+ #define OGRE_VERSION_NAME "Shoggoth"
+
+ #define OGRE_VERSION ((OGRE_VERSION_MAJOR << 16) | (OGRE_VERSION_MINOR << 8) | OGRE_VERSION_PATCH)
+
+ // define the real number values to be used
+ // default to use 'float' unless precompiler option set
+ #if OGRE_DOUBLE_PRECISION == 1
+ /** Software floating point type.
+ @note Not valid as a pointer to GPU buffers / parameters
+ */
+ typedef double Real;
+ #else
+ /** Software floating point type.
+ @note Not valid as a pointer to GPU buffers / parameters
+ */
+ typedef float Real;
+ #endif
+
+ #if OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER >= 310 && !defined(STLPORT)
+ # if OGRE_COMP_VER >= 430
+ # define HashMap ::std::tr1::unordered_map
+ # define HashSet ::std::tr1::unordered_set
+ # else
+ # define HashMap ::__gnu_cxx::hash_map
+ # define HashSet ::__gnu_cxx::hash_set
+ # endif
+ #else
+ # if OGRE_COMPILER == OGRE_COMPILER_MSVC
+ # if OGRE_COMP_VER > 1300 && !defined(_STLP_MSVC)
+ # define HashMap ::stdext::hash_map
+ # define HashSet ::stdext::hash_set
+ # else
+ # define HashMap ::std::hash_map
+ # define HashSet ::std::hash_set
+ # endif
+ # else
+ # define HashMap ::std::hash_map
+ # define HashSet ::std::hash_set
+ # endif
+ #endif
+
+ /** In order to avoid finger-aches :)
+ */
+ typedef unsigned char uchar;
+ typedef unsigned short ushort;
+ typedef unsigned int uint;
+ typedef unsigned long ulong;
+
+ #if OGRE_WCHAR_T_STRINGS
+ typedef std::wstring _StringBase;
+ #else
+ typedef std::string _StringBase;
+ #endif
+
+ typedef _StringBase String;
+
+ // Useful threading defines
+ #define OGRE_AUTO_MUTEX_NAME mutex
+ #if OGRE_THREAD_SUPPORT
+ #define OGRE_AUTO_MUTEX mutable boost::recursive_mutex OGRE_AUTO_MUTEX_NAME;
+ #define OGRE_LOCK_AUTO_MUTEX boost::recursive_mutex::scoped_lock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME);
+ #define OGRE_MUTEX(name) mutable boost::recursive_mutex name;
+ #define OGRE_STATIC_MUTEX(name) static boost::recursive_mutex name;
+ #define OGRE_STATIC_MUTEX_INSTANCE(name) boost::recursive_mutex name;
+ #define OGRE_LOCK_MUTEX(name) boost::recursive_mutex::scoped_lock ogrenameLock(name);
+ #define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName) boost::recursive_mutex::scoped_lock lockName(mutexName);
+ // like OGRE_AUTO_MUTEX but mutex held by pointer
+ #define OGRE_AUTO_SHARED_MUTEX mutable boost::recursive_mutex *OGRE_AUTO_MUTEX_NAME;
+ #define OGRE_LOCK_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); boost::recursive_mutex::scoped_lock ogreAutoMutexLock(*OGRE_AUTO_MUTEX_NAME);
+ #define OGRE_NEW_AUTO_SHARED_MUTEX assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = new boost::recursive_mutex();
+ #define OGRE_DELETE_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); delete OGRE_AUTO_MUTEX_NAME;
+ #define OGRE_COPY_AUTO_SHARED_MUTEX(from) assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = from;
+ #define OGRE_SET_AUTO_SHARED_MUTEX_NULL OGRE_AUTO_MUTEX_NAME = 0;
+ #define OGRE_MUTEX_CONDITIONAL(mutex) if (mutex)
+ #define OGRE_THREAD_SYNCHRONISER(sync) boost::condition sync;
+ #define OGRE_THREAD_WAIT(sync, lock) sync.wait(lock);
+ #define OGRE_THREAD_NOTIFY_ONE(sync) sync.notify_one();
+ #define OGRE_THREAD_NOTIFY_ALL(sync) sync.notify_all();
+ // Thread-local pointer
+ #define OGRE_THREAD_POINTER(T, var) boost::thread_specific_ptr<T> var
+ #define OGRE_THREAD_POINTER_SET(var, expr) var.reset(expr)
+ #define OGRE_THREAD_POINTER_DELETE(var) var.reset(0)
+ #define OGRE_THREAD_POINTER_GET(var) var.get()
+ #else
+ #define OGRE_AUTO_MUTEX
+ #define OGRE_LOCK_AUTO_MUTEX
+ #define OGRE_MUTEX(name)
+ #define OGRE_STATIC_MUTEX(name)
+ #define OGRE_STATIC_MUTEX_INSTANCE(name)
+ #define OGRE_LOCK_MUTEX(name)
+ #define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName)
+ #define OGRE_AUTO_SHARED_MUTEX
+ #define OGRE_LOCK_AUTO_SHARED_MUTEX
+ #define OGRE_NEW_AUTO_SHARED_MUTEX
+ #define OGRE_DELETE_AUTO_SHARED_MUTEX
+ #define OGRE_COPY_AUTO_SHARED_MUTEX(from)
+ #define OGRE_SET_AUTO_SHARED_MUTEX_NULL
+ #define OGRE_MUTEX_CONDITIONAL(name) if(true)
+ #define OGRE_THREAD_SYNCHRONISER(sync)
+ #define OGRE_THREAD_WAIT(sync, lock)
+ #define OGRE_THREAD_NOTIFY_ONE(sync)
+ #define OGRE_THREAD_NOTIFY_ALL(sync)
+ #define OGRE_THREAD_POINTER(T, var) T* var
+ #define OGRE_THREAD_POINTER_SET(var, expr) var = expr
+ #define OGRE_THREAD_POINTER_DELETE(var) OGRE_DELETE var; var = 0
+ #define OGRE_THREAD_POINTER_GET(var) var
+ #endif
+
+
+// Pre-declare classes
+// Allows use of pointers in header files without including individual .h
+// so decreases dependencies between files
+ class Angle;
+ class Animation;
+ class AnimationState;
+ class AnimationStateSet;
+ class AnimationTrack;
+ class Archive;
+ class ArchiveFactory;
+ class ArchiveManager;
+ class AutoParamDataSource;
+ class AxisAlignedBox;
+ class AxisAlignedBoxSceneQuery;
+ class Billboard;
+ class BillboardChain;
+ class BillboardSet;
+ class Bone;
+ class Camera;
+ class Codec;
+ class ColourValue;
+ class ConfigDialog;
+ template <typename T> class Controller;
+ template <typename T> class ControllerFunction;
+ class ControllerManager;
+ template <typename T> class ControllerValue;
+ class Degree;
+ class DynLib;
+ class DynLibManager;
+ class EdgeData;
+ class EdgeListBuilder;
+ class Entity;
+ class ErrorDialog;
+ class ExternalTextureSourceManager;
+ class Factory;
+ class Font;
+ class FontPtr;
+ class FontManager;
+ struct FrameEvent;
+ class FrameListener;
+ class Frustum;
+ class GpuProgram;
+ class GpuProgramPtr;
+ class GpuProgramManager;
+ class GpuProgramUsage;
+ class HardwareIndexBuffer;
+ class HardwareOcclusionQuery;
+ class HardwareVertexBuffer;
+ class HardwarePixelBuffer;
+ class HardwarePixelBufferSharedPtr;
+ class HighLevelGpuProgram;
+ class HighLevelGpuProgramPtr;
+ class HighLevelGpuProgramManager;
+ class HighLevelGpuProgramFactory;
+ class IndexData;
+ class IntersectionSceneQuery;
+ class IntersectionSceneQueryListener;
+ class Image;
+ class KeyFrame;
+ class Light;
+ class Log;
+ class LogManager;
+ class ManualResourceLoader;
+ class ManualObject;
+ class Material;
+ class MaterialPtr;
+ class MaterialManager;
+ class Math;
+ class Matrix3;
+ class Matrix4;
+ class MemoryManager;
+ class Mesh;
+ class MeshPtr;
+ class MeshSerializer;
+ class MeshSerializerImpl;
+ class MeshManager;
+ class MovableObject;
+ class MovablePlane;
+ class Node;
+ class NodeAnimationTrack;
+ class NodeKeyFrame;
+ class NumericAnimationTrack;
+ class NumericKeyFrame;
+ class Overlay;
+ class OverlayContainer;
+ class OverlayElement;
+ class OverlayElementFactory;
+ class OverlayManager;
+ class Particle;
+ class ParticleAffector;
+ class ParticleAffectorFactory;
+ class ParticleEmitter;
+ class ParticleEmitterFactory;
+ class ParticleSystem;
+ class ParticleSystemManager;
+ class ParticleSystemRenderer;
+ class ParticleSystemRendererFactory;
+ class ParticleVisualData;
+ class Pass;
+ class PatchMesh;
+ class PixelBox;
+ class Plane;
+ class PlaneBoundedVolume;
+ class Plugin;
+ class Pose;
+ class ProgressiveMesh;
+ class Profile;
+ class Profiler;
+ class Quaternion;
+ class Radian;
+ class Ray;
+ class RaySceneQuery;
+ class RaySceneQueryListener;
+ class Renderable;
+ class RenderPriorityGroup;
+ class RenderQueue;
+ class RenderQueueGroup;
+ class RenderQueueInvocation;
+ class RenderQueueInvocationSequence;
+ class RenderQueueListener;
+ class RenderSystem;
+ class RenderSystemCapabilities;
+ class RenderSystemCapabilitiesManager;
+ class RenderSystemCapabilitiesSerializer;
+ class RenderTarget;
+ class RenderTargetListener;
+ class RenderTexture;
+ class MultiRenderTarget;
+ class RenderWindow;
+ class RenderOperation;
+ class Resource;
+ class ResourceBackgroundQueue;
+ class ResourceGroupManager;
+ class ResourceManager;
+ class RibbonTrail;
+ class Root;
+ class SceneManager;
+ class SceneManagerEnumerator;
+ class SceneNode;
+ class SceneQuery;
+ class SceneQueryListener;
+ class ScriptCompiler;
+ class ScriptCompilerManager;
+ class ScriptLoader;
+ class Serializer;
+ class ShadowCaster;
+ class ShadowRenderable;
+ class ShadowTextureManager;
+ class SimpleRenderable;
+ class SimpleSpline;
+ class Skeleton;
+ class SkeletonPtr;
+ class SkeletonInstance;
+ class SkeletonManager;
+ class Sphere;
+ class SphereSceneQuery;
+ class StaticGeometry;
+ class StringConverter;
+ class StringInterface;
+ class SubEntity;
+ class SubMesh;
+ class TagPoint;
+ class Technique;
+ class TempBlendedBufferInfo;
+ class ExternalTextureSource;
+ class TextureUnitState;
+ class Texture;
+ class TexturePtr;
+ class TextureManager;
+ class TransformKeyFrame;
+ class Timer;
+ class UserDefinedObject;
+ class Vector2;
+ class Vector3;
+ class Vector4;
+ class Viewport;
+ class VertexAnimationTrack;
+ class VertexBufferBinding;
+ class VertexData;
+ class VertexDeclaration;
+ class VertexMorphKeyFrame;
+ class WireBoundingBox;
+ class Compositor;
+ class CompositorManager;
+ class CompositorChain;
+ class CompositorInstance;
+ class CompositionTechnique;
+ class CompositionPass;
+ class CompositionTargetPass;
+}
+
+#endif // __OgrePrerequisites_H__
+
+
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgrePrerequisites.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,615 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+// NOTE THAT THIS FILE IS BASED ON MATERIAL FROM:
+
+// Magic Software, Inc.
+// http://www.geometrictools.com
+// Copyright (c) 2000, All Rights Reserved
+//
+// Source code from Magic Software is supplied under the terms of a license
+// agreement and may not be copied or disclosed except in accordance with the
+// terms of that agreement. The various license agreements may be found at
+// the Magic Software web site. This file is subject to the license
+//
+// FREE SOURCE CODE
+// http://www.geometrictools.com/License/WildMagic3License.pdf
+
+#include "OgreQuaternion.h"
+
+#include "OgreMath.h"
+#include "OgreMatrix3.h"
+#include "OgreVector3.h"
+
+namespace Ogre {
+
+ const Real Quaternion::ms_fEpsilon = 1e-03;
+ const Quaternion Quaternion::ZERO(0.0,0.0,0.0,0.0);
+ const Quaternion Quaternion::IDENTITY(1.0,0.0,0.0,0.0);
+
+ //-----------------------------------------------------------------------
+ void Quaternion::FromRotationMatrix (const Matrix3& kRot)
+ {
+ // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
+ // article "Quaternion Calculus and Fast Animation".
+
+ Real fTrace = kRot[0][0]+kRot[1][1]+kRot[2][2];
+ Real fRoot;
+
+ if ( fTrace > 0.0 )
+ {
+ // |w| > 1/2, may as well choose w > 1/2
+ fRoot = Math::Sqrt(fTrace + 1.0); // 2w
+ w = 0.5*fRoot;
+ fRoot = 0.5/fRoot; // 1/(4w)
+ x = (kRot[2][1]-kRot[1][2])*fRoot;
+ y = (kRot[0][2]-kRot[2][0])*fRoot;
+ z = (kRot[1][0]-kRot[0][1])*fRoot;
+ }
+ else
+ {
+ // |w| <= 1/2
+ static size_t s_iNext[3] = { 1, 2, 0 };
+ size_t i = 0;
+ if ( kRot[1][1] > kRot[0][0] )
+ i = 1;
+ if ( kRot[2][2] > kRot[i][i] )
+ i = 2;
+ size_t j = s_iNext[i];
+ size_t k = s_iNext[j];
+
+ fRoot = Math::Sqrt(kRot[i][i]-kRot[j][j]-kRot[k][k] + 1.0);
+ Real* apkQuat[3] = { &x, &y, &z };
+ *apkQuat[i] = 0.5*fRoot;
+ fRoot = 0.5/fRoot;
+ w = (kRot[k][j]-kRot[j][k])*fRoot;
+ *apkQuat[j] = (kRot[j][i]+kRot[i][j])*fRoot;
+ *apkQuat[k] = (kRot[k][i]+kRot[i][k])*fRoot;
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::ToRotationMatrix (Matrix3& kRot) const
+ {
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwx = fTx*w;
+ Real fTwy = fTy*w;
+ Real fTwz = fTz*w;
+ Real fTxx = fTx*x;
+ Real fTxy = fTy*x;
+ Real fTxz = fTz*x;
+ Real fTyy = fTy*y;
+ Real fTyz = fTz*y;
+ Real fTzz = fTz*z;
+
+ kRot[0][0] = 1.0-(fTyy+fTzz);
+ kRot[0][1] = fTxy-fTwz;
+ kRot[0][2] = fTxz+fTwy;
+ kRot[1][0] = fTxy+fTwz;
+ kRot[1][1] = 1.0-(fTxx+fTzz);
+ kRot[1][2] = fTyz-fTwx;
+ kRot[2][0] = fTxz-fTwy;
+ kRot[2][1] = fTyz+fTwx;
+ kRot[2][2] = 1.0-(fTxx+fTyy);
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::FromAngleAxis (const Radian& rfAngle,
+ const Vector3& rkAxis)
+ {
+ // assert: axis[] is unit length
+ //
+ // The quaternion representing the rotation is
+ // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
+
+ Radian fHalfAngle ( 0.5*rfAngle );
+ Real fSin = Math::Sin(fHalfAngle);
+ w = Math::Cos(fHalfAngle);
+ x = fSin*rkAxis.x;
+ y = fSin*rkAxis.y;
+ z = fSin*rkAxis.z;
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::ToAngleAxis (Radian& rfAngle, Vector3& rkAxis) const
+ {
+ // The quaternion representing the rotation is
+ // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
+
+ Real fSqrLength = x*x+y*y+z*z;
+ if ( fSqrLength > 0.0 )
+ {
+ rfAngle = 2.0*Math::ACos(w);
+ Real fInvLength = Math::InvSqrt(fSqrLength);
+ rkAxis.x = x*fInvLength;
+ rkAxis.y = y*fInvLength;
+ rkAxis.z = z*fInvLength;
+ }
+ else
+ {
+ // angle is 0 (mod 2*pi), so any axis will do
+ rfAngle = Radian(0.0);
+ rkAxis.x = 1.0;
+ rkAxis.y = 0.0;
+ rkAxis.z = 0.0;
+ }
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::FromAxes (const Vector3* akAxis)
+ {
+ Matrix3 kRot;
+
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ kRot[0][iCol] = akAxis[iCol].x;
+ kRot[1][iCol] = akAxis[iCol].y;
+ kRot[2][iCol] = akAxis[iCol].z;
+ }
+
+ FromRotationMatrix(kRot);
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::FromAxes (const Vector3& xaxis, const Vector3& yaxis, const Vector3& zaxis)
+ {
+ Matrix3 kRot;
+
+ kRot[0][0] = xaxis.x;
+ kRot[1][0] = xaxis.y;
+ kRot[2][0] = xaxis.z;
+
+ kRot[0][1] = yaxis.x;
+ kRot[1][1] = yaxis.y;
+ kRot[2][1] = yaxis.z;
+
+ kRot[0][2] = zaxis.x;
+ kRot[1][2] = zaxis.y;
+ kRot[2][2] = zaxis.z;
+
+ FromRotationMatrix(kRot);
+
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::ToAxes (Vector3* akAxis) const
+ {
+ Matrix3 kRot;
+
+ ToRotationMatrix(kRot);
+
+ for (size_t iCol = 0; iCol < 3; iCol++)
+ {
+ akAxis[iCol].x = kRot[0][iCol];
+ akAxis[iCol].y = kRot[1][iCol];
+ akAxis[iCol].z = kRot[2][iCol];
+ }
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Quaternion::xAxis(void) const
+ {
+ //Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwy = fTy*w;
+ Real fTwz = fTz*w;
+ Real fTxy = fTy*x;
+ Real fTxz = fTz*x;
+ Real fTyy = fTy*y;
+ Real fTzz = fTz*z;
+
+ return Vector3(1.0-(fTyy+fTzz), fTxy+fTwz, fTxz-fTwy);
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Quaternion::yAxis(void) const
+ {
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwx = fTx*w;
+ Real fTwz = fTz*w;
+ Real fTxx = fTx*x;
+ Real fTxy = fTy*x;
+ Real fTyz = fTz*y;
+ Real fTzz = fTz*z;
+
+ return Vector3(fTxy-fTwz, 1.0-(fTxx+fTzz), fTyz+fTwx);
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Quaternion::zAxis(void) const
+ {
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwx = fTx*w;
+ Real fTwy = fTy*w;
+ Real fTxx = fTx*x;
+ Real fTxz = fTz*x;
+ Real fTyy = fTy*y;
+ Real fTyz = fTz*y;
+
+ return Vector3(fTxz+fTwy, fTyz-fTwx, 1.0-(fTxx+fTyy));
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::ToAxes (Vector3& xaxis, Vector3& yaxis, Vector3& zaxis) const
+ {
+ Matrix3 kRot;
+
+ ToRotationMatrix(kRot);
+
+ xaxis.x = kRot[0][0];
+ xaxis.y = kRot[1][0];
+ xaxis.z = kRot[2][0];
+
+ yaxis.x = kRot[0][1];
+ yaxis.y = kRot[1][1];
+ yaxis.z = kRot[2][1];
+
+ zaxis.x = kRot[0][2];
+ zaxis.y = kRot[1][2];
+ zaxis.z = kRot[2][2];
+ }
+
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::operator+ (const Quaternion& rkQ) const
+ {
+ return Quaternion(w+rkQ.w,x+rkQ.x,y+rkQ.y,z+rkQ.z);
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::operator- (const Quaternion& rkQ) const
+ {
+ return Quaternion(w-rkQ.w,x-rkQ.x,y-rkQ.y,z-rkQ.z);
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::operator* (const Quaternion& rkQ) const
+ {
+ // NOTE: Multiplication is not generally commutative, so in most
+ // cases p*q != q*p.
+
+ return Quaternion
+ (
+ w * rkQ.w - x * rkQ.x - y * rkQ.y - z * rkQ.z,
+ w * rkQ.x + x * rkQ.w + y * rkQ.z - z * rkQ.y,
+ w * rkQ.y + y * rkQ.w + z * rkQ.x - x * rkQ.z,
+ w * rkQ.z + z * rkQ.w + x * rkQ.y - y * rkQ.x
+ );
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::operator* (Real fScalar) const
+ {
+ return Quaternion(fScalar*w,fScalar*x,fScalar*y,fScalar*z);
+ }
+ //-----------------------------------------------------------------------
+ Quaternion operator* (Real fScalar, const Quaternion& rkQ)
+ {
+ return Quaternion(fScalar*rkQ.w,fScalar*rkQ.x,fScalar*rkQ.y,
+ fScalar*rkQ.z);
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::operator- () const
+ {
+ return Quaternion(-w,-x,-y,-z);
+ }
+ //-----------------------------------------------------------------------
+ Real Quaternion::Dot (const Quaternion& rkQ) const
+ {
+ return w*rkQ.w+x*rkQ.x+y*rkQ.y+z*rkQ.z;
+ }
+ //-----------------------------------------------------------------------
+ Real Quaternion::Norm () const
+ {
+ return w*w+x*x+y*y+z*z;
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::Inverse () const
+ {
+ Real fNorm = w*w+x*x+y*y+z*z;
+ if ( fNorm > 0.0 )
+ {
+ Real fInvNorm = 1.0/fNorm;
+ return Quaternion(w*fInvNorm,-x*fInvNorm,-y*fInvNorm,-z*fInvNorm);
+ }
+ else
+ {
+ // return an invalid result to flag the error
+ return ZERO;
+ }
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::UnitInverse () const
+ {
+ // assert: 'this' is unit length
+ return Quaternion(w,-x,-y,-z);
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::Exp () const
+ {
+ // If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then
+ // exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k). If sin(A) is near zero,
+ // use exp(q) = cos(A)+A*(x*i+y*j+z*k) since A/sin(A) has limit 1.
+
+ Radian fAngle ( Math::Sqrt(x*x+y*y+z*z) );
+ Real fSin = Math::Sin(fAngle);
+
+ Quaternion kResult;
+ kResult.w = Math::Cos(fAngle);
+
+ if ( Math::Abs(fSin) >= ms_fEpsilon )
+ {
+ Real fCoeff = fSin/(fAngle.valueRadians());
+ kResult.x = fCoeff*x;
+ kResult.y = fCoeff*y;
+ kResult.z = fCoeff*z;
+ }
+ else
+ {
+ kResult.x = x;
+ kResult.y = y;
+ kResult.z = z;
+ }
+
+ return kResult;
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::Log () const
+ {
+ // If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then
+ // log(q) = A*(x*i+y*j+z*k). If sin(A) is near zero, use log(q) =
+ // sin(A)*(x*i+y*j+z*k) since sin(A)/A has limit 1.
+
+ Quaternion kResult;
+ kResult.w = 0.0;
+
+ if ( Math::Abs(w) < 1.0 )
+ {
+ Radian fAngle ( Math::ACos(w) );
+ Real fSin = Math::Sin(fAngle);
+ if ( Math::Abs(fSin) >= ms_fEpsilon )
+ {
+ Real fCoeff = fAngle.valueRadians()/fSin;
+ kResult.x = fCoeff*x;
+ kResult.y = fCoeff*y;
+ kResult.z = fCoeff*z;
+ return kResult;
+ }
+ }
+
+ kResult.x = x;
+ kResult.y = y;
+ kResult.z = z;
+
+ return kResult;
+ }
+ //-----------------------------------------------------------------------
+ Vector3 Quaternion::operator* (const Vector3& v) const
+ {
+ // nVidia SDK implementation
+ Vector3 uv, uuv;
+ Vector3 qvec(x, y, z);
+ uv = qvec.crossProduct(v);
+ uuv = qvec.crossProduct(uv);
+ uv *= (2.0f * w);
+ uuv *= 2.0f;
+
+ return v + uv + uuv;
+
+ }
+ //-----------------------------------------------------------------------
+ bool Quaternion::equals(const Quaternion& rhs, const Radian& tolerance) const
+ {
+ Real fCos = Dot(rhs);
+ Radian angle = Math::ACos(fCos);
+
+ return (Math::Abs(angle.valueRadians()) <= tolerance.valueRadians())
+ || Math::RealEqual(angle.valueRadians(), Math::PI, tolerance.valueRadians());
+
+
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::Slerp (Real fT, const Quaternion& rkP,
+ const Quaternion& rkQ, bool shortestPath)
+ {
+ Real fCos = rkP.Dot(rkQ);
+ Quaternion rkT;
+
+ // Do we need to invert rotation?
+ if (fCos < 0.0f && shortestPath)
+ {
+ fCos = -fCos;
+ rkT = -rkQ;
+ }
+ else
+ {
+ rkT = rkQ;
+ }
+
+ if (Math::Abs(fCos) < 1 - ms_fEpsilon)
+ {
+ // Standard case (slerp)
+ Real fSin = Math::Sqrt(1 - Math::Sqr(fCos));
+ Radian fAngle = Math::ATan2(fSin, fCos);
+ Real fInvSin = 1.0f / fSin;
+ Real fCoeff0 = Math::Sin((1.0f - fT) * fAngle) * fInvSin;
+ Real fCoeff1 = Math::Sin(fT * fAngle) * fInvSin;
+ return fCoeff0 * rkP + fCoeff1 * rkT;
+ }
+ else
+ {
+ // There are two situations:
+ // 1. "rkP" and "rkQ" are very close (fCos ~= +1), so we can do a linear
+ // interpolation safely.
+ // 2. "rkP" and "rkQ" are almost inverse of each other (fCos ~= -1), there
+ // are an infinite number of possibilities interpolation. but we haven't
+ // have method to fix this case, so just use linear interpolation here.
+ Quaternion t = (1.0f - fT) * rkP + fT * rkT;
+ // taking the complement requires renormalisation
+ t.normalise();
+ return t;
+ }
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::SlerpExtraSpins (Real fT,
+ const Quaternion& rkP, const Quaternion& rkQ, int iExtraSpins)
+ {
+ Real fCos = rkP.Dot(rkQ);
+ Radian fAngle ( Math::ACos(fCos) );
+
+ if ( Math::Abs(fAngle.valueRadians()) < ms_fEpsilon )
+ return rkP;
+
+ Real fSin = Math::Sin(fAngle);
+ Radian fPhase ( Math::PI*iExtraSpins*fT );
+ Real fInvSin = 1.0/fSin;
+ Real fCoeff0 = Math::Sin((1.0-fT)*fAngle - fPhase)*fInvSin;
+ Real fCoeff1 = Math::Sin(fT*fAngle + fPhase)*fInvSin;
+ return fCoeff0*rkP + fCoeff1*rkQ;
+ }
+ //-----------------------------------------------------------------------
+ void Quaternion::Intermediate (const Quaternion& rkQ0,
+ const Quaternion& rkQ1, const Quaternion& rkQ2,
+ Quaternion& rkA, Quaternion& rkB)
+ {
+ // assert: q0, q1, q2 are unit quaternions
+
+ Quaternion kQ0inv = rkQ0.UnitInverse();
+ Quaternion kQ1inv = rkQ1.UnitInverse();
+ Quaternion rkP0 = kQ0inv*rkQ1;
+ Quaternion rkP1 = kQ1inv*rkQ2;
+ Quaternion kArg = 0.25*(rkP0.Log()-rkP1.Log());
+ Quaternion kMinusArg = -kArg;
+
+ rkA = rkQ1*kArg.Exp();
+ rkB = rkQ1*kMinusArg.Exp();
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::Squad (Real fT,
+ const Quaternion& rkP, const Quaternion& rkA,
+ const Quaternion& rkB, const Quaternion& rkQ, bool shortestPath)
+ {
+ Real fSlerpT = 2.0*fT*(1.0-fT);
+ Quaternion kSlerpP = Slerp(fT, rkP, rkQ, shortestPath);
+ Quaternion kSlerpQ = Slerp(fT, rkA, rkB);
+ return Slerp(fSlerpT, kSlerpP ,kSlerpQ);
+ }
+ //-----------------------------------------------------------------------
+ Real Quaternion::normalise(void)
+ {
+ Real len = Norm();
+ Real factor = 1.0f / Math::Sqrt(len);
+ *this = *this * factor;
+ return len;
+ }
+ //-----------------------------------------------------------------------
+ Radian Quaternion::getRoll(bool reprojectAxis) const
+ {
+ if (reprojectAxis)
+ {
+ // roll = atan2(localx.y, localx.x)
+ // pick parts of xAxis() implementation that we need
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwz = fTz*w;
+ Real fTxy = fTy*x;
+ Real fTyy = fTy*y;
+ Real fTzz = fTz*z;
+
+ // Vector3(1.0-(fTyy+fTzz), fTxy+fTwz, fTxz-fTwy);
+
+ return Radian(Math::ATan2(fTxy+fTwz, 1.0-(fTyy+fTzz)));
+
+ }
+ else
+ {
+ return Radian(Math::ATan2(2*(x*y + w*z), w*w + x*x - y*y - z*z));
+ }
+ }
+ //-----------------------------------------------------------------------
+ Radian Quaternion::getPitch(bool reprojectAxis) const
+ {
+ if (reprojectAxis)
+ {
+ // pitch = atan2(localy.z, localy.y)
+ // pick parts of yAxis() implementation that we need
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwx = fTx*w;
+ Real fTxx = fTx*x;
+ Real fTyz = fTz*y;
+ Real fTzz = fTz*z;
+
+ // Vector3(fTxy-fTwz, 1.0-(fTxx+fTzz), fTyz+fTwx);
+ return Radian(Math::ATan2(fTyz+fTwx, 1.0-(fTxx+fTzz)));
+ }
+ else
+ {
+ // internal version
+ return Radian(Math::ATan2(2*(y*z + w*x), w*w - x*x - y*y + z*z));
+ }
+ }
+ //-----------------------------------------------------------------------
+ Radian Quaternion::getYaw(bool reprojectAxis) const
+ {
+ if (reprojectAxis)
+ {
+ // yaw = atan2(localz.x, localz.z)
+ // pick parts of zAxis() implementation that we need
+ Real fTx = 2.0*x;
+ Real fTy = 2.0*y;
+ Real fTz = 2.0*z;
+ Real fTwy = fTy*w;
+ Real fTxx = fTx*x;
+ Real fTxz = fTz*x;
+ Real fTyy = fTy*y;
+
+ // Vector3(fTxz+fTwy, fTyz-fTwx, 1.0-(fTxx+fTyy));
+
+ return Radian(Math::ATan2(fTxz+fTwy, 1.0-(fTxx+fTyy)));
+
+ }
+ else
+ {
+ // internal version
+ return Radian(Math::ASin(-2*(x*z - w*y)));
+ }
+ }
+ //-----------------------------------------------------------------------
+ Quaternion Quaternion::nlerp(Real fT, const Quaternion& rkP,
+ const Quaternion& rkQ, bool shortestPath)
+ {
+ Quaternion result;
+ Real fCos = rkP.Dot(rkQ);
+ if (fCos < 0.0f && shortestPath)
+ {
+ result = rkP + fT * ((-rkQ) - rkP);
+ }
+ else
+ {
+ result = rkP + fT * (rkQ - rkP);
+ }
+ result.normalise();
+ return result;
+ }
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,257 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+// NOTE THAT THIS FILE IS BASED ON MATERIAL FROM:
+
+// Magic Software, Inc.
+// http://www.geometrictools.com/
+// Copyright (c) 2000, All Rights Reserved
+//
+// Source code from Magic Software is supplied under the terms of a license
+// agreement and may not be copied or disclosed except in accordance with the
+// terms of that agreement. The various license agreements may be found at
+// the Magic Software web site. This file is subject to the license
+//
+// FREE SOURCE CODE
+// http://www.geometrictools.com/License/WildMagic3License.pdf
+
+#ifndef __Quaternion_H__
+#define __Quaternion_H__
+
+#include "OgrePrerequisites.h"
+
+#include <cassert>
+#include "OgreMath.h"
+#include <ostream>
+
+namespace Ogre {
+
+ /** Implementation of a Quaternion, i.e. a rotation around an axis.
+ */
+ class _OgreExport Quaternion
+ {
+ public:
+ inline Quaternion (
+ Real fW = 1.0,
+ Real fX = 0.0, Real fY = 0.0, Real fZ = 0.0)
+ {
+ w = fW;
+ x = fX;
+ y = fY;
+ z = fZ;
+ }
+ /// Construct a quaternion from a rotation matrix
+ inline Quaternion(const Matrix3& rot)
+ {
+ this->FromRotationMatrix(rot);
+ }
+ /// Construct a quaternion from an angle/axis
+ inline Quaternion(const Radian& rfAngle, const Vector3& rkAxis)
+ {
+ this->FromAngleAxis(rfAngle, rkAxis);
+ }
+ /// Construct a quaternion from 3 orthonormal local axes
+ inline Quaternion(const Vector3& xaxis, const Vector3& yaxis, const Vector3& zaxis)
+ {
+ this->FromAxes(xaxis, yaxis, zaxis);
+ }
+ /// Construct a quaternion from 3 orthonormal local axes
+ inline Quaternion(const Vector3* akAxis)
+ {
+ this->FromAxes(akAxis);
+ }
+ /// Construct a quaternion from 4 manual w/x/y/z values
+ inline Quaternion(Real* valptr)
+ {
+ memcpy(&w, valptr, sizeof(Real)*4);
+ }
+
+ /// Array accessor operator
+ inline Real operator [] ( const size_t i ) const
+ {
+ assert( i < 4 );
+
+ return *(&w+i);
+ }
+
+ /// Array accessor operator
+ inline Real& operator [] ( const size_t i )
+ {
+ assert( i < 4 );
+
+ return *(&w+i);
+ }
+
+ /// Pointer accessor for direct copying
+ inline Real* ptr()
+ {
+ return &w;
+ }
+
+ /// Pointer accessor for direct copying
+ inline const Real* ptr() const
+ {
+ return &w;
+ }
+
+ void FromRotationMatrix (const Matrix3& kRot);
+ void ToRotationMatrix (Matrix3& kRot) const;
+ void FromAngleAxis (const Radian& rfAngle, const Vector3& rkAxis);
+ void ToAngleAxis (Radian& rfAngle, Vector3& rkAxis) const;
+ inline void ToAngleAxis (Degree& dAngle, Vector3& rkAxis) const {
+ Radian rAngle;
+ ToAngleAxis ( rAngle, rkAxis );
+ dAngle = rAngle;
+ }
+ void FromAxes (const Vector3* akAxis);
+ void FromAxes (const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis);
+ void ToAxes (Vector3* akAxis) const;
+ void ToAxes (Vector3& xAxis, Vector3& yAxis, Vector3& zAxis) const;
+ /// Get the local x-axis
+ Vector3 xAxis(void) const;
+ /// Get the local y-axis
+ Vector3 yAxis(void) const;
+ /// Get the local z-axis
+ Vector3 zAxis(void) const;
+
+ inline Quaternion& operator= (const Quaternion& rkQ)
+ {
+ w = rkQ.w;
+ x = rkQ.x;
+ y = rkQ.y;
+ z = rkQ.z;
+ return *this;
+ }
+ Quaternion operator+ (const Quaternion& rkQ) const;
+ Quaternion operator- (const Quaternion& rkQ) const;
+ Quaternion operator* (const Quaternion& rkQ) const;
+ Quaternion operator* (Real fScalar) const;
+ _OgreExport friend Quaternion operator* (Real fScalar,
+ const Quaternion& rkQ);
+ Quaternion operator- () const;
+ inline bool operator== (const Quaternion& rhs) const
+ {
+ return (rhs.x == x) && (rhs.y == y) &&
+ (rhs.z == z) && (rhs.w == w);
+ }
+ inline bool operator!= (const Quaternion& rhs) const
+ {
+ return !operator==(rhs);
+ }
+ // functions of a quaternion
+ Real Dot (const Quaternion& rkQ) const; // dot product
+ Real Norm () const; // squared-length
+ /// Normalises this quaternion, and returns the previous length
+ Real normalise(void);
+ Quaternion Inverse () const; // apply to non-zero quaternion
+ Quaternion UnitInverse () const; // apply to unit-length quaternion
+ Quaternion Exp () const;
+ Quaternion Log () const;
+
+ // rotation of a vector by a quaternion
+ Vector3 operator* (const Vector3& rkVector) const;
+
+ /** Calculate the local roll element of this quaternion.
+ @param reprojectAxis By default the method returns the 'intuitive' result
+ that is, if you projected the local Y of the quaternion onto the X and
+ Y axes, the angle between them is returned. If set to false though, the
+ result is the actual yaw that will be used to implement the quaternion,
+ which is the shortest possible path to get to the same orientation and
+ may involve less axial rotation.
+ */
+ Radian getRoll(bool reprojectAxis = true) const;
+ /** Calculate the local pitch element of this quaternion
+ @param reprojectAxis By default the method returns the 'intuitive' result
+ that is, if you projected the local Z of the quaternion onto the X and
+ Y axes, the angle between them is returned. If set to true though, the
+ result is the actual yaw that will be used to implement the quaternion,
+ which is the shortest possible path to get to the same orientation and
+ may involve less axial rotation.
+ */
+ Radian getPitch(bool reprojectAxis = true) const;
+ /** Calculate the local yaw element of this quaternion
+ @param reprojectAxis By default the method returns the 'intuitive' result
+ that is, if you projected the local Z of the quaternion onto the X and
+ Z axes, the angle between them is returned. If set to true though, the
+ result is the actual yaw that will be used to implement the quaternion,
+ which is the shortest possible path to get to the same orientation and
+ may involve less axial rotation.
+ */
+ Radian getYaw(bool reprojectAxis = true) const;
+ /// Equality with tolerance (tolerance is max angle difference)
+ bool equals(const Quaternion& rhs, const Radian& tolerance) const;
+
+ // spherical linear interpolation
+ static Quaternion Slerp (Real fT, const Quaternion& rkP,
+ const Quaternion& rkQ, bool shortestPath = false);
+
+ static Quaternion SlerpExtraSpins (Real fT,
+ const Quaternion& rkP, const Quaternion& rkQ,
+ int iExtraSpins);
+
+ // setup for spherical quadratic interpolation
+ static void Intermediate (const Quaternion& rkQ0,
+ const Quaternion& rkQ1, const Quaternion& rkQ2,
+ Quaternion& rka, Quaternion& rkB);
+
+ // spherical quadratic interpolation
+ static Quaternion Squad (Real fT, const Quaternion& rkP,
+ const Quaternion& rkA, const Quaternion& rkB,
+ const Quaternion& rkQ, bool shortestPath = false);
+
+ // normalised linear interpolation - faster but less accurate (non-constant rotation velocity)
+ static Quaternion nlerp(Real fT, const Quaternion& rkP,
+ const Quaternion& rkQ, bool shortestPath = false);
+
+ // cutoff for sine near zero
+ static const Real ms_fEpsilon;
+
+ // special values
+ static const Quaternion ZERO;
+ static const Quaternion IDENTITY;
+
+ Real w, x, y, z;
+
+ /** Function for writing to a stream. Outputs "Quaternion(w, x, y, z)" with w,x,y,z
+ being the member values of the quaternion.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const Quaternion& q )
+ {
+ o << "Quaternion(" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ")";
+ return o;
+ }
+
+ };
+
+}
+
+
+
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreQuaternion.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreTimer.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreTimer.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreTimer.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,44 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __OgreCommonTimer_H__
+#define __OgreCommonTimer_H__
+
+#include "OgrePrerequisites.h"
+#include "OgrePlatform.h"
+
+//Bring in the specific platform's header file
+#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
+# include "WIN32/OgreTimerImp.h"
+#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
+# include "GLX/OgreTimerImp.h"
+#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
+# include "OSX/OgreTimerImp.h"
+#endif
+
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreTimer.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector2.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector2.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector2.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,43 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+
+#include "OgreVector2.h"
+#include "OgreMath.h"
+
+namespace Ogre
+{
+ const Vector2 Vector2::ZERO( 0, 0);
+
+ const Vector2 Vector2::UNIT_X( 1, 0);
+ const Vector2 Vector2::UNIT_Y( 0, 1);
+ const Vector2 Vector2::NEGATIVE_UNIT_X( -1, 0);
+ const Vector2 Vector2::NEGATIVE_UNIT_Y( 0, -1);
+ const Vector2 Vector2::UNIT_SCALE(1, 1);
+
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector2.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector2.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector2.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector2.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,528 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Vector2_H__
+#define __Vector2_H__
+
+
+#include "OgrePrerequisites.h"
+#include "OgreMath.h"
+#include <ostream>
+
+namespace Ogre
+{
+
+ /** Standard 2-dimensional vector.
+ @remarks
+ A direction in 2D space represented as distances along the 2
+ orthogonal axes (x, y). Note that positions, directions and
+ scaling factors can be represented by a vector, depending on how
+ you interpret the values.
+ */
+ class _OgreExport Vector2
+ {
+ public:
+ Real x, y;
+
+ public:
+ inline Vector2()
+ {
+ }
+
+ inline Vector2(const Real fX, const Real fY )
+ : x( fX ), y( fY )
+ {
+ }
+
+ inline explicit Vector2( const Real scaler )
+ : x( scaler), y( scaler )
+ {
+ }
+
+ inline explicit Vector2( const Real afCoordinate[2] )
+ : x( afCoordinate[0] ),
+ y( afCoordinate[1] )
+ {
+ }
+
+ inline explicit Vector2( const int afCoordinate[2] )
+ {
+ x = (Real)afCoordinate[0];
+ y = (Real)afCoordinate[1];
+ }
+
+ inline explicit Vector2( Real* const r )
+ : x( r[0] ), y( r[1] )
+ {
+ }
+
+ inline Real operator [] ( const size_t i ) const
+ {
+ assert( i < 2 );
+
+ return *(&x+i);
+ }
+
+ inline Real& operator [] ( const size_t i )
+ {
+ assert( i < 2 );
+
+ return *(&x+i);
+ }
+
+ /// Pointer accessor for direct copying
+ inline Real* ptr()
+ {
+ return &x;
+ }
+ /// Pointer accessor for direct copying
+ inline const Real* ptr() const
+ {
+ return &x;
+ }
+
+ /** Assigns the value of the other vector.
+ @param
+ rkVector The other vector
+ */
+ inline Vector2& operator = ( const Vector2& rkVector )
+ {
+ x = rkVector.x;
+ y = rkVector.y;
+
+ return *this;
+ }
+
+ inline Vector2& operator = ( const Real fScalar)
+ {
+ x = fScalar;
+ y = fScalar;
+
+ return *this;
+ }
+
+ inline bool operator == ( const Vector2& rkVector ) const
+ {
+ return ( x == rkVector.x && y == rkVector.y );
+ }
+
+ inline bool operator != ( const Vector2& rkVector ) const
+ {
+ return ( x != rkVector.x || y != rkVector.y );
+ }
+
+ // arithmetic operations
+ inline Vector2 operator + ( const Vector2& rkVector ) const
+ {
+ return Vector2(
+ x + rkVector.x,
+ y + rkVector.y);
+ }
+
+ inline Vector2 operator - ( const Vector2& rkVector ) const
+ {
+ return Vector2(
+ x - rkVector.x,
+ y - rkVector.y);
+ }
+
+ inline Vector2 operator * ( const Real fScalar ) const
+ {
+ return Vector2(
+ x * fScalar,
+ y * fScalar);
+ }
+
+ inline Vector2 operator * ( const Vector2& rhs) const
+ {
+ return Vector2(
+ x * rhs.x,
+ y * rhs.y);
+ }
+
+ inline Vector2 operator / ( const Real fScalar ) const
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ return Vector2(
+ x * fInv,
+ y * fInv);
+ }
+
+ inline Vector2 operator / ( const Vector2& rhs) const
+ {
+ return Vector2(
+ x / rhs.x,
+ y / rhs.y);
+ }
+
+ inline const Vector2& operator + () const
+ {
+ return *this;
+ }
+
+ inline Vector2 operator - () const
+ {
+ return Vector2(-x, -y);
+ }
+
+ // overloaded operators to help Vector2
+ inline friend Vector2 operator * ( const Real fScalar, const Vector2& rkVector )
+ {
+ return Vector2(
+ fScalar * rkVector.x,
+ fScalar * rkVector.y);
+ }
+
+ inline friend Vector2 operator / ( const Real fScalar, const Vector2& rkVector )
+ {
+ return Vector2(
+ fScalar / rkVector.x,
+ fScalar / rkVector.y);
+ }
+
+ inline friend Vector2 operator + (const Vector2& lhs, const Real rhs)
+ {
+ return Vector2(
+ lhs.x + rhs,
+ lhs.y + rhs);
+ }
+
+ inline friend Vector2 operator + (const Real lhs, const Vector2& rhs)
+ {
+ return Vector2(
+ lhs + rhs.x,
+ lhs + rhs.y);
+ }
+
+ inline friend Vector2 operator - (const Vector2& lhs, const Real rhs)
+ {
+ return Vector2(
+ lhs.x - rhs,
+ lhs.y - rhs);
+ }
+
+ inline friend Vector2 operator - (const Real lhs, const Vector2& rhs)
+ {
+ return Vector2(
+ lhs - rhs.x,
+ lhs - rhs.y);
+ }
+ // arithmetic updates
+ inline Vector2& operator += ( const Vector2& rkVector )
+ {
+ x += rkVector.x;
+ y += rkVector.y;
+
+ return *this;
+ }
+
+ inline Vector2& operator += ( const Real fScaler )
+ {
+ x += fScaler;
+ y += fScaler;
+
+ return *this;
+ }
+
+ inline Vector2& operator -= ( const Vector2& rkVector )
+ {
+ x -= rkVector.x;
+ y -= rkVector.y;
+
+ return *this;
+ }
+
+ inline Vector2& operator -= ( const Real fScaler )
+ {
+ x -= fScaler;
+ y -= fScaler;
+
+ return *this;
+ }
+
+ inline Vector2& operator *= ( const Real fScalar )
+ {
+ x *= fScalar;
+ y *= fScalar;
+
+ return *this;
+ }
+
+ inline Vector2& operator *= ( const Vector2& rkVector )
+ {
+ x *= rkVector.x;
+ y *= rkVector.y;
+
+ return *this;
+ }
+
+ inline Vector2& operator /= ( const Real fScalar )
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ x *= fInv;
+ y *= fInv;
+
+ return *this;
+ }
+
+ inline Vector2& operator /= ( const Vector2& rkVector )
+ {
+ x /= rkVector.x;
+ y /= rkVector.y;
+
+ return *this;
+ }
+
+ /** Returns the length (magnitude) of the vector.
+ @warning
+ This operation requires a square root and is expensive in
+ terms of CPU operations. If you don't need to know the exact
+ length (e.g. for just comparing lengths) use squaredLength()
+ instead.
+ */
+ inline Real length () const
+ {
+ return Math::Sqrt( x * x + y * y );
+ }
+
+ /** Returns the square of the length(magnitude) of the vector.
+ @remarks
+ This method is for efficiency - calculating the actual
+ length of a vector requires a square root, which is expensive
+ in terms of the operations required. This method returns the
+ square of the length of the vector, i.e. the same as the
+ length but before the square root is taken. Use this if you
+ want to find the longest / shortest vector without incurring
+ the square root.
+ */
+ inline Real squaredLength () const
+ {
+ return x * x + y * y;
+ }
+
+ /** Calculates the dot (scalar) product of this vector with another.
+ @remarks
+ The dot product can be used to calculate the angle between 2
+ vectors. If both are unit vectors, the dot product is the
+ cosine of the angle; otherwise the dot product must be
+ divided by the product of the lengths of both vectors to get
+ the cosine of the angle. This result can further be used to
+ calculate the distance of a point from a plane.
+ @param
+ vec Vector with which to calculate the dot product (together
+ with this one).
+ @returns
+ A float representing the dot product value.
+ */
+ inline Real dotProduct(const Vector2& vec) const
+ {
+ return x * vec.x + y * vec.y;
+ }
+
+ /** Normalises the vector.
+ @remarks
+ This method normalises the vector such that it's
+ length / magnitude is 1. The result is called a unit vector.
+ @note
+ This function will not crash for zero-sized vectors, but there
+ will be no changes made to their components.
+ @returns The previous length of the vector.
+ */
+ inline Real normalise()
+ {
+ Real fLength = Math::Sqrt( x * x + y * y);
+
+ // Will also work for zero-sized vectors, but will change nothing
+ if ( fLength > 1e-08 )
+ {
+ Real fInvLength = 1.0 / fLength;
+ x *= fInvLength;
+ y *= fInvLength;
+ }
+
+ return fLength;
+ }
+
+
+
+ /** Returns a vector at a point half way between this and the passed
+ in vector.
+ */
+ inline Vector2 midPoint( const Vector2& vec ) const
+ {
+ return Vector2(
+ ( x + vec.x ) * 0.5,
+ ( y + vec.y ) * 0.5 );
+ }
+
+ /** Returns true if the vector's scalar components are all greater
+ that the ones of the vector it is compared against.
+ */
+ inline bool operator < ( const Vector2& rhs ) const
+ {
+ if( x < rhs.x && y < rhs.y )
+ return true;
+ return false;
+ }
+
+ /** Returns true if the vector's scalar components are all smaller
+ that the ones of the vector it is compared against.
+ */
+ inline bool operator > ( const Vector2& rhs ) const
+ {
+ if( x > rhs.x && y > rhs.y )
+ return true;
+ return false;
+ }
+
+ /** Sets this vector's components to the minimum of its own and the
+ ones of the passed in vector.
+ @remarks
+ 'Minimum' in this case means the combination of the lowest
+ value of x, y and z from both vectors. Lowest is taken just
+ numerically, not magnitude, so -1 < 0.
+ */
+ inline void makeFloor( const Vector2& cmp )
+ {
+ if( cmp.x < x ) x = cmp.x;
+ if( cmp.y < y ) y = cmp.y;
+ }
+
+ /** Sets this vector's components to the maximum of its own and the
+ ones of the passed in vector.
+ @remarks
+ 'Maximum' in this case means the combination of the highest
+ value of x, y and z from both vectors. Highest is taken just
+ numerically, not magnitude, so 1 > -3.
+ */
+ inline void makeCeil( const Vector2& cmp )
+ {
+ if( cmp.x > x ) x = cmp.x;
+ if( cmp.y > y ) y = cmp.y;
+ }
+
+ /** Generates a vector perpendicular to this vector (eg an 'up' vector).
+ @remarks
+ This method will return a vector which is perpendicular to this
+ vector. There are an infinite number of possibilities but this
+ method will guarantee to generate one of them. If you need more
+ control you should use the Quaternion class.
+ */
+ inline Vector2 perpendicular(void) const
+ {
+ return Vector2 (-y, x);
+ }
+ /** Calculates the 2 dimensional cross-product of 2 vectors, which results
+ in a single floating point value which is 2 times the area of the triangle.
+ */
+ inline Real crossProduct( const Vector2& rkVector ) const
+ {
+ return x * rkVector.y - y * rkVector.x;
+ }
+ /** Generates a new random vector which deviates from this vector by a
+ given angle in a random direction.
+ @remarks
+ This method assumes that the random number generator has already
+ been seeded appropriately.
+ @param
+ angle The angle at which to deviate in radians
+ @param
+ up Any vector perpendicular to this one (which could generated
+ by cross-product of this vector and any other non-colinear
+ vector). If you choose not to provide this the function will
+ derive one on it's own, however if you provide one yourself the
+ function will be faster (this allows you to reuse up vectors if
+ you call this method more than once)
+ @returns
+ A random vector which deviates from this vector by angle. This
+ vector will not be normalised, normalise it if you wish
+ afterwards.
+ */
+ inline Vector2 randomDeviant(
+ Real angle) const
+ {
+
+ angle *= Math::UnitRandom() * Math::TWO_PI;
+ Real cosa = cos(angle);
+ Real sina = sin(angle);
+ return Vector2(cosa * x - sina * y,
+ sina * x + cosa * y);
+ }
+
+ /** Returns true if this vector is zero length. */
+ inline bool isZeroLength(void) const
+ {
+ Real sqlen = (x * x) + (y * y);
+ return (sqlen < (1e-06 * 1e-06));
+
+ }
+
+ /** As normalise, except that this vector is unaffected and the
+ normalised vector is returned as a copy. */
+ inline Vector2 normalisedCopy(void) const
+ {
+ Vector2 ret = *this;
+ ret.normalise();
+ return ret;
+ }
+
+ /** Calculates a reflection vector to the plane with the given normal .
+ @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
+ */
+ inline Vector2 reflect(const Vector2& normal) const
+ {
+ return Vector2( *this - ( 2 * this->dotProduct(normal) * normal ) );
+ }
+
+ // special points
+ static const Vector2 ZERO;
+ static const Vector2 UNIT_X;
+ static const Vector2 UNIT_Y;
+ static const Vector2 NEGATIVE_UNIT_X;
+ static const Vector2 NEGATIVE_UNIT_Y;
+ static const Vector2 UNIT_SCALE;
+
+ /** Function for writing to a stream.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const Vector2& v )
+ {
+ o << "Vector2(" << v.x << ", " << v.y << ")";
+ return o;
+ }
+
+ };
+
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector2.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector3.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector3.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector3.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,43 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgreVector3.h"
+#include "OgreMath.h"
+
+namespace Ogre
+{
+ const Vector3 Vector3::ZERO( 0, 0, 0 );
+
+ const Vector3 Vector3::UNIT_X( 1, 0, 0 );
+ const Vector3 Vector3::UNIT_Y( 0, 1, 0 );
+ const Vector3 Vector3::UNIT_Z( 0, 0, 1 );
+ const Vector3 Vector3::NEGATIVE_UNIT_X( -1, 0, 0 );
+ const Vector3 Vector3::NEGATIVE_UNIT_Y( 0, -1, 0 );
+ const Vector3 Vector3::NEGATIVE_UNIT_Z( 0, 0, -1 );
+ const Vector3 Vector3::UNIT_SCALE(1, 1, 1);
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector3.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector3.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector3.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector3.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,775 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Vector3_H__
+#define __Vector3_H__
+
+#include "OgrePrerequisites.h"
+#include "OgreMath.h"
+#include "OgreQuaternion.h"
+#include <ostream>
+
+namespace Ogre
+{
+
+ /** Standard 3-dimensional vector.
+ @remarks
+ A direction in 3D space represented as distances along the 3
+ orthogonal axes (x, y, z). Note that positions, directions and
+ scaling factors can be represented by a vector, depending on how
+ you interpret the values.
+ */
+ class _OgreExport Vector3
+ {
+ public:
+ Real x, y, z;
+
+ public:
+ inline Vector3()
+ {
+ }
+
+ inline Vector3( const Real fX, const Real fY, const Real fZ )
+ : x( fX ), y( fY ), z( fZ )
+ {
+ }
+
+ inline explicit Vector3( const Real afCoordinate[3] )
+ : x( afCoordinate[0] ),
+ y( afCoordinate[1] ),
+ z( afCoordinate[2] )
+ {
+ }
+
+ inline explicit Vector3( const int afCoordinate[3] )
+ {
+ x = (Real)afCoordinate[0];
+ y = (Real)afCoordinate[1];
+ z = (Real)afCoordinate[2];
+ }
+
+ inline explicit Vector3( Real* const r )
+ : x( r[0] ), y( r[1] ), z( r[2] )
+ {
+ }
+
+ inline explicit Vector3( const Real scaler )
+ : x( scaler )
+ , y( scaler )
+ , z( scaler )
+ {
+ }
+
+
+ inline Real operator [] ( const size_t i ) const
+ {
+ assert( i < 3 );
+
+ return *(&x+i);
+ }
+
+ inline Real& operator [] ( const size_t i )
+ {
+ assert( i < 3 );
+
+ return *(&x+i);
+ }
+ /// Pointer accessor for direct copying
+ inline Real* ptr()
+ {
+ return &x;
+ }
+ /// Pointer accessor for direct copying
+ inline const Real* ptr() const
+ {
+ return &x;
+ }
+
+ /** Assigns the value of the other vector.
+ @param
+ rkVector The other vector
+ */
+ inline Vector3& operator = ( const Vector3& rkVector )
+ {
+ x = rkVector.x;
+ y = rkVector.y;
+ z = rkVector.z;
+
+ return *this;
+ }
+
+ inline Vector3& operator = ( const Real fScaler )
+ {
+ x = fScaler;
+ y = fScaler;
+ z = fScaler;
+
+ return *this;
+ }
+
+ inline bool operator == ( const Vector3& rkVector ) const
+ {
+ return ( x == rkVector.x && y == rkVector.y && z == rkVector.z );
+ }
+
+ inline bool operator != ( const Vector3& rkVector ) const
+ {
+ return ( x != rkVector.x || y != rkVector.y || z != rkVector.z );
+ }
+
+ // arithmetic operations
+ inline Vector3 operator + ( const Vector3& rkVector ) const
+ {
+ return Vector3(
+ x + rkVector.x,
+ y + rkVector.y,
+ z + rkVector.z);
+ }
+
+ inline Vector3 operator - ( const Vector3& rkVector ) const
+ {
+ return Vector3(
+ x - rkVector.x,
+ y - rkVector.y,
+ z - rkVector.z);
+ }
+
+ inline Vector3 operator * ( const Real fScalar ) const
+ {
+ return Vector3(
+ x * fScalar,
+ y * fScalar,
+ z * fScalar);
+ }
+
+ inline Vector3 operator * ( const Vector3& rhs) const
+ {
+ return Vector3(
+ x * rhs.x,
+ y * rhs.y,
+ z * rhs.z);
+ }
+
+ inline Vector3 operator / ( const Real fScalar ) const
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ return Vector3(
+ x * fInv,
+ y * fInv,
+ z * fInv);
+ }
+
+ inline Vector3 operator / ( const Vector3& rhs) const
+ {
+ return Vector3(
+ x / rhs.x,
+ y / rhs.y,
+ z / rhs.z);
+ }
+
+ inline const Vector3& operator + () const
+ {
+ return *this;
+ }
+
+ inline Vector3 operator - () const
+ {
+ return Vector3(-x, -y, -z);
+ }
+
+ // overloaded operators to help Vector3
+ inline friend Vector3 operator * ( const Real fScalar, const Vector3& rkVector )
+ {
+ return Vector3(
+ fScalar * rkVector.x,
+ fScalar * rkVector.y,
+ fScalar * rkVector.z);
+ }
+
+ inline friend Vector3 operator / ( const Real fScalar, const Vector3& rkVector )
+ {
+ return Vector3(
+ fScalar / rkVector.x,
+ fScalar / rkVector.y,
+ fScalar / rkVector.z);
+ }
+
+ inline friend Vector3 operator + (const Vector3& lhs, const Real rhs)
+ {
+ return Vector3(
+ lhs.x + rhs,
+ lhs.y + rhs,
+ lhs.z + rhs);
+ }
+
+ inline friend Vector3 operator + (const Real lhs, const Vector3& rhs)
+ {
+ return Vector3(
+ lhs + rhs.x,
+ lhs + rhs.y,
+ lhs + rhs.z);
+ }
+
+ inline friend Vector3 operator - (const Vector3& lhs, const Real rhs)
+ {
+ return Vector3(
+ lhs.x - rhs,
+ lhs.y - rhs,
+ lhs.z - rhs);
+ }
+
+ inline friend Vector3 operator - (const Real lhs, const Vector3& rhs)
+ {
+ return Vector3(
+ lhs - rhs.x,
+ lhs - rhs.y,
+ lhs - rhs.z);
+ }
+
+ // arithmetic updates
+ inline Vector3& operator += ( const Vector3& rkVector )
+ {
+ x += rkVector.x;
+ y += rkVector.y;
+ z += rkVector.z;
+
+ return *this;
+ }
+
+ inline Vector3& operator += ( const Real fScalar )
+ {
+ x += fScalar;
+ y += fScalar;
+ z += fScalar;
+ return *this;
+ }
+
+ inline Vector3& operator -= ( const Vector3& rkVector )
+ {
+ x -= rkVector.x;
+ y -= rkVector.y;
+ z -= rkVector.z;
+
+ return *this;
+ }
+
+ inline Vector3& operator -= ( const Real fScalar )
+ {
+ x -= fScalar;
+ y -= fScalar;
+ z -= fScalar;
+ return *this;
+ }
+
+ inline Vector3& operator *= ( const Real fScalar )
+ {
+ x *= fScalar;
+ y *= fScalar;
+ z *= fScalar;
+ return *this;
+ }
+
+ inline Vector3& operator *= ( const Vector3& rkVector )
+ {
+ x *= rkVector.x;
+ y *= rkVector.y;
+ z *= rkVector.z;
+
+ return *this;
+ }
+
+ inline Vector3& operator /= ( const Real fScalar )
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ x *= fInv;
+ y *= fInv;
+ z *= fInv;
+
+ return *this;
+ }
+
+ inline Vector3& operator /= ( const Vector3& rkVector )
+ {
+ x /= rkVector.x;
+ y /= rkVector.y;
+ z /= rkVector.z;
+
+ return *this;
+ }
+
+
+ /** Returns the length (magnitude) of the vector.
+ @warning
+ This operation requires a square root and is expensive in
+ terms of CPU operations. If you don't need to know the exact
+ length (e.g. for just comparing lengths) use squaredLength()
+ instead.
+ */
+ inline Real length () const
+ {
+ return Math::Sqrt( x * x + y * y + z * z );
+ }
+
+ /** Returns the square of the length(magnitude) of the vector.
+ @remarks
+ This method is for efficiency - calculating the actual
+ length of a vector requires a square root, which is expensive
+ in terms of the operations required. This method returns the
+ square of the length of the vector, i.e. the same as the
+ length but before the square root is taken. Use this if you
+ want to find the longest / shortest vector without incurring
+ the square root.
+ */
+ inline Real squaredLength () const
+ {
+ return x * x + y * y + z * z;
+ }
+
+ /** Returns the distance to another vector.
+ @warning
+ This operation requires a square root and is expensive in
+ terms of CPU operations. If you don't need to know the exact
+ distance (e.g. for just comparing distances) use squaredDistance()
+ instead.
+ */
+ inline Real distance(const Vector3& rhs) const
+ {
+ return (*this - rhs).length();
+ }
+
+ /** Returns the square of the distance to another vector.
+ @remarks
+ This method is for efficiency - calculating the actual
+ distance to another vector requires a square root, which is
+ expensive in terms of the operations required. This method
+ returns the square of the distance to another vector, i.e.
+ the same as the distance but before the square root is taken.
+ Use this if you want to find the longest / shortest distance
+ without incurring the square root.
+ */
+ inline Real squaredDistance(const Vector3& rhs) const
+ {
+ return (*this - rhs).squaredLength();
+ }
+
+ /** Calculates the dot (scalar) product of this vector with another.
+ @remarks
+ The dot product can be used to calculate the angle between 2
+ vectors. If both are unit vectors, the dot product is the
+ cosine of the angle; otherwise the dot product must be
+ divided by the product of the lengths of both vectors to get
+ the cosine of the angle. This result can further be used to
+ calculate the distance of a point from a plane.
+ @param
+ vec Vector with which to calculate the dot product (together
+ with this one).
+ @returns
+ A float representing the dot product value.
+ */
+ inline Real dotProduct(const Vector3& vec) const
+ {
+ return x * vec.x + y * vec.y + z * vec.z;
+ }
+
+ /** Calculates the absolute dot (scalar) product of this vector with another.
+ @remarks
+ This function work similar dotProduct, except it use absolute value
+ of each component of the vector to computing.
+ @param
+ vec Vector with which to calculate the absolute dot product (together
+ with this one).
+ @returns
+ A Real representing the absolute dot product value.
+ */
+ inline Real absDotProduct(const Vector3& vec) const
+ {
+ return Math::Abs(x * vec.x) + Math::Abs(y * vec.y) + Math::Abs(z * vec.z);
+ }
+
+ /** Normalises the vector.
+ @remarks
+ This method normalises the vector such that it's
+ length / magnitude is 1. The result is called a unit vector.
+ @note
+ This function will not crash for zero-sized vectors, but there
+ will be no changes made to their components.
+ @returns The previous length of the vector.
+ */
+ inline Real normalise()
+ {
+ Real fLength = Math::Sqrt( x * x + y * y + z * z );
+
+ // Will also work for zero-sized vectors, but will change nothing
+ if ( fLength > 1e-08 )
+ {
+ Real fInvLength = 1.0 / fLength;
+ x *= fInvLength;
+ y *= fInvLength;
+ z *= fInvLength;
+ }
+
+ return fLength;
+ }
+
+ /** Calculates the cross-product of 2 vectors, i.e. the vector that
+ lies perpendicular to them both.
+ @remarks
+ The cross-product is normally used to calculate the normal
+ vector of a plane, by calculating the cross-product of 2
+ non-equivalent vectors which lie on the plane (e.g. 2 edges
+ of a triangle).
+ @param
+ vec Vector which, together with this one, will be used to
+ calculate the cross-product.
+ @returns
+ A vector which is the result of the cross-product. This
+ vector will <b>NOT</b> be normalised, to maximise efficiency
+ - call Vector3::normalise on the result if you wish this to
+ be done. As for which side the resultant vector will be on, the
+ returned vector will be on the side from which the arc from 'this'
+ to rkVector is anticlockwise, e.g. UNIT_Y.crossProduct(UNIT_Z)
+ = UNIT_X, whilst UNIT_Z.crossProduct(UNIT_Y) = -UNIT_X.
+ This is because OGRE uses a right-handed coordinate system.
+ @par
+ For a clearer explanation, look a the left and the bottom edges
+ of your monitor's screen. Assume that the first vector is the
+ left edge and the second vector is the bottom edge, both of
+ them starting from the lower-left corner of the screen. The
+ resulting vector is going to be perpendicular to both of them
+ and will go <i>inside</i> the screen, towards the cathode tube
+ (assuming you're using a CRT monitor, of course).
+ */
+ inline Vector3 crossProduct( const Vector3& rkVector ) const
+ {
+ return Vector3(
+ y * rkVector.z - z * rkVector.y,
+ z * rkVector.x - x * rkVector.z,
+ x * rkVector.y - y * rkVector.x);
+ }
+
+ /** Returns a vector at a point half way between this and the passed
+ in vector.
+ */
+ inline Vector3 midPoint( const Vector3& vec ) const
+ {
+ return Vector3(
+ ( x + vec.x ) * 0.5,
+ ( y + vec.y ) * 0.5,
+ ( z + vec.z ) * 0.5 );
+ }
+
+ /** Returns true if the vector's scalar components are all greater
+ that the ones of the vector it is compared against.
+ */
+ inline bool operator < ( const Vector3& rhs ) const
+ {
+ if( x < rhs.x && y < rhs.y && z < rhs.z )
+ return true;
+ return false;
+ }
+
+ /** Returns true if the vector's scalar components are all smaller
+ that the ones of the vector it is compared against.
+ */
+ inline bool operator > ( const Vector3& rhs ) const
+ {
+ if( x > rhs.x && y > rhs.y && z > rhs.z )
+ return true;
+ return false;
+ }
+
+ /** Sets this vector's components to the minimum of its own and the
+ ones of the passed in vector.
+ @remarks
+ 'Minimum' in this case means the combination of the lowest
+ value of x, y and z from both vectors. Lowest is taken just
+ numerically, not magnitude, so -1 < 0.
+ */
+ inline void makeFloor( const Vector3& cmp )
+ {
+ if( cmp.x < x ) x = cmp.x;
+ if( cmp.y < y ) y = cmp.y;
+ if( cmp.z < z ) z = cmp.z;
+ }
+
+ /** Sets this vector's components to the maximum of its own and the
+ ones of the passed in vector.
+ @remarks
+ 'Maximum' in this case means the combination of the highest
+ value of x, y and z from both vectors. Highest is taken just
+ numerically, not magnitude, so 1 > -3.
+ */
+ inline void makeCeil( const Vector3& cmp )
+ {
+ if( cmp.x > x ) x = cmp.x;
+ if( cmp.y > y ) y = cmp.y;
+ if( cmp.z > z ) z = cmp.z;
+ }
+
+ /** Generates a vector perpendicular to this vector (eg an 'up' vector).
+ @remarks
+ This method will return a vector which is perpendicular to this
+ vector. There are an infinite number of possibilities but this
+ method will guarantee to generate one of them. If you need more
+ control you should use the Quaternion class.
+ */
+ inline Vector3 perpendicular(void) const
+ {
+ static const Real fSquareZero = 1e-06 * 1e-06;
+
+ Vector3 perp = this->crossProduct( Vector3::UNIT_X );
+
+ // Check length
+ if( perp.squaredLength() < fSquareZero )
+ {
+ /* This vector is the Y axis multiplied by a scalar, so we have
+ to use another axis.
+ */
+ perp = this->crossProduct( Vector3::UNIT_Y );
+ }
+ perp.normalise();
+
+ return perp;
+ }
+ /** Generates a new random vector which deviates from this vector by a
+ given angle in a random direction.
+ @remarks
+ This method assumes that the random number generator has already
+ been seeded appropriately.
+ @param
+ angle The angle at which to deviate
+ @param
+ up Any vector perpendicular to this one (which could generated
+ by cross-product of this vector and any other non-colinear
+ vector). If you choose not to provide this the function will
+ derive one on it's own, however if you provide one yourself the
+ function will be faster (this allows you to reuse up vectors if
+ you call this method more than once)
+ @returns
+ A random vector which deviates from this vector by angle. This
+ vector will not be normalised, normalise it if you wish
+ afterwards.
+ */
+ inline Vector3 randomDeviant(
+ const Radian& angle,
+ const Vector3& up = Vector3::ZERO ) const
+ {
+ Vector3 newUp;
+
+ if (up == Vector3::ZERO)
+ {
+ // Generate an up vector
+ newUp = this->perpendicular();
+ }
+ else
+ {
+ newUp = up;
+ }
+
+ // Rotate up vector by random amount around this
+ Quaternion q;
+ q.FromAngleAxis( Radian(Math::UnitRandom() * Math::TWO_PI), *this );
+ newUp = q * newUp;
+
+ // Finally rotate this by given angle around randomised up
+ q.FromAngleAxis( angle, newUp );
+ return q * (*this);
+ }
+
+ /** Gets the angle between 2 vectors.
+ @remarks
+ Vectors do not have to be unit-length but must represent directions.
+ */
+ inline Radian angleBetween(const Vector3& dest)
+ {
+ Real lenProduct = length() * dest.length();
+
+ // Divide by zero check
+ if(lenProduct < 1e-6f)
+ lenProduct = 1e-6f;
+
+ Real f = dotProduct(dest) / lenProduct;
+
+ f = Math::Clamp(f, (Real)-1.0, (Real)1.0);
+ return Math::ACos(f);
+
+ }
+ /** Gets the shortest arc quaternion to rotate this vector to the destination
+ vector.
+ @remarks
+ If you call this with a dest vector that is close to the inverse
+ of this vector, we will rotate 180 degrees around the 'fallbackAxis'
+ (if specified, or a generated axis if not) since in this case
+ ANY axis of rotation is valid.
+ */
+ Quaternion getRotationTo(const Vector3& dest,
+ const Vector3& fallbackAxis = Vector3::ZERO) const
+ {
+ // Based on Stan Melax's article in Game Programming Gems
+ Quaternion q;
+ // Copy, since cannot modify local
+ Vector3 v0 = *this;
+ Vector3 v1 = dest;
+ v0.normalise();
+ v1.normalise();
+
+ Real d = v0.dotProduct(v1);
+ // If dot == 1, vectors are the same
+ if (d >= 1.0f)
+ {
+ return Quaternion::IDENTITY;
+ }
+ if (d < (1e-6f - 1.0f))
+ {
+ if (fallbackAxis != Vector3::ZERO)
+ {
+ // rotate 180 degrees about the fallback axis
+ q.FromAngleAxis(Radian(Math::PI), fallbackAxis);
+ }
+ else
+ {
+ // Generate an axis
+ Vector3 axis = Vector3::UNIT_X.crossProduct(*this);
+ if (axis.isZeroLength()) // pick another if colinear
+ axis = Vector3::UNIT_Y.crossProduct(*this);
+ axis.normalise();
+ q.FromAngleAxis(Radian(Math::PI), axis);
+ }
+ }
+ else
+ {
+ Real s = Math::Sqrt( (1+d)*2 );
+ Real invs = 1 / s;
+
+ Vector3 c = v0.crossProduct(v1);
+
+ q.x = c.x * invs;
+ q.y = c.y * invs;
+ q.z = c.z * invs;
+ q.w = s * 0.5;
+ q.normalise();
+ }
+ return q;
+ }
+
+ /** Returns true if this vector is zero length. */
+ inline bool isZeroLength(void) const
+ {
+ Real sqlen = (x * x) + (y * y) + (z * z);
+ return (sqlen < (1e-06 * 1e-06));
+
+ }
+
+ /** As normalise, except that this vector is unaffected and the
+ normalised vector is returned as a copy. */
+ inline Vector3 normalisedCopy(void) const
+ {
+ Vector3 ret = *this;
+ ret.normalise();
+ return ret;
+ }
+
+ /** Calculates a reflection vector to the plane with the given normal .
+ @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
+ */
+ inline Vector3 reflect(const Vector3& normal) const
+ {
+ return Vector3( *this - ( 2 * this->dotProduct(normal) * normal ) );
+ }
+
+ /** Returns whether this vector is within a positional tolerance
+ of another vector.
+ @param rhs The vector to compare with
+ @param tolerance The amount that each element of the vector may vary by
+ and still be considered equal
+ */
+ inline bool positionEquals(const Vector3& rhs, Real tolerance = 1e-03) const
+ {
+ return Math::RealEqual(x, rhs.x, tolerance) &&
+ Math::RealEqual(y, rhs.y, tolerance) &&
+ Math::RealEqual(z, rhs.z, tolerance);
+
+ }
+
+ /** Returns whether this vector is within a positional tolerance
+ of another vector, also take scale of the vectors into account.
+ @param rhs The vector to compare with
+ @param tolerance The amount (related to the scale of vectors) that distance
+ of the vector may vary by and still be considered close
+ */
+ inline bool positionCloses(const Vector3& rhs, Real tolerance = 1e-03f) const
+ {
+ return squaredDistance(rhs) <=
+ (squaredLength() + rhs.squaredLength()) * tolerance;
+ }
+
+ /** Returns whether this vector is within a directional tolerance
+ of another vector.
+ @param rhs The vector to compare with
+ @param tolerance The maximum angle by which the vectors may vary and
+ still be considered equal
+ @note Both vectors should be normalised.
+ */
+ inline bool directionEquals(const Vector3& rhs,
+ const Radian& tolerance) const
+ {
+ Real dot = dotProduct(rhs);
+ Radian angle = Math::ACos(dot);
+
+ return Math::Abs(angle.valueRadians()) <= tolerance.valueRadians();
+
+ }
+
+ // special points
+ static const Vector3 ZERO;
+ static const Vector3 UNIT_X;
+ static const Vector3 UNIT_Y;
+ static const Vector3 UNIT_Z;
+ static const Vector3 NEGATIVE_UNIT_X;
+ static const Vector3 NEGATIVE_UNIT_Y;
+ static const Vector3 NEGATIVE_UNIT_Z;
+ static const Vector3 UNIT_SCALE;
+
+ /** Function for writing to a stream.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const Vector3& v )
+ {
+ o << "Vector3(" << v.x << ", " << v.y << ", " << v.z << ")";
+ return o;
+ }
+ };
+
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector3.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector4.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector4.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector4.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,35 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "OgreVector4.h"
+#include "OgreMath.h"
+
+namespace Ogre
+{
+ const Vector4 Vector4::ZERO( 0, 0, 0, 0 );
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector4.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/OgreVector4.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/OgreVector4.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/OgreVector4.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,392 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Vector4_H__
+#define __Vector4_H__
+
+#include "OgrePrerequisites.h"
+#include "OgreVector3.h"
+#include <ostream>
+
+namespace Ogre
+{
+
+ /** 4-dimensional homogeneous vector.
+ */
+ class _OgreExport Vector4
+ {
+ public:
+ Real x, y, z, w;
+
+ public:
+ inline Vector4()
+ {
+ }
+
+ inline Vector4( const Real fX, const Real fY, const Real fZ, const Real fW )
+ : x( fX ), y( fY ), z( fZ ), w( fW)
+ {
+ }
+
+ inline explicit Vector4( const Real afCoordinate[4] )
+ : x( afCoordinate[0] ),
+ y( afCoordinate[1] ),
+ z( afCoordinate[2] ),
+ w( afCoordinate[3] )
+ {
+ }
+
+ inline explicit Vector4( const int afCoordinate[4] )
+ {
+ x = (Real)afCoordinate[0];
+ y = (Real)afCoordinate[1];
+ z = (Real)afCoordinate[2];
+ w = (Real)afCoordinate[3];
+ }
+
+ inline explicit Vector4( Real* const r )
+ : x( r[0] ), y( r[1] ), z( r[2] ), w( r[3] )
+ {
+ }
+
+ inline explicit Vector4( const Real scaler )
+ : x( scaler )
+ , y( scaler )
+ , z( scaler )
+ , w( scaler )
+ {
+ }
+
+ inline explicit Vector4(const Vector3& rhs)
+ : x(rhs.x), y(rhs.y), z(rhs.z), w(1.0f)
+ {
+ }
+
+ inline Real operator [] ( const size_t i ) const
+ {
+ assert( i < 4 );
+
+ return *(&x+i);
+ }
+
+ inline Real& operator [] ( const size_t i )
+ {
+ assert( i < 4 );
+
+ return *(&x+i);
+ }
+
+ /// Pointer accessor for direct copying
+ inline Real* ptr()
+ {
+ return &x;
+ }
+ /// Pointer accessor for direct copying
+ inline const Real* ptr() const
+ {
+ return &x;
+ }
+
+ /** Assigns the value of the other vector.
+ @param
+ rkVector The other vector
+ */
+ inline Vector4& operator = ( const Vector4& rkVector )
+ {
+ x = rkVector.x;
+ y = rkVector.y;
+ z = rkVector.z;
+ w = rkVector.w;
+
+ return *this;
+ }
+
+ inline Vector4& operator = ( const Real fScalar)
+ {
+ x = fScalar;
+ y = fScalar;
+ z = fScalar;
+ w = fScalar;
+ return *this;
+ }
+
+ inline bool operator == ( const Vector4& rkVector ) const
+ {
+ return ( x == rkVector.x &&
+ y == rkVector.y &&
+ z == rkVector.z &&
+ w == rkVector.w );
+ }
+
+ inline bool operator != ( const Vector4& rkVector ) const
+ {
+ return ( x != rkVector.x ||
+ y != rkVector.y ||
+ z != rkVector.z ||
+ w != rkVector.w );
+ }
+
+ inline Vector4& operator = (const Vector3& rhs)
+ {
+ x = rhs.x;
+ y = rhs.y;
+ z = rhs.z;
+ w = 1.0f;
+ return *this;
+ }
+
+ // arithmetic operations
+ inline Vector4 operator + ( const Vector4& rkVector ) const
+ {
+ return Vector4(
+ x + rkVector.x,
+ y + rkVector.y,
+ z + rkVector.z,
+ w + rkVector.w);
+ }
+
+ inline Vector4 operator - ( const Vector4& rkVector ) const
+ {
+ return Vector4(
+ x - rkVector.x,
+ y - rkVector.y,
+ z - rkVector.z,
+ w - rkVector.w);
+ }
+
+ inline Vector4 operator * ( const Real fScalar ) const
+ {
+ return Vector4(
+ x * fScalar,
+ y * fScalar,
+ z * fScalar,
+ w * fScalar);
+ }
+
+ inline Vector4 operator * ( const Vector4& rhs) const
+ {
+ return Vector4(
+ rhs.x * x,
+ rhs.y * y,
+ rhs.z * z,
+ rhs.w * w);
+ }
+
+ inline Vector4 operator / ( const Real fScalar ) const
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ return Vector4(
+ x * fInv,
+ y * fInv,
+ z * fInv,
+ w * fInv);
+ }
+
+ inline Vector4 operator / ( const Vector4& rhs) const
+ {
+ return Vector4(
+ x / rhs.x,
+ y / rhs.y,
+ z / rhs.z,
+ w / rhs.w);
+ }
+
+ inline const Vector4& operator + () const
+ {
+ return *this;
+ }
+
+ inline Vector4 operator - () const
+ {
+ return Vector4(-x, -y, -z, -w);
+ }
+
+ inline friend Vector4 operator * ( const Real fScalar, const Vector4& rkVector )
+ {
+ return Vector4(
+ fScalar * rkVector.x,
+ fScalar * rkVector.y,
+ fScalar * rkVector.z,
+ fScalar * rkVector.w);
+ }
+
+ inline friend Vector4 operator / ( const Real fScalar, const Vector4& rkVector )
+ {
+ return Vector4(
+ fScalar / rkVector.x,
+ fScalar / rkVector.y,
+ fScalar / rkVector.z,
+ fScalar / rkVector.w);
+ }
+
+ inline friend Vector4 operator + (const Vector4& lhs, const Real rhs)
+ {
+ return Vector4(
+ lhs.x + rhs,
+ lhs.y + rhs,
+ lhs.z + rhs,
+ lhs.w + rhs);
+ }
+
+ inline friend Vector4 operator + (const Real lhs, const Vector4& rhs)
+ {
+ return Vector4(
+ lhs + rhs.x,
+ lhs + rhs.y,
+ lhs + rhs.z,
+ lhs + rhs.w);
+ }
+
+ inline friend Vector4 operator - (const Vector4& lhs, Real rhs)
+ {
+ return Vector4(
+ lhs.x - rhs,
+ lhs.y - rhs,
+ lhs.z - rhs,
+ lhs.w - rhs);
+ }
+
+ inline friend Vector4 operator - (const Real lhs, const Vector4& rhs)
+ {
+ return Vector4(
+ lhs - rhs.x,
+ lhs - rhs.y,
+ lhs - rhs.z,
+ lhs - rhs.w);
+ }
+
+ // arithmetic updates
+ inline Vector4& operator += ( const Vector4& rkVector )
+ {
+ x += rkVector.x;
+ y += rkVector.y;
+ z += rkVector.z;
+ w += rkVector.w;
+
+ return *this;
+ }
+
+ inline Vector4& operator -= ( const Vector4& rkVector )
+ {
+ x -= rkVector.x;
+ y -= rkVector.y;
+ z -= rkVector.z;
+ w -= rkVector.w;
+
+ return *this;
+ }
+
+ inline Vector4& operator *= ( const Real fScalar )
+ {
+ x *= fScalar;
+ y *= fScalar;
+ z *= fScalar;
+ w *= fScalar;
+ return *this;
+ }
+
+ inline Vector4& operator += ( const Real fScalar )
+ {
+ x += fScalar;
+ y += fScalar;
+ z += fScalar;
+ w += fScalar;
+ return *this;
+ }
+
+ inline Vector4& operator -= ( const Real fScalar )
+ {
+ x -= fScalar;
+ y -= fScalar;
+ z -= fScalar;
+ w -= fScalar;
+ return *this;
+ }
+
+ inline Vector4& operator *= ( const Vector4& rkVector )
+ {
+ x *= rkVector.x;
+ y *= rkVector.y;
+ z *= rkVector.z;
+ w *= rkVector.w;
+
+ return *this;
+ }
+
+ inline Vector4& operator /= ( const Real fScalar )
+ {
+ assert( fScalar != 0.0 );
+
+ Real fInv = 1.0 / fScalar;
+
+ x *= fInv;
+ y *= fInv;
+ z *= fInv;
+ w *= fInv;
+
+ return *this;
+ }
+
+ inline Vector4& operator /= ( const Vector4& rkVector )
+ {
+ x /= rkVector.x;
+ y /= rkVector.y;
+ z /= rkVector.z;
+ w /= rkVector.w;
+
+ return *this;
+ }
+
+ /** Calculates the dot (scalar) product of this vector with another.
+ @param
+ vec Vector with which to calculate the dot product (together
+ with this one).
+ @returns
+ A float representing the dot product value.
+ */
+ inline Real dotProduct(const Vector4& vec) const
+ {
+ return x * vec.x + y * vec.y + z * vec.z + w * vec.w;
+ }
+ /** Function for writing to a stream.
+ */
+ inline _OgreExport friend std::ostream& operator <<
+ ( std::ostream& o, const Vector4& v )
+ {
+ o << "Vector4(" << v.x << ", " << v.y << ", " << v.z << ", " << v.w << ")";
+ return o;
+ }
+ // special
+ static const Vector4 ZERO;
+ };
+
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/OgreVector4.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimer.cpp
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimer.cpp (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimer.cpp 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,220 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#include "ogremath/OgreTimer.h"
+
+#include "ogremath/OgreBitwise.h"
+
+using namespace Ogre;
+
+//-------------------------------------------------------------------------
+Timer::Timer()
+ : mTimerMask( 0 )
+{
+ reset();
+}
+
+//-------------------------------------------------------------------------
+Timer::~Timer()
+{
+}
+
+//-------------------------------------------------------------------------
+bool Timer::setOption( const String & key, const void * val )
+{
+ if ( key == "QueryAffinityMask" )
+ {
+ // Telling timer what core to use for a timer read
+ DWORD newTimerMask = * static_cast < const DWORD * > ( val );
+
+ // Get the current process core mask
+ DWORD procMask;
+ DWORD sysMask;
+#if _MSC_VER >= 1400 && defined (_M_X64)
+ GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
+#else
+ GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
+#endif
+
+ // If new mask is 0, then set to default behavior, otherwise check
+ // to make sure new timer core mask overlaps with process core mask
+ // and that new timer core mask is a power of 2 (i.e. a single core)
+ if( ( newTimerMask == 0 ) ||
+ ( ( ( newTimerMask & procMask ) != 0 ) && Bitwise::isPO2( newTimerMask ) ) )
+ {
+ mTimerMask = newTimerMask;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+//-------------------------------------------------------------------------
+void Timer::reset()
+{
+ // Get the current process core mask
+ DWORD procMask;
+ DWORD sysMask;
+#if _MSC_VER >= 1400 && defined (_M_X64)
+ GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
+#else
+ GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
+#endif
+
+ // If procMask is 0, consider there is only one core available
+ // (using 0 as procMask will cause an infinite loop below)
+ if (procMask == 0)
+ procMask = 1;
+
+ // Find the lowest core that this process uses
+ if( mTimerMask == 0 )
+ {
+ mTimerMask = 1;
+ while( ( mTimerMask & procMask ) == 0 )
+ {
+ mTimerMask <<= 1;
+ }
+ }
+
+ HANDLE thread = GetCurrentThread();
+
+ // Set affinity to the first core
+ DWORD oldMask = SetThreadAffinityMask(thread, mTimerMask);
+
+ // Get the constant frequency
+ QueryPerformanceFrequency(&mFrequency);
+
+ // Query the timer
+ QueryPerformanceCounter(&mStartTime);
+ mStartTick = GetTickCount();
+
+ // Reset affinity
+ SetThreadAffinityMask(thread, oldMask);
+
+ mLastTime = 0;
+ mZeroClock = clock();
+}
+
+//-------------------------------------------------------------------------
+unsigned long Timer::getMilliseconds()
+{
+ LARGE_INTEGER curTime;
+
+ HANDLE thread = GetCurrentThread();
+
+ // Set affinity to the first core
+ DWORD oldMask = SetThreadAffinityMask(thread, mTimerMask);
+
+ // Query the timer
+ QueryPerformanceCounter(&curTime);
+
+ // Reset affinity
+ SetThreadAffinityMask(thread, oldMask);
+
+ LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart;
+
+ // scale by 1000 for milliseconds
+ unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
+
+ // detect and compensate for performance counter leaps
+ // (surprisingly common, see Microsoft KB: Q274323)
+ unsigned long check = GetTickCount() - mStartTick;
+ signed long msecOff = (signed long)(newTicks - check);
+ if (msecOff < -100 || msecOff > 100)
+ {
+ // We must keep the timer running forward :)
+ LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime);
+ mStartTime.QuadPart += adjust;
+ newTime -= adjust;
+
+ // Re-calculate milliseconds
+ newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
+ }
+
+ // Record last time for adjust
+ mLastTime = newTime;
+
+ return newTicks;
+}
+
+//-------------------------------------------------------------------------
+unsigned long Timer::getMicroseconds()
+{
+ LARGE_INTEGER curTime;
+
+ HANDLE thread = GetCurrentThread();
+
+ // Set affinity to the first core
+ DWORD oldMask = SetThreadAffinityMask(thread, mTimerMask);
+
+ // Query the timer
+ QueryPerformanceCounter(&curTime);
+
+ // Reset affinity
+ SetThreadAffinityMask(thread, oldMask);
+
+ LONGLONG newTime = curTime.QuadPart - mStartTime.QuadPart;
+
+ // get milliseconds to check against GetTickCount
+ unsigned long newTicks = (unsigned long) (1000 * newTime / mFrequency.QuadPart);
+
+ // detect and compensate for performance counter leaps
+ // (surprisingly common, see Microsoft KB: Q274323)
+ unsigned long check = GetTickCount() - mStartTick;
+ signed long msecOff = (signed long)(newTicks - check);
+ if (msecOff < -100 || msecOff > 100)
+ {
+ // We must keep the timer running forward :)
+ LONGLONG adjust = (std::min)(msecOff * mFrequency.QuadPart / 1000, newTime - mLastTime);
+ mStartTime.QuadPart += adjust;
+ newTime -= adjust;
+ }
+
+ // Record last time for adjust
+ mLastTime = newTime;
+
+ // scale by 1000000 for microseconds
+ unsigned long newMicro = (unsigned long) (1000000 * newTime / mFrequency.QuadPart);
+
+ return newMicro;
+}
+
+//-------------------------------------------------------------------------
+unsigned long Timer::getMillisecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)( (float)( newClock - mZeroClock ) / ( (float)CLOCKS_PER_SEC / 1000.0 ) ) ;
+}
+
+//-------------------------------------------------------------------------
+unsigned long Timer::getMicrosecondsCPU()
+{
+ clock_t newClock = clock();
+ return (unsigned long)( (float)( newClock - mZeroClock ) / ( (float)CLOCKS_PER_SEC / 1000000.0 ) ) ;
+}
Property changes on: code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimer.cpp
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimerImp.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimerImp.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimerImp.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,103 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2006 Torus Knot Software Ltd
+Also see acknowledgements in Readme.html
+
+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, or go to
+http://www.gnu.org/copyleft/lesser.txt.
+
+You may alternatively use this source under the terms of a specific version of
+the OGRE Unrestricted License provided you have obtained such a license from
+Torus Knot Software Ltd.
+-----------------------------------------------------------------------------
+*/
+#ifndef __Win32Timer_H__
+#define __Win32Timer_H__
+
+#include <ctime>
+
+#ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+#endif
+#include "windows.h"
+
+//Get around Windows hackery
+#ifdef max
+# undef max
+#endif
+#ifdef min
+# undef min
+#endif
+
+namespace Ogre
+{
+ class _OgreExport Timer
+ {
+ private:
+ clock_t mZeroClock;
+
+ DWORD mStartTick;
+ LONGLONG mLastTime;
+ LARGE_INTEGER mStartTime;
+ LARGE_INTEGER mFrequency;
+
+ DWORD mTimerMask;
+ public:
+ /** Timer constructor. MUST be called on same thread that calls getMilliseconds() */
+ Timer();
+ ~Timer();
+
+ /** Method for setting a specific option of the Timer. These options are usually
+ specific for a certain implementation of the Timer class, and may (and probably
+ will) not exist across different implementations. reset() must be called after
+ all setOption() calls.
+ @par
+ Current options supported are:
+ <ul><li>"QueryAffinityMask" (DWORD): Set the thread affinity mask to be used
+ to check the timer. If 'reset' has been called already this mask should
+ overlap with the process mask that was in force at that point, and should
+ be a power of two (a single core).</li></ul>
+ @param
+ strKey The name of the option to set
+ @param
+ pValue A pointer to the value - the size should be calculated by the timer
+ based on the key
+ @return
+ On success, true is returned.
+ @par
+ On failure, false is returned.
+ */
+ bool setOption( const String& strKey, const void* pValue );
+
+ /** Resets timer */
+ void reset();
+
+ /** Returns milliseconds since initialisation or last reset */
+ unsigned long getMilliseconds();
+
+ /** Returns microseconds since initialisation or last reset */
+ unsigned long getMicroseconds();
+
+ /** Returns milliseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMillisecondsCPU();
+
+ /** Returns microseconds since initialisation or last reset, only CPU time measured */
+ unsigned long getMicrosecondsCPU();
+ };
+}
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/WIN32/OgreTimerImp.h
___________________________________________________________________
Added: svn:eol-style
+ native
Added: code/forks/sandbox_light/src/external/ogremath/asm_math.h
===================================================================
--- code/forks/sandbox_light/src/external/ogremath/asm_math.h (rev 0)
+++ code/forks/sandbox_light/src/external/ogremath/asm_math.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -0,0 +1,367 @@
+#ifndef __asm_math_H__
+#define __asm_math_H__
+
+#include "OgrePrerequisites.h"
+
+namespace Ogre
+{
+
+/*=============================================================================
+ ASM math routines posted by davepermen et al on flipcode forums
+=============================================================================*/
+const float pi = 4.0 * atan( 1.0 );
+const float half_pi = 0.5 * pi;
+
+/*=============================================================================
+ NO EXPLICIT RETURN REQUIRED FROM THESE METHODS!!
+=============================================================================*/
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+# pragma warning( push )
+# pragma warning( disable: 4035 )
+#endif
+
+float asm_arccos( float r ) {
+ // return half_pi + arctan( r / -sqr( 1.f - r * r ) );
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ float asm_one = 1.f;
+ float asm_half_pi = half_pi;
+ __asm {
+ fld r // r0 = r
+ fld r // r1 = r0, r0 = r
+ fmul r // r0 = r0 * r
+ fsubr asm_one // r0 = r0 - 1.f
+ fsqrt // r0 = sqrtf( r0 )
+ fchs // r0 = - r0
+ fdiv // r0 = r1 / r0
+ fld1 // {{ r0 = atan( r0 )
+ fpatan // }}
+ fadd asm_half_pi // r0 = r0 + pi / 2
+ } // returns r0
+
+#else
+
+ return float( acos( r ) );
+
+#endif
+}
+
+float asm_arcsin( float r ) {
+ // return arctan( r / sqr( 1.f - r * r ) );
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ const float asm_one = 1.f;
+ __asm {
+ fld r // r0 = r
+ fld r // r1 = r0, r0 = r
+ fmul r // r0 = r0 * r
+ fsubr asm_one // r0 = r0 - 1.f
+ fsqrt // r0 = sqrtf( r0 )
+ fdiv // r0 = r1 / r0
+ fld1 // {{ r0 = atan( r0 )
+ fpatan // }}
+ } // returns r0
+
+#else
+
+ return float( asin( r ) );
+
+#endif
+
+}
+
+float asm_arctan( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ __asm {
+ fld r // r0 = r
+ fld1 // {{ r0 = atan( r0 )
+ fpatan // }}
+ } // returns r0
+
+#else
+
+ return float( atan( r ) );
+
+#endif
+
+}
+
+float asm_sin( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ __asm {
+ fld r // r0 = r
+ fsin // r0 = sinf( r0 )
+ } // returns r0
+
+#else
+
+ return sin( r );
+
+#endif
+
+}
+
+float asm_cos( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ __asm {
+ fld r // r0 = r
+ fcos // r0 = cosf( r0 )
+ } // returns r0
+
+#else
+
+ return cos( r );
+
+#endif
+}
+
+float asm_tan( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ // return sin( r ) / cos( r );
+ __asm {
+ fld r // r0 = r
+ fsin // r0 = sinf( r0 )
+ fld r // r1 = r0, r0 = r
+ fcos // r0 = cosf( r0 )
+ fdiv // r0 = r1 / r0
+ } // returns r0
+
+#else
+
+ return tan( r );
+
+#endif
+}
+
+// returns a for a * a = r
+float asm_sqrt( float r )
+{
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ __asm {
+ fld r // r0 = r
+ fsqrt // r0 = sqrtf( r0 )
+ } // returns r0
+
+#else
+
+ return sqrt( r );
+
+#endif
+}
+
+// returns 1 / a for a * a = r
+// -- Use this for Vector normalisation!!!
+float asm_rsq( float r )
+{
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ __asm {
+ fld1 // r0 = 1.f
+ fld r // r1 = r0, r0 = r
+ fsqrt // r0 = sqrtf( r0 )
+ fdiv // r0 = r1 / r0
+ } // returns r0
+
+#else
+
+ return 1. / sqrt( r );
+
+#endif
+}
+
+// returns 1 / a for a * a = r
+// Another version
+float apx_rsq( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ const float asm_dot5 = 0.5f;
+ const float asm_1dot5 = 1.5f;
+
+ __asm {
+ fld r // r0 = r
+ fmul asm_dot5 // r0 = r0 * .5f
+ mov eax, r // eax = r
+ shr eax, 0x1 // eax = eax >> 1
+ neg eax // eax = -eax
+ add eax, 0x5F400000 // eax = eax & MAGICAL NUMBER
+ mov r, eax // r = eax
+ fmul r // r0 = r0 * r
+ fmul r // r0 = r0 * r
+ fsubr asm_1dot5 // r0 = 1.5f - r0
+ fmul r // r0 = r0 * r
+ } // returns r0
+
+#else
+
+ return 1. / sqrt( r );
+
+#endif
+}
+
+/* very MS-specific, commented out for now
+ Finally the best InvSqrt implementation?
+ Use for vector normalisation instead of 1/length() * x,y,z
+*/
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+__declspec(naked) float __fastcall InvSqrt(float fValue)
+{
+ __asm
+ {
+ mov eax, 0be6eb508h
+ mov dword ptr[esp-12],03fc00000h
+ sub eax, dword ptr[esp + 4]
+ sub dword ptr[esp+4], 800000h
+ shr eax, 1
+ mov dword ptr[esp - 8], eax
+
+ fld dword ptr[esp - 8]
+ fmul st, st
+ fld dword ptr[esp - 8]
+ fxch st(1)
+ fmul dword ptr[esp + 4]
+ fld dword ptr[esp - 12]
+ fld st(0)
+ fsub st,st(2)
+
+ fld st(1)
+ fxch st(1)
+ fmul st(3),st
+ fmul st(3),st
+ fmulp st(4),st
+ fsub st,st(2)
+
+ fmul st(2),st
+ fmul st(3),st
+ fmulp st(2),st
+ fxch st(1)
+ fsubp st(1),st
+
+ fmulp st(1), st
+ ret 4
+ }
+}
+
+#endif
+
+// returns a random number
+FORCEINLINE float asm_rand()
+{
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+ #if 0
+ #if OGRE_COMP_VER >= 1300
+
+ static unsigned __int64 q = time( NULL );
+
+ _asm {
+ movq mm0, q
+
+ // do the magic MMX thing
+ pshufw mm1, mm0, 0x1E
+ paddd mm0, mm1
+
+ // move to integer memory location and free MMX
+ movq q, mm0
+ emms
+ }
+
+ return float( q );
+ #endif
+ #else
+ // VC6 does not support pshufw
+ return float( rand() );
+ #endif
+#else
+ // GCC etc
+
+ return float( rand() );
+
+#endif
+}
+
+// returns the maximum random number
+FORCEINLINE float asm_rand_max()
+{
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+ #if 0
+ #if OGRE_COMP_VER >= 1300
+
+ return (std::numeric_limits< unsigned __int64 >::max)();
+ return 9223372036854775807.0f;
+ #endif
+ #else
+ // VC6 does not support unsigned __int64
+ return float( RAND_MAX );
+ #endif
+
+#else
+ // GCC etc
+ return float( RAND_MAX );
+
+#endif
+}
+
+// returns log2( r ) / log2( e )
+float asm_ln( float r ) {
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+
+ const float asm_e = 2.71828182846f;
+ const float asm_1_div_log2_e = .693147180559f;
+ const float asm_neg1_div_3 = -.33333333333333333333333333333f;
+ const float asm_neg2_div_3 = -.66666666666666666666666666667f;
+ const float asm_2 = 2.f;
+
+ int log_2 = 0;
+
+ __asm {
+ // log_2 = ( ( r >> 0x17 ) & 0xFF ) - 0x80;
+ mov eax, r
+ sar eax, 0x17
+ and eax, 0xFF
+ sub eax, 0x80
+ mov log_2, eax
+
+ // r = ( r & 0x807fffff ) + 0x3f800000;
+ mov ebx, r
+ and ebx, 0x807FFFFF
+ add ebx, 0x3F800000
+ mov r, ebx
+
+ // r = ( asm_neg1_div_3 * r + asm_2 ) * r + asm_neg2_div_3; // (1)
+ fld r
+ fmul asm_neg1_div_3
+ fadd asm_2
+ fmul r
+ fadd asm_neg2_div_3
+ fild log_2
+ fadd
+ fmul asm_1_div_log2_e
+ }
+
+#else
+
+ return log( r );
+
+#endif
+}
+
+#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32
+# pragma warning( pop )
+#endif
+} // namespace
+#endif
Property changes on: code/forks/sandbox_light/src/external/ogremath/asm_math.h
___________________________________________________________________
Added: svn:eol-style
+ native
Modified: code/forks/sandbox_light/src/libraries/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/libraries/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -23,5 +23,3 @@
ADD_SUBDIRECTORY(util)
ADD_SUBDIRECTORY(core)
-ADD_SUBDIRECTORY(network)
-ADD_SUBDIRECTORY(tools)
Deleted: code/forks/sandbox_light/src/libraries/core/BaseObject.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/BaseObject.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/BaseObject.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,491 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the BaseObject class.
-*/
-
-#include "BaseObject.h"
-
-#include <tinyxml/tinyxml.h>
-
-#include "CoreIncludes.h"
-#include "Event.h"
-#include "EventIncludes.h"
-#include "Iterator.h"
-#include "Template.h"
-#include "XMLFile.h"
-#include "XMLNameListener.h"
-#include "XMLPort.h"
-#include "command/Functor.h"
-
-namespace orxonox
-{
- CreateFactory(BaseObject);
-
- /**
- @brief Constructor: Registers the object in the BaseObject-list.
- */
- BaseObject::BaseObject(BaseObject* creator) : bInitialized_(false)
- {
- RegisterRootObject(BaseObject);
-
- this->bInitialized_ = true;
-
- this->bActive_ = true;
- this->bVisible_ = true;
- this->oldGametype_ = 0;
- this->bRegisteredEventStates_ = false;
-
- this->lastLoadedXMLElement_ = 0;
-
- this->mainStateFunctor_ = 0;
-
- this->setCreator(creator);
- if (this->creator_)
- {
- this->setFile(this->creator_->getFile());
- this->setNamespace(this->creator_->getNamespace());
- this->setScene(this->creator_->getScene(), this->creator_->getSceneID());
- this->setGametype(this->creator_->getGametype());
- this->setLevel(this->creator_->getLevel());
- }
- else
- {
- this->file_ = 0;
- this->namespace_ = 0;
- this->scene_ = 0;
- this->sceneID_ = OBJECTID_UNKNOWN;
- this->gametype_ = 0;
- this->level_ = 0;
- }
- }
-
- /**
- @brief Destructor
- */
- BaseObject::~BaseObject()
- {
- if (this->isInitialized())
- {
- for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); )
- this->removeEventSource((it++)->first);
-
- for (std::set<BaseObject*>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); )
- (*(it++))->removeEventSource(this);
-
- for (std::map<std::string, EventState*>::const_iterator it = this->eventStates_.begin(); it != this->eventStates_.end(); ++it)
- delete it->second;
- }
- }
-
- /** @brief Adds an object which listens to the events of this object. */
- void BaseObject::registerEventListener(BaseObject* object)
- {
- COUT(4) << "New EventListener: " << object->getIdentifier()->getName() << " &(" << object << ")." << std::endl;
- this->eventListeners_.insert(object);
- }
-
- /**
- @brief XML loading and saving.
- @param xmlelement The XML-element
- @param mode The mode defines the operation that is being executed: loading or saving the object (from or to XML respectively)
- */
- void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- XMLPortParam(BaseObject, "name", setXMLName, getName, xmlelement, mode);
- XMLPortParam(BaseObject, "visible", setVisible, isVisible, xmlelement, mode);
- XMLPortParam(BaseObject, "active", setActive, isActive, xmlelement, mode);
- XMLPortParam(BaseObject, "mainstate", setMainStateName, getMainStateName, xmlelement, mode);
- XMLPortParamTemplate(BaseObject, "template", addTemplate, getSingleTemplate, xmlelement, mode, const std::string&);
-
- XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
- XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode);
-
- Element* events = 0;
- if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
- events = xmlelement.FirstChildElement("events", false);
- else if (mode == XMLPort::SaveObject)
- {}
- if (events)
- this->XMLEventPort(*events, mode);
- }
-
- /**
- @brief Defines the possible event states of this object and parses eventsources from an XML file.
- @param xmlelement The XML-element
- @param mode The mode defines the operation that is being executed: loading or saving the object (from or to XML respectively)
- */
- void BaseObject::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
- {
- XMLPortEventState(BaseObject, BaseObject, "activity", setActive, xmlelement, mode);
- XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode);
- XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode);
-
- this->bRegisteredEventStates_ = true;
- }
-
- /**
- @brief Loads the name of the object through XML and calls all XMLNameListener.
- @param name The name of the object
- */
- void BaseObject::setXMLName(const std::string& name)
- {
- this->setName(name);
-
- for (ObjectList<XMLNameListener>::iterator it = ObjectList<XMLNameListener>::begin(); it != ObjectList<XMLNameListener>::end(); ++it)
- it->loadedNewXMLName(this);
- }
-
- /**
- @brief Returns the levelfile that loaded this object.
- @return The levelfile
- */
- const std::string& BaseObject::getFilename() const
- {
- if (this->file_)
- return this->file_->getFilename();
- else
- return BLANKSTRING;
- }
-
- /**
- @brief Adds a Template to the object.
- @param name The name of the Template
- */
- void BaseObject::addTemplate(const std::string& name)
- {
- Template* temp = Template::getTemplate(name);
- if (temp)
- this->addTemplate(temp);
- else
- COUT(1) << "Error: \"" << name << "\" is not a valid Template name (in class: " << this->getIdentifier()->getName() << ", name: " << this->getName() << ")." << std::endl;
- }
-
- /**
- @brief Adds a Template to the object.
- @param temp The Template
- */
- void BaseObject::addTemplate(Template* temp)
- {
- this->templates_.insert(temp);
- if( temp->isLink() )
- {
- this->networkTemplateNames_.insert(temp->getLink());
- assert( !Template::getTemplate(temp->getLink())->isLink() );
- }
- else
- this->networkTemplateNames_.insert(temp->getName());
- temp->applyOn(this);
- }
-
- /**
- @brief Returns the name of the first Template.
- @return The name as string.
- */
- const std::string& BaseObject::getSingleTemplate(void) const
- {
- if(this->templates_.empty())
- return BLANKSTRING;
-
- return (*this->templates_.begin())->getName();
- }
-
- /**
- @brief Returns the Template with the given index.
- @param index The index
- */
- Template* BaseObject::getTemplate(unsigned int index) const
- {
- unsigned int i = 0;
- for (std::set<Template*>::const_iterator it = this->templates_.begin(); it != this->templates_.end(); ++it)
- {
- if (i == index)
- return (*it);
- i++;
- }
- return 0;
- }
-
- /**
- @brief Adds a new event source for a specific state.
- @param source The object which sends events to this object
- @param state The state of this object which will be affected by the events
- */
- void BaseObject::addEventSource(BaseObject* source, const std::string& state)
- {
- this->eventSources_[source] = state;
- source->registerEventListener(this);
- }
-
- /**
- @brief Removes an eventsource (but doesn't unregister itself at the source).
- */
- void BaseObject::removeEventSource(BaseObject* source)
- {
- this->eventSources_.erase(source);
- source->unregisterEventListener(this);
- }
-
- /**
- @brief Returns an eventsource with a given index.
- */
- BaseObject* BaseObject::getEventSource(unsigned int index, const std::string& state) const
- {
- unsigned int i = 0;
- for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); ++it)
- {
- if (it->second != state)
- continue;
-
- if (i == index)
- return it->first;
- ++i;
- }
- return 0;
- }
-
- /**
- @brief Adds an object which listens to the events of this object. The events are sent to the other objects mainstate.
- */
- void BaseObject::addEventListener(BaseObject* listener)
- {
- this->eventListenersXML_.insert(listener);
- listener->addEventSource(this, "mainstate");
- }
-
- /**
- @brief Returns an event listener with a given index.
- */
- BaseObject* BaseObject::getEventListener(unsigned int index) const
- {
- unsigned int i = 0;
- for (std::set<BaseObject*>::const_iterator it = this->eventListenersXML_.begin(); it != this->eventListenersXML_.end(); ++it)
- {
- if (i == index)
- return *it;
- ++i;
- }
- return 0;
- }
-
- /**
- @brief Adds a new event-state to the object. Event-states are states which can be changed by events.
- @param name The name of the event
- @param state The object containing information about the event-state
- */
- void BaseObject::addEventState(const std::string& name, EventState* state)
- {
- std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
- if (it != this->eventStates_.end())
- {
- COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << '.' << std::endl;
- delete (it->second);
- }
-
- this->eventStates_[name] = state;
- }
-
- /**
- @brief Returns the event-state with the given name.
- */
- EventState* BaseObject::getEventState(const std::string& name) const
- {
- std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
- if (it != this->eventStates_.end())
- return (it->second);
- else
- return 0;
- }
-
- /**
- @brief Fires an event (without a state).
- */
- void BaseObject::fireEvent(const std::string& name)
- {
- this->fireEvent(true, name);
- this->fireEvent(false, name);
- }
-
- /**
- @brief Fires an event which activates or deactivates a state.
- */
- void BaseObject::fireEvent(bool activate, const std::string& name)
- {
- this->fireEvent(activate, this, name);
- }
-
- /**
- @brief Fires an event which activates or deactivates a state with agiven originator (the object which triggered the event).
- */
- void BaseObject::fireEvent(bool activate, BaseObject* originator, const std::string& name)
- {
- Event event(activate, originator, name);
-
- for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
- {
- event.statename_ = (*it)->eventSources_[this];
- (*it)->processEvent(event);
- }
- }
-
- /**
- @brief Fires an event, using the Event struct.
- */
- void BaseObject::fireEvent(Event& event)
- {
- for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
- (*it)->processEvent(event);
- }
-
- /**
- @brief Processing an event by calling the right main state.
- @param event The event struct which contains the information about the event
- */
- void BaseObject::processEvent(Event& event)
- {
- this->registerEventStates();
-
- COUT(4) << this->getIdentifier()->getName() << " (&" << this << ") processing event. originator: " << event.originator_->getIdentifier()->getName() << " (&" << event.originator_ << "), activate: " << event.activate_ << ", name: " << event.name_ << ", statename: " << event.statename_ << "." << std::endl;
-
- std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_);
- if (it != this->eventStates_.end())
- it->second->process(event, this);
- else if (!event.statename_.empty())
- COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
- else
- COUT(2) << "Warning: Event with invalid source sent to object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
- }
-
- /**
- @brief Sets the main state of the object to a given boolean value.
-
- Note: The main state of an object can be set with the @ref setMainStateName function.
- It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state,
- the main state is used by default).
- */
- void BaseObject::setMainState(bool state)
- {
- if (this->mainStateFunctor_)
- {
- if (this->mainStateFunctor_->getParamCount() == 0)
- {
- if (state)
- (*this->mainStateFunctor_)();
- }
- else
- {
- (*this->mainStateFunctor_)(state);
- }
- }
- else
- COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
- }
-
- /**
- @brief This function gets called if the main state name of the object changes.
- */
- void BaseObject::changedMainStateName()
- {
- this->mainStateFunctor_ = 0;
-
- if (!this->mainStateName_.empty())
- {
- this->registerEventStates();
-
- std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_);
- if (it != this->eventStates_.end() && it->second->getFunctor())
- {
- if (it->second->getFunctor()->getParamCount() <= 1)
- this->mainStateFunctor_ = it->second->getFunctor();
- else
- COUT(2) << "Warning: Can't use \"" << this->mainStateName_ << "\" as MainState because it needs a second argument." << std::endl;
- }
- else
- COUT(2) << "Warning: \"" << this->mainStateName_ << "\" is not a valid MainState." << std::endl;
- }
- }
-
- /**
- @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary.
- */
- void BaseObject::registerEventStates()
- {
- if (!this->bRegisteredEventStates_)
- {
- Element xmlelement;
- this->XMLEventPort(xmlelement, XMLPort::NOP);
- }
- }
-
- /**
- @brief Manually loads all event states, even if the class doesn't officially support them. This is needed by some classes like @ref EventDispatcher or @ref EventTarget.
- */
- void BaseObject::loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier)
- {
- Element* events = xmlelement.FirstChildElement("events", false);
- if (events)
- {
- // get the list of all states present
- std::list<std::string> eventnames;
- if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
- {
- for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
- eventnames.push_back(child->Value());
- }
- else if (mode == XMLPort::SaveObject)
- {
- }
-
- // iterate through all states and get the event sources
- for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
- {
- const std::string& statename = (*it);
-
- // if the event state is already known, continue with the next state
- orxonox::EventState* eventstate = object->getEventState(statename);
- if (eventstate)
- continue;
-
- XMLPortClassObjectContainer<BaseObject, BaseObject>* container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(identifier->getXMLPortObjectContainer(statename));
- if (!container)
- {
- const ExecutorMemberPtr<BaseObject>& setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + '(' + statename + ')');
- const ExecutorMemberPtr<BaseObject>& getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + '(' + statename + ')');
- setfunctor->setDefaultValue(1, statename);
- getfunctor->setDefaultValue(1, statename);
-
- container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(statename, identifier, setfunctor, getfunctor, false, true);
- identifier->addXMLPortObjectContainer(statename, container);
- }
- container->port(object, *events, mode);
- }
- }
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/BaseObject.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/BaseObject.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/BaseObject.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,248 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup BaseObject BaseObject
- @ingroup Core
-*/
-
-/**
- @file
- @ingroup BaseObject
- @brief Declaration of BaseObject, the base class of all objects in Orxonox.
-
- The BaseObject is the parent of all classes representing an instance in the game.
-*/
-
-#ifndef _BaseObject_H__
-#define _BaseObject_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <list>
-
-#include "util/mbool.h"
-#include "OrxonoxClass.h"
-#include "Super.h"
-#include "SmartPtr.h"
-
-namespace orxonox
-{
- class Scene;
- class Gametype;
- class Level;
-
- /// The BaseObject is the parent of all classes representing an instance in the game.
- class _CoreExport BaseObject : virtual public OrxonoxClass
- {
- template <class T> friend class XMLPortClassParamContainer;
-
- public:
- BaseObject(BaseObject* creator);
- virtual ~BaseObject();
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
- virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
-
- /** @brief Returns if the object was initialized (passed the object registration). @return True was the object is initialized */
- inline bool isInitialized() const { return this->bInitialized_; }
-
- /** @brief Sets the name of the object. @param name The name */
- inline void setName(const std::string& name) { this->oldName_ = this->name_; this->name_ = name; this->changedName(); }
- /** @brief Returns the name of the object. */
- inline const std::string& getName() const { return this->name_; }
- /** @brief Returns the old name of the object. */
- inline const std::string& getOldName() const { return this->oldName_; }
- /** @brief This function gets called if the name of the object changes. */
- virtual void changedName() {}
-
- /** @brief Sets the state of the objects activity. @param bActive True = active */
- inline void setActive(bool bActive)
- {
- if (this->bActive_ != bActive)
- {
- this->bActive_ = bActive;
- this->changedActivity();
- }
- }
- /** @brief Returns the state of the objects activity. @return The state of the activity */
- inline const mbool& isActive() const { return this->bActive_; }
- /** @brief This function gets called if the activity of the object changes. */
- virtual void changedActivity() {}
-
- /** @brief Sets the state of the objects visibility. @param bVisible True = visible */
- inline void setVisible(bool bVisible)
- {
- if (this->bVisible_ != bVisible)
- {
- this->bVisible_ = bVisible;
- this->changedVisibility();
- }
- }
- /** @brief Returns the state of the objects visibility. @return The state of the visibility */
- inline const mbool& isVisible() const { return this->bVisible_; }
- /** @brief This function gets called if the visibility of the object changes. */
- virtual void changedVisibility() {}
-
- void setMainState(bool state);
-
- /** @brief Sets the name of the main state (used for event reactions). */
- void setMainStateName(const std::string& name)
- {
- if (this->mainStateName_ != name)
- {
- this->mainStateName_ = name;
- this->changedMainStateName();
- }
- }
- /** @brief Returns the name of the main state. */
- inline const std::string& getMainStateName() const { return this->mainStateName_; }
- /** @brief This function gets called if the main state name of the object changes. */
- virtual void changedMainStateName();
-
- /** @brief Sets a pointer to the xml file that loaded this object. @param file The pointer to the XMLFile */
- inline void setFile(const XMLFile* file) { this->file_ = file; }
- /** @brief Returns a pointer to the XMLFile that loaded this object. @return The XMLFile */
- inline const XMLFile* getFile() const { return this->file_; }
- const std::string& getFilename() const;
-
- void addTemplate(const std::string& name);
- void addTemplate(Template* temp);
- /** @brief Returns the set of all aplied templates. */
- inline const std::set<Template*>& getTemplates() const
- { return this->templates_; }
-
- virtual inline void setNamespace(Namespace* ns) { this->namespace_ = ns; }
- inline Namespace* getNamespace() const { return this->namespace_; }
-
- inline void setCreator(BaseObject* creator) { this->creator_ = creator; }
- inline BaseObject* getCreator() const { return this->creator_; }
-
- inline void setScene(const SmartPtr<Scene>& scene, uint32_t sceneID) { this->scene_ = scene; this->sceneID_=sceneID; }
- inline const SmartPtr<Scene>& getScene() const { return this->scene_; }
- inline virtual uint32_t getSceneID() const { return this->sceneID_; }
-
- inline void setGametype(const SmartPtr<Gametype>& gametype)
- {
- if (gametype != this->gametype_)
- {
- this->oldGametype_ = this->gametype_;
- this->gametype_ = gametype;
- this->changedGametype();
- }
- }
- inline const SmartPtr<Gametype>& getGametype() const { return this->gametype_; }
- inline Gametype* getOldGametype() const { return this->oldGametype_; }
- virtual void changedGametype() {}
-
- inline void setLevel(const SmartPtr<Level>& level)
- {
- if (level != this->level_)
- {
- this->level_ = level;
- this->changedLevel();
- }
- }
- inline const SmartPtr<Level>& getLevel() const { return this->level_; }
- virtual void changedLevel() {}
-
- void addEventSource(BaseObject* source, const std::string& state);
- void removeEventSource(BaseObject* source);
- BaseObject* getEventSource(unsigned int index, const std::string& state) const;
-
- void addEventListener(BaseObject* listener);
- BaseObject* getEventListener(unsigned int index) const;
-
- void fireEvent(const std::string& name = "");
- void fireEvent(bool activate, const std::string& name = "");
- void fireEvent(bool activate, BaseObject* originator, const std::string& name = "");
- void fireEvent(Event& event);
-
- virtual void processEvent(Event& event);
-
- /** @brief Sets the indentation of the debug output in the Loader. @param indentation The indentation */
- inline void setLoaderIndentation(const std::string& indentation) { this->loaderIndentation_ = indentation; }
- /** @brief Returns the indentation of the debug output in the Loader. @return The indentation */
- inline const std::string& getLoaderIndentation() const { return this->loaderIndentation_; }
-
- static void loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier);
-
- protected:
- void addEventState(const std::string& name, EventState* container);
- EventState* getEventState(const std::string& name) const;
-
- std::string name_; //!< The name of the object
- std::string oldName_; //!< The old name of the object
- mbool bActive_; //!< True = the object is active
- mbool bVisible_; //!< True = the object is visible
- std::string mainStateName_;
- FunctorPtr mainStateFunctor_;
- std::set<std::string> networkTemplateNames_;
-
- private:
- /** @brief Adds an object which listens to the events of this object. */
- void registerEventListener(BaseObject* object);
- /** @brief Removes an event listener from this object. */
- inline void unregisterEventListener(BaseObject* object)
- { this->eventListeners_.erase(object); }
-
- void setXMLName(const std::string& name);
- const std::string& getSingleTemplate(void) const;
- Template* getTemplate(unsigned int index) const;
- void registerEventStates();
-
- bool bInitialized_; //!< True if the object was initialized (passed the object registration)
- const XMLFile* file_; //!< The XMLFile that loaded this object
- Element* lastLoadedXMLElement_; //!< Non 0 if the TinyXML attributes have already been copied to our own lowercase map
- std::map<std::string, std::string> xmlAttributes_; //!< Lowercase XML attributes
- std::string loaderIndentation_; //!< Indentation of the debug output in the Loader
- Namespace* namespace_;
- BaseObject* creator_;
- SmartPtr<Scene> scene_;
- uint32_t sceneID_;
- SmartPtr<Gametype> gametype_;
- Gametype* oldGametype_;
- SmartPtr<Level> level_;
- std::set<Template*> templates_;
-
- std::map<BaseObject*, std::string> eventSources_; //!< List of objects which send events to this object, mapped to the state which they affect
- std::set<BaseObject*> eventListeners_; //!< List of objects which listen to the events of this object
- std::set<BaseObject*> eventListenersXML_; //!< List of objects which listen to the events of this object through the "eventlisteners" subsection in XML
- std::map<std::string, EventState*> eventStates_; //!< Maps the name of the event states to their helper objects
- bool bRegisteredEventStates_; //!< Becomes true after the object registered its event states (with XMLEventPort)
- };
-
- SUPER_FUNCTION(0, BaseObject, XMLPort, false);
- SUPER_FUNCTION(2, BaseObject, changedActivity, false);
- SUPER_FUNCTION(3, BaseObject, changedVisibility, false);
- SUPER_FUNCTION(4, BaseObject, XMLEventPort, false);
- SUPER_FUNCTION(8, BaseObject, changedName, false);
- SUPER_FUNCTION(9, BaseObject, changedGametype, false);
-}
-
-#endif /* _BaseObject_H__ */
Modified: code/forks/sandbox_light/src/libraries/core/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/libraries/core/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -19,85 +19,15 @@
SET_SOURCE_FILES(CORE_SRC_FILES
CommandLineParser.cc
- ConfigValueContainer.cc
Core.cc
- DynLib.cc
- DynLibManager.cc
- Event.cc
- Game.cc
- GameMode.cc
- GameState.cc
- GraphicsManager.cc
- GUIManager.cc
- Language.cc
- LuaState.cc
- ObjectListBase.cc
- OrxonoxClass.cc
- Resource.cc
- WindowEventListener.cc
-
- # hierarchy
- Identifier.cc
- MetaObjectList.cc
-
- # level
- BaseObject.cc
- ClassTreeMask.cc
- Loader.cc
- Namespace.cc
- NamespaceNode.cc
- Template.cc
- XMLPort.cc
- XMLNameListener.cc
-
-COMPILATION_BEGIN FilesystemCompilation.cc
- command/ArgumentCompletionFunctions.cc
- ConfigFileManager.cc
- MemoryArchive.cc
PathConfig.cc
-COMPILATION_END
-
- # multithreading
- ThreadPool.cc
-COMPILATION_BEGIN ThreadCompilation.cc
- command/TclThreadManager.cc
- Thread.cc
-COMPILATION_END
)
-ADD_SUBDIRECTORY(command)
-ADD_SUBDIRECTORY(input)
-
ORXONOX_ADD_LIBRARY(core
FIND_HEADER_FILES
- TOLUA_FILES
- command/CommandExecutor.h
- ConfigFileManager.h
- Game.h
- GameMode.h
- GUIManager.h
- Loader.h
- LuaState.h
- PathConfig.h
- input/InputManager.h
- input/KeyBinder.h
- input/KeyBinderManager.h
- PCH_FILE
- CorePrecompiledHeaders.h
LINK_LIBRARIES
- ${OGRE_LIBRARY}
${Boost_FILESYSTEM_LIBRARY}
${Boost_SYSTEM_LIBRARY} # Filesystem dependency
- ${Boost_THREAD_LIBRARY}
- ${Boost_DATE_TIME_LIBRARY} # Thread dependency
- ${CEGUI_LIBRARY}
- ${CEGUILUA_LIBRARY}
- ${LUA_LIBRARIES}
- cpptcl_orxonox
- ogreceguirenderer_orxonox
- ois_orxonox
- tinyxml_orxonox
- tolua_orxonox
util
SOURCE_FILES
${CORE_SRC_FILES}
Deleted: code/forks/sandbox_light/src/libraries/core/ClassFactory.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ClassFactory.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ClassFactory.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,91 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Object Factory
- @brief Definition and implementation of the ClassFactory class
-
- The ClassFactory is able to create new objects of a specific class which creates objects.
-*/
-
-#ifndef _ClassFactory_H__
-#define _ClassFactory_H__
-
-#include "CorePrereqs.h"
-
-#include <string>
-
-#include "util/Debug.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- // ###########################
- // ### Factory ###
- // ###########################
- /// Base-class of ClassFactory.
- class _CoreExport Factory
- {
- public:
- virtual ~Factory() {};
- virtual BaseObject* fabricate(BaseObject* creator) = 0;
- };
-
- // ###############################
- // ### ClassFactory ###
- // ###############################
- /// The ClassFactory is able to create new objects of a specific class.
- template <class T>
- class ClassFactory : public Factory
- {
- public:
- /**
- @brief Constructor: Adds the ClassFactory to the Identifier of the same type.
- @param name The name of the class
- @param bLoadable True if the class can be loaded through XML
- */
- ClassFactory(const std::string& name, bool bLoadable = true)
- {
- COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
- ClassIdentifier<T>::getIdentifier(name)->addFactory(this);
- ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
- }
-
- /**
- @brief Creates and returns a new object of class T.
- @return The new object
- */
- inline BaseObject* fabricate(BaseObject* creator)
- {
- return static_cast<BaseObject*>(new T(creator));
- }
- };
-}
-
-#endif /* _ClassFactory_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ClassTreeMask.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ClassTreeMask.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ClassTreeMask.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,963 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the ClassTreeMask, ClassTreeMaskNode, and ClassTreeMaskIterator classes.
-*/
-
-#include "ClassTreeMask.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- // ###############################
- // ### ClassTreeMaskNode ###
- // ###############################
- /**
- @brief Constructor: Creates the node, sets the subclass and the rule.
- @param subclass The subclass the rule refers to
- @param bIncluded The rule: included (true) or excluded (false)
- */
- ClassTreeMaskNode::ClassTreeMaskNode(const Identifier* subclass, bool bIncluded)
- {
- this->subclass_ = subclass;
- this->bIncluded_ = bIncluded;
- }
-
- /**
- @brief Destructor: Deletes all subnodes.
- */
- ClassTreeMaskNode::~ClassTreeMaskNode()
- {
- // Go through the list of all subnodes and delete them
- this->deleteAllSubnodes();
- }
-
- /**
- @brief Sets the rule for the node to "included".
- @param overwrite True = overwrite previously added rules for inheriting classes
- */
- void ClassTreeMaskNode::include(bool overwrite)
- {
- this->setIncluded(true, overwrite);
- }
-
- /**
- @brief Sets the rule for the node to "excluded".
- @param overwrite True = overwrite previously added rules for inheriting classes
- */
- void ClassTreeMaskNode::exclude(bool overwrite)
- {
- this->setIncluded(false, overwrite);
- }
-
- /**
- @brief Sets the rule for the node to a given value and erases all following rules.
- @param bIncluded The rule: included (true) or excluded (false)
- @param overwrite True = overwrite previously added rules for inheriting classes
- */
- void ClassTreeMaskNode::setIncluded(bool bIncluded, bool overwrite)
- {
- if (overwrite)
- this->deleteAllSubnodes();
-
- this->bIncluded_ = bIncluded;
- }
-
- /**
- @brief Adds a new subnode to the list of subnodes.
- */
- void ClassTreeMaskNode::addSubnode(ClassTreeMaskNode* subnode)
- {
- this->subnodes_.insert(this->subnodes_.end(), subnode);
- }
-
- /**
- @brief Deletes all subnodes of this node.
- */
- void ClassTreeMaskNode::deleteAllSubnodes()
- {
- // Go through the list of all subnodes and delete them
- for (std::list<ClassTreeMaskNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); )
- delete (*(it++));
-
- // Clear the list
- this->subnodes_.clear();
- }
-
-
- // ###############################
- // ### ClassTreeMaskIterator ###
- // ###############################
- /**
- @brief Constructor: Initializes the iterator by creating a helper-list with the root-node and putting it to the stack.
- @param node The root-node
- */
- ClassTreeMaskIterator::ClassTreeMaskIterator(ClassTreeMaskNode* node)
- {
- // Create a list and put the root-note into it
- std::list<ClassTreeMaskNode*>::iterator it = this->rootlist_.insert(this->rootlist_.end(), node);
-
- // Put the iterator to the only element of the list and the corresponding end()-iterator on the stack
- this->nodes_.push(std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator>(it, this->rootlist_.end()));
- }
-
- /**
- @brief Destructor: Does nothing.
- */
- ClassTreeMaskIterator::~ClassTreeMaskIterator()
- {
- }
-
- /**
- @brief Iterates through the rule-tree.
- @return A reference to the iterator itself
- */
- const ClassTreeMaskIterator& ClassTreeMaskIterator::operator++()
- {
- // Check if the actual node has subnodes
- if ((*this->nodes_.top().first)->subnodes_.begin() != (*this->nodes_.top().first)->subnodes_.end())
- {
- // Yes it has: Push an iterator, pointing at the first subnode, on the stack
- this->nodes_.push(std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator>((*this->nodes_.top().first)->subnodes_.begin(), (*this->nodes_.top().first)->subnodes_.end()));
- }
- else
- {
- // No subnodes, meaning we reached a leaf: Go to the next node
- do
- {
- // Iterate one step in the current list
- ++this->nodes_.top().first;
-
- // Check if we reached the end of the list (the second item in the stored pair always represents the end)
- if (this->nodes_.top().first == this->nodes_.top().second)
- {
- // Yes we've reached the end: Pop the list-iterator from the stack
- this->nodes_.pop();
-
- // Continue with the loop, meaning: Try to iterate through the previous list
- continue;
- }
-
- // If we reached this point, we aren't yet at the end of the list: Leave the loop
- break;
- } while (!this->nodes_.empty()); // Stop looping if the stack is empty, meaning: We've iterated to the end
- }
-
- // Finally return a reference to the iterator itself
- return *this;
- }
-
- /**
- @brief Returns a pointer to the ClassTreeMaskNode whereon the iterator points.
- */
- ClassTreeMaskNode* ClassTreeMaskIterator::operator*() const
- {
- return (*this->nodes_.top().first);
- }
-
- /**
- @brief Returns a pointer to the ClassTreeMaskNode whereon the iterator points.
- */
- ClassTreeMaskNode* ClassTreeMaskIterator::operator->() const
- {
- return (*this->nodes_.top().first);
- }
-
- /**
- @brief Returns true if the stack is empty, meaning we've reached the end of the tree.
- */
- ClassTreeMaskIterator::operator bool() const
- {
- return (!this->nodes_.empty());
- }
-
- /**
- @brief Compares the current node with the given one and returns true if they match.
- */
- bool ClassTreeMaskIterator::operator==(ClassTreeMaskNode* compare) const
- {
- if (!this->nodes_.empty())
- return ((*this->nodes_.top().first) == compare);
- else
- return (compare == 0);
- }
-
- /**
- @brief Compares the current node with the given one and returns true if they don't match.
- */
- bool ClassTreeMaskIterator::operator!=(ClassTreeMaskNode* compare) const
- {
- if (!this->nodes_.empty())
- return ((*this->nodes_.top().first) != compare);
- else
- return (compare != 0);
- }
-
-
- // ###############################
- // ### ClassTreeMask ###
- // ###############################
- /**
- @brief Constructor: Adds the root-node of the tree with the first rule ("include everything").
- */
- ClassTreeMask::ClassTreeMask()
- {
- this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
- }
-
- /**
- @brief Copy-constructor: Adds the root-node of the tree with the first rule ("include everything") and adds all rules from the other mask.
- */
- ClassTreeMask::ClassTreeMask(const ClassTreeMask& other)
- {
- this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
- for (ClassTreeMaskIterator it = other.root_; it; ++it)
- this->add(it->getClass(), it->isIncluded(), false);
- }
-
- /**
- @brief Destructor: Deletes the root node (which will delete all subnodes too).
- */
- ClassTreeMask::~ClassTreeMask()
- {
- delete this->root_;
- }
-
- /**
- @brief Adds a new "include" rule for a given subclass to the mask.
- @param subclass The subclass
- @param overwrite True = overwrite previously added rules for inheriting classes
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::include(const Identifier* subclass, bool overwrite, bool clean)
- {
- this->add(subclass, true, overwrite, clean);
- }
-
- /**
- @brief Adds a new "exclude" rule for a given subclass to the mask.
- @param subclass The subclass
- @param overwrite True = overwrite previously added rules for inheriting classes
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::exclude(const Identifier* subclass, bool overwrite, bool clean)
- {
- this->add(subclass, false, overwrite, clean);
- }
-
- /**
- @brief Adds a new rule for a given subclass to the mask.
- @param subclass The subclass
- @param bInclude The rule: include (true) or exclude (false)
- @param overwrite True = overwrite previously added rules for inheriting classes
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::add(const Identifier* subclass, bool bInclude, bool overwrite, bool clean)
- {
- if (!subclass)
- return;
- // Check if the given subclass is a child of our root-class
- if (subclass->isA(this->root_->getClass()))
- {
- // Yes it is: Just add the rule to the three
- this->add(this->root_, subclass, bInclude, overwrite);
- }
- else
- {
- // No it's not: Search for classes inheriting from the given class and add the rules for them
- for (std::set<const Identifier*>::const_iterator it = subclass->getDirectChildrenBegin(); it != subclass->getDirectChildrenEnd(); ++it)
- if ((*it)->isA(this->root_->getClass()))
- if (overwrite || (!this->nodeExists(*it))) // If we don't want to overwrite, only add nodes that don't already exist
- this->add(this->root_, *it, bInclude, overwrite);
- }
-
- // Clean the rule-tree
- if (clean)
- this->clean();
- }
-
- /**
- @brief Adds a new rule for a given subclass to a node of the internal rule-tree (recursive function).
- @param node The node
- @param subclass The subclass
- @param bInclude The rule: include (true) or exclude (false)
- @param overwrite True = overwrite previously added rules for inheriting classes
- */
- void ClassTreeMask::add(ClassTreeMaskNode* node, const Identifier* subclass, bool bInclude, bool overwrite)
- {
- if (!subclass)
- return;
- // Check if the current node contains exactly the subclass we want to add
- if (subclass == node->getClass())
- {
- // We're at the right place, just change the mask and return
- node->setIncluded(bInclude, overwrite);
- return;
- }
- else if (subclass->isA(node->getClass()))
- {
- // Search for an already existing node, containing the subclass we want to add
- for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); ++it)
- {
- if (subclass->isA((*it)->getClass()))
- {
- // We've found an existing node -> delegate the work with a recursive function-call and return
- this->add(*it, subclass, bInclude, overwrite);
- return;
- }
- }
-
- // There is no existing node satisfying our needs -> we create a new node
- ClassTreeMaskNode* newnode = new ClassTreeMaskNode(subclass, bInclude);
-
- // Search for nodes that should actually be subnodes of our new node and erase them
- for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); )
- {
- if ((*it)->getClass()->isChildOf(subclass))
- {
- // We've found a subnode: add it to the new node and erase it from the current node
- if (!overwrite)
- newnode->addSubnode(*it);
- else
- delete (*it);
-
- node->subnodes_.erase(it++);
- }
- else
- {
- ++it;
- }
- }
-
- // Finally add the new node as a subnode to the current node
- node->addSubnode(newnode);
- }
- }
-
- /**
- @brief Adds a new "include" rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
- @param subclass The subclass
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::includeSingle(const Identifier* subclass, bool clean)
- {
- this->addSingle(subclass, true, clean);
- }
-
- /**
- @brief Adds a new "exclude" rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
- @param subclass The subclass
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::excludeSingle(const Identifier* subclass, bool clean)
- {
- this->addSingle(subclass, false, clean);
- }
-
- /**
- @brief Adds a new rule for a single subclass. The new rule doesn't change the mask for inheriting classes.
- @param bInclude The rule: include (true) or exclude (false)
- @param subclass The subclass
- @param clean True = clean the tree after adding the new rule
- */
- void ClassTreeMask::addSingle(const Identifier* subclass, bool bInclude, bool clean)
- {
- if (!subclass)
- return;
- for (std::set<const Identifier*>::const_iterator it = subclass->getDirectChildrenBegin(); it != subclass->getDirectChildrenEnd(); ++it)
- this->add(*it, this->isIncluded(*it), false, false);
-
- this->add(subclass, bInclude, false, clean);
- }
-
- /**
- @brief Resets the mask to "include everything".
- */
- void ClassTreeMask::reset()
- {
- delete this->root_;
- this->root_ = new ClassTreeMaskNode(ClassIdentifier<BaseObject>::getIdentifier(), true);
- }
-
- /**
- @brief Tells if a given subclass is included or not.
- @param subclass The subclass
- @return Included (true) or excluded (false)
- */
- bool ClassTreeMask::isIncluded(const Identifier* subclass) const
- {
- return this->isIncluded(this->root_, subclass);
- }
-
- /**
- @brief Tells if a given subclass of a node in the rule-tree is included or not (recursive function).
- @param node The node
- @param subclass The subclass
- @return Included (true) or excluded (false)
- */
- bool ClassTreeMask::isIncluded(ClassTreeMaskNode* node, const Identifier* subclass) const
- {
- if (!subclass)
- return false;
- // Check if the searched subclass is of the same type as the class in the current node or a derivative
- if (subclass->isA(node->getClass()))
- {
- // Check for the special case
- if (subclass == node->getClass())
- return node->isIncluded();
-
- // Go through the list of subnodes and look for a node containing the searched subclass and delegate the request by a recursive function-call.
- for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); ++it)
- if (subclass->isA((*it)->getClass()))
- return isIncluded(*it, subclass);
-
- // There is no subnode containing our class -> the rule of the current node takes in effect
- return node->isIncluded();
- }
- else
- {
- // The class is not included in the mask: return false
- return false;
- }
- }
-
- /**
- @brief Tells if a given subclass is excluded or not.
- @param subclass The subclass
- @return The inverted rule: Excluded (true) or included (false)
- */
- bool ClassTreeMask::isExcluded(const Identifier* subclass) const
- {
- return (!this->isIncluded(subclass));
- }
-
- /**
- @brief Removes all unneeded rules that don't change the information of the mask.
- */
- void ClassTreeMask::clean()
- {
- this->clean(this->root_);
- }
-
- /**
- @brief Removes all unneded rules that don't change the information of a node of a mask (recursive function).
- @param node The node
- */
- void ClassTreeMask::clean(ClassTreeMaskNode* node)
- {
- // Iterate through all subnodes of the given node
- for (std::list<ClassTreeMaskNode*>::iterator it = node->subnodes_.begin(); it != node->subnodes_.end(); )
- {
- // Recursive function-call: Clean the subnode
- this->clean(*it);
-
- // Now check if the subnode contains the same rule as the current node
- if ((*it)->isIncluded() == node->isIncluded())
- {
- // It does: Move all subnodes of the redundant subnode to the current node
- node->subnodes_.insert(node->subnodes_.end(), (*it)->subnodes_.begin(), (*it)->subnodes_.end());
- (*it)->subnodes_.clear();
-
- // Remove the redundant subnode from the current node
- delete (*it);
- node->subnodes_.erase(it++);
- }
- else
- {
- // The subnode is necessary: Move on to the next subnode
- ++it;
- }
- }
- }
-
- /**
- @brief Checks if a node for the given subclass exists.
- @param subclass The Identifier of the subclass
- @return True = the node exists
- */
- bool ClassTreeMask::nodeExists(const Identifier* subclass)
- {
- for (ClassTreeMaskIterator it = this->root_; it; ++it)
- if ((*it)->getClass() == subclass)
- return true;
-
- return false;
- }
-
- /**
- @brief Assignment operator: Adds all rules of the other mask.
- @param other The other mask
- @return A reference to the mask itself
- */
- ClassTreeMask& ClassTreeMask::operator=(const ClassTreeMask& other)
- {
- // Make a copy to avoid troubles with self-assignments (like A = A).
- ClassTreeMask temp(other);
-
- // Removes all current rules
- this->reset();
-
- // Copy all rules from the other mask
- for (ClassTreeMaskIterator it = temp.root_; it; ++it)
- this->add(it->getClass(), it->isIncluded(), false, false);
-
- // Return a reference to the mask itself
- return (*this);
- }
-
- /**
- @brief Compares the mask with another mask and returns true if they represent the same logic.
- @param other The other mask
- @return True if both masks represent the same logic
- */
- bool ClassTreeMask::operator==(const ClassTreeMask& other) const
- {
- ClassTreeMask temp1 = other;
- ClassTreeMask temp2 = (*this);
-
- temp1.clean();
- temp2.clean();
-
- ClassTreeMaskIterator it1 = temp1.root_;
- ClassTreeMaskIterator it2 = temp2.root_;
-
- for ( ; it1 && it2; ++it1, ++it2)
- if (it1->getClass() != it2->getClass())
- return false;
-
- return true;
- }
-
- /**
- @brief Compares the mask with another mask and returns true if they represent different logics.
- @param other The other mask
- @return True if the masks represent different logics
- */
- bool ClassTreeMask::operator!=(const ClassTreeMask& other) const
- {
- return (!((*this) == other));
- }
-
- /**
- @brief Prefix operator + does nothing.
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator+() const
- {
- return (*this);
- }
-
- /**
- @brief Prefix operator - inverts the mask.
- @return The inverted mask
- */
- ClassTreeMask ClassTreeMask::operator-() const
- {
- return (!(*this));
- }
-
- /**
- @brief Adds two masks in the sense of a union (all classes that are included in at least one of the masks will be included in the resulting mask too).
- @param other The mask to unite with
- @return The union
- */
- ClassTreeMask ClassTreeMask::operator+(const ClassTreeMask& other) const
- {
- // Create a new mask
- ClassTreeMask newmask;
-
- // Add all nodes from the first mask, calculate the rule with the or-operation
- for (ClassTreeMaskIterator it = this->root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) or other.isIncluded(subclass), false, false);
- }
-
- // Add all nodes from the second mask, calculate the rule with the or-operation
- for (ClassTreeMaskIterator it = other.root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) or other.isIncluded(subclass), false, false);
- }
-
- // Drop all redundant rules
- newmask.clean();
-
- // Return the new mask
- return newmask;
- }
-
- /**
- @brief Intersects two masks (only classes that are included in both masks will be included in the resulting mask too).
- @param other The mask to intersect with
- @return The intersection
- */
- ClassTreeMask ClassTreeMask::operator*(const ClassTreeMask& other) const
- {
- // Create a new mask
- ClassTreeMask newmask;
-
- // Add all nodes from the first mask, calculate the rule with the and-operation
- for (ClassTreeMaskIterator it = this->root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) and other.isIncluded(subclass), false, false);
- }
-
- // Add all nodes from the second mask, calculate the rule with the and-operation
- for (ClassTreeMaskIterator it = other.root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) and other.isIncluded(subclass), false, false);
- }
-
- // Drop all redundant rules
- newmask.clean();
-
- // Return the new mask
- return newmask;
- }
-
- /**
- @brief Removes all elements of the second mask from the first mask (all classes that are included in the first mask stay included, except those that are included in the second mask too).
- @param other The mask to subtract.
- @return The difference
- */
- ClassTreeMask ClassTreeMask::operator-(const ClassTreeMask& other) const
- {
- return ((*this) * (!other));
- }
-
- /**
- @brief Inverts the mask (all included classes are now excluded and vice versa).
- @return The complement
- */
- ClassTreeMask ClassTreeMask::operator!() const
- {
- // Create a new mask
- ClassTreeMask newmask;
-
- // Add all nodes from the other mask, inverting the rules
- for (ClassTreeMaskIterator it = this->root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, !this->isIncluded(subclass), false, false);
- }
-
- // Return the new mask
- return newmask;
- }
-
- /**
- @brief Unites this mask with another mask.
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator+=(const ClassTreeMask& other)
- {
- (*this) = (*this) + other;
- return (*this);
- }
-
- /**
- @brief Intersects this mask with another mask.
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator*=(const ClassTreeMask& other)
- {
- (*this) = (*this) * other;
- return (*this);
- }
-
- /**
- @brief Subtracts another mask from this mask.
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator-=(const ClassTreeMask& other)
- {
- (*this) = (*this) - other;
- return (*this);
- }
-
- /**
- @brief Intersects two masks (only classes that are included in both masks will be included in the resulting mask too).
- @param other The mask to intersect with
- @return The intersection
- */
- ClassTreeMask ClassTreeMask::operator&(const ClassTreeMask& other) const
- {
- return ((*this) * other);
- }
-
- /**
- @brief Adds two masks in the sense of a union (all classes that are included in at least one of the masks will be included in the resulting mask too).
- @param other The mask to unite with
- @return The union
- */
- ClassTreeMask ClassTreeMask::operator|(const ClassTreeMask& other) const
- {
- return ((*this) + other);
- }
-
- /**
- @brief Joins two masks in the sense of a xor (exclusivity) operation (all classes that are included in exactly one of the masks, but not in both, will be included in the resulting mask too).
- @param other The mask to join with
- @return The result
- */
- ClassTreeMask ClassTreeMask::operator^(const ClassTreeMask& other) const
- {
- // Create a new mask
- ClassTreeMask newmask;
-
- // Add all nodes from the first mask, calculate the rule with the xor-operation
- for (ClassTreeMaskIterator it = this->root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) xor other.isIncluded(subclass), false, false);
- }
-
- // Add all nodes from the second mask, calculate the rule with the xor-operation
- for (ClassTreeMaskIterator it = other.root_; it; ++it)
- {
- const Identifier* subclass = it->getClass();
- newmask.add(subclass, this->isIncluded(subclass) xor other.isIncluded(subclass), false, false);
- }
-
- // Drop all redundant rules
- newmask.clean();
-
- // Return the new mask
- return newmask;
- }
-
- /**
- @brief Inverts the mask (all included classes are now excluded and vice versa).
- @return The complement
- */
- ClassTreeMask ClassTreeMask::operator~() const
- {
- return (!(*this));
- }
-
- /**
- @brief Intersects this mask with another mask (and-operation)
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator&=(const ClassTreeMask& other)
- {
- (*this) = (*this) & other;
- return (*this);
- }
-
- /**
- @brief Unites this mask with another mask (or-operation).
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator|=(const ClassTreeMask& other)
- {
- (*this) = (*this) | other;
- return (*this);
- }
-
- /**
- @brief Joins this mask with another mask with a xor-operation.
- @param other The other mask
- @return A reference to the mask itself
- */
- const ClassTreeMask& ClassTreeMask::operator^=(const ClassTreeMask& other)
- {
- (*this) = (*this) ^ other;
- return (*this);
- }
-
- /**
- @brief Converts the content of a mask into a human readable string and puts it on the ostream.
- @param out The ostream
- @param mask The mask
- @return A reference to the ostream
- */
- std::ostream& operator<<(std::ostream& out, const ClassTreeMask& mask)
- {
- // Iterate through all rules
- for (ClassTreeMaskIterator it = mask.root_; it; ++it)
- {
- // Calculate the prefix: + means included, - means excluded
- if (it->isIncluded())
- out << '+';
- else
- out << '-';
-
- // Put the name of the corresponding class on the stream
- out << it->getClass()->getName() << ' ';
- }
-
- return out;
- }
-
-
- // ###################################
- // ### ClassTreeMaskObjectIterator ###
- // ###################################
- /**
- @brief Initializes the iterator from a given ClassTreeMask.
- @param mask The mask
- */
- ClassTreeMaskObjectIterator& ClassTreeMaskObjectIterator::operator=(const ClassTreeMask& mask)
- {
- // Clear everything, use a cleaned copy of the mask
- this->subclasses_.clear();
- ClassTreeMask temp = mask;
- temp.clean();
-
- // Create the subclass-list by going through the mask-tree, starting with the root-node
- this->create(temp.root_);
-
- // Move the subclass-iterator to the beginning of the subclass-list
- this->subclassIterator_ = this->subclasses_.begin();
-
- // If there is a first subclass, move the object-iterator to the first object of this class. Else go to the end
- if (this->subclassIterator_ != this->subclasses_.end())
- this->objectIterator_ = this->subclassIterator_->first->getObjects()->begin();
- else
- this->objectIterator_ = ObjectList<BaseObject>::end();
-
- // Check if the iterator points on a valid object. If not, go to the next object by calling ++
- if (!this->objectIterator_ || (this->subclassIterator_->second && !this->objectIterator_->isExactlyA(this->subclassIterator_->first)))
- this->operator++();
-
- return (*this);
- }
-
- /**
- @brief Iterate to the next object (if any).
- @return The iterator itself
- */
- const ClassTreeMaskObjectIterator& ClassTreeMaskObjectIterator::operator++()
- {
- if (this->objectIterator_)
- {
- // The iterator points on a valid object, therefore we also have a valid subclass-iterator at the moment
- do
- {
- // Go to the next object
- ++this->objectIterator_;
-
- while (!this->objectIterator_)
- {
- // We reached the end of the current objectlist - go to the next class
- ++this->subclassIterator_;
-
- // Check if there really is a next class. If yes, move the object-iterator to the first object
- if (this->subclassIterator_ != this->subclasses_.end())
- this->objectIterator_ = this->subclassIterator_->first->getObjects()->begin();
- else
- return (*this);
- }
-
- // Repeat this until we reach a valid object or the end
- } while (this->subclassIterator_->second && !this->objectIterator_->isExactlyA(this->subclassIterator_->first));
- }
- return (*this);
- }
-
- /**
- @brief Recursive function to create the Iterators subclass-list by going through the node-tree of the mask.
- @param node The current node
- */
- void ClassTreeMaskObjectIterator::create(ClassTreeMaskNode* node)
- {
- // Add the class of this node to the list, if the class is included
- if (node->isIncluded())
- {
- // If there are some subnodes, the bool is "true", meaning we have to check for the exact clss when iterating
- if (node->hasSubnodes())
- this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(node->getClass(), true));
- else
- this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(node->getClass(), false));
- }
-
- // Now check if the node has subnodes
- if (node->hasSubnodes())
- {
- // Get all _direct_ children of the nodes class
- std::set<const Identifier*> directChildren = node->getClass()->getDirectChildren();
-
- // Iterate through all subnodes
- for (std::list<ClassTreeMaskNode*>::iterator it1 = node->subnodes_.begin(); it1 != node->subnodes_.end(); ++it1)
- {
- // Recursive call to this function with the subnode
- this->create(*it1);
-
- // Only execute the following code if the current node is included, meaning some of the subnodes might be included too
- if (node->isIncluded())
- {
- scanChildren: // This is a label for goto
-
- // Iterate through all direct children
- for (std::set<const Identifier*>::iterator it2 = directChildren.begin(); it2 != directChildren.end(); ++it2)
- {
- // Check if the subnode (it1) is a child of the directChild (it2)
- if ((*it1)->getClass()->isA(*it2))
- {
- // Yes it is - remove the directChild (it2) from the list, because it will already be handled by a recursive call to the create() function
- directChildren.erase(it2);
-
- // Check if the removed directChild was exactly the subnode
- if (!(*it1)->getClass()->isExactlyA(*it2))
- {
- // No, it wasn't exactly the subnode - therefore there are some classes between
-
- // Add the previously removed directChild (it2) to the subclass-list
- this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(*it2, true));
-
- // Insert all directChildren of the directChild
- directChildren.insert((*it2)->getDirectChildrenBegin(), (*it2)->getDirectChildrenEnd());
-
- // Restart the scan with the expanded set of directChildren
- goto scanChildren;
- }
- break;
- }
- }
- }
- }
-
- // Now add all directChildren which don't have subnodes on their own to the subclass-list
- // The bool is "false", meaning they have no subnodes and therefore need no further checks
- if (node->isIncluded())
- for (std::set<const Identifier*>::iterator it = directChildren.begin(); it != directChildren.end(); ++it)
- this->subclasses_.insert(this->subclasses_.end(), std::pair<const Identifier*, bool>(*it, false));
- }
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/ClassTreeMask.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ClassTreeMask.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ClassTreeMask.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,305 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Class
- @brief Declaration of the ClassTreeMask, ClassTreeMaskNode, and ClassTreeMaskIterator classes.
-
- ClassTreeMask is a class to define a mask of the class-tree beginning with orxonox::BaseObject.
- You can include or exclude classes by calling the corresponding functions with the
- orxonox::Identifier of the class. This mask can then be used to filter out objects that
- are instances of classes which aren't included in the tree, for example when Loading a
- level file or if a Trigger should be triggered by only a few classes.
-
- See the description of orxonox::ClassTreeMask for a short example.
-
- You can work with a ClassTreeMask in the sense of the set-theory, meaning that you can create
- unions, intersections, complements and differences by using overloaded operators.
-
- @par Tree structure
-
- The ClassTreeMask is internally represented by a tree. The nodes in the tree are
- ClassTreeMaskNodes, containing the rule (included or excluded) for this class and all
- subclasses and a list of all subnodes. To minimize the size, the tree contains only
- nodes changing the mask. By adding new rules, the tree gets reordered dynamically.
-
- Adding a new rule overwrites all rules assigned to inherited classes. Use <tt>overwrite = false</tt>
- if you don't like this feature. Useless rules that don't change the information of the mask
- aren't saved in the internal tree. Use <tt>clean = false</tt> if you still want to save them.
-
- With <tt>overwrite = false</tt> and <tt>clean = false</tt> it doesn't matter in which order
- you create the mask. You can manually drop useless rules from the tree by calling
- @ref orxonox::ClassTreeMask::clean() "clean()".
-
- @par Objects
-
- To iterate through all objects of the classes that were included by a ClassTreeMask,
- use orxonox::ClassTreeMaskObjectIterator. The description of this class also contains
- a short example of how to use it.
-*/
-
-#ifndef _ClassTreeMask_H__
-#define _ClassTreeMask_H__
-
-#include "CorePrereqs.h"
-
-#include <list>
-#include <stack>
-#include "BaseObject.h"
-#include "Iterator.h"
-
-namespace orxonox
-{
- // ###################################
- // ### ClassTreeMaskNode ###
- // ###################################
- /**
- @brief The ClassTreeMaskNode is a node in the internal tree of the ClassTreeMask, containing the rules of the mask.
-
- The ClassTreeMaskNode is used to store the rule (included or excluded) for a given
- class (described by the corresponding Identifier). The nodes are used in the internal
- tree of ClassTreeMask. To build a tree, they store a list of all subnodes.
- */
- class _CoreExport ClassTreeMaskNode
- {
- friend class ClassTreeMask;
- friend class ClassTreeMaskIterator;
- friend class ClassTreeMaskObjectIterator;
-
- public:
- ClassTreeMaskNode(const Identifier* subclass, bool bIncluded = true);
- ~ClassTreeMaskNode();
-
- void include(bool overwrite = true);
- void exclude(bool overwrite = true);
- void setIncluded(bool bIncluded, bool overwrite = true);
-
- void addSubnode(ClassTreeMaskNode* subnode);
-
- /// Tells if the rule is "included" or not.
- inline bool isIncluded() const { return this->bIncluded_; }
- /// Tells if the rule is "excluded" or not.
- inline bool isExcluded() const { return (!this->bIncluded_); }
-
- /// Returns the Identifier of the class the rule refers to.
- inline const Identifier* getClass() const { return this->subclass_; }
-
- /// Returns true if the node has some subnodes.
- inline bool hasSubnodes() const { return !this->subnodes_.empty(); }
-
- private:
- void deleteAllSubnodes();
-
- const Identifier* subclass_; ///< The Identifier of the subclass the rule refers to
- bool bIncluded_; ///< The rule: included or excluded
- std::list<ClassTreeMaskNode*> subnodes_; ///< A list containing all subnodes of this node
- };
-
-
- // ###################################
- // ### ClassTreeMaskIterator ###
- // ###################################
- /**
- @brief The ClassTreeMaskIterator moves through all ClassTreeMaskNodes of the internal tree of a ClassTreeMask which contains the rules.
-
- Because of the complicated shape of the internal rule-tree of ClassTreeMask, an
- iterator is used to move through all nodes of the tree. It starts with the BaseObject
- and moves on to the first subclass until it reaches a leaf of the tree. Then the
- iterator moves one step back and iterates to the second subclass. If there are no more
- subclasses, it steps another step back, and so on.
-
- Example: A and B are children of BaseObject, A1 and A2 are children of A, B1 and B2 are children of B.
- The ClassTreeMaskIterator would move trough the tree in the following order:
- BaseObject, A, A1, A2, B, B1, B2.
-
- Note that the iterator doesn't move trough the whole class-tree, but only through the
- internal tree of the mask, containing the minimal needed set of nodes to describe the mask.
- */
- class _CoreExport ClassTreeMaskIterator
- {
- public:
- ClassTreeMaskIterator(ClassTreeMaskNode* node);
- ~ClassTreeMaskIterator();
-
- const ClassTreeMaskIterator& operator++();
- ClassTreeMaskNode* operator*() const;
- ClassTreeMaskNode* operator->() const;
- operator bool() const;
- bool operator==(ClassTreeMaskNode* compare) const;
- bool operator!=(ClassTreeMaskNode* compare) const;
-
- private:
- std::stack<std::pair<std::list<ClassTreeMaskNode*>::iterator, std::list<ClassTreeMaskNode*>::iterator> > nodes_; ///< A stack to store list-iterators
- std::list<ClassTreeMaskNode*> rootlist_; ///< A list for internal use (it only stores the root-node)
- };
-
-
- // ###################################
- // ### ClassTreeMask ###
- // ###################################
- /**
- @brief The ClassTreeMask is a set of rules, containing the information for each class whether it's included or not.
-
- With a ClassTreeMask, you can include or exclude subtrees of the class-tree, starting
- with a given subclass, described by the corresponding Identifier. To minimize the size
- of the mask, the mask saves only relevant rules. But you can manually add rules that
- don't change the information of the mask by using <tt>clean = false</tt>. If you want to drop
- useless rules, call the clean() function.
-
- Example:
- @code
- ClassTreeMask mymask;
- mymask.exclude(Class(A));
- mymask.exclude(Class(B));
- mymask.include(Class(ChildOfA));
- @endcode
-
- In this example, the classes A and B are excluded from the mask, but one of the child
- classes of A is included again.
- */
- class _CoreExport ClassTreeMask
- {
- friend class ClassTreeMaskObjectIterator;
-
- public:
- ClassTreeMask();
- ClassTreeMask(const ClassTreeMask& other);
- ~ClassTreeMask();
-
- void include(const Identifier* subclass, bool overwrite = true, bool clean = true);
- void exclude(const Identifier* subclass, bool overwrite = true, bool clean = true);
- void add(const Identifier* subclass, bool bInclude, bool overwrite = true, bool clean = true);
-
- void includeSingle(const Identifier* subclass, bool clean = true);
- void excludeSingle(const Identifier* subclass, bool clean = true);
- void addSingle(const Identifier* subclass, bool bInclude, bool clean = true);
-
- void reset();
- void clean();
-
- bool isIncluded(const Identifier* subclass) const;
- bool isExcluded(const Identifier* subclass) const;
-
- /// Begin of the ClassTreeMaskObjectIterator.
- inline const ClassTreeMask& begin() const { return (*this); }
- /// End of the ClassTreeMaskObjectIterator.
- inline BaseObject* end() const { return 0; }
-
- ClassTreeMask& operator=(const ClassTreeMask& other);
-
- bool operator==(const ClassTreeMask& other) const;
- bool operator!=(const ClassTreeMask& other) const;
-
- const ClassTreeMask& operator+() const;
- ClassTreeMask operator-() const;
-
- ClassTreeMask operator+(const ClassTreeMask& other) const;
- ClassTreeMask operator*(const ClassTreeMask& other) const;
- ClassTreeMask operator-(const ClassTreeMask& other) const;
- ClassTreeMask operator!() const;
-
- const ClassTreeMask& operator+=(const ClassTreeMask& other);
- const ClassTreeMask& operator*=(const ClassTreeMask& other);
- const ClassTreeMask& operator-=(const ClassTreeMask& other);
-
- ClassTreeMask operator&(const ClassTreeMask& other) const;
- ClassTreeMask operator|(const ClassTreeMask& other) const;
- ClassTreeMask operator^(const ClassTreeMask& other) const;
- ClassTreeMask operator~() const;
-
- const ClassTreeMask& operator&=(const ClassTreeMask& other);
- const ClassTreeMask& operator|=(const ClassTreeMask& other);
- const ClassTreeMask& operator^=(const ClassTreeMask& other);
-
- friend std::ostream& operator<<(std::ostream& out, const ClassTreeMask& mask);
-
- private:
- void add(ClassTreeMaskNode* node, const Identifier* subclass, bool bInclude, bool overwrite = true);
- bool isIncluded(ClassTreeMaskNode* node, const Identifier* subclass) const;
- void clean(ClassTreeMaskNode* node);
- bool nodeExists(const Identifier* subclass);
-
- ClassTreeMaskNode* root_; ///< The root-node of the internal rule-tree, usually BaseObject
- };
-
-
- // ###################################
- // ### ClassTreeMaskObjectIterator ###
- // ###################################
- /**
- @brief The ClassTreeMaskObjectIterator iterates through all objects of the classes that were included by a ClassTreeMask.
-
- This is done the following way:
- @code
- ClassTreeMask mask;
- for (ClassTreeMaskObjectIterator it = mask.begin(); it != mask.end(); ++it)
- it->doSomething();
- @endcode
-
- @note The ClassTreeMaskObjectIterator handles all objects as BaseObjects. If
- you want to use another class, you should use a dynamic_cast.
-
- The performance of ClassTreeMaskObjectIterator is good as long as you don't exclude
- subclasses of included classes. Of course you can still exlucde subclasses, but
- if this is done more often, we need a new implementation using a second ObjectList
- in the Identifier, containing all objects of exactly one class.
- */
- class _CoreExport ClassTreeMaskObjectIterator
- {
- public:
- /// Default-constructor: Does nothing.
- inline ClassTreeMaskObjectIterator() {}
- /// Copy-Constructor: Initializes the iterator from another ClassTreeMask.
- inline ClassTreeMaskObjectIterator(const ClassTreeMask& mask) { (*this) = mask; }
-
- ClassTreeMaskObjectIterator& operator=(const ClassTreeMask& mask);
-
- const ClassTreeMaskObjectIterator& operator++();
-
- /// Returns true if the ClassTreeMaskObjectIterator points at the given object.
- inline bool operator==(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) == pointer) || (!this->objectIterator_ && pointer == 0); }
- /// Returns true if the ClassTreeMaskObjectIterator doesn't point at the given object.
- inline bool operator!=(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) != pointer) || (!this->objectIterator_ && pointer != 0); }
- /// Returns true if the ClassTreeMaskObjectIterator hasn't already reached the end.
- inline operator bool() const { return (this->objectIterator_); }
- /// Returns the object the ClassTreeMaskObjectIterator currently points at.
- inline BaseObject* operator*() const { return (*this->objectIterator_); }
- /// Returns the object the ClassTreeMaskObjectIterator currently points at.
- inline BaseObject* operator->() const { return (*this->objectIterator_); }
-
- private:
- void create(ClassTreeMaskNode* node);
-
- std::list<std::pair<const Identifier*, bool> > subclasses_; ///< A list of all Identifiers through which objects the iterator should iterate
- std::list<std::pair<const Identifier*, bool> >::iterator subclassIterator_; ///< The current class of the iterator
- Iterator<BaseObject> objectIterator_; ///< The current object of the iterator
- };
-}
-
-#endif /* _ClassTreeMask_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ConfigFileManager.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ConfigFileManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ConfigFileManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,774 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of ConfigFileManager and its helper classes.
-*/
-
-#include "ConfigFileManager.h"
-
-#include <boost/filesystem.hpp>
-
-#include "util/Convert.h"
-#include "util/Math.h"
-#include "util/StringUtils.h"
-#include "ConfigValueContainer.h"
-#include "PathConfig.h"
-#include "command/ConsoleCommand.h"
-
-namespace orxonox
-{
- //////////////////////////
- // ConfigFileEntryValue //
- //////////////////////////
- /**
- @brief Updates the string that will be stored in the file after one of it's components (name, value, comment) has changed.
- */
- void ConfigFileEntryValue::update()
- {
- // Make sure we remove the quotes when bString changes
- if (this->bString_)
- this->value_ = stripEnclosingQuotes(this->value_);
- // Assemble the entry line
- this->fileEntry_ = this->getKeyString() + " = ";
- if (this->bString_ && !this->value_.empty())
- this->fileEntry_ += '"' + addSlashes(this->value_) + '"';
- else
- this->fileEntry_ += this->value_;
- if (!this->additionalComment_.empty())
- this->fileEntry_ += ' ' + this->additionalComment_;
- }
-
-
- ////////////////////////////////
- // ConfigFileEntryVectorValue //
- ////////////////////////////////
- /**
- @brief Updates the string that will be stored in the file after one of it's components (name, value, index, comment) has changed.
- */
- void ConfigFileEntryVectorValue::update()
- {
- this->keyString_ = this->name_ + '[' + multi_cast<std::string>(this->index_) + ']';
- ConfigFileEntryValue::update();
- }
-
-
- ///////////////////////
- // ConfigFileSection //
- ///////////////////////
- /**
- @brief Destructor: Deletes all entries.
- */
- ConfigFileSection::~ConfigFileSection()
- {
- for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
- delete (*(it++));
- }
-
- /**
- @brief Deletes all elements of a config vector if their index is greater or equal to @a startindex.
-
- @param name The name of the vector
- @param startindex The index of the first element that will be deleted
- */
- void ConfigFileSection::deleteVectorEntries(const std::string& name, unsigned int startindex)
- {
- for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
- {
- if (((*it)->getName() == name) && ((*it)->getIndex() >= startindex))
- {
- delete (*it);
- this->entries_.erase(it++);
- }
- else
- {
- ++it;
- }
- }
- }
-
- /**
- @brief Returns the size of a config vector.
- @param name The name of the vector
- */
- unsigned int ConfigFileSection::getVectorSize(const std::string& name) const
- {
- unsigned int size = 0;
- for (std::list<ConfigFileEntry*>::const_iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
- if ((*it)->getName() == name)
- if ((*it)->getIndex() > size)
- size = (*it)->getIndex();
- if (size == 0)
- return 0;
- else
- return (size + 1);
- }
-
- /**
- @brief Returns the title and comment of the section as it will be stored in the file.
- */
- std::string ConfigFileSection::getFileEntry() const
- {
- if (this->additionalComment_.empty())
- return ('[' + this->name_ + ']');
- else
- return ('[' + this->name_ + "] " + this->additionalComment_);
- }
-
- /**
- @brief Returns the entry with given name (or NULL if it doesn't exist).
-
- @param name The name of the entry
- */
- ConfigFileEntry* ConfigFileSection::getEntry(const std::string& name) const
- {
- for (std::list<ConfigFileEntry*>::const_iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
- {
- if ((*it)->getName() == name)
- return *it;
- }
- return NULL;
- }
-
- /**
- @brief Returns the entry of a vector element with given name and index (or NULL if it doesn't exist).
-
- @param name The name of the vector
- @param index The index of the element in the vector
- */
- ConfigFileEntry* ConfigFileSection::getEntry(const std::string& name, unsigned int index) const
- {
- for (std::list<ConfigFileEntry*>::const_iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
- {
- if (((*it)->getName() == name) && ((*it)->getIndex() == index))
- return *it;
- }
- return NULL;
- }
-
- /**
- @brief Returns the iterator to the entry with given name. If the entry doesn't exist, it is created using the fallback value.
-
- @param name The name of the entry
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- std::list<ConfigFileEntry*>::iterator ConfigFileSection::getOrCreateEntryIterator(const std::string& name, const std::string& fallback, bool bString)
- {
- for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
- {
- if ((*it)->getName() == name)
- {
- (*it)->setString(bString);
- return it;
- }
- }
-
- this->bUpdated_ = true;
-
- return this->entries_.insert(this->entries_.end(), new ConfigFileEntryValue(name, fallback, bString));
- }
-
- /**
- @brief Returns the iterator to the entry of a vector element with given name and index. If the entry doesn't exist, it is created using the fallback value.
-
- @param name The name of the vector
- @param index The index of the element in the vector
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- std::list<ConfigFileEntry*>::iterator ConfigFileSection::getOrCreateEntryIterator(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
- {
- for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
- {
- if (((*it)->getName() == name) && ((*it)->getIndex() == index))
- {
- (*it)->setString(bString);
- return it;
- }
- }
-
- this->bUpdated_ = true;
-
- if (index == 0)
- return this->entries_.insert(this->entries_.end(), new ConfigFileEntryVectorValue(name, index, fallback, bString));
- else
- return this->entries_.insert(++this->getOrCreateEntryIterator(name, index - 1, "", bString), new ConfigFileEntryVectorValue(name, index, fallback, bString));
- }
-
-
- ////////////////
- // ConfigFile //
- ////////////////
-
- const char* ConfigFile::DEFAULT_CONFIG_FOLDER = "defaultConfig";
-
- /**
- @brief Constructor: Initializes the config file.
- @param filename The file-name of this config file
- @param bCopyFallbackFile If true, the default config file is copied into the config-directory before loading the file
- */
- ConfigFile::ConfigFile(const std::string& filename, bool bCopyFallbackFile)
- : filename_(filename)
- , bCopyFallbackFile_(bCopyFallbackFile)
- , bUpdated_(false)
- {
- }
-
- /**
- @brief Destructor: Deletes all sections and entries.
- */
- ConfigFile::~ConfigFile()
- {
- this->clear();
- }
-
- /**
- @brief Loads the config file from the hard-disk and reads the sections and their values.
- */
- void ConfigFile::load()
- {
- // Be sure we start from new in the memory
- this->clear();
-
- boost::filesystem::path filepath(this->filename_);
- if (!filepath.is_complete())
- {
- filepath = PathConfig::getConfigPath() / filepath;
- if (this->bCopyFallbackFile_)
- {
- // Look for default file in the data folder
- if (!boost::filesystem::exists(filepath))
- {
- boost::filesystem::path defaultFilepath(PathConfig::getDataPath() / DEFAULT_CONFIG_FOLDER / this->filename_);
- if (boost::filesystem::exists(defaultFilepath))
- {
- // Try to copy default file from the data folder
- try
- {
- boost::filesystem::copy_file(defaultFilepath, filepath);
- COUT(3) << "Copied " << this->filename_ << " from the default config folder." << std::endl;
- }
- catch (const boost::filesystem::filesystem_error& ex)
- { COUT(1) << "Error in ConfigFile: " << ex.what() << std::endl; }
- }
- }
- }
- }
-
- // Open the file
- std::ifstream file;
- file.open(filepath.string().c_str(), std::fstream::in);
- if (file.is_open())
- {
- ConfigFileSection* newsection = 0;
-
- while (file.good() && !file.eof())
- {
- std::string line;
- std::getline(file, line);
-
- const std::string& temp = getStripped(line);
- if (!isEmpty(temp) && !isComment(temp))
- {
- size_t pos1 = temp.find('[');
- if (pos1 == 0) pos1 = line.find('['); else pos1 = std::string::npos;
- size_t pos2 = line.find(']');
-
- if (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1 + 1)
- {
- // New section
- const std::string& comment = line.substr(pos2 + 1);
- if (isComment(comment))
- newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1), comment);
- else
- newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1));
- this->sections_.insert(this->sections_.end(), newsection);
- continue;
- }
- }
-
- if (newsection != 0)
- {
- if (isComment(line))
- {
- // New comment
- newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryComment(removeTrailingWhitespaces(line)));
- continue;
- }
- else
- {
- size_t pos1 = line.find('=');
-
- if (pos1 != std::string::npos && pos1 > 0)
- {
- // New entry
- size_t pos2 = line.find('[');
- size_t pos3 = line.find(']');
- size_t commentposition = getNextCommentPosition(line, pos1 + 1);
- while (isBetweenQuotes(line, commentposition))
- {
- commentposition = getNextCommentPosition(line, commentposition + 1);
- }
- std::string value, comment;
- if (commentposition == std::string::npos)
- {
- value = line.substr(pos1 + 1);
- }
- else
- {
- value = line.substr(pos1 + 1, commentposition - pos1 - 1);
- comment = removeTrailingWhitespaces(line.substr(commentposition));
- }
-
- value = removeTrailingWhitespaces(value);
- value = removeSlashes(value);
-
- if (pos2 != std::string::npos && pos3 != std::string::npos && pos3 > pos2 + 1)
- {
- // There might be an array index
- unsigned int index = 0;
- if (convertValue(&index, line.substr(pos2 + 1, pos3 - pos2 - 1)))
- {
- // New array
- std::list<ConfigFileEntry*>::iterator it = newsection->getOrCreateEntryIterator(getStripped(line.substr(0, pos2)), index, value, false);
- (*it)->setValue(value);
- (*it)->setComment(comment);
- continue;
- }
- }
-
- // New value
- newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryValue(getStripped(line.substr(0, pos1)), value, false, comment));
- continue;
- }
- }
- }
- }
-
- file.close();
-
- COUT(3) << "Loaded config file \"" << this->filename_ << "\"." << std::endl;
-
- // DO NOT save the file --> we can open supposedly read only config files
- } // end file.is_open()
- }
-
- /**
- @brief Writes the sections and values to the hard-disk.
- */
- void ConfigFile::save() const
- {
- this->saveAs(this->filename_);
- }
-
- /**
- @brief Writes the sections and values to a given file on the hard-disk.
- */
- void ConfigFile::saveAs(const std::string& filename) const
- {
- boost::filesystem::path filepath(filename);
- if (!filepath.is_complete())
- filepath = PathConfig::getConfigPath() / filename;
- std::ofstream file;
- file.open(filepath.string().c_str(), std::fstream::out);
- file.setf(std::ios::fixed, std::ios::floatfield);
- file.precision(6);
-
- if (!file.is_open())
- {
- COUT(1) << "Error: Couldn't open config-file \"" << filename << "\"." << std::endl;
- return;
- }
-
- for (std::list<ConfigFileSection*>::const_iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
- {
- file << (*it)->getFileEntry() << std::endl;
-
- for (std::list<ConfigFileEntry*>::const_iterator it_entries = (*it)->getEntriesBegin(); it_entries != (*it)->getEntriesEnd(); ++it_entries)
- file << (*it_entries)->getFileEntry() << std::endl;
-
- file << std::endl;
- }
-
- file.close();
-
- COUT(4) << "Saved config file \"" << filename << "\"." << std::endl;
- }
-
- /**
- @brief Deletes all sections (which again delete all their values) and clears the list of sections.
- */
- void ConfigFile::clear()
- {
- for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); )
- delete (*(it++));
- this->sections_.clear();
- }
-
- /**
- @brief Deletes all elements of a config vector if their index is greater or equal to @a startindex.
-
- @param section The name of the section
- @param name The name of the vector
- @param startindex The index of the first element that will be deleted
- */
- void ConfigFile::deleteVectorEntries(const std::string& section, const std::string& name, unsigned int startindex)
- {
- if (ConfigFileSection* sectionPtr = this->getSection(section))
- {
- sectionPtr->deleteVectorEntries(name, startindex);
- this->save();
- }
- }
-
- /**
- @brief Returns a pointer to the section with given name (or NULL if the section doesn't exist).
- */
- ConfigFileSection* ConfigFile::getSection(const std::string& section) const
- {
- for (std::list<ConfigFileSection*>::const_iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
- if ((*it)->getName() == section)
- return (*it);
- return NULL;
- }
-
- /**
- @brief Returns a pointer to the section with given name. If it doesn't exist, the section is created.
- */
- ConfigFileSection* ConfigFile::getOrCreateSection(const std::string& section)
- {
- for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
- if ((*it)->getName() == section)
- return (*it);
-
- this->bUpdated_ = true;
-
- return (*this->sections_.insert(this->sections_.end(), new ConfigFileSection(section)));
- }
-
- /**
- @brief Saves the config file if it was updated (or if any of its sections were updated).
- */
- void ConfigFile::saveIfUpdated()
- {
- bool sectionsUpdated = false;
-
- for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
- {
- if ((*it)->bUpdated_)
- {
- sectionsUpdated = true;
- (*it)->bUpdated_ = false;
- }
- }
-
- if (this->bUpdated_ || sectionsUpdated)
- {
- this->bUpdated_ = false;
- this->save();
- }
- }
-
-
- ////////////////////////
- // SettingsConfigFile //
- ////////////////////////
-
- static const std::string __CC_load_name = "reloadSettings";
- static const std::string __CC_setFilename_name = "setSettingsFile";
- static const std::string __CC_config_name = "config";
- static const std::string __CC_tconfig_name = "tconfig";
- static const std::string __CC_getConfig_name = "getConfig";
-
- SetConsoleCommand(__CC_load_name, &ConfigFile::load);
- SetConsoleCommand(__CC_setFilename_name, &SettingsConfigFile::setFilename);
- SetConsoleCommand(__CC_config_name, &SettingsConfigFile::config).argumentCompleter(0, autocompletion::settingssections()).argumentCompleter(1, autocompletion::settingsentries()).argumentCompleter(2, autocompletion::settingsvalue());
- SetConsoleCommand(__CC_tconfig_name, &SettingsConfigFile::tconfig).argumentCompleter(0, autocompletion::settingssections()).argumentCompleter(1, autocompletion::settingsentries()).argumentCompleter(2, autocompletion::settingsvalue());
- SetConsoleCommand(__CC_getConfig_name, &SettingsConfigFile::getConfig).argumentCompleter(0, autocompletion::settingssections()).argumentCompleter(1, autocompletion::settingsentries());
-
- SettingsConfigFile* SettingsConfigFile::singletonPtr_s = 0;
-
- /**
- @brief Constructor: Activates the console commands.
- */
- SettingsConfigFile::SettingsConfigFile(const std::string& filename)
- : ConfigFile(filename)
- {
- ModifyConsoleCommand(__CC_load_name).setObject(this);
- ModifyConsoleCommand(__CC_setFilename_name).setObject(this);
- ModifyConsoleCommand(__CC_config_name).setObject(this);
- ModifyConsoleCommand(__CC_tconfig_name).setObject(this);
- ModifyConsoleCommand(__CC_getConfig_name).setObject(this);
- }
-
- /**
- @brief Destructor: Deactivates the console commands.
- */
- SettingsConfigFile::~SettingsConfigFile()
- {
- ModifyConsoleCommand(__CC_load_name).setObject(0);
- ModifyConsoleCommand(__CC_setFilename_name).setObject(0);
- ModifyConsoleCommand(__CC_config_name).setObject(0);
- ModifyConsoleCommand(__CC_tconfig_name).setObject(0);
- ModifyConsoleCommand(__CC_getConfig_name).setObject(0);
- }
-
- /**
- @brief Loads the config file and updates the @ref ConfigValueContainer "config value containers".
- */
- void SettingsConfigFile::load()
- {
- ConfigFile::load();
- this->updateConfigValues();
- }
-
- /**
- @brief Changes the file-name.
- */
- void SettingsConfigFile::setFilename(const std::string& filename)
- {
- ConfigFileManager::getInstance().setFilename(ConfigFileType::Settings, filename);
- }
-
- /**
- @brief Registers a new @ref ConfigValueContainer "config value container".
- */
- void SettingsConfigFile::addConfigValueContainer(ConfigValueContainer* container)
- {
- if (container == NULL)
- return;
- std::pair<std::string, ConfigValueContainer*> second(getLowercase(container->getName()), container);
- this->containers_.insert(std::make_pair(getLowercase(container->getSectionName()), second));
- this->sectionNames_.insert(container->getSectionName());
- }
-
- /**
- @brief Unregisters a @ref ConfigValueContainer "config value container".
- */
- void SettingsConfigFile::removeConfigValueContainer(ConfigValueContainer* container)
- {
- if (container == NULL)
- return;
- const std::string& sectionLC = getLowercase(container->getSectionName());
- ContainerMap::iterator upper = this->containers_.upper_bound(sectionLC);
- for (ContainerMap::iterator it = this->containers_.lower_bound(sectionLC); it != upper; ++it)
- {
- if (it->second.second == container)
- {
- // Remove entry from section name set this was the last container for that section
- if (upper == this->containers_.lower_bound(sectionLC))
- this->sectionNames_.erase(container->getSectionName());
- this->containers_.erase(it);
- break;
- }
- }
- }
-
- /**
- @brief Updates all @ref ConfigValueContainer "config value containers".
- */
- void SettingsConfigFile::updateConfigValues()
- {
- // todo: can this be done more efficiently? looks like some identifiers will be updated multiple times.
-
- for (ContainerMap::const_iterator it = this->containers_.begin(); it != this->containers_.end(); ++it)
- {
- it->second.second->update();
- it->second.second->getIdentifier()->updateConfigValues();
- }
- }
-
- /**
- @brief Removes entries and sections from the file that don't exist anymore (i.e. if there's no corresponding @ref ConfigValueContainer "config value container").
- @param bCleanComments If true, comments are also removed from the file
- */
- void SettingsConfigFile::clean(bool bCleanComments)
- {
- for (std::list<ConfigFileSection*>::iterator itSection = this->sections_.begin(); itSection != this->sections_.end(); )
- {
- const std::string& sectionLC = getLowercase((*itSection)->getName());
- ContainerMap::const_iterator lower = this->containers_.lower_bound(sectionLC);
- ContainerMap::const_iterator upper = this->containers_.upper_bound(sectionLC);
- if (lower != upper)
- {
- // The section exists, delete comment
- if (bCleanComments)
- (*itSection)->setComment("");
- for (std::list<ConfigFileEntry*>::iterator itEntry = (*itSection)->entries_.begin(); itEntry != (*itSection)->entries_.end(); )
- {
- const std::string& entryLC = getLowercase((*itEntry)->getName());
- bool bFound = false;
- for (ContainerMap::const_iterator itContainer = lower; itContainer != upper; ++itContainer)
- {
- if (itContainer->second.first == entryLC)
- {
- // The config-value exists, delete comment
- if (bCleanComments)
- (*itEntry)->setComment("");
- ++itEntry;
- bFound = true;
- break;
- }
- }
- if (!bFound)
- {
- // The config-value doesn't exist
- delete (*itEntry);
- (*itSection)->entries_.erase(itEntry++);
- }
- }
- ++itSection;
- }
- else
- {
- // The section doesn't exist
- delete (*itSection);
- this->sections_.erase(itSection++);
- }
- }
-
- // Save the file
- this->save();
- }
-
- /**
- @brief Console-command: Changes the value of an entry and stores it the file.
-
- @param section The section of the config value
- @param entry The name of the config value
- @param value The new value
- */
- void SettingsConfigFile::config(const std::string& section, const std::string& entry, const std::string& value)
- {
- if (!this->configImpl(section, entry, value, &ConfigValueContainer::set))
- COUT(1) << "Error: Config value \"" << entry << "\" in section \"" << section << "\" doesn't exist." << std::endl;
- }
-
- /**
- @brief Console-command: Changes the value of an entry, but doesn't store it in the file (it's only a temporary change).
-
- @param section The section of the config value
- @param entry The name of the config value
- @param value The new value
- */
- void SettingsConfigFile::tconfig(const std::string& section, const std::string& entry, const std::string& value)
- {
- if (!this->configImpl(section, entry, value, &ConfigValueContainer::tset))
- COUT(1) << "Error: Config value \"" << entry << "\" in section \"" << section << "\" doesn't exist." << std::endl;
- }
-
- /**
- @brief Changes the value of an entry, depending on @a function, either by using "set" or "tset"
-
- @param section The section of the config value
- @param entry The name of the config value
- @param value The new value
- @param function The function ("set" or "tset") that will be used to change the value.
- */
- bool SettingsConfigFile::configImpl(const std::string& section, const std::string& entry, const std::string& value, bool (ConfigValueContainer::*function)(const MultiType&))
- {
- const std::string& sectionLC = getLowercase(section);
- const std::string& entryLC = getLowercase(entry);
- ContainerMap::iterator upper = this->containers_.upper_bound(sectionLC);
- for (ContainerMap::iterator it = this->containers_.lower_bound(sectionLC); it != upper; ++it)
- {
- // Note: Config value vectors cannot be supported
- if (it->second.first == entryLC && !it->second.second->isVector())
- {
- return (it->second.second->*function)(value);
- }
- }
- return false;
- }
-
- /**
- @brief Console-command: Returns the value of a given entry.
-
- @param section The section of the config value
- @param entry The name of the config value
- */
- std::string SettingsConfigFile::getConfig(const std::string& section, const std::string& entry)
- {
- const std::string& sectionLC = getLowercase(section);
- const std::string& entryLC = getLowercase(entry);
- ContainerMap::iterator upper = this->containers_.upper_bound(sectionLC);
- for (ContainerMap::iterator it = this->containers_.lower_bound(sectionLC); it != upper; ++it)
- {
- // Note: Config value vectors cannot be supported
- if (it->second.first == entryLC && ! it->second.second->isVector())
- {
- std::string value;
- it->second.second->getValue<std::string, OrxonoxClass>(&value, NULL);
- return value;
- }
- }
- return "";
- }
-
-
- ///////////////////////
- // ConfigFileManager //
- ///////////////////////
-
- ConfigFileManager* ConfigFileManager::singletonPtr_s = 0;
-
- /// Constructor: Initializes the array of config files with NULL.
- ConfigFileManager::ConfigFileManager()
- {
- this->configFiles_.assign(NULL);
- }
-
- /// Destructor: Deletes the config files.
- ConfigFileManager::~ConfigFileManager()
- {
- for (boost::array<ConfigFile*, 3>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
- if (*it)
- delete (*it);
- }
-
- /// Defines the file-name for the config file of a given type (settings, calibration, etc.).
- void ConfigFileManager::setFilename(ConfigFileType::Value type, const std::string& filename)
- {
- if (this->getConfigFile(type))
- delete this->configFiles_[type];
- // Create and load config file
- switch (type)
- {
- case ConfigFileType::Settings:
- this->configFiles_[type] = new SettingsConfigFile(filename);
- break;
- case ConfigFileType::JoyStickCalibration:
- case ConfigFileType::CommandHistory:
- this->configFiles_[type] = new ConfigFile(filename);
- break;
- }
- this->configFiles_[type]->load();
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/ConfigFileManager.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ConfigFileManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ConfigFileManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,602 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Config ConfigFile
- @brief Declaration of ConfigFileManager and its helper classes, used to load and save config files.
-*/
-
-#ifndef _ConfigFileManager_H__
-#define _ConfigFileManager_H__
-
-#include "CorePrereqs.h"
-
-#include <list>
-#include <map>
-#include <set>
-#include <string>
-#include <boost/array.hpp>
-
-#include "util/Singleton.h"
-
-namespace orxonox // tolua_export
-{ // tolua_export
-
- /////////////////////
- // ConfigFileEntry //
- /////////////////////
- /**
- @brief This class represents an entry in the config file.
-
- This class is pure virtual. Use one of the derived classes to define the type of the entry.
- */
- class _CoreExport ConfigFileEntry
- {
- public:
- /// Destructor
- virtual ~ConfigFileEntry() {};
-
- /// Changes the value of the entry.
- virtual void setValue(const std::string& value) = 0;
- /// Returns the value of the entry.
- virtual const std::string& getValue() const = 0;
-
- /// Returns the name of the entry
- virtual const std::string& getName() const = 0;
-
- /// Changes the comment of the entry (will be placed after the value)
- virtual void setComment(const std::string& comment) = 0;
-
- /// Returns the index of the entry in a vector (used only if it is a vector)
- virtual unsigned int getIndex() const { return 0; }
-
- /// Defines if this entry is treated as string which means some special treatment of special characters.
- virtual void setString(bool bString) = 0;
-
- /// Returns the line as it will be stored in the config file.
- virtual const std::string& getFileEntry() const = 0;
- };
-
-
- //////////////////////////
- // ConfigFileEntryValue //
- //////////////////////////
- /**
- @brief This class represents a normal value in the config file.
- */
- class _CoreExport ConfigFileEntryValue : public ConfigFileEntry
- {
- public:
- /**
- @brief Constructor: Initializes the entry.
-
- @param name The name of the entry
- @param value The value of the entry
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- @param additionalComment An optional comment that will be placed behind the value in the config file
- */
- inline ConfigFileEntryValue(const std::string& name, const std::string& value = "", bool bString = false, const std::string& additionalComment = "")
- : name_(name)
- , value_(value)
- , additionalComment_(additionalComment)
- , bString_(bString)
- { this->update(); }
-
- /// Destructor
- inline virtual ~ConfigFileEntryValue() {}
-
- inline virtual const std::string& getName() const
- { return this->name_; }
-
- inline virtual void setComment(const std::string& comment)
- { this->additionalComment_ = comment; this->update(); }
-
- inline virtual void setValue(const std::string& value)
- { this->value_ = value; this->update(); }
- inline virtual const std::string& getValue() const
- { return this->value_; }
-
- inline void virtual setString(bool bString)
- { this->bString_ = bString; this->update(); }
-
- inline virtual const std::string& getFileEntry() const
- { return this->fileEntry_; }
-
- /// Returns the "key" of the value (in this case it's just the name of the entry, but for vectors it's different)
- inline virtual const std::string& getKeyString() const
- { return this->name_; }
-
- protected:
- virtual void update();
-
- const std::string name_; ///< The name of the value
- std::string value_; ///< The value
- std::string additionalComment_; ///< The additional comment
- std::string fileEntry_; ///< The string as it will be stored in the config file
- bool bString_; ///< If true, the value is treated as string which means some special treatment of special characters.
- };
-
-
- ////////////////////////////////
- // ConfigFileEntryVectorValue //
- ////////////////////////////////
- /**
- @brief Subclass of ConfigFileEntryValue, represents an element of a vector.
- */
- class _CoreExport ConfigFileEntryVectorValue : public ConfigFileEntryValue
- {
- public:
- /**
- @brief Constructor: Initializes the entry.
-
- @param name The name of the vector
- @param index The index of the element in the vector
- @param value The value of the element
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- @param additionalComment An optional comment that will be placed behind the value in the config file
- */
- inline ConfigFileEntryVectorValue(const std::string& name, unsigned int index, const std::string& value = "", bool bString = false, const std::string& additionalComment = "")
- : ConfigFileEntryValue(name, value, bString, additionalComment)
- , index_(index)
- { this->update(); /*No virtual calls in base class ctor*/ }
-
- /// Destructor
- inline ~ConfigFileEntryVectorValue() {}
-
- inline unsigned int getIndex() const
- { return this->index_; }
-
- /// Returns the "key" of the value (the name of the vector plus the index of the element)
- inline const std::string& getKeyString() const
- { return this->keyString_; }
-
- private:
- void update();
-
- unsigned int index_; ///< The index of the element in the vector
- std::string keyString_; ///< The full name of the entry (the name of the vector plus the index of the element)
- };
-
-
- ////////////////////////////
- // ConfigFileEntryComment //
- ////////////////////////////
- /**
- @brief This class represents a line in the config file which contains only a comment.
- */
- class _CoreExport ConfigFileEntryComment : public ConfigFileEntry
- {
- public:
- /// Constructor: Initializes the object.
- inline ConfigFileEntryComment(const std::string& comment) : comment_(comment) {}
-
- /// Destructor
- inline virtual ~ConfigFileEntryComment() {}
-
- inline virtual const std::string& getName() const
- { return this->comment_; }
-
- inline virtual void setComment(const std::string& comment)
- { this->comment_ = comment; }
-
- inline virtual void setValue(const std::string& value)
- {}
- inline virtual const std::string& getValue() const
- { return BLANKSTRING; }
-
- inline void setString(bool bString)
- {}
-
- inline virtual const std::string& getFileEntry() const
- { return this->comment_; }
-
- private:
- std::string comment_; ///< The comment
- };
-
-
- ///////////////////////
- // ConfigFileSection //
- ///////////////////////
- /**
- @brief Represents a section in a config file.
-
- A section has a name and a list of config values.
- */
- class _CoreExport ConfigFileSection
- {
- friend class ConfigFile;
- friend class SettingsConfigFile;
-
- public:
- /**
- @brief Constructor: Initializes the section.
-
- @param name The name of the section
- @param additionalComment An additional comment placed after the title of the section in the config file
- */
- inline ConfigFileSection(const std::string& name, const std::string& additionalComment = "")
- : name_(name)
- , additionalComment_(additionalComment)
- , bUpdated_(false)
- {}
- ~ConfigFileSection();
-
- /// Returns the name of the section.
- inline const std::string& getName() const
- { return this->name_; }
-
- /// Changes the comment which is placed after the title of the section in the config file.
- inline void setComment(const std::string& comment)
- { this->additionalComment_ = comment; }
-
- /**
- @brief Stores a value in the section. If the entry doesn't exist, it's created.
-
- @param name The name of the entry
- @param value The new value
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline void setValue(const std::string& name, const std::string& value, bool bString)
- { this->getOrCreateEntry(name, value, bString)->setValue(value); }
- /**
- @brief Returns the value of a given entry in the section. Returns a blank string if the value doesn't exist.
-
- @param name The name of the entry
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getValue(const std::string& name, bool bString)
- {
- ConfigFileEntry* entry = this->getEntry(name);
- if (entry)
- {
- entry->setString(bString); // if the entry was loaded from the config file, we have to tell it if it's a string
- return entry->getValue();
- }
- return BLANKSTRING;
- }
- /**
- @brief Returns the value of a given entry in the section. If it doesn't exist, the entry is created using the fallback value.
-
- @param name The name of the entry
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getOrCreateValue(const std::string& name, const std::string& fallback, bool bString)
- { return this->getOrCreateEntry(name, fallback, bString)->getValue(); }
-
- /**
- @brief Stores the value of an element of a vector in the section. If the entry doesn't exist, it's created.
-
- @param name The name of the vector
- @param index The index of the element in the vector
- @param value The new value
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline void setValue(const std::string& name, unsigned int index, const std::string& value, bool bString)
- { this->getOrCreateEntry(name, index, value, bString)->setValue(value); }
- /**
- @brief Returns the value of a given element of a vector in the section. Returns a blank string if the value doesn't exist.
-
- @param name The name of the vector
- @param index The index of the element in the vector
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getValue(const std::string& name, unsigned int index, bool bString)
- {
- ConfigFileEntry* entry = this->getEntry(name, index);
- if (entry)
- {
- entry->setString(bString); // if the entry was loaded from the config file, we have to tell it if it's a string
- return entry->getValue();
- }
- return BLANKSTRING;
- }
- /**
- @brief Returns the value of a given element of a vector in the section. If it doesn't exist, the entry is created using the fallback value.
-
- @param name The name of the vector
- @param index The index of the element in the vector
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getOrCreateValue(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
- { return this->getOrCreateEntry(name, index, fallback, bString)->getValue(); }
-
- void deleteVectorEntries(const std::string& name, unsigned int startindex = 0);
- unsigned int getVectorSize(const std::string& name) const;
-
- std::string getFileEntry() const;
-
- private:
- /// Returns the list of entries in this section.
- std::list<ConfigFileEntry*>& getEntries()
- { return this->entries_; }
- /// Returns the begin-iterator of the list of entries in this section.
- std::list<ConfigFileEntry*>::const_iterator getEntriesBegin() const
- { return this->entries_.begin(); }
- /// Returns the end-iterator of the list of entries in this section.
- std::list<ConfigFileEntry*>::const_iterator getEntriesEnd() const
- { return this->entries_.end(); }
-
- std::list<ConfigFileEntry*>::iterator getOrCreateEntryIterator(const std::string& name, const std::string& fallback, bool bString);
- std::list<ConfigFileEntry*>::iterator getOrCreateEntryIterator(const std::string& name, unsigned int index, const std::string& fallback, bool bString);
-
- ConfigFileEntry* getEntry(const std::string& name) const;
- /**
- @brief Returns the entry with given name. If it doesn't exist, the entry is created using the fallback value.
-
- @param name The name of the entry
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline ConfigFileEntry* getOrCreateEntry(const std::string& name, const std::string& fallback, bool bString)
- { return (*this->getOrCreateEntryIterator(name, fallback, bString)); }
-
- ConfigFileEntry* getEntry(const std::string& name, unsigned int index) const;
- /**
- @brief Returns the entry that contains an element of a vector with given name. If it doesn't exist, the entry is created using the fallback value.
-
- @param name The name of the entry
- @param index The index of the element in the vector
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline ConfigFileEntry* getOrCreateEntry(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
- { return (*this->getOrCreateEntryIterator(name, index, fallback, bString)); }
-
- std::string name_; ///< The name of the section
- std::string additionalComment_; ///< The additional comment which is placed after the title of the section in the config file
- std::list<ConfigFileEntry*> entries_; ///< The list of entries in this section
- bool bUpdated_; ///< True if an entry is created
- };
-
-
- ////////////////
- // ConfigFile //
- ////////////////
- /**
- @brief This class represents a config file, which is stored on the hard-disk and contains config values in different sections.
-
- It provides an interface to manipulate the sections and values.
- */
- class _CoreExport ConfigFile
- {
- public:
- ConfigFile(const std::string& filename, bool bCopyFallbackFile = true);
- virtual ~ConfigFile();
-
- virtual void load();
- virtual void save() const;
- virtual void saveAs(const std::string& filename) const;
- virtual void clear();
-
- /// Returns the file-name of this config file
- inline const std::string& getFilename()
- { return this->filename_; }
-
- /**
- @brief Stores a value in the config file. If the entry or its section doesn't exist, it's created.
-
- @param section The name of the section
- @param name The name of the entry
- @param value The new value
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline void setValue(const std::string& section, const std::string& name, const std::string& value, bool bString)
- {
- this->getOrCreateSection(section)->setValue(name, value, bString);
- this->save();
- }
- /**
- @brief Returns the value of a given entry in the config file. Returns a blank string if the value doesn't exist.
-
- @param section The name of the section
- @param name The name of the entry
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getValue(const std::string& section, const std::string& name, bool bString)
- {
- ConfigFileSection* sectionPtr = this->getSection(section);
- return (sectionPtr ? sectionPtr->getValue(name, bString) : BLANKSTRING);
- }
- /**
- @brief Returns the value of a given entry in the config file. If it doesn't exist, the entry is created using the fallback value.
-
- @param section The name of the section
- @param name The name of the entry
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getOrCreateValue(const std::string& section, const std::string& name, const std::string& fallback, bool bString)
- {
- const std::string& output = this->getOrCreateSection(section)->getOrCreateValue(name, fallback, bString);
- this->saveIfUpdated();
- return output;
- }
-
- /**
- @brief Stores the value of an element of a vector in the config file. If the entry or its section doesn't exist, it's created.
-
- @param section The name of the section
- @param name The name of the vector
- @param index The index of the element in the vector
- @param value The new value
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline void setValue(const std::string& section, const std::string& name, unsigned int index, const std::string& value, bool bString)
- {
- this->getOrCreateSection(section)->setValue(name, index, value, bString);
- this->save();
- }
- /**
- @brief Returns the value of a given element of a vector in the config file. Returns a blank string if the value doesn't exist.
-
- @param section The name of the section
- @param name The name of the vector
- @param index The index of the element in the vector
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- inline const std::string& getValue(const std::string& section, const std::string& name, unsigned int index, bool bString)
- {
- ConfigFileSection* sectionPtr = this->getSection(section);
- return (sectionPtr ? sectionPtr->getValue(name, index, bString) : BLANKSTRING);
- }
- /**
- @brief Returns the value of a given element of a vector in the config file. If it doesn't exist, the entry is created using the fallback value.
-
- @param section The name of the section
- @param name The name of the vector
- @param index The index of the element in the vector
- @param fallback The value that will be used if the entry doesn't exist
- @param bString If true, the value is treated as string which means some special treatment of special characters.
- */
- const std::string& getOrCreateValue(const std::string& section, const std::string& name, unsigned int index, const std::string& fallback, bool bString)
- {
- const std::string& output = this->getOrCreateSection(section)->getOrCreateValue(name, index, fallback, bString);
- this->saveIfUpdated();
- return output;
- }
-
- void deleteVectorEntries(const std::string& section, const std::string& name, unsigned int startindex = 0);
- /**
- @brief Returns the size of a config vector.
- @param section The section of the vector
- @param name The name of the vector
- */
- inline unsigned int getVectorSize(const std::string& section, const std::string& name) const
- {
- ConfigFileSection* sectionPtr = this->getSection(section);
- return (sectionPtr ? sectionPtr->getVectorSize(name) : 0);
- }
-
- static const char* DEFAULT_CONFIG_FOLDER; ///< The folder where the default config files will be stored
-
- protected:
- ConfigFileSection* getSection(const std::string& section) const;
- ConfigFileSection* getOrCreateSection(const std::string& section);
-
- std::list<ConfigFileSection*> sections_; ///< A list of sections in this config file
-
- private:
- void saveIfUpdated();
-
- const std::string filename_; ///< The filename of this config file
- const bool bCopyFallbackFile_; ///< If true, the default config file is copied into the config-directory before loading the file
- bool bUpdated_; ///< Becomes true if a section is added
- };
-
-
- ////////////////////////
- // SettingsConfigFile //
- ////////////////////////
- /**
- @brief Child class of ConfigFile, used to store the settings of the game.
-
- In addition to ConfigFile, this class provides an interface to manipulate the settings
- with console commands and to cache entries in instances of ConfigValueContainer.
-
- SettingsConfigFile is a Singleton, meaning there's only one instance of this class
- (and thus only one config file that stores settings).
- */
- class _CoreExport SettingsConfigFile // tolua_export
- : public ConfigFile, public Singleton<SettingsConfigFile>
- { // tolua_export
- friend class Singleton<SettingsConfigFile>;
-
- public:
- typedef std::multimap<std::string, std::pair<std::string, ConfigValueContainer*> > ContainerMap;
-
- SettingsConfigFile(const std::string& filename);
- ~SettingsConfigFile();
-
- void load(); // tolua_export
- void setFilename(const std::string& filename); // tolua_export
- void clean(bool bCleanComments = false); // tolua_export
-
- void config(const std::string& section, const std::string& entry, const std::string& value); // tolua_export
- void tconfig(const std::string& section, const std::string& entry, const std::string& value); // tolua_export
- std::string getConfig(const std::string& section, const std::string& entry); // tolua_export
-
- void addConfigValueContainer(ConfigValueContainer* container);
- void removeConfigValueContainer(ConfigValueContainer* container);
-
- /// Returns a set containing the names of all sections in this config file.
- inline const std::set<std::string>& getSectionNames()
- { return this->sectionNames_; }
- /// Returns the lower-bound-iterator of the @ref ConfigValueContainer "config value containers" for the given section.
- inline ContainerMap::const_iterator getContainerLowerBound(const std::string section)
- { return this->containers_.lower_bound(section); }
- /// Returns the upper-bound-iterator of the @ref ConfigValueContainer "config value containers" for the given section.
- inline ContainerMap::const_iterator getContainerUpperBound(const std::string section)
- { return this->containers_.upper_bound(section); }
-
- static SettingsConfigFile& getInstance() { return Singleton<SettingsConfigFile>::getInstance(); } // tolua_export
-
- private:
- void updateConfigValues();
- bool configImpl(const std::string& section, const std::string& entry, const std::string& value, bool (ConfigValueContainer::*function)(const MultiType&));
-
- ContainerMap containers_; ///< Stores all @ref ConfigValueContainer "config value containers"
- std::set<std::string> sectionNames_; ///< Stores all section names
- static SettingsConfigFile* singletonPtr_s; ///< The singleton pointer
- }; // tolua_export
-
-
- ///////////////////////
- // ConfigFileManager //
- ///////////////////////
- /**
- @brief Manages the different config files (settings, calibration, etc). Implemented as Singleton.
- */
- class _CoreExport ConfigFileManager : public Singleton<ConfigFileManager>
- {
- friend class Singleton<ConfigFileManager>;
- public:
- ConfigFileManager();
- ~ConfigFileManager();
-
- void setFilename(ConfigFileType::Value type, const std::string& filename);
-
- /// Returns the config file of a given type (settings, calibration, etc.)
- inline ConfigFile* getConfigFile(ConfigFileType::Value type)
- {
- // Check array bounds
- return configFiles_.at(type);
- }
-
- private:
- ConfigFileManager(const ConfigFileManager&); ///< Copy-constructor: not implemented
-
- boost::array<ConfigFile*, 3> configFiles_; ///< Stores the config files for each type in an array (must have the same size like ConfigFileType::Value)
- static ConfigFileManager* singletonPtr_s; ///< Stores the singleton-pointer
- };
-} // tolua_export
-
-#endif /* _ConfigFileManager_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,353 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the ConfigValueContainer class.
-*/
-
-#include "ConfigValueContainer.h"
-
-#include "util/Convert.h"
-#include "util/SubString.h"
-#include "ConfigFileManager.h"
-#include "Language.h"
-
-namespace orxonox
-{
- const unsigned int MAX_VECTOR_INDEX = 255; // to avoid up to 4*10^9 vector entries in the config file after accidentally using a wrong argument
-
- /**
- @brief Initializes the ConfigValueContainer with default values.
- */
- void ConfigValueContainer::init(ConfigFileType::Value type, Identifier* identifier, const std::string& sectionname, const std::string& varname)
- {
- this->type_ = type;
- this->identifier_ = identifier;
- this->sectionname_ = sectionname;
- this->varname_ = varname;
- this->callback_ = 0;
- this->bContainerIsNew_ = true;
- this->bDoInitialCallback_ = false;
- this->bAddedDescription_ = false;
-
- // Register containers for general settings
- if (this->type_ == ConfigFileType::Settings)
- SettingsConfigFile::getInstance().addConfigValueContainer(this);
- }
-
- /**
- @brief Does some special initialization for single config-values.
- */
- void ConfigValueContainer::initValue(const MultiType& defvalue)
- {
- this->value_ = defvalue;
- this->bIsVector_ = false;
-
- this->defvalueString_ = this->value_.getString();
- this->update();
- }
-
- /**
- @brief Does some special initialization for vector config-values.
- */
- void ConfigValueContainer::initVector()
- {
- this->bIsVector_ = true;
-
- for (unsigned int i = 0; i < this->valueVector_.size(); i++)
- {
- ConfigFileManager::getInstance().getConfigFile(this->type_)->getOrCreateValue(this->sectionname_, this->varname_, i, this->valueVector_[i], this->value_.isType(MT_Type::String));
- this->defvalueStringVector_.push_back(this->valueVector_[i]);
- }
-
- this->update();
- }
-
- /**
- @brief Destructor: Deletes the callback object if necessary.
- */
- ConfigValueContainer::~ConfigValueContainer()
- {
- if (this->callback_)
- delete this->callback_;
-
- // Unregister general settings containers
- if (this->type_ == ConfigFileType::Settings && SettingsConfigFile::exists())
- SettingsConfigFile::getInstance().removeConfigValueContainer(this);
- }
-
- /**
- @brief Assigns a new value to the config-value of all objects and writes the change into the config-file.
- @param input The new value
- @return True if the new value was successfully assigned
- */
- bool ConfigValueContainer::set(const MultiType& input)
- {
- if (this->bIsVector_)
- {
- return this->callFunctionWithIndex(&ConfigValueContainer::set, input);
- }
- else
- {
- if (this->tset(input))
- {
- ConfigFileManager::getInstance().getConfigFile(this->type_)->setValue(this->sectionname_, this->varname_, input, this->value_.isType(MT_Type::String));
- return true;
- }
- }
- return false;
- }
-
- /**
- @brief Assigns a new value to the config-value of all objects and writes the change into the config-file.
- @param index The index in the vector
- @param input The new value
- @return True if the new value was successfully assigned
- */
- bool ConfigValueContainer::set(unsigned int index, const MultiType& input)
- {
- if (this->bIsVector_)
- {
- if (this->tset(index, input))
- {
- ConfigFileManager::getInstance().getConfigFile(this->type_)->setValue(this->sectionname_, this->varname_, index, input, this->value_.isType(MT_Type::String));
- return true;
- }
- }
- else
- {
- COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
- }
- return false;
- }
-
- /**
- @brief Assigns a new value to the config-value of all objects, but doesn't change the config-file (t stands for temporary).
- @param input The new value. If bIsVector_ then write "index value"
- @return True if the new value was successfully assigned
- */
- bool ConfigValueContainer::tset(const MultiType& input)
- {
- if (this->bIsVector_)
- {
- return this->callFunctionWithIndex(&ConfigValueContainer::tset, input);
- return false;
- }
- else
- {
- this->value_ = input;
-
- if (this->identifier_)
- this->identifier_->updateConfigValues();
-
- return true;
- }
- }
-
- /**
- @brief Assigns a new value to the config-value of all objects, but doesn't change the config-file (t stands for temporary).
- @param index The index in the vector
- @param input The new value
- @return True if the new value was successfully assigned
- */
- bool ConfigValueContainer::tset(unsigned int index, const MultiType& input)
- {
- if (this->bIsVector_)
- {
- if (index > MAX_VECTOR_INDEX)
- {
- COUT(1) << "Error: Index " << index << " is too large." << std::endl;
- return false;
- }
-
- if (index >= this->valueVector_.size())
- {
- for (unsigned int i = this->valueVector_.size(); i <= index; i++)
- {
- this->valueVector_.push_back(MultiType());
- }
- }
-
- this->valueVector_[index] = input;
-
- if (this->identifier_)
- this->identifier_->updateConfigValues();
-
- return true;
- }
- else
- {
- COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
- return false;
- }
- }
-
- /**
- @brief Adds a new entry to the end of the vector.
- @param input The new entry
- @return True if the new entry was successfully added
- */
- bool ConfigValueContainer::add(const MultiType& input)
- {
- if (this->bIsVector_)
- return this->set(this->valueVector_.size(), input);
-
- COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
- return false;
- }
-
- /**
- @brief Removes an existing entry from the vector.
- @param index The index of the entry
- @return True if the entry was removed
- */
- bool ConfigValueContainer::remove(unsigned int index)
- {
- if (this->bIsVector_)
- {
- if (index < this->valueVector_.size())
- {
- // Erase the entry from the vector, change (shift) all entries beginning with index in the config file, remove the last entry from the file
- this->valueVector_.erase(this->valueVector_.begin() + index);
- for (unsigned int i = index; i < this->valueVector_.size(); i++)
- ConfigFileManager::getInstance().getConfigFile(this->type_)->setValue(this->sectionname_, this->varname_, i, this->valueVector_[i], this->value_.isType(MT_Type::String));
- ConfigFileManager::getInstance().getConfigFile(this->type_)->deleteVectorEntries(this->sectionname_, this->varname_, this->valueVector_.size());
-
- return true;
- }
- COUT(1) << "Error: Invalid vector-index." << std::endl;
- }
-
- COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is not a vector." << std::endl;
- return false;
- }
-
- /**
- @brief Sets the value of the variable back to the default value and resets the config-file entry.
- */
- bool ConfigValueContainer::reset()
- {
- if (!this->bIsVector_)
- return this->set(this->defvalueString_);
- else
- {
- bool success = true;
- for (unsigned int i = 0; i < this->defvalueStringVector_.size(); i++)
- if (!this->set(i, this->defvalueStringVector_[i]))
- success = false;
- ConfigFileManager::getInstance().getConfigFile(this->type_)->deleteVectorEntries(this->sectionname_, this->varname_, this->defvalueStringVector_.size());
- return success;
- }
- }
-
- /**
- @brief Retrieves the configured value from the currently loaded config-file.
- */
- void ConfigValueContainer::update()
- {
- if (!this->bIsVector_)
- this->value_ = ConfigFileManager::getInstance().getConfigFile(this->type_)->getOrCreateValue(this->sectionname_, this->varname_, this->defvalueString_, this->value_.isType(MT_Type::String));
- else
- {
- this->valueVector_.clear();
- unsigned int vectorSize = ConfigFileManager::getInstance().getConfigFile(this->type_)->getVectorSize(this->sectionname_, this->varname_);
- for (unsigned int i = 0; i < vectorSize; i++)
- {
- if (i < this->defvalueStringVector_.size())
- {
- this->value_ = ConfigFileManager::getInstance().getConfigFile(this->type_)->getOrCreateValue(this->sectionname_, this->varname_, i, this->defvalueStringVector_[i], this->value_.isType(MT_Type::String));
- }
- else
- {
- this->value_ = ConfigFileManager::getInstance().getConfigFile(this->type_)->getOrCreateValue(this->sectionname_, this->varname_, i, MultiType(), this->value_.isType(MT_Type::String));
- }
-
- this->valueVector_.push_back(this->value_);
- }
- }
- }
-
- /**
- @brief Calls the given function with parsed index and the parsed argument from the input string.
- @param function The function to call
- @param input The input string
- @return The returnvalue of the functioncall
- */
- bool ConfigValueContainer::callFunctionWithIndex(bool (ConfigValueContainer::* function) (unsigned int, const MultiType&), const std::string& input)
- {
- SubString token(input, " ", SubString::WhiteSpaces, true, '\\', false, '"', false, '\0', '\0', false, '\0');
- int index = -1;
- bool success = false;
-
- if (token.size() > 0)
- success = convertValue(&index, token[0]);
-
- if (!success || index < 0 || index > (signed int)MAX_VECTOR_INDEX)
- {
- if (!success)
- {
- COUT(1) << "Error: Config-value '" << this->varname_ << "' in " << this->sectionname_ << " is a vector." << std::endl;
- }
- else
- {
- COUT(1) << "Error: Invalid vector-index." << std::endl;
- }
- return false;
- }
-
- if (token.size() >= 2)
- return (this->*function)(index, token.subSet(1).join());
- else
- return (this->*function)(index, "");
- }
-
- /**
- @brief Adds a description to the config-value.
- @param description The description
- */
- ConfigValueContainer& ConfigValueContainer::description(const std::string& description)
- {
- if (!this->bAddedDescription_)
- {
- this->description_ = std::string("ConfigValueDescription::" + this->sectionname_ + "::" + this->varname_);
- AddLanguageEntry(this->description_, description);
- this->bAddedDescription_ = true;
- }
- return (*this);
- }
-
- /**
- @brief Returns the description of the config-value.
- @return The description
- */
- const std::string& ConfigValueContainer::getDescription() const
- {
- return GetLocalisation(this->description_);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ConfigValueContainer.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,305 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Config ConfigFile
- @brief Declaration of the ConfigValueContainer class, caches a config-value.
-
- The ConfigValueContainer class contains all needed information about a configurable variable:
- - the name of the variable
- - the name of the class the variable belongs to
- - the default value
- - the user-specified value
- - a pointer to the entry in the config-file
-
- This is needed to assign the configured values to all newly created objects.
-*/
-
-#ifndef _ConfigValueContainer_H__
-#define _ConfigValueContainer_H__
-
-#include "CorePrereqs.h"
-
-#include <string>
-#include <vector>
-
-#include "util/MultiType.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- class ConfigValueCallbackBase
- {
- public:
- virtual void call(void* object) = 0;
- inline virtual ~ConfigValueCallbackBase() {}
- };
-
- template <class T>
- class ConfigValueCallback: public ConfigValueCallbackBase
- {
- public:
- inline ConfigValueCallback(void (T::*function) (void)) : function_(function) {}
- inline virtual ~ConfigValueCallback() {}
- inline virtual void call(void* object)
- {
- if (!Identifier::isCreatingHierarchy())
- (static_cast<T*>(object)->*this->function_)();
- }
-
- private:
- void (T::*function_) (void);
- };
-
-
- /**
- @brief The ConfigValuecontainer contains all needed information about a configurable variable.
-
- The ConfigValueContainer class contains all needed information about a configurable variable:
- - the name of the variable
- - the name of the class the variable belongs to
- - the default value
- - the user-specified value
- - a pointer to the entry in the config-file
-
- This is needed to assign the configured values to all newly created objects.
-
- The container searches for the entry in the config file.
- If there is an entry, it parses the specified value and assigns it to the variable of the right type.
- If there is no entry, it adds the entry with the default-value to the section of the variables class.
- If there is no section, the section and the entry are added to the end of the config-file.
- */
- class _CoreExport ConfigValueContainer
- {
- public:
- /**
- @brief Constructor: Converts the default-value to a string, checks the config-file for a changed value, sets the intern value variable.
- @param type The type of the corresponding config-file
- @param identifier The identifier of the class the variable belongs to
- @param sectionname Name of the section the configValue should be put in.
- @param varname The name of the variable
- @param defvalue The default-value
- @param value Only needed do determine the right type.
- */
- template <class D, class V>
- ConfigValueContainer(ConfigFileType::Value type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const D& defvalue, const V& value)
- {
- this->init(type, identifier, sectionname, varname);
- this->initValue(static_cast<V>(defvalue));
- }
-
- /**
- @brief Constructor: Converts the default-value to a string, checks the config-file for a changed value, sets the intern value variable.
- @param type The type of the corresponding config-file
- @param identifier The identifier of the class the variable belongs to
- @param sectionname Name of the section the configValue should be put in.
- @param varname The name of the variable
- @param defvalue The default-value
- @param value Only needed do determine the right type.
- */
- template <class D, class V>
- ConfigValueContainer(ConfigFileType::Value type, Identifier* identifier, const std::string& sectionname, const std::string& varname, const std::vector<D>& defvalue, const std::vector<V>& value)
- {
- this->init(type, identifier, sectionname, varname);
-
- this->value_ = V();
- for (unsigned int i = 0; i < defvalue.size(); i++)
- this->valueVector_.push_back(MultiType(defvalue[i]));
-
- this->initVector();
- }
-
- ~ConfigValueContainer();
-
- /**
- @brief Returns the configured value.
- @param value A pointer to the variable to store the value.
- @param object The object calling this function
- @return The ConfigValueContainer
- */
- template <typename T, class C>
- ConfigValueContainer& getValue(T* value, C* object)
- {
- if ((this->callback_ && object) || this->bContainerIsNew_)
- {
- T temp = *value;
- this->value_.getValue(value);
- if (this->bContainerIsNew_ || (*value) != temp)
- {
- this->bContainerIsNew_ = false;
- if (this->callback_ && object)
- this->callback_->call(object);
- else
- this->bDoInitialCallback_ = true;
- }
- }
- else
- {
- this->value_.getValue(value);
- }
- return *this;
- }
-
- /**
- @brief Returns the configured vector.
- @param value A pointer to the vector to store the values.
- @param object The object calling this function
- @return The ConfigValueContainer
- */
- template <typename T, class C>
- ConfigValueContainer& getValue(std::vector<T>* value, C* object)
- {
- if ((this->callback_ && object) || this->bContainerIsNew_)
- {
- if (this->bContainerIsNew_)
- this->bContainerIsNew_ = false;
-
- std::vector<T> temp = *value;
- value->clear();
- for (unsigned int i = 0; i < this->valueVector_.size(); ++i)
- value->push_back(this->valueVector_[i]);
-
- if (value->size() != temp.size())
- {
- if (this->callback_ && object)
- this->callback_->call(object);
- else
- this->bDoInitialCallback_ = true;
- }
- else
- {
- for (unsigned int i = 0; i < value->size(); ++i)
- {
- if ((*value)[i] != temp[i])
- {
- if (this->callback_ && object)
- this->callback_->call(object);
- else
- this->bDoInitialCallback_ = true;
- break;
- }
- }
- }
- }
- else
- {
- value->clear();
- for (unsigned int i = 0; i < this->valueVector_.size(); ++i)
- value->push_back(this->valueVector_[i]);
- }
- return *this;
- }
-
- /// Returns the name of this container.
- inline const std::string& getName() const
- { return this->varname_; }
- /// Returns the name of the section this config value is in.
- inline const std::string& getSectionName() const
- { return this->sectionname_; }
- /// Returns the associated identifier (can be NULL).
- inline Identifier* getIdentifier() const
- { return this->identifier_; }
- /// Returns true if this config-value is a vector.
- inline bool isVector() const
- { return this->bIsVector_; }
- /// Returns the vectors size (or zero if it's not a vector).
- inline unsigned int getVectorSize() const
- { return this->valueVector_.size(); }
-
- ConfigValueContainer& description(const std::string& description);
- const std::string& getDescription() const;
-
- /**
- @brief Adds a callback function, that gets called after getValue() if the newly assigned value differs from the old value of the variable.
- @param object The object to call the function
- @param function The callback function
- */
- template <class T>
- inline ConfigValueContainer& callback(T* object, void (T::*function) (void))
- {
- if (!this->callback_)
- {
- this->callback_ = new ConfigValueCallback<T>(function);
-
- if (this->bDoInitialCallback_)
- {
- this->bDoInitialCallback_ = false;
- this->callback_->call(object);
- }
- }
-
- return (*this);
- }
-
- bool set(const MultiType& input);
- bool tset(const MultiType& input);
-
- bool set(unsigned int index, const MultiType& input);
- bool tset(unsigned int index, const MultiType& input);
- bool add(const MultiType& input);
- bool remove(unsigned int index);
-
- bool reset();
- void update();
-
- /// Converts the config-value to a string.
- inline std::string toString() const
- { return this->value_; }
- /// Returns the typename of the assigned config-value.
- inline std::string getTypename() const
- { return this->value_.getTypename(); }
-
- private:
- void init(ConfigFileType::Value type, Identifier* identifier, const std::string& sectionname, const std::string& varname);
- void initValue(const MultiType& defvalue);
- void initVector();
- bool callFunctionWithIndex(bool (ConfigValueContainer::* function) (unsigned int, const MultiType&), const std::string& input);
-
- bool bIsVector_; //!< True if the container contains a std::vector
-
- ConfigFileType::Value type_; //!< The type of the corresponding config-file
- Identifier* identifier_; //!< The identifier of the class
- std::string sectionname_; //!< The name of the class the variable belongs to
- std::string varname_; //!< The name of the variable
- std::string defvalueString_; //!< The string of the default-value
- std::vector<std::string> defvalueStringVector_; //!< A vector, containg the strings of the default-values in case we're storing a vector
-
- MultiType value_; //!< The value
- std::vector<MultiType> valueVector_; //!< A vector, containg the values in case we're storing a vector
-
- bool bAddedDescription_; //!< True if a description was added
- LanguageEntryLabel description_; //!< The description
- ConfigValueCallbackBase* callback_; //!< A callback function to call after getValue if the value changed
-
- bool bContainerIsNew_; //!< True if it's the first time getValue() gets called
- bool bDoInitialCallback_; //!< True if the callback should be called as soon as it gets created
- };
-}
-
-#endif /* _ConfigValueContainer_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ConfigValueIncludes.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ConfigValueIncludes.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ConfigValueIncludes.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,257 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * Reto Grieder (functions)
- *
- */
-
-/**
- @defgroup ConfigFile Config file
- @ingroup Config
-*/
-
-/**
- @file
- @ingroup Config ConfigFile
- @brief Definition of macros and functions for config-values.
-
- An example of how to use SetConfigValue():
-
- Definition of a class in the header-file:
- @code
- class MyClass : public BaseObject
- {
- public:
- MyClass(); // Constructor
- void setConfigValues(); // Inherited function
-
- const std::string& getName()
- { return this->name_; }
-
- float getVersion()
- { return this->version_; }
-
- private:
- std::string name_;
- float version_;
- };
- @endcode
-
- Implementation of the class source-file:
- @code
- MyClass::MyClass()
- {
- // Macro-call to create an Identifier
- RegisterObject(MyClass);
-
- // Function-call to assign the config-values to the new object
- this->setConfigValues();
- }
-
- void MyClass::setConfigValues()
- {
- SetConfigValue(name_, "Orxonox").description("The name of the game");
- SetConfigValue(version_, "1.0").description("The version-number");
- }
- @endcode
-
- Extract of orxonox.ini:
- @code
- [MyClass]
- name_ = "Orxonox"
- version_ = 1.1 // We have changed this value from 1.0 to 1.1
- @endcode
-
- Some other code:
- @code
- MyObject orxonoxobject;
- std::cout << "Name: " << orxonoxobject.getName() << std::endl;
- std::cout << "Version: " << orxonoxobject.getVersion() << std::endl;
- @endcode
-
- Output:
- @code
- Name: Orxonox
- Version: 1.1
- @endcode
-*/
-
-#ifndef _ConfigValueIncludes_H__
-#define _ConfigValueIncludes_H__
-
-#include "CorePrereqs.h"
-
-#include "Identifier.h"
-#include "ConfigValueContainer.h"
-
-namespace orxonox
-{
- /** Sets a runtime configurable value.
- If the container for the value doesn't yet exist, a new one is created.
- Also, the @a variable argument will be modified and set to the new value (default or from ini file).
- @param object
- Class instance that the config value should belong to (usually just 'this')
- @param variable
- Pointer to the variable where the value should be written to
- @param type
- Type of the config file, usually ConfigFileType::Settings
- @param sectionName
- Name of the section in the ini file (e.g. [MySection])
- @param entryName
- Name of the entry in the ini file (e.g. [MySection] myValue)
- @param defaultValue
- Value to be used if it cannot be read from the ini file
- */
- template <class T, class D, class V>
- inline ConfigValueContainer& setConfigValueGeneric(T* object, V* variable, ConfigFileType::Value type, const std::string& sectionName, const std::string& entryName, const D& defaultValue)
- {
- ConfigValueContainer* container = ClassIdentifier<T>::getIdentifier()->getConfigValueContainer(entryName);
- if (!container)
- {
- container = new ConfigValueContainer(type, ClassIdentifier<T>::getIdentifier(), sectionName, entryName, defaultValue, *variable);
- ClassIdentifier<T>::getIdentifier()->addConfigValueContainer(entryName, container);
- }
- return container->getValue(variable, object);
- }
-}
-
-/** Sets a runtime configurable value (simplified macro version of setConfigValueGeneric)
- If the container for the value doesn't yet exist, a new one is created.
- Also, the @a varname argument will be modified and set to the new value (default or from ini file).
- at param varname
- Variable name as C++ identifier. It will be used as entry name and as variable pointer
- at param defaultValue
- Value to be used if it cannot be read from the ini file
-*/
-#define SetConfigValue(varname, defaultValue) \
- orxonox::setConfigValueGeneric(this, &varname, ConfigFileType::Settings, this->getIdentifier()->getName(), #varname, defaultValue)
-
-/** Sets a runtime configurable value (simplified macro version of setConfigValueGeneric)
- If the container for the value doesn't yet exist, a new one is created.
- Also, the @a varname argument will be modified and set to the new value (default or from ini file).
- at param variable
- Variable name as C++ identifier.
- at param entryName
- Name of the entry in the ini file (e.g. [MySection] myValue)
- at param defaultValue
- Value to be used if it cannot be read from the ini file
-*/
-#define SetConfigValueAlias(variable, entryName, defaultValue) \
- orxonox::setConfigValueGeneric(this, &variable, ConfigFileType::Settings, this->getIdentifier()->getName(), entryName, defaultValue)
-
-/** Sets a runtime configurable value (simplified macro version of setConfigValueGeneric)
- If the container for the value doesn't yet exist, a new one is created.
- Also, the @a varname argument will be modified and set to the new value (default or from ini file).
- at param variable
- Variable name as C++ identifier.
- at param sectionName
- Name of the section in the ini file (e.g. [MySection])
- at param entryName
- Name of the entry in the ini file (e.g. [MySection] myValue)
- at param defaultValue
- Value to be used if it cannot be read from the ini file
-*/
-#define SetConfigValueExternal(variable, sectionName, entryName, defaultValue) \
- orxonox::setConfigValueGeneric(this, &variable, ConfigFileType::Settings, sectionName, entryName, defaultValue)
-
-
-namespace orxonox
-{
- /** Resets a runtime configurable value to its default.
- If the container for the value doesn't yet exist, a warning is displayed.
- Also, the @a variable argument will be modified and set to the default value.
- @param object
- Class instance that the config value should belong to (usually just 'this')
- @param variable
- Pointer to the variable where the value should be written to
- @param entryName
- Name of the entry in the ini file (e.g. [MySection] myValue)
- */
- template <class T, class V>
- inline void resetConfigValueGeneric(T* object, V* variable, const std::string& entryName)
- {
- ConfigValueContainer* container = ClassIdentifier<T>::getIdentifier()->getConfigValueContainer(entryName);
- if (container)
- {
- container->reset();
- container->getValue(variable, object);
- }
- else
- {
- COUT(2) << "Warning: Couldn't reset config-value '" << entryName << "' in class '"
- << ClassIdentifier<T>::getIdentifier()->getName() << "', corresponding container doesn't exist." << std::endl;
- }
- }
-}
-
-/** Resets a runtime configurable value to its default (simplified macro version of modifyConfigValueGeneric)
- If the container for the value doesn't yet exist, a warning is displayed.
- Also, the @a varname argument will be modified and set to the default value.
- at param varname
- Variable name as C++ identifier. It will be used as entry name and as variable pointer
-*/
-#define ResetConfigValue(varname) \
- orxonox::resetConfigValueGeneric(this, &varname, #varname)
-
-
-/** Modifies a runtime configurable value by using a modifier and some arguments.
- If the container for the value doesn't yet exist, a warning is displayed.
- Also, the @a variable argument will be modified and set to the current value.
- at param object
- Class instance that the config value should belong to (usually just 'this')
- at param variable
- Pointer to the variable where the value should be written to
- at param entryName
- Name of the entry in the ini file (e.g. [MySection] myValue)
- at param modifier
- On of these functions: set, tset, add, remove, reset, update
- at param ...
- Arguments for the modifier function
-*/
-#define ModifyConfigValueGeneric(object, variable, entryName, modifier, ...) \
- if (orxonox::ConfigValueContainer* container = ClassByObjectType(object)->getConfigValueContainer(entryName)) \
- { \
- container->modifier(__VA_ARGS__); \
- container->getValue(variable, object); \
- } \
- else \
- { \
- COUT(2) << "Warning: Couln't modify config-value '" << entryName << "' in class '" \
- << ClassByObjectType(object)->getName() << "', corresponding container doesn't exist." << std::endl; \
- }
-
-/** Modifies a runtime configurable value by using a modifier and some arguments.
- If the container for the value doesn't yet exist, a warning is displayed.
- Also, the @a varname argument will be modified and set to the current value.
- at param varname
- Variable name as C++ identifier. It will be used as entry name and as variable pointer
- at param modifier
- On of these functions: set, tset, add, remove, reset, update
- at param ...
- Arguments for the modifier function
-*/
-#define ModifyConfigValue(varname, modifier, ...) \
- ModifyConfigValueGeneric(this, &varname, #varname, modifier, __VA_ARGS__)
-
-#endif /* _ConfigValueIncludes_H__ */
Modified: code/forks/sandbox_light/src/libraries/core/Core.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Core.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Core.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -50,72 +50,25 @@
# undef max
#endif
-#include "util/Clock.h"
#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/Scope.h"
-#include "util/ScopedSingletonManager.h"
#include "util/SignalHandler.h"
#include "PathConfig.h"
#include "CommandLineParser.h"
-#include "ConfigFileManager.h"
-#include "ConfigValueIncludes.h"
-#include "CoreIncludes.h"
-#include "DynLibManager.h"
-#include "GameMode.h"
-#include "GraphicsManager.h"
-#include "GUIManager.h"
-#include "Identifier.h"
-#include "Language.h"
-#include "LuaState.h"
-#include "command/ConsoleCommand.h"
-#include "command/IOConsole.h"
-#include "command/TclBind.h"
-#include "command/TclThreadManager.h"
-#include "input/InputManager.h"
namespace orxonox
{
//! Static pointer to the singleton
Core* Core::singletonPtr_s = 0;
- SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
- SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
-
#ifdef ORXONOX_PLATFORM_WINDOWS
SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)");
#endif
Core::Core(const std::string& cmdLine)
- // Cleanup guard for identifier destruction (incl. XMLPort, configValues, consoleCommands)
- : identifierDestroyer_(Identifier::destroyAllIdentifiers)
- // Cleanup guard for external console commands that don't belong to an Identifier
- , consoleCommandDestroyer_(ConsoleCommand::destroyAll)
- , bGraphicsLoaded_(false)
- , bStartIOConsole_(true)
- , lastLevelTimestamp_(0)
- , ogreConfigTimestamp_(0)
{
// Set the hard coded fixed paths
this->pathConfig_.reset(new PathConfig());
- // Create a new dynamic library manager
- this->dynLibManager_.reset(new DynLibManager());
-
- // Load modules
- const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
- for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
- {
- try
- {
- this->dynLibManager_->load(*it);
- }
- catch (...)
- {
- COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
- }
- }
-
// Parse command line arguments AFTER the modules have been loaded (static code!)
CommandLineParser::parseCommandLine(cmdLine);
@@ -142,40 +95,6 @@
setThreadAffinity(static_cast<unsigned int>(limitToCPU));
#endif
- // Manage ini files and set the default settings file (usually orxonox.ini)
- this->configFileManager_.reset(new ConfigFileManager());
- this->configFileManager_->setFilename(ConfigFileType::Settings,
- CommandLineParser::getValue("settingsFile").getString());
-
- // Required as well for the config values
- this->languageInstance_.reset(new Language());
-
- // Do this soon after the ConfigFileManager has been created to open up the
- // possibility to configure everything below here
- ClassIdentifier<Core>::getIdentifier("Core")->initialiseObject(this, "Core", true);
- this->setConfigValues();
-
- // create persistent io console
- if (CommandLineParser::getValue("noIOConsole").getBool())
- {
- ModifyConfigValue(bStartIOConsole_, tset, false);
- }
- if (this->bStartIOConsole_)
- this->ioConsole_.reset(new IOConsole());
-
- // creates the class hierarchy for all classes with factories
- Identifier::createClassHierarchy();
-
- // Load OGRE excluding the renderer and the render window
- this->graphicsManager_.reset(new GraphicsManager(false));
-
- // initialise Tcl
- this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
- this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
-
- // Create singletons that always exist (in other libraries)
- this->rootScope_.reset(new Scope<ScopeID::Root>());
-
// Generate documentation instead of normal run?
std::string docFilename;
CommandLineParser::getValue("generateDoc", &docFilename);
@@ -198,43 +117,8 @@
*/
Core::~Core()
{
- // Remove us from the object lists again to avoid problems when destroying them
- this->unregisterObject();
}
- //! Function to collect the SetConfigValue-macro calls.
- void Core::setConfigValues()
- {
-#ifdef ORXONOX_RELEASE
- const unsigned int defaultLevelLogFile = 3;
-#else
- const unsigned int defaultLevelLogFile = 4;
-#endif
- SetConfigValueExternal(softDebugLevelLogFile_, "OutputHandler", "softDebugLevelLogFile", defaultLevelLogFile)
- .description("The maximum level of debug output shown in the log file");
- OutputHandler::getInstance().setSoftDebugLevel(OutputHandler::logFileOutputListenerName_s, this->softDebugLevelLogFile_);
-
- SetConfigValue(language_, Language::getInstance().defaultLanguage_)
- .description("The language of the in game text")
- .callback(this, &Core::languageChanged);
- SetConfigValue(bInitRandomNumberGenerator_, true)
- .description("If true, all random actions are different each time you start the game")
- .callback(this, &Core::initRandomNumberGenerator);
- SetConfigValue(bStartIOConsole_, true)
- .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
- SetConfigValue(lastLevelTimestamp_, 0)
- .description("Timestamp when the last level was started.");
- SetConfigValue(ogreConfigTimestamp_, 0)
- .description("Timestamp when the ogre config file was changed.");
- }
-
- //! Callback function if the language has changed.
- void Core::languageChanged()
- {
- // Read the translation file after the language was configured
- Language::getInstance().readTranslatedLanguageFile();
- }
-
void Core::initRandomNumberGenerator()
{
static bool bInitialized = false;
@@ -246,82 +130,6 @@
}
}
- void Core::loadGraphics()
- {
- // Any exception should trigger this, even in upgradeToGraphics (see its remarks)
- Loki::ScopeGuard unloader = Loki::MakeObjGuard(*this, &Core::unloadGraphics);
-
- // Upgrade OGRE to receive a render window
- try
- {
- graphicsManager_->upgradeToGraphics();
- }
- catch (const InitialisationFailedException&)
- {
- // Exit the application if the Ogre config dialog was canceled
- COUT(1) << Exception::handleMessage() << std::endl;
- exit(EXIT_FAILURE);
- }
- catch (...)
- {
- // Recovery from this is very difficult. It requires to completely
- // destroy Ogre related objects and load again (without graphics).
- // However since Ogre 1.7 there seems to be a problem when Ogre
- // throws an exception and the graphics engine then gets destroyed
- // and reloaded between throw and catch (access violation in MSVC).
- // That's why we abort completely and only display the exception.
- COUT(1) << "An exception occurred during upgrade to graphics. "
- << "That is unrecoverable. The message was:" << endl
- << Exception::handleMessage() << endl;
- abort();
- }
-
- // Calls the InputManager which sets up the input devices.
- inputManager_.reset(new InputManager());
-
- // Load the CEGUI interface
- guiManager_.reset(new GUIManager(inputManager_->getMousePosition()));
-
- bGraphicsLoaded_ = true;
- GameMode::bShowsGraphics_s = true;
-
- // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
- graphicsManager_->loadDebugOverlay();
-
- // Create singletons associated with graphics (in other libraries)
- graphicsScope_.reset(new Scope<ScopeID::Graphics>());
-
- unloader.Dismiss();
- }
-
- void Core::unloadGraphics()
- {
- this->graphicsScope_.reset();
- this->guiManager_.reset();
- this->inputManager_.reset();
- this->graphicsManager_.reset();
-
- // Load Ogre::Root again, but without the render system
- try
- { this->graphicsManager_.reset(new GraphicsManager(false)); }
- catch (...)
- {
- COUT(0) << "An exception occurred during 'unloadGraphics':" << Exception::handleMessage() << std::endl
- << "Another exception might be being handled which may lead to undefined behaviour!" << std::endl
- << "Terminating the program." << std::endl;
- abort();
- }
-
- bGraphicsLoaded_ = false;
- GameMode::bShowsGraphics_s = false;
- }
-
- //! Sets the language in the config-file back to the default.
- void Core::resetLanguage()
- {
- ResetConfigValue(language_);
- }
-
/**
@note
The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
@@ -367,47 +175,4 @@
SetThreadAffinityMask(GetCurrentThread(), threadMask);
#endif
}
-
- void Core::preUpdate(const Clock& time)
- {
- // Update singletons before general ticking
- ScopedSingletonManager::preUpdate<ScopeID::Root>(time);
- if (this->bGraphicsLoaded_)
- {
- // Process input events
- this->inputManager_->preUpdate(time);
- // Update GUI
- this->guiManager_->preUpdate(time);
- // Update singletons before general ticking
- ScopedSingletonManager::preUpdate<ScopeID::Graphics>(time);
- }
- // Process console events and status line
- if (this->ioConsole_ != NULL)
- this->ioConsole_->preUpdate(time);
- // Process thread commands
- this->tclThreadManager_->preUpdate(time);
- }
-
- void Core::postUpdate(const Clock& time)
- {
- // Update singletons just before rendering
- ScopedSingletonManager::postUpdate<ScopeID::Root>(time);
- if (this->bGraphicsLoaded_)
- {
- // Update singletons just before rendering
- ScopedSingletonManager::postUpdate<ScopeID::Graphics>(time);
- // Render (doesn't throw)
- this->graphicsManager_->postUpdate(time);
- }
- }
-
- void Core::updateLastLevelTimestamp()
- {
- ModifyConfigValue(lastLevelTimestamp_, set, static_cast<long long>(time(NULL)));
- }
-
- void Core::updateOgreConfigTimestamp()
- {
- ModifyConfigValue(ogreConfigTimestamp_, set, static_cast<long long>(time(NULL)));
- }
}
Modified: code/forks/sandbox_light/src/libraries/core/Core.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Core.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Core.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -45,10 +45,8 @@
#include <string>
#include <boost/scoped_ptr.hpp>
-#include <loki/ScopeGuard.h>
#include "util/Singleton.h"
-#include "OrxonoxClass.h"
namespace orxonox
{
@@ -58,11 +56,9 @@
@remark
You should only create this singleton once because it destroys the identifiers!
*/
- class _CoreExport Core : public Singleton<Core>, public OrxonoxClass
+ class _CoreExport Core : public Singleton<Core>
{
- typedef Loki::ScopeGuardImpl0<void (*)()> SimpleScopeGuard;
friend class Singleton<Core>;
- friend class Game;
public:
/**
@@ -75,60 +71,20 @@
Core(const std::string& cmdLine);
~Core();
- void setConfigValues();
-
- //! Returns the configured language.
- const std::string& getLanguage()
- { return this->language_; }
- void resetLanguage();
-
- void updateLastLevelTimestamp();
- inline long long getLastLevelTimestamp() const
- { return this->lastLevelTimestamp_; }
-
- void updateOgreConfigTimestamp();
- inline long long getOgreConfigTimestamp() const
- { return this->ogreConfigTimestamp_; }
-
private:
Core(const Core&); //!< Don't use (undefined symbol)
- void languageChanged();
void initRandomNumberGenerator();
- void preUpdate(const Clock& time);
- void postUpdate(const Clock& time);
-
- void loadGraphics();
- void unloadGraphics();
-
void setThreadAffinity(int limitToCPU);
+
// MANAGED SINGLETONS/OBJECTS
// Mind the order for the destruction!
scoped_ptr<PathConfig> pathConfig_;
- scoped_ptr<DynLibManager> dynLibManager_;
scoped_ptr<SignalHandler> signalHandler_;
- SimpleScopeGuard identifierDestroyer_;
- SimpleScopeGuard consoleCommandDestroyer_;
- scoped_ptr<ConfigFileManager> configFileManager_;
- scoped_ptr<Language> languageInstance_;
- scoped_ptr<IOConsole> ioConsole_;
- scoped_ptr<TclBind> tclBind_;
- scoped_ptr<TclThreadManager> tclThreadManager_;
- scoped_ptr<Scope<ScopeID::Root> > rootScope_;
- // graphical
- scoped_ptr<GraphicsManager> graphicsManager_; //!< Interface to OGRE
- scoped_ptr<InputManager> inputManager_; //!< Interface to OIS
- scoped_ptr<GUIManager> guiManager_; //!< Interface to GUI
- scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_;
- bool bGraphicsLoaded_;
int softDebugLevelLogFile_; //!< The debug level for the log file (belongs to OutputHandler)
- std::string language_; //!< The language
bool bInitRandomNumberGenerator_; //!< If true, srand(time(0)) is called
- bool bStartIOConsole_; //!< Set to false if you don't want to use the IOConsole
- long long lastLevelTimestamp_; ///< Timestamp when the last level was started
- long long ogreConfigTimestamp_; ///< Timestamp wehen the ogre config level was modified
static Core* singletonPtr_s;
};
Deleted: code/forks/sandbox_light/src/libraries/core/CoreIncludes.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/CoreIncludes.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/CoreIncludes.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,179 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Factory RegisterObject() and CreateFactory()
- @ingroup Object
-*/
-
-/**
- @file
- @ingroup Object Factory
- @brief Defines several very important macros used to register objects, create factories, and to work with identifiers.
-
- Every class needs the @c RegisterObject(class) macro in its constructor. If the class is an interface
- or the @c BaseObject itself, it needs the macro @c RegisterRootObject(class) instead.
-
- To allow the object being created through the factory, use the @c CreateFactory(class) macro outside
- of the class implementation, so it gets executed statically before @c main(). This will at the same time
- register @a class in the class-hierarchy. If you don't want @a class to be loadable, but still
- register it, call @c CreateUnloadableFactory(class).
-
- Example:
- @code
- // Create the factory for MyClass
- CreateFactory(MyClass);
-
- // Constructor:
- MyClass::MyClass()
- {
- // Register the object in the Identifier of MyClass
- RegisterObject(MyClass);
- }
- @endcode
-
- This file also defines a number of other useful macros, like, for example, @c Class(class) which
- returns the @ref orxonox::Identifier "Identifier" of @a class, or @c ClassByString("class") which
- returns the Identifier of a class with name @a "class".
-
- Example:
- @code
- // Assigns the Identifier of MyClass
- Identifier* identifier = Class(MyClass);
- @endcode
- @code
- // Assigns the Identifier of a class named "MyClass"
- Identifier* identifier = ClassByString("MyClass");
- @endcode
-*/
-
-#ifndef _CoreIncludes_H__
-#define _CoreIncludes_H__
-
-#include "CorePrereqs.h"
-
-#include "util/Debug.h"
-#include "Identifier.h"
-#include "SubclassIdentifier.h"
-#include "ClassFactory.h"
-#include "ObjectList.h"
-
-
-/**
- @brief Intern macro, containing the common parts of @c RegisterObject and @c RegisterRootObject.
- @param ClassName The name of the class
- @param bRootClass True if the class is directly derived from orxonox::OrxonoxClass
-*/
-#define InternRegisterObject(ClassName, bRootClass) \
- if (ClassIdentifier<ClassName>::getIdentifier(#ClassName)->initialiseObject(this, #ClassName, bRootClass)) \
- return; \
- else \
- ((void)0)
-
-/**
- @brief Registers a newly created object in the core. Has to be called at the beginning of the constructor of @a ClassName.
- @param ClassName The name of the class
-*/
-#define RegisterObject(ClassName) \
- InternRegisterObject(ClassName, false)
-
-/**
- @brief Registers a newly created object in the core. Has to be called at the beginning of the constructor of @a ClassName.
- @param ClassName The name of the class
-
- In contrast to RegisterObject, this is used for classes that inherit directly from
- orxonox::OrxonoxClass, namely all interfaces and orxonox::BaseObject.
-*/
-#define RegisterRootObject(ClassName) \
- InternRegisterObject(ClassName, true)
-
-/**
- @brief Creates the Factory.
- @param ClassName The name of the class
-*/
-#define CreateFactory(ClassName) \
- Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, true)
-
-/**
- @brief Creates the Factory for classes which should not be loaded through XML.
- @param ClassName The name of the class
-*/
-#define CreateUnloadableFactory(ClassName) \
- Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, false)
-
-/**
- @brief Returns the Identifier of the given class.
- @param ClassName The name of the class
-*/
-#define Class(ClassName) \
- orxonox::ClassIdentifier<ClassName>::getIdentifier()
-
-
-namespace orxonox
-{
- /**
- @brief Returns the Identifier with a given name.
- @param name The name of the class
- */
- inline Identifier* ClassByString(const std::string& name)
- {
- return Identifier::getIdentifierByString(name);
- }
-
- /**
- @brief Returns the Identifier with a given lowercase name.
- @param name The lowercase name of the class
- */
- inline Identifier* ClassByLowercaseString(const std::string& name)
- {
- return Identifier::getIdentifierByLowercaseString(name);
- }
-
- /**
- @brief Returns the Identifier with a given network ID.
- @param id The network ID of the class
- */
- inline Identifier* ClassByID(uint32_t id)
- {
- return Identifier::getIdentifierByID(id);
- }
-
- /**
- @brief Returns the Identifier with a given 'this' pointer.
- @note This of course only works with OrxonoxClasses.
- The only use is in conjunction with macros that don't know the class type.
- @param object Pointer to an OrxonoxClass
- */
- template <class T>
- inline Identifier* ClassByObjectType(const T* object)
- {
- return ClassIdentifier<T>::getIdentifier();
- }
-}
-
-#endif /* _CoreIncludes_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/CorePrecompiledHeaders.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/CorePrecompiledHeaders.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/CorePrecompiledHeaders.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,86 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at brief
- Compilation of the most often used header files in the core library
- at details
- Updated: 13. September 2009
- Total Files: 56
-*/
-
-#include "OrxonoxConfig.h"
-
-///////////////////////////////////////////
-///// Stable Headers /////
-///////////////////////////////////////////
-
-#include <string> // 54
-#include <vector> // 54
-#include <cassert> // 53
-#include <fstream> // 53
-#include <iostream> // 53
-#include <map> // 53
-#include <sstream> // 53
-#include <set> // 50
-
-#include "util/Debug.h" // 48
-
-#include <deque> // 43
-#include <list> // 44
-#include <cmath> // 42
-
-#include <loki/ScopeGuard.h> // 38
-
-#include <OgreMath.h> // 36
-#include <OgreVector2.h> // 36
-#include <OgreVector3.h> // 36
-#include <OgreVector4.h> // 36
-#include <OgreQuaternion.h> // 36
-#include <OgreColourValue.h> // 36
-#include <boost/preprocessor/cat.hpp> // 27
-#include <boost/shared_ptr.hpp> // 21
-
-#ifdef ORXONOX_COMPILER_MSVC
-
-#include <ois/OISKeyboard.h> // 15
-#include <ois/OISMouse.h> // 15
-#include <ois/OISJoyStick.h> // 15
-
-#include "util/SubString.h" // 14
-
-#include <boost/scoped_ptr.hpp> // 13
-#include <stack> // 12
-
-#endif /*ORXONOX_COMPILER_MSVC */
-
-
-// Just in case some header included windows.h
-#undef min
-#undef max
Modified: code/forks/sandbox_light/src/libraries/core/CorePrereqs.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/CorePrereqs.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/CorePrereqs.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -64,7 +64,6 @@
namespace orxonox
{
- static const uint32_t OBJECTID_UNKNOWN = static_cast<uint32_t>(-1);
}
//-----------------------------------------------------------------------
@@ -73,38 +72,6 @@
namespace orxonox
{
- namespace XMLPort
- {
- enum Mode
- {
- NOP,
- LoadObject,
- SaveObject,
- ExpandObject
- };
- }
-
- namespace ConfigFileType
- {
- enum Value
- {
- Settings,
- JoyStickCalibration,
- CommandHistory
- // Don't forget to adjust the array size in the ConfigFileManager when adding a new entry here!
- };
- }
-
- namespace KeybindMode
- {
- enum Value
- {
- OnPress,
- OnHold,
- OnRelease,
- None
- };
- };
}
//-----------------------------------------------------------------------
@@ -113,146 +80,12 @@
namespace orxonox
{
- typedef std::string LanguageEntryLabel;
-
- template <class T, class U>
- T orxonox_cast(U*);
-
- class BaseObject;
- template <class T>
- class ClassFactory;
- template <class T>
- class ClassIdentifier;
- class ClassTreeMask;
- class ClassTreeMaskIterator;
- class ClassTreeMaskNode;
- class ClassTreeMaskObjectIterator;
class CommandLineParser;
class CommandLineArgument;
- class ConfigFile;
- class ConfigFileEntry;
- class ConfigFileEntryComment;
- class ConfigFileEntryValue;
- class ConfigFileManager;
- class ConfigFileSection;
- class ConfigValueContainer;
class Core;
- class DestructionListener;
- class DynLib;
- class DynLibManager;
- struct Event;
- class EventState;
- class Factory;
- class Game;
- class GameState;
- struct GameStateInfo;
- struct GameStateTreeNode;
- class GraphicsManager;
- class GUIManager;
- class Identifier;
- template <class T>
- class Iterator;
- class Language;
- class LuaFunctor;
- class LuaState;
- class MemoryArchive;
- class MemoryArchiveFactory;
- class MetaObjectList;
- class MetaObjectListElement;
- class Namespace;
- class NamespaceNode;
- template <class T>
- class ObjectList;
- class ObjectListBase;
- class ObjectListBaseElement;
- template <class T>
- class ObjectListElement;
- template <class T>
- class ObjectListIterator;
- class OgreWindowEventListener;
- class OrxonoxClass;
class PathConfig;
- struct ResourceInfo;
- class SettingsConfigFile;
- template <class T>
- class SmartPtr;
- template <class T>
- class SubclassIdentifier;
- class Template;
- class Thread;
- class ThreadPool;
- template <class T>
- class WeakPtr;
- class WindowEventListener;
- class XMLFile;
- class XMLNameListener;
- template <class T, class O>
- class XMLPortClassObjectContainer;
- template <class T>
- class XMLPortClassParamContainer;
- class XMLPortObjectContainer;
- class XMLPortParamContainer;
-
- // Command
- class ArgumentCompleter;
- class ArgumentCompletionListElement;
- class CommandEvaluation;
- class ConsoleCommand;
- class Executor;
- template <class T>
- class ExecutorMember;
- class ExecutorStatic;
- class Functor;
- template <class O>
- class FunctorMember;
- typedef FunctorMember<void> FunctorStatic;
- template <class F, class O>
- class FunctorPointer;
- class IOConsole;
- class IRC;
- class Shell;
- class ShellListener;
- class TclBind;
- struct TclInterpreterBundle;
- template <class T>
- class TclThreadList;
- class TclThreadManager;
-
- // Input
- class BaseCommand;
- class BufferedParamCommand;
- class Button;
- class HalfAxis;
- class InputBuffer;
- class InputDevice;
- template <class Traits>
- class InputDeviceTemplated;
- class InputHandler;
- class InputManager;
- class InputState;
- struct InputStatePriority;
- class JoyStickQuantityListener;
- class JoyStick;
- class KeyBinder;
- class KeyBinderManager;
- class Keyboard;
- class KeyDetector;
- class KeyEvent;
- class Mouse;
- class ParamCommand;
- class SimpleCommand;
}
-#include "command/FunctorPtr.h"
-#include "command/ExecutorPtr.h"
-
-// CppTcl
-namespace Tcl
-{
- class interpreter;
- class object;
-}
-
// Boost
namespace boost
{
@@ -277,67 +110,6 @@
using filesystem2::path;
}
#endif
- class thread;
- class mutex;
- class shared_mutex;
- class condition_variable;
}
-// Ogre
-namespace Ogre
-{
- class DataStream;
- template <class T> class SharedPtr;
- typedef SharedPtr<DataStream> DataStreamPtr;
-}
-namespace orxonox
-{
- // Import the Ogre::DataStream
- using Ogre::DataStream;
- using Ogre::DataStreamPtr;
-}
-
-// CEGUI
-namespace CEGUI
-{
- class DefaultLogger;
- class Logger;
- class LuaScriptModule;
-
- class OgreCEGUIRenderer;
- class OgreCEGUIResourceProvider;
- class OgreCEGUITexture;
-}
-
-// Lua
-struct lua_State;
-
-// TinyXML and TinyXML++
-class TiXmlString;
-class TiXmlOutStream;
-class TiXmlNode;
-class TiXmlHandle;
-class TiXmlDocument;
-class TiXmlElement;
-class TiXmlComment;
-class TiXmlUnknown;
-class TiXmlAttribute;
-class TiXmlText;
-class TiXmlDeclaration;
-class TiXmlParsingData;
-namespace ticpp
-{
- class Document;
- class Element;
- class Declaration;
- class StylesheetReference;
- class Text;
- class Comment;
- class Attribute;
-}
-namespace orxonox
-{
- using ticpp::Element;
-}
-
#endif /* _CorePrereqs_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/DynLib.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/DynLib.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/DynLib.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,138 +0,0 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
- (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2006 Torus Knot Software Ltd
-Also see acknowledgements in Readme.html
-
-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, or go to
-http://www.gnu.org/copyleft/lesser.txt.
-
-You may alternatively use this source under the terms of a specific version of
-the OGRE Unrestricted License provided you have obtained such a license from
-Torus Knot Software Ltd.
------------------------------------------------------------------------------
-*/
-
-// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
-
-#include "DynLib.h"
-
-#include "util/Exception.h"
-
-#ifdef ORXONOX_PLATFORM_WINDOWS
-# define WIN32_LEAN_AND_MEAN
-# ifndef NOMINMAX
-# define NOMINMAX // required to stop windows.h messing up std::min
-# endif
-# include <windows.h>
-#endif
-
-#ifdef ORXONOX_PLATFORM_LINUX
-# include <dlfcn.h>
-#endif
-
-#ifdef ORXONOX_PLATFORM_APPLE
-# include <macPlugins.h>
-#endif
-
-namespace orxonox
-{
- //-----------------------------------------------------------------------
- DynLib::DynLib( const std::string& name )
- {
- mName = name;
- m_hInst = NULL;
- }
-
- //-----------------------------------------------------------------------
- DynLib::~DynLib()
- {
- }
-
- //-----------------------------------------------------------------------
- void DynLib::load()
- {
- // Log library load
- COUT(2) << "Loading module " << mName << std::endl;
-
- std::string name = mName;
-#ifdef ORXONOX_PLATFORM_LINUX
- // dlopen() does not add .so to the filename, like windows does for .dll
- if (name.substr(name.length() - 3, 3) != ".so")
- name += ".so";
-#endif
-
- m_hInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() );
-
- if (!m_hInst)
- ThrowException(
- General,
- "Could not load dynamic library " + mName +
- ". System Error: " + dynlibError());
- }
-
- //-----------------------------------------------------------------------
- void DynLib::unload()
- {
- // Log library unload
- COUT(4) << "Unloading module " << mName << std::endl;
-
- if (DYNLIB_UNLOAD( m_hInst ))
- {
- ThrowException(
- General,
- "Could not unload dynamic library " + mName +
- ". System Error: " + dynlibError());
- }
-
- }
-
- //-----------------------------------------------------------------------
- void* DynLib::getSymbol( const std::string& strName ) const throw()
- {
- return (void*)DYNLIB_GETSYM( m_hInst, strName.c_str() );
- }
- //-----------------------------------------------------------------------
- std::string DynLib::dynlibError( void )
- {
-#if defined(ORXONOX_PLATFORM_WINDOWS)
- LPVOID lpMsgBuf;
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL
- );
- std::string ret = (char*)lpMsgBuf;
- // Free the buffer.
- LocalFree( lpMsgBuf );
- return ret;
-#elif defined(ORXONOX_PLATFORM_LINUX)
- return std::string(dlerror());
-#elif defined(ORXONOX_PLATFORM_APPLE)
- return std::string(mac_errorBundle());
-#else
- return "";
-#endif
- }
-
-}
Deleted: code/forks/sandbox_light/src/libraries/core/DynLib.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/DynLib.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/DynLib.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,125 +0,0 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
- (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2006 Torus Knot Software Ltd
-Also see acknowledgements in Readme.html
-
-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, or go to
-http://www.gnu.org/copyleft/lesser.txt.
-
-You may alternatively use this source under the terms of a specific version of
-the OGRE Unrestricted License provided you have obtained such a license from
-Torus Knot Software Ltd.
------------------------------------------------------------------------------
-*/
-
-// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
-
-/**
- @file
- @ingroup Management CoreGame
- @brief Declaration of DynLib which represents a dynamically loaded module.
-*/
-
-#ifndef _Core_DynLib_H__
-#define _Core_DynLib_H__
-
-#include "CorePrereqs.h"
-
-#include <string>
-
-#if defined(ORXONOX_PLATFORM_WINDOWS)
-# define DYNLIB_HANDLE hInstance
-# define DYNLIB_LOAD( a ) LoadLibraryEx( a, NULL, LOAD_WITH_ALTERED_SEARCH_PATH )
-# define DYNLIB_GETSYM( a, b ) GetProcAddress( a, b )
-# define DYNLIB_UNLOAD( a ) !FreeLibrary( a )
-
-struct HINSTANCE__;
-typedef struct HINSTANCE__* hInstance;
-
-#elif defined(ORXONOX_PLATFORM_LINUX)
-# define DYNLIB_HANDLE void*
-# define DYNLIB_LOAD( a ) dlopen( a, RTLD_LAZY | RTLD_GLOBAL)
-# define DYNLIB_GETSYM( a, b ) dlsym( a, b )
-# define DYNLIB_UNLOAD( a ) dlclose( a )
-
-#elif defined(ORXONOX_PLATFORM_APPLE)
-# define DYNLIB_HANDLE CFBundleRef
-# define DYNLIB_LOAD( a ) mac_loadExeBundle( a )
-# define DYNLIB_GETSYM( a, b ) mac_getBundleSym( a, b )
-# define DYNLIB_UNLOAD( a ) mac_unloadExeBundle( a )
-#endif
-
-namespace orxonox
-{
- /** %Resource holding data about a dynamic library.
- @remarks
- This class holds the data required to get symbols from
- libraries loaded at run-time (i.e. from DLL's for so's)
- @author
- Adrian Cearnãu (cearny at cearny.ro)
- @since
- 27 January 2002
- */
- class _CoreExport DynLib
- {
- protected:
- std::string mName;
- /// Gets the last loading error
- std::string dynlibError(void);
- public:
- /** Default constructor - used by DynLibManager.
- @warning
- Do not call directly
- */
- DynLib( const std::string& name );
-
- /** Default destructor.
- */
- ~DynLib();
-
- /** Load the library
- */
- void load();
- /** Unload the library
- */
- void unload();
- /// Get the name of the library
- const std::string& getName(void) const { return mName; }
-
- /**
- Returns the address of the given symbol from the loaded library.
- @param
- strName The name of the symbol to search for
- @returns
- If the function succeeds, the returned value is a handle to
- the symbol.
- @par
- If the function fails, the returned value is <b>NULL</b>.
-
- */
- void* getSymbol( const std::string& strName ) const throw();
-
- protected:
-
- /// Handle to the loaded library.
- DYNLIB_HANDLE m_hInst;
- };
-
-}
-
-#endif /* _Core_DynLib_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/DynLibManager.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/DynLibManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/DynLibManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,86 +0,0 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
- (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2006 Torus Knot Software Ltd
-Also see acknowledgements in Readme.html
-
-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, or go to
-http://www.gnu.org/copyleft/lesser.txt.
-
-You may alternatively use this source under the terms of a specific version of
-the OGRE Unrestricted License provided you have obtained such a license from
-Torus Knot Software Ltd.
------------------------------------------------------------------------------
-*/
-
-// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
-
-#include "DynLibManager.h"
-
-#include "DynLib.h"
-
-namespace orxonox
-{
- //-----------------------------------------------------------------------
- //! Static pointer to the singleton
- DynLibManager* DynLibManager::singletonPtr_s = 0;
-
- //-----------------------------------------------------------------------
- DynLibManager::DynLibManager()
- {
- }
- //-----------------------------------------------------------------------
- DynLib* DynLibManager::load( const std::string& filename)
- {
- DynLibList::iterator i = mLibList.find(filename);
- if (i != mLibList.end())
- {
- return i->second;
- }
- else
- {
- DynLib* pLib = new DynLib(filename);
- pLib->load();
- mLibList[filename] = pLib;
- return pLib;
- }
- }
- //-----------------------------------------------------------------------
- void DynLibManager::unload(DynLib* lib)
- {
- DynLibList::iterator i = mLibList.find(lib->getName());
- if (i != mLibList.end())
- {
- mLibList.erase(i);
- }
- lib->unload();
- delete lib;
- }
- //-----------------------------------------------------------------------
- DynLibManager::~DynLibManager()
- {
- // Unload & delete resources in turn
- for (DynLibList::iterator it = mLibList.begin(); it != mLibList.end(); ++it)
- {
- it->second->unload();
- delete it->second;
- }
-
- // Empty the list
- mLibList.clear();
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/DynLibManager.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/DynLibManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/DynLibManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,104 +0,0 @@
-/*
------------------------------------------------------------------------------
-This source file is part of OGRE
- (Object-oriented Graphics Rendering Engine)
-For the latest info, see http://www.ogre3d.org/
-
-Copyright (c) 2000-2006 Torus Knot Software Ltd
-Also see acknowledgements in Readme.html
-
-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, or go to
-http://www.gnu.org/copyleft/lesser.txt.
-
-You may alternatively use this source under the terms of a specific version of
-the OGRE Unrestricted License provided you have obtained such a license from
-Torus Knot Software Ltd.
------------------------------------------------------------------------------
-*/
-
-// 08/11/2009: Small adjustments for Orxonox by Fabian 'x3n' Landau
-
-/**
- @file
- @ingroup Management CoreGame
- @brief Declaration of DynLibManager, used to load modules at runtime.
-*/
-
-#ifndef _Core_DynLibManager_H__
-#define _Core_DynLibManager_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-#include "util/Singleton.h"
-
-namespace orxonox
-{
- /** Manager for Dynamic-loading Libraries.
- @remarks
- This manager keeps a track of all the open dynamic-loading
- libraries, opens them and returns references to already-open
- libraries.
- */
- class _CoreExport DynLibManager: public Singleton<DynLibManager>
- {
- friend class Singleton<DynLibManager>;
-
- protected:
- typedef std::map<std::string, DynLib*> DynLibList;
- DynLibList mLibList;
-
- public:
- /**
- @brief
- Default constructor.
- @note
- Should never be called as the singleton is automatically
- created during the creation of the Root object.
- @see
- Root::Root
- */
- DynLibManager();
-
- /**
- @brief
- Default destructor.
- @see
- Root::~Root
- */
- virtual ~DynLibManager();
-
- /**
- @brief
- Loads the passed library.
- @param filename
- The name of the library. The extension can be omitted
- */
- DynLib* load(const std::string& filename);
-
- /**
- @brief
- Unloads the passed library.
- @param lib
- A pointer to the library object
- */
- void unload(DynLib* lib);
-
- private:
- static DynLibManager* singletonPtr_s;
- };
-}
-
-#endif /* _Core_DynLibManager_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Event.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Event.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Event.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,110 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the classes Event and EventState.
-*/
-
-#include "Event.h"
-
-#include "BaseObject.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- /**
- @brief Processes an event (calls the set-function if the necessary conditions are met).
-
- @param event The fired event
- @param object The object whose state is affected by the event (only needed for debug output)
- */
- void EventState::process(const Event& event, BaseObject* object)
- {
- if (this->bProcessingEvent_)
- {
- COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << '"' << std::endl;
- return;
- }
-
- this->bProcessingEvent_ = true;
-
- COUT(4) << "Processing event (EventState) : originator: " << event.originator_->getIdentifier()->getName() << " (&" << event.originator_ << "), activate: " << event.activate_ << ", name: " << event.name_ << ", statename: " << event.statename_ << ", object: " << object->getIdentifier()->getName() << " (&" << object << ")" << "." << std::endl;
-
- // check if the originator is an instance of the requested class
- if (event.originator_->isA(this->subclass_))
- {
- // If the EventState doesn't act as an EventSink.
- // actualize the activationcounter
- if(!this->bSink_)
- {
- if (event.activate_)
- ++this->activeEvents_;
- else
- {
- --this->activeEvents_;
-
- if (this->activeEvents_ < 0)
- this->activeEvents_ = 0;
- }
- }
-
- if (this->statefunction_->getParamCount() == 0 && event.activate_)
- {
- // if the eventfunction doesn't have a state, just call it whenever an activation-event comes in
- (*this->statefunction_)();
- }
- else if (this->bSink_ || (!this->bSink_ && ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_)) ) )
- {
- // if the eventfunction needs a state, we just call the function if the state changed from 0 to 1 (state = true) or from 1 to 0 (state = false) [but not if activeEvents_ is > 1]
- if (this->statefunction_->getParamCount() == 1)
- {
- // one argument: just the eventstate
- (*this->statefunction_)(event.activate_);
- }
- else if (this->statefunction_->getParamCount() >= 2)
- {
- // two arguments: the eventstate and the originator
- if (this->subclass_->isExactlyA(ClassIdentifier<BaseObject>::getIdentifier()))
- {
- // if the subclass is BaseObject, we don't have to cast the pointer
- (*this->statefunction_)(event.activate_, event.originator_);
- }
- else
- {
- // else cast the pointer to the desired class
- void* castOriginator = event.originator_->getDerivedPointer(this->subclass_->getClassID());
- (*this->statefunction_)(event.activate_, castOriginator);
- }
- }
- }
- }
-
- this->bProcessingEvent_ = false;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Event.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Event.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Event.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,96 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Event Events
- @ingroup Core
-*/
-
-/**
- @file
- @ingroup Event
- @brief Declaration of the classes Event and EventState.
-*/
-
-#ifndef _Event_H__
-#define _Event_H__
-
-#include "CorePrereqs.h"
-#include <string>
-
-namespace orxonox
-{
- /**
- @brief The Event struct contains information about a fired Event.
- */
- struct _CoreExport Event
- {
- Event(bool activate, BaseObject* originator, const std::string& name) : activate_(activate), originator_(originator), name_(name) {}
-
- bool activate_; //!< True if this is an activating event (the event source was inactive before and just triggered the event) - false otherwise
- std::string statename_; //!< The name of the state this event affects
- BaseObject* originator_; //!< The object which triggered this event
- std::string name_; //!< The name of this event
-
- };
-
- /**
- @brief The EventState contains information about an event state.
-
- An event state is a state of an object, which can be changed by events.
- Event states are changed through functions. Possible functions headers for set event states are:
- - memoryless state: <tt>function()</tt>
- - boolean state: <tt>function(bool state)</tt>
- - individual state: <tt>function(bool state, SomeClass originator)</tt>
-
- Note that SomeClass may be any class deriving from BaseObject. You will not receive events from originators of other classes.
- The actual class for SomeClass must be specified as the second argument of the XMLPortEventState() macro.
-
- The this pointer of the affected object is hidden in the functors, because the events are processed in the BaseObject, but some
- statefunctions may be from child-classes.
- */
- class _CoreExport EventState
- {
- public:
- EventState(const FunctorPtr& statefunction, Identifier* subclass, bool bSink = false) : bProcessingEvent_(false), activeEvents_(0), statefunction_(statefunction), subclass_(subclass), bSink_(bSink) {}
-
- void process(const Event& event, BaseObject* object);
-
- const FunctorPtr& getFunctor() const
- { return this->statefunction_; }
-
- private:
- bool bProcessingEvent_; //!< This becomes true while the container processes an event (used to prevent loops)
- int activeEvents_; //!< The number of events which affect this state and are currently active
- FunctorPtr statefunction_; //!< A functor to set the state
- Identifier* subclass_; //!< Originators must be an instance of this class (usually BaseObject, but some statefunctions allow a second argument with an originator of a specific class)
- bool bSink_; //!< Determines whether the EventState acts as an EventSink forwarding any Event (even if the state didn't change) or in the normal manner, only processing Events that change the state.
- };
-}
-
-#endif /* _Event_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/EventIncludes.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/EventIncludes.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/EventIncludes.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,108 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Event
- @brief Definition of the XMLPortEventState() macro, as well as some more useful macros.
-*/
-
-#ifndef _EventIncludes_H__
-#define _EventIncludes_H__
-
-#include "CorePrereqs.h"
-#include "XMLPort.h"
-#include "command/Executor.h"
-
-/**
- @brief Defines a new event state (a state of the object which can be changed by events).
-
- @param classname The name of this class
- @param subclassname Usually BaseObject - if different, only instances of this class can send events to this object
- @param statename The name (string) of this state
- @param function The function which should be used to set the state
- @param xmlelement Argument for XMLPort
- @param mode Argument for XMLPort
-*/
-#define XMLPortEventState(classname, subclassname, statename, function, xmlelement, mode) \
- orxonox::EventState* containername##function = this->getEventState(statename); \
- if (!containername##function) \
- { \
- containername##function = new orxonox::EventState(orxonox::createFunctor(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
- this->addEventState(statename, containername##function); \
- } \
- XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
-
-/**
- @brief Like XMLPortEventState but creates an event sink instead of an event state.
- The most important destinction between an EventState and an EventSink is, that an EventState only processes events which change the state of the EventState, where as an EventSink is an EventState that processes any Event that reaches it.
-*/
-
-#define XMLPortEventSink(classname, subclassname, statename, function, xmlelement, mode) \
- orxonox::EventState* containername##function = this->getEventState(statename); \
- if (!containername##function) \
- { \
- containername##function = new orxonox::EventState(orxonox::createFunctor(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier(), true); \
- this->addEventState(statename, containername##function); \
- } \
- XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
-
-
-#define XMLPortEventStateTemplate(classname, subclassname, statename, function, xmlelement, mode, ...) \
- orxonox::EventState* containername##function = this->getEventState(statename); \
- if (!containername##function) \
- { \
- containername##function = new orxonox::EventState(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
- this->addEventState(statename, containername##function); \
- } \
- XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
-
-#define XMLPortEventStateIntern(name, classname, statename, xmlelement, mode) \
- static orxonox::ExecutorMemberPtr<classname> xmlsetfunctor##name = orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + '(' + statename + ')').cast<orxonox::ExecutorMember<classname> >(); \
- static orxonox::ExecutorMemberPtr<classname> xmlgetfunctor##name = orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + '(' + statename + ')').cast<orxonox::ExecutorMember<classname> >(); \
- xmlsetfunctor##name->setDefaultValue(1, statename); \
- xmlgetfunctor##name->setDefaultValue(1, statename); \
- XMLPortObjectGeneric(xmlport##name, classname, orxonox::BaseObject, statename, xmlsetfunctor##name, xmlgetfunctor##name, xmlelement, mode, false, true)
-
-
-/**
- @brief Defines a new event name for a class. Named events can only have names which were defined with this macro.
-
- @param classname The name of the class
- @param name The name of the event
-*/
-#define CreateEventName(classname, name) \
- static std::string eventname##classname##name = #name
-
-/**
- @brief This macro is needed to fire an event with this name. The event name must previously be declared with @ref CreateEventName.
-*/
-#define FireEventName(classname, name) \
- eventname##classname##name
-
-#endif /* _EventIncludes_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/GUIManager.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GUIManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GUIManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,526 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Benjamin Knecht
- * Co-authors:
- * ...
- *
- */
-
-#include "GUIManager.h"
-
-#include <boost/bind.hpp>
-#include <memory>
-extern "C" {
-#include <lua.h>
-}
-#include <CEGUIDefaultLogger.h>
-#include <CEGUIExceptions.h>
-#include <CEGUIInputEvent.h>
-#include <CEGUIMouseCursor.h>
-#include <CEGUIResourceProvider.h>
-#include <CEGUISystem.h>
-#include <CEGUIWindow.h>
-#include <CEGUIWindowManager.h>
-#include <elements/CEGUIListbox.h>
-#include <elements/CEGUIListboxItem.h>
-#include <ogreceguirenderer/OgreCEGUIRenderer.h>
-
-#include "SpecialConfig.h" // Configures the macro below
-#ifdef CEGUILUA_USE_INTERNAL_LIBRARY
-# include <ceguilua/CEGUILua.h>
-#else
-# include <CEGUILua.h>
-#endif
-
-#include "util/Clock.h"
-#include "util/Convert.h"
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/OrxAssert.h"
-#include "ConfigValueIncludes.h"
-#include "Core.h"
-#include "CoreIncludes.h"
-#include "Game.h"
-#include "GraphicsManager.h"
-#include "LuaState.h"
-#include "PathConfig.h"
-#include "Resource.h"
-#include "command/ConsoleCommand.h"
-#include "input/InputManager.h"
-#include "input/InputState.h"
-#include "input/KeyBinderManager.h"
-
-namespace orxonox
-{
- static void key_esc()
- { GUIManager::getInstance().keyESC(); }
- SetConsoleCommand("keyESC", &key_esc);
-
- class CEGUILogger : public CEGUI::DefaultLogger
- {
- public:
- void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
- {
- int orxonoxLevel = CEGUI::Standard;
- switch (level)
- {
- case CEGUI::Errors: orxonoxLevel = 1; break;
- case CEGUI::Warnings: orxonoxLevel = 2; break;
- case CEGUI::Standard: orxonoxLevel = 4; break;
- case CEGUI::Informative: orxonoxLevel = 5; break;
- case CEGUI::Insane: orxonoxLevel = 6; break;
- default: OrxAssert(false, "CEGUI log level out of range, inpect immediately!");
- }
- OutputHandler::getOutStream(orxonoxLevel)
- << "CEGUI: " << message << std::endl;
-
- CEGUI::DefaultLogger::logEvent(message, level);
- }
- };
-
- static CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button);
-
- GUIManager* GUIManager::singletonPtr_s = 0;
- /*static*/ const std::string GUIManager::defaultScheme_ = "TaharezGreen";
-
- SetConsoleCommand("showGUI", &GUIManager::showGUI).defaultValue(1, false).defaultValue(2, false);
- SetConsoleCommand("hideGUI", &GUIManager::hideGUI);
-
- /**
- @brief
- Constructs the GUIManager by starting up CEGUI
-
- Creates the interface to Ogre, sets up the CEGUI renderer and the Lua script module together with the Lua engine.
- The log is set up and connected to the CEGUILogger.
- After Lua setup tolua++-elements are linked to Lua-state to give Lua access to C++-code.
- Finally initial Lua code is executed (maybe we can do this with the CEGUI startup script automatically).
- @return true if success, otherwise false
- */
- GUIManager::GUIManager(const std::pair<int, int>& mousePosition)
- : resourceProvider_(NULL)
- , camera_(NULL)
- {
- RegisterRootObject(GUIManager);
- this->setConfigValues();
-
- using namespace CEGUI;
-
- COUT(3) << "Initialising CEGUI." << std::endl;
-
- // Note: No SceneManager specified yet
- guiRenderer_.reset(new OgreCEGUIRenderer(GraphicsManager::getInstance().getRenderWindow(), Ogre::RENDER_QUEUE_OVERLAY, false, 3000));
- resourceProvider_ = guiRenderer_->createResourceProvider();
- resourceProvider_->setDefaultResourceGroup("General");
-
- // Setup scripting
- luaState_.reset(new LuaState());
- rootFileInfo_ = Resource::getInfo("InitialiseGUI.lua");
- // This is necessary to ensure that input events also use the right resource info when triggering lua functions
- luaState_->setDefaultResourceInfo(this->rootFileInfo_);
- scriptModule_.reset(new LuaScriptModule(luaState_->getInternalLuaState()));
- scriptModule_->setDefaultPCallErrorHandler(LuaState::ERROR_HANDLER_NAME);
-
- // Create our own logger to specify the filepath
- std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
- ceguiLogger->setLogFilename(PathConfig::getLogPathString() + "cegui.log");
- // set the log level according to ours (translate by subtracting 1)
- ceguiLogger->setLoggingLevel(
- static_cast<LoggingLevel>(OutputHandler::getInstance().getSoftDebugLevel("logFile") - 1));
- this->ceguiLogger_ = ceguiLogger.release();
-
- // Create the CEGUI system singleton
- guiSystem_.reset(new System(guiRenderer_.get(), resourceProvider_, 0, scriptModule_.get()));
-
- // Align CEGUI mouse with OIS mouse
- guiSystem_->injectMousePosition((float)mousePosition.first, (float)mousePosition.second);
-
- // Initialise the Lua framework and load the schemes
- this->luaState_->doFile("InitialiseGUI.lua");
-
- // Create the root nodes
- this->rootWindow_ = CEGUI::WindowManager::getSingleton().createWindow("MenuWidgets/StaticImage", "AbsoluteRootWindow");
- this->rootWindow_->setProperty("FrameEnabled", "False");
- this->hudRootWindow_ = CEGUI::WindowManager::getSingleton().createWindow("DefaultWindow", "HUDRootWindow");
- this->menuRootWindow_ = CEGUI::WindowManager::getSingleton().createWindow("DefaultWindow", "MenuRootWindow");
- // And connect them
- CEGUI::System::getSingleton().setGUISheet(this->rootWindow_);
- this->rootWindow_->addChildWindow(this->hudRootWindow_);
- this->rootWindow_->addChildWindow(this->menuRootWindow_);
-
- // No background to start with (sets the alpha value to 0)
- this->setBackgroundImage("");
-
- // Set up the sheet manager in the Lua framework
- this->luaState_->doFile("SheetManager.lua");
- }
-
- /**
- @brief
- Basically shuts down CEGUI (member smart pointers) but first unloads our Tolua modules.
- */
- GUIManager::~GUIManager()
- {
- }
-
- void GUIManager::setConfigValues(void)
- {
- SetConfigValue(guiScheme_, GUIManager::defaultScheme_) .description("Changes the current GUI scheme.") .callback(this, &GUIManager::changedGUIScheme);
- }
-
- void GUIManager::changedGUIScheme(void)
- {
-
- }
-
- /**
- @brief
- used to tick the GUI
- @param time
- clock which provides time value for the GUI System
-
- Ticking the GUI means updating it with a certain regularity.
- The elapsed time since the last call is given in the time value provided by the clock.
- This time value is then used to provide a fluent animation of the GUI.
- */
- void GUIManager::preUpdate(const Clock& time)
- {
- assert(guiSystem_);
- this->protectedCall(boost::bind(&CEGUI::System::injectTimePulse, _1, time.getDeltaTime()));
- }
-
- /**
- @brief
- Tells the GUIManager which SceneManager to use
- @param camera
- The current camera on which the GUI should be displayed on.
-
- In fact the GUIManager needs the SceneManager and not the Camera to display the GUI.
- This means the GUI is not bound to a camera but rather to the SceneManager.
- Hiding the GUI when needed can therefore not be resolved by just NOT setting the current camera.
- */
- void GUIManager::setCamera(Ogre::Camera* camera)
- {
- this->camera_ = camera;
- if (camera == NULL)
- this->guiRenderer_->setTargetSceneManager(0);
- else
- this->guiRenderer_->setTargetSceneManager(camera->getSceneManager());
- }
-
- /**
- @brief
- Executes Lua code
- @param str
- reference to string object holding the Lua code which is to be executed
- */
- void GUIManager::executeCode(const std::string& str)
- {
- this->luaState_->doString(str, rootFileInfo_);
- }
-
- /** Loads a GUI sheet by Lua script
- @param name
- The name of the GUI (like the script name, but without the extension)
- */
- void GUIManager::loadGUI(const std::string& name)
- {
- this->executeCode("loadSheet(\"" + name + "\")");
- }
-
- /**
- @brief
- Displays specified GUI on screen
- @param name
- The name of the GUI
- @param bHidePrevious
- If true all displayed GUIs on the stack, that are below this GUI are hidden.
- @param bNoInput
- If true the GUI is transparent to input.
-
- The function executes the Lua function with the same name in case the GUIManager is ready.
- */
- /*static*/ void GUIManager::showGUI(const std::string& name, bool bHidePrevious, bool bNoInput)
- {
- GUIManager::getInstance().executeCode("showMenuSheet(\"" + name + "\", " + multi_cast<std::string>(bHidePrevious) + ", " + multi_cast<std::string>(bNoInput) + ")");
- }
-
- /**
- @brief
- Hack-ish. Needed for GUIOverlay.
- */
- void GUIManager::showGUIExtra(const std::string& name, const std::string& ptr, bool bHidePrevious, bool bNoInput)
- {
- this->executeCode("showMenuSheet(\"" + name + "\", " + multi_cast<std::string>(bHidePrevious) + ", " + multi_cast<std::string>(bNoInput) + ", " + ptr + ")");
- }
-
- /**
- @brief
- Hides specified GUI.
- @param name
- The name of the GUI.
- */
- /*static*/ void GUIManager::hideGUI(const std::string& name)
- {
- GUIManager::getInstance().executeCode("hideMenuSheet(\"" + name + "\")");
- }
-
- const std::string& GUIManager::createInputState(const std::string& name, TriBool::Value showCursor, TriBool::Value useKeyboard, bool bBlockJoyStick)
- {
- InputState* state = InputManager::getInstance().createInputState(name);
- if (!state)
- return BLANKSTRING;
-
- /* Table that maps isFullScreen() and showCursor to mouseExclusive
- isFullscreen / showCursor | True | False | Dontcare
- ----------------------------------------------------
- true | True | True | Dontcare
- ----------------------------------------------------
- false | False | True | Dontcare
- */
- if (showCursor == TriBool::Dontcare)
- state->setMouseExclusive(TriBool::Dontcare);
- else if (GraphicsManager::getInstance().isFullScreen() || showCursor == TriBool::False)
- state->setMouseExclusive(TriBool::True);
- else
- state->setMouseExclusive(TriBool::False);
-
- if (showCursor == TriBool::True)
- state->setMouseHandler(this);
- else if (showCursor == TriBool::False)
- state->setMouseHandler(&InputHandler::EMPTY);
-
- if (useKeyboard == TriBool::True)
- state->setKeyHandler(this);
- else if (useKeyboard == TriBool::False)
- state->setKeyHandler(&InputHandler::EMPTY);
-
- if (bBlockJoyStick)
- state->setJoyStickHandler(&InputHandler::EMPTY);
-
- return state->getName();
- }
-
- void GUIManager::keyESC()
- {
- this->executeCode("keyESC()");
- }
-
- void GUIManager::setBackgroundImage(const std::string& imageSet, const std::string imageName)
- {
- if (imageSet.empty() || imageName.empty())
- this->setBackgroundImage("");
- else
- this->setBackgroundImage("set: " + imageSet + " image: " + imageName);
- }
-
- void GUIManager::setBackgroundImage(const std::string& image)
- {
- if (image.empty())
- this->rootWindow_->setProperty("Alpha", "0.0");
- else
- this->rootWindow_->setProperty("Alpha", "1.0");
- this->rootWindow_->setProperty("Image", image);
- }
-
- void GUIManager::buttonPressed(const KeyEvent& evt)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectKeyDown, _1, evt.getKeyCode()));
- this->protectedCall(boost::bind(&CEGUI::System::injectChar, _1, evt.getText()));
- }
-
- void GUIManager::buttonReleased(const KeyEvent& evt)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectKeyUp, _1, evt.getKeyCode()));
- }
-
- /**
- @brief
- Function receiving a mouse button pressed event.
- @param id
- ID of the mouse button which got pressed
-
- This function is inherited by MouseHandler and injects the event into CEGUI.
- It is for CEGUI to process the event.
- */
- void GUIManager::buttonPressed(MouseButtonCode::ByEnum id)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectMouseButtonDown, _1, convertButton(id)));
- }
-
- /**
- @brief
- Function receiving a mouse button released event.
- @param id
- ID of the mouse button which got released
-
- This function is inherited by MouseHandler and injects the event into CEGUI.
- It is for CEGUI to process the event.
- */
- void GUIManager::buttonReleased(MouseButtonCode::ByEnum id)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectMouseButtonUp, _1, convertButton(id)));
- }
-
- void GUIManager::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectMousePosition, _1, (float)abs.x, (float)abs.y));
- }
-
- void GUIManager::mouseScrolled(int abs, int rel)
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectMouseWheelChange, _1, (float)rel));
- }
-
- /**
- @brief Indicates that the mouse left the application's window.
- */
- void GUIManager::mouseLeft()
- {
- this->protectedCall(boost::bind(&CEGUI::System::injectMouseLeaves, _1));
- }
-
- /**
- @brief
- converts mouse event code to CEGUI event code
- @param button
- code of the mouse button as we use it in Orxonox
- @return
- code of the mouse button as it is used by CEGUI
-
- Simple conversion from mouse event code in Orxonox to the one used in CEGUI.
- */
- static inline CEGUI::MouseButton convertButton(MouseButtonCode::ByEnum button)
- {
- switch (button)
- {
- case MouseButtonCode::Left:
- return CEGUI::LeftButton;
-
- case MouseButtonCode::Right:
- return CEGUI::RightButton;
-
- case MouseButtonCode::Middle:
- return CEGUI::MiddleButton;
-
- case MouseButtonCode::Button3:
- return CEGUI::X1Button;
-
- case MouseButtonCode::Button4:
- return CEGUI::X2Button;
-
- default:
- return CEGUI::NoButton;
- }
- }
-
- /** Executes a CEGUI function normally, but catches CEGUI::ScriptException.
- When a ScriptException occurs, the error message will be displayed and
- the program carries on.
- @remarks
- The exception behaviour may pose problems if the code is not written
- exception-safe (and you can forget about that in Lua). The program might
- be left in an undefined state. But otherwise one script error would
- terminate the whole program...
- @note
- Your life gets easier if you use boost::bind to create the object/function.
- @param function
- Any callable object/function that takes this->guiSystem_ as its only parameter.
- @return
- True if input was handled, false otherwise. A caught exception yields true.
- */
- template <typename FunctionType>
- bool GUIManager::protectedCall(FunctionType function)
- {
- try
- {
- return function(this->guiSystem_);
- }
- catch (CEGUI::ScriptException& ex)
- {
- // Display the error and proceed. See @remarks why this can be dangerous.
- COUT(1) << ex.getMessage() << std::endl;
- return true;
- }
- }
-
- /**
- @brief
- Subscribe the input function to the input event for the input window.
- This is a helper to be used in lua, because subscribeScriptedEvent() doesn't work in lua.
- @param window
- The window for which the event is subscribed.
- @param event
- The type of event to which we subscribe.
- @param function
- The function that is called when the event occurs.
- */
- void GUIManager::subscribeEventHelper(CEGUI::Window* window, const std::string& event, const std::string& function)
- {
- window->subscribeScriptedEvent(event, function);
- }
-
- /**
- @brief
- Set the input tooltip text for the input ListboxItem.
- @param item
- The ListboxItem for which the tooltip should be set.
- @param tooltip
- The tooltip text that should be set.
- */
- void GUIManager::setTooltipTextHelper(CEGUI::ListboxItem* item, const std::string& tooltip)
- {
- item->setTooltipText(tooltip);
- }
-
- /**
- @brief
- Set whether the tooltips for the input Listbox are enabled.
- @param listbox
- The Listbox for which to enable (or disable) tooltips.
- @param enabled
- Whether to enable or disabel the tooltips.
- */
- void GUIManager::setItemTooltipsEnabledHelper(CEGUI::Listbox* listbox, bool enabled)
- {
- listbox->setItemTooltipsEnabled(enabled);
- }
-
- /**
- @brief Callback of window event listener, called if the window is resized. Sets the display size of CEGUI.
- */
- void GUIManager::windowResized(unsigned int newWidth, unsigned int newHeight)
- {
- this->guiRenderer_->setDisplaySize(CEGUI::Size(newWidth, newHeight));
- }
-
- /**
- @brief Notify CEGUI if the windows loses the focus (stops higlight of menu items, etc).
- */
- void GUIManager::windowFocusChanged(bool bFocus)
- {
- if (!bFocus)
- this->mouseLeft();
- }
-
-}
Deleted: code/forks/sandbox_light/src/libraries/core/GUIManager.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GUIManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GUIManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,162 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Benjamin Knecht
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Graphics
-*/
-
-#ifndef _GUIManager_H__
-#define _GUIManager_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <set>
-#include <string>
-#include <CEGUIForwardRefs.h>
-#include <boost/scoped_ptr.hpp>
-#include <boost/shared_ptr.hpp>
-
-#include "util/OgreForwardRefs.h"
-#include "util/TriBool.h"
-#include "util/Singleton.h"
-#include "input/InputHandler.h"
-#include "OrxonoxClass.h"
-#include "WindowEventListener.h"
-
-// Tolua includes (have to be relative to the current directory)
-/*
-$cfile "../util/TriBool.h" // tolua_export
-*/
-
-namespace orxonox // tolua_export
-{ // tolua_export
- class PlayerInfo; // Forward declaration
-
- /**
- @class GUIManager
- @brief
- Provides a simple interface to CEGUI with tolua methods and console commands. It also acts as a key and mouse handler.
-
- The GUIManager is a singleton and can be called anywhere when access on the GUI is needed.
-
- Since the GUI needs user input, the GUIManager implements the functions needed to act as a key and/or mouse handler.
- Those input events are then injected into CEGUI in Lua.
- */
- class _CoreExport GUIManager // tolua_export
- : public Singleton<GUIManager>, public InputHandler, public WindowEventListener
- { // tolua_export
- friend class Singleton<GUIManager>;
- public:
- GUIManager(const std::pair<int, int>& mousePosition);
- ~GUIManager();
-
- void setConfigValues(void);
- void changedGUIScheme(void);
-
- void preUpdate(const Clock& time);
-
- void loadGUI(const std::string& name);
- static void showGUI(const std::string& name, bool bHidePrevious = false, bool bNoInput = false);
- void showGUIExtra(const std::string& name, const std::string& ptr, bool bHidePrevious = false, bool bNoInput = false);
- static void hideGUI(const std::string& name);
- void keyESC();
- void setBackgroundImage(const std::string& imageSet, const std::string imageName); // tolua_export
- void setBackgroundImage(const std::string& image);
-
- //! Creates a new InputState to be used with a GUI Sheet
- const std::string& createInputState(const std::string& name, TriBool::Value showCursor = TriBool::True, TriBool::Value useKeyboard = TriBool::True, bool bBlockJoyStick = false); // tolua_export
- LuaState* getLuaState(void)
- { return this->luaState_.get(); }
-
- //! Returns the root window for all menu sheets
- CEGUI::Window* getMenuRootWindow() { return this->menuRootWindow_; } // tolua_export
- //! Returns the root window for all HUD sheets
- CEGUI::Window* getHUDRootWindow() { return this->hudRootWindow_; } // tolua_export
-
- void setCamera(Ogre::Camera* camera);
- Ogre::Camera* getCamera() { return this->camera_; }
-
- inline void setPlayer(const std::string& guiname, PlayerInfo* player)
- { this->players_[guiname] = player; }
- inline orxonox::PlayerInfo* getPlayer(const std::string& guiname) const { std::map<std::string, PlayerInfo*>::const_iterator it = this->players_.find(guiname); return (it != this->players_.end()) ? it->second : 0; } // tolua_export
-
- // TODO: Temporary hack because the tolua exported CEGUI method does not seem to work
- static void subscribeEventHelper(CEGUI::Window* window, const std::string& event, const std::string& function); //tolua_export
- static void setTooltipTextHelper(CEGUI::ListboxItem* item, const std::string& toooltip); //tolua_export
- static void setItemTooltipsEnabledHelper(CEGUI::Listbox* listbox, bool enabled); //tolua_export
-
- static GUIManager& getInstance() { return Singleton<GUIManager>::getInstance(); } // tolua_export
-
- private:
- GUIManager(const GUIManager& instance); //!< private and undefined copy c'tor (this is a singleton class)
- void executeCode(const std::string& str);
-
- template <typename FunctionType>
- bool protectedCall(FunctionType function);
-
- // keyHandler functions
- void buttonPressed (const KeyEvent& evt);
- void buttonReleased(const KeyEvent& evt);
-
- // mouseHandler functions
- void buttonPressed (MouseButtonCode::ByEnum id);
- void buttonReleased(MouseButtonCode::ByEnum id);
- void mouseMoved (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
- void mouseScrolled (int abs, int rel);
- void mouseLeft ();
-
- // window event handler
- virtual void windowResized(unsigned int newWidth, unsigned int newHeight);
- virtual void windowFocusChanged(bool bFocus);
-
- scoped_ptr<CEGUI::OgreCEGUIRenderer> guiRenderer_; //!< CEGUI's interface to the Ogre Engine
- scoped_ptr<LuaState> luaState_; //!< LuaState, access point to the Lua engine
- scoped_ptr<CEGUI::LuaScriptModule> scriptModule_; //!< CEGUI's script module to use Lua
- scoped_ptr<CEGUI::System> guiSystem_; //!< CEGUI's main system
- shared_ptr<ResourceInfo> rootFileInfo_; //!< Resource information about the root script
- CEGUI::ResourceProvider* resourceProvider_; //!< CEGUI's resource provider
- CEGUI::Logger* ceguiLogger_; //!< CEGUI's logger to be able to log CEGUI errors in our log
- CEGUI::Window* rootWindow_; //!< Root node for all windows
- CEGUI::Window* hudRootWindow_; //!< Root node for the HUD sheets
- CEGUI::Window* menuRootWindow_; //!< Root node for the menu sheets (used by Lua)
- std::map<std::string, PlayerInfo*> players_; //!< Stores the player (owner) for each GUI
- Ogre::Camera* camera_; //!< Camera used to render the scene with the GUI
-
- static GUIManager* singletonPtr_s; //!< Singleton reference to GUIManager
-
- // The used CEGUI scheme.
- static const std::string defaultScheme_;
- std::string guiScheme_;
-
- }; // tolua_export
-} // tolua_export
-
-#endif /* _GUIManager_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Game.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Game.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Game.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,610 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at brief
- Implementation of the Game class.
-*/
-
-#include "Game.h"
-
-#include <exception>
-#include <boost/weak_ptr.hpp>
-#include <loki/ScopeGuard.h>
-
-#include "util/Clock.h"
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/Sleep.h"
-#include "util/SubString.h"
-#include "CommandLineParser.h"
-#include "Core.h"
-#include "CoreIncludes.h"
-#include "ConfigValueIncludes.h"
-#include "GameMode.h"
-#include "GameState.h"
-#include "GUIManager.h"
-#include "command/ConsoleCommand.h"
-
-namespace orxonox
-{
- static void stop_game()
- { Game::getInstance().stop(); }
- SetConsoleCommand("exit", &stop_game);
- static void printFPS()
- { COUT(0) << Game::getInstance().getAvgFPS() << std::endl; }
- SetConsoleCommand("printFPS", &printFPS);
- static void printTickTime()
- { COUT(0) << Game::getInstance().getAvgTickTime() << std::endl; }
- SetConsoleCommand("printTickTime", &printTickTime);
-
- std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
- Game* Game::singletonPtr_s = 0;
-
- //! Represents one node of the game state tree.
- struct GameStateTreeNode
- {
- std::string name_;
- weak_ptr<GameStateTreeNode> parent_;
- std::vector<shared_ptr<GameStateTreeNode> > children_;
- };
-
- Game::Game(const std::string& cmdLine)
- // Destroy factories before the Core!
- : gsFactoryDestroyer_(Game::GameStateFactory::getFactories(), &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
- {
- this->bAbort_ = false;
- bChangingState_ = false;
-
-#ifdef ORXONOX_PLATFORM_WINDOWS
- minimumSleepTime_ = 1000/*us*/;
-#else
- minimumSleepTime_ = 0/*us*/;
-#endif
-
- // reset statistics
- this->statisticsStartTime_ = 0;
- this->statisticsTickTimes_.clear();
- this->periodTickTime_ = 0;
- this->periodTime_ = 0;
- this->avgFPS_ = 0.0f;
- this->avgTickTime_ = 0.0f;
- this->excessSleepTime_ = 0;
-
- // Create an empty root state
- this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
-
- // Set up a basic clock to keep time
- this->gameClock_.reset(new Clock());
-
- // Create the Core
- this->core_.reset(new Core(cmdLine));
-
- // Do this after the Core creation!
- ClassIdentifier<Game>::getIdentifier("Game")->initialiseObject(this, "Game", true);
- this->setConfigValues();
-
- // After the core has been created, we can safely instantiate the GameStates that don't require graphics
- for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
- it != gameStateDeclarations_s.end(); ++it)
- {
- if (!it->second.bGraphicsMode)
- constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second);
- }
-
- // The empty root state is ALWAYS loaded!
- this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
- this->rootStateNode_->name_ = "emptyRootGameState";
- this->loadedTopStateNode_ = this->rootStateNode_;
- this->loadedStates_.push_back(this->getState(rootStateNode_->name_));
- }
-
- /**
- @brief
- All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
- */
- Game::~Game()
- {
- // Remove us from the object lists again to avoid problems when destroying them
- this->unregisterObject();
- }
-
- void Game::setConfigValues()
- {
- SetConfigValue(statisticsRefreshCycle_, 250000)
- .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
- SetConfigValue(statisticsAvgLength_, 1000000)
- .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
- SetConfigValue(fpsLimit_, 50)
- .description("Sets the desired frame rate (0 for no limit).");
- }
-
- /**
- @brief
- Main loop of the orxonox game.
- @note
- We use the Ogre::Timer to measure time since it uses the most precise
- method an any platform (however the windows timer lacks time when under
- heavy kernel load!).
- */
- void Game::run()
- {
- if (this->requestedStateNodes_.empty())
- COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
-
- // START GAME
- // first delta time should be about 0 seconds
- this->gameClock_->capture();
- // A first item is required for the fps limiter
- StatisticsTickInfo tickInfo = {0, 0};
- statisticsTickTimes_.push_back(tickInfo);
- while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
- {
- // Generate the dt
- this->gameClock_->capture();
-
- // Statistics init
- StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
- statisticsTickTimes_.push_back(tickInfo);
- this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
-
- // Update the GameState stack if required
- this->updateGameStateStack();
-
- // Core preUpdate
- try
- { this->core_->preUpdate(*this->gameClock_); }
- catch (...)
- {
- COUT(0) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << std::endl;
- COUT(0) << "This should really never happen! Closing the program." << std::endl;
- this->stop();
- break;
- }
-
- // Update the GameStates bottom up in the stack
- this->updateGameStates();
-
- // Core postUpdate
- try
- { this->core_->postUpdate(*this->gameClock_); }
- catch (...)
- {
- COUT(0) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << std::endl;
- COUT(0) << "This should really never happen! Closing the program." << std::endl;
- this->stop();
- break;
- }
-
- // Evaluate statistics
- this->updateStatistics();
-
- // Limit frame rate
- this->updateFPSLimiter();
- }
-
- // UNLOAD all remaining states
- while (this->loadedStates_.size() > 1)
- this->unloadState(this->loadedStates_.back()->getName());
- this->loadedTopStateNode_ = this->rootStateNode_;
- this->requestedStateNodes_.clear();
- }
-
- void Game::updateGameStateStack()
- {
- while (this->requestedStateNodes_.size() > 0)
- {
- shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
- assert(this->loadedTopStateNode_);
- if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
- this->unloadState(loadedTopStateNode_->name_);
- else // has to be child
- {
- try
- {
- this->loadState(requestedStateNode->name_);
- }
- catch (...)
- {
- COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << std::endl;
- // All scheduled operations have now been rendered inert --> flush them and issue a warning
- if (this->requestedStateNodes_.size() > 1)
- COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
- this->requestedStateNodes_.clear();
- break;
- }
- }
- this->loadedTopStateNode_ = requestedStateNode;
- this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
- }
- }
-
- void Game::updateGameStates()
- {
- // Note: The first element is the empty root state, which doesn't need ticking
- for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1;
- it != this->loadedStates_.end(); ++it)
- {
- try
- {
- // Add tick time for most of the states
- uint64_t timeBeforeTick = 0;
- if ((*it)->getInfo().bIgnoreTickTime)
- timeBeforeTick = this->gameClock_->getRealMicroseconds();
- (*it)->update(*this->gameClock_);
- if ((*it)->getInfo().bIgnoreTickTime)
- this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
- }
- catch (...)
- {
- COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Exception::handleMessage() << std::endl;
- COUT(1) << "This should really never happen!" << std::endl;
- COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
- shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_;
- while (current->name_ != (*it)->getName() && current)
- current = current->parent_.lock();
- if (current && current->parent_.lock())
- this->requestState(current->parent_.lock()->name_);
- else
- this->stop();
- break;
- }
- }
- }
-
- void Game::updateStatistics()
- {
- // Add the tick time of this frame (rendering time has already been subtracted)
- uint64_t currentTime = gameClock_->getMicroseconds();
- uint64_t currentRealTime = gameClock_->getRealMicroseconds();
- this->statisticsTickTimes_.back().tickLength += (uint32_t)(currentRealTime - currentTime);
- this->periodTickTime_ += (uint32_t)(currentRealTime - currentTime);
- if (this->periodTime_ > this->statisticsRefreshCycle_)
- {
- std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
- assert(it != this->statisticsTickTimes_.end());
- int64_t lastTime = currentTime - this->statisticsAvgLength_;
- if (static_cast<int64_t>(it->tickTime) < lastTime)
- {
- do
- {
- assert(this->periodTickTime_ >= it->tickLength);
- this->periodTickTime_ -= it->tickLength;
- ++it;
- assert(it != this->statisticsTickTimes_.end());
- } while (static_cast<int64_t>(it->tickTime) < lastTime);
- this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
- }
-
- uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
- // Why minus 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too low
- this->avgFPS_ = -1 + static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
- this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
-
- this->periodTime_ -= this->statisticsRefreshCycle_;
- }
- }
-
- void Game::updateFPSLimiter()
- {
- uint64_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / fpsLimit_);
- uint64_t currentRealTime = gameClock_->getRealMicroseconds();
- while (currentRealTime < nextTime - minimumSleepTime_)
- {
- usleep((unsigned long)(nextTime - currentRealTime));
- currentRealTime = gameClock_->getRealMicroseconds();
- }
- // Integrate excess to avoid steady state error
- excessSleepTime_ = (int)(currentRealTime - nextTime);
- // Anti windup
- if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
- excessSleepTime_ = 50000;
- }
-
- void Game::stop()
- {
- this->bAbort_ = true;
- }
-
- void Game::subtractTickTime(int32_t length)
- {
- assert(!this->statisticsTickTimes_.empty());
- this->statisticsTickTimes_.back().tickLength -= length;
- this->periodTickTime_ -= length;
- }
-
-
- /***** GameState related *****/
-
- void Game::requestState(const std::string& name)
- {
- if (!this->checkState(name))
- {
- COUT(2) << "Warning: GameState named '" << name << "' doesn't exist!" << std::endl;
- return;
- }
-
- if (this->bChangingState_)
- {
- COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
- return;
- }
-
- shared_ptr<GameStateTreeNode> lastRequestedNode;
- if (this->requestedStateNodes_.empty())
- lastRequestedNode = this->loadedTopStateNode_;
- else
- lastRequestedNode = this->requestedStateNodes_.back();
- if (name == lastRequestedNode->name_)
- {
- COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
- return;
- }
-
- // Check children first
- std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
- for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
- {
- if (lastRequestedNode->children_[i]->name_ == name)
- {
- requestedNodes.push_back(lastRequestedNode->children_[i]);
- break;
- }
- }
-
- if (requestedNodes.empty())
- {
- // Check parent and all its grand parents
- shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
- while (currentNode != NULL)
- {
- if (currentNode->name_ == name)
- break;
- currentNode = currentNode->parent_.lock();
- requestedNodes.push_back(currentNode);
- }
- if (currentNode == NULL)
- requestedNodes.clear();
- }
-
- if (requestedNodes.empty())
- COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
- else
- this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
- }
-
- void Game::requestStates(const std::string& names)
- {
- SubString tokens(names, ",;", " ");
- for (unsigned int i = 0; i < tokens.size(); ++i)
- this->requestState(tokens[i]);
- }
-
- void Game::popState()
- {
- shared_ptr<GameStateTreeNode> lastRequestedNode;
- if (this->requestedStateNodes_.empty())
- lastRequestedNode = this->loadedTopStateNode_;
- else
- lastRequestedNode = this->requestedStateNodes_.back();
- if (lastRequestedNode != this->rootStateNode_)
- this->requestState(lastRequestedNode->parent_.lock()->name_);
- else
- COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
- }
-
- shared_ptr<GameState> Game::getState(const std::string& name)
- {
- GameStateMap::const_iterator it = constructedStates_.find(name);
- if (it != constructedStates_.end())
- return it->second;
- else
- {
- std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
- if (it != gameStateDeclarations_s.end())
- COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl;
- else
- COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl;
- return shared_ptr<GameState>();
- }
- }
-
- void Game::setStateHierarchy(const std::string& str)
- {
- // Split string into pieces of the form whitespacesText
- std::vector<std::pair<std::string, int> > stateStrings;
- size_t pos = 0;
- size_t startPos = 0;
- while (pos < str.size())
- {
- int indentation = 0;
- while (pos < str.size() && str[pos] == ' ')
- ++indentation, ++pos;
- startPos = pos;
- while (pos < str.size() && str[pos] != ' ')
- ++pos;
- stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
- }
- if (stateStrings.empty())
- ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
- // Add element with large identation to detect the last with just an iterator
- stateStrings.push_back(std::make_pair("", -1));
-
- // Parse elements recursively
- std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
- parseStates(begin, this->rootStateNode_);
- }
-
- /*** Internal ***/
-
- void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
- {
- SubString tokens(it->first, ",");
- std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
-
- for (unsigned int i = 0; i < tokens.size(); ++i)
- {
- it = startIt; // Reset iterator to the beginning of the sub tree
- if (!this->checkState(tokens[i]))
- ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
- if (tokens[i] == this->rootStateNode_->name_)
- ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
- shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
- node->name_ = tokens[i];
- node->parent_ = currentNode;
- currentNode->children_.push_back(node);
-
- int currentLevel = it->second;
- ++it;
- while (it->second != -1)
- {
- if (it->second <= currentLevel)
- break;
- else if (it->second == currentLevel + 1)
- parseStates(it, node);
- else
- ThrowException(GameState, "Indentation error while parsing the hierarchy.");
- }
- }
- }
-
- void Game::loadGraphics()
- {
- if (!GameMode::showsGraphics())
- {
- core_->loadGraphics();
- Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
-
- // Construct all the GameStates that require graphics
- for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
- it != gameStateDeclarations_s.end(); ++it)
- {
- if (it->second.bGraphicsMode)
- {
- // Game state loading failure is serious --> don't catch
- shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second);
- if (!constructedStates_.insert(std::make_pair(
- it->second.stateName, gameState)).second)
- assert(false); // GameState was already created!
- }
- }
- graphicsUnloader.Dismiss();
- }
- }
-
- void Game::unloadGraphics()
- {
- if (GameMode::showsGraphics())
- {
- // Destroy all the GameStates that require graphics
- for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
- {
- if (it->second->getInfo().bGraphicsMode)
- constructedStates_.erase(it++);
- else
- ++it;
- }
-
- core_->unloadGraphics();
- }
- }
-
- bool Game::checkState(const std::string& name) const
- {
- std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
- if (it == gameStateDeclarations_s.end())
- return false;
- else
- return true;
- }
-
- void Game::loadState(const std::string& name)
- {
- this->bChangingState_ = true;
- LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState);
-
- // If state requires graphics, load it
- Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
- if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
- this->loadGraphics();
- else
- graphicsUnloader.Dismiss();
-
- shared_ptr<GameState> state = this->getState(name);
- state->activateInternal();
- if (!this->loadedStates_.empty())
- this->loadedStates_.back()->activity_.topState = false;
- this->loadedStates_.push_back(state);
- state->activity_.topState = true;
-
- graphicsUnloader.Dismiss();
- }
-
- void Game::unloadState(const std::string& name)
- {
- this->bChangingState_ = true;
- try
- {
- shared_ptr<GameState> state = this->getState(name);
- state->activity_.topState = false;
- this->loadedStates_.pop_back();
- if (!this->loadedStates_.empty())
- this->loadedStates_.back()->activity_.topState = true;
- state->deactivateInternal();
- }
- catch (...)
- {
- COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << std::endl;
- COUT(2) << " There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
- }
- // Check if graphics is still required
- if (!bAbort_)
- {
- bool graphicsRequired = false;
- for (unsigned i = 0; i < loadedStates_.size(); ++i)
- graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
- if (!graphicsRequired)
- this->unloadGraphics();
- }
- this->bChangingState_ = false;
- }
-
- /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories()
- {
- static std::map<std::string, shared_ptr<GameStateFactory> > factories;
- return factories;
- }
-
- /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
- {
- std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
- assert(it != getFactories().end());
- return it->second->fabricateInternal(info);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Game.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Game.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Game.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,226 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at ingroup Management CoreGame
- at brief
- Declaration of Game Singleton which is responsible for running the game.
- */
-
-#ifndef _Game_H__
-#define _Game_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-#include <list>
-#include <map>
-#include <string>
-#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <boost/scoped_ptr.hpp>
-#include <boost/preprocessor/cat.hpp>
-#include <loki/ScopeGuard.h>
-
-#include "util/Debug.h"
-#include "util/Singleton.h"
-#include "OrxonoxClass.h"
-
-/**
- at brief
- Adds a new GameState to the Game. The second parameter is the name as string
- and every following paramter is a constructor argument (which is usually non existent)
-*/
-#define DeclareGameState(className, stateName, bIgnoreTickTime, bGraphicsMode) \
- static bool BOOST_PP_CAT(bGameStateDummy_##className, __LINE__) = orxonox::Game::declareGameState<className>(#className, stateName, bIgnoreTickTime, bGraphicsMode)
-// tolua_begin
-namespace orxonox
-{
-// tolua_end
-
- //! Helper object required before GameStates are being constructed
- struct GameStateInfo
- {
- std::string stateName;
- std::string className;
- bool bIgnoreTickTime;
- bool bGraphicsMode;
- };
-
- /**
- @brief
- Main class responsible for running the game.
- @remark
- You should only create this singleton once because it owns the Core class! (see remark there)
- */
-// tolua_begin
- class _CoreExport Game
-// tolua_end
- : public Singleton<Game>, public OrxonoxClass
- { // tolua_export
- friend class Singleton<Game>;
- typedef std::vector<shared_ptr<GameState> > GameStateVector;
- typedef std::map<std::string, shared_ptr<GameState> > GameStateMap;
- typedef shared_ptr<GameStateTreeNode> GameStateTreeNodePtr;
-
- public:
- Game(const std::string& cmdLine);
- ~Game();
-
- void setConfigValues();
-
- void setStateHierarchy(const std::string& str);
- shared_ptr<GameState> getState(const std::string& name);
-
- void run();
- void stop();
-
- static Game& getInstance(){ return Singleton<Game>::getInstance(); } // tolua_export
-
- void requestState(const std::string& name); //tolua_export
- void requestStates(const std::string& names); //tolua_export
- void popState(); //tolua_export
-
- const Clock& getGameClock() { return *this->gameClock_; }
-
- float getAvgTickTime() { return this->avgTickTime_; }
- float getAvgFPS() { return this->avgFPS_; }
-
- void subtractTickTime(int32_t length);
-
- template <class T>
- static bool declareGameState(const std::string& className, const std::string& stateName, bool bIgnoreTickTime, bool bConsoleMode);
-
- private:
- class _CoreExport GameStateFactory
- {
- public:
- virtual ~GameStateFactory() { }
- static shared_ptr<GameState> fabricate(const GameStateInfo& info);
- template <class T>
- static void createFactory(const std::string& className)
- { getFactories()[className].reset(new TemplateGameStateFactory<T>()); }
-
- virtual shared_ptr<GameState> fabricateInternal(const GameStateInfo& info) = 0;
- static std::map<std::string, shared_ptr<GameStateFactory> >& getFactories();
- };
- template <class T>
- class TemplateGameStateFactory : public GameStateFactory
- {
- public:
- shared_ptr<GameState> fabricateInternal(const GameStateInfo& info)
- { return shared_ptr<GameState>(new T(info)); }
- };
- // For the factory destruction
- typedef Loki::ObjScopeGuardImpl0<std::map<std::string, shared_ptr<GameStateFactory> >, void (std::map<std::string, shared_ptr<GameStateFactory> >::*)()> ObjScopeGuard;
-
- struct StatisticsTickInfo
- {
- uint64_t tickTime;
- uint32_t tickLength;
- };
-
- Game(Game&); // don't mess with singletons
-
- void loadGraphics();
- void unloadGraphics();
-
- void parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode);
- bool checkState(const std::string& name) const;
- void loadState(const std::string& name);
- void unloadState(const std::string& name);
-
- // Main loop structuring
- void updateGameStateStack();
- void updateGameStates();
- void updateStatistics();
- void updateFPSLimiter();
-
- // ScopeGuard helper function
- void resetChangingState() { this->bChangingState_ = false; }
-
- scoped_ptr<Clock> gameClock_;
- scoped_ptr<Core> core_;
- ObjScopeGuard gsFactoryDestroyer_;
-
- GameStateMap constructedStates_;
- GameStateVector loadedStates_;
- GameStateTreeNodePtr rootStateNode_;
- GameStateTreeNodePtr loadedTopStateNode_;
- std::vector<GameStateTreeNodePtr> requestedStateNodes_;
-
- bool bChangingState_;
- bool bAbort_;
-
- // variables for time statistics
- uint64_t statisticsStartTime_;
- std::list<StatisticsTickInfo> statisticsTickTimes_;
- uint32_t periodTime_;
- uint32_t periodTickTime_;
- float avgFPS_;
- float avgTickTime_;
- int excessSleepTime_;
- unsigned int minimumSleepTime_;
-
- // config values
- unsigned int statisticsRefreshCycle_;
- unsigned int statisticsAvgLength_;
- unsigned int fpsLimit_;
-
- static std::map<std::string, GameStateInfo> gameStateDeclarations_s;
- static Game* singletonPtr_s; //!< Pointer to the Singleton
- }; //tolua_export
-
- template <class T>
- /*static*/ bool Game::declareGameState(const std::string& className, const std::string& stateName, bool bIgnoreTickTime, bool bGraphicsMode)
- {
- std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(stateName);
- if (it == gameStateDeclarations_s.end())
- {
- GameStateInfo& info = gameStateDeclarations_s[stateName];
- info.stateName = stateName;
- info.className = className;
- info.bIgnoreTickTime = bIgnoreTickTime;
- info.bGraphicsMode = bGraphicsMode;
- }
- else
- {
- COUT(0) << "Error: Cannot declare two GameStates with the same name." << std::endl;
- COUT(0) << " Ignoring second one ('" << stateName << "')." << std::endl;
- }
-
- // Create a factory to delay GameState creation
- GameStateFactory::createFactory<T>(className);
-
- // just a required dummy return value
- return true;
- }
-} //tolua_export
-
-#endif /* _Game_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/GameMode.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GameMode.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GameMode.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,39 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-#include "GameMode.h"
-
-namespace orxonox
-{
- bool GameMode::bShowsGraphics_s = false;
- bool GameMode::bPlaysSound_s = false;
- bool GameMode::bIsServer_s = false;
- bool GameMode::bIsClient_s = false;
- bool GameMode::bIsStandalone_s = false;
- bool GameMode::bIsMaster_s = false;
-}
Deleted: code/forks/sandbox_light/src/libraries/core/GameMode.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GameMode.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GameMode.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,84 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Management CoreGame
- @brief Declaration of the GameMode class which stores and returns the current mode of the game.
-*/
-
-#ifndef _GameMode_H__
-#define _GameMode_H__
-
-#include "CorePrereqs.h"
-
-// tolua_begin
-namespace orxonox
-{
- /// Helper class, stores and returns the current mode of the game.
- class _CoreExport GameMode
- {
-// tolua_end
- friend class Core;
-
- public:
-// tolua_begin
- static bool showsGraphics() { return bShowsGraphics_s; } ///< Returns true if the game shows graphics, false if it is in text-console mode
- static bool playsSound() { return bPlaysSound_s; } ///< Returns true if the game is able to play sounds
- static bool isServer() { return bIsServer_s; } ///< Returns true if we're currently a server (online)
- static bool isClient() { return bIsClient_s; } ///< Returns true if we're currently a client (online)
- static bool isStandalone() { return bIsStandalone_s; } ///< Returns true if we're in standalone mode (offline)
- static bool isMaster() { return bIsMaster_s; } ///< Returns true if we're in control of the game (either standalone or server)
-// tolua_end
-
- static void setPlaysSound (bool val) { bPlaysSound_s = val; } ///< Defines if the game can play sounds
- static void setIsServer (bool val) { bIsServer_s = val; updateIsMaster(); } ///< Defines if the program is in server mode (online)
- static void setIsClient (bool val) { bIsClient_s = val; updateIsMaster(); } ///< Defines if the program is in client mode (online)
- static void setIsStandalone (bool val) { bIsStandalone_s = val; updateIsMaster(); } ///< Defines if the program is in standalone mode (offline)
-
- private:
- GameMode();
- GameMode(const GameMode& inst);
- ~GameMode();
-
- /// Checks if we're in control of the game (either standalone or server).
- static void updateIsMaster()
- {
- bIsMaster_s = (bIsServer_s || bIsStandalone_s);
- }
-
- static bool bShowsGraphics_s; //!< global variable that tells whether to show graphics
- static bool bPlaysSound_s; //!< global variable that tells whether to sound works
- static bool bIsServer_s; //!< global variable that tells whether this is a server (online)
- static bool bIsClient_s; //!< global variable that tells whether this is a client (online)
- static bool bIsStandalone_s; //!< global variable that tells whether the game is running in standalone mode (offline)
- static bool bIsMaster_s; //!< global variable that tells whether we're in control of the game (standalone or server)
- }; // tolua_export
-} // tolua_export
-
-#endif /* _GameMode_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/GameState.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GameState.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GameState.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,97 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at brief
- Implementation of GameState class.
-*/
-
-#include "GameState.h"
-
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/OrxAssert.h"
-#include "Game.h"
-
-namespace orxonox
-{
- /**
- @brief
- Constructor only initialises variables and sets the name permanently.
- */
- GameState::GameState(const GameStateInfo& info)
- : info_(info)
- {
- this->activity_.activating = false;
- this->activity_.active = false;
- this->activity_.deactivating = false;
- this->activity_.suspended = false;
- this->activity_.topState = false;
- this->activity_.updating = false;
- }
-
- /**
- @brief
- Destructor only checks that we don't delete an active state.
- */
- GameState::~GameState()
- {
- OrxAssert(this->activity_.active == false, "Deleting an active GameState is a very bad idea..");
- }
-
- const std::string& GameState::getName() const
- {
- return info_.stateName;
- }
-
- void GameState::activateInternal()
- {
- this->activity_.activating = true;
- this->activate();
- this->activity_.activating = false;
- this->activity_.active = true;
- }
-
- void GameState::deactivateInternal()
- {
- this->activity_.active = false;
- this->activity_.deactivating = true;
- this->deactivate();
- this->activity_.deactivating = false;
- this->activity_.suspended = false;
- this->activity_.updating = false;
- }
-
- void GameState::updateInternal(const Clock& time)
- {
- this->activity_.updating = true;
- this->update(time);
- this->activity_.updating = false;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/GameState.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GameState.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GameState.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,104 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at ingroup Management CoreGame
- at brief
- Definition of GameState class.
-*/
-
-#ifndef _GameState_H__
-#define _GameState_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-#include "util/UtilPrereqs.h"
-
-namespace orxonox
-{
- /**
- @brief
- An implementation of a tree to manage game states.
- This leads to a certain hierarchy that is created at runtime.
- To actually use the structure, you will have to derive from it and
- implement 'enter', 'leave' and 'tick'. The latter corresponds to an
- update function.
-
- Internally the tree is managed by two maps per node: One stores all its
- children, grandchildren, etc. by name of the state. The other maps these
- children states to the actual child of the node.
- An example: Foo is a grandchildren of Bar and Foofoo is the Foo's parent.
- Then Bar stores Foo in map by its name. The other one then maps Foo to Foofoo.
- */
- class _CoreExport GameState
- {
- friend class Game;
-
- public:
- /**
- @brief
- Gives information about what the GameState is currently doing
- */
- struct State
- {
- unsigned active : 1;
- unsigned activating : 1;
- unsigned deactivating : 1;
- unsigned updating : 1;
- unsigned suspended : 1;
- unsigned topState : 1;
- };
-
- public:
- GameState(const GameStateInfo& info);
- virtual ~GameState();
-
- const std::string& getName() const;
- State getActivity() const { return activity_; }
- const GameStateInfo& getInfo() const { return info_; }
-
- protected:
- virtual void activate() { }
- virtual void deactivate() { }
- virtual void update(const Clock& time) { }
-
- private:
- void setActivity(State activity);
- void activateInternal();
- void deactivateInternal();
- void updateInternal(const Clock& time);
-
- const GameStateInfo& info_;
- State activity_;
- };
-}
-
-#endif /* _GameState_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/GraphicsManager.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GraphicsManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GraphicsManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,462 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
- * Co-authors:
- * Felix Schulthess
- *
- */
-
-#include "GraphicsManager.h"
-
-#include <fstream>
-#include <sstream>
-#include <boost/filesystem.hpp>
-#include <boost/shared_array.hpp>
-
-#include <OgreArchiveFactory.h>
-#include <OgreArchiveManager.h>
-#include <OgreFrameListener.h>
-#include <OgreRoot.h>
-#include <OgreLogManager.h>
-#include <OgreRenderWindow.h>
-#include <OgreRenderSystem.h>
-#include <OgreResourceGroupManager.h>
-#include <OgreTextureManager.h>
-#include <OgreViewport.h>
-#include <OgreWindowEventUtilities.h>
-
-#include "SpecialConfig.h"
-#include "util/Clock.h"
-#include "util/Exception.h"
-#include "util/StringUtils.h"
-#include "util/SubString.h"
-#include "ConfigValueIncludes.h"
-#include "CoreIncludes.h"
-#include "Core.h"
-#include "Game.h"
-#include "GameMode.h"
-#include "Loader.h"
-#include "MemoryArchive.h"
-#include "PathConfig.h"
-#include "WindowEventListener.h"
-#include "XMLFile.h"
-#include "command/ConsoleCommand.h"
-
-namespace orxonox
-{
- static const std::string __CC_printScreen_name = "printScreen";
- DeclareConsoleCommand(__CC_printScreen_name, &prototype::void__void);
-
- class OgreWindowEventListener : public Ogre::WindowEventListener
- {
- public:
- void windowResized (Ogre::RenderWindow* rw)
- { orxonox::WindowEventListener::resizeWindow(rw->getWidth(), rw->getHeight()); }
- void windowFocusChange (Ogre::RenderWindow* rw)
- { orxonox::WindowEventListener::changeWindowFocus(rw->isActive()); }
- void windowClosed (Ogre::RenderWindow* rw)
- { orxonox::Game::getInstance().stop(); }
- void windowMoved (Ogre::RenderWindow* rw)
- { orxonox::WindowEventListener::moveWindow(); }
- };
-
- GraphicsManager* GraphicsManager::singletonPtr_s = 0;
-
- /**
- @brief
- Non-initialising constructor.
- */
- GraphicsManager::GraphicsManager(bool bLoadRenderer)
- : ogreWindowEventListener_(new OgreWindowEventListener())
-#if OGRE_VERSION < 0x010600
- , memoryArchiveFactory_(new MemoryArchiveFactory())
-#endif
- , renderWindow_(0)
- , viewport_(0)
- {
- RegisterObject(GraphicsManager);
-
- this->setConfigValues();
-
- // Ogre setup procedure (creating Ogre::Root)
- this->loadOgreRoot();
-
- // At first, add the root paths of the data directories as resource locations
- Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem");
- // Load resources
- resources_.reset(new XMLFile("DefaultResources.oxr"));
- resources_->setLuaSupport(false);
- Loader::open(resources_.get());
-
- // Only for development runs
- if (PathConfig::isDevelopmentRun())
- {
- Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem");
- extResources_.reset(new XMLFile("resources.oxr"));
- extResources_->setLuaSupport(false);
- Loader::open(extResources_.get());
- }
-
- if (bLoadRenderer)
- {
- // Reads the ogre config and creates the render window
- this->upgradeToGraphics();
- }
- }
-
- /**
- @brief
- Destruction is done by the member scoped_ptrs.
- */
- GraphicsManager::~GraphicsManager()
- {
- Loader::unload(debugOverlay_.get());
-
- Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
- ModifyConsoleCommand(__CC_printScreen_name).resetFunction();
-
- // Undeclare the resources
- Loader::unload(resources_.get());
- if (PathConfig::isDevelopmentRun())
- Loader::unload(extResources_.get());
- }
-
- void GraphicsManager::setConfigValues()
- {
- SetConfigValue(ogreConfigFile_, "ogre.cfg")
- .description("Location of the Ogre config file");
- SetConfigValue(ogrePluginsDirectory_, specialConfig::ogrePluginsDirectory)
- .description("Folder where the Ogre plugins are located.");
- SetConfigValue(ogrePlugins_, specialConfig::ogrePlugins)
- .description("Comma separated list of all plugins to load.");
- SetConfigValue(ogreLogFile_, "ogre.log")
- .description("Logfile for messages from Ogre. Use \"\" to suppress log file creation.");
- SetConfigValue(ogreLogLevelTrivial_ , 5)
- .description("Corresponding orxonox debug level for ogre Trivial");
- SetConfigValue(ogreLogLevelNormal_ , 4)
- .description("Corresponding orxonox debug level for ogre Normal");
- SetConfigValue(ogreLogLevelCritical_, 2)
- .description("Corresponding orxonox debug level for ogre Critical");
- }
-
- /**
- @brief
- Loads the renderer and creates the render window if not yet done so.
- @remarks
- This operation is irreversible without recreating the GraphicsManager!
- So if it throws you HAVE to recreate the GraphicsManager!!!
- It therefore offers almost no exception safety.
- */
- void GraphicsManager::upgradeToGraphics()
- {
- if (renderWindow_ != NULL)
- return;
-
- // load all the required plugins for Ogre
- this->loadOgrePlugins();
-
- this->loadRenderer();
-
-#if OGRE_VERSION < 0x010600
- // WORKAROUND: There is an incompatibility for particle scripts when trying
- // to support both Ogre 1.4 and 1.6. The hacky solution is to create
- // scripts for the 1.6 version and then remove the inserted "particle_system"
- // keyword. But we need to supply these new scripts as well, which is why
- // there is an extra Ogre::Archive dealing with it in the memory.
- using namespace Ogre;
- ArchiveManager::getSingleton().addArchiveFactory(memoryArchiveFactory_.get());
- const StringVector& groups = ResourceGroupManager::getSingleton().getResourceGroups();
- // Travers all groups
- for (StringVector::const_iterator itGroup = groups.begin(); itGroup != groups.end(); ++itGroup)
- {
- FileInfoListPtr files = ResourceGroupManager::getSingleton().findResourceFileInfo(*itGroup, "*.particle");
- for (FileInfoList::const_iterator itFile = files->begin(); itFile != files->end(); ++itFile)
- {
- // open file
- Ogre::DataStreamPtr input = ResourceGroupManager::getSingleton().openResource(itFile->filename, *itGroup, false);
- std::stringstream output;
- // Parse file and replace "particle_system" with nothing
- while (!input->eof())
- {
- std::string line = input->getLine();
- size_t pos = line.find("particle_system");
- if (pos != std::string::npos)
- {
- // 15 is the length of "particle_system"
- line.replace(pos, 15, "");
- }
- output << line << std::endl;
- }
- // Add file to the memory archive
- shared_array<char> data(new char[output.str().size()]);
- // Debug optimisations
- const std::string& outputStr = output.str();
- char* rawData = data.get();
- for (unsigned i = 0; i < outputStr.size(); ++i)
- rawData[i] = outputStr[i];
- MemoryArchive::addFile("particle_scripts_ogre_1.4_" + *itGroup, itFile->filename, data, output.str().size());
- }
- if (!files->empty())
- {
- // Declare the files, but using a new group
- ResourceGroupManager::getSingleton().addResourceLocation("particle_scripts_ogre_1.4_" + *itGroup,
- "Memory", "particle_scripts_ogre_1.4_" + *itGroup);
- }
- }
-#endif
-
- // Initialise all resources (do this AFTER the renderer has been loaded!)
- // Note: You can only do this once! Ogre will check whether a resource group has
- // already been initialised. If you need to load resources later, you will have to
- // choose another resource group.
- Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
- }
-
- /**
- @brief
- Creates the Ogre Root object and sets up the ogre log.
- */
- void GraphicsManager::loadOgreRoot()
- {
- COUT(3) << "Setting up Ogre..." << std::endl;
-
- if (ogreConfigFile_.empty())
- {
- COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
- ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
- }
- if (ogreLogFile_.empty())
- {
- COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
- ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
- }
-
- boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
- boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
-
- // create a new logManager
- // Ogre::Root will detect that we've already created a Log
- ogreLogger_.reset(new Ogre::LogManager());
- COUT(4) << "Ogre LogManager created" << std::endl;
-
- // create our own log that we can listen to
- Ogre::Log *myLog;
- myLog = ogreLogger_->createLog(ogreLogFilepath.string(), true, false, false);
- COUT(4) << "Ogre Log created" << std::endl;
-
- myLog->setLogDetail(Ogre::LL_BOREME);
- myLog->addListener(this);
-
- COUT(4) << "Creating Ogre Root..." << std::endl;
-
- // check for config file existence because Ogre displays (caught) exceptions if not
- if (!boost::filesystem::exists(ogreConfigFilepath))
- {
- // create a zero sized file
- std::ofstream creator;
- creator.open(ogreConfigFilepath.string().c_str());
- creator.close();
- }
-
- // Leave plugins file empty. We're going to do that part manually later
- ogreRoot_.reset(new Ogre::Root("", ogreConfigFilepath.string(), ogreLogFilepath.string()));
-
- COUT(3) << "Ogre set up done." << std::endl;
- }
-
- void GraphicsManager::loadOgrePlugins()
- {
- // just to make sure the next statement doesn't segfault
- if (ogrePluginsDirectory_.empty())
- ogrePluginsDirectory_ = '.';
-
- boost::filesystem::path folder(ogrePluginsDirectory_);
- // Do some SubString magic to get the comma separated list of plugins
- SubString plugins(ogrePlugins_, ",", " ", false, '\\', false, '"', false, '{', '}', false, '\0');
- // Use backslash paths on Windows! file_string() already does that though.
- for (unsigned int i = 0; i < plugins.size(); ++i)
- ogreRoot_->loadPlugin((folder / plugins[i]).file_string());
- }
-
- void GraphicsManager::loadRenderer()
- {
- CCOUT(4) << "Configuring Renderer" << std::endl;
-
- if (!ogreRoot_->restoreConfig() || Core::getInstance().getOgreConfigTimestamp() > Core::getInstance().getLastLevelTimestamp())
- {
- if (!ogreRoot_->showConfigDialog())
- ThrowException(InitialisationFailed, "OGRE graphics configuration dialogue canceled.");
- else
- Core::getInstance().updateOgreConfigTimestamp();
- }
-
- CCOUT(4) << "Creating render window" << std::endl;
-
- this->renderWindow_ = ogreRoot_->initialise(true, "Orxonox");
- // Propagate the size of the new winodw
- this->ogreWindowEventListener_->windowResized(renderWindow_);
-
- Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, ogreWindowEventListener_.get());
-
- // create a full screen default viewport
- // Note: This may throw when adding a viewport with an existing z-order!
- // But in our case we only have one viewport for now anyway, therefore
- // no ScopeGuards or anything to handle exceptions.
- this->viewport_ = this->renderWindow_->addViewport(0, 0);
-
- Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(Ogre::MIP_UNLIMITED);
-
- // add console commands
- ModifyConsoleCommand(__CC_printScreen_name).setFunction(&GraphicsManager::printScreen, this);
- }
-
- void GraphicsManager::loadDebugOverlay()
- {
- // Load debug overlay to show info about fps and tick time
- COUT(4) << "Loading Debug Overlay..." << std::endl;
- debugOverlay_.reset(new XMLFile("debug.oxo"));
- Loader::open(debugOverlay_.get());
- }
-
- /**
- @note
- A note about the Ogre::FrameListener: Even though we don't use them,
- they still get called. However, the delta times are not correct (except
- for timeSinceLastFrame, which is the most important). A little research
- as shown that there is probably only one FrameListener that doesn't even
- need the time. So we shouldn't run into problems.
- */
- void GraphicsManager::postUpdate(const Clock& time)
- {
- Ogre::FrameEvent evt;
- evt.timeSinceLastFrame = time.getDeltaTime();
- evt.timeSinceLastEvent = time.getDeltaTime(); // note: same time, but shouldn't matter anyway
-
- // don't forget to call _fireFrameStarted to OGRE to make sure
- // everything goes smoothly
- ogreRoot_->_fireFrameStarted(evt);
-
- // Pump messages in all registered RenderWindows
- // This calls the WindowEventListener objects.
- Ogre::WindowEventUtilities::messagePump();
- // make sure the window stays active even when not focused
- // (probably only necessary on windows)
- this->renderWindow_->setActive(true);
-
- // Time before rendering
- uint64_t timeBeforeTick = time.getRealMicroseconds();
-
- // Render frame
- ogreRoot_->_updateAllRenderTargets();
-
- uint64_t timeAfterTick = time.getRealMicroseconds();
- // Subtract the time used for rendering from the tick time counter
- Game::getInstance().subtractTickTime((int32_t)(timeAfterTick - timeBeforeTick));
-
- // again, just to be sure OGRE works fine
- ogreRoot_->_fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
- }
-
- void GraphicsManager::setCamera(Ogre::Camera* camera)
- {
- this->viewport_->setCamera(camera);
- }
-
- /**
- @brief
- Method called by the LogListener interface from Ogre.
- We use it to capture Ogre log messages and handle it ourselves.
- @param message
- The message to be logged
- @param lml
- The message level the log is using
- @param maskDebug
- If we are printing to the console or not
- @param logName
- The name of this log (so you can have several listeners
- for different logs, and identify them)
- */
- void GraphicsManager::messageLogged(const std::string& message,
- Ogre::LogMessageLevel lml, bool maskDebug, const std::string& logName)
- {
- int orxonoxLevel;
- std::string introduction;
- // Do not show caught OGRE exceptions in front
- if (message.find("EXCEPTION") != std::string::npos)
- {
- orxonoxLevel = OutputLevel::Debug;
- introduction = "Ogre, caught exception: ";
- }
- else
- {
- switch (lml)
- {
- case Ogre::LML_TRIVIAL:
- orxonoxLevel = this->ogreLogLevelTrivial_;
- break;
- case Ogre::LML_NORMAL:
- orxonoxLevel = this->ogreLogLevelNormal_;
- break;
- case Ogre::LML_CRITICAL:
- orxonoxLevel = this->ogreLogLevelCritical_;
- break;
- default:
- orxonoxLevel = 0;
- }
- introduction = "Ogre: ";
- }
- OutputHandler::getOutStream(orxonoxLevel)
- << introduction << message << std::endl;
- }
-
- size_t GraphicsManager::getRenderWindowHandle()
- {
- size_t windowHnd = 0;
- renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
- return windowHnd;
- }
-
- bool GraphicsManager::isFullScreen() const
- {
- Ogre::ConfigOptionMap& options = ogreRoot_->getRenderSystem()->getConfigOptions();
- if (options.find("Full Screen") != options.end())
- {
- if (options["Full Screen"].currentValue == "Yes")
- return true;
- else
- return false;
- }
- else
- {
- COUT(0) << "Could not find 'Full Screen' render system option. Fix This!!!" << std::endl;
- return false;
- }
- }
-
- void GraphicsManager::printScreen()
- {
- assert(this->renderWindow_);
- this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".png");
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/GraphicsManager.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/GraphicsManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/GraphicsManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,126 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
- * Co-authors:
- * Felix Schulthess
- *
- */
-
-/**
- @defgroup Graphics Graphics and GUI
- @ingroup Core
-*/
-
-/**
- at file
- at ingroup Graphics
- at brief
- Declaration of GraphicsManager Singleton.
- */
-
-#ifndef _GraphicsManager_H__
-#define _GraphicsManager_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-#include <string>
-#include <OgreLog.h>
-#include <boost/scoped_ptr.hpp>
-#include <boost/shared_ptr.hpp>
-
-#include "util/Singleton.h"
-#include "OrxonoxClass.h"
-
-namespace orxonox
-{
- /**
- @brief
- Graphics engine manager class
- */
- class _CoreExport GraphicsManager : public Singleton<GraphicsManager>, public OrxonoxClass, public Ogre::LogListener
- {
- friend class Singleton<GraphicsManager>;
- public:
- GraphicsManager(bool bLoadRenderer = true);
- ~GraphicsManager();
-
- void setConfigValues();
-
- void postUpdate(const Clock& time);
-
- Ogre::Viewport* getViewport() { return this->viewport_; }
- Ogre::RenderWindow* getRenderWindow() { return this->renderWindow_; }
- size_t getRenderWindowHandle();
- bool isFullScreen() const;
-
- void upgradeToGraphics();
- void loadDebugOverlay();
- bool rendererLoaded() const { return renderWindow_ != NULL; }
-
- void setCamera(Ogre::Camera* camera);
-
- private:
- GraphicsManager(GraphicsManager&); // don't mess with singletons
-
- // OGRE initialisation
- void loadOgreRoot();
- void loadOgrePlugins();
- void loadRenderer();
-
- // event from Ogre::LogListener
- void messageLogged(const std::string& message, Ogre::LogMessageLevel lml,
- bool maskDebug, const std::string& logName);
-
- // console commands
- void printScreen();
-
- scoped_ptr<OgreWindowEventListener> ogreWindowEventListener_; //!< Pimpl to hide OgreWindowUtilities.h
-#if OGRE_VERSION < 0x010600
- scoped_ptr<MemoryArchiveFactory> memoryArchiveFactory_; //!< Stores the modified particle scripts
-#endif
- scoped_ptr<Ogre::LogManager> ogreLogger_;
- scoped_ptr<Ogre::Root> ogreRoot_; //!< Ogre's root
- Ogre::RenderWindow* renderWindow_; //!< the one and only render window
- Ogre::Viewport* viewport_; //!< default full size viewport
-
- // XML files for the resources and the debug overlay
- shared_ptr<XMLFile> resources_; //!< XML with resource locations
- shared_ptr<XMLFile> extResources_; //!< XML with resource locations in the external path (only for dev runs)
- shared_ptr<XMLFile> debugOverlay_; //!< XML with various debug overlays
-
- // config values
- std::string ogreConfigFile_; //!< ogre config filename
- std::string ogrePluginsDirectory_; //!< Directory where the Ogre plugins are located
- std::string ogrePlugins_; //!< Comma separated list of all plugins to load
- std::string ogreLogFile_; //!< log filename for Ogre log messages
- int ogreLogLevelTrivial_; //!< Corresponding Orxonox debug level for LL_TRIVIAL
- int ogreLogLevelNormal_; //!< Corresponding Orxonox debug level for LL_NORMAL
- int ogreLogLevelCritical_; //!< Corresponding Orxonox debug level for LL_CRITICAL
-
- static GraphicsManager* singletonPtr_s; //!< Pointer to the Singleton
- };
-}
-
-#endif /* _GraphicsManager_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Identifier.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Identifier.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Identifier.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,507 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the Identifier class.
-*/
-
-#include "Identifier.h"
-
-#include <ostream>
-
-#include "util/StringUtils.h"
-#include "ConfigValueContainer.h"
-#include "ClassFactory.h"
-#include "XMLPort.h"
-
-namespace orxonox
-{
- // ###############################
- // ### Identifier ###
- // ###############################
- int Identifier::hierarchyCreatingCounter_s = 0;
- unsigned int Identifier::classIDCounter_s = 0;
-
- /**
- @brief Constructor: No factory, no object created, new ObjectList and a unique networkID.
- */
- Identifier::Identifier()
- : classID_(classIDCounter_s++)
- {
- this->objects_ = new ObjectListBase(this);
-
- this->bCreatedOneObject_ = false;
- this->bSetName_ = false;
- this->factory_ = 0;
- this->bLoadable_ = false;
-
- this->bHasConfigValues_ = false;
-
- // Default network ID is the class ID
- this->networkID_ = this->classID_;
- }
-
- /**
- @brief Destructor: Deletes the list containing the children.
- */
- Identifier::~Identifier()
- {
- delete this->objects_;
-
- if (this->factory_)
- delete this->factory_;
-
- for (std::map<std::string, ConfigValueContainer*>::iterator it = this->configValues_.begin(); it != this->configValues_.end(); ++it)
- delete (it->second);
- for (std::map<std::string, XMLPortParamContainer*>::iterator it = this->xmlportParamContainers_.begin(); it != this->xmlportParamContainers_.end(); ++it)
- delete (it->second);
- for (std::map<std::string, XMLPortObjectContainer*>::iterator it = this->xmlportObjectContainers_.begin(); it != this->xmlportObjectContainers_.end(); ++it)
- delete (it->second);
- }
-
- /**
- @brief Returns the identifier map with the names as received by typeid(). This is only used internally.
- */
- std::map<std::string, Identifier*>& Identifier::getTypeIDIdentifierMap()
- {
- static std::map<std::string, Identifier*> identifiers; //!< The map to store all Identifiers.
- return identifiers;
- }
-
- /**
- @brief Returns an identifier by name and adds it if not available
- @param name The name of the identifier as typeid().name() suggests
- @param proposal A pointer to a newly created identifier for the case of non existance in the map
- @return The identifier (unique instance)
- */
- Identifier* Identifier::getIdentifierSingleton(const std::string& name, Identifier* proposal)
- {
- std::map<std::string, Identifier*>::const_iterator it = getTypeIDIdentifierMap().find(name);
-
- if (it != getTypeIDIdentifierMap().end())
- {
- // There is already an entry: return it and delete the proposal
- delete proposal;
- return it->second;
- }
- else
- {
- // There is no entry: put the proposal into the map and return it
- getTypeIDIdentifierMap()[name] = proposal;
- return proposal;
- }
- }
-
- /**
- @brief Registers a class, which means that the name and the parents get stored.
- @param parents A list, containing the Identifiers of all parents of the class
- @param bRootClass True if the class is either an Interface or the BaseObject itself
- */
- void Identifier::initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass)
- {
- // Check if at least one object of the given type was created
- if (!this->bCreatedOneObject_ && Identifier::isCreatingHierarchy())
- {
- // If no: We have to store the information and initialize the Identifier
- COUT(4) << "*** ClassIdentifier: Register Class in " << this->getName() << "-Singleton -> Initialize Singleton." << std::endl;
- if (bRootClass)
- this->initialize(0); // If a class is derived from two interfaces, the second interface might think it's derived from the first because of the order of constructor-calls. Thats why we set parents to zero in that case.
- else
- this->initialize(parents);
- }
- }
-
- /**
- @brief Initializes the Identifier with a list containing all parents of the class the Identifier belongs to.
- @param parents A list containing all parents
- */
- void Identifier::initialize(std::set<const Identifier*>* parents)
- {
- COUT(4) << "*** Identifier: Initialize " << this->name_ << "-Singleton." << std::endl;
- this->bCreatedOneObject_ = true;
-
- if (parents)
- {
- this->parents_ = (*parents);
- this->directParents_ = (*parents);
-
- // Iterate through all parents
- for (std::set<const Identifier*>::iterator it = parents->begin(); it != parents->end(); ++it)
- {
- // Tell the parent we're one of it's children
- (*it)->children_.insert((*it)->children_.end(), this);
-
- // Erase all parents of our parent from our direct-parent-list
- for (std::set<const Identifier*>::const_iterator it1 = (*it)->getParents().begin(); it1 != (*it)->getParents().end(); ++it1)
- {
- // Search for the parent's parent in our direct-parent-list
- for (std::set<const Identifier*>::iterator it2 = this->directParents_.begin(); it2 != this->directParents_.end(); ++it2)
- {
- if ((*it1) == (*it2))
- {
- // We've found a non-direct parent in our list: Erase it
- this->directParents_.erase(it2);
- break;
- }
- }
- }
- }
-
- // Now iterate through all direct parents
- for (std::set<const Identifier*>::iterator it = this->directParents_.begin(); it != this->directParents_.end(); ++it)
- {
- // Tell the parent we're one of it's direct children
- (*it)->directChildren_.insert((*it)->directChildren_.end(), this);
-
- // Create the super-function dependencies
- (*it)->createSuperFunctionCaller();
- }
- }
- }
-
- /**
- @brief Creates the class-hierarchy by creating and destroying one object of each type.
- */
- void Identifier::createClassHierarchy()
- {
- COUT(3) << "*** Identifier: Create class-hierarchy" << std::endl;
- Identifier::startCreatingHierarchy();
- for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMap().begin(); it != Identifier::getStringIdentifierMap().end(); ++it)
- {
- // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
- if (it->second->hasFactory())
- {
- BaseObject* temp = it->second->fabricate(0);
- temp->destroy();
- }
- }
- Identifier::stopCreatingHierarchy();
- COUT(3) << "*** Identifier: Finished class-hierarchy creation" << std::endl;
- }
-
- /**
- @brief Destroys all Identifiers. Called when exiting the program.
- */
- void Identifier::destroyAllIdentifiers()
- {
- for (std::map<std::string, Identifier*>::iterator it = Identifier::getTypeIDIdentifierMap().begin(); it != Identifier::getTypeIDIdentifierMap().end(); ++it)
- delete (it->second);
- }
-
- /**
- @brief Sets the name of the class.
- */
- void Identifier::setName(const std::string& name)
- {
- if (!this->bSetName_)
- {
- this->name_ = name;
- this->bSetName_ = true;
- Identifier::getStringIdentifierMapIntern()[name] = this;
- Identifier::getLowercaseStringIdentifierMapIntern()[getLowercase(name)] = this;
- Identifier::getIDIdentifierMapIntern()[this->networkID_] = this;
- }
- }
-
- /**
- @brief Creates an object of the type the Identifier belongs to.
- @return The new object
- */
- BaseObject* Identifier::fabricate(BaseObject* creator)
- {
- if (this->factory_)
- {
- return this->factory_->fabricate(creator); // We have to return a BaseObject, because we don't know the exact type.
- }
- else
- {
- COUT(1) << "An error occurred in Identifier.cc:" << std::endl;
- COUT(1) << "Error: Cannot fabricate an object of type '" << this->name_ << "'. Class has no factory." << std::endl;
- COUT(1) << "Aborting..." << std::endl;
- abort();
- return 0;
- }
- }
-
- /**
- @brief Sets the network ID to a new value and changes the entry in the ID-Identifier-map.
- */
- void Identifier::setNetworkID(uint32_t id)
- {
-// Identifier::getIDIdentifierMapIntern().erase(this->networkID_);
- Identifier::getIDIdentifierMapIntern()[id] = this;
- this->networkID_ = id;
- }
-
- /**
- @brief Returns true, if the Identifier is at least of the given type.
- @param identifier The identifier to compare with
- */
- bool Identifier::isA(const Identifier* identifier) const
- {
- return (identifier == this || (this->parents_.find(identifier) != this->parents_.end()));
- }
-
- /**
- @brief Returns true, if the Identifier is exactly of the given type.
- @param identifier The identifier to compare with
- */
- bool Identifier::isExactlyA(const Identifier* identifier) const
- {
- return (identifier == this);
- }
-
- /**
- @brief Returns true, if the assigned identifier is a child of the given identifier.
- @param identifier The identifier to compare with
- */
- bool Identifier::isChildOf(const Identifier* identifier) const
- {
- return (this->parents_.find(identifier) != this->parents_.end());
- }
-
- /**
- @brief Returns true, if the assigned identifier is a direct child of the given identifier.
- @param identifier The identifier to compare with
- */
- bool Identifier::isDirectChildOf(const Identifier* identifier) const
- {
- return (this->directParents_.find(identifier) != this->directParents_.end());
- }
-
- /**
- @brief Returns true, if the assigned identifier is a parent of the given identifier.
- @param identifier The identifier to compare with
- */
- bool Identifier::isParentOf(const Identifier* identifier) const
- {
- return (this->children_.find(identifier) != this->children_.end());
- }
-
- /**
- @brief Returns true, if the assigned identifier is a direct parent of the given identifier.
- @param identifier The identifier to compare with
- */
- bool Identifier::isDirectParentOf(const Identifier* identifier) const
- {
- return (this->directChildren_.find(identifier) != this->directChildren_.end());
- }
-
- /**
- @brief Returns the map that stores all Identifiers with their names.
- @return The map
- */
- std::map<std::string, Identifier*>& Identifier::getStringIdentifierMapIntern()
- {
- static std::map<std::string, Identifier*> identifierMap;
- return identifierMap;
- }
-
- /**
- @brief Returns the map that stores all Identifiers with their names in lowercase.
- @return The map
- */
- std::map<std::string, Identifier*>& Identifier::getLowercaseStringIdentifierMapIntern()
- {
- static std::map<std::string, Identifier*> lowercaseIdentifierMap;
- return lowercaseIdentifierMap;
- }
-
- /**
- @brief Returns the map that stores all Identifiers with their network IDs.
- @return The map
- */
- std::map<uint32_t, Identifier*>& Identifier::getIDIdentifierMapIntern()
- {
- static std::map<uint32_t, Identifier*> identifierMap;
- return identifierMap;
- }
-
- /**
- @brief Returns the Identifier with a given name.
- @param name The name of the wanted Identifier
- @return The Identifier
- */
- Identifier* Identifier::getIdentifierByString(const std::string& name)
- {
- std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapIntern().find(name);
- if (it != Identifier::getStringIdentifierMapIntern().end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Returns the Identifier with a given name in lowercase.
- @param name The name of the wanted Identifier
- @return The Identifier
- */
- Identifier* Identifier::getIdentifierByLowercaseString(const std::string& name)
- {
- std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapIntern().find(name);
- if (it != Identifier::getLowercaseStringIdentifierMapIntern().end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Returns the Identifier with a given network ID.
- @param id The network ID of the wanted Identifier
- @return The Identifier
- */
- Identifier* Identifier::getIdentifierByID(const uint32_t id)
- {
- std::map<uint32_t, Identifier*>::const_iterator it = Identifier::getIDIdentifierMapIntern().find(id);
- if (it != Identifier::getIDIdentifierMapIntern().end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Cleans the NetworkID map (needed on clients for correct initialization)
- */
- void Identifier::clearNetworkIDs()
- {
- Identifier::getIDIdentifierMapIntern().clear();
- }
-
- /**
- @brief Adds the ConfigValueContainer of a variable, given by the string of its name.
- @param varname The name of the variablee
- @param container The container
- */
- void Identifier::addConfigValueContainer(const std::string& varname, ConfigValueContainer* container)
- {
- std::map<std::string, ConfigValueContainer*>::const_iterator it = this->configValues_.find(varname);
- if (it != this->configValues_.end())
- {
- COUT(2) << "Warning: Overwriting config-value with name " << varname << " in class " << this->getName() << '.' << std::endl;
- delete (it->second);
- }
-
- this->bHasConfigValues_ = true;
- this->configValues_[varname] = container;
- }
-
- /**
- @brief Returns the ConfigValueContainer of a variable, given by the string of its name.
- @param varname The name of the variable
- @return The ConfigValueContainer
- */
- ConfigValueContainer* Identifier::getConfigValueContainer(const std::string& varname)
- {
- std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_.find(varname);
- if (it != configValues_.end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Returns a XMLPortParamContainer that loads a parameter of this class.
- @param paramname The name of the parameter
- @return The container
- */
- XMLPortParamContainer* Identifier::getXMLPortParamContainer(const std::string& paramname)
- {
- std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
- if (it != this->xmlportParamContainers_.end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Adds a new XMLPortParamContainer that loads a parameter of this class.
- @param paramname The name of the parameter
- @param container The container
- */
- void Identifier::addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container)
- {
- std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
- if (it != this->xmlportParamContainers_.end())
- {
- COUT(2) << "Warning: Overwriting XMLPortParamContainer in class " << this->getName() << '.' << std::endl;
- delete (it->second);
- }
-
- this->xmlportParamContainers_[paramname] = container;
- }
-
- /**
- @brief Returns a XMLPortObjectContainer that attaches an object to this class.
- @param sectionname The name of the section that contains the attachable objects
- @return The container
- */
- XMLPortObjectContainer* Identifier::getXMLPortObjectContainer(const std::string& sectionname)
- {
- std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
- if (it != this->xmlportObjectContainers_.end())
- return it->second;
- else
- return 0;
- }
-
- /**
- @brief Adds a new XMLPortObjectContainer that attaches an object to this class.
- @param sectionname The name of the section that contains the attachable objects
- @param container The container
- */
- void Identifier::addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container)
- {
- std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
- if (it != this->xmlportObjectContainers_.end())
- {
- COUT(2) << "Warning: Overwriting XMLPortObjectContainer in class " << this->getName() << '.' << std::endl;
- delete (it->second);
- }
-
- this->xmlportObjectContainers_[sectionname] = container;
- }
-
- /**
- @brief Lists the names of all Identifiers in a std::set<const Identifier*>.
- @param out The outstream
- @param list The list (or set) of Identifiers
- @return The outstream
- */
- std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list)
- {
- for (std::set<const Identifier*>::const_iterator it = list.begin(); it != list.end(); ++it)
- {
- if (it != list.begin())
- out << ' ';
- out << (*it)->getName();
- }
-
- return out;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Identifier.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Identifier.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Identifier.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,502 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Identifier Identifier
- @ingroup Class
-*/
-
-/**
- @file
- @ingroup Class Identifier
- @brief Declaration of Identifier, definition of ClassIdentifier<T>; used to identify the class of an object.
-
- @anchor IdentifierExample
-
- An Identifier "identifies" the class of an object. It contains different information about
- the class: Its name and ID, a list of all instances of this class, a factory to create new
- instances of this class, and more.
-
- It also contains information about the inheritance of this class: It stores a list of the
- Identifiers of all parent-classes as well as a list of all child-classes. These relationships
- can be tested using functions like @c isA(), @c isChildOf(), @c isParentOf(), and more.
-
- Every Identifier is in fact a ClassIdentifier<T> (where T is the class that is identified
- by the Identifier), Identifier is just the common base-class.
-
- Example:
- @code
- MyClass* object = new MyClass(); // create an instance of MyClass
-
- object->getIdentifier()->getName(); // returns "MyClass"
-
- BaseObject* other = object->getIdentifier()->fabricate(0); // fabricates a new instance of MyClass
-
-
- // iterate through all objects of type MyClass:
- ObjectListBase* objects = object->getIdentifier()->getObjects(); // get a pointer to the object-list
- int count;
- for (Iterator<BaseObject> it = objects.begin(); it != objects.end(); ++it) // iterate through the objects
- ++count;
- COUT(0) << count << std::endl; // prints "2" because we created 2 instances of MyClass so far
-
-
- // test the class hierarchy
- object->getIdentifier()->isA(Class(MyClass)); // returns true
- object->isA(Class(MyClass)); // returns true (short version)
-
- object->isA(Class(BaseClass)); // returns true if MyClass is a child of BaseClass
-
- Class(ChildClass)->isChildOf(object->getIdentifier()); // returns true if ChildClass is a child of MyClass
- @endcode
-*/
-
-#ifndef _Identifier_H__
-#define _Identifier_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-#include <map>
-#include <set>
-#include <string>
-#include <typeinfo>
-#include <loki/TypeTraits.h>
-
-#include "util/Debug.h"
-#include "MetaObjectList.h"
-#include "ObjectList.h"
-#include "ObjectListBase.h"
-#include "Super.h"
-
-namespace orxonox
-{
- // ###############################
- // ### Identifier ###
- // ###############################
- /**
- @brief The Identifier is used to identify the class of an object and to store information about the class.
-
- Each Identifier stores information about one class. The Identifier can then be used to identify
- this class. On the other hand it's also possible to get the corresponding Identifier of a class,
- for example by using the macro Class().
-
- @see See @ref IdentifierExample "Identifier.h" for more information and some examples.
-
- @note You can't directly create an Identifier, it's just the base-class of ClassIdentifier<T>.
- */
- class _CoreExport Identifier
- {
- public:
- /// Returns the name of the class the Identifier belongs to.
- inline const std::string& getName() const { return this->name_; }
- void setName(const std::string& name);
-
- /// Returns the network ID to identify a class through the network.
- inline const uint32_t getNetworkID() const { return this->networkID_; }
- void setNetworkID(uint32_t id);
-
- /// Returns the unique ID of the class.
- FORCEINLINE unsigned int getClassID() const { return this->classID_; }
-
- /// Returns the list of all existing objects of this class.
- inline ObjectListBase* getObjects() const { return this->objects_; }
-
- /// Sets the Factory.
- inline void addFactory(Factory* factory) { this->factory_ = factory; }
- /// Returns true if the Identifier has a Factory.
- inline bool hasFactory() const { return (this->factory_ != 0); }
-
- BaseObject* fabricate(BaseObject* creator);
-
- /// Returns true if the class can be loaded through XML.
- inline bool isLoadable() const { return this->bLoadable_; }
- /// Set the class to be loadable through XML or not.
- inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
-
- bool isA(const Identifier* identifier) const;
- bool isExactlyA(const Identifier* identifier) const;
- bool isChildOf(const Identifier* identifier) const;
- bool isDirectChildOf(const Identifier* identifier) const;
- bool isParentOf(const Identifier* identifier) const;
- bool isDirectParentOf(const Identifier* identifier) const;
-
-
- /////////////////////////////
- ////// Class Hierarchy //////
- /////////////////////////////
- static void createClassHierarchy();
-
- /// Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents.
- inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
-
- /// Returns the parents of the class the Identifier belongs to.
- inline const std::set<const Identifier*>& getParents() const { return this->parents_; }
- /// Returns the begin-iterator of the parents-list.
- inline std::set<const Identifier*>::const_iterator getParentsBegin() const { return this->parents_.begin(); }
- /// Returns the end-iterator of the parents-list.
- inline std::set<const Identifier*>::const_iterator getParentsEnd() const { return this->parents_.end(); }
-
- /// Returns the children of the class the Identifier belongs to.
- inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
- /// Returns the begin-iterator of the children-list.
- inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
- /// Returns the end-iterator of the children-list.
- inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
-
- /// Returns the direct parents of the class the Identifier belongs to.
- inline const std::set<const Identifier*>& getDirectParents() const { return this->directParents_; }
- /// Returns the begin-iterator of the direct-parents-list.
- inline std::set<const Identifier*>::const_iterator getDirectParentsBegin() const { return this->directParents_.begin(); }
- /// Returns the end-iterator of the direct-parents-list.
- inline std::set<const Identifier*>::const_iterator getDirectParentsEnd() const { return this->directParents_.end(); }
-
- /// Returns the direct children the class the Identifier belongs to.
- inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
- /// Returns the begin-iterator of the direct-children-list.
- inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
- /// Returns the end-iterator of the direct-children-list.
- inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_.end(); }
-
-
- //////////////////////////
- ///// Identifier Map /////
- //////////////////////////
- static void destroyAllIdentifiers();
-
- static Identifier* getIdentifierByString(const std::string& name);
- static Identifier* getIdentifierByLowercaseString(const std::string& name);
- static Identifier* getIdentifierByID(uint32_t id);
-
- static void clearNetworkIDs();
-
- /// Returns the map that stores all Identifiers with their names.
- static inline const std::map<std::string, Identifier*>& getStringIdentifierMap() { return Identifier::getStringIdentifierMapIntern(); }
- /// Returns a const_iterator to the beginning of the map that stores all Identifiers with their names.
- static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapBegin() { return Identifier::getStringIdentifierMap().begin(); }
- /// Returns a const_iterator to the end of the map that stores all Identifiers with their names.
- static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapEnd() { return Identifier::getStringIdentifierMap().end(); }
-
- /// Returns the map that stores all Identifiers with their names in lowercase.
- static inline const std::map<std::string, Identifier*>& getLowercaseStringIdentifierMap() { return Identifier::getLowercaseStringIdentifierMapIntern(); }
- /// Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase.
- static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapBegin() { return Identifier::getLowercaseStringIdentifierMap().begin(); }
- /// Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase.
- static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapEnd() { return Identifier::getLowercaseStringIdentifierMap().end(); }
-
- /// Returns the map that stores all Identifiers with their IDs.
- static inline const std::map<uint32_t, Identifier*>& getIDIdentifierMap() { return Identifier::getIDIdentifierMapIntern(); }
- /// Returns a const_iterator to the beginning of the map that stores all Identifiers with their IDs.
- static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapBegin() { return Identifier::getIDIdentifierMap().begin(); }
- /// Returns a const_iterator to the end of the map that stores all Identifiers with their IDs.
- static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapEnd() { return Identifier::getIDIdentifierMap().end(); }
-
-
- /////////////////////////
- ///// Config Values /////
- /////////////////////////
- virtual void updateConfigValues(bool updateChildren = true) const = 0;
-
- /// Returns true if this class has at least one config value.
- inline bool hasConfigValues() const { return this->bHasConfigValues_; }
-
- void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
- ConfigValueContainer* getConfigValueContainer(const std::string& varname);
-
-
- ///////////////////
- ///// XMLPort /////
- ///////////////////
- /// Returns the map that stores all XMLPort params.
- inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
- /// Returns a const_iterator to the beginning of the map that stores all XMLPort params.
- inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapBegin() const { return this->xmlportParamContainers_.begin(); }
- /// Returns a const_iterator to the end of the map that stores all XMLPort params.
- inline std::map<std::string, XMLPortParamContainer*>::const_iterator getXMLPortParamMapEnd() const { return this->xmlportParamContainers_.end(); }
-
- /// Returns the map that stores all XMLPort objects.
- inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortObjectMap() const { return this->xmlportObjectContainers_; }
- /// Returns a const_iterator to the beginning of the map that stores all XMLPort objects.
- inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapBegin() const { return this->xmlportObjectContainers_.begin(); }
- /// Returns a const_iterator to the end of the map that stores all XMLPort objects.
- inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
-
- void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
- XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
-
- void addXMLPortObjectContainer(const std::string& sectionname, XMLPortObjectContainer* container);
- XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
-
-
- protected:
- Identifier();
- Identifier(const Identifier& identifier); // don't copy
- virtual ~Identifier();
-
- static Identifier* getIdentifierSingleton(const std::string& name, Identifier* proposal);
- virtual void createSuperFunctionCaller() const = 0;
-
- void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
-
- /// Returns the map that stores all Identifiers with their names.
- static std::map<std::string, Identifier*>& getStringIdentifierMapIntern();
- /// Returns the map that stores all Identifiers with their names in lowercase.
- static std::map<std::string, Identifier*>& getLowercaseStringIdentifierMapIntern();
- /// Returns the map that stores all Identifiers with their network IDs.
- static std::map<uint32_t, Identifier*>& getIDIdentifierMapIntern();
-
- /// Returns the children of the class the Identifier belongs to.
- inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
- /// Returns the direct children of the class the Identifier belongs to.
- inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
-
- ObjectListBase* objects_; //!< The list of all objects of this class
-
- private:
- /// Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents.
- inline static void startCreatingHierarchy() { hierarchyCreatingCounter_s++; }
- /// Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents.
- inline static void stopCreatingHierarchy() { hierarchyCreatingCounter_s--; }
-
- static std::map<std::string, Identifier*>& getTypeIDIdentifierMap();
-
- void initialize(std::set<const Identifier*>* parents);
-
- std::set<const Identifier*> parents_; //!< The parents of the class the Identifier belongs to
- mutable std::set<const Identifier*> children_; //!< The children of the class the Identifier belongs to
-
- std::set<const Identifier*> directParents_; //!< The direct parents of the class the Identifier belongs to
- mutable std::set<const Identifier*> directChildren_; //!< The direct children of the class the Identifier belongs to
-
- bool bCreatedOneObject_; //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
- bool bSetName_; //!< True if the name is set
- bool bLoadable_; //!< False = it's not permitted to load the object through XML
- std::string name_; //!< The name of the class the Identifier belongs to
- Factory* factory_; //!< The Factory, able to create new objects of the given class (if available)
- static int hierarchyCreatingCounter_s; //!< Bigger than zero if at least one Identifier stores its parents (its an int instead of a bool to avoid conflicts with multithreading)
- uint32_t networkID_; //!< The network ID to identify a class through the network
- const unsigned int classID_; //!< Uniquely identifies a class (might not be the same as the networkID_)
- static unsigned int classIDCounter_s; //!< Static counter for the unique classIDs
-
- bool bHasConfigValues_; //!< True if this class has at least one assigned config value
- std::map<std::string, ConfigValueContainer*> configValues_; //!< A map to link the string of configurable variables with their ConfigValueContainer
-
- std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_; //!< All loadable parameters
- std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_; //!< All attachable objects
- };
-
- _CoreExport std::ostream& operator<<(std::ostream& out, const std::set<const Identifier*>& list);
-
-
- // ###############################
- // ### ClassIdentifier ###
- // ###############################
- /**
- @brief The ClassIdentifier is derived from Identifier and holds all class-specific functions and variables the Identifier cannot have.
-
- ClassIdentifier is a Singleton, which means that only one ClassIdentifier for a given type T exists.
- This makes it possible to store information about a class, sharing them with all
- objects of that class without defining static variables in every class.
-
- To be really sure that not more than exactly one object exists (even with libraries),
- ClassIdentifiers are stored in a static map in Identifier.
- */
- template <class T>
- class ClassIdentifier : public Identifier
- {
- #ifndef DOXYGEN_SHOULD_SKIP_THIS
- #define SUPER_INTRUSIVE_DECLARATION_INCLUDE
- #include "Super.h"
- #endif
-
- public:
- static ClassIdentifier<T>* getIdentifier();
- static ClassIdentifier<T>* getIdentifier(const std::string& name);
-
- bool initialiseObject(T* object, const std::string& className, bool bRootClass);
-
- void updateConfigValues(bool updateChildren = true) const;
-
- private:
- static void initialiseIdentifier();
- ClassIdentifier(const ClassIdentifier<T>& identifier) {} // don't copy
- ClassIdentifier()
- {
- SuperFunctionInitialization<0, T>::initialize(this);
- }
- ~ClassIdentifier()
- {
- SuperFunctionDestruction<0, T>::destroy(this);
- }
-
- static ClassIdentifier<T>* classIdentifier_s;
- };
-
- template <class T>
- ClassIdentifier<T>* ClassIdentifier<T>::classIdentifier_s = 0;
-
- /**
- @brief Returns the only instance of this class.
- @return The unique Identifier
- */
- template <class T>
- inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
- {
- // check if the Identifier already exists
- if (!ClassIdentifier<T>::classIdentifier_s)
- ClassIdentifier<T>::initialiseIdentifier();
-
- return ClassIdentifier<T>::classIdentifier_s;
- }
-
- /**
- @brief Does the same as getIdentifier() but sets the name if this wasn't done yet.
- @param name The name of this Identifier
- @return The Identifier
- */
- template <class T>
- inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier(const std::string& name)
- {
- ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
- identifier->setName(name);
- return identifier;
- }
-
- /**
- @brief Assigns the static field for the identifier singleton.
- */
- template <class T>
- void ClassIdentifier<T>::initialiseIdentifier()
- {
- // Get the name of the class
- const std::string& name = typeid(T).name();
-
- // create a new identifier anyway. Will be deleted in Identifier::getIdentifier if not used.
- ClassIdentifier<T>* proposal = new ClassIdentifier<T>();
-
- // Get the entry from the map
- ClassIdentifier<T>::classIdentifier_s = (ClassIdentifier<T>*)Identifier::getIdentifierSingleton(name, proposal);
-
- if (ClassIdentifier<T>::classIdentifier_s == proposal)
- {
- COUT(4) << "*** Identifier: Requested Identifier for " << name << " was not yet existing and got created." << std::endl;
- }
- else
- {
- COUT(4) << "*** Identifier: Requested Identifier for " << name << " was already existing and got assigned." << std::endl;
- }
- }
-
- /**
- @brief Adds an object of the given type to the ObjectList.
- @param object The object to add
- @param className The name of the class T
- @param bRootClass True if this is a root class (i.e. it inherits directly from OrxonoxClass)
- */
- template <class T>
- bool ClassIdentifier<T>::initialiseObject(T* object, const std::string& className, bool bRootClass)
- {
- if (bRootClass)
- COUT(5) << "*** Register Root-Object: " << className << std::endl;
- else
- COUT(5) << "*** Register Object: " << className << std::endl;
-
- object->identifier_ = this;
- if (Identifier::isCreatingHierarchy())
- {
- if (bRootClass && !object->parents_)
- object->parents_ = new std::set<const Identifier*>();
-
- if (object->parents_)
- {
- this->initializeClassHierarchy(object->parents_, bRootClass);
- object->parents_->insert(object->parents_->end(), this);
- }
-
- object->setConfigValues();
- return true;
- }
- else
- {
- COUT(5) << "*** ClassIdentifier: Added object to " << this->getName() << "-list." << std::endl;
- object->metaList_->add(this->objects_, this->objects_->add(new ObjectListElement<T>(object)));
-
- // Add pointer of type T to the map in the OrxonoxClass instance that enables "dynamic_casts"
- object->objectPointers_.push_back(std::make_pair(this->getClassID(), static_cast<void*>(object)));
- return false;
- }
- }
-
- /**
- @brief Updates the config-values of all existing objects of this class by calling their setConfigValues() function.
- */
- template <class T>
- void ClassIdentifier<T>::updateConfigValues(bool updateChildren) const
- {
- if (!this->hasConfigValues())
- return;
-
- for (ObjectListIterator<T> it = ObjectList<T>::begin(); it; ++it)
- it->setConfigValues();
-
- if (updateChildren)
- for (std::set<const Identifier*>::const_iterator it = this->getChildrenBegin(); it != this->getChildrenEnd(); ++it)
- (*it)->updateConfigValues(false);
- }
-
-
- // ###############################
- // ### orxonox_cast ###
- // ###############################
- /**
- @brief
- Casts on object of type OrxonoxClass to any derived type that is
- registered in the class hierarchy.
- @return
- Returns NULL if the cast is not possible
- @note
- In case of NULL return (and using MSVC), a dynamic_cast might still be possible if
- a class forgot to register its objects.
- Also note that the function is implemented differently for GCC/MSVC.
- */
- template <class T, class U>
- FORCEINLINE T orxonox_cast(U* source)
- {
-#ifdef ORXONOX_COMPILER_MSVC
- typedef Loki::TypeTraits<typename Loki::TypeTraits<T>::PointeeType>::NonConstType ClassType;
- if (source != NULL)
- return source->template getDerivedPointer<ClassType>(ClassIdentifier<ClassType>::getIdentifier()->getClassID());
- else
- return NULL;
-#else
- return dynamic_cast<T>(source);
-#endif
- }
-}
-
-#endif /* _Identifier_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Iterator.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Iterator.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Iterator.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,311 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Object ObjectList
- @brief Definition of the Iterator class, used to iterate through object-lists.
-
- @anchor IteratorExample
-
- @ref orxonox::Iterator "Iterator" allows to iterate through an @ref orxonox::ObjectListBase
- "ObjectListBase". Objects in this list are cast to the template argument @a T of Iterator<T> using
- @c dynamic_cast. In contrast to @ref orxonox::ObjectListIterator "ObjectListIterator<T>",
- @ref orxonox::Iterator "Iterator<T>" can iterate through every object-list. In practice though it
- is limited to objects of type @a T and its subclasses. Because of the @c dynamic_cast, this iterator
- is much slower than ObjectListIterator.
-
- Usage:
- @code
- for (Iterator<myClass> it = anyidentifier->getObjects()->begin(); it != anyidentifier->getObjects()->end(); ++it)
- {
- it->someFunction(...);
- myClass* myObject = *it;
- }
- @endcode
-*/
-
-#ifndef _Iterator_H__
-#define _Iterator_H__
-
-#include "CorePrereqs.h"
-
-#include "Identifier.h"
-#include "ObjectListBase.h"
-
-namespace orxonox
-{
- /**
- @brief The Iterator allows to iterate through a given ObjectList.
-
- Independent of the object-list's type, the objects in the list are always casted
- to @a T using @c dynamic_cast.
-
- @see See @ref IteratorExample "Iterator.h" for more information an example.
- */
- template <class T = OrxonoxClass>
- class Iterator
- {
- public:
- /**
- @brief Constructor: Sets the element, whereon the iterator points, to zero.
- */
- inline Iterator()
- {
- this->element_ = 0;
- this->list_ = 0;
- }
-
- /**
- @brief Constructor: Sets this element to the exported element.
- @param exp The exported element
- */
- inline Iterator(const ObjectListBase::Export& exp)
- {
- this->element_ = exp.element_;
- this->list_ = exp.list_;
- this->list_->registerIterator(this);
- }
-
- /**
- @brief Constructor: Sets this element to the element of another Iterator.
- @param other The other Iterator
- */
- inline Iterator(const Iterator<T>& other)
- {
- this->element_ = other.element_;
- this->list_ = other.list_;
- this->list_->registerIterator(this);
- }
-
- /**
- @brief Constructor: Sets this element to a given element
- @param element The element
- */
- template <class O>
- inline Iterator(ObjectListElement<O>* element)
- {
- this->element_ = element;
- this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
- this->list_->registerIterator(this);
- }
-
- /**
- @brief Constructor: Sets this element to the element an ObjectListIterator.
- @param other The ObjectListIterator
- */
- template <class O>
- inline Iterator(const ObjectListIterator<O>& other)
- {
- this->element_ = other.element_;
- this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
- this->list_->registerIterator(this);
- }
-
- /**
- @brief Unregisters the Iterator from the ObjectList.
- */
- inline ~Iterator()
- {
- this->list_->unregisterIterator(this);
- }
-
- /**
- @brief Assigns an exported element.
- @param exp The exported element
- */
- inline Iterator<T>& operator=(const ObjectListBase::Export& exp)
- {
- if (this->list_)
- this->list_->unregisterIterator(this);
-
- this->element_ = exp.element_;
- this->list_ = exp.list_;
- this->list_->registerIterator(this);
-
- return (*this);
- }
-
- /**
- @brief Assigns the element of another Iterator.
- @param other The other Iterator
- */
- inline Iterator<T>& operator=(const Iterator<T>& other)
- {
- if (this->list_)
- this->list_->unregisterIterator(this);
-
- this->element_ = other.element_;
- this->list_ = other.list_;
- this->list_->registerIterator(this);
-
- return (*this);
- }
-
- /**
- @brief Assigns a given element.
- @param element The element
- */
- template <class O>
- inline Iterator<T>& operator=(ObjectListElement<O>* element)
- {
- if (this->list_)
- this->list_->unregisterIterator(this);
-
- this->element_ = element;
- this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
- this->list_->registerIterator(this);
-
- return (*this);
- }
-
- /**
- @brief Assigns the element of an ObjectListIterator.
- @param other The ObjectListIterator
- */
- template <class O>
- inline Iterator<T>& operator=(const ObjectListIterator<O>& other)
- {
- if (this->list_)
- this->list_->unregisterIterator(this);
-
- this->element_ = other.element_;
- this->list_ = ClassIdentifier<O>::getIdentifier()->getObjects();
- this->list_->registerIterator(this);
-
- return (*this);
- }
-
- /**
- @brief Overloading of the ++it operator: Iterator points to the next object in the list.
- @return The Iterator itself
- */
- inline const Iterator<T>& operator++()
- {
- this->element_ = this->element_->next_;
- return *this;
- }
-
- /**
- @brief Overloading of the it++ operator: Iterator points to the next object in the list.
- @return The Iterator itself
- */
- inline Iterator<T> operator++(int)
- {
- Iterator<T> copy = *this;
- this->element_ = this->element_->next_;
- return copy;
- }
-
- /**
- @brief Overloading of the --it operator: Iterator points to the previous object in the list.
- @return The Iterator itself
- */
- inline const Iterator<T>& operator--()
- {
- this->element_ = this->element_->prev_;
- return *this;
- }
-
- /**
- @brief Overloading of the it-- operator: Iterator points to the previous object in the list.
- @return The Iterator itself
- */
- inline Iterator<T> operator--(int i)
- {
- Iterator<T> copy = *this;
- this->element_ = this->element_->prev_;
- return copy;
- }
-
- /**
- @brief Overloading of the *it operator: returns the pointer to the object.
- @return The object the Iterator points at
- */
- inline T* operator*() const
- {
- return orxonox_cast<T*>(this->element_->objectBase_);
- }
-
- /**
- @brief Overloading of the it-> operator: returns the pointer to the object.
- @return The object the Iterator points at
- */
- inline T* operator->() const
- {
- return orxonox_cast<T*>(this->element_->objectBase_);
- }
-
- /**
- @brief Overloading of the typecast-operator to bool: returns true if the iterator points to an existing object.
- @return True if the Iterator points to an existing object.
- */
- inline operator bool() const
- {
- return (this->element_ != 0);
- }
-
- /**
- @brief Overloading of the == operator to compare with another Iterator.
- @param compare The other Iterator
- @return True if the iterators point to the same element
- */
- inline bool operator==(const Iterator<T>& compare) const
- {
- return (this->element_ == compare.element_);
- }
-
- /**
- @brief Overloading of the != operator to compare with another Iterator.
- @param compare The other Iterator
- @return True if the iterators point to different elements
- */
- inline bool operator!=(const Iterator<T>& compare) const
- {
- return (this->element_ != compare.element_);
- }
-
- /**
- @brief Increments the Iterator if it points at the given object.
- @param object The object to compare with
- */
- inline void incrementIfEqual(OrxonoxClass* object)
- {
- if (this->element_ && this->element_->objectBase_ == object)
- this->operator++();
- }
-
- protected:
- ObjectListBaseElement* element_; //!< The element the Iterator points at
- ObjectListBase* list_; //!< The list wherein the element is
- };
-
- typedef Iterator<OrxonoxClass> BaseIterator;
-}
-
-#endif /* _Iterator_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Language.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Language.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Language.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,329 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the Language and the LanguageEntry classes.
-*/
-
-#include "Language.h"
-
-#include <fstream>
-#include "util/Debug.h"
-#include "util/StringUtils.h"
-#include "Core.h"
-#include "PathConfig.h"
-
-namespace orxonox
-{
- // ###############################
- // ### LanguageEntry ###
- // ###############################
- /**
- @brief Constructor: Sets the default entry.
- @param fallbackEntry The default entry
- */
- LanguageEntry::LanguageEntry(const std::string& fallbackEntry)
- {
- this->fallbackEntry_ = fallbackEntry;
- this->localisedEntry_ = fallbackEntry; // Set the localisation to the fallback entry, for the case that no translation gets assigned
- this->bLocalisationSet_ = false;
- }
-
- /**
- @brief Sets the localisation of the entry.
- @param localisation The localisation
- */
- void LanguageEntry::setLocalisation(const std::string& localisation)
- {
- // Check if the translation is more than just an empty string
- if (!localisation.empty())
- {
- this->localisedEntry_ = localisation;
- this->bLocalisationSet_ = true;
- }
- else
- this->localisedEntry_ = this->fallbackEntry_;
- }
-
- /**
- @brief Sets the default entry.
- @param fallbackEntry The default entry
- */
- void LanguageEntry::setDefault(const std::string& fallbackEntry)
- {
- // If the default entry changes and the translation wasn't set yet, use the new default entry as translation
- if (!this->bLocalisationSet_)
- this->localisedEntry_ = fallbackEntry;
-
- this->fallbackEntry_ = fallbackEntry;
- }
-
- // ###############################
- // ### Language ###
- // ###############################
-
- Language* Language::singletonPtr_s = 0;
-
- /**
- @brief Constructor: Reads the default language file and sets some values.
- */
- Language::Language()
- {
- this->defaultLanguage_ = "default";
- this->defaultLocalisation_ = "ERROR: LANGUAGE ENTRY DOESN'T EXIST!";
-
- // Read the default language file to create all known LanguageEntry objects
- this->readDefaultLanguageFile();
- }
-
- /**
- @brief Destructor: Deletes all language entries.
- */
- Language::~Language()
- {
- for (std::map<std::string, LanguageEntry*>::iterator it = this->languageEntries_.begin(); it != this->languageEntries_.end(); ++it)
- delete (it->second);
- }
-
- /**
- @brief Creates a new LanguageEntry with a given label and a given default entry.
- @param label The label of the entry
- @param entry The default entry
- @return The created LanguageEntry object
- */
- LanguageEntry* Language::createEntry(const LanguageEntryLabel& label, const std::string& entry)
- {
- std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
-
- // Make sure we don't create a duplicate entry
- if (it == this->languageEntries_.end())
- {
- LanguageEntry* newEntry = new LanguageEntry(entry);
- newEntry->setLabel(label);
- this->languageEntries_[label] = newEntry;
- return newEntry;
- }
-
- COUT(2) << "Warning: Language entry " << label << " is duplicate in " << getFilename(this->defaultLanguage_) << '!' << std::endl;
- return it->second;
- }
-
- /**
- @brief Adds a new LanguageEntry, if it's not already existing.
- @param label The label of the entry
- @param entry The default entry
- */
- void Language::addEntry(const LanguageEntryLabel& label, const std::string& entry)
- {
- COUT(5) << "Language: Called addEntry with\n label: " << label << "\n entry: " << entry << std::endl;
- std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
- if (it == this->languageEntries_.end())
- {
- // The entry isn't available yet, meaning it's new, so create it
- this->createEntry(label, entry);
- }
- else if (it->second->getDefault().compare(entry) == 0)
- {
- // The entry is available and the default string is the same, so return because everything is fine
- return;
- }
- else
- {
- // The defined default entry is not the same as in the default language file - change it to the new entry
- it->second->setDefault(entry);
- }
-
- // Write the default language file because either a new entry was created or an existing entry has changed
- this->writeDefaultLanguageFile();
-
- }
-
- /**
- @brief Returns the localisation of a given entry.
- @param label The label of the entry
- @param bError If true, an error is printed if the label doesn't exist and the default localisation is returned. If false, no error is printed and an empty string is returned.
- @return The localisation
- */
- const std::string& Language::getLocalisation(const LanguageEntryLabel& label, bool bError) const
- {
- std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(label);
- if (it != this->languageEntries_.end())
- return it->second->getLocalisation();
- else if (bError)
- {
- // Uh, oh, an undefined entry was requested: return the default string
- COUT(2) << "Warning: Language entry \"" << label << "\" not found!" << std::endl;
- return this->defaultLocalisation_;
- }
- else
- return BLANKSTRING;
- }
-
- /**
- @brief Creates the name of the language file out of the languages name.
- @param language The name of the language
- @return The filename
- */
- std::string Language::getFilename(const std::string& language)
- {
- return std::string("translation_" + language + ".lang");
- }
-
- /**
- @brief Reads the default language file and creates a LanguageEntry objects for every entry.
- */
- void Language::readDefaultLanguageFile()
- {
- COUT(4) << "Read default language file." << std::endl;
-
- const std::string& filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
-
- // This creates the file if it's not existing
- std::ofstream createFile;
- createFile.open(filepath.c_str(), std::fstream::app);
- createFile.close();
-
- // Open the file
- std::ifstream file;
- file.open(filepath.c_str(), std::fstream::in);
-
- if (!file.is_open())
- {
- COUT(1) << "An error occurred in Language.cc:" << std::endl;
- COUT(1) << "Error: Couldn't open file " << getFilename(this->defaultLanguage_) << " to read the default language entries!" << std::endl;
- return;
- }
-
- // Iterate through the file and create the LanguageEntries
- while (file.good() && !file.eof())
- {
- std::string lineString;
- std::getline(file, lineString);
-
- // Check if the line is empty
- if (!lineString.empty())
- {
- size_t pos = lineString.find('=');
-
- // Check if the length is at least 3 and if there's an entry before and behind the =
- if (pos > 0 && pos < (lineString.size() - 1) && lineString.size() >= 3)
- this->createEntry(lineString.substr(0, pos), lineString.substr(pos + 1));
- else
- {
- COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(this->defaultLanguage_) << std::endl;
- }
- }
- }
-
- file.close();
- }
-
- /**
- @brief Reads the language file of the configured language and assigns the localisation to the corresponding LanguageEntry object.
- */
- void Language::readTranslatedLanguageFile()
- {
- COUT(4) << "Read translated language file (" << Core::getInstance().getLanguage() << ")." << std::endl;
-
- const std::string& filepath = PathConfig::getConfigPathString() + getFilename(Core::getInstance().getLanguage());
-
- // Open the file
- std::ifstream file;
- file.open(filepath.c_str(), std::fstream::in);
-
- if (!file.is_open())
- {
- COUT(1) << "An error occurred in Language.cc:" << std::endl;
- COUT(1) << "Error: Couldn't open file " << getFilename(Core::getInstance().getLanguage()) << " to read the translated language entries!" << std::endl;
- Core::getInstance().resetLanguage();
- COUT(3) << "Info: Reset language to " << this->defaultLanguage_ << '.' << std::endl;
- return;
- }
-
- // Iterate through the file and create the LanguageEntries
- while (file.good() && !file.eof())
- {
- std::string lineString;
- std::getline(file, lineString);
-
- // Check if the line is empty
- if (!lineString.empty())
- {
- size_t pos = lineString.find('=');
-
- // Check if the length is at least 3 and if there's an entry before and behind the =
- if (pos > 0 && pos < (lineString.size() - 1) && lineString.size() >= 3)
- {
- std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.find(lineString.substr(0, pos));
-
- // Check if the entry exists
- if (it != this->languageEntries_.end())
- it->second->setLocalisation(lineString.substr(pos + 1));
- else
- this->createEntry(lineString.substr(0, pos), this->defaultLocalisation_)->setLocalisation(lineString.substr(pos + 1));
- }
- else
- {
- COUT(2) << "Warning: Invalid language entry \"" << lineString << "\" in " << getFilename(Core::getInstance().getLanguage()) << std::endl;
- }
- }
- }
-
- file.close();
- }
-
- /**
- @brief Writes all default entries to the default language file.
- */
- void Language::writeDefaultLanguageFile() const
- {
- COUT(4) << "Language: Write default language file." << std::endl;
-
- const std::string& filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
-
- // Open the file
- std::ofstream file;
- file.open(filepath.c_str(), std::fstream::out);
-
- if (!file.is_open())
- {
- COUT(1) << "An error occurred in Language.cc:" << std::endl;
- COUT(1) << "Error: Couldn't open file " << getFilename(this->defaultLanguage_) << " to write the default language entries!" << std::endl;
- return;
- }
-
- // Iterate through the list an write the lines into the file
- for (std::map<std::string, LanguageEntry*>::const_iterator it = this->languageEntries_.begin(); it != this->languageEntries_.end(); ++it)
- {
- file << it->second->getLabel() << '=' << it->second->getDefault() << std::endl;
- }
-
- file.close();
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Language.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Language.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Language.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,207 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Language Language
- @ingroup Core
-*/
-
-/**
- @file
- @ingroup Language
- @brief Declaration of the Language and the LanguageEntry class, as well as some helper functions.
-
- @anchor LanguageExample
-
- The Language class is used, to get a localisation of a string in the configured language.
- The string is identified by another string, the label of the entry.
- If the translation in the configured language isn't available, the default entry, defined in the code, is used.
-
- Usage:
- - Set the entry with the default string:
- @code
- Language::getInstance()->addEntry("label of the entry", "the string to translate");
- @endcode
-
- - Get the localisation of the entry in the configured language:
- @code
- std::cout << Language::getInstance()->getLocalisation("name of the entry") << std::endl;
- @endcode
-
- Example:
- @code
- int age = 20;
- AddLanguageEntry("user_age", "Age");
- std::cout << GetLocalisation("user_age") << ": " << age << std::endl;
- @endcode
-
- Resulting output:
- @code
- Age: 20
- @endcode
-
- The language entry is now defined in @a translation_default.lang:
- @code
- user_age=Age
- @endcode
-
- We can add a translation for another language, for example @a translation_german.lang:
- @code
- user_age=Alter
- @endcode
-
- Now change the language in @a orxonox.ini to "german":
- @code
- language_ = "german"
- @endcode
-
- Now you will see the translated language entry in the resulting output of the above code:
- @code
- Alter: 20
- @endcode
-*/
-
-#ifndef _Language_H__
-#define _Language_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-#include <cassert>
-#include "util/Singleton.h"
-
-namespace orxonox
-{
- // ###############################
- // ### LanguageEntry ###
- // ###############################
- /**
- @brief The LanguageEntry class stores the default- and the translated string of a given entry in the language file.
-
- This class belongs to the Language class.
- */
- class _CoreExport LanguageEntry
- {
- public:
- explicit LanguageEntry(const std::string& fallbackEntry);
- void setLocalisation(const std::string& localisation);
- void setDefault(const std::string& fallbackEntry);
-
- /**
- @brief Returns the localised entry in the configured language.
- @return The translated entry
- */
- inline const std::string& getLocalisation()
- { return this->localisedEntry_; }
-
- /**
- @brief Returns the default entry.
- @return The default entry
- */
- inline const std::string& getDefault()
- { return this->fallbackEntry_; }
-
- /**
- @brief Sets the label of this entry.
- @param label The label
- */
- inline void setLabel(const LanguageEntryLabel& label)
- { this->label_ = label; }
-
- /**
- @brief Returns the label of this entry.
- @return The label
- */
- inline const LanguageEntryLabel& getLabel() const
- { return this->label_; }
-
- private:
- LanguageEntryLabel label_; //!< The label of the entry
- std::string fallbackEntry_; //!< The default entry: Used, if no translation is available or no language configured
- std::string localisedEntry_; //!< The localised entry in the configured language
- bool bLocalisationSet_; //!< True if the translation was set
- };
-
-
- // ###############################
- // ### Language ###
- // ###############################
- /**
- @brief The Language class manges the language files and entries and stores the LanguageEntry objects in a map.
-
- @see See @ref LanguageExample "Language.h" for some examples.
- */
- class _CoreExport Language : public Singleton<Language>
- {
- friend class Singleton<Language>;
- friend class Core;
-
- public:
- Language();
- ~Language();
-
- void addEntry(const LanguageEntryLabel& label, const std::string& entry);
- const std::string& getLocalisation(const LanguageEntryLabel& label, bool bError = true) const;
-
- private:
- Language(const Language&);
-
- void readDefaultLanguageFile();
- void readTranslatedLanguageFile();
- void writeDefaultLanguageFile() const;
- static std::string getFilename(const std::string& language);
- LanguageEntry* createEntry(const LanguageEntryLabel& label, const std::string& entry);
-
- std::string defaultLanguage_; //!< The default language
- std::string defaultLocalisation_; //!< The returned string, if an entry unavailable entry is requested
- std::map<std::string, LanguageEntry*> languageEntries_; //!< A map to store all LanguageEntry objects and their labels
-
- static Language* singletonPtr_s;
- };
-
- /// Shortcut function for Language::addEntry
- inline void AddLanguageEntry(const LanguageEntryLabel& label, const std::string& fallbackString)
- {
- Language::getInstance().addEntry(label, fallbackString);
- }
-
- /// Shortcut function for Language::getLocalisation
- inline const std::string& GetLocalisation(const LanguageEntryLabel& label)
- {
- return Language::getInstance().getLocalisation(label);
- }
-
- /// Shortcut function for Language::getLocalisation without printing an error in case the label doesn't exist
- inline const std::string& GetLocalisation_noerror(const LanguageEntryLabel& label)
- {
- return Language::getInstance().getLocalisation(label, false);
- }
-}
-
-#endif /* _Language_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Loader.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Loader.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Loader.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,423 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "Loader.h"
-
-#include <sstream>
-#include <tinyxml/ticpp.h>
-#include <boost/scoped_ptr.hpp>
-
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/StringUtils.h"
-#include "BaseObject.h"
-#include "Iterator.h"
-#include "ObjectList.h"
-#include "LuaState.h"
-#include "Namespace.h"
-#include "Resource.h"
-#include "XMLFile.h"
-
-namespace orxonox
-{
- std::vector<std::pair<const XMLFile*, ClassTreeMask> > Loader::files_s;
- ClassTreeMask Loader::currentMask_s;
-
- bool Loader::open(const XMLFile* file, const ClassTreeMask& mask)
- {
- Loader::add(file, mask);
- return Loader::load(file, mask);
- }
-
- void Loader::close()
- {
- Loader::unload();
- Loader::files_s.clear();
- }
-
- void Loader::close(const XMLFile* file)
- {
- Loader::unload(file);
- Loader::remove(file);
- }
-
- void Loader::add(const XMLFile* file, const ClassTreeMask& mask)
- {
- if (!file)
- return;
- Loader::files_s.insert(Loader::files_s.end(), std::pair<const XMLFile*, ClassTreeMask>(file, mask));
- }
-
- void Loader::remove(const XMLFile* file)
- {
- if (!file)
- return;
- for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it)
- {
- if (it->first == file)
- {
- Loader::files_s.erase(it);
- break;
- }
- }
- }
-
- /**
- @brief
- Loads all opened files, while conforming to the restrictions given by the input ClassTreeMask.
- @param mask
- A ClassTreeMask, which defines which types of classes are loaded and which aren't.
- @param verbose
- Whether the loader is verbose (prints its progress in a low output level) or not.
- @return
- Returns true if successful.
- */
- bool Loader::load(const ClassTreeMask& mask, bool verbose)
- {
- bool success = true;
- for (std::vector<std::pair<const XMLFile*, ClassTreeMask> >::iterator it = Loader::files_s.begin(); it != Loader::files_s.end(); ++it)
- if (!Loader::load(it->first, it->second * mask, verbose))
- success = false;
-
- return success;
- }
-
- void Loader::unload(const ClassTreeMask& mask)
- {
- for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); )
- {
- if (mask.isIncluded(it->getIdentifier()))
- (it++)->destroy();
- else
- ++it;
- }
- }
-
- /**
- @brief
- Reloads all opened files, while conforming to the restrictions given by the input ClassTreeMask.
- @param mask
- A ClassTreeMask, which defines which types of classes are reloaded and which aren't.
- @param verbose
- Whether the loader is verbose (prints its progress in a low output level) or not.
- @return
- Returns true if successful.
- */
- bool Loader::reload(const ClassTreeMask& mask, bool verbose)
- {
- Loader::unload(mask);
- return Loader::load(mask, verbose);
- }
-
- /**
- @brief
- Loads the input file, while conforming to the restrictions given by the input ClassTreeMask.
- @param file
- The file to be loaded.
- @param mask
- A ClassTreeMask, which defines which types of classes are loaded and which aren't.
- @param verbose
- Whether the loader is verbose (prints its progress in a low output level) or not.
- @return
- Returns true if successful.
- */
- bool Loader::load(const XMLFile* file, const ClassTreeMask& mask, bool verbose)
- {
- if (!file)
- return false;
-
- Loader::currentMask_s = file->getMask() * mask;
-
- std::string xmlInput;
- if (file->getLuaSupport())
- {
- // Use the LuaState to replace the XML tags (calls our function)
- scoped_ptr<LuaState> luaState(new LuaState());
- luaState->setIncludeParser(&Loader::replaceLuaTags);
- luaState->includeFile(file->getFilename());
- xmlInput = luaState->getOutput().str();
- }
- else
- {
- shared_ptr<ResourceInfo> info = Resource::getInfo(file->getFilename());
- if (info == NULL)
- {
- COUT(1) << "Error: Could not find XML file '" << file->getFilename() << "'." << std::endl;
- return false;
- }
- xmlInput = Resource::open(file->getFilename())->getAsString();
- }
-
- try
- {
- if(verbose)
- {
- COUT(0) << "Start loading " << file->getFilename() << "..." << std::endl;
- COUT(3) << "Mask: " << Loader::currentMask_s << std::endl;
- }
- else
- {
- COUT(4) << "Start loading " << file->getFilename() << "..." << std::endl;
- COUT(4) << "Mask: " << Loader::currentMask_s << std::endl;
- }
-
- ticpp::Document xmlfile(file->getFilename());
- xmlfile.Parse(xmlInput, true);
-
- ticpp::Element rootElement;
- rootElement.SetAttribute("name", "root");
- rootElement.SetAttribute("bAutogenerated", true);
-
- for (ticpp::Iterator<ticpp::Element> child = xmlfile.FirstChildElement(false); child != child.end(); child++)
- rootElement.InsertEndChild(*child);
-
- COUT(4) << " creating root-namespace..." << std::endl;
- Namespace* rootNamespace = new Namespace(0);
- rootNamespace->setLoaderIndentation(" ");
- rootNamespace->setFile(file);
- rootNamespace->setNamespace(rootNamespace);
- rootNamespace->setRoot(true);
- rootNamespace->XMLPort(rootElement, XMLPort::LoadObject);
-
- if(verbose)
- COUT(0) << "Finished loading " << file->getFilename() << '.' << std::endl;
- else
- COUT(4) << "Finished loading " << file->getFilename() << '.' << std::endl;
-
- COUT(4) << "Namespace-tree:" << std::endl << rootNamespace->toString(" ") << std::endl;
-
- return true;
- }
- catch (ticpp::Exception& ex)
- {
- COUT(1) << std::endl;
- COUT(1) << "An XML-error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl;
- COUT(1) << ex.what() << std::endl;
- COUT(1) << "Loading aborted." << std::endl;
- return false;
- }
- catch (Exception& ex)
- {
- COUT(1) << std::endl;
- COUT(1) << "A loading-error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl;
- COUT(1) << ex.what() << std::endl;
- COUT(1) << "Loading aborted." << std::endl;
- return false;
- }
- catch (...)
- {
- COUT(1) << std::endl;
- COUT(1) << "An error occurred in Loader.cc while loading " << file->getFilename() << ':' << std::endl;
- COUT(1) << Exception::handleMessage() << std::endl;
- COUT(1) << "Loading aborted." << std::endl;
- return false;
- }
- }
-
- void Loader::unload(const XMLFile* file, const ClassTreeMask& mask)
- {
- if (!file)
- return;
- for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it; )
- {
- if ((it->getFile() == file) && mask.isIncluded(it->getIdentifier()))
- (it++)->destroy();
- else
- ++it;
- }
- }
-
- /**
- @brief
- Reloads the input file, while conforming to the restrictions given by the input ClassTreeMask.
- @param file
- The file to be reloaded.
- @param mask
- A ClassTreeMask, which defines which types of classes are reloaded and which aren't.
- @param verbose
- Whether the loader is verbose (prints its progress in a low output level) or not.
- @return
- Returns true if successful.
- */
- bool Loader::reload(const XMLFile* file, const ClassTreeMask& mask, bool verbose)
- {
- Loader::unload(file, mask);
- return Loader::load(file, mask, verbose);
- }
-
- std::string Loader::replaceLuaTags(const std::string& text)
- {
- // create map with all Lua tags
- std::map<size_t, bool> luaTags;
- {
- size_t pos = 0;
- while ((pos = text.find("<?lua", pos)) != std::string::npos)
- luaTags[pos++] = true;
- }
- {
- size_t pos = 0;
- while ((pos = text.find("?>", pos)) != std::string::npos)
- luaTags[pos++] = false;
- }
-
- // erase all tags from the map that are between two quotes
- {
- std::map<size_t, bool>::iterator it = luaTags.begin();
- std::map<size_t, bool>::iterator it2 = it;
- bool bBetweenQuotes = false;
- size_t pos = 0;
- while ((pos = getNextQuote(text, pos)) != std::string::npos)
- {
- while ((it != luaTags.end()) && (it->first < pos))
- {
- if (bBetweenQuotes)
- {
- it2++;
- if (it->second && !(it2->second) && it2->first < pos)
- it = ++it2;
- else
- luaTags.erase(it++);
- }
- else
- ++it;
- }
- bBetweenQuotes = !bBetweenQuotes;
- pos++;
- }
- }
-
- // check whether on every opening <?lua tag a closing ?> tag follows
- {
- bool expectedValue = true;
- for (std::map<size_t, bool>::iterator it = luaTags.begin(); it != luaTags.end(); ++it)
- {
- if (it->second == expectedValue)
- expectedValue = !expectedValue;
- else
- {
- expectedValue = false;
- break;
- }
- }
- if (!expectedValue)
- {
- COUT(2) << "Warning: Error in level file" << std::endl;
- // todo: errorhandling
- return "";
- }
- }
-
- // Use a stringstream object to speed up the parsing
- std::ostringstream output;
-
- // cut the original string into pieces and put them together with print() instead of lua tags
- {
- std::map<size_t, bool>::iterator it = luaTags.begin();
- bool bInPrintFunction = true;
- size_t start = 0;
- size_t end = 0;
-
- do
- {
- if (it != luaTags.end())
- end = (it++)->first;
- else
- end = std::string::npos;
-
- unsigned int equalSignCounter = 0;
-
- if (bInPrintFunction)
- {
- // count ['='[ and ]'='] and replace tags with print([[ and ]])
- const std::string& temp = text.substr(start, end - start);
- {
- size_t pos = 0;
- while ((pos = temp.find('[', pos)) != std::string::npos)
- {
- unsigned int tempCounter = 1;
- size_t tempPos = pos++;
- while (temp[++tempPos] == '=')
- {
- tempCounter++;
- }
- if (temp[tempPos] != '[')
- {
- tempCounter = 0;
- }
- else if (tempCounter == 0)
- {
- tempCounter = 1;
- }
- if (tempCounter > equalSignCounter)
- equalSignCounter = tempCounter;
- }
- }
- {
- size_t pos = 0;
- while ((pos = temp.find(']', pos)) != std::string::npos)
- {
- unsigned int tempCounter = 1;
- size_t tempPos = pos++;
- while (temp[++tempPos] == '=')
- {
- tempCounter++;
- }
- if (temp[tempPos] != ']')
- {
- tempCounter = 0;
- }
- else if (tempCounter == 0)
- {
- tempCounter = 1;
- }
- if (tempCounter > equalSignCounter)
- equalSignCounter = tempCounter;
- }
- }
- std::string equalSigns;
- for (unsigned int i = 0; i < equalSignCounter; i++)
- {
- equalSigns += '=';
- }
- output << "print([" + equalSigns + '[' + temp + ']' + equalSigns +"])";
- start = end + 5;
- }
- else
- {
- output << text.substr(start, end - start);
- start = end + 2;
- }
-
- bInPrintFunction = !bInPrintFunction;
- }
- while (end != std::string::npos);
- }
-
- return output.str();
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Loader.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Loader.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Loader.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,76 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Loader Loader
- @ingroup XML
-*/
-
-/**
- @file
- @ingroup XML Loader
-*/
-
-#ifndef _Loader_H__
-#define _Loader_H__
-
-#include "CorePrereqs.h"
-
-#include <vector>
-#include "ClassTreeMask.h"
-
-namespace orxonox
-{
- class _CoreExport Loader
- {
- public:
- static bool open(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
- static void close();
- static void close(const XMLFile* file);
-
- static void add(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
- static void remove(const XMLFile* file);
-
- static bool load(const ClassTreeMask& mask = ClassTreeMask(), bool verbose = true);
- static void unload(const ClassTreeMask& mask = ClassTreeMask());
- static bool reload(const ClassTreeMask& mask = ClassTreeMask(), bool verbose = true);
-
- static bool load(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask(), bool verbose = true);
- static void unload(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask());
- static bool reload(const XMLFile* file, const ClassTreeMask& mask = ClassTreeMask(), bool verbose = true);
-
- static std::string replaceLuaTags(const std::string& text);
-
- static ClassTreeMask currentMask_s;
-
- private:
- static std::vector<std::pair<const XMLFile*, ClassTreeMask> > files_s;
- };
-}
-
-#endif /* _Loader_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/LuaState.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/LuaState.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/LuaState.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,376 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Benjamin Knecht
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-#include "LuaState.h"
-
-#include <tolua/tolua++.h>
-extern "C" {
-#include <lua.h>
-#include <lualib.h>
-}
-#include <loki/ScopeGuard.h>
-
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "Resource.h"
-#include "ToluaBindCore.h"
-#include "command/IOConsole.h"
-
-namespace orxonox
-{
- LuaState::ToluaInterfaceMap LuaState::toluaInterfaces_s;
- std::vector<LuaState*> LuaState::instances_s;
-
- const std::string LuaState::ERROR_HANDLER_NAME = "errorHandler";
-
- // Do this after declaring toluaInterfaces_s and instances_s to avoid larger problems
- DeclareToluaInterface(Core);
-
- LuaState::LuaState()
- : bIsRunning_(false)
- , includeParseFunction_(NULL)
- {
- // Create new lua state and configure it
- luaState_ = lua_open();
- Loki::ScopeGuard luaStateGuard = Loki::MakeGuard(&lua_close, luaState_);
-#if LUA_VERSION_NUM == 501
- luaL_openlibs(luaState_);
-#else
- luaopen_base(luaState_);
- luaopen_string(luaState_);
- luaopen_table(luaState_);
- luaopen_math(luaState_);
- luaopen_io(luaState_);
- luaopen_debug(luaState_);
-#endif
-
- // Open all available tolua interfaces
- this->openToluaInterfaces(luaState_);
-
- // Create dummy file info
- sourceFileInfo_.reset(new ResourceInfo());
- sourceFileInfo_->group = "General";
- sourceFileInfo_->size = 0;
-
- // Push 'this' pointer
- tolua_pushusertype(luaState_, static_cast<void*>(this), "orxonox::LuaState");
- lua_setglobal(luaState_, "luaState");
-
- // Parse init script
- if (!this->doFile("LuaStateInit.lua"))
- ThrowException(InitialisationFailed, "Running LuaStateInit.lua failed");
-
- luaStateGuard.Dismiss();
- }
-
- LuaState::~LuaState()
- {
- lua_close(luaState_);
- }
-
- shared_ptr<ResourceInfo> LuaState::getFileInfo(const std::string& filename)
- {
- // Look in the current directory first
- shared_ptr<ResourceInfo> sourceInfo = Resource::getInfo(sourceFileInfo_->path + filename);
- // Continue search in root directories
- if (sourceInfo == NULL && !sourceFileInfo_->path.empty())
- sourceInfo = Resource::getInfo(filename);
- return sourceInfo;
- }
-
- bool LuaState::includeFile(const std::string& filename)
- {
- shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
- if (sourceInfo != NULL)
- return this->includeString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
- else
- {
- COUT(2) << "LuaState: Cannot include file '" << filename << "' (not found)." << std::endl;
- return false;
- }
- }
-
- bool LuaState::includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
- {
- // Parse string with provided include parser (otherwise don't preparse at all)
- std::string luaInput;
- if (includeParseFunction_ != NULL)
- luaInput = (*includeParseFunction_)(code);
- else
- luaInput = code;
-
- if (sourceFileInfo != NULL)
- {
- // Also fill a map with the actual source code. This is just for the include* commands
- // where the content of sourceFileInfo->filename doesn't match 'code'
- this->sourceCodeMap_[sourceFileInfo->filename] = code;
- }
-
- bool returnValue = this->doString(luaInput, sourceFileInfo);
-
- if (sourceFileInfo != NULL)
- {
- // Delete source code entry
- if (sourceFileInfo != NULL)
- this->sourceCodeMap_.erase(sourceFileInfo->filename);
- }
-
- return returnValue;
- }
-
- bool LuaState::doFile(const std::string& filename)
- {
- shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
- if (sourceInfo != NULL)
- return this->doString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
- else
- {
- COUT(2) << "LuaState: Cannot do file '" << filename << "' (not found)." << std::endl;
- return false;
- }
- }
-
- bool LuaState::doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
- {
- // Save the old source file info
- shared_ptr<ResourceInfo> oldSourceFileInfo = sourceFileInfo_;
- // Only override if sourceFileInfo provides useful information
- if (sourceFileInfo != NULL)
- sourceFileInfo_ = sourceFileInfo;
-
- std::string chunkname;
- if (sourceFileInfo != NULL)
- {
- // Provide lua_load with the filename for debug purposes
- // The '@' is a Lua convention to identify the chunk name as filename
- chunkname = '@' + sourceFileInfo->filename;
- }
- else
- {
- // Use the code string to identify the chunk
- chunkname = code;
- }
-
- // Push custom error handler that uses the debugger
- lua_getglobal(this->luaState_, ERROR_HANDLER_NAME.c_str());
- int errorHandler = lua_gettop(luaState_);
- if (lua_isnil(this->luaState_, -1))
- {
- lua_pop(this->luaState_, 1);
- errorHandler = 0;
- }
-
-#if LUA_VERSION_NUM != 501
- LoadS ls;
- ls.s = code.c_str();
- ls.size = code.size();
- int error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, chunkname.c_str());
-#else
- int error = luaL_loadbuffer(luaState_, code.c_str(), code.size(), chunkname.c_str());
-#endif
-
- switch (error)
- {
- case LUA_ERRSYNTAX: // Syntax error
- COUT(1) << "Lua syntax error: " << lua_tostring(luaState_, -1) << std::endl;
- break;
- case LUA_ERRMEM: // Memory allocation error
- COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
- break;
- }
-
- if (error == 0)
- {
- // Execute the chunk in protected mode with an error handler function (stack index)
- error = lua_pcall(luaState_, 0, 1, errorHandler);
-
- switch (error)
- {
- case LUA_ERRRUN: // Runtime error
- if (errorHandler)
- {
- // Do nothing (we already display the error in the
- // 'errorHandler' Lua function in LuaStateInit.lua)
- }
- else
- {
- std::string errorString = lua_tostring(this->luaState_, -1);
- if (errorString.find("Error propagation") == std::string::npos)
- COUT(1) << "Lua runtime error: " << errorString << std::endl;
- }
- break;
- case LUA_ERRERR: // Error in the error handler
- COUT(1) << "Lua error in error handler. No message available." << std::endl;
- break;
- case LUA_ERRMEM: // Memory allocation error
- COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
- break;
- }
- }
-
- if (error != 0)
- {
- lua_pop(luaState_, 1); // Remove error message
- lua_pushnil(luaState_); // Push a nil return value
- }
-
- if (errorHandler != 0)
- lua_remove(luaState_, errorHandler); // Remove error handler from stack
-
- // Set return value to a global variable because we cannot return a table in this function
- // here. It would work for numbers, pointers and strings, but certainly not for Lua tables.
- lua_setglobal(luaState_, "LuaStateReturnValue");
-
- // Load the old info again
- sourceFileInfo_ = oldSourceFileInfo;
-
- return (error == 0);
- }
-
- void LuaState::luaPrint(const std::string& str)
- {
- output_ << str;
- }
-
- void LuaState::luaLog(unsigned int level, const std::string& message)
- {
- OutputHandler::getOutStream(level) << message << std::endl;
- }
-
- bool LuaState::fileExists(const std::string& filename)
- {
- shared_ptr<ResourceInfo> info = this->getFileInfo(filename);
- if (info == NULL)
- return false;
- else
- return true;
- }
-
- //! Returns the content of a file
- std::string LuaState::getSourceCode(const std::string& filename)
- {
- // Try the internal map first to get the actual Lua code
- // and not just some pseudo Lua-XML code when using include* commands
- std::map<std::string, std::string>::const_iterator it = this->sourceCodeMap_.find(filename);
- if (it != this->sourceCodeMap_.end())
- return it->second;
- shared_ptr<ResourceInfo> info = Resource::getInfo(filename);
- if (info == NULL)
- return "";
- else
- return Resource::open(info)->getAsString();
- }
-
- bool LuaState::usingIOConsole() const
- {
- return IOConsole::exists();
- }
-
-#if LUA_VERSION_NUM != 501
- const char * LuaState::lua_Chunkreader(lua_State *L, void *data, size_t *size)
- {
- LoadS* ls = static_cast<LoadS*>(data);
- if (ls->size == 0)
- return NULL;
- *size = ls->size;
- ls->size = 0;
- return ls->s;
- }
-#endif
-
- /*static*/ bool LuaState::addToluaInterface(int (*function)(lua_State*), const std::string& name)
- {
- for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
- {
- if (it->first == name || it->second == function)
- {
- COUT(2) << "Warning: Trying to add a Tolua interface with the same name or function." << std::endl;
- return true;
- }
- }
- toluaInterfaces_s[name] = function;
-
- // Open interface in all LuaStates
- for (std::vector<LuaState*>::const_iterator it = instances_s.begin(); it != instances_s.end(); ++it)
- (*function)((*it)->luaState_);
-
- // Return dummy bool
- return true;
- }
-
- /*static*/ bool LuaState::removeToluaInterface(const std::string& name)
- {
- ToluaInterfaceMap::iterator it = toluaInterfaces_s.find(name);
- if (it == toluaInterfaces_s.end())
- {
- COUT(2) << "Warning: Cannot remove Tolua interface '" << name << "': Not found" << std::endl;
- return true;
- }
-
- // Close interface in all LuaStates
- for (std::vector<LuaState*>::const_iterator itState = instances_s.begin(); itState != instances_s.end(); ++itState)
- {
- lua_pushnil((*itState)->luaState_);
- lua_setglobal((*itState)->luaState_, it->first.c_str());
- }
-
- // Remove entry
- toluaInterfaces_s.erase(it);
-
- // Return dummy bool
- return true;
- }
-
- /*static*/ void LuaState::openToluaInterfaces(lua_State* state)
- {
- for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
- (*it->second)(state);
- }
-
- /*static*/ void LuaState::closeToluaInterfaces(lua_State* state)
- {
- for (ToluaInterfaceMap::const_iterator it = toluaInterfaces_s.begin(); it != toluaInterfaces_s.end(); ++it)
- {
- lua_pushnil(state);
- lua_setglobal(state, it->first.c_str());
- }
- }
-
-
- LuaFunctor::LuaFunctor(const std::string& code, LuaState* luaState)
- {
- this->code_ = code;
- this->lua_ = luaState;
- }
-
- void LuaFunctor::operator()()
- {
- lua_->doString(this->code_);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/LuaState.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/LuaState.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/LuaState.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,138 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Benjamin Knecht
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Lua Lua
- @ingroup Core
-*/
-
-/**
- @file
- @ingroup Lua
-*/
-
-#ifndef _LuaState_H__
-#define _LuaState_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <sstream>
-#include <string>
-#include <vector>
-#include <boost/shared_ptr.hpp>
-#include <loki/ScopeGuard.h>
-
-#include "ToluaInterface.h"
-
-namespace orxonox // tolua_export
-{ // tolua_export
- class LuaFunctor; // tolua_export
-
- //! callback class that executes lua code
- class _CoreExport LuaFunctor
- {
- public:
- LuaFunctor(const std::string& code, LuaState* luaState);
- void operator()();
-
- private:
- std::string code_;
- LuaState* lua_;
- };
-
-
- /**
- @brief
- Representation of an interface to lua
- */
- class _CoreExport LuaState // tolua_export
- { // tolua_export
- public:
- LuaState();
- ~LuaState();
-
- bool doFile(const std::string& filename); // tolua_export
- bool doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
-
- bool includeFile(const std::string& filename); // tolua_export
- bool includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
-
- void luaPrint(const std::string& str); // tolua_export
- void luaLog(unsigned int level, const std::string& message); // tolua_export
- bool fileExists(const std::string& filename); // tolua_export
- std::string getSourceCode(const std::string& filename); // tolua_export
-
- const std::stringstream& getOutput() const { return output_; }
- void clearOutput() { output_.clear(); } // tolua_export
-
- void setIncludeParser(std::string (*function)(const std::string&)) { includeParseFunction_ = function; }
- lua_State* getInternalLuaState() { return luaState_; }
-
- void setDefaultResourceInfo(const shared_ptr<ResourceInfo>& sourceFileInfo) { this->sourceFileInfo_ = sourceFileInfo; }
- const shared_ptr<ResourceInfo>& getDefaultResourceInfo() { return this->sourceFileInfo_; }
-
- LuaFunctor* createLuaFunctor(const std::string& code) { return new LuaFunctor(code, this); } // tolua_export
- //! Tells about whether IOConsole was activated. The Lua debugger only works with a normal console.
- bool usingIOConsole() const; // tolua_export
-
- static bool addToluaInterface(int (*function)(lua_State*), const std::string& name);
- static bool removeToluaInterface(const std::string& name);
- static void openToluaInterfaces(lua_State* state);
- static void closeToluaInterfaces(lua_State* state);
-
- static const std::string ERROR_HANDLER_NAME;
-
- private:
- shared_ptr<ResourceInfo> getFileInfo(const std::string& filename);
-
-#if LUA_VERSION_NUM != 501
- struct LoadS
- {
- const char* s;
- size_t size;
- };
-
- static const char * lua_Chunkreader(lua_State *L, void *data, size_t *size);
-#endif
-
- std::stringstream output_;
- lua_State* luaState_;
- bool bIsRunning_;
- shared_ptr<ResourceInfo> sourceFileInfo_;
- std::map<std::string, std::string> sourceCodeMap_;
- std::string (*includeParseFunction_)(const std::string&);
-
- typedef std::map<std::string, int (*)(lua_State *L)> ToluaInterfaceMap;
- static ToluaInterfaceMap toluaInterfaces_s;
- static std::vector<LuaState*> instances_s;
- }; // tolua_export
-} // tolua_export
-
-#endif /* _LuaState_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/MemoryArchive.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/MemoryArchive.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/MemoryArchive.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,141 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-#include "MemoryArchive.h"
-
-#if OGRE_VERSION < 0x010600
-
-#include <OgreException.h>
-#include <boost/filesystem.hpp>
-#include <boost/version.hpp>
-
-// Boost 1.36 has some issues with deprecated functions that have been omitted
-#if (BOOST_VERSION == 103600)
-# define BOOST_HAS_BRANCH_PATH_FUNCTION has_parent_path
-#else
-# define BOOST_HAS_BRANCH_PATH_FUNCTION has_branch_path
-#endif
-
-namespace orxonox
-{
- using namespace Ogre;
-
- MemoryArchive::ArchiveMap MemoryArchive::archives_s;
-
- void MemoryArchive::load()
- {
- if (archives_s.find(this->getName()) == archives_s.end())
- OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, this->getName() + " - MemoryArchive not found.", "MemoryArchive");
- }
-
- DataStreamPtr MemoryArchive::open(const Ogre::String& filename) const
- {
- const FileMap& files = archives_s[this->getName()];
- FileMap::const_iterator itFile = files.find(filename);
- if (itFile == files.end())
- return DataStreamPtr();
- else
- return MemoryDataStreamPtr(new MemoryDataStream(itFile->second.first.get(), itFile->second.second));
- }
-
- void MemoryArchive::findFiles(const Ogre::String& pattern, bool bRecursive,
- bool bDirs, Ogre::StringVector* simpleList, Ogre::FileInfoList* detailList)
- {
- const FileMap& files = archives_s[this->getName()];
-
- for (FileMap::const_iterator it = files.begin(); it != files.end(); ++it)
- {
- boost::filesystem::path file = it->first;
- // Check pattern
- if (!StringUtil::match(file.string(), pattern, true))
- continue;
- if (bDirs)
- file = file.branch_path();
- if (file.empty())
- continue;
- if (file.BOOST_HAS_BRANCH_PATH_FUNCTION() && !bRecursive)
- continue;
- if (simpleList)
- simpleList->push_back(file.string());
- if (detailList)
- {
- FileInfo fi;
- fi.archive = this;
- fi.filename = file.string();
- fi.basename = file.leaf();
- fi.path = file.branch_path().string();
- fi.compressedSize = it->second.second;
- fi.uncompressedSize = it->second.second;
- detailList->push_back(fi);
- }
- }
- }
- StringVectorPtr MemoryArchive::list(bool recursive, bool dirs)
- {
- StringVectorPtr ret(new StringVector());
- findFiles("*", recursive, dirs, ret.getPointer(), 0);
- return ret;
- }
-
- FileInfoListPtr MemoryArchive::listFileInfo(bool recursive, bool dirs)
- {
- FileInfoListPtr ret(new FileInfoList());
- findFiles("*", recursive, dirs, 0, ret.getPointer());
- return ret;
- }
-
- StringVectorPtr MemoryArchive::find(const Ogre::String& pattern,
- bool recursive, bool dirs)
- {
- StringVectorPtr ret(new StringVector());
- findFiles(pattern, recursive, dirs, ret.getPointer(), 0);
- return ret;
- }
-
- FileInfoListPtr MemoryArchive::findFileInfo(const Ogre::String& pattern,
- bool recursive, bool dirs)
- {
- FileInfoListPtr ret(new FileInfoList());
- findFiles(pattern, recursive, dirs, 0, ret.getPointer());
- return ret;
- }
-
- bool MemoryArchive::exists(const Ogre::String& filename)
- {
- const FileMap& files = archives_s[this->getName()];
- return files.find(filename) != files.end();
- }
-
- const Ogre::String& MemoryArchiveFactory::getType(void) const
- {
- static std::string result("Memory");
- return result;
- }
-}
-
-#endif /* OGRE_VERSION < 0x010600 */
Deleted: code/forks/sandbox_light/src/libraries/core/MemoryArchive.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/MemoryArchive.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/MemoryArchive.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,106 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Management Resources
-*/
-
-#ifndef _MemoryArchive_H__
-#define _MemoryArchive_H__
-
-#include "CorePrereqs.h"
-#include <OgrePrerequisites.h>
-
-#if OGRE_VERSION < 0x010600
-
-#include <map>
-#include <OgreArchive.h>
-#include <OgreArchiveFactory.h>
-#include <boost/shared_array.hpp>
-
-namespace orxonox
-{
- /**
- @brief
- Provides a simple mechanism of 'memory mapped IO', but compatible for Ogre 1.4
-
- Files are stored as shared_array<char> in a static map with the archive names
- (imaging the different archives as resource locations). This map then contains
- yet another map with the actual files.
- If you want to know why we make such a fuss, contact GraphicsManager::upgradeToGraphics()
- for more information.
- */
- class MemoryArchive : public Ogre::Archive
- {
- public:
- MemoryArchive(const Ogre::String& name, const Ogre::String& archiveType) : Ogre::Archive(name, archiveType) { }
- ~MemoryArchive() { }
-
- bool isCaseSensitive(void) const { return true; }
-
- void load();
- void unload() { }
-
- Ogre::DataStreamPtr open(const Ogre::String& filename) const;
-
- Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false);
- Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false);
-
- Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true,
- bool dirs = false);
- Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true,
- bool dirs = false);
-
- bool exists(const Ogre::String& filename);
-
- static void addFile(const std::string& archiveName, const std::string& filename, shared_array<char> content, size_t size)
- { archives_s[archiveName][filename] = std::make_pair(content, size); }
-
- private:
- void findFiles(const Ogre::String& pattern, bool bRecursive,
- bool bDirs, Ogre::StringVector* simpleList, Ogre::FileInfoList* detailList);
-
- typedef std::map<std::string, std::pair<shared_array<char>, size_t> > FileMap;
- typedef std::map<std::string, FileMap> ArchiveMap;
- static ArchiveMap archives_s;
- };
-
- //! Specialisation of ArchiveFactory for MemoryArchive.
- class _CoreExport MemoryArchiveFactory : public Ogre::ArchiveFactory
- {
- public:
- const Ogre::String& getType(void) const;
- Ogre::Archive* createInstance(const Ogre::String& name) { return new MemoryArchive(name, "Memory"); }
- void destroyInstance(Ogre::Archive* arch) { delete arch; }
- };
-}
-
-#endif /* OGRE_VERSION < 0x010600 */
-
-#endif /* _MemoryArchive_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/MetaObjectList.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/MetaObjectList.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/MetaObjectList.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,103 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the MetaObjectList class.
-*/
-
-#include "MetaObjectList.h"
-
-#include "util/Debug.h"
-#include "Identifier.h"
-#include "ObjectListBase.h"
-
-namespace orxonox
-{
- // ###############################
- // ### MetaObjectListElement ###
- // ###############################
- /**
- @brief Destructor: Removes the ObjectListBaseElement from the ObjectListBase by linking next_ and prev_ of the ObjectListBaseElement.
- */
- MetaObjectListElement::~MetaObjectListElement()
- {
- COUT(5) << "*** MetaObjectList: Removing Object from " << this->list_->getIdentifier()->getName() << "-list." << std::endl;
- this->list_->notifyIterators(this->element_->objectBase_);
-
- if (this->element_->next_)
- this->element_->next_->prev_ = this->element_->prev_;
- else
- this->list_->last_ = this->element_->prev_; // If there is no next_, we deleted the last object and have to update the last_ pointer of the list
-
- if (this->element_->prev_)
- this->element_->prev_->next_ = this->element_->next_;
- else
- this->list_->first_ = this->element_->next_; // If there is no prev_, we deleted the first object and have to update the first_ pointer of the list
-
- delete this->element_;
- }
-
-
- // ###############################
- // ### MetaObjectList ###
- // ###############################
- /**
- @brief Constructor: Sets first_ to zero.
- */
- MetaObjectList::MetaObjectList()
- {
- this->first_ = 0;
- }
-
- /**
- @brief Destructor: Removes all elements from the list, causing them to remove the stored ObjectListElement from the ObjectList.
- */
- MetaObjectList::~MetaObjectList()
- {
- MetaObjectListElement* temp;
- while (this->first_)
- {
- temp = this->first_->next_;
- delete this->first_;
- this->first_ = temp;
- }
- }
-
- /**
- @brief Adds an ObjectList and an element of that list to the MetaObjectList.
- @param list The ObjectList wherein the element is
- @param element The element wherein the object is
- */
- void MetaObjectList::add(ObjectListBase* list, ObjectListBaseElement* element)
- {
- MetaObjectListElement* temp = this->first_;
- this->first_ = new MetaObjectListElement(list, element);
- this->first_->next_ = temp;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/MetaObjectList.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/MetaObjectList.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/MetaObjectList.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,86 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Object ObjectList
- @brief Declaration of the MetaObjectList class.
-
- The MetaObjectList is a single-linked list, containing all list-elements and their
- lists wherein the object, owning the MetaObjectList, is registered.
- This allows much faster deletion of objects because no iteration is needed.
-*/
-
-#ifndef _MetaObjectList_H__
-#define _MetaObjectList_H__
-
-#include "CorePrereqs.h"
-
-namespace orxonox
-{
- // ###############################
- // ### MetaObjectListElement ###
- // ###############################
- /// The list-element of the MetaObjectList
- class _CoreExport MetaObjectListElement
- {
- public:
- /**
- @brief Constructor: Creates the list-element with given list and element.
- */
- MetaObjectListElement(ObjectListBase* list, ObjectListBaseElement* element) : next_(0), element_(element), list_(list) {}
- ~MetaObjectListElement();
-
- MetaObjectListElement* next_; //!< The next Element in the list
- ObjectListBaseElement* element_; //!< The list element, containing the object
- ObjectListBase* list_; //!< The list, containing the element
- };
-
-
- // ###############################
- // ### MetaObjectList ###
- // ###############################
- /**
- @brief The MetaObjectList contains ObjectListBaseElements and their ObjectListBases.
-
- The MetaObjectList is a single-linked list, containing all list-elements and their
- lists wherein the object that owns the MetaObjectList is registered.
- This allows much faster deletion of objects because no iteration is needed.
- */
- class _CoreExport MetaObjectList
- {
- public:
- MetaObjectList();
- ~MetaObjectList();
- void add(ObjectListBase* list, ObjectListBaseElement* element);
-
- MetaObjectListElement* first_; //!< The first element in the list
- };
-}
-
-#endif /* _MetaObjectList_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Namespace.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Namespace.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Namespace.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,176 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "Namespace.h"
-
-#include <set>
-
-#include "NamespaceNode.h"
-#include "CoreIncludes.h"
-#include "XMLPort.h"
-#include "util/SubString.h"
-
-namespace orxonox
-{
- CreateFactory(Namespace);
-
- Namespace::Namespace(BaseObject* creator) : BaseObject(creator),
- bAutogeneratedFileRootNamespace_(false),
- bRoot_(false),
- operator_("or")
- {
- RegisterObject(Namespace);
- }
-
- Namespace::~Namespace()
- {
- if (this->bRoot_)
- for (std::set<NamespaceNode*>::iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); ++it)
- delete (*it);
- }
-
- void Namespace::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- SUPER(Namespace, XMLPort, xmlelement, mode);
-
- std::string name = this->getName();
- size_t pos = 0;
- while ((pos = name.find(',')) != std::string::npos)
- name.replace(pos, 1, " ");
- while ((pos = name.find(';')) != std::string::npos)
- name.replace(pos, 1, " ");
- while ((pos = name.find('\n')) != std::string::npos)
- name.replace(pos, 1, " ");
- while ((pos = name.find('\t')) != std::string::npos)
- name.replace(pos, 1, " ");
- SubString tokens(name, " ", "", false, '\\', true, '"', true, '\0', '\0', true, '\0');
- if (this->bRoot_)
- {
- this->representingNamespaces_.insert(new NamespaceNode(this->getName()));
- }
- else
- {
- for (unsigned int i = 0; i < tokens.size(); i++)
- {
- for (std::set<NamespaceNode*>::iterator it = this->getNamespace()->representingNamespaces_.begin(); it != this->getNamespace()->representingNamespaces_.end(); ++it)
- {
- std::set<NamespaceNode*> temp = (*it)->getNodeRelative(tokens[i]);
- this->representingNamespaces_.insert(temp.begin(), temp.end());
- }
- }
- }
-
- XMLPortParam(Namespace, "operator", setOperator, getOperator, xmlelement, mode);
- XMLPortParam(Namespace, "bAutogenerated", setAutogenerated, isAutogenerated, xmlelement, mode);
-
- if (this->bAutogeneratedFileRootNamespace_)
- {
- for (std::set<NamespaceNode*>::iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); ++it)
- {
- (*it)->setRoot(true);
- (*it)->setHidden(true);
- }
- }
-
- XMLPortObjectExtended(Namespace, BaseObject, "", loadObjects, saveObjects, xmlelement, mode, true, false);
- }
-
- void Namespace::loadObjects(BaseObject* object)
- {
- object->setNamespace(this);
- }
-
- const BaseObject* Namespace::saveObjects(unsigned int index) const
- {
- return 0; // todo
- }
-
- bool Namespace::includes(const Namespace* ns) const
- {
- for (std::set<NamespaceNode*>::const_iterator it1 = this->representingNamespaces_.begin(); it1 != this->representingNamespaces_.end(); ++it1)
- {
- for (std::set<NamespaceNode*>::const_iterator it2 = ns->representingNamespaces_.begin(); it2 != ns->representingNamespaces_.end(); ++it2)
- {
- if ((*it1)->includes(*it2))
- {
- if (this->operator_ == "or")
- return true;
-
- if (this->operator_ == "not")
- return false;
- }
- else
- {
- if (this->operator_ == "and")
- return false;
- }
- }
- }
-
- if (this->operator_ == "or")
- return false;
- else if (this->operator_ == "and")
- return true;
- else if (this->operator_ == "not")
- return true;
-
- return false;
- }
-
- std::string Namespace::toString() const
- {
- std::string output;
-
- int i = 0;
- for (std::set<NamespaceNode*>::const_iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); i++, ++it)
- {
- if (i > 0)
- output += " / ";
-
- output += (*it)->toString();
- }
-
- return output;
- }
-
- std::string Namespace::toString(const std::string& indentation) const
- {
- std::string output;
-
- int i = 0;
- for (std::set<NamespaceNode*>::const_iterator it = this->representingNamespaces_.begin(); it != this->representingNamespaces_.end(); i++, ++it)
- {
- if (i > 0)
- output += '\n';
-
- output += (*it)->toString(indentation);
- }
-
- return output;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Namespace.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Namespace.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Namespace.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,83 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup XML Loader
-*/
-
-#ifndef _Namespace_H__
-#define _Namespace_H__
-
-#include "CorePrereqs.h"
-
-#include <set>
-#include <string>
-#include "BaseObject.h"
-
-namespace orxonox
-{
- class Namespace : public BaseObject
- {
- public:
- Namespace(BaseObject* creator);
- virtual ~Namespace();
-
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
-
- void loadObjects(BaseObject* object);
- const BaseObject* saveObjects(unsigned int index) const;
-
- void setAutogenerated(bool bAutogenerated)
- { this->bAutogeneratedFileRootNamespace_ = bAutogenerated; }
- bool isAutogenerated() const
- { return this->bAutogeneratedFileRootNamespace_; }
-
- void setOperator(const std::string& op)
- { this->operator_ = op; }
- const std::string& getOperator() const
- { return this->operator_; }
-
- void setRoot(bool bRoot)
- { this->bRoot_ = bRoot; }
-
- bool includes(const Namespace* ns) const;
- bool isIncludedIn(const Namespace* ns) const { return ns->includes(this); }
-
- std::string toString() const;
- std::string toString(const std::string& indentation) const;
-
- private:
- std::set<NamespaceNode*> representingNamespaces_;
- bool bAutogeneratedFileRootNamespace_;
- bool bRoot_;
- std::string operator_;
- };
-}
-
-#endif /* _Namespace_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/NamespaceNode.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/NamespaceNode.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/NamespaceNode.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,174 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "NamespaceNode.h"
-#include "util/Debug.h"
-
-namespace orxonox
-{
- NamespaceNode::NamespaceNode(const std::string& name, NamespaceNode* parent)
- {
- this->name_ = name;
- this->parent_ = parent;
- this->bRoot_ = false;
- this->bHidden_ = false;
- }
-
- NamespaceNode::~NamespaceNode()
- {
- for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); )
- delete (it++)->second;
- }
-
- std::set<NamespaceNode*> NamespaceNode::getNodeRelative(const std::string& name)
- {
- std::set<NamespaceNode*> nodes;
-
- if (name.empty())
- {
- nodes.insert(this);
- }
- else
- {
- size_t pos = name.find("::");
- std::string firstPart = name;
- std::string secondPart;
-
- if (pos != std::string::npos)
- {
- firstPart = name.substr(0, pos);
- secondPart = name.substr(pos + 2, std::string::npos);
- }
-
- if (firstPart == "..")
- {
- if (this->bRoot_)
- {
- COUT(2) << "Warning: Can't go to enclosing namespace with '..' operator in namespace " << this->name_ << ", namespace is root." << std::endl;
- nodes = this->getNodeRelative(secondPart);
- }
- else if (!this->parent_)
- {
- COUT(2) << "Warning: Can't go to enclosing namespace with '..' operator in namespace " << this->name_ << ", no parent namespace set." << std::endl;
- nodes = this->getNodeRelative(secondPart);
- }
- else
- {
- nodes = this->parent_->getNodeRelative(secondPart);
- }
- }
- else if (name.find('@') != 0)
- {
- std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.find(firstPart);
- if (it == this->subnodes_.end())
- it = this->subnodes_.insert(this->subnodes_.begin(), std::pair<std::string, NamespaceNode*>(firstPart, new NamespaceNode(firstPart, this)));
-
- if (it->second->isHidden())
- {
- COUT(2) << "Warning: Subnamespace '" << firstPart << "' in namespace '" << this->name_ << "' is hidden and can't be accessed." << std::endl;
- nodes.insert(this);
- }
- else
- {
- nodes = it->second->getNodeRelative(secondPart);
- }
- }
- else
- {
- bool bFoundMatchingNamespace = false;
-
- for (std::map<std::string, NamespaceNode*>::iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
- {
- if (it->first.find(firstPart) == (it->first.size() - firstPart.size()))
- {
- std::set<NamespaceNode*> temp2 = it->second->getNodeRelative(secondPart);
- nodes.insert(temp2.begin(), temp2.end());
- bFoundMatchingNamespace = true;
- }
- }
-
- if (!bFoundMatchingNamespace)
- {
- COUT(2) << "Warning: No file included with name '" << firstPart.substr(1, std::string::npos) << "' at this part of the level file, using parent namespace instead." << std::endl;
- nodes = this->getNodeRelative(secondPart);
- }
- }
- }
-
- return nodes;
- }
-
- bool NamespaceNode::includes(const NamespaceNode* ns) const
- {
- if (ns == this)
- {
- return true;
- }
- else
- {
- for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
- if (it->second->includes(ns))
- return true;
- }
-
- return false;
- }
-
- std::string NamespaceNode::toString() const
- {
- std::string output = this->name_;
-
- if (this->subnodes_.size() > 0)
- {
- output += " (";
-
- int i = 0;
- for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); i++, ++it)
- {
- if (i > 0)
- output += ", ";
-
- output += it->second->toString();
- }
-
- output += ')';
- }
-
- return output;
- }
-
- std::string NamespaceNode::toString(const std::string& indentation) const
- {
- std::string output = (indentation + this->name_ + '\n');
-
- for (std::map<std::string, NamespaceNode*>::const_iterator it = this->subnodes_.begin(); it != this->subnodes_.end(); ++it)
- output += it->second->toString(indentation + " ");
-
- return output;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/NamespaceNode.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/NamespaceNode.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/NamespaceNode.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,73 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup XML Loader
-*/
-
-#ifndef _NamespaceNode_H__
-#define _NamespaceNode_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <set>
-#include <string>
-
-namespace orxonox
-{
- class NamespaceNode
- {
- public:
- NamespaceNode(const std::string& name, NamespaceNode* parent = 0);
- ~NamespaceNode();
-
- std::set<NamespaceNode*> getNodeRelative(const std::string& name);
-
- void setRoot(bool bRoot) { this->bRoot_ = bRoot; }
- void setHidden(bool bHidden) { this->bHidden_ = bHidden; }
-
- bool isRoot() const { return this->bRoot_; }
- bool isHidden() const { return this->bHidden_; }
-
- bool includes(const NamespaceNode*) const;
-
- std::string toString() const;
- std::string toString(const std::string& indentation) const;
-
- private:
- std::string name_;
- NamespaceNode* parent_;
- std::map<std::string, NamespaceNode*> subnodes_;
- bool bHidden_;
- bool bRoot_;
- };
-}
-
-#endif /* _NamespaceNode_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ObjectList.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ObjectList.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ObjectList.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,101 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup ObjectList Object-lists and iterators
- @ingroup Object
-*/
-
-/**
- @file
- @ingroup Object ObjectList
- @brief Definition of the ObjectList class, a wrapper of ObjectListBase.
-
- @ref orxonox::ObjectList "ObjectList<T>" is a wrapper of an @ref orxonox::ObjectListBase
- "ObjectListBase" of class @a T. Use @ref orxonox::ObjectListIterator "ObjectListIterator<T>"
- to iterate through the list.
-*/
-
-#ifndef _ObjectList_H__
-#define _ObjectList_H__
-
-#include "CorePrereqs.h"
-
-#include "Identifier.h"
-#include "ObjectListBase.h"
-#include "ObjectListIterator.h"
-
-namespace orxonox
-{
- // ###############################
- // ### ObjectList ###
- // ###############################
- /**
- @brief The ObjectList contains all objects of the given class.
-
- Wraps the ObjectListBase which contains all objects of type @a T. Use @ref ObjectListIterator
- "ObjectListIterator<T>" or its typedef ObjectList<T>::iterator to iterate through all objects
- in the list.
- */
- template <class T>
- class ObjectList
- {
- public:
- typedef ObjectListIterator<T> iterator;
-
- /// Returns an Iterator to the first element in the list.
- inline static ObjectListElement<T>* begin()
- {
- ObjectListBase* list = ClassIdentifier<T>::getIdentifier()->getObjects();
- return static_cast<ObjectListElement<T>*>(list->begin().element_);
- }
-
- /// Returns an Iterator to the element after the last element in the list.
- inline static ObjectListElement<T>* end()
- {
- ObjectListBase* list = ClassIdentifier<T>::getIdentifier()->getObjects();
- return static_cast<ObjectListElement<T>*>(list->end().element_);
- }
-
- /// Returns an Iterator to the last element in the list.
- inline static ObjectListElement<T>* rbegin()
- {
- ObjectListBase* list = ClassIdentifier<T>::getIdentifier()->getObjects();
- return static_cast<ObjectListElement<T>*>(list->rbegin().element_);
- }
-
- /// Returns an Iterator to the element before the first element in the list.
- inline static ObjectListElement<T>* rend()
- {
- ObjectListBase* list = ClassIdentifier<T>::getIdentifier()->getObjects();
- return static_cast<ObjectListElement<T>*>(list->rend().element_);
- }
- };
-}
-
-#endif /* _ObjectList_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ObjectListBase.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ObjectListBase.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ObjectListBase.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,103 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of the ObjectListBase class.
-*/
-
-#include "ObjectListBase.h"
-
-#include <set>
-#include "Identifier.h"
-#include "Iterator.h"
-#include "ObjectListIterator.h"
-
-namespace orxonox
-{
- /**
- @brief Constructor: Sets default values.
- */
- ObjectListBase::ObjectListBase(Identifier* identifier)
- {
- this->identifier_ = identifier;
- this->first_ = 0;
- this->last_ = 0;
- }
-
- /**
- @brief Destructor: Deletes all list-elements, but NOT THE OBJECTS.
- */
- ObjectListBase::~ObjectListBase()
- {
- ObjectListBaseElement* temp;
- while (this->first_)
- {
- temp = this->first_->next_;
- delete this->first_;
- this->first_ = temp;
- }
- }
-
- /**
- @brief Increases all Iterators that currently point on the given element (because it gets removed).
- @param object The object that gets removed
- */
- void ObjectListBase::notifyIterators(OrxonoxClass* object) const
- {
- for (std::vector<void*>::const_iterator it = this->iterators_.begin(); it != this->iterators_.end(); ++it)
- ((Iterator<OrxonoxClass>*)(*it))->incrementIfEqual(object);
- for (std::vector<void*>::const_iterator it = this->objectListIterators_.begin(); it != this->objectListIterators_.end(); ++it)
- ((ObjectListIterator<OrxonoxClass>*)(*it))->incrementIfEqual(object);
- }
-
- /**
- @brief Adds a new object to the end of the list.
- @param element The element to add
- @return The pointer to the new ObjectListBaseElement, needed by the MetaObjectList of the added object
- */
- ObjectListBaseElement* ObjectListBase::add(ObjectListBaseElement* element)
- {
- if (!this->last_)
- {
- // If the list is empty
- this->last_ = element;
- this->first_ = this->last_; // There's only one object in the list now
- }
- else
- {
- // If the list isn't empty
- ObjectListBaseElement* temp = this->last_;
- this->last_ = element;
- this->last_->prev_ = temp;
- temp->next_ = this->last_;
- }
-
- return this->last_;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/ObjectListBase.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ObjectListBase.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ObjectListBase.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,159 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Object ObjectList
- @brief Declaration of the ObjectListBase class which stores all objects of each class.
-
- orxonox::ObjectListBase is a double-linked list, used by @ref orxonox::Identifier "Identifiers"
- to store all objects of a given class. Newly created objects are added to the list through the
- @c RegisterObject() macro in the constructor.
-*/
-
-#ifndef _ObjectListBase_H__
-#define _ObjectListBase_H__
-
-#include "CorePrereqs.h"
-
-#include <vector>
-#include "OrxonoxClass.h"
-
-namespace orxonox
-{
- // ###############################
- // ### ObjectListBaseElement ###
- // ###############################
- /// The list-element of the ObjectListBase
- class _CoreExport ObjectListBaseElement
- {
- public:
- /**
- @brief Constructor: Creates the list-element with an object.
- @param objectBase The object to store
- */
- ObjectListBaseElement(OrxonoxClass* objectBase) : next_(0), prev_(0), objectBase_(objectBase) {}
-
- ObjectListBaseElement* next_; //!< The next element in the list
- ObjectListBaseElement* prev_; //!< The previous element in the list
- OrxonoxClass* objectBase_;
- };
-
-
- // ###############################
- // ### ObjectListElement ###
- // ###############################
- /// The list-element that actually contains the object
- template <class T>
- class ObjectListElement : public ObjectListBaseElement
- {
- public:
- ObjectListElement(T* object) : ObjectListBaseElement(static_cast<OrxonoxClass*>(object)), object_(object) {}
- T* object_; //!< The object
- };
-
-
- // ###############################
- // ### ObjectListBase ###
- // ###############################
- /**
- @brief The ObjectListBase contains all objects of a given class.
-
- The ObjectListBase is used by Identifiers to store all objects of their class.
- You can use Identifier::getObjects() to get the object-list from an Identifier.
- Use @ref Iterator "Iterator<T>" to iterate through them.
-
- Alternatively you can also use the static helper class @ref orxonox::ObjectList "ObjectList<T>"
- to get the list of all objects of type @a T. Use @ref ObjectListIterator "ObjectListIterator<T>"
- or @ref Iterator "Iterator<T>" to iterate through them.
- */
- class _CoreExport ObjectListBase
- {
- friend class MetaObjectListElement;
-
- public:
- ObjectListBase(Identifier* identifier);
- ~ObjectListBase();
-
- ObjectListBaseElement* add(ObjectListBaseElement* element);
-
- /// Helper struct, used to export an element and the list to an instance of Iterator.
- struct Export
- {
- Export(ObjectListBase* list, ObjectListBaseElement* element) : list_(list), element_(element) {}
- ObjectListBase* list_;
- ObjectListBaseElement* element_;
- };
-
- /// Returns a pointer to the first element in the list. Works only with Iterator.
- inline Export begin() { return ObjectListBase::Export(this, this->first_); }
- /// Returns a pointer to the element after the last element in the list. Works only with Iterator.
- inline Export end() { return ObjectListBase::Export(this, 0); }
- /// Returns a pointer to the last element in the list. Works only with Iterator.
- inline Export rbegin() { return ObjectListBase::Export(this, this->last_); }
- /// Returns a pointer to the element in front of the first element in the list. Works only with Iterator.
- inline Export rend() { return ObjectListBase::Export(this, 0); }
-
- inline void registerIterator(void* iterator) { this->iterators_.push_back(iterator); }
- inline void unregisterIterator(void* iterator)
- {
- for (unsigned int i = 0; i < this->iterators_.size(); ++i)
- {
- if (iterators_[i] == iterator)
- {
- iterators_.erase(iterators_.begin() + i);
- break;
- }
- }
- }
- inline void registerObjectListIterator(void* iterator) { this->objectListIterators_.push_back(iterator); }
- inline void unregisterObjectListIterator(void* iterator)
- {
- for (unsigned int i = 0; i < this->objectListIterators_.size(); ++i)
- {
- if (objectListIterators_[i] == iterator)
- {
- objectListIterators_.erase(objectListIterators_.begin() + i);
- break;
- }
- }
- }
- void notifyIterators(OrxonoxClass* object) const;
-
- inline Identifier* getIdentifier() const { return this->identifier_; }
-
- private:
- Identifier* identifier_; //!< The Iterator owning this list
- ObjectListBaseElement* first_; //!< The first element in the list
- ObjectListBaseElement* last_; //!< The last element in the list
- std::vector<void*> iterators_; //!< A list of Iterators pointing on an element in this list
- std::vector<void*> objectListIterators_; //!< A list of ObjectListIterators pointing on an element in this list
- };
-}
-
-#endif /* _ObjectListBase_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ObjectListIterator.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ObjectListIterator.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ObjectListIterator.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,236 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Object ObjectList
- @brief Definition of the ObjectListIterator class, used to iterate through object-lists.
-
- @anchor ObjectListIteratorExample
-
- @ref orxonox::ObjectListIterator "ObjectListIterator<T>" allows to iterate through
- @ref orxonox::ObjectList "ObjectList<T>", containing all objects of type @a T. In contrast to
- @ref orxonox::Iterator "Iterator<T>", this iterator is limited to the object-list of type @a T.
- It is, however, much faster as it doesn't need a @c dynamic_cast.
-
- Usage:
- @code
- for (ObjectListIterator<myClass> it = ObjectList<myClass>::begin(); it != ObjectList<myClass>::end(); ++it)
- {
- it->someFunction(...);
- myClass* myObject = *it;
- }
- @endcode
-
- @note @ref orxonox::ObjectList::iterator "ObjectList<T>::iterator" is identical to
- @ref orxonox::ObjectListIterator "ObjectListIterator<T>" (it's just a typedef).
-*/
-
-#ifndef _ObjectListIterator_H__
-#define _ObjectListIterator_H__
-
-#include "CorePrereqs.h"
-#include "Identifier.h"
-#include "ObjectList.h"
-
-namespace orxonox
-{
- /**
- @brief ObjectListIterator<T> allows to iterate through the ObjectList of class @a T.
-
- @see See @ref ObjectListIteratorExample "ObjectListIterator.h" for more information an example.
- */
- template <class T>
- class ObjectListIterator
- {
- template <class I>
- friend class Iterator;
-
- public:
- /**
- @brief Constructor: Sets the element, whereon the ObjectListIterator points, to zero.
- */
- inline ObjectListIterator()
- {
- this->element_ = 0;
- ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
- }
-
- /**
- @brief Constructor: Sets this element to a given element.
- @param element The element to start with
- */
- inline ObjectListIterator(ObjectListElement<T>* element)
- {
- this->element_ = element;
- ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
- }
-
- /**
- @brief Constructor: Sets this element to the element of another ObjectListIterator.
- @param other The other ObjectListIterator
- */
- inline ObjectListIterator(const ObjectListIterator<T>& other)
- {
- this->element_ = other.element_;
- ClassIdentifier<T>::getIdentifier()->getObjects()->registerObjectListIterator(this);
- }
-
- /**
- @brief Unregisters the ObjectListIterator from the ObjectList.
- */
- inline ~ObjectListIterator()
- {
- ClassIdentifier<T>::getIdentifier()->getObjects()->unregisterObjectListIterator(this);
- }
-
- /**
- @brief Assigns an ObjectListElement.
- @param element The ObjectListElement
- */
- inline ObjectListIterator<T>& operator=(ObjectListElement<T>* element)
- {
- this->element_ = element;
- return (*this);
- }
-
- /**
- @brief Assigns the element of another ObjectListIterator.
- @param other The other ObjectListIterator
- */
- inline ObjectListIterator<T>& operator=(const ObjectListIterator<T>& other)
- {
- this->element_ = other.element_;
- return (*this);
- }
-
- /**
- @brief Overloading of the ++it operator: ObjectListIterator points to the next object in the list.
- @return The ObjectListIterator itself
- */
- inline const ObjectListIterator<T>& operator++()
- {
- this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
- return *this;
- }
-
- /**
- @brief Overloading of the it++ operator: ObjectListIterator points to the next object in the list.
- @return The ObjectListIterator itself
- */
- inline ObjectListIterator<T> operator++(int)
- {
- ObjectListIterator<T> copy = *this;
- this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
- return copy;
- }
-
- /**
- @brief Overloading of the --it operator: ObjectListIterator points to the previous object in the list.
- @return The ObjectListIterator itself
- */
- inline const ObjectListIterator<T>& operator--()
- {
- this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
- return *this;
- }
-
- /**
- @brief Overloading of the it-- operator: ObjectListIterator points to the previous object in the list.
- @return The ObjectListIterator itself
- */
- inline ObjectListIterator<T> operator--(int i)
- {
- ObjectListIterator<T> copy = *this;
- this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
- return copy;
- }
-
- /**
- @brief Overloading of the *it operator: returns the pointer to the object.
- @return The object the ObjectListIterator points at
- */
- inline T* operator*() const
- {
- return this->element_->object_;
- }
-
- /**
- @brief Overloading of the it-> operator: returns the pointer to the object.
- @return The object the ObjectListIterator points at
- */
- inline T* operator->() const
- {
- return this->element_->object_;
- }
-
- /**
- @brief Overloading of the typecast-operator to bool: returns true if the ObjectListIterator points to an existing object.
- @return True if the ObjectListIterator points to an existing object.
- */
- inline operator bool() const
- {
- return (this->element_ != 0);
- }
-
- /**
- @brief Overloading of the == operator to compare with another ObjectListIterator.
- @param compare The other ObjectListIterator
- @return True if the ObjectListIterator point to the same element
- */
- inline bool operator==(const ObjectListIterator<T>& compare) const
- {
- return (this->element_ == compare.element_);
- }
-
- /**
- @brief Overloading of the != operator to compare with another ObjectListIterator.
- @param compare The other ObjectListIterator
- @return True if the ObjectListIterator point to different elements
- */
- inline bool operator!=(const ObjectListIterator<T>& compare) const
- {
- return (this->element_ != compare.element_);
- }
-
- /**
- @brief Increments the ObjectListIterator if it points at the given object.
- @param object The object to compare with
- */
- inline void incrementIfEqual(OrxonoxClass* object)
- {
- if (this->element_ && this->element_->objectBase_ == object)
- this->operator++();
- }
-
- private:
- ObjectListElement<T>* element_; //!< The element the iterator points at
- };
-}
-
-#endif /* _ObjectListIterator_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/OrxonoxClass.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/OrxonoxClass.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/OrxonoxClass.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,140 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Implementation of OrxonoxClass.
-*/
-
-#include "OrxonoxClass.h"
-
-#include <cassert>
-#include "MetaObjectList.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- /**
- @brief Constructor: Sets the default values.
- */
- OrxonoxClass::OrxonoxClass()
- {
- this->identifier_ = 0;
- this->parents_ = 0;
- this->metaList_ = new MetaObjectList();
- this->referenceCount_ = 0;
- this->requestedDestruction_ = false;
- // Optimisation
- this->objectPointers_.reserve(6);
- }
-
- /**
- @brief Destructor: Removes the object from the object-lists, notifies all DestructionListener (for example @ref WeakPtr "weak pointers") that this object is being deleted.
- */
- OrxonoxClass::~OrxonoxClass()
- {
-// if (!this->requestedDestruction_)
-// COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ')' << std::endl;
-
- assert(this->referenceCount_ <= 0);
-
- this->unregisterObject();
-
- // parents_ exists only if isCreatingHierarchy() of the associated Identifier returned true while creating the class
- if (this->parents_)
- delete this->parents_;
-
- // notify all destruction listeners
- for (std::set<DestructionListener*>::iterator it = this->destructionListeners_.begin(); it != this->destructionListeners_.end(); )
- (*(it++))->objectDeleted();
- }
-
- /**
- @brief Deletes the object if no @ref orxonox::SmartPtr "smart pointers" point to this object. Otherwise schedules the object to be deleted as soon as possible.
- */
- void OrxonoxClass::destroy()
- {
- assert(this); // Just in case someone tries to delete a NULL pointer
- this->requestedDestruction_ = true;
- if (this->referenceCount_ == 0)
- {
- this->preDestroy();
- if (this->referenceCount_ == 0)
- delete this;
- }
- }
-
- /**
- @brief Removes this object from the object-lists.
- */
- void OrxonoxClass::unregisterObject()
- {
- if (this->metaList_)
- delete this->metaList_;
- this->metaList_ = 0;
- }
-
- /// Returns true if the object's class is of the given type or a derivative.
- bool OrxonoxClass::isA(const Identifier* identifier)
- { return this->getIdentifier()->isA(identifier); }
- /// Returns true if the object's class is exactly of the given type.
- bool OrxonoxClass::isExactlyA(const Identifier* identifier)
- { return this->getIdentifier()->isExactlyA(identifier); }
- /// Returns true if the object's class is a child of the given type.
- bool OrxonoxClass::isChildOf(const Identifier* identifier)
- { return this->getIdentifier()->isChildOf(identifier); }
- /// Returns true if the object's class is a direct child of the given type.
- bool OrxonoxClass::isDirectChildOf(const Identifier* identifier)
- { return this->getIdentifier()->isDirectChildOf(identifier); }
- /// Returns true if the object's class is a parent of the given type.
- bool OrxonoxClass::isParentOf(const Identifier* identifier)
- { return this->getIdentifier()->isParentOf(identifier); }
- /// Returns true if the object's class is a direct parent of the given type.
- bool OrxonoxClass::isDirectParentOf(const Identifier* identifier)
- { return this->getIdentifier()->isDirectParentOf(identifier); }
-
-
- /// Returns true if the object's class is of the given type or a derivative.
- bool OrxonoxClass::isA(const OrxonoxClass* object)
- { return this->getIdentifier()->isA(object->getIdentifier()); }
- /// Returns true if the object's class is exactly of the given type.
- bool OrxonoxClass::isExactlyA(const OrxonoxClass* object)
- { return this->getIdentifier()->isExactlyA(object->getIdentifier()); }
- /// Returns true if the object's class is a child of the given type.
- bool OrxonoxClass::isChildOf(const OrxonoxClass* object)
- { return this->getIdentifier()->isChildOf(object->getIdentifier()); }
- /// Returns true if the object's class is a direct child of the given type.
- bool OrxonoxClass::isDirectChildOf(const OrxonoxClass* object)
- { return this->getIdentifier()->isDirectChildOf(object->getIdentifier()); }
- /// Returns true if the object's class is a parent of the given type.
- bool OrxonoxClass::isParentOf(const OrxonoxClass* object)
- { return this->getIdentifier()->isParentOf(object->getIdentifier()); }
- /// Returns true if the object's class is a direct child of the given type.
- bool OrxonoxClass::isDirectParentOf(const OrxonoxClass* object)
- { return this->getIdentifier()->isDirectParentOf(object->getIdentifier()); }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/OrxonoxClass.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/OrxonoxClass.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/OrxonoxClass.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,207 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup OrxonoxClass OrxonoxClass
- @ingroup Class
-*/
-
-/**
- @file
- @ingroup Class OrxonoxClass
- @brief Declaration of OrxonoxClass, the base class of all objects and interfaces in Orxonox.
-
- All objects and interfaces of the game-logic (not the engine) are derived from OrxonoxClass.
- It stores the Identifier and the MetaObjectList and has all needed functions to create and use the class-hierarchy.
-*/
-
-#ifndef _OrxonoxClass_H__
-#define _OrxonoxClass_H__
-
-#include "CorePrereqs.h"
-#include "Super.h"
-
-#include <set>
-#include <vector>
-
-/**
- at def CCOUT
- Acts almost exactly like COUT(x), but prepends "ClassName: "
-*/
-#define CCOUT(level) \
- COUT(level) << this->getIdentifier()->getName() << ": "
-
-namespace orxonox
-{
- /**
- @brief The class all objects and interfaces of the game-logic (not the engine) are derived from.
-
- The BaseObject and Interfaces are derived with @c virtual @c public @c OrxonoxClass from OrxonoxClass.
- OrxonoxClass is needed to create the class-hierarchy at startup and to store the Identifier and the
- MetaObjectList, as well as to provide an interface for SmartPtr and WeakPtr.
- */
- class _CoreExport OrxonoxClass
- {
- template <class T>
- friend class ClassIdentifier;
-
- template <class T>
- friend class SmartPtr;
-
- friend class DestructionListener;
-
- public:
- OrxonoxClass();
- virtual ~OrxonoxClass();
-
- void destroy();
- void unregisterObject();
-
- /// Function to collect the SetConfigValue-macro calls.
- void setConfigValues() {};
-
- /// Returns the Identifier of the object.
- inline Identifier* getIdentifier() const { return this->identifier_; }
-
- bool isA(const Identifier* identifier);
- bool isExactlyA(const Identifier* identifier);
- bool isChildOf(const Identifier* identifier);
- bool isDirectChildOf(const Identifier* identifier);
- bool isParentOf(const Identifier* identifier);
- bool isDirectParentOf(const Identifier* identifier);
-
- /// Returns true if the object's class is of the given type or a derivative.
- template <class B> inline bool isA(const SubclassIdentifier<B>* identifier)
- { return this->isA(*identifier); }
- /// Returns true if the object's class is exactly of the given type.
- template <class B> inline bool isExactlyA(const SubclassIdentifier<B>* identifier)
- { return this->isExactlyA(*identifier); }
- /// Returns true if the object's class is a child of the given type.
- template <class B> inline bool isChildOf(const SubclassIdentifier<B>* identifier)
- { return this->isChildOf(*identifier); }
- /// Returns true if the object's class is a direct child of the given type.
- template <class B> inline bool isDirectChildOf(const SubclassIdentifier<B>* identifier)
- { return this->isDirectChildOf(*identifier); }
- /// Returns true if the object's class is a parent of the given type.
- template <class B> inline bool isParentOf(const SubclassIdentifier<B>* identifier)
- { return this->isParentOf(*identifier); }
- /// Returns true if the object's class is a direct parent of the given type.
- template <class B> inline bool isDirectParentOf(const SubclassIdentifier<B>* identifier)
- { return this->isDirectParentOf(*identifier); }
-
- bool isA(const OrxonoxClass* object);
- bool isExactlyA(const OrxonoxClass* object);
- bool isChildOf(const OrxonoxClass* object);
- bool isDirectChildOf(const OrxonoxClass* object);
- bool isParentOf(const OrxonoxClass* object);
- bool isDirectParentOf(const OrxonoxClass* object);
-
- virtual void clone(OrxonoxClass*& item) {}
-
- /// Returns the number of @ref orxonox::SmartPtr "smart pointers" that point to this object.
- inline unsigned int getReferenceCount() const
- { return this->referenceCount_; }
-
- /**
- @brief
- Returns a valid pointer of any derived type that is
- registered in the class hierarchy.
- @return
- Returns NULL if the no pointer was found.
- */
- FORCEINLINE void* getDerivedPointer(unsigned int classID)
- {
- for (int i = this->objectPointers_.size() - 1; i >= 0; --i)
- {
- if (this->objectPointers_[i].first == classID)
- return this->objectPointers_[i].second;
- }
- return NULL;
- }
-
- /// Version of getDerivedPointer with template
- template <class T> FORCEINLINE T* getDerivedPointer(unsigned int classID)
- { return static_cast<T*>(this->getDerivedPointer(classID)); }
- /// Const version of getDerivedPointer with template
- template <class T> FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
- { return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID); }
-
- protected:
- /// This virtual function is called if destroy() is called and no SmartPtr points to this object. Used in some cases to create a new SmartPtr to prevent destruction.
- virtual void preDestroy() {}
-
- private:
- /// Increments the reference counter (for smart pointers).
- inline void incrementReferenceCount()
- { ++this->referenceCount_; }
- /// Decrements the reference counter (for smart pointers).
- inline void decrementReferenceCount()
- {
- --this->referenceCount_;
- if (this->referenceCount_ == 0 && this->requestedDestruction_)
- this->destroy();
- }
-
- /// Register a destruction listener (for example a weak pointer which points to this object).
- inline void registerDestructionListener(DestructionListener* pointer)
- { this->destructionListeners_.insert(pointer); }
- /// Unegister a destruction listener (for example a weak pointer which pointed to this object before).
- inline void unregisterDestructionListener(DestructionListener* pointer)
- { this->destructionListeners_.erase(pointer); }
-
- Identifier* identifier_; //!< The Identifier of the object
- std::set<const Identifier*>* parents_; //!< List of all parents of the object
- MetaObjectList* metaList_; //!< MetaObjectList, containing all ObjectLists and ObjectListElements the object is registered in
- int referenceCount_; //!< Counts the references from smart pointers to this object
- bool requestedDestruction_; //!< Becomes true after someone called delete on this object
- std::set<DestructionListener*> destructionListeners_; //!< All destruction listeners (for example weak pointers which point to this object and like to get notified if it dies)
-
- /// 'Fast map' that holds this-pointers of all derived types
- std::vector<std::pair<unsigned int, void*> > objectPointers_;
- };
-
- /**
- @brief This listener is used to inform weak pointers if an object of type OrxonoxClass gets destroyed.
- */
- class _CoreExport DestructionListener
- {
- friend class OrxonoxClass;
-
- protected:
- inline void registerAsDestructionListener(OrxonoxClass* object)
- { if (object) { object->registerDestructionListener(this); } }
- inline void unregisterAsDestructionListener(OrxonoxClass* object)
- { if (object) { object->unregisterDestructionListener(this); } }
-
- virtual void objectDeleted() = 0;
- };
-
- SUPER_FUNCTION(11, OrxonoxClass, clone, false);
-}
-
-#endif /* _OrxonoxClass_H__ */
Modified: code/forks/sandbox_light/src/libraries/core/PathConfig.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/PathConfig.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/PathConfig.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -75,9 +75,7 @@
PathConfig::PathConfig()
: rootPath_(*(new bf::path()))
, executablePath_(*(new bf::path()))
- , modulePath_(*(new bf::path()))
, dataPath_(*(new bf::path()))
- , externalDataPath_(*(new bf::path()))
, configPath_(*(new bf::path()))
, logPath_(*(new bf::path()))
, bDevRun_(false)
@@ -137,7 +135,6 @@
{
COUT(1) << "Running from the build tree." << std::endl;
PathConfig::bDevRun_ = true;
- modulePath_ = specialConfig::moduleDevDirectory;
}
else
{
@@ -152,14 +149,9 @@
if (rootPath_.empty())
ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
- // Module path is fixed as well
- modulePath_ = rootPath_ / specialConfig::defaultModulePath;
-
#else
// There is no root path, so don't set it at all
- // Module path is fixed as well
- modulePath_ = specialConfig::moduleInstallDirectory;
#endif
}
@@ -169,9 +161,7 @@
{
delete &rootPath_;
delete &executablePath_;
- delete &modulePath_;
delete &dataPath_;
- delete &externalDataPath_;
delete &configPath_;
delete &logPath_;
}
@@ -183,12 +173,6 @@
dataPath_ = specialConfig::dataDevDirectory;
configPath_ = specialConfig::configDevDirectory;
logPath_ = specialConfig::logDevDirectory;
-
- // Check for data path override by the command line
- if (!CommandLineParser::getArgument("externalDataPath")->hasDefaultValue())
- externalDataPath_ = CommandLineParser::getValue("externalDataPath").getString();
- else
- externalDataPath_ = specialConfig::externalDataDevDirectory;
}
else
{
@@ -250,46 +234,6 @@
}
}
- std::vector<std::string> PathConfig::getModulePaths()
- {
- std::vector<std::string> modulePaths;
-
- // We search for helper files with the following extension
- const std::string& moduleextension = specialConfig::moduleExtension;
- size_t moduleextensionlength = moduleextension.size();
-
- // Add that path to the PATH variable in case a module depends on another one
- std::string pathVariable(getenv("PATH"));
- putenv(const_cast<char*>(("PATH=" + pathVariable + ';' + modulePath_.string()).c_str()));
-
- // Make sure the path exists, otherwise don't load modules
- if (!boost::filesystem::exists(modulePath_))
- return modulePaths;
-
- boost::filesystem::directory_iterator file(modulePath_);
- boost::filesystem::directory_iterator end;
-
- // Iterate through all files
- while (file != end)
- {
- const std::string& filename = file->BOOST_LEAF_FUNCTION();
-
- // Check if the file ends with the exension in question
- if (filename.size() > moduleextensionlength)
- {
- if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
- {
- // We've found a helper file
- const std::string& library = filename.substr(0, filename.size() - moduleextensionlength);
- modulePaths.push_back((modulePath_ / library).file_string());
- }
- }
- ++file;
- }
-
- return modulePaths;
- }
-
/*static*/ std::string PathConfig::getRootPathString()
{
return getInstance().rootPath_.string() + '/';
@@ -305,11 +249,6 @@
return getInstance().dataPath_.string() + '/';
}
- /*static*/ std::string PathConfig::getExternalDataPathString()
- {
- return getInstance().externalDataPath_.string() + '/';
- }
-
/*static*/ std::string PathConfig::getConfigPathString()
{
return getInstance().configPath_.string() + '/';
@@ -319,9 +258,4 @@
{
return getInstance().logPath_.string() + '/';
}
-
- /*static*/ std::string PathConfig::getModulePathString()
- {
- return getInstance().modulePath_.string() + '/';
- }
}
Modified: code/forks/sandbox_light/src/libraries/core/PathConfig.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/PathConfig.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/PathConfig.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -84,18 +84,12 @@
//! Returns the path to the data files as boost::filesystem::path
static const boost::filesystem::path& getDataPath()
{ return getInstance().dataPath_; }
- //! Returns the path to the external data files as boost::filesystem::path
- static const boost::filesystem::path& getExternalDataPath()
- { return getInstance().externalDataPath_; }
//! Returns the path to the config files as boost::filesystem::path
static const boost::filesystem::path& getConfigPath()
{ return getInstance().configPath_; }
//! Returns the path to the log files as boost::filesystem::path
static const boost::filesystem::path& getLogPath()
{ return getInstance().logPath_; }
- //! Returns the path to the modules as boost::filesystem::path
- static const boost::filesystem::path& getModulePath()
- { return getInstance().modulePath_; }
//! Returns the path to the root folder as std::string
static std::string getRootPathString();
@@ -103,14 +97,10 @@
static std::string getExecutablePathString();
//! Returns the path to the data files as std::string
static std::string getDataPathString();
- //! Returns the path to the external data files as std::string
- static std::string getExternalDataPathString();
//! Returns the path to the config files as std::string
static std::string getConfigPathString(); //tolua_export
//! Returns the path to the log files as std::string
static std::string getLogPathString();
- //! Returns the path to the modules as std::string
- static std::string getModulePathString();
//! Return trrue for runs in the build directory (not installed)
static bool isDevelopmentRun() { return getInstance().bDevRun_; }
@@ -125,15 +115,11 @@
GeneralException
*/
void setConfigurablePaths();
- //! Returns a list with all modules declared by a *.module file in the module folder.
- std::vector<std::string> getModulePaths();
//! Path to the parent directory of the ones above if program was installed with relativ paths
boost::filesystem::path& rootPath_;
boost::filesystem::path& executablePath_; //!< Path to the executable
- boost::filesystem::path& modulePath_; //!< Path to the modules
boost::filesystem::path& dataPath_; //!< Path to the data files folder
- boost::filesystem::path& externalDataPath_; //!< Path to the external data files folder
boost::filesystem::path& configPath_; //!< Path to the config files folder
boost::filesystem::path& logPath_; //!< Path to the log files folder
Deleted: code/forks/sandbox_light/src/libraries/core/Resource.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Resource.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Resource.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,116 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-#include "Resource.h"
-
-#include <boost/filesystem/path.hpp>
-#include <OgreException.h>
-#include <OgreFileSystem.h>
-#include <OgreResourceGroupManager.h>
-
-namespace orxonox
-{
- std::string Resource::DEFAULT_GROUP(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
-
- DataStreamPtr Resource::open(const std::string& name)
- {
- return Ogre::ResourceGroupManager::getSingleton().openResource(name,
- Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
- }
-
- DataStreamListPtr Resource::openMulti(const std::string& pattern)
- {
- DataStreamListPtr resources(new Ogre::DataStreamList());
- const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
- for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it)
- {
- DataStreamListPtr temp = Ogre::ResourceGroupManager::getSingleton().openResources(pattern, *it);
- resources->insert(resources->end(), temp->begin(), temp->end());
- }
- return resources;
- }
-
- bool Resource::exists(const std::string& name)
- {
- try
- {
- Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name);
- return true;
- }
- catch (const Ogre::Exception&)
- {
- return false;
- }
- }
-
- shared_ptr<ResourceInfo> Resource::getInfo(const std::string& name)
- {
- std::string group;
- try
- {
- group = Ogre::ResourceGroupManager::getSingleton().findGroupContainingResource(name);
- }
- catch (const Ogre::Exception&)
- {
- return shared_ptr<ResourceInfo>();
- }
- Ogre::FileInfoListPtr infos = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo(group, name);
- for (Ogre::FileInfoList::const_iterator it = infos->begin(); it != infos->end(); ++it)
- {
- if (it->filename == name)
- {
- shared_ptr<ResourceInfo> ptr(new ResourceInfo());
- ptr->filename = name;
- ptr->path = it->path;
- ptr->basename = it->basename;
- ptr->group = group;
- ptr->size = it->uncompressedSize;
- if (dynamic_cast<Ogre::FileSystemArchive*>(it->archive) != NULL)
- {
- boost::filesystem::path base(it->archive->getName());
- base /= it->filename;
- ptr->fileSystemPath = base.string();
- }
- return ptr;
- }
- }
- return shared_ptr<ResourceInfo>();
- }
-
- StringVectorPtr Resource::findResourceNames(const std::string& pattern)
- {
- StringVectorPtr resourceNames(new Ogre::StringVector());
- const Ogre::StringVector& groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
- for (Ogre::StringVector::const_iterator it = groups.begin(); it != groups.end(); ++it)
- {
- StringVectorPtr temp = Ogre::ResourceGroupManager::getSingleton().findResourceNames(*it, pattern);
- resourceNames->insert(resourceNames->end(), temp->begin(), temp->end());
- }
- return resourceNames;
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Resource.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Resource.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Resource.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,148 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Resources Resources
- @ingroup Management
-*/
-
-/**
- @file
- @ingroup Management Resources
-*/
-
-#ifndef _Core_Resource_H__
-#define _Core_Resource_H__
-
-#include "CorePrereqs.h"
-
-#include <boost/shared_ptr.hpp>
-#include <OgreDataStream.h>
-#include <OgreStringVector.h>
-
-namespace orxonox
-{
- // Import the Ogre::DataStreamList
- using Ogre::DataStreamList;
- using Ogre::DataStreamListPtr;
- using Ogre::StringVector;
- using Ogre::StringVectorPtr;
-
- //! Stores basic information about a Resource from Ogre
- struct ResourceInfo
- {
- //! The file's fully qualified name
- std::string filename;
- //! Path name; separated by '/' and ending with '/'
- std::string path;
- //! Base filename
- std::string basename;
- //! Resource group the file is in
- std::string group;
- //! Uncompressed size
- size_t size;
- //! Absolute file path ("" for files not on filesystem)
- std::string fileSystemPath;
- };
-
- /** Provides simple functions to easily access the Ogre::ResourceGroupManager.
- The wrapper functions also avoid having to deal with resource groups.
- */
- class _CoreExport Resource
- {
- // Docs by Ogre::ResourceGroupManager.h
- public:
- /**
- @brief
- Open a single resource by name and return a DataStream
- pointing at the source of the data.
- @param name
- The name of the resource to locate.
- Even if resource locations are added recursively, you
- must provide a fully qualified name to this method.
- @return
- Shared pointer to data stream containing the data. Will be
- destroyed automatically when no longer referenced.
- */
- static DataStreamPtr open(const std::string& name);
-
- //! Similar to open(string, string, bool), but with a fileInfo struct
- static DataStreamPtr open(shared_ptr<ResourceInfo> fileInfo)
- {
- return open(fileInfo->filename);
- }
-
- /**
- @brief
- Open all resources matching a given pattern (which can contain
- the character '*' as a wildcard), and return a collection of
- DataStream objects on them.
- @param pattern
- The pattern to look for. If resource locations have been
- added recursively, subdirectories will be searched too so this
- does not need to be fully qualified.
- @return
- Shared pointer to a data stream list , will be
- destroyed automatically when no longer referenced
- */
- static DataStreamListPtr openMulti(const std::string& pattern);
-
- /**
- Find out if the named file exists.
- @param name
- Fully qualified name of the file to test for
- */
- static bool exists(const std::string& name);
-
- /**
- Get struct with information about path and size.
- @param name
- Fully qualified name of the file to test for
- */
- static shared_ptr<ResourceInfo> getInfo(const std::string& name);
-
- /**
- Retrieves a list with all resources matching a certain pattern.
- @param pattern
- The pattern to look for. If resource locations have been
- added recursively, subdirectories will be searched too so this
- does not need to be fully qualified.
- */
- static StringVectorPtr findResourceNames(const std::string& pattern);
-
- //! Name of the default resource group (usually "General")
- static std::string DEFAULT_GROUP;
-
- private:
- Resource();
- ~Resource();
- Resource(const Resource& instance);
- };
-}
-
-#endif /* _Core_Resource_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/SmartPtr.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/SmartPtr.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/SmartPtr.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,317 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-// Inspired by boost::intrusive_ptr by Peter Dimov
-
-/**
- @defgroup SmartPtr SmartPtr<T> and WeakPtr<T>
- @ingroup Object
-*/
-
-/**
- @file
- @ingroup Object SmartPtr
- @brief Definition of SmartPtr<T>, wraps a pointer to an object and keeps it alive.
-
- @anchor SmartPtrExample
-
- orxonox::SmartPtr is an implementation of a smart pointer - it wraps a pointer to an
- object and keeps this object alive until no SmartPtr points to this object anymore.
- In contrast to orxonox::SharedPtr, SmartPtr works only with classes that are derived
- from orxonox::OrxonoxClass, because it's an intrusive implementation, meaning the
- reference counter is stored in the object itself.
-
- It's possible to use normal pointers and smart pointers to an object simultaneously.
- You don't have to use SmartPtr all the time, you can create a SmartPtr for an object
- at any time and also convert it back to a normal pointer if you like. This is possible
- because the reference counter is stored in the object itself and not in SmartPtr (in
- contrast to SharedPtr).
-
- @b Important: If you want to delete an object, you must not use @c delete @c object but
- rather @c object->destroy(). This function will check if there are smart pointers
- pointing to the object. If yes, the object will be kept alive until all smart pointes
- are destroyed. If no, the object is deleted instantly.
-
- If all smart pointers that point to an object are destroyed, but you never called
- @c object->destroy() before, the object will not be deleted! All a SmartPtr will do
- is to really just keep an object alive, but it will not delete it automatically
- unless you tried to destroy it before.
-
- Example:
- @code
- class MyClass // class declaration
- {
- public:
- void setObject(OtherClass* object) // passes a normal pointer which will be stored in a SmartPtr
- { this->object_ = object; }
-
- OtherClass* getObject() const // converts the SmartPtr to a normal pointer and returns it
- { return this->object_; }
-
- private:
- SmartPtr<OtherClass> object_; // a pointer to an instance of OtherClass is stored in a SmartPtr
- };
- @endcode
- In this example we assume that OtherClass is a child of OrxonoxClass. We don't care
- about the inheritance of MyClass though.
-
- Now we create an instance of MyClass and assign a pointer to an instance of OtherClass:
- @code
- MyClass* myclass = new MyClass(); // create an instance of MyClass
- OtherClass* object = new OtherClass(); // create an instance of OtherClass
- myclass->setObject(object); // the object is now stored in a SmartPtr inside myclass
-
- object->destroy(); // we try to destroy object, but there's still a SmartPtr pointing at it.
-
- # object still exists at this point (because a SmartPtr points at it)
-
- delete myclass; // now we delete myclass, which also destroys the SmartPtr
-
- # object doesn't exist anymore (because the SmartPtr is now destroyed)
- @endcode
-
- Now we look at the same example, but we first delete myclass, then destroy object:
- @code
- MyClass* myclass = new MyClass(); // create an instance of MyClass
- OtherClass* object = new OtherClass(); // create an instance of OtherClass
- myclass->setObject(object); // the object is now stored in a SmartPtr inside myclass
-
- delete myclass; // we delete myclass, which also destroys the SmartPtr
-
- # object still exists at this point (because destroy() was not called yet)
-
- object->destroy(); // now we try to destroy object, which works instantly
-
- # object doesn't exist anymore (because we just destroyed it)
- @endcode
-
- Note that in any case @c object->destroy() has to be called to delete the object.
- However if a SmartPtr points at it, the destruction is delayed until all SmartPtr
- are destroyed.
-*/
-
-#ifndef _SmartPtr_H__
-#define _SmartPtr_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-
-#include "Identifier.h"
-#include "OrxonoxClass.h"
-#include "WeakPtr.h"
-
-namespace orxonox
-{
- /**
- @brief A smart pointer which wraps a pointer to an object and keeps this object alive as long as the smart pointer exists.
-
- @see See @ref SmartPtrExample "this description" for more information and an example.
- */
- template <class T>
- class SmartPtr
- {
- public:
- /// Constructor: Initializes the smart pointer with a null pointer.
- inline SmartPtr() : pointer_(0), base_(0)
- {
- }
-
- /// Constructor: Used to explicitly initialize the smart pointer with a null pointer
- inline SmartPtr(int) : pointer_(0), base_(0)
- {
- }
-
- /// Constructor: Initializes the smart pointer with a pointer to an object. @param pointer The pointer @param bAddRef If true, the reference counter is increased. Don't set this to false unless you know exactly what you're doing! (for example to avoid circular references if the @c this pointer of the possessing object is stored)
- inline SmartPtr(T* pointer, bool bAddRef = true) : pointer_(pointer), base_(pointer)
- {
- if (this->base_ && bAddRef)
- this->base_->incrementReferenceCount();
- }
-
- /// Copy-constructor
- inline SmartPtr(const SmartPtr& other) : pointer_(other.pointer_), base_(other.base_)
- {
- if (this->base_)
- this->base_->incrementReferenceCount();
- }
-
- /// Copy-constructor for smart pointers to objects of another class.
- template <class O>
- inline SmartPtr(const SmartPtr<O>& other) : pointer_(other.get()), base_(other.base_)
- {
- if (this->base_)
- this->base_->incrementReferenceCount();
- }
-
- /// Constructor: Initializes the smart pointer with the pointer that is stored in a WeakPtr.
- template <class O>
- inline SmartPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.getBase())
- {
- if (this->base_)
- this->base_->incrementReferenceCount();
- }
-
- /// Destructor: Decrements the reference counter.
- inline ~SmartPtr()
- {
- if (this->base_)
- this->base_->decrementReferenceCount();
- }
-
- /// Used to assign a null pointer.
- inline SmartPtr& operator=(int)
- {
- SmartPtr(0).swap(*this);
- return *this;
- }
-
- /// Assigns a new pointer.
- inline SmartPtr& operator=(T* pointer)
- {
- SmartPtr(pointer).swap(*this);
- return *this;
- }
-
- /// Assigns the wrapped pointer of another SmartPtr.
- inline SmartPtr& operator=(const SmartPtr& other)
- {
- SmartPtr(other).swap(*this);
- return *this;
- }
-
- /// Assigns the wrapped pointer of a SmartPtr of another class
- template <class O>
- inline SmartPtr& operator=(const SmartPtr<O>& other)
- {
- SmartPtr(other).swap(*this);
- return *this;
- }
-
- /// Assigns the wrapped pointer of a WeakPtr.
- template <class O>
- inline SmartPtr& operator=(const WeakPtr<O>& other)
- {
- SmartPtr(other).swap(*this);
- return *this;
- }
-
- /// Returns the wrapped pointer as @c T*
- inline T* get() const
- {
- return this->pointer_;
- }
-
- /// Returns the wrapped pointer as @c OrxonoxClass*
- inline OrxonoxClass* getBase() const
- {
- return this->base_;
- }
-
- /// Implicitly converts the SmartPtr to a pointer of type @c T*
- inline operator T*() const
- {
- return this->pointer_;
- }
-
- /// Overloaded operator, returns a pointer to the stored object.
- inline T* operator->() const
- {
- assert(this->pointer_ != 0);
- return this->pointer_;
- }
-
- /// Overloaded operator, returns a reference to the stored object.
- inline T& operator*() const
- {
- assert(this->pointer_ != 0);
- return *this->pointer_;
- }
-
- /// Returns true if the wrapped pointer is NULL.
- inline bool operator!() const
- {
- return (this->pointer_ == 0);
- }
-
- /// Swaps the contents of two smart pointers.
- inline void swap(SmartPtr& other)
- {
- {
- T* temp = this->pointer_;
- this->pointer_ = other.pointer_;
- other.pointer_ = temp;
- }
- {
- OrxonoxClass* temp = this->base_;
- this->base_ = other.base_;
- other.base_ = temp;
- }
- }
-
- /// Resets the smart pointer (equivalent to assigning a NULL pointer).
- inline void reset()
- {
- SmartPtr().swap(*this);
- }
-
- private:
- T* pointer_; ///< The wrapped pointer to an object of type @a T
- OrxonoxClass* base_; ///< The wrapped pointer, casted up to OrxonoxClass (this is needed because with just a T* pointer, SmartPtr couln't be used with forward declarations)
- };
-
- /// Swaps the contents of two smart pointers.
- template <class T>
- void swap(SmartPtr<T>& a, SmartPtr<T>& b)
- {
- a.swap(b);
- }
-
- /// Uses a static_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new SmartPtr<T>.
- template <class T, class U>
- SmartPtr<T> static_pointer_cast(const SmartPtr<U>& p)
- {
- return static_cast<T*>(p.get());
- }
-
- /// Uses a const_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new SmartPtr<T>.
- template <class T, class U>
- SmartPtr<T> const_pointer_cast(const SmartPtr<U>& p)
- {
- return const_cast<T*>(p.get());
- }
-
- /// Uses a dynamic_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new SmartPtr<T>.
- template <class T, class U>
- SmartPtr<T> dynamic_pointer_cast(const SmartPtr<U>& p)
- {
- return orxonox_cast<T*>(p.get());
- }
-}
-
-#endif /* _SmartPtr_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/SubclassIdentifier.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/SubclassIdentifier.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/SubclassIdentifier.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,204 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Class Identifier
- @brief Definition of SubclassIdentifier.
-
- @anchor SubclassIdentifierExample
-
- SubclassIdentifier is a separated class, acting like an Identifier, but has a given class.
- You can only assign Identifiers of exactly the given class or of a derivative to a SubclassIdentifier.
-
- Example:
-
- You can assign an Identifier either through the constructor or by using the assignment @c operator=:
- @code
- SubclassIdentifier<BaseClass> identifier = Class(SubClass);
- @endcode
-
- The @c operator-> is overloaded an returns the assigned Identifier. That way you can just call
- functions of the assigned Identifier by using @c ->function():
- @code
- SubclassIdentifier<BaseClass> identifier = Class(SubClass);
- identifier->getName(); // returns "SubClass"
- @endcode
-
- There are two possibilities to create an object out of a SubclassIdentifier: Either you just use
- the @c fabricate() function of the assigned Identifier through the overloaded @c operator->, which
- returns a @c BaseObject* pointer, or you use the function of SubclassIdentifier, this time by using
- @c operator., which returns a @c BaseClass* pointer (@a BaseClass is the baseclass specified by the
- template argument):
- @code
- identifier->fabricate(); // calls Identifier::fabricate(), creates a SubClass, returns a BaseObject* pointer
-
- identifier.fabricate(); // calls SubclassIdentifier::fabricate(), creates a SubClass, returns a BaseClass* pointer
- @endcode
-*/
-
-#ifndef _SubclassIdentifier_H__
-#define _SubclassIdentifier_H__
-
-#include "CorePrereqs.h"
-
-#include <cstdlib>
-#include "util/Debug.h"
-#include "Identifier.h"
-
-namespace orxonox
-{
- // ###############################
- // ### SubclassIdentifier ###
- // ###############################
- /**
- @brief The SubclassIdentifier acts almost like an Identifier, but has some prerequisites.
-
- You can only assign an Identifier that belongs to a class T (or derived) to a SubclassIdentifier<T>.
- If you assign something else, the program prints an error.
-
- Because we know the base-type, a @c dynamic_cast is done, which makes it easier to create a new object.
-
- @see See @ref SubclassIdentifierExample "SubclassIdentifier.h" for some examples.
- */
- template <class T>
- class SubclassIdentifier
- {
- public:
- /// Constructor: Automaticaly assigns the Identifier of the given class.
- SubclassIdentifier()
- {
- this->identifier_ = ClassIdentifier<T>::getIdentifier();
- }
-
- /// Constructor: Assigns the given Identifier.
- SubclassIdentifier(Identifier* identifier)
- {
- this->operator=(identifier);
- }
-
- /// Copyconstructor: Assigns the identifier of another SubclassIdentifier.
- template <class O>
- SubclassIdentifier(const SubclassIdentifier<O>& identifier)
- {
- this->operator=(identifier.getIdentifier());
- }
-
- /**
- @brief Overloading of the = operator: assigns the identifier and checks its type.
- @param identifier The Identifier to assign
- @return The SubclassIdentifier itself
- */
- SubclassIdentifier<T>& operator=(Identifier* identifier)
- {
- if (!identifier || !identifier->isA(ClassIdentifier<T>::getIdentifier()))
- {
- COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
- if (identifier)
- {
- COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << '!' << std::endl;
- COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl;
- }
- else
- {
- COUT(1) << "Error: Can't assign NULL identifier" << std::endl;
- }
- }
- else
- {
- this->identifier_ = identifier;
- }
- return *this;
- }
-
- /// Overloading of the = operator: assigns the identifier of another SubclassIdentifier.
- template <class O>
- SubclassIdentifier<T>& operator=(const SubclassIdentifier<O>& identifier)
- {
- return this->operator=(identifier.getIdentifier());
- }
-
- /// Overloading of the * operator: returns the assigned identifier.
- inline Identifier* operator*() const
- {
- return this->identifier_;
- }
-
- /// Overloading of the -> operator: returns the assigned identifier.
- inline Identifier* operator->() const
- {
- return this->identifier_;
- }
-
- /// Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
- inline operator Identifier*() const
- {
- return this->identifier_;
- }
-
- /// Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
- T* fabricate(BaseObject* creator) const
- {
- BaseObject* newObject = this->identifier_->fabricate(creator);
-
- // Check if the creation was successful
- if (newObject)
- {
- return orxonox_cast<T*>(newObject);
- }
- else
- {
- // Something went terribly wrong
- if (this->identifier_)
- {
- COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
- COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << '!' << std::endl;
- COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl;
- }
- else
- {
- COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
- COUT(1) << "Error: Couldn't fabricate a new Object - Identifier is undefined." << std::endl;
- }
-
- COUT(1) << "Aborting..." << std::endl;
- abort();
- return 0;
- }
- }
-
- /// Returns the assigned identifier.
- inline Identifier* getIdentifier() const
- { return this->identifier_; }
-
- private:
- Identifier* identifier_; //!< The assigned identifier
- };
-}
-
-#endif /* _SubclassIdentifier_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Super.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Super.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Super.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,616 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Super Super
- @ingroup Class
-*/
-
-/**
- @file
- @ingroup Class Super
- @brief Definition of all super-function related macros, used to call functions of the base class.
-
- This file defines all macros needed to add a new "super-function". If you add
- a super-function, you can call <tt>SUPER(myclass, functionname, arguments)</tt>
- inside your code and the function of the parent-class gets called. This is comparable
- to <tt>super.functionname(arguments)</tt> in Java or other languages.
-
- This works only with virtual functions that return nothing (@c void) and belong to
- classes that have an @ref orxonox::Identifier "Identifier". Arguments however are
- supported, there's no limitation for their number and type, except that the type has
- to be known in Super.h.
-
- To add a new super-function, you have to process 4 steps:
-
- -# Add a new @c SUPER macro <br />
- This allows you to call the super-function in your code. <br />
- Location: This file (Super.h), marked with "--> HERE <--" comments (1/3)
- -# Call the @c SUPER_FUNCTION_GLOBAL_DECLARATION_PART1/2 macros. <br />
- This defines some global classes and templates, needed to create and call the super-functions. <br />
- Location: This file (Super.h), marked with "--> HERE <--" comments (2/3)
- -# Call the @c SUPER_INTRUSIVE_DECLARATION macro. <br />
- This will be included into the declaration of @c ClassIdentifier<T>. <br />
- Location: This file (Super.h), marked with "--> HERE <--" comments (3/3)
- -# Call the @c SUPER_FUNCTION macro. <br />
- This defines a partially specialized template that will decide if a class is "super" to another class.
- If the check returns true, a @c SuperFunctionCaller gets created, which will be used by the @c SUPER macro.
- You have to add this into the header-file of the baseclass of the super-function (the class that first
- implements the function), below the class declaration. You can't call it directly in this file, because
- otherwise you had to include the headerfile right here, which would cause some ugly back-dependencies,
- include loops and slower compilation. <br />
- Dont forget to include Super.h in the header-file. <br />
- Location: The header-file of the baseclass (Baseclass.h), below the class declaration
-*/
-
-#ifndef _Super_H__
-#define _Super_H__
-
-#include "CorePrereqs.h"
-
-#include "util/Debug.h"
-#include "Event.h"
-
-///////////////////////
-// Macro definitions //
-///////////////////////
-
-//// Common macros ////
-
- /**
- @brief Declares a new super-function by creating a specialized template. Add this below the class declaration of the baseclass.
- @param functionnumber Each super-function needs a unique number, starting with zero, increasing by one
- @param baseclass The baseclass of the super-function (~the root)
- @param functionname The name of the super-function
- @param purevirtualbase "true" if the function is pure virtual in the baseclass, "false" if the function is implemented (without "")
- */
- #define SUPER_FUNCTION(functionnumber, baseclass, functionname, purevirtualbase) \
- template <class T, int templatehack2> \
- struct SuperFunctionCondition<functionnumber, T, 0, templatehack2> \
- { \
- static void check() \
- { \
- SuperFunctionCondition<functionnumber, T, 0, templatehack2>::apply(static_cast<T*>(0)); \
- SuperFunctionCondition<functionnumber + 1, T, 0, templatehack2>::check(); \
- } \
- \
- static void apply(void* temp) {} \
- \
- static void apply(baseclass* temp) \
- { \
- ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier(); \
- for (std::set<const Identifier*>::iterator it = identifier->getDirectChildrenIntern().begin(); it != identifier->getDirectChildrenIntern().end(); ++it) \
- { \
- if (((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ && ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_) \
- { \
- delete ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_; \
- ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = 0; \
- ((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ = false; \
- } \
- \
- if (!((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_) \
- { \
- COUT(5) << "Added SuperFunctionCaller for " << #functionname << ": " << ClassIdentifier<T>::getIdentifier()->getName() << " <- " << ((ClassIdentifier<T>*)(*it))->getName() << std::endl; \
- ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_##functionname <T>; \
- } \
- } \
- } \
- }; \
- \
- SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND##purevirtualbase(functionnumber, baseclass)
-
- #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND0(functionnumber, baseclass) SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDfalse(functionnumber, baseclass)
- #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND1(functionnumber, baseclass) SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDtrue(functionnumber, baseclass)
- #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDfalse(functionnumber, baseclass)
- #define SUPER_FUNCTION_PUREVIRTUAL_WORKAROUNDtrue(functionnumber, baseclass) \
- template <int templatehack2> \
- struct SuperFunctionCondition<functionnumber, baseclass, 0, templatehack2> \
- { \
- static void check() \
- { \
- SuperFunctionCondition<functionnumber + 1, baseclass, 0, templatehack2>::check(); \
- } \
- };
-
-
- /*
- //// Comments about the macro ////
-
- // Partially specialized template (templatehack is now specialized too).
- //
- // This ensures the compiler takes THIS template if the header-file of the super-function
- // is included. In any other case, the compiler just uses the fallback template which is
- // defined in this file.
- template <class T, templatehack2>
- struct SuperFunctionCondition<functionnumber, T, 0, templatehack2>
- {
- static void check()
- {
- // This call to the apply-function is the whole check. By calling the function with
- // a T* pointer, the right function get's called.
- SuperFunctionCondition<functionnumber, T, 0, templatehack2>::apply(static_cast<T*>(0));
-
- // Go go the check for of next super-function (functionnumber + 1)
- SuperFunctionCondition<functionnumber + 1, T, 0, templatehack2>::check();
- }
-
- // This function gets called if T is not a child of the baseclass.
- // The function does nothing.
- static void apply(void* temp) {}
-
- // This function gets called if T is a child of the baseclass and can therefore be converted.
- // The function adds a SuperFunctionCaller to the Identifier of all subclasses of T.
- static void apply(baseclass* temp)
- {
- ClassIdentifier<T>* identifier = ClassIdentifier<T>::getIdentifier();
-
- // Iterate through all children
- for (std::set<const Identifier*>::iterator it = identifier->getDirectChildrenIntern().begin(); it != identifier->getDirectChildrenIntern().end(); ++it)
- {
- // Check if the caller is a fallback-caller
- if (((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ && ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_)
- {
- // Delete the fallback caller an prepare to get a real caller
- delete ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_;
- ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = 0;
- ((ClassIdentifier<T>*)(*it))->bSuperFunctionCaller_##functionname##_isFallback_ = false;
- }
-
- // Check if there's not already a caller
- if (!((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_)
- {
- // Add the SuperFunctionCaller
- COUT(5) << "adding functionpointer to " << ((ClassIdentifier<T>*)(*it))->getName() << std::endl;
- ((ClassIdentifier<T>*)(*it))->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_##functionname <T>;
- }
- }
- }
- };
- SUPER_FUNCTION_PUREVIRTUAL_WORKAROUND##purevirtualbase
-
-
- // The following piece of code is only added if purevirtualbase = true
-
- // Explicit specialization of the Condition template for the baseclass to avoid
- // errors if the function is pure virtual in the baseclass.
- template <int templatehack2> \
- struct SuperFunctionCondition<functionnumber, baseclass, 0, templatehack2> \
- { \
- // The check function acts like the fallback - it advances to the check for the next super-function (functionnumber + 1)
- static void check() \
- { \
- SuperFunctionCondition<functionnumber + 1, baseclass, 0, templatehack2>::check(); \
- } \
- };
- */
-
- /// SUPER-macro: Calls Parent::functionname(...) where Parent is the direct parent of @a classname
- #ifdef ORXONOX_COMPILER_MSVC
- #define SUPER(classname, functionname, ...) \
- __super::functionname(__VA_ARGS__)
- #else
- #define SUPER(classname, functionname, ...) \
- SUPER_##functionname(classname, functionname, __VA_ARGS__)
- #endif
-
- // helper macro: for functions without arguments
- #define SUPER_NOARGS(classname, functionname) \
- (*ClassIdentifier<classname>::getIdentifier()->superFunctionCaller_##functionname##_)(this)
-
- // helper macro: for functions with arguments
- #define SUPER_ARGS(classname, functionname, ...) \
- (*ClassIdentifier<classname>::getIdentifier()->superFunctionCaller_##functionname##_)(this, __VA_ARGS__)
-
-
-//// Function-specific macros ////
-
- /*
- Add a macro for each super-function
-
- Example (no arguments):
- #define SUPER_myfunction(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- Example (with arguments):
- #define SUPER_myfunction(classname, functionname, ...) \
- SUPER_ARGS(classname, functionname, __VA_ARGS__)
- */
-
- // (1/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
- #define SUPER_XMLPort(classname, functionname, ...) \
- SUPER_ARGS(classname, functionname, __VA_ARGS__)
-
- #define SUPER_tick(classname, functionname, ...) \
- SUPER_ARGS(classname, functionname, __VA_ARGS__)
-
- #define SUPER_changedActivity(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedVisibility(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_XMLEventPort(classname, functionname, ...) \
- SUPER_ARGS(classname, functionname, __VA_ARGS__)
-
- #define SUPER_changedScale(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedOwner(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedOverlayGroup(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedName(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedGametype(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedUsed(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_clone(classname, functionname, ...) \
- SUPER_ARGS(classname, functionname, __VA_ARGS__)
-
- #define SUPER_changedCarrier(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- #define SUPER_changedPickedUp(classname, functionname, ...) \
- SUPER_NOARGS(classname, functionname)
-
- // (1/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
-
-
-namespace orxonox
-{
- /////////////////////////////////////////////////////////////////////////////////////////////////////
- // This code gets included by Identifier.h and every other header file that needs a super-function //
- /////////////////////////////////////////////////////////////////////////////////////////////////////
-
- //// Common code ////
-
- // Base templates
- /**
- @brief Creates the SuperFunctionCaller if T is a child of the super-functions baseclass.
- */
- template <int functionnumber, class T, int templatehack1, int templatehack2>
- struct SuperFunctionCondition
- {
- static void check() {}
- };
-
- /**
- @brief Initializes the SuperFunctionCaller-pointer with zero.
- */
- template <int functionnumber, class T>
- struct SuperFunctionInitialization
- {
- static void initialize(ClassIdentifier<T>* identifier) {}
- };
-
- /**
- @brief Deletes the SuperFunctionCaller.
- */
- template <int functionnumber, class T>
- struct SuperFunctionDestruction
- {
- static void destroy(ClassIdentifier<T>* identifier) {}
- };
-
-
- //// Function-specific code ////
-
- /**
- @brief Creates the needed objects and templates to call a super-function.
- @param functionnumber Each super-function needs a unique number, starting with zero, increasing by one
- @param functionname The name of the super-function
- @param hasarguments "false" if the function doesn't take any arguments, "true" if it does (without "")
- @param ... Variadic: If the function takes arguments, add them here with type and name. Example: int myvalue, float myothervalue
- */
- #define SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(functionnumber, functionname, hasarguments, ...) \
- template <class T, int templatehack1, int templatehack2> \
- struct SuperFunctionCondition<functionnumber, T, templatehack1, templatehack2> \
- { \
- static void check() \
- { \
- SuperFunctionCondition<functionnumber + 1, T, templatehack1, templatehack2>::check(); \
- } \
- }; \
- \
- class _CoreExport SuperFunctionCaller_##functionname \
- { \
- public: \
- virtual void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) = 0; \
- virtual ~SuperFunctionCaller_##functionname () {} \
- }; \
- \
- template <class T> \
- class SuperFunctionClassCaller_purevirtualfallback_##functionname : public SuperFunctionCaller_##functionname \
- { \
- public: \
- inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) \
- { \
- } \
- }; \
- \
- template <class T> \
- struct SuperFunctionInitialization<functionnumber, T> \
- { \
- static void initialize(ClassIdentifier<T>* identifier) \
- { \
- identifier->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_purevirtualfallback_##functionname <T>; \
- identifier->bSuperFunctionCaller_##functionname##_isFallback_ = true; \
- SuperFunctionInitialization<functionnumber + 1, T>::initialize(identifier); \
- } \
- }; \
- \
- template <class T> \
- struct SuperFunctionDestruction<functionnumber, T> \
- { \
- static void destroy(ClassIdentifier<T>* identifier) \
- { \
- if (identifier->superFunctionCaller_##functionname##_) \
- delete identifier->superFunctionCaller_##functionname##_; \
- SuperFunctionDestruction<functionnumber + 1, T>::destroy(identifier); \
- } \
- }; \
- \
- template <class T> \
- class SuperFunctionClassCaller_##functionname : public SuperFunctionCaller_##functionname \
- { \
- public: \
- inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) \
- { \
- (dynamic_cast<T*>(object))->T:: functionname
-
- /*
- JUST ADD THE FUNCTION ARGUMENTS BETWEEN BOTH MACROS, ENCLOSED BY BRACKETS
- EXAMPLE:
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(0, myfunction, true, int myvalue, float myothervalue) <-- !!! DONT ADD A SEMICOLON HERE !!!
- (myvalue, myothervalue)
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2
- */
-
- #define SUPER_FUNCTION_GLOBAL_DECLARATION_PART2 \
- ; \
- } \
- };
-
- #define SUPER_CALL_ARGUMENTSfalse(...) OrxonoxClass* object
- #define SUPER_CALL_ARGUMENTS0(...) OrxonoxClass* object
- #define SUPER_CALL_ARGUMENTStrue(...) OrxonoxClass* object, __VA_ARGS__
- #define SUPER_CALL_ARGUMENTS1(...) OrxonoxClass* object, __VA_ARGS__
-
-
- /*
- //// COMMENTS ABOUT THE MACRO ////
-
- // Partially specialized template (templatehack not yet specialized, this
- // will be done by the real condition in the header-file of the super-function)
- // Only used as fallback
- template <class T, int templatehack1, int templatehack2>
- struct SuperFunctionCondition<functionnumber, T, templatehack1, templatehack2>
- {
- // If this function gets called, the header-file of the super function is not
- // included, so this fallback template (templatehack not specialized) is used
- static void check()
- {
- // Calls the condition-check of the next super-function (functionnumber + 1)
- SuperFunctionCondition<functionnumber + 1, T, templatehack1, templatehack2>::check();
- }
- };
-
- // Baseclass of the super-function caller. The real call will be done by a
- // templatized subclass through the virtual () operator.
- class _CoreExport SuperFunctionCaller_##functionname
- {
- public:
- virtual void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) ) = 0;
- virtual ~SuperFunctionCaller_##functionname () {}
- };
-
- // Fallback if the base is pure virtual
- template <class T>
- class SuperFunctionClassCaller_purevirtualfallback_##functionname : public SuperFunctionCaller_##functionname
- {
- public:
- // Fallback does nothing
- inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) )
- {
- }
- };
-
- // Initializes the SuperFunctionCaller-pointer with a fallback caller in case the base function is pure virtual
- template <class T>
- struct SuperFunctionInitialization<functionnumber, T>
- {
- static void initialize(ClassIdentifier<T>* identifier)
- {
- identifier->superFunctionCaller_##functionname##_ = new SuperFunctionClassCaller_purevirtualfallback_##functionname <T>;
- identifier->bSuperFunctionCaller_##functionname##_isFallback_ = true;
-
- // Calls the initialization of the next super-function (functionnumber + 1)
- SuperFunctionInitialization<functionnumber + 1, T>::initialize(identifier);
- }
- };
-
- // Deletes the SuperFunctionCaller.
- template <class T>
- struct SuperFunctionDestruction<functionnumber, T>
- {
- static void destroy(ClassIdentifier<T>* identifier)
- {
- if (identifier->superFunctionCaller_##functionname##_)
- delete identifier->superFunctionCaller_##functionname##_;
-
- // Calls the destruction of the next super-function (functionnumber + 1)
- SuperFunctionDestruction<functionnumber + 1, T>::destroy(identifier);
- }
- };
-
- // The real super-function caller: Calls T::functionname()
- // T should be the parent, but this will be done by the spezialized condition template
- template <class T>
- class SuperFunctionClassCaller_##functionname : public SuperFunctionCaller_##functionname
- {
- public:
- // @brief Calls the function.
- // @param object The object to call the function on
- // @param ... The arguments of the function
- inline void operator()( SUPER_CALL_ARGUMENTS##hasarguments(__VA_ARGS__) )
- {
- (dynamic_cast<T*>(object))->T:: functionname ( Call the function with it's arguments );
- }
- }
- */
-
-
- //// Execute the code for each super-function ////
-
- // (2/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(0, XMLPort, true, Element& xmlelement, XMLPort::Mode mode)
- (xmlelement, mode)
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(1, tick, true, float dt)
- (dt)
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(2, changedActivity, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(3, changedVisibility, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, XMLEventPort, true, Element& xmlelement, XMLPort::Mode mode)
- (xmlelement, mode)
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(5, changedScale, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedOwner, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOverlayGroup, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedName, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedGametype, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(10, changedUsed, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(11, clone, true, OrxonoxClass* item)
- (item)
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(12, changedCarrier, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(13, changedPickedUp, false)
- ()
- SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
- // (2/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
-
-}
-
-#else /* _Super_H__ */
- #ifdef SUPER_INTRUSIVE_DECLARATION_INCLUDE
-
-//////////////////////////////////////////////////////////////////////////
-// This code gets included within the declaration of ClassIdentifier<T> //
-//////////////////////////////////////////////////////////////////////////
-
-//// Common code ////
-
- private:
-
- template <int functionnumber, class TT, int templatehack1, int templatehack2>
- friend struct SuperFunctionCondition;
-
- // Creates the super-function-callers by calling the first SuperFunctionCondition check
- // This get's called within the initialization of an Identifier
- virtual void createSuperFunctionCaller() const
- {
- SuperFunctionCondition<0, T, 0, 0>::check();
- }
-
-
-//// Function-specific code ////
-
- public:
- /**
- @brief Adds a pointer to the SuperFunctionCaller as a member of ClassIdentifier.
- @param functionname The name of the super-function
- */
- #ifndef SUPER_INTRUSIVE_DECLARATION
- #define SUPER_INTRUSIVE_DECLARATION(functionname) \
- SuperFunctionCaller_##functionname * superFunctionCaller_##functionname##_; \
- bool bSuperFunctionCaller_##functionname##_isFallback_
- #endif
-
-
-//// Execute the code for each super-function ////
-
- // (3/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
- SUPER_INTRUSIVE_DECLARATION(XMLPort);
- SUPER_INTRUSIVE_DECLARATION(tick);
- SUPER_INTRUSIVE_DECLARATION(changedActivity);
- SUPER_INTRUSIVE_DECLARATION(changedVisibility);
- SUPER_INTRUSIVE_DECLARATION(XMLEventPort);
- SUPER_INTRUSIVE_DECLARATION(changedScale);
- SUPER_INTRUSIVE_DECLARATION(changedOwner);
- SUPER_INTRUSIVE_DECLARATION(changedOverlayGroup);
- SUPER_INTRUSIVE_DECLARATION(changedName);
- SUPER_INTRUSIVE_DECLARATION(changedGametype);
- SUPER_INTRUSIVE_DECLARATION(changedUsed);
- SUPER_INTRUSIVE_DECLARATION(clone);
- SUPER_INTRUSIVE_DECLARATION(changedCarrier);
- SUPER_INTRUSIVE_DECLARATION(changedPickedUp);
- // (3/3) --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <-- --> HERE <--
-
-
- #undef SUPER_INTRUSIVE_DECLARATION_INCLUDE
- #endif /* SUPER_INTRUSIVE_DECLARATION_INCLUDE */
-#endif /* _Super_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Template.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Template.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Template.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,183 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "Template.h"
-
-#include <tinyxml/tinyxml.h>
-#include <tinyxml/ticpp.h>
-
-#include "util/Debug.h"
-#include "CoreIncludes.h"
-#include "XMLPort.h"
-
-namespace orxonox
-{
- CreateFactory(Template);
-
- Template::Template(BaseObject* creator) : BaseObject(creator)
- {
- this->xmlelement_ = new TiXmlElement("");
-
- RegisterObject(Template);
-
- this->bIsLink_ = false;
- this->bLoadDefaults_ = true;
- this->bIsReturningXMLElement_ = false;
- this->baseclassIdentifier_ = 0;
- }
-
- Template::~Template()
- {
- Template::getTemplateMap().erase(this->getName());
- delete this->xmlelement_;
- }
-
- void Template::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- SUPER(Template, XMLPort, xmlelement, mode);
-
- XMLPortParam(Template, "link", setLink, getLink, xmlelement, mode);
- XMLPortParam(Template, "baseclass", setBaseclass, getBaseclass, xmlelement, mode);
- XMLPortParam(Template, "defaults", setLoadDefaults, getLoadDefaults, xmlelement, mode).defaultValues(true);
-
- Element* element = xmlelement.FirstChildElement(false);
- if (element)
- {
- TiXmlElement* tixmlelement = static_cast<TiXmlElement*>(element->GetTiXmlPointer());
- if (tixmlelement)
- this->setXMLElement(*tixmlelement);
- }
- }
-
- void Template::changedName()
- {
- SUPER(Template, changedName);
-
- if (!this->getName().empty())
- {
- std::map<std::string, Template*>::iterator it;
- it = Template::getTemplateMap().find(this->getOldName());
- if (it != Template::getTemplateMap().end())
- Template::getTemplateMap().erase(it);
-
- it = Template::getTemplateMap().find(this->getName());
- if (it != Template::getTemplateMap().end())
- COUT(2) << "Warning: Template with name \"" << this->getName() << "\" already exists." << std::endl;
- else
- Template::getTemplateMap()[this->getName()] = this;
- }
- }
-
- void Template::setXMLElement(const TiXmlElement& xmlelement)
- {
- *this->xmlelement_ = xmlelement;
- }
-
- const TiXmlElement& Template::getXMLElement()
- {
- if (this->bIsLink_)
- {
- Template* temp = Template::getTemplate(this->link_);
- if (temp)
- {
- this->bLoadDefaults_ = temp->bLoadDefaults_;
-
- if (!temp->bIsReturningXMLElement_)
- {
- this->bIsReturningXMLElement_ = true;
- const TiXmlElement& element = temp->getXMLElement();
- this->bIsReturningXMLElement_ = false;
- return element;
- }
- else
- {
- COUT(2) << "Warning: Linking from " << this->getName() << " to " << this->link_ << " leads to an infinite loop. Returning own element." << std::endl;
- }
- }
- else
- {
- COUT(2) << "Warning: " << this->link_ << " is not an existing Template name. Returning own element." << std::endl;
- }
- }
-
- return *this->xmlelement_;
- }
-
- void Template::setBaseclass(const std::string& baseclass)
- {
- this->baseclassIdentifier_ = ClassByString(baseclass);
- if (this->baseclassIdentifier_)
- this->baseclass_ = baseclass;
- }
-
- void Template::applyOn(BaseObject* object)
- {
- if (this->baseclassIdentifier_)
- {
- if (!object->isA(this->baseclassIdentifier_))
- {
- COUT(1) << "Error: Can't apply template (name: " << this->getName() << "), object (name: " << object->getName() << ", class: " << object->getIdentifier()->getName() << ") is not a " << this->baseclassIdentifier_->getName() << std::endl;
- return;
- }
- }
-
- COUT(4) << object->getLoaderIndentation() << " aplying Template \"" << this->getName() << "\"..." << std::endl;
-
- Element temp = &const_cast<TiXmlElement&>(this->getXMLElement());
-
- if (this->bLoadDefaults_)
- object->XMLPort(temp, XMLPort::LoadObject);
- else
- object->XMLPort(temp, XMLPort::ExpandObject);
- }
-
- std::map<std::string, Template*>& Template::getTemplateMap()
- {
- static std::map<std::string, Template*> templateMap;
- return templateMap;
- }
-
- Template* Template::getTemplate(const std::string& name)
- {
- std::map<std::string, Template*>::iterator it = Template::getTemplateMap().find(name);
- if (it != Template::getTemplateMap().end())
- return it->second;
- else
- {
- COUT(2) << "Warning: Template with name " << name << " doesn't exist." << std::endl;
- return 0;
- }
- }
-
- void Template::apply(const std::string& name, BaseObject* object)
- {
- std::map<std::string, Template*>::iterator it = Template::getTemplateMap().find(name);
- if (it != Template::getTemplateMap().end())
- it->second->applyOn(object);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Template.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Template.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Template.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,97 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup Template Template
- @ingroup XML
-*/
-
-/**
- @file
- @ingroup XML Template
-*/
-
-#ifndef _Template_H__
-#define _Template_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-#include "BaseObject.h"
-
-namespace orxonox
-{
- class _CoreExport Template : public BaseObject
- {
- public:
- Template(BaseObject* creator);
- virtual ~Template();
-
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
- virtual void changedName();
-
- inline void setLink(const std::string& link)
- { this->link_ = link; this->bIsLink_ = !link.empty(); }
- inline const std::string& getLink() const
- { return this->link_; }
- inline bool isLink() const
- { return this->bIsLink_; }
-
- inline void setLoadDefaults(bool bLoadDefaults)
- { this->bLoadDefaults_ = bLoadDefaults; }
- inline bool getLoadDefaults() const
- { return this->bLoadDefaults_; }
-
- void setXMLElement(const TiXmlElement& xmlelement);
- const TiXmlElement& getXMLElement();
-
- void setBaseclass(const std::string& baseclass);
- inline const std::string& getBaseclass() const
- { return this->baseclass_; }
- inline Identifier* getBaseclassIdentifier() const
- { return this->baseclassIdentifier_; }
-
- void applyOn(BaseObject* object);
-
- static std::map<std::string, Template*>& getTemplateMap();
- static Template* getTemplate(const std::string& name);
- static void apply(const std::string& name, BaseObject* object);
-
- private:
- TiXmlElement* xmlelement_;
- std::string link_;
- std::string baseclass_;
- Identifier* baseclassIdentifier_;
- bool bIsLink_;
- bool bLoadDefaults_;
- mutable bool bIsReturningXMLElement_;
- };
-}
-
-#endif /* _Template_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/Thread.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Thread.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Thread.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,128 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oliver Scheuss
- * Co-authors:
- * ...
- *
- */
-
-#include "Thread.h"
-
-#include <cassert>
-#include <boost/thread/thread.hpp>
-#include <boost/bind.hpp>
-#include <boost/thread/mutex.hpp>
-#include <boost/thread/thread_time.hpp>
-
-#include "util/Sleep.h"
-#include "command/Executor.h"
-
-namespace orxonox
-{
- boost::posix_time::millisec THREAD_WAIT_BEFORE_DETACH(1000);
-
-
- Thread::Thread():
- executor_(0),
- isWorking_(false),
- stopThread_(false)
- {
- this->executorMutex_ = new boost::mutex;
- this->isWorkingMutex_ = new boost::mutex;
- this->stopThreadMutex_ = new boost::mutex;
- this->workerThread_ = new boost::thread( boost::bind(&Thread::threadLoop, this) );
- }
-
- Thread::~Thread()
- {
- this->stopThreadMutex_->lock();
- this->stopThread_ = true;
- this->stopThreadMutex_->unlock();
- if( !this->workerThread_->timed_join( THREAD_WAIT_BEFORE_DETACH ) )
- assert(0); // this should not happen
- delete this->workerThread_;
- delete this->executorMutex_;
- delete this->stopThreadMutex_;
- delete this->isWorkingMutex_;
- }
-
- bool Thread::isWorking()
- {
- this->isWorkingMutex_->lock();
- bool isWorking = this->isWorking_;
- this->isWorkingMutex_->unlock();
- return isWorking;
- }
-
- bool Thread::evaluateExecutor( const ExecutorPtr& executor )
- {
- this->isWorkingMutex_->lock();
- this->isWorking_=true;
- this->isWorkingMutex_->unlock();
- this->executorMutex_->lock();
- this->executor_ = executor;
- this->executorMutex_->unlock();
- return true;
- }
-
- void Thread::threadLoop()
- {
- bool stopThread = false;
- while( !stopThread )
- {
- //this->executorMutex_->lock();
- ExecutorPtr executor = this->executor_;
- //this->executorMutex_->unlock();
- if( executor )
- {
- (*executor)();
- this->executorMutex_->lock();
- this->executor_ = 0;
- this->executorMutex_->unlock();
- this->isWorkingMutex_->lock();
- this->isWorking_=false;
- this->isWorkingMutex_->unlock();
- }
- else
- {
- this->workerThread_->yield();
- }
- //this->stopThreadMutex_->lock();
- stopThread = this->stopThread_;
- //this->stopThreadMutex_->unlock();
- }
- }
-
- void Thread::waitUntilFinished()
- {
- bool stillWorking = true;
- while( stillWorking )
- {
- this->isWorkingMutex_->lock();
- stillWorking = this->isWorking_;
- this->isWorkingMutex_->unlock();
- if( stillWorking )
- msleep( 1 );
- }
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/Thread.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/Thread.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/Thread.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,69 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oliver Scheuss
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup ThreadPool
-*/
-
-#ifndef _Thread_H__
-#define _Thread_H__
-
-#include "CorePrereqs.h"
-
-namespace boost{
- class recursive_mutex;
-}
-
- namespace orxonox
-{
- class _CoreExport Thread
- {
- public:
- Thread();
- virtual ~Thread();
-
- bool isWorking();
- void waitUntilFinished();
- bool evaluateExecutor( const ExecutorPtr& executor );
-
- private:
- void threadLoop();
-
- ExecutorPtr executor_;
- bool isWorking_;
- bool stopThread_;
- boost::thread* workerThread_;
- boost::mutex* executorMutex_;
- boost::mutex* isWorkingMutex_;
- boost::mutex* stopThreadMutex_;
- };
-
- }
-
-#endif /* _Thread_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ThreadPool.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ThreadPool.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ThreadPool.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,115 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oliver Scheuss
- * Co-authors:
- * ...
- *
- */
-
-#include "ThreadPool.h"
-#include "Thread.h"
-#include <cassert>
-
-namespace orxonox
-{
-
- ThreadPool::ThreadPool()
- {
- }
-
- ThreadPool::~ThreadPool()
- {
- unsigned int a = this->setNrOfThreads(0);
- assert(a == 0);
- }
-
- void ThreadPool::addThreads( unsigned int nr )
- {
- for( unsigned int i=0; i<nr; i++ )
- this->threadPool_.push_back(new Thread());
- }
- unsigned int ThreadPool::removeThreads( unsigned int nr )
- {
- unsigned int i=0;
- std::vector<Thread*>::iterator it;
- for( it = this->threadPool_.begin(); it != threadPool_.end() && i<nr; )
- {
- if( ! (*it)->isWorking() )
- {
- Thread* temp = *it;
- it=this->threadPool_.erase( it );
- delete temp;
- ++i;
- }
- else
- ++it;
- }
- return i;
- }
- unsigned int ThreadPool::setNrOfThreads( unsigned int nr )
- {
- unsigned int currentsize = this->threadPool_.size();
- if ( nr < currentsize )
- return currentsize - removeThreads( currentsize - nr );
- else if ( nr == currentsize )
- return currentsize;
- else
- {
- addThreads( nr - currentsize );
- return nr;
- }
- }
-
- bool ThreadPool::passFunction( const ExecutorPtr& executor, bool addThread )
- {
- std::vector<Thread*>::iterator it;
- for ( it=this->threadPool_.begin(); it!=this->threadPool_.end(); ++it )
- {
- if ( ! (*it)->isWorking() )
- {
- bool b = (*it)->evaluateExecutor( executor );
- assert(b); // if b is false then there is some code error
- return true;
- }
- }
- if ( addThread )
- {
- addThreads( 1 );
- bool b = this->threadPool_.back()->evaluateExecutor( executor ); // access the last element
- assert(b);
- return true;
- }
- else
- return false;
- }
-
- void ThreadPool::synchronise()
- {
- std::vector<Thread*>::iterator it;
- for ( it=this->threadPool_.begin(); it!=this->threadPool_.end(); ++it )
- {
- (*it)->waitUntilFinished();
- }
- }
-
-}
Deleted: code/forks/sandbox_light/src/libraries/core/ThreadPool.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ThreadPool.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ThreadPool.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,67 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oliver Scheuss
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup ThreadPool Thread pool
- @ingroup Core
-*/
-
-/**
- @file
- @ingroup ThreadPool
-*/
-
-#ifndef _ThreadPool_H__
-#define _ThreadPool_H__
-
-#include "CorePrereqs.h"
-
-#include <vector>
-
- namespace orxonox
-{
- class _CoreExport ThreadPool
- {
- public:
- ThreadPool();
- virtual ~ThreadPool();
-
- void addThreads( unsigned int nr );
- unsigned int removeThreads( unsigned int nr );
- unsigned int setNrOfThreads( unsigned int nr );
-
- bool passFunction( const ExecutorPtr& executor, bool addThread=false );
- void synchronise();
-
- private:
- std::vector<Thread*> threadPool_;
-
- };
-}
-
-#endif /* _ThreadPool_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/ToluaInterface.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/ToluaInterface.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/ToluaInterface.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,47 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at ingroup Lua
- at brief
- This is required because tolua would parse this macro in LuaState.h and fail
-*/
-
-#ifndef _ToluaInterface_H__
-#define _ToluaInterface_H__
-
-#include "CorePrereqs.h"
-#include <boost/preprocessor/cat.hpp>
-
-// Macro for declaring a tolua interface of a library/module
-#define DeclareToluaInterface(libraryName) \
- static bool BOOST_PP_CAT(bDummy##libraryName, __LINE__) = orxonox::LuaState::addToluaInterface(&tolua_##libraryName##_open, #libraryName); \
- static Loki::ScopeGuardImpl1<bool (*)(const std::string&), std::string> BOOST_PP_CAT(dummy##libraryName, __LINE__)(&orxonox::LuaState::removeToluaInterface, #libraryName)
-
-#endif /* _ToluaInterface_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/WeakPtr.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/WeakPtr.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/WeakPtr.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,286 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-// Inspired by boost::intrusive_ptr by Peter Dimov
-
-/**
- @file
- @ingroup Object SmartPtr
- @brief Definition of WeakPtr<T>, wraps a pointer to an object.
-
- @anchor WeakPtrExample
-
- A WeakPtr wraps a pointer to an object. If the object gets deleted, the WeakPtr becomes
- NULL. This can be used to store pointers to objects without knowing when they will be
- destroyed.
-
- WeakPtr works only with objects that are derived from orxonox::OrxonoxClass, because
- WeakPtr is intrusive and registers itself in the stored object, to get a notification if
- the object is being deleted.
-
- Example:
- @code
- MyClass* object = new MyClass(); // create an instance of MyClass
-
- WeakPtr<MyClass> pointer = object; // create a WeakPtr and assign the object
-
- if (pointer) // checks if pointer is not NULL (which is true)
- pointer->someFunction(); // calls MyClass::someFunction()
-
- object->destroy(); // calls destroy() which deletes the object
-
- if (pointer) // checks if pointer is not NULL (which is now false)
- pointer->someFunction(); // this will not be executed
- @endcode
- In this example we assumed that MyClass is derived of OrxonoxClass (otherwise it couldn't
- be used with a WeakPtr).
-
- A callback can be registerd with the WeakPtr that will be called if the object gets deleted.
- @code
- void myCallback() // definition of the callback function
- {
- COUT(0) << "Object destroyed" << std::endl;
- }
-
- MyClass* object = new MyClass(); // create an instance of MyClass
-
- WeakPtr<MyClass> pointer = object; // create a WeakPtr and assign the object
-
- pointer.setCallback(createFunctor(&myCallback)); // defines a callback
-
- object->destroy(); // calls destroy() which deletes the object. prints "Object destroyed" to the console
- @endcode
-*/
-
-#ifndef _WeakPtr_H__
-#define _WeakPtr_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-#include "Identifier.h"
-#include "OrxonoxClass.h"
-#include "command/Functor.h"
-
-namespace orxonox
-{
- /**
- @brief WeakPtr wraps a pointer to an object, which becomes NULL if the object is deleted.
-
- @see See @ref WeakPtrExample "this description" for more information and an example.
- */
- template <class T>
- class WeakPtr : public DestructionListener
- {
- public:
- /// Constructor: Initializes the weak pointer with a null pointer.
- inline WeakPtr() : pointer_(0), base_(0), callback_(0)
- {
- }
-
- /// Constructor: Used to explicitly initialize the weak pointer with a null pointer
- inline WeakPtr(int) : pointer_(0), base_(0), callback_(0)
- {
- }
-
- /// Constructor: Initializes the weak pointer with a pointer to an object.
- inline WeakPtr(T* pointer) : pointer_(pointer), base_(pointer), callback_(0)
- {
- this->registerAsDestructionListener(this->base_);
- }
-
- /// Copy-constructor
- inline WeakPtr(const WeakPtr& other) : pointer_(other.pointer_), base_(other.base_), callback_(0)
- {
- this->registerAsDestructionListener(this->base_);
- }
-
- /// Copy-constructor for weak pointers to objects of another class.
- template <class O>
- inline WeakPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.base_), callback_(0)
- {
- this->registerAsDestructionListener(this->base_);
- }
-
- /// Destructor
- inline ~WeakPtr()
- {
- this->unregisterAsDestructionListener(this->base_);
- }
-
- /// Used to assign a null pointer.
- inline WeakPtr& operator=(int)
- {
- WeakPtr(0).swap(*this);
- return *this;
- }
-
- /// Assigns a new pointer.
- inline WeakPtr& operator=(T* pointer)
- {
- WeakPtr(pointer).swap(*this);
- return *this;
- }
-
- /// Assigns the wrapped pointer of another WeakPtr.
- inline WeakPtr& operator=(const WeakPtr& other)
- {
- WeakPtr(other).swap(*this);
- return *this;
- }
-
- /// Assigns the wrapped pointer of a WeakPtr of another class
- template <class O>
- inline WeakPtr& operator=(const WeakPtr<O>& other)
- {
- WeakPtr(other).swap(*this);
- return *this;
- }
-
- /// Returns the wrapped pointer as @c T*
- inline T* get() const
- {
- return this->pointer_;
- }
-
- /// Returns the wrapped pointer as @c OrxonoxClass*
- inline OrxonoxClass* getBase() const
- {
- return this->base_;
- }
-
- /// Implicitly converts the WeakPtr to a pointer of type @c T*
- inline operator T*() const
- {
- return this->pointer_;
- }
-
- /// Overloaded operator, returns a pointer to the stored object.
- inline T* operator->() const
- {
- assert(this->pointer_ != 0);
- return this->pointer_;
- }
-
- /// Overloaded operator, returns a reference to the stored object.
- inline T& operator*() const
- {
- assert(this->pointer_ != 0);
- return *this->pointer_;
- }
-
- /// Returns true if the wrapped pointer is NULL.
- inline bool operator!() const
- {
- return (this->pointer_ == 0);
- }
-
- /// Swaps the contents of two weak pointers.
- inline void swap(WeakPtr& other)
- {
- this->unregisterAsDestructionListener(this->base_);
- other.unregisterAsDestructionListener(other.base_);
-
- {
- T* temp = this->pointer_;
- this->pointer_ = other.pointer_;
- other.pointer_ = temp;
- }
- {
- OrxonoxClass* temp = this->base_;
- this->base_ = other.base_;
- other.base_ = temp;
- }
-
- this->registerAsDestructionListener(this->base_);
- other.registerAsDestructionListener(other.base_);
- }
-
- /// Resets the weak pointer (equivalent to assigning a NULL pointer).
- inline void reset()
- {
- WeakPtr().swap(*this);
- }
-
- /// Registers a callback that will be executed if the stored object is destroyed.
- inline void setCallback(const FunctorPtr& callback)
- {
- this->callback_ = callback;
- }
-
- /// Returns the registered callback.
- inline const FunctorPtr& getCallback() const
- {
- return this->callback_;
- }
-
- private:
- /// Will be called by OrxonoxClass::~OrxonoxClass() if the stored object is deleted. Resets the wrapped pointer and executes the callback.
- inline void objectDeleted()
- {
- this->base_ = 0;
- this->pointer_ = 0;
- if (this->callback_)
- (*this->callback_)();
- }
-
- T* pointer_; ///< The wrapped pointer to an object of type @a T
- OrxonoxClass* base_; ///< The wrapped pointer, casted up to OrxonoxClass (this is needed because with just a T* pointer, WeakPtr couln't be used with forward declarations)
- FunctorPtr callback_; ///< This callback will be executed if the stored object is deleted
- };
-
- /// Swaps the contents of two weak pointers.
- template <class T>
- void swap(WeakPtr<T>& a, WeakPtr<T>& b)
- {
- a.swap(b);
- }
-
- /// Uses a static_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>.
- template <class T, class U>
- WeakPtr<T> static_pointer_cast(const WeakPtr<U>& p)
- {
- return static_cast<T*>(p.get());
- }
-
- /// Uses a const_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>.
- template <class T, class U>
- WeakPtr<T> const_pointer_cast(const WeakPtr<U>& p)
- {
- return const_cast<T*>(p.get());
- }
-
- /// Uses a dynamic_cast to cast a pointer of type U* to a pointer of type T* and returns it in a new WeakPtr<T>.
- template <class T, class U>
- WeakPtr<T> dynamic_pointer_cast(const WeakPtr<U>& p)
- {
- return orxonox_cast<T*>(p.get());
- }
-}
-
-#endif /* _WeakPtr_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/WindowEventListener.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/WindowEventListener.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/WindowEventListener.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,64 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-#include "WindowEventListener.h"
-#include "CoreIncludes.h"
-
-namespace orxonox
-{
- unsigned int WindowEventListener::windowWidth_s = 0;
- unsigned int WindowEventListener::windowHeight_s = 0;
-
- WindowEventListener::WindowEventListener()
- {
- RegisterRootObject(WindowEventListener);
- }
-
- //! Calls all registered objects
- /*static*/ void WindowEventListener::moveWindow()
- {
- for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
- it->windowMoved();
- }
-
- //! Calls all registered objects and sets the static variables
- /*static*/ void WindowEventListener::resizeWindow(unsigned int newWidth, unsigned int newHeight)
- {
- windowWidth_s = newWidth;
- windowHeight_s = newHeight;
- for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
- it->windowResized(newWidth, newHeight);
- }
-
- //! Calls all registered objects
- /*static*/ void WindowEventListener::changeWindowFocus(bool bFocus)
- {
- for (ObjectList<WindowEventListener>::iterator it = ObjectList<WindowEventListener>::begin(); it; ++it)
- it->windowFocusChanged(bFocus);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/WindowEventListener.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/WindowEventListener.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/WindowEventListener.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,76 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Graphics
-*/
-
-#ifndef _WindowEventListener_H__
-#define _WindowEventListener_H__
-
-#include "CorePrereqs.h"
-#include "OrxonoxClass.h"
-
-namespace orxonox
-{
- //! Interface for receiving window events like resize, moved and focusChanged
- class _CoreExport WindowEventListener : virtual public OrxonoxClass
- {
- friend class OgreWindowEventListener;
-
- protected:
- WindowEventListener();
- virtual ~WindowEventListener() { }
-
- //! Returns the current render window width
- unsigned int getWindowWidth() const { return windowWidth_s; }
- //! Returns the current render window height
- unsigned int getWindowHeight() const { return windowHeight_s; }
-
- private:
- //! Window has been moved
- virtual void windowMoved() { }
-
- //! Window has resized
- virtual void windowResized(unsigned int newWidth, unsigned int newHeight) { }
-
- //! Window has lost/gained focus
- virtual void windowFocusChanged(bool bFocus) { }
-
- static void moveWindow();
- static void resizeWindow(unsigned int newWidth, unsigned int newHeight);
- static void changeWindowFocus(bool bFocus);
-
- //! Static variable that holds the latest distributed information
- static unsigned int windowWidth_s;
- static unsigned int windowHeight_s;
- };
-}
-
-#endif /* _WindowEventListener_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/XMLFile.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/XMLFile.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/XMLFile.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,70 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup XML XMLPort
-*/
-
-#ifndef _XMLFile_H__
-#define _XMLFile_H__
-
-#include "CorePrereqs.h"
-
-#include <string>
-#include "ClassTreeMask.h"
-
-namespace orxonox
-{
- class _CoreExport XMLFile
- {
- public:
- XMLFile(const std::string& filename)
- : filename_(filename)
- , bLuaSupport_(true)
- { }
- XMLFile(const ClassTreeMask& mask, const std::string& filename)
- : filename_(filename)
- , mask_(mask)
- , bLuaSupport_(true)
- { }
-
- void setLuaSupport(bool val) { bLuaSupport_ = val; }
-
- const std::string& getFilename() const { return this->filename_; }
- const ClassTreeMask& getMask() const { return this->mask_; }
- bool getLuaSupport() const { return this->bLuaSupport_; }
-
- private:
- std::string filename_;
- ClassTreeMask mask_;
- bool bLuaSupport_; // Default is true
- };
-}
-
-#endif /* _XMLFile_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/XMLNameListener.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/XMLNameListener.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/XMLNameListener.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,38 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "XMLNameListener.h"
-#include "CoreIncludes.h"
-
-namespace orxonox
-{
- XMLNameListener::XMLNameListener()
- {
- RegisterRootObject(XMLNameListener);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/XMLNameListener.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/XMLNameListener.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/XMLNameListener.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,52 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup XML XMLPort
-*/
-
-#ifndef _XMLNameListener_H__
-#define _XMLNameListener_H__
-
-#include "CorePrereqs.h"
-#include "OrxonoxClass.h"
-
-namespace orxonox
-{
- class _CoreExport XMLNameListener : virtual public OrxonoxClass
- {
- public:
- XMLNameListener();
- virtual ~XMLNameListener() {}
-
- virtual void loadedNewXMLName(BaseObject* object) = 0;
- };
-}
-
-#endif /* _XMLNameListener_H__ */
Deleted: code/forks/sandbox_light/src/libraries/core/XMLPort.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/core/XMLPort.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/XMLPort.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,138 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "XMLPort.h"
-
-#include "Loader.h"
-#include "Namespace.h"
-
-namespace orxonox
-{
- // ################################
- // ### XMLPortObjectContainer ###
- // ################################
- bool XMLPortObjectContainer::identifierIsIncludedInLoaderMask(const Identifier* identifier)
- {
- return ((!this->bApplyLoaderMask_) || identifier->isA(ClassIdentifier<Namespace>::getIdentifier()) || Loader::currentMask_s.isIncluded(identifier));
- }
-
- XMLPortObjectContainer& XMLPortObjectContainer::port(BaseObject* object, Element& xmlelement, XMLPort::Mode mode)
- {
- if ((mode == XMLPort::LoadObject) || (mode == XMLPort::ExpandObject))
- {
- try
- {
- Element* xmlsubelement;
- if (!this->sectionname_.empty())
- xmlsubelement = xmlelement.FirstChildElement(this->sectionname_, false);
- else
- xmlsubelement = &xmlelement;
-
- if (!xmlsubelement)
- return (*this);
-
- for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
- {
- Identifier* identifier = Identifier::getIdentifierByString(child->Value());
- if (!identifier)
- {
- if (!this->sectionname_.empty())
- {
- COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not a valid classname." << std::endl;
- }
- else
- {
- // It's probably just another subsection
- }
- continue;
- }
- if (!identifier->isA(objectIdentifier_))
- {
- COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not a '" << objectIdentifier_->getName() << "'." << std::endl;
- continue;
- }
- if (!identifier->isLoadable())
- {
- COUT(2) << object->getLoaderIndentation() << "Warning: '" << child->Value() << "' is not loadable." << std::endl;
- continue;
- }
- if (!this->identifierIsIncludedInLoaderMask(identifier))
- continue;
-
- try
- {
- COUT(4) << object->getLoaderIndentation() << "fabricating " << child->Value() << "..." << std::endl;
-
- BaseObject* newObject = identifier->fabricate(object);
- newObject->setLoaderIndentation(object->getLoaderIndentation() + " ");
-
- if (this->bLoadBefore_)
- {
- newObject->XMLPort(*child, XMLPort::LoadObject);
- COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (objectname " << newObject->getName() << ") to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ')' << std::endl;
- }
- else
- {
- COUT(4) << object->getLoaderIndentation() << "assigning " << child->Value() << " (object not yet loaded) to " << this->identifier_->getName() << " (objectname " << static_cast<BaseObject*>(object)->getName() << ')' << std::endl;
- }
-
- COUT(5) << object->getLoaderIndentation();
-
- this->callLoadExecutor(object, newObject);
-
- if (!this->bLoadBefore_)
- newObject->XMLPort(*child, XMLPort::LoadObject);
-
- COUT(5) << object->getLoaderIndentation() << "...fabricated " << child->Value() << " (objectname " << newObject->getName() << ")." << std::endl;
- }
- catch (AbortLoadingException& ex)
- {
- COUT(1) << "An error occurred while loading object, abort loading..." << std::endl;
- throw ex;
- }
- catch (...)
- {
- COUT(1) << "An error occurred while loading object:" << std::endl;
- COUT(1) << Exception::handleMessage() << std::endl;
- }
- }
- }
- catch (ticpp::Exception& ex)
- {
- COUT(1) << std::endl;
- COUT(1) << "An error occurred in XMLPort.h while loading a '" << objectIdentifier_->getName() << "' in '" << this->sectionname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << object->getName() << ") in " << object->getFilename() << ':' << std::endl;
- COUT(1) << ex.what() << std::endl;
- }
- }
- else if (mode == XMLPort::SaveObject)
- {
- }
-
- return (*this);
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/core/XMLPort.h
===================================================================
--- code/forks/sandbox_light/src/libraries/core/XMLPort.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/core/XMLPort.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,614 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @defgroup XMLPort XMLPort
- @ingroup XML
-*/
-
-/**
- @file
- @ingroup XML XMLPort
- @brief Declaration of the XMLPort helper classes and macros.
-
- XMLPort is a virtual function of every BaseObject. Every object can change this function.
- The XMLPort function gets called with an XMLElement, containing all attributes and
- subclasses the object gets from the levelfile.
-
- This file declares classes and macros to simplify XML-parsing.
-*/
-
-#ifndef _XMLPort_H__
-#define _XMLPort_H__
-
-#include "CorePrereqs.h"
-
-#include <cassert>
-#include <string>
-#include <tinyxml/ticpp.h>
-
-#include "util/Debug.h"
-#include "util/Exception.h"
-#include "util/MultiType.h"
-#include "util/OrxAssert.h"
-#include "util/StringUtils.h"
-#include "Identifier.h"
-#include "BaseObject.h"
-#include "command/Executor.h"
-
-// ------------
-// XMLPortParam
-
-/**
- @brief Declares an XML attribute with a name, which will be set through load- and savefunctions.
- @param classname The name of the class owning this param
- @param paramname The name of the attribute
- @param loadfunction A function to set the param in the object with a given value (~a set-function)
- @param savefunction A function to get the value of the param from the object (~a get-function)
- @param xmlelement The XMLElement, you get this from the XMLPort function
- @param mode The mode (load or save), you get this from the XMLPort function
-
- In the XML file, a param or attribute will be set like this:
- @code
- <classname paramname="value" />
- @endcode
-
- The macro will then call loadfunction(value) to set the given value (or call savefunction() to
- write an existing value to an XML file).
-*/
-#define XMLPortParam(classname, paramname, loadfunction, savefunction, xmlelement, mode) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, classname, this, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode)
-
-/**
- @brief Declares an XML attribute with a name, which will be set through a variable.
- @param classname The name of the class owning this param
- @param paramname The name of the attribute
- @param variable Name of the variable used to save and load the value
- @param xmlelement The XMLElement, you get this from the XMLPort function
- @param mode The mode (load or save), you get this from the XMLPort function
-
- In the XML file, a param or attribute will be set like this:
- @code
- <classname paramname="value" />
- @endcode
-
- The macro will then store "value" in the variable or read it when saving.
-*/
-#define XMLPortParamVariable(classname, paramname, variable, xmlelement, mode) \
- XMLPortVariableHelperClass xmlcontainer##variable##dummy(static_cast<void*>(&variable)); \
- static ExecutorMemberPtr<orxonox::XMLPortVariableHelperClass> xmlcontainer##variable##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(orxonox::XMLPortVariableHelperClass::getLoader(variable)), std::string( #classname ) + "::" + #variable + "loader"); \
- static ExecutorMemberPtr<orxonox::XMLPortVariableHelperClass> xmlcontainer##variable##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(orxonox::XMLPortVariableHelperClass::getSaver (variable)), std::string( #classname ) + "::" + #variable + "saver" ); \
- XMLPortParamGeneric(xmlcontainer##variable, classname, orxonox::XMLPortVariableHelperClass, &xmlcontainer##variable##dummy, paramname, xmlcontainer##variable##loadexecutor, xmlcontainer##variable##saveexecutor, xmlelement, mode)
-
-/**
- @brief This is the same as XMLPortParam, but you can set the template arguments needed to store the loadfunction.
-
- Sometimes the name of the loadfunction is ambiguous (example: setPosition(Vector3) or
- setPosition(float, float, float)). In this case, you can choose the right function by
- telling the types of the functionparams. In our example, this would be either
- > XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, Vector3);
- or
- > XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, float, float, float);
- You don't have to use this, if there exist only one function with the given name.
-*/
-#define XMLPortParamTemplate(classname, paramname, loadfunction, savefunction, xmlelement, mode, ...) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<void, classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, classname, this, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode)
-
-// --------------------
-// XMLPortParamLoadOnly
-
-/**
- @brief Declares an XML attribute with a name, which can be set through a loadfunction.
-
- This is the same as XMLPortParam, but you don't need a savefunction (get-function). Therefore,
- this param won't be saved in an XML file, but you can add the attribute manually an it will be
- loaded.
-
- This might be helpful in cases, when you have several options to set a value, for example the
- rotation. You can set the rotation with a quaternion, but you could also use three angles.
- When saving the object, only one of both options has to be saved; this is, where this macro helps.
-*/
-#define XMLPortParamLoadOnly(classname, paramname, loadfunction, xmlelement, mode) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##0##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##0, classname, classname, this, paramname, xmlcontainer##loadfunction##0##loadexecutor, 0, xmlelement, mode)
-/**
- @brief This is the same as XMLPortParamTemplate, but for load-only attributes (see XMLPortParamLoadOnly).
-*/
-#define XMLPortParamLoadOnlyTemplate(classname, paramname, loadfunction, xmlelement, mode, ...) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##0##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<void, classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##0, classname, classname, this, paramname, xmlcontainer##loadfunction##0##loadexecutor, 0, xmlelement, mode)
-
-// ------------------
-// XMLPortParamExtern
-
-/**
- @brief This is the same as XMLPortParam, but for attributes in an extern class.
- @param classname The name of the class owning the object owning the attribute
- @param externclass The name of the extern class (the objects class)
- @param object The name of the object of the extern class (a member of the main class)
- @param paramname The name of the attribute
- @param loadfunction The function to set the attribute inside of the member object.
- @param savefunction The function to get the attribute from the member object
- @param xmlelement The XML-element that is parsed by this macro
- @param mode Loading or saving
-
- Sometimes you'll have a member object in your class, which has it's own load- and savefunctions.
- With this macro, you can simply use them instead of writing your own functions.
-
- Example:
- Your class is called SpaceShip and this class has an object (myPilot_) of class Pilot. Pilot has a name
- and two functions, setName(name) and getName(). Now you want an attribute "pilotname" in your
- SpaceShip class. Instead of writing wrapper functions, you can simply use the XMLPortParamExtern
- macro:
- > XMLPortParamExtern(SpaceShip, Pilot, myPilot_, "pilotname", setName, getName, xmlelement, mode);
-*/
-#define XMLPortParamExtern(classname, externclass, object, paramname, loadfunction, savefunction, xmlelement, mode) \
- static ExecutorMemberPtr<externclass> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::loadfunction), std::string( #externclass ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<externclass> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::savefunction), std::string( #externclass ) + "::" + #savefunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, externclass, object, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode);
-/**
- @brief This is the same as XMLPortParamTemplate, but for extern attributes (see XMLPortParamExtern).
-*/
-#define XMLPortParamExternTemplate(classname, externclass, object, paramname, loadfunction, savefunction, xmlelement, mode, ...) \
- static ExecutorMemberPtr<externclass> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<void, externclass, __VA_ARGS__ >(&externclass::loadfunction), std::string( #externclass ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<externclass> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&externclass::savefunction), std::string( #externclass ) + "::" + #savefunction); \
- XMLPortParamGeneric(xmlcontainer##loadfunction##savefunction, classname, externclass, object, paramname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode);
-
-// -------------------
-// XMLPortParamGeneric
-
-/**
- @brief This is the generic XMLPort param macro, which is used by all six specialized macros above.
-*/
-#define XMLPortParamGeneric(containername, classname, objectclass, object, paramname, loadexecutor, saveexecutor, xmlelement, mode) \
- orxonox::XMLPortClassParamContainer<objectclass>* containername = static_cast<orxonox::XMLPortClassParamContainer<objectclass>*>(ClassIdentifier<classname>::getIdentifier()->getXMLPortParamContainer(paramname)); \
- if (!containername) \
- { \
- containername = new orxonox::XMLPortClassParamContainer<objectclass>(std::string(paramname), ClassIdentifier<classname>::getIdentifier(), loadexecutor, saveexecutor); \
- ClassIdentifier<classname>::getIdentifier()->addXMLPortParamContainer(paramname, containername); \
- } \
- containername->port(dynamic_cast<BaseObject*>(this), object, xmlelement, mode)
-
-// --------------------
-// XMLPortObjectExtended
-
-/**
- @brief Declares a possible sub-object that can be added in the XML file.
- @param classname The name of the class that uses this macro
- @param objectclass The baseclass of objects that can be added
- @param sectionname The name of the subsection in the XML file that encloses the sub-objects ("" means no subsection)
- @param loadfunction The function to add a new object to the class
- @param savefunction The function to get all added objects from the class
- @param xmlelement The XMLElement (received through the XMLPort function)
- @param mode The mode (load/save) (received through the XMLPort function)
- @param bApplyLoaderMask If this is true, an added sub-object gets loaded only if it's class is included in the Loaders ClassTreeMask (this is usually false)
- @param bLoadBefore If this is true, the sub-object gets loaded (through XMLPort) BEFORE it gets added to the main class (this is usually true)
-
- bApplyLoaderMask is usually false for the following reason:
- If the loaders mask says, for example, "load only SpaceShips" and you added weapons to the
- SpaceShips, then the Weapons will still be loaded (which is most probably what you want).
- Of course, if there are "standalone" weapons in the level, they wont be loaded.
-
- If bLoadBefore is true, an added object already has all attributes set (like it's name). This is most
- likely the best option, so this is usually true.
-
- @details
- The load- and savefunctions have to follow an exactly defined protocol.
- Loadfunction:
- The loadfunction gets a pointer to the object.
- @code
- void loadfunction(objectclass* pointer);
- @endcode
-
- Savefunction:
- The savefunction gets an index, starting with 0. For every returnvalue != 0, the savefunction
- gets called again, but with index + 1. It's the functions responsibility to do something smart
- with the index and to return 0 if all objects were returned.
- @code
- objectclass* savefunction(unsigned int index) const;
- @endcode
-
- Possible implementation:
- @code
- objectclass* savefunction(unsigned int index) const
- {
- if (index < number_of_added_objects_)
- return my_added_objects[index];
- else
- return 0;
- }
- @endcode
-
- Example:
- Possible usage of the macro:
- @code
- XMLPortObject(SpaceShip, Weapon, "weapons", addWeapon, getWeapon, xmlelement, mode, false, true);
- @endcode
-
- Now you can add weapons through the XML file:
- @code
- <SpaceShip someattribute="..." ...>
- <weapons>
- <Weapon someattribute="..." ... />
- <Weapon someattribute="..." ... />
- <Weapon someattribute="..." ... />
- </weapons>
- </SpaceShip>
- @endcode
-
- Note that "weapons" is the subsection. This allows you to add more types of sub-objects. In our example,
- you could add pilots, blinking lights or other stuff. If you don't want a subsection, just use "" (an
- empty string). Then you can add sub-objects directly into the mainclass.
-*/
-#define XMLPortObjectExtended(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, bApplyLoaderMask, bLoadBefore) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore)
-/**
- @brief This is the same as XMLPortObjectExtended, but you can specify the loadfunction by adding the param types. See XMLPortParamTemplate for more details about the types.
-*/
-#define XMLPortObjectExtendedTemplate(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, bApplyLoaderMask, bLoadBefore, ...) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<void, classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore)
-
-// -------------
-// XMLPortObject
-
-/**
- @brief This is the same as XMLPortObjectExtended, but bApplyLoaderMask is false and bLoadBefore is true by default.
-*/
-#define XMLPortObject(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, false, true)
-/**
- @brief This is the same as XMLPortObject, but you can specify the loadfunction by adding the param types. See XMLPortParamTemplate for more details about the types.
-*/
-#define XMLPortObjectTemplate(classname, objectclass, sectionname, loadfunction, savefunction, xmlelement, mode, ...) \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##loadexecutor = orxonox::createExecutor(orxonox::createFunctor<void, classname, __VA_ARGS__ >(&classname::loadfunction), std::string( #classname ) + "::" + #loadfunction); \
- static ExecutorMemberPtr<classname> xmlcontainer##loadfunction##savefunction##saveexecutor = orxonox::createExecutor(orxonox::createFunctor(&classname::savefunction), std::string( #classname ) + "::" + #savefunction); \
- XMLPortObjectGeneric(xmlcontainer##loadfunction##savefunction, classname, objectclass, sectionname, xmlcontainer##loadfunction##savefunction##loadexecutor, xmlcontainer##loadfunction##savefunction##saveexecutor, xmlelement, mode, false, true)
-
-// --------------------
-// XMLPortObjectGeneric
-
-/**
- @brief Generic XMLPortObject macro, that gets called by all other XMLPortObject macros above.
-*/
-#define XMLPortObjectGeneric(containername, classname, objectclass, sectionname, loadexecutor, saveexecutor, xmlelement, mode, bApplyLoaderMask, bLoadBefore) \
- orxonox::XMLPortClassObjectContainer<classname, objectclass>* containername = (orxonox::XMLPortClassObjectContainer<classname, objectclass>*)(ClassIdentifier<classname>::getIdentifier()->getXMLPortObjectContainer(sectionname)); \
- if (!containername) \
- { \
- containername = new orxonox::XMLPortClassObjectContainer<classname, objectclass>(std::string(sectionname), ClassIdentifier<classname>::getIdentifier(), loadexecutor, saveexecutor, bApplyLoaderMask, bLoadBefore); \
- ClassIdentifier<classname>::getIdentifier()->addXMLPortObjectContainer(sectionname, containername); \
- } \
- containername->port(this, xmlelement, mode)
-
-
-namespace orxonox
-{
- // ###############################
- // ### XMLPortParamContainer ###
- // ###############################
- class _CoreExport XMLPortParamContainer
- {
- public:
- enum ParseResult
- {
- PR_not_started,
- PR_finished,
- PR_waiting_for_default_values
- };
-
- public:
- XMLPortParamContainer()
- { this->parseResult_ = PR_not_started; }
- virtual ~XMLPortParamContainer() {}
-
- inline const std::string& getName() const
- { return this->paramname_; }
-
- inline XMLPortParamContainer& description(const std::string& description)
- { this->description_ = description; return *this; }
- inline const std::string& getDescription() const
- { return this->description_; }
-
- virtual XMLPortParamContainer& defaultValue(unsigned int index, const MultiType& param) = 0;
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1) = 0;
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2) = 0;
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3) = 0;
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4) = 0;
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5) = 0;
-
- protected:
- std::string paramname_;
- ParseResult parseResult_;
- Identifier* identifier_;
- BaseObject* owner_;
- std::string description_;
- };
-
- template <class T>
- class XMLPortClassParamContainer : public XMLPortParamContainer
- {
- struct ParseParams
- {
- T* object;
- Element* xmlelement;
- XMLPort::Mode mode;
- };
-
- public:
- XMLPortClassParamContainer(const std::string& paramname, Identifier* identifier, const ExecutorMemberPtr<T>& loadexecutor, const ExecutorMemberPtr<T>& saveexecutor)
- {
- this->paramname_ = paramname;
- this->identifier_ = identifier;
- this->loadexecutor_ = loadexecutor;
- this->saveexecutor_ = saveexecutor;
- }
-
- ~XMLPortClassParamContainer()
- {
- }
-
- XMLPortParamContainer& port(BaseObject* owner, T* object, Element& xmlelement, XMLPort::Mode mode)
- {
- OrxAssert(owner, "XMLPortParamContainer must have a BaseObject as owner.");
- this->owner_ = owner;
- this->parseParams_.object = object;
- this->parseParams_.xmlelement = &xmlelement;
- this->parseParams_.mode = mode;
-
- if ((mode == XMLPort::LoadObject) || (mode == XMLPort::ExpandObject))
- {
- try
- {
- if (this->owner_->lastLoadedXMLElement_ != &xmlelement)
- {
- this->owner_->xmlAttributes_.clear();
- // Iterate through the attributes manually in order to make them case insensitive
- ticpp::Attribute* attribute = xmlelement.FirstAttribute(false);
- while (attribute != 0)
- {
- this->owner_->xmlAttributes_[getLowercase(attribute->Name())] = attribute->Value();
- attribute = attribute->Next(false);
- }
- this->owner_->lastLoadedXMLElement_ = &xmlelement;
- }
- std::map<std::string, std::string>::const_iterator it = this->owner_->xmlAttributes_.find(getLowercase(this->paramname_));
- std::string attributeValue;
- if (it != this->owner_->xmlAttributes_.end())
- attributeValue = it->second;
-
- // TODO: Checking the iterator would be better since then we can have strings with value "" as well.
- // Unfortunately this does not seem to work with the Executor parser yet.
- if ((!attributeValue.empty()) || ((mode != XMLPort::ExpandObject) && this->loadexecutor_->allDefaultValuesSet()))
- {
- COUT(5) << this->owner_->getLoaderIndentation() << "Loading parameter " << this->paramname_ << " in " << this->identifier_->getName() << " (objectname " << this->owner_->getName() << ")." << std::endl << this->owner_->getLoaderIndentation();
- int error;
- this->loadexecutor_->parse(object, attributeValue, &error, ",");
- if (!error || (mode == XMLPort::ExpandObject))
- this->parseResult_ = PR_finished;
- else
- this->parseResult_ = PR_waiting_for_default_values;
- }
- else if (mode == XMLPort::ExpandObject)
- this->parseResult_ = PR_finished;
- else
- this->parseResult_ = PR_waiting_for_default_values;
- }
- catch (ticpp::Exception& ex)
- {
- COUT(1) << std::endl;
- COUT(1) << "An error occurred in XMLPort.h while loading attribute '" << this->paramname_ << "' of '" << this->identifier_->getName() << "' (objectname: " << this->owner_->getName() << ") in " << this->owner_->getFilename() << ':' << std::endl;
- COUT(1) << ex.what() << std::endl;
- }
- }
- else if (mode == XMLPort::SaveObject)
- {
- if (this->saveexecutor_)
- {
-// xmlelement.SetAttribute(this->paramname_, "...");
- }
- }
-
- return (*this);
- }
-
- XMLPortParamContainer& port(BaseObject* owner, const ParseParams& parseParams)
- {
- return this->port(owner, parseParams.object, *parseParams.xmlelement, parseParams.mode);
- }
-
- XMLPortParamContainer& portIfWaitingForDefaultValues(const ParseResult& result, const ParseParams& params)
- {
- if (result == PR_waiting_for_default_values)
- return this->port(this->owner_, params);
- else
- return (*this);
- }
-
- virtual XMLPortParamContainer& defaultValue(unsigned int index, const MultiType& param)
- {
- if (!this->loadexecutor_->defaultValueSet(index))
- this->loadexecutor_->setDefaultValue(index, param);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1)
- {
- if (!this->loadexecutor_->defaultValueSet(0))
- this->loadexecutor_->setDefaultValues(param1);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2)
- {
- if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)))
- this->loadexecutor_->setDefaultValues(param1, param2);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3)
- {
- if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)))
- this->loadexecutor_->setDefaultValues(param1, param2, param3);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4)
- {
- if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)) || (!this->loadexecutor_->defaultValueSet(3)))
- this->loadexecutor_->setDefaultValues(param1, param2, param3, param4);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
- virtual XMLPortParamContainer& defaultValues(const MultiType& param1, const MultiType& param2, const MultiType& param3, const MultiType& param4, const MultiType& param5)
- {
- if ((!this->loadexecutor_->defaultValueSet(0)) || (!this->loadexecutor_->defaultValueSet(1)) || (!this->loadexecutor_->defaultValueSet(2)) || (!this->loadexecutor_->defaultValueSet(3)) || (!this->loadexecutor_->defaultValueSet(4)))
- this->loadexecutor_->setDefaultValues(param1, param2, param3, param4, param5);
- return this->portIfWaitingForDefaultValues(this->parseResult_, this->parseParams_);
- }
-
- private:
- ExecutorMemberPtr<T> loadexecutor_;
- ExecutorMemberPtr<T> saveexecutor_;
- ParseParams parseParams_;
- };
-
-
- // ################################
- // ### XMLPortObjectContainer ###
- // ################################
- class _CoreExport XMLPortObjectContainer
- {
- public:
- XMLPortObjectContainer()
- { this->bApplyLoaderMask_ = false; }
- virtual ~XMLPortObjectContainer() {}
-
- XMLPortObjectContainer& port(BaseObject* object, Element& xmlelement, XMLPort::Mode mode);
-
- virtual void callLoadExecutor(BaseObject* object, BaseObject* newObject) = 0;
-
- inline const std::string& getName() const
- { return this->sectionname_; }
-
- inline XMLPortObjectContainer& description(const std::string& description)
- { this->description_ = description; return *this; }
- const std::string& getDescription() const
- { return this->description_; }
-
- bool identifierIsIncludedInLoaderMask(const Identifier* identifier);
-
- protected:
- std::string sectionname_;
- bool bApplyLoaderMask_;
- bool bLoadBefore_;
- Identifier* identifier_;
- Identifier* objectIdentifier_;
- std::string description_;
- };
-
- template <class T, class O>
- class XMLPortClassObjectContainer : public XMLPortObjectContainer
- {
- public:
- XMLPortClassObjectContainer(const std::string& sectionname, Identifier* identifier, const ExecutorMemberPtr<T>& loadexecutor, const ExecutorMemberPtr<T>& saveexecutor, bool bApplyLoaderMask, bool bLoadBefore)
- {
- this->sectionname_ = sectionname;
- this->identifier_ = identifier;
- assert(identifier->isA(ClassIdentifier<T>::getIdentifier()));
- this->objectIdentifier_ = ClassIdentifier<O>::getIdentifier();
- this->loadexecutor_ = loadexecutor;
- this->saveexecutor_ = saveexecutor;
- this->bApplyLoaderMask_ = bApplyLoaderMask;
- this->bLoadBefore_ = bLoadBefore;
- }
-
- ~XMLPortClassObjectContainer()
- {
- }
-
- void callLoadExecutor(BaseObject* object, BaseObject* newObject)
- {
- T* castObject = orxonox_cast<T*>(object);
- assert(castObject);
- O* castNewObject = orxonox_cast<O*>(newObject);
- assert(castNewObject);
-
- (*this->loadexecutor_)(castObject, castNewObject);
- }
-
- private:
- ExecutorMemberPtr<T> loadexecutor_;
- ExecutorMemberPtr<T> saveexecutor_;
- };
-
-
- // ####################################
- // ### XMLPortVariableHelperClass ###
- // ####################################
- /**
- @brief
- Helper class to load and save simple variables with XMLPort.
-
- getLoader and getSaver were necessary to get the type T with
- the help of template function type deduction (const T& is unused).
- These functions return the adress of save<T> or load<T>.
- */
- class XMLPortVariableHelperClass
- {
- public:
- XMLPortVariableHelperClass(void* var)
- : variable_(var)
- { }
- virtual ~XMLPortVariableHelperClass() {}
-
- template <class T>
- void load(const T& value)
- { *static_cast<T*>(this->variable_) = value; }
-
- template <class T>
- const T& save()
- { return *static_cast<T*>(this->variable_); }
-
- template <class T>
- static void (XMLPortVariableHelperClass::*getLoader(const T& var))(const T& value)
- { return &XMLPortVariableHelperClass::load<T>; }
-
- template <class T>
- static const T& (XMLPortVariableHelperClass::*getSaver(const T& var))()
- { return &XMLPortVariableHelperClass::save<T>; }
-
- private:
- void* variable_;
- };
-}
-
-#endif /* _XMLPort_H__ */
Modified: code/forks/sandbox_light/src/libraries/util/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/libraries/util/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -20,17 +20,13 @@
SET_SOURCE_FILES(UTIL_SRC_FILES
Clock.cc
Exception.cc
- ExprParser.cc
Math.cc
MultiType.cc
- Scope.cc
StringUtils.cc
COMPILATION_BEGIN StableCompilation.cc
- Clipboard.cc
Convert.cc
CRC32.cc
OutputHandler.cc
- ScopedSingletonManager.cc
SharedPtr.cc
SignalHandler.cc
Sleep.cc
@@ -53,8 +49,7 @@
ORXONOX_ADD_LIBRARY(util
FIND_HEADER_FILES
LINK_LIBRARIES
- ${CEGUI_LIBRARY}
- ${OGRE_LIBRARY}
+ ogremath_orxonox
SOURCE_FILES
${UTIL_SRC_FILES}
)
Deleted: code/forks/sandbox_light/src/libraries/util/Clipboard.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Clipboard.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Clipboard.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,142 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- * Windows version inspired by "Copy Text To Clipboard" by Laszlo Szathmary, 2007
- * http://www.loria.fr/~szathmar/off/projects/C/CopyTextToClipboard/index.php
- */
-
-/**
- @file
- @brief OS-specific implementations of the clipboard functions.
-*/
-
-#include "Clipboard.h"
-
-#ifdef ORXONOX_PLATFORM_WINDOWS
-
-/////////////
-// Windows //
-/////////////
-
-#ifndef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-#endif
-#include <windows.h>
-#undef min
-#undef max
-#include "Debug.h"
-
-namespace orxonox
-{
-
- /**
- @brief Puts text into the Windows-clipboard
- @return True if the action was successful
- */
- bool toClipboard(const std::string& text)
- {
- try
- {
- if (OpenClipboard(0))
- {
- EmptyClipboard();
- HGLOBAL clipbuffer = GlobalAlloc(GMEM_DDESHARE, text.size() + 1);
- char* buffer = static_cast<char*>(GlobalLock(clipbuffer));
- strcpy(buffer, text.c_str());
- GlobalUnlock(clipbuffer);
- SetClipboardData(CF_TEXT, clipbuffer);
- CloseClipboard();
-
- return true;
- }
- }
- catch (...)
- {
- COUT(1) << "Error: Unable to copy the following text to the clipboard:" << std::endl;
- COUT(1) << " \"" << text << '"' << std::endl;
- }
- return false;
- }
-
- /**
- @brief Gets text from the windows-clipboard if there is any text.
- @return The retrieved text
- */
- std::string fromClipboard()
- {
- try
- {
- if (OpenClipboard(0))
- {
- HANDLE hData = GetClipboardData(CF_TEXT);
- if (hData == NULL)
- return "";
- std::string output(static_cast<char*>(GlobalLock(hData)));
- GlobalUnlock(hData);
- CloseClipboard();
-
- return output;
- }
- }
- catch (...)
- {
- COUT(1) << "Error: Unable to retrieve text from the clipboard." << std::endl;
- }
- return "";
- }
-}
-
-#else /* ORXONOX_PLATFORM_WINDOWS */
-
-/////////////
-// Default //
-/////////////
-
-namespace orxonox
-{
- static std::string clipboard; ///< Keeps the text of our internal clipboard
-
- /**
- @brief Default implementation if there is no OS-specific implementation or no clipboard. Copies the text into an internal clipboard.
- @see fromClipboard()
- */
- bool toClipboard(const std::string& text)
- {
- clipboard = text;
- return true;
- }
-
- /**
- @brief Default implementation if there is no OS-specific implementation or no clipboard. Gets the text from the internal clipboard.
- @see toClipboard()
- */
- std::string fromClipboard()
- {
- return clipboard;
- }
-}
-
-#endif /* ORXONOX_PLATFORM_WINDOWS */
Deleted: code/forks/sandbox_light/src/libraries/util/Clipboard.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Clipboard.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Clipboard.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,55 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Util Command
- @brief Some functions to exchange text between the OS clipboard and the Shell in Orxonox.
-
- Use fromClipboard() to get text from the clipboard (if there is any text) and
- toClipboard() to put text into the clipboard.
-
- These functions can only work properly if there's an OS-specific implementation
- in Clipboard.cc. If a specific OS is not supported, the clipboard only works
- within Orxonox, but the exchange with other programs is not possible.
-*/
-
-#ifndef _Clipboard_H__
-#define _Clipboard_H__
-
-#include "UtilPrereqs.h"
-#include <string>
-
-namespace orxonox
-{
- _UtilExport bool toClipboard(const std::string& text);
- _UtilExport std::string fromClipboard();
-}
-
-#endif /* _Clipboard_H__ */
-
Modified: code/forks/sandbox_light/src/libraries/util/Clock.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Clock.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Clock.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -27,7 +27,7 @@
*/
#include "Clock.h"
-#include <OgreTimer.h>
+#include <ogremath/OgreTimer.h>
namespace orxonox
{
Deleted: code/forks/sandbox_light/src/libraries/util/DisplayStringConversions.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/DisplayStringConversions.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/DisplayStringConversions.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,79 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Reto Grieder
- * Co-authors:
- * ...
- */
-
-/**
- at file
- at brief
- std::sring to Ogre::UTFString conversion functions
-*/
-
-#ifndef _DisplayStringConversions_H__
-#define _DisplayStringConversions_H__
-
-#include "UtilPrereqs.h"
-#include <OgreOverlayElement.h>
-
-#if OGRE_UNICODE_SUPPORT
- #include <OgreUTFString.h>
-
- namespace orxonox
- {
- template <>
- struct ConverterExplicit<std::string, Ogre::DisplayString>
- {
- //! Converts an std::string into an Ogre::UTFString
- inline static bool convert(Ogre::DisplayString* output, const std::string& input)
- {
- Ogre::UTFString::code_point cp;
- for (unsigned int i = 0; i < input.size(); ++i)
- {
- cp = input[i];
- cp &= 0xFF;
- output->append(1, cp);
- }
- return true;
- }
- };
- }
-#else
- namespace orxonox
- {
- template <>
- struct ConverterExplicit<std::string, Ogre::DisplayString>
- {
- //! Converts an std::string into an Ogre::String
- inline static bool convert(Ogre::DisplayString* output, const std::string& input)
- {
- *output = input;
- return true;
- }
- };
- }
-#endif
-
-#endif /* _DisplayStringConversions_H__ */
Modified: code/forks/sandbox_light/src/libraries/util/Exception.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Exception.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Exception.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -34,7 +34,6 @@
#include "Exception.h"
-#include <CEGUIExceptions.h>
#include "Debug.h"
namespace orxonox
@@ -98,15 +97,6 @@
{
return ex.what();
}
- catch (const CEGUI::Exception& ex)
- {
-#if CEGUI_VERSION_MAJOR == 0 && CEGUI_VERSION_MINOR < 6
- return GeneralException(ex.getMessage().c_str()).getDescription();
-#else
- return GeneralException(ex.getMessage().c_str(), ex.getLine(),
- ex.getFileName().c_str(), ex.getName().c_str()).getDescription();
-#endif
- }
catch (...)
{
COUT(0) << "BIG WARNING: Unknown exception type encountered."
Deleted: code/forks/sandbox_light/src/libraries/util/ExprParser.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/ExprParser.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/ExprParser.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,464 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Declaration of FloatParser
-*/
-
-#include "ExprParser.h"
-
-#include <cmath>
-#include <cstring>
-#include <cstdlib>
-#include "Math.h"
-
-// macros for easier if, else statements
-#define CASE_1(var) if (!strcmp(SWITCH,var))
-#define CASE(var) else if (!strcmp(SWITCH,var))
-#define CASE_ELSE else
-
-//! skip white spaces
-#define PARSE_BLANKS while (*reading_stream == ' ') ++reading_stream
-
-namespace orxonox
-{
- ExprParser::ExprParser()
- {
- this->failed_ = false;
- this->variables_["pi"] = math::pi_d;
- this->variables_["e"] = math::e_d;
- }
-
- void ExprParser::setVariable(const std::string& varname, double value)
- {
- this->variables_[varname] = value;
- }
-
- void ExprParser::parse(const std::string& str)
- {
- this->reading_stream = str.c_str();
- if (str.size() == 0 || *reading_stream == '\0')
- {
- this->failed_ = true;
- this->result_ = 0.0;
- }
- else
- {
- this->result_ = parse_expr_8();
- this->remains_ = reading_stream;
- }
- }
-
- //Private functions:
- /******************/
- double ExprParser::parse_argument()
- {
- double value = parse_expr_8();
- if (*reading_stream == ',')
- {
- ++reading_stream;
- return value;
- }
- else
- {
- this->failed_ = true;
- return 0;
- }
- }
-
- double ExprParser::parse_last_argument()
- {
- double value = parse_expr_8();
- if (*reading_stream == ')')
- {
- ++reading_stream;
- return value;
- }
- else
- {
- this->failed_ = true;
- return 0;
- }
- }
-
- double ExprParser::parse_expr_8()
- {
- double value = parse_expr_7();
- for(;;)
- {
- switch (op)
- {
- case oder:
- value = parse_expr_7() || value;
- break;
- default: return value;
- }
- };
- }
-
-
- double ExprParser::parse_expr_7()
- {
- double value = parse_expr_6();
- for(;;)
- {
- switch (op)
- {
- case und:
- value = value && parse_expr_6();
- break;
- default: return value;
- }
- };
- }
-
- double ExprParser::parse_expr_6()
- {
- double value = parse_expr_5();
- for(;;)
- {
- switch (op)
- {
- case gleich:
- value = (value == parse_expr_5());
- break;
- case ungleich:
- value = (value != parse_expr_5());
- break;
- default:
- return value;
- }
- };
- }
-
- double ExprParser::parse_expr_5()
- {
- double value = parse_expr_4();
- for(;;)
- {
- switch (op)
- {
- case kleiner:
- value = (value < parse_expr_4());
- break;
- case kleinergleich:
- value = (value <= parse_expr_4());
- break;
- case groesser:
- value = (value > parse_expr_4());
- break;
- case groessergleich:
- value = (value >= parse_expr_4());
- break;
- default:
- return value;
- }
- };
- }
-
- double ExprParser::parse_expr_4()
- {
- double value = parse_expr_3();
- for(;;)
- {
- switch (op)
- {
- case b_plus:
- value += parse_expr_3();
- break;
- case b_minus:
- value -= parse_expr_3();
- break;
- default:
- return value;
- }
- };
- }
-
- double ExprParser::parse_expr_3()
- {
- double value = parse_expr_2();
- for(;;)
- {
- switch (op)
- {
- case mal:
- value *= parse_expr_2();
- break;
- case durch:
- value /= parse_expr_2();
- break;
- case modulo:
- {
- double temp = parse_expr_2();
- value = value - floor(value/temp)*temp;
- break;
- }
- default:
- return value;
- }
- };
- }
-
- double ExprParser::parse_expr_2()
- {
- double value = parse_expr_1();
- while (*reading_stream != '\0')
- {
- op = parse_binary_operator();
- switch (op)
- {
- case hoch:
- value = pow(value,parse_expr_1());
- break;
- default:
- return value;
- }
- };
- op = undef;
- return value;
- }
-
- double ExprParser::parse_expr_1()
- {
- PARSE_BLANKS;
- double value;
-
- unary_operator op = parse_unary_operator();
- PARSE_BLANKS;
-
- if (*reading_stream == '\0')
- {
- // end of string
- this->failed_ = true;
- return 0;
- }
- else if ((*reading_stream > 47 && *reading_stream < 59) || *reading_stream == 46)
- { // number
- value = strtod(reading_stream, const_cast<char**>(&reading_stream));
- }
- else if ((*reading_stream > 64 && *reading_stream < 91) || (*reading_stream > 96 && *reading_stream < 123) || *reading_stream == 46)
- { // variable or function
- char* word = new char[256];
- parse_word(word);
- PARSE_BLANKS;
- if (*reading_stream == '(')
- {
- ++reading_stream;
-#define SWITCH word
- CASE_1("sin")
- value = sin(parse_last_argument());
- CASE("asin")
- value = asin(parse_last_argument());
- CASE("sinh")
- value = sinh(parse_last_argument());
- CASE("asinh")
- {
- value = parse_last_argument();
- value = log(sqrt(pow(value, 2) + 1) + value);
- }
- CASE("cos")
- value = cos(parse_last_argument());
- CASE("acos")
- value = acos(parse_last_argument());
- CASE("cosh")
- value = cosh(parse_last_argument());
- CASE("acosh")
- {
- value = parse_last_argument();
- value = log(sqrt(pow(value, 2) - 1) + value);
- }
- CASE("tan")
- value = tan(parse_last_argument());
- CASE("atan")
- value = atan(parse_last_argument());
- CASE("atan2")
- value = atan2(parse_argument(),parse_last_argument());
- CASE("tanh")
- value = tanh(parse_last_argument());
- CASE("atanh")
- {
- value = parse_last_argument();
- value = 0.5*log((value + 1)/(value - 1));
- }
- CASE("int")
- value = floor(parse_last_argument());
- CASE("floor")
- value = floor(parse_last_argument());
- CASE("ceil")
- value = ceil(parse_last_argument());
- CASE("abs")
- value = fabs(parse_last_argument());
- CASE("exp")
- value = exp(parse_last_argument());
- CASE("log")
- value = log10(parse_last_argument());
- CASE("ln")
- value = log(parse_last_argument());
- CASE("sign")
- {
- value = parse_last_argument();
- value = (value>0 ? 1 : (value<0 ? -1 : 0));
- }
- CASE("sqrt")
- value = sqrt(parse_last_argument());
- CASE("degrees")
- value = parse_last_argument()*180/math::pi_d;
- CASE("radians")
- value = parse_last_argument()*math::pi_d/180;
- CASE("mod")
- {
- value = parse_argument();
- double value2 = parse_last_argument();
- value = value - floor(value/value2)*value2;
- }
- CASE("pow")
- value = pow(parse_argument(),parse_last_argument());
- CASE("div")
- value = floor(parse_argument()/parse_last_argument());
- CASE("max")
- value = std::max(parse_argument(),parse_last_argument());
- CASE("min")
- value = std::min(parse_argument(),parse_last_argument());
- CASE_ELSE
- {
- this->failed_ = true;
- delete[] word;
- return 0;
- }
- }
- else
- {
- std::map<std::string, double>::const_iterator it = this->variables_.find(word);
- if (it != this->variables_.end())
- value = it->second;
- else
- {
- this->failed_ = true;
- delete[] word;
- return 0;
- }
- }
- delete[] word;
- }
- else if (*reading_stream == 40)
- { // expression in parenthesis
- ++reading_stream;
- value = parse_last_argument();
- }
- else
- {
- this->failed_ = true;
- return 0;
- }
-
- PARSE_BLANKS;
- switch (op)
- {
- case u_nicht: return !value;
- case u_plus: return value;
- case u_minus: return -value;
- default:
- this->failed_ = true;
- return 0;
- }
- }
-
- char* ExprParser::parse_word(char* str)
- {
- char* word = str;
- int counter = 0;
- while ((*reading_stream > 47 && *reading_stream < 58) || (*reading_stream > 64 && *reading_stream < 91) || (*reading_stream > 96 && *reading_stream < 123) || *reading_stream == 46)
- {
- *word++ = *reading_stream++;
- counter++;
- if (counter > 255)
- {
- this->failed_ = true;
- return '\0';
- }
- };
- *word = '\0';
- return str;
- }
-
- ExprParser::binary_operator ExprParser::parse_binary_operator()
- {
- binary_operator op;
- switch (*reading_stream)
- {
- case '+': op = b_plus; break;
- case '-': op = b_minus; break;
- case '*': op = mal; break;
- case '/': op = durch; break;
- case '^': op = hoch; break;
- case '%': op = modulo; break;
- case '&': op = und; break;
- case '|': op = oder; break;
- case '=': op = gleich; break;
- case '!': op = b_nicht; break;
- case '<': op = kleiner; break;
- case '>': op = groesser; break;
- default: return undef;
- }
- if (*++reading_stream == '=')
- {
- if (op > 9)
- {
- ++reading_stream;
- return (binary_operator)(op + 3);
- }
- else
- {
- --reading_stream;
- return undef;
- }
- }
- else
- return op;
- }
-
- ExprParser::unary_operator ExprParser::parse_unary_operator()
- {
- switch (*reading_stream)
- {
- case '!':
- ++reading_stream;
- return u_nicht;
- case '+':
- ++reading_stream;
- return u_plus;
- case '-':
- ++reading_stream;
- return u_minus;
- default :
- return u_plus;
- }
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/util/ExprParser.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/ExprParser.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/ExprParser.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,164 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at ingroup Util
- at brief Declaration of FloatParser
-*/
-
-#ifndef _FloatParser_H__
-#define _FloatParser_H__
-
-#include "UtilPrereqs.h"
-
-#include <map>
-#include <string>
-
-namespace orxonox
-{
- /** Parser for expressions like \c "3 * cos(5 + 4) / a" where \a a is a predeclared
- variable.
- @par Usage
- Using it is rather simple:
- @code
- std::string str("3 + 4");
- ExprParser expr;
- expr.parse(str);
- if (expr.getSuccess())
- {
- if (!expr.getRemains().empty())
- {
- COUT(2) << "Warning: Expression could not be parsed to the end! Remains: '" << expr.getRemains() << '\'' << std::endl;
- }
- double result = expr.getResult();
- }
- else
- COUT(1) << "Error: Cannot calculate expression: Parse error." << std::endl;
- @endcode
- getRemains() returns the expression after what could be parsed. For instance
- \c "2*3 text" will return \c "text" as remains.
- @details
- The implementation of this class is really old and sort of a trial for
- a first C++ class by Reto. That explains why it looks more like C than
- C++... Also some of the variable names are in German. <br>
- Explaining how it works exactly is probably not possible anymore, but it
- is based on recursively parsing the expression character by character.
- That much I can remember.
- @par Functions, operators and variables supported
- - Variables:
- - e
- - pi
- - Functions:
- - sin, asin, sinh, asinh
- - cos, acos, cosh, acosh
- - tan, atan, tanh, atanh
- - int, floor, ceil, abs, sign
- - pow, sqrt, exp, ln, log
- - mod, div
- - min, max
- - radians, degrees
- - Operators:
- - +, -, ! (unary)
- - +, -, *, /, %, ^, |, &, !, <, >, !=, <=, >=, =
- @note
- Operators may not be very consistent with C++ rules, but using the class
- for plus and minus should be perfectly ok.
- */
- class _UtilExport ExprParser
- {
- public:
- enum binary_operator
- {
- b_plus,
- b_minus,
- mal,
- durch,
- modulo,
- hoch,
- undef,
- oder,
- und,
- gleich,
- b_nicht,
- kleiner,
- groesser,
- ungleich,
- kleinergleich,
- groessergleich
- };
-
- enum unary_operator
- {
- u_plus,
- u_minus,
- u_nicht
- };
-
-
- ExprParser();
- void parse(const std::string& str);
- const std::string& getRemains() { return this->remains_; }
- double getResult() { return this->result_; }
- bool getSuccess() { return !this->failed_; }
-
- void setVariable(const std::string& varname, double value);
-
- private:
- double parse_expr_1();
- double parse_expr_2();
- double parse_expr_3();
- double parse_expr_4();
- double parse_expr_5();
- double parse_expr_6();
- double parse_expr_7();
- double parse_expr_8();
- char* parse_word(char* str);
- binary_operator parse_binary_operator();
- unary_operator parse_unary_operator();
-
- double parse_argument();
- double parse_last_argument();
-
- binary_operator op;
- const char* reading_stream;
- bool failed_;
- double result_;
- std::string remains_;
- std::map<std::string, double> variables_;
- };
-
- //Endzeichen für float expression: ')', '}', ']', ',', ';'
- _UtilExport bool parse_float(char* const, char**, double*);
- //Endzeichen angegeben
- _UtilExport bool parse_float(char* const, char**, char, double*);
- //Letzter Teil-float eines Vektors parsen (keine Vergleichs- und Logikoperationen)
- _UtilExport bool parse_vector_float(char* const, char**, bool, double*);
-}
-
-#endif /* _FloatParser_H__ */
Modified: code/forks/sandbox_light/src/libraries/util/Math.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Math.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Math.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -33,7 +33,7 @@
#include "Math.h"
-#include <OgrePlane.h>
+#include <ogremath/OgrePlane.h>
#include "MathConvert.h"
#include "SubString.h"
Modified: code/forks/sandbox_light/src/libraries/util/Math.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Math.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Math.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -46,12 +46,12 @@
#include <cmath>
#include <cstdlib>
-#include <OgreMath.h>
-#include <OgreVector2.h>
-#include <OgreVector3.h>
-#include <OgreVector4.h>
-#include <OgreQuaternion.h>
-#include <OgreColourValue.h>
+#include <ogremath/OgreMath.h>
+#include <ogremath/OgreVector2.h>
+#include <ogremath/OgreVector3.h>
+#include <ogremath/OgreVector4.h>
+#include <ogremath/OgreQuaternion.h>
+#include <ogremath/OgreColourValue.h>
// Certain headers might define unwanted macros...
#undef max
Modified: code/forks/sandbox_light/src/libraries/util/MultiType.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/MultiType.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/MultiType.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -99,11 +99,11 @@
#include <cassert>
#include <string>
-#include <OgreVector2.h>
-#include <OgreVector3.h>
-#include <OgreVector4.h>
-#include <OgreQuaternion.h>
-#include <OgreColourValue.h>
+#include <ogremath/OgreVector2.h>
+#include <ogremath/OgreVector3.h>
+#include <ogremath/OgreVector4.h>
+#include <ogremath/OgreQuaternion.h>
+#include <ogremath/OgreColourValue.h>
#include <loki/TypeTraits.h>
#include "mbool.h"
@@ -260,10 +260,6 @@
virtual void toString(std::ostream& outstream) const = 0;
- virtual void importData( uint8_t*& mem )=0;
- virtual void exportData( uint8_t*& mem ) const=0;
- virtual uint8_t getSize() const=0;
-
MT_Type::Value type_; ///< The type of the current value
bool bHasDefaultValue_; ///< True if the last conversion wasn't successful
};
@@ -373,16 +369,6 @@
template <typename T> inline bool isType() const { return false; } // Only works for specialized values - see below
std::string getTypename() const;
- /// Saves the value of the MT to a bytestream (pointed at by mem) and increases mem pointer by size of MT
- inline void exportData(uint8_t*& mem) const { assert(sizeof(MT_Type::Value)<=8); *static_cast<uint8_t*>(mem) = this->getType(); mem+=sizeof(uint8_t); this->value_->exportData(mem); }
- /// Loads the value of the MT from a bytestream (pointed at by mem) and increases mem pointer by size of MT
- inline void importData(uint8_t*& mem) { assert(sizeof(MT_Type::Value)<=8); this->setType(static_cast<MT_Type::Value>(*static_cast<uint8_t*>(mem))); mem+=sizeof(uint8_t); this->value_->importData(mem); }
- /// Saves the value of the MT to a bytestream and increases pointer to bytestream by size of MT
- inline uint8_t*& operator << (uint8_t*& mem) { importData(mem); return mem; }
- /// Loads the value of the MT to a bytestream and increases pointer to bytestream by size of MT
- inline void operator >> (uint8_t*& mem) const { exportData(mem); }
- inline uint32_t getNetworkSize() const { assert(this->value_); return this->value_->getSize() + sizeof(uint8_t); }
-
/// Checks whether the value is a default one (assigned after a failed conversion)
bool hasDefaultValue() const { return this->value_->hasDefaultValue(); }
Modified: code/forks/sandbox_light/src/libraries/util/MultiTypeValue.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/MultiTypeValue.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/MultiTypeValue.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -42,7 +42,6 @@
#include <cassert>
#include "MathConvert.h"
#include "MultiType.h"
-#include "Serialise.h"
namespace orxonox
{
@@ -154,118 +153,8 @@
/// Puts the current value on the stream
inline void toString(std::ostream& outstream) const { outstream << this->value_; }
- /// loads data from the bytestream (mem) into the MT and increases the bytestream pointer by the size of the data
- inline void importData( uint8_t*& mem ) { loadAndIncrease( /*(const T&)*/this->value_, mem ); }
- /// saves data from the MT into the bytestream (mem) and increases the bytestream pointer by the size of the data
- inline void exportData( uint8_t*& mem ) const { saveAndIncrease( /*(const T&)*/this->value_, mem ); }
- /// returns the size of the data that would be saved by exportData
- inline uint8_t getSize() const { return returnSize( this->value_ ); }
-
T value_; ///< The stored value
};
-
- // Import / Export specialisation
- // ColourValue
- template <> inline void MT_Value<ColourValue>::importData( uint8_t*& mem )
- {
- loadAndIncrease( this->value_.r, mem );
- loadAndIncrease( this->value_.g, mem );
- loadAndIncrease( this->value_.b, mem );
- loadAndIncrease( this->value_.a, mem );
- }
- template <> inline void MT_Value<ColourValue>::exportData( uint8_t*& mem ) const
- {
- saveAndIncrease( this->value_.r, mem );
- saveAndIncrease( this->value_.g, mem );
- saveAndIncrease( this->value_.b, mem );
- saveAndIncrease( this->value_.a, mem );
- }
- template <> inline uint8_t MT_Value<ColourValue>::getSize() const
- {
- return 4*returnSize(this->value_.r);
- }
- // Ogre::Quaternion
- template <> inline void MT_Value<Ogre::Quaternion>::importData( uint8_t*& mem )
- {
- loadAndIncrease( this->value_.x, mem );
- loadAndIncrease( this->value_.y, mem );
- loadAndIncrease( this->value_.z, mem );
- loadAndIncrease( this->value_.w, mem );
- }
- template <> inline void MT_Value<Ogre::Quaternion>::exportData( uint8_t*& mem ) const
- {
- saveAndIncrease( this->value_.x, mem );
- saveAndIncrease( this->value_.y, mem );
- saveAndIncrease( this->value_.z, mem );
- saveAndIncrease( this->value_.w, mem );
- }
- template <> inline uint8_t MT_Value<Ogre::Quaternion>::getSize() const
- {
- return 4*returnSize(this->value_.x);
- }
- // Ogre::Vector2
- template <> inline void MT_Value<Ogre::Vector2>::importData( uint8_t*& mem )
- {
- loadAndIncrease( this->value_.x, mem );
- loadAndIncrease( this->value_.y, mem );
- }
- template <> inline void MT_Value<Ogre::Vector2>::exportData( uint8_t*& mem ) const
- {
- saveAndIncrease( this->value_.x, mem );
- saveAndIncrease( this->value_.y, mem );
- }
- template <> inline uint8_t MT_Value<Ogre::Vector2>::getSize() const
- {
- return 2*returnSize(this->value_.x);
- }
- // Ogre::Vector3
- template <> inline void MT_Value<Ogre::Vector3>::importData( uint8_t*& mem )
- {
- loadAndIncrease( this->value_.x, mem );
- loadAndIncrease( this->value_.y, mem );
- loadAndIncrease( this->value_.z, mem );
- }
- template <> inline void MT_Value<Ogre::Vector3>::exportData( uint8_t*& mem ) const
- {
- saveAndIncrease( this->value_.x, mem );
- saveAndIncrease( this->value_.y, mem );
- saveAndIncrease( this->value_.z, mem );
- }
- template <> inline uint8_t MT_Value<Ogre::Vector3>::getSize() const
- {
- return 3*returnSize(this->value_.x);
- }
- // Ogre::Vector4
- template <> inline void MT_Value<Ogre::Vector4>::importData( uint8_t*& mem )
- {
- loadAndIncrease( this->value_.x, mem );
- loadAndIncrease( this->value_.y, mem );
- loadAndIncrease( this->value_.z, mem );
- loadAndIncrease( this->value_.w, mem );
- }
- template <> inline void MT_Value<Ogre::Vector4>::exportData( uint8_t*& mem ) const
- {
- saveAndIncrease( this->value_.x, mem );
- saveAndIncrease( this->value_.y, mem );
- saveAndIncrease( this->value_.z, mem );
- saveAndIncrease( this->value_.w, mem );
- }
- template <> inline uint8_t MT_Value<Ogre::Vector4>::getSize() const
- {
- return 4*returnSize(this->value_.x);
- }
- template <> inline void MT_Value<void*>::importData( uint8_t*& mem )
- {
- assert(0);
- }
- template <> inline void MT_Value<void*>::exportData( uint8_t*& mem ) const
- {
- assert(0);
- }
- template <> inline uint8_t MT_Value<void*>::getSize() const
- {
- assert(0); return 0;
- }
}
#endif /* _MultiTypeValue_H__ */
Deleted: code/forks/sandbox_light/src/libraries/util/Scope.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Scope.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Scope.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,40 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Static linkage of the two maps in orxonox::ScopeManager.
-*/
-
-#include "Scope.h"
-
-namespace orxonox
-{
- std::map<ScopeID::Value, int> ScopeManager::instanceCounts_s;
- std::map<ScopeID::Value, std::set<ScopeListener*> > ScopeManager::listeners_s;
-}
Deleted: code/forks/sandbox_light/src/libraries/util/Scope.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Scope.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Scope.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,192 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-/**
- at file
- at ingroup SingletonScope
- at brief Declaration of the classes that are needed to use Scopes:
-orxonox::Scope, orxonox::ScopeListener, and orxonox::ScopeManager.
-
- at anchor Scope
-
-A virtual scope can be represented by an instance of class orxonox::Scope. orxonox::Scope<@a scope> is a template
-an its template argument defines the name of the virtual scope. See orxonox::ScopeID for an enumeration of the
-available values for @a scope. The orxonox::Scope object for a given @a scope can be activated or deactivated.
-Instances of orxonox::ScopeListener can register for a given @a scope and will get a notification if the
-corresponding orxonox::Scope object changes its state.
-
-To avoid multiple instances of orxonox::Scope<@a scope> in different libraries, each instance of orxonox::Scope
-registers in orxonox::ScopeManager, where they are linked statically in the util library.
-
-Scopes are usually used to control the creation and destruction of Singletons.
-
- at see orxonox::ScopedSingletonManager
- at see orxonox::Singleton
-*/
-
-#ifndef __Util_Scope_H__
-#define __Util_Scope_H__
-
-#include "UtilPrereqs.h"
-
-#include <cassert>
-#include <map>
-#include <set>
-#include <loki/ScopeGuard.h>
-
-#include "Debug.h"
-
-namespace orxonox
-{
- /**
- @brief The ScopeManager stores the variables of the Scope templates in a statically linked context.
-
- If all Scope objects are managed by this class, they are statically linked in the util library.
- Without this, a new instance of Scope<T> for each T would be created in every library of Orxonox,
- which is of course not the desired behavior.
-
- @see See @ref Scope "this description" for details about the interrelationship of Scope, ScopeListener, and ScopeManager.
- */
- class _UtilExport ScopeManager
- {
- template <ScopeID::Value scope>
- friend class Scope;
- friend class ScopeListener;
-
- private:
- static std::map<ScopeID::Value, int> instanceCounts_s; //!< Counts the number of active instances (>0 means active) for a scope
- static std::map<ScopeID::Value, std::set<ScopeListener*> > listeners_s; //!< Stores all listeners for a scope
- };
-
- /**
- @brief ScopeListeners register themselves in the corresponding Scope and wait for notifications.
- Notifications are sent if a Scope is activated or deactivated.
-
- @see See @ref Scope "this description" for details about the interrelationship of Scope, ScopeListener, and ScopeManager.
- */
- class _UtilExport ScopeListener
- {
- template <ScopeID::Value scope>
- friend class Scope;
-
- protected:
- //! Constructor: Registers the instance.
- ScopeListener(ScopeID::Value scope) : scope_(scope), bActivated_(false)
- { ScopeManager::listeners_s[this->scope_].insert(this); }
- //! Destructor: Unregisters the instance.
- virtual ~ScopeListener()
- { ScopeManager::listeners_s[this->scope_].erase(this); }
-
- //! Gets called if the scope is activated
- virtual void activated() = 0;
- //! Gets called if the scope is deactivated
- virtual void deactivated() = 0;
-
- private:
- ScopeID::Value scope_; //!< Store the scope to unregister on destruction
- bool bActivated_;
- };
-
- /**
- @brief A scope for a given template argument is either active or not.
-
- Objects inheriting from a ScopeListener are registered in a list (different for each scope).
- If the scope gets activated or deactivated, all objects in this list are notified.
-
- @see See @ref Scope "this description" for details about the interrelationship of Scope, ScopeListener, and ScopeManager.
- */
- template <ScopeID::Value scope>
- class Scope
- {
- public:
- //! Constructor: Increases the instance counter and activates the scope if the count went from 0 to 1. Counts >1 don't change anything.
- Scope()
- {
- try
- {
- ScopeManager::instanceCounts_s[scope]++;
- assert(ScopeManager::instanceCounts_s[scope] > 0);
- if (ScopeManager::instanceCounts_s[scope] == 1)
- {
- Loki::ScopeGuard deactivator = Loki::MakeObjGuard(*this, &Scope::deactivateListeners);
- for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
- {
- (*it)->activated();
- (*(it++))->bActivated_ = true;
- }
- deactivator.Dismiss();
- }
- }
- catch (...)
- {
- ScopeManager::instanceCounts_s[scope]--;
- throw;
- }
- }
-
- //! Destructor: Decreases the instance counter and deactivates the scope if the count went from 1 to 0. Counts >0 don't change anything.
- ~Scope()
- {
- ScopeManager::instanceCounts_s[scope]--;
-
- // This shouldn't happen but just to be sure: check if the count is positive
- assert(ScopeManager::instanceCounts_s[scope] >= 0);
- if (ScopeManager::instanceCounts_s[scope] < 0)
- ScopeManager::instanceCounts_s[scope] = 0;
-
- if (ScopeManager::instanceCounts_s[scope] == 0)
- this->deactivateListeners();
- }
-
- //! Deactivates the listeners of this scope in case the scope is destroyed or the construction fails.
- void deactivateListeners()
- {
- for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
- {
- if ((*it)->bActivated_)
- {
- try
- { (*it)->deactivated(); }
- catch (...)
- { COUT(0) << "ScopeListener::deactivated() failed! This MUST NOT happen, fix it!" << std::endl; }
- (*(it++))->bActivated_ = false;
- }
- else
- ++it;
- }
- }
-
- //! Returns true if the scope is active.
- static bool isActive()
- {
- return (ScopeManager::instanceCounts_s[scope] > 0);
- }
- };
-}
-
-#endif /* __Util_Scope_H__ */
Deleted: code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.cc
===================================================================
--- code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,54 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @brief Static linkage of the ScopedSingletonManager maps.
-*/
-
-#include "ScopedSingletonManager.h"
-
-namespace orxonox
-{
- /*static*/ std::map<std::string, ScopedSingletonManager*>& ScopedSingletonManager::getManagers()
- {
- static std::map<std::string, ScopedSingletonManager*> managers;
- return managers;
- }
- /*static*/ ScopedSingletonManager::ManagerMultiMap& ScopedSingletonManager::getManagersByScope()
- {
- static ManagerMultiMap managers;
- return managers;
- }
-
- /*static*/ void ScopedSingletonManager::addManager(ScopedSingletonManager* manager)
- {
- getManagers()[manager->className_] = manager;
- getManagersByScope().insert(std::make_pair(manager->scope_, manager));
- }
-}
Deleted: code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/ScopedSingletonManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,282 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup SingletonScope
- @brief Definition of orxonox::ScopedSingletonManager, orxonox::ClassScopedSingletonManager, and the ManageScopedSingleton macro.
-
- ScopedSingletonManager is used to create and destroy Singletons that belong to
- a given Scope. For each one of these singletons, the macro ManageScopedSingleton()
- has to be called to register the singleton with orxonox::ScopedSingletonManager.
-
- See @ref SingletonExample "this code" for an example.
-
- @see orxonox::Singleton
- @see orxonox::Scope
-*/
-
-#ifndef __ScopedSingletonManager_H__
-#define __ScopedSingletonManager_H__
-
-#include "UtilPrereqs.h"
-
-#include <cassert>
-#include <map>
-#include "util/Exception.h"
-#include "util/Scope.h"
-#include "util/Singleton.h"
-
-/**
- @brief Registers an orxonox::Singleton with orxonox::ScopedSingletonManager.
- @param className The name of the singleton class
- @param scope The scope in which the singleton should exist
- @param allowedToFail If true, the singleton is allowed to fail and thus a try-catch block is used when creating the singleton.
-
- If this macro is called for a singleton, it is registered with ScopedSingletonManager
- and will thus be created if its scope becomes active and destroyed if is deactivated.
-*/
-#define ManageScopedSingleton(className, scope, allowedToFail) \
- className* className::singletonPtr_s = NULL; \
- static ClassScopedSingletonManager<className, scope, allowedToFail> className##ScopedSingletonManager(#className)
-
-namespace orxonox
-{
- class OrxonoxClass;
-
- /**
- @brief Base class of ClassScopedSingletonManager, implements some static functions
- used to dispatch calls to preUpdate and postUpdate to all instances of this class.
- It also keeps track of all existing ScopedSingletonManagers and stores them in a
- map, sorted by the scope they belong to.
- */
- class _UtilExport ScopedSingletonManager
- {
- public:
- /// Constructor: Initializes all the values
- ScopedSingletonManager(const std::string& className, ScopeID::Value scope)
- : className_(className)
- , scope_(scope)
- { }
- virtual ~ScopedSingletonManager() { }
-
- /// Adds a new instance of ScopedSingletonManager to the map.
- static void addManager(ScopedSingletonManager* manager);
-
- /// Calls preUpdate in all instances of ScopedSingletonManager that are registered in the map.
- template<ScopeID::Value scope>
- static void preUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it)
- it->second->preUpdate(time);
- }
- virtual void preUpdate(const Clock& time) = 0;
-
- /// Calls postUpdate in all instances of ScopedSingletonManager that are registered in the map.
- template<ScopeID::Value scope>
- static void postUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it)
- it->second->postUpdate(time);
- }
- virtual void postUpdate(const Clock& time) = 0;
-
- static std::map<std::string, ScopedSingletonManager*>& getManagers();
- typedef std::multimap<ScopeID::Value, ScopedSingletonManager*> ManagerMultiMap;
- static ManagerMultiMap& getManagersByScope();
-
- protected:
- const std::string className_; ///< The name of the scoped singleton class that is managed by this object
- const ScopeID::Value scope_; ///< The scope of the singleton that is managed by this object
- };
-
- /**
- @anchor ClassScopedSingletonManager
-
- @brief Manages a scoped singleton for a given scope.
- @param T The managed singleton class
- @param scope The scope in which the singleton @a T should be active
- @param allowedToFail If true, a specialization of this template is used, that uses try-catch blocks to handle possible failures.
-
- This class inherits from ScopeListener for the given scope and thus its functions
- activated() and deactivated() are called whenever the Scope changes its state.
-
- If the Scope is activated, a new instance of @a T (which must be a singleton) is created.
- If the Scope is deactivated, the singleton is destroyed.
-
- @see Singleton
- */
- template <class T, ScopeID::Value scope, bool allowedToFail>
- class ClassScopedSingletonManager : public ScopedSingletonManager, public ScopeListener
- {
- public:
- //! Constructor: Initializes the singleton pointer and passes the scope to ScopedSingletonManager and ScopeListener
- ClassScopedSingletonManager(const std::string& className)
- : ScopedSingletonManager(className, scope)
- , ScopeListener(scope)
- , singletonPtr_(NULL)
- {
- ScopedSingletonManager::addManager(this);
- }
-
- ~ClassScopedSingletonManager()
- {
- }
-
- //! Called if the Scope of the Singleton gets active (creates the instance)
- void activated()
- {
- assert(singletonPtr_ == NULL);
- singletonPtr_ = new T();
- }
-
- //! Called if the Scope of this Singleton gets deactivated (destroys the instance)
- void deactivated()
- {
- assert(singletonPtr_ != NULL);
- this->destroy(singletonPtr_);
- singletonPtr_ = NULL;
- }
-
- //! Destroys the singleton instance - overloaded for OrxonoxClass, calls OrxonoxClass::destroy()
- void destroy(OrxonoxClass*)
- {
- singletonPtr_->destroy();
- }
- //! Destroys the singleton instance - overloaded for all other pointers, calls delete
- void destroy(void*)
- {
- delete singletonPtr_;
- }
-
- //! Called every frame by the ScopedSingletonManager
- void preUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- // assuming T inherits Singleton<T>
- singletonPtr_->preUpdateSingleton(time);
- }
-
- //! Called every frame by the ScopedSingletonManager
- void postUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- // assuming T inherits Singleton<T>
- singletonPtr_->postUpdateSingleton(time);
- }
-
- private:
- T* singletonPtr_; ///< Unique instance of the singleton class @a T
- };
-
- /**
- @brief This class partially spezializes ClassScopedSingletonManager for classes @a T that are allowed to fail.
- @param T The managed singleton class
- @param scope The scope in which the singleton @a T should be active
-
- Because @a T could fail when being created, this partial spezialization of ClassScopedSingletonManager
- uses a try-catch block to handle exceptions.
-
- See @ref ClassScopedSingletonManager for a full documentation of the basis template.
- */
- template <class T, ScopeID::Value scope>
- class ClassScopedSingletonManager<T, scope, true> : public ScopedSingletonManager, public ScopeListener
- {
- public:
- //! Constructor: Initializes the singleton pointer and passes the scope to ScopedSingletonManager and ScopeListener
- ClassScopedSingletonManager(const std::string& className)
- : ScopedSingletonManager(className, scope)
- , ScopeListener(scope)
- , singletonPtr_(NULL)
- {
- ScopedSingletonManager::addManager(this);
- }
-
- ~ClassScopedSingletonManager()
- {
- }
-
- //! Called if the Scope of the Singleton gets active (creates the instance)
- void activated()
- {
- assert(singletonPtr_ == NULL);
- try
- { singletonPtr_ = new T(); }
- catch (const InitialisationAbortedException& ex)
- { COUT(3) << ex.getDescription() << std::endl; }
- catch (...)
- { COUT(1) << "Singleton creation failed: " << Exception::handleMessage() << std::endl; }
- }
-
- //! Called if the Scope of this Singleton gets deactivated (destroys the instance)
- void deactivated()
- {
- if (singletonPtr_ != NULL)
- {
- this->destroy(singletonPtr_);
- singletonPtr_ = NULL;
- }
- }
-
- //! Destroys the singleton instance - overloaded for OrxonoxClass, calls OrxonoxClass::destroy()
- void destroy(OrxonoxClass* ptr)
- {
- singletonPtr_->destroy();
- }
- //! Destroys the singleton instance - overloaded for void*, calls delete
- void destroy(void* ptr)
- {
- delete singletonPtr_;
- }
-
- //! Called every frame by the ScopedSingletonManager
- void preUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- // assuming T inherits Singleton<T>
- if (singletonPtr_ != NULL)
- singletonPtr_->preUpdateSingleton(time);
- }
-
- //! Called every frame by the ScopedSingletonManager
- void postUpdate(const Clock& time)
- {
- assert(Scope<scope>::isActive());
- // assuming T inherits Singleton<T>
- if (singletonPtr_ != NULL)
- singletonPtr_->postUpdateSingleton(time);
- }
-
- private:
- T* singletonPtr_; ///< Unique instance of the singleton class @a T
- };
-}
-
-#endif /* __ScopedSingletonManager_H__ */
Deleted: code/forks/sandbox_light/src/libraries/util/Serialise.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/Serialise.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/Serialise.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,736 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oliver Scheuss
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file
- @ingroup Util
- @brief Functions to serialise most of the types/classed used in Orxonox
-*/
-
-#ifndef _Serialise_H__
-#define _Serialise_H__
-
-#include "UtilPrereqs.h"
-
-#include <cstring>
-#include <set>
-#include "Math.h"
-#include "mbool.h"
-
-namespace orxonox{
-
- /** @brief returns the size of the variable in a datastream */
- template <class T> inline uint32_t returnSize( const T& variable );
- /** @brief loads the value of a variable out of the bytestream and increases the mem pointer */
- template <class T> inline void loadAndIncrease( const T& variable, uint8_t*& mem );
- /** @brief saves the value of a variable into the bytestream and increases the mem pointer */
- template <class T> inline void saveAndIncrease( const T& variable, uint8_t*& mem );
- /** @brief checks whether the variable of type T is the same as in the bytestream */
- template <class T> inline bool checkEquality( const T& variable, uint8_t* mem );
-
-
- // =========== char*
-
- inline uint32_t returnSize( char*& variable )
- {
- return strlen(variable)+1;
- }
-
- inline void saveAndIncrease( char*& variable, uint8_t*& mem )
- {
- strcpy((char*)mem, variable);
- mem += returnSize(variable);
- }
-
- inline void loadAndIncrease( char*& variable, uint8_t*& mem )
- {
- if( variable )
- delete variable;
- uint32_t len = strlen((char*)mem)+1;
- variable = new char[len];
- strcpy((char*)variable, (char*)mem);
- mem += len;
- }
-
- inline bool checkEquality( char*& variable, uint8_t* mem )
- {
- return strcmp(variable, (char*)mem)==0;
- }
-
-// =================== Template specialisation stuff =============
-
-// =========== bool
-
- template <> inline uint32_t returnSize( const bool& variable )
- {
- return sizeof(uint8_t);
- }
-
- template <> inline void loadAndIncrease( const bool& variable, uint8_t*& mem )
- {
- *(uint8_t*)( &variable ) = *static_cast<uint8_t*>(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const bool& variable, uint8_t*& mem )
- {
- *static_cast<uint8_t*>(mem) = *(uint8_t*)( &variable );
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const bool& variable, uint8_t* mem )
- {
- return *static_cast<uint8_t*>(mem) == *(uint8_t*)( &variable );
- }
-
-// =========== char
-
- template <> inline uint32_t returnSize( const char& variable )
- {
- return sizeof(uint8_t);
- }
-
- template <> inline void loadAndIncrease( const char& variable, uint8_t*& mem )
- {
- *(uint8_t*)( &variable ) = *static_cast<uint8_t*>(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const char& variable, uint8_t*& mem )
- {
- *static_cast<uint8_t*>(mem) = *(uint8_t*)( &variable );
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const char& variable, uint8_t* mem )
- {
- return *static_cast<uint8_t*>(mem) == *(uint8_t*)( &variable );
- }
-
-// =========== unsigned char
-
- template <> inline uint32_t returnSize( const unsigned char& variable )
- {
- return sizeof(uint8_t);
- }
-
- template <> inline void loadAndIncrease( const unsigned char& variable, uint8_t*& mem )
- {
- *(uint8_t*)( &variable ) = *static_cast<uint8_t*>(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const unsigned char& variable, uint8_t*& mem )
- {
- *static_cast<uint8_t*>(mem) = *(uint8_t*)( &variable );
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const unsigned char& variable, uint8_t* mem )
- {
- return *static_cast<uint8_t*>(mem) == *(uint8_t*)( &variable );
- }
-
-// =========== short
-
- template <> inline uint32_t returnSize( const short& variable )
- {
- return sizeof(int16_t);
- }
-
- template <> inline void loadAndIncrease( const short& variable, uint8_t*& mem )
- {
- *(short*)( &variable ) = *(int16_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const short& variable, uint8_t*& mem )
- {
- *(int16_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const short& variable, uint8_t* mem )
- {
- return *(int16_t*)(mem) == static_cast<int16_t>(variable);
- }
-
-// =========== unsigned short
-
- template <> inline uint32_t returnSize( const unsigned short& variable )
- {
- return sizeof(uint16_t);
- }
-
- template <> inline void loadAndIncrease( const unsigned short& variable, uint8_t*& mem )
- {
- *(unsigned short*)( &variable ) = *(uint16_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const unsigned short& variable, uint8_t*& mem )
- {
- *(uint16_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const unsigned short& variable, uint8_t* mem )
- {
- return *(uint16_t*)(mem) == variable;
- }
-
-// =========== int
-
- template <> inline uint32_t returnSize( const int& variable )
- {
- return sizeof(int32_t);
- }
-
- template <> inline void loadAndIncrease( const int& variable, uint8_t*& mem )
- {
- *(int *)( &variable ) = *(int32_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const int& variable, uint8_t*& mem )
- {
- *(int32_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const int& variable, uint8_t* mem )
- {
- return *(int32_t*)(mem) == variable;
- }
-
-// =========== unsigned int
-
- template <> inline uint32_t returnSize( const unsigned int& variable )
- {
- return sizeof(uint32_t);
- }
-
- template <> inline void loadAndIncrease( const unsigned int& variable, uint8_t*& mem )
- {
- *(unsigned int*)( &variable ) = *(uint32_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const unsigned int& variable, uint8_t*& mem )
- {
- *(uint32_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const unsigned int& variable, uint8_t* mem )
- {
- return *(uint32_t*)(mem) == variable;
- }
-
-// =========== long
-
- template <> inline uint32_t returnSize( const long& variable )
- {
- return sizeof(int32_t);
- }
-
- template <> inline void loadAndIncrease( const long& variable, uint8_t*& mem )
- {
- *(long*)( &variable ) = *(int32_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const long& variable, uint8_t*& mem )
- {
- *(int32_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const long& variable, uint8_t* mem )
- {
- return *(int32_t*)(mem) == variable;
- }
-
-// =========== unsigned long
-
- template <> inline uint32_t returnSize( const unsigned long& variable )
- {
- return sizeof(uint32_t);
- }
-
- template <> inline void loadAndIncrease( const unsigned long& variable, uint8_t*& mem )
- {
- *(unsigned long*)( &variable ) = *(uint32_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const unsigned long& variable, uint8_t*& mem )
- {
- *(uint32_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const unsigned long& variable, uint8_t* mem )
- {
- return *(uint32_t*)(mem) == variable;
- }
-
-// =========== long long
-
- template <> inline uint32_t returnSize( const long long& variable )
- {
- return sizeof(int64_t);
- }
-
- template <> inline void loadAndIncrease( const long long& variable, uint8_t*& mem )
- {
- *(long long*)( &variable ) = *(int64_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const long long& variable, uint8_t*& mem )
- {
- *(int64_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const long long& variable, uint8_t* mem )
- {
- return *(int64_t*)(mem) == variable;
- }
-
-// =========== unsigned long long
-
- template <> inline uint32_t returnSize( const unsigned long long& variable )
- {
- return sizeof(uint64_t);
- }
-
- template <> inline void loadAndIncrease( const unsigned long long& variable, uint8_t*& mem )
- {
- *(unsigned long long*)( &variable ) = *(uint64_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const unsigned long long& variable, uint8_t*& mem )
- {
- *(uint64_t*)(mem) = variable;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const unsigned long long& variable, uint8_t* mem )
- {
- return *(uint64_t*)(mem) == variable;
- }
-
-// =========== float
-
- template <> inline uint32_t returnSize( const float& variable )
- {
- return sizeof(uint32_t);
- }
-
- template <> inline void loadAndIncrease( const float& variable, uint8_t*& mem )
- {
- *(uint32_t*)( &variable ) = *(uint32_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const float& variable, uint8_t*& mem )
- {
- *(uint32_t*)(mem) = *(uint32_t*)( &variable );
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const float& variable, uint8_t* mem )
- {
- return *(uint32_t*)(mem) == *(uint32_t*)( &variable );
- }
-
-// =========== double
-
- template <> inline uint32_t returnSize( const double& variable )
- {
- return sizeof(uint64_t);
- }
-
- template <> inline void loadAndIncrease( const double& variable, uint8_t*& mem )
- {
- *(uint64_t*)( &variable ) = *(uint64_t*)(mem);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const double& variable, uint8_t*& mem )
- {
- *(uint64_t*)(mem) = *(uint64_t*)( &variable );
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const double& variable, uint8_t* mem )
- {
- return *(uint64_t*)(mem) == *(uint64_t*)( &variable );
- }
-
-// =========== long double
-
- template <> inline uint32_t returnSize( const long double& variable )
- {
- return sizeof(uint64_t);
- }
-
- template <> inline void loadAndIncrease( const long double& variable, uint8_t*& mem )
- {
- double temp;
- memcpy(&temp, mem, sizeof(uint64_t));
- *(long double*)( &variable ) = static_cast<long double>(temp);
- mem += returnSize( variable );
- }
-
- template <> inline void saveAndIncrease( const long double& variable, uint8_t*& mem )
- {
- double temp = static_cast<double>(variable);
- memcpy(mem, &temp, sizeof(uint64_t));
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const long double& variable, uint8_t* mem )
- {
- double temp = static_cast<double>(variable);
- return memcmp(&temp, mem, sizeof(uint64_t))==0;
- }
-
-// =========== string
-
- template <> inline uint32_t returnSize( const std::string& variable )
- {
- return variable.length()+1;
- }
-
- template <> inline void saveAndIncrease( const std::string& variable, uint8_t*& mem )
- {
- memcpy(mem, variable.c_str(), variable.length()+1);
- mem += variable.length()+1;
- }
-
- template <> inline void loadAndIncrease( const std::string& variable, uint8_t*& mem )
- {
- *(std::string*)( &variable ) = (const char *)mem;
- mem += variable.length()+1;
- }
-
- template <> inline bool checkEquality( const std::string& variable, uint8_t* mem )
- {
- //return std::string((const char*)mem)==variable;
- return (const char*)mem==variable;
- }
-
-// =========== Degree
-
- template <> inline uint32_t returnSize( const Degree& variable )
- {
- return sizeof(Ogre::Real);
- }
-
- template <> inline void saveAndIncrease( const Degree& variable, uint8_t*& mem )
- {
- Ogre::Real r = variable.valueDegrees();
- memcpy(mem, &r, returnSize( variable ));
- mem += returnSize( variable );
- }
-
- template <> inline void loadAndIncrease( const Degree& variable, uint8_t*& mem )
- {
- Ogre::Real* r = (Ogre::Real*)mem;
- (Degree&)variable = *r;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const Degree& variable, uint8_t* mem )
- {
- Ogre::Real* r = (Ogre::Real*)mem;
- return variable==Degree(*r);
- }
-
-// =========== Radian
-
- template <> inline uint32_t returnSize( const Radian& variable )
- {
- return sizeof(Ogre::Real);
- }
-
- template <> inline void saveAndIncrease( const Radian& variable, uint8_t*& mem )
- {
- Ogre::Real r = variable.valueRadians();
- memcpy(mem, &r, returnSize( variable ));
- mem += returnSize( variable );
- }
-
- template <> inline void loadAndIncrease( const Radian& variable, uint8_t*& mem )
- {
- Ogre::Real* r = (Ogre::Real*)mem;
- (Radian&)variable = *r;
- mem += returnSize( variable );
- }
-
- template <> inline bool checkEquality( const Radian& variable, uint8_t* mem )
- {
- Ogre::Real* r = (Ogre::Real*)mem;
- return variable==Degree(*r);
- }
-
- // =========== Vector2
-
- template <> inline uint32_t returnSize( const Vector2& variable )
- {
- return returnSize( variable.x )+returnSize( variable.y );
- }
-
- template <> inline void saveAndIncrease( const Vector2& variable, uint8_t*& mem )
- {
- saveAndIncrease( variable.x, mem );
- saveAndIncrease( variable.y, mem );
- }
-
- template <> inline void loadAndIncrease( const Vector2& variable, uint8_t*& mem )
- {
- loadAndIncrease( variable.x, mem );
- loadAndIncrease( variable.y, mem );
- }
-
- template <> inline bool checkEquality( const Vector2& variable, uint8_t* mem )
- {
- return checkEquality(variable.x, mem) && checkEquality(variable.y, mem+returnSize(variable.x));
- }
-
- // =========== Vector3
-
- template <> inline uint32_t returnSize( const Vector3& variable )
- {
- return returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z );
- }
-
- template <> inline void saveAndIncrease( const Vector3& variable, uint8_t*& mem )
- {
- saveAndIncrease( variable.x, mem );
- saveAndIncrease( variable.y, mem );
- saveAndIncrease( variable.z, mem );
- }
-
- template <> inline void loadAndIncrease( const Vector3& variable, uint8_t*& mem )
- {
- loadAndIncrease( variable.x, mem );
- loadAndIncrease( variable.y, mem );
- loadAndIncrease( variable.z, mem );
- }
-
- template <> inline bool checkEquality( const Vector3& variable, uint8_t* mem )
- {
- return checkEquality(variable.x, mem) && checkEquality(variable.y, mem+returnSize(variable.x)) &&
- checkEquality(variable.z, mem+returnSize(variable.x)+returnSize(variable.y));
- }
-
- // =========== Vector4
-
- template <> inline uint32_t returnSize( const Vector4& variable )
- {
- return returnSize( variable.w )+returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z );
- }
-
- template <> inline void saveAndIncrease( const Vector4& variable, uint8_t*& mem )
- {
- saveAndIncrease( variable.w, mem );
- saveAndIncrease( variable.x, mem );
- saveAndIncrease( variable.y, mem );
- saveAndIncrease( variable.z, mem );
- }
-
- template <> inline void loadAndIncrease( const Vector4& variable, uint8_t*& mem )
- {
- loadAndIncrease( variable.w, mem );
- loadAndIncrease( variable.x, mem );
- loadAndIncrease( variable.y, mem );
- loadAndIncrease( variable.z, mem );
- }
-
- template <> inline bool checkEquality( const Vector4& variable, uint8_t* mem )
- {
- return checkEquality(variable.w, mem) && checkEquality(variable.x, mem+returnSize(variable.w)) &&
- checkEquality(variable.y, mem+returnSize(variable.w)+returnSize(variable.x)) &&
- checkEquality(variable.z, mem+returnSize(variable.w)+returnSize(variable.x)+returnSize(variable.y));
- }
-
- // =========== Quaternion
-
- template <> inline uint32_t returnSize( const Quaternion& variable )
- {
- return returnSize( variable.w )+returnSize( variable.x )+returnSize( variable.y )+returnSize( variable.z );
- }
-
- template <> inline void saveAndIncrease( const Quaternion& variable, uint8_t*& mem )
- {
- saveAndIncrease( variable.w, mem );
- saveAndIncrease( variable.x, mem );
- saveAndIncrease( variable.y, mem );
- saveAndIncrease( variable.z, mem );
- }
-
- template <> inline void loadAndIncrease( const Quaternion& variable, uint8_t*& mem )
- {
- loadAndIncrease( variable.w, mem );
- loadAndIncrease( variable.x, mem );
- loadAndIncrease( variable.y, mem );
- loadAndIncrease( variable.z, mem );
- }
-
- template <> inline bool checkEquality( const Quaternion& variable, uint8_t* mem )
- {
- return checkEquality(variable.w, mem) && checkEquality(variable.x, mem+returnSize(variable.w)) &&
- checkEquality(variable.y, mem+returnSize(variable.w)+returnSize(variable.x)) &&
- checkEquality(variable.z, mem+returnSize(variable.w)+returnSize(variable.x)+returnSize(variable.y));
- }
-
- // =========== ColourValue
-
- template <> inline uint32_t returnSize( const ColourValue& variable )
- {
- return returnSize( variable.r )+returnSize( variable.g )+returnSize( variable.b )+returnSize( variable.a );
- }
-
- template <> inline void saveAndIncrease( const ColourValue& variable, uint8_t*& mem )
- {
- saveAndIncrease( variable.r, mem );
- saveAndIncrease( variable.g, mem );
- saveAndIncrease( variable.b, mem );
- saveAndIncrease( variable.a, mem );
- }
-
- template <> inline void loadAndIncrease( const ColourValue& variable, uint8_t*& mem )
- {
- loadAndIncrease( variable.r, mem );
- loadAndIncrease( variable.g, mem );
- loadAndIncrease( variable.b, mem );
- loadAndIncrease( variable.a, mem );
- }
-
- template <> inline bool checkEquality( const ColourValue& variable, uint8_t* mem )
- {
- return checkEquality(variable.r, mem) && checkEquality(variable.g, mem+returnSize(variable.r)) &&
- checkEquality(variable.b, mem+returnSize(variable.r)+returnSize(variable.g)) &&
- checkEquality(variable.a, mem+returnSize(variable.r)+returnSize(variable.g)+returnSize(variable.b));
- }
-
- // =========== mbool
-
- template <> inline uint32_t returnSize( const mbool& variable )
- {
- return returnSize( (unsigned char&)((mbool&)variable).getMemory() );
- }
-
- template <> inline void saveAndIncrease( const mbool& variable, uint8_t*& mem )
- {
- saveAndIncrease( (unsigned char&)((mbool&)variable).getMemory(), mem );
- }
-
- template <> inline void loadAndIncrease( const mbool& variable, uint8_t*& mem )
- {
- loadAndIncrease( (unsigned char&)((mbool&)variable).getMemory(), mem );
- }
-
- template <> inline bool checkEquality( const mbool& variable, uint8_t* mem )
- {
- return checkEquality( (unsigned char&)((mbool&)variable).getMemory(), mem );
- }
-
- // =========== std::set
-
- template <class T> inline uint32_t returnSize( const std::set<T>& variable )
- {
- uint32_t tempsize = sizeof(uint32_t); // for the number of entries
- for( typename std::set<T>::iterator it=((std::set<T>*)(&variable))->begin(); it!=((std::set<T>*)(&variable))->end(); ++it)
- tempsize += returnSize( *it );
- return tempsize;
- }
-
- template <class T> inline void saveAndIncrease( const std::set<T>& variable, uint8_t*& mem )
- {
- typename std::set<T>::const_iterator it = variable.begin();
- saveAndIncrease( (uint32_t)variable.size(), mem );
- for( ; it!=variable.end(); ++it )
- saveAndIncrease( *it, mem );
- }
-
- template <class T> inline void loadAndIncrease(std::set<T>& variable, uint8_t*& mem )
- {
- uint32_t nrOfElements = 0;
- loadAndIncrease( nrOfElements, mem );
- typename std::set<T>::iterator it = variable.begin();
- for( uint32_t i = 0; i<nrOfElements; ++i )
- {
- T temp;
- loadAndIncrease(temp, mem);
- while( it!=variable.end() && *it!=temp )
- {
- variable.erase(it++);
- ++it;
- }
- if( it==variable.end() )
- {
- variable.insert(temp);
- }
- }
- }
-
- template <class T> inline bool checkEquality( const std::set<T>& variable, uint8_t* mem )
- {
- uint8_t* temp = mem;
- uint32_t nrOfElements;
- loadAndIncrease(nrOfElements, mem);
- if( variable.size() == nrOfElements )
- {
- T tempT;
- for( uint32_t i=0; i<nrOfElements; ++i )
- {
- loadAndIncrease(tempT, mem);
- if( variable.find(tempT) == variable.end() )
- {
- mem = temp;
- return false;
- }
- }
- }
- else
- {
- mem = temp;
- return false;
- }
- return true;
- }
-}
-
-
-#endif
Modified: code/forks/sandbox_light/src/libraries/util/UtilPrereqs.h
===================================================================
--- code/forks/sandbox_light/src/libraries/util/UtilPrereqs.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/libraries/util/UtilPrereqs.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -63,15 +63,6 @@
namespace orxonox
{
- namespace ScopeID
- {
- //!A list of available scopes for the Scope template.
- enum Value
- {
- Root,
- Graphics
- };
- }
}
//-----------------------------------------------------------------------
@@ -82,17 +73,11 @@
{
class Clock;
class Exception;
- class ExprParser;
class IntVector2;
class IntVector3;
class MultiType;
class OutputHandler;
class OutputListener;
- template <ScopeID::Value>
- class Scope;
- template <class, ScopeID::Value>
- class ScopedSingleton;
- class ScopeListener;
class SignalHandler;
template <class T>
class Singleton;
Modified: code/forks/sandbox_light/src/orxonox/CMakeLists.txt
===================================================================
--- code/forks/sandbox_light/src/orxonox/CMakeLists.txt 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/CMakeLists.txt 2011-02-17 04:47:22 UTC (rev 7908)
@@ -23,66 +23,17 @@
)
SET_SOURCE_FILES(ORXONOX_SRC_FILES
- Level.cc
- LevelInfo.cc
- LevelManager.cc
Main.cc
- MoodManager.cc
- PawnManager.cc
- PlayerManager.cc
- Radar.cc
- ChatHistory.cc
- ChatInputHandler.cc
-# Test.cc
-COMPILATION_BEGIN SceneCompilation.cc
- CameraManager.cc
- Scene.cc
-COMPILATION_END
)
-ADD_SUBDIRECTORY(collisionshapes)
-ADD_SUBDIRECTORY(controllers)
-ADD_SUBDIRECTORY(gamestates)
-ADD_SUBDIRECTORY(gametypes)
-ADD_SUBDIRECTORY(graphics)
-ADD_SUBDIRECTORY(infos)
-ADD_SUBDIRECTORY(interfaces)
-ADD_SUBDIRECTORY(items)
-ADD_SUBDIRECTORY(overlays)
-ADD_SUBDIRECTORY(pickup)
-ADD_SUBDIRECTORY(sound)
-ADD_SUBDIRECTORY(weaponsystem)
-ADD_SUBDIRECTORY(worldentities)
-
ORXONOX_ADD_LIBRARY(orxonox
FIND_HEADER_FILES
- TOLUA_FILES
- ChatInputHandler.h
- LevelInfo.h
- LevelManager.h
- MoodManager.h
- controllers/HumanController.h
- infos/PlayerInfo.h
- sound/SoundManager.h
PCH_FILE
OrxonoxPrecompiledHeaders.h
LINK_LIBRARIES
${Boost_FILESYSTEM_LIBRARY}
${Boost_SYSTEM_LIBRARY} # Filesystem dependency
- ${Boost_THREAD_LIBRARY}
- ${Boost_DATE_TIME_LIBRARY} # Thread dependency
- ${OGRE_LIBRARY}
- ${OPENAL_LIBRARY}
- ${ALUT_LIBRARY}
- ${VORBISFILE_LIBRARY}
- ${VORBIS_LIBRARY}
- ${OGG_LIBRARY}
- tinyxml_orxonox
- tolua_orxonox
- bullet_orxonox
util
core
- network
- tools
SOURCE_FILES ${ORXONOX_SRC_FILES}
)
Deleted: code/forks/sandbox_light/src/orxonox/CameraManager.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/CameraManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/CameraManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,127 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Benjamin Knecht
- * Co-authors:
- * Fabian 'x3n' Landau
- *
- */
-
-#include "CameraManager.h"
-
-#include <OgreSceneManager.h>
-#include <OgreViewport.h>
-#include <OgreCompositorManager.h>
-
-#include "util/StringUtils.h"
-#include "util/ScopedSingletonManager.h"
-#include "core/GameMode.h"
-#include "core/GraphicsManager.h"
-#include "core/GUIManager.h"
-#include "core/ObjectList.h"
-#include "tools/Shader.h"
-#include "graphics/Camera.h"
-#include "Scene.h"
-
-namespace orxonox
-{
- ManageScopedSingleton(CameraManager, ScopeID::Graphics, false);
-
- CameraManager::CameraManager()
- : viewport_(GraphicsManager::getInstance().getViewport())
- {
- assert(GameMode::showsGraphics());
- }
-
- CameraManager::~CameraManager()
- {
- GUIManager::getInstance().setCamera(0);
- }
-
- Camera* CameraManager::getActiveCamera() const
- {
- if (!this->cameraList_.empty())
- return this->cameraList_.front();
- else
- return 0;
- }
-
- void CameraManager::requestFocus(Camera* camera)
- {
- // notify old camera (if it exists)
- if (!this->cameraList_.empty())
- this->cameraList_.front()->removeFocus();
-
- camera->setFocus();
-
- // make sure we don't add it twice
- for (std::list<Camera*>::iterator it = this->cameraList_.begin(); it != this->cameraList_.end();)
- if ((*it) == camera)
- this->cameraList_.erase(it++);
- else
- ++it;
- // add to list
- this->cameraList_.push_front(camera);
- }
-
- void CameraManager::releaseFocus(Camera* camera)
- {
- // notify the cam of releasing the focus
- if (!this->cameraList_.empty() && this->cameraList_.front() == camera)
- {
- camera->removeFocus();
- this->cameraList_.pop_front();
-
- // set new focus if possible
- if (!this->cameraList_.empty())
- this->cameraList_.front()->setFocus();
- }
- else
- this->cameraList_.remove(camera);
- }
-
- void CameraManager::useCamera(Ogre::Camera* camera)
- {
- // This workaround is needed to avoid weird behaviour with active compositors while
- // switching the camera (like freezing the image)
- //
- // Last known Ogre version needing this workaround:
- // 1.4.8
- // 1.7.2
-
- // deactivate all compositors
- {
- Ogre::ResourceManager::ResourceMapIterator iterator = Ogre::CompositorManager::getSingleton().getResourceIterator();
- while (iterator.hasMoreElements())
- Ogre::CompositorManager::getSingleton().setCompositorEnabled(this->viewport_, iterator.getNext()->getName(), false);
- }
-
- this->viewport_->setCamera(camera);
- GUIManager::getInstance().setCamera(camera);
-
- // reactivate all visible compositors
- {
- for (ObjectList<Shader>::iterator it = ObjectList<Shader>::begin(); it != ObjectList<Shader>::end(); ++it)
- it->updateVisibility();
- }
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/CameraManager.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/CameraManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/CameraManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,73 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Benjamin Knecht
- * Co-authors:
- * Fabian 'x3n' Landau
- *
- */
-
- /**
- @file
- @brief Handles the instances of Camera class
- @author Benjamin Knecht <beni_at_orxonox.net>
- */
-
-#ifndef _CameraManager_H__
-#define _CameraManager_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <cassert>
-#include <list>
-#include "util/OgreForwardRefs.h"
-#include "util/Singleton.h"
-#include "core/OrxonoxClass.h"
-#include "core/SmartPtr.h"
-
-namespace orxonox
-{
- class _OrxonoxExport CameraManager : public Singleton<CameraManager>, public OrxonoxClass
- {
- friend class Singleton<CameraManager>;
- public:
- CameraManager();
- ~CameraManager();
-
- Camera* getActiveCamera() const;
-
- void requestFocus(Camera* camera);
- void releaseFocus(Camera* camera);
-
- void useCamera(Ogre::Camera* camera);
-
- private:
- CameraManager(const CameraManager&); // don't use
-
- std::list<Camera*> cameraList_;
- Ogre::Viewport* viewport_;
-
- static CameraManager* singletonPtr_s;
- };
-}
-
-#endif /* _CameraManager_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/ChatHistory.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/ChatHistory.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/ChatHistory.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,195 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Sandro 'smerkli' Merkli
- * Co-authors:
- * ...
- *
- */
-
-#include "ChatHistory.h"
-#include "util/ScopedSingletonManager.h"
-
-#ifndef CHATTEST
-namespace orxonox
-{
- /* singleton */
- ManageScopedSingleton( ChatHistory, ScopeID::Root, false );
-#endif
-
- /* constructor */
-#ifndef CHATTEST
- //ChatHistory::ChatHistory( BaseObject* creator ) : BaseObject(creator)
- ChatHistory::ChatHistory()
-#else
- ChatHistory::ChatHistory()
-#endif
- {
- /* register the object */
-#ifndef CHATTEST
- RegisterObject(ChatHistory);
-#endif
-
- this->hist_log_enabled = true;
-
- /* Read setting for logfiles */
- if( hist_log_enabled ) /* NOTE Make this a check for the logfile setting */
- { this->chat_hist_openlog();
-
- /* push starting line */
- this->chat_hist_logline( "--- Logfile opened ---" );
- }
-
- /* Read setting for maximum number of lines and set limit */
- this->hist_maxlines = 200; /* NOTE to be changed, 200 is just for testing */
- }
-
- /* destructor */
- ChatHistory::~ChatHistory()
- {
- chat_hist_closelog();
-
- /* clear list */
- this->hist_buffer.clear();
- }
-
- /* react to incoming chat */
- void ChatHistory::incomingChat(const std::string& message,
- unsigned int senderID)
- {
- /* --> a) look up the actual name of the sender */
- std::string text;
-
-#ifndef CHATTEST
- /* get sender ID and prepend it to the message */
- if (senderID != CLIENTID_UNKNOWN)
- {
- /* if we can't find anything, use "unknown" as default */
- std::string name = "unknown";
-
- PlayerInfo* player = PlayerManager::getInstance().getClient(senderID);
- if (player)
- name = player->getName();
-
- text = name + ": " + message;
- }
- else
- text = message;
-#else
- text = message;
-#endif
-
- /* add the line to the history */
- this->chat_hist_addline( text );
-
- /* add the line to the log */
- this->chat_hist_logline( text );
- }
-
- /* Synchronize logfile onto the hard drive */ /* MARK MARK */
- int ChatHistory::syncLog()
- {
- //if( this->hist_logfile )
- //this->hist_logfile.sync();
- return 0;
- }
-
- /* add a line to this history */
- int ChatHistory::chat_hist_addline( const std::string& toadd )
- {
- /* crop history at the end if it's too large */
- while( this->hist_buffer.size() > this->hist_maxlines+1 )
- this->hist_buffer.pop_front();
-
- /* push to the front of the history */
- this->hist_buffer.push_back( toadd );
- return 0;
- }
-
- /* log a line to a logfile */
- int ChatHistory::chat_hist_logline( const std::string& toadd )
- {
- /* output the line to the file if logging is enabled */
- if( this->hist_log_enabled )
- this->hist_logfile << toadd << std::endl;
- return 0;
- }
-
- /* open logfile */
- int ChatHistory::chat_hist_openlog()
- {
- /* TODO: find out the name of the file to log to via settings
- * and set the this->hist_logfile_path variable to it
- */
-#ifndef CHATTEST
- this->hist_logfile.open( (PathConfig::getInstance().getLogPathString() +
- "chatlog.log").c_str(),
- std::fstream::out | std::fstream::app );
-#else
- this->hist_logfile.open( "/tmp/chatlog.log",
- std::fstream::out | std::fstream::app );
-#endif
-
- /* TODO check whether this works (not sure how you'd like it?) */
- if( !this->hist_logfile )
- { this->hist_log_enabled = false;
-#ifndef CHATTEST
- COUT(2) << "Warning: Could not open logfile." << std::endl;
-#endif
- }
-
- /* if it worked */
- return 0;
- }
-
- /* close logfile */
- void ChatHistory::chat_hist_closelog()
- {
- /* see if we've actually got a logfile */
- if( this->hist_logfile )
- {
- /* yes, we've got one, add a line that shows we're closing it */
- this->chat_hist_logline( "--- Logfile closed ---" );
-
- /* actually close down the file */
- this->hist_logfile.close();
- }
- }
-
- /* output history for debugging */
- void ChatHistory::debug_printhist()
- {
- /* create deque iterator */
- std::deque<std::string>::iterator it;
-
- /* output all the strings */
- for( it = this->hist_buffer.begin(); it != this->hist_buffer.end();
- ++it )
- std::cout << *it << std::endl;
-
- /* output size */
- std::cout << "Size: " << hist_buffer.size() << std::endl;
- }
-
-#ifndef CHATTEST
-}
-#endif
Deleted: code/forks/sandbox_light/src/orxonox/ChatHistory.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/ChatHistory.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/ChatHistory.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,149 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Sandro 'smerkli' Merkli
- * Co-authors:
- * ...
- *
- */
-
-#include <deque>
-#include <string>
-#include <fstream>
-#include <iostream>
-#include <cassert>
-
-/* define this if you're unit testing */
-//#define CHATTEST
-
-#ifndef CHATTEST
-#include <OrxonoxPrereqs.h>
-#include <PlayerManager.h>
-#include <infos/PlayerInfo.h>
-#include <core/BaseObject.h>
-#include <network/ChatListener.h>
-#include <core/PathConfig.h>
-#include <util/Singleton.h>
-#endif
-
-#ifndef _ChatHistory_H__
-#define _ChatHistory_H__
-
-
-/* Class to implement chat history */
-#ifndef CHATTEST
-namespace orxonox
-{
-#endif
-
- /* constructor */
-#ifndef CHATTEST
- class _OrxonoxExport ChatHistory : public ChatListener,
- public Singleton<ChatHistory>
-
-#else
- class ChatHistory
-#endif
- {
- public:
- /* constructors, destructors */
-#ifndef CHATTEST
- ChatHistory();
- friend class Singleton<ChatHistory>;
-#else
- ChatHistory();
-#endif
- virtual ~ChatHistory();
-
-
- //protected:
- /** what to do with incoming chat
- *
- * \param message The incoming message
- * \param senderID Identification number of the sender
- */
- virtual void incomingChat(const std::string& message,
- unsigned int senderID);
-
- /** Synchronize logfile onto the hard drive
- *
- * \return 0 for success, other for error
- */
- int syncLog();
-
- /** debug-print: output the whole history to stdout */
- void debug_printhist();
-
- private:
- /* FIELDS */
- /** Vector to store the history in */
- std::deque<std::string> hist_buffer;
-
- /** Maximum number of lines stored in this history */
- unsigned int hist_maxlines;
-
- /** is logging enabled? */
- bool hist_log_enabled;
-
- /** path of logfile on the file system */
- std::string hist_logfile_path;
-
- /** Output file stream for logfile */
- std::ofstream hist_logfile;
-
-#ifndef CHATTEST
- static ChatHistory* singletonPtr_s;
-#endif
-
-
-
- /* METHODS */
- /** Append line to chat history
- *
- * \param toadd The line to add to the history
- * \return 0 for success, other for error TODO: Throw exception
- */
- int chat_hist_addline( const std::string& toadd );
-
- /** Append line to logfile
- *
- * \param toadd The line to add to the logfile
- * \return 0 for success, other for error TODO: Throw exception
- */
- int chat_hist_logline( const std::string& toadd );
-
- /** open logfile to log to
- *
- * \return 0 for success,s other for error
- */
- int chat_hist_openlog();
-
-
- /** close logfile */
- void chat_hist_closelog();
- };
-
-#ifndef CHATTEST
-}
-#endif
-
-#endif /* _ChatHistory_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/ChatInputHandler.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/ChatInputHandler.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/ChatInputHandler.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,343 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Sandro 'smerkli' Merkli
- * Co-authors:
- * ...
- *
- */
-
-#include "ChatInputHandler.h"
-#include "util/ScopedSingletonManager.h"
-#include "core/CoreIncludes.h"
-#include "core/GUIManager.h"
-#include "core/CorePrereqs.h"
-#include "core/command/ConsoleCommand.h"
-#include <CEGUIWindow.h>
-#include <elements/CEGUIListbox.h>
-#include <elements/CEGUIListboxItem.h>
-#include <elements/CEGUIListboxTextItem.h>
-#include <CEGUIWindowManager.h>
-#include <string>
-
-namespace orxonox
-{
- /* singleton */
- ManageScopedSingleton( ChatInputHandler, ScopeID::Graphics, false );
-
- /* add commands to console */
- SetConsoleCommand( "startchat", &ChatInputHandler::activate_static );
- SetConsoleCommand( "startchat_small", &ChatInputHandler::activate_small_static );
-
- /* constructor */
- ChatInputHandler::ChatInputHandler()
- {
- /* register the object */
- RegisterObject(ChatInputHandler);
-
- /* create necessary objects */
- this->inpbuf = new InputBuffer();
- this->disp_offset = 0;
- assert( this->inpbuf != NULL );
-
- /* generate chatbox ui and chatbox-inputonly ui */
- GUIManager::getInstance().loadGUI( "ChatBox" );
- GUIManager::getInstance().loadGUI( "ChatBox-inputonly" );
-
- /* setup colors */
- setupColors();
-
- /* configure the input buffer */
- configureInputBuffer();
-
- this->inputState = InputManager::getInstance().createInputState( "chatinput", false, false, InputStatePriority::Dynamic );
- this->inputState->setKeyHandler(this->inpbuf);
- }
-
- /* configure input buffer, sub for the constructor */
- void ChatInputHandler::configureInputBuffer()
- {
- /* INSTALL CALLBACKS */
- /* input has changed */
- this->inpbuf->registerListener(this, &ChatInputHandler::inputChanged, true);
-
- /* add a line */
- this->inpbuf->registerListener(this, &ChatInputHandler::addline, '\r', false);
- this->inpbuf->registerListener(this, &ChatInputHandler::addline, '\n', false);
-
- /* backspace */
- this->inpbuf->registerListener(this, &ChatInputHandler::backspace, '\b', true);
- //this->inpbuf->registerListener(this, &ChatInputHandler::backspace, '\177', true);
-
- /* exit the chatinputhandler thingy (tbd) */
- this->inpbuf->registerListener(this, &ChatInputHandler::exit, '\033', true); // escape
-
- /* delete character */
- this->inpbuf->registerListener(this, &ChatInputHandler::deleteChar, KeyCode::Delete);
-
- /* cursor movement */
- this->inpbuf->registerListener(this, &ChatInputHandler::cursorRight, KeyCode::Right);
- this->inpbuf->registerListener(this, &ChatInputHandler::cursorLeft, KeyCode::Left);
- this->inpbuf->registerListener(this, &ChatInputHandler::cursorEnd, KeyCode::End);
- this->inpbuf->registerListener(this, &ChatInputHandler::cursorHome, KeyCode::Home);
-
- /* GET WINDOW POINTERS */
- input = CEGUI::WindowManager::getSingleton().getWindow( "orxonox/ChatBox/input" );
- inputonly = CEGUI::WindowManager::getSingleton().getWindow( "orxonox/ChatBox-inputonly/input" );
-
- /* get pointer to the history window */
- CEGUI::Window *history = CEGUI::WindowManager::getSingleton().getWindow( "orxonox/ChatBox/history" );
-
- /* cast it to a listbox */
- lb_history = dynamic_cast<CEGUI::Listbox*>(history);
-
- /* assert wee */
- assert( lb_history );
- }
-
- /* setup the colors, sub for the constructor */
- void ChatInputHandler::setupColors()
- {
- /* auto variables */
- float red = 1.0, green = 0.5, blue = 0.5;
- int i = 0;
-
- // three loops: red tones, blue tones and green tones
- // reds
- for( i = 0; i < NumberOfColors/3; ++i )
- { this->text_colors[ i ] = new CEGUI::colour( red, green, blue );
- assert( this->text_colors[ i ] );
- green += 0.2f, blue += 0.2f;
- }
-
- // greens
- red = 0.5, green = 1, blue = 0.5;
- for( ; i < NumberOfColors*2/3; ++i )
- { this->text_colors[ i ] = new CEGUI::colour( red, green, blue );
- assert( this->text_colors[ i ] );
- red += 0.2f, blue += 0.2f;
- }
-
- // blues
- red = 0.5, green = 0.5, blue = 1;
- for( ; i < NumberOfColors; ++i )
- { this->text_colors[ i ] = new CEGUI::colour( red, green, blue );
- assert( this->text_colors[ i ] );
- red += 0.2f, green += 0.2f;
- }
- }
-
-
- /* activate, deactivate */
- void ChatInputHandler::activate_static()
- { ChatInputHandler::getInstance().activate( true ); }
-
- void ChatInputHandler::activate_small_static()
- { ChatInputHandler::getInstance().activate( false ); }
-
- void ChatInputHandler::activate( bool full )
- {
- /* start listening */
- InputManager::getInstance().enterState("chatinput");
-
- /* MARK add spawning of chat widget stuff here.*/
- if( full )
- GUIManager::getInstance().showGUI( "ChatBox" );
- else
- GUIManager::getInstance().showGUI( "ChatBox-inputonly" );
-
- this->fullchat = full;
- }
-
- void ChatInputHandler::deactivate()
- {
- /* stop listening */
- InputManager::getInstance().leaveState("chatinput");
-
- /* un-spawning of chat widget stuff */
- GUIManager::getInstance().hideGUI( "ChatBox" );
- GUIManager::getInstance().hideGUI( "ChatBox-inputonly" );
- }
-
-
- /* subs for incomingChat */
- void ChatInputHandler::sub_setcolor( CEGUI::ListboxTextItem *tocolor,
- std::string name )
- {
- /* sanity checks */
- if( !tocolor )
- COUT(2) << "Empty ListBoxTextItem given to "
- "ChatInputhandler::sub_setcolor().\n";
-
- /* "hash" the name */
- int hash = 0;
- for( int i = name.length(); i > 0; --i )
- hash += name[i-1];
- hash = hash % this->NumberOfColors;
-
- /* set the color according to the hash */
- tocolor->setTextColours( *(this->text_colors[ hash ]) );
- }
-
- /* handle incoming chat */
- void ChatInputHandler::incomingChat(const std::string& message,
- unsigned int senderID)
- {
- /* look up the actual name of the sender */
- std::string text, name = "unknown";
-
- /* setup player name info */
- if (senderID != CLIENTID_UNKNOWN)
- {
- PlayerInfo* player = PlayerManager::getInstance().getClient(senderID);
- if (player)
- name = player->getName();
- }
-
- /* assemble the text */
- text = name + ": " + message;
-
- /* create item */
- CEGUI::ListboxTextItem *toadd = new CEGUI::ListboxTextItem( text );
-
- /* setup colors */
- sub_setcolor( toadd, name );
-
- /* now add */
- this->lb_history->addItem( dynamic_cast<CEGUI::ListboxItem*>(toadd) );
- this->lb_history->ensureItemIsVisible(
- dynamic_cast<CEGUI::ListboxItem*>(toadd) );
-
- /* make sure the history handles it */
- this->lb_history->handleUpdatedItemData();
- }
-
-
- /* sub for inputchanged */
- void ChatInputHandler::sub_adjust_dispoffset( int maxlen,
- int cursorpos,
- int inplen )
- {
- /* already start offsetting 5 characters before end */
- if( cursorpos+5 > maxlen )
- {
- /* always stay 5 characters ahead of end, looks better */
- ((disp_offset = cursorpos-maxlen+5) >= 0) ? 1 : disp_offset = 0;
-
- /* enforce visibility of cursor */
- (disp_offset > cursorpos ) ? disp_offset = 0 : 1;
- }
-
- /* make sure we don't die at substr */
- if( inplen <= disp_offset ) disp_offset = 0;
- }
-
- /* callbacks for InputBuffer */
- void ChatInputHandler::inputChanged()
- {
- /* update the cursor and the window */
- std::string raw = this->inpbuf->get();
- int cursorpos = this->inpbuf->getCursorPosition();
-
- /* get string before cursor */
- std::string left = raw.substr( 0, cursorpos );
-
- /* see if there's a string after the cursor */
- std::string right = "";
- if( raw.length() >= left.length()+1 )
- right = raw.substr( cursorpos );
-
- /* set the text */
- std::string assembled = "$ " + left + "|" + right;
-
- if( this->fullchat )
- {
- /* adjust curser position - magic number 5 for font width */
- sub_adjust_dispoffset( (int)(this->input->getUnclippedInnerRect().getWidth()/6),
- cursorpos, assembled.length() );
- this->input->setProperty( "Text", assembled.substr( disp_offset ) );
- }
- else
- {
- /* adjust curser position - magic number 5 for font width */
- sub_adjust_dispoffset( (int)(this->inputonly->getUnclippedInnerRect().getWidth()/6),
- cursorpos, assembled.length() );
- this->inputonly->setProperty( "Text", assembled.substr( disp_offset) );
- }
-
- /* reset display offset */
- disp_offset = 0;
- }
-
- void ChatInputHandler::addline()
- {
- /* actually do send what was input */
- /* a) get the string out of the inputbuffer */
- std::string msgtosend = this->inpbuf->get();
-
- if( msgtosend.length() == 0 )
- { this->deactivate();
- return;
- }
-
- /* b) clear the input buffer */
- if (this->inpbuf->getSize() > 0)
- this->inpbuf->clear();
-
- /* c) send the chat via some call */
- Host::Chat( msgtosend );
-
- /* d) stop listening to input - only if this is not fullchat */
- if( !this->fullchat )
- this->deactivate();
-
- }
-
- void ChatInputHandler::backspace()
- { this->inpbuf->removeBehindCursor(); }
-
- void ChatInputHandler::deleteChar()
- { this->inpbuf->removeAtCursor(); }
-
- void ChatInputHandler::cursorRight()
- { this->inpbuf->increaseCursor(); }
-
- void ChatInputHandler::cursorLeft()
- { this->inpbuf->decreaseCursor(); }
-
- void ChatInputHandler::cursorEnd()
- { this->inpbuf->setCursorToEnd(); }
-
- void ChatInputHandler::cursorHome()
- { this->inpbuf->setCursorToBegin(); }
-
- void ChatInputHandler::exit()
- {
- /* b) clear the input buffer */
- if (this->inpbuf->getSize() > 0)
- this->inpbuf->clear();
-
- /* d) stop listening to input */
- this->deactivate();
- }
-
-}
Deleted: code/forks/sandbox_light/src/orxonox/ChatInputHandler.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/ChatInputHandler.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/ChatInputHandler.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,148 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Sandro 'smerkli' Merkli
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _ChatInputHandler_H__
-#define _ChatInputHandler_H__
-
-/* std includes */
-#include <deque>
-#include <string>
-#include <fstream>
-#include <iostream>
-#include <cassert>
-#include <CEGUIForwardRefs.h>
-
-/* project includes */
-#include <OrxonoxPrereqs.h>
-#include <core/BaseObject.h>
-#include <core/PathConfig.h>
-
-#include "core/input/InputBuffer.h"
-#include "core/input/InputManager.h"
-#include "core/input/InputState.h"
-
-#include <network/ChatListener.h>
-#include <PlayerManager.h>
-#include <infos/PlayerInfo.h>
-
-#include "../libraries/network/Host.h"
-#include <util/Singleton.h>
-
-namespace orxonox // tolua_export
-{ // tolua_export
- /* class to handle chat using an InputBuffer */
- class _OrxonoxExport ChatInputHandler // tolua_export
- : public Singleton<ChatInputHandler>, public ChatListener
- { // tolua_export
- private:
- /** Input buffer, to be used to catch input from the
- * keyboard
- */
- InputBuffer *inpbuf;
- int disp_offset, width;
- bool fullchat;
-
- /* colors for nickname coloring */
- static const int NumberOfColors = 10;
- CEGUI::colour *text_colors[ NumberOfColors ];
-
- /** input state */
- InputState *inputState;
-
- /** setup input buffer, the constructor calls this */
- void configureInputBuffer();
-
- /** adjust display offset depending on cursor position */
- void sub_adjust_dispoffset( int maxlen, int cursorpos, int inplen );
-
- /** singleton pointer */
- static ChatInputHandler* singletonPtr_s;
-
- /** cegui window handles */
- CEGUI::Window *input, *inputonly;
-
- /** cegui handle for the history window */
- CEGUI::Listbox *lb_history;
-
- /* methods to deal with colors */
- void sub_setcolor( CEGUI::ListboxTextItem *tocolor,
- std::string name );
-
- void setupColors();
-
- /* callbacks for input handler */
- void inputChanged();
- void addline();
- void backspace();
- void deleteChar();
- void cursorRight();
- void cursorLeft();
- void cursorEnd();
- void cursorHome();
- void exit();
-
- public:
- /** constructor */
- ChatInputHandler();
- friend class Singleton<ChatInputHandler>;
-
- static ChatInputHandler& getInstance(void) { return Singleton<ChatInputHandler>::getInstance(); } // tolua_export
-
- /** start listening */
- static void activate_static();
-
- /** stop listening */
- static void activate_small_static();
-
- /** \param message the message text
- * \param senderID ID of the player who sent the message
- *
- * Deal with incoming chat (which means in our case: Add it to the
- * history window of the full chat window)
- */
- void incomingChat( const std::string& message,
- unsigned int senderID );
-
- /** \param full true means show full chat window with history,
- false means show only an input line
- *
- * Show the chat window and redirect the game's keyboard input
- * into it.
- */
- void activate( bool full );
-
- /** Deactivate the chat window, meaning: hide it. */
- void deactivate(); // tolua_export
-
- }; // tolua_export
-
-
-} // tolua_export
-
-
-#endif /*_ChatInputHandler_H__*/
Deleted: code/forks/sandbox_light/src/orxonox/Level.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/Level.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Level.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,182 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "Level.h"
-
-#include "util/Math.h"
-#include "core/CoreIncludes.h"
-#include "core/Loader.h"
-#include "core/Template.h"
-#include "core/XMLFile.h"
-#include "core/XMLPort.h"
-
-#include "infos/PlayerInfo.h"
-#include "gametypes/Gametype.h"
-#include "overlays/OverlayGroup.h"
-#include "LevelManager.h"
-
-namespace orxonox
-{
- CreateFactory(Level);
-
- Level::Level(BaseObject* creator) : BaseObject(creator), Synchronisable(creator)
- {
- RegisterObject(Level);
-
-
- this->registerVariables();
- this->xmlfilename_ = this->getFilename();
- this->xmlfile_ = 0;
- }
-
- Level::~Level()
- {
- if (this->isInitialized())
- {
- if (LevelManager::exists())
- LevelManager::getInstance().releaseActivity(this);
-
- if (this->xmlfile_)
- Loader::unload(this->xmlfile_);
- }
- }
-
- void Level::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- SUPER(Level, XMLPort, xmlelement, mode);
-
- XMLPortParam(Level, "description", setDescription, getDescription, xmlelement, mode);
- XMLPortParam(Level, "gametype", setGametypeString, getGametypeString, xmlelement, mode).defaultValues("Gametype");
-
- XMLPortObject(Level, MeshLodInformation, "lodinformation", addLodInfo, getLodInfo, xmlelement, mode);
- XMLPortObjectExtended(Level, BaseObject, "", addObject, getObject, xmlelement, mode, true, false);
- }
-
- void Level::registerVariables()
- {
- registerVariable(this->xmlfilename_, VariableDirection::ToClient, new NetworkCallback<Level>(this, &Level::networkcallback_applyXMLFile));
- registerVariable(this->name_, VariableDirection::ToClient, new NetworkCallback<Level>(this, &Level::changedName));
- registerVariable(this->description_, VariableDirection::ToClient);
- registerVariable(this->networkTemplateNames_, VariableDirection::ToClient, new NetworkCallback<Level>(this, &Level::networkCallbackTemplatesChanged));
- }
-
- void Level::networkcallback_applyXMLFile()
- {
- COUT(0) << "Loading level \"" << this->xmlfilename_ << "\"..." << std::endl;
-
- ClassTreeMask mask;
- mask.exclude(Class(BaseObject));
- mask.include(Class(Template));
- mask.include(Class(OverlayGroup)); // HACK to include the ChatOverlay
-
- this->xmlfile_ = new XMLFile(mask, this->xmlfilename_);
-
- Loader::open(this->xmlfile_);
- }
-
- void Level::networkCallbackTemplatesChanged()
- {
- for( std::set<std::string>::iterator it = this->networkTemplateNames_.begin(); it!=this->networkTemplateNames_.end(); ++it )
- {
- assert(Template::getTemplate(*it));
- Template::getTemplate(*it)->applyOn(this);
- }
- }
-
- void Level::setGametypeString(const std::string& gametype)
- {
- Identifier* identifier = ClassByString(gametype);
-
- if (!identifier || !identifier->isA(Class(Gametype)))
- {
- COUT(0) << "Error: \"" << gametype << "\" is not a valid gametype." << std::endl;
- identifier = Class(Gametype);
- this->gametype_ = "Gametype";
- }
- else
- this->gametype_ = gametype;
-
- Gametype* rootgametype = orxonox_cast<Gametype*>(identifier->fabricate(this));
- this->setGametype(rootgametype);
-
- for (std::list<BaseObject*>::iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
- (*it)->setGametype(rootgametype);
-
- if (LevelManager::exists())
- LevelManager::getInstance().requestActivity(this);
- }
-
-
- void Level::addObject(BaseObject* object)
- {
- this->objects_.push_back(object);
- object->setGametype(this->getGametype());
- object->setLevel(this);
- }
-
- BaseObject* Level::getObject(unsigned int index) const
- {
- unsigned int i = 0;
- for (std::list<BaseObject*>::const_iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
- {
- if (i == index)
- return (*it);
- ++i;
- }
- return 0;
- }
-
- void Level::addLodInfo(MeshLodInformation* lodInformation)
- {
- std::string meshName = lodInformation->getMeshName();
-// this->lodInformation_.insert(std::make_pair(meshName,lodInformation));
- if( this->lodInformation_.find(meshName) != this->lodInformation_.end())
- CCOUT(4) << "replacing lod information for " << meshName << endl;
- this->lodInformation_[meshName] = lodInformation;
- }
-
- MeshLodInformation* Level::getLodInfo(std::string meshName) const
- {
- if(this->lodInformation_.find(meshName)!=this->lodInformation_.end())
- return this->lodInformation_.find(meshName)->second;
-
- return 0;
- }
-
- void Level::playerEntered(PlayerInfo* player)
- {
- COUT(3) << "player entered level (id: " << player->getClientID() << ", name: " << player->getName() << ')' << std::endl;
- player->setGametype(this->getGametype());
- }
-
- void Level::playerLeft(PlayerInfo* player)
- {
- COUT(3) << "player left level (id: " << player->getClientID() << ", name: " << player->getName() << ')' << std::endl;
- player->setGametype(0);
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/Level.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/Level.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Level.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,87 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _Level_H__
-#define _Level_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <list>
-#include <string>
-#include <map>
-#include "core/BaseObject.h"
-#include "network/synchronisable/Synchronisable.h"
-#include "graphics/MeshLodInformation.h"
-
-namespace orxonox
-{
- class _OrxonoxExport Level : public BaseObject, public Synchronisable
- {
- public:
- Level(BaseObject* creator);
- virtual ~Level();
-
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
-
- inline void setDescription(const std::string& description)
- { this->description_ = description; }
- inline const std::string& getDescription() const
- { return this->description_; }
-
- void playerEntered(PlayerInfo* player);
- void playerLeft(PlayerInfo* player);
-
- MeshLodInformation* getLodInfo(std::string meshName) const;
-
-
- private:
- void registerVariables();
- void addObject(BaseObject* object);
- BaseObject* getObject(unsigned int index) const;
-
- void addLodInfo(MeshLodInformation* object);
- void networkCallbackTemplatesChanged();
-// const MeshLodInformation* getLodInfo(std::string meshName) const;
-// MeshLodInformation* getLodInfo(unsigned int index) const;
-
- void setGametypeString(const std::string& gametype);
- inline const std::string& getGametypeString() const
- { return this->gametype_; }
-
- void networkcallback_applyXMLFile();
-
- std::string description_;
- std::string gametype_;
- std::string xmlfilename_;
- XMLFile* xmlfile_;
- std::list<BaseObject*> objects_;
- std::map<std::string,MeshLodInformation*> lodInformation_;
- };
-}
-
-#endif /* _Level_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/LevelInfo.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/LevelInfo.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/LevelInfo.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,210 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Damian 'Mozork' Frick
- * Co-authors:
- * ...
- *
- */
-
-#include "LevelInfo.h"
-
-#include <sstream>
-#include <vector>
-
-#include "util/SubString.h"
-#include "core/CoreIncludes.h"
-#include "core/XMLPort.h"
-
-#include "LevelManager.h"
-
-namespace orxonox
-{
-
- // LevelInfoItem
-
- //! The list of allowed tags.
- /*static*/ std::set<std::string> LevelInfoItem::possibleTags_s = std::set<std::string>();
-
- /**
- @brief
- Default constructor.
- */
- LevelInfoItem::LevelInfoItem()
- {
-
- }
-
- /**
- @brief
- Constructor. Initializes the object.
- @param name
- The name of the Level.
- @param filename
- The XML-filename of the Level.
- */
- LevelInfoItem::LevelInfoItem(const std::string& name, const std::string filename)
- {
- this->setName(name);
- this->setXMLFilename(filename);
- }
-
- /**
- @brief
- Destructor.
- */
- LevelInfoItem::~LevelInfoItem()
- {
-
- }
-
- /**
- @brief
- Initialize the set of allowed tags.
- */
- /*static*/ void LevelInfoItem::initializeTags(void)
- {
- if(!LevelInfoItem::initialized_s)
- {
- LevelInfoItem::possibleTags_s.insert("test");
- LevelInfoItem::possibleTags_s.insert("singleplayer");
- LevelInfoItem::possibleTags_s.insert("multiplayer");
- LevelInfoItem::possibleTags_s.insert("showcase");
- LevelInfoItem::possibleTags_s.insert("tutorial");
- LevelInfoItem::possibleTags_s.insert("presentation");
- }
- }
-
- /**
- @brief
- Set the tags the Level is tagged with.
- @param tags
- A comma-seperated string of all the tags to be set.
- */
- void LevelInfoItem::setTags(const std::string& tags)
- {
- SubString substr = SubString(tags, ",", " "); // Split the string into tags.
- const std::vector<std::string>& strings = substr.getAllStrings();
- for(std::vector<std::string>::const_iterator it = strings.begin(); it != strings.end(); it++)
- this->addTag(*it, false);
-
- this->tagsUpdated();
- }
-
- /**
- @brief
- Add a tag to the set of tags the Level is tagged with.
- @param tag
- The tag to be added.
- @param update
- Whether the comma-seperated string of all tags should be updated. Default is true.
- @return
- Returns true if the tag was successfully added, if the tag was already present it returns false.
- */
- bool LevelInfoItem::addTag(const std::string& tag, bool update)
- {
- if(!this->validateTag(tag))
- {
- COUT(2) << "Bad LevelInfo tag '" << tag << "' in " << this->getXMLFilename() << ". Ignoring..." << std::endl;
- return false;
- }
- bool success = this->tags_.insert(*LevelInfoItem::possibleTags_s.find(tag)).second;
- if(update && success)
- this->tagsUpdated();
- return success;
- }
-
- /**
- @brief
- Updates the comma-seperated string of all tags, if the set of tags has changed.
- */
- void LevelInfoItem::tagsUpdated(void)
- {
- std::stringstream stream;
- std::set<std::string>::iterator temp;
- for(std::set<std::string>::iterator it = this->tags_.begin(); it != this->tags_.end(); )
- {
- temp = it;
- if(++it == this->tags_.end()) // If this is the last tag we don't add a comma.
- stream << *temp;
- else
- stream << *temp << ", ";
- }
-
- this->tagsString_ = std::string(stream.str());
- }
-
- // LevelInfo
-
- CreateFactory(LevelInfo);
-
- /**
- @brief
-
- @param creator
- The creator of this object.
- */
- LevelInfo::LevelInfo(BaseObject* creator) : BaseObject(creator)
- {
- RegisterObject(LevelInfo);
-
- this->xmlfilename_ = this->getFilename();
- }
-
- /**
- @brief
- Destructor.
- */
- LevelInfo::~LevelInfo()
- {
-
- }
-
- /**
- @brief
- Creates a LevelInfo object through XML.
- */
- void LevelInfo::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- SUPER(LevelInfo, XMLPort, xmlelement, mode);
-
- XMLPortParam(LevelInfo, "description", setDescription, getDescription, xmlelement, mode);
- XMLPortParam(LevelInfo, "tags", setTags, getTags, xmlelement, mode);
- }
-
- /**
- @brief
- Copies the contents of this LevelInfo object to a new LevelInfoItem object.
- This is needed, because a LeveInfo object is only created within the scope of the XML-file it is loaded with and is destroyed once that is unloaded.
- @return
- Returns a new LevelInfoItem with the same contents as the LevelInfo object.
- */
- LevelInfoItem* LevelInfo::copy(void)
- {
- LevelInfoItem* info = new LevelInfoItem(this->BaseObject::getName(), this->getXMLFilename());
- info->setDescription(this->getDescription());
- info->setTags(this->getTags());
- return info;
- }
-
-}
-
Deleted: code/forks/sandbox_light/src/orxonox/LevelInfo.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/LevelInfo.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/LevelInfo.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,219 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Damian 'Mozork' Frick
- * Co-authors:
- * ...
- *
- */
-
-/**
- @file LevelInfo.h
- @brief Definition of the LevelInfo and LevelInfoItem class.
- @ingroup Orxonox
-*/
-
-#ifndef _LevelInfo_H__
-#define _LevelInfo_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <set>
-#include <string>
-#include "util/StringUtils.h"
-
-#include "core/BaseObject.h"
-#include "core/OrxonoxClass.h"
-
-namespace orxonox // tolua_export
-{ // tolua_export
-
- /**
- @brief
- The LevelInfoItem class stores information regarding a @ref orxonox::Level "Level" and makes that information accessible through the @ref orxonox::LevelManager "LevelManager".
- A LevelInfoItem object is commonly created from a @ref orxonox::LevelInfo "LevelInfo" object, using its <code>copy()</code> method.
-
- @author
- Damian 'Mozork' Frick
-
- @ingroup Orxonox
- */
- class _OrxonoxExport LevelInfoItem // tolua_export
- : virtual public OrxonoxClass
- { // tolua_export
- public:
- LevelInfoItem(); //!< Default constructor.
- LevelInfoItem(const std::string& name, const std::string filename); //!< Constructor. Initializes the object.
- virtual ~LevelInfoItem(); //!< Destructor.
-
- /**
- @brief Set the name of the Level.
- @param name The name to be set.
- */
- inline void setName(const std::string& name)
- { this->name_ = std::string(name); }
- /**
- @brief Get the name of the Level.
- @return Returns the name of the Level.
- */
- inline const std::string& getName(void) const { return this->name_; } // tolua_export
-
- /**
- @brief Set the description of the Level.
- @param description The description to be set.
- */
- inline void setDescription(const std::string& description)
- { this->description_ = std::string(description); }
- /**
- @brief Get the description of the Level.
- @return Returns the description of the Level.
- */
- inline const std::string& getDescription() const { return this->description_; } // tolua_export
-
- void setTags(const std::string& tags); //!< Set the tags the Level is tagged with.
- bool addTag(const std::string& tag, bool update = true); //!< Add a tag to the set of tags the Level is tagged with.
- /**
- @brief Get the lis of the tags the Level is tagged with.
- @return Returns a comma-seperated string of all the tags the Level is tagged with.
- */
- inline const std::string& getTags(void) const
- { return this->tagsString_; }
- /**
- @brief Get whether the Level has a specific tag.
- @param tag The tag for which is checked.
- @return Returns true if the Level is tagged with the input tag.
- */
- inline bool hasTag(const std::string& tag) const { return this->tags_.find(tag) != this->tags_.end(); } // tolua_export
-
- /**
- @brief Get the XML-filename of the Level.
- @return Returns the XML-filename (including *.oxw extension) of the Level.
- */
- inline const std::string& getXMLFilename(void) { return this->xmlfilename_; } // tolua_export
-
- protected:
- /**
- @brief Set the XML-filename of the Level.
- @param filename The XML-filename to be set.
- */
- inline void setXMLFilename(const std::string& filename)
- { this->xmlfilename_ = std::string(filename); }
-
- std::string xmlfilename_; //!< The XML-filename of the Level.
-
- private:
- void tagsUpdated(void); //!< Updates the comma-seperated string of all tags, if the set of tags has changed.
-
- static void initializeTags(void); //!< Initialize the set of allowed tags.
- /**
- @brief Check whether an input tag is allowed.
- @param tag The tag to check.
- @return Returns true if the input tag is allowed, false if not.
- */
- static bool validateTag(const std::string& tag)
- { LevelInfoItem::initializeTags(); return LevelInfoItem::possibleTags_s.find(tag) != LevelInfoItem::possibleTags_s.end(); }
-
- static std::set<std::string> possibleTags_s; //!< The set of allowed tags.
- static const bool initialized_s = false; //!< Whether the set of allowed tags has been inizialized.
-
- std::string name_; //!< The name of the Level.
- std::string description_; //!< The description of the Level.
- std::set<std::string> tags_; //!< The set of tags the Level is tagged with.
- std::string tagsString_; //!< The comma-seperated string of all the tags the Level is tagged with.
- }; // tolua_export
-
- /**
- @brief
- The LevelInfo class can be used to store information regarding a @ref orxonox::Level "Level" in its level file.
- The following parameters can be specified:
- - @b name The name of the level.
- - @b description The description of the level.
- - @b tags A comma-seperated string of tags. Allowed tags are: <em>test</em>, <em>singleplayer</em>, <em>multiplayer</em>, <em>showcase</em>, <em>tutorial</em>, <em>presentation</em>.
-
- An example would be:
- @code
- <LevelInfo
- name = "Levelname"lhs->compare(rhs) < 0
- description = "This is just some awesome level."
- tags = "test, awesome"
- />
- @endcode
- The LevelInfo is best located at the top of the level file.
-
- @author
- Damian 'Mozork' Frick
-
- @ingroup Orxonox
- */
- class _OrxonoxExport LevelInfo : public BaseObject, public LevelInfoItem
- {
- public:
- LevelInfo(BaseObject* creator);
- virtual ~LevelInfo();
-
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Creates a LevelInfo object through XML.
-
- /**
- @brief Set the description of the Level.
- @param description The description to be set.
- */
- inline void setDescription(const std::string& description)
- { this->LevelInfoItem::setDescription(description); }
- /**
- @brief Get the description of the Level.
- @return Returns the description of the Level.
- */
- inline const std::string& getDescription() const
- { return this->LevelInfoItem::getDescription(); }
-
- /**
- @brief Set the tags the Level is tagged with.
- @param tags A comma-seperated string of all the tags to be set.
- */
- inline void setTags(const std::string& tags)
- { this->LevelInfoItem::setTags(tags); }
- /**
- @brief Get the lis of the tags the Level is tagged with.
- @return Returns a comma-seperated string of all the tags the Level is tagged with.
- */
- inline const std::string& getTags(void) const
- { return this->LevelInfoItem::getTags(); }
-
- LevelInfoItem* copy(void); //!< Copies the contents of this LevelInfo object to a new LevelInfoItem object.
-
- };
-
- /**
- @brief
- Struct that overloads the compare operation between two @ref orxonox::LevelInfoItem "LevelInfoItem" pointers.
-
- @ingroup Orxonox
- */
- struct LevelInfoCompare
- {
- bool operator() (const LevelInfoItem* lhs, const LevelInfoItem* rhs) const
- { return getLowercase(lhs->getName()).compare(getLowercase(rhs->getName())) < 0; }
- };
-
-} // tolua_export
-
-#endif /* _LevelInfo_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/LevelManager.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/LevelManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/LevelManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,281 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * Damian 'Mozork' Frick
- *
- */
-
-/**
- @file LevelManager.cc
- @brief Implementation of the LevelManager singleton.
-*/
-
-#include "LevelManager.h"
-
-#include <map>
-
-#include "util/ScopedSingletonManager.h"
-#include "core/ClassTreeMask.h"
-#include "core/CommandLineParser.h"
-#include "core/ConfigValueIncludes.h"
-#include "core/CoreIncludes.h"
-#include "core/Loader.h"
-#include "core/Resource.h"
-#include "core/XMLFile.h"
-#include "Level.h"
-#include "PlayerManager.h"
-
-namespace orxonox
-{
- SetCommandLineArgument(level, "").shortcut("l").information("Default level file (overrides LevelManager::defaultLevelName_ configValue)");
-
- ManageScopedSingleton(LevelManager, ScopeID::Root, false);
-
- /**
- @brief
- Constructor. Registers the object, sets config values and initializes variables.
- */
- LevelManager::LevelManager()
- {
- RegisterRootObject(LevelManager);
- this->setConfigValues();
-
- // check override
- if (!CommandLineParser::getArgument("level")->hasDefaultValue())
- {
- ModifyConfigValue(defaultLevelName_, tset, CommandLineParser::getValue("level").getString());
- }
-
- this->compileAvailableLevelList();
- this->nextIndex_ = 0;
- this->nextLevel_ = this->availableLevels_.begin();
- }
-
- LevelManager::~LevelManager()
- {
- }
-
- /**
- @brief
- Set the config values for this object.
- */
- void LevelManager::setConfigValues()
- {
- SetConfigValue(defaultLevelName_, "presentationDM.oxw")
- .description("Sets the pre selection of the level in the main menu.");
- }
-
- /**
- @brief
- Request activity for the input Level.
- The Level will be added to the list of Levels whose activity is requested. The list is accessed in a FIFO manner.
- If the Level is the only Level in the list it will be immediately activated. If not it will be activated as soon as it reaches the front of the list.
- @param level
- A pointer to the Level whose activity is requested.
- */
- void LevelManager::requestActivity(Level* level)
- {
- assert( std::find(this->levels_.begin(), this->levels_.end(), level)==this->levels_.end() );
- // If the level is already in list.
- if( std::find(this->levels_.begin(), this->levels_.end(), level)!=this->levels_.end() )
- return;
- // If it isn't insert it at the back.
- this->levels_.push_back(level);
- // If it is the only level in the list activate it.
- if (this->levels_.size() == 1)
- this->activateNextLevel();
- }
-
- /**
- @brief
- Release activity for the input Level.
- Removes the Level from the list. If the Level was the one currently active, it is deactivated and the next Level in line is activated.
- @param level
- A pointer to the Level whose activity is to be released.
- */
- void LevelManager::releaseActivity(Level* level)
- {
- if (this->levels_.size() > 0)
- {
- // If the level is the active level in the front of the list.
- if (this->levels_.front() == level)
- {
- // Deactivate it, remove it from the list and activate the next level in line.
- level->setActive(false);
- this->levels_.pop_front();
- this->activateNextLevel();
- }
- else // Else just remove it from the list.
- this->levels_.erase(std::find(this->levels_.begin(), this->levels_.end(), level));
- }
- }
-
- /**
- @brief
- Get the currently active Level.
- @return
- Returns a pointer to the currently active level or NULL if there currently are no active Levels.
- */
- Level* LevelManager::getActiveLevel()
- {
- if (this->levels_.size() > 0)
- return this->levels_.front();
- else
- return 0;
- }
-
- /**
- @brief
- Activate the next Level.
- */
- void LevelManager::activateNextLevel()
- {
- if (this->levels_.size() > 0)
- {
- // Activate the level that is the first in the list of levels whose activity has been requested.
- this->levels_.front()->setActive(true);
- // Make every player enter the newly activated level.
- for (std::map<unsigned int, PlayerInfo*>::const_iterator it = PlayerManager::getInstance().getClients().begin(); it != PlayerManager::getInstance().getClients().end(); ++it)
- this->levels_.front()->playerEntered(it->second);
- }
- }
-
- /**
- @brief
- Set the default Level.
- @param levelName
- The filename of the default Level.
- */
- void LevelManager::setDefaultLevel(const std::string& levelName)
- {
- ModifyConfigValue(defaultLevelName_, set, levelName);
- }
-
- /**
- @brief
- Get the number of available Levels.
- Also updates the list of available Levels.
- @return
- Returns the number of available Levels.
- */
- unsigned int LevelManager::getNumberOfLevels()
- {
- this->updateAvailableLevelList();
-
- return this->availableLevels_.size();
- }
-
- /**
- @brief
- Get the LevelInfoItem at the given index in the list of available Levels.
- The LevelInfoItems are sorted in alphabetical order accoridng to the name of the Level.
- This method is most efficiently called with consecutive indices (or at least ascending indices).
- @param index
- The index of the item that should be returned.
- @return
- Returns a pointer to the LevelInfoItem at the given index.
- */
- LevelInfoItem* LevelManager::getAvailableLevelListItem(unsigned int index)
- {
- if(index >= this->availableLevels_.size())
- return NULL;
-
- // If this index directly follows the last we can optimize a lot.
- if(index == this->nextIndex_)
- {
- this->nextIndex_++;
- std::set<LevelInfoItem*, LevelInfoCompare>::iterator it = this->nextLevel_;
- this->nextLevel_++;
- return *it;
- }
- else
- {
- // If this index is bigger than the last, we can optimize a little.
- if(index < this->nextIndex_)
- {
- this->nextIndex_ = 0;
- this->nextLevel_ = this->availableLevels_.begin();
- }
- while(this->nextIndex_ != index)
- {
- this->nextIndex_++;
- this->nextLevel_++;
- }
- this->nextIndex_++;
- std::set<LevelInfoItem*, LevelInfoCompare>::iterator it = this->nextLevel_;
- this->nextLevel_++;
- return *it;
- }
- }
-
- /**
- @brief
- Compile the list of available Levels.
- Iterates over all *.oxw files, loads the LevelInfo objects in them and from that it creates the LevelInfoItems which are inserted in a list.
- */
- void LevelManager::compileAvailableLevelList()
- {
- Ogre::StringVectorPtr levels = Resource::findResourceNames("*.oxw");
- // Iterate over all *.oxw level files.
- COUT(3) << "Loading LevelInfos..." << std::endl;
- for (Ogre::StringVector::const_iterator it = levels->begin(); it != levels->end(); ++it)
- {
- //TODO: Replace with tag?
- if (it->find("old/") != 0)
- {
- size_t pos = it->find(".oxw");
-
- // Load the LevelInfo object from the level file.
- bool infoExists = false;
- XMLFile file = XMLFile(*it);
- ClassTreeMask mask = ClassTreeMask();
- mask.exclude(ClassIdentifier<BaseObject>::getIdentifier());
- mask.include(ClassIdentifier<LevelInfo>::getIdentifier());
- Loader::load(&file, mask, false);
- // Iterate over all LevelInfos.
- for(ObjectList<LevelInfo>::iterator item = ObjectList<LevelInfo>::begin(); item != ObjectList<LevelInfo>::end(); ++item)
- {
- LevelInfoItem* info = item->copy();
- if(info->getXMLFilename() == *it) // If the LevelInfo for this level exists we insert it into the list of available levels.
- {
- this->availableLevels_.insert(info);
- infoExists = true;
- }
- }
- Loader::unload(&file, mask);
- if(!infoExists) // If the LevelInfo for this level doesn't exist, we create a new one and insert it into the list of available levels.
- this->availableLevels_.insert(new LevelInfoItem(it->substr(0, pos), *it));
- }
- }
- }
-
- /**
- @brief
- Update the list of available Levels.
- */
- void LevelManager::updateAvailableLevelList(void)
- {
- //TODO: Implement some kind of update?
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/LevelManager.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/LevelManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/LevelManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,123 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * Damian 'Mozork' Frick
- *
- */
-
-/**
- @file LevelManager.h
- @brief Definition of the LevelManager singleton.
- @ingroup Orxonox
-*/
-
-#ifndef _LevelManager_H__
-#define _LevelManager_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <cassert>
-#include <list>
-#include <map>
-#include <string>
-
-#include "LevelInfo.h"
-
-#include "util/Singleton.h"
-#include "core/OrxonoxClass.h"
-
-// tolua_begin
-namespace orxonox
-{
-
- /**
- @brief
- The LevelManager keeps track of @ref orxonox::Level "Levels" whose activity has been requested and activates the @ref orxonox::Level "Levels" in the list in a FIFO manner with exactly one Level (the first in the list) being active at all times (unless the list is empty).
- It also serves as an access point to get a list of all available @ref orxonox::Level "Levels" (or rather their respective @ref orxonox::LevelInfoItem "LevelInfoItems").
-
- @author
- Fabian 'x3n' Landau
-
- @author
- Damian 'Mozork' Frick
-
- @ingroup Orxonox
- */
- class _OrxonoxExport LevelManager
- // tolua_end
- : public Singleton<LevelManager>, public OrxonoxClass
- { // tolua_export
- friend class Singleton<LevelManager>;
- public:
- LevelManager();
- virtual ~LevelManager();
-
- void setConfigValues(); //!< Set the config values for this object.
-
- void requestActivity(Level* level); //!< Request activity for the input Level.
- void releaseActivity(Level* level); //!< Release activity for the input Level.
- Level* getActiveLevel(); //!< Get the currently active Level.
-
- // tolua_begin
- void setDefaultLevel(const std::string& levelName); //!< Set the default Level.
- /**
- @brief Get the default level.
- @return Returns the filename of the default level.
- */
- const std::string& getDefaultLevel() const
- { return defaultLevelName_; }
- unsigned int getNumberOfLevels(void);
- LevelInfoItem* getAvailableLevelListItem(unsigned int index); //!< Get the LevelInfoItem at the given index in the list of available Levels.
-
- /**
- @brief Get the instance of the LevelManager.
- @return Returns the instance of the LevelManager.
- */
- static LevelManager& getInstance()
- { return Singleton<LevelManager>::getInstance(); }
- // tolua_end
-
- private:
- LevelManager(const LevelManager&);
-
- void activateNextLevel(); //!< Activate the next level.
-
- void compileAvailableLevelList(void); //!< Compile the list of available Levels.
- void updateAvailableLevelList(void); //!< Update the list of available Levels.
-
- std::list<Level*> levels_; //!< A list of all the Levels whose activity has been requested, in the order in which they will become active.
- std::set<LevelInfoItem*, LevelInfoCompare> availableLevels_; //!< The set of available Levels sorted alphabetically according to the name of the Level.
-
- // Helpers to allow fast access to the availableLevels list.
- unsigned int nextIndex_; //! The next expected index to be accessed.
- std::set<LevelInfoItem*, LevelInfoCompare>::iterator nextLevel_; //! The nex expected Level to be accessed.
-
- // config values
- std::string defaultLevelName_;
-
- static LevelManager* singletonPtr_s;
- }; // tolua_export
-} // tolua_export
-
-#endif /* _LevelManager_H__ */
Modified: code/forks/sandbox_light/src/orxonox/Main.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/Main.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Main.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -36,26 +36,10 @@
#include "Main.h"
#include "core/CommandLineParser.h"
-#include "core/Game.h"
-#include "core/LuaState.h"
-#include "ToluaBindOrxonox.h"
-#include "ToluaBindNetwork.h"
+#include "core/Core.h"
-DeclareToluaInterface(Orxonox);
-DeclareToluaInterface(Network);
-
namespace orxonox
{
- SetCommandLineSwitch(console).information("Start in console mode (text IO only)");
- SetCommandLineSwitch(server).information("Start in server mode");
- SetCommandLineSwitch(client).information("Start in client mode");
- SetCommandLineSwitch(dedicated).information("Start in dedicated server mode");
- SetCommandLineSwitch(standalone).information("Start in standalone mode");
- SetCommandLineSwitch(dedicatedClient).information("Start in dedicated client mode");
-
- /* ADD masterserver command */
- SetCommandLineSwitch(masterserver).information("Start in masterserver mode");
-
SetCommandLineArgument(generateDoc, "")
.information("Generates a Doxygen file from things like SetConsoleCommand");
@@ -65,47 +49,14 @@
*/
int main(const std::string& strCmdLine)
{
- Game* game = new Game(strCmdLine);
+ Core* core = new Core(strCmdLine);
if (CommandLineParser::getValue("generateDoc").getString().empty())
{
- /* TODO make this clear */
- game->setStateHierarchy(
- "root"
- " graphics"
- " mainMenu"
- " standalone,server,client"
- " level"
- " server,client,masterserver"
- " level"
- );
-
- game->requestState("root");
-
- // Some development hacks (not really, but in the future, these calls won't make sense anymore)
- if (CommandLineParser::getValue("standalone").getBool())
- Game::getInstance().requestStates("graphics, standalone, level");
- else if (CommandLineParser::getValue("server").getBool())
- Game::getInstance().requestStates("graphics, server, level");
- else if (CommandLineParser::getValue("client").getBool())
- Game::getInstance().requestStates("graphics, client, level");
- else if (CommandLineParser::getValue("dedicated").getBool())
- Game::getInstance().requestStates("server, level");
- else if (CommandLineParser::getValue("dedicatedClient").getBool())
- Game::getInstance().requestStates("client, level");
- /* ADD masterserver command */
- else if (CommandLineParser::getValue("masterserver").getBool())
- Game::getInstance().requestStates("masterserver");
- else
- {
- if (!CommandLineParser::getValue("console").getBool())
- Game::getInstance().requestStates("graphics, mainMenu");
- }
-
- game->run();
+ // Start your program here
}
- delete game;
+ delete core;
return 0;
}
Deleted: code/forks/sandbox_light/src/orxonox/MoodManager.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/MoodManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/MoodManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,105 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Kevin 'youngk' Young
- * Co-authors:
- * ...
- *
- */
-
-#include "MoodManager.h"
-
-#include "util/ScopedSingletonManager.h"
-#include "core/ConfigValueIncludes.h"
-#include "core/CoreIncludes.h"
-#include "core/Resource.h"
-
-namespace orxonox
-{
- ManageScopedSingleton(MoodManager, ScopeID::Root, false);
-
- // Note: I'm (Kevin Young) not entirely sure whether that's good code style:
- const std::string MoodManager::defaultMood_ = "default";
-
- MoodManager::MoodManager()
- {
- RegisterRootObject(MoodManager);
- this->setConfigValues();
-
- // Need to use a variable to store old data because ResetConfigValues() doesn't seem to work.
- oldMood_ = MoodManager::defaultMood_;
-
- // Checking for the existence of the folder for the default mood
- const std::string& path = "ambient/" + MoodManager::defaultMood_ + "/.";
- if (!Resource::exists(path))
- {
- // TODO: Non-fatal error handling (non-critical resource missing)
- COUT(2) << "Mood Warning: Folder for default mood (" << MoodManager::defaultMood_ << ") does not exist!" << std::endl;
- }
- }
-
- void MoodManager::setConfigValues()
- {
- SetConfigValue(mood_, MoodManager::defaultMood_)
- .description("Sets the mood for the current level.")
- .callback(this, &MoodManager::checkMoodValidity);
- }
-
- /** Set a new mood
- */
- void MoodManager::setMood(const std::string& mood)
- {
- oldMood_ = mood_;
- ModifyConfigValue(mood_, set, mood);
- }
-
- void MoodManager::checkMoodValidity()
- {
- // Generic mood validation
- const std::string& path = "ambient/" + mood_ + "/.";
- if (!Resource::exists(path))
- {
- COUT(3) << "Mood " << mood_ << " does not exist. Will not change." << std::endl;
- this->setMood(oldMood_);
- }
- else
- {
- COUT(3) << "Mood changed to " << mood_ << std::endl;
- MoodListener::changedMood(mood_);
- }
- }
-
-
- std::string MoodListener::mood_s;
-
- MoodListener::MoodListener()
- {
- RegisterRootObject(MoodListener);
- }
-
- /*static*/ void MoodListener::changedMood(const std::string& mood)
- {
- mood_s = mood;
- for (ObjectList<MoodListener>::iterator it = ObjectList<MoodListener>::begin(); it; ++it)
- it->moodChanged(mood_s);
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/MoodManager.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/MoodManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/MoodManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,91 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Kevin 'youngk' Young
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _MoodManager_H__
-#define _MoodManager_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <string>
-#include "util/Singleton.h"
-#include "core/OrxonoxClass.h"
-
-namespace orxonox
-{
- /*
- @brief
- The MoodListener class is aware of a change in themes and directs that info to dependent classes.
- */
- class _OrxonoxExport MoodListener : virtual public OrxonoxClass
- {
- friend class MoodManager;
-
- protected:
- MoodListener();
- virtual ~MoodListener() {}
-
- const std::string& getMood() const { return mood_s; }
-
- private:
- virtual void moodChanged(const std::string& mood) = 0;
-
- static void changedMood(const std::string& mood);
- static std::string mood_s;
- };
-
- /*
- @brief
- The MoodManager class serves to allow for different musical themes in the game.
- */
- class _OrxonoxExport MoodManager : public Singleton<MoodManager>, public OrxonoxClass
- {
- friend class Singleton<MoodManager>;
- public:
- MoodManager();
-
- void setConfigValues();
-
- void setMood(const std::string& mood);
- inline const std::string& getMood() const { return this->mood_; }
-
- static MoodManager& getInstance() { return Singleton<MoodManager>::getInstance(); }
-
- private:
- ~MoodManager() {}
- void checkMoodValidity();
-
- // config values
- std::string mood_;
- std::string oldMood_;
- static const std::string defaultMood_;
-
- static MoodManager* singletonPtr_s;
- };
-}
-
-#endif /* _MoodManager_H__ */
Modified: code/forks/sandbox_light/src/orxonox/OrxonoxPrecompiledHeaders.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/OrxonoxPrecompiledHeaders.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/OrxonoxPrecompiledHeaders.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -37,61 +37,6 @@
#include "OrxonoxConfig.h"
-///////////////////////////////////////////
-///// Stable Headers /////
-///////////////////////////////////////////
-
-#include <cassert> // 87
-#include <cstring> // 87
-#include <fstream> // 87
-#include <iostream> // 87
-#include <map> // 87
-#include <set> // 87
-#include <sstream> // 87
-#include <string> // 87
-#include <vector> // 87
-#include <list> // 86
-#include <ctime> // 82
-#include <cmath> // 81
-#include <deque> // 81
-#include <queue> // 81
-
-#include <OgreMath.h> // 81
-#include <OgreVector2.h> // 81
-#include <OgreVector3.h> // 81
-#include <OgreVector4.h> // 81
-#include <OgreQuaternion.h> // 81
-#include <OgreColourValue.h> // 81
-
-#include "util/OgreForwardRefs.h" // 67
-#include <LinearMath/btMotionState.h> // 60
-#include "util/SubString.h" // 55
-#include <tinyxml/ticpp.h> // 41
-
-//#include <OgreRenderable.h> // 14, 5.1MB
-//#include <OgreSceneNode.h> // 13, 1MB
-//#include <OgreResourceGroupManager.h> // 12, 1.5MB
-//#include <OgreTexture.h> // 11, 0.6MB
-//#include <OgreMovableObject.h> // 10, 1.6MB
-//#include <OgreSceneManager.h> // 9, 8.7MB
-
-///////////////////////////////////////////
-///// All Rebuild Headers /////
-///////////////////////////////////////////
-
-#include "core/BaseObject.h" // 82
-#include "core/CoreIncludes.h" // 80
-
-///////////////////////////////////////////
-///// Not so Stable Headers /////
-///////////////////////////////////////////
-
-#include "network/synchronisable/Synchronisable.h" // 70
-#include "util/MultiType.h" // 65
-#include "core/command/Executor.h" // 55
-//#include "core/XMLPort.h" // 41
-
-
// Just in case some header included windows.h
#undef min
#undef max
Modified: code/forks/sandbox_light/src/orxonox/OrxonoxPrereqs.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/OrxonoxPrereqs.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/OrxonoxPrereqs.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -36,7 +36,6 @@
#define _OrxonoxPrereqs_H__
#include "OrxonoxConfig.h"
-#include "tools/ToolsPrereqs.h"
//-----------------------------------------------------------------------
// Shared library settings
@@ -64,151 +63,6 @@
namespace orxonox
{
- class CameraManager;
- class Level;
- class LevelInfo;
- class LevelInfoItem;
- class LevelManager;
- class PawnManager;
- class PlayerManager;
- class Radar;
- class Scene;
-
- // collisionshapes
- class CollisionShape;
- class CompoundCollisionShape;
- class WorldEntityCollisionShape;
-
- // controllers
- class AIController;
- class ArtificialController;
- class Controller;
- class DroneController;
- class HumanController;
- class ScriptController;
- class WaypointController;
- class WaypointPatrolController;
-
- // gametypes
- class Asteroids;
- class Deathmatch;
- class Dynamicmatch;
- class Gametype;
- class LastManStanding;
- class TeamBaseMatch;
- class TeamDeathmatch;
- class UnderAttack;
-
- // graphics
- class Backlight;
- class Billboard;
- class BlinkingBillboard;
- class Camera;
- class FadingBillboard;
- class GlobalShader;
- class Light;
- class Model;
- class ParticleEmitter;
- class ParticleSpawner;
-
- // infos
- class Bot;
- class GametypeInfo;
- class HumanPlayer;
- class Info;
- class PlayerInfo;
-
- // interfaces
- class GametypeMessageListener;
- class NotificationListener;
- class Pickupable;
- class PickupCarrier;
- class PlayerTrigger;
- class RadarListener;
- class RadarViewable;
- class Rewardable;
- class TeamColourable;
-
- // items
- class Engine;
- class Item;
- class MultiStateEngine;
-
- // overlays
- class InGameConsole;
- class Map;
- class OrxonoxOverlay;
- class OverlayGroup;
-
- // pickup
- class PickupIdentifier;
-
- //sound
- class AmbientSound;
- class BaseSound;
- class SoundBuffer;
- class SoundManager;
- class SoundStreamer;
- class WorldSound;
- class WorldAmbientSound;
-
- // weaponsystem
- class DefaultWeaponmodeLink;
- class Munition;
- class Weapon;
- class WeaponMode;
- class WeaponPack;
- class WeaponSet;
- class WeaponSlot;
- class WeaponSystem;
-
- // worldentities
- class BigExplosion;
- class CameraPosition;
- class ControllableEntity;
- class Drone;
- class EffectContainer;
- class ExplosionChunk;
- class MobileEntity;
- class MovableEntity;
- class SpawnPoint;
- class StaticEntity;
- class TeamSpawnPoint;
- class WorldEntity;
- class Rocket;
- // worldentities, pawns
- class Destroyer;
- class Pawn;
- class SpaceShip;
- class Spectator;
- class TeamBaseMatchBase;
}
-// Bullet Physics Engine
-class btTransform;
-class btVector3;
-
-class btRigidBody;
-class btCollisionObject;
-class btGhostObject;
-class btManifoldPoint;
-
-class btCollisionShape;
-class btSphereShape;
-class btCompoundShape;
-class btStaticPlaneShape;
-
-class btDiscreteDynamicsWorld;
-class bt32BitAxisSweep3;
-class btDefaultCollisionConfiguration;
-class btCollisionDispatcher;
-class btSequentialImpulseConstraintSolver;
-
-// ALUT
-typedef struct ALCcontext_struct ALCcontext;
-typedef struct ALCdevice_struct ALCdevice;
-typedef unsigned int ALuint;
-typedef int ALint;
-typedef int ALenum;
-
#endif /* _OrxonoxPrereqs_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/PawnManager.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/PawnManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/PawnManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,67 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "PawnManager.h"
-
-#include "core/CoreIncludes.h"
-#include "worldentities/pawns/Pawn.h"
-
-namespace orxonox
-{
- PawnManager* PawnManager::singletonPtr_s = 0;
-
- PawnManager::PawnManager()
- {
- RegisterRootObject(PawnManager);
- }
-
- PawnManager::~PawnManager()
- {
- }
-
- void PawnManager::touch()
- {
- if (!PawnManager::singletonPtr_s)
- new PawnManager();
- }
-
- void PawnManager::tick(float dt)
- {
- unsigned int count = 0;
- for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); ++count)
- {
- if (!it->isAlive())
- (it++)->destroy();
- else
- ++it;
- }
-
- if (count == 0)
- this->destroy();
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/PawnManager.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/PawnManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/PawnManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,55 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _PawnManager_H__
-#define _PawnManager_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include "util/Singleton.h"
-#include "tools/interfaces/Tickable.h"
-
-namespace orxonox
-{
- class _OrxonoxExport PawnManager : protected Singleton<PawnManager>, public Tickable
- {
- friend class Singleton<PawnManager>;
- public:
- static void touch();
-
- virtual void tick(float dt);
-
- private:
- PawnManager();
- virtual ~PawnManager();
-
- static PawnManager* singletonPtr_s;
- };
-}
-
-#endif /* _PawnManager_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/PlayerManager.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/PlayerManager.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/PlayerManager.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,117 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#include "PlayerManager.h"
-
-#include "core/CoreIncludes.h"
-#include "core/GameMode.h"
-#include "util/ScopedSingletonManager.h"
-
-#include "Level.h"
-#include "LevelManager.h"
-#include "infos/HumanPlayer.h"
-
-namespace orxonox
-{
- ManageScopedSingleton(PlayerManager, ScopeID::Root, false);
-
- PlayerManager::PlayerManager()
- {
- RegisterRootObject(PlayerManager);
-
- this->getConnectedClients();
- }
-
- PlayerManager::~PlayerManager()
- {
- }
-
- void PlayerManager::clientConnected(unsigned int clientID)
- {
- if (GameMode::isMaster())
- {
- if (clientID != 0)
- COUT(3) << "client connected" << std::endl;
-
- // create new HumanPlayer instance
- HumanPlayer* player = new HumanPlayer(0);
- player->setClientID(clientID);
-
- // add to clients-map
- assert(!this->clients_[clientID]);
- this->clients_[clientID] = player;
-
- if (LevelManager::exists() && LevelManager::getInstance().getActiveLevel())
- LevelManager::getInstance().getActiveLevel()->playerEntered(player);
- }
- }
-
- void PlayerManager::clientDisconnected(unsigned int clientID)
- {
- if (GameMode::isMaster())
- {
- if (clientID != 0)
- COUT(3) << "client disconnected" << std::endl;
-
- // remove from clients-map
- PlayerInfo* player = this->clients_[clientID];
- this->clients_.erase(clientID);
-
- if (LevelManager::exists() && LevelManager::getInstance().getActiveLevel())
- LevelManager::getInstance().getActiveLevel()->playerLeft(player);
-
- // delete PlayerInfo instance
- if (player)
- player->destroy();
- }
- }
-
- void PlayerManager::disconnectAllClients()
- {
- for( std::map<unsigned int, PlayerInfo*>::iterator it = this->clients_.begin(); it != this->clients_.end(); )
- this->clientDisconnected( (it++)->first );
- }
-
-
- PlayerInfo* PlayerManager::getClient(unsigned int clientID) const
- {
- if (GameMode::isMaster())
- {
- std::map<unsigned int, PlayerInfo*>::const_iterator it = this->clients_.find(clientID);
- if (it != this->clients_.end())
- return it->second;
- }
- else
- {
- for (ObjectList<PlayerInfo>::iterator it = ObjectList<PlayerInfo>::begin(); it != ObjectList<PlayerInfo>::end(); ++it)
- if (it->getClientID() == clientID)
- return (*it);
- }
- return 0;
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/PlayerManager.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/PlayerManager.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/PlayerManager.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,63 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _PlayerManager_H__
-#define _PlayerManager_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <cassert>
-#include <map>
-#include "util/Singleton.h"
-#include "network/ClientConnectionListener.h"
-
-namespace orxonox
-{
- class _OrxonoxExport PlayerManager : public Singleton<PlayerManager>, public ClientConnectionListener
- {
- friend class Singleton<PlayerManager>;
- public:
- PlayerManager();
- virtual ~PlayerManager();
-
- PlayerInfo* getClient(unsigned int clientID) const;
- inline const std::map<unsigned int, PlayerInfo*>& getClients() const
- { return this->clients_; }
-
- void clientConnected(unsigned int clientID);
- void clientDisconnected(unsigned int clientID);
- void disconnectAllClients();
-
- private:
- std::map<unsigned int, PlayerInfo*> clients_;
-
- static PlayerManager* singletonPtr_s;
- };
-}
-
-#endif /* _PlayerManager_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/Radar.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/Radar.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Radar.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,213 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * Felix Schulthess
- *
- */
-
-/**
- at file
- at brief
-*/
-
-#include "Radar.h"
-
-#include <cassert>
-
-//#include "util/Math.h"
-#include "core/ObjectList.h"
-#include "core/command/ConsoleCommand.h"
-#include "interfaces/RadarListener.h"
-#include "controllers/HumanController.h"
-#include "worldentities/pawns/Pawn.h"
-
-namespace orxonox
-{
-
- Radar::Radar()
- : itFocus_(0)
- , focus_(0)
- , objectTypeCounter_(0)
- {
- // TODO: make this mapping configurable. Maybe there's a possibility with self configured
- // configValues..
- this->objectTypes_["Asteroid"] = RadarViewable::Dot;
- this->objectTypes_["SpaceShip"] = RadarViewable::Square;
- this->objectTypes_["AsdfQwerty"] = RadarViewable::Triangle;
-
- /*WorldEntity* object;
- object = new WorldEntity();
- object->setPosition(2000.0, 0.0, 0.0);
- addRadarObject(object, ColourValue(0.5, 0, 0, 1));
- object = new WorldEntity();
- object->setPosition(0.0, 2000.0, 0.0);
- addRadarObject(object, ColourValue(0.5, 0, 0, 1));
- object = new WorldEntity();
- object->setPosition(0.0, 0.0, 2000.0);
- addRadarObject(object, ColourValue(0.5, 0, 0, 1));
- object = new WorldEntity();
- object->setPosition(10000.0,16000.0,0.0);
- addRadarObject(object);*/
-
- }
-
- Radar::~Radar()
- {
- }
-
- void Radar::addRadarObject(RadarViewable* rv)
- {
- assert( this->radarObjects_.find(rv) == this->radarObjects_.end() );
- this->radarObjects_.insert(rv);
- // iterate through all radarlisteners and notify them
- for (ObjectList<RadarListener>::iterator itListener = ObjectList<RadarListener>::begin(); itListener; ++itListener)
- {
- (*itListener)->addObject(rv);
- }
- }
-
- void Radar::removeRadarObject(RadarViewable* rv)
- {
- assert( this->radarObjects_.find(rv) != this->radarObjects_.end() );
- this->radarObjects_.erase(rv);
- // iterate through all radarlisteners and notify them
- for (ObjectList<RadarListener>::iterator itListener = ObjectList<RadarListener>::begin(); itListener; ++itListener)
- {
- (*itListener)->removeObject(rv);
- }
- }
-
- const RadarViewable* Radar::getFocus()
- {
- if (this->itFocus_)
- return *(this->itFocus_);
- else
- return 0;
- }
-
- RadarViewable::Shape Radar::addObjectDescription(const std::string& name)
- {
- std::map<std::string, RadarViewable::Shape>::iterator it = this->objectTypes_.find(name);
- if (it == this->objectTypes_.end())
- return this->objectTypes_[name] = RadarViewable::Square; // default, configure!!
- else
- return this->objectTypes_[name];
- }
-
-
- void Radar::tick(float dt)
- {
- SUPER(Radar, tick, dt);
-
- if (this->itFocus_ && (this->focus_ != *(this->itFocus_)))
- {
- // focus object was deleted, release focus
- this->focus_ = 0;
- this->itFocus_ = 0;
- }
-
- for (ObjectList<RadarListener>::iterator itListener = ObjectList<RadarListener>::begin(); itListener; ++itListener)
- {
- (*itListener)->radarTick(dt);
- }
- }
-
- void Radar::cycleFocus()
- {
- if (ObjectList<RadarViewable>::begin() == ObjectList<RadarViewable>::end())
- {
- // list is empty
- this->itFocus_ = 0;
- this->focus_ = 0;
- }
-
- else if (HumanController::getLocalControllerEntityAsPawn())
- {
- Vector3 localPosition = HumanController::getLocalControllerEntityAsPawn()->getWorldPosition();
- Vector3 targetPosition = localPosition;
- if (this->itFocus_ && *(this->itFocus_))
- targetPosition = this->itFocus_->getRVWorldPosition();
-
- // find the closest object further away than targetPosition
- float currentDistance = localPosition.squaredDistance(targetPosition);
- float nextDistance = FLT_MAX;
- float minimumDistance = FLT_MAX;
- ObjectList<RadarViewable>::iterator itFallback = 0;
-
- for (ObjectList<RadarViewable>::iterator it = ObjectList<RadarViewable>::begin(); it; ++it)
- {
- if (*it == static_cast<RadarViewable*>(HumanController::getLocalControllerEntityAsPawn()))
- continue;
-
- float targetDistance = localPosition.squaredDistance((*it)->getRVWorldPosition());
- if (targetDistance > currentDistance && targetDistance < nextDistance)
- {
- this->itFocus_ = it;
- nextDistance = targetDistance;
- }
- if (targetDistance < minimumDistance)
- {
- itFallback = it;
- minimumDistance = targetDistance;
- }
- }
-
- if (nextDistance == FLT_MAX)
- {
- // we already had the furthest object
- this->itFocus_ = itFallback;
- this->focus_ = *itFallback;
- }
- else
- {
- this->focus_ = *(this->itFocus_);
- }
- }
- }
-
- void Radar::releaseFocus()
- {
- this->itFocus_ = 0;
- this->focus_ = 0;
- }
-
- void Radar::listObjects() const
- {
- COUT(3) << "List of RadarObjects:\n";
- // iterate through all Radar Objects
- unsigned int i = 0;
- for (ObjectList<RadarViewable>::iterator it = ObjectList<RadarViewable>::begin(); it; ++it, ++i)
- {
- COUT(3) << i++ << ": " << (*it)->getRVWorldPosition() << std::endl;
- }
- }
-
- void Radar::radarObjectChanged(RadarViewable* rv)
- {
- for (ObjectList<RadarListener>::iterator itListener = ObjectList<RadarListener>::begin(); itListener; ++itListener)
- {
- (*itListener)->objectChanged(rv);
- }
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/Radar.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/Radar.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Radar.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,83 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Reto Grieder
- * Co-authors:
- * Felix Schulthess
- *
- */
-
-/**
- at file
- at brief
-*/
-
-#ifndef _Radar_H__
-#define _Radar_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <map>
-#include <set>
-#include <string>
-
-#include "core/ObjectListIterator.h"
-#include "interfaces/RadarViewable.h"
-#include "tools/interfaces/Tickable.h"
-
-namespace orxonox
-{
- class _OrxonoxExport Radar : public Tickable
- {
- friend class RadarViewable;
- public:
- Radar();
- virtual ~Radar();
-
- virtual void tick(float dt);
-
- const RadarViewable* getFocus();
- RadarViewable::Shape addObjectDescription(const std::string& name);
-
- void listObjects() const;
- const std::set<RadarViewable*>& getRadarObjects() const
- { return this->radarObjects_; }
-
- void releaseFocus();
- void cycleFocus();
-
- private:
- Radar(Radar& instance);
-
- void updateFocus();
- void addRadarObject(RadarViewable* rv);
- void removeRadarObject(RadarViewable* rv);
- void radarObjectChanged(RadarViewable* rv);
-
- ObjectListIterator<RadarViewable> itFocus_;
- RadarViewable* focus_;
- std::map<std::string, RadarViewable::Shape> objectTypes_;
- std::set<RadarViewable*> radarObjects_;
- int objectTypeCounter_;
- };
-}
-#endif /* _Radar_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/Scene.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/Scene.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Scene.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,352 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Reto Grieder (physics)
- * Co-authors:
- * ...
- *
- */
-
-#include "Scene.h"
-
-#include <OgreRoot.h>
-#include <OgreSceneManager.h>
-#include <OgreSceneManagerEnumerator.h>
-#include <OgreSceneNode.h>
-
-#include <BulletCollision/BroadphaseCollision/btAxisSweep3.h>
-#include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h>
-#include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h>
-#include <BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h>
-
-#include "core/CoreIncludes.h"
-#include "core/GameMode.h"
-#include "core/GUIManager.h"
-#include "core/XMLPort.h"
-#include "tools/BulletConversions.h"
-#include "Radar.h"
-#include "worldentities/WorldEntity.h"
-#include "Level.h"
-
-namespace orxonox
-{
- CreateFactory(Scene);
-
- Scene::Scene(BaseObject* creator) : BaseObject(creator), Synchronisable(creator)
- {
- RegisterObject(Scene);
-
- this->setScene(SmartPtr<Scene>(this, false), OBJECTID_UNKNOWN);
- this->bShadows_ = true;
- this->soundReferenceDistance_ = 20.0;
-
- if (GameMode::showsGraphics())
- {
- assert(Ogre::Root::getSingletonPtr());
- this->sceneManager_ = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC);
- this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
-
- this->radar_ = new Radar();
- }
- else
- {
- // create a dummy SceneManager of our own since we don't have Ogre::Root.
- this->sceneManager_ = new Ogre::DefaultSceneManager("");
- this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
-
- this->radar_ = 0;
- }
-
- // No physics yet, XMLPort will do that.
- const int defaultMaxWorldSize = 100000;
- this->negativeWorldRange_ = Vector3::UNIT_SCALE * -defaultMaxWorldSize;
- this->positiveWorldRange_ = Vector3::UNIT_SCALE * defaultMaxWorldSize;
- this->gravity_ = Vector3::ZERO;
- this->physicalWorld_ = 0;
- this->solver_ = 0;
- this->dispatcher_ = 0;
- this->collisionConfig_ = 0;
- this->broadphase_ = 0;
-
- this->registerVariables();
- }
-
- Scene::~Scene()
- {
- if (this->isInitialized())
- {
- if (GameMode::showsGraphics())
- Ogre::Root::getSingleton().destroySceneManager(this->sceneManager_);
- else
- delete this->sceneManager_;
-
- if (this->radar_)
- this->radar_->destroy();
-
- this->setPhysicalWorld(false);
- }
- }
-
- void Scene::XMLPort(Element& xmlelement, XMLPort::Mode mode)
- {
- SUPER(Scene, XMLPort, xmlelement, mode);
-
- XMLPortParam(Scene, "skybox", setSkybox, getSkybox, xmlelement, mode);
- XMLPortParam(Scene, "ambientlight", setAmbientLight, getAmbientLight, xmlelement, mode).defaultValues(ColourValue(0.2f, 0.2f, 0.2f, 1.0f));
- XMLPortParam(Scene, "shadow", setShadow, getShadow, xmlelement, mode).defaultValues(true);
- XMLPortParam(Scene, "soundReferenceDistance", setSoundReferenceDistance, getSoundReferenceDistance, xmlelement, mode);
-
- XMLPortParam(Scene, "gravity", setGravity, getGravity, xmlelement, mode);
- XMLPortParam(Scene, "negativeWorldRange", setNegativeWorldRange, getNegativeWorldRange, xmlelement, mode);
- XMLPortParam(Scene, "positiveWorldRange", setPositiveWorldRange, getPositiveWorldRange, xmlelement, mode);
- XMLPortParam(Scene, "hasPhysics", setPhysicalWorld, hasPhysics, xmlelement, mode).defaultValues(true);
-
- XMLPortObjectExtended(Scene, BaseObject, "", addObject, getObject, xmlelement, mode, true, false);
- }
-
- void Scene::registerVariables()
- {
- registerVariable(this->skybox_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applySkybox));
- registerVariable(this->ambientLight_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyAmbientLight));
- registerVariable(this->negativeWorldRange_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_negativeWorldRange));
- registerVariable(this->positiveWorldRange_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_positiveWorldRange));
- registerVariable(this->gravity_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_gravity));
- registerVariable(this->bHasPhysics_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_hasPhysics));
- registerVariable(this->bShadows_, VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::networkcallback_applyShadows));
- registerVariable(this->getLevel(), VariableDirection::ToClient, new NetworkCallback<Scene>(this, &Scene::changedLevel));
- }
-
- void Scene::setNegativeWorldRange(const Vector3& range)
- {
- if (range.length() < 10.0f)
- {
- CCOUT(2) << "Warning: Setting the negative world range to a very small value: "
- << multi_cast<std::string>(range) << std::endl;
- }
- if (this->hasPhysics())
- {
- CCOUT(2) << "Warning: Attempting to set the physical world range at run time. "
- << "This causes a complete physical reload which might take some time." << std::endl;
- this->setPhysicalWorld(false);
- this->negativeWorldRange_ = range;
- this->setPhysicalWorld(true);
- }
- else
- this->negativeWorldRange_ = range;
- }
-
- void Scene::setPositiveWorldRange(const Vector3& range)
- {
- if (range.length() < 10.0f)
- {
- CCOUT(2) << "Warning: Setting the positive world range to a very small value: "
- << multi_cast<std::string>(range) << std::endl;
- }
- if (this->hasPhysics())
- {
- CCOUT(2) << "Warning: Attempting to set the physical world range at run time. "
- << "This causes a complete physical reload which might take some time." << std::endl;
- this->setPhysicalWorld(false);
- this->positiveWorldRange_ = range;
- this->setPhysicalWorld(true);
- }
- else
- this->positiveWorldRange_ = range;
- }
-
- void Scene::setGravity(const Vector3& gravity)
- {
- this->gravity_ = gravity;
- if (this->hasPhysics())
- this->physicalWorld_->setGravity(multi_cast<btVector3>(this->gravity_));
- }
-
- void Scene::setPhysicalWorld(bool wantPhysics)
- {
- this->bHasPhysics_ = wantPhysics;
- if (wantPhysics && !hasPhysics())
- {
- // Note: These are all little known default classes and values.
- // It would require further investigation to properly dertermine the right choices.
- this->broadphase_ = new bt32BitAxisSweep3(
- multi_cast<btVector3>(this->negativeWorldRange_), multi_cast<btVector3>(this->positiveWorldRange_));
- this->collisionConfig_ = new btDefaultCollisionConfiguration();
- this->dispatcher_ = new btCollisionDispatcher(this->collisionConfig_);
- this->solver_ = new btSequentialImpulseConstraintSolver();
-
- this->physicalWorld_ = new btDiscreteDynamicsWorld(this->dispatcher_, this->broadphase_, this->solver_, this->collisionConfig_);
- this->physicalWorld_->setGravity(multi_cast<btVector3>(this->gravity_));
-
- // also set the collision callback variable.
- // Note: This is a global variable which we assign a static function.
- // TODO: Check whether this (or anything about Bullet) works with multiple physics engine instances.
- gContactAddedCallback = &Scene::collisionCallback;
- }
- else if (!wantPhysics && hasPhysics())
- {
- // Remove all WorldEntities and shove them to the queue since they would still like to be in a physical world.
- for (std::set<WorldEntity*>::const_iterator it = this->physicalObjects_.begin();
- it != this->physicalObjects_.end(); ++it)
- {
- this->physicalWorld_->removeRigidBody((*it)->physicalBody_);
- this->physicalObjectQueue_.insert(*it);
- }
- this->physicalObjects_.clear();
-
- delete this->physicalWorld_;
- delete this->solver_;
- delete this->dispatcher_;
- delete this->collisionConfig_;
- delete this->broadphase_;
- this->physicalWorld_ = 0;
- this->solver_ = 0;
- this->dispatcher_ = 0;
- this->collisionConfig_ = 0;
- this->broadphase_ = 0;
- }
- }
-
- void Scene::tick(float dt)
- {
- if (!GameMode::showsGraphics())
- {
- // We need to update the scene nodes if we don't render
- this->rootSceneNode_->_update(true, false);
- }
- if (this->hasPhysics())
- {
- // TODO: This here is bad practice! It will slow down the first tick() by ages.
- // Rather have an initialise() method as well, called by the Level after everything has been loaded.
- if (this->physicalObjectQueue_.size() > 0)
- {
- // Add all scheduled WorldEntities
- for (std::set<WorldEntity*>::const_iterator it = this->physicalObjectQueue_.begin();
- it != this->physicalObjectQueue_.end(); ++it)
- {
- this->physicalWorld_->addRigidBody((*it)->physicalBody_);
- this->physicalObjects_.insert(*it);
- }
- this->physicalObjectQueue_.clear();
- }
-
- // Note: 60 means that Bullet will do physics correctly down to 1 frames per seconds.
- // Under that mark, the simulation will "loose time" and get unusable.
- physicalWorld_->stepSimulation(dt, 60);
- }
- }
-
- void Scene::setSkybox(const std::string& skybox)
- {
- if (GameMode::showsGraphics() && this->sceneManager_)
- this->sceneManager_->setSkyBox(true, skybox);
-
- this->skybox_ = skybox;
- }
-
- void Scene::setAmbientLight(const ColourValue& colour)
- {
- if (GameMode::showsGraphics() && this->sceneManager_)
- this->sceneManager_->setAmbientLight(colour);
-
- this->ambientLight_ = colour;
- }
-
- void Scene::setShadow(bool bShadow)
- {
- if (GameMode::showsGraphics() && this->sceneManager_)
- {
- if (bShadow)
- this->sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);
- else
- this->sceneManager_->setShadowTechnique(Ogre::SHADOWTYPE_NONE);
- }
-
- this->bShadows_ = bShadow;
- }
-
- void Scene::addObject(BaseObject* object)
- {
- this->objects_.push_back(object);
- object->setScene(this, this->getObjectID());
- }
-
- BaseObject* Scene::getObject(unsigned int index) const
- {
- unsigned int i = 0;
- for (std::list<BaseObject*>::const_iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
- {
- if (i == index)
- return (*it);
- ++i;
- }
- return 0;
- }
-
- void Scene::addPhysicalObject(WorldEntity* object)
- {
- if (object)
- {
- std::set<WorldEntity*>::iterator it = this->physicalObjects_.find(object);
- if (it != this->physicalObjects_.end())
- return;
-
- this->physicalObjectQueue_.insert(object);
- }
- }
-
- void Scene::removePhysicalObject(WorldEntity* object)
- {
- // check queue first
- std::set<WorldEntity*>::iterator it = this->physicalObjectQueue_.find(object);
- if (it != this->physicalObjectQueue_.end())
- {
- this->physicalObjectQueue_.erase(it);
- return;
- }
-
- it = this->physicalObjects_.find(object);
- if (it == this->physicalObjects_.end())
- return;
- this->physicalObjects_.erase(it);
-
- if (this->hasPhysics())
- this->physicalWorld_->removeRigidBody(object->physicalBody_);
- }
-
- /*static*/ bool Scene::collisionCallback(btManifoldPoint& cp, const btCollisionObject* colObj0, int partId0,
- int index0, const btCollisionObject* colObj1, int partId1, int index1)
- {
- // get the WorldEntity pointers
- SmartPtr<WorldEntity> object0 = static_cast<WorldEntity*>(colObj0->getUserPointer());
- SmartPtr<WorldEntity> object1 = static_cast<WorldEntity*>(colObj1->getUserPointer());
-
- // false means that bullet will assume we didn't modify the contact
- bool modified = false;
- if (object0->isCollisionCallbackActive())
- modified |= object0->collidesAgainst(object1, cp);
- if (object1->isCollisionCallbackActive())
- modified |= object1->collidesAgainst(object0, cp);
-
- return modified;
- }
-}
Deleted: code/forks/sandbox_light/src/orxonox/Scene.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/Scene.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Scene.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,161 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Fabian 'x3n' Landau
- * Reto Grieder (physics)
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _Scene_H__
-#define _Scene_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <list>
-#include <set>
-#include <string>
-
-#include "util/Math.h"
-#include "util/OgreForwardRefs.h"
-#include "core/BaseObject.h"
-#include "network/synchronisable/Synchronisable.h"
-#include "tools/interfaces/Tickable.h"
-
-namespace orxonox
-{
- class _OrxonoxExport Scene : public BaseObject, public Synchronisable, public Tickable
- {
- public:
- Scene(BaseObject* creator);
- virtual ~Scene();
-
- virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
- void registerVariables();
-
- inline Ogre::SceneManager* getSceneManager() const
- { return this->sceneManager_; }
- inline Ogre::SceneNode* getRootSceneNode() const
- { return this->rootSceneNode_; }
-
- void setSkybox(const std::string& skybox);
- inline const std::string& getSkybox() const
- { return this->skybox_; }
-
- void setAmbientLight(const ColourValue& colour);
- inline const ColourValue& getAmbientLight() const
- { return this->ambientLight_; }
-
- void setShadow(bool bShadow);
- inline bool getShadow() const
- { return this->bShadows_; }
-
- inline void setSoundReferenceDistance(float distance)
- { this->soundReferenceDistance_ = distance; }
- inline float getSoundReferenceDistance() const
- { return this->soundReferenceDistance_; }
-
- inline Radar* getRadar()
- { return this->radar_; }
-
- inline virtual uint32_t getSceneID() const { return this->getObjectID(); }
-
- virtual void tick(float dt);
-
- private:
- void addObject(BaseObject* object);
- BaseObject* getObject(unsigned int index) const;
-
- void networkcallback_applySkybox()
- { this->setSkybox(this->skybox_); }
- void networkcallback_applyAmbientLight()
- { this->setAmbientLight(this->ambientLight_); }
- void networkcallback_applyShadows()
- { this->setShadow(this->bShadows_); }
-
- Ogre::SceneManager* sceneManager_;
- Ogre::SceneNode* rootSceneNode_;
-
- std::string skybox_;
- ColourValue ambientLight_;
- std::list<BaseObject*> objects_;
- bool bShadows_;
- float soundReferenceDistance_;
- Radar* radar_;
-
-
- /////////////
- // Physics //
- /////////////
-
- public:
- inline bool hasPhysics()
- { return this->physicalWorld_ != 0; }
- void setPhysicalWorld(bool wantsPhysics);
-
- void setNegativeWorldRange(const Vector3& range);
- inline const Vector3& getNegativeWorldRange() const
- { return this->negativeWorldRange_; }
-
- void setPositiveWorldRange(const Vector3& range);
- inline const Vector3& getPositiveWorldRange() const
- { return this->positiveWorldRange_; }
-
- void setGravity(const Vector3& gravity);
- inline const Vector3& getGravity() const
- { return this->gravity_; }
-
- void addPhysicalObject(WorldEntity* object);
- void removePhysicalObject(WorldEntity* object);
-
- private:
- inline void networkcallback_hasPhysics()
- { this->setPhysicalWorld(this->bHasPhysics_); }
- inline void networkcallback_negativeWorldRange()
- { this->setNegativeWorldRange(this->negativeWorldRange_); }
- inline void networkcallback_positiveWorldRange()
- { this->setPositiveWorldRange(this->positiveWorldRange_); }
- inline void networkcallback_gravity()
- { this->setGravity(this->gravity_); }
-
- // collision callback from bullet
- static bool collisionCallback(btManifoldPoint& cp, const btCollisionObject* colObj0, int partId0,
- int index0, const btCollisionObject* colObj1, int partId1, int index1);
-
- // Bullet objects
- btDiscreteDynamicsWorld* physicalWorld_;
- bt32BitAxisSweep3* broadphase_;
- btDefaultCollisionConfiguration* collisionConfig_;
- btCollisionDispatcher* dispatcher_;
- btSequentialImpulseConstraintSolver* solver_;
-
- std::set<WorldEntity*> physicalObjectQueue_;
- std::set<WorldEntity*> physicalObjects_;
- bool bHasPhysics_;
- Vector3 negativeWorldRange_;
- Vector3 positiveWorldRange_;
- Vector3 gravity_;
- };
-}
-
-#endif /* _Scene_H__ */
Deleted: code/forks/sandbox_light/src/orxonox/Test.cc
===================================================================
--- code/forks/sandbox_light/src/orxonox/Test.cc 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Test.cc 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,152 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oli Scheuss
- * Co-authors:
- * ...
- *
- */
-
-#include "core/CoreIncludes.h"
-#include "core/ConfigValueIncludes.h"
-#include "core/command/ConsoleCommand.h"
-#include "network/NetworkFunction.h"
-#include "Test.h"
-#include "util/MultiType.h"
-
-namespace orxonox
-{
- CreateFactory ( Test );
-
- SetConsoleCommand("Test", "printV1", &Test::printV1).addShortcut();
- SetConsoleCommand("Test", "printV2", &Test::printV2).addShortcut();
- SetConsoleCommand("Test", "printV3", &Test::printV3).addShortcut();
- SetConsoleCommand("Test", "printV4", &Test::printV4).addShortcut();
- SetConsoleCommand("Test", "call", &Test::call).addShortcut();
- SetConsoleCommand("Test", "call2", &Test::call2).addShortcut();
-
-
- //void=* aaaaa = copyPtr<sizeof(&Test::printV1)>( &NETWORK_FUNCTION_POINTER, &Test::printV1 );
- //void* NETWORK_FUNCTION_TEST_B = memcpy(&NETWORK_FUNCTION_POINTER, &a, sizeof(a));
-// NetworkFunctionBase* NETWORK_FUNCTION_TEST_C = new NetworkFunctionStatic( createFunctor(&Test::printV1), "bla", NETWORK_FUNCTION_POINTER );
-
- registerStaticNetworkFunction( &Test::printV1 );
- registerMemberNetworkFunction( Test, checkU1 );
- registerMemberNetworkFunction( Test, printBlaBla );
-
- Test* Test::instance_ = 0;
-
- Test::Test(BaseObject* creator) : BaseObject(creator), Synchronisable(creator)
- {
- assert(instance_==0);
- instance_=this;
- RegisterObject ( Test );
- setConfigValues();
- registerVariables();
- setSyncMode(0x3);
- this->pointer_ = 0;
- }
-
- Test::~Test()
- {
- instance_=0;
- }
-
- void Test::setConfigValues()
- {
- SetConfigValue ( u1, 1 )/*.callback ( this, &Test::checkV1 )*/;
- SetConfigValue ( u2, 2 )/*.callback ( this, &Test::checkV2 )*/;
- SetConfigValue ( u3, 3 )/*.callback ( this, &Test::checkV3 )*/;
- SetConfigValue ( u4, 4 )/*.callback ( this, &Test::checkV4 )*/;
-
- SetConfigValue ( s1, 1 )/*.callback ( this, &Test::checkV1 )*/;
- SetConfigValue ( s2, 2 )/*.callback ( this, &Test::checkV2 )*/;
- SetConfigValue ( s3, 3 )/*.callback ( this, &Test::checkV3 )*/;
- SetConfigValue ( s4, 4 )/*.callback ( this, &Test::checkV4 )*/;
- }
-
-
- void Test::registerVariables()
- {
- registerVariable ( this->mySet_, VariableDirection::ToClient );
-
-// registerVariable ( u1, VariableDirection::ToClient, new NetworkCallback<Test> ( this, &Test::checkU1 ));
-// registerVariable ( u2, VariableDirection::ToServer, new NetworkCallback<Test> ( this, &Test::checkU2 ));
-// registerVariable ( u3, Bidirectionality::ServerMaster, new NetworkCallback<Test> ( this, &Test::checkU3 ), true );
-// registerVariable ( u4, Bidirectionality::ClientMaster, new NetworkCallback<Test> ( this, &Test::checkU4 ), true );
-
-// registerVariable ( s1, VariableDirection::ToClient, new NetworkCallback<Test> ( this, &Test::checkS1 ));
-// registerVariable ( s2, VariableDirection::ToServer, new NetworkCallback<Test> ( this, &Test::checkS2 ));
-// registerVariable ( s3, Bidirectionality::ServerMaster, new NetworkCallback<Test> ( this, &Test::checkS3 ), true );
-// registerVariable ( s4, Bidirectionality::ClientMaster, new NetworkCallback<Test> ( this, &Test::checkS4 ), true );
-
-// registerVariable ( pointer_, VariableDirection::ToClient, new NetworkCallback<Test> ( this, &Test::printPointer ) );
- }
-
- void Test::call(unsigned int clientID)
- {
- callStaticNetworkFunction( &Test::printV1, clientID );
- callStaticNetworkFunction( &Test::printV1, clientID );
- }
-
- void Test::call2(unsigned int clientID, std::string s1, std::string s2, std::string s3, std::string s4)
- {
- callMemberNetworkFunction( Test, printBlaBla, this->getObjectID(), clientID, s1, s2, s3, s4, s4 );
- }
-
- void Test::tick(float dt)
- {
- // std::string str1 = "blub";
- // //MultiType mt1(std::string("blub"));
- // MultiType mt1(str1);
- // uint8_t* mem = new uint8_t[mt1.getNetworkSize()];
- // uint8_t* temp = mem;
- // mt1.exportData( temp );
- // assert( temp-mem == mt1.getNetworkSize() );
- // MultiType mt2;
- // temp = mem;
- // mt2.importData( temp );
- // assert( temp-mem == mt1.getNetworkSize() );
- // COUT(0) << mt2 << endl;
- // if(!Core::isMaster())
- // call2(0, "bal", "a", "n", "ce");
- // callMemberNetworkFunction( Test, checkU1, this->getObjectID(), 0 );
- }
-
- void Test::printBlaBla(std::string s1, std::string s2, std::string s3, std::string s4, std::string s5)
- {
- COUT(0) << s1 << s2 << s3 << s4 << s5 << endl;
- }
-
- void Test::checkU1(){ COUT(1) << "U1 changed: " << u1 << std::endl; }
- void Test::checkU2(){ COUT(1) << "U2 changed: " << u2 << std::endl; }
- void Test::checkU3(){ COUT(1) << "U3 changed: " << u3 << std::endl; }
- void Test::checkU4(){ COUT(1) << "U4 changed: " << u4 << std::endl; }
-
- void Test::checkS1(){ COUT(1) << "S1 changed: " << s1 << std::endl; }
- void Test::checkS2(){ COUT(1) << "S2 changed: " << s2 << std::endl; }
- void Test::checkS3(){ COUT(1) << "S3 changed: " << s3 << std::endl; }
- void Test::checkS4(){ COUT(1) << "S4 changed: " << s4 << std::endl; }
-
- void Test::printPointer(){ CCOUT(1) << "pointer: " << this->pointer_ << endl; }
-
-}
Deleted: code/forks/sandbox_light/src/orxonox/Test.h
===================================================================
--- code/forks/sandbox_light/src/orxonox/Test.h 2011-02-17 04:42:45 UTC (rev 7907)
+++ code/forks/sandbox_light/src/orxonox/Test.h 2011-02-17 04:47:22 UTC (rev 7908)
@@ -1,114 +0,0 @@
-/*
- * ORXONOX - the hottest 3D action shooter ever to exist
- * > www.orxonox.net <
- *
- *
- * License notice:
- *
- * 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.
- *
- * Author:
- * Oli Scheuss
- * Co-authors:
- * ...
- *
- */
-
-#ifndef _Test_H__
-#define _Test_H__
-
-#include "OrxonoxPrereqs.h"
-#include "core/BaseObject.h"
-#include "network/synchronisable/Synchronisable.h"
-#include "tools/interfaces/Tickable.h"
-
-#include <set>
-
-typedef int TYPE;
-typedef unsigned int UTYPE;
-
-
-namespace orxonox
-{
- class _OrxonoxExport Test: public BaseObject, public Synchronisable, public Tickable
- {
- public:
- Test(BaseObject* creator);
- virtual ~Test();
-
- void setConfigValues();
-
- static void call(unsigned int clientID);
- void call2(unsigned int clientID, std::string s1, std::string s2, std::string s3, std::string s4);
- virtual void tick(float dt);
-
-
- //unsigned functions
- void setU1(UTYPE value){ u1 = value; }
- void setU2(UTYPE value){ u2 = value; }
- void setU3(UTYPE value){ u3 = value; }
- void setU4(UTYPE value){ u4 = value; }
- void checkU1();
- void checkU2();
- void checkU3();
- void checkU4();
-
- //signed functions
- void setS1(TYPE value){ s1 = value; }
- void setS2(TYPE value){ s2 = value; }
- void setS3(TYPE value){ s3 = value; }
- void setS4(TYPE value){ s4 = value; }
- void checkS1();
- void checkS2();
- void checkS3();
- void checkS4();
-
- void printPointer();
-
- static void printV1(){ instance_->blub(); }
- static void printV2(){ instance_->blub2(); }
- static void printV3(){ instance_->checkU3(); }
- static void printV4(){ instance_->checkU4(); }
-
- void printBlaBla(std::string s1, std::string s2, std::string s3, std::string s4, std::string s5);
-
- private:
- void registerVariables();
-
- UTYPE u1;
- UTYPE u2;
- UTYPE u3;
- UTYPE u4;
-
- TYPE s1;
- TYPE s2;
- TYPE s3;
- TYPE s4;
-
- Test* pointer_;
-
- std::set<uint32_t> mySet_;
-
- static Test* instance_;
-
- void blub()
- { mySet_.insert(2); }
-
- void blub2()
- { for( std::set<uint32_t>::iterator it=mySet_.begin(); it!=mySet_.end(); ++it ) COUT(0) << *it << endl; }
- };
-}
-
-#endif /* _Test_H__ */
More information about the Orxonox-commit
mailing list