Index: /code/trunk/bin/CMakeLists.txt
===================================================================
--- /code/trunk/bin/CMakeLists.txt	(revision 5928)
+++ /code/trunk/bin/CMakeLists.txt	(revision 5929)
@@ -26,5 +26,5 @@
 
 # Create run scripts for Windows to manually add the DLL path when executing
-SET(RUN_SCRIPTS run standalone client1 client2 server dedicated)
+SET(RUN_SCRIPTS run standalone client1 client2 server dedicated dedicatedClient)
 IF(WIN32)
   FOREACH(_script ${RUN_SCRIPTS})
Index: /code/trunk/bin/dedicatedClient.bat.in
===================================================================
--- /code/trunk/bin/dedicatedClient.bat.in	(revision 5929)
+++ /code/trunk/bin/dedicatedClient.bat.in	(revision 5929)
@@ -0,0 +1,4 @@
+title @PROJECT_NAME@
+path @RUNTIME_LIBRARY_DIRECTORY_WINDOWS@;%path%
+@CURRENT_RUNTIME_DIR_WINDOWS@\@ORXONOX_EXECUTABLE_NAME@ --dedicatedClient --writingPathSuffix dedicatedClient
+pause
Index: /code/trunk/bin/dedicatedClient.in
===================================================================
--- /code/trunk/bin/dedicatedClient.in	(revision 5929)
+++ /code/trunk/bin/dedicatedClient.in	(revision 5929)
@@ -0,0 +1,4 @@
+#!/bin/sh
+# convenience script for starting orxonox on Linux
+
+exec @CURRENT_RUNTIME_DIR@/@ORXONOX_EXECUTABLE_NAME@ --dedicatedClient --writingPathSuffix dedicatedClient $@
Index: /code/trunk/bin/vld.ini.in
===================================================================
--- /code/trunk/bin/vld.ini.in	(revision 5928)
+++ /code/trunk/bin/vld.ini.in	(revision 5929)
@@ -56,5 +56,5 @@
 ;   Default: None.
 ;
-ForceIncludeModules =
+ForceIncludeModules = boost_date_time-vc80-mt-gd-1_39.dll, boost_filesystem-vc80-mt-gd-1_39.dll, boost_system-vc80-mt-gd-1_39.dll, boost_thread-vc80-mt-gd-1_39.dll, enet_d.dll, lua_d.dll, ogg_d.dll, vorbis_d.dll, vorbifile_d.dll
 
 ; Maximum number of data bytes to display for each leaked block. If zero, then
@@ -66,5 +66,5 @@
 ;   Default: 4294967295
 ;
-MaxDataDump = 
+MaxDataDump = 0
 
 ; Maximum number of call stack frames to trace back during leak detection.
Index: /code/trunk/cmake/CompilerConfigMSVC.cmake
===================================================================
--- /code/trunk/cmake/CompilerConfigMSVC.cmake	(revision 5928)
+++ /code/trunk/cmake/CompilerConfigMSVC.cmake	(revision 5929)
@@ -70,8 +70,8 @@
 
 # Overwrite CMake default flags here.
-SET_COMPILER_FLAGS("-MDd -Od -Zi -D_DEBUG -Gm -RTC1" Debug          CACHE)
-SET_COMPILER_FLAGS("-MD  -O2     -DNDEBUG -MP2"      Release        CACHE)
-SET_COMPILER_FLAGS("-MD  -O2 -Zi -DNDEBUG -MP2"      RelWithDebInfo CACHE)
-SET_COMPILER_FLAGS("-MD  -O1     -DNDEBUG -MP2"      MinSizeRel     CACHE)
+SET_COMPILER_FLAGS("-MDd -Od -Zi -D_DEBUG -MP2 -RTC1" Debug          CACHE)
+SET_COMPILER_FLAGS("-MD  -O2     -DNDEBUG -MP2"       Release        CACHE)
+SET_COMPILER_FLAGS("-MD  -O2 -Zi -DNDEBUG -MP2"       RelWithDebInfo CACHE)
+SET_COMPILER_FLAGS("-MD  -O1     -DNDEBUG -MP2"       MinSizeRel     CACHE)
 
 # Use Link time code generation for Release config if ORXONOX_RELEASE is defined
Index: /code/trunk/cmake/ParseMacroArguments.cmake
===================================================================
--- /code/trunk/cmake/ParseMacroArguments.cmake	(revision 5928)
+++ /code/trunk/cmake/ParseMacroArguments.cmake	(revision 5929)
@@ -39,4 +39,9 @@
   # Using LIST(FIND ...) speeds up the process
   SET(_keywords ${_switches} ${_list_names})
+
+  # Reset all arguments
+  FOREACH(_arg ${_switches} ${_list_names})
+    SET(_arg_${_arg})
+  ENDFOREACH(_arg)
 
   # Parse all the arguments and set the corresponding variable
Index: /code/trunk/cmake/PrecompiledHeaderFiles.cmake
===================================================================
--- /code/trunk/cmake/PrecompiledHeaderFiles.cmake	(revision 5928)
+++ /code/trunk/cmake/PrecompiledHeaderFiles.cmake	(revision 5929)
@@ -110,5 +110,5 @@
     GET_GCC_COMPILER_FLAGS(${_target_name} _pch_gcc_flags)
     # Make sure we recompile the pch file even if only the flags change
-    IF(NOT "${_pch_gcc_flags}" STREQUAL "${_INTERNAL_${_target_name}_PCH_GCC_FLAGS}")
+    IF(NOT "${_pch_gcc_flags}" STREQUAL "${_INTERNAL_${_target_name}_PCH_GCC_FLAGS}" OR NOT EXISTS "${_pch_dep_helper_file}")
       SET(_INTERNAL_${_target_name}_PCH_GCC_FLAGS "${_pch_gcc_flags}" CACHE INTERNAL "")
       FILE(WRITE ${_pch_dep_helper_file} "/* ${_pch_gcc_flags} */")
Index: /code/trunk/cmake/SourceFileUtilities.cmake
===================================================================
--- /code/trunk/cmake/SourceFileUtilities.cmake	(revision 5928)
+++ /code/trunk/cmake/SourceFileUtilities.cmake	(revision 5929)
@@ -24,16 +24,60 @@
  #    [ADD/SET]_SOURCE_FILES - Writes source files to the cache by force and
  #                             adds the current directory.
- #    GET_ALL_HEADER_FILES - Finds all header files recursively.
+ #                             Also compiles multiple source files into a single
+ #                             one by including them
+ #                             Use COMPILATION_[BEGIN|END] in
+ #                             [ADD|SET]_SOURCE_FILES and specify the name of
+ #                             the new source file after COMPILATION_BEGIN
+ #    GET_ALL_HEADER_FILES   - Finds all header files recursively.
  #    GENERATE_SOURCE_GROUPS - Set Visual Studio source groups.
  #
 
+FUNCTION(PREPARE_SOURCE_FILES)
+  SET(_fullpath_sources)
+  FOREACH(_file ${ARGN})
+    IF(_file STREQUAL "COMPILATION_BEGIN")
+      SET(_compile TRUE)
+      # Next file is the name of the compilation
+      SET(_get_name TRUE)
+    ELSEIF(_get_name)
+      SET(_get_name FALSE)
+      SET(_compilation_name ${_file})
+    ELSEIF(_file STREQUAL "COMPILATION_END")
+      IF(NOT _compilation_name)
+        MESSAGE(FATAL_ERROR "No name provided for source file compilation")
+      ENDIF()
+      IF(NOT DISABLE_COMPILATIONS)
+        SET(_include_string)
+        FOREACH(_file2 ${_compilation})
+          SET(_include_string "${_include_string}#include \"${_file2}\"\n")
+        ENDFOREACH(_file2)
+        IF(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${_compilation_name})
+          FILE(READ ${CMAKE_CURRENT_BINARY_DIR}/${_compilation_name} _include_string_file)
+        ENDIF()
+        IF(NOT _include_string STREQUAL "${_include_string_file}")
+          FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${_compilation_name} "${_include_string}")
+        ENDIF()
+        LIST(APPEND _fullpath_sources ${CMAKE_CURRENT_BINARY_DIR}/${_compilation_name})
+      ENDIF()
+      SET(_compilation_name)
+      SET(_compilation)
+      SET(_compile FALSE)
+    ELSE()
+      # Prefix the full path
+      GET_SOURCE_FILE_PROPERTY(_filepath ${_file} LOCATION)
+      LIST(APPEND _fullpath_sources ${_filepath})
+      IF(_compile AND NOT DISABLE_COMPILATIONS)
+        LIST(APPEND _compilation ${_filepath})
+	LIST(APPEND _fullpath_sources "H")
+      ENDIF()
+    ENDIF()
+  ENDFOREACH(_file)
+  SET(_fullpath_sources ${_fullpath_sources} PARENT_SCOPE)
+ENDFUNCTION(PREPARE_SOURCE_FILES)
+
+
 # Adds source files with the full path to a list
 FUNCTION(ADD_SOURCE_FILES _varname)
-  # Prefix the full path
-  SET(_fullpath_sources)
-  FOREACH(_file ${ARGN})
-    GET_SOURCE_FILE_PROPERTY(_filepath ${_file} LOCATION)
-    LIST(APPEND _fullpath_sources ${_filepath})
-  ENDFOREACH(_file)
+  PREPARE_SOURCE_FILES(${ARGN})
   # Write into the cache to avoid variable scoping in subdirs
   SET(${_varname} ${${_varname}} ${_fullpath_sources} CACHE INTERNAL "Do not edit")
@@ -43,10 +87,5 @@
 # Sets source files with the full path
 FUNCTION(SET_SOURCE_FILES _varname)
-  # Prefix the full path
-  SET(_fullpath_sources)
-  FOREACH(_file ${ARGN})
-    GET_SOURCE_FILE_PROPERTY(_filepath ${_file} LOCATION)
-    LIST(APPEND _fullpath_sources ${_filepath})
-  ENDFOREACH(_file)
+  PREPARE_SOURCE_FILES(${ARGN})
   # Write into the cache to avoid variable scoping in subdirs
   SET(${_varname} ${_fullpath_sources} CACHE INTERNAL "Do not edit")
@@ -66,7 +105,12 @@
     GET_SOURCE_FILE_PROPERTY(_full_filepath ${_file} LOCATION)
     FILE(RELATIVE_PATH _relative_path ${CMAKE_CURRENT_SOURCE_DIR} ${_full_filepath})
-    GET_FILENAME_COMPONENT(_relative_path ${_relative_path} PATH)
-    STRING(REPLACE "/" "\\\\" _group_path "${_relative_path}")
-    SOURCE_GROUP("Source\\${_group_path}" FILES ${_file})
+    IF(NOT _relative_path MATCHES "^\\.\\.")
+      GET_FILENAME_COMPONENT(_relative_path ${_relative_path} PATH)
+      STRING(REPLACE "/" "\\\\" _group_path "${_relative_path}")
+      SOURCE_GROUP("Source\\${_group_path}" FILES ${_file})
+    ELSE()
+      # Has to be a compilation
+      SOURCE_GROUP("Compilations" FILES ${_file})
+    ENDIF()
   ENDFOREACH(_file)
 
Index: /code/trunk/cmake/TargetUtilities.cmake
===================================================================
--- /code/trunk/cmake/TargetUtilities.cmake	(revision 5928)
+++ /code/trunk/cmake/TargetUtilities.cmake	(revision 5929)
@@ -67,14 +67,14 @@
 ENDIF()
 
-FUNCTION(ORXONOX_ADD_LIBRARY _target_name)
+MACRO(ORXONOX_ADD_LIBRARY _target_name)
   TU_ADD_TARGET(${_target_name} LIBRARY "STATIC;SHARED" ${ARGN})
-ENDFUNCTION(ORXONOX_ADD_LIBRARY)
-
-FUNCTION(ORXONOX_ADD_EXECUTABLE _target_name)
+ENDMACRO(ORXONOX_ADD_LIBRARY)
+
+MACRO(ORXONOX_ADD_EXECUTABLE _target_name)
   TU_ADD_TARGET(${_target_name} EXECUTABLE "WIN32" ${ARGN})
-ENDFUNCTION(ORXONOX_ADD_EXECUTABLE)
-
-
-FUNCTION(TU_ADD_TARGET _target_name _target_type _additional_switches)
+ENDMACRO(ORXONOX_ADD_EXECUTABLE)
+
+
+MACRO(TU_ADD_TARGET _target_name _target_type _additional_switches)
   CAPITALISE_NAME(${_target_name} _target_name_capitalised)
 
@@ -88,11 +88,22 @@
 
 
-  # GET_HEADER_FILES
+  # Workaround: Source file properties get lost when leaving a subdirectory
+  # Therefore an "H" after a file means we have to set it as HEADER_FILE_ONLY
+  FOREACH(_file ${_arg_SOURCE_FILES})
+    IF(_file STREQUAL "H")
+      SET_SOURCE_FILES_PROPERTIES(${_last_file} PROPERTIES HEADER_FILE_ONLY TRUE)
+    ELSE()
+      SET(_last_file ${_file})
+      LIST(APPEND _${_target_name}_source_files ${_file})
+    ENDIF()
+  ENDFOREACH(_file)
+
+  # Assemble all header files of the library
   IF(_arg_FIND_HEADER_FILES)
-    GET_ALL_HEADER_FILES(_${target_name}_header_files)
+    GET_ALL_HEADER_FILES(_${_target_name}_header_files)
   ENDIF()
 
   # Remove potential duplicates
-  SET(_${_target_name}_files ${_${target_name}_header_files} ${_arg_SOURCE_FILES})
+  SET(_${_target_name}_files ${_${_target_name}_header_files} ${_${_target_name}_source_files})
   LIST(REMOVE_DUPLICATES _${_target_name}_files)
 
@@ -141,4 +152,10 @@
   ENDIF()
 
+  # No warnings needed from third party libraries
+  IF(_arg_ORXONOX_EXTERNAL)
+    REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
+    ADD_COMPILER_FLAGS("-w")
+  ENDIF()
+
   # Set default linking if required
   IF(NOT _arg_SHARED AND NOT _arg_STATIC)
@@ -171,4 +188,11 @@
     ADD_EXECUTABLE(${_target_name} ${_arg_WIN32} ${_arg_EXCLUDE_FROM_ALL}
                    ${_${_target_name}_files})
+  ENDIF()
+
+  # Change library prefix to "lib"
+  IF(MSVC AND ${_target_type} STREQUAL "LIBRARY")
+    SET_TARGET_PROPERTIES(${_target_name} PROPERTIES
+      PREFIX "lib"
+    )
   ENDIF()
 
@@ -223,5 +247,5 @@
   ENDIF()
 
-ENDFUNCTION(TU_ADD_TARGET)
+ENDMACRO(TU_ADD_TARGET)
 
 
Index: /code/trunk/data/defaultConfig/keybindings.ini
===================================================================
--- /code/trunk/data/defaultConfig/keybindings.ini	(revision 5928)
+++ /code/trunk/data/defaultConfig/keybindings.ini	(revision 5929)
@@ -25,5 +25,5 @@
 KeyEscape="exit"
 KeyF="scale -1 moveUpDown"
-KeyF1=
+KeyF1="OverlayGroup toggleVisibility Debug"
 KeyF10=
 KeyF11=
@@ -41,7 +41,7 @@
 KeyF9=
 KeyG=greet
-KeyGrave=
+KeyGrave="openConsole"
 KeyH=
-KeyHome=showGUI
+KeyHome=
 KeyI=
 KeyInsert=
@@ -126,5 +126,5 @@
 KeyU=
 KeyUP="scale 1 moveFrontBack"
-KeyUnassigned=
+KeyUnassigned="openConsole"
 KeyUnderline=
 KeyUnlabeled=
Index: de/trunk/data/defaultConfig/masterKeybindings.ini
===================================================================
--- /code/trunk/data/defaultConfig/masterKeybindings.ini	(revision 5928)
+++ 	(revision )
@@ -1,167 +1,0 @@
-[Keys]
-KeyA=
-KeyABNT_C1=
-KeyABNT_C2=
-KeyAT=
-KeyAX=
-KeyApostrophe=
-KeyApps=
-KeyB=
-KeyBack=
-KeyBackslash=
-KeyC=
-KeyCalculator=
-KeyCapsLock=
-KeyColon=
-KeyComma=
-KeyConvert=
-KeyD=
-KeyDelete=
-KeyDivide=
-KeyDown=
-KeyE=
-KeyEnd=
-KeyEquals=
-KeyEscape=
-KeyF=
-KeyF1="OverlayGroup toggleVisibility Debug"
-KeyF10=
-KeyF11=
-KeyF12=
-KeyF13=
-KeyF14=
-KeyF15=
-KeyF2=
-KeyF3=
-KeyF4=
-KeyF5=
-KeyF6=
-KeyF7=
-KeyF8=
-KeyF9=
-KeyG=
-KeyGrave="openConsole"
-KeyH=
-KeyHome=
-KeyI=
-KeyInsert=
-KeyJ=
-KeyK=
-KeyKana=
-KeyKanji=
-KeyL=
-KeyLeft=
-KeyLeftAlt=
-KeyLeftBracket=
-KeyLeftControl=
-KeyLeftShift=
-KeyLeftWindows=
-KeyLessThan=
-KeyM=
-KeyMail=
-KeyMediaSelect=
-KeyMediaStop=
-KeyMinus=
-KeyMultiply=
-KeyMute=
-KeyMyComputer=
-KeyN=
-KeyNextTrack=
-KeyNoConvert=
-KeyNumLock=
-KeyNumRow0=
-KeyNumRow1=
-KeyNumRow2=
-KeyNumRow3=
-KeyNumRow4=
-KeyNumRow5=
-KeyNumRow6=
-KeyNumRow7=
-KeyNumRow8=
-KeyNumRow9=
-KeyNumpad0=
-KeyNumpad1=
-KeyNumpad2=
-KeyNumpad3=
-KeyNumpad4=
-KeyNumpad5=
-KeyNumpad6=
-KeyNumpad7=
-KeyNumpad8=
-KeyNumpad9=
-KeyNumpadAdd=
-KeyNumpadComma=
-KeyNumpadEnter=
-KeyNumpadEquals=
-KeyNumpadPeriod=
-KeyNumpadSubtract=
-KeyO=
-KeyP=
-KeyPageDown=
-KeyPageUp=
-KeyPause=
-KeyPeriod=
-KeyPlayPause=
-KeyPower=
-KeyPreviousTrack=
-KeyQ=
-KeyR=
-KeyReturn=
-KeyRight=
-KeyRightAlt=
-KeyRightBracket=
-KeyRightControl=
-KeyRightShift=
-KeyRightWindows=
-KeyS=
-KeyScrollLock=
-KeySemicolon=
-KeySlash=
-KeySleep=
-KeySpace=
-KeyStop=
-KeySystemRequest=
-KeyT=
-KeyTab=
-KeyU=
-KeyUP=
-KeyUnassigned="openConsole"
-KeyUnderline=
-KeyUnlabeled=
-KeyV=
-KeyVolumeDown=
-KeyVolumeUp=
-KeyW=
-KeyWake=
-KeyWebBack=
-KeyWebFavorites=
-KeyWebForward=
-KeyWebHome=
-KeyWebRefresh=
-KeyWebSearch=
-KeyWebStop=
-KeyX=
-KeyY=
-KeyYen=
-KeyZ=
-
-[MouseButtons]
-MouseButton3=
-MouseButton4=
-MouseButton5=
-MouseButton6=
-MouseButton7=
-MouseLeft=
-MouseMiddle=
-MouseRight=
-MouseWheel1Down=
-MouseWheel1Up=
-MouseWheel2Down=
-MouseWheel2Up=
-
-[MouseAxes]
-MouseXNeg=
-MouseXPos=
-MouseYNeg=
-MouseYPos=
-
Index: /code/trunk/data/levels/events.oxw
===================================================================
--- /code/trunk/data/levels/events.oxw	(revision 5929)
+++ /code/trunk/data/levels/events.oxw	(revision 5929)
@@ -0,0 +1,223 @@
+<?lua
+  include("hudtemplates3.oxo")
+  include("stats.oxo")
+  include("templates/spaceship_assff.oxt")
+  include("templates/spaceship_H2.oxt")
+?>
+
+<Level
+ name         = "Event testing"
+ description  = "A simple level to test the event-system (with comments)"
+>
+  <Scene
+   ambientlight = "0.5, 0.5, 0.5"
+   skybox       = "Orxonox/skypanoramagen1"
+  >
+    <Light type=directional position="0,0,0" direction="0.253, 0.593, -0.765" diffuse="1.0, 0.9, 0.9, 1.0" specular="1.0, 0.9, 0.9, 1.0" />
+
+    <SpawnPoint position="0,-100,0" lookat="0,0,0" roll=180 spawnclass=SpaceShip pawndesign=spaceshipassff />
+
+    <Billboard position=" 300,100,  0" material="Examples/Flare" colour="1.0, 0.0, 0.0" />
+    <Billboard position=" 200,100,  0" material="Examples/Flare" colour="1.0, 0.5, 0.0" />
+    <Billboard position=" 200,100,100" material="Examples/Flare" colour="1.0, 0.5, 0.0" />
+    <Billboard position=" 100,100,  0" material="Examples/Flare" colour="1.0, 1.0, 0.0" />
+    <Billboard position="   0,100,  0" material="Examples/Flare" colour="0.0, 1.0, 0.0" />
+    <Billboard position="-100,100,  0" material="Examples/Flare" colour="0.0, 1.0, 1.0" />
+    <Billboard position="-100,100,100" material="Examples/Flare" colour="0.0, 1.0, 1.0" />
+    <Billboard position="-200,100,  0" material="Examples/Flare" colour="0.0, 0.0, 1.0" />
+    <Billboard position="-300,100,  0" material="Examples/Flare" colour="1.0, 0.0, 1.0" />
+
+
+
+    <!--
+      Begin of the tutorial section.
+    -->
+
+
+
+    <!--
+      Note:
+      All following examples use only one subobject (in nested layouts). But of course you can add more
+      objects. They will all follow the same rules (depending on the example receive, send or pipe events).
+
+      Some examples address objects by name. Those methods always address ALL objects with this name, no
+      matter where they are in the XML-file (before or after the addressing object). Of course this also
+      works with all amounts of objects from zero to infinity. In the examples I used two objects each.
+    -->
+      
+
+    <!-- red -->
+    <!--
+      Standard:
+      Direct event-connection between an event-listener (Billboard) and an event source (DistanceTrigger).
+      Every fired event of the source is mapped to the "visibility" state of the listener.
+
+      This is a 1:1 mapping between event-listener and event-source.
+    -->
+    <Billboard position="300,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0>
+      <events>
+        <visibility>
+          <DistanceTrigger position="300,100,0" distance=25 target="ControllableEntity" />
+        </visibility>
+      </events>
+    </Billboard>
+
+
+    <!-- orange -->
+    <!--
+      EventListener:
+      The EventListener object forwards all events from objects, whose names equal the "event" attribute
+      of the EventListener, to the enclosing object (Billboard).
+      In this case, both triggers have the name "trigger2" and thus both triggers send events to the Billboard.
+
+      The EventListener provides an 1:n mapping between one listener and multiple event-sources.
+    -->
+    <Billboard position="200,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0>
+      <events>
+        <visibility>
+          <EventListener event="trigger2" />
+        </visibility>
+      </events>
+    </Billboard>
+    <DistanceTrigger name="trigger2" position="200,100,0" distance=25 target="ControllableEntity" />
+    <DistanceTrigger name="trigger2" position="200,100,100" distance=25 target="ControllableEntity" />
+
+
+    <!-- yellow -->
+    <!--
+      EventTarget:
+      The EventTarget object forwards the events, received from objects whithin the "events" subsection,
+      to all  objects whose names equal the "name" attribute.
+      In this case, the EventTarget forwards the event from the DistanceTrigger to all listeners with
+      name "bb3".
+
+      The EventTarget provides an n:1 mapping between several listeners and one event-source.
+    -->
+    <Billboard name="bb3" position="100,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 />
+    <Billboard name="bb3" position="100,150,100" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 />
+    <EventTarget target="bb3">
+      <events>
+        <visibility>
+          <DistanceTrigger position="100,100,0" distance=25 target="ControllableEntity" />
+        </visibility>
+      </events>
+    </EventTarget>
+
+
+    <!-- green -->
+    <!--
+      EventDispatcher:
+      The EventDispatcher catches events from objects in its "events" subsection. Those events are forwared
+      to all objects in the "targets" subsection. The EventDispatcher resembles the EventTarget, but
+      doesn't address objects with the "name" attribute. It rather places them directly inside the "targets"
+      subsection.
+      In this case, the EventDispatcher receives events from the DistanceTrigger and forwards those events
+      to the Billboard object.
+
+      The EventDispatcher provides an n:1 mapping between several targets (listeners) and one event source.
+    -->
+    <EventDispatcher>
+      <targets>
+        <Billboard position="0,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 />
+      </targets>
+      <events>
+        <visibility>
+          <DistanceTrigger position="0,100,0" distance=25 target="ControllableEntity" />
+        </visibility>
+      </events>
+    </EventDispatcher>
+
+
+    <!-- turquoise -->
+    <!--
+      Combination:
+      By combinding the above three classes, namely EventDispatcher, EventTarget and EventListener, you can
+      extract the event logic completely from the actual objects (Billboards and DistanceTriggers).
+      In this case, both triggers (whith names "trigger5") send events to both Billboards (with names "bb5").
+
+      This combination allows an n:n mapping between event-listeners and event-sources.
+    -->
+    <Billboard name="bb5" position="-100,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 />
+    <Billboard name="bb5" position="-100,150,100" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 />
+    <DistanceTrigger name="trigger5" position="-100,100,0" distance=25 target="ControllableEntity" />
+    <DistanceTrigger name="trigger5" position="-100,100,100" distance=25 target="ControllableEntity" />
+    <EventDispatcher>
+      <targets>
+        <EventTarget target="bb5" />
+      </targets>
+      <events>
+        <visibility>
+          <EventListener event="trigger5" />
+        </visibility>
+      </events>
+    </EventDispatcher>
+
+
+    <!-- blue -->
+    <!--
+      Mainstate:
+      Apart from the standard states (like activity and visibility), each object can have a mainstate.
+      You can define the mainstate with an xml-attribute: mainstate="state". "state" must be one of the
+      supported states of the object (except states which need the originator as a second argument). If
+      the mainstate is set (by default that's not the case), you can send events to the "mainstate" state.
+      This allows you to hide the actually affected state in the event-listener, while the event-source
+      just sends events.
+      Note that this example is exactly like the standard case, but the event is sent to the main-state,
+      which in turn is set to "visibility".
+    -->
+    <Billboard position="-200,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 mainstate="visibility">
+      <events>
+        <mainstate>
+          <DistanceTrigger position="-200,100,0" distance=25 target="ControllableEntity" />
+        </mainstate>
+      </events>
+    </Billboard>
+
+
+    <!-- violet -->
+    <!--
+      Event forwarding:
+      As a consequence of the mainstate, events can also be sent without any explicit declaration of
+      the targets state. This allows us to forward events from an event-source directly to a bunch of
+      event-listeners. The events are automatically piped into the mainstate. Therefore the listeners
+      have to declare their main-state.
+      In this example, the DistanceTrigger forwards the events to the Billboards main-state (visibility).
+      This does the same like the example above, but instead of piping events backwards from the source
+      into the mainstate of the listener, we're forwarding the event implicitly to the mainstate.
+    -->
+    <DistanceTrigger position="-300,100,0" distance=25 target="ControllableEntity">
+      <eventlisteners>
+        <Billboard position="-300,150,0" material="Examples/Flare" colour="1.0, 1.0, 1.0" visible=0 mainstate="visibility" />
+      </eventlisteners>
+    </DistanceTrigger>
+
+
+
+    <!--
+      End of the tutorial section.
+    -->
+
+
+
+    <!--
+      The following example shows again the red (standard layout) and the violet (event forwarding) example,
+      but this time with a memoryless state (spawn) from the ParticleSpawner instead of the boolean state
+      (visibility) in the other examples.
+    -->
+    <Billboard position=" 300,100,300" material="Examples/Flare" colour="1.0, 0.0, 0.0" />
+    <Billboard position="-300,100,300" material="Examples/Flare" colour="1.0, 0.0, 1.0" />
+    <ParticleSpawner position="300,150,300" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0>
+      <events>
+        <spawn>
+          <DistanceTrigger position="300,100,300" distance=25 target="ControllableEntity" />
+        </spawn>
+      </events>
+    </ParticleSpawner>
+    <DistanceTrigger position="-300,100,300" distance=25 target="ControllableEntity">
+      <eventlisteners>
+        <ParticleSpawner position="-300,150,300" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 mainstate="spawn" />
+      </eventlisteners>
+    </DistanceTrigger>
+
+  </Scene>
+</Level>
Index: /code/trunk/data/levels/old/physicstest2.oxw
===================================================================
--- /code/trunk/data/levels/old/physicstest2.oxw	(revision 5928)
+++ /code/trunk/data/levels/old/physicstest2.oxw	(revision 5929)
@@ -243,7 +243,7 @@
     <!--EventDispatcher>
       <targets>
-        <EventTarget name=fireright />
-        <EventTarget name=firecenter />
-        <EventTarget name=fireleft />
+        <EventTarget target=fireright />
+        <EventTarget target=firecenter />
+        <EventTarget target=fireleft />
       </targets>
       <events>
Index: /code/trunk/data/levels/old/princessaeryn.oxw
===================================================================
--- /code/trunk/data/levels/old/princessaeryn.oxw	(revision 5928)
+++ /code/trunk/data/levels/old/princessaeryn.oxw	(revision 5929)
@@ -264,5 +264,5 @@
             <EventDispatcher>
                 <targets>
-                    <EventTarget name=trail />
+                    <EventTarget target=trail />
                 </targets>
                 <events>
Index: /code/trunk/data/levels/old/sample4.oxw
===================================================================
--- /code/trunk/data/levels/old/sample4.oxw	(revision 5928)
+++ /code/trunk/data/levels/old/sample4.oxw	(revision 5929)
@@ -123,7 +123,7 @@
     <EventDispatcher>
       <targets>
-        <EventTarget name=fireright />
-        <EventTarget name=firecenter />
-        <EventTarget name=fireleft />
+        <EventTarget target=fireright />
+        <EventTarget target=firecenter />
+        <EventTarget target=fireleft />
       </targets>
       <events>
Index: /code/trunk/data/levels/presentation.oxw
===================================================================
--- /code/trunk/data/levels/presentation.oxw	(revision 5928)
+++ /code/trunk/data/levels/presentation.oxw	(revision 5929)
@@ -151,7 +151,7 @@
     <EventDispatcher>
       <targets>
-        <EventTarget name=fireright />
-        <EventTarget name=firecenter />
-        <EventTarget name=fireleft />
+        <EventTarget target=fireright />
+        <EventTarget target=firecenter />
+        <EventTarget target=fireleft />
       </targets>
       <events>
Index: /code/trunk/data/levels/presentation09b.oxw
===================================================================
--- /code/trunk/data/levels/presentation09b.oxw	(revision 5928)
+++ /code/trunk/data/levels/presentation09b.oxw	(revision 5929)
@@ -111,5 +111,5 @@
     <EventDispatcher>
       <targets>
-        <EventTarget name=pirates />
+        <EventTarget target=pirates />
       </targets>
       <events>
@@ -163,5 +163,5 @@
     <EventDispatcher>
       <targets>
-        <EventTarget name=attacker />
+        <EventTarget target=attacker />
       </targets>
       <events>
Index: /code/trunk/data/levels/presentation_pong.oxw
===================================================================
--- /code/trunk/data/levels/presentation_pong.oxw	(revision 5928)
+++ /code/trunk/data/levels/presentation_pong.oxw	(revision 5929)
@@ -32,5 +32,9 @@
       <Backlight scale=0.2 colour="1.0, 1.0, 0.5" width=7 length=500 lifetime=0.3 elements=20 trailmaterial="Trail/backlighttrail" material="Examples/Flare" />
       <Light type=point diffuse="1.0, 1.0, 0.5" specular="1.0, 1.0, 0.5" attenuation="1200, 1.0, 0.0035, 0.00005" />
-    </attached>
+      <ParticleSpawner name=hiteffect position="0,0,0" source="Orxonox/sparks2" lifetime=0.01 autostart=0 mainstate=spawn />
+    </attached>
+    <eventlisteners>
+      <EventTarget target=hiteffect />
+    </eventlisteners>
   </PongBall>
 </Template>
@@ -42,4 +46,6 @@
  gametype     = Pong
 >
+  <AmbientSound source="ambient/mainmenu.wav" playOnLoad=true />
+
   <Scene
    ambientlight = "0.5, 0.5, 0.5"
@@ -58,20 +64,41 @@
   <MovableEntity rotationrate=5 rotationaxis="0,0,1">
     <attached>
-      <PongCenterpoint name=pongcenter dimension="200,120" balltemplate=pongball battemplate=pongbat ballspeed=200 batspeed=130 batlength=0.25>
+      <PongCenterpoint name=pongcenter dimension="200,120" balltemplate=pongball battemplate=pongbat ballspeed=200 ballaccfactor=1.0 batspeed=130 batlength=0.25>
         <attached>
           <Model position="0,0,60" mesh="cube.mesh" scale3D="105,1,1" />
           <Model position="0,0,-60" mesh="cube.mesh" scale3D="105,1,1" />
-<!--
-          <ParticleSpawner name=scoreeffect_R position=" 100,0, 60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position="  50,0, 60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position="   0,0, 60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position=" -50,0, 60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect_L position="-100,0, 60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect_R position=" 100,0,-60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position="  50,0,-60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position="   0,0,-60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect position=" -50,0,-60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
-          <ParticleSpawner name=scoreeffect_L position="-100,0,-60" source="Orxonox/BigExplosion1part1" lifetime=3.0 autostart=0 />
--->
+
+          <ParticleSpawner name=scoreeffect_right position="120,0, 45" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0, 30" source="Orxonox/BigExplosion1part2" lifetime=3.0 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0, 15" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0,  0" source="Orxonox/BigExplosion1part2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0,-15" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0,-30" source="Orxonox/BigExplosion1part2" lifetime=3.0 autostart=0 />
+          <ParticleSpawner name=scoreeffect_right position="120,0,-45" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+
+          <ParticleSpawner name=scoreeffect_left position="-120,0, 45" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0, 30" source="Orxonox/BigExplosion1part2" lifetime=3.0 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0, 15" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0,  0" source="Orxonox/BigExplosion1part2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0,-15" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0,-30" source="Orxonox/BigExplosion1part2" lifetime=3.0 autostart=0 />
+          <ParticleSpawner name=scoreeffect_left position="-120,0,-45" source="Orxonox/sparks2" lifetime=0.1 autostart=0 />
+
+          <WorldSound name="scoreSound" position="0,0,0" source="sounds/pong_score.wav" >
+            <events>
+              <play>
+                <EventListener event=pongcenter />
+              </play>
+            </events>
+          </WorldSound>
+
+<?lua
+for i = 1, 15, 1
+do ?>
+          <ParticleSpawner name=scoreeffect_center position="<?lua print(math.random() * 200 - 100) ?>,0,<?lua print(math.random() * 120 - 60) ?>" source="Orxonox/sparks2" lifetime=0.02 autostart=0 startdelay=<?lua print(math.random() * 0.7) ?> />
+<?lua
+end
+?>
+
         </attached>
       </PongCenterpoint>
@@ -81,9 +108,31 @@
   <EventDispatcher>
     <targets>
-      <EventTarget name=scoreeffect />
+      <EventTarget target=scoreeffect_right />
+      <EventTarget target=scoreeffect_center />
     </targets>
     <events>
       <spawn>
-        <EventListener event=pongcenter />
+        <EventFilter>
+          <names>
+            <EventName name=right />
+          </names>
+          <EventListener event=pongcenter />
+        </EventFilter>
+      </spawn>
+    </events>
+  </EventDispatcher>
+  <EventDispatcher>
+    <targets>
+      <EventTarget target=scoreeffect_left />
+      <EventTarget target=scoreeffect_center />
+    </targets>
+    <events>
+      <spawn>
+        <EventFilter>
+          <names>
+            <EventName name=left />
+          </names>
+          <EventListener event=pongcenter />
+        </EventFilter>
       </spawn>
     </events>
Index: /code/trunk/data/levels/princessaeryn.oxw
===================================================================
--- /code/trunk/data/levels/princessaeryn.oxw	(revision 5928)
+++ /code/trunk/data/levels/princessaeryn.oxw	(revision 5929)
@@ -6,5 +6,5 @@
 
 <?lua
-	dofile("../../media/levels/includes/CuboidSpaceStation.lua")
+	dofile("includes/CuboidSpaceStation.lua")
 ?>
 
@@ -227,5 +227,5 @@
             <EventDispatcher>
                 <targets>
-                    <EventTarget name=trail />
+                    <EventTarget target=trail />
                 </targets>
                 <events>
Index: /code/trunk/data/particle/ExplosionComp1.particle
===================================================================
--- /code/trunk/data/particle/ExplosionComp1.particle	(revision 5928)
+++ /code/trunk/data/particle/ExplosionComp1.particle	(revision 5929)
@@ -41,5 +41,5 @@
 		repeat_delay_max	2.5
 		width		20
-		hight		20
+		height		20
 		depth		0
 	}
Index: /code/trunk/data/particle/sparks2.particle
===================================================================
--- /code/trunk/data/particle/sparks2.particle	(revision 5929)
+++ /code/trunk/data/particle/sparks2.particle	(revision 5929)
@@ -0,0 +1,51 @@
+
+particle_system Orxonox/sparks2
+{
+	quota	1000
+	material	PE/Flare
+	particle_width	15
+	particle_height	40
+	cull_each	true
+	renderer	billboard
+	sorted	false
+	local_space	false
+	iteration_interval	0
+	nonvisible_update_timeout	0
+	billboard_type	oriented_self
+	billboard_origin	center
+	billboard_rotation_type	texcoord
+	common_up_vector	0 1 0
+	point_rendering	false
+	accurate_facing	false
+
+	emitter Point
+	{
+		angle	180
+		colour	0.1 0.1 0.1 1
+		colour_range_start	0.1 0.1 0.1 1
+		colour_range_end	1 1 1 1
+		direction	0 0 -1
+		emission_rate	5000
+		position	0 0 0
+		velocity	10
+		velocity_min	15
+		velocity_max	150
+		time_to_live	0.5
+		time_to_live_min	0.5
+		time_to_live_max	0.5
+		duration	0
+		duration_min	0
+		duration_max	0
+		repeat_delay	0
+		repeat_delay_min	0
+		repeat_delay_max	0
+	}
+
+	affector ColourFader
+	{
+		red	-2.0
+		green	-2.0
+		blue	-2.0
+		alpha	0
+	}
+}
Index: /code/trunk/src/Orxonox.cc
===================================================================
--- /code/trunk/src/Orxonox.cc	(revision 5928)
+++ /code/trunk/src/Orxonox.cc	(revision 5929)
@@ -63,7 +63,7 @@
         for (int i = 1; i < argc; ++i)
             strCmdLine += argv[i] + std::string(" ");
+#endif
 
         return orxonox::main(strCmdLine);
-#endif
     }
     catch (...)
Index: /code/trunk/src/OrxonoxConfig.cmake
===================================================================
--- /code/trunk/src/OrxonoxConfig.cmake	(revision 5928)
+++ /code/trunk/src/OrxonoxConfig.cmake	(revision 5929)
@@ -38,4 +38,7 @@
   OPTION(PCH_ENABLE "Global PCH switch" TRUE)
 ENDIF()
+
+# Global switch to disable multiple file compilations
+OPTION(DISABLE_COMPILATIONS "Global multi-file compilation switch" FALSE)
 
 # Use WinMain() or main()?
Index: /code/trunk/src/external/bullet/BulletCollision/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/bullet/BulletCollision/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/bullet/BulletCollision/CMakeLists.txt	(revision 5929)
@@ -1,3 +1,6 @@
 ADD_SOURCE_FILES(BULLET_FILES
+
+COMPILATION_BEGIN BulletCollisionCompilation.cpp
+
 	BroadphaseCollision/btAxisSweep3.cpp
 	BroadphaseCollision/btBroadphaseProxy.cpp
@@ -68,13 +71,9 @@
 	Gimpact/btContactProcessing.cpp
 	Gimpact/btGImpactShape.cpp
-	Gimpact/gim_contact.cpp
 	Gimpact/btGImpactBvh.cpp
 	Gimpact/btGenericPoolAllocator.cpp
-	Gimpact/gim_memory.cpp
 	Gimpact/btGImpactCollisionAlgorithm.cpp
 	Gimpact/btTriangleShapeEx.cpp
-	Gimpact/gim_tri_collision.cpp
 	Gimpact/btGImpactQuantizedBvh.cpp
-	Gimpact/gim_box_set.cpp
 
 	NarrowPhaseCollision/btContinuousConvexCollision.cpp
@@ -89,4 +88,13 @@
 	NarrowPhaseCollision/btSubSimplexConvexCast.cpp
 	NarrowPhaseCollision/btVoronoiSimplexSolver.cpp
+
+COMPILATION_END
+
+COMPILATION_BEGIN BulletGImpactCompilation.cpp
+	Gimpact/gim_contact.cpp
+	Gimpact/gim_memory.cpp
+	Gimpact/gim_tri_collision.cpp
+	Gimpact/gim_box_set.cpp
+COMPILATION_END
 
 	# Headers
Index: /code/trunk/src/external/bullet/BulletDynamics/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/bullet/BulletDynamics/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/bullet/BulletDynamics/CMakeLists.txt	(revision 5929)
@@ -1,3 +1,6 @@
 ADD_SOURCE_FILES(BULLET_FILES
+
+COMPILATION_BEGIN BulletDynamicsCompilation.cpp
+
 	ConstraintSolver/btContactConstraint.cpp
 	ConstraintSolver/btConeTwistConstraint.cpp
@@ -19,4 +22,6 @@
 
 	Character/btKinematicCharacterController.cpp
+
+COMPILATION_END
 
 	# Headers
Index: de/trunk/src/external/bullet/BulletPrecompiledHeaders.h
===================================================================
--- /code/trunk/src/external/bullet/BulletPrecompiledHeaders.h	(revision 5928)
+++ 	(revision )
@@ -1,48 +1,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
-    Compilation of the most often used header files in the external bullet library
-@details
-    Updated: 19. September 2009
-    Total Files: 105
-*/
-
-///////////////////////////////////////////
-/////          Stable Headers         /////
-///////////////////////////////////////////
-
-#include <bullet/BulletCollision/CollisionShapes/btConvexInternalShape.h> // 37
-#include <bullet/BulletCollision/CollisionDispatch/btCollisionObject.h> // 33
-
-
-// Just in case some header included windows.h
-#undef min
-#undef max
Index: /code/trunk/src/external/bullet/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/bullet/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/bullet/CMakeLists.txt	(revision 5929)
@@ -27,13 +27,7 @@
 ADD_SUBDIRECTORY(LinearMath)
 
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
-
 ORXONOX_ADD_LIBRARY(bullet_orxonox
   ORXONOX_EXTERNAL
   NO_DLL_INTERFACE
-  PCH_FILE
-    BulletPrecompiledHeaders.h
   VERSION
     2.74
Index: /code/trunk/src/external/bullet/LinearMath/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/bullet/LinearMath/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/bullet/LinearMath/CMakeLists.txt	(revision 5929)
@@ -1,7 +1,10 @@
 ADD_SOURCE_FILES(BULLET_FILES
+
+COMPILATION_BEGIN BulletLinearMathCompilation.cpp
 		btConvexHull.cpp
 		btQuickprof.cpp
 		btGeometryUtil.cpp
 		btAlignedAllocator.cpp
+COMPILATION_END
 
 		# Headers
Index: /code/trunk/src/external/ceguilua/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ceguilua/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ceguilua/CMakeLists.txt	(revision 5929)
@@ -67,8 +67,4 @@
 )
 
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
-
 SOURCE_GROUP("Source" FILES ${CEGUILUA_FILES})
 
Index: /code/trunk/src/external/cpptcl/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/cpptcl/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/cpptcl/CMakeLists.txt	(revision 5929)
@@ -32,8 +32,4 @@
 )
 
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
-
 ORXONOX_ADD_LIBRARY(cpptcl_orxonox
   ORXONOX_EXTERNAL
Index: /code/trunk/src/external/ogreceguirenderer/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ogreceguirenderer/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ogreceguirenderer/CMakeLists.txt	(revision 5929)
@@ -18,17 +18,15 @@
  #
 
-SET(OCR_FILES
+SET_SOURCE_FILES(OCR_FILES
   OgreCEGUIRenderer.h
   OgreCEGUIResourceProvider.h
   OgreCEGUITexture.h
 
+COMPILATION_BEGIN OgreCEGUIRendererCompilation.cpp
   OgreCEGUIRenderer.cpp
   OgreCEGUIResourceProvider.cpp
   OgreCEGUITexture.cpp
+COMPILATION_END
 )
-
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
 
 ORXONOX_ADD_LIBRARY(ogreceguirenderer_orxonox
Index: /code/trunk/src/external/ois/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ois/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ois/CMakeLists.txt	(revision 5929)
@@ -34,4 +34,5 @@
   OISPrereqs.h
 
+COMPILATION_BEGIN OISCompilation.cpp
   OISEffect.cpp
   OISException.cpp
@@ -41,4 +42,5 @@
   OISKeyboard.cpp
   OISObject.cpp
+COMPILATION_END
 )
 IF(WIN32)
@@ -49,8 +51,4 @@
   ADD_SUBDIRECTORY(linux)
 ENDIF()
-
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
 
 INCLUDE_DIRECTORIES(.)
Index: /code/trunk/src/external/ois/changes_orxonox.diff
===================================================================
--- /code/trunk/src/external/ois/changes_orxonox.diff	(revision 5928)
+++ /code/trunk/src/external/ois/changes_orxonox.diff	(revision 5929)
@@ -23,2 +23,13 @@
  
 
+--- win32/Win32ForceFeedback.cpp
++++ win32/Win32ForceFeedback.cpp
+@@ -25,7 +25,7 @@
+ #include <Math.h>
+ 
+ // 0 = No trace; 1 = Important traces; 2 = Debug traces
+-#define OIS_WIN32_JOYFF_DEBUG 1
++#define OIS_WIN32_JOYFF_DEBUG 0
+ 
+ #if (defined (_DEBUG) || defined(OIS_WIN32_JOYFF_DEBUG))
+   #include <iostream>
Index: /code/trunk/src/external/ois/linux/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ois/linux/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ois/linux/CMakeLists.txt	(revision 5929)
@@ -8,4 +8,5 @@
   LinuxPrereqs.h
 
+COMPILATION_BEGIN OISLinuxCompilation.cpp
   EventHelpers.cpp
   LinuxForceFeedback.cpp
@@ -14,3 +15,4 @@
   LinuxKeyboard.cpp
   LinuxMouse.cpp
+COMPILATION_END
 )
Index: /code/trunk/src/external/ois/mac/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ois/mac/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ois/mac/CMakeLists.txt	(revision 5929)
@@ -7,4 +7,5 @@
   MacPrereqs.h
 
+COMPILATION_BEGIN OISMacCompilation.cpp
   MacHelpers.cpp
   MacHIDManager.cpp
@@ -12,3 +13,4 @@
   MacKeyboard.cpp
   MacMouse.cpp
+COMPILATION_END
 )
Index: /code/trunk/src/external/ois/win32/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/ois/win32/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/ois/win32/CMakeLists.txt	(revision 5929)
@@ -7,4 +7,5 @@
   Win32Prereqs.h
 
+COMPILATION_BEGIN OISWin32Compilation.cpp
   Win32ForceFeedback.cpp
   Win32InputManager.cpp
@@ -12,3 +13,4 @@
   Win32KeyBoard.cpp
   Win32Mouse.cpp
+COMPILATION_END
 )
Index: /code/trunk/src/external/ois/win32/Win32ForceFeedback.cpp
===================================================================
--- /code/trunk/src/external/ois/win32/Win32ForceFeedback.cpp	(revision 5928)
+++ /code/trunk/src/external/ois/win32/Win32ForceFeedback.cpp	(revision 5929)
@@ -26,5 +26,5 @@
 
 // 0 = No trace; 1 = Important traces; 2 = Debug traces
-#define OIS_WIN32_JOYFF_DEBUG 1
+#define OIS_WIN32_JOYFF_DEBUG 0
 
 #if (defined (_DEBUG) || defined(OIS_WIN32_JOYFF_DEBUG))
Index: /code/trunk/src/external/tinyxml/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/tinyxml/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/tinyxml/CMakeLists.txt	(revision 5929)
@@ -18,5 +18,5 @@
  #
 
-SET(TINYXML++_FILES
+SET_SOURCE_FILES(TINYXML++_FILES
   ticpp.h
   ticpprc.h
@@ -24,4 +24,5 @@
   tinyxml.h
 
+COMPILATION_BEGIN TicppCompilation.cpp
   ticpp.cpp
   tinystr.cpp
@@ -29,9 +30,6 @@
   tinyxmlerror.cpp
   tinyxmlparser.cpp
+COMPILATION_END
 )
-
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
 
 ORXONOX_ADD_LIBRARY(tinyxml++_orxonox
Index: /code/trunk/src/external/tolua/CMakeLists.txt
===================================================================
--- /code/trunk/src/external/tolua/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/external/tolua/CMakeLists.txt	(revision 5929)
@@ -20,8 +20,8 @@
 ################### Tolua++ library ###################
 
-SET(TOLUA++_FILES
+SET_SOURCE_FILES(TOLUA++_FILES
   tolua_event.h
   tolua++.h
-
+COMPILATION_BEGIN ToluaCompilation.c
   tolua_event.c
   tolua_is.c
@@ -29,10 +29,6 @@
   tolua_push.c
   tolua_to.c
+COMPILATION_END
 )
-GENERATE_SOURCE_GROUPS(${TOLUA++_FILES})
-
-# No warnings needed from third party libraries
-REMOVE_COMPILER_FLAGS("-W3 -W4" MSVC)
-ADD_COMPILER_FLAGS("-w")
 
 ORXONOX_ADD_LIBRARY(tolua++_orxonox
Index: /code/trunk/src/libraries/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/CMakeLists.txt	(revision 5929)
@@ -25,6 +25,6 @@
 ################ Sub Directories ################
 
+ADD_SUBDIRECTORY(util)
 ADD_SUBDIRECTORY(core)
 ADD_SUBDIRECTORY(network)
 ADD_SUBDIRECTORY(tools)
-ADD_SUBDIRECTORY(util)
Index: /code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc
===================================================================
--- /code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5929)
@@ -100,5 +100,5 @@
             ArgumentCompletionList classlist;
 
-            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
                 if ((*it).second->hasConfigValues())
                     classlist.push_back(ArgumentCompletionListElement((*it).second->getName(), getLowercase((*it).first)));
@@ -110,7 +110,7 @@
         {
             ArgumentCompletionList configvalues;
-            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getIdentifierMap().find(classname);
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getStringIdentifierMap().find(classname);
 
-            if (identifier != Identifier::getIdentifierMapEnd() && (*identifier).second->hasConfigValues())
+            if (identifier != Identifier::getStringIdentifierMapEnd() && (*identifier).second->hasConfigValues())
             {
                 for (std::map<std::string, ConfigValueContainer*>::const_iterator it = (*identifier).second->getConfigValueMapBegin(); it != (*identifier).second->getConfigValueMapEnd(); ++it)
@@ -124,6 +124,6 @@
         {
             ArgumentCompletionList oldvalue;
-            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-            if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+            if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
             {
                 std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
Index: /code/trunk/src/libraries/core/BaseObject.cc
===================================================================
--- /code/trunk/src/libraries/core/BaseObject.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/BaseObject.cc	(revision 5929)
@@ -63,9 +63,9 @@
         this->bVisible_ = true;
         this->oldGametype_ = 0;
+        this->bRegisteredEventStates_ = false;
 
         this->lastLoadedXMLElement_ = 0;
 
-        this->functorSetMainState_ = 0;
-        this->functorGetMainState_ = 0;
+        this->mainStateFunctor_ = 0;
 
         this->setCreator(creator);
@@ -74,5 +74,5 @@
             this->setFile(this->creator_->getFile());
             this->setNamespace(this->creator_->getNamespace());
-            this->setScene(this->creator_->getScene());
+            this->setScene(this->creator_->getScene(), this->creator_->getSceneID());
             this->setGametype(this->creator_->getGametype());
         }
@@ -82,4 +82,5 @@
             this->namespace_ = 0;
             this->scene_ = 0;
+            this->sceneID_ = OBJECTID_UNKNOWN;
             this->gametype_ = 0;
         }
@@ -93,14 +94,12 @@
         if (this->isInitialized())
         {
-            for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
-                (*it)->unregisterEventListener(this);
-
-            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-                it->first->removeEvent(this);
-
-            if (this->functorSetMainState_)
-                delete this->functorSetMainState_;
-            if (this->functorGetMainState_)
-                delete this->functorGetMainState_;
+            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;
         }
     }
@@ -110,5 +109,4 @@
         @param xmlelement The XML-element
         @param loading Loading (true) or saving (false)
-        @return The XML-element
     */
     void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
@@ -120,39 +118,27 @@
 
         XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
-
-        Element* events = xmlelement.FirstChildElement("events", false);
-
+        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)
-        {
-            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)
-            {
-                for (std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->getIdentifier()->getXMLPortEventMapBegin(); it != this->getIdentifier()->getXMLPortEventMapEnd(); ++it)
-                    eventnames.push_back(it->first);
-            }
-
-            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
-            {
-                std::string sectionname = (*it);
-                ExecutorMember<BaseObject>* loadexecutor = createExecutor(createFunctor(&BaseObject::addEvent), std::string( "BaseObject" ) + "::" + "addEvent");
-                ExecutorMember<BaseObject>* saveexecutor = createExecutor(createFunctor(&BaseObject::getEvent), std::string( "BaseObject" ) + "::" + "getEvent");
-                loadexecutor->setDefaultValue(1, sectionname);
-
-                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = 0;
-                container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(this->getIdentifier()->getXMLPortEventContainer(sectionname));
-                if (!container)
-                {
-                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(sectionname, this->getIdentifier(), loadexecutor, saveexecutor, false, true);
-                    this->getIdentifier()->addXMLPortEventContainer(sectionname, container);
-                }
-                container->port(this, *events, mode);
-            }
-        }
+            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 loading Loading (true) or saving (false)
+    */
+    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;
     }
 
@@ -220,22 +206,37 @@
     }
 
-    void BaseObject::addEvent(BaseObject* event, const std::string& sectionname)
-    {
-        event->registerEventListener(this, sectionname);
-        this->events_.push_back(event);
-    }
-
-    void BaseObject::removeEvent(BaseObject* event)
-    {
-        this->events_.remove(event);
-    }
-
-    BaseObject* BaseObject::getEvent(unsigned int index) const
+    /**
+        @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::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
-        {
+        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);
+                return it->first;
             ++i;
         }
@@ -243,20 +244,52 @@
     }
 
-    void BaseObject::addEventContainer(const std::string& sectionname, EventContainer* container)
-    {
-        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
-        if (it != this->eventContainers_.end())
-        {
-            COUT(2) << "Warning: Overwriting EventContainer in class " << this->getIdentifier()->getName() << "." << std::endl;
+    /**
+        @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->eventContainers_[sectionname] = container;
-    }
-
-    EventContainer* BaseObject::getEventContainer(const std::string& sectionname) const
-    {
-        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
-        if (it != this->eventContainers_.end())
+        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
@@ -264,79 +297,165 @@
     }
 
-    void BaseObject::fireEvent()
-    {
-        this->fireEvent(true);
-        this->fireEvent(false);
-    }
-
-    void BaseObject::fireEvent(bool activate)
-    {
-        this->fireEvent(activate, this);
-    }
-
-    void BaseObject::fireEvent(bool activate, BaseObject* originator)
-    {
-        Event event(activate, originator);
-
-        for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-        {
-            event.sectionname_ = it->second;
-            it->first->processEvent(event);
-        }
-    }
-
+    /**
+        @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::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-            it->first->processEvent(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)
     {
-        ORXONOX_SET_EVENT(BaseObject, "activity", setActive, event);
-        ORXONOX_SET_EVENT(BaseObject, "visibility", setVisible, event);
-    }
-
-    void BaseObject::setMainStateName(const std::string& name)
-    {
-        if (this->mainStateName_ != name)
-        {
-            this->mainStateName_ = name;
-            if (this->functorSetMainState_)
-                delete this->functorSetMainState_;
-            if (this->functorGetMainState_)
-                delete this->functorGetMainState_;
-            this->changedMainState();
-            if (!this->functorSetMainState_)
-                COUT(2) << "Warning: \"" << name << "\" is not a valid MainState." << std::endl;
-        }
-    }
-
+        this->registerEventStates();
+        
+        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_ != "")
+            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->functorSetMainState_)
-            (*this->functorSetMainState_)(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;
     }
 
-    bool BaseObject::getMainState() const
-    {
-        if (this->functorGetMainState_)
-        {
-            (*this->functorGetMainState_)();
-            return this->functorGetMainState_->getReturnvalue();
-        }
-        else
-        {
-            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
-            return false;
-        }
-    }
-
-    void BaseObject::changedMainState()
-    {
-        SetMainState(BaseObject, "activity",   setActive,  isActive);
-        SetMainState(BaseObject, "visibility", setVisible, isVisible);
+    /**
+        @brief This function gets called if the main state name of the object changes.
+    */
+    void BaseObject::changedMainStateName()
+    {
+        this->mainStateFunctor_ = 0;
+
+        if (this->mainStateName_ != "")
+        {
+            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)
+            {
+                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)
+                {
+                    ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + "(" + statename + ")");
+                    ExecutorMember<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);
+            }
+        }
     }
 }
Index: /code/trunk/src/libraries/core/BaseObject.h
===================================================================
--- /code/trunk/src/libraries/core/BaseObject.h	(revision 5928)
+++ /code/trunk/src/libraries/core/BaseObject.h	(revision 5929)
@@ -37,12 +37,4 @@
 #define _BaseObject_H__
 
-#define SetMainState(classname, statename, setfunction, getfunction) \
-    if (this->getMainStateName() == statename) \
-    { \
-        this->functorSetMainState_ = createFunctor(&classname::setfunction)->setObject(this); \
-        this->functorGetMainState_ = createFunctor(&classname::getfunction)->setObject(this); \
-    }
-
-
 #include "CorePrereqs.h"
 
@@ -53,4 +45,5 @@
 #include "OrxonoxClass.h"
 #include "Super.h"
+#include "SmartPtr.h"
 
 namespace orxonox
@@ -68,4 +61,5 @@
             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 */
@@ -110,9 +104,18 @@
 
             void setMainState(bool state);
-            bool getMainState() const;
-
-            void setMainStateName(const std::string& name);
+
+            /** @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_; }
-            virtual void changedMainState();
+            /** @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 */
@@ -134,8 +137,9 @@
             inline BaseObject* getCreator() const { return this->creator_; }
 
-            inline void setScene(Scene* scene) { this->scene_ = scene; }
-            inline Scene* getScene() const { return this->scene_; }
-
-            inline void setGametype(Gametype* gametype)
+            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_)
@@ -146,26 +150,21 @@
                 }
             }
-            inline Gametype* getGametype() const { return this->gametype_; }
+            inline const SmartPtr<Gametype>& getGametype() const { return this->gametype_; }
             inline Gametype* getOldGametype() const { return this->oldGametype_; }
             virtual void changedGametype() {}
 
-            void fireEvent();
-            void fireEvent(bool activate);
-            void fireEvent(bool activate, BaseObject* originator);
+            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);
-
-            inline void registerEventListener(BaseObject* object, const std::string& sectionname)
-                { this->eventListeners_[object] = sectionname; }
-            inline void unregisterEventListener(BaseObject* object)
-                { this->eventListeners_.erase(object); }
-
-            void addEvent(BaseObject* event, const std::string& sectionname);
-            void removeEvent(BaseObject* event);
-            BaseObject* getEvent(unsigned int index) const;
-
-            void addEventContainer(const std::string& sectionname, EventContainer* container);
-            EventContainer* getEventContainer(const std::string& sectionname) const;
 
             /** @brief Sets the indentation of the debug output in the Loader. @param indentation The indentation */
@@ -173,6 +172,11 @@
             /** @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
@@ -180,10 +184,17 @@
             mbool       bVisible_;                             //!< True = the object is visible
             std::string mainStateName_;
-            Functor*    functorSetMainState_;
-            Functor*    functorGetMainState_;
+            Functor*    mainStateFunctor_;
 
         private:
+            /** @brief Adds an object which listens to the events of this object. */
+            inline void registerEventListener(BaseObject* object)
+                { this->eventListeners_.insert(object); }
+            /** @brief Removes an event listener from this object. */
+            inline void unregisterEventListener(BaseObject* object)
+                { this->eventListeners_.erase(object); }
+
             void setXMLName(const std::string& name);
             Template* getTemplate(unsigned int index) const;
+            void registerEventStates();
 
             bool                   bInitialized_;              //!< True if the object was initialized (passed the object registration)
@@ -194,11 +205,15 @@
             Namespace*             namespace_;
             BaseObject*            creator_;
-            Scene*                 scene_;
-            Gametype*              gametype_;
+            SmartPtr<Scene>        scene_;
+            uint32_t               sceneID_;
+            SmartPtr<Gametype>     gametype_;
             Gametype*              oldGametype_;
             std::set<Template*>    templates_;
-            std::map<BaseObject*,  std::string> eventListeners_;
-            std::list<BaseObject*> events_;
-            std::map<std::string, EventContainer*> eventContainers_;
+            
+            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)
     };
 
@@ -206,8 +221,7 @@
     SUPER_FUNCTION(2, BaseObject, changedActivity, false);
     SUPER_FUNCTION(3, BaseObject, changedVisibility, false);
-    SUPER_FUNCTION(4, BaseObject, processEvent, false);
-    SUPER_FUNCTION(6, BaseObject, changedMainState, false);
-    SUPER_FUNCTION(9, BaseObject, changedName, false);
-    SUPER_FUNCTION(10, BaseObject, changedGametype, false);
+    SUPER_FUNCTION(4, BaseObject, XMLEventPort, false);
+    SUPER_FUNCTION(8, BaseObject, changedName, false);
+    SUPER_FUNCTION(9, BaseObject, changedGametype, false);
 }
 
Index: /code/trunk/src/libraries/core/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/core/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/core/CMakeLists.txt	(revision 5929)
@@ -19,6 +19,4 @@
 
 SET_SOURCE_FILES(CORE_SRC_FILES
-  Clock.cc
-  ConfigFileManager.cc
   ConfigValueContainer.cc
   Core.cc
@@ -33,12 +31,11 @@
   Language.cc
   LuaState.cc
-  MemoryArchive.cc
   ObjectListBase.cc
   OrxonoxClass.cc
   Resource.cc
+  ScopedSingletonManager.cc
   WindowEventListener.cc
 
   # command
-  ArgumentCompletionFunctions.cc
   CommandEvaluation.cc
   CommandExecutor.cc
@@ -49,5 +46,4 @@
 
   # hierarchy
-  Factory.cc
   Identifier.cc
   MetaObjectList.cc
@@ -67,10 +63,20 @@
   Shell.cc
   TclBind.cc
+
+COMPILATION_BEGIN FilesystemCompilation.cc
+  ArgumentCompletionFunctions.cc
+  ConfigFileManager.cc
+  MemoryArchive.cc
+  PathConfig.cc
+COMPILATION_END
+
+  # multithreading
+  ThreadPool.cc
+COMPILATION_BEGIN ThreadCompilation.cc
   TclThreadManager.cc
-  
-  # multithreading
   Thread.cc
-  ThreadPool.cc
+COMPILATION_END
 )
+
 ADD_SUBDIRECTORY(input)
 
Index: /code/trunk/src/libraries/core/ClassFactory.h
===================================================================
--- /code/trunk/src/libraries/core/ClassFactory.h	(revision 5928)
+++ /code/trunk/src/libraries/core/ClassFactory.h	(revision 5929)
@@ -42,9 +42,19 @@
 
 #include "util/Debug.h"
-#include "Factory.h"
 #include "Identifier.h"
 
 namespace orxonox
 {
+    // ###########################
+    // ###       Factory       ###
+    // ###########################
+    //! Base-class of ClassFactory.
+    class _CoreExport Factory
+    {
+        public:
+            virtual ~Factory() {};
+            virtual BaseObject* fabricate(BaseObject* creator) = 0;
+    };
+
     // ###############################
     // ###      ClassFactory       ###
@@ -52,54 +62,28 @@
     //! The ClassFactory is able to create new objects of a specific class.
     template <class T>
-    class ClassFactory : public BaseFactory
+    class ClassFactory : public Factory
     {
         public:
-            static bool create(const std::string& name, bool bLoadable = true);
-            BaseObject* fabricate(BaseObject* creator);
+            /**
+                @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);
+            }
 
-        private:
-            ClassFactory() {}                               // Don't create
-            ClassFactory(const ClassFactory& factory) {}    // Don't copy
-            virtual ~ClassFactory() {}                      // Don't delete
-
-            static T* createNewObject(BaseObject* creator);
+            /**
+                @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));
+            }
     };
-
-    /**
-        @brief Adds the ClassFactory to the Identifier of the same type and the Identifier to the Factory.
-        @param name The name of the class
-        @param bLoadable True if the class can be loaded through XML
-        @return Always true (this is needed because the compiler only allows assignments before main())
-    */
-    template <class T>
-    bool ClassFactory<T>::create(const std::string& name, bool bLoadable)
-    {
-        COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
-        ClassIdentifier<T>::getIdentifier(name)->addFactory(new ClassFactory<T>);
-        ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
-        Factory::add(name, ClassIdentifier<T>::getIdentifier());
-
-        return true;
-    }
-
-    /**
-        @brief Creates and returns a new object of class T.
-        @return The new object
-    */
-    template <class T>
-    inline BaseObject* ClassFactory<T>::fabricate(BaseObject* creator)
-    {
-        return ClassFactory<T>::createNewObject(creator);
-    }
-
-    /**
-        @brief Creates and returns a new object of class T; this is a wrapper for the new operator.
-        @return The new object
-    */
-    template <class T>
-    inline T* ClassFactory<T>::createNewObject(BaseObject* creator)
-    {
-        return new T(creator);
-    }
 }
 
Index: /code/trunk/src/libraries/core/ClassTreeMask.cc
===================================================================
--- /code/trunk/src/libraries/core/ClassTreeMask.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/ClassTreeMask.cc	(revision 5929)
@@ -488,4 +488,5 @@
 
                 // Remove the redundant subnode from the current node
+                delete (*it);
                 node->subnodes_.erase(it++);
             }
Index: /code/trunk/src/libraries/core/ClassTreeMask.h
===================================================================
--- /code/trunk/src/libraries/core/ClassTreeMask.h	(revision 5928)
+++ /code/trunk/src/libraries/core/ClassTreeMask.h	(revision 5929)
@@ -265,7 +265,7 @@
 
             /** @brief Returns true if the ClassTreeMaskObjectIterator points at the given object. @param pointer The pointer of the object */
-            inline bool operator==(BaseObject* pointer) const { return ((*this->objectIterator_) == pointer); }
+            inline bool operator==(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) == pointer) || (!this->objectIterator_ && pointer == 0); }
             /** @brief Returns true if the ClassTreeMaskObjectIterator doesn't point at the given object. @param pointer The pointer of the object */
-            inline bool operator!=(BaseObject* pointer) const { return ((*this->objectIterator_) != pointer); }
+            inline bool operator!=(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) != pointer) || (!this->objectIterator_ && pointer != 0); }
             /** @brief Returns true if the ClassTreeMaskObjectIterator hasn't already reached the end. */
             inline operator bool() const { return (this->objectIterator_); }
Index: de/trunk/src/libraries/core/Clock.cc
===================================================================
--- /code/trunk/src/libraries/core/Clock.cc	(revision 5928)
+++ 	(revision )
@@ -1,78 +1,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
-*/
-
-#include "Clock.h"
-#include <OgreTimer.h>
-
-namespace orxonox
-{
-    Clock::Clock()
-        : timer_(new Ogre::Timer())
-        , storedTime_(0)
-        , tickTime_(0)
-        , tickDt_(0)
-        , tickDtFloat_(0.0f)
-        , lastTimersTime_(0)
-    {
-    }
-
-    Clock::~Clock()
-    {
-        delete timer_;
-    }
-    
-    void Clock::capture()
-    {
-        unsigned long timersTime = timer_->getMicroseconds();
-        tickTime_ = storedTime_ + timersTime;
-        tickDt_ = timersTime - lastTimersTime_;
-        tickDtFloat_ = static_cast<float>(tickDt_) / 1000000.0f;
-
-        if (timersTime > 0xFFFFFFFF/4)
-        {
-            // Ogre timer will overflow at 2^32 microseconds if unsigned long is 32 bit
-            storedTime_ += timersTime;
-            lastTimersTime_ = 0;
-            timer_->reset();
-        }
-        else
-        {
-            lastTimersTime_ = timersTime;
-        }
-    }
-
-    unsigned long long Clock::getRealMicroseconds() const
-    {
-        return this->timer_->getMicroseconds() + this->storedTime_;
-    }
-}
Index: de/trunk/src/libraries/core/Clock.h
===================================================================
--- /code/trunk/src/libraries/core/Clock.h	(revision 5928)
+++ 	(revision )
@@ -1,67 +1,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:
- *      ...
- *
- */
-
-#ifndef _Clock_H__
-#define _Clock_H__
-
-#include "CorePrereqs.h"
-#include "util/OgreForwardRefs.h"
-
-namespace orxonox
-{
-    class _CoreExport Clock
-    {
-    public:
-        Clock();
-        ~Clock();
-
-        void capture();
-
-        unsigned long long getMicroseconds()   const { return tickTime_; }
-        unsigned long long getMilliseconds()   const { return tickTime_ / 1000; }
-        unsigned long      getSeconds()        const { return static_cast<long> (tickTime_ / 1000000); }
-        float              getSecondsPrecise() const { return static_cast<float>(tickTime_ / 1000000.0f); }
-
-        float              getDeltaTime()      const { return tickDtFloat_; }
-        long               getDeltaTimeMicroseconds() const { return tickDt_; }
-
-        unsigned long long getRealMicroseconds() const;
-
-    private:
-        Clock(const Clock& instance);
-
-        Ogre::Timer*       timer_;
-        unsigned long long storedTime_;
-        unsigned long long tickTime_;
-        long               tickDt_;
-        float              tickDtFloat_;
-        unsigned long      lastTimersTime_;
-    };
-}
-
-#endif /* _Clock_H__ */
Index: /code/trunk/src/libraries/core/CommandExecutor.cc
===================================================================
--- /code/trunk/src/libraries/core/CommandExecutor.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/CommandExecutor.cc	(revision 5929)
@@ -468,5 +468,5 @@
         CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear();
         std::string lowercase = getLowercase(fragment);
-        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMapBegin(); it != Identifier::getLowercaseIdentifierMapEnd(); ++it)
+        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapBegin(); it != Identifier::getLowercaseStringIdentifierMapEnd(); ++it)
             if ((*it).second->hasConsoleCommands())
                 if ((*it).first.find(lowercase) == 0 || fragment == "")
@@ -516,6 +516,6 @@
     {
         std::string lowercase = getLowercase(name);
-        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMap().find(lowercase);
-        if ((it != Identifier::getLowercaseIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
+        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMap().find(lowercase);
+        if ((it != Identifier::getLowercaseStringIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
             return (*it).second;
 
Index: /code/trunk/src/libraries/core/CommandLine.cc
===================================================================
--- /code/trunk/src/libraries/core/CommandLine.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/CommandLine.cc	(revision 5929)
@@ -31,5 +31,4 @@
 #include <algorithm>
 #include <sstream>
-#include <boost/filesystem.hpp>
 
 #include "util/Convert.h"
@@ -38,5 +37,5 @@
 #include "util/StringUtils.h"
 #include "util/SubString.h"
-#include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -285,4 +284,5 @@
         }
 
+        infoStr << std::endl;
         infoStr << "Usage: orxonox [options]" << std::endl;
         infoStr << "Available options:" << std::endl;
@@ -348,10 +348,9 @@
     {
         std::string filename = CommandLine::getValue("optionsFile").getString();
-        boost::filesystem::path filepath(Core::getConfigPath() / filename);
 
         // look for additional arguments in given file or start.ini as default
         // They will not overwrite the arguments given directly
         std::ifstream file;
-        file.open(filepath.string().c_str());
+        file.open((PathConfig::getConfigPathString() + filename).c_str());
         std::vector<std::string> args;
         if (file)
Index: /code/trunk/src/libraries/core/ConfigFileManager.cc
===================================================================
--- /code/trunk/src/libraries/core/ConfigFileManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/ConfigFileManager.cc	(revision 5929)
@@ -36,5 +36,5 @@
 #include "ConsoleCommand.h"
 #include "ConfigValueContainer.h"
-#include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -48,6 +48,6 @@
     bool config(const std::string& classname, const std::string& varname, const std::string& value)
     {
-        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
         {
             std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
@@ -60,6 +60,6 @@
     bool tconfig(const std::string& classname, const std::string& varname, const std::string& value)
     {
-        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
         {
             std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
@@ -222,9 +222,9 @@
 
         // Get default file if necessary and available
-        boost::filesystem::path filepath(Core::getConfigPath() / this->filename_);
+        boost::filesystem::path filepath(PathConfig::getConfigPath() / this->filename_);
         if (!boost::filesystem::exists(filepath))
         {
             // Try to get default one from the data folder
-            boost::filesystem::path defaultFilepath(Core::getDataPath() / "defaultConfig" / this->filename_);
+            boost::filesystem::path defaultFilepath(PathConfig::getDataPath() / "defaultConfig" / this->filename_);
             if (boost::filesystem::exists(defaultFilepath))
             {
@@ -336,5 +336,5 @@
     {
         std::ofstream file;
-        file.open((Core::getConfigPathString() + filename_).c_str(), std::fstream::out);
+        file.open((PathConfig::getConfigPathString() + filename_).c_str(), std::fstream::out);
         file.setf(std::ios::fixed, std::ios::floatfield);
         file.precision(6);
@@ -376,6 +376,6 @@
         for (std::list<ConfigFileSection*>::iterator it1 = this->sections_.begin(); it1 != this->sections_.end(); )
         {
-            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getIdentifierMap().find((*it1)->getName());
-            if (it2 != Identifier::getIdentifierMapEnd() && (*it2).second->hasConfigValues())
+            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getStringIdentifierMap().find((*it1)->getName());
+            if (it2 != Identifier::getStringIdentifierMapEnd() && (*it2).second->hasConfigValues())
             {
                 // The section exists, delete comment
@@ -455,5 +455,5 @@
         if (this->type_ == ConfigFileType::Settings)
         {
-            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
             {
                 if (it->second->hasConfigValues())
Index: /code/trunk/src/libraries/core/Core.cc
===================================================================
--- /code/trunk/src/libraries/core/Core.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Core.cc	(revision 5929)
@@ -37,9 +37,5 @@
 
 #include <cassert>
-#include <fstream>
-#include <cstdlib>
-#include <cstdio>
-#include <boost/version.hpp>
-#include <boost/filesystem.hpp>
+#include <vector>
 
 #ifdef ORXONOX_PLATFORM_WINDOWS
@@ -50,17 +46,11 @@
 #  undef min
 #  undef max
-#elif defined(ORXONOX_PLATFORM_APPLE)
-#  include <sys/param.h>
-#  include <mach-o/dyld.h>
-#else /* Linux */
-#  include <sys/types.h>
-#  include <unistd.h>
 #endif
 
-#include "SpecialConfig.h"
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
 #include "util/SignalHandler.h"
-#include "Clock.h"
+#include "PathConfig.h"
 #include "CommandExecutor.h"
 #include "CommandLine.h"
@@ -69,5 +59,4 @@
 #include "CoreIncludes.h"
 #include "DynLibManager.h"
-#include "Factory.h"
 #include "GameMode.h"
 #include "GraphicsManager.h"
@@ -76,4 +65,5 @@
 #include "Language.h"
 #include "LuaState.h"
+#include "ScopedSingletonManager.h"
 #include "Shell.h"
 #include "TclBind.h"
@@ -81,11 +71,4 @@
 #include "input/InputManager.h"
 
-// Boost 1.36 has some issues with deprecated functions that have been omitted
-#if (BOOST_VERSION == 103600)
-#  define BOOST_LEAF_FUNCTION filename
-#else
-#  define BOOST_LEAF_FUNCTION leaf
-#endif
-
 namespace orxonox
 {
@@ -93,6 +76,4 @@
     Core* Core::singletonPtr_s  = 0;
 
-    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
-    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
     SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
 #ifdef ORXONOX_PLATFORM_WINDOWS
@@ -117,12 +98,4 @@
             RegisterRootObject(CoreConfiguration);
             this->setConfigValues();
-
-            // External data directory only exists for dev runs
-            if (Core::isDevelopmentRun())
-            {
-                // Possible data path override by the command line
-                if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
-                    tsetExternalDataPath(CommandLine::getValue("externalDataPath"));
-            }
         }
 
@@ -194,15 +167,4 @@
         }
 
-        /**
-        @brief
-            Temporary sets the external data path
-        @param path
-            The new data path
-        */
-        void tsetExternalDataPath(const std::string& path)
-        {
-            externalDataPath_ = boost::filesystem::path(path);
-        }
-
         void initializeRandomNumberGenerator()
         {
@@ -222,13 +184,4 @@
         std::string language_;                          //!< The language
         bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
-
-        //! Path to the parent directory of the ones above if program was installed with relativ pahts
-        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 file folder
-        boost::filesystem::path externalDataPath_;      //!< Path to the external data file folder
-        boost::filesystem::path configPath_;            //!< Path to the config file folder
-        boost::filesystem::path logPath_;               //!< Path to the log file folder
     };
 
@@ -240,9 +193,8 @@
         , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
         , configuration_(new CoreConfiguration()) // Don't yet create config values!
-        , bDevRun_(false)
         , bGraphicsLoaded_(false)
     {
         // Set the hard coded fixed paths
-        this->setFixedPaths();
+        this->pathConfig_.reset(new PathConfig());
 
         // Create a new dynamic library manager
@@ -250,51 +202,15 @@
 
         // Load modules
-        try
-        {
-            // We search for helper files with the following extension
-            std::string moduleextension = specialConfig::moduleExtension;
-            size_t moduleextensionlength = moduleextension.size();
-
-            // Search in the directory of our executable
-            boost::filesystem::path searchpath = this->configuration_->modulePath_;
-
-            // 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 + ";" + configuration_->modulePath_.string()).c_str()));
-
-            boost::filesystem::directory_iterator file(searchpath);
-            boost::filesystem::directory_iterator end;
-
-            // Iterate through all files
-            while (file != end)
+        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
+        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
+        {
+            try
             {
-                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 - now load the library with the same name
-                        std::string library = filename.substr(0, filename.size() - moduleextensionlength);
-                        boost::filesystem::path librarypath = searchpath / library;
-
-                        try
-                        {
-                            DynLibManager::getInstance().load(librarypath.string());
-                        }
-                        catch (...)
-                        {
-                            COUT(1) << "Couldn't load module \"" << librarypath.string() << "\": " << Exception::handleMessage() << std::endl;
-                        }
-                    }
-                }
-
-                ++file;
+                this->dynLibManager_->load(*it);
             }
-        }
-        catch (...)
-        {
-            COUT(1) << "An error occurred while loading modules: " << Exception::handleMessage() << std::endl;
+            catch (...)
+            {
+                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
+            }
         }
 
@@ -303,13 +219,13 @@
 
         // Set configurable paths like log, config and media
-        this->setConfigurablePaths();
+        this->pathConfig_->setConfigurablePaths();
 
         // create a signal handler (only active for linux)
         // This call is placed as soon as possible, but after the directories are set
         this->signalHandler_.reset(new SignalHandler());
-        this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
+        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
 
         // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
-        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
+        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
 
         // Parse additional options file now that we know its path
@@ -334,5 +250,5 @@
 
         // creates the class hierarchy for all classes with factories
-        Factory::createClassHierarchy();
+        Identifier::createClassHierarchy();
 
         // Do this soon after the ConfigFileManager has been created to open up the
@@ -344,9 +260,12 @@
 
         // initialise Tcl
-        this->tclBind_.reset(new TclBind(Core::getDataPathString()));
+        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
         this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
 
         // create a shell
         this->shell_.reset(new Shell());
+
+        // Create singletons that always exist (in other libraries)
+        this->rootScope_.reset(new Scope<ScopeID::Root>());
     }
 
@@ -370,17 +289,25 @@
         inputManager_.reset(new InputManager());
 
-        // load the CEGUI interface
+        // Load the CEGUI interface
         guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
             inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
 
+        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();
-
-        bGraphicsLoaded_ = true;
     }
 
     void Core::unloadGraphics()
     {
-        this->guiManager_.reset();;
-        this->inputManager_.reset();;
+        this->graphicsScope_.reset();
+        this->guiManager_.reset();
+        this->inputManager_.reset();
         this->graphicsManager_.reset();
 
@@ -397,4 +324,5 @@
 
         bGraphicsLoaded_ = false;
+        GameMode::bShowsGraphics_s = false;
     }
 
@@ -457,54 +385,4 @@
     }
 
-    /*static*/ void Core::tsetExternalDataPath(const std::string& path)
-    {
-        getInstance().configuration_->tsetExternalDataPath(path);
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getDataPath()
-    {
-        return getInstance().configuration_->dataPath_;
-    }
-    /*static*/ std::string Core::getDataPathString()
-    {
-        return getInstance().configuration_->dataPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getExternalDataPath()
-    {
-        return getInstance().configuration_->externalDataPath_;
-    }
-    /*static*/ std::string Core::getExternalDataPathString()
-    {
-        return getInstance().configuration_->externalDataPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getConfigPath()
-    {
-        return getInstance().configuration_->configPath_;
-    }
-    /*static*/ std::string Core::getConfigPathString()
-    {
-        return getInstance().configuration_->configPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getLogPath()
-    {
-        return getInstance().configuration_->logPath_;
-    }
-    /*static*/ std::string Core::getLogPathString()
-    {
-        return getInstance().configuration_->logPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getRootPath()
-    {
-        return getInstance().configuration_->rootPath_;
-    }
-    /*static*/ std::string Core::getRootPathString()
-    {
-        return getInstance().configuration_->rootPath_.string() + '/';
-    }
-
     /**
     @note
@@ -553,176 +431,8 @@
     }
 
-    /**
-    @brief
-        Retrievs the executable path and sets all hard coded fixed path (currently only the module path)
-        Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
-        If found it means that this is not an installed run, hence we
-        don't write the logs and config files to ~/.orxonox
-    @throw
-        GeneralException
-    */
-    void Core::setFixedPaths()
-    {
-        //////////////////////////
-        // FIND EXECUTABLE PATH //
-        //////////////////////////
-
-#ifdef ORXONOX_PLATFORM_WINDOWS
-        // get executable module
-        TCHAR buffer[1024];
-        if (GetModuleFileName(NULL, buffer, 1024) == 0)
-            ThrowException(General, "Could not retrieve executable path.");
-
-#elif defined(ORXONOX_PLATFORM_APPLE)
-        char buffer[1024];
-        unsigned long path_len = 1023;
-        if (_NSGetExecutablePath(buffer, &path_len))
-            ThrowException(General, "Could not retrieve executable path.");
-
-#else /* Linux */
-        /* written by Nicolai Haehnle <prefect_@gmx.net> */
-
-        /* Get our PID and build the name of the link in /proc */
-        char linkname[64]; /* /proc/<pid>/exe */
-        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
-        {
-            /* This should only happen on large word systems. I'm not sure
-               what the proper response is here.
-               Since it really is an assert-like condition, aborting the
-               program seems to be in order. */
-            assert(false);
-        }
-
-        /* Now read the symbolic link */
-        char buffer[1024];
-        int ret;
-        ret = readlink(linkname, buffer, 1024);
-        /* In case of an error, leave the handling up to the caller */
-        if (ret == -1)
-            ThrowException(General, "Could not retrieve executable path.");
-
-        /* Ensure proper NUL termination */
-        buffer[ret] = 0;
-#endif
-
-        configuration_->executablePath_ = boost::filesystem::path(buffer);
-#ifndef ORXONOX_PLATFORM_APPLE
-        configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
-#endif
-
-        /////////////////////
-        // SET MODULE PATH //
-        /////////////////////
-
-        if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
-        {
-            COUT(1) << "Running from the build tree." << std::endl;
-            Core::bDevRun_ = true;
-            configuration_->modulePath_ = specialConfig::moduleDevDirectory;
-        }
-        else
-        {
-
-#ifdef INSTALL_COPYABLE // --> relative paths
-
-            // Also set the root path
-            boost::filesystem::path relativeExecutablePath(specialConfig::defaultRuntimePath);
-            configuration_->rootPath_ = configuration_->executablePath_;
-            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
-                   && !configuration_->rootPath_.empty())
-                configuration_->rootPath_ = configuration_->rootPath_.branch_path();
-            if (configuration_->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
-            configuration_->modulePath_ = configuration_->rootPath_ / specialConfig::defaultModulePath;
-
-#else
-
-            // There is no root path, so don't set it at all
-            // Module path is fixed as well
-            configuration_->modulePath_ = specialConfig::moduleInstallDirectory;
-
-#endif
-        }
-    }
-
-    /**
-    @brief
-        Sets config, log and media path and creates folders if necessary.
-    @throws
-        GeneralException
-    */
-    void Core::setConfigurablePaths()
-    {
-        if (Core::isDevelopmentRun())
-        {
-            configuration_->dataPath_  = specialConfig::dataDevDirectory;
-            configuration_->externalDataPath_ = specialConfig::externalDataDevDirectory;
-            configuration_->configPath_ = specialConfig::configDevDirectory;
-            configuration_->logPath_    = specialConfig::logDevDirectory;
-        }
-        else
-        {
-
-#ifdef INSTALL_COPYABLE // --> relative paths
-
-            // Using paths relative to the install prefix, complete them
-            configuration_->dataPath_   = configuration_->rootPath_ / specialConfig::defaultDataPath;
-            configuration_->configPath_ = configuration_->rootPath_ / specialConfig::defaultConfigPath;
-            configuration_->logPath_    = configuration_->rootPath_ / specialConfig::defaultLogPath;
-
-#else
-
-            configuration_->dataPath_  = specialConfig::dataInstallDirectory;
-
-            // Get user directory
-#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
-            char* userDataPathPtr(getenv("HOME"));
-#  else
-            char* userDataPathPtr(getenv("APPDATA"));
-#  endif
-            if (userDataPathPtr == NULL)
-                ThrowException(General, "Could not retrieve user data path.");
-            boost::filesystem::path userDataPath(userDataPathPtr);
-            userDataPath /= ".orxonox";
-
-            configuration_->configPath_ = userDataPath / specialConfig::defaultConfigPath;
-            configuration_->logPath_    = userDataPath / specialConfig::defaultLogPath;
-
-#endif
-
-        }
-
-        // Option to put all the config and log files in a separate folder
-        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
-        {
-            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
-            configuration_->configPath_ = configuration_->configPath_ / directory;
-            configuration_->logPath_    = configuration_->logPath_    / directory;
-        }
-
-        // Create directories to avoid problems when opening files in non existent folders.
-        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
-        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
-        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
-
-        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
-            it != directories.end(); ++it)
-        {
-            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
-            {
-                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
-                                         Please remove " + it->first.string());
-            }
-            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
-            {
-                COUT(4) << "Created " << it->second << " directory" << std::endl;
-            }
-        }
-    }
-
     void Core::preUpdate(const Clock& time)
     {
+        // singletons from other libraries
+        ScopedSingletonManager::update<ScopeID::Root>(time);
         if (this->bGraphicsLoaded_)
         {
@@ -731,4 +441,6 @@
             // process gui events
             this->guiManager_->update(time);
+            // graphics singletons from other libraries
+            ScopedSingletonManager::update<ScopeID::Graphics>(time);
         }
         // process thread commands
Index: /code/trunk/src/libraries/core/Core.h
===================================================================
--- /code/trunk/src/libraries/core/Core.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Core.h	(revision 5929)
@@ -28,13 +28,4 @@
  */
 
-/**
-@file
-@brief
-    Declaration of the Core class.
-@details
-    The Core class is a singleton, only used to configure some variables
-    in the core through the config-file.
-*/
-
 #ifndef _Core_H__
 #define _Core_H__
@@ -45,4 +36,5 @@
 #include <boost/scoped_ptr.hpp>
 #include "util/OutputHandler.h"
+#include "util/Scope.h"
 #include "util/ScopeGuard.h"
 #include "util/Singleton.h"
@@ -55,7 +47,4 @@
     @brief
         The Core class is a singleton used to configure the program basics.
-    @details
-        The class provides information about the data, config and log path.
-        It determines those by the use of platform specific functions.
     @remark
         You should only create this singleton once because it destroys the identifiers!
@@ -85,28 +74,4 @@
             static void  resetLanguage();
 
-            static void tsetExternalDataPath(const std::string& path);
-            //! Returns the path to the data files as boost::filesystem::path
-            static const boost::filesystem::path& getDataPath();
-            //! Returns the path to the external data files as boost::filesystem::path
-            static const boost::filesystem::path& getExternalDataPath();
-            //! Returns the path to the config files as boost::filesystem::path
-            static const boost::filesystem::path& getConfigPath();
-            //! Returns the path to the log files as boost::filesystem::path
-            static const boost::filesystem::path& getLogPath();
-            //! Returns the path to the root folder as boost::filesystem::path
-            static const boost::filesystem::path& getRootPath();
-            //! 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();
-            //! Returns the path to the log files as std::string
-            static std::string getLogPathString();
-            //! Returns the path to the root folder as std::string
-            static std::string getRootPathString();
-
-            static bool isDevelopmentRun() { return getInstance().bDevRun_; }
-
         private:
             Core(const Core&); //!< Don't use (undefined symbol)
@@ -118,9 +83,8 @@
             void unloadGraphics();
 
-            void setFixedPaths();
-            void setConfigurablePaths();
             void setThreadAffinity(int limitToCPU);
 
             // Mind the order for the destruction!
+            scoped_ptr<PathConfig>        pathConfig_;
             scoped_ptr<DynLibManager>     dynLibManager_;
             scoped_ptr<SignalHandler>     signalHandler_;
@@ -137,8 +101,8 @@
             scoped_ptr<InputManager>      inputManager_;        //!< Interface to OIS
             scoped_ptr<GUIManager>        guiManager_;          //!< Interface to GUI
+            scoped_ptr<Scope<ScopeID::Root> >     rootScope_;
+            scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_;
 
-            bool                          bDevRun_;             //!< True for runs in the build directory (not installed)
             bool                          bGraphicsLoaded_;
-
             static Core* singletonPtr_s;
     };
Index: /code/trunk/src/libraries/core/CoreIncludes.h
===================================================================
--- /code/trunk/src/libraries/core/CoreIncludes.h	(revision 5928)
+++ /code/trunk/src/libraries/core/CoreIncludes.h	(revision 5929)
@@ -29,5 +29,5 @@
 /**
     @file
-    @brief Definition of macros for Identifier and Factory.
+    @brief Definition of macros for Identifiers
 
     Every class needs the RegisterObject(class) macro in its constructor. If the class is an interface
@@ -45,5 +45,5 @@
 #include "util/Debug.h"
 #include "Identifier.h"
-#include "Factory.h"
+#include "SubclassIdentifier.h"
 #include "ClassFactory.h"
 #include "ObjectList.h"
@@ -76,16 +76,16 @@
 
 /**
-    @brief Creates the entry in the Factory.
+    @brief Creates the Factory.
     @param ClassName The name of the class
 */
 #define CreateFactory(ClassName) \
-    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, true)
+    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, true)
 
 /**
-    @brief Creates the entry in the Factory for classes which should not be loaded through XML.
+    @brief Creates the Factory for classes which should not be loaded through XML.
     @param ClassName The name of the class
 */
 #define CreateUnloadableFactory(ClassName) \
-    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, false)
+    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, false)
 
 /**
@@ -100,19 +100,28 @@
 {
     /**
-        @brief Returns the Identifier with a given name through the factory.
+        @brief Returns the Identifier with a given name.
         @param String The name of the class
     */
     inline Identifier* ClassByString(const std::string& name)
     {
-        return Factory::getIdentifier(name);
+        return Identifier::getIdentifierByString(name);
     }
 
     /**
-        @brief Returns the Identifier with a given network ID through the factory.
+        @brief Returns the Identifier with a given lowercase name.
+        @param String 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 networkID The network ID of the class
     */
     inline Identifier* ClassByID(uint32_t id)
     {
-        return Factory::getIdentifier(id);
+        return Identifier::getIdentifierByID(id);
     }
 }
Index: /code/trunk/src/libraries/core/CorePrereqs.h
===================================================================
--- /code/trunk/src/libraries/core/CorePrereqs.h	(revision 5928)
+++ /code/trunk/src/libraries/core/CorePrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the core library
 */
 
@@ -40,4 +41,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( CORE_STATIC_BUILD )
 #  ifdef CORE_SHARED_BUILD
@@ -56,8 +58,17 @@
 #endif
 
-
-//-----------------------------------------------------------------------
-// Forward declarations
-//-----------------------------------------------------------------------
+//-----------------------------------------------------------------------
+// Constants
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
+    static const uint32_t OBJECTID_UNKNOWN = static_cast<uint32_t>(-1);
+}
+
+//-----------------------------------------------------------------------
+// Enums
+//-----------------------------------------------------------------------
+
 namespace orxonox
 {
@@ -66,4 +77,5 @@
         enum Mode
         {
+            NOP,
             LoadObject,
             SaveObject,
@@ -82,11 +94,16 @@
         };
     };
-
+}
+
+//-----------------------------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
     typedef std::string LanguageEntryLabel;
 
     class ArgumentCompleter;
     class ArgumentCompletionListElement;
-    class BaseFactory;
-    class BaseMetaObjectListElement;
     class BaseObject;
     template <class T>
@@ -98,7 +115,5 @@
     class ClassTreeMaskNode;
     class ClassTreeMaskObjectIterator;
-    class Clock;
     class CommandEvaluation;
-    class CommandExecutor;
     class CommandLine;
     class CommandLineArgument;
@@ -109,4 +124,5 @@
     class ConfigFileManager;
     class ConfigFileSection;
+    struct ConfigFileType;
     class ConfigValueContainer;
     class ConsoleCommand;
@@ -115,5 +131,5 @@
     class DynLibManager;
     struct Event;
-    class EventContainer;
+    class EventState;
     class Executor;
     template <class T>
@@ -125,4 +141,8 @@
     class FunctorMember;
     class FunctorStatic;
+    class Game;
+    class GameState;
+    struct GameStateInfo;
+    struct GameStateTreeNode;
     class GraphicsManager;
     class GUIManager;
@@ -131,8 +151,5 @@
     template <class T>
     class Iterator;
-    class IteratorBase;
     class Language;
-    class LanguageEntry;
-    class Loader;
     class LuaState;
     class MemoryArchive;
@@ -152,8 +169,11 @@
     class OgreWindowEventListener;
     class OrxonoxClass;
+    class PathConfig;
     struct ResourceInfo;
     class Shell;
     class ShellListener;
     template <class T>
+    class SmartPtr;
+    template <class T>
     class SubclassIdentifier;
     class TclBind;
@@ -163,4 +183,8 @@
     class TclThreadManager;
     class Template;
+    class Thread;
+    class ThreadPool;
+    template <class T>
+    class WeakPtr;
     class WindowEventListener;
     class XMLFile;
@@ -173,15 +197,8 @@
     class XMLPortParamContainer;
 
-    // game states
-    class Game;
-    class GameState;
-    struct GameStateInfo;
-    struct GameStateTreeNode;
-
-    // input
+    // Input
     class BaseCommand;
     class BufferedParamCommand;
     class Button;
-    class CalibratorCallback;
     class HalfAxis;
     class InputBuffer;
@@ -192,16 +209,15 @@
     class InputManager;
     class InputState;
+    struct InputStatePriority;
+    class JoyStickQuantityListener;
     class JoyStick;
+    class KeyBinder;
+    class KeyBinderManager;
+    class Keyboard;
+    class KeyDetector;
+    class KeyEvent;
     class Mouse;
-    class Keyboard;
-    class KeyBinder;
-    class KeyDetector;
     class ParamCommand;
     class SimpleCommand;
-
-
-    // multithreading
-    class Thread;
-    class ThreadPool;
 }
 
@@ -282,13 +298,6 @@
 namespace orxonox
 {
-    using ticpp::Document;
     using ticpp::Element;
-    using ticpp::Declaration;
-    using ticpp::StylesheetReference;
-    using ticpp::Text;
-    using ticpp::Comment;
-    using ticpp::Attribute;
-}
-
+}
 
 #endif /* _CorePrereqs_H__ */
Index: /code/trunk/src/libraries/core/Event.cc
===================================================================
--- /code/trunk/src/libraries/core/Event.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Event.cc	(revision 5929)
@@ -30,50 +30,79 @@
 
 #include "BaseObject.h"
-#include "Executor.h"
+#include "Identifier.h"
 
 namespace orxonox
 {
-    EventContainer::~EventContainer()
+    /**
+        @brief Destructor: Deletes the functor of the event state.
+    */
+    EventState::~EventState()
     {
-        delete this->eventfunction_;
+        if (this->statefunction_)
+            delete this->statefunction_;
     }
 
-    void EventContainer::process(BaseObject* object, const Event& event)
+    /**
+        @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->bActive_)
+        if (this->bProcessingEvent_)
         {
-            COUT(2) << "Warning: Detected Event loop in section \"" << this->eventname_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
+            COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
             return;
         }
 
-        this->bActive_ = true;
+        this->bProcessingEvent_ = true;
 
-        if (this->eventname_ == event.sectionname_)
+        // check if the originator is an instance of the requested class
+        if (event.originator_->isA(this->subclass_))
         {
-            if (event.originator_->isA(this->subclass_))
+            // actualize the activationcounter
+            if (event.activate_)
+                ++this->activeEvents_;
+            else
             {
-                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->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)
                 {
-                    --this->activeEvents_;
-
-                    if (this->activeEvents_ < 0)
-                        this->activeEvents_ = 0;
+                    // one argument: just the eventstate
+                    (*this->statefunction_)(this->activeEvents_);
                 }
-
-                if (this->eventfunction_->getParamCount() == 0 && event.activate_)
-                    (*this->eventfunction_)();
-                else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
+                else if (this->statefunction_->getParamCount() >= 2)
                 {
-                    if (this->eventfunction_->getParamCount() == 1)
-                        (*this->eventfunction_)(this->activeEvents_);
-                    else if (this->eventfunction_->getParamCount() >= 2 && event.castedOriginator_)
-                        (*this->eventfunction_)(this->activeEvents_, event.castedOriginator_);
+                    // 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_)(this->activeEvents_, event.originator_);
+                    }
+                    else
+                    {
+                        // else cast the pointer to the desired class
+                        void* castedOriginator = event.originator_->getDerivedPointer(this->subclass_->getClassID());
+                        (*this->statefunction_)(this->activeEvents_, castedOriginator);
+                    }
                 }
             }
         }
 
-        this->bActive_ = false;
+        this->bProcessingEvent_ = false;
     }
 }
Index: /code/trunk/src/libraries/core/Event.h
===================================================================
--- /code/trunk/src/libraries/core/Event.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Event.h	(revision 5929)
@@ -35,29 +35,48 @@
 namespace orxonox
 {
+    /**
+        @brief The Event struct contains information about a fired Event.
+    */
     struct _CoreExport Event
     {
-            Event(bool activate, BaseObject* originator) : activate_(activate), originator_(originator), castedOriginator_(0) {}
+        Event(bool activate, BaseObject* originator, const std::string& name) : activate_(activate), originator_(originator), name_(name) {}
 
-            bool        activate_;
-            BaseObject* originator_;
-            void*       castedOriginator_;
-            std::string sectionname_;
+        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
     };
 
-    class _CoreExport EventContainer
+    /**
+        @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: function()
+         - boolean state:    function(bool state)
+         - individual state: function(bool state, SomeClass originator)
+         
+        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:
-            EventContainer(const std::string& eventname, Executor* eventfunction, Identifier* subclass) : bActive_(false), eventname_(eventname), eventfunction_(eventfunction), subclass_(subclass), activeEvents_(0) {}
-            virtual ~EventContainer();
+            EventState(Functor* statefunction, Identifier* subclass) : bProcessingEvent_(false), activeEvents_(0), statefunction_(statefunction), subclass_(subclass) {}
+            virtual ~EventState();
 
-            void process(BaseObject* object, const Event& event);
+            void process(const Event& event, BaseObject* object);
+            
+            Functor* getFunctor() const
+                { return this->statefunction_; }
 
         private:
-            bool bActive_;
-            std::string eventname_;
-            Executor* eventfunction_;
-            Identifier* subclass_;
-
-            int activeEvents_;
+            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
+            Functor*    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)
     };
 }
Index: /code/trunk/src/libraries/core/EventIncludes.h
===================================================================
--- /code/trunk/src/libraries/core/EventIncludes.h	(revision 5928)
+++ /code/trunk/src/libraries/core/EventIncludes.h	(revision 5929)
@@ -32,40 +32,57 @@
 #include "CorePrereqs.h"
 #include "Executor.h"
+#include "XMLPort.h"
 
-#define ORXONOX_SET_EVENT(classname, eventname, functionname, event) \
-    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject)
+/**
+    @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)
 
-#define ORXONOX_SET_EVENT_TEMPLATE(classname, eventname, functionname, event, ...) \
-    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject, __VA_ARGS__)
+/**
+    @brief Like XMLPortEventState but with additional template arguments to identify the function of the state (if ambiguous).
+*/
+#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 ORXONOX_SET_SUBCLASS_EVENT(classname, eventname, functionname, event, subclassname) \
-    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname)
+#define XMLPortEventStateIntern(name, classname, statename, xmlelement, mode) \
+    static orxonox::ExecutorMember<classname>* xmlsetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
+    static orxonox::ExecutorMember<classname>* xmlgetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
+    XMLPortObjectGeneric(xmlport##name, classname, orxonox::BaseObject, statename, xmlsetfunctor##name, xmlgetfunctor##name, xmlelement, mode, false, true)
+    
 
-#define ORXONOX_SET_SUBCLASS_EVENT_TEMPLATE(classname, eventname, functionname, event, subclassname, ...) \
-    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname, __VA_ARGS__)
+/**
+    @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
 
-#define ORXONOX_SET_EVENT_GENERIC(containername, classname, eventname, functionname, event, subclassname) \
-    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
-    if (!containername) \
-    { \
-        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
-        executor->setObject(this); \
-        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
-        this->addEventContainer(eventname, containername); \
-    } \
-    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
-    containername->process(this, event)
-
-#define ORXONOX_SET_EVENT_GENERIC_TEMPLATE(containername, classname, eventname, functionname, event, subclassname, ...) \
-    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
-    if (!containername) \
-    { \
-        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
-        executor->setObject(this); \
-        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
-        this->addEventContainer(eventname, containername); \
-    } \
-    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
-    containername->process(this, event)
-
+/**
+    @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__ */
Index: de/trunk/src/libraries/core/Factory.cc
===================================================================
--- /code/trunk/src/libraries/core/Factory.cc	(revision 5928)
+++ 	(revision )
@@ -1,129 +1,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 Factory class.
-*/
-
-#include "Factory.h"
-
-#include "util/Debug.h"
-#include "Identifier.h"
-#include "BaseObject.h"
-
-namespace orxonox
-{
-    /**
-        @brief Returns the Identifier with a given name.
-        @param name The name of the wanted Identifier
-        @return The Identifier
-    */
-    Identifier* Factory::getIdentifier(const std::string& name)
-    {
-        std::map<std::string, Identifier*>::const_iterator it = getFactoryPointer()->identifierStringMap_.find(name);
-        if (it != getFactoryPointer()->identifierStringMap_.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* Factory::getIdentifier(const uint32_t id)
-    {
-        std::map<uint32_t, Identifier*>::const_iterator it = getFactoryPointer()->identifierNetworkIDMap_.find(id);
-        if (it != getFactoryPointer()->identifierNetworkIDMap_.end())
-            return it->second;
-        else
-            return 0;
-    }
-
-    /**
-        @brief Adds a new Identifier to both maps.
-        @param name The name of the identifier
-        @param identifier The identifier to add
-    */
-    void Factory::add(const std::string& name, Identifier* identifier)
-    {
-        getFactoryPointer()->identifierStringMap_[name] = identifier;
-        getFactoryPointer()->identifierNetworkIDMap_[identifier->getNetworkID()] = identifier;
-    }
-
-    /**
-        @brief Removes the entry with the old network ID and adds a new one.
-        @param identifier The identifier to change
-        @param oldID The old networkID
-        @param newID The new networkID
-    */
-    void Factory::changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID)
-    {
-//        getFactoryPointer()->identifierNetworkIDMap_.erase(oldID);
-        getFactoryPointer()->identifierNetworkIDMap_[newID] = identifier;
-    }
-
-    /**
-        @brief Cleans the NetworkID map (needed on clients for correct initialization)
-    */
-    void Factory::cleanNetworkIDs()
-    {
-        getFactoryPointer()->identifierNetworkIDMap_.clear();
-    }
-
-    /**
-        @brief Creates the class-hierarchy by creating and destroying one object of each type.
-    */
-    void Factory::createClassHierarchy()
-    {
-        COUT(3) << "*** Factory: Create class-hierarchy" << std::endl;
-        std::map<std::string, Identifier*>::iterator it;
-        it = getFactoryPointer()->identifierStringMap_.begin();
-        (*getFactoryPointer()->identifierStringMap_.begin()).second->startCreatingHierarchy();
-        for (it = getFactoryPointer()->identifierStringMap_.begin(); it != getFactoryPointer()->identifierStringMap_.end(); ++it)
-        {
-            // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
-            BaseObject* temp = (*it).second->fabricate(0);
-            delete temp;
-        }
-        (*getFactoryPointer()->identifierStringMap_.begin()).second->stopCreatingHierarchy();
-        COUT(3) << "*** Factory: Finished class-hierarchy creation" << std::endl;
-    }
-
-    /**
-        @brief Ensures the Factory gets created in the right moment.
-        @return The Factory.
-    */
-    Factory* Factory::getFactoryPointer()
-    {
-      static Factory theOneAndOnlyFactoryInstance = Factory();
-      return &theOneAndOnlyFactoryInstance;
-    }
-}
Index: de/trunk/src/libraries/core/Factory.h
===================================================================
--- /code/trunk/src/libraries/core/Factory.h	(revision 5928)
+++ 	(revision )
@@ -1,101 +1,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 Definition of the Factory and the BaseFactory class.
-
-    The Factory is a singleton, containing two maps to map either the name or the network ID
-    of a class with the corresponding Identifier.
-
-    Usage:
-    ID(classname) or ID(networkID) returns the corresponding Identifier.
-
-
-    BaseObject is the parent of ClassFactory which is defined in ClassFactory.h.
-    It can't be defined in ClassFactory.h, because of circular dependencies.
-*/
-
-#ifndef _Factory_H__
-#define _Factory_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-
-namespace orxonox
-{
-    // ###############################
-    // ###         Factory         ###
-    // ###############################
-    //! The Factory is used to map the name or the network ID of a class with its Identifier.
-    class _CoreExport Factory
-    {
-        public:
-            static Identifier* getIdentifier(const std::string& name);
-            static Identifier* getIdentifier(const uint32_t id);
-            static void add(const std::string& name, Identifier* identifier);
-            static void changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID);
-            static void cleanNetworkIDs();
-            static void createClassHierarchy();
-
-            static Factory* getFactoryPointer();    // avoid overriding order problem in the static intialisation process
-
-            /** @brief Returns the factory-map. */
-            static const std::map<std::string, Identifier*>& getFacbtoryMap()
-                { return Factory::getFactoryPointer()->identifierStringMap_; }
-            /** @brief Returns the begin-iterator of the factory-map. */
-            static std::map<std::string, Identifier*>::const_iterator getFactoryMapBegin()
-                { return Factory::getFactoryPointer()->identifierStringMap_.begin(); }
-            /** @brief Returns the end-iterator of the factory-map. */
-            static std::map<std::string, Identifier*>::const_iterator getFactoryMapEnd()
-                { return Factory::getFactoryPointer()->identifierStringMap_.end(); }
-
-        private:
-            Factory() {}                            // don't create
-            Factory(const Factory& factory);        // don't copy
-            ~Factory() {}                           // don't delete
-
-            std::map<std::string, Identifier*> identifierStringMap_;            //!< The map, mapping the name with the Identifier
-            std::map<uint32_t, Identifier*> identifierNetworkIDMap_;        //!< The map, mapping the network ID with the Identifier
-    };
-
-    // ###############################
-    // ###       BaseFactory       ###
-    // ###############################
-    //! Base-class of ClassFactory. Has to be defined separate because of circular dependencies.
-    class _CoreExport BaseFactory
-    {
-        public:
-            virtual BaseObject* fabricate(BaseObject* creator) = 0;
-            virtual ~BaseFactory() {};
-    };
-}
-
-#endif /* _Factory_H__ */
Index: /code/trunk/src/libraries/core/Functor.h
===================================================================
--- /code/trunk/src/libraries/core/Functor.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Functor.h	(revision 5929)
@@ -191,29 +191,35 @@
 
 
-#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams
-#define FUNCTOR_TEMPLATE000
-#define FUNCTOR_TEMPLATE001 template <class P1>
-#define FUNCTOR_TEMPLATE002 template <class P1, class P2>
-#define FUNCTOR_TEMPLATE003 template <class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE004 template <class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE005 template <class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE010 template <class R>
-#define FUNCTOR_TEMPLATE011 template <class R, class P1>
-#define FUNCTOR_TEMPLATE012 template <class R, class P1, class P2>
-#define FUNCTOR_TEMPLATE013 template <class R, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE014 template <class R, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE015 template <class R, class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE100 template <class T>
-#define FUNCTOR_TEMPLATE101 template <class T, class P1>
-#define FUNCTOR_TEMPLATE102 template <class T, class P1, class P2>
-#define FUNCTOR_TEMPLATE103 template <class T, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE104 template <class T, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE105 template <class T, class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE110 template <class T, class R>
-#define FUNCTOR_TEMPLATE111 template <class T, class R, class P1>
-#define FUNCTOR_TEMPLATE112 template <class T, class R, class P1, class P2>
-#define FUNCTOR_TEMPLATE113 template <class T, class R, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE114 template <class T, class R, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE115 template <class T, class R, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams, additionalobject) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams(additionalobject)
+#define FUNCTOR_TEMPLATE000(additionalobject)
+#define FUNCTOR_TEMPLATE001(additionalobject) template <class P1>
+#define FUNCTOR_TEMPLATE002(additionalobject) template <class P1, class P2>
+#define FUNCTOR_TEMPLATE003(additionalobject) template <class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE004(additionalobject) template <class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE005(additionalobject) template <class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE010(additionalobject) template <class R>
+#define FUNCTOR_TEMPLATE011(additionalobject) template <class R, class P1>
+#define FUNCTOR_TEMPLATE012(additionalobject) template <class R, class P1, class P2>
+#define FUNCTOR_TEMPLATE013(additionalobject) template <class R, class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE014(additionalobject) template <class R, class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE015(additionalobject) template <class R, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE100(additionalobject) template <class T FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE101(additionalobject) template <class T, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE102(additionalobject) template <class T, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE103(additionalobject) template <class T, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE104(additionalobject) template <class T, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE105(additionalobject) template <class T, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE110(additionalobject) template <class T, class R FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE111(additionalobject) template <class T, class R, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE112(additionalobject) template <class T, class R, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE113(additionalobject) template <class T, class R, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE114(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE115(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+
+
+
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT##additionalobject
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT0
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT1 , class O
 
 
@@ -317,5 +323,5 @@
 
 #define CREATE_STATIC_FUNCTOR(returnvalue, numparams) \
-    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
     class FunctorStatic##returnvalue##numparams : public FunctorStatic \
     { \
@@ -347,5 +353,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
     inline FunctorStatic##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(0, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
     { \
@@ -358,5 +364,5 @@
 
 #define CREATE_MEMBER_FUNCTOR(returnvalue, numparams) \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     class FunctorMember##returnvalue##numparams : public FunctorMember<T> \
     { \
@@ -391,5 +397,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     class FunctorConstMember##returnvalue##numparams : public FunctorMember<T> \
     { \
@@ -423,5 +429,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
     { \
@@ -430,8 +436,25 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const) \
     { \
         return new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+    } \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
+    inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)), O* object) \
+    { \
+        FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+        functor->setObject(object); \
+        return functor; \
+    } \
+    \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
+    inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const, O* object) \
+    { \
+        FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+        functor->setObject(object); \
+        return functor; \
     }
 
Index: /code/trunk/src/libraries/core/GUIManager.cc
===================================================================
--- /code/trunk/src/libraries/core/GUIManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/GUIManager.cc	(revision 5929)
@@ -49,10 +49,11 @@
 #endif
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
 #include "util/OrxAssert.h"
 #include "Core.h"
-#include "Clock.h"
 #include "LuaState.h"
+#include "PathConfig.h"
 #include "Resource.h"
 
@@ -62,5 +63,5 @@
     {
     public:
-	    void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
+        void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
         {
             int orxonoxLevel = CEGUI::Standard;
@@ -100,4 +101,5 @@
         : renderWindow_(renderWindow)
         , resourceProvider_(0)
+        , camera_(NULL)
     {
         using namespace CEGUI;
@@ -116,5 +118,5 @@
         // Create our own logger to specify the filepath
         std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
-        ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
+        ceguiLogger->setLogFilename(PathConfig::getLogPathString() + "cegui.log");
         // set the log level according to ours (translate by subtracting 1)
         ceguiLogger->setLoggingLevel(
@@ -173,4 +175,5 @@
     void GUIManager::setCamera(Ogre::Camera* camera)
     {
+        this->camera_ = camera;
         if (camera == NULL)
             this->guiRenderer_->setTargetSceneManager(0);
Index: /code/trunk/src/libraries/core/GUIManager.h
===================================================================
--- /code/trunk/src/libraries/core/GUIManager.h	(revision 5928)
+++ /code/trunk/src/libraries/core/GUIManager.h	(revision 5929)
@@ -71,4 +71,5 @@
 
         void setCamera(Ogre::Camera* camera);
+        Ogre::Camera* getCamera() { return this->camera_; }
 
         static GUIManager* getInstancePtr() { return singletonPtr_s; }
@@ -101,4 +102,5 @@
         CEGUI::Logger*                       ceguiLogger_;      //!< CEGUI's logger to be able to log CEGUI errors in our log
         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
Index: /code/trunk/src/libraries/core/Game.cc
===================================================================
--- /code/trunk/src/libraries/core/Game.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Game.cc	(revision 5929)
@@ -38,4 +38,5 @@
 #include <boost/weak_ptr.hpp>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
@@ -43,5 +44,4 @@
 #include "util/Sleep.h"
 #include "util/SubString.h"
-#include "Clock.h"
 #include "CommandLine.h"
 #include "ConsoleCommand.h"
@@ -57,4 +57,10 @@
         { Game::getInstance().stop(); }
     SetConsoleCommandShortcutExternAlias(stop_game, "exit");
+    static void printFPS()
+        { COUT(0) << Game::getInstance().getAvgFPS() << std::endl; }
+    SetConsoleCommandShortcutExternAlias(printFPS, "printFPS");
+    static void printTickTime()
+        { COUT(0) << Game::getInstance().getAvgTickTime() << std::endl; }
+    SetConsoleCommandShortcutExternAlias(printTickTime, "printTickTime");
 
     std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
@@ -111,5 +117,5 @@
     Game::Game(const std::string& cmdLine)
         // Destroy factories before the Core!
-        : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
+        : gsFactoryDestroyer_(Game::GameStateFactory::getFactories(), &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
     {
         this->bAbort_ = false;
@@ -410,4 +416,6 @@
                 requestedNodes.push_back(currentNode);
             }
+            if (currentNode == NULL)
+                requestedNodes.clear();
         }
 
@@ -457,10 +465,10 @@
     {
         // Split string into pieces of the form whitespacesText
-        std::vector<std::pair<std::string, unsigned> > stateStrings;
+        std::vector<std::pair<std::string, int> > stateStrings;
         size_t pos = 0;
         size_t startPos = 0;
         while (pos < str.size())
         {
-            unsigned indentation = 0;
+            int indentation = 0;
             while(pos < str.size() && str[pos] == ' ')
                 ++indentation, ++pos;
@@ -470,45 +478,53 @@
             stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
         }
-        unsigned int currentLevel = 0;
-        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
-        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
-        {
-            std::string newStateName = it->first;
-            unsigned newLevel = it->second + 1; // empty root is 0
-            if (!this->checkState(newStateName))
-                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
-            if (newStateName == this->rootStateNode_->name_)
+        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> newNode(new GameStateTreeNode);
-            newNode->name_ = newStateName;
-
-            if (newLevel <= currentLevel)
-            {
-                do
-                    currentNode = currentNode->parent_.lock();
-                while (newLevel <= --currentLevel);
-            }
-            if (newLevel == currentLevel + 1)
-            {
-                // Add the child
-                newNode->parent_ = currentNode;
-                currentNode->children_.push_back(newNode);
-            }
-            else
-                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
-            currentNode = newNode;
-            currentLevel = newLevel;
-        }
-    }
-
-    /*** Internal ***/
+            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::bShowsGraphics_s)
+        if (!GameMode::showsGraphics())
         {
             core_->loadGraphics();
             Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
-            GameMode::bShowsGraphics_s = true;
 
             // Construct all the GameStates that require graphics
@@ -531,5 +547,5 @@
     void Game::unloadGraphics()
     {
-        if (GameMode::bShowsGraphics_s)
+        if (GameMode::showsGraphics())
         {
             // Destroy all the GameStates that require graphics
@@ -543,5 +559,4 @@
 
             core_->unloadGraphics();
-            GameMode::bShowsGraphics_s = false;
         }
     }
@@ -607,10 +622,14 @@
     }
 
-    std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
+    /*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 = factories_s.find(info.className);
-        assert(it != factories_s.end());
+        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
+        assert(it != getFactories().end());
         return it->second->fabricateInternal(info);
     }
Index: /code/trunk/src/libraries/core/Game.h
===================================================================
--- /code/trunk/src/libraries/core/Game.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Game.h	(revision 5929)
@@ -117,8 +117,8 @@
             template <class T>
             static void createFactory(const std::string& className)
-                { factories_s[className].reset(new TemplateGameStateFactory<T>()); }
+                { getFactories()[className].reset(new TemplateGameStateFactory<T>()); }
 
             virtual shared_ptr<GameState> fabricateInternal(const GameStateInfo& info) = 0;
-            static std::map<std::string, shared_ptr<GameStateFactory> > factories_s;
+            static std::map<std::string, shared_ptr<GameStateFactory> >& getFactories();
         };
         template <class T>
@@ -143,4 +143,5 @@
         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);
Index: /code/trunk/src/libraries/core/GameMode.cc
===================================================================
--- /code/trunk/src/libraries/core/GameMode.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/GameMode.cc	(revision 5929)
@@ -27,9 +27,4 @@
  */
 
-/**
-    @file
-    @brief Implementation of the GameMode class.
-*/
-
 #include "GameMode.h"
 
@@ -37,4 +32,5 @@
 {
     bool GameMode::bShowsGraphics_s = false;
+    bool GameMode::bPlaysSound_s    = false;
     bool GameMode::bHasServer_s     = false;
     bool GameMode::bIsClient_s      = false;
Index: /code/trunk/src/libraries/core/GameMode.h
===================================================================
--- /code/trunk/src/libraries/core/GameMode.h	(revision 5928)
+++ /code/trunk/src/libraries/core/GameMode.h	(revision 5929)
@@ -41,8 +41,9 @@
     class _CoreExport GameMode
     {
-        friend class Game;
+        friend class Core;
 
         public:
             static bool showsGraphics() { return bShowsGraphics_s; }
+            static bool playsSound()    { return bPlaysSound_s; }
             static bool hasServer()     { return bHasServer_s; }
             static bool isClient()      { return bIsClient_s; }
@@ -50,4 +51,5 @@
             static bool isMaster()      { return bIsMaster_s; }
 
+            static void setPlaysSound   (bool val) { bPlaysSound_s    = val; }
             static void setHasServer    (bool val) { bHasServer_s     = val; updateIsMaster(); }
             static void setIsClient     (bool val) { bIsClient_s      = val; updateIsMaster(); }
@@ -65,4 +67,5 @@
 
             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 bHasServer_s;                       //!< global variable that tells whether this is a server
             static bool bIsClient_s;
Index: /code/trunk/src/libraries/core/GameState.h
===================================================================
--- /code/trunk/src/libraries/core/GameState.h	(revision 5928)
+++ /code/trunk/src/libraries/core/GameState.h	(revision 5929)
@@ -40,4 +40,5 @@
 #include <map>
 #include <string>
+#include "util/UtilPrereqs.h"
 
 namespace orxonox
Index: /code/trunk/src/libraries/core/GraphicsManager.cc
===================================================================
--- /code/trunk/src/libraries/core/GraphicsManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/GraphicsManager.cc	(revision 5929)
@@ -48,16 +48,16 @@
 
 #include "SpecialConfig.h"
+#include "util/Clock.h"
 #include "util/Exception.h"
 #include "util/StringUtils.h"
 #include "util/SubString.h"
-#include "Clock.h"
 #include "ConsoleCommand.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"
@@ -102,5 +102,5 @@
 
         // At first, add the root paths of the data directories as resource locations
-        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
+        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem", "dataRoot", false);
         // Load resources
         resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
@@ -109,7 +109,7 @@
 
         // Only for development runs
-        if (Core::isDevelopmentRun())
-        {
-            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
+        if (PathConfig::isDevelopmentRun())
+        {
+            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
             extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
             extResources_->setLuaSupport(false);
@@ -130,6 +130,13 @@
     GraphicsManager::~GraphicsManager()
     {
+        Loader::unload(debugOverlay_.get());
+
         Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
         // TODO: Destroy the console command
+
+        // Undeclare the resources
+        Loader::unload(resources_.get());
+        if (PathConfig::isDevelopmentRun())
+            Loader::unload(extResources_.get());
     }
 
@@ -241,6 +248,6 @@
         }
 
-        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
-        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
+        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
+        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
 
         // create a new logManager
@@ -313,9 +320,24 @@
 
         // add console commands
-        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
-        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
+        ccPrintScreen_ = createConsoleCommand(createFunctor(&GraphicsManager::printScreen, this), "printScreen");
         CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
     }
 
+    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::update(const Clock& time)
     {
@@ -418,5 +440,5 @@
         assert(this->renderWindow_);
        
-        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
+        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".jpg");
     }
 }
Index: /code/trunk/src/libraries/core/GraphicsManager.h
===================================================================
--- /code/trunk/src/libraries/core/GraphicsManager.h	(revision 5928)
+++ /code/trunk/src/libraries/core/GraphicsManager.h	(revision 5929)
@@ -71,4 +71,5 @@
 
         void upgradeToGraphics();
+        void loadDebugOverlay();
         bool rendererLoaded() const { return renderWindow_ != NULL; }
 
@@ -99,7 +100,8 @@
         Ogre::Viewport*     viewport_;                 //!< default full size viewport
 
-        // XML files for the resources
+        // 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
Index: /code/trunk/src/libraries/core/Identifier.cc
===================================================================
--- /code/trunk/src/libraries/core/Identifier.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Identifier.cc	(revision 5929)
@@ -39,5 +39,5 @@
 #include "ConfigValueContainer.h"
 #include "ConsoleCommand.h"
-#include "Factory.h"
+#include "ClassFactory.h"
 #include "XMLPort.h"
 
@@ -61,12 +61,9 @@
         this->bSetName_ = false;
         this->factory_ = 0;
-        this->bLoadable_ = true;
+        this->bLoadable_ = false;
 
         this->bHasConfigValues_ = false;
         this->bHasConsoleCommands_ = false;
 
-        this->children_ = new std::set<const Identifier*>();
-        this->directChildren_ = new std::set<const Identifier*>();
-
         // Default network ID is the class ID
         this->networkID_ = this->classID_;
@@ -78,6 +75,4 @@
     Identifier::~Identifier()
     {
-        delete this->children_;
-        delete this->directChildren_;
         delete this->objects_;
 
@@ -118,5 +113,5 @@
             // There is already an entry: return it and delete the proposal
             delete proposal;
-            return (*it).second;
+            return it->second;
         }
         else
@@ -165,5 +160,5 @@
             {
                 // Tell the parent we're one of it's children
-                (*it)->getChildrenIntern().insert((*it)->getChildrenIntern().end(), this);
+                (*it)->children_.insert((*it)->children_.end(), this);
 
                 // Erase all parents of our parent from our direct-parent-list
@@ -187,5 +182,5 @@
             {
                 // Tell the parent we're one of it's direct children
-                (*it)->getDirectChildrenIntern().insert((*it)->getDirectChildrenIntern().end(), this);
+                (*it)->directChildren_.insert((*it)->directChildren_.end(), this);
 
                 // Create the super-function dependencies
@@ -196,4 +191,24 @@
 
     /**
+        @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.
     */
@@ -214,6 +229,7 @@
             this->name_ = name;
             this->bSetName_ = true;
-            Identifier::getIdentifierMapIntern()[name] = this;
-            Identifier::getLowercaseIdentifierMapIntern()[getLowercase(name)] = this;
+            Identifier::getStringIdentifierMapIntern()[name] = this;
+            Identifier::getLowercaseStringIdentifierMapIntern()[getLowercase(name)] = this;
+            Identifier::getIDIdentifierMapIntern()[this->networkID_] = this;
         }
     }
@@ -235,15 +251,16 @@
             COUT(1) << "Aborting..." << std::endl;
             abort();
-            return NULL;
-        }
-    }
-
-    /**
-        @brief Sets the network ID to a new value and changes the entry in the Factory.
+            return 0;
+        }
+    }
+
+    /**
+        @brief Sets the network ID to a new value and changes the entry in the ID-Identifier-map.
         @param id The new network ID
     */
     void Identifier::setNetworkID(uint32_t id)
     {
-        Factory::changeNetworkID(this, this->networkID_, id);
+//        Identifier::getIDIdentifierMapIntern().erase(this->networkID_);
+        Identifier::getIDIdentifierMapIntern()[id] = this;
         this->networkID_ = id;
     }
@@ -291,5 +308,5 @@
     bool Identifier::isParentOf(const Identifier* identifier) const
     {
-        return (this->children_->find(identifier) != this->children_->end());
+        return (this->children_.find(identifier) != this->children_.end());
     }
 
@@ -300,12 +317,12 @@
     bool Identifier::isDirectParentOf(const Identifier* identifier) const
     {
-        return (this->directChildren_->find(identifier) != this->directChildren_->end());
-    }
-
-    /**
-        @brief Returns the map that stores all Identifiers.
+        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::getIdentifierMapIntern()
+    std::map<std::string, Identifier*>& Identifier::getStringIdentifierMapIntern()
     {
         static std::map<std::string, Identifier*> identifierMap;
@@ -314,11 +331,71 @@
 
     /**
-        @brief Returns the map that stores all Identifiers.
+        @brief Returns the map that stores all Identifiers with their names in lowercase.
         @return The map
     */
-    std::map<std::string, Identifier*>& Identifier::getLowercaseIdentifierMapIntern()
+    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();
     }
 
@@ -351,5 +428,5 @@
         std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_.find(varname);
         if (it != configValues_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -365,5 +442,5 @@
         std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_LC_.find(varname);
         if (it != configValues_LC_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -404,5 +481,5 @@
         std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_.find(name);
         if (it != this->consoleCommands_.end())
-            return (*it).second;
+            return it->second;
         else
             return 0;
@@ -418,5 +495,5 @@
         std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_LC_.find(name);
         if (it != this->consoleCommands_LC_.end())
-            return (*it).second;
+            return it->second;
         else
             return 0;
@@ -432,5 +509,5 @@
         std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
         if (it != this->xmlportParamContainers_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -463,5 +540,5 @@
         std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
         if (it != this->xmlportObjectContainers_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -483,35 +560,4 @@
 
         this->xmlportObjectContainers_[sectionname] = container;
-    }
-
-    /**
-        @brief Returns a XMLPortEventContainer that attaches an event to this class.
-        @param sectionname The name of the section that contains the event
-        @return The container
-    */
-    XMLPortObjectContainer* Identifier::getXMLPortEventContainer(const std::string& eventname)
-    {
-        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
-        if (it != this->xmlportEventContainers_.end())
-            return ((*it).second);
-        else
-            return 0;
-    }
-
-    /**
-        @brief Adds a new XMLPortEventContainer that attaches an event to this class.
-        @param sectionname The name of the section that contains the event
-        @param container The container
-    */
-    void Identifier::addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container)
-    {
-        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
-        if (it != this->xmlportEventContainers_.end())
-        {
-            COUT(2) << "Warning: Overwriting XMLPortEventContainer in class " << this->getName() << "." << std::endl;
-            delete (it->second);
-        }
-
-        this->xmlportEventContainers_[eventname] = container;
     }
 
@@ -525,5 +571,9 @@
     {
         for (std::set<const Identifier*>::const_iterator it = list.begin(); it != list.end(); ++it)
-            out << (*it)->getName() << " ";
+        {
+            if (it != list.begin())
+                out << " ";
+            out << (*it)->getName();
+        }
 
         return out;
Index: /code/trunk/src/libraries/core/Identifier.h
===================================================================
--- /code/trunk/src/libraries/core/Identifier.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Identifier.h	(revision 5929)
@@ -29,5 +29,5 @@
 /**
     @file
-    @brief Definition of the Identifier, ClassIdentifier and SubclassIdentifier classes, implementation of the ClassIdentifier and SubclassIdentifier classes.
+    @brief Definition of the Identifier class, definition and implementation of the ClassIdentifier class.
 
     The Identifier contains all needed information about the class it belongs to:
@@ -45,7 +45,4 @@
 
     Every Identifier is in fact a ClassIdentifier, but they are derived from Identifier.
-
-    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.
 */
 
@@ -90,14 +87,31 @@
     class _CoreExport Identifier
     {
-        template <class T>
-        friend class SubclassIdentifier;
-
-        friend class Factory;
-
         public:
+            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
+            inline const std::string& getName() const { return this->name_; }
+            void setName(const std::string& name);
+
+            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
+            inline const uint32_t getNetworkID() const { return this->networkID_; }
+            void setNetworkID(uint32_t id);
+
+            /** @brief Returns the unique ID of the class */
+            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
+
+            /** @brief Returns the list of all existing objects of this class. @return The list */
+            inline ObjectListBase* getObjects() const { return this->objects_; }
+
             /** @brief Sets the Factory. @param factory The factory to assign */
-            inline void addFactory(BaseFactory* factory) { this->factory_ = factory; }
+            inline void addFactory(Factory* factory) { this->factory_ = factory; }
+            /** @brief Returns true if the Identifier has a Factory. */
+            inline bool hasFactory() const { return (this->factory_ != 0); }
 
             BaseObject* fabricate(BaseObject* creator);
+
+            /** @brief Returns true if the class can be loaded through XML. */
+            inline bool isLoadable() const { return this->bLoadable_; }
+            /** @brief 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;
@@ -107,18 +121,12 @@
             bool isDirectParentOf(const Identifier* identifier) const;
 
-            /** @brief Returns true if the class can be loaded through XML. */
-            inline bool isLoadable() const { return this->bLoadable_; }
-            /** @brief Set the class to be loadable through XML or not. */
-            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
-
-            /** @brief Returns the list of all existing objects of this class. @return The list */
-            inline ObjectListBase* getObjects() const
-                { return this->objects_; }
-
-            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
-            inline const std::string& getName() const { return this->name_; }
-            void setName(const std::string& name);
-
-            virtual void updateConfigValues(bool updateChildren = true) const = 0;
+
+            /////////////////////////////
+            ////// Class Hierarchy //////
+            /////////////////////////////
+            static void createClassHierarchy();
+
+            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
+            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
 
             /** @brief Returns the parents of the class the Identifier belongs to. @return The list of all parents */
@@ -130,9 +138,9 @@
 
             /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
-            inline const std::set<const Identifier*>& getChildren() const { return (*this->children_); }
+            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
             /** @brief Returns the begin-iterator of the children-list. @return The begin-iterator */
-            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_->begin(); }
+            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
             /** @brief Returns the end-iterator of the children-list. @return The end-iterator */
-            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_->end(); }
+            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
 
             /** @brief Returns the direct parents of the class the Identifier belongs to. @return The list of all direct parents */
@@ -144,25 +152,51 @@
 
             /** @brief Returns the direct children the class the Identifier belongs to. @return The list of all direct children */
-            inline const std::set<const Identifier*>& getDirectChildren() const { return (*this->directChildren_); }
+            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
             /** @brief Returns the begin-iterator of the direct-children-list. @return The begin-iterator */
-            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_->begin(); }
+            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
             /** @brief Returns the end-iterator of the direct-children-list. @return The end-iterator */
-            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_->end(); }
-
-
-            /** @brief Returns the map that stores all Identifiers. @return The map */
-            static inline const std::map<std::string, Identifier*>& getIdentifierMap() { return Identifier::getIdentifierMapIntern(); }
-            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapBegin() { return Identifier::getIdentifierMap().begin(); }
-            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapEnd() { return Identifier::getIdentifierMap().end(); }
+            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();
+
+            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
+            static inline const std::map<std::string, Identifier*>& getStringIdentifierMap() { return Identifier::getStringIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapBegin() { return Identifier::getStringIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapEnd() { return Identifier::getStringIdentifierMap().end(); }
 
             /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
-            static inline const std::map<std::string, Identifier*>& getLowercaseIdentifierMap() { return Identifier::getLowercaseIdentifierMapIntern(); }
+            static inline const std::map<std::string, Identifier*>& getLowercaseStringIdentifierMap() { return Identifier::getLowercaseStringIdentifierMapIntern(); }
             /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapBegin() { return Identifier::getLowercaseIdentifierMap().begin(); }
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapBegin() { return Identifier::getLowercaseStringIdentifierMap().begin(); }
             /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapEnd() { return Identifier::getLowercaseIdentifierMap().end(); }
-
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapEnd() { return Identifier::getLowercaseStringIdentifierMap().end(); }
+
+            /** @brief Returns the map that stores all Identifiers with their IDs. @return The map */
+            static inline const std::map<uint32_t, Identifier*>& getIDIdentifierMap() { return Identifier::getIDIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their IDs. @return The const_iterator */
+            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapBegin() { return Identifier::getIDIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their IDs. @return The const_iterator */
+            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapEnd() { return Identifier::getIDIdentifierMap().end(); }
+
+
+            /////////////////////////
+            ///// Config Values /////
+            /////////////////////////
+            virtual void updateConfigValues(bool updateChildren = true) const = 0;
+
+            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
+            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
 
             /** @brief Returns the map that stores all config values. @return The const_iterator */
@@ -180,4 +214,14 @@
             inline std::map<std::string, ConfigValueContainer*>::const_iterator getLowercaseConfigValueMapEnd() const { return this->configValues_LC_.end(); }
 
+            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
+            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
+            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
+
+
+            ////////////////////////////
+            ///// Console Commands /////
+            ////////////////////////////
+            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
+            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
 
             /** @brief Returns the map that stores all console commands. @return The const_iterator */
@@ -195,4 +239,12 @@
             inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandMapEnd() const { return this->consoleCommands_LC_.end(); }
 
+            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
+            ConsoleCommand* getConsoleCommand(const std::string& name) const;
+            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
+
+
+            ///////////////////
+            ///// XMLPort /////
+            ///////////////////
             /** @brief Returns the map that stores all XMLPort params. @return The const_iterator */
             inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
@@ -209,32 +261,4 @@
             inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
 
-            /** @brief Returns the map that stores all XMLPort events. @return The const_iterator */
-            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortEventMap() const { return this->xmlportEventContainers_; }
-            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort events. @return The const_iterator */
-            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapBegin() const { return this->xmlportEventContainers_.begin(); }
-            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort events. @return The const_iterator */
-            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapEnd() const { return this->xmlportEventContainers_.end(); }
-
-            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
-            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
-            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
-            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
-
-            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
-            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
-
-            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
-            inline const uint32_t getNetworkID() const { return this->networkID_; }
-
-            /** @brief Sets the network ID to a new value. @param id The new value */
-            void setNetworkID(uint32_t id);
-
-            /** @brief Returns the unique ID of the class */
-            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
-
-            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
-            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
-            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
-
             void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
             XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
@@ -243,14 +267,4 @@
             XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
 
-            void addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container);
-            XMLPortObjectContainer* getXMLPortEventContainer(const std::string& eventname);
-
-            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
-            ConsoleCommand* getConsoleCommand(const std::string& name) const;
-            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
-
-            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
-
-            static void destroyAllIdentifiers();
 
         protected:
@@ -262,34 +276,25 @@
             virtual void createSuperFunctionCaller() const = 0;
 
-            /** @brief Returns the map that stores all Identifiers. @return The map */
-            static std::map<std::string, Identifier*>& getIdentifierMapIntern();
+            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
+
+            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
+            static std::map<std::string, Identifier*>& getStringIdentifierMapIntern();
             /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
-            static std::map<std::string, Identifier*>& getLowercaseIdentifierMapIntern();
+            static std::map<std::string, Identifier*>& getLowercaseStringIdentifierMapIntern();
+            /** @brief Returns the map that stores all Identifiers with their network IDs. @return The map */
+            static std::map<uint32_t, Identifier*>& getIDIdentifierMapIntern();
 
             /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
-            inline std::set<const Identifier*>& getChildrenIntern() const { return (*this->children_); }
+            inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
             /** @brief Returns the direct children of the class the Identifier belongs to. @return The list of all direct children */
-            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return (*this->directChildren_); }
+            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
 
             ObjectListBase* objects_;                                      //!< The list of all objects of this class
 
         private:
-            /**
-                @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents.
-            */
-            inline static void startCreatingHierarchy()
-            {
-                hierarchyCreatingCounter_s++;
-                COUT(4) << "*** Identifier: Increased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
-            }
-
-            /**
-                @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents.
-            */
-            inline static void stopCreatingHierarchy()
-            {
-                hierarchyCreatingCounter_s--;
-                COUT(4) << "*** Identifier: Decreased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
-            }
+            /** @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents. */
+            inline static void startCreatingHierarchy() { hierarchyCreatingCounter_s++; }
+            /** @brief 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();
@@ -298,8 +303,8 @@
 
             std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
-            std::set<const Identifier*>* children_;                        //!< The children 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
-            std::set<const Identifier*>* directChildren_;                  //!< The direct children 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)
@@ -307,5 +312,5 @@
             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
-            BaseFactory* factory_;                                         //!< The Factory, able to create new objects of the given class (if available)
+            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
@@ -323,5 +328,4 @@
             std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
             std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
-            std::map<std::string, XMLPortObjectContainer*> xmlportEventContainers_;    //!< All events
     };
 
@@ -348,6 +352,6 @@
 
         public:
-            static ClassIdentifier<T> *getIdentifier();
-            static ClassIdentifier<T> *getIdentifier(const std::string& name);
+            static ClassIdentifier<T>* getIdentifier();
+            static ClassIdentifier<T>* getIdentifier(const std::string& name);
 
             bool initialiseObject(T* object, const std::string& className, bool bRootClass);
@@ -380,6 +384,6 @@
     inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
     {
-        // check if the static field has already been filled
-        if (ClassIdentifier<T>::classIdentifier_s == 0)
+        // check if the Identifier already exists
+        if (!ClassIdentifier<T>::classIdentifier_s)
             ClassIdentifier<T>::initialiseIdentifier();
 
@@ -508,153 +512,4 @@
 #endif
     }
-
-
-    // ###############################
-    // ###   SubclassIdentifier    ###
-    // ###############################
-    //! 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 aborts.
-        Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
-    */
-    template <class T>
-    class SubclassIdentifier
-    {
-        public:
-            /**
-                @brief Constructor: Automaticaly assigns the Identifier of the given class.
-            */
-            SubclassIdentifier()
-            {
-                this->identifier_ = ClassIdentifier<T>::getIdentifier();
-            }
-
-            /**
-                @brief Copyconstructor: Assigns the given Identifier.
-                @param identifier The Identifier
-            */
-            SubclassIdentifier(Identifier* identifier)
-            {
-                this->operator=(identifier);
-            }
-
-            /**
-                @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;
-            }
-
-            /**
-                @brief Overloading of the * operator: returns the assigned identifier.
-            */
-            inline Identifier* operator*() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Overloading of the -> operator: returns the assigned identifier.
-            */
-            inline Identifier* operator->() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
-            */
-            inline operator Identifier*() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
-                @return The new object
-            */
-            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;
-                        COUT(1) << "Aborting..." << 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;
-                    }
-
-                    assert(false);
-                    return 0;
-                }
-            }
-
-            /** @brief Returns the assigned identifier. @return The identifier */
-            inline Identifier* getIdentifier() const
-                { return this->identifier_; }
-
-//            /** @brief Returns true, if the assigned identifier is at least of the given type. @param identifier The identifier to compare with */
-//            inline bool isA(const Identifier* identifier) const
-//                { return this->identifier_->isA(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is exactly of the given type. @param identifier The identifier to compare with */
-//            inline bool isExactlyA(const Identifier* identifier) const
-//                { return this->identifier_->isExactlyA(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a child of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isChildOf(const Identifier* identifier) const
-//                { return this->identifier_->isChildOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a direct child of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isDirectChildOf(const Identifier* identifier) const
-//                { return this->identifier_->isDirectChildOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a parent of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isParentOf(const Identifier* identifier) const
-//                { return this->identifier_->isParentOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a direct parent of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isDirectParentOf(const Identifier* identifier) const
-//                { return this->identifier_->isDirectParentOf(identifier); }
-
-        private:
-            Identifier* identifier_;            //!< The assigned identifier
-    };
 }
 
Index: /code/trunk/src/libraries/core/Iterator.h
===================================================================
--- /code/trunk/src/libraries/core/Iterator.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Iterator.h	(revision 5929)
@@ -167,5 +167,4 @@
 
                 return (*this);
-                return *this;
             }
 
@@ -193,6 +192,5 @@
             inline const Iterator<T>& operator++()
             {
-                if (this->element_)
-                    this->element_ = this->element_->next_;
+                this->element_ = this->element_->next_;
                 return *this;
             }
@@ -205,6 +203,5 @@
             {
                 Iterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = this->element_->next_;
+                this->element_ = this->element_->next_;
                 return copy;
             }
@@ -216,6 +213,5 @@
             inline const Iterator<T>& operator--()
             {
-                if (this->element_)
-                    this->element_ = this->element_->prev_;
+                this->element_ = this->element_->prev_;
                 return *this;
             }
@@ -228,6 +224,5 @@
             {
                 Iterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = this->element_->prev_;
+                this->element_ = this->element_->prev_;
                 return copy;
             }
@@ -239,8 +234,5 @@
             inline T* operator*() const
             {
-                if (this->element_)
-                    return orxonox_cast<T*>(this->element_->objectBase_);
-                else
-                    return 0;
+                return orxonox_cast<T*>(this->element_->objectBase_);
             }
 
@@ -251,8 +243,5 @@
             inline T* operator->() const
             {
-                if (this->element_)
-                    return orxonox_cast<T*>(this->element_->objectBase_);
-                else
-                    return 0;
+                return orxonox_cast<T*>(this->element_->objectBase_);
             }
 
Index: /code/trunk/src/libraries/core/Language.cc
===================================================================
--- /code/trunk/src/libraries/core/Language.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Language.cc	(revision 5929)
@@ -35,8 +35,7 @@
 
 #include <fstream>
-#include <boost/filesystem.hpp>
-
 #include "util/Debug.h"
 #include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -200,14 +199,14 @@
         COUT(4) << "Read default language file." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
 
         // This creates the file if it's not existing
         std::ofstream createFile;
-        createFile.open(filepath.string().c_str(), std::fstream::app);
+        createFile.open(filepath.c_str(), std::fstream::app);
         createFile.close();
 
         // Open the file
         std::ifstream file;
-        file.open(filepath.string().c_str(), std::fstream::in);
+        file.open(filepath.c_str(), std::fstream::in);
 
         if (!file.is_open())
@@ -249,9 +248,9 @@
         COUT(4) << "Read translated language file (" << Core::getLanguage() << ")." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(Core::getLanguage()));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(Core::getLanguage());
 
         // Open the file
         std::ifstream file;
-        file.open(filepath.string().c_str(), std::fstream::in);
+        file.open(filepath.c_str(), std::fstream::in);
 
         if (!file.is_open())
@@ -303,9 +302,9 @@
         COUT(4) << "Language: Write default language file." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
 
         // Open the file
         std::ofstream file;
-        file.open(filepath.string().c_str(), std::fstream::out);
+        file.open(filepath.c_str(), std::fstream::out);
 
         if (!file.is_open())
Index: /code/trunk/src/libraries/core/Loader.cc
===================================================================
--- /code/trunk/src/libraries/core/Loader.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Loader.cc	(revision 5929)
@@ -103,5 +103,5 @@
         {
             if (mask.isIncluded(it->getIdentifier()))
-                delete (*(it++));
+                (it++)->destroy();
             else
                 ++it;
@@ -204,5 +204,5 @@
         {
             if ((it->getFile() == file) && mask.isIncluded(it->getIdentifier()))
-                delete (*(it++));
+                (it++)->destroy();
             else
                 ++it;
Index: /code/trunk/src/libraries/core/LuaState.cc
===================================================================
--- /code/trunk/src/libraries/core/LuaState.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/LuaState.cc	(revision 5929)
@@ -37,5 +37,4 @@
 
 #include "util/Debug.h"
-#include "Core.h"
 #include "Resource.h"
 #include "ToluaBindCore.h"
Index: /code/trunk/src/libraries/core/MemoryArchive.cc
===================================================================
--- /code/trunk/src/libraries/core/MemoryArchive.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/MemoryArchive.cc	(revision 5929)
@@ -68,8 +68,8 @@
                 continue;
             if (bDirs)
-                file = file.parent_path();
+                file = file.branch_path();
             if (file.empty())
                 continue;
-            if (file.has_parent_path() && !bRecursive)
+            if (file.has_branch_path() && !bRecursive)
                 continue;
             if (simpleList)
@@ -80,6 +80,6 @@
                 fi.archive = this;
                 fi.filename = file.string();
-                fi.basename = file.filename();
-                fi.path = file.parent_path().string();
+                fi.basename = file.leaf();
+                fi.path = file.branch_path().string();
                 fi.compressedSize = it->second.second;
                 fi.uncompressedSize = it->second.second;
@@ -119,8 +119,8 @@
 
     bool MemoryArchive::exists(const String& filename)
-	{
+    {
         const FileMap& files = archives_s[this->getName()];
         return files.find(filename) != files.end();
-	}
+    }
 
     const Ogre::String& MemoryArchiveFactory::getType(void) const
Index: /code/trunk/src/libraries/core/ObjectListIterator.h
===================================================================
--- /code/trunk/src/libraries/core/ObjectListIterator.h	(revision 5928)
+++ /code/trunk/src/libraries/core/ObjectListIterator.h	(revision 5929)
@@ -123,6 +123,5 @@
             inline const ObjectListIterator<T>& operator++()
             {
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
                 return *this;
             }
@@ -135,6 +134,5 @@
             {
                 ObjectListIterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
                 return copy;
             }
@@ -146,6 +144,5 @@
             inline const ObjectListIterator<T>& operator--()
             {
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
                 return *this;
             }
@@ -158,6 +155,5 @@
             {
                 ObjectListIterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
                 return copy;
             }
@@ -169,8 +165,5 @@
             inline T* operator*() const
             {
-                if (this->element_)
-                    return this->element_->object_;
-                else
-                    return 0;
+                return this->element_->object_;
             }
 
@@ -181,8 +174,5 @@
             inline T* operator->() const
             {
-                if (this->element_)
-                    return this->element_->object_;
-                else
-                    return 0;
+                return this->element_->object_;
             }
 
Index: /code/trunk/src/libraries/core/OrxonoxClass.cc
===================================================================
--- /code/trunk/src/libraries/core/OrxonoxClass.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/OrxonoxClass.cc	(revision 5929)
@@ -36,4 +36,5 @@
 #include "MetaObjectList.h"
 #include "Identifier.h"
+#include "WeakPtr.h"
 
 namespace orxonox
@@ -45,4 +46,6 @@
         this->parents_ = 0;
         this->metaList_ = new MetaObjectList();
+        this->referenceCount_ = 0;
+        this->requestedDestruction_ = false;
     }
 
@@ -50,4 +53,9 @@
     OrxonoxClass::~OrxonoxClass()
     {
+//        if (!this->requestedDestruction_)
+//            COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ")" << std::endl;
+
+        assert(this->referenceCount_ <= 0);
+
         delete this->metaList_;
 
@@ -55,4 +63,16 @@
         if (this->parents_)
             delete this->parents_;
+            
+        // reset all weak pointers pointing to this object
+        for (std::set<WeakPtr<OrxonoxClass>*>::iterator it = this->weakPointers_.begin(); it != this->weakPointers_.end(); )
+            (*(it++))->objectDeleted();
+    }
+
+    /** @brief Deletes the object if no smart pointers point to this object. Otherwise schedules the object to be deleted as soon as possible. */
+    void OrxonoxClass::destroy()
+    {
+        this->requestedDestruction_ = true;
+        if (this->referenceCount_ == 0)
+            delete this;
     }
 
@@ -78,44 +98,4 @@
 
     /** @brief Returns true if the objects class is of the given type or a derivative. */
-    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isA(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is exactly of the given type. */
-    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isExactlyA(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a child of the given type. */
-    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isChildOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct child of the given type. */
-    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isDirectChildOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a parent of the given type. */
-    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isParentOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct parent of the given type. */
-    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isDirectParentOf(identifier->getIdentifier()); }
-
-
-    /** @brief Returns true if the objects class is of the given type or a derivative. */
-    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isA(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is exactly of the given type. */
-    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isExactlyA(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a child of the given type. */
-    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isChildOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct child of the given type. */
-    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isDirectChildOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a parent of the given type. */
-    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isParentOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct parent of the given type. */
-    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isDirectParentOf(identifier.getIdentifier()); }
-
-
-    /** @brief Returns true if the objects class is of the given type or a derivative. */
     bool OrxonoxClass::isA(const OrxonoxClass* object)
         { return this->getIdentifier()->isA(object->getIdentifier()); }
Index: /code/trunk/src/libraries/core/OrxonoxClass.h
===================================================================
--- /code/trunk/src/libraries/core/OrxonoxClass.h	(revision 5928)
+++ /code/trunk/src/libraries/core/OrxonoxClass.h	(revision 5929)
@@ -55,7 +55,15 @@
         friend class ClassIdentifier;
 
+        template <class T>
+        friend class SmartPtr;
+
+        template <class T>
+        friend class WeakPtr;
+
         public:
             OrxonoxClass();
             virtual ~OrxonoxClass();
+
+            void destroy();
 
             /** @brief Function to collect the SetConfigValue-macro calls. */
@@ -72,17 +80,16 @@
             bool isDirectParentOf(const Identifier* identifier);
 
-            template <class B> bool isA(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isExactlyA(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isChildOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isDirectChildOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isParentOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isDirectParentOf(const SubclassIdentifier<B>* identifier);
-
-            template <class B> bool isA(const SubclassIdentifier<B> identifier);
-            template <class B> bool isExactlyA(const SubclassIdentifier<B> identifier);
-            template <class B> bool isChildOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isDirectChildOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isParentOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isDirectParentOf(const SubclassIdentifier<B> identifier);
+            template <class B> inline bool isA(const SubclassIdentifier<B>* identifier)
+                { return this->isA(*identifier); }
+            template <class B> inline bool isExactlyA(const SubclassIdentifier<B>* identifier)
+                { return this->isExactlyA(*identifier); }
+            template <class B> inline bool isChildOf(const SubclassIdentifier<B>* identifier)
+                { return this->isChildOf(*identifier); }
+            template <class B> inline bool isDirectChildOf(const SubclassIdentifier<B>* identifier)
+                { return this->isDirectChildOf(*identifier); }
+            template <class B> inline bool isParentOf(const SubclassIdentifier<B>* identifier)
+                { return this->isParentOf(*identifier); }
+            template <class B> inline bool isDirectParentOf(const SubclassIdentifier<B>* identifier)
+                { return this->isDirectParentOf(*identifier); }
 
             bool isA(const OrxonoxClass* object);
@@ -93,4 +100,7 @@
             bool isDirectParentOf(const OrxonoxClass* object);
 
+            inline unsigned int getReferenceCount() const
+                { return this->referenceCount_; }
+
             /**
             @brief
@@ -100,25 +110,45 @@
                 Returns NULL if the no pointer was found.
             */
-            template <class T>
-            FORCEINLINE T* getDerivedPointer(unsigned int classID)
+            FORCEINLINE void* getDerivedPointer(unsigned int classID)
             {
                 for (int i = this->objectPointers_.size() - 1; i >= 0; --i)
                 {
                     if (this->objectPointers_[i].first == classID)
-                        return static_cast<T*>(this->objectPointers_[i].second);
+                        return this->objectPointers_[i].second;
                 }
                 return NULL;
             }
-            //! Const version of getDerivedPointer
-            template <class T>
-            FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
-            {
-                return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);
-            }
+
+            //! 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);   }
 
         private:
+            /** @brief Increments the reference counter (for smart pointers). */
+            inline void incrementReferenceCount()
+                { ++this->referenceCount_; }
+            /** @brief Decrements the reference counter (for smart pointers). */
+            inline void decrementReferenceCount()
+                { --this->referenceCount_; if (this->referenceCount_ == 0 && this->requestedDestruction_) { delete this; } }
+                
+            /** @brief Register a weak pointer which points to this object. */
+            template <class T>
+            inline void registerWeakPtr(WeakPtr<T>* pointer)
+                { this->weakPointers_.insert(reinterpret_cast<WeakPtr<OrxonoxClass>*>(pointer)); }
+            /** @brief Unegister a weak pointer which pointed to this object before. */
+            template <class T>
+            inline void unregisterWeakPtr(WeakPtr<T>* pointer)
+                { this->weakPointers_.erase(reinterpret_cast<WeakPtr<OrxonoxClass>*>(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<WeakPtr<OrxonoxClass>*> weakPointers_; //!< All 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_;
Index: /code/trunk/src/libraries/core/PathConfig.cc
===================================================================
--- /code/trunk/src/libraries/core/PathConfig.cc	(revision 5929)
+++ /code/trunk/src/libraries/core/PathConfig.cc	(revision 5929)
@@ -0,0 +1,323 @@
+/*
+ *   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 "PathConfig.h"
+
+#include <cassert>
+#include <cstdlib>
+#include <cstdio>
+#include <vector>
+#include <boost/version.hpp>
+#include <boost/filesystem.hpp>
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
+#  include <windows.h>
+#  undef min
+#  undef max
+#elif defined(ORXONOX_PLATFORM_APPLE)
+#  include <sys/param.h>
+#  include <mach-o/dyld.h>
+#else /* Linux */
+#  include <sys/types.h>
+#  include <unistd.h>
+#endif
+
+#include "SpecialConfig.h"
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "CommandLine.h"
+
+// Boost 1.36 has some issues with deprecated functions that have been omitted
+#if (BOOST_VERSION == 103600)
+#  define BOOST_LEAF_FUNCTION filename
+#else
+#  define BOOST_LEAF_FUNCTION leaf
+#endif
+
+namespace orxonox
+{
+    namespace bf = boost::filesystem;
+
+    //! Static pointer to the singleton
+    PathConfig* PathConfig::singletonPtr_s  = 0;
+
+    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
+    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
+
+    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)
+    {
+        //////////////////////////
+        // FIND EXECUTABLE PATH //
+        //////////////////////////
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        // get executable module
+        TCHAR buffer[1024];
+        if (GetModuleFileName(NULL, buffer, 1024) == 0)
+            ThrowException(General, "Could not retrieve executable path.");
+
+#elif defined(ORXONOX_PLATFORM_APPLE)
+        char buffer[1024];
+        unsigned long path_len = 1023;
+        if (_NSGetExecutablePath(buffer, &path_len))
+            ThrowException(General, "Could not retrieve executable path.");
+
+#else /* Linux */
+        /* written by Nicolai Haehnle <prefect_@gmx.net> */
+
+        /* Get our PID and build the name of the link in /proc */
+        char linkname[64]; /* /proc/<pid>/exe */
+        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
+        {
+            /* This should only happen on large word systems. I'm not sure
+               what the proper response is here.
+               Since it really is an assert-like condition, aborting the
+               program seems to be in order. */
+            assert(false);
+        }
+
+        /* Now read the symbolic link */
+        char buffer[1024];
+        int ret;
+        ret = readlink(linkname, buffer, 1024);
+        /* In case of an error, leave the handling up to the caller */
+        if (ret == -1)
+            ThrowException(General, "Could not retrieve executable path.");
+
+        /* Ensure proper NUL termination */
+        buffer[ret] = 0;
+#endif
+
+        executablePath_ = bf::path(buffer);
+#ifndef ORXONOX_PLATFORM_APPLE
+        executablePath_ = executablePath_.branch_path(); // remove executable name
+#endif
+
+        /////////////////////
+        // SET MODULE PATH //
+        /////////////////////
+
+        if (bf::exists(executablePath_ / "orxonox_dev_build.keep_me"))
+        {
+            COUT(1) << "Running from the build tree." << std::endl;
+            PathConfig::bDevRun_ = true;
+            modulePath_ = specialConfig::moduleDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Also set the root path
+            bf::path relativeExecutablePath(specialConfig::defaultRuntimePath);
+            rootPath_ = executablePath_;
+            while (!bf::equivalent(rootPath_ / relativeExecutablePath, executablePath_) && !rootPath_.empty())
+                rootPath_ = rootPath_.branch_path();
+            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
+        }
+    }
+
+    PathConfig::~PathConfig()
+    {
+        delete &rootPath_;
+        delete &executablePath_;
+        delete &modulePath_;
+        delete &dataPath_;
+        delete &externalDataPath_;
+        delete &configPath_;
+        delete &logPath_;
+    }
+
+    void PathConfig::setConfigurablePaths()
+    {
+        if (bDevRun_)
+        {
+            dataPath_         = specialConfig::dataDevDirectory;
+            configPath_       = specialConfig::configDevDirectory;
+            logPath_          = specialConfig::logDevDirectory;
+
+            // Check for data path override by the command line
+            if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
+                externalDataPath_ = CommandLine::getValue("externalDataPath").getString();
+            else
+                externalDataPath_ = specialConfig::externalDataDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Using paths relative to the install prefix, complete them
+            dataPath_   = rootPath_ / specialConfig::defaultDataPath;
+            configPath_ = rootPath_ / specialConfig::defaultConfigPath;
+            logPath_    = rootPath_ / specialConfig::defaultLogPath;
+
+#else
+
+            dataPath_  = specialConfig::dataInstallDirectory;
+
+            // Get user directory
+#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
+            char* userDataPathPtr(getenv("HOME"));
+#  else
+            char* userDataPathPtr(getenv("APPDATA"));
+#  endif
+            if (userDataPathPtr == NULL)
+                ThrowException(General, "Could not retrieve user data path.");
+            bf::path userDataPath(userDataPathPtr);
+            userDataPath /= ".orxonox";
+
+            configPath_ = userDataPath / specialConfig::defaultConfigPath;
+            logPath_    = userDataPath / specialConfig::defaultLogPath;
+
+#endif
+
+        }
+
+        // Option to put all the config and log files in a separate folder
+        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
+        {
+            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
+            configPath_ = configPath_ / directory;
+            logPath_    = logPath_    / directory;
+        }
+
+        // Create directories to avoid problems when opening files in non existent folders.
+        std::vector<std::pair<bf::path, std::string> > directories;
+        directories.push_back(std::make_pair(bf::path(configPath_), "config"));
+        directories.push_back(std::make_pair(bf::path(logPath_), "log"));
+
+        for (std::vector<std::pair<bf::path, std::string> >::iterator it = directories.begin();
+            it != directories.end(); ++it)
+        {
+            if (bf::exists(it->first) && !bf::is_directory(it->first))
+            {
+                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
+                                         Please remove " + it->first.string());
+            }
+            if (bf::create_directories(it->first)) // function may not return true at all (bug?)
+            {
+                COUT(4) << "Created " << it->second << " directory" << std::endl;
+            }
+        }
+    }
+
+    std::vector<std::string> PathConfig::getModulePaths()
+    {
+        std::vector<std::string> modulePaths;
+
+        // We search for helper files with the following extension
+        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()));
+
+        boost::filesystem::directory_iterator file(modulePath_);
+        boost::filesystem::directory_iterator end;
+
+        // Iterate through all files
+        while (file != end)
+        {
+            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
+                    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() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getExecutablePathString()
+    {
+        return getInstance().executablePath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getDataPathString()
+    {
+        return getInstance().dataPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getExternalDataPathString()
+    {
+        return getInstance().externalDataPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getConfigPathString()
+    {
+        return getInstance().configPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getLogPathString()
+    {
+        return getInstance().logPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getModulePathString()
+    {
+        return getInstance().modulePath_.string() + '/';
+    }
+}
Index: /code/trunk/src/libraries/core/PathConfig.h
===================================================================
--- /code/trunk/src/libraries/core/PathConfig.h	(revision 5929)
+++ /code/trunk/src/libraries/core/PathConfig.h	(revision 5929)
@@ -0,0 +1,137 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _PathConfig_H__
+#define _PathConfig_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include <vector>
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        The PathConfig class is a singleton used to configure different paths.
+    @details
+        The class provides information about the data, config, log, executable,
+        root and module path.
+        It determines those by the use of platform specific functions.
+    @remarks
+        Not all paths are always available:
+        - root only when installed copyable
+        - externalData only for development builds in the build tree
+    */
+    class _CoreExport PathConfig : public Singleton<PathConfig>
+    {
+        friend class Singleton<PathConfig>;
+        friend class Core;
+
+        public:
+            /**
+            @brief
+                Retrievs the executable path and sets all hard coded fixed paths (currently only the module path)
+                Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
+                If found it means that this is not an installed run, hence we
+                don't write the logs and config files to ~/.orxonox
+            @throw
+                GeneralException
+            */
+            PathConfig();
+            ~PathConfig();
+
+            //! Returns the path to the root folder as boost::filesystem::path
+            static const boost::filesystem::path& getRootPath()
+                { return getInstance().rootPath_; }
+            //! Returns the path to the executable folder as boost::filesystem::path
+            static const boost::filesystem::path& getExecutablePath()
+                { return getInstance().executablePath_; }
+            //! 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();
+            //! Returns the path to the executable folder as std::string
+            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();
+            //! 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_; }
+
+        private:
+            PathConfig(const PathConfig&); //!< Don't use (undefined symbol)
+
+            /**
+            @brief
+                Sets config, log and media path and creates the folders if necessary.
+            @throws
+                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
+
+            bool                     bDevRun_;               //!< True for runs in the build directory (not installed)
+            static PathConfig* singletonPtr_s;
+    };
+}
+
+#endif /* _PathConfig_H__ */
Index: /code/trunk/src/libraries/core/Resource.h
===================================================================
--- /code/trunk/src/libraries/core/Resource.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Resource.h	(revision 5929)
@@ -64,5 +64,5 @@
         // Docs by Ogre::ResourceGroupManager.h
     public:
-		/**
+        /**
         @brief
             Open a single resource by name and return a DataStream
@@ -81,10 +81,10 @@
             Shared pointer to data stream containing the data. Will be
             destroyed automatically when no longer referenced.
-		*/
+        */
         static DataStreamPtr open(const std::string& name,
             const std::string& group = Resource::DEFAULT_GROUP,
             bool bSearchGroupsIfNotFound = false);
 
-		/**
+        /**
         @brief
             Open all resources matching a given pattern (which can contain
@@ -101,5 +101,5 @@
             Shared pointer to a data stream list , will be
             destroyed automatically when no longer referenced
-		*/
+        */
         static DataStreamListPtr openMulti(const std::string& pattern, const std::string& group = Resource::DEFAULT_GROUP);
 
Index: /code/trunk/src/libraries/core/ScopedSingletonManager.cc
===================================================================
--- /code/trunk/src/libraries/core/ScopedSingletonManager.cc	(revision 5929)
+++ /code/trunk/src/libraries/core/ScopedSingletonManager.cc	(revision 5929)
@@ -0,0 +1,59 @@
+/*
+ *   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 "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));
+    }
+
+    /*static*/ void ScopedSingletonManager::removeManager(ScopedSingletonManager* manager)
+    {
+        getManagers().erase(getManagers().find(manager->className_));
+        for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(manager->scope_); it != getManagersByScope().upper_bound(manager->scope_);)
+            if (it->second == manager)
+                getManagersByScope().erase(it++);
+            else
+                ++it;
+    }
+}
Index: /code/trunk/src/libraries/core/ScopedSingletonManager.h
===================================================================
--- /code/trunk/src/libraries/core/ScopedSingletonManager.h	(revision 5929)
+++ /code/trunk/src/libraries/core/ScopedSingletonManager.h	(revision 5929)
@@ -0,0 +1,189 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef __ScopedSingletonManager_H__
+#define __ScopedSingletonManager_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <map>
+#include "util/Exception.h"
+#include "util/Scope.h"
+#include "util/Singleton.h"
+
+#define ManageScopedSingleton(className, scope, allowedToFail) \
+    static ClassScopedSingletonManager<className, scope, allowedToFail> className##ScopedSingletonManager(#className)
+
+namespace orxonox
+{
+    class _CoreExport ScopedSingletonManager
+    {
+        public:
+            ScopedSingletonManager(const std::string& className, ScopeID::Value scope)
+                : className_(className)
+                , scope_(scope)
+            { }
+            virtual ~ScopedSingletonManager() { }
+            static void addManager(ScopedSingletonManager* manager);
+            static void removeManager(ScopedSingletonManager* manager);
+
+            template<ScopeID::Value scope>
+            static void update(const Clock& time)
+            {
+                assert(Scope<scope>::isActive());
+                for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it)
+                    it->second->update(time);
+            }
+            virtual void update(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_;
+            const ScopeID::Value scope_;
+    };
+
+    template <class T, ScopeID::Value scope, bool allowedToFail>
+    class ClassScopedSingletonManager : public ScopedSingletonManager, public ScopeListener
+    {
+    public:
+        ClassScopedSingletonManager(const std::string& className)
+            : ScopedSingletonManager(className, scope)
+            , ScopeListener(scope)
+            , singletonPtr_(NULL)
+        {
+            ScopedSingletonManager::addManager(this);
+        }
+
+        ~ClassScopedSingletonManager()
+        {
+            //assert(singletonPtr_ == NULL); // Might get triggered in the SignalHandler
+            ScopedSingletonManager::removeManager(this);
+        }
+
+        //! 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;
+        }
+
+        void destroy(OrxonoxClass*)
+        {
+            singletonPtr_->destroy();
+        }
+        void destroy(void*)
+        {
+            delete singletonPtr_;
+        }
+
+        //! Called every frame by the ScopedSingletonManager
+        void update(const Clock& time)
+        {
+            assert(Scope<scope>::isActive());
+            // assuming T inherits Singleton<T>
+            singletonPtr_->updateSingleton(time);
+        }
+
+    private:
+        T* singletonPtr_;
+    };
+
+    template <class T, ScopeID::Value scope>
+    class ClassScopedSingletonManager<T, scope, true> : public ScopedSingletonManager, public ScopeListener
+    {
+    public:
+        ClassScopedSingletonManager(const std::string& className)
+            : ScopedSingletonManager(className, scope)
+            , ScopeListener(scope)
+            , singletonPtr_(NULL)
+        {
+            ScopedSingletonManager::addManager(this);
+        }
+
+        ~ClassScopedSingletonManager()
+        {
+            assert(singletonPtr_ == NULL);
+            ScopedSingletonManager::removeManager(this);
+        }
+
+        //! Called if the Scope of the Singleton gets active (creates the instance)
+        void activated()
+        {
+            assert(singletonPtr_ == NULL);
+            try
+                { singletonPtr_ = new T(); }
+            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;
+            }
+        }
+
+        void destroy(OrxonoxClass* ptr)
+        {
+            singletonPtr_->destroy();
+        }
+        void destroy(void* ptr)
+        {
+            delete singletonPtr_;
+        }
+
+        //! Called every frame by the ScopedSingletonManager
+        void update(const Clock& time)
+        {
+            assert(Scope<scope>::isActive());
+            // assuming T inherits Singleton<T>
+            if (singletonPtr_ != NULL)
+                singletonPtr_->updateSingleton(time);
+        }
+
+    private:
+        T* singletonPtr_;
+    };
+}
+
+#endif /* __ScopedSingletonManager_H__ */
Index: /code/trunk/src/libraries/core/Shell.cc
===================================================================
--- /code/trunk/src/libraries/core/Shell.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/Shell.cc	(revision 5929)
@@ -88,5 +88,5 @@
         OutputHandler::getOutStream().setOutputBuffer(0);
         if (this->inputBuffer_)
-            delete this->inputBuffer_;
+            this->inputBuffer_->destroy();
     }
 
Index: /code/trunk/src/libraries/core/SmartPtr.h
===================================================================
--- /code/trunk/src/libraries/core/SmartPtr.h	(revision 5929)
+++ /code/trunk/src/libraries/core/SmartPtr.h	(revision 5929)
@@ -0,0 +1,200 @@
+/*
+ *   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
+
+#ifndef _SmartPtr_H__
+#define _SmartPtr_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+
+#include "OrxonoxClass.h"
+#include "WeakPtr.h"
+
+namespace orxonox
+{
+    template <class T>
+    class SmartPtr
+    {
+        public:
+            inline SmartPtr() : pointer_(0), base_(0)
+            {
+            }
+
+            inline SmartPtr(int) : pointer_(0), base_(0)
+            {
+            }
+
+            inline SmartPtr(T* pointer, bool bAddRef = true) : pointer_(pointer), base_(pointer)
+            {
+                if (this->base_ && bAddRef)
+                    this->base_->incrementReferenceCount();
+            }
+
+            inline SmartPtr(const SmartPtr& other) : pointer_(other.pointer_), base_(other.base_)
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            template <class O>
+            inline SmartPtr(const SmartPtr<O>& other) : pointer_(other.get()), base_(other.base_)
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            template <class O>
+            inline SmartPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.getBase())
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            inline ~SmartPtr()
+            {
+                if (this->base_)
+                    this->base_->decrementReferenceCount();
+            }
+            
+            inline const SmartPtr& operator=(int)
+            {
+                SmartPtr(0).swap(*this);
+                return *this;
+            }
+
+            inline const SmartPtr& operator=(T* pointer)
+            {
+                SmartPtr(pointer).swap(*this);
+                return *this;
+            }
+
+            inline const SmartPtr& operator=(const SmartPtr& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const SmartPtr& operator=(const SmartPtr<O>& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const SmartPtr& operator=(const WeakPtr<O>& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            inline T* get() const
+            {
+                return this->pointer_;
+            }
+
+            inline OrxonoxClass* getBase() const
+            {
+                return this->base_;
+            }
+
+            inline operator T*() const
+            {
+                return this->pointer_;
+            }
+
+            inline T* operator->() const
+            {
+                assert(this->pointer_ != 0);
+                return this->pointer_;
+            }
+
+            inline T& operator*() const
+            {
+                assert(this->pointer_ != 0);
+                return *this->pointer_;
+            }
+
+            inline bool operator!() const
+            {
+                return (this->pointer_ == 0);
+            }
+
+            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;
+                }
+            }
+
+            inline void reset()
+            {
+                SmartPtr().swap(*this);
+            }
+
+        private:
+            T* pointer_;
+            OrxonoxClass* base_;
+    };
+
+    template <class T>
+    void swap(SmartPtr<T>& a, SmartPtr<T>& b)
+    {
+        a.swap(b);
+    }
+
+    template <class T, class U>
+    SmartPtr<T> static_pointer_cast(const SmartPtr<U>& p)
+    {
+        return static_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    SmartPtr<T> const_pointer_cast(const SmartPtr<U>& p)
+    {
+        return const_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    SmartPtr<T> dynamic_pointer_cast(const SmartPtr<U>& p)
+    {
+        return dynamic_cast<T*>(p.get());
+    }
+}
+
+#endif /* _SmartPtr_H__ */
Index: /code/trunk/src/libraries/core/SubclassIdentifier.h
===================================================================
--- /code/trunk/src/libraries/core/SubclassIdentifier.h	(revision 5929)
+++ /code/trunk/src/libraries/core/SubclassIdentifier.h	(revision 5929)
@@ -0,0 +1,192 @@
+/*
+ *   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 Definition of SubclassIdentifier.
+
+    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.
+*/
+
+#ifndef _SubclassIdentifier_H__
+#define _SubclassIdentifier_H__
+
+#include "CorePrereqs.h"
+
+#include <cstdlib>
+#include "util/Debug.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###   SubclassIdentifier    ###
+    // ###############################
+    //! 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 aborts.
+        Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
+    */
+    template <class T>
+    class SubclassIdentifier
+    {
+        public:
+            /**
+                @brief Constructor: Automaticaly assigns the Identifier of the given class.
+            */
+            SubclassIdentifier()
+            {
+                this->identifier_ = ClassIdentifier<T>::getIdentifier();
+            }
+
+            /**
+                @brief Constructor: Assigns the given Identifier.
+                @param identifier The Identifier
+            */
+            SubclassIdentifier(Identifier* identifier)
+            {
+                this->operator=(identifier);
+            }
+
+            /**
+                @brief Copyconstructor: Assigns the identifier of the other SubclassIdentifier.
+                @param identifier The other SublcassIdentifier
+            */
+            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
+            */
+            const 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;
+            }
+
+            /**
+                @brief Overloading of the = operator: assigns the identifier of the other SubclassIdentifier.
+                @param identifier The other SublcassIdentifier
+            */
+            template <class O>
+            const SubclassIdentifier<T>& operator=(const SubclassIdentifier<O>& identifier)
+            {
+                return this->operator=(identifier.getIdentifier());
+            }
+
+            /**
+                @brief Overloading of the * operator: returns the assigned identifier.
+            */
+            inline Identifier* operator*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Overloading of the -> operator: returns the assigned identifier.
+            */
+            inline Identifier* operator->() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
+            */
+            inline operator Identifier*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
+                @return The new object
+            */
+            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;
+                }
+            }
+
+            /** @brief Returns the assigned identifier. @return The identifier */
+            inline Identifier* getIdentifier() const
+                { return this->identifier_; }
+
+        private:
+            Identifier* identifier_;            //!< The assigned identifier
+    };
+}
+
+#endif /* _SubclassIdentifier_H__ */
Index: /code/trunk/src/libraries/core/Super.h
===================================================================
--- /code/trunk/src/libraries/core/Super.h	(revision 5928)
+++ /code/trunk/src/libraries/core/Super.h	(revision 5929)
@@ -250,11 +250,8 @@
         SUPER_NOARGS(classname, functionname)
 
-    #define SUPER_processEvent(classname, functionname, ...) \
+    #define SUPER_XMLEventPort(classname, functionname, ...) \
         SUPER_ARGS(classname, functionname, __VA_ARGS__)
 
     #define SUPER_changedScale(classname, functionname, ...) \
-        SUPER_NOARGS(classname, functionname)
-
-    #define SUPER_changedMainState(classname, functionname, ...) \
         SUPER_NOARGS(classname, functionname)
 
@@ -497,6 +494,6 @@
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, processEvent, true, Event& event)
-            (event)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, XMLEventPort, true, Element& xmlelement, XMLPort::Mode mode)
+            (xmlelement, mode)
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
@@ -505,21 +502,17 @@
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedMainState, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOwner, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedOverlayGroup, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedName, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(10, changedGametype, false)
+        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;
@@ -571,7 +564,6 @@
     SUPER_INTRUSIVE_DECLARATION(changedActivity);
     SUPER_INTRUSIVE_DECLARATION(changedVisibility);
-    SUPER_INTRUSIVE_DECLARATION(processEvent);
+    SUPER_INTRUSIVE_DECLARATION(XMLEventPort);
     SUPER_INTRUSIVE_DECLARATION(changedScale);
-    SUPER_INTRUSIVE_DECLARATION(changedMainState);
     SUPER_INTRUSIVE_DECLARATION(changedOwner);
     SUPER_INTRUSIVE_DECLARATION(changedOverlayGroup);
Index: /code/trunk/src/libraries/core/TclBind.cc
===================================================================
--- /code/trunk/src/libraries/core/TclBind.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/TclBind.cc	(revision 5929)
@@ -39,5 +39,5 @@
 #include "CommandExecutor.h"
 #include "ConsoleCommand.h"
-#include "Core.h"
+#include "PathConfig.h"
 #include "TclThreadManager.h"
 
@@ -123,8 +123,8 @@
     {
 #ifdef DEPENDENCY_PACKAGE_ENABLE
-        if (Core::isDevelopmentRun())
+        if (PathConfig::isDevelopmentRun())
             return (std::string(specialConfig::dependencyLibraryDirectory) + "/tcl");
         else
-            return (Core::getRootPathString() + "lib/tcl");
+            return (PathConfig::getRootPathString() + "lib/tcl");
 #else
         return "";
Index: /code/trunk/src/libraries/core/TclThreadManager.cc
===================================================================
--- /code/trunk/src/libraries/core/TclThreadManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/TclThreadManager.cc	(revision 5929)
@@ -36,7 +36,7 @@
 #include <cpptcl/cpptcl.h>
 
+#include "util/Clock.h"
 #include "util/Convert.h"
 #include "util/Exception.h"
-#include "Clock.h"
 #include "CommandExecutor.h"
 #include "ConsoleCommand.h"
Index: /code/trunk/src/libraries/core/WeakPtr.h
===================================================================
--- /code/trunk/src/libraries/core/WeakPtr.h	(revision 5929)
+++ /code/trunk/src/libraries/core/WeakPtr.h	(revision 5929)
@@ -0,0 +1,219 @@
+/*
+ *   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
+
+#ifndef _WeakPtr_H__
+#define _WeakPtr_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include "OrxonoxClass.h"
+#include "Functor.h"
+
+namespace orxonox
+{
+    template <class T>
+    class WeakPtr
+    {
+        friend class OrxonoxClass;
+        
+        public:
+            inline WeakPtr() : pointer_(0), base_(0), callback_(0)
+            {
+            }
+
+            inline WeakPtr(int) : pointer_(0), base_(0), callback_(0)
+            {
+            }
+
+            inline WeakPtr(T* pointer) : pointer_(pointer), base_(pointer), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            inline WeakPtr(const WeakPtr& other) : pointer_(other.pointer_), base_(other.base_), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            template <class O>
+            inline WeakPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.base_), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            inline ~WeakPtr()
+            {
+                if (this->base_)
+                    this->base_->unregisterWeakPtr(this);
+                if (this->callback_)
+                    delete this->callback_;
+                    
+            }
+            
+            inline const WeakPtr& operator=(int)
+            {
+                WeakPtr(0).swap(*this);
+                return *this;
+            }
+
+            inline const WeakPtr& operator=(T* pointer)
+            {
+                WeakPtr(pointer).swap(*this);
+                return *this;
+            }
+
+            inline const WeakPtr& operator=(const WeakPtr& other)
+            {
+                WeakPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const WeakPtr& operator=(const WeakPtr<O>& other)
+            {
+                WeakPtr(other).swap(*this);
+                return *this;
+            }
+
+            inline T* get() const
+            {
+                return this->pointer_;
+            }
+
+            inline OrxonoxClass* getBase() const
+            {
+                return this->base_;
+            }
+
+            inline operator T*() const
+            {
+                return this->pointer_;
+            }
+
+            inline T* operator->() const
+            {
+                assert(this->pointer_ != 0);
+                return this->pointer_;
+            }
+
+            inline T& operator*() const
+            {
+                assert(this->pointer_ != 0);
+                return *this->pointer_;
+            }
+
+            inline bool operator!() const
+            {
+                return (this->pointer_ == 0);
+            }
+
+            inline void swap(WeakPtr& other)
+            {
+                if (this->base_)
+                    this->base_->unregisterWeakPtr(this);
+                if (other.base_)
+                    other.base_->unregisterWeakPtr(&other);
+                
+                {
+                    T* temp = this->pointer_;
+                    this->pointer_ = other.pointer_;
+                    other.pointer_ = temp;
+                }
+                {
+                    OrxonoxClass* temp = this->base_;
+                    this->base_ = other.base_;
+                    other.base_ = temp;
+                }
+
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+                if (other.base_)
+                    other.base_->registerWeakPtr(&other);
+            }
+
+            inline void reset()
+            {
+                WeakPtr().swap(*this);
+            }
+            
+            inline void setCallback(Functor* callback)
+            {
+                this->callback_ = callback;
+            }
+            
+            inline Functor* getFunctor() const
+            {
+                return this->callback_;
+            }
+
+        private:
+            inline void objectDeleted()
+            {
+                this->base_ = 0;
+                this->pointer_ = 0;
+                if (this->callback_)
+                    (*this->callback_)();
+            }
+        
+            T* pointer_;
+            OrxonoxClass* base_;
+            Functor* callback_;
+    };
+
+    template <class T>
+    void swap(WeakPtr<T>& a, WeakPtr<T>& b)
+    {
+        a.swap(b);
+    }
+
+    template <class T, class U>
+    WeakPtr<T> static_pointer_cast(const WeakPtr<U>& p)
+    {
+        return static_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    WeakPtr<T> const_pointer_cast(const WeakPtr<U>& p)
+    {
+        return const_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    WeakPtr<T> dynamic_pointer_cast(const WeakPtr<U>& p)
+    {
+        return dynamic_cast<T*>(p.get());
+    }
+}
+
+#endif /* _WeakPtr_H__ */
Index: /code/trunk/src/libraries/core/XMLPort.h
===================================================================
--- /code/trunk/src/libraries/core/XMLPort.h	(revision 5928)
+++ /code/trunk/src/libraries/core/XMLPort.h	(revision 5929)
@@ -51,5 +51,4 @@
 #include "util/MultiType.h"
 #include "util/OrxAssert.h"
-#include "Factory.h"
 #include "Identifier.h"
 #include "Executor.h"
@@ -377,5 +376,5 @@
                             this->owner_->xmlAttributes_.clear();
                             // Iterate through the attributes manually in order to make them case insensitive
-                            Attribute* attribute = xmlelement.FirstAttribute(false);
+                            ticpp::Attribute* attribute = xmlelement.FirstAttribute(false);
                             while (attribute != 0)
                             {
@@ -412,5 +411,5 @@
                     }
                 }
-                else
+                else if (mode == XMLPort::SaveObject)
                 {
                     if (this->saveexecutor_)
@@ -548,5 +547,5 @@
                             for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
                             {
-                                Identifier* identifier = Factory::getIdentifier(child->Value());
+                                Identifier* identifier = Identifier::getIdentifierByString(child->Value());
                                 if (identifier)
                                 {
@@ -629,5 +628,5 @@
                     }
                 }
-                else
+                else if (mode == XMLPort::SaveObject)
                 {
                 }
Index: /code/trunk/src/libraries/core/input/Button.cc
===================================================================
--- /code/trunk/src/libraries/core/input/Button.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/Button.cc	(revision 5929)
@@ -170,8 +170,8 @@
 
                 // evaluate the command
-                CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
+                const CommandEvaluation& eval = CommandExecutor::evaluate(commandStr);
                 if (!eval.isValid())
                 {
-                    parseError("Command evaluation failed.", true);
+                    parseError("Command evaluation of \"" + commandStr + "\"failed.", true);
                     continue;
                 }
Index: /code/trunk/src/libraries/core/input/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/core/input/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/core/input/CMakeLists.txt	(revision 5929)
@@ -9,4 +9,5 @@
   JoyStickQuantityListener.cc
   KeyBinder.cc
+  KeyBinderManager.cc
   Keyboard.cc
   KeyDetector.cc
Index: /code/trunk/src/libraries/core/input/InputDevice.h
===================================================================
--- /code/trunk/src/libraries/core/input/InputDevice.h	(revision 5928)
+++ /code/trunk/src/libraries/core/input/InputDevice.h	(revision 5929)
@@ -41,7 +41,7 @@
 #include <ois/OISInputManager.h>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
-#include "core/Clock.h"
 #include "InputState.h"
 
Index: /code/trunk/src/libraries/core/input/InputManager.cc
===================================================================
--- /code/trunk/src/libraries/core/input/InputManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/InputManager.cc	(revision 5929)
@@ -41,8 +41,8 @@
 #include <boost/foreach.hpp>
 
+#include "util/Clock.h"
 #include "util/Convert.h"
 #include "util/Exception.h"
 #include "util/ScopeGuard.h"
-#include "core/Clock.h"
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
@@ -53,5 +53,4 @@
 
 #include "InputBuffer.h"
-#include "KeyDetector.h"
 #include "JoyStick.h"
 #include "JoyStickQuantityListener.h"
@@ -88,7 +87,6 @@
         , oisInputManager_(0)
         , devices_(2)
-        , bExclusiveMouse_(false)
+        , mouseMode_(MouseMode::Nonexclusive)
         , emptyState_(0)
-        , keyDetector_(0)
         , calibratorCallbackHandler_(0)
     {
@@ -99,4 +97,6 @@
         this->setConfigValues();
 
+        if (GraphicsManager::getInstance().isFullScreen())
+            mouseMode_ = MouseMode::Exclusive;
         this->loadDevices();
 
@@ -105,13 +105,4 @@
         emptyState_->setHandler(&InputHandler::EMPTY);
         activeStates_[emptyState_->getPriority()] = emptyState_;
-
-        // KeyDetector to evaluate a pressed key's name
-        InputState* detector = createInputState("detector", false, false, InputStatePriority::Detector);
-        // Create a callback to avoid buttonHeld events after the key has been detected
-        FunctorMember<InputManager>* bufferFunctor = createFunctor(&InputManager::clearBuffers);
-        bufferFunctor->setObject(this);
-        detector->setLeaveFunctor(bufferFunctor);
-        keyDetector_ = new KeyDetector();
-        detector->setHandler(keyDetector_);
 
         // Joy stick calibration helper callback
@@ -124,16 +115,8 @@
         this->updateActiveStates();
 
-        {
-            // calibrate console command
-            FunctorMember<InputManager>* functor = createFunctor(&InputManager::calibrate);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "calibrate"), true);
-        }
-        {
-            // reload console command
-            FunctorMember<InputManager>* functor = createFunctor(&InputManager::reload);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "reload"), false);
-        }
+        // calibrate console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::calibrate, this), "calibrate"), true);
+        // reload console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::reload, this), "reload"), false);
 
         CCOUT(4) << "Construction complete." << std::endl;
@@ -172,5 +155,5 @@
         paramList.insert(std::make_pair("w32_keyboard", "DISCL_FOREGROUND"));
         paramList.insert(std::make_pair("w32_mouse", "DISCL_FOREGROUND"));
-        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
         {
             // Disable Windows key plus special keys (like play, stop, next, etc.)
@@ -185,5 +168,5 @@
         paramList.insert(std::make_pair("XAutoRepeatOn", "true"));
 
-        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
         {
             if (CommandLine::getValue("keyboard_no_grab").getBool())
@@ -274,9 +257,4 @@
     }
 
-    void InputManager::setKeyDetectorCallback(const std::string& command)
-    {
-        this->keyDetector_->setCallbackCommand(command);
-    }
-
     // ############################################################
     // #####                    Destruction                   #####
@@ -289,9 +267,7 @@
 
         // Destroy calibrator helper handler and state
-        delete keyDetector_;
         this->destroyState("calibrator");
         // Destroy KeyDetector and state
-        delete calibratorCallbackHandler_;
-        this->destroyState("detector");
+        calibratorCallbackHandler_->destroy();
         // destroy the empty InputState
         this->destroyStateInternal(this->emptyState_);
@@ -528,9 +504,13 @@
 
         // Check whether we have to change the mouse mode
+        MouseMode::Value requestedMode = MouseMode::Dontcare;
         std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
-        if (mouseStates.empty() && bExclusiveMouse_ ||
-            !mouseStates.empty() && mouseStates.front()->getIsExclusiveMouse() != bExclusiveMouse_)
-        {
-            bExclusiveMouse_ = !bExclusiveMouse_;
+        if (mouseStates.empty())
+            requestedMode = MouseMode::Nonexclusive;
+        else 
+            requestedMode = mouseStates.front()->getMouseMode();
+        if (requestedMode != MouseMode::Dontcare && mouseMode_ != requestedMode)
+        {
+            mouseMode_ = requestedMode;
             if (!GraphicsManager::getInstance().isFullScreen())
                 this->reloadInternal();
@@ -722,5 +702,5 @@
         }
         statesByName_.erase(state->getName());
-        delete state;
+        state->destroy();
     }
 }
Index: /code/trunk/src/libraries/core/input/InputManager.h
===================================================================
--- /code/trunk/src/libraries/core/input/InputManager.h	(revision 5928)
+++ /code/trunk/src/libraries/core/input/InputManager.h	(revision 5929)
@@ -161,6 +161,4 @@
         // Various getters and setters
         //-------------------------------
-        //! Sets the the name of the command used by the KeyDetector as callback.
-        void setKeyDetectorCallback(const std::string& command);
         //! Returns the number of joy stick that have been created since the c'tor or last call to reload().
         unsigned int getJoyStickQuantity() const
@@ -193,9 +191,8 @@
         OIS::InputManager*                  oisInputManager_;      //!< OIS input manager
         std::vector<InputDevice*>           devices_;              //!< List of all input devices (keyboard, mouse, joy sticks)
-        bool                                bExclusiveMouse_;      //!< Currently applied mouse mode
+        MouseMode::Value                    mouseMode_;            //!< Currently applied mouse mode
 
         // some internally handled states and handlers
         InputState*                         emptyState_;           //!< Lowest priority states (makes handling easier)
-        KeyDetector*                        keyDetector_;          //!< KeyDetector instance
         //! InputBuffer that reacts to the Enter key when calibrating the joy sticks
         InputBuffer*                        calibratorCallbackHandler_;
Index: /code/trunk/src/libraries/core/input/InputState.cc
===================================================================
--- /code/trunk/src/libraries/core/input/InputState.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/InputState.cc	(revision 5929)
@@ -37,5 +37,5 @@
         , bAlwaysGetsInput_(bAlwaysGetsInput)
         , bTransparent_(bTransparent)
-        , bExclusiveMouse_(true)
+        , mouseMode_(MouseMode::Dontcare)
         , bExpired_(true)
         , handlers_(2)
Index: /code/trunk/src/libraries/core/input/InputState.h
===================================================================
--- /code/trunk/src/libraries/core/input/InputState.h	(revision 5928)
+++ /code/trunk/src/libraries/core/input/InputState.h	(revision 5929)
@@ -55,4 +55,14 @@
         static const int Detector     = HighPriority + 2;
     };
+
+    namespace MouseMode
+    {
+        enum Value
+        {
+            Exclusive,
+            Nonexclusive,
+            Dontcare
+        };
+    }
 
     /**
@@ -120,6 +130,6 @@
         void setHandler        (InputHandler* handler);
 
-        void setIsExclusiveMouse(bool value) { bExclusiveMouse_ = value; this->bExpired_ = true; }
-        bool getIsExclusiveMouse() const { return bExclusiveMouse_; }
+        void setMouseMode(MouseMode::Value value) { mouseMode_ = value; this->bExpired_ = true; }
+        MouseMode::Value getMouseMode() const { return mouseMode_; }
 
         //! Returns the name of the state (which is unique!)
@@ -174,5 +184,5 @@
         const bool                  bAlwaysGetsInput_;      //!< See class declaration for explanation
         const bool                  bTransparent_;          //!< See class declaration for explanation
-        bool                        bExclusiveMouse_;       //!< See class declaration for explanation
+        MouseMode::Value            mouseMode_;             //!< See class declaration for explanation
         int                         priority_;              //!< Current priority (might change)
         bool                        bExpired_;              //!< See hasExpired()
Index: /code/trunk/src/libraries/core/input/KeyBinder.cc
===================================================================
--- /code/trunk/src/libraries/core/input/KeyBinder.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/KeyBinder.cc	(revision 5929)
@@ -27,13 +27,9 @@
  */
 
-/**
- @file
- @brief Implementation of the different input handlers.
- */
-
 #include "KeyBinder.h"
 
 #include "util/Convert.h"
 #include "util/Debug.h"
+#include "util/Exception.h"
 #include "core/ConfigValueIncludes.h"
 #include "core/CoreIncludes.h"
@@ -48,6 +44,7 @@
         Constructor that does as little as necessary.
     */
-    KeyBinder::KeyBinder()
+    KeyBinder::KeyBinder(const std::string& filename)
         : deriveTime_(0.0f)
+        , filename_(filename)
     {
         mouseRelative_[0] = 0;
@@ -103,4 +100,8 @@
         // set them here to use allHalfAxes_
         setConfigValues();
+
+        // Load the bindings if filename was given
+        if (!this->filename_.empty())
+            this->loadBindings();
     }
 
@@ -240,24 +241,15 @@
     @brief
         Loads the key and button bindings.
-    @return
-        True if loading succeeded.
-    */
-    void KeyBinder::loadBindings(const std::string& filename)
+    */
+    void KeyBinder::loadBindings()
     {
         COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
 
-        if (filename.empty())
-            return;
-
-        if (this->configFile_ == ConfigFileType::NoType)
-        {
-            // Get a new ConfigFileType from the ConfigFileManager
-            this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
-        }
-
-        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
+        // Get a new ConfigFileType from the ConfigFileManager
+        this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
+
+        ConfigFileManager::getInstance().setFilename(this->configFile_, this->filename_);
 
         // Parse bindings and create the ConfigValueContainers if necessary
-        clearBindings();
         for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
             it->second->readConfigValue(this->configFile_);
Index: /code/trunk/src/libraries/core/input/KeyBinder.h
===================================================================
--- /code/trunk/src/libraries/core/input/KeyBinder.h	(revision 5928)
+++ /code/trunk/src/libraries/core/input/KeyBinder.h	(revision 5929)
@@ -26,10 +26,4 @@
  *
  */
-
-/**
-@file
-@brief
-    Different definitions of input processing.
-*/
 
 #ifndef _KeyBinder_H__
@@ -53,20 +47,32 @@
     /**
     @brief
-        Handles mouse, keyboard and joy stick input while in the actual game mode.
-        Manages the key bindings.
+        Maps mouse, keyboard and joy stick input to command strings and executes them.
+
+        The bindings are stored in ini-files (like the one for configValues) in the config Path.
+    @remarks
+        You cannot change the filename because the KeyBinderManager maps these filenames to the
+        KeyBinders. If you need to load other bindings, just create a new one.
     */
     class _CoreExport KeyBinder : public InputHandler, public JoyStickQuantityListener
     {
     public:
-        KeyBinder ();
+        KeyBinder (const std::string& filename);
         virtual ~KeyBinder();
 
-        void loadBindings(const std::string& filename);
         void clearBindings();
         bool setBinding(const std::string& binding, const std::string& name, bool bTemporary = false);
+        const std::string& getBindingsFilename()
+            { return this->filename_; }
         void setConfigValues();
         void resetJoyStickAxes();
 
     protected: // functions
+        void loadBindings();
+        void buttonThresholdChanged();
+        void initialiseJoyStickBindings();
+        void compilePointerLists();
+        // from JoyStickQuantityListener interface
+        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
         void allDevicesUpdated(float dt);
         void mouseUpdated(float dt);
@@ -74,10 +80,4 @@
         // internal
         void tickHalfAxis(HalfAxis& halfAxis);
-
-        void buttonThresholdChanged();
-        // from JoyStickQuantityListener interface
-        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
-        void initialiseJoyStickBindings();
-        void compilePointerLists();
 
         void buttonPressed (const KeyEvent& evt);
@@ -144,4 +144,6 @@
         float deriveTime_;
 
+        //! Name of the file used in this KeyBinder (constant!)
+        const std::string filename_;
         //! Config file used. ConfigFileType::NoType in case of KeyDetector. Also indicates whether we've already loaded.
         ConfigFileType configFile_;
@@ -171,4 +173,5 @@
     };
 
+
     inline void KeyBinder::buttonPressed (const KeyEvent& evt)
     { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnPress); }
Index: /code/trunk/src/libraries/core/input/KeyBinderManager.cc
===================================================================
--- /code/trunk/src/libraries/core/input/KeyBinderManager.cc	(revision 5929)
+++ /code/trunk/src/libraries/core/input/KeyBinderManager.cc	(revision 5929)
@@ -0,0 +1,169 @@
+/*
+ *   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 "KeyBinderManager.h"
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "core/ConfigValueIncludes.h"
+#include "core/ConsoleCommand.h"
+#include "core/CoreIncludes.h"
+#include "core/ScopedSingletonManager.h"
+#include "InputManager.h"
+#include "KeyDetector.h"
+
+namespace orxonox
+{
+    KeyBinderManager* KeyBinderManager::singletonPtr_s = 0;
+    ManageScopedSingleton(KeyBinderManager, ScopeID::Graphics, false);
+
+    KeyBinderManager::KeyBinderManager()
+        : currentBinder_(NULL)
+        , bDefaultFileLoaded_(true)
+        , bBinding_(false)
+    {
+        this->callbackFunction_ = createFunctor(&KeyBinderManager::callback, this);
+
+        RegisterObject(KeyBinderManager);
+        this->setConfigValues();
+
+        // keybind console commands
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::keybind,  this), "keybind" ))
+            .defaultValues("");
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::tkeybind, this), "tkeybind"))
+            .defaultValues("");
+
+        // Load default key binder
+        this->setCurrent(defaultFilename_);
+    }
+
+    KeyBinderManager::~KeyBinderManager()
+    {
+        // Delete all remaining KeyBinders
+        for (std::map<std::string, KeyBinder*>::const_iterator it = this->binders_.begin(); it != this->binders_.end(); ++it)
+            delete it->second;
+        delete this->callbackFunction_;
+    }
+
+    void KeyBinderManager::setConfigValues()
+    {
+        SetConfigValue(defaultFilename_, "keybindings.ini")
+            .description("Filename for the default keybindings file.")
+            .callback(this, &KeyBinderManager::defaultFilenameChanged);
+    }
+
+    void KeyBinderManager::defaultFilenameChanged()
+    {
+        if (this->bDefaultFileLoaded_)
+            this->setCurrent(this->defaultFilename_);
+    }
+
+    void KeyBinderManager::setCurrent(const std::string& filename)
+    {
+        this->currentBinder_ = this->get(filename);
+        if (filename == this->defaultFilename_)
+            this->bDefaultFileLoaded_ = true;
+        else
+            this->bDefaultFileLoaded_ = false;
+    }
+
+    void KeyBinderManager::load(const std::string& filename)
+    {
+        std::map<std::string, KeyBinder*>::const_iterator it = this->binders_.find(filename);
+        if (it != this->binders_.end())
+            return;
+
+        KeyBinder* binder = new KeyBinder(filename);
+        this->binders_[filename] = binder;
+    }
+
+    void KeyBinderManager::unload(const std::string& filename)
+    {
+        if (filename == this->defaultFilename_)
+            ThrowException(General, "KeyBinderManager: Cannot unload the default file");
+        if (filename == this->currentBinder_->getBindingsFilename())
+        {
+            // unloading current file --> set default file
+            this->setCurrent(this->defaultFilename_);
+        }
+        std::map<std::string, KeyBinder*>::iterator it = this->binders_.find(filename);
+        if (it != this->binders_.end())
+        {
+            delete it->second;
+            this->binders_.erase(it);
+        }
+    }
+
+    KeyBinder* KeyBinderManager::get(const std::string& name)
+    {
+        this->load(name);
+        return this->binders_[name];
+    }
+
+    InputHandler* KeyBinderManager::getCurrentAsHandler()
+    {
+        return this->getCurrent();
+    }
+
+    InputHandler* KeyBinderManager::getDefaultAsHandler()
+    {
+        return this->getDefault();
+    }
+
+    InputHandler* KeyBinderManager::getAsHandler(const std::string& name)
+    {
+        return this->get(name);
+    }
+
+    void KeyBinderManager::keybindInternal(const std::string& command, bool bTemporary)
+    {
+        if (!this->bBinding_)
+        {
+            COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
+            KeyDetector::getInstance().setCallback(callbackFunction_);
+            InputManager::getInstance().enterState("detector");
+            this->command_ = command;
+            this->bTemporary_ = bTemporary;
+            this->bBinding_ = true;
+        }
+        // else: We're still in a keybind command. Ignore this call.
+    }
+
+    // Gets called by the KeyDetector (registered with a Functor)
+    void KeyBinderManager::callback(const std::string& keyName)
+    {
+        if (this->bBinding_)
+        {
+            COUT(0) << "Binding string \"" << command_ << "\" on key '" << keyName << "'" << std::endl;
+            this->currentBinder_->setBinding(command_, keyName, bTemporary_);
+            InputManager::getInstance().leaveState("detector");
+            this->bBinding_ = false;
+        }
+        // else: A key was probably pressed within the same tick, ignore it.
+    }
+}
Index: /code/trunk/src/libraries/core/input/KeyBinderManager.h
===================================================================
--- /code/trunk/src/libraries/core/input/KeyBinderManager.h	(revision 5929)
+++ /code/trunk/src/libraries/core/input/KeyBinderManager.h	(revision 5929)
@@ -0,0 +1,120 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _KeyBinderManager_H__
+#define _KeyBinderManager_H__
+
+#include "InputPrereqs.h"
+
+#include <map>
+#include <string>
+#include "util/Singleton.h"
+#include "core/OrxonoxClass.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Handles the KeyBinders and supplies them throughout the game.
+
+        This interface merely serves to provide a static "keybind" command that always
+        maps to the currently active KeyBinder. You can set that with setCurrent().
+        There is also a default one, retrieved with getDefault(). The idea is that
+        mostly the default KeyBinder is active except for special situtations (mini-game for inst).
+    @remarks
+        You are not forced to use the KeyBinder imposed by getCurrent(). But be aware that "keybind"
+        will not work as expected!
+    */
+    class _CoreExport KeyBinderManager : public Singleton<KeyBinderManager>, public OrxonoxClass
+    {
+        friend class Singleton<KeyBinderManager>;
+    public:
+        KeyBinderManager();
+        ~KeyBinderManager();
+        void setConfigValues();
+
+        //! Returns the currently selected KeyBinder
+        KeyBinder*    getCurrent()
+            { return this->currentBinder_; }
+        //! Like getCurrent(), but returns it as InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getCurrentAsHandler();
+        //! Selects the current KeyBinder and creates it if not yet loaded.
+        void setCurrent(const std::string& filename);
+
+        //! Returns the default KeyBinder
+        KeyBinder*    getDefault()
+            { return binders_[this->defaultFilename_]; }
+        //! Returns the default KeyBinder as InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getDefaultAsHandler();
+        //! Returns the filename of the default key bindings
+        const std::string& getDefaultFilename()
+            { return defaultFilename_; }
+        //! Selects the default KeyBinder as current one
+        void setToDefault()
+            { this->setCurrent(this->defaultFilename_); }
+
+        //! Returns a pointer to a KeyBinder (creates it if not yet loaded)
+        KeyBinder*    get(const std::string& name);
+        //! Like get() but return value is of type InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getAsHandler(const std::string& name);
+
+        //! Loads a KeyBinder by creating it (no different from get() except for the return value)
+        void load  (const std::string& filename);
+        //! Destroys a KeyBinder completely (does nothing if not yet loaded)
+        void unload(const std::string& filename);
+
+        //! Bind 'command' to any key pressed after this call (use with care!)
+        inline void keybind(const std::string& command)
+            { this->keybindInternal(command, false); }
+        //! Bind 'command' to any key pressed after this call (use with care!), but temporarily (no file save)
+        inline void tkeybind(const std::string& command)
+            { this->keybindInternal(command, true); }
+
+    private:
+        KeyBinderManager(const KeyBinderManager&);
+        void keybindInternal(const std::string& command, bool bTemporary);
+        void callback(const std::string& keyName);
+        void defaultFilenameChanged();
+
+        // KeyBinder management
+        KeyBinder* currentBinder_;                   //! Currently selected KeyBinder (never NULL!)
+        std::map<std::string, KeyBinder*> binders_;  //! All loaded KeyBinders
+        bool bDefaultFileLoaded_;                    //! Tells whether the default one is loaded
+        std::string defaultFilename_;                //! Name of the file with the default key bindings
+
+        // keybind command related
+        Functor* callbackFunction_;                  //! Function to be called when key was pressed after "keybind" command
+        bool bBinding_;                              //! Tells whether a key binding process is active
+        bool bTemporary_;                            //! Stores tkeybind/keybind value
+        std::string command_;                        //! Stores the command received by (t)keybind
+
+        static KeyBinderManager* singletonPtr_s;
+    };
+}
+
+#endif /* _KeyBinderManager_H__ */
Index: /code/trunk/src/libraries/core/input/KeyDetector.cc
===================================================================
--- /code/trunk/src/libraries/core/input/KeyDetector.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/KeyDetector.cc	(revision 5929)
@@ -29,40 +29,53 @@
 #include "KeyDetector.h"
 
-#include "util/Debug.h"
+#include "core/ConsoleCommand.h"
 #include "core/CoreIncludes.h"
+#include "core/ScopedSingletonManager.h"
 #include "Button.h"
+#include "InputManager.h"
+#include "InputState.h"
 
 namespace orxonox
 {
-    /**
-    @brief
-        Constructor
-    */
+    std::string KeyDetector::callbackCommand_s = "KeyDetectorKeyPressed";
+    KeyDetector* KeyDetector::singletonPtr_s = 0;
+    ManageScopedSingleton(KeyDetector, ScopeID::Graphics, false);
+
     KeyDetector::KeyDetector()
+        : KeyBinder("")
     {
         RegisterObject(KeyDetector);
+
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyDetector::callback,  this), callbackCommand_s));
+        this->assignCommands();
+
+        inputState_ = InputManager::getInstance().createInputState("detector", false, false, InputStatePriority::Detector);
+        // Create a callback to avoid buttonHeld events after the key has been detected
+        inputState_->setLeaveFunctor(createFunctor(&InputManager::clearBuffers, &InputManager::getInstance()));
+        inputState_->setHandler(this);
     }
 
-    /**
-    @brief
-        Destructor
-    */
     KeyDetector::~KeyDetector()
     {
+        inputState_->setHandler(NULL);
+        InputManager::getInstance().destroyState("detector");
     }
 
-    /**
-    @brief
-        Assigns all the buttons 'command' plus the button's name.
-    */
-    void KeyDetector::setCallbackCommand(const std::string& command)
+    void KeyDetector::assignCommands()
     {
-        callbackCommand_ = command;
+        // Assign every button/axis the same command, but with its name as argument
         clearBindings();
         for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
         {
-            it->second->bindingString_ = callbackCommand_ + it->second->groupName_ + "." + it->second->name_;
+            it->second->bindingString_ = callbackCommand_s + " " + it->second->groupName_ + "." + it->second->name_;
             it->second->parse();
         }
+    }
+
+    void KeyDetector::callback(const std::string& name)
+    {
+        // Call the registered function
+        if (this->callbackFunction_)
+            (*this->callbackFunction_)(name);
     }
 
@@ -70,6 +83,5 @@
     {
         KeyBinder::JoyStickQuantityChanged(joyStickList);
-        if (!callbackCommand_.empty())
-            setCallbackCommand(callbackCommand_);
+        this->assignCommands();
     }
 }
Index: /code/trunk/src/libraries/core/input/KeyDetector.h
===================================================================
--- /code/trunk/src/libraries/core/input/KeyDetector.h	(revision 5928)
+++ /code/trunk/src/libraries/core/input/KeyDetector.h	(revision 5929)
@@ -32,19 +32,30 @@
 #include "InputPrereqs.h"
 
-#include <string>
+#include "util/Singleton.h"
 #include "KeyBinder.h"
 
 namespace orxonox
 {
-    class _CoreExport KeyDetector : public KeyBinder
+    class _CoreExport KeyDetector : public KeyBinder, public Singleton<KeyDetector>
     {
+        friend class Singleton<KeyDetector>;
+
     public:
         KeyDetector();
         ~KeyDetector();
-        void setCallbackCommand(const std::string& command);
-        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
+        void setCallback(Functor* function) { this->callbackFunction_ = function; }
 
     private:
-        std::string callbackCommand_;
+        KeyDetector(const KeyDetector&);
+
+        void callback(const std::string& name);
+        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+        void assignCommands();
+
+        Functor* callbackFunction_;
+        InputState* inputState_;
+        static std::string callbackCommand_s;
+        static KeyDetector* singletonPtr_s;
     };
 }
Index: /code/trunk/src/libraries/core/input/Mouse.cc
===================================================================
--- /code/trunk/src/libraries/core/input/Mouse.cc	(revision 5928)
+++ /code/trunk/src/libraries/core/input/Mouse.cc	(revision 5929)
@@ -48,16 +48,8 @@
 
 #ifdef ORXONOX_PLATFORM_LINUX
-        {
-            // Mouse grab console command
-            FunctorMember<Mouse>* functor = createFunctor(&Mouse::grab);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "grab"), false);
-        }
-        {
-            // Mouse ungrab console command
-            FunctorMember<Mouse>* functor = createFunctor(&Mouse::ungrab);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "ungrab"), false);
-        }
+        // Mouse grab console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::grab, this), "grab"), false);
+        // Mouse ungrab console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::ungrab, this), "ungrab"), false);
 #endif
     }
Index: /code/trunk/src/libraries/network/Client.cc
===================================================================
--- /code/trunk/src/libraries/network/Client.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/Client.cc	(revision 5929)
@@ -43,10 +43,12 @@
 #include <cassert>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
-#include "core/Clock.h"
 #include "synchronisable/Synchronisable.h"
 #include "packet/Chat.h"
 #include "packet/Gamestate.h"
 #include "FunctionCallManager.h"
+#include "core/CoreIncludes.h"
+#include "core/Game.h"
 
 namespace orxonox
@@ -158,4 +160,20 @@
     return;
   }
+  
+  void Client::connectionClosed()
+  {
+    ObjectList<Synchronisable>::iterator it;
+    for(it = ObjectList<Synchronisable>::begin(); it; )
+    {
+      if( it->getSyncMode() != 0x0 )
+        (it++)->destroy();
+      else
+      {
+        ++it;
+      }
+    }
+    Game::getInstance().popState();
+    Game::getInstance().popState();
+  }
 
 }
Index: /code/trunk/src/libraries/network/Client.h
===================================================================
--- /code/trunk/src/libraries/network/Client.h	(revision 5928)
+++ /code/trunk/src/libraries/network/Client.h	(revision 5929)
@@ -45,4 +45,6 @@
 
 #include <string>
+
+#include "util/UtilPrereqs.h"
 #include "ClientConnection.h"
 #include "GamestateClient.h"
@@ -72,5 +74,6 @@
 
     void update(const Clock& time);
-
+  protected:
+    virtual void connectionClosed();
   private:
     Client(const Client& copy); // not used
Index: /code/trunk/src/libraries/network/ClientConnection.cc
===================================================================
--- /code/trunk/src/libraries/network/ClientConnection.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/ClientConnection.cc	(revision 5929)
@@ -118,4 +118,5 @@
           case ENET_EVENT_TYPE_DISCONNECT:
             COUT(4) << "received disconnect confirmation from server" << endl;
+            this->connectionClosed();
             return true;
         }
@@ -123,4 +124,5 @@
     }
     enet_peer_reset( this->server_ );
+    this->connectionClosed();
     return false;
   }
@@ -133,13 +135,14 @@
   }
 
-  void ClientConnection::addClient(ENetEvent* event)
+  void ClientConnection::addPeer(ENetEvent* event)
   {
     assert(0);
   }
-  void ClientConnection::disconnectPeer(ENetEvent* event)
+  void ClientConnection::removePeer(ENetEvent* event)
   {
     this->established_=false;
     COUT(1) << "Received disconnect Packet from Server!" << endl;
         // server closed the connection
+    this->connectionClosed();
   }
 
Index: /code/trunk/src/libraries/network/ClientConnection.h
===================================================================
--- /code/trunk/src/libraries/network/ClientConnection.h	(revision 5928)
+++ /code/trunk/src/libraries/network/ClientConnection.h	(revision 5929)
@@ -53,7 +53,9 @@
     bool addPacket(ENetPacket *packet);
     inline bool isConnected(){ return this->established_; }
+  protected:
+    virtual void connectionClosed()=0;
   private:
-    virtual void addClient(ENetEvent* event);
-    virtual void disconnectPeer(ENetEvent* event);
+    virtual void addPeer(ENetEvent* event);
+    virtual void removePeer(ENetEvent* event);
     
     bool disconnectConnection();
Index: /code/trunk/src/libraries/network/ClientConnectionListener.cc
===================================================================
--- /code/trunk/src/libraries/network/ClientConnectionListener.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/ClientConnectionListener.cc	(revision 5929)
@@ -33,21 +33,32 @@
 #include "ClientInformation.h"
 
-namespace orxonox{
+namespace orxonox
+{
+    ClientConnectionListener::ClientConnectionListener()
+    { 
+        RegisterRootObject(ClientConnectionListener); 
+    }
 
-  ClientConnectionListener::ClientConnectionListener()
-  { 
-    RegisterRootObject(ClientConnectionListener); 
-  }
+    void ClientConnectionListener::broadcastClientConnected(unsigned int clientID)
+    {
+        for (ObjectList<ClientConnectionListener>::iterator it = ObjectList<ClientConnectionListener>::begin(); it != ObjectList<ClientConnectionListener>::end(); ++it)
+            it->clientConnected(clientID);
+    }
+    
+    void ClientConnectionListener::broadcastClientDisconnected(unsigned int clientID)
+    {
+        for (ObjectList<ClientConnectionListener>::iterator it = ObjectList<ClientConnectionListener>::begin(); it != ObjectList<ClientConnectionListener>::end(); ++it)
+            it->clientDisconnected(clientID);
+    }
 
-  void ClientConnectionListener::getConnectedClients(){
-    if(GameMode::showsGraphics())
-      this->clientConnected(0); //server client id
-    ClientInformation *client = ClientInformation::getBegin();
-    while(client){
-      this->clientConnected(client->getID());
-      client=client->next();
+    void ClientConnectionListener::getConnectedClients()
+    {
+        ClientInformation* client = ClientInformation::getBegin();
+        while (client)
+        {
+            this->clientConnected(client->getID());
+            client = client->next();
+        }
     }
-  }
-
 }
 
Index: /code/trunk/src/libraries/network/ClientConnectionListener.h
===================================================================
--- /code/trunk/src/libraries/network/ClientConnectionListener.h	(revision 5928)
+++ /code/trunk/src/libraries/network/ClientConnectionListener.h	(revision 5929)
@@ -33,21 +33,21 @@
 #include "core/OrxonoxClass.h"
 
-namespace orxonox{
+namespace orxonox
+{
+    class _NetworkExport ClientConnectionListener : virtual public OrxonoxClass
+    {
+        public:
+            ClientConnectionListener();
+            virtual ~ClientConnectionListener() {}
+            
+            static void broadcastClientConnected(unsigned int clientID);
+            static void broadcastClientDisconnected(unsigned int clientID);
 
-  class _NetworkExport ClientConnectionListener : virtual public OrxonoxClass
-  {
-    friend class Server;
+            virtual void clientConnected(unsigned int clientID) = 0;
+            virtual void clientDisconnected(unsigned int clientID) = 0;
 
-  public:
-    ClientConnectionListener();
-    virtual ~ClientConnectionListener() {}
-
-    void getConnectedClients();
-
-  protected:
-    virtual void clientConnected(unsigned int clientID) = 0;
-    virtual void clientDisconnected(unsigned int clientID) = 0;
-  };
-
+        protected:
+            void getConnectedClients();
+    };
 }
 
Index: /code/trunk/src/libraries/network/Connection.cc
===================================================================
--- /code/trunk/src/libraries/network/Connection.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/Connection.cc	(revision 5929)
@@ -83,8 +83,8 @@
         // log handling ================
         case ENET_EVENT_TYPE_CONNECT:
-          addClient( &event );
+          addPeer( &event );
           break;
         case ENET_EVENT_TYPE_DISCONNECT:
-          disconnectPeer( &event );
+          removePeer( &event );
           break;
         case ENET_EVENT_TYPE_RECEIVE:
Index: /code/trunk/src/libraries/network/Connection.h
===================================================================
--- /code/trunk/src/libraries/network/Connection.h	(revision 5928)
+++ /code/trunk/src/libraries/network/Connection.h	(revision 5929)
@@ -64,9 +64,9 @@
     
     int service(ENetEvent* event);
-    void disconnectPeer(ENetPeer *peer);
+    virtual void disconnectPeer(ENetPeer *peer);
     
     void processQueue();
-    virtual void addClient(ENetEvent* event)=0;
-    virtual void disconnectPeer(ENetEvent* event)=0;
+    virtual void addPeer(ENetEvent* event)=0;
+    virtual void removePeer(ENetEvent* event)=0;
     virtual bool processPacket(ENetEvent* event);
     
Index: /code/trunk/src/libraries/network/GamestateClient.cc
===================================================================
--- /code/trunk/src/libraries/network/GamestateClient.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/GamestateClient.cc	(revision 5929)
@@ -108,5 +108,5 @@
     ObjectList<Synchronisable>::iterator temp=it;
     ++it;
-    delete  *temp;
+    temp->destroy(); // or delete?
   }
 
Index: /code/trunk/src/libraries/network/GamestateManager.cc
===================================================================
--- /code/trunk/src/libraries/network/GamestateManager.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/GamestateManager.cc	(revision 5929)
@@ -77,5 +77,5 @@
         delete (*it2).second;
     }
-    delete this->trafficControl_;
+    this->trafficControl_->destroy();
 //     delete this->threadMutex_;
 //     delete this->threadPool_;
@@ -160,6 +160,5 @@
       finishGamestate( cid, &clientGamestates.back(), client, reference );
       //FunctorMember<GamestateManager>* functor = 
-//       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate) );
-//       executor->setObject(this);
+//       ExecutorMember<GamestateManager>* executor = createExecutor( createFunctor(&GamestateManager::finishGamestate, this) );
 //       executor->setDefaultValues( cid, &clientGamestates.back(), client, reference );
 //       (*static_cast<Executor*>(executor))();
Index: /code/trunk/src/libraries/network/NetworkFunction.cc
===================================================================
--- /code/trunk/src/libraries/network/NetworkFunction.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/NetworkFunction.cc	(revision 5929)
@@ -60,5 +60,5 @@
     std::map<std::string, NetworkFunctionBase*>::iterator it;
     for( it=NetworkFunctionBase::nameMap_.begin(); it!=NetworkFunctionBase::nameMap_.end(); ++it )
-      delete it->second;
+      it->second->destroy();
   }
   
Index: /code/trunk/src/libraries/network/NetworkPrereqs.h
===================================================================
--- /code/trunk/src/libraries/network/NetworkPrereqs.h	(revision 5928)
+++ /code/trunk/src/libraries/network/NetworkPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the network library
 */
 
@@ -40,4 +41,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( NETWORK_STATIC_BUILD )
 #  ifdef NETWORK_SHARED_BUILD
@@ -57,11 +59,31 @@
 
 //-----------------------------------------------------------------------
-// Library global contants
+// Constants
 //-----------------------------------------------------------------------
+
 namespace orxonox
 {
   static const unsigned int GAMESTATEID_INITIAL = static_cast<unsigned int>(-1);
   static const unsigned int CLIENTID_UNKNOWN    = static_cast<unsigned int>(-2);
-  static const uint32_t     OBJECTID_UNKNOWN    = static_cast<uint32_t>(-1);
+}
+
+//-----------------------------------------------------------------------
+// Enums
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
+  namespace packet
+  {
+    namespace PacketFlag
+    {
+      enum Value
+      {
+        Reliable   = 1,
+        Unsequence = 2,
+        NoAllocate = 4
+      };
+    }
+  }
 }
 
@@ -84,37 +106,26 @@
 namespace orxonox
 {
+  class ChatListener;
   class Client;
   class ClientConnection;
   class ClientConnectionListener;
-  class ClientFrameListener;
   class ClientInformation;
   class Connection;
   class FunctionCallManager;
   class GamestateClient;
+  class GamestateHandler;
   class GamestateManager;
-  class GamestateHandler;
-  class NetworkCallbackBase;
-  template <class T> class NetworkCallback;
-  class NetworkCallbackManager;
+  class Host;
   class NetworkFunctionBase;
+  struct NetworkFunctionPointer;
   class NetworkFunctionStatic;
+  template <class T>
+  class NetworkMemberFunction;
   class NetworkMemberFunctionBase;
-  template <class T> class NetworkMemeberFunction;
-  struct NetworkFunctionPointer;
   class Server;
   class ServerConnection;
-  class ServerFrameListener;
-  class Synchronisable;
-  class SynchronisableVariableBase;
-  template <class T> class SynchronisableVariable;
-  template <class T> class SynchronisableVariableBidirectional;
-  struct ClientList;
-  struct PacketEnvelope;
-  struct QueueItem;
-  struct syncData;
   class TrafficControl;
-  class obj;
-  class objInfo;
 
+  // packet
   namespace packet
   {
@@ -122,21 +133,24 @@
     class Chat;
     class ClassID;
+    class DeleteObjects;
     class FunctionCalls;
     class FunctionIDs;
     class Gamestate;
-    class NetworkIDs;
     class Packet;
     class Welcome;
+  }
 
-    namespace PacketFlag
-    {
-      enum Value
-      {
-        Reliable   = 1,
-        Unsequence = 2,
-        NoAllocate = 4
-      };
-    }
-  }
+  // synchronisable
+  template <class T>
+  class NetworkCallback;
+  class NetworkCallbackBase;
+  class NetworkCallbackManager;
+  class Synchronisable;
+  class SynchronisableHeader;
+  template <class T>
+  class SynchronisableVariable;
+  class SynchronisableVariableBase;
+  template <class T>
+  class SynchronisableVariableBidirectional;
 }
 
Index: /code/trunk/src/libraries/network/Server.cc
===================================================================
--- /code/trunk/src/libraries/network/Server.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/Server.cc	(revision 5929)
@@ -46,6 +46,6 @@
 #include <string>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
-#include "core/Clock.h"
 #include "core/ObjectList.h"
 #include "core/Executor.h"
@@ -245,5 +245,8 @@
     packet::DeleteObjects *del = new packet::DeleteObjects();
     if(!del->fetchIDs())
+    {
+      delete del;
       return true;  //everything ok (no deletes this tick)
+    }
 //     COUT(3) << "sending DeleteObjects" << std::endl;
     while(temp != NULL){
@@ -267,5 +270,5 @@
 
 
-  void Server::addClient(ENetEvent *event){
+  void Server::addPeer(ENetEvent *event){
     static unsigned int newid=1;
 
@@ -279,9 +282,5 @@
 
     // inform all the listeners
-    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
-    while(listener){
-      listener->clientConnected(newid);
-      listener++;
-    }
+    ClientConnectionListener::broadcastClientConnected(newid);
 
     ++newid;
@@ -290,4 +289,18 @@
     createClient(temp->getID());
 }
+
+  void Server::removePeer(ENetEvent *event)
+  {
+    COUT(4) << "removing client from list" << std::endl;
+    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
+    if(!client)
+      return;
+    else
+    {
+      //ServerConnection::disconnectClient( client );
+      ClientConnectionListener::broadcastClientDisconnected( client->getID() );
+      delete client;
+    }
+  }
 
   bool Server::createClient(int clientID){
@@ -329,11 +342,6 @@
     ServerConnection::disconnectClient( client );
     GamestateManager::removeClient(client);
-// inform all the listeners
-    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
-    while(listener){
-      listener->clientDisconnected(client->getID());
-      ++listener;
-    }
-    delete client; //remove client from list
+    // inform all the listeners
+    ClientConnectionListener::broadcastClientDisconnected(client->getID());
   }
 
Index: /code/trunk/src/libraries/network/Server.h
===================================================================
--- /code/trunk/src/libraries/network/Server.h	(revision 5928)
+++ /code/trunk/src/libraries/network/Server.h	(revision 5929)
@@ -32,4 +32,5 @@
 #include "NetworkPrereqs.h"
 
+#include "util/UtilPrereqs.h"
 #include "core/CorePrereqs.h"
 #include "Host.h"
@@ -65,5 +66,7 @@
     unsigned int playerID(){return 0;}
     
-    void addClient(ENetEvent *event);
+    void addPeer(ENetEvent *event);
+    void removePeer(ENetEvent *event);
+    
     bool createClient(int clientID);
     void disconnectClient( ClientInformation *client);
Index: /code/trunk/src/libraries/network/ServerConnection.cc
===================================================================
--- /code/trunk/src/libraries/network/ServerConnection.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/ServerConnection.cc	(revision 5929)
@@ -103,15 +103,4 @@
   {
     Connection::disconnectPeer( client->getPeer() );
-    delete client;
-  }
-  
-  void ServerConnection::disconnectPeer( ENetEvent* event )
-  {
-    COUT(4) << "removing client from list" << std::endl;
-    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
-    if(!client)
-      return;
-    else
-      ServerConnection::disconnectClient( client );
   }
   
@@ -119,5 +108,5 @@
     ClientInformation *client = ClientInformation::findClient(clientID);
     if(client)
-      disconnectClient(client);
+      ServerConnection::disconnectClient(client);
   }
 
@@ -126,5 +115,5 @@
     ClientInformation *temp = ClientInformation::getBegin();
     while(temp!=0){
-      disconnectClient( temp );
+      ServerConnection::disconnectClient( temp );
       temp = temp->next();
     }
@@ -141,6 +130,5 @@
           break;
         case ENET_EVENT_TYPE_DISCONNECT:
-          if(ClientInformation::findClient(&(event.peer->address)))
-            delete ClientInformation::findClient(&(event.peer->address));
+          removePeer( &event );
           temp = ClientInformation::getBegin();
           break;
Index: /code/trunk/src/libraries/network/ServerConnection.h
===================================================================
--- /code/trunk/src/libraries/network/ServerConnection.h	(revision 5928)
+++ /code/trunk/src/libraries/network/ServerConnection.h	(revision 5929)
@@ -59,5 +59,4 @@
     static bool addPacketAll(ENetPacket *packet);
     virtual void disconnectClient(ClientInformation *client);
-    void disconnectPeer( ENetEvent* event );
     void disconnectClient(int clientID);
   protected:
Index: /code/trunk/src/libraries/network/packet/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/network/packet/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/network/packet/CMakeLists.txt	(revision 5929)
@@ -1,3 +1,4 @@
 ADD_SOURCE_FILES(NETWORK_SRC_FILES
+COMPILATION_BEGIN PacketCompilation.cc
   Acknowledgement.cc
   Chat.cc
@@ -9,4 +10,5 @@
   Packet.cc
   Welcome.cc
+COMPILATION_END
 )
 
Index: /code/trunk/src/libraries/network/packet/ClassID.cc
===================================================================
--- /code/trunk/src/libraries/network/packet/ClassID.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/packet/ClassID.cc	(revision 5929)
@@ -49,20 +49,18 @@
   Identifier *id;
   std::string classname;
-  unsigned int nrOfClasses=0; 
+  unsigned int nrOfClasses=0;
   unsigned int packetSize=2*sizeof(uint32_t); //space for the packetID and for the nrofclasses
   uint32_t network_id;
   flags_ = flags_ | PACKET_FLAGS_CLASSID;
   std::queue<std::pair<uint32_t, std::string> > tempQueue;
-  
+
   //calculate total needed size (for all strings and integers)
-  std::map<std::string, Identifier*>::const_iterator it = Factory::getFactoryMapBegin();
-  for(;it != Factory::getFactoryMapEnd();++it){
+  std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin();
+  for(;it != Identifier::getStringIdentifierMapEnd();++it){
     id = (*it).second;
-    if(id == NULL)
+    if(id == NULL || !id->hasFactory())
       continue;
     classname = id->getName();
     network_id = id->getNetworkID();
-    if(network_id==0)
-      COUT(3) << "we got a null class id: " << id->getName() << std::endl;
     // now push the network id and the classname to the stack
     tempQueue.push( std::pair<unsigned int, std::string>(network_id, classname) );
@@ -70,15 +68,15 @@
     packetSize += (classname.size()+1)+sizeof(uint32_t)+sizeof(uint32_t);
   }
-  
+
   this->data_=new uint8_t[ packetSize ];
   //set the appropriate packet id
   assert(this->data_);
   *(Type::Value *)(this->data_ + _PACKETID ) = Type::ClassID;
-  
+
   uint8_t *temp=data_+sizeof(uint32_t);
   // save the number of all classes
   *(uint32_t*)temp = nrOfClasses;
   temp += sizeof(uint32_t);
-  
+
   // now save all classids and classnames
   std::pair<uint32_t, std::string> tempPair;
@@ -91,7 +89,7 @@
     temp+=2*sizeof(uint32_t)+tempPair.second.size()+1;
   }
-  
+
   COUT(5) << "classid packetSize is " << packetSize << endl;
-  
+
 }
 
@@ -111,5 +109,5 @@
   temp += sizeof(uint32_t);
   totalsize += sizeof(uint32_t); // storage size for nr of all classes
-  
+
   for(unsigned int i=0; i<nrOfClasses; i++){
     totalsize += 2*sizeof(uint32_t) + *(uint32_t*)(temp + sizeof(uint32_t));
@@ -125,9 +123,9 @@
   uint32_t stringsize;
   unsigned char *classname;
-  
-  
-  //clean the map of network ids
-  Factory::cleanNetworkIDs();
-  
+
+
+  //clear the map of network ids
+  Identifier::clearNetworkIDs();
+
   COUT(4) << "=== processing classids: " << endl;
   std::pair<uint32_t, std::string> tempPair;
@@ -136,5 +134,5 @@
   nrOfClasses = *(uint32_t*)temp;
   temp += sizeof(uint32_t);
-  
+
   for( int i=0; i<nrOfClasses; i++){
     networkID = *(uint32_t*)temp;
Index: /code/trunk/src/libraries/network/packet/Gamestate.cc
===================================================================
--- /code/trunk/src/libraries/network/packet/Gamestate.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/packet/Gamestate.cc	(revision 5929)
@@ -378,4 +378,5 @@
   rawDiff( dest2, dest, basep, header_->getDataSize(), base->header_->getDataSize() );
   assert( memcmp( dest2, gs, dest_length) == 0 );
+  delete dest2;
 #endif
 
Index: /code/trunk/src/libraries/network/synchronisable/Synchronisable.cc
===================================================================
--- /code/trunk/src/libraries/network/synchronisable/Synchronisable.cc	(revision 5928)
+++ /code/trunk/src/libraries/network/synchronisable/Synchronisable.cc	(revision 5929)
@@ -47,7 +47,7 @@
   /**
   * Constructor:
-  * Initializes all Variables and sets the right objectID
+  * Initializes all Variables and sets the right objectID_
   */
-  Synchronisable::Synchronisable(BaseObject* creator){
+  Synchronisable::Synchronisable(BaseObject* creator ){
     RegisterRootObject(Synchronisable);
     static uint32_t idCounter=0;
@@ -55,14 +55,11 @@
     if ( GameMode::isMaster() || ( Host::running() && Host::isServer() ) )
     {
-      this->objectID = idCounter++; //this is only needed when running a server
-    //add synchronisable to the objectMap
-      objectMap_[this->objectID] = this;
+      this->setObjectID( idCounter++ );
     }
     else
     {
-      objectID=OBJECTID_UNKNOWN;
-      this->setObjectMode(0x0);   //make sure this object doesn't get synchronized
-    }
-    classID = static_cast<uint32_t>(-1);
+      objectID_=OBJECTID_UNKNOWN;
+    }
+    classID_ = static_cast<uint32_t>(-1);
     
     // set dataSize to 0
@@ -72,7 +69,10 @@
 
     // get creator id
-    this->creatorID = OBJECTID_UNKNOWN;
-
-    searchcreatorID:
+    if( creator )
+      this->creatorID_ = creator->getSceneID();
+    else
+      this->creatorID_ = OBJECTID_UNKNOWN;
+
+    /*searchcreatorID:
     if (creator)
     {
@@ -80,5 +80,5 @@
         if (synchronisable_creator && synchronisable_creator->objectMode_)
         {
-            this->creatorID = synchronisable_creator->getObjectID();
+            this->creatorID = synchronisable_creator->getScene()->getObjectID();
         }
         else if (creator != creator->getCreator())
@@ -87,10 +87,10 @@
             goto searchcreatorID;
         }
-    }
+    }*/
   }
 
   /**
    * Destructor:
-   * Delete all callback objects and remove objectID from the objectMap_
+   * Delete all callback objects and remove objectID_ from the objectMap_
    */
   Synchronisable::~Synchronisable(){
@@ -99,5 +99,5 @@
       // remove object from the static objectMap
       if (this->objectMode_ != 0x0 && (Host::running() && Host::isServer()))
-        deletedObjects_.push(objectID);
+        deletedObjects_.push(objectID_);
     }
     // delete all Synchronisable Variables from syncList ( which are also in stringList )
@@ -107,5 +107,5 @@
     stringList.clear();
     std::map<uint32_t, Synchronisable*>::iterator it;
-    it = objectMap_.find(objectID);
+    it = objectMap_.find(objectID_);
     if (it != objectMap_.end())
       objectMap_.erase(it);
@@ -172,11 +172,12 @@
     Synchronisable *no = orxonox_cast<Synchronisable*>(bo);
     assert(no);
-    no->objectID=header.getObjectID();
-    no->creatorID=header.getCreatorID(); //TODO: remove this
-    no->classID=header.getClassID();
-    COUT(4) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
+    assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
+    no->setObjectID(header.getObjectID());
+    //no->creatorID=header.getCreatorID(); //TODO: remove this
+    no->setClassID(header.getClassID());
+    assert(no->creatorID_ == header.getCreatorID());
+    //assert(no->classID_ == header.getClassID());
+    COUT(4) << "fabricate objectID_: " << no->objectID_ << " classID_: " << no->classID_ << std::endl;
           // update data and create object/entity...
-    assert( Synchronisable::objectMap_.find(header.getObjectID()) == Synchronisable::objectMap_.end() );
-    Synchronisable::objectMap_[header.getObjectID()] = no;
     bool b = no->updateData(mem, mode, true);
     assert(b);
@@ -191,15 +192,15 @@
 
   /**
-   * Finds and deletes the Synchronisable with the appropriate objectID
-   * @param objectID objectID of the Synchronisable
+   * Finds and deletes the Synchronisable with the appropriate objectID_
+   * @param objectID_ objectID_ of the Synchronisable
    * @return true/false
    */
-  bool Synchronisable::deleteObject(uint32_t objectID){
-    if(!getSynchronisable(objectID))
+  bool Synchronisable::deleteObject(uint32_t objectID_){
+    if(!getSynchronisable(objectID_))
       return false;
-    assert(getSynchronisable(objectID)->objectID==objectID);
-    Synchronisable *s = getSynchronisable(objectID);
+    assert(getSynchronisable(objectID_)->objectID_==objectID_);
+    Synchronisable *s = getSynchronisable(objectID_);
     if(s)
-      delete s;
+      s->destroy(); // or delete?
     else
       return false;
@@ -208,11 +209,11 @@
 
   /**
-   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
-   * @param objectID objectID of the Synchronisable
-   * @return pointer to the Synchronisable with the objectID
-   */
-  Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID){
+   * This function looks up the objectID_ in the objectMap_ and returns a pointer to the right Synchronisable
+   * @param objectID_ objectID_ of the Synchronisable
+   * @return pointer to the Synchronisable with the objectID_
+   */
+  Synchronisable* Synchronisable::getSynchronisable(uint32_t objectID_){
     std::map<uint32_t, Synchronisable*>::iterator it1;
-    it1 = objectMap_.find(objectID);
+    it1 = objectMap_.find(objectID_);
     if (it1 != objectMap_.end())
       return it1->second;
@@ -220,6 +221,6 @@
 //     ObjectList<Synchronisable>::iterator it;
 //     for(it = ObjectList<Synchronisable>::begin(); it; ++it){
-//       if( it->getObjectID()==objectID ){
-//         objectMap_[objectID] = *it;
+//       if( it->getObjectID()==objectID_ ){
+//         objectMap_[objectID_] = *it;
 //         return *it;
 //       }
@@ -231,8 +232,8 @@
 
   /**
-   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
+   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID_ and classID_ to the given memory
    * takes a pointer to already allocated memory (must have at least getSize bytes length)
    * structure of the bitstream:
-   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
+   * |totalsize,objectID_,classID_,var1,var2,string1_length,string1,var3,...|
    * length of varx: size saved int syncvarlist
    * @param mem pointer to allocated memory with enough size
@@ -252,13 +253,14 @@
     uint32_t tempsize = 0;
 #ifndef NDEBUG
-    if (this->classID==0)
+    if (this->classID_==0)
       COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
 #endif
 
-    if (this->classID == static_cast<uint32_t>(-1))
-        this->classID = this->getIdentifier()->getNetworkID();
-
-    assert(ClassByID(this->classID));
-    assert(this->classID==this->getIdentifier()->getNetworkID());
+    if (this->classID_ == static_cast<uint32_t>(-1))
+        this->classID_ = this->getIdentifier()->getNetworkID();
+
+    assert(ClassByID(this->classID_));
+    assert(this->classID_==this->getIdentifier()->getNetworkID());
+    assert(this->objectID_!=OBJECTID_UNKNOWN);
     std::vector<SynchronisableVariableBase*>::iterator i;
 
@@ -269,5 +271,5 @@
 
 
-    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << std::endl;
+    COUT(5) << "Synchronisable getting data from objectID_: " << objectID_ << " classID_: " << classID_ << std::endl;
     // copy to location
     for(i=syncList.begin(); i!=syncList.end(); ++i){
@@ -277,7 +279,7 @@
     
     tempsize += SynchronisableHeader::getSize();
-    header.setObjectID( this->objectID );
-    header.setCreatorID( this->creatorID );
-    header.setClassID( this->classID );
+    header.setObjectID( this->objectID_ );
+    header.setCreatorID( this->creatorID_ );
+    header.setClassID( this->classID_ );
     header.setDataAvailable( true );
     header.setDataSize( tempsize );
@@ -311,7 +313,7 @@
     // start extract header
     SynchronisableHeader syncHeader(mem);
-    assert(syncHeader.getObjectID()==this->objectID);
-    assert(syncHeader.getCreatorID()==this->creatorID);
-    assert(syncHeader.getClassID()==this->classID);
+    assert(syncHeader.getObjectID()==this->objectID_);
+    assert(syncHeader.getCreatorID()==this->creatorID_);
+    assert(syncHeader.getClassID()==this->classID_);
     if(syncHeader.isDataAvailable()==false){
       mem += syncHeader.getDataSize();
@@ -322,5 +324,5 @@
     // stop extract header
 
-    //COUT(5) << "Synchronisable: objectID " << syncHeader.getObjectID() << ", classID " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << std::endl;
+    //COUT(5) << "Synchronisable: objectID_ " << syncHeader.getObjectID() << ", classID_ " << syncHeader.getClassID() << " size: " << syncHeader.getDataSize() << " synchronising data" << std::endl;
     for(i=syncList.begin(); i!=syncList.end(); i++)
     {
@@ -361,9 +363,9 @@
     if(mode==0x0)
       mode=state_;
-    return ( (objectMode_&mode)!=0 && (!syncList.empty() ) );
-  }
-
-  /**
-   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
+    return ( (this->objectMode_ & mode)!=0 && (!syncList.empty() ) );
+  }
+
+  /**
+   * This function looks at the header located in the bytestream and checks wheter objectID_ and classID_ match with the Synchronisables ones
    * @param mem pointer to the bytestream
    */
@@ -371,5 +373,5 @@
   {
     SynchronisableHeader header(mem);
-    assert(header.getObjectID()==this->objectID);
+    assert(header.getObjectID()==this->objectID_);
     return header.isDataAvailable();
   }
@@ -383,7 +385,7 @@
    * @param mode same as in registerVar
    */
-  void Synchronisable::setObjectMode(uint8_t mode){
+  void Synchronisable::setSyncMode(uint8_t mode){
     assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
-    objectMode_=mode;
+    this->objectMode_=mode;
   }
 
Index: /code/trunk/src/libraries/network/synchronisable/Synchronisable.h
===================================================================
--- /code/trunk/src/libraries/network/synchronisable/Synchronisable.h	(revision 5928)
+++ /code/trunk/src/libraries/network/synchronisable/Synchronisable.h	(revision 5929)
@@ -68,11 +68,11 @@
    * @brief: stores information about a Synchronisable 
    * 
-   * This class stores the information about a Synchronisable (objectID, classID, creatorID, dataSize)
+   * This class stores the information about a Synchronisable (objectID_, classID_, creatorID_, dataSize)
    * in an emulated bitset.
    * Bit 1 to 31 store the size of the Data the synchronisable consumes in the stream
    * Bit 32 is a bool and defines whether the data is actually stored or is just filled up with 0
-   * Byte 5 to 8: objectID
-   * Byte 9 to 12: classID
-   * Byte 13 to 16: creatorID
+   * Byte 5 to 8: objectID_
+   * Byte 9 to 12: classID_
+   * Byte 13 to 16: creatorID_
    */
   class _NetworkExport SynchronisableHeader{
@@ -94,14 +94,14 @@
       inline uint32_t getObjectID() const
         { return *(uint32_t*)(data_+4); }
-      inline void setObjectID(uint32_t objectID)
-        { *(uint32_t*)(data_+4) = objectID; }
+      inline void setObjectID(uint32_t objectID_)
+        { *(uint32_t*)(data_+4) = objectID_; }
       inline uint32_t getClassID() const
         { return *(uint32_t*)(data_+8); }
-      inline void setClassID(uint32_t classID)
-        { *(uint32_t*)(data_+8) = classID; }
+      inline void setClassID(uint32_t classID_)
+        { *(uint32_t*)(data_+8) = classID_; }
       inline uint32_t getCreatorID() const
         { return *(uint32_t*)(data_+12); }
-      inline void setCreatorID(uint32_t creatorID)
-        { *(uint32_t*)(data_+12) = creatorID; }
+      inline void setCreatorID(uint32_t creatorID_)
+        { *(uint32_t*)(data_+12) = creatorID_; }
       inline void operator=(SynchronisableHeader& h)
         { memcpy(data_, h.data_, getSize()); }
@@ -122,13 +122,16 @@
 
     static Synchronisable *fabricate(uint8_t*& mem, uint8_t mode=0x0);
-    static bool deleteObject(uint32_t objectID);
-    static Synchronisable *getSynchronisable(uint32_t objectID);
+    static bool deleteObject(uint32_t objectID_);
+    static Synchronisable *getSynchronisable(uint32_t objectID_);
     static unsigned int getNumberOfDeletedObject(){ return deletedObjects_.size(); }
     static uint32_t popDeletedObject(){ uint32_t i = deletedObjects_.front(); deletedObjects_.pop(); return i; }
 
-    inline uint32_t getObjectID() const {return objectID;}
-    inline unsigned int getCreatorID() const {return creatorID;}
-    inline uint32_t getClassID() const {return classID;}
-    inline unsigned int getPriority() const { return objectFrequency_;}
+    inline uint32_t getObjectID() const {return this->objectID_;}
+    inline unsigned int getCreatorID() const {return this->creatorID_;}
+    inline uint32_t getClassID() const {return this->classID_;}
+    inline unsigned int getPriority() const { return this->objectFrequency_;}
+    inline uint8_t getSyncMode() const { return this->objectMode_; }
+    
+    void setSyncMode(uint8_t mode);
 
   protected:
@@ -136,5 +139,4 @@
     template <class T> void registerVariable(T& variable, uint8_t mode=0x1, NetworkCallbackBase *cb=0, bool bidirectional=false);
     //template <class T> void unregisterVariable(T& var);
-    void setObjectMode(uint8_t mode);
     void setPriority(unsigned int freq){ objectFrequency_ = freq; }
 
@@ -146,8 +148,11 @@
     bool isMyData(uint8_t* mem);
     bool doSync(int32_t id, uint8_t mode=0x0);
-
-    uint32_t objectID;
-    uint32_t creatorID;
-    uint32_t classID;
+    
+    inline void setObjectID(uint32_t id){ this->objectID_ = id; objectMap_[this->objectID_] = this; }
+    inline void setClassID(uint32_t id){ this->classID_ = id; }
+
+    uint32_t objectID_;
+    uint32_t creatorID_;
+    uint32_t classID_;
 
     std::vector<SynchronisableVariableBase*> syncList;
Index: /code/trunk/src/libraries/tools/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/tools/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/tools/CMakeLists.txt	(revision 5929)
@@ -1,3 +1,10 @@
-ADD_SOURCE_FILES(TOOLS_SRC_FILES
+SET_SOURCE_FILES(TOOLS_SRC_FILES
+COMPILATION_BEGIN ResourceCompilation.cc
+  ResourceCollection.cc
+  ResourceLocation.cc
+COMPILATION_END
+  TextureGenerator.cc
+  Timer.cc
+COMPILATION_BEGIN OgreCompilation.cc
   BillboardSet.cc
   DynamicLines.cc
@@ -5,9 +12,6 @@
   Mesh.cc
   ParticleInterface.cc
-  ResourceCollection.cc
-  ResourceLocation.cc
   Shader.cc
-  TextureGenerator.cc
-  Timer.cc
+COMPILATION_END
 )
 ADD_SUBDIRECTORY(interfaces)
@@ -15,6 +19,4 @@
 ORXONOX_ADD_LIBRARY(tools
   FIND_HEADER_FILES
-  PCH_FILE
-    ToolsPrecompiledHeaders.h
   DEFINE_SYMBOL
     "TOOLS_SHARED_BUILD"
Index: /code/trunk/src/libraries/tools/ResourceLocation.cc
===================================================================
--- /code/trunk/src/libraries/tools/ResourceLocation.cc	(revision 5928)
+++ /code/trunk/src/libraries/tools/ResourceLocation.cc	(revision 5929)
@@ -33,6 +33,6 @@
 
 #include "util/Exception.h"
-#include "core/Core.h"
 #include "core/CoreIncludes.h"
+#include "core/PathConfig.h"
 #include "core/XMLFile.h"
 #include "core/XMLPort.h"
@@ -71,9 +71,10 @@
 
         // Find the path
-        boost::filesystem::path path;
-        if (boost::filesystem::exists(Core::getDataPath() / this->getPath()))
-            path = Core::getDataPath() / this->getPath();
-        else if (Core::isDevelopmentRun() && boost::filesystem::exists(Core::getExternalDataPath() / this->getPath()))
-            path = Core::getExternalDataPath() / this->getPath();
+        namespace bf = boost::filesystem;
+        bf::path path;
+        if (bf::exists(PathConfig::getDataPath() / this->getPath()))
+            path = PathConfig::getDataPath() / this->getPath();
+        else if (PathConfig::isDevelopmentRun() && bf::exists(PathConfig::getExternalDataPath() / this->getPath()))
+            path = PathConfig::getExternalDataPath() / this->getPath();
         else
         {
Index: /code/trunk/src/libraries/tools/Timer.cc
===================================================================
--- /code/trunk/src/libraries/tools/Timer.cc	(revision 5928)
+++ /code/trunk/src/libraries/tools/Timer.cc	(revision 5929)
@@ -31,8 +31,8 @@
 #include <set>
 
+#include "util/Clock.h"
 #include "core/CoreIncludes.h"
 #include "core/ConsoleCommand.h"
 #include "core/CommandExecutor.h"
-#include "core/Clock.h"
 #include "core/Functor.h"
 
@@ -42,5 +42,5 @@
     SetConsoleCommandShortcutExtern(killdelays);
 
-    static std::set<StaticTimer*> delaytimerset;
+    static std::set<Timer*> delaytimerset;
 
     /**
@@ -51,5 +51,5 @@
     void delay(float delay, const std::string& command)
     {
-        StaticTimer *delaytimer = new StaticTimer();
+        Timer* delaytimer = new Timer();
         delaytimerset.insert(delaytimer);
 
@@ -64,8 +64,8 @@
         @param command The command to execute
     */
-    void executeDelayedCommand(StaticTimer* timer, const std::string& command)
+    void executeDelayedCommand(Timer* timer, const std::string& command)
     {
         CommandExecutor::execute(command);
-        delete timer;
+        timer->destroy();
         delaytimerset.erase(timer);
     }
@@ -76,6 +76,6 @@
     void killdelays()
     {
-        for (std::set<StaticTimer*>::iterator it = delaytimerset.begin(); it != delaytimerset.end(); ++it)
-            delete (*it);
+        for (std::set<Timer*>::iterator it = delaytimerset.begin(); it != delaytimerset.end(); ++it)
+            (*it)->destroy();
 
         delaytimerset.clear();
@@ -85,5 +85,36 @@
         @brief Constructor: Sets the default-values.
     */
-    TimerBase::TimerBase()
+    Timer::Timer()
+    {
+        this->init();
+        RegisterObject(Timer);
+    }
+
+    /**
+        @brief Constructor: Initializes the Timer with given values.
+        @param interval The timer-interval in seconds
+        @param bLoop If true, the function gets called every 'interval' seconds
+        @param exeuctor A executor of the function to call
+    */
+    Timer::Timer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall)
+    {
+        this->init();
+        RegisterObject(Timer);
+
+        this->setTimer(interval, bLoop, executor, bKillAfterCall);
+    }
+
+    /**
+        @brief Deletes the executor.
+    */
+    Timer::~Timer()
+    {
+        this->deleteExecutor();
+    }
+    
+    /**
+        @brief Initializes the Timer
+    */
+    void Timer::init()
     {
         this->executor_ = 0;
@@ -94,14 +125,4 @@
 
         this->time_ = 0;
-
-        RegisterObject(TimerBase);
-    }
-
-    /**
-        @brief Deletes the executor.
-    */
-    TimerBase::~TimerBase()
-    {
-        this->deleteExecutor();
     }
 
@@ -109,5 +130,5 @@
         @brief Executes the executor.
     */
-    void TimerBase::run() const
+    void Timer::run()
     {
         bool temp = this->bKillAfterCall_; // to avoid errors with bKillAfterCall_=false and an exutors which destroy the timer
@@ -116,5 +137,5 @@
 
         if (temp)
-            delete this;
+            this->destroy();
     }
 
@@ -122,5 +143,5 @@
         @brief Deletes the executor.
     */
-    void TimerBase::deleteExecutor()
+    void Timer::deleteExecutor()
     {
       if (this->executor_)
@@ -131,5 +152,5 @@
         @brief Updates the timer before the frames are rendered.
     */
-    void TimerBase::tick(const Clock& time)
+    void Timer::tick(const Clock& time)
     {
         if (this->bActive_)
Index: /code/trunk/src/libraries/tools/Timer.h
===================================================================
--- /code/trunk/src/libraries/tools/Timer.h	(revision 5928)
+++ /code/trunk/src/libraries/tools/Timer.h	(revision 5929)
@@ -40,5 +40,5 @@
                 ClassName();
                 void functionName();
-                Timer<ClassName> myTimer;
+                Timer myTimer;
         };
 
@@ -48,5 +48,5 @@
         ClassName::ClassName()
         {
-            myTimer.setTimer(interval_in_seconds, bLoop, this, createExecutor(createFunctor(&ClassName::functionName)));
+            myTimer.setTimer(interval_in_seconds, bLoop, createExecutor(createFunctor(&ClassName::functionName, this)));
         }
 
@@ -69,16 +69,38 @@
 namespace orxonox
 {
-    class StaticTimer;
     void delay(float delay, const std::string& command);
     void killdelays();
-    void executeDelayedCommand(StaticTimer* timer, const std::string& command);
+    void executeDelayedCommand(Timer* timer, const std::string& command);
 
-    //! TimerBase is the parent of the Timer class.
-    class _ToolsExport TimerBase : public TimeFactorListener
+    //! The Timer is a callback-object, calling a given function after a given time-interval.
+    class _ToolsExport Timer : public TimeFactorListener
     {
         public:
-            ~TimerBase();
+            Timer();
+            ~Timer();
 
-            void run() const;
+            Timer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall = false);
+
+            /**
+                @brief Initializes the Timer with given values.
+                @param interval The timer-interval in seconds
+                @param bLoop If true, the function gets called every 'interval' seconds
+                @param object The object owning the timer and the function
+                @param executor A executor of the function to call
+            */
+            void setTimer(float interval, bool bLoop, Executor* executor, bool bKillAfterCall = false)
+            {
+                this->deleteExecutor();
+
+                this->setInterval(interval);
+                this->bLoop_ = bLoop;
+                this->executor_ = executor;
+                this->bActive_ = true;
+
+                this->time_ = this->interval_;
+                this->bKillAfterCall_ = bKillAfterCall;
+            }
+
+            void run();
             void deleteExecutor();
 
@@ -116,7 +138,7 @@
             void tick(const Clock& time);
 
-        protected:
-            TimerBase();
-
+        private:
+            void init();
+        
             Executor* executor_;  //!< The executor of the function that should be called when the time expires
 
@@ -128,84 +150,4 @@
             long long time_;      //!< Internal variable, counting the time till the next function-call
     };
-
-    //! The Timer is a callback-object, calling a given function after a given time-interval.
-    template <class T = BaseObject>
-    class Timer : public TimerBase
-    {
-        public:
-            Timer() {}
-
-            /**
-                @brief Constructor: Initializes the Timer with given values.
-                @param interval The timer-interval in seconds
-                @param bLoop If true, the function gets called every 'interval' seconds
-                @param object The object owning the timer and the function
-                @param exeuctor A executor of the function to call
-            */
-            Timer(float interval, bool bLoop, T* object, ExecutorMember<T>* exeuctor, bool bKillAfterCall = false)
-            {
-                this->setTimer(interval, bLoop, object, exeuctor, bKillAfterCall);
-            }
-
-            /**
-                @brief Initializes the Timer with given values.
-                @param interval The timer-interval in seconds
-                @param bLoop If true, the function gets called every 'interval' seconds
-                @param object The object owning the timer and the function
-                @param exeuctor A executor of the function to call
-            */
-            void setTimer(float interval, bool bLoop, T* object, ExecutorMember<T>* executor, bool bKillAfterCall = false)
-            {
-                this->deleteExecutor();
-
-                this->setInterval(interval);
-                this->bLoop_ = bLoop;
-                executor->setObject(object);
-                this->executor_ = static_cast<Executor*>(executor);
-                this->bActive_ = true;
-
-                this->time_ = this->interval_;
-                this->bKillAfterCall_ = bKillAfterCall;
-            }
-    };
-
-    //! The StaticTimer is a callback-object, calling a static function after a given time-interval.
-    class _ToolsExport StaticTimer : public TimerBase
-    {
-        public:
-            StaticTimer() {}
-
-            /**
-                @brief Constructor: Initializes the Timer with given values.
-                @param interval The timer-interval in seconds
-                @param bLoop If true, the function gets called every 'interval' seconds
-                @param exeuctor A executor of the function to call
-            */
-            StaticTimer(float interval, bool bLoop, ExecutorStatic* executor, bool bKillAfterCall = false)
-            {
-                this->setTimer(interval, bLoop, executor, bKillAfterCall);
-            }
-
-            /**
-                @brief Initializes the Timer with given values.
-                @param interval The timer-interval in seconds
-                @param bLoop If true, the function gets called every 'interval' seconds
-                @param object The object owning the timer and the function
-                @param executor A executor of the function to call
-            */
-            void setTimer(float interval, bool bLoop, ExecutorStatic* executor, bool bKillAfterCall = false)
-            {
-                this->deleteExecutor();
-
-                this->setInterval(interval);
-                this->bLoop_ = bLoop;
-                this->executor_ = executor;
-                this->bActive_ = true;
-
-                this->time_ = this->interval_;
-                this->bKillAfterCall_ = bKillAfterCall;
-            }
-    };
-
 }
 
Index: de/trunk/src/libraries/tools/ToolsPrecompiledHeaders.h
===================================================================
--- /code/trunk/src/libraries/tools/ToolsPrecompiledHeaders.h	(revision 5928)
+++ 	(revision )
@@ -1,70 +1,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
-    Compilation of the most often used header files in the tools library
-@details
-    Updated: 19. September 2009
-    Total Files: 11
-*/
-
-#include "OrxonoxConfig.h"
-
-///////////////////////////////////////////
-/////          Stable Headers         /////
-///////////////////////////////////////////
-
-#include <cassert>  // 11
-#include <cstring>  // 11
-#include <fstream>  // 11
-#include <iostream> // 11
-#include <map>      // 11
-#include <set>      // 11
-#include <sstream>  // 11
-#include <string>   // 11
-#include <vector>   // 11
-#include <cmath>    // 10
-#include <deque>    // 10
-#include <list>     // 10
-#include <queue>    // 10
-
-#include <OgreMath.h>        // 10
-#include <OgreVector2.h>     // 10
-#include <OgreVector3.h>     // 10
-#include <OgreVector4.h>     // 10
-#include <OgreQuaternion.h>  // 10
-#include <OgreColourValue.h> // 10
-
-#include "util/Debug.h"      // 9
-
-
-// Just in case some header included windows.h
-#undef min
-#undef max
Index: /code/trunk/src/libraries/tools/ToolsPrereqs.h
===================================================================
--- /code/trunk/src/libraries/tools/ToolsPrereqs.h	(revision 5928)
+++ /code/trunk/src/libraries/tools/ToolsPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the tools module
 */
 
@@ -40,4 +41,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef TOOLS_SHARED_BUILD
@@ -57,5 +59,5 @@
 
 //-----------------------------------------------------------------------
-// Forward declarations
+// Enums
 //-----------------------------------------------------------------------
 
@@ -72,12 +74,21 @@
         };
     }
+}
 
+//-----------------------------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
     class BillboardSet;
     class Mesh;
     class ParticleInterface;
+    class ResourceCollection;
+    class ResourceLocation;
     class Shader;
-    template <class T>
+    class Tickable;
+    class TimeFactorListener;
     class Timer;
-    class StaticTimer;
 }
 
Index: /code/trunk/src/libraries/util/CMakeLists.txt
===================================================================
--- /code/trunk/src/libraries/util/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/libraries/util/CMakeLists.txt	(revision 5929)
@@ -19,17 +19,20 @@
 
 SET_SOURCE_FILES(UTIL_SRC_FILES
-  Clipboard.cc
-  CRC32.cc
   Exception.cc
-  ExprParser.cc
   Math.cc
   MultiType.cc
+  Scope.cc
+  StringUtils.cc
+COMPILATION_BEGIN StableCompilation.cc
+  Clipboard.cc
+  Clock.cc
+  CRC32.cc
+  ExprParser.cc
   OutputBuffer.cc
   OutputHandler.cc
-  Scope.cc
   SignalHandler.cc
   Sleep.cc
-  StringUtils.cc
   SubString.cc
+COMPILATION_END
 )
 
Index: /code/trunk/src/libraries/util/Clock.cc
===================================================================
--- /code/trunk/src/libraries/util/Clock.cc	(revision 5929)
+++ /code/trunk/src/libraries/util/Clock.cc	(revision 5929)
@@ -0,0 +1,73 @@
+/*
+ *   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 "Clock.h"
+#include <OgreTimer.h>
+
+namespace orxonox
+{
+    Clock::Clock()
+        : timer_(new Ogre::Timer())
+        , storedTime_(0)
+        , tickTime_(0)
+        , tickDt_(0)
+        , tickDtFloat_(0.0f)
+        , lastTimersTime_(0)
+    {
+    }
+
+    Clock::~Clock()
+    {
+        delete timer_;
+    }
+    
+    void Clock::capture()
+    {
+        unsigned long timersTime = timer_->getMicroseconds();
+        tickTime_ = storedTime_ + timersTime;
+        tickDt_ = timersTime - lastTimersTime_;
+        tickDtFloat_ = static_cast<float>(tickDt_) / 1000000.0f;
+
+        if (timersTime > 0xFFFFFFFF/4)
+        {
+            // Ogre timer will overflow at 2^32 microseconds if unsigned long is 32 bit
+            storedTime_ += timersTime;
+            lastTimersTime_ = 0;
+            timer_->reset();
+        }
+        else
+        {
+            lastTimersTime_ = timersTime;
+        }
+    }
+
+    unsigned long long Clock::getRealMicroseconds() const
+    {
+        return this->timer_->getMicroseconds() + this->storedTime_;
+    }
+}
Index: /code/trunk/src/libraries/util/Clock.h
===================================================================
--- /code/trunk/src/libraries/util/Clock.h	(revision 5929)
+++ /code/trunk/src/libraries/util/Clock.h	(revision 5929)
@@ -0,0 +1,67 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _Clock_H__
+#define _Clock_H__
+
+#include "UtilPrereqs.h"
+#include "OgreForwardRefs.h"
+
+namespace orxonox
+{
+    class _UtilExport Clock
+    {
+    public:
+        Clock();
+        ~Clock();
+
+        void capture();
+
+        unsigned long long getMicroseconds()   const { return tickTime_; }
+        unsigned long long getMilliseconds()   const { return tickTime_ / 1000; }
+        unsigned long      getSeconds()        const { return static_cast<long> (tickTime_ / 1000000); }
+        float              getSecondsPrecise() const { return static_cast<float>(tickTime_ / 1000000.0f); }
+
+        float              getDeltaTime()      const { return tickDtFloat_; }
+        long               getDeltaTimeMicroseconds() const { return tickDt_; }
+
+        unsigned long long getRealMicroseconds() const;
+
+    private:
+        Clock(const Clock& instance);
+
+        Ogre::Timer*       timer_;
+        unsigned long long storedTime_;
+        unsigned long long tickTime_;
+        long               tickDt_;
+        float              tickDtFloat_;
+        unsigned long      lastTimersTime_;
+    };
+}
+
+#endif /* _Clock_H__ */
Index: /code/trunk/src/libraries/util/Scope.h
===================================================================
--- /code/trunk/src/libraries/util/Scope.h	(revision 5928)
+++ /code/trunk/src/libraries/util/Scope.h	(revision 5929)
@@ -31,26 +31,14 @@
 
 #include "UtilPrereqs.h"
+
 #include <cassert>
+#include <map>
 #include <set>
-#include <map>
+
 #include "Debug.h"
+#include "ScopeGuard.h"
 
 namespace orxonox
 {
-    namespace ScopeID
-    {
-        /**
-            @brief A list of available scopes for the Scope template.
-        */
-        enum Value
-        {
-            GSRoot,
-            GSGraphics,
-            GSLevel
-        };
-    }
-
-    class ScopeListener; // Forward declaration
-
     /**
         @brief The ScopeManager stores the variables of the scope templates in a statically linked context.
@@ -77,5 +65,5 @@
         protected:
             //! Constructor: Registers the instance.
-            ScopeListener(ScopeID::Value scope) : scope_(scope)
+            ScopeListener(ScopeID::Value scope) : scope_(scope), bActivated_(false)
                 { ScopeManager::listeners_s[this->scope_].insert(this); }
             //! Destructor: Unregisters the instance.
@@ -90,4 +78,5 @@
         private:
             ScopeID::Value scope_; //!< Store the scope to unregister on destruction
+            bool bActivated_;
     };
 
@@ -105,10 +94,23 @@
             Scope()
             {
-                ScopeManager::instanceCounts_s[scope]++;
-                assert(ScopeManager::instanceCounts_s[scope] > 0);
-                if (ScopeManager::instanceCounts_s[scope] == 1)
+                try
                 {
-                    for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
-                        (*(it++))->activated();
+                    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;
                 }
             }
@@ -125,7 +127,21 @@
 
                 if (ScopeManager::instanceCounts_s[scope] == 0)
+                    this->deactivateListeners();
+            }
+
+            void deactivateListeners()
+            {
+                for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
                 {
-                    for (typename std::set<ScopeListener*>::iterator it = ScopeManager::listeners_s[scope].begin(); it != ScopeManager::listeners_s[scope].end(); )
-                        (*(it++))->deactivated();
+                    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;
                 }
             }
Index: de/trunk/src/libraries/util/ScopedSingleton.h
===================================================================
--- /code/trunk/src/libraries/util/ScopedSingleton.h	(revision 5928)
+++ 	(revision )
@@ -1,102 +1,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 __Util_ScopedSingleton_H__
-#define __Util_ScopedSingleton_H__
-
-#include "UtilPrereqs.h"
-#include <cassert>
-
-#include "Scope.h"
-
-namespace orxonox
-{
-    /**
-    @brief
-        Base for scoped singleton classes.
-        A Scoped singleton creates itself if the scope is active and getInstance() is called.
-        Destroys itself if the scope is deactivated.
-
-        Usage:
-        Inherit publicly from ScopedSingleton<MyClass, scope> and provide access to
-        MyClass::singletonPtr_s.
-        This can easily be done with a friend declaration.
-
-        See @ref UtilPrereqs.h for a list of scopes (ScopeID::Value).
-    */
-    template <class T, ScopeID::Value scope>
-    class ScopedSingleton : public ScopeListener
-    {
-        public:
-            //! Returns a reference to the singleton instance
-            static T& getInstance()
-            {
-                assert(Scope<scope>::isActive());
-
-                if (!T::singletonPtr_s && Scope<scope>::isActive())
-                    T::singletonPtr_s = new T();
-
-                return *T::singletonPtr_s;
-            }
-
-        protected:
-            //! Constructor sets the singleton instance pointer
-            ScopedSingleton() : ScopeListener(scope)
-            {
-                assert(T::singletonPtr_s == 0);
-                T::singletonPtr_s = static_cast<T*>(this);
-            }
-
-            //! Constructor resets the singleton instance pointer
-            ~ScopedSingleton()
-            {
-                assert(T::singletonPtr_s != 0);
-                T::singletonPtr_s = 0;
-            }
-
-        private:
-            //! Called if the Scope of this Singleton gets active (no instance should be active then)
-            void activated()
-            {
-                // The ScopedSingleton shouldn't be active bevor the scope is activated -> always assertion failed
-                assert(T::singletonPtr_s == 0 && false);
-            }
-
-            //! Called if the Scope of this Singleton gets deactivated (destroys the instance)
-            void deactivated()
-            {
-                if (T::singletonPtr_s)
-                {
-                    delete T::singletonPtr_s;
-                    T::singletonPtr_s = 0;
-                }
-            }
-    };
-}
-
-#endif /* __Util_ScopedSingleton_H__ */
Index: /code/trunk/src/libraries/util/Singleton.h
===================================================================
--- /code/trunk/src/libraries/util/Singleton.h	(revision 5928)
+++ /code/trunk/src/libraries/util/Singleton.h	(revision 5929)
@@ -55,4 +55,9 @@
         }
 
+        //! Update method called by ClassSingletonManager (if used)
+        void updateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->update(time); }
+        //! Empty update method for the static polymorphism
+        void update(const Clock& time) { }
+
     protected:
         //! Constructor sets the singleton instance pointer
Index: /code/trunk/src/libraries/util/UtilPrereqs.h
===================================================================
--- /code/trunk/src/libraries/util/UtilPrereqs.h	(revision 5928)
+++ /code/trunk/src/libraries/util/UtilPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the util library
 */
 
@@ -40,4 +41,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( UTIL_STATIC_BUILD )
 #  ifdef UTIL_SHARED_BUILD
@@ -56,4 +58,20 @@
 #endif
 
+//-----------------------------------------------------------------------
+// Enums
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
+    namespace ScopeID
+    {
+        //!A list of available scopes for the Scope template.
+        enum Value
+        {
+            Root,
+            Graphics
+        };
+    }
+}
 
 //-----------------------------------------------------------------------
@@ -63,4 +81,5 @@
 namespace orxonox
 {
+    class Clock;
     class Exception;
     class ExprParser;
@@ -71,5 +90,12 @@
     class OutputBufferListener;
     class OutputHandler;
+    template <ScopeID::Value>
+    class Scope;
+    template <class, ScopeID::Value>
+    class ScopedSingleton;
+    class ScopeListener;
     class SignalHandler;
+    template <class T>
+    class Singleton;
     class SubString;
 }
Index: /code/trunk/src/modules/CMakeLists.txt
===================================================================
--- /code/trunk/src/modules/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/modules/CMakeLists.txt	(revision 5929)
@@ -27,5 +27,4 @@
 ################ Sub Directories ################
 
-ADD_SUBDIRECTORY(gamestates)
 ADD_SUBDIRECTORY(objects)
 ADD_SUBDIRECTORY(overlays)
Index: /code/trunk/src/modules/objects/Attacher.cc
===================================================================
--- /code/trunk/src/modules/objects/Attacher.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/Attacher.cc	(revision 5929)
@@ -53,6 +53,6 @@
     void Attacher::processEvent(Event& event)
     {
-        for (std::list<WorldEntity*>::iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
-            (*it)->fireEvent(event);
+        if (this->target_)
+            this->target_->processEvent(event);
     }
 
@@ -102,6 +102,11 @@
 
         for (ObjectList<WorldEntity>::iterator it = ObjectList<WorldEntity>::begin(); it != ObjectList<WorldEntity>::end(); ++it)
+        {
             if (it->getName() == this->targetname_)
+            {
+                this->target_ = *it;
                 this->attachToParent(*it);
+            }
+        }
     }
 
Index: /code/trunk/src/modules/objects/ObjectsPrereqs.h
===================================================================
--- /code/trunk/src/modules/objects/ObjectsPrereqs.h	(revision 5928)
+++ /code/trunk/src/modules/objects/ObjectsPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the objects module
 */
 
@@ -36,5 +37,4 @@
 
 #include "OrxonoxConfig.h"
-
 #include "OrxonoxPrereqs.h"
 
@@ -42,4 +42,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef OBJECTS_SHARED_BUILD
@@ -76,13 +77,15 @@
 
     // eventsystem
+    class EventDispatcher;
+    class EventFilter;
     class EventListener;
-    class EventDispatcher;
+    class EventName;
     class EventTarget;
 
     // triggers
-    class Trigger;
+    class CheckPoint;
     class DistanceTrigger;
     class EventTrigger;
-    class CheckPoint;
+    class Trigger;
 }
 
Index: /code/trunk/src/modules/objects/Planet.cc
===================================================================
--- /code/trunk/src/modules/objects/Planet.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/Planet.cc	(revision 5929)
@@ -47,5 +47,5 @@
      * @brief Constructor
      */
-    Planet::Planet(BaseObject* creator): MovableEntity(creator)
+    Planet::Planet(BaseObject* creator) : MovableEntity(creator)
     {
         RegisterObject(Planet);
@@ -64,5 +64,5 @@
     void Planet::tick(float dt)
     {
-        if(!this->isVisible())
+        if (!this->isVisible())
             return;
 
@@ -70,5 +70,5 @@
         {
             Camera* activeCamera = CameraManager::getInstance().getActiveCamera();
-            if(activeCamera)
+            if (activeCamera)
             {
                 float distance = this->getPosition().distance( activeCamera->getWorldPosition() );
Index: /code/trunk/src/modules/objects/eventsystem/CMakeLists.txt
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/CMakeLists.txt	(revision 5929)
@@ -1,5 +1,7 @@
 ADD_SOURCE_FILES(OBJECTS_SRC_FILES
   EventDispatcher.cc
+  EventFilter.cc
   EventListener.cc
+  EventName.cc
   EventTarget.cc
 )
Index: /code/trunk/src/modules/objects/eventsystem/EventDispatcher.cc
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventDispatcher.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventDispatcher.cc	(revision 5929)
@@ -32,5 +32,4 @@
 #include "core/EventIncludes.h"
 #include "core/XMLPort.h"
-#include "EventTarget.h"
 
 namespace orxonox
@@ -46,6 +45,6 @@
     {
         if (this->isInitialized())
-            for (std::list<EventTarget*>::iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
-                delete (*it);
+            for (std::list<BaseObject*>::iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
+                (*it)->destroy();
     }
 
@@ -54,22 +53,25 @@
         SUPER(EventDispatcher, XMLPort, xmlelement, mode);
 
-        XMLPortObject(EventDispatcher, EventTarget, "targets", addTarget, getTarget, xmlelement, mode);
+        XMLPortObject(EventDispatcher, BaseObject, "targets", addTarget, getTarget, xmlelement, mode);
+
+        // since we need event sources mapped to any state, we have to parse XML by ourselves
+        this->loadAllEventStates(xmlelement, mode, this, Class(EventDispatcher));
     }
 
     void EventDispatcher::processEvent(Event& event)
     {
-        for (std::list<EventTarget*>::iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
-            (*it)->fireEvent(event);
+        for (std::list<BaseObject*>::iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
+            (*it)->processEvent(event);
     }
 
-    void EventDispatcher::addTarget(EventTarget* target)
+    void EventDispatcher::addTarget(BaseObject* target)
     {
         this->targets_.push_back(target);
     }
 
-    EventTarget* EventDispatcher::getTarget(unsigned int index) const
+    BaseObject* EventDispatcher::getTarget(unsigned int index) const
     {
         unsigned int i = 0;
-        for (std::list<EventTarget*>::const_iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
+        for (std::list<BaseObject*>::const_iterator it = this->targets_.begin(); it != this->targets_.end(); ++it)
         {
             if (i == index)
Index: /code/trunk/src/modules/objects/eventsystem/EventDispatcher.h
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventDispatcher.h	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventDispatcher.h	(revision 5929)
@@ -47,9 +47,9 @@
             virtual void processEvent(Event& event);
 
-            void addTarget(EventTarget* target);
-            EventTarget* getTarget(unsigned int index) const;
+            void addTarget(BaseObject* target);
+            BaseObject* getTarget(unsigned int index) const;
 
         private:
-            std::list<EventTarget*> targets_;
+            std::list<BaseObject*> targets_;
     };
 }
Index: /code/trunk/src/modules/objects/eventsystem/EventFilter.cc
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventFilter.cc	(revision 5929)
+++ /code/trunk/src/modules/objects/eventsystem/EventFilter.cc	(revision 5929)
@@ -0,0 +1,122 @@
+/*
+ *   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 "EventFilter.h"
+
+#include "core/CoreIncludes.h"
+#include "core/XMLPort.h"
+#include "EventName.h"
+
+namespace orxonox
+{
+    CreateFactory(EventFilter);
+
+    EventFilter::EventFilter(BaseObject* creator) : BaseObject(creator)
+    {
+        RegisterObject(EventFilter);
+
+        this->bActive_ = false;
+    }
+
+    EventFilter::~EventFilter()
+    {
+        for (std::list<EventName*>::const_iterator it = this->names_.begin(); it != this->names_.end(); )
+            (*(it++))->destroy();
+    }
+
+    void EventFilter::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(EventFilter, XMLPort, xmlelement, mode);
+
+        XMLPortObject(EventFilter, BaseObject, "", addFilterSource, getFilterSource, xmlelement, mode);
+        XMLPortObject(EventFilter, EventName, "names", addEventName, getEventName, xmlelement, mode);
+    }
+
+    void EventFilter::processEvent(Event& event)
+    {
+        if (this->bActive_)
+        {
+            COUT(2) << "Warning: Detected Event loop in EventFilter \"" << this->getName() << "\"" << std::endl;
+            return;
+        }
+
+        if (this->names_.size() > 0)
+        {
+            bool success = false;
+            for (std::list<EventName*>::const_iterator it = this->names_.begin(); it != this->names_.end(); ++it)
+            {
+                if ((*it)->getName() == event.name_)
+                {
+                    success = true;
+                    break;
+                }
+            }
+            if (!success)
+                return;
+        }
+
+        this->bActive_ = true;
+        this->fireEvent(event.activate_, event.originator_, event.name_);
+        this->bActive_ = false;
+    }
+
+    void EventFilter::addFilterSource(BaseObject* source)
+    {
+        this->sources_.push_back(source);
+        this->addEventSource(source, "");
+    }
+
+    BaseObject* EventFilter::getFilterSource(unsigned int index) const
+    {
+        unsigned int i = 0;
+        for (std::list<BaseObject*>::const_iterator it = this->sources_.begin(); it != this->sources_.end(); ++it)
+        {
+            if (i == index)
+                return (*it);
+            ++i;
+        }
+        return 0;
+    }
+
+    void EventFilter::addEventName(EventName* eventname)
+    {
+        this->names_.push_back(eventname);
+    }
+
+    EventName* EventFilter::getEventName(unsigned int index) const
+    {
+        unsigned int i = 0;
+        for (std::list<EventName*>::const_iterator it = this->names_.begin(); it != this->names_.end(); ++it)
+        {
+            if (i == index)
+                return (*it);
+            ++i;
+        }
+        return 0;
+    }
+}
Index: /code/trunk/src/modules/objects/eventsystem/EventFilter.h
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventFilter.h	(revision 5929)
+++ /code/trunk/src/modules/objects/eventsystem/EventFilter.h	(revision 5929)
@@ -0,0 +1,62 @@
+/*
+ *   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 _EventFilter_H__
+#define _EventFilter_H__
+
+#include "objects/ObjectsPrereqs.h"
+
+#include <list>
+#include "core/BaseObject.h"
+
+namespace orxonox
+{
+    class _ObjectsExport EventFilter : public BaseObject
+    {
+        public:
+            EventFilter(BaseObject* creator);
+            virtual ~EventFilter();
+
+            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+
+            virtual void processEvent(Event& event);
+
+            void addFilterSource(BaseObject* source);
+            BaseObject* getFilterSource(unsigned int index) const;
+
+            void addEventName(EventName* eventname);
+            EventName* getEventName(unsigned int index) const;
+
+        private:
+            std::list<BaseObject*> sources_;
+            std::list<EventName*> names_;
+            bool bActive_;
+    };
+}
+
+#endif /* _EventFilter_H__ */
Index: /code/trunk/src/modules/objects/eventsystem/EventListener.cc
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventListener.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventListener.cc	(revision 5929)
@@ -63,7 +63,5 @@
 
         this->bActive_ = true;
-
-        this->fireEvent(event.activate_, event.originator_);
-
+        this->fireEvent(event.activate_, event.originator_, event.name_);
         this->bActive_ = false;
     }
@@ -78,5 +76,5 @@
         for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); ++it)
             if (it->getName() == this->eventName_)
-                this->registerAsListener(*it);
+                this->addEventSource(*it, "");
     }
 
@@ -87,10 +85,5 @@
 
         if (object->getName() == this->eventName_)
-            this->registerAsListener(object);
-    }
-
-    void EventListener::registerAsListener(BaseObject* object)
-    {
-        object->registerEventListener(this, "");
+            this->addEventSource(object, "");
     }
 }
Index: /code/trunk/src/modules/objects/eventsystem/EventListener.h
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventListener.h	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventListener.h	(revision 5929)
@@ -54,5 +54,4 @@
         private:
             virtual void loadedNewXMLName(BaseObject* object);
-            void registerAsListener(BaseObject* object);
 
             std::string eventName_;
Index: /code/trunk/src/modules/objects/eventsystem/EventName.cc
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventName.cc	(revision 5929)
+++ /code/trunk/src/modules/objects/eventsystem/EventName.cc	(revision 5929)
@@ -0,0 +1,40 @@
+/*
+ *   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 "EventName.h"
+#include "core/CoreIncludes.h"
+
+namespace orxonox
+{
+    CreateFactory(EventName);
+
+    EventName::EventName(BaseObject* creator) : BaseObject(creator)
+    {
+        RegisterObject(EventName);
+    }
+}
Index: /code/trunk/src/modules/objects/eventsystem/EventName.h
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventName.h	(revision 5929)
+++ /code/trunk/src/modules/objects/eventsystem/EventName.h	(revision 5929)
@@ -0,0 +1,46 @@
+/*
+ *   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 _EventName_H__
+#define _EventName_H__
+
+#include "objects/ObjectsPrereqs.h"
+
+#include "core/BaseObject.h"
+
+namespace orxonox
+{
+    class _ObjectsExport EventName : public BaseObject
+    {
+        public:
+            EventName(BaseObject* creator);
+            virtual ~EventName() {}
+    };
+}
+
+#endif /* _EventName_H__ */
Index: /code/trunk/src/modules/objects/eventsystem/EventTarget.cc
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventTarget.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventTarget.cc	(revision 5929)
@@ -29,4 +29,5 @@
 #include "EventTarget.h"
 #include "core/CoreIncludes.h"
+#include "core/XMLPort.h"
 
 namespace orxonox
@@ -37,4 +38,6 @@
     {
         RegisterObject(EventTarget);
+
+        this->bActive_ = false;
     }
 
@@ -42,27 +45,50 @@
     {
     }
+    
+    void EventTarget::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(EventTarget, XMLPort, xmlelement, mode);
 
-    void EventTarget::changedName()
+        XMLPortParam(EventTarget, "target", setTargetName, getTargetName, xmlelement, mode);
+
+        // since we need event sources mapped to any state, we have to parse XML by ourselves
+        this->loadAllEventStates(xmlelement, mode, this, Class(EventTarget));
+    }
+
+    void EventTarget::processEvent(Event& event)
     {
-        SUPER(EventTarget, changedName);
+        if (this->bActive_)
+        {
+            COUT(2) << "Warning: Detected Event loop in EventTarget \"" << this->getName() << "\"" << std::endl;
+            return;
+        }
 
+        this->bActive_ = true;
+        this->fireEvent(event);
+        this->bActive_ = false;
+    }
+
+    void EventTarget::setTargetName(const std::string& name)
+    {
+        this->target_ = name;
+        
         for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); ++it)
-            if (it->getName() == this->getName())
-                this->addAsEvent(*it);
+            if (it->getName() == this->target_)
+                this->addEventTarget(*it);
     }
 
     void EventTarget::loadedNewXMLName(BaseObject* object)
     {
-        if (this->getName() == "")
+        if (this->target_ == "")
             return;
 
-        if (object->getName() == this->getName())
-            this->addAsEvent(object);
+        if (object->getName() == this->target_)
+            this->addEventTarget(object);
     }
 
-    void EventTarget::addAsEvent(BaseObject* object)
+    void EventTarget::addEventTarget(BaseObject* object)
     {
         if (object != static_cast<BaseObject*>(this))
-            object->addEvent(this, "");
+            object->addEventSource(this, "");
     }
 }
Index: /code/trunk/src/modules/objects/eventsystem/EventTarget.h
===================================================================
--- /code/trunk/src/modules/objects/eventsystem/EventTarget.h	(revision 5928)
+++ /code/trunk/src/modules/objects/eventsystem/EventTarget.h	(revision 5929)
@@ -42,10 +42,19 @@
             EventTarget(BaseObject* creator);
             virtual ~EventTarget();
+            
+            virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+            
+            virtual void processEvent(Event& event);
 
-            virtual void changedName();
+            void setTargetName(const std::string& name);
+            inline const std::string& getTargetName() const
+                { return this->target_; }
 
         private:
             virtual void loadedNewXMLName(BaseObject* object);
-            void addAsEvent(BaseObject* object);
+            void addEventTarget(BaseObject* object);
+            
+            std::string target_;
+            bool bActive_;
     };
 }
Index: /code/trunk/src/modules/objects/triggers/CheckPoint.cc
===================================================================
--- /code/trunk/src/modules/objects/triggers/CheckPoint.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/triggers/CheckPoint.cc	(revision 5929)
@@ -85,5 +85,5 @@
         DistanceTrigger::triggered(bIsTriggered);
 
-        Asteroids* gametype = orxonox_cast<Asteroids*>(this->getGametype());
+        Asteroids* gametype = orxonox_cast<Asteroids*>(this->getGametype().get());
         if (gametype)
         {
Index: /code/trunk/src/modules/objects/triggers/EventTrigger.cc
===================================================================
--- /code/trunk/src/modules/objects/triggers/EventTrigger.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/triggers/EventTrigger.cc	(revision 5929)
@@ -47,9 +47,9 @@
     }
 
-    void EventTrigger::processEvent(Event& event)
+    void EventTrigger::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
     {
-        SUPER(EventTrigger, processEvent, event);
+        SUPER(EventTrigger, XMLEventPort, xmlelement, mode);
 
-        ORXONOX_SET_EVENT(EventTrigger, "trigger", trigger, event);
+        XMLPortEventState(EventTrigger, BaseObject, "trigger", trigger, xmlelement, mode);
     }
 
Index: /code/trunk/src/modules/objects/triggers/EventTrigger.h
===================================================================
--- /code/trunk/src/modules/objects/triggers/EventTrigger.h	(revision 5928)
+++ /code/trunk/src/modules/objects/triggers/EventTrigger.h	(revision 5929)
@@ -41,5 +41,5 @@
             virtual ~EventTrigger();
 
-            virtual void processEvent(Event& event);
+            virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
 
             inline void trigger(bool bTriggered)
Index: /code/trunk/src/modules/objects/triggers/Trigger.cc
===================================================================
--- /code/trunk/src/modules/objects/triggers/Trigger.cc	(revision 5928)
+++ /code/trunk/src/modules/objects/triggers/Trigger.cc	(revision 5929)
@@ -72,5 +72,5 @@
     }
 
-    this->setObjectMode(0x0);
+    this->setSyncMode(0x0);
   }
 
Index: /code/trunk/src/modules/overlays/FadeoutText.cc
===================================================================
--- /code/trunk/src/modules/overlays/FadeoutText.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/FadeoutText.cc	(revision 5929)
@@ -46,5 +46,5 @@
 
         this->bFadingOut_ = false;
-        this->fadeouttimer_.setTimer(3.0f, false, this, createExecutor(createFunctor(&FadeoutText::fadeout)));
+        this->fadeouttimer_.setTimer(3.0f, false, createExecutor(createFunctor(&FadeoutText::fadeout, this)));
         this->fadeouttimer_.stopTimer();
 
Index: /code/trunk/src/modules/overlays/FadeoutText.h
===================================================================
--- /code/trunk/src/modules/overlays/FadeoutText.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/FadeoutText.h	(revision 5929)
@@ -68,5 +68,5 @@
 
             bool bFadingOut_;
-            Timer<FadeoutText> fadeouttimer_;
+            Timer fadeouttimer_;
 
             float initialAlpha_;
Index: /code/trunk/src/modules/overlays/OverlaysPrereqs.h
===================================================================
--- /code/trunk/src/modules/overlays/OverlaysPrereqs.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/OverlaysPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the overlays module
 */
 
@@ -36,8 +37,10 @@
 
 #include "OrxonoxConfig.h"
+#include "OrxonoxPrereqs.h"
 
 //-----------------------------------------------------------------------
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef OVERLAYS_SHARED_BUILD
@@ -62,23 +65,29 @@
 namespace orxonox
 {
-    class BarColour;
+    class FadeoutText;
+    class GUIOverlay;
+    class OverlayText;
+
+    // debugging
     class DebugFPSText;
     class DebugRTRText;
-    class GUIOverlay;
+
+    // hud
+    class AnnounceMessage;
+    class BarColour;
+    class ChatOverlay;
+    class DeathMessage;
+    class GametypeStatus;
     class HUDBar;
+    class HUDHealthBar;
     class HUDNavigation;
     class HUDRadar;
     class HUDSpeedBar;
-    class HUDHealthBar;
     class HUDTimer;
-    class OrxonoxOverlay;
-    class OverlayGroup;
-    class OverlayText;
-    class FadeoutText;
-    class GametypeStatus;
-    class AnnounceMessage;
     class KillMessage;
-    class DeathMessage;
+    class TeamBaseMatchScore;
+    class UnderAttackHealthBar;
 
+    // stats
     class CreateLines;
     class Scoreboard;
Index: /code/trunk/src/modules/overlays/hud/ChatOverlay.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/ChatOverlay.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/ChatOverlay.cc	(revision 5929)
@@ -58,4 +58,6 @@
     ChatOverlay::~ChatOverlay()
     {
+        for (std::set<Timer*>::iterator it = this->timers_.begin(); it != this->timers_.end(); ++it)
+            delete (*it);
     }
 
@@ -87,14 +89,19 @@
         COUT(0) << "Chat: " << text << std::endl;
 
-        new Timer<ChatOverlay>(this->displayTime_, false, this, createExecutor(createFunctor(&ChatOverlay::dropMessage)), true);
+        Timer* timer = new Timer();
+        this->timers_.insert(timer); // store the timer in a set to destroy it in the destructor
+        Executor* executor = createExecutor(createFunctor(&ChatOverlay::dropMessage, this));
+        executor->setDefaultValues(timer);
+        timer->setTimer(this->displayTime_, false, executor, true);
 
         this->updateOverlayText();
     }
 
-    void ChatOverlay::dropMessage()
+    void ChatOverlay::dropMessage(Timer* timer)
     {
         if (this->messages_.size() > 0)
             this->messages_.pop_front();
         this->updateOverlayText();
+        this->timers_.erase(timer); // the timer destroys itself, but we have to remove it from the set
     }
 
Index: /code/trunk/src/modules/overlays/hud/ChatOverlay.h
===================================================================
--- /code/trunk/src/modules/overlays/hud/ChatOverlay.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/ChatOverlay.h	(revision 5929)
@@ -55,7 +55,8 @@
         private:
             void updateOverlayText();
-            void dropMessage();
+            void dropMessage(Timer* timer);
 
             float displayTime_;
+            std::set<Timer*> timers_;
     };
 }
Index: /code/trunk/src/modules/overlays/hud/HUDBar.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/HUDBar.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/HUDBar.cc	(revision 5929)
@@ -96,5 +96,9 @@
     {
         if (this->isInitialized())
+        {
             Ogre::OverlayManager::getSingleton().destroyOverlayElement(this->bar_);
+            for (std::vector<BarColour*>::const_iterator it = this->barColours_.begin(); it != this->barColours_.end(); )
+                (*it++)->destroy();
+        }
     }
 
Index: /code/trunk/src/modules/overlays/hud/HUDHealthBar.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/HUDHealthBar.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/HUDHealthBar.cc	(revision 5929)
@@ -56,5 +56,5 @@
     {
         if (this->isInitialized())
-            delete this->textoverlay_;
+            this->textoverlay_->destroy();
     }
 
@@ -84,4 +84,9 @@
             this->setValue(this->owner_->getHealth() / this->owner_->getInitialHealth());
             this->textoverlay_->setCaption(multi_cast<std::string>(static_cast<int>(this->owner_->getHealth())));
+        }
+        else
+        {
+            this->setValue(0);
+            this->textoverlay_->setCaption("0");
         }
 
Index: /code/trunk/src/modules/overlays/hud/HUDHealthBar.h
===================================================================
--- /code/trunk/src/modules/overlays/hud/HUDHealthBar.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/HUDHealthBar.h	(revision 5929)
@@ -111,5 +111,5 @@
 
         private:
-            Pawn* owner_;
+            WeakPtr<Pawn> owner_;
             OverlayText* textoverlay_;
             bool bUseBarColour_;
Index: /code/trunk/src/modules/overlays/hud/HUDNavigation.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/HUDNavigation.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/HUDNavigation.cc	(revision 5929)
@@ -39,4 +39,5 @@
 #include "core/CoreIncludes.h"
 #include "core/XMLPort.h"
+#include "Scene.h"
 #include "Radar.h"
 
@@ -130,5 +131,8 @@
         SUPER(HUDNavigation, tick, dt);
 
-        if (!Radar::getInstance().getFocus())
+        // Get radar
+        Radar* radar = this->getOwner()->getScene()->getRadar();
+
+        if (!radar->getFocus())
         {
             this->overlay_->hide();
@@ -150,5 +154,5 @@
 */
         // transform to screen coordinates
-        Vector3 pos = /*transformationMatrix * */Radar::getInstance().getFocus()->getRVWorldPosition();
+        Vector3 pos = /*transformationMatrix * */radar->getFocus()->getRVWorldPosition();
 
         bool outOfView;
Index: /code/trunk/src/modules/overlays/hud/TeamBaseMatchScore.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/TeamBaseMatchScore.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/TeamBaseMatchScore.cc	(revision 5929)
@@ -118,5 +118,5 @@
 
         if (this->getOwner() && this->getOwner()->getGametype())
-            this->owner_ = orxonox_cast<TeamBaseMatch*>(this->getOwner()->getGametype());
+            this->owner_ = orxonox_cast<TeamBaseMatch*>(this->getOwner()->getGametype().get());
         else
             this->owner_ = 0;
Index: /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.cc
===================================================================
--- /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.cc	(revision 5929)
@@ -52,5 +52,5 @@
         this->text_->setPickPoint(Vector2(0.5, 0));
 
-        this->inittimer_.setTimer(0.0f, false, this, createExecutor(createFunctor(&UnderAttackHealthBar::init)));
+        this->inittimer_.setTimer(0.0f, false, createExecutor(createFunctor(&UnderAttackHealthBar::init, this)));
     }
 
@@ -58,5 +58,5 @@
     {
         if (this->isInitialized())
-            delete this->text_;
+            this->text_->destroy();
     }
 
@@ -78,5 +78,5 @@
             this->owner_ = player;
 
-            UnderAttack* ua = orxonox_cast<UnderAttack*>(player->getGametype());
+            UnderAttack* ua = orxonox_cast<UnderAttack*>(player->getGametype().get());
             if (ua)
             {
Index: /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.h
===================================================================
--- /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/hud/UnderAttackHealthBar.h	(revision 5929)
@@ -62,5 +62,5 @@
             PlayerInfo* owner_;
             OverlayText* text_;
-            Timer<UnderAttackHealthBar> inittimer_;
+            Timer inittimer_;
     };
 }
Index: /code/trunk/src/modules/overlays/stats/CreateLines.cc
===================================================================
--- /code/trunk/src/modules/overlays/stats/CreateLines.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/stats/CreateLines.cc	(revision 5929)
@@ -59,8 +59,8 @@
     CreateLines::~CreateLines()
     {
-        delete this->playerNameText_;
-        delete this->scoreText_;
-        delete this->deathsText_;
-        delete this->background_;
+        this->playerNameText_->destroy();
+        this->scoreText_->destroy();
+        this->deathsText_->destroy();
+        this->background_->destroy();
     }
 
Index: /code/trunk/src/modules/overlays/stats/Scoreboard.cc
===================================================================
--- /code/trunk/src/modules/overlays/stats/Scoreboard.cc	(revision 5928)
+++ /code/trunk/src/modules/overlays/stats/Scoreboard.cc	(revision 5929)
@@ -44,4 +44,14 @@
     {
         RegisterObject(Scoreboard);
+    }
+
+    Scoreboard::~Scoreboard()
+    {
+        while (this->lines_.size() > 0)
+        {
+            // destroy lines
+            delete this->lines_.back();
+            this->lines_.pop_back();
+        }
     }
 
Index: /code/trunk/src/modules/overlays/stats/Scoreboard.h
===================================================================
--- /code/trunk/src/modules/overlays/stats/Scoreboard.h	(revision 5928)
+++ /code/trunk/src/modules/overlays/stats/Scoreboard.h	(revision 5929)
@@ -42,5 +42,5 @@
     public: // functions
         Scoreboard(BaseObject* creator);
-        virtual ~Scoreboard() {}
+        virtual ~Scoreboard();
 
         virtual void XMLPort(Element& xmlElement, XMLPort::Mode mode);
Index: /code/trunk/src/modules/pong/CMakeLists.txt
===================================================================
--- /code/trunk/src/modules/pong/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/modules/pong/CMakeLists.txt	(revision 5929)
@@ -1,3 +1,4 @@
 SET_SOURCE_FILES(PONG_SRC_FILES
+COMPILATION_BEGIN PongCompilation.cc
   Pong.cc
   PongAI.cc
@@ -7,4 +8,5 @@
   PongCenterpoint.cc
   PongScore.cc
+COMPILATION_END
 )
 
@@ -12,7 +14,4 @@
   MODULE
   FIND_HEADER_FILES
-  PCH_FILE
-    PongPrecompiledHeaders.h
-  PCH_NO_DEFAULT
   DEFINE_SYMBOL
     "PONG_SHARED_BUILD"
Index: /code/trunk/src/modules/pong/Pong.cc
===================================================================
--- /code/trunk/src/modules/pong/Pong.cc	(revision 5928)
+++ /code/trunk/src/modules/pong/Pong.cc	(revision 5929)
@@ -30,4 +30,5 @@
 
 #include "core/CoreIncludes.h"
+#include "core/EventIncludes.h"
 #include "core/Executor.h"
 #include "PongCenterpoint.h"
@@ -39,4 +40,7 @@
 namespace orxonox
 {
+    CreateEventName(PongCenterpoint, right);
+    CreateEventName(PongCenterpoint, left);
+    
     CreateUnloadableFactory(Pong);
 
@@ -52,5 +56,5 @@
         this->setHUDTemplate("PongHUD");
 
-        this->starttimer_.setTimer(1.0, false, this, createExecutor(createFunctor(&Pong::startBall)));
+        this->starttimer_.setTimer(1.0, false, createExecutor(createFunctor(&Pong::startBall, this)));
         this->starttimer_.stopTimer();
 
@@ -72,4 +76,5 @@
             this->ball_->setFieldDimension(this->center_->getFieldDimension());
             this->ball_->setSpeed(0);
+            this->ball_->setAccelerationFactor(this->center_->getBallAccelerationFactor());
             this->ball_->setBatLength(this->center_->getBatLength());
 
@@ -120,5 +125,5 @@
         if (this->ball_)
         {
-            delete this->ball_;
+            this->ball_->destroy();
             this->ball_ = 0;
         }
@@ -155,8 +160,11 @@
         if (this->center_)
         {
-            this->center_->fireEvent();
-
+            if (player == this->getRightPlayer())
+                this->center_->fireEvent(FireEventName(PongCenterpoint, right));
+            else if (player == this->getLeftPlayer())
+                this->center_->fireEvent(FireEventName(PongCenterpoint, left));
+            
             if (player)
-                this->gtinfo_.sendAnnounceMessage(player->getName() + " scored");
+                this->gtinfo_->sendAnnounceMessage(player->getName() + " scored");
         }
 
@@ -165,4 +173,5 @@
             this->ball_->setPosition(Vector3::ZERO);
             this->ball_->setVelocity(Vector3::ZERO);
+            this->ball_->setAcceleration(Vector3::ZERO);
             this->ball_->setSpeed(0);
         }
Index: /code/trunk/src/modules/pong/Pong.h
===================================================================
--- /code/trunk/src/modules/pong/Pong.h	(revision 5928)
+++ /code/trunk/src/modules/pong/Pong.h	(revision 5929)
@@ -62,5 +62,5 @@
             PongBall* ball_;
             PongBat* bat_[2];
-            Timer<Pong> starttimer_;
+            Timer starttimer_;
     };
 }
Index: /code/trunk/src/modules/pong/PongAI.cc
===================================================================
--- /code/trunk/src/modules/pong/PongAI.cc	(revision 5928)
+++ /code/trunk/src/modules/pong/PongAI.cc	(revision 5929)
@@ -49,4 +49,5 @@
         this->ballEndPosition_ = 0;
         this->randomOffset_ = 0;
+        this->bChangedRandomOffset_ = false;
         this->relHysteresisOffset_ = 0.02f;
         this->strength_ = 0.5f;
@@ -60,6 +61,6 @@
     PongAI::~PongAI()
     {
-        for (std::list<std::pair<Timer<PongAI>*, char> >::iterator it = this->reactionTimers_.begin(); it != this->reactionTimers_.end(); ++it)
-            delete (*it).first;
+        for (std::list<std::pair<Timer*, char> >::iterator it = this->reactionTimers_.begin(); it != this->reactionTimers_.end(); ++it)
+            (*it).first->destroy();
     }
 
@@ -113,4 +114,5 @@
                 this->ballEndPosition_ = 0;
                 this->randomOffset_ = 0;
+                this->bChangedRandomOffset_ = false;
 
                 this->calculateRandomOffset();
@@ -129,4 +131,16 @@
                 this->bOscillationAvoidanceActive_ = false;
             }
+            
+            // If the ball is close enough, calculate another random offset to accelerate the ball
+            if (!this->bChangedRandomOffset_)
+            {
+                float timetohit = (-this->ball_->getPosition().x + this->ball_->getFieldDimension().x / 2 * sgn(this->ball_->getVelocity().x)) / this->ball_->getVelocity().x;
+                if (timetohit < 0.05)
+                {
+                    this->bChangedRandomOffset_ = true;
+                    if (rnd() < this->strength_)
+                        this->calculateRandomOffset();
+                }
+            }
 
             // Move to the predicted end position with an additional offset (to hit the ball with the side of the bat)
@@ -184,31 +198,98 @@
         Vector3 position = this->ball_->getPosition();
         Vector3 velocity = this->ball_->getVelocity();
+        Vector3 acceleration = this->ball_->getAcceleration();
         Vector2 dimension = this->ball_->getFieldDimension();
 
-        // calculate end-height: current height + slope * distance
-        this->ballEndPosition_ = position.z + velocity.z / velocity.x * (-position.x + dimension.x / 2 * sgn(velocity.x));
-
-        // Calculate bounces
-        for (float limit = 0.35f; limit < this->strength_ || this->strength_ > 0.99f; limit += 0.4f)
-        {
-            // Calculate a random prediction error, based on the vertical speed of the ball and the strength of the AI
-            float randomError = rnd(-1, 1) * dimension.y * (velocity.z / velocity.x / PongBall::MAX_REL_Z_VELOCITY) * (1 - this->strength_);
-
-            // Bounce from the lower bound
-            if (this->ballEndPosition_ > dimension.y / 2)
-            {
-                // Mirror the predicted position at the upper bound and add some random error
-                this->ballEndPosition_ = dimension.y - this->ballEndPosition_ + randomError;
-                continue;
-            }
-            // Bounce from the upper bound
-            if (this->ballEndPosition_ < -dimension.y / 2)
-            {
-                // Mirror the predicted position at the lower bound and add some random error
-                this->ballEndPosition_ = -dimension.y - this->ballEndPosition_ + randomError;
-                continue;
-            }
-            // No bounce - break
-            break;
+        // Calculate bounces. The number of predicted bounces is limited by the AIs strength
+        for (float limit = -0.05f; limit < this->strength_ || this->strength_ > 0.99f; limit += 0.4f)
+        {
+            // calculate the time until the ball reaches the other side
+            float totaltime = (-position.x + dimension.x / 2 * sgn(velocity.x)) / velocity.x;
+            
+            // calculate wall bounce position (four possible solutions of the equation: pos.z + vel.z*t + acc.z/2*t^2 = +/- dim.z/2)
+            float bouncetime = totaltime;
+            bool bUpperWall = false;
+            
+            if (acceleration.z == 0)
+            {
+                if (velocity.z > 0)
+                {
+                    bUpperWall = true;
+                    bouncetime = (dimension.y/2 - position.z) / velocity.z;
+                }
+                else if (velocity.z < 0)
+                {
+                    bUpperWall = false;
+                    bouncetime = (-dimension.y/2 - position.z) / velocity.z;
+                }
+            }
+            else
+            {
+                // upper wall
+                float temp = velocity.z*velocity.z + 2*acceleration.z*(dimension.y/2 - position.z);
+                if (temp >= 0)
+                {
+                    float t1 = (sqrt(temp) - velocity.z) / acceleration.z;
+                    float t2 = (sqrt(temp) + velocity.z) / acceleration.z * (-1);
+                    if (t1 > 0 && t1 < bouncetime)
+                    {
+                        bouncetime = t1;
+                        bUpperWall = true;
+                    }
+                    if (t2 > 0 && t2 < bouncetime)
+                    {
+                        bouncetime = t2;
+                        bUpperWall = true;
+                    }
+                }
+                // lower wall
+                temp = velocity.z*velocity.z - 2*acceleration.z*(dimension.y/2 + position.z);
+                if (temp >= 0)
+                {
+                    float t1 = (sqrt(temp) - velocity.z) / acceleration.z;
+                    float t2 = (sqrt(temp) + velocity.z) / acceleration.z * (-1);
+                    if (t1 > 0 && t1 < bouncetime)
+                    {
+                        bouncetime = t1;
+                        bUpperWall = false;
+                    }
+                    if (t2 > 0 && t2 < bouncetime)
+                    {
+                        bouncetime = t2;
+                        bUpperWall = false;
+                    }
+                }
+            }
+
+            if (bouncetime < totaltime)
+            {
+                // Calculate a random prediction error, based on the vertical speed of the ball and the strength of the AI
+                float randomErrorX = rnd(-1, 1) * dimension.y * (velocity.z / velocity.x / PongBall::MAX_REL_Z_VELOCITY) * (1 - this->strength_);
+                float randomErrorZ = rnd(-1, 1) * dimension.y * (velocity.z / velocity.x / PongBall::MAX_REL_Z_VELOCITY) * (1 - this->strength_);
+
+                // ball bounces after <bouncetime> seconds, update the position and continue
+                velocity.z = velocity.z + acceleration.z * bouncetime;
+                
+                if (bUpperWall)
+                {
+                    position.z = dimension.y / 2;
+                    velocity.z = -fabs(velocity.z) + fabs(randomErrorZ);
+                }
+                else
+                {
+                    position.z = -dimension.y / 2;
+                    velocity.z = fabs(velocity.z) - fabs(randomErrorZ);
+                }
+                    
+                position.x = position.x + velocity.x * bouncetime + randomErrorX;
+                this->ballEndPosition_ = position.z;
+            }
+            else
+            {
+                // ball doesn't bounce, calculate the end position and return
+                // calculate end-height: current height + slope * distance incl. acceleration
+                this->ballEndPosition_ = position.z + velocity.z * totaltime + acceleration.z / 2 * totaltime * totaltime;
+                return;
+            }
         }
     }
@@ -231,6 +312,6 @@
 
             // Add a new Timer
-            Timer<PongAI>* timer = new Timer<PongAI>(delay, false, this, createExecutor(createFunctor(&PongAI::delayedMove)));
-            this->reactionTimers_.push_back(std::pair<Timer<PongAI>*, char>(timer, direction));
+            Timer* timer = new Timer(delay, false, createExecutor(createFunctor(&PongAI::delayedMove, this)));
+            this->reactionTimers_.push_back(std::pair<Timer*, char>(timer, direction));
         }
         else
@@ -246,6 +327,6 @@
 
         // Destroy the timer and remove it from the list
-        Timer<PongAI>* timer = this->reactionTimers_.front().first;
-        delete timer;
+        Timer* timer = this->reactionTimers_.front().first;
+        timer->destroy();
 
         this->reactionTimers_.pop_front();
Index: /code/trunk/src/modules/pong/PongAI.h
===================================================================
--- /code/trunk/src/modules/pong/PongAI.h	(revision 5928)
+++ /code/trunk/src/modules/pong/PongAI.h	(revision 5929)
@@ -62,8 +62,9 @@
             float ballEndPosition_;
             float randomOffset_;
+            bool bChangedRandomOffset_;
             float relHysteresisOffset_;
             float strength_;
 
-            std::list<std::pair<Timer<PongAI>*, char> > reactionTimers_;
+            std::list<std::pair<Timer*, char> > reactionTimers_;
             char movement_;
             char oldMove_;
Index: /code/trunk/src/modules/pong/PongBall.cc
===================================================================
--- /code/trunk/src/modules/pong/PongBall.cc	(revision 5928)
+++ /code/trunk/src/modules/pong/PongBall.cc	(revision 5929)
@@ -33,5 +33,4 @@
 #include "gametypes/Gametype.h"
 #include "PongBat.h"
-#include "sound/SoundBase.h"
 
 namespace orxonox
@@ -41,9 +40,11 @@
     const float PongBall::MAX_REL_Z_VELOCITY = 1.5;
 
-    PongBall::PongBall(BaseObject* creator) : MovableEntity(creator)
+    PongBall::PongBall(BaseObject* creator)
+        : MovableEntity(creator)
     {
         RegisterObject(PongBall);
 
         this->speed_ = 0;
+        this->accelerationFactor_ = 1.0f;
         this->bat_ = 0;
         this->batID_ = new unsigned int[2];
@@ -53,13 +54,8 @@
 
         this->registerVariables();
+    }
 
-        this->sidesound_ = new SoundBase(this);
-        this->sidesound_->loadFile("sounds/pong_side.wav");
-
-        this->batsound_ = new SoundBase(this);
-        this->batsound_->loadFile("sounds/pong_bat.wav");
-
-        this->scoresound_ = new SoundBase(this);
-        this->scoresound_->loadFile("sounds/pong_score.wav");
+    PongBall::~PongBall()
+    {
     }
 
@@ -79,126 +75,76 @@
         SUPER(PongBall, tick, dt);
 
-        if (GameMode::isMaster())
+        Vector3 position = this->getPosition();
+        Vector3 velocity = this->getVelocity();
+        Vector3 acceleration = this->getAcceleration();
+
+        if (position.z > this->fieldHeight_ / 2 || position.z < -this->fieldHeight_ / 2)
         {
-            Vector3 position = this->getPosition();
-            Vector3 velocity = this->getVelocity();
+            velocity.z = -velocity.z;
+            if (position.z > this->fieldHeight_ / 2)
+                position.z = this->fieldHeight_ / 2;
+            if (position.z < -this->fieldHeight_ / 2)
+                position.z = -this->fieldHeight_ / 2;
 
-            if (position.z > this->fieldHeight_ / 2 || position.z < -this->fieldHeight_ / 2)
+            this->fireEvent();
+        }
+
+        if (position.x > this->fieldWidth_ / 2 || position.x < -this->fieldWidth_ / 2)
+        {
+            float distance = 0;
+
+            if (this->bat_)
             {
-                velocity.z = -velocity.z;
-                this->sidesound_->play();
-
-                if (position.z > this->fieldHeight_ / 2)
-                    position.z = this->fieldHeight_ / 2;
-                if (position.z < -this->fieldHeight_ / 2)
-                    position.z = -this->fieldHeight_ / 2;
-            }
-
-            if (position.x > this->fieldWidth_ / 2 || position.x < -this->fieldWidth_ / 2)
-            {
-                float distance = 0;
-
-                if (this->bat_)
+                if (position.x > this->fieldWidth_ / 2 && this->bat_[1])
                 {
-                    if (position.x > this->fieldWidth_ / 2 && this->bat_[1])
+                    distance = (position.z - this->bat_[1]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
+                    if (fabs(distance) <= 1)
                     {
-                        distance = (position.z - this->bat_[1]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
-                        if (fabs(distance) <= 1)
+                        position.x = this->fieldWidth_ / 2;
+                        velocity.x = -velocity.x;
+                        velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
+                        acceleration = this->bat_[1]->getVelocity() * this->accelerationFactor_ * -1;
+                        
+                        this->fireEvent();
+                    }
+                    else if (GameMode::isMaster() && position.x > this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
+                    {
+                        if (this->getGametype() && this->bat_[0])
                         {
-                            position.x = this->fieldWidth_ / 2;
-                            velocity.x = -velocity.x;
-                            velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
-                            this->batsound_->play();
-                        }
-                        else if (position.x > this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
-                        {
-                            if (this->getGametype() && this->bat_[0])
-                            {
-                                this->getGametype()->playerScored(this->bat_[0]->getPlayer());
-                                this->scoresound_->play();
-                                return;
-                            }
+                            this->getGametype()->playerScored(this->bat_[0]->getPlayer());
+                            return;
                         }
                     }
-                    if (position.x < -this->fieldWidth_ / 2 && this->bat_[0])
+                }
+                if (position.x < -this->fieldWidth_ / 2 && this->bat_[0])
+                {
+                    distance = (position.z - this->bat_[0]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
+                    if (fabs(distance) <= 1)
                     {
-                        distance = (position.z - this->bat_[0]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
-                        if (fabs(distance) <= 1)
+                        position.x = -this->fieldWidth_ / 2;
+                        velocity.x = -velocity.x;
+                        velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
+                        acceleration = this->bat_[0]->getVelocity() * this->accelerationFactor_ * -1;
+
+                        this->fireEvent();
+                    }
+                    else if (GameMode::isMaster() && position.x < -this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
+                    {
+                        if (this->getGametype() && this->bat_[1])
                         {
-                            position.x = -this->fieldWidth_ / 2;
-                            velocity.x = -velocity.x;
-                            velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
-                            this->batsound_->play();
-                        }
-                        else if (position.x < -this->fieldWidth_ / 2 * (1 + this->relMercyOffset_))
-                        {
-                            if (this->getGametype() && this->bat_[1])
-                            {
-                                this->scoresound_->play();
-                                this->getGametype()->playerScored(this->bat_[1]->getPlayer());
-                                return;
-                            }
+                            this->getGametype()->playerScored(this->bat_[1]->getPlayer());
+                            return;
                         }
                     }
                 }
             }
+        }
 
-            if (velocity != this->getVelocity())
-                this->setVelocity(velocity);
-            if (position != this->getPosition())
-                this->setPosition(position);
-        }
-        else
-        {
-          Vector3 position = this->getPosition();
-          Vector3 velocity = this->getVelocity();
-
-          if (position.z > this->fieldHeight_ / 2 || position.z < -this->fieldHeight_ / 2)
-          {
-            velocity.z = -velocity.z;
-            this->sidesound_->play();
-
-            if (position.z > this->fieldHeight_ / 2)
-              position.z = this->fieldHeight_ / 2;
-            if (position.z < -this->fieldHeight_ / 2)
-              position.z = -this->fieldHeight_ / 2;
-          }
-
-          if (position.x > this->fieldWidth_ / 2 || position.x < -this->fieldWidth_ / 2)
-          {
-            float distance = 0;
-
-            if (this->bat_)
-            {
-              if (position.x > this->fieldWidth_ / 2 && this->bat_[1])
-              {
-                distance = (position.z - this->bat_[1]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
-                if (fabs(distance) <= 1)
-                {
-                  position.x = this->fieldWidth_ / 2;
-                  velocity.x = -velocity.x;
-                  this->batsound_->play();
-                  velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
-                }
-              }
-              if (position.x < -this->fieldWidth_ / 2 && this->bat_[0])
-              {
-                distance = (position.z - this->bat_[0]->getPosition().z) / (this->fieldHeight_ * (this->batlength_ * 1.10f) / 2);
-                if (fabs(distance) <= 1)
-                {
-                  position.x = -this->fieldWidth_ / 2;
-                  velocity.x = -velocity.x;
-                  this->batsound_->play();
-                  velocity.z = distance * distance * sgn(distance) * PongBall::MAX_REL_Z_VELOCITY * this->speed_;
-                }
-              }
-            }
-          }
-
-          if (velocity != this->getVelocity())
+        if (acceleration != this->getAcceleration())
+            this->setAcceleration(acceleration);
+        if (velocity != this->getVelocity())
             this->setVelocity(velocity);
-          if (position != this->getPosition())
+        if (position != this->getPosition())
             this->setPosition(position);
-        }
     }
 
Index: /code/trunk/src/modules/pong/PongBall.h
===================================================================
--- /code/trunk/src/modules/pong/PongBall.h	(revision 5928)
+++ /code/trunk/src/modules/pong/PongBall.h	(revision 5929)
@@ -41,5 +41,5 @@
         public:
             PongBall(BaseObject* creator);
-            virtual ~PongBall() {}
+            virtual ~PongBall();
 
             virtual void tick(float dt);
@@ -58,4 +58,9 @@
                 { return this->speed_; }
 
+            void setAccelerationFactor(float factor)
+                { this->accelerationFactor_ = factor; }
+            float getAccelerationFactor() const
+                { return this->accelerationFactor_; }
+
             void setBatLength(float batlength)
                 { this->batlength_ = batlength; }
@@ -72,12 +77,9 @@
             float fieldHeight_;
             float speed_;
+            float accelerationFactor_;
             float batlength_;
             PongBat** bat_;
             unsigned int* batID_;
             float relMercyOffset_;
-
-            SoundBase* sidesound_;
-            SoundBase* batsound_;
-            SoundBase* scoresound_;
     };
 }
Index: /code/trunk/src/modules/pong/PongCenterpoint.cc
===================================================================
--- /code/trunk/src/modules/pong/PongCenterpoint.cc	(revision 5928)
+++ /code/trunk/src/modules/pong/PongCenterpoint.cc	(revision 5929)
@@ -44,4 +44,5 @@
         this->height_ = 120;
         this->ballspeed_ = 100;
+        this->ballaccfactor_ = 1.0;
         this->batspeed_ = 60;
         this->batlength_ = 0.25;
@@ -58,4 +59,5 @@
         XMLPortParam(PongCenterpoint, "battemplate", setBattemplate, getBattemplate, xmlelement, mode);
         XMLPortParam(PongCenterpoint, "ballspeed", setBallSpeed, getBallSpeed, xmlelement, mode);
+        XMLPortParam(PongCenterpoint, "ballaccfactor", setBallAccelerationFactor, getBallAccelerationFactor, xmlelement, mode);
         XMLPortParam(PongCenterpoint, "batspeed", setBatSpeed, getBatSpeed, xmlelement, mode);
         XMLPortParam(PongCenterpoint, "batlength", setBatLength, getBatLength, xmlelement, mode);
@@ -73,5 +75,5 @@
         if (this->getGametype() && this->getGametype()->isA(Class(Pong)))
         {
-            Pong* pong_gametype = orxonox_cast<Pong*>(this->getGametype());
+            Pong* pong_gametype = orxonox_cast<Pong*>(this->getGametype().get());
             pong_gametype->setCenterpoint(this);
         }
Index: /code/trunk/src/modules/pong/PongCenterpoint.h
===================================================================
--- /code/trunk/src/modules/pong/PongCenterpoint.h	(revision 5928)
+++ /code/trunk/src/modules/pong/PongCenterpoint.h	(revision 5929)
@@ -68,4 +68,9 @@
                 { return this->ballspeed_; }
 
+            void setBallAccelerationFactor(float ballaccfactor)
+                { this->ballaccfactor_ = ballaccfactor; }
+            float getBallAccelerationFactor() const
+                { return this->ballaccfactor_; }
+
             void setBatSpeed(float batspeed)
                 { this->batspeed_ = batspeed; }
@@ -85,4 +90,5 @@
 
             float ballspeed_;
+            float ballaccfactor_;
             float batspeed_;
             float batlength_;
Index: de/trunk/src/modules/pong/PongPrecompiledHeaders.h
===================================================================
--- /code/trunk/src/modules/pong/PongPrecompiledHeaders.h	(revision 5928)
+++ 	(revision )
@@ -1,58 +1,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
-    Compilation of the most often used header files in the pong module
-@details
-    Updated: 19. September 2009
-    Total Files: 7
-*/
-
-#include "OrxonoxConfig.h"
-
-///////////////////////////////////////////
-/////          Stable Headers         /////
-///////////////////////////////////////////
-
-#include "util/OgreForwardRefs.h" // 6
-
-///////////////////////////////////////////
-/////       All Rebuild Headers       /////
-///////////////////////////////////////////
-
-#include "core/BaseObject.h"   // 7
-#include "core/CoreIncludes.h" // 7
-#include "core/Executor.h"     // 6
-#include "network/synchronisable/Synchronisable.h" // 7
-
-
-// Just in case some header included windows.h
-#undef min
-#undef max
Index: /code/trunk/src/modules/pong/PongPrereqs.h
===================================================================
--- /code/trunk/src/modules/pong/PongPrereqs.h	(revision 5928)
+++ /code/trunk/src/modules/pong/PongPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the pong module
 */
 
@@ -36,8 +37,10 @@
 
 #include "OrxonoxConfig.h"
+#include "OrxonoxPrereqs.h"
 
 //-----------------------------------------------------------------------
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef PONG_SHARED_BUILD
Index: /code/trunk/src/modules/pong/PongScore.cc
===================================================================
--- /code/trunk/src/modules/pong/PongScore.cc	(revision 5928)
+++ /code/trunk/src/modules/pong/PongScore.cc	(revision 5929)
@@ -133,5 +133,5 @@
 
         if (this->getOwner() && this->getOwner()->getGametype())
-            this->owner_ = orxonox_cast<Pong*>(this->getOwner()->getGametype());
+            this->owner_ = orxonox_cast<Pong*>(this->getOwner()->getGametype().get());
         else
             this->owner_ = 0;
Index: /code/trunk/src/modules/questsystem/QuestEffectBeacon.cc
===================================================================
--- /code/trunk/src/modules/questsystem/QuestEffectBeacon.cc	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestEffectBeacon.cc	(revision 5929)
@@ -75,16 +75,14 @@
         XMLPortObject(QuestEffectBeacon, QuestEffect, "effects", addEffect, getEffect, xmlelement, mode);
 
+        XMLPortEventState(QuestEffectBeacon, PlayerTrigger, "execute", execute, xmlelement, mode);
+
         COUT(3) << "New QuestEffectBeacon created." << std::endl;
     }
 
-    /**
-    @brief
-        Processes an event for this QuestEffectBeacon.
-    */
-    void QuestEffectBeacon::processEvent(Event& event)
-    {
-        SUPER(QuestEffectBeacon, processEvent, event);
-
-        ORXONOX_SET_SUBCLASS_EVENT(QuestEffectBeacon, "execute", execute, event, PlayerTrigger);
+    void QuestEffectBeacon::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(QuestEffectBeacon, XMLEventPort, xmlelement, mode);
+
+        XMLPortEventState(QuestEffectBeacon, PlayerTrigger, "execute", execute, xmlelement, mode);
     }
 
Index: /code/trunk/src/modules/questsystem/QuestEffectBeacon.h
===================================================================
--- /code/trunk/src/modules/questsystem/QuestEffectBeacon.h	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestEffectBeacon.h	(revision 5929)
@@ -86,6 +86,5 @@
 
             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode); //!< Method for creating a QuestEffectBeacon object through XML.
-
-            virtual void processEvent(Event& event); //!< Processes an event for this QuestEffectBeacon.
+            virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
 
             bool execute(bool b, PlayerTrigger* trigger); //!< Executes the QuestEffects of the QuestEffectBeacon.
Index: /code/trunk/src/modules/questsystem/QuestGUI.cc
===================================================================
--- /code/trunk/src/modules/questsystem/QuestGUI.cc	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestGUI.cc	(revision 5929)
@@ -79,5 +79,5 @@
         
         if(this->root_ != NULL)
-            delete this->root_;
+            this->root_->destroy();
     }
 
@@ -146,5 +146,5 @@
             COUT(3) << "Clearing Node '" << *str << "' ..." << std::endl;
             delete str;
-            delete node;
+            node->destroy();
         }
         this->nodes_.clear();
Index: /code/trunk/src/modules/questsystem/QuestManager.cc
===================================================================
--- /code/trunk/src/modules/questsystem/QuestManager.cc	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestManager.cc	(revision 5929)
@@ -41,4 +41,5 @@
 #include "core/ConsoleCommand.h"
 #include "core/LuaState.h"
+#include "core/ScopedSingletonManager.h"
 #include "infos/PlayerInfo.h"
 #include "overlays/GUIOverlay.h"
@@ -56,4 +57,5 @@
     //! Pointer to the current (and single) instance of this class.
     /*static*/ QuestManager* QuestManager::singletonPtr_s = NULL;
+    ManageScopedSingleton(QuestManager, ScopeID::Root, false);
 
     /**
@@ -76,5 +78,5 @@
         for(std::map<PlayerInfo*, QuestGUI*>::iterator it = this->questGUIs_.begin(); it != this->questGUIs_.end(); it++)
         {
-            delete (*it).second;
+            (*it).second->destroy();
         }
         this->questGUIs_.clear();
Index: /code/trunk/src/modules/questsystem/QuestManager.h
===================================================================
--- /code/trunk/src/modules/questsystem/QuestManager.h	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestManager.h	(revision 5929)
@@ -42,5 +42,5 @@
 #include <string>
 
-#include "util/ScopedSingleton.h"
+#include "util/Singleton.h"
 #include "core/OrxonoxClass.h"
 
@@ -50,7 +50,4 @@
 namespace orxonox
 {
-
-    typedef ScopedSingleton<QuestManager, ScopeID::GSLevel> ScopedSingletonQuestManagerGSLevel; // workaround for tolua
-
     /**
     @brief
@@ -60,9 +57,10 @@
         Damian 'Mozork' Frick
     */
-    class _QuestsystemExport QuestManager : public ScopedSingletonQuestManagerGSLevel, public orxonox::OrxonoxClass
-    {
+    class _QuestsystemExport QuestManager
 // tolua_end
+        : public Singleton<QuestManager>, public orxonox::OrxonoxClass
+    { // tolua_export
 
-            friend class ScopedSingleton<QuestManager, ScopeID::GSLevel>;
+            friend class Singleton<QuestManager>;
             friend class QuestGUI;
 
@@ -72,5 +70,5 @@
 
             //! Returns a reference to the single instance of the Quest Manager.
-            static QuestManager& getInstance() { return ScopedSingleton<QuestManager, ScopeID::GSLevel>::getInstance(); } // tolua_export
+            static QuestManager& getInstance() { return Singleton<QuestManager>::getInstance(); } // tolua_export
 
             //! Retreive the main window for the GUI. 
Index: /code/trunk/src/modules/questsystem/QuestsystemPrecompiledHeaders.h
===================================================================
--- /code/trunk/src/modules/questsystem/QuestsystemPrecompiledHeaders.h	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestsystemPrecompiledHeaders.h	(revision 5929)
@@ -51,6 +51,6 @@
 #include <OgreColourValue.h> // 16
 
-#include <tinyxml/ticpp.h>        // 14
-#include "util/ScopedSingleton.h" // 13
+#include <tinyxml/ticpp.h>   // 14
+#include "util/Singleton.h"  // 13
 
 ///////////////////////////////////////////
Index: /code/trunk/src/modules/questsystem/QuestsystemPrereqs.h
===================================================================
--- /code/trunk/src/modules/questsystem/QuestsystemPrereqs.h	(revision 5928)
+++ /code/trunk/src/modules/questsystem/QuestsystemPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the questsystem module
 */
 
@@ -36,5 +37,4 @@
 
 #include "OrxonoxConfig.h"
-
 #include "OrxonoxPrereqs.h"
 
@@ -42,4 +42,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef QUESTSYSTEM_SHARED_BUILD
@@ -76,6 +77,6 @@
     class QuestEffect;
     class QuestEffectBeacon;
+    class QuestGUI;
     class QuestGUINode;
-    class QuestGUI;
     class QuestHint;
     class QuestItem;
@@ -83,8 +84,7 @@
     class QuestManager;
     class QuestNotification;
-    class Rewardable;
 
+    // notifications
     class Notification;
-    class NotificationListener;
     class NotificationManager;
     class NotificationOverlay;
Index: /code/trunk/src/modules/questsystem/notifications/NotificationManager.cc
===================================================================
--- /code/trunk/src/modules/questsystem/notifications/NotificationManager.cc	(revision 5928)
+++ /code/trunk/src/modules/questsystem/notifications/NotificationManager.cc	(revision 5929)
@@ -37,4 +37,5 @@
 
 #include "core/CoreIncludes.h"
+#include "core/ScopedSingletonManager.h"
 #include "Notification.h"
 #include "interfaces/NotificationListener.h"
@@ -47,4 +48,5 @@
 
     NotificationManager* NotificationManager::singletonPtr_s = NULL;
+    ManageScopedSingleton(NotificationManager, ScopeID::Root, false);
 
     /**
Index: /code/trunk/src/modules/questsystem/notifications/NotificationManager.h
===================================================================
--- /code/trunk/src/modules/questsystem/notifications/NotificationManager.h	(revision 5928)
+++ /code/trunk/src/modules/questsystem/notifications/NotificationManager.h	(revision 5929)
@@ -41,10 +41,9 @@
 #include <string>
 
-#include "util/ScopedSingleton.h"
+#include "util/Singleton.h"
 #include "core/OrxonoxClass.h"
 
 namespace orxonox
 {
-
     /**
     @brief
@@ -54,7 +53,7 @@
         Damian 'Mozork' Frick
     */
-    class _QuestsystemExport NotificationManager : public ScopedSingleton<NotificationManager, ScopeID::GSLevel>, public OrxonoxClass
+    class _QuestsystemExport NotificationManager : public Singleton<NotificationManager>, public OrxonoxClass
     {
-            friend class ScopedSingleton<NotificationManager, ScopeID::GSLevel>;
+            friend class Singleton<NotificationManager>;
         public:
             NotificationManager();
Index: /code/trunk/src/modules/questsystem/notifications/NotificationQueue.cc
===================================================================
--- /code/trunk/src/modules/questsystem/notifications/NotificationQueue.cc	(revision 5928)
+++ /code/trunk/src/modules/questsystem/notifications/NotificationQueue.cc	(revision 5929)
@@ -426,5 +426,5 @@
         this->containers_.erase(container);
         this->overlays_.erase(container->notification);
-        delete container->overlay;
+        container->overlay->destroy();
         delete container;
         this->size_= this->size_-1;
Index: /code/trunk/src/modules/weapons/MuzzleFlash.cc
===================================================================
--- /code/trunk/src/modules/weapons/MuzzleFlash.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/MuzzleFlash.cc	(revision 5929)
@@ -41,13 +41,6 @@
         RegisterObject(MuzzleFlash);
         this->setScale(0.1f);
-        
-        this->delayTimer_.setTimer(0.1f, false, this, createExecutor(createFunctor(&MuzzleFlash::destroy)));
 
+        this->delayTimer_.setTimer(0.1f, false, createExecutor(createFunctor(&MuzzleFlash::destroy, this)));
     }
-
-    void MuzzleFlash::destroy()
-    {
-        delete this;
-    }
- 
 }
Index: /code/trunk/src/modules/weapons/MuzzleFlash.h
===================================================================
--- /code/trunk/src/modules/weapons/MuzzleFlash.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/MuzzleFlash.h	(revision 5929)
@@ -43,10 +43,6 @@
             virtual ~MuzzleFlash() {}
 
-
-
         private:
-            void destroy();
-            Timer<MuzzleFlash> delayTimer_;
-
+            Timer delayTimer_;
     };
 }
Index: /code/trunk/src/modules/weapons/WeaponsPrereqs.h
===================================================================
--- /code/trunk/src/modules/weapons/WeaponsPrereqs.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/WeaponsPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the weapons module
 */
 
@@ -36,5 +37,4 @@
 
 #include "OrxonoxConfig.h"
-
 #include "OrxonoxPrereqs.h"
 
@@ -42,4 +42,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef WEAPONS_SHARED_BUILD
@@ -64,20 +65,23 @@
 namespace orxonox
 {
-    class LaserFire;
+    class MuzzleFlash;
+
+    // munitions
+    class FusionMunition;
+    class LaserMunition;
+    class ReplenishingMunition;
+
+    // projectiles
+    class BillboardProjectile;
+    class LightningGunProjectile;
+    class ParticleProjectile;
+    class Projectile;
+
+    // weaponmodes
+    class EnergyDrink;
     class FusionFire;
     class HsW01;
+    class LaserFire;
     class LightningGun;
-    class EnergyDrink;
-
-    class Projectile;
-    class BillboardProjectile;
-    class ParticleProjectile;
-    class LightningGunProjectile;
-
-    class ReplenishingMunition;
-    class LaserMunition;
-    class FusionMunition;
-
-    class MuzzleFlash;
 }
 
Index: /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.cc
===================================================================
--- /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.cc	(revision 5929)
@@ -44,5 +44,5 @@
         // replenishIntervall_ and replenishMunitionAmount_ will be set in the constructor of the
         // inheriting class, which comes after this constructor)
-        this->replenishingTimer_.setTimer(0.0f, false, this, createExecutor(createFunctor(&ReplenishingMunition::initializeTimer)));
+        this->replenishingTimer_.setTimer(0.0f, false, createExecutor(createFunctor(&ReplenishingMunition::initializeTimer, this)));
     }
 
@@ -50,5 +50,5 @@
     {
         // Initialize the timer
-        this->replenishingTimer_.setTimer(this->replenishIntervall_, true, this, createExecutor(createFunctor(&ReplenishingMunition::replenish)));
+        this->replenishingTimer_.setTimer(this->replenishIntervall_, true, createExecutor(createFunctor(&ReplenishingMunition::replenish, this)));
     }
 
Index: /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.h
===================================================================
--- /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/munitions/ReplenishingMunition.h	(revision 5929)
@@ -51,5 +51,5 @@
             void initializeTimer();
 
-            Timer<ReplenishingMunition> replenishingTimer_;
+            Timer replenishingTimer_;
     };
 }
Index: /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.cc
===================================================================
--- /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.cc	(revision 5929)
@@ -42,5 +42,5 @@
         this->textureIndex_ = 1;
         this->maxTextureIndex_ = 8;
-        this->textureTimer_.setTimer(0.01f, true, this, createExecutor(createFunctor(&LightningGunProjectile::changeTexture)));
+        this->textureTimer_.setTimer(0.01f, true, createExecutor(createFunctor(&LightningGunProjectile::changeTexture, this)));
         
         registerVariables();
Index: /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.h
===================================================================
--- /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/projectiles/LightningGunProjectile.h	(revision 5929)
@@ -50,5 +50,5 @@
             unsigned int textureIndex_;
             unsigned int maxTextureIndex_;
-            Timer<LightningGunProjectile> textureTimer_;
+            Timer textureTimer_;
             std::string materialBase_;
       private:
Index: /code/trunk/src/modules/weapons/projectiles/ParticleProjectile.cc
===================================================================
--- /code/trunk/src/modules/weapons/projectiles/ParticleProjectile.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/projectiles/ParticleProjectile.cc	(revision 5929)
@@ -59,5 +59,5 @@
         {
             this->detachOgreObject(this->particles_->getParticleSystem());
-            delete this->particles_;
+            this->particles_->destroy();
         }
     }
Index: /code/trunk/src/modules/weapons/projectiles/Projectile.cc
===================================================================
--- /code/trunk/src/modules/weapons/projectiles/Projectile.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/projectiles/Projectile.cc	(revision 5929)
@@ -61,5 +61,5 @@
             this->attachCollisionShape(shape);
 
-            this->destroyTimer_.setTimer(this->lifetime_, false, this, createExecutor(createFunctor(&Projectile::destroyObject)));
+            this->destroyTimer_.setTimer(this->lifetime_, false, createExecutor(createFunctor(&Projectile::destroyObject, this)));
         }
     }
@@ -84,5 +84,5 @@
 
         if (this->bDestroy_)
-            delete this;
+            this->destroy(); // TODO: use a scheduler instead of deleting the object right here in tick()
     }
 
@@ -90,5 +90,5 @@
     {
         if (GameMode::isMaster())
-            delete this;
+            this->destroy();
     }
 
@@ -133,8 +133,7 @@
     }
 
-    void Projectile::destroyedPawn(Pawn* pawn)
+    void Projectile::setOwner(Pawn* owner)
     {
-        if (this->owner_ == pawn)
-            this->owner_ = 0;
+        this->owner_ = owner;
     }
 }
Index: /code/trunk/src/modules/weapons/projectiles/Projectile.h
===================================================================
--- /code/trunk/src/modules/weapons/projectiles/Projectile.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/projectiles/Projectile.h	(revision 5929)
@@ -33,10 +33,9 @@
 
 #include "tools/Timer.h"
-#include "interfaces/PawnListener.h"
 #include "worldentities/MovableEntity.h"
 
 namespace orxonox
 {
-    class _WeaponsExport Projectile : public MovableEntity, public PawnListener
+    class _WeaponsExport Projectile : public MovableEntity
     {
         public:
@@ -49,5 +48,4 @@
             virtual void tick(float dt);
             virtual bool collidesAgainst(WorldEntity* otherObject, btManifoldPoint& contactPoint);
-            virtual void destroyedPawn(Pawn* pawn);
 
             inline void setDamage(float damage)
@@ -56,15 +54,14 @@
                 { return this->damage_; }
 
-            inline void setOwner(Pawn* owner)
-                { this->owner_ = owner; }
+            void setOwner(Pawn* owner);
             inline Pawn* getOwner() const
                 { return this->owner_; }
 
         private:
-            Pawn* owner_;
+            WeakPtr<Pawn> owner_;
             float lifetime_;
             float damage_;
             bool bDestroy_;
-            Timer<Projectile> destroyTimer_;
+            Timer destroyTimer_;
     };
 }
Index: /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.cc
===================================================================
--- /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.cc	(revision 5929)
@@ -54,5 +54,5 @@
         this->setMunitionName("FusionMunition");
 
-        this->delayTimer_.setTimer(1.0f, false, this, createExecutor(createFunctor(&EnergyDrink::shot)));
+        this->delayTimer_.setTimer(1.0f, false, createExecutor(createFunctor(&EnergyDrink::shot, this)));
         this->delayTimer_.stopTimer();
     }
Index: /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.h
===================================================================
--- /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/weaponmodes/EnergyDrink.h	(revision 5929)
@@ -59,5 +59,5 @@
             float speed_;
             float delay_;
-            Timer<EnergyDrink> delayTimer_;
+            Timer delayTimer_;
     };
 }
Index: /code/trunk/src/modules/weapons/weaponmodes/HsW01.cc
===================================================================
--- /code/trunk/src/modules/weapons/weaponmodes/HsW01.cc	(revision 5928)
+++ /code/trunk/src/modules/weapons/weaponmodes/HsW01.cc	(revision 5929)
@@ -54,5 +54,5 @@
         this->setMunitionName("LaserMunition");
 
-        this->delayTimer_.setTimer(1.0f, false, this, createExecutor(createFunctor(&HsW01::shot)));
+        this->delayTimer_.setTimer(1.0f, false, createExecutor(createFunctor(&HsW01::shot, this)));
         this->delayTimer_.stopTimer();
     }
Index: /code/trunk/src/modules/weapons/weaponmodes/HsW01.h
===================================================================
--- /code/trunk/src/modules/weapons/weaponmodes/HsW01.h	(revision 5928)
+++ /code/trunk/src/modules/weapons/weaponmodes/HsW01.h	(revision 5929)
@@ -57,5 +57,5 @@
             float speed_;
             float delay_;
-            Timer<HsW01> delayTimer_;
+            Timer delayTimer_;
     };
 }
Index: /code/trunk/src/orxonox/CMakeLists.txt
===================================================================
--- /code/trunk/src/orxonox/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/orxonox/CMakeLists.txt	(revision 5929)
@@ -25,18 +25,19 @@
 
 SET_SOURCE_FILES(ORXONOX_SRC_FILES
+  Level.cc
+  LevelManager.cc
   Main.cc
-
-  CameraManager.cc
-  LevelManager.cc
   PawnManager.cc
   PlayerManager.cc
-
-  Level.cc
   Radar.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)
Index: /code/trunk/src/orxonox/CameraManager.cc
===================================================================
--- /code/trunk/src/orxonox/CameraManager.cc	(revision 5928)
+++ /code/trunk/src/orxonox/CameraManager.cc	(revision 5929)
@@ -26,4 +26,5 @@
  *
  */
+
 #include "CameraManager.h"
 
@@ -34,6 +35,8 @@
 #include "util/StringUtils.h"
 #include "core/GameMode.h"
+#include "core/GraphicsManager.h"
 #include "core/GUIManager.h"
 #include "core/ObjectList.h"
+#include "core/ScopedSingletonManager.h"
 #include "tools/Shader.h"
 #include "graphics/Camera.h"
@@ -43,20 +46,20 @@
 {
     CameraManager* CameraManager::singletonPtr_s = 0;
+    ManageScopedSingleton(CameraManager, ScopeID::Graphics, false);
 
-    CameraManager::CameraManager(Ogre::Viewport* viewport)
-        : viewport_(viewport)
+    CameraManager::CameraManager()
+        : viewport_(GraphicsManager::getInstance().getViewport())
     {
-        this->fallbackCamera_ = 0;
+        assert(GameMode::showsGraphics());
     }
 
     CameraManager::~CameraManager()
     {
-        if (this->fallbackCamera_)
-            this->fallbackCamera_->getSceneManager()->destroyCamera(this->fallbackCamera_);
+        GUIManager::getInstance().setCamera(0);
     }
 
     Camera* CameraManager::getActiveCamera() const
     {
-        if (this->cameraList_.size() > 0)
+        if (!this->cameraList_.empty())
             return this->cameraList_.front();
         else
@@ -66,23 +69,16 @@
     void CameraManager::requestFocus(Camera* camera)
     {
-        if (!GameMode::showsGraphics())
-            return;
-
         // notify old camera (if it exists)
-        if (this->cameraList_.size() > 0)
+        if (!this->cameraList_.empty())
             this->cameraList_.front()->removeFocus();
-        else if (this->fallbackCamera_)
-        {
-            this->fallbackCamera_->getSceneManager()->destroyCamera(this->fallbackCamera_);
-            this->fallbackCamera_ = 0;
-        }
 
         camera->setFocus();
 
         // make sure we don't add it twice
-        for (std::list<Camera*>::iterator it = this->cameraList_.begin(); it != this->cameraList_.end(); ++it)
+        for (std::list<Camera*>::iterator it = this->cameraList_.begin(); it != this->cameraList_.end();)
             if ((*it) == camera)
-                return;
-
+                this->cameraList_.erase(it++);
+            else
+                ++it;
         // add to list
         this->cameraList_.push_front(camera);
@@ -91,9 +87,6 @@
     void CameraManager::releaseFocus(Camera* camera)
     {
-        if (!GameMode::showsGraphics())
-            return;
-
         // notify the cam of releasing the focus
-        if (this->cameraList_.front() == camera)
+        if (!this->cameraList_.empty() && this->cameraList_.front() == camera)
         {
             camera->removeFocus();
@@ -101,18 +94,9 @@
 
             // set new focus if possible
-            if (this->cameraList_.size() > 0)
+            if (!this->cameraList_.empty())
                 this->cameraList_.front()->setFocus();
-            else
-            {
-                // there are no more cameras, create a fallback
-                if (!this->fallbackCamera_)
-                    this->fallbackCamera_ = camera->getScene()->getSceneManager()->createCamera(getUniqueNumberString());
-                this->useCamera(this->fallbackCamera_);
-            }
         }
         else
-        {
             this->cameraList_.remove(camera);
-        }
     }
 
Index: /code/trunk/src/orxonox/CameraManager.h
===================================================================
--- /code/trunk/src/orxonox/CameraManager.h	(revision 5928)
+++ /code/trunk/src/orxonox/CameraManager.h	(revision 5929)
@@ -42,12 +42,14 @@
 #include "util/OgreForwardRefs.h"
 #include "util/Singleton.h"
+#include "core/OrxonoxClass.h"
+#include "core/SmartPtr.h"
 
 namespace orxonox
 {
-    class _OrxonoxExport CameraManager : public Singleton<CameraManager>
+    class _OrxonoxExport CameraManager : public Singleton<CameraManager>, public OrxonoxClass
     {
             friend class Singleton<CameraManager>;
         public:
-            CameraManager(Ogre::Viewport* viewport);
+            CameraManager();
             ~CameraManager();
 
@@ -66,5 +68,4 @@
             std::list<Camera*>    cameraList_;
             Ogre::Viewport*       viewport_;
-            Ogre::Camera*         fallbackCamera_;
 
             static CameraManager* singletonPtr_s;
Index: /code/trunk/src/orxonox/Level.cc
===================================================================
--- /code/trunk/src/orxonox/Level.cc	(revision 5928)
+++ /code/trunk/src/orxonox/Level.cc	(revision 5929)
@@ -30,5 +30,4 @@
 
 #include "util/Math.h"
-#include "core/Core.h"
 #include "core/CoreIncludes.h"
 #include "core/Loader.h"
@@ -40,5 +39,4 @@
 #include "gametypes/Gametype.h"
 #include "overlays/OverlayGroup.h"
-#include "sound/SoundBase.h"
 #include "LevelManager.h"
 
@@ -53,4 +51,5 @@
         this->registerVariables();
         this->xmlfilename_ = this->getFilename();
+        this->xmlfile_ = 0;
     }
 
@@ -64,7 +63,4 @@
             if (this->xmlfile_)
                 Loader::unload(this->xmlfile_);
-
-            if(this->ambientsound_ != NULL)
-                delete this->ambientsound_;
         }
     }
@@ -76,6 +72,4 @@
         XMLPortParam(Level, "description", setDescription, getDescription, xmlelement, mode);
         XMLPortParam(Level, "gametype", setGametypeString, getGametypeString, xmlelement, mode).defaultValues("Gametype");
-
-        XMLPortParamLoadOnly(Level, "ambientsound", loadAmbientSound, xmlelement, mode);
 
         XMLPortObjectExtended(Level, BaseObject, "", addObject, getObject, xmlelement, mode, true, false);
@@ -116,10 +110,6 @@
             this->gametype_ = gametype;
 
-std::cout << "Load Gametype: " << this->gametype_ << std::endl;
-
         Gametype* rootgametype = orxonox_cast<Gametype*>(identifier->fabricate(this));
         this->setGametype(rootgametype);
-
-std::cout << "root gametype: " << rootgametype->getIdentifier()->getName() << std::endl;
 
         for (std::list<BaseObject*>::iterator it = this->objects_.begin(); it != this->objects_.end(); ++it)
@@ -149,19 +139,4 @@
     }
 
-    void Level::loadAmbientSound(const std::string& filename)
-    {
-        if(filename == "") return;
-        else
-        {
-            if(this->ambientsound_ == NULL)
-            {
-                this->ambientsound_ = new SoundBase();
-            }
-
-            this->ambientsound_->loadFile(filename);
-            this->ambientsound_->play(true);
-        }
-    }
-
     void Level::playerEntered(PlayerInfo* player)
     {
Index: /code/trunk/src/orxonox/Level.h
===================================================================
--- /code/trunk/src/orxonox/Level.h	(revision 5928)
+++ /code/trunk/src/orxonox/Level.h	(revision 5929)
@@ -53,6 +53,4 @@
                 { return this->description_; }
 
-            void loadAmbientSound(const std::string& filename);
-
             void playerEntered(PlayerInfo* player);
             void playerLeft(PlayerInfo* player);
@@ -73,6 +71,4 @@
             XMLFile*               xmlfile_;
             std::list<BaseObject*> objects_;
-
-            SoundBase*             ambientsound_;
     };
 }
Index: /code/trunk/src/orxonox/LevelManager.cc
===================================================================
--- /code/trunk/src/orxonox/LevelManager.cc	(revision 5928)
+++ /code/trunk/src/orxonox/LevelManager.cc	(revision 5929)
@@ -34,10 +34,9 @@
 #include "core/CommandLine.h"
 #include "core/ConfigValueIncludes.h"
-#include "core/Core.h"
 #include "core/CoreIncludes.h"
 #include "core/Loader.h"
+#include "core/ScopedSingletonManager.h"
 #include "PlayerManager.h"
 #include "Level.h"
-#include "infos/HumanPlayer.h"
 
 namespace orxonox
@@ -46,4 +45,5 @@
 
     LevelManager* LevelManager::singletonPtr_s = 0;
+    ManageScopedSingleton(LevelManager, ScopeID::Root, false);
 
     LevelManager::LevelManager()
Index: /code/trunk/src/orxonox/Main.cc
===================================================================
--- /code/trunk/src/orxonox/Main.cc	(revision 5928)
+++ /code/trunk/src/orxonox/Main.cc	(revision 5929)
@@ -31,11 +31,9 @@
 @file
 @brief
-    The main function of Orxonox.
+    The main function of Orxonox (but not the entry point of the program!)
 */
 
 #include "OrxonoxPrereqs.h"
-#include "SpecialConfig.h"
 
-#include "util/Exception.h"
 #include "core/CommandLine.h"
 #include "core/Game.h"
@@ -50,4 +48,5 @@
 SetCommandLineSwitch(dedicated).information("Start in dedicated server mode");
 SetCommandLineSwitch(standalone).information("Start in standalone mode");
+SetCommandLineSwitch(dedicatedClient).information("Start in dedicated client mode");
 
 DeclareToluaInterface(Orxonox);
@@ -57,5 +56,5 @@
     /**
     @brief
-        Main method. Game starts here (except for static initialisations).
+        Starting point of orxonox (however not the entry point of the program!)
     */
     int main(const std::string& strCmdLine)
@@ -67,11 +66,7 @@
         " graphics"
         "  mainMenu"
-        "  standalone"
+        "  standalone,server,client"
         "   level"
-        "  server"
-        "   level"
-        "  client"
-        "   level"
-        " dedicated"
+        " dedicated,dedicatedClient"
         "  level"
         " ioConsole"
@@ -89,4 +84,6 @@
         else if (CommandLine::getValue("dedicated").getBool())
             Game::getInstance().requestStates("dedicated, level");
+        else if (CommandLine::getValue("dedicatedClient").getBool())
+            Game::getInstance().requestStates("dedicatedClient, level");
         else if (CommandLine::getValue("console").getBool())
             Game::getInstance().requestStates("ioConsole");
Index: /code/trunk/src/orxonox/OrxonoxPrereqs.h
===================================================================
--- /code/trunk/src/orxonox/OrxonoxPrereqs.h	(revision 5928)
+++ /code/trunk/src/orxonox/OrxonoxPrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the orxonox library
 */
 
@@ -36,5 +37,4 @@
 
 #include "OrxonoxConfig.h"
-
 #include "tools/ToolsPrereqs.h"
 
@@ -42,4 +42,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined(ORXONOX_STATIC_BUILD)
 #  ifdef ORXONOX_SHARED_BUILD
@@ -65,69 +66,73 @@
 {
     class CameraManager;
+    class Level;
     class LevelManager;
     class PawnManager;
     class PlayerManager;
-
-    class Level;
+    class Radar;
     class Scene;
-    class Tickable;
+
+    // collisionshapes
+    class CollisionShape;
+    class CompoundCollisionShape;
+    class WorldEntityCollisionShape;
+
+    // controllers
+    class AIController;
+    class ArtificialController;
+    class Controller;
+    class HumanController;
+    class ScriptController;
+    class WaypointController;
+    class WaypointPatrolController;
+
+    // gametypes
+    class Asteroids;
+    class Deathmatch;
+    class Gametype;
+    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 PawnListener;
     class PlayerTrigger;
     class RadarListener;
     class RadarViewable;
     class Rewardable;
-    class Teamcolourable;
-
-    // worldentities
-    class WorldEntity;
-    class StaticEntity;
-    class MobileEntity;
-    class ControllableEntity;
-    class MovableEntity;
-
-    // graphics
-    class Model;
-    class Billboard;
-    class BlinkingBillboard;
-    class BigExplosion;
-    class ExplosionChunk;
-    class FadingBillboard;
-    class GlobalShader;
-    class Light;
-    class Backlight;
-    class ParticleEmitter;
-    class ParticleSpawner;
-    class Camera;
-
-    // mixed
-    class SpawnPoint;
-    class TeamSpawnPoint;
-
-    class CameraPosition;
-    class Sublevel;
-    class Radar;
-
-    class Test;
-
-    // pawns
-    class Spectator;
-    class Pawn;
-    class SpaceShip;
-    class TeamBaseMatchBase;
-    class Destroyer;
-
-    // gametypes
-    class Gametype;
-    class Deathmatch;
-    class TeamDeathmatch;
-    class Asteroids;
-    class TeamBaseMatch;
-    class UnderAttack;
-
-    // pickups
+    class TeamColourable;
+
+    // items
+    class Engine;
+    class Item;
+    class MultiStateEngine;
+
+    // overlays
+    class InGameConsole;
+    class Map;
+    class OrxonoxOverlay;
+    class OverlayGroup;
+
+    // pickup
     class BaseItem;
     class DroppedItem;
@@ -139,58 +144,42 @@
     class PickupSpawner;
     class UsableItem;
-
+    // pickup, items
+    class HealthImmediate;
+    class HealthUsable;
     class Jump;
-    class HealthUsable;
-    class PassiveItem;
-
-    // items
-    class Item;
-    class Engine;
-    class MultiStateEngine;
-    class RotatingEngine;
+
+    //sound
+    class AmbientSound;
+    class BaseSound;
+    class SoundManager;
+    class WorldSound;
 
     // weaponsystem
-    class WeaponSystem;
+    class DefaultWeaponmodeLink;
+    class Munition;
+    class Weapon;
+    class WeaponMode;
+    class WeaponPack;
     class WeaponSet;
     class WeaponSlot;
-    class WeaponPack;
-    class Weapon;
-    class WeaponMode;
-    class DefaultWeaponmodeLink;
-    class Munition;
-
-    // controller
-    class Controller;
-    class HumanController;
-    class ArtificialController;
-    class AIController;
-    class ScriptController;
-    class WaypointController;
-    class WaypointPatrolController;
-
-    // infos
-    class Info;
-    class PlayerInfo;
-    class HumanPlayer;
-    class Bot;
-    class GametypeInfo;
-
-    // collision
-    class CollisionShape;
-    class CompoundCollisionShape;
-    class WorldEntityCollisionShape;
-
-    // overlays
-    class OverlayGroup;
-    class OrxonoxOverlay;
-    class Notification;
-    class NotificationManager;
-    class InGameConsole;
-    class Map;
-
-    //sound
-    class SoundBase;
-    class SoundManager;
-    class SoundMainMenu;
+    class WeaponSystem;
+
+    // worldentities
+    class BigExplosion;
+    class CameraPosition;
+    class ControllableEntity;
+    class ExplosionChunk;
+    class MobileEntity;
+    class MovableEntity;
+    class SpawnPoint;
+    class StaticEntity;
+    class TeamSpawnPoint;
+    class WorldEntity;
+    // worldentities, pawns
+    class Destroyer;
+    class Pawn;
+    class SpaceShip;
+    class Spectator;
+    class TeamBaseMatchBase;
 }
 
Index: /code/trunk/src/orxonox/PawnManager.cc
===================================================================
--- /code/trunk/src/orxonox/PawnManager.cc	(revision 5928)
+++ /code/trunk/src/orxonox/PawnManager.cc	(revision 5929)
@@ -57,5 +57,5 @@
         {
             if (!it->isAlive())
-                delete (*(it++));
+                (it++)->destroy();
             else
                 ++it;
@@ -63,5 +63,5 @@
 
         if (count == 0)
-            delete this;
+            this->destroy();
     }
 }
Index: /code/trunk/src/orxonox/PlayerManager.cc
===================================================================
--- /code/trunk/src/orxonox/PlayerManager.cc	(revision 5928)
+++ /code/trunk/src/orxonox/PlayerManager.cc	(revision 5929)
@@ -31,4 +31,5 @@
 #include "core/CoreIncludes.h"
 #include "core/GameMode.h"
+#include "core/ScopedSingletonManager.h"
 #include "Level.h"
 #include "infos/HumanPlayer.h"
@@ -38,4 +39,5 @@
 {
     PlayerManager* PlayerManager::singletonPtr_s = 0;
+    ManageScopedSingleton(PlayerManager, ScopeID::Root, false);
 
     PlayerManager::PlayerManager()
@@ -74,5 +76,6 @@
         if (GameMode::isMaster())
         {
-            COUT(3) << "client disconnected" << std::endl;
+            if (clientID != 0)
+                COUT(3) << "client disconnected" << std::endl;
 
             // remove from clients-map
@@ -85,5 +88,5 @@
             // delete PlayerInfo instance
             if (player)
-                delete player;
+                player->destroy();
         }
     }
Index: /code/trunk/src/orxonox/PlayerManager.h
===================================================================
--- /code/trunk/src/orxonox/PlayerManager.h	(revision 5928)
+++ /code/trunk/src/orxonox/PlayerManager.h	(revision 5929)
@@ -50,8 +50,8 @@
                 { return this->clients_; }
 
-        private:
             void clientConnected(unsigned int clientID);
             void clientDisconnected(unsigned int clientID);
 
+        private:
             std::map<unsigned int, PlayerInfo*> clients_;
 
Index: /code/trunk/src/orxonox/Radar.cc
===================================================================
--- /code/trunk/src/orxonox/Radar.cc	(revision 5928)
+++ /code/trunk/src/orxonox/Radar.cc	(revision 5929)
@@ -43,8 +43,4 @@
 namespace orxonox
 {
-    SetConsoleCommand(Radar, cycleNavigationFocus, true).accessLevel(AccessLevel::User);
-    SetConsoleCommand(Radar, releaseNavigationFocus, true).accessLevel(AccessLevel::User);
-
-    Radar* Radar::instance_s = 0;
 
     Radar::Radar()
@@ -52,7 +48,4 @@
         , objectTypeCounter_(0)
     {
-        assert(instance_s == 0);
-        instance_s = this;
-
         // TODO: make this mapping configurable. Maybe there's a possibility with self configured
         //       configValues..
@@ -79,10 +72,12 @@
     Radar::~Radar()
     {
-        instance_s = 0;
     }
 
     const RadarViewable* Radar::getFocus()
     {
-        return *(this->itFocus_);
+        if (this->itFocus_)
+            return *(this->itFocus_);
+        else
+            return 0;
     }
 
@@ -101,5 +96,5 @@
         SUPER(Radar, tick, dt);
 
-        if (this->focus_ != *(this->itFocus_))
+        if (this->itFocus_ && (this->focus_ != *(this->itFocus_)))
         {
             // focus object was deleted, release focus
@@ -191,26 +186,3 @@
         }
     }
-
-
-    /*static*/ Radar& Radar::getInstance()
-    {
-        assert(instance_s);
-        return *instance_s;
-    }
-
-    /*static*/ void Radar::cycleNavigationFocus()
-    {
-        // avoid using getInstance because of the assert().
-        // User might call this fuction even if HUDNavigation doesn't exist.
-        if (instance_s)
-            instance_s->cycleFocus();
-    }
-
-    /*static*/ void Radar::releaseNavigationFocus()
-    {
-        // avoid using getInstance because of the assert().
-        // User might call this fuction even if HUDNavigation doesn't exist.
-        if (instance_s)
-            instance_s->releaseFocus();
-    }
 }
Index: /code/trunk/src/orxonox/Radar.h
===================================================================
--- /code/trunk/src/orxonox/Radar.h	(revision 5928)
+++ /code/trunk/src/orxonox/Radar.h	(revision 5929)
@@ -46,19 +46,9 @@
 namespace orxonox
 {
-    /**
-    @brief This class merely ensures that no one can inherit from Radar.
-    */
-    class _OrxonoxExport RadarBase
-    {
-    private:
-        friend class Radar;
-        RadarBase() { }
-    };
-
-    class _OrxonoxExport Radar : public Tickable, private virtual RadarBase
+    class _OrxonoxExport Radar : public Tickable
     {
     public:
         Radar();
-        ~Radar();
+        virtual ~Radar();
 
         virtual void tick(float dt);
@@ -69,16 +59,11 @@
         void listObjects() const;
 
-        static Radar& getInstance();
-        static Radar* getInstancePtr() { return instance_s; }
-
-        static void cycleNavigationFocus();
-        static void releaseNavigationFocus();
+        void releaseFocus();
+        void cycleFocus();
 
     private:
         Radar(Radar& instance);
 
-        void releaseFocus();
         void updateFocus();
-        void cycleFocus();
 
         ObjectListIterator<RadarViewable> itFocus_;
@@ -86,6 +71,4 @@
         std::map<std::string, RadarViewable::Shape> objectTypes_;
         int objectTypeCounter_;
-
-        static Radar* instance_s;
     };
 }
Index: /code/trunk/src/orxonox/Scene.cc
===================================================================
--- /code/trunk/src/orxonox/Scene.cc	(revision 5928)
+++ /code/trunk/src/orxonox/Scene.cc	(revision 5929)
@@ -42,6 +42,8 @@
 #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"
 
@@ -54,5 +56,5 @@
         RegisterObject(Scene);
 
-        this->setScene(this);
+        this->setScene(SmartPtr<Scene>(this, false), OBJECTID_UNKNOWN);
         this->bShadows_ = true;
 
@@ -62,4 +64,6 @@
             this->sceneManager_ = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC);
             this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
+
+            this->radar_ = new Radar();
         }
         else
@@ -68,4 +72,6 @@
             this->sceneManager_ = new Ogre::DefaultSceneManager("");
             this->rootSceneNode_ = this->sceneManager_->getRootSceneNode();
+
+            this->radar_ = 0;
         }
 
@@ -92,4 +98,7 @@
             else
                 delete this->sceneManager_;
+
+            if (this->radar_)
+                this->radar_->destroy();
 
             this->setPhysicalWorld(false);
@@ -275,5 +284,5 @@
     {
         this->objects_.push_back(object);
-        object->setScene(this);
+        object->setScene(this, this->getObjectID());
     }
 
Index: /code/trunk/src/orxonox/Scene.h
===================================================================
--- /code/trunk/src/orxonox/Scene.h	(revision 5928)
+++ /code/trunk/src/orxonox/Scene.h	(revision 5929)
@@ -71,4 +71,9 @@
                 { return this->bShadows_; }
 
+            inline Radar* getRadar()
+                { return this->radar_; }
+            
+            inline virtual uint32_t getSceneID() const { return this->getObjectID(); }
+
             virtual void tick(float dt);
 
@@ -91,4 +96,5 @@
             std::list<BaseObject*>   objects_;
             bool                     bShadows_;
+            Radar*                   radar_;
 
 
Index: /code/trunk/src/orxonox/Test.cc
===================================================================
--- /code/trunk/src/orxonox/Test.cc	(revision 5928)
+++ /code/trunk/src/orxonox/Test.cc	(revision 5929)
@@ -63,5 +63,5 @@
     setConfigValues();
     registerVariables();
-		setObjectMode(0x3);
+		setSyncMode(0x3);
 	}
 
Index: /code/trunk/src/orxonox/collisionshapes/CompoundCollisionShape.cc
===================================================================
--- /code/trunk/src/orxonox/collisionshapes/CompoundCollisionShape.cc	(revision 5928)
+++ /code/trunk/src/orxonox/collisionshapes/CompoundCollisionShape.cc	(revision 5929)
@@ -56,5 +56,5 @@
                 // make sure that the child doesn't want to detach itself --> speedup because of the missing update
                 it->first->notifyDetached();
-                delete it->first;
+                it->first->destroy();
             }
 
Index: /code/trunk/src/orxonox/collisionshapes/WorldEntityCollisionShape.cc
===================================================================
--- /code/trunk/src/orxonox/collisionshapes/WorldEntityCollisionShape.cc	(revision 5928)
+++ /code/trunk/src/orxonox/collisionshapes/WorldEntityCollisionShape.cc	(revision 5929)
@@ -43,5 +43,5 @@
         this->worldEntityOwner_ = creator;
         // suppress synchronisation
-        this->setObjectMode(0x0);
+        this->setSyncMode(0x0);
     }
 
Index: /code/trunk/src/orxonox/controllers/AIController.cc
===================================================================
--- /code/trunk/src/orxonox/controllers/AIController.cc	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/AIController.cc	(revision 5929)
@@ -44,5 +44,5 @@
         RegisterObject(AIController);
 
-        this->actionTimer_.setTimer(ACTION_INTERVAL, true, this, createExecutor(createFunctor(&AIController::action)));
+        this->actionTimer_.setTimer(ACTION_INTERVAL, true, createExecutor(createFunctor(&AIController::action, this)));
     }
 
Index: /code/trunk/src/orxonox/controllers/AIController.h
===================================================================
--- /code/trunk/src/orxonox/controllers/AIController.h	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/AIController.h	(revision 5929)
@@ -50,5 +50,5 @@
 
         private:
-            Timer<AIController> actionTimer_;
+            Timer actionTimer_;
     };
 }
Index: /code/trunk/src/orxonox/controllers/ArtificialController.cc
===================================================================
--- /code/trunk/src/orxonox/controllers/ArtificialController.cc	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/ArtificialController.cc	(revision 5929)
@@ -46,4 +46,6 @@
         this->bHasTargetPosition_ = false;
         this->targetPosition_ = Vector3::ZERO;
+        
+        this->target_.setCallback(createFunctor(&ArtificialController::targetDied, this));
     }
 
@@ -162,11 +164,14 @@
     }
 
-    void ArtificialController::destroyedPawn(Pawn* ship)
-    {
-        if (ship == this->target_)
-        {
-            this->forgetTarget();
-            this->searchRandomTargetPosition();
-        }
+    void ArtificialController::abandonTarget(Pawn* target)
+    {
+        if (target == this->target_)
+            this->targetDied();
+    }
+
+    void ArtificialController::targetDied()
+    {
+        this->forgetTarget();
+        this->searchRandomTargetPosition();
     }
 
Index: /code/trunk/src/orxonox/controllers/ArtificialController.h
===================================================================
--- /code/trunk/src/orxonox/controllers/ArtificialController.h	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/ArtificialController.h	(revision 5929)
@@ -33,18 +33,19 @@
 
 #include "util/Math.h"
-#include "interfaces/PawnListener.h"
 #include "Controller.h"
 
 namespace orxonox
 {
-    class _OrxonoxExport ArtificialController : public Controller, public PawnListener
+    class _OrxonoxExport ArtificialController : public Controller
     {
         public:
             ArtificialController(BaseObject* creator);
             virtual ~ArtificialController();
-
-            virtual void destroyedPawn(Pawn* pawn);
+            
+            void abandonTarget(Pawn* target);
 
         protected:
+            void targetDied();
+
             void moveToPosition(const Vector3& target);
             void moveToTargetPosition();
@@ -65,5 +66,5 @@
             bool bHasTargetPosition_;
             Vector3 targetPosition_;
-            Pawn* target_;
+            WeakPtr<Pawn> target_;
             bool bShooting_;
 
Index: /code/trunk/src/orxonox/controllers/HumanController.cc
===================================================================
--- /code/trunk/src/orxonox/controllers/HumanController.cc	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/HumanController.cc	(revision 5929)
@@ -36,4 +36,8 @@
 #include "infos/PlayerInfo.h"
 #include "overlays/Map.h"
+#include "graphics/Camera.h"
+#include "sound/SoundManager.h"
+#include "Radar.h"
+#include "Scene.h"
 
 namespace orxonox
@@ -56,4 +60,6 @@
     SetConsoleCommand(HumanController, dropItems,     true);
     SetConsoleCommand(HumanController, useItem,       true);
+    SetConsoleCommand(HumanController, cycleNavigationFocus,   true);
+    SetConsoleCommand(HumanController, releaseNavigationFocus, true);
 
     CreateUnloadableFactory(HumanController);
@@ -71,4 +77,20 @@
     {
         HumanController::localController_s = 0;
+    }
+
+    void HumanController::tick(float dt)
+    {
+        if (GameMode::playsSound() && HumanController::localController_s && HumanController::localController_s->controllableEntity_)
+        {
+            // Update sound listener
+            Camera* camera = HumanController::localController_s->controllableEntity_->getCamera();
+            if (camera)
+            {
+                SoundManager::getInstance().setListenerPosition(camera->getWorldPosition());
+                SoundManager::getInstance().setListenerOrientation(camera->getWorldOrientation());
+            }
+            else
+                COUT(3) << "HumanController, Warning: Using a ControllableEntity without Camera" << std::endl;
+        }
     }
 
@@ -200,3 +222,15 @@
             return NULL;
     }
+
+    void HumanController::cycleNavigationFocus()
+    {
+        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
+            HumanController::localController_s->controllableEntity_->getScene()->getRadar()->cycleFocus();
+    }
+
+    void HumanController::releaseNavigationFocus()
+    {
+        if (HumanController::localController_s && HumanController::localController_s->controllableEntity_)
+            HumanController::localController_s->controllableEntity_->getScene()->getRadar()->releaseFocus();
+    }
 }
Index: /code/trunk/src/orxonox/controllers/HumanController.h
===================================================================
--- /code/trunk/src/orxonox/controllers/HumanController.h	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/HumanController.h	(revision 5929)
@@ -31,13 +31,17 @@
 
 #include "OrxonoxPrereqs.h"
+
+#include "tools/interfaces/Tickable.h"
 #include "Controller.h"
 
 namespace orxonox
 {
-    class _OrxonoxExport HumanController : public Controller
+    class _OrxonoxExport HumanController : public Controller, public Tickable
     {
         public:
             HumanController(BaseObject* creator);
             virtual ~HumanController();
+
+            virtual void tick(float dt);
 
             static void moveFrontBack(const Vector2& value);
@@ -58,4 +62,6 @@
             static void dropItems();
             static void useItem();
+            static void cycleNavigationFocus();
+            static void releaseNavigationFocus();
 
             static void suicide();
Index: /code/trunk/src/orxonox/controllers/WaypointController.cc
===================================================================
--- /code/trunk/src/orxonox/controllers/WaypointController.cc	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/WaypointController.cc	(revision 5929)
@@ -50,5 +50,5 @@
         {
             for (size_t i = 0; i < this->waypoints_.size(); ++i)
-                delete this->waypoints_[i];
+                this->waypoints_[i]->destroy();
         }
     }
Index: /code/trunk/src/orxonox/controllers/WaypointPatrolController.cc
===================================================================
--- /code/trunk/src/orxonox/controllers/WaypointPatrolController.cc	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/WaypointPatrolController.cc	(revision 5929)
@@ -45,5 +45,5 @@
         this->alertnessradius_ = 500;
 
-        this->patrolTimer_.setTimer(rnd(), true, this, createExecutor(createFunctor(&WaypointPatrolController::searchEnemy)));
+        this->patrolTimer_.setTimer(rnd(), true, createExecutor(createFunctor(&WaypointPatrolController::searchEnemy, this)));
     }
 
Index: /code/trunk/src/orxonox/controllers/WaypointPatrolController.h
===================================================================
--- /code/trunk/src/orxonox/controllers/WaypointPatrolController.h	(revision 5928)
+++ /code/trunk/src/orxonox/controllers/WaypointPatrolController.h	(revision 5929)
@@ -61,5 +61,5 @@
             int team_;
             float alertnessradius_;
-            Timer<WaypointPatrolController> patrolTimer_;
+            Timer patrolTimer_;
     };
 }
Index: /code/trunk/src/orxonox/gamestates/CMakeLists.txt
===================================================================
--- /code/trunk/src/orxonox/gamestates/CMakeLists.txt	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/CMakeLists.txt	(revision 5929)
@@ -0,0 +1,12 @@
+ADD_SOURCE_FILES(ORXONOX_SRC_FILES
+  GSClient.cc
+  GSDedicated.cc
+  GSDedicatedClient.cc
+  GSGraphics.cc
+  GSIOConsole.cc
+  GSLevel.cc
+  GSMainMenu.cc
+  GSRoot.cc
+  GSServer.cc
+  GSStandalone.cc
+)
Index: /code/trunk/src/orxonox/gamestates/GSClient.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSClient.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSClient.cc	(revision 5929)
@@ -0,0 +1,80 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *
+ */
+
+#include "GSClient.h"
+
+#include "util/Clock.h"
+#include "util/Exception.h"
+#include "core/CommandLine.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "network/Client.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSClient, "client", false, true);
+
+    SetCommandLineArgument(ip, "127.0.0.1").information("Sever IP as string in the form #.#.#.#");
+
+    GSClient::GSClient(const GameStateInfo& info)
+        : GameState(info)
+        , client_(0)
+    {
+    }
+
+    GSClient::~GSClient()
+    {
+    }
+
+    void GSClient::activate()
+    {
+        GameMode::setIsClient(true);
+
+        this->client_ = new Client(CommandLine::getValue("ip").getString(), CommandLine::getValue("port"));
+
+        if(!client_->establishConnection())
+            ThrowException(InitialisationFailed, "Could not establish connection with server.");
+
+        client_->update(Game::getInstance().getGameClock());
+    }
+
+    void GSClient::deactivate()
+    {
+        client_->closeConnection();
+
+        // destroy client
+        delete this->client_;
+
+        GameMode::setIsClient(false);
+    }
+
+    void GSClient::update(const Clock& time)
+    {
+        client_->update(time);
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSClient.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSClient.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSClient.h	(revision 5929)
@@ -0,0 +1,54 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSClient_H__
+#define _GSClient_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "core/GameState.h"
+#include "network/NetworkPrereqs.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSClient : public GameState
+    {
+    public:
+        GSClient(const GameStateInfo& info);
+        ~GSClient();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+        Client* client_;
+    };
+}
+
+#endif /* _GSClient_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSDedicated.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSDedicated.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSDedicated.cc	(revision 5929)
@@ -0,0 +1,301 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *
+ */
+
+#include "GSDedicated.h"
+
+#include <iomanip>
+#include <iostream>
+#include <boost/bind.hpp>
+
+#include "util/Clock.h"
+#include "util/Debug.h"
+#include "util/Sleep.h"
+#include "core/CommandLine.h"
+#include "core/CommandExecutor.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "network/Server.h"
+
+#ifdef ORXONOX_PLATFORM_UNIX
+#include <termios.h>
+#endif
+
+
+namespace orxonox
+{
+    const unsigned int MAX_COMMAND_LENGTH = 255;
+    
+    DeclareGameState(GSDedicated, "dedicated", false, false);
+    
+    termios* GSDedicated::originalTerminalSettings_;
+
+    GSDedicated::GSDedicated(const GameStateInfo& info)
+        : GameState(info)
+        , server_(0)
+        , closeThread_(false)
+        , cleanLine_(true)
+        , inputIterator_(0)
+        , cursorX_(0)
+        , cursorY_(0)
+    {
+    }
+
+    GSDedicated::~GSDedicated()
+    {
+    }
+
+    void GSDedicated::activate()
+    {
+        GameMode::setHasServer(true);
+        
+        this->inputThread_ = new boost::thread(boost::bind(&GSDedicated::inputThread, this));
+        
+#ifndef ORXONOX_PLATFORM_WINDOWS
+        this->originalTerminalSettings_ = new termios;
+        this->setTerminalMode();
+#endif
+
+        this->server_ = new Server(CommandLine::getValue("port"));
+        COUT(0) << "Loading scene in server mode" << std::endl;
+
+        server_->open();
+    }
+
+    void GSDedicated::deactivate()
+    {
+        this->server_->close();
+        delete this->server_;
+        
+        closeThread_ = true;
+#ifdef ORXONOX_PLATFORM_UNIX
+        std::cout << "\033[0G\033[K";
+        std::cout.flush();
+        resetTerminalMode();
+        delete this->originalTerminalSettings_;
+#else
+        COUT(0) << "Press enter to end the game..." << std::endl;
+#endif
+        inputThread_->join();
+        delete this->inputThread_;
+
+        GameMode::setHasServer(false);
+    }
+
+    void GSDedicated::update(const Clock& time)
+    {
+        server_->update(time);
+        processQueue();
+        printLine();
+    }
+    
+    void GSDedicated::inputThread()
+    {
+        this->commandLine_ = new unsigned char[MAX_COMMAND_LENGTH];
+//         memset( this->commandLine_, 0, MAX_COMMAND_LENGTH );
+        unsigned char c;
+        unsigned int  escapeChar=0;
+        while(!closeThread_)
+        {
+#ifdef ORXONOX_PLATFORM_UNIX
+            size_t count = read(STDIN_FILENO, &c, 1);
+            if (count == 1)
+#else
+            c = getchar();
+#endif
+            {
+//                 boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                if ( inputIterator_>=MAX_COMMAND_LENGTH-1 && c!='\n' )
+                    continue;
+                if( escapeChar > 0 )
+                {
+                    if( c == '[' )
+                    {
+                        escapeChar = 2;
+                        continue;
+                    }
+                    else if ( escapeChar == 2 )
+                    {
+                        switch (c)
+                        {
+                            case 'A': //keyup
+                                
+                                break;
+                            case 'B': //keydown
+                                
+                                break;
+                            case 'C': //keyright
+                                if(cursorX_<inputIterator_)
+                                    ++cursorX_;
+                                break;
+                            case 'D': //keyleft
+                                if(cursorX_>0)
+                                    --cursorX_;
+                                break;
+                            default: //not supported...
+//                                 std::cout << endl << c << endl;
+                                break;
+                        }
+                        escapeChar = 0;
+                    }
+                }
+                else // not in escape sequence mode
+                {
+                    switch (c)
+                    {
+                        case '\n':
+                            this->cleanLine_ = true;
+                            {
+                                boost::recursive_mutex::scoped_lock(this->inputQueueMutex_);
+                                boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                                this->commandQueue_.push( std::string((const char*)this->commandLine_,inputIterator_) );
+                            }
+                            memset( this->commandLine_, 0, inputIterator_ );
+                            inputIterator_ = 0;
+                            this->cursorX_ = 0;
+                            this->cursorY_ = 0;
+                            std::cout << endl;
+                            break;
+                        case 127: // backspace
+                        case '\b':
+                            deleteCharacter( this->cursorX_ );
+                            break;
+                        case '\t':
+                        {
+//                             boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                            std::cout << endl << CommandExecutor::hint( std::string((const char*)this->commandLine_,inputIterator_) ) << endl;
+                            strncpy(reinterpret_cast<char*>(this->commandLine_), CommandExecutor::complete( std::string(reinterpret_cast<char*>(this->commandLine_),inputIterator_) ).c_str(), MAX_COMMAND_LENGTH);
+                            this->inputIterator_ = strlen((const char*)this->commandLine_);
+                            this->cursorX_ = this->inputIterator_;
+                            break;
+                        }
+                        case '\033': // 1. escape character
+                            escapeChar = 1;
+                            break;
+                        default:
+                            insertCharacter( this->cursorX_, c );
+                            break;
+                    }
+                }
+            }
+        }
+
+        delete[] this->commandLine_;
+    }
+    
+    void GSDedicated::printLine()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        // set cursor to the begining of the line and erase the line
+        std::cout << "\033[0G\033[K";
+//         boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+        // print status line
+        std::cout << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, " << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms avg ticktime # ";
+        //save cursor position
+        std::cout << "\033[s";
+        //print commandLine buffer
+        std::cout << std::string((const char*)this->commandLine_, inputIterator_);
+        //restore cursor position and move it cursorX_ to the right
+        std::cout << "\033[u";
+        if( this->cursorX_ > 0 )
+            std::cout << "\033[" << this->cursorX_ << "C";
+        std::cout.flush();
+#endif
+    }
+    
+    void GSDedicated::processQueue()
+    {
+        std::string tempstr;
+        {
+            boost::recursive_mutex::scoped_lock lock1(this->inputQueueMutex_);
+            while(true)
+            {
+                if ( !this->commandQueue_.empty() )
+                {
+                    tempstr = this->commandQueue_.front();
+                    this->commandQueue_.pop();
+                    lock1.unlock();
+                }
+                else
+                    break;
+                CommandExecutor::execute(tempstr, true);
+            }
+        }
+    }
+    
+    void GSDedicated::setTerminalMode()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        termios new_settings;
+     
+        tcgetattr(0,this->originalTerminalSettings_);
+        new_settings = *this->originalTerminalSettings_;
+        new_settings.c_lflag &= ~( ICANON | ECHO );
+//         new_settings.c_lflag |= ( ISIG | IEXTEN );
+        new_settings.c_cc[VTIME] = 1;
+        new_settings.c_cc[VMIN] = 0;
+        tcsetattr(0,TCSANOW,&new_settings);
+        COUT(0) << endl;
+//       atexit(&GSDedicated::resetTerminalMode);
+#endif
+    }
+    
+    void GSDedicated::resetTerminalMode()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        tcsetattr(0, TCSANOW, GSDedicated::originalTerminalSettings_);
+#endif
+    }
+    
+    void GSDedicated::insertCharacter( unsigned int position, char c )
+    {
+//         std::cout << endl << static_cast<unsigned int>(c) << endl;
+        // check that we do not exceed MAX_COMMAND_LENGTH
+        if( inputIterator_+1 < MAX_COMMAND_LENGTH )
+        {
+            // if cursor not at end of line then move the rest of the line
+            if( position != this->inputIterator_ )
+                    memmove( this->commandLine_+position+1, this->commandLine_+position, this->inputIterator_-position);
+//             boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+            this->commandLine_[position] = c;
+            ++this->cursorX_;
+            ++this->inputIterator_;
+        }
+    }
+    void GSDedicated::deleteCharacter( unsigned int position )
+    {
+//         boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+        if ( this->inputIterator_>0 && position>0 )
+        {
+            if ( position != this->inputIterator_ )
+                memmove( this->commandLine_+position-1, this->commandLine_+position, this->inputIterator_-position);
+            --this->cursorX_;
+            --this->inputIterator_;
+        }
+    }
+    
+}
Index: /code/trunk/src/orxonox/gamestates/GSDedicated.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSDedicated.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSDedicated.h	(revision 5929)
@@ -0,0 +1,85 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSDedicated_H__
+#define _GSDedicated_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include <cstring>
+#include <queue>
+#include <boost/thread/thread.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/thread/recursive_mutex.hpp>
+
+#include "core/GameState.h"
+#include "network/NetworkPrereqs.h"
+
+struct termios;
+
+namespace orxonox
+{
+
+    class _OrxonoxExport GSDedicated : public GameState
+    {
+    public:
+        GSDedicated(const GameStateInfo& info);
+        ~GSDedicated();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+        void inputThread();
+        void printLine();
+        void processQueue();
+        void setTerminalMode();
+        static void resetTerminalMode();
+
+        void insertCharacter( unsigned int position, char c );
+        void deleteCharacter( unsigned int position );
+
+        Server*                 server_;
+
+        boost::thread           *inputThread_;
+        boost::recursive_mutex  inputLineMutex_;
+        boost::recursive_mutex  inputQueueMutex_;
+        bool                    closeThread_;
+        bool                    cleanLine_;
+        unsigned char*          commandLine_;
+        unsigned int            inputIterator_;
+        std::queue<std::string> commandQueue_;
+        static termios*         originalTerminalSettings_;
+
+        unsigned int            cursorX_;
+        unsigned int            cursorY_;
+    };
+}
+
+#endif /* _GSDedicated_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSDedicatedClient.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSDedicatedClient.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSDedicatedClient.cc	(revision 5929)
@@ -0,0 +1,306 @@
+/*
+ *   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:
+ *      Oliver Scheuss
+ *
+ */
+
+#include "GSDedicatedClient.h"
+
+#include <iomanip>
+#include <iostream>
+#include <boost/bind.hpp>
+
+#include "util/Clock.h"
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/Sleep.h"
+#include "core/CommandLine.h"
+#include "core/CommandExecutor.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "network/Client.h"
+
+#ifdef ORXONOX_PLATFORM_UNIX
+#include <termios.h>
+#endif
+
+
+namespace orxonox
+{
+    const unsigned int MAX_COMMAND_LENGTH = 255;
+    
+    DeclareGameState(GSDedicatedClient, "dedicatedClient", false, false);
+    
+    termios* GSDedicatedClient::originalTerminalSettings_;
+
+    GSDedicatedClient::GSDedicatedClient(const GameStateInfo& info)
+        : GameState(info)
+        , client_(0)
+        , closeThread_(false)
+        , cleanLine_(true)
+        , inputIterator_(0)
+        , cursorX_(0)
+        , cursorY_(0)
+    {
+    }
+
+    GSDedicatedClient::~GSDedicatedClient()
+    {
+    }
+
+    void GSDedicatedClient::activate()
+    {
+        this->inputThread_ = new boost::thread(boost::bind(&GSDedicatedClient::inputThread, this));
+        
+#ifndef ORXONOX_PLATFORM_WINDOWS
+        this->originalTerminalSettings_ = new termios;
+        this->setTerminalMode();
+#endif
+
+        this->client_ = new Client(CommandLine::getValue("ip").getString(), CommandLine::getValue("port"));
+        COUT(0) << "Loading scene in client mode" << std::endl;
+
+        if( !client_->establishConnection() )
+            ThrowException(InitialisationFailed, "Could not establish connection with server.");
+            
+        client_->update(Game::getInstance().getGameClock());
+
+
+    }
+
+    void GSDedicatedClient::deactivate()
+    {
+        if( this->client_ )
+        {
+            this->client_->closeConnection();
+            delete this->client_;
+        }
+        
+        closeThread_ = true;
+#ifdef ORXONOX_PLATFORM_UNIX
+        std::cout << "\033[0G\033[K";
+        std::cout.flush();
+        resetTerminalMode();
+        delete this->originalTerminalSettings_;
+#else
+        COUT(0) << "Press enter to end the game..." << std::endl;
+#endif
+        inputThread_->join();
+        delete this->inputThread_;
+    }
+
+    void GSDedicatedClient::update(const Clock& time)
+    {
+        client_->update(time);
+        processQueue();
+        printLine();
+    }
+    
+    void GSDedicatedClient::inputThread()
+    {
+        this->commandLine_ = new unsigned char[MAX_COMMAND_LENGTH];
+//         memset( this->commandLine_, 0, MAX_COMMAND_LENGTH );
+        unsigned char c;
+        unsigned int  escapeChar=0;
+        while(!closeThread_)
+        {
+#ifdef ORXONOX_PLATFORM_UNIX
+            size_t count = read(STDIN_FILENO, &c, 1);
+            if (count == 1)
+#else
+            c = getchar();
+#endif
+            {
+//                 boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                if ( inputIterator_>=MAX_COMMAND_LENGTH-1 && c!='\n' )
+                    continue;
+                if( escapeChar > 0 )
+                {
+                    if( c == '[' )
+                    {
+                        escapeChar = 2;
+                        continue;
+                    }
+                    else if ( escapeChar == 2 )
+                    {
+                        switch (c)
+                        {
+                            case 'A': //keyup
+                                
+                                break;
+                            case 'B': //keydown
+                                
+                                break;
+                            case 'C': //keyright
+                                if(cursorX_<inputIterator_)
+                                    ++cursorX_;
+                                break;
+                            case 'D': //keyleft
+                                if(cursorX_>0)
+                                    --cursorX_;
+                                break;
+                            default: //not supported...
+//                                 std::cout << endl << c << endl;
+                                break;
+                        }
+                        escapeChar = 0;
+                    }
+                }
+                else // not in escape sequence mode
+                {
+                    switch (c)
+                    {
+                        case '\n':
+                            this->cleanLine_ = true;
+                            {
+                                boost::recursive_mutex::scoped_lock(this->inputQueueMutex_);
+                                boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                                this->commandQueue_.push( std::string((const char*)this->commandLine_,inputIterator_) );
+                            }
+                            memset( this->commandLine_, 0, inputIterator_ );
+                            inputIterator_ = 0;
+                            this->cursorX_ = 0;
+                            this->cursorY_ = 0;
+                            std::cout << endl;
+                            break;
+                        case 127: // backspace
+                        case '\b':
+                            deleteCharacter( this->cursorX_ );
+                            break;
+                        case '\t':
+                        {
+//                             boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+                            std::cout << endl << CommandExecutor::hint( std::string((const char*)this->commandLine_,inputIterator_) ) << endl;
+                            strncpy(reinterpret_cast<char*>(this->commandLine_), CommandExecutor::complete( std::string(reinterpret_cast<char*>(this->commandLine_),inputIterator_) ).c_str(), MAX_COMMAND_LENGTH);
+                            this->inputIterator_ = strlen((const char*)this->commandLine_);
+                            this->cursorX_ = this->inputIterator_;
+                            break;
+                        }
+                        case '\033': // 1. escape character
+                            escapeChar = 1;
+                            break;
+                        default:
+                            insertCharacter( this->cursorX_, c );
+                            break;
+                    }
+                }
+            }
+        }
+
+        delete[] this->commandLine_;
+    }
+    
+    void GSDedicatedClient::printLine()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        // set cursor to the begining of the line and erase the line
+        std::cout << "\033[0G\033[K";
+//         boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+        // print status line
+        std::cout << std::fixed << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgFPS() << " fps, " << std::setprecision(2) << std::setw(5) << Game::getInstance().getAvgTickTime() << " ms avg ticktime # ";
+        //save cursor position
+        std::cout << "\033[s";
+        //print commandLine buffer
+        std::cout << std::string((const char*)this->commandLine_, inputIterator_);
+        //restore cursor position and move it cursorX_ to the right
+        std::cout << "\033[u";
+        if( this->cursorX_ > 0 )
+            std::cout << "\033[" << this->cursorX_ << "C";
+        std::cout.flush();
+#endif
+    }
+    
+    void GSDedicatedClient::processQueue()
+    {
+        std::string tempstr;
+        {
+            boost::recursive_mutex::scoped_lock lock1(this->inputQueueMutex_);
+            while(true)
+            {
+                if ( !this->commandQueue_.empty() )
+                {
+                    tempstr = this->commandQueue_.front();
+                    this->commandQueue_.pop();
+                    lock1.unlock();
+                }
+                else
+                    break;
+                CommandExecutor::execute(tempstr, true);
+            }
+        }
+    }
+    
+    void GSDedicatedClient::setTerminalMode()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        termios new_settings;
+     
+        tcgetattr(0,this->originalTerminalSettings_);
+        new_settings = *this->originalTerminalSettings_;
+        new_settings.c_lflag &= ~( ICANON | ECHO );
+//         new_settings.c_lflag |= ( ISIG | IEXTEN );
+        new_settings.c_cc[VTIME] = 1;
+        new_settings.c_cc[VMIN] = 0;
+        tcsetattr(0,TCSANOW,&new_settings);
+        COUT(0) << endl;
+//       atexit(&GSDedicatedClient::resetTerminalMode);
+#endif
+    }
+    
+    void GSDedicatedClient::resetTerminalMode()
+    {
+#ifdef ORXONOX_PLATFORM_UNIX
+        tcsetattr(0, TCSANOW, GSDedicatedClient::originalTerminalSettings_);
+#endif
+    }
+    
+    void GSDedicatedClient::insertCharacter( unsigned int position, char c )
+    {
+//         std::cout << endl << static_cast<unsigned int>(c) << endl;
+        // check that we do not exceed MAX_COMMAND_LENGTH
+        if( inputIterator_+1 < MAX_COMMAND_LENGTH )
+        {
+            // if cursor not at end of line then move the rest of the line
+            if( position != this->inputIterator_ )
+                    memmove( this->commandLine_+position+1, this->commandLine_+position, this->inputIterator_-position);
+//             boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+            this->commandLine_[position] = c;
+            ++this->cursorX_;
+            ++this->inputIterator_;
+        }
+    }
+    void GSDedicatedClient::deleteCharacter( unsigned int position )
+    {
+//         boost::recursive_mutex::scoped_lock(this->inputLineMutex_);
+        if ( this->inputIterator_>0 && position>0 )
+        {
+            if ( position != this->inputIterator_ )
+                memmove( this->commandLine_+position-1, this->commandLine_+position, this->inputIterator_-position);
+            --this->cursorX_;
+            --this->inputIterator_;
+        }
+    }
+    
+}
Index: /code/trunk/src/orxonox/gamestates/GSDedicatedClient.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSDedicatedClient.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSDedicatedClient.h	(revision 5929)
@@ -0,0 +1,84 @@
+/*
+ *   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:
+ *      Oliver Scheuss
+ *
+ */
+
+#ifndef _GSDedicatedClient_H__
+#define _GSDedicatedClient_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "core/GameState.h"
+#include "network/NetworkPrereqs.h"
+#include <queue>
+#include <cstring>
+#include <boost/thread/thread.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/thread/recursive_mutex.hpp>
+
+struct termios;
+
+namespace orxonox
+{
+
+    class _OrxonoxExport GSDedicatedClient : public GameState
+    {
+    public:
+        GSDedicatedClient(const GameStateInfo& info);
+        ~GSDedicatedClient();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+        void inputThread();
+        void printLine();
+        void processQueue();
+        void setTerminalMode();
+        static void resetTerminalMode();
+
+        void insertCharacter( unsigned int position, char c );
+        void deleteCharacter( unsigned int position );
+
+        Client*                 client_;
+
+        boost::thread           *inputThread_;
+        boost::recursive_mutex  inputLineMutex_;
+        boost::recursive_mutex  inputQueueMutex_;
+        bool                    closeThread_;
+        bool                    cleanLine_;
+        unsigned char*          commandLine_;
+        unsigned int            inputIterator_;
+        std::queue<std::string> commandQueue_;
+        static termios*         originalTerminalSettings_;
+
+        unsigned int            cursorX_;
+        unsigned int            cursorY_;
+    };
+}
+
+#endif /* _GSDedicatedClient_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSGraphics.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSGraphics.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSGraphics.cc	(revision 5929)
@@ -0,0 +1,101 @@
+/*
+ *   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:
+ *      Benjamin Knecht
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of Graphics GameState class.
+ */
+
+#include "GSGraphics.h"
+
+#include "core/CommandExecutor.h"
+#include "core/ConsoleCommand.h"
+#include "core/Game.h"
+#include "core/GUIManager.h"
+// HACK:
+#include "overlays/Map.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSGraphics, "graphics", false, true);
+
+    GSGraphics::GSGraphics(const GameStateInfo& info)
+        : GameState(info)
+    {
+    }
+
+    GSGraphics::~GSGraphics()
+    {
+    }
+
+    /**
+    @brief
+        This function is called when we enter this game state.
+
+        There is only one thing to do here:
+        \li create console command to toggle GUI
+    */
+    void GSGraphics::activate()
+    {
+        // add console command to toggle GUI
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSGraphics::toggleGUI, this), "toggleGUI"));
+    }
+
+    /**
+    @brief
+        This function is called when the game state is left
+    */
+    void GSGraphics::deactivate()
+    {
+        // HACK: (destroys a resource smart pointer)
+        Map::hackDestroyMap();
+    }
+
+    /**
+    @brief
+        Toggles the visibility of the current GUI
+
+        This function just executes a Lua function in the main script of the GUI by accessing the GUIManager.
+        For more details on this function check out the Lua code.
+    */
+    void GSGraphics::toggleGUI()
+    {
+        GUIManager::getInstance().executeCode("toggleGUI()");
+    }
+
+    void GSGraphics::update(const Clock& time)
+    {
+        if (this->getActivity().topState)
+        {
+            // This state can not 'survive' on its own.
+            // Load a user interface therefore
+            Game::getInstance().requestState("mainMenu");
+        }
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSGraphics.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSGraphics.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSGraphics.h	(revision 5929)
@@ -0,0 +1,65 @@
+/*
+ *   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:
+ *      Benjamin Knecht (documentation)
+ *
+ */
+
+/**
+@file
+@brief
+    Declaration of the Graphics GameState class.
+*/
+
+#ifndef _GSGraphics_H__
+#define _GSGraphics_H__
+
+#include "OrxonoxPrereqs.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Game state used when displaying graphics of any kind. Another blubb resides here.
+
+        This game state is only left out if we start a dedicated server where no graphics are present.
+    */
+    class _OrxonoxExport GSGraphics : public GameState
+    {
+    public:
+        GSGraphics(const GameStateInfo& info);
+        ~GSGraphics();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+        void toggleGUI();
+
+    private:
+    };
+}
+
+#endif /* _GSGraphics_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSIOConsole.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSIOConsole.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSIOConsole.cc	(revision 5929)
@@ -0,0 +1,71 @@
+/*
+ *   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 "GSIOConsole.h"
+
+#include <iostream>
+#include "core/ConsoleCommand.h"
+#include "core/CommandExecutor.h"
+#include "core/Game.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSIOConsole, "ioConsole", false, false);
+
+    GSIOConsole::GSIOConsole(const GameStateInfo& info)
+        : GameState(info)
+    {
+    }
+
+    GSIOConsole::~GSIOConsole()
+    {
+    }
+
+    void GSIOConsole::activate()
+    {
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSIOConsole::loadMenu, this), "loadMenu"));
+    }
+
+    void GSIOConsole::deactivate()
+    {
+    }
+
+    void GSIOConsole::update(const Clock& time)
+    {
+        std::cout << ">";
+        std::string command;
+        std::getline(std::cin, command);
+        CommandExecutor::execute(command, true);
+    }
+
+    void GSIOConsole::loadMenu()
+    {
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("graphics, mainMenu");
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSIOConsole.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSIOConsole.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSIOConsole.h	(revision 5929)
@@ -0,0 +1,52 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSIOConsole_H__
+#define _GSIOConsole_H__
+
+#include "OrxonoxPrereqs.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSIOConsole : public GameState
+    {
+    public:
+        GSIOConsole(const GameStateInfo& info);
+        ~GSIOConsole();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+        void loadMenu();
+    };
+}
+
+#endif /* _GSIOConsole_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSLevel.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSLevel.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSLevel.cc	(revision 5929)
@@ -0,0 +1,182 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *      Benjamin Knecht
+ *
+ */
+
+#include "GSLevel.h"
+
+#include <OgreCompositorManager.h>
+
+#include "util/Clock.h"
+#include "core/input/InputManager.h"
+#include "core/input/InputState.h"
+#include "core/input/KeyBinderManager.h"
+#include "core/ConsoleCommand.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "core/GUIManager.h"
+#include "core/Loader.h"
+#include "core/XMLFile.h"
+
+#include "LevelManager.h"
+#include "PlayerManager.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSLevel, "level", false, false);
+
+    GSLevel::GSLevel(const GameStateInfo& info)
+        : GameState(info)
+        , gameInputState_(0)
+        , guiMouseOnlyInputState_(0)
+        , guiKeysOnlyInputState_(0)
+        , startFile_(0)
+    {
+    }
+
+    GSLevel::~GSLevel()
+    {
+    }
+
+    void GSLevel::activate()
+    {
+        if (GameMode::showsGraphics())
+        {
+            gameInputState_ = InputManager::getInstance().createInputState("game");
+            gameInputState_->setMouseMode(MouseMode::Exclusive);
+            gameInputState_->setHandler(KeyBinderManager::getInstance().getDefaultAsHandler());
+            KeyBinderManager::getInstance().setToDefault();
+
+            guiMouseOnlyInputState_ = InputManager::getInstance().createInputState("guiMouseOnly");
+            guiMouseOnlyInputState_->setMouseMode(MouseMode::Exclusive);
+            guiMouseOnlyInputState_->setMouseHandler(GUIManager::getInstancePtr());
+
+            guiKeysOnlyInputState_ = InputManager::getInstance().createInputState("guiKeysOnly");
+            guiKeysOnlyInputState_->setKeyHandler(GUIManager::getInstancePtr());
+
+            CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSLevel::showIngameGUI, this), "showIngameGUI"));
+        }
+
+        if (GameMode::isMaster())
+        {
+            this->loadLevel();
+        }
+
+        if (GameMode::showsGraphics())
+        {
+            // level is loaded: we can start capturing the input
+            InputManager::getInstance().enterState("game");
+            
+            // connect the HumanPlayer to the game
+            PlayerManager::getInstance().clientConnected(0);
+        }
+    }
+
+    void GSLevel::showIngameGUI(bool show)
+    {
+        if (show)
+        {
+            GUIManager::getInstance().showGUI("inGameTest");
+            GUIManager::getInstance().executeCode("showCursor()");
+            InputManager::getInstance().enterState("guiMouseOnly");
+        }
+        else
+        {
+            GUIManager::getInstance().executeCode("hideGUI(\"inGameTest\")");
+            GUIManager::getInstance().executeCode("hideCursor()");
+            InputManager::getInstance().leaveState("guiMouseOnly");
+        }
+    }
+
+    void GSLevel::deactivate()
+    {
+        if (GameMode::showsGraphics())
+        {
+            // disconnect the HumanPlayer
+            PlayerManager::getInstance().clientDisconnected(0);
+            
+            // unload all compositors (this is only necessary because we don't yet destroy all resources!)
+            Ogre::CompositorManager::getSingleton().removeAll();
+
+            InputManager::getInstance().leaveState("game");
+        }
+
+        if (GameMode::isMaster())
+            this->unloadLevel();
+
+        if (GameMode::showsGraphics())
+        {
+            gameInputState_->setHandler(0);
+            guiMouseOnlyInputState_->setHandler(0);
+            guiKeysOnlyInputState_->setHandler(0);
+            InputManager::getInstance().destroyState("game");
+            InputManager::getInstance().destroyState("guiKeysOnly");
+            InputManager::getInstance().destroyState("guiMouseOnly");
+        }
+    }
+
+    void GSLevel::update(const Clock& time)
+    {
+        // Note: Temporarily moved to GSRoot.
+        //// Call the scene objects
+        //for (ObjectList<Tickable>::iterator it = ObjectList<Tickable>::begin(); it; ++it)
+        //    it->tick(time.getDeltaTime() * this->timeFactor_);
+    }
+
+    void GSLevel::loadLevel()
+    {
+        for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); ++it)
+            this->staticObjects_.insert(*it);
+        
+        // call the loader
+        COUT(0) << "Loading level..." << std::endl;
+        startFile_ = new XMLFile(LevelManager::getInstance().getDefaultLevel());
+        Loader::open(startFile_);
+    }
+
+    void GSLevel::unloadLevel()
+    {
+        Loader::unload(startFile_);
+        delete startFile_;
+
+        COUT(3) << "Unloaded level. Remaining objects:" << std::endl;
+        unsigned int i = 0;
+        for (ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it != ObjectList<BaseObject>::end(); ++it)
+        {
+            std::set<BaseObject*>::const_iterator find = this->staticObjects_.find(*it);
+            if (find == this->staticObjects_.end())
+            {
+                COUT(3) << ++i << ": " << it->getIdentifier()->getName() << " (" << *it << ")" << std::endl;
+            }
+        }
+        COUT(3) << i << " objects remaining.";
+        if (i == 0)
+            COUT(3) << " Well done!" << std::endl;
+        else
+            COUT(3) << " Try harder!" << std::endl;
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSLevel.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSLevel.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSLevel.h	(revision 5929)
@@ -0,0 +1,65 @@
+/*
+ *   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:
+ *      Benjamin Knecht
+ *
+ */
+
+#ifndef _GSLevel_H__
+#define _GSLevel_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include <string>
+#include <set>
+#include "core/OrxonoxClass.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSLevel : public GameState
+    {
+    public:
+        GSLevel(const GameStateInfo& info);
+        ~GSLevel();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    protected:
+        void loadLevel();
+        void unloadLevel();
+        void showIngameGUI(bool show);
+
+        InputState*              gameInputState_;          //!< input state for normal ingame playing
+        InputState*              guiMouseOnlyInputState_;  //!< input state if we only need the mouse to use the GUI
+        InputState*              guiKeysOnlyInputState_;   //!< input state if we only need the keys to use the GUI
+
+        XMLFile* startFile_;
+        std::set<BaseObject*> staticObjects_;
+    };
+}
+
+#endif /* _GSLevel_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSMainMenu.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSMainMenu.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSMainMenu.cc	(revision 5929)
@@ -0,0 +1,164 @@
+/*
+ *   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 "GSMainMenu.h"
+
+#include <OgreSceneManager.h>
+
+#include "core/input/InputManager.h"
+#include "core/input/InputState.h"
+#include "core/input/KeyBinderManager.h"
+#include "core/Game.h"
+#include "core/ConsoleCommand.h"
+#include "core/GraphicsManager.h"
+#include "core/GUIManager.h"
+#include "Scene.h"
+#include "sound/AmbientSound.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSMainMenu, "mainMenu", false, true);
+
+    GSMainMenu::GSMainMenu(const GameStateInfo& info)
+        : GameState(info)
+        , inputState_(0)
+    {
+        inputState_ = InputManager::getInstance().createInputState("mainMenu");
+        inputState_->setMouseMode(MouseMode::Nonexclusive);
+        inputState_->setHandler(GUIManager::getInstancePtr());
+        inputState_->setKeyHandler(KeyBinderManager::getInstance().getDefaultAsHandler());
+        inputState_->setJoyStickHandler(&InputHandler::EMPTY);
+
+        // create an empty Scene
+        this->scene_ = new Scene(NULL);
+        this->scene_->setSyncMode( 0x0 );
+        // and a Camera
+        this->camera_ = this->scene_->getSceneManager()->createCamera("mainMenu/Camera");
+        if (GameMode::playsSound())
+        {
+            // Load sound
+            this->ambient_ = new AmbientSound(0);
+            this->ambient_->setSource("ambient/mainmenu.wav");
+        }
+    }
+
+    GSMainMenu::~GSMainMenu()
+    {
+        if (GameMode::playsSound())
+            delete this->ambient_;
+
+        InputManager::getInstance().destroyState("mainMenu");
+
+        this->scene_->getSceneManager()->destroyCamera(this->camera_);
+        this->scene_->destroy();
+    }
+
+    void GSMainMenu::activate()
+    {
+        // show main menu
+        GUIManager::getInstance().showGUI("MainMenu");
+        GUIManager::getInstance().setCamera(this->camera_);
+        GraphicsManager::getInstance().setCamera(this->camera_);
+
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startStandalone), "startGame"));
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startServer), "startServer"));
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startClient), "startClient"));
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startDedicated), "startDedicated"));
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startMainMenu), "startMainMenu"));
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&GSMainMenu::startIOConsole), "startIOConsole"));
+
+        KeyBinderManager::getInstance().setToDefault();
+        InputManager::getInstance().enterState("mainMenu");
+
+        if (GameMode::playsSound())
+        {
+            this->ambient_->setLoop(true);
+            this->ambient_->play();
+        }
+    }
+
+    void GSMainMenu::deactivate()
+    {
+        if (GameMode::playsSound())
+        {
+            this->ambient_->stop();
+        }
+
+        InputManager::getInstance().leaveState("mainMenu");
+
+        GUIManager::getInstance().setCamera(0);
+        GraphicsManager::getInstance().setCamera(0);
+    }
+
+    void GSMainMenu::update(const Clock& time)
+    {
+    }
+
+    void GSMainMenu::startStandalone()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("standalone, level");
+    }
+
+    void GSMainMenu::startServer()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("server, level");
+    }
+
+    void GSMainMenu::startClient()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("client, level");
+    }
+
+    void GSMainMenu::startDedicated()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("dedicated, level");
+    }
+    void GSMainMenu::startMainMenu()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("mainmenu");
+    }
+    void GSMainMenu::startIOConsole()
+    {
+        // HACK - HACK
+        Game::getInstance().popState();
+        Game::getInstance().popState();
+        Game::getInstance().requestStates("ioConsole");
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSMainMenu.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSMainMenu.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSMainMenu.h	(revision 5929)
@@ -0,0 +1,66 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSMainMenu_H__
+#define _GSMainMenu_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "util/OgreForwardRefs.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSMainMenu : public GameState
+    {
+    public:
+        GSMainMenu(const GameStateInfo& info);
+        ~GSMainMenu();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+        static void startStandalone();
+        static void startServer();
+        static void startClient();
+        static void startDedicated();
+        static void startMainMenu();
+        static void startIOConsole();
+
+    private:
+        InputState*       inputState_;
+        Scene*            scene_;
+        Ogre::Camera*     camera_;
+
+        // ambient sound for the main menu
+        AmbientSound*     ambient_;
+    };
+}
+
+#endif /* _GSMainMenu_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSRoot.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSRoot.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSRoot.cc	(revision 5929)
@@ -0,0 +1,157 @@
+/*
+ *   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 "GSRoot.h"
+
+#include "util/Clock.h"
+#include "core/ConsoleCommand.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "network/NetworkFunction.h"
+#include "tools/Timer.h"
+#include "tools/interfaces/TimeFactorListener.h"
+#include "tools/interfaces/Tickable.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSRoot, "root", false, false);
+    SetConsoleCommandShortcut(GSRoot, printObjects);
+
+    GSRoot::GSRoot(const GameStateInfo& info)
+        : GameState(info)
+        , timeFactor_(1.0f)
+        , bPaused_(false)
+        , timeFactorPauseBackup_(1.0f)
+    {
+    }
+
+    GSRoot::~GSRoot()
+    {
+        NetworkFunctionBase::destroyAllNetworkFunctions();
+    }
+    
+    void GSRoot::printObjects()
+    {
+        unsigned int nr=0;
+        for(ObjectList<BaseObject>::iterator it = ObjectList<BaseObject>::begin(); it; ++it){
+            if( dynamic_cast<Synchronisable*>(*it) )
+                COUT(0) << "object: " << it->getIdentifier()->getName() << " id: " << dynamic_cast<Synchronisable*>(*it)->getObjectID() << std::endl;
+            else
+                COUT(0) << "object: " << it->getIdentifier()->getName() << std::endl;
+            nr++;
+        }
+        COUT(0) << "currently got " << nr << " objects" << std::endl;
+    
+    }
+
+    void GSRoot::activate()
+    {
+        // reset game speed to normal
+        this->timeFactor_ = 1.0f;
+
+        // time factor console command
+        ConsoleCommand* command = createConsoleCommand(createFunctor(&GSRoot::setTimeFactor, this), "setTimeFactor");
+        CommandExecutor::addConsoleCommandShortcut(command).accessLevel(AccessLevel::Offline).defaultValue(0, 1.0);
+
+        // time factor console command
+        command = createConsoleCommand(createFunctor(&GSRoot::pause, this), "pause");
+        CommandExecutor::addConsoleCommandShortcut(command).accessLevel(AccessLevel::Offline);
+    }
+
+    void GSRoot::deactivate()
+    {
+    }
+
+    void GSRoot::update(const Clock& time)
+    {
+        if (this->getActivity().topState)
+        {
+            // This state can not 'survive' on its own.
+            // Load a user interface therefore
+            Game::getInstance().requestState("ioConsole");
+        }
+
+        for (ObjectList<Timer>::iterator it = ObjectList<Timer>::begin(); it; )
+            (it++)->tick(time);
+
+        /*** HACK *** HACK ***/
+        // Call the Tickable objects
+        float leveldt = time.getDeltaTime();
+        if (leveldt > 1.0f)
+        {
+            // just loaded
+            leveldt = 0.0f;
+        }
+        for (ObjectList<Tickable>::iterator it = ObjectList<Tickable>::begin(); it; )
+            (it++)->tick(leveldt * this->timeFactor_);
+        /*** HACK *** HACK ***/
+    }
+
+    /**
+    @brief
+        Changes the speed of Orxonox
+    @remark
+        This function is a hack when placed here!
+        Timefactor should be related to the scene (level or so), not the game
+    */
+    void GSRoot::setTimeFactor(float factor)
+    {
+        if (GameMode::isMaster())
+        {
+            if (!this->bPaused_)
+            {
+                TimeFactorListener::timefactor_s = factor;
+
+                for (ObjectList<TimeFactorListener>::iterator it = ObjectList<TimeFactorListener>::begin(); it != ObjectList<TimeFactorListener>::end(); ++it)
+                    it->changedTimeFactor(factor, this->timeFactor_);
+
+                this->timeFactor_ = factor;
+            }
+            else
+                this->timeFactorPauseBackup_ = factor;
+        }
+    }
+
+    void GSRoot::pause()
+    {
+        if (GameMode::isMaster())
+        {
+            if (!this->bPaused_)
+            {
+                this->timeFactorPauseBackup_ = this->timeFactor_;
+                this->setTimeFactor(0.0f);
+                this->bPaused_ = true;
+            }
+            else
+            {
+                this->bPaused_ = false;
+                this->setTimeFactor(this->timeFactorPauseBackup_);
+            }
+        }
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSRoot.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSRoot.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSRoot.h	(revision 5929)
@@ -0,0 +1,62 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSRoot_H__
+#define _GSRoot_H__
+
+#include "OrxonoxPrereqs.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSRoot : public GameState
+    {
+    public:
+        GSRoot(const GameStateInfo& info);
+        ~GSRoot();
+
+        static void printObjects();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+        // this has to be public because proteced triggers a bug in msvc
+        // when taking the function address.
+        void setTimeFactor(float factor);
+        void pause();
+        float getTimeFactor() { return this->timeFactor_; }
+
+    private:
+        float                 timeFactor_;              //!< A factor that sets the gamespeed. 1 is normal.
+        bool                  bPaused_;
+        float                 timeFactorPauseBackup_;
+    };
+}
+
+#endif /* _GSRoot_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSServer.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSServer.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSServer.cc	(revision 5929)
@@ -0,0 +1,75 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *
+ */
+
+#include "GSServer.h"
+
+#include "util/Debug.h"
+#include "core/CommandLine.h"
+#include "core/Game.h"
+#include "core/GameMode.h"
+#include "network/Server.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSServer, "server", false, true);
+
+    SetCommandLineArgument(port, 55556).shortcut("p").information("Network communication port to be used 0-65535 (default: 55556)");
+
+    GSServer::GSServer(const GameStateInfo& info)
+        : GameState(info)
+        , server_(0)
+    {
+    }
+
+    GSServer::~GSServer()
+    {
+    }
+
+    void GSServer::activate()
+    {
+        GameMode::setHasServer(true);
+
+        this->server_ = new Server(CommandLine::getValue("port"));
+        COUT(0) << "Loading scene in server mode" << std::endl;
+
+        server_->open();
+    }
+
+    void GSServer::deactivate()
+    {
+        this->server_->close();
+        delete this->server_;
+
+        GameMode::setHasServer(false);
+    }
+
+    void GSServer::update(const Clock& time)
+    {
+        server_->update(time);
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSServer.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSServer.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSServer.h	(revision 5929)
@@ -0,0 +1,54 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSServer_H__
+#define _GSServer_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "core/GameState.h"
+#include "network/NetworkPrereqs.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSServer : public GameState
+    {
+    public:
+        GSServer(const GameStateInfo& info);
+        ~GSServer();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+        Server* server_;
+    };
+}
+
+#endif /* _GSServer_H__ */
Index: /code/trunk/src/orxonox/gamestates/GSStandalone.cc
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSStandalone.cc	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSStandalone.cc	(revision 5929)
@@ -0,0 +1,61 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *
+ */
+
+#include "GSStandalone.h"
+
+#include "core/Game.h"
+#include "core/GameMode.h"
+
+namespace orxonox
+{
+    DeclareGameState(GSStandalone, "standalone", false, true);
+
+    GSStandalone::GSStandalone(const GameStateInfo& info)
+        : GameState(info)
+    {
+    }
+
+    GSStandalone::~GSStandalone()
+    {
+    }
+
+
+    void GSStandalone::activate()
+    {
+        GameMode::setIsStandalone(true);
+    }
+
+    void GSStandalone::deactivate()
+    {
+        GameMode::setIsStandalone(false);
+    }
+
+    void GSStandalone::update(const Clock& time)
+    {
+    }
+}
Index: /code/trunk/src/orxonox/gamestates/GSStandalone.h
===================================================================
--- /code/trunk/src/orxonox/gamestates/GSStandalone.h	(revision 5929)
+++ /code/trunk/src/orxonox/gamestates/GSStandalone.h	(revision 5929)
@@ -0,0 +1,51 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _GSStandalone_H__
+#define _GSStandalone_H__
+
+#include "OrxonoxPrereqs.h"
+#include "core/GameState.h"
+
+namespace orxonox
+{
+    class _OrxonoxExport GSStandalone : public GameState
+    {
+    public:
+        GSStandalone(const GameStateInfo& info);
+        ~GSStandalone();
+
+        void activate();
+        void deactivate();
+        void update(const Clock& time);
+
+    private:
+    };
+}
+
+#endif /* _GSStandalone_H__ */
Index: /code/trunk/src/orxonox/gametypes/Asteroids.cc
===================================================================
--- /code/trunk/src/orxonox/gametypes/Asteroids.cc	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/Asteroids.cc	(revision 5929)
@@ -54,5 +54,5 @@
         if (this->time_ < 0 && !this->hasEnded() && this->timerIsActive_)
         {
-            this->gtinfo_.sendAnnounceMessage("Time's up - you have lost the match!");
+            this->gtinfo_->sendAnnounceMessage("Time's up - you have lost the match!");
             this->end();
         }
@@ -63,5 +63,5 @@
         if (victim && victim->getPlayer())
         {
-            this->gtinfo_.sendAnnounceMessage("You're dead - you have lost the match!");
+            this->gtinfo_->sendAnnounceMessage("You're dead - you have lost the match!");
             this->end();
         }
Index: /code/trunk/src/orxonox/gametypes/Gametype.cc
===================================================================
--- /code/trunk/src/orxonox/gametypes/Gametype.cc	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/Gametype.cc	(revision 5929)
@@ -33,4 +33,5 @@
 #include "core/ConfigValueIncludes.h"
 #include "core/GameMode.h"
+#include "core/ConsoleCommand.h"
 
 #include "infos/PlayerInfo.h"
@@ -47,9 +48,11 @@
     CreateUnloadableFactory(Gametype);
 
-    Gametype::Gametype(BaseObject* creator) : BaseObject(creator), gtinfo_(creator)
+    Gametype::Gametype(BaseObject* creator) : BaseObject(creator)
     {
         RegisterObject(Gametype);
-
-        this->setGametype(this);
+        
+        this->gtinfo_ = new GametypeInfo(creator);
+
+        this->setGametype(SmartPtr<Gametype>(this, false));
 
         this->defaultControllableEntity_ = Class(Spectator);
@@ -76,4 +79,23 @@
         else
             this->scoreboard_ = 0;
+        
+        /* HACK HACK HACK */
+        this->hackAddBots_ = createConsoleCommand( createFunctor(&Gametype::addBots, this), "hackAddBots");
+        this->hackKillBots_ = createConsoleCommand( createFunctor(&Gametype::killBots, this), "hackKillBots");
+        CommandExecutor::addConsoleCommandShortcut( this->hackAddBots_ );
+        CommandExecutor::addConsoleCommandShortcut( this->hackKillBots_ );
+        /* HACK HACK HACK */
+    }
+    
+    Gametype::~Gametype()
+    {
+        if (this->isInitialized())
+        {
+            this->gtinfo_->destroy();
+            if( this->hackAddBots_ )
+                delete this->hackAddBots_;
+            if( this->hackKillBots_ )
+                delete this->hackKillBots_;
+        }
     }
 
@@ -100,10 +122,10 @@
         }
 
-        if (this->gtinfo_.bStartCountdownRunning_ && !this->gtinfo_.bStarted_)
-            this->gtinfo_.startCountdown_ -= dt;
-
-        if (!this->gtinfo_.bStarted_)
+        if (this->gtinfo_->bStartCountdownRunning_ && !this->gtinfo_->bStarted_)
+            this->gtinfo_->startCountdown_ -= dt;
+
+        if (!this->gtinfo_->bStarted_)
             this->checkStart();
-        else if (!this->gtinfo_.bEnded_)
+        else if (!this->gtinfo_->bEnded_)
             this->spawnDeadPlayersIfRequested();
 
@@ -115,5 +137,5 @@
         this->addBots(this->numberOfBots_);
 
-        this->gtinfo_.bStarted_ = true;
+        this->gtinfo_->bStarted_ = true;
 
         this->spawnPlayersIfRequested();
@@ -122,5 +144,5 @@
     void Gametype::end()
     {
-        this->gtinfo_.bEnded_ = true;
+        this->gtinfo_->bEnded_ = true;
 
         for (std::map<PlayerInfo*, Player>::iterator it = this->players_.begin(); it != this->players_.end(); ++it)
@@ -130,5 +152,5 @@
                 ControllableEntity* oldentity = it->first->getControllableEntity();
 
-                ControllableEntity* entity = this->defaultControllableEntity_.fabricate(oldentity->getCreator());
+                ControllableEntity* entity = this->defaultControllableEntity_.fabricate(oldentity);
                 if (oldentity->getCamera())
                 {
@@ -243,7 +265,7 @@
 
                         if (killer->getPlayer()->getClientID() != CLIENTID_UNKNOWN)
-                            this->gtinfo_.sendKillMessage("You killed " + victim->getPlayer()->getName(), killer->getPlayer()->getClientID());
+                            this->gtinfo_->sendKillMessage("You killed " + victim->getPlayer()->getName(), killer->getPlayer()->getClientID());
                         if (victim->getPlayer()->getClientID() != CLIENTID_UNKNOWN)
-                            this->gtinfo_.sendDeathMessage("You were killed by " + killer->getPlayer()->getName(), victim->getPlayer()->getClientID());
+                            this->gtinfo_->sendDeathMessage("You were killed by " + killer->getPlayer()->getName(), victim->getPlayer()->getClientID());
                     }
                 }
@@ -308,5 +330,5 @@
                 it->second.state_ = PlayerState::Dead;
 
-                if (!it->first->isReadyToSpawn() || !this->gtinfo_.bStarted_)
+                if (!it->first->isReadyToSpawn() || !this->gtinfo_->bStarted_)
                 {
                     this->spawnPlayerAsDefaultPawn(it->first);
@@ -319,12 +341,12 @@
     void Gametype::checkStart()
     {
-        if (!this->gtinfo_.bStarted_)
-        {
-            if (this->gtinfo_.bStartCountdownRunning_)
-            {
-                if (this->gtinfo_.startCountdown_ <= 0)
-                {
-                    this->gtinfo_.bStartCountdownRunning_ = false;
-                    this->gtinfo_.startCountdown_ = 0;
+        if (!this->gtinfo_->bStarted_)
+        {
+            if (this->gtinfo_->bStartCountdownRunning_)
+            {
+                if (this->gtinfo_->startCountdown_ <= 0)
+                {
+                    this->gtinfo_->bStartCountdownRunning_ = false;
+                    this->gtinfo_->startCountdown_ = 0;
                     this->start();
                 }
@@ -349,6 +371,6 @@
                     if (allplayersready && hashumanplayers)
                     {
-                        this->gtinfo_.startCountdown_ = this->initialStartCountdown_;
-                        this->gtinfo_.bStartCountdownRunning_ = true;
+                        this->gtinfo_->startCountdown_ = this->initialStartCountdown_;
+                        this->gtinfo_->bStartCountdownRunning_ = true;
                     }
                 }
@@ -419,7 +441,9 @@
             if (it->getGametype() == this)
             {
-                delete (*(it++));
+                (it++)->destroy();
                 ++i;
             }
+            else
+                ++it;
         }
     }
Index: /code/trunk/src/orxonox/gametypes/Gametype.h
===================================================================
--- /code/trunk/src/orxonox/gametypes/Gametype.h	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/Gametype.h	(revision 5929)
@@ -37,5 +37,5 @@
 
 #include "core/BaseObject.h"
-#include "core/Identifier.h"
+#include "core/SubclassIdentifier.h"
 #include "tools/interfaces/Tickable.h"
 #include "infos/GametypeInfo.h"
@@ -68,5 +68,5 @@
         public:
             Gametype(BaseObject* creator);
-            virtual ~Gametype() {}
+            virtual ~Gametype();
 
             void setConfigValues();
@@ -75,10 +75,10 @@
 
             inline const GametypeInfo* getGametypeInfo() const
-                { return &this->gtinfo_; }
+                { return this->gtinfo_; }
 
             inline bool hasStarted() const
-                { return this->gtinfo_.bStarted_; }
+                { return this->gtinfo_->bStarted_; }
             inline bool hasEnded() const
-                { return this->gtinfo_.bEnded_; }
+                { return this->gtinfo_->bEnded_; }
 
             virtual void start();
@@ -114,12 +114,12 @@
 
             inline bool isStartCountdownRunning() const
-                { return this->gtinfo_.bStartCountdownRunning_; }
+                { return this->gtinfo_->bStartCountdownRunning_; }
             inline float getStartCountdown() const
-                { return this->gtinfo_.startCountdown_; }
+                { return this->gtinfo_->startCountdown_; }
 
             inline void setHUDTemplate(const std::string& name)
-                { this->gtinfo_.hudtemplate_ = name; }
+                { this->gtinfo_->hudtemplate_ = name; }
             inline const std::string& getHUDTemplate() const
-                { return this->gtinfo_.hudtemplate_; }
+                { return this->gtinfo_->hudtemplate_; }
 
             void addBots(unsigned int amount);
@@ -163,5 +163,5 @@
             virtual void spawnDeadPlayersIfRequested();
 
-            GametypeInfo gtinfo_;
+            SmartPtr<GametypeInfo> gtinfo_;
 
             bool bAutoStart_;
@@ -184,4 +184,9 @@
             // Config Values
             std::string scoreboardTemplate_;
+            
+            /* HACK HACK HACK */
+            ConsoleCommand* hackAddBots_;
+            ConsoleCommand* hackKillBots_;
+            /* HACK HACK HACK */
     };
 }
Index: /code/trunk/src/orxonox/gametypes/TeamBaseMatch.cc
===================================================================
--- /code/trunk/src/orxonox/gametypes/TeamBaseMatch.cc	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/TeamBaseMatch.cc	(revision 5929)
@@ -42,6 +42,6 @@
         RegisterObject(TeamBaseMatch);
 
-        this->scoreTimer_.setTimer(10, true, this, createExecutor(createFunctor(&TeamBaseMatch::winPoints)));
-        this->outputTimer_.setTimer(10, true, this, createExecutor(createFunctor(&TeamBaseMatch::showPoints)));
+        this->scoreTimer_.setTimer(10, true, createExecutor(createFunctor(&TeamBaseMatch::winPoints, this)));
+        this->outputTimer_.setTimer(10, true, createExecutor(createFunctor(&TeamBaseMatch::showPoints, this)));
 
         this->pointsTeam1_ = 0;
@@ -67,10 +67,10 @@
                 {
                     base->setState(BaseState::ControlTeam1);
-                    this->gtinfo_.sendAnnounceMessage("The red team captured a base");
+                    this->gtinfo_->sendAnnounceMessage("The red team captured a base");
                 }
                 if (teamnr == 1)
                 {
                     base->setState(BaseState::ControlTeam2);
-                    this->gtinfo_.sendAnnounceMessage("The blue team captured a base");
+                    this->gtinfo_->sendAnnounceMessage("The blue team captured a base");
                 }
             }
@@ -194,7 +194,7 @@
 
                 if (it->second == winningteam)
-                    this->gtinfo_.sendAnnounceMessage("You have won the match!", it->first->getClientID());
+                    this->gtinfo_->sendAnnounceMessage("You have won the match!", it->first->getClientID());
                 else
-                    this->gtinfo_.sendAnnounceMessage("You have lost the match!", it->first->getClientID());
+                    this->gtinfo_->sendAnnounceMessage("You have lost the match!", it->first->getClientID());
             }
 
Index: /code/trunk/src/orxonox/gametypes/TeamBaseMatch.h
===================================================================
--- /code/trunk/src/orxonox/gametypes/TeamBaseMatch.h	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/TeamBaseMatch.h	(revision 5929)
@@ -65,6 +65,6 @@
 
             std::set<TeamBaseMatchBase*> bases_;
-            Timer<TeamBaseMatch> scoreTimer_;
-            Timer<TeamBaseMatch> outputTimer_;
+            Timer scoreTimer_;
+            Timer outputTimer_;
 
             //points for each team
Index: /code/trunk/src/orxonox/gametypes/TeamDeathmatch.cc
===================================================================
--- /code/trunk/src/orxonox/gametypes/TeamDeathmatch.cc	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/TeamDeathmatch.cc	(revision 5929)
@@ -93,5 +93,5 @@
 
         if (valid_player)
-            this->players_.erase(player);
+            this->teamnumbers_.erase(player);
 
         return valid_player;
@@ -100,15 +100,15 @@
     bool TeamDeathmatch::allowPawnHit(Pawn* victim, Pawn* originator)
     {
-        return (!this->pawnsAreInTheSameTeam(victim, originator));
+        return (!this->pawnsAreInTheSameTeam(victim, originator) || !originator);
     }
 
     bool TeamDeathmatch::allowPawnDamage(Pawn* victim, Pawn* originator)
     {
-        return (!this->pawnsAreInTheSameTeam(victim, originator));
+        return (!this->pawnsAreInTheSameTeam(victim, originator) || !originator);
     }
 
     bool TeamDeathmatch::allowPawnDeath(Pawn* victim, Pawn* originator)
     {
-        return (!this->pawnsAreInTheSameTeam(victim, originator));
+        return (!this->pawnsAreInTheSameTeam(victim, originator) || !originator);
     }
 
Index: /code/trunk/src/orxonox/gametypes/UnderAttack.cc
===================================================================
--- /code/trunk/src/orxonox/gametypes/UnderAttack.cc	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/UnderAttack.cc	(revision 5929)
@@ -46,4 +46,5 @@
         this->teams_ = 2;
         this->destroyer_ = 0;
+        this->destroyer_.setCallback(createFunctor(&UnderAttack::killedDestroyer, this));
         this->gameEnded_ = false;
 
@@ -65,24 +66,21 @@
 
 
-    void UnderAttack::destroyedPawn(Pawn* pawn)
+    void UnderAttack::killedDestroyer()
     {
-        if (pawn == this->destroyer_)
+        this->end(); //end gametype
+        std::string message = "Ship destroyed! Team 0 has won!";
+        COUT(0) << message << std::endl;
+        Host::Broadcast(message);
+        this->gameEnded_ = true;
+
+        for (std::map<PlayerInfo*, int>::iterator it = this->teamnumbers_.begin(); it != this->teamnumbers_.end(); ++it)
         {
-            this->end(); //end gametype
-            std::string message = "Ship destroyed! Team 0 has won!";
-            COUT(0) << message << std::endl;
-            Host::Broadcast(message);
-            this->gameEnded_ = true;
+            if (it->first->getClientID() == CLIENTID_UNKNOWN)
+                continue;
 
-            for (std::map<PlayerInfo*, int>::iterator it = this->teamnumbers_.begin(); it != this->teamnumbers_.end(); ++it)
-            {
-                if (it->first->getClientID() == CLIENTID_UNKNOWN)
-                    continue;
-
-                if (it->second == 0)
-                    this->gtinfo_.sendAnnounceMessage("You have won the match!", it->first->getClientID());
-                else
-                    this->gtinfo_.sendAnnounceMessage("You have lost the match!", it->first->getClientID());
-            }
+            if (it->second == 0)
+                this->gtinfo_->sendAnnounceMessage("You have won the match!", it->first->getClientID());
+            else
+                this->gtinfo_->sendAnnounceMessage("You have lost the match!", it->first->getClientID());
         }
     }
@@ -164,7 +162,7 @@
 
                     if (it->second == 1)
-                        this->gtinfo_.sendAnnounceMessage("You have won the match!", it->first->getClientID());
+                        this->gtinfo_->sendAnnounceMessage("You have won the match!", it->first->getClientID());
                     else
-                        this->gtinfo_.sendAnnounceMessage("You have lost the match!", it->first->getClientID());
+                        this->gtinfo_->sendAnnounceMessage("You have lost the match!", it->first->getClientID());
                 }
             }
@@ -178,5 +176,5 @@
                 Host::Broadcast(message);
 */
-                this->gtinfo_.sendAnnounceMessage(message);
+                this->gtinfo_->sendAnnounceMessage(message);
 
                 if (timesequence_ >= 30 && timesequence_ <= 60)
Index: /code/trunk/src/orxonox/gametypes/UnderAttack.h
===================================================================
--- /code/trunk/src/orxonox/gametypes/UnderAttack.h	(revision 5928)
+++ /code/trunk/src/orxonox/gametypes/UnderAttack.h	(revision 5929)
@@ -32,10 +32,9 @@
 #include "OrxonoxPrereqs.h"
 
-#include "interfaces/PawnListener.h"
 #include "TeamDeathmatch.h"
 
 namespace orxonox
 {
-    class _OrxonoxExport UnderAttack : public TeamDeathmatch, public PawnListener
+    class _OrxonoxExport UnderAttack : public TeamDeathmatch
     {
         public:
@@ -54,7 +53,7 @@
 
         protected:
-            virtual void destroyedPawn(Pawn* pawn);
+            virtual void killedDestroyer();
 
-            Destroyer* destroyer_;
+            WeakPtr<Destroyer> destroyer_;
             unsigned int teams_;
             float gameTime_;
Index: /code/trunk/src/orxonox/graphics/CMakeLists.txt
===================================================================
--- /code/trunk/src/orxonox/graphics/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/CMakeLists.txt	(revision 5929)
@@ -1,12 +1,14 @@
 ADD_SOURCE_FILES(ORXONOX_SRC_FILES
-  Backlight.cc
   Billboard.cc
   BlinkingBillboard.cc
-  Camera.cc
   FadingBillboard.cc
   GlobalShader.cc
-  Light.cc
   Model.cc
   ParticleEmitter.cc
   ParticleSpawner.cc
+COMPILATION_BEGIN GraphicsCompilation.cc
+  Backlight.cc
+  Camera.cc
+  Light.cc
+COMPILATION_END
 )
Index: /code/trunk/src/orxonox/graphics/Camera.cc
===================================================================
--- /code/trunk/src/orxonox/graphics/Camera.cc	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/Camera.cc	(revision 5929)
@@ -38,4 +38,6 @@
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
+#include "core/GameMode.h"
+#include "core/GUIManager.h"
 #include "Scene.h"
 #include "CameraManager.h"
@@ -49,4 +51,6 @@
         RegisterObject(Camera);
 
+        if (!GameMode::showsGraphics())
+            ThrowException(AbortLoading, "Can't create Camera, no graphics.");
         if (!this->getScene())
             ThrowException(AbortLoading, "Can't create Camera, no scene.");
@@ -65,5 +69,5 @@
         this->nearClipDistance_ = 1;
 
-        this->setObjectMode(0x0);
+        this->setSyncMode(0x0);
 
         this->setConfigValues();
@@ -75,4 +79,6 @@
         if (this->isInitialized())
         {
+            if (GUIManager::getInstance().getCamera() == this->camera_)
+                GUIManager::getInstance().setCamera(NULL);
             this->releaseFocus();
 
Index: /code/trunk/src/orxonox/graphics/FadingBillboard.cc
===================================================================
--- /code/trunk/src/orxonox/graphics/FadingBillboard.cc	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/FadingBillboard.cc	(revision 5929)
@@ -103,5 +103,5 @@
         {
             this->changedirection_ = 1;
-            this->turnonofftimer_.setTimer(this->turnontime_, false, this, createExecutor(createFunctor(&FadingBillboard::stopturnonoff)));
+            this->turnonofftimer_.setTimer(this->turnontime_, false, createExecutor(createFunctor(&FadingBillboard::stopturnonoff, this)));
 
             if (this->isVisible())
@@ -111,5 +111,5 @@
         {
             this->changedirection_ = -1;
-            this->turnonofftimer_.setTimer(this->turnofftime_, false, this, createExecutor(createFunctor(&FadingBillboard::stopturnonoff)));
+            this->turnonofftimer_.setTimer(this->turnofftime_, false, createExecutor(createFunctor(&FadingBillboard::stopturnonoff, this)));
         }
     }
@@ -126,5 +126,5 @@
             this->fadedColour_ = ColourValue::ZERO;
             this->getBillboardSet().setColour(this->fadedColour_);
-            this->turnonofftimer_.setTimer(this->postprocessingtime_, false, this, createExecutor(createFunctor(&FadingBillboard::poststopturnonoff)));
+            this->turnonofftimer_.setTimer(this->postprocessingtime_, false, createExecutor(createFunctor(&FadingBillboard::poststopturnonoff, this)));
         }
         this->changedirection_ = 0;
Index: /code/trunk/src/orxonox/graphics/FadingBillboard.h
===================================================================
--- /code/trunk/src/orxonox/graphics/FadingBillboard.h	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/FadingBillboard.h	(revision 5929)
@@ -74,5 +74,5 @@
             float turnofftime_;
             float postprocessingtime_;
-            Timer<FadingBillboard> turnonofftimer_;
+            Timer turnonofftimer_;
             char changedirection_;
             ColourValue fadedColour_;
Index: /code/trunk/src/orxonox/graphics/ParticleEmitter.cc
===================================================================
--- /code/trunk/src/orxonox/graphics/ParticleEmitter.cc	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/ParticleEmitter.cc	(revision 5929)
@@ -63,5 +63,5 @@
         {
             this->detachOgreObject(this->particles_->getParticleSystem());
-            delete this->particles_;
+            this->particles_->destroy();
         }
     }
@@ -101,5 +101,5 @@
         if (this->particles_)
         {
-            delete this->particles_;
+            this->particles_->destroy();
             this->particles_ = 0;
         }
Index: /code/trunk/src/orxonox/graphics/ParticleSpawner.cc
===================================================================
--- /code/trunk/src/orxonox/graphics/ParticleSpawner.cc	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/ParticleSpawner.cc	(revision 5929)
@@ -71,9 +71,9 @@
     }
 
-    void ParticleSpawner::processEvent(Event& event)
+    void ParticleSpawner::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
     {
-        SUPER(ParticleSpawner, processEvent, event);
+        SUPER(ParticleSpawner, XMLEventPort, xmlelement, mode);
 
-        ORXONOX_SET_EVENT(ParticleSpawner, "spawn", spawn, event);
+        XMLPortEventState(ParticleSpawner, BaseObject, "spawn", spawn, xmlelement, mode);
     }
 
@@ -88,13 +88,13 @@
     void ParticleSpawner::startParticleSpawner()
     {
-        if (!this->particles_)
-            return;
-
         this->setActive(false);
 
         if (this->bForceDestroy_ || this->bSuppressStart_)
+        {
+            this->timer_.stopTimer();
             return;
+        }
 
-        this->timer_.setTimer(this->startdelay_, false, this, createExecutor(createFunctor(&ParticleSpawner::fireParticleSpawner)));
+        this->timer_.setTimer(this->startdelay_, false, createExecutor(createFunctor(&ParticleSpawner::fireParticleSpawner, this)));
     }
 
@@ -103,5 +103,5 @@
         this->setActive(true);
         if (this->lifetime_ != 0)
-            this->timer_.setTimer(this->lifetime_, false, this, createExecutor(createFunctor(&ParticleSpawner::stopParticleSpawner)));
+            this->timer_.setTimer(this->lifetime_, false, createExecutor(createFunctor(&ParticleSpawner::stopParticleSpawner, this)));
     }
 
@@ -116,9 +116,9 @@
 
             if (!this->timer_.isActive() || this->timer_.getRemainingTime() > this->destroydelay_)
-                this->timer_.setTimer(this->destroydelay_, false, this, createExecutor(createFunctor(&ParticleSpawner::destroyParticleSpawner)));
+                this->timer_.setTimer(this->destroydelay_, false, createExecutor(createFunctor(&ParticleSpawner::destroyParticleSpawner, this)));
         }
         else if (this->bLoop_)
         {
-            this->timer_.setTimer(this->destroydelay_, false, this, createExecutor(createFunctor(&ParticleSpawner::startParticleSpawner)));
+            this->timer_.setTimer(this->destroydelay_, false, createExecutor(createFunctor(&ParticleSpawner::startParticleSpawner, this)));
         }
     }
@@ -126,5 +126,5 @@
     void ParticleSpawner::destroyParticleSpawner()
     {
-        delete this;
+        this->destroy();
     }
 }
Index: /code/trunk/src/orxonox/graphics/ParticleSpawner.h
===================================================================
--- /code/trunk/src/orxonox/graphics/ParticleSpawner.h	(revision 5928)
+++ /code/trunk/src/orxonox/graphics/ParticleSpawner.h	(revision 5929)
@@ -44,8 +44,8 @@
 
             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
-            virtual void processEvent(Event& event);
+            virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
 
-            inline void destroy()
-                { this->bForceDestroy_ = true; this->stopParticleSpawner(); }
+            inline void stop(bool bDestroy)
+                { this->bForceDestroy_ = bDestroy; this->stopParticleSpawner(); }
             inline void spawn()
                 { this->bSuppressStart_ = false; this->startParticleSpawner(); }
@@ -89,5 +89,5 @@
             void destroyParticleSpawner();
 
-            Timer<ParticleSpawner> timer_;
+            Timer timer_;
 
             bool  bSuppressStart_;
Index: /code/trunk/src/orxonox/infos/HumanPlayer.cc
===================================================================
--- /code/trunk/src/orxonox/infos/HumanPlayer.cc	(revision 5928)
+++ /code/trunk/src/orxonox/infos/HumanPlayer.cc	(revision 5929)
@@ -64,8 +64,8 @@
         {
             if (this->humanHud_)
-                delete this->humanHud_;
+                this->humanHud_->destroy();
 
             if (this->gametypeHud_)
-                delete this->gametypeHud_;
+                this->gametypeHud_->destroy();
         }
     }
@@ -116,5 +116,5 @@
 
             if (!GameMode::isMaster())
-                this->setObjectMode(ObjectDirection::Bidirectional);
+                this->setSyncMode(ObjectDirection::Bidirectional);
             else
                 this->setName(this->nick_);
@@ -162,6 +162,10 @@
 
         if (this->isInitialized() && this->isLocalPlayer())
-            if (this->getGametype()->getHUDTemplate() != "")
+        {
+            if (this->getGametype() && this->getGametype()->getHUDTemplate() != "")
                 this->setGametypeHUDTemplate(this->getGametype()->getHUDTemplate());
+            else
+                this->setGametypeHUDTemplate("");
+        }
     }
 
@@ -170,9 +174,9 @@
         if (this->humanHud_)
         {
-            delete this->humanHud_;
+            this->humanHud_->destroy();
             this->humanHud_ = 0;
         }
 
-        if (this->isLocalPlayer() && this->humanHudTemplate_ != "")
+        if (this->isLocalPlayer() && this->humanHudTemplate_ != "" && GameMode::showsGraphics())
         {
             this->humanHud_ = new OverlayGroup(this);
@@ -186,5 +190,5 @@
         if (this->gametypeHud_)
         {
-            delete this->gametypeHud_;
+            this->gametypeHud_->destroy();
             this->gametypeHud_ = 0;
         }
Index: /code/trunk/src/orxonox/infos/PlayerInfo.cc
===================================================================
--- /code/trunk/src/orxonox/infos/PlayerInfo.cc	(revision 5928)
+++ /code/trunk/src/orxonox/infos/PlayerInfo.cc	(revision 5929)
@@ -35,4 +35,5 @@
 #include "gametypes/Gametype.h"
 #include "worldentities/ControllableEntity.h"
+#include "controllers/Controller.h"
 
 namespace orxonox
@@ -66,5 +67,5 @@
             if (this->controller_)
             {
-                delete this->controller_;
+                this->controller_->destroy();
                 this->controller_ = 0;
             }
@@ -131,5 +132,5 @@
         if (this->controller_)
         {
-            delete this->controller_;
+            this->controller_->destroy();
             this->controller_ = 0;
         }
Index: /code/trunk/src/orxonox/infos/PlayerInfo.h
===================================================================
--- /code/trunk/src/orxonox/infos/PlayerInfo.h	(revision 5928)
+++ /code/trunk/src/orxonox/infos/PlayerInfo.h	(revision 5929)
@@ -33,6 +33,5 @@
 
 #include "Info.h"
-#include "core/Identifier.h"
-#include "controllers/Controller.h"
+#include "core/SubclassIdentifier.h"
 
 namespace orxonox
Index: /code/trunk/src/orxonox/interfaces/InterfaceCompilation.cc
===================================================================
--- /code/trunk/src/orxonox/interfaces/InterfaceCompilation.cc	(revision 5928)
+++ /code/trunk/src/orxonox/interfaces/InterfaceCompilation.cc	(revision 5929)
@@ -34,5 +34,4 @@
 
 #include "GametypeMessageListener.h"
-#include "PawnListener.h"
 #include "PlayerTrigger.h"
 #include "RadarListener.h"
@@ -51,15 +50,4 @@
     {
         RegisterRootObject(GametypeMessageListener);
-    }
-
-    //----------------------------
-    // PawnListener
-    //----------------------------
-    /**
-        @brief Constructor for the PawnListener.
-    */
-    PawnListener::PawnListener()
-    {
-        RegisterRootObject(PawnListener);
     }
 
Index: /code/trunk/src/orxonox/interfaces/NotificationListener.h
===================================================================
--- /code/trunk/src/orxonox/interfaces/NotificationListener.h	(revision 5928)
+++ /code/trunk/src/orxonox/interfaces/NotificationListener.h	(revision 5929)
@@ -45,4 +45,6 @@
 namespace orxonox
 {
+    class Notification;
+
     class _OrxonoxExport NotificationListener : virtual public OrxonoxClass
     {
Index: de/trunk/src/orxonox/interfaces/PawnListener.h
===================================================================
--- /code/trunk/src/orxonox/interfaces/PawnListener.h	(revision 5928)
+++ 	(revision )
@@ -1,47 +1,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 _PawnListener_H__
-#define _PawnListener_H__
-
-#include "OrxonoxPrereqs.h"
-#include "core/OrxonoxClass.h"
-
-namespace orxonox
-{
-    class _OrxonoxExport PawnListener : virtual public OrxonoxClass
-    {
-        public:
-            PawnListener();
-            virtual ~PawnListener() {}
-
-            virtual void destroyedPawn(Pawn* pawn) = 0;
-    };
-}
-
-#endif /* _PawnListener_H__ */
Index: /code/trunk/src/orxonox/interfaces/RadarViewable.cc
===================================================================
--- /code/trunk/src/orxonox/interfaces/RadarViewable.cc	(revision 5928)
+++ /code/trunk/src/orxonox/interfaces/RadarViewable.cc	(revision 5929)
@@ -38,4 +38,5 @@
 #include "worldentities/WorldEntity.h"
 #include "Radar.h"
+#include "Scene.h"
 #include "overlays/Map.h"
 
@@ -135,5 +136,5 @@
     void RadarViewable::setRadarObjectDescription(const std::string& str)
     {
-        Radar* radar = Radar::getInstancePtr();
+        Radar* radar = this->getWorldEntity()->getScene()->getRadar();
         if (radar)
             this->radarObjectShape_ = radar->addObjectDescription(str);
Index: /code/trunk/src/orxonox/items/Engine.cc
===================================================================
--- /code/trunk/src/orxonox/items/Engine.cc	(revision 5928)
+++ /code/trunk/src/orxonox/items/Engine.cc	(revision 5929)
@@ -37,5 +37,4 @@
 #include "pickup/ModifierType.h"
 #include "tools/Shader.h"
-#include "sound/SoundBase.h"
 
 namespace orxonox
@@ -68,6 +67,4 @@
         this->setConfigValues();
         this->registerVariables();
-
-        this->sound_ = NULL;
     }
 
@@ -79,8 +76,5 @@
 
             if (this->boostBlur_)
-                delete this->boostBlur_;
-
-            if(this->sound_ != NULL)
-                delete this->sound_;
+                this->boostBlur_->destroy();
         }
     }
@@ -102,6 +96,4 @@
         XMLPortParam(Engine, "accelerationleftright", setAccelerationLeftRight, setAccelerationLeftRight, xmlelement, mode);
         XMLPortParam(Engine, "accelerationupdown",    setAccelerationUpDown,    setAccelerationUpDown,    xmlelement, mode);
-
-        XMLPortParamLoadOnly(Engine, "sound", loadSound, xmlelement, mode);
     }
 
@@ -237,10 +229,7 @@
             if (this->boostBlur_)
             {
-                delete this->boostBlur_;
+                this->boostBlur_->destroy();
                 this->boostBlur_ = 0;
             }
-
-            if(this->sound_ != NULL)
-                this->sound_->attachToEntity(ship);
         }
     }
@@ -253,18 +242,3 @@
             return Vector3::ZERO;
     }
-
-    void Engine::loadSound(const std::string filename)
-    {
-        if(filename == "") return;
-        else
-        {
-            if(this->sound_ == NULL)
-            {
-                this->sound_ = new SoundBase(this->ship_);
-            }
-
-            this->sound_->loadFile(filename);
-            this->sound_->play(true);
-        }
-    }
 }
Index: /code/trunk/src/orxonox/items/Engine.h
===================================================================
--- /code/trunk/src/orxonox/items/Engine.h	(revision 5928)
+++ /code/trunk/src/orxonox/items/Engine.h	(revision 5929)
@@ -130,6 +130,4 @@
             Shader* boostBlur_;
             float blurStrength_;
-
-            SoundBase* sound_;
     };
 }
Index: /code/trunk/src/orxonox/items/MultiStateEngine.cc
===================================================================
--- /code/trunk/src/orxonox/items/MultiStateEngine.cc	(revision 5928)
+++ /code/trunk/src/orxonox/items/MultiStateEngine.cc	(revision 5929)
@@ -60,11 +60,11 @@
             // We have no ship, so the effects are not attached and won't be destroyed automatically
             for (std::list<WorldEntity*>::const_iterator it = this->activeEffects_.begin(); it != this->activeEffects_.end(); ++it)
-                delete (*it);
+                (*it)->destroy();
             for (std::list<WorldEntity*>::const_iterator it = this->forwardEffects_.begin(); it != this->forwardEffects_.end(); ++it)
-                delete (*it);
+                (*it)->destroy();
             for (std::list<WorldEntity*>::const_iterator it = this->boostEffects_.begin(); it != this->boostEffects_.end(); ++it)
-                delete (*it);
+                (*it)->destroy();
             for (std::list<WorldEntity*>::const_iterator it = this->brakeEffects_.begin(); it != this->brakeEffects_.end(); ++it)
-                delete (*it);
+                (*it)->destroy();
         }
     }
@@ -91,5 +91,5 @@
             if (this->getShip()->hasLocalController())
             {
-                this->setObjectMode(ObjectDirection::Bidirectional);
+                this->setSyncMode(ObjectDirection::Bidirectional);
 
                 const Vector3& direction = this->getDirection();
Index: /code/trunk/src/orxonox/overlays/CMakeLists.txt
===================================================================
--- /code/trunk/src/orxonox/overlays/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/CMakeLists.txt	(revision 5929)
@@ -3,5 +3,7 @@
   OverlayGroup.cc
 
+COMPILATION_BEGIN OverlayCompilation.cc
   InGameConsole.cc
   Map.cc
+COMPILATION_END
 )
Index: /code/trunk/src/orxonox/overlays/InGameConsole.cc
===================================================================
--- /code/trunk/src/orxonox/overlays/InGameConsole.cc	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/InGameConsole.cc	(revision 5929)
@@ -41,11 +41,12 @@
 #include <OgreFont.h>
 
+#include "util/Clock.h"
+#include "util/Convert.h"
 #include "util/Math.h"
-#include "util/Convert.h"
 #include "util/UTFStringConversions.h"
-#include "core/Clock.h"
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
 #include "core/ConsoleCommand.h"
+#include "core/ScopedSingletonManager.h"
 #include "core/input/InputManager.h"
 #include "core/input/InputState.h"
@@ -61,4 +62,5 @@
 
     InGameConsole* InGameConsole::singletonPtr_s = 0;
+    ManageScopedSingleton(InGameConsole, ScopeID::Graphics, false);
 
     /**
@@ -85,4 +87,5 @@
 
         this->setConfigValues();
+        this->initialise();
     }
 
Index: /code/trunk/src/orxonox/overlays/InGameConsole.h
===================================================================
--- /code/trunk/src/orxonox/overlays/InGameConsole.h	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/InGameConsole.h	(revision 5929)
@@ -50,5 +50,4 @@
 
         void initialise();
-        void destroy();
         void setConfigValues();
 
Index: /code/trunk/src/orxonox/overlays/Map.cc
===================================================================
--- /code/trunk/src/orxonox/overlays/Map.cc	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/Map.cc	(revision 5929)
@@ -290,5 +290,5 @@
        for(ObjectList<orxonox::RadarViewable>::iterator it = ObjectList<orxonox::RadarViewable>::begin();
             it!=ObjectList<orxonox::RadarViewable>::end();
-            it++)
+            ++it)
         {
             //COUT(0) << "Radar_Position: " << it->getRVWorldPosition() << std::endl;
@@ -392,5 +392,5 @@
         for(ObjectList<orxonox::Map>::iterator it = ObjectList<orxonox::Map>::begin();
             it!=ObjectList<orxonox::Map>::end();
-            it++)
+            ++it)
         {
         //Map * m = it->getMap();
Index: /code/trunk/src/orxonox/overlays/OrxonoxOverlay.h
===================================================================
--- /code/trunk/src/orxonox/overlays/OrxonoxOverlay.h	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/OrxonoxOverlay.h	(revision 5929)
@@ -213,6 +213,6 @@
   };
 
-  SUPER_FUNCTION(7, OrxonoxOverlay, changedOwner, false);
-  SUPER_FUNCTION(8, OrxonoxOverlay, changedOverlayGroup, false);
+  SUPER_FUNCTION(6, OrxonoxOverlay, changedOwner, false);
+  SUPER_FUNCTION(7, OrxonoxOverlay, changedOverlayGroup, false);
 }
 
Index: /code/trunk/src/orxonox/overlays/OverlayGroup.cc
===================================================================
--- /code/trunk/src/orxonox/overlays/OverlayGroup.cc	(revision 5928)
+++ /code/trunk/src/orxonox/overlays/OverlayGroup.cc	(revision 5929)
@@ -61,5 +61,5 @@
     {
         for (std::set<OrxonoxOverlay*>::iterator it = hudElements_.begin(); it != hudElements_.end(); ++it)
-            delete (*it);
+            (*it)->destroy();
     }
 
Index: /code/trunk/src/orxonox/pickup/DroppedItem.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/DroppedItem.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/DroppedItem.cc	(revision 5929)
@@ -56,5 +56,5 @@
         if (this->item_)
         {
-            for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); it++)
+            for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); ++it)
             {
                 Vector3 distance = it->getWorldPosition() - this->getWorldPosition();
@@ -69,5 +69,5 @@
         {
             COUT(3) << "DroppedItem '" << this->item_->getPickupIdentifier() << "' picked up." << std::endl;
-            delete this;
+            this->destroy();
         }
     }
@@ -76,6 +76,5 @@
         if (this->timeToLive_ > 0)
         {
-            ExecutorMember<DroppedItem>* exec = createExecutor(createFunctor(&DroppedItem::timerCallback));
-            this->timer_.setTimer(this->timeToLive_, false, this, exec, false);
+            this->timer_.setTimer(this->timeToLive_, false, createExecutor(createFunctor(&DroppedItem::timerCallback, this)), false);
         }
     }
@@ -85,8 +84,8 @@
         {
             COUT(3) << "Delete DroppedItem with '" << this->item_->getPickupIdentifier() << "'" << std::endl;
-            delete this->item_;
+            this->item_->destroy();
         }
 
-        delete this;
+        this->destroy();
     }
 
Index: /code/trunk/src/orxonox/pickup/DroppedItem.h
===================================================================
--- /code/trunk/src/orxonox/pickup/DroppedItem.h	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/DroppedItem.h	(revision 5929)
@@ -77,5 +77,5 @@
         BaseItem* item_;
 
-        Timer<DroppedItem> timer_;
+        Timer timer_;
     };
 }
Index: /code/trunk/src/orxonox/pickup/ModifierPickup.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/ModifierPickup.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/ModifierPickup.cc	(revision 5929)
@@ -101,7 +101,7 @@
             if (this->duration_ > 0.0f)
             {
-                ExecutorMember<ModifierPickup>* executor = createExecutor(createFunctor(&ModifierPickup::timerCallback));
+                Executor* executor = createExecutor(createFunctor(&ModifierPickup::timerCallback, this));
                 executor->setDefaultValues(pawn);
-                this->timer_.setTimer(this->duration_, false, this, executor);
+                this->timer_.setTimer(this->duration_, false, executor);
             }
 
@@ -139,5 +139,5 @@
                 this->timer_.stopTimer();
 
-            delete this;
+            this->destroy();
 
             return true;
Index: /code/trunk/src/orxonox/pickup/ModifierPickup.h
===================================================================
--- /code/trunk/src/orxonox/pickup/ModifierPickup.h	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/ModifierPickup.h	(revision 5929)
@@ -129,4 +129,5 @@
 
         void timerCallback(Pawn* pawn);     //!< Method called when the timer runs out.
+        
     private:
         float getAdditiveModifier(ModifierType::Value type) const;               //!< Get the additive modifier for a given ModifierType.
@@ -138,6 +139,6 @@
         std::map<ModifierType::Value, float> multiplicativeModifiers_;           //!< Map of multiplicative modifiers, indexed by ModifierType.
 
-        float duration_;                                                        //!< Duration of this pickup's effect (0 for unlimited).
-        Timer<ModifierPickup> timer_;                                           //!< Timer used if the pickup's effect has a time limit.
+        float duration_;                                                         //!< Duration of this pickup's effect (0 for unlimited).
+        Timer timer_;                                                            //!< Timer used if the pickup's effect has a time limit.
     };
 }
Index: /code/trunk/src/orxonox/pickup/PickupSpawner.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/PickupSpawner.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/PickupSpawner.cc	(revision 5929)
@@ -91,5 +91,5 @@
             asItem->addTemplate(this->itemTemplate_);
             PickupInventory::getImageForItem(asItem);
-            delete newObject;
+            newObject->destroy();
         }
 
@@ -127,5 +127,5 @@
         if (this->isActive())
         {
-            for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); it++)
+            for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it != ObjectList<Pawn>::end(); ++it)
             {
                 Vector3 distance = it->getWorldPosition() - this->getWorldPosition();
@@ -166,6 +166,5 @@
                     if (this->respawnTime_ > 0.0f)
                     {
-                        ExecutorMember<PickupSpawner>* executor = createExecutor(createFunctor(&PickupSpawner::respawnTimerCallback));
-                        this->respawnTimer_.setTimer(this->respawnTime_, false, this, executor);
+                        this->respawnTimer_.setTimer(this->respawnTime_, false, createExecutor(createFunctor(&PickupSpawner::respawnTimerCallback, this)));
 
                         this->setActive(false);
@@ -174,5 +173,5 @@
                 }
                 else
-                    delete newObject;
+                    newObject->destroy();
             }
         }
Index: /code/trunk/src/orxonox/pickup/PickupSpawner.h
===================================================================
--- /code/trunk/src/orxonox/pickup/PickupSpawner.h	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/PickupSpawner.h	(revision 5929)
@@ -114,5 +114,5 @@
 
         float respawnTime_;                     //!< Time after which this gets re-actived.
-        Timer<PickupSpawner> respawnTimer_;     //!< Timer used for re-activating.
+        Timer respawnTimer_;                    //!< Timer used for re-activating.
     };
 }
Index: /code/trunk/src/orxonox/pickup/items/HealthImmediate.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/items/HealthImmediate.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/items/HealthImmediate.cc	(revision 5929)
@@ -67,5 +67,5 @@
         {
             pawn->addHealth(this->recoveredHealth_);
-            delete this;
+            this->destroy();
         }
 
Index: /code/trunk/src/orxonox/pickup/items/HealthUsable.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/items/HealthUsable.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/items/HealthUsable.cc	(revision 5929)
@@ -82,5 +82,5 @@
 
             this->removeFrom(pawn);
-            delete this;
+            this->destroy();
         }
     }
Index: /code/trunk/src/orxonox/pickup/items/Jump.cc
===================================================================
--- /code/trunk/src/orxonox/pickup/items/Jump.cc	(revision 5928)
+++ /code/trunk/src/orxonox/pickup/items/Jump.cc	(revision 5929)
@@ -84,5 +84,5 @@
         {
             this->removeFrom(pawn);
-            delete this;
+            this->destroy();
         }
     }
Index: /code/trunk/src/orxonox/sound/AmbientSound.cc
===================================================================
--- /code/trunk/src/orxonox/sound/AmbientSound.cc	(revision 5929)
+++ /code/trunk/src/orxonox/sound/AmbientSound.cc	(revision 5929)
@@ -0,0 +1,62 @@
+/*
+ *   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 "AmbientSound.h"
+
+#include "core/CoreIncludes.h"
+#include "core/EventIncludes.h"
+#include "core/XMLPort.h"
+
+namespace orxonox
+{
+    CreateFactory(AmbientSound);
+
+    AmbientSound::AmbientSound(BaseObject* creator)
+        : BaseObject(creator)
+    {
+        RegisterObject(AmbientSound);
+    }
+
+    AmbientSound::~AmbientSound()
+    {
+    }
+
+    void AmbientSound::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(AmbientSound, XMLPort, xmlelement, mode);
+        XMLPortParamExtern(AmbientSound, BaseSound, this, "source", setSource, getSource, xmlelement, mode);
+        XMLPortParamExtern(AmbientSound, BaseSound, this, "loop", setLoop, getLoop, xmlelement, mode);
+        XMLPortParamExtern(AmbientSound, BaseSound, this, "playOnLoad", setPlayOnLoad, getPlayOnLoad, xmlelement, mode);
+    }
+
+    void AmbientSound::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(AmbientSound, XMLEventPort, xmlelement, mode);
+        XMLPortEventState(AmbientSound, BaseObject, "play", play, xmlelement, mode);
+    }
+}
Index: /code/trunk/src/orxonox/sound/AmbientSound.h
===================================================================
--- /code/trunk/src/orxonox/sound/AmbientSound.h	(revision 5929)
+++ /code/trunk/src/orxonox/sound/AmbientSound.h	(revision 5929)
@@ -0,0 +1,56 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+#ifndef _AmbientSound_H__
+#define _AmbientSound_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "core/BaseObject.h"
+#include "sound/BaseSound.h"
+
+namespace orxonox
+{
+    /**
+     * The AmbientSound class is the base class for all sound file loader classes.
+     * It server as main interface to the OpenAL library.
+     *
+     */
+    class _OrxonoxExport AmbientSound : public BaseSound, public BaseObject
+    {
+    public:
+        AmbientSound(BaseObject* creator);
+        virtual ~AmbientSound();
+
+        virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+        virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
+
+    private:
+    };
+}
+
+#endif /* _AmbientSound_H__ */
Index: /code/trunk/src/orxonox/sound/BaseSound.cc
===================================================================
--- /code/trunk/src/orxonox/sound/BaseSound.cc	(revision 5929)
+++ /code/trunk/src/orxonox/sound/BaseSound.cc	(revision 5929)
@@ -0,0 +1,262 @@
+/*
+ *   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:
+ *      Erwin 'vaiursch' Herrsche
+ *   Co-authors:
+ *      Reto Grieder
+ *
+ */
+
+#include "BaseSound.h"
+
+#include <vector>
+#include <AL/alut.h>
+#include <vorbis/vorbisfile.h>
+
+#include "core/CoreIncludes.h"
+#include "core/GameMode.h"
+#include "core/Resource.h"
+
+namespace orxonox
+{
+    BaseSound::BaseSound()
+        : audioSource_(0)
+        , audioBuffer_(0)
+        , bPlayOnLoad_(false)
+        , bLoop_(false)
+    {
+        RegisterRootObject(BaseSound);
+    }
+
+    BaseSound::~BaseSound()
+    {
+        this->setSource("");
+    }
+
+    void BaseSound::play()
+    {
+        if (alIsSource(this->audioSource_))
+        {
+            if (this->bLoop_)
+                alSourcei(this->audioSource_, AL_LOOPING, AL_TRUE);
+            else
+                alSourcei(this->audioSource_, AL_LOOPING, AL_FALSE);
+            alSourcePlay(this->audioSource_);
+
+            if (alGetError() != AL_NO_ERROR)
+            {
+                 COUT(2) << "Sound: OpenAL: Error playin sound " << this->audioSource_ << std::endl;
+            }
+        }
+    }
+
+    void BaseSound::stop()
+    {
+        if (alIsSource(this->audioSource_))
+            alSourceStop(this->audioSource_);
+    }
+
+    void BaseSound::pause()
+    {
+        if (alIsSource(this->audioSource_))
+            alSourcePause(this->audioSource_);
+    }
+
+    bool BaseSound::isPlaying()
+    {
+        if (alIsSource(this->audioSource_))
+            return getSourceState() == AL_PLAYING;
+        return false;
+    }
+
+    bool BaseSound::isPaused()
+    {
+        if (alIsSource(this->audioSource_))
+            return getSourceState() == AL_PAUSED;
+        return true;
+    }
+
+    bool BaseSound::isStopped()
+    {
+        if (alIsSource(this->audioSource_))
+            return getSourceState() == AL_INITIAL || getSourceState() == AL_STOPPED;
+        return true;
+    }
+
+    void BaseSound::setPlayOnLoad(bool val)
+    {
+        this->bPlayOnLoad_ = true;
+        this->play();
+    }
+
+    void BaseSound::setSource(const std::string& source)
+    {
+        this->source_ = source;
+        if (!GameMode::playsSound())
+            return;
+
+        if (source.empty() && alIsSource(this->audioSource_))
+        {
+            // Unload sound
+            alSourcei(this->audioSource_, AL_BUFFER, 0);
+            alDeleteSources(1, &this->audioSource_);
+            alDeleteBuffers(1, &this->audioBuffer_);
+            return;
+        }
+
+        COUT(3) << "Sound: OpenAL ALUT: loading file " << source << std::endl;
+        // Get DataStream from the resources
+        shared_ptr<ResourceInfo> fileInfo = Resource::getInfo(source);
+        if (fileInfo == NULL)
+        {
+            COUT(2) << "Warning: Sound file '" << source << "' not found" << std::endl;
+            return;
+        }
+        dataStream_ = Resource::open(source);
+        // Read everything into a temporary buffer
+        char* buffer = new char[fileInfo->size];
+        dataStream_->read(buffer, fileInfo->size);
+        dataStream_->seek(0);
+
+        this->audioBuffer_ = alutCreateBufferFromFileImage(buffer, fileInfo->size);
+        delete[] buffer;
+
+        if (this->audioBuffer_ == AL_NONE)
+        {
+            COUT(2) << "Sound: OpenAL ALUT: " << alutGetErrorString(alutGetError()) << std::endl;
+            if (source.find("ogg", 0) != std::string::npos)
+            {
+                COUT(2) << "Sound: Trying fallback ogg loader" << std::endl;
+                this->audioBuffer_ = loadOggFile();
+            }
+
+            if (this->audioBuffer_ == AL_NONE)
+            {
+                COUT(2) << "Sound: fallback ogg loader failed: " << alutGetErrorString(alutGetError()) << std::endl;
+                return;
+            }
+        }
+
+        alGenSources(1, &this->audioSource_);
+        alSourcei(this->audioSource_, AL_BUFFER, this->audioBuffer_);
+        if (alGetError() != AL_NO_ERROR)
+        {
+            COUT(2) << "Sound: OpenAL: Error loading sample file: " << source << std::endl;
+            return;
+        }
+
+        alSource3f(this->audioSource_, AL_POSITION,  0, 0, 0);
+
+        if (this->bPlayOnLoad_)
+            this->play();
+    }
+
+    ALint BaseSound::getSourceState()
+    {
+        ALint state;
+        alGetSourcei(this->audioSource_, AL_SOURCE_STATE, &state);
+        return state;
+    }
+
+    size_t readVorbis(void* ptr, size_t size, size_t nmemb, void* datasource)
+    {
+        return static_cast<Ogre::DataStream*>(datasource)->read(ptr, size * nmemb);
+    }
+
+    int seekVorbis(void* datasource, ogg_int64_t offset, int whence)
+    {
+        Ogre::DataStream* stream = static_cast<Ogre::DataStream*>(datasource);
+        int offset_beg = offset;
+        if (whence == SEEK_CUR)
+            offset_beg = stream->tell() + offset;
+        else if (whence == SEEK_END)
+            offset_beg = stream->size() + offset;
+        else if (whence != SEEK_SET)
+            return -1;
+        stream->seek(offset_beg);
+        return 0;
+    }
+
+    long tellVorbis(void* datasource)
+    {
+        return static_cast<long>(static_cast<Ogre::DataStream*>(datasource)->tell());
+    }
+
+    ALuint BaseSound::loadOggFile()
+    {
+        char inbuffer[4096];
+        std::vector<char> outbuffer;
+        OggVorbis_File vf;
+        vorbis_info* vorbisInfo;
+        int eof = false;
+        int current_section;
+        ALuint buffer;
+        ALenum format;
+
+        // Open file with custom streaming
+        ov_callbacks vorbisCallbacks;
+        vorbisCallbacks.read_func  = &readVorbis;
+        vorbisCallbacks.seek_func  = &seekVorbis;
+        vorbisCallbacks.tell_func  = &tellVorbis;
+        vorbisCallbacks.close_func = NULL;
+
+        int ret = ov_open_callbacks(dataStream_.get(), &vf, NULL, 0, vorbisCallbacks);
+        if (ret < 0)
+        {
+            COUT(2) << "Sound: libvorbisfile: File does not seem to be an Ogg Vorbis bitstream" << std::endl;
+            ov_clear(&vf);
+            return AL_NONE;
+        }
+
+        while (!eof)
+        {
+            long ret = ov_read(&vf, inbuffer, sizeof(inbuffer), 0, 2, 1, &current_section);
+            if (ret == 0)
+            {
+                eof = true;
+            }
+            else if (ret < 0)
+            {
+                COUT(2) << "Sound: libvorbisfile: error reading the file" << std::endl;
+                ov_clear(&vf);
+                return AL_NONE;
+            }
+            else
+            {
+                outbuffer.insert(outbuffer.end(), inbuffer, inbuffer + sizeof(inbuffer));
+            }
+        }
+
+        vorbisInfo = ov_info(&vf, -1);
+        if (vorbisInfo->channels == 1)
+            format = AL_FORMAT_MONO16;
+        else
+            format = AL_FORMAT_STEREO16;
+
+        alGenBuffers(1, &buffer);
+        alBufferData(buffer, format, &outbuffer[0], outbuffer.size(), vorbisInfo->rate);
+        ov_clear(&vf);
+
+        return buffer;
+    }
+
+} // namespace: orxonox
Index: /code/trunk/src/orxonox/sound/BaseSound.h
===================================================================
--- /code/trunk/src/orxonox/sound/BaseSound.h	(revision 5929)
+++ /code/trunk/src/orxonox/sound/BaseSound.h	(revision 5929)
@@ -0,0 +1,83 @@
+/*
+ *   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:
+ *      Erwin 'vaiursch' Herrsche
+ *   Co-authors:
+ *      Reto Grieder
+ *
+ */
+#ifndef _BaseSound_H__
+#define _BaseSound_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include <string>
+#include <OgreSharedPtr.h>
+#include <OgreDataStream.h>
+#include "core/OrxonoxClass.h"
+
+namespace orxonox
+{
+    /**
+     * The BaseSound class is the base class for all sound file loader classes.
+     * It server as main interface to the OpenAL library.
+     *
+     */
+    class _OrxonoxExport BaseSound : virtual public OrxonoxClass
+    {
+    public:
+        BaseSound();
+        virtual ~BaseSound();
+
+        void play();
+        void stop();
+        void pause();
+
+        bool isPlaying();
+        bool isPaused();
+        bool isStopped();
+
+        void setSource(const std::string& source);
+        const std::string& getSource() { return this->source_; }
+
+        bool getPlayOnLoad() { return this->bPlayOnLoad_; }
+        void setPlayOnLoad(bool val);
+
+        bool getLoop() { return this->bLoop_; }
+        void setLoop(bool val) { this->bLoop_ = val; }
+
+    protected:
+        ALuint loadOggFile();
+        ALint getSourceState();
+
+        ALuint audioSource_;
+        ALuint audioBuffer_;
+
+    private:
+        std::string source_;
+        bool bPlayOnLoad_;
+        bool bLoop_;
+        DataStreamPtr dataStream_;
+    };
+}
+
+#endif /* _BaseSound_H__ */
Index: /code/trunk/src/orxonox/sound/CMakeLists.txt
===================================================================
--- /code/trunk/src/orxonox/sound/CMakeLists.txt	(revision 5928)
+++ /code/trunk/src/orxonox/sound/CMakeLists.txt	(revision 5929)
@@ -1,6 +1,7 @@
 ADD_SOURCE_FILES(ORXONOX_SRC_FILES
+    AmbientSound.cc
+    BaseSound.cc
     SoundManager.cc
-    SoundBase.cc
-    SoundMainMenu.cc
+    WorldSound.cc
 )
 
Index: de/trunk/src/orxonox/sound/SoundBase.cc
===================================================================
--- /code/trunk/src/orxonox/sound/SoundBase.cc	(revision 5928)
+++ 	(revision )
@@ -1,240 +1,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:
- *       Erwin 'vaiursch' Herrsche
- *   Co-authors:
- *      ...
- *
- */
-
-#include "SoundBase.h"
-
-#include <string>
-#include <vector>
-#include <AL/alut.h>
-#include <vorbis/vorbisfile.h>
-
-#include "util/Math.h"
-#include "core/Core.h"
-#include "core/Resource.h"
-#include "worldentities/WorldEntity.h"
-#include "SoundManager.h"
-
-namespace orxonox
-{
-    SoundBase::SoundBase(WorldEntity* entity)
-    {
-        this->source_ = 0;
-        this->buffer_ = 0;
-        this->entity_ = entity;
-
-        SoundManager::getInstance().addSound(this);
-    }
-
-    SoundBase::~SoundBase()
-    {
-        alSourcei(this->source_, AL_BUFFER, 0);
-        alDeleteSources(1, &this->source_);
-        alDeleteBuffers(1, &this->buffer_);
-    }
-
-    void SoundBase::attachToEntity(WorldEntity* entity)
-    {
-        this->entity_ = entity;
-        this->update();
-    }
-
-    void SoundBase::update() {
-        if(this->entity_ != NULL && alIsSource(this->source_)) {
-            const Vector3& pos = this->entity_->getPosition();
-            alSource3f(this->source_, AL_POSITION, pos.x, pos.y, pos.z);
-            ALenum error = alGetError();
-            if(error == AL_INVALID_VALUE)
-                COUT(2) << "Sound: OpenAL: Invalid sound position" << std::endl;
-
-            const Vector3& vel = this->entity_->getVelocity();
-            alSource3f(this->source_, AL_VELOCITY, vel.x, vel.y, vel.z);
-            error = alGetError();
-            if(error == AL_INVALID_VALUE)
-                COUT(2) << "Sound: OpenAL: Invalid sound velocity" << std::endl;
-
-            const Quaternion& orient = this->entity_->getOrientation();
-            Vector3 at = orient.zAxis();
-            alSource3f(this->source_, AL_DIRECTION, at.x, at.y, at.z);
-            error = alGetError();
-            if(error == AL_INVALID_VALUE)
-                COUT(2) << "Sound: OpenAL: Invalid sound direction" << std::endl;
-        }
-    }
-
-    void SoundBase::play(bool loop) {
-        if(alIsSource(this->source_)) {
-            if(loop)
-                alSourcei(this->source_, AL_LOOPING, AL_TRUE);
-            else
-                alSourcei(this->source_, AL_LOOPING, AL_FALSE);
-            alSourcePlay(this->source_);
-
-            if(alGetError() != AL_NO_ERROR)
-            {
-                 COUT(2) << "Sound: OpenAL: Error playing sound " << this->source_ << std::endl;
-            }
-        }
-    }
-
-    void SoundBase::stop() {
-        if(alIsSource(this->source_)) {
-            alSourceStop(this->source_);
-        }
-    }
-
-    void SoundBase::pause() {
-        if(alIsSource(this->source_)) {
-            alSourcePause(this->source_);
-        }
-    }
-
-    bool SoundBase::isPlaying() {
-        if(alIsSource(this->source_)) {
-            return getSourceState() == AL_PLAYING;
-        }
-        return false;
-    }
-
-    bool SoundBase::isPaused() {
-        if(alIsSource(this->source_)) {
-            return getSourceState() == AL_PAUSED;
-        }
-        return true;
-    }
-
-    bool SoundBase::isStopped() {
-        if(alIsSource(this->source_)) {
-            return getSourceState() == AL_INITIAL || getSourceState() == AL_STOPPED;
-        }
-        return true;
-    }
-
-    bool SoundBase::loadFile(const std::string& filename) {
-        if(!SoundManager::getInstance().isSoundAvailable())
-        {
-            COUT(3) << "Sound: not available, skipping " << filename << std::endl;
-            return false;
-        }
-
-        COUT(3) << "Sound: OpenAL ALUT: loading file " << filename << std::endl;
-        // Get DataStream from the resources
-        shared_ptr<ResourceInfo> fileInfo = Resource::getInfo(filename);
-        if (fileInfo == NULL) {
-            COUT(2) << "Warning: Sound file '" << filename << "' not found" << std::endl;
-            return false;
-        }
-        DataStreamPtr stream = Resource::open(filename);
-        // Read everything into a temporary buffer
-        char* buffer = new char[fileInfo->size];
-        stream->read(buffer, fileInfo->size);
-
-        this->buffer_ = alutCreateBufferFromFileImage(buffer, fileInfo->size);
-        delete[] buffer;
-
-        if(this->buffer_ == AL_NONE) {
-            COUT(2) << "Sound: OpenAL ALUT: " << alutGetErrorString(alutGetError()) << std::endl;
-            if(filename.find("ogg", 0) != std::string::npos)
-            {
-                COUT(2) << "Sound: Trying fallback ogg loader" << std::endl;
-                this->buffer_ = loadOggFile(filename);
-            }
-
-            if(this->buffer_ == AL_NONE)
-            {
-                COUT(2) << "Sound: fallback ogg loader failed: " << alutGetErrorString(alutGetError()) << std::endl;
-                return false;
-            }
-        }
-
-        alGenSources(1, &this->source_);
-        alSourcei(this->source_, AL_BUFFER, this->buffer_);
-        if(alGetError() != AL_NO_ERROR) {
-            COUT(2) << "Sound: OpenAL: Error loading sample file: " << filename << std::endl;
-            return false;
-        }
-        return true;
-    }
-
-    ALint SoundBase::getSourceState() {
-        ALint state;
-        alGetSourcei(this->source_, AL_SOURCE_STATE, &state);
-        return state;
-    }
-
-    ALuint SoundBase::loadOggFile(const std::string& filename)
-    {
-        char inbuffer[4096];
-        std::vector<char> outbuffer;
-        OggVorbis_File vf;
-        vorbis_info* vorbisInfo;
-        int eof = false;
-        int current_section;
-        ALuint buffer;
-        ALenum format;
-
-        FILE* f = fopen(filename.c_str(), "rb");
-
-        if(ov_open(f, &vf, NULL, 0) < 0)
-        {
-            COUT(2) << "Sound: libvorbisfile: File does not seem to be an Ogg Vorbis bitstream" << std::endl;
-            ov_clear(&vf);
-            return AL_NONE;
-        }
-
-        while(!eof)
-        {
-            long ret = ov_read(&vf, inbuffer, sizeof(inbuffer), 0, 2, 1, &current_section);
-            if (ret == 0)
-            {
-                eof = true;
-            }
-            else if (ret < 0)
-            {
-                COUT(2) << "Sound: libvorbisfile: error reading the file" << std::endl;
-                ov_clear(&vf);
-                return AL_NONE;
-            }
-            else
-            {
-                outbuffer.insert(outbuffer.end(), inbuffer, inbuffer + sizeof(inbuffer));
-            }
-        }
-
-        vorbisInfo = ov_info(&vf, -1);
-        if(vorbisInfo->channels == 1)
-            format = AL_FORMAT_MONO16;
-        else
-            format = AL_FORMAT_STEREO16;
-
-        alGenBuffers(1, &buffer);
-        alBufferData(buffer, format, &outbuffer[0], outbuffer.size(), vorbisInfo->rate);
-        ov_clear(&vf);
-
-        return buffer;
-    }
-} // namespace: orxonox
Index: de/trunk/src/orxonox/sound/SoundBase.h
===================================================================
--- /code/trunk/src/orxonox/sound/SoundBase.h	(revision 5928)
+++ 	(revision )
@@ -1,69 +1,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:
- *       Erwin 'vaiursch' Herrsche
- *   Co-authors:
- *      ...
- *
- */
-#ifndef _SoundBase_H__
-#define _SoundBase_H__
-
-#include "OrxonoxPrereqs.h"
-#include <cstring> // define NULL
-
-namespace orxonox
-{
-    /**
-     * The SoundBase class is the base class for all sound file loader classes.
-     * It server as main interface to the OpenAL library.
-     *
-     */
-    class _OrxonoxExport SoundBase
-    {
-    public:
-        SoundBase(WorldEntity* entity = NULL);
-        ~SoundBase();
-
-        void attachToEntity(WorldEntity* entity);
-        void update();
-        void play(bool loop = false);
-        void stop();
-        void pause();
-
-        bool isPlaying();
-        bool isPaused();
-        bool isStopped();
-
-        bool loadFile(const std::string& filename);
-
-    private:
-        ALuint loadOggFile(const std::string& filename);
-        ALuint source_;
-        ALuint buffer_;
-        WorldEntity* entity_;
-
-        ALint getSourceState();
-    }; // class SoundBase
-} // namepsace orxonox
-
-#endif /* _SoundBase_H__ */
Index: de/trunk/src/orxonox/sound/SoundMainMenu.cc
===================================================================
--- /code/trunk/src/orxonox/sound/SoundMainMenu.cc	(revision 5928)
+++ 	(revision )
@@ -1,47 +1,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:
- *       Erwin 'vaiursch' Herrsche
- *   Co-authors:
- *      ...
- *
- */
-
-#include "SoundMainMenu.h"
-
-#include "core/CoreIncludes.h"
-#include "core/ConfigValueIncludes.h"
-
-namespace orxonox
-{
-    SoundMainMenu::SoundMainMenu()
-    {
-        RegisterObject(SoundMainMenu);
-        setConfigValues();
-        loadFile(this->filename_);
-    }
-
-    void SoundMainMenu::setConfigValues()
-    {
-        SetConfigValue(filename_, "ambient/mainmenu.wav");
-    }
-}
Index: de/trunk/src/orxonox/sound/SoundMainMenu.h
===================================================================
--- /code/trunk/src/orxonox/sound/SoundMainMenu.h	(revision 5928)
+++ 	(revision )
@@ -1,51 +1,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:
- *       Erwin 'vaiursch' Herrsche
- *   Co-authors:
- *      ...
- *
- */
-
-#ifndef _SoundMainMenu_H__
-#define _SoundMainMenu_H__
-
-#include "OrxonoxPrereqs.h"
-
-#include <string>
-#include "core/OrxonoxClass.h"
-#include "SoundBase.h"
-
-namespace orxonox
-{
-    class _OrxonoxExport SoundMainMenu : public SoundBase, public virtual OrxonoxClass
-    {
-        public:
-            SoundMainMenu();
-            void setConfigValues();
-
-        private:
-            std::string filename_;
-    };
-}
-
-#endif /* _SoundMainMenu_H__ */
Index: /code/trunk/src/orxonox/sound/SoundManager.cc
===================================================================
--- /code/trunk/src/orxonox/sound/SoundManager.cc	(revision 5928)
+++ /code/trunk/src/orxonox/sound/SoundManager.cc	(revision 5929)
@@ -31,63 +31,60 @@
 #include <AL/alut.h>
 
+#include "util/Exception.h"
 #include "util/Math.h"
-#include "CameraManager.h"
-#include "graphics/Camera.h"
-#include "SoundBase.h"
+#include "util/ScopeGuard.h"
+#include "core/GameMode.h"
+#include "core/ScopedSingletonManager.h"
 
 namespace orxonox
 {
     SoundManager* SoundManager::singletonPtr_s = NULL;
+    ManageScopedSingleton(SoundManager, ScopeID::Graphics, true);
 
-    /**
-     * Default constructor
-     */
     SoundManager::SoundManager()
     {
-        this->device_ = NULL;
-        this->soundavailable_ = true;
-        if(!alutInitWithoutContext(NULL,NULL))
+        if (!alutInitWithoutContext(NULL,NULL))
+            ThrowException(InitialisationFailed, "OpenAL ALUT error: " << alutGetErrorString(alutGetError()));
+        Loki::ScopeGuard alutExitGuard = Loki::MakeGuard(&alutExit);
+
+        COUT(3) << "OpenAL: Opening sound device..." << std::endl;
+        this->device_ = alcOpenDevice(NULL);
+        if (this->device_ == NULL)
         {
-            COUT(2) << "Sound: OpenAL ALUT: " << alutGetErrorString(alutGetError()) << std::endl;
-            this->soundavailable_ = false;
+            COUT(0) << "OpenaAL: Could not open sound device. Have you installed OpenAL?" << std::endl;
+#ifdef ORXONOX_PLATFORM_WINDOWS
+            COUT(0) << "Just getting the DLL with the dependencies is not enough for Windows (esp. Windows 7)!" << std::endl;
+#endif
+            ThrowException(InitialisationFailed, "OpenAL error: Could not open sound device.");
         }
+        Loki::ScopeGuard closeDeviceGuard = Loki::MakeGuard(&alcCloseDevice, this->device_);
+
+        COUT(3) << "OpenAL: Sound device opened" << std::endl;
+        this->context_ = alcCreateContext(this->device_, NULL);
+        if (this->context_ == NULL)
+            ThrowException(InitialisationFailed, "OpenAL error: Could not create sound context");
+        Loki::ScopeGuard desroyContextGuard = Loki::MakeGuard(&alcDestroyContext, this->context_);
+
+        if (alcMakeContextCurrent(this->context_) == AL_TRUE)
+            COUT(3) << "OpenAL: Context " << this->context_ << " loaded" << std::endl;
+
+        COUT(4) << "Sound: OpenAL ALUT version: " << alutGetMajorVersion() << "." << alutGetMinorVersion() << std::endl;
+
+        const char* str = alutGetMIMETypes(ALUT_LOADER_BUFFER);
+        if (str == NULL)
+            COUT(2) << "OpenAL ALUT error: " << alutGetErrorString(alutGetError()) << std::endl;
         else
-        {
-            assert(this->device_ == NULL);
-            COUT(3) << "Sound: OpenAL: Open sound device..." << std::endl;
-            this->device_ = alcOpenDevice(NULL);
+            COUT(4) << "OpenAL ALUT supported MIME types: " << str << std::endl;
 
-            if(this->device_ == NULL)
-            {
-                COUT(2) << "Sound: OpenAL: Could not open sound device" << std::endl;
-                this->soundavailable_ = false;
-            }
-            else
-            {
-                COUT(3) << "Sound: OpenAL: Sound device opened" << std::endl;
-                this->context_ = alcCreateContext(this->device_, NULL);
-                if(this->context_ == NULL)
-                {
-                    COUT(2) << "Sound: OpenAL: Could not create sound context" << std::endl;
-                    this->soundavailable_ = false;
-                }
-                else
-                {
-                    if(alcMakeContextCurrent(this->context_) == AL_TRUE)
-                        COUT(3) << "Sound: OpenAL: Context " << this->context_ << " loaded" << std::endl;
-
-                    COUT(4) << "Sound: OpenAL ALUT version: " << alutGetMajorVersion() << "." << alutGetMinorVersion() << std::endl;
-                    const char* str = alutGetMIMETypes(ALUT_LOADER_BUFFER);
-                    if (str == NULL)
-                        COUT(2) << "Sound: OpenAL ALUT: " << alutGetErrorString(alutGetError()) << std::endl;
-                    else
-                        COUT(4) << "Sound: OpenAL ALUT supported MIME types: " << str << std::endl;
-                }
-            }
-        }
+        GameMode::setPlaysSound(true);
+        // Disarm guards
+        alutExitGuard.Dismiss();
+        closeDeviceGuard.Dismiss();
+        desroyContextGuard.Dismiss();
     }
 
     SoundManager::~SoundManager()
     {
+        GameMode::setPlaysSound(false);
         alcDestroyContext(this->context_);
         alcCloseDevice(this->device_);
@@ -95,74 +92,25 @@
     }
 
-    /**
-     * Add a SoundBase object to the list. Every SoundBase object should be in
-     * this list.
-     *
-     * @param sound Pointer to the SoundBase object to add
-     */
-    void SoundManager::addSound(SoundBase* sound)
+    void SoundManager::setListenerPosition(const Vector3& position)
     {
-        this->soundlist_.push_back(sound);
+        alListener3f(AL_POSITION, position.x, position.y, position.z);
+        ALenum error = alGetError();
+        if (error == AL_INVALID_VALUE)
+            COUT(2) << "Sound: OpenAL: Invalid listener position" << std::endl;
     }
 
-    /**
-     * Remove a SoundBase object from the list and destroy it.
-     */
-    void SoundManager::removeSound(SoundBase* sound)
+    void SoundManager::setListenerOrientation(const Quaternion& orientation)
     {
-        std::list<SoundBase*>::iterator pos = this->soundlist_.end();
-        for(std::list<SoundBase*>::iterator i = this->soundlist_.begin(); i != this->soundlist_.end(); i++)
-        {
-            if((*i) == sound)
-                pos = i;
-        }
+        // update listener orientation
+        Vector3 up = orientation.xAxis(); // just a wild guess
+        Vector3 at = orientation.zAxis();
 
-        delete (*pos);
-        this->soundlist_.erase(pos);
-    }
+        ALfloat orient[6] = { at.x, at.y, at.z,
+                              up.x, up.y, up.z };
 
-    /**
-     * Tick function, updates listener and registred SoundBase objects
-     *
-     * @param dt @see Orxonox::Tickable
-     */
-    void SoundManager::tick(float dt)
-    {
-        if (!CameraManager::getInstancePtr())
-            return;
-
-        // update listener position
-        Camera* camera = CameraManager::getInstance().getActiveCamera();
-        if(camera == NULL) return;
-        Vector3 pos = camera->getPosition();
-        alListener3f(AL_POSITION, pos.x, pos.y, pos.z);
+        alListenerfv(AL_POSITION, orient);
         ALenum error = alGetError();
-        if(error == AL_INVALID_VALUE)
-            COUT(2) << "Sound: OpenAL: Invalid listener position" << std::endl;
-
-        // update listener orientation
-        const Quaternion& orient = camera->getOrientation();
-        Vector3 up = orient.xAxis(); // just a wild guess
-        Vector3 at = orient.zAxis();
-
-        ALfloat orientation[6] = { at.x, at.y, at.z,
-                                 up.x, up.y, up.z };
-
-        alListenerfv(AL_POSITION, orientation);
-        error = alGetError();
-        if(error == AL_INVALID_VALUE)
+        if (error == AL_INVALID_VALUE)
             COUT(2) << "Sound: OpenAL: Invalid listener orientation" << std::endl;
-
-        // update sounds
-        for(std::list<SoundBase*>::iterator i = this->soundlist_.begin(); i != this->soundlist_.end(); i++)
-            (*i)->update();
-    }
-
-    /**
-    * Check if sound is available
-    */
-    bool SoundManager::isSoundAvailable()
-    {
-        return this->soundavailable_;
     }
 }
Index: /code/trunk/src/orxonox/sound/SoundManager.h
===================================================================
--- /code/trunk/src/orxonox/sound/SoundManager.h	(revision 5928)
+++ /code/trunk/src/orxonox/sound/SoundManager.h	(revision 5929)
@@ -39,9 +39,8 @@
     /**
      * The SoundManager class manages the OpenAL device, context and listener
-     * position. It has a list of all SoundBase objects and calls their update
-     * function every tick. It is a singleton.
+     * position. It is a singleton.
      *
      */
-    class _OrxonoxExport SoundManager : public Singleton<SoundManager>, public Tickable
+    class _OrxonoxExport SoundManager : public Singleton<SoundManager>
     {
         friend class Singleton<SoundManager>;
@@ -49,18 +48,15 @@
         SoundManager();
         ~SoundManager();
-        void addSound(SoundBase* sound);
-        void removeSound(SoundBase* sound);
-        void tick(float dt);
-        bool isSoundAvailable();
+
+        void setListenerPosition(const Vector3& position);
+        void setListenerOrientation(const Quaternion& orientation);
 
     private:
         ALCdevice* device_;
         ALCcontext* context_;
-        std::list<SoundBase*> soundlist_;
-        bool soundavailable_;
 
         static SoundManager* singletonPtr_s;
-    }; // class SoundManager
-} // namespace orxonox
+    };
+}
 
 #endif /* _SoundManager_H__ */
Index: /code/trunk/src/orxonox/sound/WorldSound.cc
===================================================================
--- /code/trunk/src/orxonox/sound/WorldSound.cc	(revision 5929)
+++ /code/trunk/src/orxonox/sound/WorldSound.cc	(revision 5929)
@@ -0,0 +1,91 @@
+/*
+ *   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:
+ *      Erwin 'vaiursch' Herrsche
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+#include "WorldSound.h"
+
+#include <AL/alut.h>
+#include "util/Math.h"
+#include "core/CoreIncludes.h"
+#include "core/EventIncludes.h"
+#include "core/XMLPort.h"
+
+namespace orxonox
+{
+    CreateFactory(WorldSound);
+
+    WorldSound::WorldSound(BaseObject* creator)
+        : StaticEntity(creator)
+    {
+        RegisterObject(WorldSound);
+    }
+
+    WorldSound::~WorldSound()
+    {
+    }
+
+    void WorldSound::XMLPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(WorldSound, XMLPort, xmlelement, mode);
+        XMLPortParamExtern(WorldSound, BaseSound, this, "source", setSource, getSource, xmlelement, mode);
+        XMLPortParamExtern(WorldSound, BaseSound, this, "loop", setLoop, getLoop, xmlelement, mode);
+        XMLPortParamExtern(WorldSound, BaseSound, this, "playOnLoad", setPlayOnLoad, getPlayOnLoad, xmlelement, mode);
+    }
+
+    void WorldSound::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        SUPER(WorldSound, XMLEventPort, xmlelement, mode);
+        XMLPortEventState(WorldSound, BaseObject, "play", play, xmlelement, mode);
+    }
+
+    void WorldSound::tick(float dt)
+    {
+        if (alIsSource(this->audioSource_))
+        {
+            const Vector3& pos = this->getWorldPosition();
+            alSource3f(this->audioSource_, AL_POSITION, pos.x, pos.y, pos.z);
+            ALenum error = alGetError();
+            if (error == AL_INVALID_VALUE)
+                COUT(2) << "Sound: OpenAL: Invalid sound position" << std::endl;
+
+            const Vector3& vel = this->getVelocity();
+            alSource3f(this->audioSource_, AL_VELOCITY, vel.x, vel.y, vel.z);
+            error = alGetError();
+            if (error == AL_INVALID_VALUE)
+                COUT(2) << "Sound: OpenAL: Invalid sound velocity" << std::endl;
+
+            const Quaternion& orient = this->getWorldOrientation();
+            Vector3 at = orient.zAxis();
+            alSource3f(this->audioSource_, AL_DIRECTION, at.x, at.y, at.z);
+            error = alGetError();
+            if (error == AL_INVALID_VALUE)
+                COUT(2) << "Sound: OpenAL: Invalid sound direction" << std::endl;
+        }
+    }
+
+}
Index: /code/trunk/src/orxonox/sound/WorldSound.h
===================================================================
--- /code/trunk/src/orxonox/sound/WorldSound.h	(revision 5929)
+++ /code/trunk/src/orxonox/sound/WorldSound.h	(revision 5929)
@@ -0,0 +1,58 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+#ifndef _WorldSound_H__
+#define _WorldSound_H__
+
+#include "OrxonoxPrereqs.h"
+
+#include "tools/interfaces/Tickable.h"
+#include "sound/BaseSound.h"
+#include "worldentities/StaticEntity.h"
+
+namespace orxonox
+{
+    /*
+    @brief
+        The WorldSound class is to be used for sounds with position and orientation.
+    */
+    class _OrxonoxExport WorldSound : public StaticEntity, public BaseSound, public Tickable
+    {
+    public:
+        WorldSound(BaseObject* creator);
+        virtual ~WorldSound();
+
+        virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+        virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
+
+        virtual void tick(float dt);
+
+    private:
+    };
+}
+
+#endif /* _WorldSound_H__ */
Index: /code/trunk/src/orxonox/weaponsystem/Munition.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/Munition.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/Munition.cc	(revision 5929)
@@ -461,8 +461,8 @@
         if (bUseReloadTime && (munition->reloadTime_ > 0 || munition->bStackMunition_))
         {
-            ExecutorMember<Magazine>* executor = createExecutor(createFunctor(&Magazine::loaded));
+            Executor* executor = createExecutor(createFunctor(&Magazine::loaded, this));
             executor->setDefaultValues(munition);
 
-            this->loadTimer_.setTimer(munition->reloadTime_, false, this, executor);
+            this->loadTimer_.setTimer(munition->reloadTime_, false, executor);
         }
         else
Index: /code/trunk/src/orxonox/weaponsystem/Munition.h
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/Munition.h	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/Munition.h	(revision 5929)
@@ -47,5 +47,5 @@
 
                 unsigned int munition_;
-                Timer<Magazine> loadTimer_;
+                Timer loadTimer_;
                 bool bLoaded_;
 
Index: /code/trunk/src/orxonox/weaponsystem/Weapon.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/Weapon.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/Weapon.cc	(revision 5929)
@@ -50,5 +50,5 @@
         this->reloadingWeaponmode_ = WeaponSystem::WEAPON_MODE_UNASSIGNED;
 
-        this->reloadTimer_.setTimer(0.0f, false, this, createExecutor(createFunctor(&Weapon::reloaded)));
+        this->reloadTimer_.setTimer(0.0f, false, createExecutor(createFunctor(&Weapon::reloaded, this)));
         this->reloadTimer_.stopTimer();
     }
@@ -62,5 +62,5 @@
 
             for (std::multimap<unsigned int, WeaponMode*>::iterator it = this->weaponmodes_.begin(); it != this->weaponmodes_.end(); ++it)
-                delete it->second;
+                it->second->destroy();
         }
     }
Index: /code/trunk/src/orxonox/weaponsystem/Weapon.h
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/Weapon.h	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/Weapon.h	(revision 5929)
@@ -71,5 +71,5 @@
             std::multimap<unsigned int, WeaponMode*> weaponmodes_;
 
-            Timer<Weapon> reloadTimer_;
+            Timer reloadTimer_;
             bool bReloading_;
             unsigned int reloadingWeaponmode_;
Index: /code/trunk/src/orxonox/weaponsystem/WeaponMode.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/WeaponMode.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/WeaponMode.cc	(revision 5929)
@@ -57,5 +57,5 @@
         this->bParallelReload_ = true;
 
-        this->reloadTimer_.setTimer(0.0f, false, this, createExecutor(createFunctor(&WeaponMode::reloaded)));
+        this->reloadTimer_.setTimer(0.0f, false, createExecutor(createFunctor(&WeaponMode::reloaded, this)));
         this->reloadTimer_.stopTimer();
 
Index: /code/trunk/src/orxonox/weaponsystem/WeaponMode.h
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/WeaponMode.h	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/WeaponMode.h	(revision 5929)
@@ -36,5 +36,5 @@
 #include "util/Math.h"
 #include "core/BaseObject.h"
-#include "core/Identifier.h"
+#include "core/SubclassIdentifier.h"
 #include "tools/Timer.h"
 
@@ -150,5 +150,5 @@
             std::string munitionname_;
 
-            Timer<WeaponMode> reloadTimer_;
+            Timer reloadTimer_;
             bool bReloading_;
     };
Index: /code/trunk/src/orxonox/weaponsystem/WeaponPack.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/WeaponPack.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/WeaponPack.cc	(revision 5929)
@@ -54,8 +54,8 @@
 
             while (!this->weapons_.empty())
-                delete (*this->weapons_.begin());
+                (*this->weapons_.begin())->destroy();
 
             for (std::set<DefaultWeaponmodeLink*>::iterator it = this->links_.begin(); it != this->links_.end(); )
-                delete (*(it++));
+                (*(it++))->destroy();
         }
     }
Index: /code/trunk/src/orxonox/weaponsystem/WeaponSlot.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/WeaponSlot.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/WeaponSlot.cc	(revision 5929)
@@ -46,5 +46,5 @@
         this->weapon_ = 0;
 
-        this->setObjectMode(0x0);
+        this->setSyncMode(0x0);
     }
 
Index: /code/trunk/src/orxonox/weaponsystem/WeaponSystem.cc
===================================================================
--- /code/trunk/src/orxonox/weaponsystem/WeaponSystem.cc	(revision 5928)
+++ /code/trunk/src/orxonox/weaponsystem/WeaponSystem.cc	(revision 5929)
@@ -62,14 +62,14 @@
 
             while (!this->weaponSets_.empty())
-                delete (this->weaponSets_.begin()->second);
+                this->weaponSets_.begin()->second->destroy();
 
             while (!this->weaponPacks_.empty())
-                delete (*this->weaponPacks_.begin());
+                (*this->weaponPacks_.begin())->destroy();
 
             while (!this->weaponSlots_.empty())
-                delete (*this->weaponSlots_.begin());
+                (*this->weaponSlots_.begin())->destroy();
 
             while (!this->munitions_.empty())
-                { delete (this->munitions_.begin()->second); this->munitions_.erase(this->munitions_.begin()); }
+                { this->munitions_.begin()->second->destroy(); this->munitions_.erase(this->munitions_.begin()); }
         }
     }
Index: /code/trunk/src/orxonox/worldentities/BigExplosion.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/BigExplosion.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/BigExplosion.cc	(revision 5929)
@@ -90,5 +90,5 @@
             this->setVelocity(velocity);
 
-            this->destroyTimer_.setTimer(rnd(2, 4), false, this, createExecutor(createFunctor(&BigExplosion::stop)));
+            this->destroyTimer_.setTimer(rnd(2, 4), false, createExecutor(createFunctor(&BigExplosion::stop, this)));
         }
         this->registerVariables();
@@ -226,10 +226,10 @@
             {
                 this->debris1_->detachOgreObject(this->debrisFire1_->getParticleSystem());
-                delete this->debrisFire1_;
+                this->debrisFire1_->destroy();
             }
             if (this->debrisSmoke1_)
             {
                 this->debris1_->detachOgreObject(this->debrisSmoke1_->getParticleSystem());
-                delete this->debrisSmoke1_;
+                this->debrisSmoke1_->destroy();
             }
 
@@ -237,10 +237,10 @@
             {
                 this->debris2_->detachOgreObject(this->debrisFire2_->getParticleSystem());
-                delete this->debrisFire2_;
+                this->debrisFire2_->destroy();
             }
             if (this->debrisSmoke2_)
             {
                 this->debris2_->detachOgreObject(this->debrisSmoke2_->getParticleSystem());
-                delete this->debrisSmoke2_;
+                this->debrisSmoke2_->destroy();
             }
 
@@ -248,10 +248,10 @@
             {
                 this->debris3_->detachOgreObject(this->debrisFire3_->getParticleSystem());
-                delete this->debrisFire3_;
+                this->debrisFire3_->destroy();
             }
             if (this->debrisSmoke3_)
             {
                 this->debris3_->detachOgreObject(this->debrisSmoke3_->getParticleSystem());
-                delete this->debrisSmoke3_;
+                this->debrisSmoke3_->destroy();
             }
 
@@ -259,10 +259,10 @@
             {
                 this->debris4_->detachOgreObject(this->debrisFire4_->getParticleSystem());
-                delete this->debrisFire4_;
+                this->debrisFire4_->destroy();
             }
             if (this->debrisSmoke4_)
             {
                 this->debris4_->detachOgreObject(this->debrisSmoke4_->getParticleSystem());
-                delete this->debrisSmoke4_;
+                this->debrisSmoke4_->destroy();
             }
         }
@@ -329,11 +329,6 @@
         {
             this->bStop_ = true;
-            this->destroyTimer_.setTimer(1.0f, false, this, createExecutor(createFunctor(&BigExplosion::destroy)));
-        }
-    }
-
-    void BigExplosion::destroy()
-    {
-        delete this;
+            this->destroyTimer_.setTimer(1.0f, false, createExecutor(createFunctor(&BigExplosion::destroy, this)));
+        }
     }
 
Index: /code/trunk/src/orxonox/worldentities/BigExplosion.h
===================================================================
--- /code/trunk/src/orxonox/worldentities/BigExplosion.h	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/BigExplosion.h	(revision 5929)
@@ -57,5 +57,4 @@
             void checkStop();
             void stop();
-            void destroy();
             void init();
             void initZero();
@@ -98,6 +97,6 @@
             ParticleInterface*    explosionFire_;
 
-            LODParticle::Value      LOD_;
-            Timer<BigExplosion> destroyTimer_;
+            LODParticle::Value    LOD_;
+            Timer                 destroyTimer_;
     };
 }
Index: /code/trunk/src/orxonox/worldentities/CameraPosition.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/CameraPosition.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/CameraPosition.cc	(revision 5929)
@@ -46,5 +46,5 @@
         this->bRenderCamera_ = false;
 
-        this->setObjectMode(0x0);
+        this->setSyncMode(0x0);
     }
 
Index: /code/trunk/src/orxonox/worldentities/ControllableEntity.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/ControllableEntity.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/ControllableEntity.cc	(revision 5929)
@@ -96,14 +96,14 @@
 
             if (this->xmlcontroller_)
-                delete this->xmlcontroller_;
+                this->xmlcontroller_->destroy();
 
             if (this->hud_)
-                delete this->hud_;
+                this->hud_->destroy();
 
             if (this->camera_)
-                delete this->camera_;
-
-            for (std::list<CameraPosition*>::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
-                delete (*it);
+                this->camera_->destroy();
+
+            for (std::list<SmartPtr<CameraPosition> >::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
+                (*it)->destroy();
 
             if (this->getScene()->getSceneManager())
@@ -153,5 +153,5 @@
     {
         unsigned int i = 0;
-        for (std::list<CameraPosition*>::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
+        for (std::list<SmartPtr<CameraPosition> >::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
         {
             if (i == index)
@@ -172,5 +172,5 @@
             else if (this->cameraPositions_.size() > 0)
             {
-                for (std::list<CameraPosition*>::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
+                for (std::list<SmartPtr<CameraPosition> >::const_iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
                 {
                     if ((*it) == this->camera_->getParent())
@@ -238,5 +238,5 @@
             {
                 this->client_overwrite_ = this->server_overwrite_;
-                this->setObjectMode(ObjectDirection::Bidirectional);
+                this->setSyncMode(ObjectDirection::Bidirectional);
             }
         }
@@ -254,10 +254,10 @@
         this->bHasLocalController_ = false;
         this->bHasHumanController_ = false;
-        this->setObjectMode(ObjectDirection::ToClient);
+        this->setSyncMode(ObjectDirection::ToClient);
 
         this->changedPlayer();
 
         if (this->bDestroyWhenPlayerLeft_)
-            delete this;
+            this->destroy();
     }
 
@@ -275,5 +275,5 @@
     void ControllableEntity::startLocalHumanControl()
     {
-        if (!this->camera_)
+        if (!this->camera_ && GameMode::showsGraphics())
         {
             this->camera_ = new Camera(this);
@@ -287,5 +287,5 @@
         }
 
-        if (!this->hud_)
+        if (!this->hud_ && GameMode::showsGraphics())
         {
             if (this->hudtemplate_ != "")
@@ -303,5 +303,5 @@
         {
             this->camera_->detachFromParent();
-            delete this->camera_;
+            this->camera_->destroy();
             this->camera_ = 0;
         }
@@ -309,5 +309,5 @@
         if (this->hud_)
         {
-            delete this->hud_;
+            this->hud_->destroy();
             this->hud_ = 0;
         }
@@ -333,5 +333,5 @@
         if (parent)
         {
-            for (std::list<CameraPosition*>::iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
+            for (std::list<SmartPtr<CameraPosition> >::iterator it = this->cameraPositions_.begin(); it != this->cameraPositions_.end(); ++it)
                 if ((*it)->getIsAbsolute())
                     parent->attach((*it));
Index: /code/trunk/src/orxonox/worldentities/ControllableEntity.h
===================================================================
--- /code/trunk/src/orxonox/worldentities/ControllableEntity.h	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/ControllableEntity.h	(revision 5929)
@@ -104,5 +104,5 @@
             void addCameraPosition(CameraPosition* position);
             CameraPosition* getCameraPosition(unsigned int index) const;
-            inline const std::list<CameraPosition*>& getCameraPositions() const
+            inline const std::list<SmartPtr<CameraPosition> >& getCameraPositions() const
                 { return this->cameraPositions_; }
 
@@ -198,5 +198,5 @@
             float mouseLookSpeed_;
             Ogre::SceneNode* cameraPositionRootNode_;
-            std::list<CameraPosition*> cameraPositions_;
+            std::list<SmartPtr<CameraPosition> > cameraPositions_;
             std::string cameraPositionTemplate_;
             Controller* xmlcontroller_;
Index: /code/trunk/src/orxonox/worldentities/ExplosionChunk.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/ExplosionChunk.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/ExplosionChunk.cc	(revision 5929)
@@ -79,5 +79,5 @@
             this->setVelocity(velocity);
 
-            this->destroyTimer_.setTimer(rnd(1, 2), false, this, createExecutor(createFunctor(&ExplosionChunk::stop)));
+            this->destroyTimer_.setTimer(rnd(1, 2), false, createExecutor(createFunctor(&ExplosionChunk::stop, this)));
         }
 
@@ -92,10 +92,10 @@
             {
                 this->detachOgreObject(this->fire_->getParticleSystem());
-                delete this->fire_;
+                this->fire_->destroy();
             }
             if (this->smoke_)
             {
                 this->detachOgreObject(this->smoke_->getParticleSystem());
-                delete this->smoke_;
+                this->smoke_->destroy();
             }
         }
@@ -132,11 +132,6 @@
         {
             this->bStop_ = true;
-            this->destroyTimer_.setTimer(1.0f, false, this, createExecutor(createFunctor(&ExplosionChunk::destroy)));
+            this->destroyTimer_.setTimer(1.0f, false, createExecutor(createFunctor(&ExplosionChunk::destroy, this)));
         }
-    }
-
-    void ExplosionChunk::destroy()
-    {
-        delete this;
     }
 
Index: /code/trunk/src/orxonox/worldentities/ExplosionChunk.h
===================================================================
--- /code/trunk/src/orxonox/worldentities/ExplosionChunk.h	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/ExplosionChunk.h	(revision 5929)
@@ -55,11 +55,10 @@
             void checkStop();
             void stop();
-            void destroy();
 
             bool                  bStop_;
             ParticleInterface*    fire_;
             ParticleInterface*    smoke_;
-            LODParticle::Value      LOD_;
-            Timer<ExplosionChunk> destroyTimer_;
+            LODParticle::Value    LOD_;
+            Timer                 destroyTimer_;
     };
 }
Index: /code/trunk/src/orxonox/worldentities/MovableEntity.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/MovableEntity.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/MovableEntity.cc	(revision 5929)
@@ -61,5 +61,5 @@
         if (this->isInitialized())
             if (this->continuousResynchroTimer_)
-                delete this->continuousResynchroTimer_;
+                this->continuousResynchroTimer_->destroy();
     }
 
@@ -98,5 +98,5 @@
     void MovableEntity::clientConnected(unsigned int clientID)
     {
-        this->resynchronizeTimer_.setTimer(rnd() * MAX_RESYNCHRONIZE_TIME, false, this, createExecutor(createFunctor(&MovableEntity::resynchronize)));
+        this->resynchronizeTimer_.setTimer(rnd() * MAX_RESYNCHRONIZE_TIME, false, createExecutor(createFunctor(&MovableEntity::resynchronize, this)));
     }
 
@@ -110,6 +110,6 @@
         {
             // Resynchronise every few seconds because we only work with velocities (no positions)
-            continuousResynchroTimer_ = new Timer<MovableEntity>(CONTINUOUS_SYNCHRONIZATION_TIME + rnd(-1, 1),
-                true, this, createExecutor(createFunctor(&MovableEntity::resynchronize)), false);
+            continuousResynchroTimer_ = new Timer(CONTINUOUS_SYNCHRONIZATION_TIME + rnd(-1, 1),
+                true, createExecutor(createFunctor(&MovableEntity::resynchronize, this)), false);
         }
 
Index: /code/trunk/src/orxonox/worldentities/MovableEntity.h
===================================================================
--- /code/trunk/src/orxonox/worldentities/MovableEntity.h	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/MovableEntity.h	(revision 5929)
@@ -96,6 +96,6 @@
             Quaternion overwrite_orientation_;
 
-            Timer<MovableEntity> resynchronizeTimer_;
-            Timer<MovableEntity>* continuousResynchroTimer_;
+            Timer resynchronizeTimer_;
+            Timer* continuousResynchroTimer_;
 
             Pawn* owner_;
Index: /code/trunk/src/orxonox/worldentities/SpawnPoint.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/SpawnPoint.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/SpawnPoint.cc	(revision 5929)
@@ -50,5 +50,5 @@
             COUT(1) << "Error: SpawnPoint has no Gametype" << std::endl;
 
-        this->setObjectMode(0x0);
+        this->setSyncMode(0x0);
     }
 
Index: /code/trunk/src/orxonox/worldentities/SpawnPoint.h
===================================================================
--- /code/trunk/src/orxonox/worldentities/SpawnPoint.h	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/SpawnPoint.h	(revision 5929)
@@ -33,5 +33,5 @@
 
 #include <string>
-#include "core/Identifier.h"
+#include "core/SubclassIdentifier.h"
 #include "worldentities/StaticEntity.h"
 
Index: /code/trunk/src/orxonox/worldentities/WorldEntity.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/WorldEntity.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/WorldEntity.cc	(revision 5929)
@@ -119,5 +119,5 @@
             {
                 if ((*it)->getDeleteWithParent())
-                    delete (*(it++));
+                    (*(it++))->destroy();
                 else
                 {
@@ -132,5 +132,5 @@
                 delete this->physicalBody_;
             }
-            delete this->collisionShape_;
+            this->collisionShape_->destroy();
 
             this->node_->detachAllObjects();
@@ -175,5 +175,5 @@
     void WorldEntity::registerVariables()
     {
-        registerVariable(this->mainStateName_,  VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedMainState));
+        registerVariable(this->mainStateName_,  VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedMainStateName));
 
         registerVariable(this->bActive_,        VariableDirection::ToClient, new NetworkCallback<WorldEntity>(this, &WorldEntity::changedActivity));
Index: /code/trunk/src/orxonox/worldentities/pawns/Destroyer.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/pawns/Destroyer.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/pawns/Destroyer.cc	(revision 5929)
@@ -40,5 +40,5 @@
         RegisterObject(Destroyer);
 
-        UnderAttack* gametype = orxonox_cast<UnderAttack*>(this->getGametype());
+        UnderAttack* gametype = orxonox_cast<UnderAttack*>(this->getGametype().get());
         if (gametype)
         {
Index: /code/trunk/src/orxonox/worldentities/pawns/Pawn.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/pawns/Pawn.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/pawns/Pawn.cc	(revision 5929)
@@ -36,5 +36,4 @@
 #include "network/NetworkFunction.h"
 
-#include "interfaces/PawnListener.h"
 #include "PawnManager.h"
 #include "infos/PlayerInfo.h"
@@ -93,9 +92,6 @@
         if (this->isInitialized())
         {
-            for (ObjectList<PawnListener>::iterator it = ObjectList<PawnListener>::begin(); it != ObjectList<PawnListener>::end(); ++it)
-                it->destroyedPawn(this);
-
             if (this->weaponSystem_)
-                delete this->weaponSystem_;
+                this->weaponSystem_->destroy();
         }
     }
Index: /code/trunk/src/orxonox/worldentities/pawns/SpaceShip.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/pawns/SpaceShip.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/pawns/SpaceShip.cc	(revision 5929)
@@ -75,5 +75,5 @@
     {
         if (this->isInitialized() && this->engine_)
-            delete this->engine_;
+            this->engine_->destroy();
     }
 
@@ -207,5 +207,5 @@
                     else
                     {
-                        delete object;
+                        object->destroy();
                     }
                 }
Index: /code/trunk/src/orxonox/worldentities/pawns/Spectator.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/pawns/Spectator.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/pawns/Spectator.cc	(revision 5929)
@@ -145,5 +145,5 @@
         ControllableEntity::setPlayer(player);
 
-//        this->setObjectMode(ObjectDirection::ToClient);
+//        this->setSyncMode(ObjectDirection::ToClient);
     }
 
Index: /code/trunk/src/orxonox/worldentities/pawns/TeamBaseMatchBase.cc
===================================================================
--- /code/trunk/src/orxonox/worldentities/pawns/TeamBaseMatchBase.cc	(revision 5928)
+++ /code/trunk/src/orxonox/worldentities/pawns/TeamBaseMatchBase.cc	(revision 5929)
@@ -31,5 +31,5 @@
 
 #include "core/CoreIncludes.h"
-#include "interfaces/PawnListener.h"
+#include "controllers/ArtificialController.h"
 #include "interfaces/TeamColourable.h"
 #include "gametypes/TeamBaseMatch.h"
@@ -45,5 +45,5 @@
         this->state_ = BaseState::Uncontrolled;
 
-        TeamBaseMatch* gametype = orxonox_cast<TeamBaseMatch*>(this->getGametype());
+        TeamBaseMatch* gametype = orxonox_cast<TeamBaseMatch*>(this->getGametype().get());
         if (gametype)
         {
@@ -58,5 +58,5 @@
         this->fireEvent();
 
-        TeamDeathmatch* gametype = orxonox_cast<TeamDeathmatch*>(this->getGametype());
+        TeamDeathmatch* gametype = orxonox_cast<TeamDeathmatch*>(this->getGametype().get());
         if (!gametype)
             return;
@@ -92,6 +92,6 @@
 
         // Call this so bots stop shooting at the base after they converted it
-        for (ObjectList<PawnListener>::iterator it = ObjectList<PawnListener>::begin(); it != ObjectList<PawnListener>::end(); ++it)
-            it->destroyedPawn(this);
+        for (ObjectList<ArtificialController>::iterator it = ObjectList<ArtificialController>::begin(); it != ObjectList<ArtificialController>::end(); ++it)
+            it->abandonTarget(this);
     }
 }
