actorid
Jason Hooks 14 years ago
commit 2236f69645

4
.gitmodules vendored

@ -1,6 +1,6 @@
[submodule "libs/mangle"]
path = libs/mangle
url = git://github.com/korslund/mangle.git
url = git://github.com/zinnschlag/mangle.git
[submodule "libs/openengine"]
path = libs/openengine
url = git://github.com/korslund/OpenEngine
url = git://github.com/zinnschlag/OpenEngine

@ -5,9 +5,22 @@ option(USE_AUDIERE "use Audiere for sound" OFF)
option(USE_FFMPEG "use ffmpeg for sound" OFF)
option(USE_MPG123 "use mpg123 + libsndfile for sound" ON)
find_program(DPKG_PROGRAM dpkg DOC "dpkg program of Debian-based systems")
# Location of morrowind data files
set(MORROWIND_DATA_FILES "data"
CACHE PATH "location of Morrowind data files")
if(DPKG_PROGRAM)
set(MORROWIND_DATA_FILES "/usr/share/games/openmw/data/" CACHE PATH "location of Morrowind data files")
set(MORROWIND_RESOURCE_FILES "/usr/share/games/openmw/resources/" CACHE PATH "location of Morrowind data files")
else()
if (APPLE)
# set path inside bundle
set(MORROWIND_DATA_FILES "Contents/Resources/data" CACHE PATH "location of Morrowind data files")
set(MORROWIND_RESOURCE_FILES "Contents/Resources/resources" CACHE PATH "location of Morrowind data files")
else()
set(MORROWIND_DATA_FILES "data" CACHE PATH "location of Morrowind data files")
set(MORROWIND_RESOURCE_FILES "resources" CACHE PATH "location of Morrowind data files")
endif(APPLE)
endif(DPKG_PROGRAM)
if (WIN32)
option(USE_DEBUG_CONSOLE "whether a debug console should be enabled for debug builds, if false debug output is redirected to Visual Studio output" ON)
@ -16,31 +29,30 @@ endif()
# We probably support older versions than this.
cmake_minimum_required(VERSION 2.6)
#
# Pre-built binaries being used?
#
IF(EXISTS "${CMAKE_SOURCE_DIR}/prebuilt/vc100-mt-gd/ogre_1_7_1")
set(PREBUILT_DIR "${CMAKE_SOURCE_DIR}/prebuilt/vc100-mt-gd")
message (STATUS "OpenMW pre-built binaries found at ${PREBUILT_DIR}.")
SET(ENV{OGRE_HOME} "${PREBUILT_DIR}/ogre_1_7_1")
SET(ENV{BOOST_ROOT} "${PREBUILT_DIR}/boost_1_42_0")
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(ENV{BOOST_INCLUDEDIR} "${BOOST_ROOT}/include")
set(ENV{BOOST_LIBRARYDIR} "${BOOST_ROOT}/lib")
set(ENV{FREETYPE_DIR} "${PREBUILT_DIR}/freetype-2.3.5-1")
set(USE_MPG123 OFF)
set(USE_AUDIERE ON)
set(USE_AUDIERE ON)
set(AUDIERE_INCLUDE_DIR "${PREBUILT_DIR}/audiere-1.9.4/include")
set(AUDIERE_LIBRARY "${PREBUILT_DIR}/audiere-1.9.4/lib/audiere.lib")
set(ENV{OPENALDIR} "${PREBUILT_DIR}/OpenAL 1.1 SDK")
ELSE()
message (STATUS "OpenMW pre-built binaries not found. Using standard locations.")
ENDIF()
@ -81,6 +93,12 @@ set(NIFOGRE_HEADER
${COMP_DIR}/nifogre/ogre_nif_loader.hpp)
source_group(components\\nifogre FILES ${NIFOGRE} ${NIFOGRE_HEADER})
set(NIFBULLET
${COMP_DIR}/nifbullet/bullet_nif_loader.cpp)
set(NIFBULLET_HEADER
${COMP_DIR}/nifbullet/bullet_nif_loader.hpp)
source_group(components\\nifbullet FILES ${NIFBULLET} ${NIFBULLET_HEADER})
set(TO_UTF8
${COMP_DIR}/to_utf8/to_utf8.cpp)
set(TO_UTF8_HEADER
@ -130,10 +148,10 @@ file(GLOB INTERPRETER_HEADER ${COMP_DIR}/interpreter/*.hpp)
source_group(components\\interpreter FILES ${INTERPRETER} ${INTERPRETER_HEADER})
set(COMPONENTS ${BSA} ${NIF} ${NIFOGRE} ${ESM_STORE} ${MISC} ${TO_UTF8}
${COMPILER} ${INTERPRETER} ${ESM} ${FILE_FINDER})
${COMPILER} ${INTERPRETER} ${ESM} ${FILE_FINDER} ${NIFBULLET})
set(COMPONENTS_HEADER ${BSA_HEADER} ${NIF_HEADER} ${NIFOGRE_HEADER} ${ESM_STORE_HEADER}
${ESM_HEADER} ${MISC_HEADER} ${COMPILER_HEADER} ${TO_UTF8_HEADER}
${INTERPRETER_HEADER} ${FILE_FINDER_HEADER})
${INTERPRETER_HEADER} ${FILE_FINDER_HEADER} ${NIFBULLET_HEADER})
# source directory: libs
@ -153,6 +171,21 @@ set(OENGINE_GUI
${LIBDIR}/openengine/gui/manager.cpp
)
set(OENGINE_BULLET
${LIBDIR}/openengine/bullet/btKinematicCharacterController.cpp
${LIBDIR}/openengine/bullet/btKinematicCharacterController.h
${LIBDIR}/openengine/bullet/BtOgre.cpp
${LIBDIR}/openengine/bullet/BtOgreExtras.h
${LIBDIR}/openengine/bullet/BtOgreGP.h
${LIBDIR}/openengine/bullet/BtOgrePG.h
${LIBDIR}/openengine/bullet/CMotionState.cpp
${LIBDIR}/openengine/bullet/CMotionState.h
${LIBDIR}/openengine/bullet/physic.cpp
${LIBDIR}/openengine/bullet/physic.hpp
${LIBDIR}/openengine/bullet/BulletShapeLoader.cpp
${LIBDIR}/openengine/bullet/BulletShapeLoader.h
)
# Sound setup
if (USE_AUDIERE)
set(MANGLE_SOUND_OUTPUT
@ -193,7 +226,7 @@ set(OENGINE_SOUND
${LIBDIR}/mangle/sound/outputs/openal_out.cpp
${MANGLE_SOUND_OUTPUT}
)
set(OENGINE_ALL ${OENGINE_OGRE} ${OENGINE_GUI} ${OENGINE_SOUND})
set(OENGINE_ALL ${OENGINE_OGRE} ${OENGINE_GUI} ${OENGINE_SOUND} ${OENGINE_BULLET})
source_group(libs\\openengine FILES ${OENGINE_ALL})
set(OPENMW_LIBS ${MANGLE_ALL} ${OENGINE_ALL})
@ -205,25 +238,34 @@ if (WIN32)
add_definitions(-DBOOST_ALL_NO_LIB)
else (WIN32)
set(PLATFORM_INCLUDE_DIR "")
find_path (UUID_INCLUDE_DIR uuid/uuid.h)
include_directories(${UUID_INCLUDE_DIR})
endif (WIN32)
if (MSVC10)
set(PLATFORM_INCLUDE_DIR "")
set(PLATFORM_INCLUDE_DIR "")
add_definitions(-DMYGUI_DONT_REPLACE_NULLPTR)
endif()
if (APPLE)
set(Boost_USE_STATIC_LIBS ON)
endif (APPLE)
# Dependencies
find_package(OGRE REQUIRED)
find_package(Boost REQUIRED COMPONENTS system filesystem program_options thread)
find_package(OIS REQUIRED)
find_package(OpenAL REQUIRED)
find_package(Bullet REQUIRED)
include_directories("."
${OGRE_INCLUDE_DIR} ${OGRE_INCLUDE_DIR}/Ogre
${OGRE_INCLUDE_DIR} ${OGRE_INCLUDE_DIR}/Ogre ${OGRE_INCLUDE_DIR}/OGRE
${OIS_INCLUDE_DIR} ${Boost_INCLUDE_DIR}
${PLATFORM_INCLUDE_DIR}
${CMAKE_HOME_DIRECTORY}/extern/caelum/include
${CMAKE_HOME_DIRECTORY}/extern/mygui_3.0.1/MyGUIEngine/include
${CMAKE_HOME_DIRECTORY}/extern/mygui_3.0.1/OgrePlatform/include
${OPENAL_INCLUDE_DIR}
${UUID_INCLUDE_DIR}
${LIBDIR}
)
@ -251,21 +293,19 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${OpenMW_BINARY_DIR}")
if (WIN32)
configure_file(${OpenMW_SOURCE_DIR}/files/plugins.cfg.win32
"${OpenMW_BINARY_DIR}/plugins.cfg" COPYONLY)
else (WIN32)
configure_file(${OpenMW_SOURCE_DIR}/files/plugins.cfg.linux
"${OpenMW_BINARY_DIR}/plugins.cfg" COPYONLY)
endif (WIN32)
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
configure_file(${OpenMW_SOURCE_DIR}/files/plugins.cfg.linux
"${OpenMW_BINARY_DIR}/plugins.cfg")
endif()
if (APPLE)
configure_file(${OpenMW_SOURCE_DIR}/files/plugins.cfg.mac
"${OpenMW_BINARY_DIR}/plugins.cfg")
endif (APPLE)
configure_file(${OpenMW_SOURCE_DIR}/files/openmw.cfg
"${OpenMW_BINARY_DIR}/openmw.cfg")
if (APPLE)
set(APPLE_BUNDLE_RESOURCES
${CMAKE_SOURCE_DIR}/files/openmw.cfg
${CMAKE_SOURCE_DIR}/files/mac/plugins.cfg
)
endif (APPLE)
# Compiler settings
if (CMAKE_COMPILER_IS_GNUCC)
#add_definitions (-Wall -Werror)
@ -275,21 +315,17 @@ endif (CMAKE_COMPILER_IS_GNUCC)
# Apple bundling
if (APPLE)
set(MISC_FILES
${CMAKE_SOURCE_DIR}/files/openmw.cfg
${CMAKE_SOURCE_DIR}/files/mac/plugins.cfg
${CMAKE_SOURCE_DIR}/files/mac/ogre.cfg)
install(TARGETS openmw
BUNDLE DESTINATION .
RUNTIME DESTINATION ../MacOS
COMPONENT Runtime)
${OpenMW_BINARY_DIR}/openmw.cfg
${OpenMW_BINARY_DIR}/plugins.cfg)
install(FILES ${MISC_FILES} DESTINATION ../MacOS)
install(DIRECTORY "${OpenMW_BINARY_DIR}/resources" DESTINATION ../Resources)
set(CPACK_GENERATOR "Bundle")
set(CPACK_BUNDLE_PLIST "${CMAKE_SOURCE_DIR}/files/mac/Info.plist")
set(CPACK_BUNDLE_ICON "${CMAKE_SOURCE_DIR}/files/mac/openmw.icns")
set(CPACK_BUNDLE_NAME "OpenMW")
set(CPACK_PACKAGE_VERSION "0.07")
set(CPACK_PACKAGE_VERSION "0.10")
set(CPACK_PACKAGE_VERSION_MAJOR "0")
set(CPACK_PACKAGE_VERSION_MINOR "07")
set(CPACK_PACKAGE_VERSION_MINOR "10")
set(CPACK_PACKAGE_VERSION_PATCH "")
include(CPack)
@ -299,6 +335,57 @@ set(CMAKE_CXX_FLAGS "-arch i386")
endif (APPLE)
if(DPKG_PROGRAM)
SET(CMAKE_INSTALL_PREFIX "/usr")
if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/.git")
exec_program("git" ${CMAKE_CURRENT_SOURCE_DIR} ARGS "describe" OUTPUT_VARIABLE GIT_VERSION )
STRING(REGEX REPLACE "openmw-" "" VERSION_STRING "${GIT_VERSION}")
exec_program("git" ARGS "config --get user.name" OUTPUT_VARIABLE GIT_NAME )
exec_program("git" ARGS "config --get user.email" OUTPUT_VARIABLE GIT_EMAIL)
set(PACKAGE_MAINTAINER "${GIT_NAME} <${GIT_EMAIL}>")
else()
#FIXME this should probably be read from some file like ${CMAKE_CURRENT_SOURCE_DIR}/VERSION or something that gets updated when changing version
set(VERSION_STRING "0.10.0")
set(PACKAGE_MAINTAINER "unknown")
endif()
#Install global configuration files
INSTALL(FILES "${OpenMW_BINARY_DIR}/openmw.cfg" DESTINATION "../etc/openmw/" PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ COMPONENT "openmw")
INSTALL(FILES "${OpenMW_BINARY_DIR}/plugins.cfg" DESTINATION "../etc/openmw/" PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ COMPONENT "openmw")
#Install resources
INSTALL(DIRECTORY "${OpenMW_BINARY_DIR}/resources" DESTINATION "share/games/openmw/" FILE_PERMISSIONS OWNER_READ GROUP_READ WORLD_READ COMPONENT "Resources")
INSTALL(DIRECTORY DESTINATION "share/games/openmw/data/" COMPONENT "Resources")
SET(CPACK_GENERATOR "DEB")
SET(CPACK_PACKAGE_NAME "openmw")
SET(CPACK_DEBIAN_PACKAGE_HOMEPAGE "http://openmw.com")
SET(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
SET(CPACK_DEBIAN_PACKAGE_MAINTAINER "${PACKAGE_MAINTAINER}")
SET(CPACK_DEBIAN_PACKAGE_DESCRIPTION "A reimplementation of The Elder Scrolls III: Morrowind
OpenMW is a reimplementation of the Bethesda Game Studios game The Elder Scrolls III: Morrowind.
Data files from the original game is required to run it.")
SET(CPACK_DEBIAN_PACKAGE_NAME "openmw")
SET(CPACK_DEBIAN_PACKAGE_VERSION "${VERSION_STRING}")
SET(CPACK_PACKAGE_EXECUTABLES "openmw;OpenMW")
SET(CPACK_DEBIAN_PACKAGE_DEPENDS "libogremain-1.7.1 (>= 1.7.1-1), libbullet2.77 (>= 2.77), libboost-filesystem1.42.0 (>= 1.42.0), libboost-program-options1.42.0 (>= 1.42.0), libboost-system1.42.0 (>= 1.42.0), libboost-thread1.42.0 (>= 1.42.0), libc6 (>= 2.11.2), libfreetype6 (>= 2.2.1), libgcc1 (>= 1:4.1.1), libmpg123-0 (>= 1.12.1), libois-1.2.0 (>= 1.2.0), libopenal1 (>= 1:1.12.854), libsndfile1 (>= 1.0.23), libstdc++6 (>= 4.4.5), libuuid1 (>= 2.17.2)")
SET(CPACK_DEBIAN_PACKAGE_SECTION "Games")
string(TOLOWER "${CPACK_PACKAGE_NAME}" CPACK_PACKAGE_NAME_LOWERCASE)
execute_process(
COMMAND ${DPKG_PROGRAM} --print-architecture
OUTPUT_VARIABLE CPACK_DEBIAN_PACKAGE_ARCHITECTURE
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME_LOWERCASE}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}")
include(CPack)
endif(DPKG_PROGRAM)
# Apps and tools
add_subdirectory( apps/openmw )
@ -308,22 +395,40 @@ if (BUILD_ESMTOOL)
endif()
if (WIN32)
if (MSVC)
if (USE_DEBUG_CONSOLE)
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:CONSOLE")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:CONSOLE")
set_target_properties(openmw PROPERTIES COMPILE_DEFINITIONS_DEBUG "_CONSOLE")
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:CONSOLE")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:CONSOLE")
set_target_properties(openmw PROPERTIES COMPILE_DEFINITIONS_DEBUG "_CONSOLE")
else()
# Turn off debug console, debug output will be written to visual studio output instead
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:WINDOWS")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:WINDOWS")
# Turn off debug console, debug output will be written to visual studio output instead
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:WINDOWS")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:WINDOWS")
endif()
# Release builds use the debug console
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:CONSOLE")
set_target_properties(openmw PROPERTIES COMPILE_DEFINITIONS_RELEASE "_CONSOLE")
set_target_properties(openmw PROPERTIES LINK_FLAGS_MINSIZEREL "/SUBSYSTEM:CONSOLE")
endif(MSVC)
# Same for MinGW
if (MINGW)
if (USE_DEBUG_CONSOLE)
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "-Wl,-subsystem,console")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "-Wl,-subsystem,console")
set_target_properties(openmw PROPERTIES COMPILE_DEFINITIONS_DEBUG "_CONSOLE")
else(USE_DEBUG_CONSOLE)
set_target_properties(openmw PROPERTIES LINK_FLAGS_DEBUG "-Wl,-subsystem,windows")
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELWITHDEBINFO "-Wl,-subsystem,windows")
endif(USE_DEBUG_CONSOLE)
set_target_properties(openmw PROPERTIES LINK_FLAGS_RELEASE "-Wl,-subsystem,console")
set_target_properties(openmw PROPERTIES LINK_FLAGS_MINSIZEREL "-Wl,-subsystem,console")
set_target_properties(openmw PROPERTIES COMPILE_DEFINITIONS_RELEASE "_CONSOLE")
endif(MINGW)
# TODO: At some point release builds should not use the console but rather write to a log file
#set_target_properties(openmw PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:WINDOWS")
#set_target_properties(openmw PROPERTIES LINK_FLAGS_MINSIZEREL "/SUBSYSTEM:WINDOWS")
# TODO: At some point release builds should not use the console but rather write to a log file
#set_target_properties(openmw PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:WINDOWS")
#set_target_properties(openmw PROPERTIES LINK_FLAGS_MINSIZEREL "/SUBSYSTEM:WINDOWS")
endif()

@ -29,22 +29,28 @@ Getting OpenMW Working
----------------------
1. Clone this repository.
2. Install `bjam` through MacPorts.
3. Download [boost][] 1.43 and install it with the following command:
2. Note about libs: I prefer not to install them globally (i. e. in /usr/local/), so I installing them in directory in my home directory. If OpenMW sources is in $HOME/path/openmw, I'm using $HOME/path/libs/root as prefix for boost and other libs.
It's useful to create env var for lib install prefix:
$ export OMW_LIB_PREFIX=$HOME/path/libs/root
$ mkdir build && sudo bjam --build-dir=build \
--layout=versioned --toolset=darwin architecture=i386 \
address-model=32 --link=shared,static install
3. First of all, set for current terminal some env vars:
$ export CFLAGS="-arch i386"
$ export CXXFLAGS="-arch i386"
$ export LDFLAGS="-arch i386"
All libs will build with correct architecture.
If you close your terminal, you should set env vars again before pcoceeding to next steps!
4. Download [boost][] (tested with 1.45) and install it with the following command:
4. Download [Ogre][] 1.7.1 and build and Xcode project with CMake:
$ cd /path/to/boost/source
$ ./bootstrap.sh --prefix=$OMW_LIB_PREFIX
$ ./bjam --build-dir=build --layout=versioned \
--toolset=darwin architecture=x86 address-model=32 \
--link-shared,static --prefix=$OMW_LIB_PREFIX install
$ mdkir build && cd build && \
BOOST_INCLUDEDIR=/usr/local/include/boost-1_43 \
BOOST_LIBRARYDIR=/usr/local/lib cmake -G Xcode ..
5. Once the build completes, move `lib/Release/Ogre.framework` into
`/Library/Frameworks`.
5. Download [Ogre][] SDK (tested with 1.7.2) and move `lib/Release/Ogre.framework` into
`Library/Frameworks`.
6. Download [OIS][] and use the XCode project provided in
`ois/Mac/XCode-2.2`. Be sure to set your build architecture to
@ -52,20 +58,89 @@ Getting OpenMW Working
builds, move `ois/Mac/XCode-2.2/build/Debug/OIS.framework` to
`/Library/Frameworks`.
7. Generate the Makefile for OpenMW as follows:
$ mkdir build && cd build && \
BOOST_INCLUDEDIR=/usr/local/include/boost-1_43 \
BOOST_LIBRARYDIR=/usr/local/lib CMAKE_OSX_ARCHITECTURES=i386 \
cmake ..
8. Move your Morrowind `Data Files` directory into the root `openmw`
directory with the name `data`. Symlink it into the build directory.
$ cd build && ln -s ../data data
7. Download [mpg123][] and build it:
$ cd /path/to/mpg123/source
$ ./configure --prefix=$OMW_LIB_PREFIX --disable-debug \
--disable-dependency-tracking \
--with-optimization=4 \
--with-audio=coreaudio \
--with-default-audio=coreaudio \
--with-cpu=sse_alone \
$ make install
8. Download [libsndfile][] and build it:
$ cd /path/to/libsndfile/source
$ ./configure --prefix=$OMW_LIB_PREFIX \
--disable-dependency-tracking
$ make install
9. Download [Bullet][] and build it:
$ cd /path/to/bullet/source
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=$OMW_LIB_PREFIX \
-DBUILD_EXTRAS=OFF \
-DBUILD_DEMOS=OFF \
-DCMAKE_OSX_ARCHITECTURES=i386 \
-DCMAKE_INSTALL_NAME_DIR=$OMW_LIB_RPEFIX/lib \
-G"Unix Makefiles" ../
$ make install
10. Generate the Makefile for OpenMW as follows and build OpenMW:
$ mkdir /path/to/openmw/build/dir
$ cd /path/to/open/build/dir
$ cmake \
-D CMAKE_OSX_ARCHITECTURES=i386 \
-D BOOST_INCLUDEDIR=$OMW_LIB_PREFIX/include/boost-1_45 \
-D BOOST_LIBRARYDIR=$OMW_LIB_PREFIX/lib \
-D SNDFILE_INCLUDE_DIR=$OMW_LIB_PREFIX/include \
-D SNDFILE_LIBRARY=$OMW_LIB_PREFIX/lib/libsndfile.a \
-D MPG123_LIBRARY=$OMW_LIB_PREFIX/lib/libmpg123.a \
-D MPG123_INCLUDE_DIR=$OMW_LIB_PREFIX/include \
-D BULLET_DYNAMICS_LIBRARY=$OMW_LIB_PREFIX/lib/libBulletDynamics.a \
-D BULLET_COLLISION_LIBRARY=$OMW_LIB_PREFIX/lib/libBulletCollision.a \
-D BULLET_MATH_LIBRARY=$OMW_LIB_PREFIX/lib/libLinearMath.a \
-D BULLET_SOFTBODY_LIBRARY=$OMW_LIB_PREFIX/lib/libBulletSoftBody.a \
-D BULLET_INCLUDE_DIR=$OMW_LIB_PREFIX/include/bullet/ \
-G "Unix Makefiles" /path/to/openmw/source/dir
$ make
You can use -G"Xcode" if you prefer Xcode, or -G"Eclipse CDT4 - Unix Makefiles"
if you prefer Eclipse. You also can specify -D CMAKE_BUILD_TYPE=Debug for debug
build.
11. In build directory create directory for game resources:
$ cd /path/to/openmw/build/dir
$ mkdir Contents
$ mkdir Contents/Resources
$ mkdir Contents/Plugins
Copy Ogre plugins from Ogre SDK to Plugins subdir:
$ cp /path/to/ogre/sdk/lib/*.dylib Contents/Plugins
Create symlink to resources subdirectory:
$ ln -s resources Contents/Resources/resources
Create symlinks for *.cfg files:
$ ln -s plugins.cfg Contents/MacOS/plugins.cfg
$ ln -s openmw.cfg Contents/MacOS/openmw.cfg
12. Move your Morrowind `Data Files` directory into the `Contents/Resources`
with the name `data` or create symlink:
$ ln -s /path/to/morrowind/data/files Contents/Resources/data
13. From your build directory run:
$ ./openmw
Enjoy!
14. Optionally you can create .app bundle:
$ make package
But for now you shold manually copy Contents directory from build directory to bundle
(because there is no plugins and resources in generated .app).
[boost]: http://www.boost.org
[Ogre]: http://www.ogre3d.org
[Bullet]: http://bulletphysics.org
[OIS]: http://wgois.sf.net
[mpg123]: http://www.mpg123.de
[libsndfile]: http://www.mega-nerd.com/libsndfile
[official website]: http://openmw.com
[Will Thimbleby's Ogre Framework]: http://www.thimbleby.net/ogre/

@ -354,45 +354,45 @@ struct option
/* Names for the values of the `has_arg' field of `struct option'. */
#ifndef no_argument
#define no_argument 0
#define no_argument 0
#endif
#ifndef required_argument
#define required_argument 1
#define required_argument 1
#endif
#ifndef optional_argument
#define optional_argument 2
#define optional_argument 2
#endif
struct custom_getopt_data {
/*
* These have exactly the same meaning as the corresponding global variables,
* except that they are used for the reentrant versions of getopt.
*/
int custom_optind;
int custom_opterr;
int custom_optopt;
char *custom_optarg;
/* True if the internal members have been initialized. */
int initialized;
/*
* The next char to be scanned in the option-element in which the last option
* character we returned was found. This allows us to pick up the scan where
* we left off. If this is zero, or a null string, it means resume the scan by
* advancing to the next ARGV-element.
*/
char *nextchar;
/*
* Describe the part of ARGV that contains non-options that have been skipped.
* `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is
* the index after the last of them.
*/
int first_nonopt;
int last_nonopt;
/*
* These have exactly the same meaning as the corresponding global variables,
* except that they are used for the reentrant versions of getopt.
*/
int custom_optind;
int custom_opterr;
int custom_optopt;
char *custom_optarg;
/* True if the internal members have been initialized. */
int initialized;
/*
* The next char to be scanned in the option-element in which the last option
* character we returned was found. This allows us to pick up the scan where
* we left off. If this is zero, or a null string, it means resume the scan by
* advancing to the next ARGV-element.
*/
char *nextchar;
/*
* Describe the part of ARGV that contains non-options that have been skipped.
* `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is
* the index after the last of them.
*/
int first_nonopt;
int last_nonopt;
};
/*
@ -448,137 +448,137 @@ static int custom_optopt = '?';
*/
static void exchange(char **argv, struct custom_getopt_data *d)
{
int bottom = d->first_nonopt;
int middle = d->last_nonopt;
int top = d->custom_optind;
char *tem;
/*
* Exchange the shorter segment with the far end of the longer segment.
* That puts the shorter segment into the right place. It leaves the
* longer segment in the right place overall, but it consists of two
* parts that need to be swapped next.
*/
while (top > middle && middle > bottom) {
if (top - middle > middle - bottom) {
/* Bottom segment is the short one. */
int len = middle - bottom;
int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] =
argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
} else {
/* Top segment is the short one. */
int len = top - middle;
int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
d->first_nonopt += (d->custom_optind - d->last_nonopt);
d->last_nonopt = d->custom_optind;
int bottom = d->first_nonopt;
int middle = d->last_nonopt;
int top = d->custom_optind;
char *tem;
/*
* Exchange the shorter segment with the far end of the longer segment.
* That puts the shorter segment into the right place. It leaves the
* longer segment in the right place overall, but it consists of two
* parts that need to be swapped next.
*/
while (top > middle && middle > bottom) {
if (top - middle > middle - bottom) {
/* Bottom segment is the short one. */
int len = middle - bottom;
int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] =
argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
} else {
/* Top segment is the short one. */
int len = top - middle;
int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++) {
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
d->first_nonopt += (d->custom_optind - d->last_nonopt);
d->last_nonopt = d->custom_optind;
}
/* Initialize the internal data when the first call is made. */
static void custom_getopt_initialize(struct custom_getopt_data *d)
{
/*
* Start processing options with ARGV-element 1 (since ARGV-element 0
* is the program name); the sequence of previously skipped non-option
* ARGV-elements is empty.
*/
d->first_nonopt = d->last_nonopt = d->custom_optind;
d->nextchar = NULL;
d->initialized = 1;
/*
* Start processing options with ARGV-element 1 (since ARGV-element 0
* is the program name); the sequence of previously skipped non-option
* ARGV-elements is empty.
*/
d->first_nonopt = d->last_nonopt = d->custom_optind;
d->nextchar = NULL;
d->initialized = 1;
}
#define NONOPTION_P (argv[d->custom_optind][0] != '-' || argv[d->custom_optind][1] == '\0')
/* return: zero: continue, nonzero: return given value to user */
static int shuffle_argv(int argc, char *const *argv,const struct option *longopts,
struct custom_getopt_data *d)
struct custom_getopt_data *d)
{
/*
* Give FIRST_NONOPT & LAST_NONOPT rational values if CUSTOM_OPTIND has been
* moved back by the user (who may also have changed the arguments).
*/
if (d->last_nonopt > d->custom_optind)
d->last_nonopt = d->custom_optind;
if (d->first_nonopt > d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* If we have just processed some options following some
* non-options, exchange them so that the options come first.
*/
if (d->first_nonopt != d->last_nonopt &&
d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->last_nonopt != d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* Skip any additional non-options and extend the range of
* non-options previously skipped.
*/
while (d->custom_optind < argc && NONOPTION_P)
d->custom_optind++;
d->last_nonopt = d->custom_optind;
/*
* The special ARGV-element `--' means premature end of options. Skip
* it like a null option, then exchange with previous non-options as if
* it were an option, then skip everything else like a non-option.
*/
if (d->custom_optind != argc && !strcmp(argv[d->custom_optind], "--")) {
d->custom_optind++;
if (d->first_nonopt != d->last_nonopt
&& d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->first_nonopt == d->last_nonopt)
d->first_nonopt = d->custom_optind;
d->last_nonopt = argc;
d->custom_optind = argc;
}
/*
* If we have done all the ARGV-elements, stop the scan and back over
* any non-options that we skipped and permuted.
*/
if (d->custom_optind == argc) {
/*
* Set the next-arg-index to point at the non-options that we
* previously skipped, so the caller will digest them.
*/
if (d->first_nonopt != d->last_nonopt)
d->custom_optind = d->first_nonopt;
return -1;
}
/*
* If we have come to a non-option and did not permute it, either stop
* the scan or describe it to the caller and pass it by.
*/
if (NONOPTION_P) {
d->custom_optarg = argv[d->custom_optind++];
return 1;
}
/*
* We have found another option-ARGV-element. Skip the initial
* punctuation.
*/
d->nextchar = (argv[d->custom_optind] + 1 + (longopts != NULL && argv[d->custom_optind][1] == '-'));
return 0;
/*
* Give FIRST_NONOPT & LAST_NONOPT rational values if CUSTOM_OPTIND has been
* moved back by the user (who may also have changed the arguments).
*/
if (d->last_nonopt > d->custom_optind)
d->last_nonopt = d->custom_optind;
if (d->first_nonopt > d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* If we have just processed some options following some
* non-options, exchange them so that the options come first.
*/
if (d->first_nonopt != d->last_nonopt &&
d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->last_nonopt != d->custom_optind)
d->first_nonopt = d->custom_optind;
/*
* Skip any additional non-options and extend the range of
* non-options previously skipped.
*/
while (d->custom_optind < argc && NONOPTION_P)
d->custom_optind++;
d->last_nonopt = d->custom_optind;
/*
* The special ARGV-element `--' means premature end of options. Skip
* it like a null option, then exchange with previous non-options as if
* it were an option, then skip everything else like a non-option.
*/
if (d->custom_optind != argc && !strcmp(argv[d->custom_optind], "--")) {
d->custom_optind++;
if (d->first_nonopt != d->last_nonopt
&& d->last_nonopt != d->custom_optind)
exchange((char **) argv, d);
else if (d->first_nonopt == d->last_nonopt)
d->first_nonopt = d->custom_optind;
d->last_nonopt = argc;
d->custom_optind = argc;
}
/*
* If we have done all the ARGV-elements, stop the scan and back over
* any non-options that we skipped and permuted.
*/
if (d->custom_optind == argc) {
/*
* Set the next-arg-index to point at the non-options that we
* previously skipped, so the caller will digest them.
*/
if (d->first_nonopt != d->last_nonopt)
d->custom_optind = d->first_nonopt;
return -1;
}
/*
* If we have come to a non-option and did not permute it, either stop
* the scan or describe it to the caller and pass it by.
*/
if (NONOPTION_P) {
d->custom_optarg = argv[d->custom_optind++];
return 1;
}
/*
* We have found another option-ARGV-element. Skip the initial
* punctuation.
*/
d->nextchar = (argv[d->custom_optind] + 1 + (longopts != NULL && argv[d->custom_optind][1] == '-'));
return 0;
}
/*
@ -592,180 +592,180 @@ static int shuffle_argv(int argc, char *const *argv,const struct option *longopt
*
*/
static int check_long_opt(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind,
int print_errors, struct custom_getopt_data *d)
const struct option *longopts, int *longind,
int print_errors, struct custom_getopt_data *d)
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = d->nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match or abbreviated matches */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, d->nextchar, nameend - d->nextchar)) {
if ((unsigned int) (nameend - d->nextchar)
== (unsigned int) strlen(p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
} else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
} else if (pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact) {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' is ambiguous\n",
argv[0], argv[d->custom_optind]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optind++;
d->custom_optopt = 0;
return '?';
}
if (pfound) {
option_index = indfound;
d->custom_optind++;
if (*nameend) {
if (pfound->has_arg != no_argument)
d->custom_optarg = nameend + 1;
else {
if (print_errors) {
if (argv[d->custom_optind - 1][1] == '-') {
/* --option */
fprintf(stderr, "%s: option `--%s' doesn't allow an argument\n",
argv[0], pfound->name);
} else {
/* +option or -option */
fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n",
argv[0], argv[d->custom_optind - 1][0], pfound->name);
}
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return '?';
}
} else if (pfound->has_arg == required_argument) {
if (d->custom_optind < argc)
d->custom_optarg = argv[d->custom_optind++];
else {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' requires an argument\n",
argv[0],
argv[d->custom_optind - 1]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
d->nextchar += strlen(d->nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/*
* Can't find it as a long option. If this is not getopt_long_only, or
* the option starts with '--' or is not a valid short option, then
* it's an error. Otherwise interpret it as a short option.
*/
if (print_errors) {
if (argv[d->custom_optind][1] == '-') {
/* --option */
fprintf(stderr,
"%s: unrecognized option `--%s'\n",
argv[0], d->nextchar);
} else {
/* +option or -option */
fprintf(stderr,
"%s: unrecognized option `%c%s'\n",
argv[0], argv[d->custom_optind][0],
d->nextchar);
}
}
d->nextchar = (char *) "";
d->custom_optind++;
d->custom_optopt = 0;
return '?';
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = d->nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match or abbreviated matches */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp(p->name, d->nextchar, nameend - d->nextchar)) {
if ((unsigned int) (nameend - d->nextchar)
== (unsigned int) strlen(p->name)) {
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
} else if (pfound == NULL) {
/* First nonexact match found. */
pfound = p;
indfound = option_index;
} else if (pfound->has_arg != p->has_arg
|| pfound->flag != p->flag
|| pfound->val != p->val)
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact) {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' is ambiguous\n",
argv[0], argv[d->custom_optind]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optind++;
d->custom_optopt = 0;
return '?';
}
if (pfound) {
option_index = indfound;
d->custom_optind++;
if (*nameend) {
if (pfound->has_arg != no_argument)
d->custom_optarg = nameend + 1;
else {
if (print_errors) {
if (argv[d->custom_optind - 1][1] == '-') {
/* --option */
fprintf(stderr, "%s: option `--%s' doesn't allow an argument\n",
argv[0], pfound->name);
} else {
/* +option or -option */
fprintf(stderr, "%s: option `%c%s' doesn't allow an argument\n",
argv[0], argv[d->custom_optind - 1][0], pfound->name);
}
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return '?';
}
} else if (pfound->has_arg == required_argument) {
if (d->custom_optind < argc)
d->custom_optarg = argv[d->custom_optind++];
else {
if (print_errors) {
fprintf(stderr,
"%s: option `%s' requires an argument\n",
argv[0],
argv[d->custom_optind - 1]);
}
d->nextchar += strlen(d->nextchar);
d->custom_optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
d->nextchar += strlen(d->nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag) {
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/*
* Can't find it as a long option. If this is not getopt_long_only, or
* the option starts with '--' or is not a valid short option, then
* it's an error. Otherwise interpret it as a short option.
*/
if (print_errors) {
if (argv[d->custom_optind][1] == '-') {
/* --option */
fprintf(stderr,
"%s: unrecognized option `--%s'\n",
argv[0], d->nextchar);
} else {
/* +option or -option */
fprintf(stderr,
"%s: unrecognized option `%c%s'\n",
argv[0], argv[d->custom_optind][0],
d->nextchar);
}
}
d->nextchar = (char *) "";
d->custom_optind++;
d->custom_optopt = 0;
return '?';
}
static int check_short_opt(int argc, char *const *argv, const char *optstring,
int print_errors, struct custom_getopt_data *d)
int print_errors, struct custom_getopt_data *d)
{
char c = *d->nextchar++;
const char *temp = strchr(optstring, c);
/* Increment `custom_optind' when we start to process its last character. */
if (*d->nextchar == '\0')
++d->custom_optind;
if (!temp || c == ':') {
if (print_errors)
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
d->custom_optopt = c;
return '?';
}
if (temp[1] == ':') {
if (temp[2] == ':') {
/* This is an option that accepts an argument optionally. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
d->custom_optind++;
} else
d->custom_optarg = NULL;
d->nextchar = NULL;
} else {
/* This is an option that requires an argument. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
/*
* If we end this ARGV-element by taking the
* rest as an arg, we must advance to the next
* element now.
*/
d->custom_optind++;
} else if (d->custom_optind == argc) {
if (print_errors) {
fprintf(stderr,
"%s: option requires an argument -- %c\n",
argv[0], c);
}
d->custom_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
} else
/*
* We already incremented `custom_optind' once;
* increment it again when taking next ARGV-elt
* as argument.
*/
d->custom_optarg = argv[d->custom_optind++];
d->nextchar = NULL;
}
}
return c;
char c = *d->nextchar++;
const char *temp = strchr(optstring, c);
/* Increment `custom_optind' when we start to process its last character. */
if (*d->nextchar == '\0')
++d->custom_optind;
if (!temp || c == ':') {
if (print_errors)
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
d->custom_optopt = c;
return '?';
}
if (temp[1] == ':') {
if (temp[2] == ':') {
/* This is an option that accepts an argument optionally. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
d->custom_optind++;
} else
d->custom_optarg = NULL;
d->nextchar = NULL;
} else {
/* This is an option that requires an argument. */
if (*d->nextchar != '\0') {
d->custom_optarg = d->nextchar;
/*
* If we end this ARGV-element by taking the
* rest as an arg, we must advance to the next
* element now.
*/
d->custom_optind++;
} else if (d->custom_optind == argc) {
if (print_errors) {
fprintf(stderr,
"%s: option requires an argument -- %c\n",
argv[0], c);
}
d->custom_optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
} else
/*
* We already incremented `custom_optind' once;
* increment it again when taking next ARGV-elt
* as argument.
*/
d->custom_optarg = argv[d->custom_optind++];
d->nextchar = NULL;
}
}
return c;
}
/*
@ -839,59 +839,59 @@ static int check_short_opt(int argc, char *const *argv, const char *optstring,
*/
static int getopt_internal_r(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind,
struct custom_getopt_data *d)
const struct option *longopts, int *longind,
struct custom_getopt_data *d)
{
int ret, print_errors = d->custom_opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
d->custom_optarg = NULL;
/*
* This is a big difference with GNU getopt, since optind == 0
* means initialization while here 1 means first call.
*/
if (d->custom_optind == 0 || !d->initialized) {
if (d->custom_optind == 0)
d->custom_optind = 1; /* Don't scan ARGV[0], the program name. */
custom_getopt_initialize(d);
}
if (d->nextchar == NULL || *d->nextchar == '\0') {
ret = shuffle_argv(argc, argv, longopts, d);
if (ret)
return ret;
}
if (longopts && (argv[d->custom_optind][1] == '-' ))
return check_long_opt(argc, argv, optstring, longopts,
longind, print_errors, d);
return check_short_opt(argc, argv, optstring, print_errors, d);
int ret, print_errors = d->custom_opterr;
if (optstring[0] == ':')
print_errors = 0;
if (argc < 1)
return -1;
d->custom_optarg = NULL;
/*
* This is a big difference with GNU getopt, since optind == 0
* means initialization while here 1 means first call.
*/
if (d->custom_optind == 0 || !d->initialized) {
if (d->custom_optind == 0)
d->custom_optind = 1; /* Don't scan ARGV[0], the program name. */
custom_getopt_initialize(d);
}
if (d->nextchar == NULL || *d->nextchar == '\0') {
ret = shuffle_argv(argc, argv, longopts, d);
if (ret)
return ret;
}
if (longopts && (argv[d->custom_optind][1] == '-' ))
return check_long_opt(argc, argv, optstring, longopts,
longind, print_errors, d);
return check_short_opt(argc, argv, optstring, print_errors, d);
}
static int custom_getopt_internal(int argc, char *const *argv, const char *optstring,
const struct option *longopts, int *longind)
const struct option *longopts, int *longind)
{
int result;
/* Keep a global copy of all internal members of d */
static struct custom_getopt_data d;
d.custom_optind = custom_optind;
d.custom_opterr = custom_opterr;
result = getopt_internal_r(argc, argv, optstring, longopts,
longind, &d);
custom_optind = d.custom_optind;
custom_optarg = d.custom_optarg;
custom_optopt = d.custom_optopt;
return result;
int result;
/* Keep a global copy of all internal members of d */
static struct custom_getopt_data d;
d.custom_optind = custom_optind;
d.custom_opterr = custom_opterr;
result = getopt_internal_r(argc, argv, optstring, longopts,
longind, &d);
custom_optind = d.custom_optind;
custom_optarg = d.custom_optarg;
custom_optopt = d.custom_optopt;
return result;
}
static int custom_getopt_long (int argc, char *const *argv, const char *options,
const struct option *long_options, int *opt_index)
const struct option *long_options, int *opt_index)
{
return custom_getopt_internal(argc, argv, options, long_options,
opt_index);
return custom_getopt_internal(argc, argv, options, long_options,
opt_index);
}
@ -989,7 +989,7 @@ cmdline_parser_internal (
int argc, char * const *argv, struct gengetopt_args_info *args_info,
struct cmdline_parser_params *params, const char *additional_error)
{
int c; /* Character of the parsed option. */
int c; /* Character of the parsed option. */
int error = 0;
struct gengetopt_args_info local_args_info;
@ -1026,11 +1026,11 @@ cmdline_parser_internal (
int option_index = 0;
static struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "version", 0, NULL, 'V' },
{ "raw", 0, NULL, 'r' },
{ "quiet", 0, NULL, 'q' },
{ "loadcells", 0, NULL, 'C' },
{ "help", 0, NULL, 'h' },
{ "version", 0, NULL, 'V' },
{ "raw", 0, NULL, 'r' },
{ "quiet", 0, NULL, 'q' },
{ "loadcells", 0, NULL, 'C' },
{ 0, 0, 0, 0 }
};
@ -1046,21 +1046,21 @@ cmdline_parser_internal (
opterr = custom_opterr;
optopt = custom_optopt;
if (c == -1) break; /* Exit from `while (1)' loop. */
if (c == -1) break; /* Exit from `while (1)' loop. */
switch (c)
{
case 'h': /* Print help and exit. */
case 'h': /* Print help and exit. */
cmdline_parser_print_help ();
cmdline_parser_free (&local_args_info);
exit (EXIT_SUCCESS);
case 'V': /* Print version and exit. */
case 'V': /* Print version and exit. */
cmdline_parser_print_version ();
cmdline_parser_free (&local_args_info);
exit (EXIT_SUCCESS);
case 'r': /* Show an unformattet list of all records and subrecords. */
case 'r': /* Show an unformattet list of all records and subrecords. */
if (update_arg( 0 ,
@ -1072,7 +1072,7 @@ cmdline_parser_internal (
goto failure;
break;
case 'q': /* Supress all record information. Useful for speed tests.. */
case 'q': /* Supress all record information. Useful for speed tests.. */
if (update_arg( 0 ,
@ -1084,7 +1084,7 @@ cmdline_parser_internal (
goto failure;
break;
case 'C': /* Browse through contents of all cells.. */
case 'C': /* Browse through contents of all cells.. */
if (update_arg( 0 ,
@ -1097,12 +1097,12 @@ cmdline_parser_internal (
break;
case 0: /* Long option with no short option */
case '?': /* Invalid option. */
case 0: /* Long option with no short option */
case '?': /* Invalid option. */
/* `getopt_long' already printed an error message. */
goto failure;
default: /* bug: option not considered. */
default: /* bug: option not considered. */
fprintf (stderr, "%s: option unknown: %c%s\n", CMDLINE_PARSER_PACKAGE, c, (additional_error ? additional_error : ""));
abort ();
} /* switch */

@ -43,11 +43,11 @@ struct gengetopt_args_info
const char *quiet_help; /**< @brief Supress all record information. Useful for speed tests. help description. */
const char *loadcells_help; /**< @brief Browse through contents of all cells. help description. */
unsigned int help_given ; /**< @brief Whether help was given. */
unsigned int version_given ; /**< @brief Whether version was given. */
unsigned int raw_given ; /**< @brief Whether raw was given. */
unsigned int quiet_given ; /**< @brief Whether quiet was given. */
unsigned int loadcells_given ; /**< @brief Whether loadcells was given. */
unsigned int help_given ; /**< @brief Whether help was given. */
unsigned int version_given ; /**< @brief Whether version was given. */
unsigned int raw_given ; /**< @brief Whether raw was given. */
unsigned int quiet_given ; /**< @brief Whether quiet was given. */
unsigned int loadcells_given ; /**< @brief Whether loadcells was given. */
char **inputs ; /**< @brief unamed options (options without names) */
unsigned inputs_num ; /**< @brief unamed options number */

@ -4,7 +4,8 @@ project(OpenMW)
set(GAME
main.cpp
engine.cpp)
engine.cpp
path.cpp)
set(GAME_HEADER
engine.hpp)
source_group(game FILES ${GAME} ${GAME_HEADER})
@ -14,16 +15,18 @@ set(GAMEREND
mwrender/cellimp.cpp
mwrender/interior.cpp
mwrender/exterior.cpp
mwrender/playerpos.cpp
mwrender/sky.cpp)
mwrender/sky.cpp
mwrender/player.cpp
)
set(GAMEREND_HEADER
mwrender/cell.hpp
mwrender/cellimp.hpp
mwrender/mwscene.hpp
mwrender/interior.hpp
mwrender/exterior.hpp
mwrender/playerpos.hpp
mwrender/sky.hpp)
mwrender/sky.hpp
mwrender/player.hpp
)
source_group(apps\\openmw\\mwrender FILES ${GAMEREND} ${GAMEREND_HEADER})
set(GAMEINPUT
@ -46,6 +49,7 @@ set(GAMEGUI_HEADER
mwgui/dialogue.hpp
mwgui/dialogue_history.hpp
mwgui/window_base.hpp
mwgui/stats_window.hpp
)
set(GAMEGUI
mwgui/window_manager.cpp
@ -60,6 +64,7 @@ set(GAMEGUI
mwgui/dialogue.cpp
mwgui/dialogue_history.cpp
mwgui/window_base.cpp
mwgui/stats_window.cpp
)
source_group(apps\\openmw\\mwgui FILES ${GAMEGUI_HEADER} ${GAMEGUI})
@ -103,6 +108,7 @@ set(GAMESCRIPT_HEADER
mwscript/controlextensions.hpp
mwscript/extensions.hpp
mwscript/globalscripts.hpp
mwscript/ref.hpp
)
source_group(apps\\openmw\\mwscript FILES ${GAMESCRIPT} ${GAMESCRIPT_HEADER})
@ -120,6 +126,8 @@ set(GAMEWORLD
mwworld/actiontalk.cpp
mwworld/actiontake.cpp
mwworld/containerutil.cpp
mwworld/player.cpp
mwworld/doingphysics.cpp
)
set(GAMEWORLD_HEADER
mwworld/refdata.hpp
@ -137,6 +145,9 @@ set(GAMEWORLD_HEADER
mwworld/containerstore.hpp
mwworld/manualref.hpp
mwworld/containerutil.hpp
mwworld/player.hpp
mwworld/doingphysics.hpp
mwworld/cellfunctors.hpp
)
source_group(apps\\openmw\\mwworld FILES ${GAMEWORLD} ${GAMEWORLD_HEADER})
@ -198,6 +209,7 @@ set(GAMEMECHANICS_HEADER
mwmechanics/stat.hpp
mwmechanics/creaturestats.hpp
mwmechanics/magiceffects.hpp
mwmechanics/movement.hpp
)
source_group(apps\\openmw\\mwmechanics FILES ${GAMEMECHANICS} ${GAMEMECHANICS_HEADER})
@ -219,7 +231,7 @@ add_executable(openmw
# Sound stuff - here so CMake doesn't stupidly recompile EVERYTHING
# when we change the backend.
include_directories(${SOUND_INPUT_INCLUDES})
include_directories(${SOUND_INPUT_INCLUDES} ${BULLET_INCLUDE_DIRS})
add_definitions(${SOUND_DEFINE})
target_link_libraries(openmw
@ -228,6 +240,7 @@ target_link_libraries(openmw
${Boost_LIBRARIES}
${OPENAL_LIBRARY}
${SOUND_INPUT_LIBRARY}
${BULLET_LIBRARIES}
caelum
MyGUIEngine
MyGUIOgrePlatform
@ -236,4 +249,12 @@ target_link_libraries(openmw
if (APPLE)
find_library(CARBON_FRAMEWORK Carbon)
target_link_libraries(openmw ${CARBON_FRAMEWORK})
install(TARGETS openmw
BUNDLE DESTINATION .
RUNTIME DESTINATION ../MacOS
COMPONENT Runtime)
endif (APPLE)
if(DPKG_PROGRAM)
INSTALL(TARGETS openmw RUNTIME DESTINATION games COMPONENT openmw)
endif()

@ -6,6 +6,8 @@
#include <iostream>
#include <utility>
#include <OgreVector3.h>
#include "components/esm/records.hpp"
#include <components/esm_store/cell_store.hpp>
#include <components/misc/fileops.hpp>
@ -29,6 +31,7 @@
#include "mwworld/ptr.hpp"
#include "mwworld/environment.hpp"
#include "mwworld/class.hpp"
#include "mwworld/player.hpp"
#include "mwclass/classes.hpp"
@ -38,11 +41,15 @@
#include <OgreRoot.h>
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <OSX/macUtils.h>
#endif
#include <MyGUI_WidgetManager.h>
#include "mwgui/class.hpp"
#include "path.hpp"
#include "components/nifbullet/bullet_nif_loader.hpp"
//using namespace ESM;
@ -69,73 +76,76 @@ void OMW::Engine::executeLocalScripts()
bool OMW::Engine::frameStarted(const Ogre::FrameEvent& evt)
{
if(! (mEnvironment.mSoundManager->isMusicPlaying()))
{
// Play some good 'ol tunes
mEnvironment.mSoundManager->startRandomTitle();
}
std::string effect;
MWWorld::Ptr::CellStore *current = mEnvironment.mWorld->getPlayerPos().getPlayer().getCell();
//If the region has changed
if(!(current->cell->data.flags & current->cell->Interior) && timer.elapsed() >= 10){
timer.restart();
if (test.name != current->cell->region)
{
total = 0;
test = (ESM::Region) *(mEnvironment.mWorld->getStore().regions.find(current->cell->region));
}
if(test.soundList.size() > 0)
{
std::vector<ESM::Region::SoundRef>::iterator soundIter = test.soundList.begin();
//mEnvironment.mSoundManager
if(total == 0){
while (!(soundIter == test.soundList.end()))
{
ESM::NAME32 go = soundIter->sound;
int chance = (int) soundIter->chance;
//std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
soundIter++;
total += chance;
}
}
srand ( time(NULL) );
int r = rand() % total; //old random code
int pos = 0;
soundIter = test.soundList.begin();
while (!(soundIter == test.soundList.end()))
{
const ESM::NAME32 go = soundIter->sound;
int chance = (int) soundIter->chance;
//std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
soundIter++;
if( r - pos < chance)
{
effect = go.name;
//play sound
std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
mEnvironment.mSoundManager->playSound(effect, 20.0, 1.0);
break;
}
pos += chance;
}
}
//mEnvironment.mSoundManager->playSound(effect, 1.0, 1.0);
//printf("REGION: %s\n", test.name);
}
else if(current->cell->data.flags & current->cell->Interior)
{
test.name = "";
}
if(mShowFPS)
{
mEnvironment.mWindowManager->wmSetFPS(mOgre.getFPS());
}
if(mUseSound && !(mEnvironment.mSoundManager->isMusicPlaying()))
{
// Play some good 'ol tunes
mEnvironment.mSoundManager->startRandomTitle();
}
std::string effect;
MWWorld::Ptr::CellStore *current = mEnvironment.mWorld->getPlayer().getPlayer().getCell();
//If the region has changed
if(!(current->cell->data.flags & current->cell->Interior) && timer.elapsed() >= 10){
timer.restart();
if (test.name != current->cell->region)
{
total = 0;
test = (ESM::Region) *(mEnvironment.mWorld->getStore().regions.find(current->cell->region));
}
if(test.soundList.size() > 0)
{
std::vector<ESM::Region::SoundRef>::iterator soundIter = test.soundList.begin();
//mEnvironment.mSoundManager
if(total == 0){
while (!(soundIter == test.soundList.end()))
{
ESM::NAME32 go = soundIter->sound;
int chance = (int) soundIter->chance;
//std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
soundIter++;
total += chance;
}
}
srand ( time(NULL) );
int r = rand() % total; //old random code
int pos = 0;
soundIter = test.soundList.begin();
while (!(soundIter == test.soundList.end()))
{
const ESM::NAME32 go = soundIter->sound;
int chance = (int) soundIter->chance;
//std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
soundIter++;
if( r - pos < chance)
{
effect = go.name;
//play sound
std::cout << "Sound: " << go.name <<" Chance:" << chance << "\n";
mEnvironment.mSoundManager->playSound(effect, 20.0, 1.0);
break;
}
pos += chance;
}
}
//mEnvironment.mSoundManager->playSound(effect, 1.0, 1.0);
//printf("REGION: %s\n", test.name);
}
else if(current->cell->data.flags & current->cell->Interior)
{
test.name = "";
}
try
{
@ -160,7 +170,8 @@ bool OMW::Engine::frameStarted(const Ogre::FrameEvent& evt)
mEnvironment.mWorld->markCellAsUnchanged();
// update actors
mEnvironment.mMechanicsManager->update();
std::vector<std::pair<std::string, Ogre::Vector3> > movement;
mEnvironment.mMechanicsManager->update (movement);
if (focusFrameCounter++ == focusUpdateFrame)
{
@ -181,21 +192,27 @@ bool OMW::Engine::frameStarted(const Ogre::FrameEvent& evt)
focusFrameCounter = 0;
}
if (mEnvironment.mWindowManager->getMode()==MWGui::GM_Game)
mEnvironment.mWorld->doPhysics (movement, mEnvironment.mFrameDuration);
}
catch (const std::exception& e)
{
std::cerr << "Error in framelistener: " << e.what() << std::endl;
}
//std::cout << "TESTING2";
//std::cout << "TESTING2";
return true;
}
OMW::Engine::Engine()
: mDebug (false)
: mPhysicEngine (0)
, mShowFPS (false)
, mDebug (false)
, mVerboseScripts (false)
, mNewGame (false)
, mUseSound (true)
, mCompileAll (false)
, mScriptManager (0)
, mScriptContext (0)
, mGuiManager (0)
@ -213,6 +230,7 @@ OMW::Engine::~Engine()
delete mEnvironment.mDialogueManager;
delete mScriptManager;
delete mScriptContext;
delete mPhysicEngine;
}
// Load all BSA files in data directory.
@ -226,7 +244,7 @@ void OMW::Engine::loadBSA()
if (boost::filesystem::extension (iter->path())==".bsa")
{
std::cout << "Adding " << iter->path().string() << std::endl;
addBSA(iter->path().file_string());
addBSA(iter->path().string());
}
}
}
@ -236,7 +254,7 @@ void OMW::Engine::loadBSA()
void OMW::Engine::addResourcesDirectory (const boost::filesystem::path& path)
{
mOgre.getRoot()->addResourceLocation (path.file_string(), "FileSystem",
mOgre.getRoot()->addResourceLocation (path.string(), "FileSystem",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true);
}
@ -247,6 +265,12 @@ void OMW::Engine::setDataDir (const boost::filesystem::path& dataDir)
mDataDir = boost::filesystem::system_complete (dataDir);
}
// Set resource dir
void OMW::Engine::setResourceDir (const boost::filesystem::path& parResDir)
{
mResDir = boost::filesystem::system_complete(parResDir);
}
// Set start cell name (only interiors for now)
void OMW::Engine::setCell (const std::string& cellName)
@ -295,55 +319,60 @@ void OMW::Engine::go()
assert (!mCellName.empty());
assert (!mMaster.empty());
test.name = "";
total = 0;
test.name = "";
total = 0;
std::cout << "Data directory: " << mDataDir << "\n";
const char* plugCfg = "plugins.cfg";
std::string cfgDir = OMW::Path::getPath(OMW::Path::GLOBAL_CFG_PATH, "openmw", "");
std::string cfgUserDir = OMW::Path::getPath(OMW::Path::USER_CFG_PATH, "openmw", "");
std::string plugCfg = "plugins.cfg";
std::string ogreCfg = "ogre.cfg";
ogreCfg.insert(0, cfgUserDir);
//A local plugins.cfg will be used if it exist, otherwise look in the default path
if(!isFile(plugCfg.c_str()))
{
plugCfg.insert(0, cfgDir);
}
mOgre.configure(!isFile("ogre.cfg"), plugCfg, false);
mOgre.configure(!isFile(ogreCfg.c_str()), cfgUserDir, plugCfg, false);
addResourcesDirectory (mDataDir / "Meshes");
addResourcesDirectory (mDataDir / "Textures");
//boost::filesystem::copy_file("meshes\\b\\B_N_Argonian_F_Skins.nif",mDataDir / "b2\\B_N_Argonian_F_Skins.nif",boost::filesystem::copy_option::overwrite_if_exists);
/*CFileOperation fo; // create object
fo.SetOverwriteMode(false); // reset OverwriteMode flag (optional)
if (!fo.Copy("c:\\source", "c:\\dest")) // do Copy
{
fo.ShowError(); // if copy fails show error message
}*/
// This has to be added BEFORE MyGUI is initialized, as it needs
// to find core.xml here.
addResourcesDirectory("resources/mygui/");
addResourcesDirectory(mResDir / "mygui");
// Create the window
mOgre.createWindow("OpenMW");
loadBSA();
// Create physics. shapeLoader is deleted by the physic engine
ManualBulletShapeLoader* shapeLoader = new ManualBulletShapeLoader();
mPhysicEngine = new OEngine::Physic::PhysicEngine(shapeLoader);
// Create the world
mEnvironment.mWorld = new MWWorld::World (mOgre, mDataDir, mMaster, mNewGame, mEnvironment);
mEnvironment.mWorld = new MWWorld::World (mOgre, mPhysicEngine, mDataDir, mMaster, mResDir, mNewGame, mEnvironment);
// Set up the GUI system
mGuiManager = new OEngine::GUI::MyGUIManager(mOgre.getWindow(),
mOgre.getScene());
mGuiManager = new OEngine::GUI::MyGUIManager(mOgre.getWindow(), mOgre.getScene(), false, cfgDir);
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSkill>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWAttribute>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSpell>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWSpellEffect>("Widget");
MyGUI::FactoryManager::getInstance().registerFactory<MWGui::Widgets::MWDynamicStat>("Widget");
// Create window manager - this manages all the MW-specific GUI windows
MWScript::registerExtensions (mExtensions);
mEnvironment.mWindowManager = new MWGui::WindowManager(mGuiManager->getGui(), mEnvironment,
mExtensions, mNewGame);
mExtensions, mShowFPS, mNewGame);
// Create sound system
mEnvironment.mSoundManager = new MWSound::SoundManager(mOgre.getRoot(),
@ -371,12 +400,23 @@ void OMW::Engine::go()
// load cell
ESM::Position pos;
pos.pos[0] = pos.pos[1] = pos.pos[2] = 0;
pos.rot[0] = pos.rot[1] = pos.rot[2] = 0;
mEnvironment.mWorld->changeCell (mCellName, pos);
pos.pos[2] = 0;
if (const ESM::Cell *exterior = mEnvironment.mWorld->getExterior (mCellName))
{
mEnvironment.mWorld->indexToPosition (exterior->data.gridX, exterior->data.gridY,
pos.pos[0], pos.pos[1], true);
mEnvironment.mWorld->changeToExteriorCell (pos);
}
else
{
pos.pos[0] = pos.pos[1] = 0;
mEnvironment.mWorld->changeToInteriorCell (mCellName, pos);
}
// Sets up the input system
MWInput::MWInputManager input(mOgre, mEnvironment.mWorld->getPlayerPos(),
MWInput::MWInputManager input(mOgre, mEnvironment.mWorld->getPlayer(),
*mEnvironment.mWindowManager, mDebug, *this);
mEnvironment.mInputManager = &input;
@ -389,6 +429,29 @@ void OMW::Engine::go()
// Play some good 'ol tunes
mEnvironment.mSoundManager->startRandomTitle();
// scripts
if (mCompileAll)
{
typedef ESMS::ScriptListT<ESM::Script>::MapType Container;
Container scripts = mEnvironment.mWorld->getStore().scripts.list;
int count = 0;
int success = 0;
for (Container::const_iterator iter (scripts.begin()); iter!=scripts.end(); ++iter, ++count)
if (mScriptManager->compile (iter->first))
++success;
if (count)
std::cout
<< "compiled " << success << " of " << count << " scripts ("
<< 100*static_cast<double> (success)/count
<< "%)"
<< std::endl;
}
// Start the main rendering loop
mOgre.start();
@ -397,35 +460,49 @@ void OMW::Engine::go()
void OMW::Engine::activate()
{
std::string handle = mEnvironment.mWorld->getFacedHandle();
// TODO: This is only a workaround. The input dispatcher should catch any exceptions thrown inside
// the input handling functions. Looks like this will require an OpenEngine modification.
try
{
std::string handle = mEnvironment.mWorld->getFacedHandle();
if (handle.empty())
return;
if (handle.empty())
return;
MWWorld::Ptr ptr = mEnvironment.mWorld->getPtrViaHandle (handle);
MWWorld::Ptr ptr = mEnvironment.mWorld->getPtrViaHandle (handle);
if (ptr.isEmpty())
return;
if (ptr.isEmpty())
return;
MWScript::InterpreterContext interpreterContext (mEnvironment,
&ptr.getRefData().getLocals(), ptr);
MWScript::InterpreterContext interpreterContext (mEnvironment,
&ptr.getRefData().getLocals(), ptr);
boost::shared_ptr<MWWorld::Action> action =
MWWorld::Class::get (ptr).activate (ptr, mEnvironment.mWorld->getPlayerPos().getPlayer(),
mEnvironment);
boost::shared_ptr<MWWorld::Action> action =
MWWorld::Class::get (ptr).activate (ptr, mEnvironment.mWorld->getPlayer().getPlayer(),
mEnvironment);
interpreterContext.activate (ptr, action);
interpreterContext.activate (ptr, action);
std::string script = MWWorld::Class::get (ptr).getScript (ptr);
std::string script = MWWorld::Class::get (ptr).getScript (ptr);
if (!script.empty())
{
mIgnoreLocalPtr = ptr;
mScriptManager->run (script, interpreterContext);
}
if (!script.empty())
{
mIgnoreLocalPtr = ptr;
mScriptManager->run (script, interpreterContext);
}
if (!interpreterContext.hasActivationBeenHandled())
if (!interpreterContext.hasActivationBeenHandled())
{
interpreterContext.executeActivation();
}
}
catch (const std::exception& e)
{
interpreterContext.executeActivation();
std::cerr << "Activation failed: " << e.what() << std::endl;
}
}
void OMW::Engine::setCompileAll (bool all)
{
mCompileAll = all;
}

@ -8,6 +8,7 @@
#include <OgreFrameListener.h>
#include <openengine/ogre/renderer.hpp>
#include <openengine/bullet/physic.hpp>
#include <components/compiler/extensions.hpp>
#include "mwworld/environment.hpp"
@ -55,11 +56,14 @@ namespace OMW
class Engine : private Ogre::FrameListener
{
//int nFiles;
//int nFiles;
boost::filesystem::path mDataDir;
boost::filesystem::path mResDir;
OEngine::Render::OgreRenderer mOgre;
OEngine::Physic::PhysicEngine* mPhysicEngine;
std::string mCellName;
std::string mMaster;
bool mShowFPS;
bool mDebug;
bool mVerboseScripts;
bool mNewGame;
@ -72,8 +76,8 @@ namespace OMW
Compiler::Extensions mExtensions;
Compiler::Context *mScriptContext;
OEngine::GUI::MyGUIManager *mGuiManager;
ESM::Region test;
boost::timer timer;
ESM::Region test;
boost::timer timer;
int focusFrameCounter;
static const int focusUpdateFrame = 10;
@ -107,6 +111,9 @@ namespace OMW
/// Set data dir
void setDataDir (const boost::filesystem::path& dataDir);
/// Set resource dir
void setResourceDir (const boost::filesystem::path& parResDir);
/// Set start cell name (only interiors for now)
void setCell (const std::string& cellName);
@ -115,6 +122,9 @@ namespace OMW
/// - Currently OpenMW only supports one master at the same time.
void addMaster (const std::string& master);
/// Enable fps counter
void showFPS() { mShowFPS = true; }
/// Enable debug mode:
/// - non-exclusive input
void enableDebugMode();

@ -7,9 +7,10 @@
#include <components/misc/fileops.hpp>
#include "engine.hpp"
#include "path.hpp"
#if defined(_WIN32) && !defined(_CONSOLE)
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream_buffer.hpp>
# if !defined(_DEBUG)
@ -42,10 +43,13 @@ bool parseOptions (int argc, char**argv, OMW::Engine& engine)
("help", "print help message")
("data", bpo::value<std::string>()->default_value ("data"),
"set data directory")
("resources", bpo::value<std::string>()->default_value ("resources"),
"set resources directory")
("start", bpo::value<std::string>()->default_value ("Beshara"),
"set initial cell")
("master", bpo::value<std::string>()->default_value ("Morrowind"),
"master file")
( "showfps", "show fps counter")
( "debug", "debug mode" )
( "nosound", "disable all sound" )
( "script-verbose", "verbose script output" )
@ -55,20 +59,23 @@ bool parseOptions (int argc, char**argv, OMW::Engine& engine)
bpo::variables_map variables;
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
std::string configFilePath(macBundlePath() + "/Contents/MacOS/openmw.cfg");
std::ifstream configFile (configFilePath.c_str());
#else
std::ifstream configFile ("openmw.cfg");
#endif
std::string cfgFile = OMW::Path::getPath(OMW::Path::GLOBAL_CFG_PATH, "openmw", "openmw.cfg");
std::cout << "Using global config file: " << cfgFile << std::endl;
std::ifstream globalConfigFile(cfgFile.c_str());
cfgFile = OMW::Path::getPath(OMW::Path::USER_CFG_PATH, "openmw", "openmw.cfg");
std::cout << "Using user config file: " << cfgFile << std::endl;
std::ifstream userConfigFile(cfgFile.c_str());
bpo::parsed_options valid_opts = bpo::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
bpo::store(valid_opts, variables);
bpo::notify(variables);
if (configFile.is_open())
bpo::store ( bpo::parse_config_file (configFile, desc), variables);
if (userConfigFile.is_open())
bpo::store ( bpo::parse_config_file (userConfigFile, desc), variables);
if (globalConfigFile.is_open())
bpo::store ( bpo::parse_config_file (globalConfigFile, desc), variables);
if (variables.count ("help"))
{
@ -77,9 +84,13 @@ bool parseOptions (int argc, char**argv, OMW::Engine& engine)
}
engine.setDataDir (variables["data"].as<std::string>());
engine.setResourceDir (variables["resources"].as<std::string>());
engine.setCell (variables["start"].as<std::string>());
engine.addMaster (variables["master"].as<std::string>());
if (variables.count ("showfps"))
engine.showFPS();
if (variables.count ("debug"))
engine.enableDebugMode();
@ -100,6 +111,11 @@ bool parseOptions (int argc, char**argv, OMW::Engine& engine)
int main(int argc, char**argv)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
// set current dir to bundle path
boost::filesystem::path bundlePath = boost::filesystem::path(Ogre::macBundlePath());
boost::filesystem::current_path(bundlePath);
#endif
try
{

@ -23,6 +23,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -23,6 +23,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -35,6 +35,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertActorPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}
@ -90,7 +91,7 @@ namespace MWClass
const MWWorld::Ptr& actor, const MWWorld::Environment& environment) const
{
return boost::shared_ptr<MWWorld::Action> (new MWWorld::ActionTalk (ptr));
}
}
MWWorld::ContainerStore<MWWorld::RefData>& Creature::getContainerStore (const MWWorld::Ptr& ptr)
const
@ -106,7 +107,7 @@ namespace MWClass
}
return *ptr.getRefData().getContainerStore();
}
}
std::string Creature::getScript (const MWWorld::Ptr& ptr) const
{

@ -5,8 +5,7 @@
#include <components/esm_store/cell_store.hpp>
#include "../mwrender/playerpos.hpp"
#include "../mwworld/player.hpp"
#include "../mwworld/ptr.hpp"
#include "../mwworld/nullaction.hpp"
#include "../mwworld/actionteleport.hpp"
@ -31,6 +30,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}
@ -65,7 +65,7 @@ namespace MWClass
if (ref->ref.teleport)
{
// teleport door
if (environment.mWorld->getPlayerPos().getPlayer()==actor)
if (environment.mWorld->getPlayer().getPlayer()==actor)
{
// the player is using the door
return boost::shared_ptr<MWWorld::Action> (

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -31,6 +31,7 @@ namespace MWClass
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
// Extract the color and convert to floating point
const int color = ref->base->data.color;

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -16,6 +16,12 @@
#include "../mwmechanics/mechanicsmanager.hpp"
#include <OgreSceneNode.h>
namespace
{
const Ogre::Radian kOgrePi (Ogre::Math::PI);
const Ogre::Radian kOgrePiOverTwo (Ogre::Math::PI / Ogre::Real(2.0));
}
namespace MWClass
{
std::string Npc::getId (const MWWorld::Ptr& ptr) const
@ -29,227 +35,236 @@ namespace MWClass
void Npc::insertObj (const MWWorld::Ptr& ptr, MWRender::CellRenderImp& cellRender,
MWWorld::Environment& environment) const
{
//Ogre::SceneNode *chest;
//Ogre::SceneNode *chest;
ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> *ref =
ptr.get<ESM::NPC>();
//Store scenenodes by npc's name + bodypart [0] , npc's name + bodypart [1]
//Ex. Fargothchest , Fargothneck
//Store scenenodes by npc's name + bodypart [0] , npc's name + bodypart [1]
//Ex. Fargothchest , Fargothneck
assert (ref->base != NULL);
std::string hairID = ref->base->hair;
std::string hairID = ref->base->hair;
std::string headID = ref->base->head;
std::string npcName = ref->base->name;
//std::cout << "NPC: " << npcName << "\n";
// very ugly workaround to stop OGRE from chocking on non-unique scene node handles
static int uniqueId = 0;
std::ostringstream stream;
stream << "npc$" << uniqueId++;
std::string npcName = stream.str(); // ref->base->name;
//std::cout << "NPC: " << npcName << "\n";
//get the part of the bodypart id which describes the race and the gender
std::string bodyRaceID = headID.substr(0, headID.find_last_of("head_") - 4);
std::string headModel = "meshes\\" +
environment.mWorld->getStore().bodyParts.find(headID)->model;
std::string hairModel = "meshes\\" +
std::string hairModel = "meshes\\" +
environment.mWorld->getStore().bodyParts.find(hairID)->model;
MWRender::Rendering rendering (cellRender, ref->ref);
//TODO: define consts for each bodypart e.g. chest, foot, wrist... and put the parts in the
// right place
const ESM::BodyPart *bodyPart =
environment.mWorld->getStore().bodyParts.search (bodyRaceID + "chest");
//bodyPart->model->
Ogre::Vector3 pos = Ogre::Vector3( 20, 20, 20);
Ogre::Vector3 axis = Ogre::Vector3( 0, 0, 1);
Ogre::Radian angle = Ogre::Radian(0);
std::string addresses[6] = {"", "", "", "","", ""};
std::string addresses2[6] = {"", "", "", "", "", ""};
std::string upperleft[5] = {"", "", "", "", ""};
std::string upperright[5] = {"", "", "", "", ""};
std::string neckandup[5] = {"", "", "","",""};
std::string empty[6] = {"", "", "", "","", ""};
int numbers = 0;
int uppernumbers = 0;
int neckNumbers = 0;
//bodyPart->model->
Ogre::Vector3 pos = Ogre::Vector3( 20, 20, 20);
Ogre::Vector3 axis = Ogre::Vector3( 0, 0, 1);
Ogre::Radian angle = Ogre::Radian(0);
std::string addresses[6] = {"", "", "", "","", ""};
std::string addresses2[6] = {"", "", "", "", "", ""};
std::string upperleft[5] = {"", "", "", "", ""};
std::string upperright[5] = {"", "", "", "", ""};
std::string neckandup[5] = {"", "", "","",""};
int numbers = 0;
int uppernumbers = 0;
int neckNumbers = 0;
if (bodyPart){
cellRender.insertMesh("meshes\\" + bodyPart->model, pos, axis, angle, npcName + "chest", addresses, numbers, true); //2 0
addresses2[numbers] = npcName + "chest";
addresses[numbers++] = npcName + "chest";
upperleft[uppernumbers] = npcName + "chest";
upperright[uppernumbers++] = npcName + "chest";
neckandup[neckNumbers++] = npcName + "chest";
}
//std::cout << "GETTING NPC PART";
//Orgre::SceneNode test = cellRender.getNpcPart();
const ESM::BodyPart *upperleg = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "upper leg");
const ESM::BodyPart *groin = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "groin");
const ESM::BodyPart *arm = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "upper arm");
const ESM::BodyPart *neck = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "neck");
const ESM::BodyPart *knee = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "knee");
const ESM::BodyPart *ankle = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "ankle");
const ESM::BodyPart *foot = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "foot");
const ESM::BodyPart *feet = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "feet");
const ESM::BodyPart *tail = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "tail");
const ESM::BodyPart *wrist = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "wrist");
const ESM::BodyPart *forearm = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "forearm");
const ESM::BodyPart *hand = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "hand.1st");
const ESM::BodyPart *hands = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "hands.1st");
//std::cout << "RACE" << bodyRaceID << "\n";
Ogre::Vector3 pos2 = Ogre::Vector3( 0, .5, 75);
std::string upperarmpath[2] = {npcName + "chest", npcName + "upper arm"};
addresses2[numbers] = npcName + "chest";
addresses[numbers++] = npcName + "chest";
upperleft[uppernumbers] = npcName + "chest";
upperright[uppernumbers++] = npcName + "chest";
neckandup[neckNumbers++] = npcName + "chest";
}
//std::cout << "GETTING NPC PART";
//Orgre::SceneNode test = cellRender.getNpcPart();
const ESM::BodyPart *upperleg = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "upper leg");
const ESM::BodyPart *groin = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "groin");
const ESM::BodyPart *arm = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "upper arm");
const ESM::BodyPart *neck = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "neck");
const ESM::BodyPart *knee = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "knee");
const ESM::BodyPart *ankle = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "ankle");
const ESM::BodyPart *foot = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "foot");
const ESM::BodyPart *feet = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "feet");
const ESM::BodyPart *tail = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "tail");
const ESM::BodyPart *wrist = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "wrist");
const ESM::BodyPart *forearm = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "forearm");
const ESM::BodyPart *hand = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "hand.1st");
const ESM::BodyPart *hands = environment.mWorld->getStore().bodyParts.search (bodyRaceID + "hands.1st");
//std::cout << "RACE" << bodyRaceID << "\n";
Ogre::Vector3 pos2 = Ogre::Vector3( 0, .5, 75);
if (groin){
cellRender.insertMesh("meshes\\" + groin->model, pos2, axis, Ogre::Radian(3.14), npcName + "groin", addresses, numbers);
addresses2[numbers] = npcName + "groin";
addresses[numbers++] = npcName + "groin";
}
if (tail) {
cellRender.insertMesh("tail\\" + tail->model, Ogre::Vector3(0 , 0, -76), axis, Ogre::Radian(3.14), npcName + "tail", addresses, numbers, "tail");
//std::cout << "TAIL\n";
}
//addresses[1] = npcName + "groin";
if(upperleg){
cellRender.insertMesh ("meshes\\" + upperleg->model, Ogre::Vector3( 6, 0, -16), axis, Ogre::Radian(3.14), npcName + "upper leg", addresses, numbers); //-18
cellRender.insertMesh ("meshes\\" + upperleg->model, Ogre::Vector3( -6, 0, -16), axis, Ogre::Radian(0), npcName + "upper leg2", addresses2, numbers);
addresses2[numbers] = npcName + "upper leg2";
addresses[numbers++] = npcName + "upper leg";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if(knee)
{
cellRender.insertMesh ("meshes\\" + knee->model, Ogre::Vector3( 0, -1, -23), axis, Ogre::Radian(0), npcName + "knee", addresses, numbers);
//cellRender.rotateMesh(Ogre::Vector3(0, 1, 0), Ogre::Radian (1), npcName + "upper arm");
cellRender.insertMesh ("meshes\\" + knee->model, Ogre::Vector3( 0, -1, -23), axis, Ogre::Radian(0), npcName + "knee2", addresses2, numbers);
addresses2[numbers] = npcName + "knee2";
addresses[numbers++] = npcName + "knee";
}
if(ankle){
cellRender.insertMesh ("meshes\\" + ankle->model, Ogre::Vector3( 0, 0, -20), axis, Ogre::Radian(0), npcName + "ankle", addresses, numbers); //-1
cellRender.insertMesh ("meshes\\" + ankle->model, Ogre::Vector3( 0,0, -20), axis, Ogre::Radian(0), npcName + "ankle2", addresses2, numbers); //-1
addresses2[numbers] = npcName + "ankle2";
addresses[numbers++] = npcName + "ankle";
}
if(foot){
if(bodyRaceID.compare("b_n_khajiit_m_") == 0)
{
feet = foot;
}
else
{
cellRender.insertMesh ("meshes\\" + foot->model, Ogre::Vector3( 0, -4, -15), axis, Ogre::Radian(0), npcName + "foot", addresses, numbers);
cellRender.insertMesh ("meshes\\" + foot->model, Ogre::Vector3( 0, -4, -15), axis, Ogre::Radian(0), npcName + "foot2", addresses2, numbers);
addresses2[numbers] = npcName + "foot2";
addresses[numbers++] = npcName + "foot";
}
//cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if(feet){
cellRender.insertMesh ("foot\\" + feet->model, Ogre::Vector3( 7, 4, -16), axis, Ogre::Radian(3.14), npcName + "foot", addresses, numbers); //9, 0, -14
cellRender.insertMesh ("foot\\" + feet->model, Ogre::Vector3( 7, 4, -16), axis, Ogre::Radian(3.14), npcName + "foot2", addresses2, numbers);
addresses2[numbers] = npcName + "foot2";
addresses[numbers++] = npcName + "foot";
//cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if (arm){
//010
cellRender.insertMesh("meshes\\" + arm->model, Ogre::Vector3(-12.5, 0, 104), Ogre::Vector3(0, 1, 0), Ogre::Radian(-3.14 / 2), npcName + "upper arm", upperleft, uppernumbers); //1, 0,.75
//cellRender.rotateMesh(Ogre::Vector3(1, 0, 0), Ogre::Radian (.45), upperarmpath, 2); //-.5, 0, -.75
cellRender.insertMesh("meshes\\" + arm->model, Ogre::Vector3(12.5, 0, 105), Ogre::Vector3(-.5, 0, -.75), Ogre::Radian(3.14), npcName + "upper arm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "upper arm";
upperright[uppernumbers++] = npcName + "upper arm2";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers); //1 -1 1
cellRender.rotateMesh(Ogre::Vector3(0, .1, 0), Ogre::Radian(3.14/2), upperleft, uppernumbers);
}
if (forearm)
{
//addresses[1] = npcName + "upper arm";
cellRender.insertMesh("meshes\\" + forearm->model, Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "forearm", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\" + forearm->model, Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "forearm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "forearm";
upperright[uppernumbers++] = npcName + "forearm2";
}
//else
// std::cout << npcName << "has no forearm";
if (wrist)
{
if(upperleft[uppernumbers - 1].compare(npcName + "upper arm") == 0)
{
cellRender.insertMesh("meshes\\b\\B_N_Argonian_M_Forearm.nif", Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "forearm", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\b\\B_N_Argonian_M_Forearm.nif", Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "forearm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "forearm";
upperright[uppernumbers++] = npcName + "forearm2";
}
cellRender.insertMesh("meshes\\" + wrist->model, Ogre::Vector3(-9.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "wrist", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\" + wrist->model, Ogre::Vector3(-9.5, 0, 0), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "wrist2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "wrist";
upperright[uppernumbers++] = npcName + "wrist2";
}
if(hand)
{
//std::cout << "WE FOUND A HAND\n";
//-50, 0, -120
//std::cout << "WE FOUND HANDS\n";
std::string pass;
if(hand->model.compare("b\\B_N_Dark Elf_F_Hands.1st.NIF")==0 && bodyRaceID.compare("b_n_dark elf_m_") == 0)
pass = "b\\B_N_Dark Elf_M_Hands.1st.NIF";
else
pass = hand->model;
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "hand", upperleft, uppernumbers,false); //0, 100, -100 0,0,120
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0,0), Ogre::Radian(3.14), npcName + "hand2", upperright, uppernumbers, false); //0, 100, -100 0,0,120
upperleft[uppernumbers] = npcName + "hand";
upperright[uppernumbers++] = npcName + "hand2";
//cellRender.rotateMesh(Ogre::Vector3(0, 0,0), Ogre::Radian(3.14), upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperright, uppernumbers);
}
if(hands)
{
std::string pass;
if(hands->model.compare("b\\B_N_Redguard_F_Hands.1st.nif")==0 && bodyRaceID.compare("b_n_redguard_m_") == 0)
pass = "b\\B_N_Redguard_M_Hands.1st.nif";
else if(hands->model.compare("b\\B_N_Imperial_M_Hands.1st.nif") == 0 && bodyRaceID.compare("b_n_nord_m_") == 0)
pass = "b\\B_N_Nord_M_Hands.1st.nif";
else
pass =hands->model; //-50, 0, -120
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1,-110), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "hand", upperleft, uppernumbers, false); //0, 100, -100 42, 0, -110
//cellRender.insertMesh("meshes\\" + hands->model, Ogre::Vector3(42, 0,110), Ogre::Vector3(1, 0, 0), Ogre::Radian(3.14), npcName + "hand", upperleft, uppernumbers, false); //0, 100, -100 42, 0, -110
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0, 0), Ogre::Radian(3.14), npcName + "hand2", upperright, uppernumbers, false); //0, 100, -100 0,0,120
upperleft[uppernumbers] = npcName + "hand";
upperright[uppernumbers++] = npcName + "hand2";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperright, uppernumbers);
}
if(neck)
{
cellRender.insertMesh ("meshes\\" + neck->model, Ogre::Vector3( 0, 0, 120), axis, Ogre::Radian(3.14), npcName + "neck", neckandup, neckNumbers);
neckandup[neckNumbers++] = npcName + "neck";
}
cellRender.insertMesh (headModel, Ogre::Vector3( 0, 0, 5), axis, Ogre::Radian(0), npcName + "head", neckandup, neckNumbers);
neckandup[neckNumbers++] = npcName + "head";
cellRender.insertMesh (hairModel, Ogre::Vector3( 0, -1, 0), axis, Ogre::Radian(0), npcName + "hair", neckandup, neckNumbers);
cellRender.insertMesh("meshes\\base_anim.nif");
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
//
}
cellRender.insertMesh("meshes\\" + groin->model, pos2, axis, kOgrePi, npcName + "groin", addresses, numbers);
addresses2[numbers] = npcName + "groin";
addresses[numbers++] = npcName + "groin";
}
if (tail) {
cellRender.insertMesh("tail\\" + tail->model, Ogre::Vector3(0 , 0, -76), axis, kOgrePi, npcName + "tail", addresses, numbers, "tail");
//std::cout << "TAIL\n";
}
//addresses[1] = npcName + "groin";
if(upperleg){
cellRender.insertMesh ("meshes\\" + upperleg->model, Ogre::Vector3( 6, 0, -16), axis, kOgrePi, npcName + "upper leg", addresses, numbers); //-18
cellRender.insertMesh ("meshes\\" + upperleg->model, Ogre::Vector3( -6, 0, -16), axis, Ogre::Radian(0), npcName + "upper leg2", addresses2, numbers);
addresses2[numbers] = npcName + "upper leg2";
addresses[numbers++] = npcName + "upper leg";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if(knee)
{
cellRender.insertMesh ("meshes\\" + knee->model, Ogre::Vector3( 0, -1, -23), axis, Ogre::Radian(0), npcName + "knee", addresses, numbers);
//cellRender.rotateMesh(Ogre::Vector3(0, 1, 0), Ogre::Radian (1), npcName + "upper arm");
cellRender.insertMesh ("meshes\\" + knee->model, Ogre::Vector3( 0, -1, -23), axis, Ogre::Radian(0), npcName + "knee2", addresses2, numbers);
addresses2[numbers] = npcName + "knee2";
addresses[numbers++] = npcName + "knee";
}
if(ankle){
cellRender.insertMesh ("meshes\\" + ankle->model, Ogre::Vector3( 0, 0, -20), axis, Ogre::Radian(0), npcName + "ankle", addresses, numbers); //-1
cellRender.insertMesh ("meshes\\" + ankle->model, Ogre::Vector3( 0,0, -20), axis, Ogre::Radian(0), npcName + "ankle2", addresses2, numbers); //-1
addresses2[numbers] = npcName + "ankle2";
addresses[numbers++] = npcName + "ankle";
}
if(foot){
if(bodyRaceID.compare("b_n_khajiit_m_") == 0)
{
feet = foot;
}
else
{
cellRender.insertMesh ("meshes\\" + foot->model, Ogre::Vector3( 0, -4, -15), axis, Ogre::Radian(0), npcName + "foot", addresses, numbers);
cellRender.insertMesh ("meshes\\" + foot->model, Ogre::Vector3( 0, -4, -15), axis, Ogre::Radian(0), npcName + "foot2", addresses2, numbers);
addresses2[numbers] = npcName + "foot2";
addresses[numbers++] = npcName + "foot";
}
//cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if(feet){
cellRender.insertMesh ("foot\\" + feet->model, Ogre::Vector3( 7, 4, -16), axis, kOgrePi, npcName + "foot", addresses, numbers); //9, 0, -14
cellRender.insertMesh ("foot\\" + feet->model, Ogre::Vector3( 7, 4, -16), axis, kOgrePi, npcName + "foot2", addresses2, numbers);
addresses2[numbers] = npcName + "foot2";
addresses[numbers++] = npcName + "foot";
//cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), addresses, numbers);
}
if (arm){
//010
cellRender.insertMesh("meshes\\" + arm->model, Ogre::Vector3(-12.5, 0, 104), Ogre::Vector3(0, 1, 0), -kOgrePiOverTwo, npcName + "upper arm", upperleft, uppernumbers); //1, 0,.75
//cellRender.rotateMesh(Ogre::Vector3(1, 0, 0), Ogre::Radian (.45), upperarmpath, 2); //-.5, 0, -.75
cellRender.insertMesh("meshes\\" + arm->model, Ogre::Vector3(12.5, 0, 105), Ogre::Vector3(-.5, 0, -.75), kOgrePi, npcName + "upper arm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "upper arm";
upperright[uppernumbers++] = npcName + "upper arm2";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers); //1 -1 1
cellRender.rotateMesh(Ogre::Vector3(0, .1, 0), kOgrePiOverTwo, upperleft, uppernumbers);
}
if (forearm)
{
//addresses[1] = npcName + "upper arm";
cellRender.insertMesh("meshes\\" + forearm->model, Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "forearm", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\" + forearm->model, Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "forearm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "forearm";
upperright[uppernumbers++] = npcName + "forearm2";
}
//else
// std::cout << npcName << "has no forearm";
if (wrist)
{
if(upperleft[uppernumbers - 1].compare(npcName + "upper arm") == 0)
{
cellRender.insertMesh("meshes\\b\\B_N_Argonian_M_Forearm.nif", Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "forearm", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\b\\B_N_Argonian_M_Forearm.nif", Ogre::Vector3(-12.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "forearm2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "forearm";
upperright[uppernumbers++] = npcName + "forearm2";
}
cellRender.insertMesh("meshes\\" + wrist->model, Ogre::Vector3(-9.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "wrist", upperleft, uppernumbers);
cellRender.insertMesh("meshes\\" + wrist->model, Ogre::Vector3(-9.5, 0, 0), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "wrist2", upperright, uppernumbers);
upperleft[uppernumbers] = npcName + "wrist";
upperright[uppernumbers++] = npcName + "wrist2";
}
if(hand)
{
//std::cout << "WE FOUND A HAND\n";
//-50, 0, -120
//std::cout << "WE FOUND HANDS\n";
std::string pass;
if(hand->model.compare("b\\B_N_Dark Elf_F_Hands.1st.NIF")==0 && bodyRaceID.compare("b_n_dark elf_m_") == 0)
pass = "b\\B_N_Dark Elf_M_Hands.1st.NIF";
else
pass = hand->model;
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "hand", upperleft, uppernumbers,false); //0, 100, -100 0,0,120
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0,0), kOgrePi, npcName + "hand2", upperright, uppernumbers, false); //0, 100, -100 0,0,120
upperleft[uppernumbers] = npcName + "hand";
upperright[uppernumbers++] = npcName + "hand2";
//cellRender.rotateMesh(Ogre::Vector3(0, 0,0), kOgrePi, upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperright, uppernumbers);
}
if(hands)
{
std::string pass;
if(hands->model.compare("b\\B_N_Redguard_F_Hands.1st.nif")==0 && bodyRaceID.compare("b_n_redguard_m_") == 0)
pass = "b\\B_N_Redguard_M_Hands.1st.nif";
else if(hands->model.compare("b\\B_N_Imperial_M_Hands.1st.nif") == 0 && bodyRaceID.compare("b_n_nord_m_") == 0)
pass = "b\\B_N_Nord_M_Hands.1st.nif";
else
pass =hands->model; //-50, 0, -120
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1,-110), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "hand", upperleft, uppernumbers, false); //0, 100, -100 42, 0, -110
//cellRender.insertMesh("meshes\\" + hands->model, Ogre::Vector3(42, 0,110), Ogre::Vector3(1, 0, 0), kOgrePi, npcName + "hand", upperleft, uppernumbers, false); //0, 100, -100 42, 0, -110
cellRender.insertMesh("meshes\\" + pass, Ogre::Vector3(42, 1, -110), Ogre::Vector3(0, 0, 0), kOgrePi, npcName + "hand2", upperright, uppernumbers, false); //0, 100, -100 0,0,120
upperleft[uppernumbers] = npcName + "hand";
upperright[uppernumbers++] = npcName + "hand2";
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperleft, uppernumbers);
cellRender.scaleMesh(Ogre::Vector3(1, -1, 1), upperright, uppernumbers);
}
//neck will reset chest counter
if(neck)
{
cellRender.insertMesh ("meshes\\" + neck->model, Ogre::Vector3( 0, 0, 120), axis, kOgrePi, npcName + "neck", neckandup, neckNumbers);
neckandup[neckNumbers++] = npcName + "neck";
}
cellRender.insertMesh (headModel, Ogre::Vector3( 0, 0, 5), axis, Ogre::Radian(0), npcName + "head", neckandup, neckNumbers);
neckandup[neckNumbers++] = npcName + "head";
cellRender.insertMesh (hairModel, Ogre::Vector3( 0, -1, 0), axis, Ogre::Radian(0), npcName + "hair", neckandup, neckNumbers);
cellRender.insertActorPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
void Npc::enable (const MWWorld::Ptr& ptr, MWWorld::Environment& environment) const
{
@ -302,7 +317,6 @@ namespace MWClass
{
if (!ptr.getRefData().getNpcStats().get())
{
// xxx
boost::shared_ptr<MWMechanics::NpcStats> stats (
new MWMechanics::NpcStats);
@ -354,6 +368,113 @@ namespace MWClass
return ref->base->script;
}
void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const
{
MWMechanics::NpcStats& stats = getNpcStats (ptr);
switch (stance)
{
case Run:
stats.mForceRun = force;
break;
case Sneak:
stats.mForceSneak = force;
break;
case Combat:
throw std::runtime_error ("combat stance not enforcable for NPCs");
}
}
void Npc::setStance (const MWWorld::Ptr& ptr, Stance stance, bool set) const
{
MWMechanics::NpcStats& stats = getNpcStats (ptr);
switch (stance)
{
case Run:
stats.mRun = set;
break;
case Sneak:
stats.mSneak = set;
break;
case Combat:
stats.mCombat = set;
break;
}
}
bool Npc::getStance (const MWWorld::Ptr& ptr, Stance stance, bool ignoreForce) const
{
MWMechanics::NpcStats& stats = getNpcStats (ptr);
switch (stance)
{
case Run:
if (!ignoreForce && stats.mForceRun)
return true;
return stats.mRun;
case Sneak:
if (!ignoreForce && stats.mForceSneak)
return true;
return stats.mSneak;
case Combat:
return stats.mCombat;
}
return false;
}
float Npc::getSpeed (const MWWorld::Ptr& ptr) const
{
return getStance (ptr, Run) ? 600 : 300; // TODO calculate these values from stats
}
MWMechanics::Movement& Npc::getMovementSettings (const MWWorld::Ptr& ptr) const
{
if (!ptr.getRefData().getMovement().get())
{
boost::shared_ptr<MWMechanics::Movement> movement (
new MWMechanics::Movement);
ptr.getRefData().getMovement() = movement;
}
return *ptr.getRefData().getMovement();
}
Ogre::Vector3 Npc::getMovementVector (const MWWorld::Ptr& ptr) const
{
Ogre::Vector3 vector (0, 0, 0);
if (ptr.getRefData().getMovement().get())
{
vector.x = - ptr.getRefData().getMovement()->mLeftRight * 200;
vector.y = ptr.getRefData().getMovement()->mForwardBackward * 200;
if (getStance (ptr, Run, false))
vector *= 2;
}
return vector;
}
void Npc::registerSelf()
{
boost::shared_ptr<Class> instance (new Npc);

@ -8,7 +8,7 @@ namespace MWClass
class Npc : public MWWorld::Class
{
public:
virtual std::string getId (const MWWorld::Ptr& ptr) const;
///< Return ID of \a ptr
@ -43,6 +43,26 @@ namespace MWClass
virtual std::string getScript (const MWWorld::Ptr& ptr) const;
///< Return name of the script attached to ptr
virtual void setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const;
///< Force or unforce a stance.
virtual void setStance (const MWWorld::Ptr& ptr, Stance stance, bool set) const;
///< Set or unset a stance.
virtual bool getStance (const MWWorld::Ptr& ptr, Stance stance, bool ignoreForce = false)
const;
////< Check if a stance is active or not.
virtual float getSpeed (const MWWorld::Ptr& ptr) const;
///< Return movement speed.
virtual MWMechanics::Movement& getMovementSettings (const MWWorld::Ptr& ptr) const;
///< Return desired movement.
virtual Ogre::Vector3 getMovementVector (const MWWorld::Ptr& ptr) const;
///< Return desired movement vector (determined based on movement settings,
/// stance and stats).
static void registerSelf();
};
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -21,6 +21,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -26,6 +26,7 @@ namespace MWClass
{
MWRender::Rendering rendering (cellRender, ref->ref);
cellRender.insertMesh ("meshes\\" + model);
cellRender.insertObjectPhysics();
ref->mData.setHandle (rendering.end (ref->mData.isEnabled()));
}
}

@ -13,6 +13,7 @@
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "../mwworld/refdata.hpp"
#include "../mwworld/player.hpp"
#include "../mwinput/inputmanager.hpp"
@ -225,7 +226,7 @@ namespace MWDialogue
// check cell
if (!info.cell.empty())
if (mEnvironment.mWorld->getPlayerPos().getPlayer().getCell()->cell->name != info.cell)
if (mEnvironment.mWorld->getPlayer().getPlayer().getCell()->cell->name != info.cell)
return false;
// TODO check DATAstruct

@ -1,6 +1,4 @@
#include "birth.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "widgets.hpp"
#include "components/esm_store/store.hpp"
@ -11,8 +9,8 @@
using namespace MWGui;
using namespace Widgets;
BirthDialog::BirthDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_birth_layout.xml", environment)
BirthDialog::BirthDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_birth_layout.xml", parWindowManager)
{
// Centre dialog
center();
@ -94,7 +92,7 @@ void BirthDialog::setBirthId(const std::string &birthId)
void BirthDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void BirthDialog::onBackClicked(MyGUI::Widget* _sender)
@ -121,7 +119,7 @@ void BirthDialog::updateBirths()
{
birthList->removeAllItems();
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
ESMS::RecListT<ESM::BirthSign>::MapType::const_iterator it = store.birthSigns.list.begin();
ESMS::RecListT<ESM::BirthSign>::MapType::const_iterator end = store.birthSigns.list.end();
@ -151,7 +149,7 @@ void BirthDialog::updateSpells()
const int lineHeight = 18;
MyGUI::IntCoord coord(0, 0, spellArea->getWidth(), 18);
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
const ESM::BirthSign *birth = store.birthSigns.find(currentBirthId);
std::string texturePath = std::string("textures\\") + birth->texture;
@ -191,7 +189,7 @@ void BirthDialog::updateSpells()
if (!categories[category].spells.empty())
{
MyGUI::StaticTextPtr label = spellArea->createWidget<MyGUI::StaticText>("SandBrightText", coord, MyGUI::Align::Default, std::string("Label"));
label->setCaption(environment.mWindowManager->getGameSettingString(categories[category].label, ""));
label->setCaption(mWindowManager.getGameSettingString(categories[category].label, ""));
spellItems.push_back(label);
coord.top += lineHeight;
@ -200,7 +198,7 @@ void BirthDialog::updateSpells()
{
const std::string &spellId = *it;
spellWidget = spellArea->createWidget<MWSpell>("MW_StatName", coord, MyGUI::Align::Default, std::string("Spell") + boost::lexical_cast<std::string>(i));
spellWidget->setEnvironment(&environment);
spellWidget->setWindowManager(&mWindowManager);
spellWidget->setSpellId(spellId);
spellItems.push_back(spellWidget);

@ -3,11 +3,6 @@
#include "window_base.hpp"
namespace MWWorld
{
class Environment;
}
/*
This file contains the dialog for choosing a birth sign.
Layout is defined by resources/mygui/openmw_chargen_race_layout.xml.
@ -17,10 +12,12 @@ namespace MWGui
{
using namespace MyGUI;
class WindowManager;
class BirthDialog : public WindowBase
{
public:
BirthDialog(MWWorld::Environment& environment);
BirthDialog(WindowManager& parWindowManager);
enum Gender
{
@ -42,11 +39,6 @@ namespace MWGui
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onSelectBirth(MyGUI::List* _sender, size_t _index);

@ -1,6 +1,4 @@
#include "class.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "components/esm_store/store.hpp"
@ -10,18 +8,20 @@
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#undef min
#undef max
using namespace MWGui;
/* GenerateClassResultDialog */
GenerateClassResultDialog::GenerateClassResultDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_generate_class_result_layout.xml", environment)
GenerateClassResultDialog::GenerateClassResultDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_generate_class_result_layout.xml", parWindowManager)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("ReflectT", wm->getGameSettingString("sMessageQuestionAnswer1", ""));
setText("ReflectT", mWindowManager.getGameSettingString("sMessageQuestionAnswer1", ""));
getWidget(classImage, "ClassImage");
getWidget(className, "ClassName");
@ -50,7 +50,7 @@ void GenerateClassResultDialog::setClassId(const std::string &classId)
{
currentClassId = classId;
classImage->setImageTexture(std::string("textures\\levelup\\") + currentClassId + ".dds");
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
className->setCaption(store.classes.find(currentClassId)->name);
}
@ -58,7 +58,7 @@ void GenerateClassResultDialog::setClassId(const std::string &classId)
void GenerateClassResultDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void GenerateClassResultDialog::onBackClicked(MyGUI::Widget* _sender)
@ -68,31 +68,30 @@ void GenerateClassResultDialog::onBackClicked(MyGUI::Widget* _sender)
/* PickClassDialog */
PickClassDialog::PickClassDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_class_layout.xml", environment)
PickClassDialog::PickClassDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_class_layout.xml", parWindowManager)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("SpecializationT", wm->getGameSettingString("sChooseClassMenu1", "Specialization"));
setText("SpecializationT", mWindowManager.getGameSettingString("sChooseClassMenu1", "Specialization"));
getWidget(specializationName, "SpecializationName");
setText("FavoriteAttributesT", wm->getGameSettingString("sChooseClassMenu2", "Favorite Attributes:"));
setText("FavoriteAttributesT", mWindowManager.getGameSettingString("sChooseClassMenu2", "Favorite Attributes:"));
getWidget(favoriteAttribute[0], "FavoriteAttribute0");
getWidget(favoriteAttribute[1], "FavoriteAttribute1");
favoriteAttribute[0]->setWindowManager(wm);
favoriteAttribute[1]->setWindowManager(wm);
favoriteAttribute[0]->setWindowManager(&mWindowManager);
favoriteAttribute[1]->setWindowManager(&mWindowManager);
setText("MajorSkillT", wm->getGameSettingString("sChooseClassMenu3", "Major Skills:"));
setText("MinorSkillT", wm->getGameSettingString("sChooseClassMenu4", "Minor Skills:"));
setText("MajorSkillT", mWindowManager.getGameSettingString("sChooseClassMenu3", "Major Skills:"));
setText("MinorSkillT", mWindowManager.getGameSettingString("sChooseClassMenu4", "Minor Skills:"));
for(int i = 0; i < 5; i++)
{
char theIndex = '0'+i;
getWidget(majorSkill[i], std::string("MajorSkill").append(1, theIndex));
getWidget(minorSkill[i], std::string("MinorSkill").append(1, theIndex));
majorSkill[i]->setWindowManager(wm);
minorSkill[i]->setWindowManager(wm);
majorSkill[i]->setWindowManager(&mWindowManager);
minorSkill[i]->setWindowManager(&mWindowManager);
}
getWidget(classList, "ClassList");
@ -170,7 +169,7 @@ void PickClassDialog::setClassId(const std::string &classId)
void PickClassDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void PickClassDialog::onBackClicked(MyGUI::Widget* _sender)
@ -197,7 +196,7 @@ void PickClassDialog::updateClasses()
{
classList->removeAllItems();
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
ESMS::RecListT<ESM::Class>::MapType::const_iterator it = store.classes.list.begin();
ESMS::RecListT<ESM::Class>::MapType::const_iterator end = store.classes.list.end();
@ -221,8 +220,7 @@ void PickClassDialog::updateStats()
{
if (currentClassId.empty())
return;
WindowManager *wm = environment.mWindowManager;
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
const ESM::Class *klass = store.classes.search(currentClassId);
if (!klass)
return;
@ -234,7 +232,7 @@ void PickClassDialog::updateStats()
"sSpecializationMagic",
"sSpecializationStealth"
};
specializationName->setCaption(wm->getGameSettingString(specIds[specialization], specIds[specialization]));
specializationName->setCaption(mWindowManager.getGameSettingString(specIds[specialization], specIds[specialization]));
favoriteAttribute[0]->setAttributeId(klass->data.attribute[0]);
favoriteAttribute[1]->setAttributeId(klass->data.attribute[1]);
@ -280,8 +278,8 @@ void InfoBoxDialog::layoutVertically(MyGUI::WidgetPtr widget, int margin)
widget->setSize(width, pos);
}
InfoBoxDialog::InfoBoxDialog(MWWorld::Environment& environment)
: WindowBase("openmw_infobox_layout.xml", environment)
InfoBoxDialog::InfoBoxDialog(WindowManager& parWindowManager)
: WindowBase("openmw_infobox_layout.xml", parWindowManager)
, currentButton(-1)
{
getWidget(textBox, "TextBox");
@ -355,7 +353,7 @@ void InfoBoxDialog::onButtonClicked(MyGUI::WidgetPtr _sender)
if (*it == _sender)
{
currentButton = i;
eventButtonSelected(_sender, i);
eventButtonSelected(i);
return;
}
++i;
@ -364,23 +362,22 @@ void InfoBoxDialog::onButtonClicked(MyGUI::WidgetPtr _sender)
/* ClassChoiceDialog */
ClassChoiceDialog::ClassChoiceDialog(MWWorld::Environment& environment)
: InfoBoxDialog(environment)
ClassChoiceDialog::ClassChoiceDialog(WindowManager& parWindowManager)
: InfoBoxDialog(parWindowManager)
{
WindowManager *mw = environment.mWindowManager;
setText("");
ButtonList buttons;
buttons.push_back(mw->getGameSettingString("sClassChoiceMenu1", ""));
buttons.push_back(mw->getGameSettingString("sClassChoiceMenu2", ""));
buttons.push_back(mw->getGameSettingString("sClassChoiceMenu3", ""));
buttons.push_back(mw->getGameSettingString("sBack", ""));
buttons.push_back(mWindowManager.getGameSettingString("sClassChoiceMenu1", ""));
buttons.push_back(mWindowManager.getGameSettingString("sClassChoiceMenu2", ""));
buttons.push_back(mWindowManager.getGameSettingString("sClassChoiceMenu3", ""));
buttons.push_back(mWindowManager.getGameSettingString("sBack", ""));
setButtons(buttons);
}
/* CreateClassDialog */
CreateClassDialog::CreateClassDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_create_class_layout.xml", environment)
CreateClassDialog::CreateClassDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_create_class_layout.xml", parWindowManager)
, specDialog(nullptr)
, attribDialog(nullptr)
, skillDialog(nullptr)
@ -389,22 +386,21 @@ CreateClassDialog::CreateClassDialog(MWWorld::Environment& environment)
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("SpecializationT", wm->getGameSettingString("sChooseClassMenu1", "Specialization"));
setText("SpecializationT", mWindowManager.getGameSettingString("sChooseClassMenu1", "Specialization"));
getWidget(specializationName, "SpecializationName");
specializationName->setCaption(wm->getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Combat], ""));
specializationName->setCaption(mWindowManager.getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Combat], ""));
specializationName->eventMouseButtonClick = MyGUI::newDelegate(this, &CreateClassDialog::onSpecializationClicked);
setText("FavoriteAttributesT", wm->getGameSettingString("sChooseClassMenu2", "Favorite Attributes:"));
setText("FavoriteAttributesT", mWindowManager.getGameSettingString("sChooseClassMenu2", "Favorite Attributes:"));
getWidget(favoriteAttribute0, "FavoriteAttribute0");
getWidget(favoriteAttribute1, "FavoriteAttribute1");
favoriteAttribute0->setWindowManager(wm);
favoriteAttribute1->setWindowManager(wm);
favoriteAttribute0->setWindowManager(&mWindowManager);
favoriteAttribute1->setWindowManager(&mWindowManager);
favoriteAttribute0->eventClicked = MyGUI::newDelegate(this, &CreateClassDialog::onAttributeClicked);
favoriteAttribute1->eventClicked = MyGUI::newDelegate(this, &CreateClassDialog::onAttributeClicked);
setText("MajorSkillT", wm->getGameSettingString("sSkillClassMajor", ""));
setText("MinorSkillT", wm->getGameSettingString("sSkillClassMinor", ""));
setText("MajorSkillT", mWindowManager.getGameSettingString("sSkillClassMajor", ""));
setText("MinorSkillT", mWindowManager.getGameSettingString("sSkillClassMinor", ""));
for(int i = 0; i < 5; i++)
{
char theIndex = '0'+i;
@ -417,11 +413,11 @@ CreateClassDialog::CreateClassDialog(MWWorld::Environment& environment)
std::vector<Widgets::MWSkillPtr>::const_iterator end = skills.end();
for (std::vector<Widgets::MWSkillPtr>::const_iterator it = skills.begin(); it != end; ++it)
{
(*it)->setWindowManager(wm);
(*it)->setWindowManager(&mWindowManager);
(*it)->eventClicked = MyGUI::newDelegate(this, &CreateClassDialog::onSkillClicked);
}
setText("LabelT", wm->getGameSettingString("sName", ""));
setText("LabelT", mWindowManager.getGameSettingString("sName", ""));
getWidget(editName, "EditName");
// Make sure the edit box has focus
@ -563,7 +559,7 @@ void CreateClassDialog::onSpecializationClicked(MyGUI::WidgetPtr _sender)
{
if (specDialog)
delete specDialog;
specDialog = new SelectSpecializationDialog(environment, environment.mWindowManager->getGui()->getViewSize());
specDialog = new SelectSpecializationDialog(mWindowManager);
specDialog->eventCancel = MyGUI::newDelegate(this, &CreateClassDialog::onDialogCancel);
specDialog->eventItemSelected = MyGUI::newDelegate(this, &CreateClassDialog::onSpecializationSelected);
specDialog->setVisible(true);
@ -572,7 +568,7 @@ void CreateClassDialog::onSpecializationClicked(MyGUI::WidgetPtr _sender)
void CreateClassDialog::onSpecializationSelected()
{
specializationId = specDialog->getSpecializationId();
specializationName->setCaption(environment.mWindowManager->getGameSettingString(ESM::Class::gmstSpecializationIds[specializationId], ""));
specializationName->setCaption(mWindowManager.getGameSettingString(ESM::Class::gmstSpecializationIds[specializationId], ""));
specDialog->setVisible(false);
}
@ -580,7 +576,7 @@ void CreateClassDialog::onAttributeClicked(Widgets::MWAttributePtr _sender)
{
if (attribDialog)
delete attribDialog;
attribDialog = new SelectAttributeDialog(environment, environment.mWindowManager->getGui()->getViewSize());
attribDialog = new SelectAttributeDialog(mWindowManager);
attribDialog->setAffectedWidget(_sender);
attribDialog->eventCancel = MyGUI::newDelegate(this, &CreateClassDialog::onDialogCancel);
attribDialog->eventItemSelected = MyGUI::newDelegate(this, &CreateClassDialog::onAttributeSelected);
@ -609,7 +605,7 @@ void CreateClassDialog::onSkillClicked(Widgets::MWSkillPtr _sender)
{
if (skillDialog)
delete skillDialog;
skillDialog = new SelectSkillDialog(environment, environment.mWindowManager->getGui()->getViewSize());
skillDialog = new SelectSkillDialog(mWindowManager);
skillDialog->setAffectedWidget(_sender);
skillDialog->eventCancel = MyGUI::newDelegate(this, &CreateClassDialog::onDialogCancel);
skillDialog->eventItemSelected = MyGUI::newDelegate(this, &CreateClassDialog::onSkillSelected);
@ -640,21 +636,21 @@ void CreateClassDialog::onSkillSelected()
void CreateClassDialog::onDescriptionClicked(MyGUI::Widget* _sender)
{
descDialog = new DescriptionDialog(environment, environment.mWindowManager->getGui()->getViewSize());
descDialog = new DescriptionDialog(mWindowManager);
descDialog->setTextInput(description);
descDialog->eventDone = MyGUI::newDelegate(this, &CreateClassDialog::onDescriptionEntered);
descDialog->setVisible(true);
}
void CreateClassDialog::onDescriptionEntered()
void CreateClassDialog::onDescriptionEntered(WindowBase* parWindow)
{
description = descDialog->getTextInput();
environment.mWindowManager->removeDialog(descDialog);
mWindowManager.removeDialog(descDialog);
}
void CreateClassDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void CreateClassDialog::onBackClicked(MyGUI::Widget* _sender)
@ -664,31 +660,29 @@ void CreateClassDialog::onBackClicked(MyGUI::Widget* _sender)
/* SelectSpecializationDialog */
SelectSpecializationDialog::SelectSpecializationDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize)
: WindowBase("openmw_chargen_select_specialization_layout.xml", environment)
SelectSpecializationDialog::SelectSpecializationDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_select_specialization_layout.xml", parWindowManager)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("LabelT", wm->getGameSettingString("sSpecializationMenu1", ""));
setText("LabelT", mWindowManager.getGameSettingString("sSpecializationMenu1", ""));
getWidget(specialization0, "Specialization0");
getWidget(specialization1, "Specialization1");
getWidget(specialization2, "Specialization2");
specialization0->setCaption(wm->getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Combat], ""));
specialization0->setCaption(mWindowManager.getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Combat], ""));
specialization0->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectSpecializationDialog::onSpecializationClicked);
specialization1->setCaption(wm->getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Magic], ""));
specialization1->setCaption(mWindowManager.getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Magic], ""));
specialization1->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectSpecializationDialog::onSpecializationClicked);
specialization2->setCaption(wm->getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Stealth], ""));
specialization2->setCaption(mWindowManager.getGameSettingString(ESM::Class::gmstSpecializationIds[ESM::Class::Stealth], ""));
specialization2->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectSpecializationDialog::onSpecializationClicked);
specializationId = ESM::Class::Combat;
// TODO: These buttons should be managed by a Dialog class
MyGUI::ButtonPtr cancelButton;
getWidget(cancelButton, "CancelButton");
cancelButton->setCaption(wm->getGameSettingString("sCancel", ""));
cancelButton->setCaption(mWindowManager.getGameSettingString("sCancel", ""));
cancelButton->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectSpecializationDialog::onCancelClicked);
}
@ -715,15 +709,13 @@ void SelectSpecializationDialog::onCancelClicked(MyGUI::Widget* _sender)
/* SelectAttributeDialog */
SelectAttributeDialog::SelectAttributeDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize)
: WindowBase("openmw_chargen_select_attribute_layout.xml", environment)
SelectAttributeDialog::SelectAttributeDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_select_attribute_layout.xml", parWindowManager)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("LabelT", wm->getGameSettingString("sAttributesMenu1", ""));
setText("LabelT", mWindowManager.getGameSettingString("sAttributesMenu1", ""));
for (int i = 0; i < 8; ++i)
{
@ -731,7 +723,7 @@ SelectAttributeDialog::SelectAttributeDialog(MWWorld::Environment& environment,
char theIndex = '0'+i;
getWidget(attribute, std::string("Attribute").append(1, theIndex));
attribute->setWindowManager(wm);
attribute->setWindowManager(&parWindowManager);
attribute->setAttributeId(ESM::Attribute::attributeIds[i]);
attribute->eventClicked = MyGUI::newDelegate(this, &SelectAttributeDialog::onAttributeClicked);
}
@ -739,7 +731,7 @@ SelectAttributeDialog::SelectAttributeDialog(MWWorld::Environment& environment,
// TODO: These buttons should be managed by a Dialog class
MyGUI::ButtonPtr cancelButton;
getWidget(cancelButton, "CancelButton");
cancelButton->setCaption(wm->getGameSettingString("sCancel", ""));
cancelButton->setCaption(mWindowManager.getGameSettingString("sCancel", ""));
cancelButton->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectAttributeDialog::onCancelClicked);
}
@ -760,18 +752,16 @@ void SelectAttributeDialog::onCancelClicked(MyGUI::Widget* _sender)
/* SelectSkillDialog */
SelectSkillDialog::SelectSkillDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize)
: WindowBase("openmw_chargen_select_skill_layout.xml", environment)
SelectSkillDialog::SelectSkillDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_select_skill_layout.xml", parWindowManager)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
setText("LabelT", wm->getGameSettingString("sSkillsMenu1", ""));
setText("CombatLabelT", wm->getGameSettingString("sSpecializationCombat", ""));
setText("MagicLabelT", wm->getGameSettingString("sSpecializationMagic", ""));
setText("StealthLabelT", wm->getGameSettingString("sSpecializationStealth", ""));
setText("LabelT", mWindowManager.getGameSettingString("sSkillsMenu1", ""));
setText("CombatLabelT", mWindowManager.getGameSettingString("sSpecializationCombat", ""));
setText("MagicLabelT", mWindowManager.getGameSettingString("sSpecializationMagic", ""));
setText("StealthLabelT", mWindowManager.getGameSettingString("sSpecializationStealth", ""));
for(int i = 0; i < 9; i++)
{
@ -821,7 +811,7 @@ SelectSkillDialog::SelectSkillDialog(MWWorld::Environment& environment, MyGUI::I
{
for (int i = 0; i < 9; ++i)
{
skills[spec][i].widget->setWindowManager(wm);
skills[spec][i].widget->setWindowManager(&mWindowManager);
skills[spec][i].widget->setSkillId(skills[spec][i].skillId);
skills[spec][i].widget->eventClicked = MyGUI::newDelegate(this, &SelectSkillDialog::onSkillClicked);
}
@ -830,7 +820,7 @@ SelectSkillDialog::SelectSkillDialog(MWWorld::Environment& environment, MyGUI::I
// TODO: These buttons should be managed by a Dialog class
MyGUI::ButtonPtr cancelButton;
getWidget(cancelButton, "CancelButton");
cancelButton->setCaption(wm->getGameSettingString("sCancel", ""));
cancelButton->setCaption(mWindowManager.getGameSettingString("sCancel", ""));
cancelButton->eventMouseButtonClick = MyGUI::newDelegate(this, &SelectSkillDialog::onCancelClicked);
}
@ -849,8 +839,8 @@ void SelectSkillDialog::onCancelClicked(MyGUI::Widget* _sender)
/* DescriptionDialog */
DescriptionDialog::DescriptionDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize)
: WindowBase("openmw_chargen_class_description_layout.xml", environment)
DescriptionDialog::DescriptionDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_class_description_layout.xml", parWindowManager)
{
// Centre dialog
center();
@ -861,7 +851,7 @@ DescriptionDialog::DescriptionDialog(MWWorld::Environment& environment, MyGUI::I
MyGUI::ButtonPtr okButton;
getWidget(okButton, "OKButton");
okButton->eventMouseButtonClick = MyGUI::newDelegate(this, &DescriptionDialog::onOkClicked);
okButton->setCaption(environment.mWindowManager->getGameSettingString("sInputMenu1", ""));
okButton->setCaption(mWindowManager.getGameSettingString("sInputMenu1", ""));
// Make sure the edit box has focus
MyGUI::InputManager::getInstance().setKeyFocusWidget(textEdit);
@ -871,5 +861,5 @@ DescriptionDialog::DescriptionDialog(MWWorld::Environment& environment, MyGUI::I
void DescriptionDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}

@ -5,11 +5,6 @@
#include "widgets.hpp"
#include "window_base.hpp"
namespace MWWorld
{
class Environment;
}
/*
This file contains the dialogs for choosing a class.
Layout is defined by resources/mygui/openmw_chargen_class_layout.xml.
@ -19,10 +14,12 @@ namespace MWGui
{
using namespace MyGUI;
class WindowManager;
class InfoBoxDialog : public WindowBase
{
public:
InfoBoxDialog(MWWorld::Environment& environment);
InfoBoxDialog(WindowManager& parWindowManager);
typedef std::vector<std::string> ButtonList;
@ -34,12 +31,12 @@ namespace MWGui
int getChosenButton() const;
// Events
typedef delegates::CDelegate2<MyGUI::WidgetPtr, int> EventHandle_WidgetInt;
typedef delegates::CDelegate1<int> EventHandle_Int;
/** Event : Button was clicked.\n
signature : void method(MyGUI::WidgetPtr widget, int index)\n
*/
EventHandle_WidgetInt eventButtonSelected;
EventHandle_Int eventButtonSelected;
protected:
void onButtonClicked(MyGUI::WidgetPtr _sender);
@ -67,13 +64,13 @@ namespace MWGui
Class_Create = 2,
Class_Back = 3
};
ClassChoiceDialog(MWWorld::Environment& environment);
ClassChoiceDialog(WindowManager& parWindowManager);
};
class GenerateClassResultDialog : public WindowBase
{
public:
GenerateClassResultDialog(MWWorld::Environment& environment);
GenerateClassResultDialog(WindowManager& parWindowManager);
std::string getClassId() const;
void setClassId(const std::string &classId);
@ -88,11 +85,6 @@ namespace MWGui
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onOkClicked(MyGUI::Widget* _sender);
void onBackClicked(MyGUI::Widget* _sender);
@ -107,7 +99,7 @@ namespace MWGui
class PickClassDialog : public WindowBase
{
public:
PickClassDialog(MWWorld::Environment& environment);
PickClassDialog(WindowManager& parWindowManager);
const std::string &getClassId() const { return currentClassId; }
void setClassId(const std::string &classId);
@ -123,11 +115,6 @@ namespace MWGui
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onSelectClass(MyGUI::List* _sender, size_t _index);
@ -151,7 +138,7 @@ namespace MWGui
class SelectSpecializationDialog : public WindowBase
{
public:
SelectSpecializationDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize);
SelectSpecializationDialog(WindowManager& parWindowManager);
ESM::Class::Specialization getSpecializationId() const { return specializationId; }
@ -181,7 +168,7 @@ namespace MWGui
class SelectAttributeDialog : public WindowBase
{
public:
SelectAttributeDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize);
SelectAttributeDialog(WindowManager& parWindowManager);
ESM::Attribute::AttributeID getAttributeId() const { return attributeId; }
Widgets::MWAttributePtr getAffectedWidget() const { return affectedWidget; }
@ -213,7 +200,7 @@ namespace MWGui
class SelectSkillDialog : public WindowBase
{
public:
SelectSkillDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize);
SelectSkillDialog(WindowManager& parWindowManager);
ESM::Skill::SkillEnum getSkillId() const { return skillId; }
Widgets::MWSkillPtr getAffectedWidget() const { return affectedWidget; }
@ -248,19 +235,11 @@ namespace MWGui
class DescriptionDialog : public WindowBase
{
public:
DescriptionDialog(MWWorld::Environment& environment, MyGUI::IntSize gameWindowSize);
DescriptionDialog(WindowManager& parWindowManager);
std::string getTextInput() const { return textEdit ? textEdit->getOnlyText() : ""; }
void setTextInput(const std::string &text) { if (textEdit) textEdit->setOnlyText(text); }
// Events
typedef delegates::CDelegate0 EventHandle_Void;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onOkClicked(MyGUI::Widget* _sender);
@ -271,7 +250,7 @@ namespace MWGui
class CreateClassDialog : public WindowBase
{
public:
CreateClassDialog(MWWorld::Environment& environment);
CreateClassDialog(WindowManager& parWindowManager);
virtual ~CreateClassDialog();
std::string getName() const;
@ -292,11 +271,6 @@ namespace MWGui
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onOkClicked(MyGUI::Widget* _sender);
void onBackClicked(MyGUI::Widget* _sender);
@ -308,7 +282,7 @@ namespace MWGui
void onSkillClicked(Widgets::MWSkillPtr _sender);
void onSkillSelected();
void onDescriptionClicked(MyGUI::Widget* _sender);
void onDescriptionEntered();
void onDescriptionEntered(WindowBase* parWindow);
void onDialogCancel();
private:

@ -1,6 +1,8 @@
#include "console.hpp"
#include <algorithm>
#include <components/compiler/exception.hpp>
#include "../mwscript/extensions.hpp"
@ -67,6 +69,31 @@ namespace MWGui
printError ((type==ErrorMessage ? "error: " : "warning: ") + message);
}
void Console::listNames()
{
if (mNames.empty())
{
// keywords
std::istringstream input ("");
Compiler::Scanner scanner (*this, input, mCompilerContext.getExtensions());
scanner.listKeywords (mNames);
// identifier
const ESMS::ESMStore& store = mEnvironment.mWorld->getStore();
for (ESMS::RecListList::const_iterator iter (store.recLists.begin());
iter!=store.recLists.end(); ++iter)
{
iter->second->listIdentifier (mNames);
}
// sort
std::sort (mNames.begin(), mNames.end());
}
}
Console::Console(int w, int h, MWWorld::Environment& environment,
const Compiler::Extensions& extensions)
: Layout("openmw_console_layout.xml"),

@ -21,10 +21,11 @@ namespace MWGui
class Console : private OEngine::GUI::Layout, private Compiler::ErrorHandler
{
private:
MWScript::CompilerContext mCompilerContext;
MWWorld::Environment& mEnvironment;
std::vector<std::string> mNames;
bool compile (const std::string& cmd, Compiler::Output& output);
/// Report error to the user.
@ -32,7 +33,13 @@ namespace MWGui
/// Report a file related error
virtual void report (const std::string& message, Type type);
void listNames();
///< Write all valid identifiers and keywords into mNames and sort them.
/// \note If mNames is not empty, this function is a no-op.
/// \note The list may contain duplicates (if a name is a keyword and an identifier at the same
/// time).
public:
MyGUI::EditPtr command;
MyGUI::EditPtr history;

@ -1,7 +1,5 @@
#include "dialogue.hpp"
#include "dialogue_history.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "widgets.hpp"
#include "components/esm_store/store.hpp"
@ -16,8 +14,8 @@
using namespace MWGui;
using namespace Widgets;
DialogueWindow::DialogueWindow(MWWorld::Environment& environment)
: WindowBase("openmw_dialogue_window_layout.xml", environment)
DialogueWindow::DialogueWindow(WindowManager& parWindowManager)
: WindowBase("openmw_dialogue_window_layout.xml", parWindowManager)
{
// Centre dialog
center();

@ -4,9 +4,9 @@
#include "window_base.hpp"
#include <boost/array.hpp>
namespace MWWorld
namespace MWGui
{
class Environment;
class WindowManager;
}
/*
@ -23,7 +23,7 @@ namespace MWGui
class DialogueWindow: public WindowBase
{
public:
DialogueWindow(MWWorld::Environment& environment);
DialogueWindow(WindowManager& parWindowManager);
void open();

@ -1,6 +1,4 @@
#include "dialogue_history.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "widgets.hpp"
#include "components/esm_store/store.hpp"

@ -1,412 +1,126 @@
#include "layouts.hpp"
#include "../mwworld/class.hpp"
#include "../mwmechanics/mechanicsmanager.hpp"
#include "../mwgui/window_manager.hpp"
#include "window_manager.hpp"
#include <cmath>
#include <algorithm>
#include <iterator>
#include <boost/lexical_cast.hpp>
#undef min
#undef max
using namespace MWGui;
const int StatsWindow::lineHeight = 18;
StatsWindow::StatsWindow (MWWorld::Environment& environment)
: WindowBase("openmw_stats_window_layout.xml", environment)
, lastPos(0)
, reputation(0)
, bounty(0)
HUD::HUD(int width, int height, bool fpsSwitch)
: Layout("openmw_hud_layout.xml")
{
setCoord(0,0,498, 342);
setCoord(0,0, width, height);
const char *names[][2] =
{
{ "Attrib1", "sAttributeStrength" },
{ "Attrib2", "sAttributeIntelligence" },
{ "Attrib3", "sAttributeWillpower" },
{ "Attrib4", "sAttributeAgility" },
{ "Attrib5", "sAttributeSpeed" },
{ "Attrib6", "sAttributeEndurance" },
{ "Attrib7", "sAttributePersonality" },
{ "Attrib8", "sAttributeLuck" },
{ "Health_str", "sHealth" },
{ "Magicka_str", "sMagic" },
{ "Fatigue_str", "sFatigue" },
{ "Level_str", "sLevel" },
{ "Race_str", "sRace" },
{ "Class_str", "sClass" },
{ 0, 0 }
};
// Energy bars
getWidget(health, "Health");
getWidget(magicka, "Magicka");
getWidget(stamina, "Stamina");
const ESMS::ESMStore &store = environment.mWorld->getStore();
for (int i=0; names[i][0]; ++i)
{
setText (names[i][0], store.gameSettings.find (names[i][1])->str);
}
// Item and spell images and status bars
getWidget(weapImage, "WeapImage");
getWidget(weapStatus, "WeapStatus");
getWidget(spellImage, "SpellImage");
getWidget(spellStatus, "SpellStatus");
getWidget(skillAreaWidget, "Skills");
getWidget(skillClientWidget, "SkillClient");
getWidget(skillScrollerWidget, "SkillScroller");
getWidget(effectBox, "EffectBox");
getWidget(effect1, "Effect1");
skillScrollerWidget->eventScrollChangePosition = MyGUI::newDelegate(this, &StatsWindow::onScrollChangePosition);
updateScroller();
getWidget(minimap, "MiniMap");
getWidget(compass, "Compass");
for (int i = 0; i < ESM::Skill::Length; ++i)
{
skillValues.insert(std::pair<int, MWMechanics::Stat<float> >(i, MWMechanics::Stat<float>()));
skillWidgetMap.insert(std::pair<int, MyGUI::StaticTextPtr>(i, (MyGUI::StaticTextPtr) nullptr));
}
getWidget(crosshair, "Crosshair");
MyGUI::WindowPtr t = static_cast<MyGUI::WindowPtr>(mMainWidget);
t->eventWindowChangeCoord = MyGUI::newDelegate(this, &StatsWindow::onWindowResize);
}
getWidget(fpsbox, "FPSBox");
getWidget(fpscounter, "FPSCounter");
void StatsWindow::onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos)
{
int diff = lastPos - pos;
// Adjust position of all widget according to difference
if (diff == 0)
return;
lastPos = pos;
fpsbox->setVisible(fpsSwitch);
std::vector<MyGUI::WidgetPtr>::const_iterator end = skillWidgets.end();
for (std::vector<MyGUI::WidgetPtr>::const_iterator it = skillWidgets.begin(); it != end; ++it)
{
(*it)->setCoord((*it)->getCoord() + MyGUI::IntPoint(0, diff));
}
}
compass->setImageTexture("textures\\compass.dds");
crosshair->setImageTexture("textures\\target.dds");
void StatsWindow::onWindowResize(MyGUI::WidgetPtr window)
{
updateScroller();
// These are just demo values, you should replace these with
// real calls from outside the class later.
setWeapIcon("icons\\w\\tx_knife_iron.dds");
setWeapStatus(90, 100);
setSpellIcon("icons\\s\\b_tx_s_rstor_health.dds");
setSpellStatus(65, 100);
setEffect("icons\\s\\tx_s_chameleon.dds");
}
void StatsWindow::setBar(const std::string& name, const std::string& tname, int val, int max)
void HUD::setFPS(float fps)
{
MyGUI::ProgressPtr pt;
getWidget(pt, name);
pt->setProgressRange(max);
pt->setProgressPosition(val);
std::stringstream out;
out << val << "/" << max;
setText(tname, out.str().c_str());
fpscounter->setCaption(boost::lexical_cast<std::string>((int)fps));
}
void StatsWindow::setPlayerName(const std::string& playerName)
void HUD::setStats(int h, int hmax, int m, int mmax, int s, int smax)
{
mMainWidget->setCaption(playerName);
health->setProgressRange(hmax);
health->setProgressPosition(h);
magicka->setProgressRange(mmax);
magicka->setProgressPosition(m);
stamina->setProgressRange(smax);
stamina->setProgressPosition(s);
}
void StatsWindow::setStyledText(MyGUI::StaticTextPtr widget, ColorStyle style, const std::string &value)
void HUD::setWeapIcon(const char *str)
{
widget->setCaption(value);
if (style == CS_Super)
widget->setTextColour(MyGUI::Colour(0, 1, 0));
else if (style == CS_Sub)
widget->setTextColour(MyGUI::Colour(1, 0, 0));
else
widget->setTextColour(MyGUI::Colour(1, 1, 1));
weapImage->setImageTexture(str);
}
void StatsWindow::setValue (const std::string& id, const MWMechanics::Stat<int>& value)
void HUD::setSpellIcon(const char *str)
{
static const char *ids[] =
{
"AttribVal1", "AttribVal2", "AttribVal3", "AttribVal4", "AttribVal5",
"AttribVal6", "AttribVal7", "AttribVal8",
0
};
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
std::ostringstream valueString;
valueString << value.getModified();
setText (id, valueString.str());
if (value.getModified()>value.getBase())
setTextColor (id, 0, 1, 0);
else if (value.getModified()<value.getBase())
setTextColor (id, 1, 0, 0);
else
setTextColor (id, 1, 1, 1);
break;
}
spellImage->setImageTexture(str);
}
void StatsWindow::setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value)
void HUD::setWeapStatus(int s, int smax)
{
static const char *ids[] =
{
"HBar", "MBar", "FBar",
0
};
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
std::string id (ids[i]);
setBar (id, id + "T", value.getCurrent(), value.getModified());
}
weapStatus->setProgressRange(smax);
weapStatus->setProgressPosition(s);
}
void StatsWindow::setValue (const std::string& id, const std::string& value)
void HUD::setSpellStatus(int s, int smax)
{
if (id=="name")
setPlayerName (value);
else if (id=="race")
setText ("RaceText", value);
else if (id=="class")
setText ("ClassText", value);
spellStatus->setProgressRange(smax);
spellStatus->setProgressPosition(s);
}
void StatsWindow::setValue (const std::string& id, int value)
void HUD::setEffect(const char *img)
{
if (id=="level")
{
std::ostringstream text;
text << value;
setText("LevelText", text.str());
}
effect1->setImageTexture(img);
}
void StatsWindow::setValue (const std::string& id, const MWMechanics::Stat<float>& value)
void HUD::setValue(const std::string& id, const MWMechanics::DynamicStat<int>& value)
{
static struct {const char *id; ESM::Skill::SkillEnum skillId; } skillMap[] =
static const char *ids[] =
{
{"SkillBlock", ESM::Skill::Block},
{"SkillArmorer", ESM::Skill::Armorer},
{"SkillMediumArmor", ESM::Skill::MediumArmor},
{"SkillHeavyArmor", ESM::Skill::HeavyArmor},
{"SkillBluntWeapon", ESM::Skill::BluntWeapon},
{"SkillLongBlade", ESM::Skill::LongBlade},
{"SkillAxe", ESM::Skill::Axe},
{"SkillSpear", ESM::Skill::Spear},
{"SkillAthletics", ESM::Skill::Athletics},
{"SkillEnchant", ESM::Skill::Armorer},
{"SkillDestruction", ESM::Skill::Destruction},
{"SkillAlteration", ESM::Skill::Alteration},
{"SkillIllusion", ESM::Skill::Illusion},
{"SkillConjuration", ESM::Skill::Conjuration},
{"SkillMysticism", ESM::Skill::Mysticism},
{"SkillRestoration", ESM::Skill::Restoration},
{"SkillAlchemy", ESM::Skill::Alchemy},
{"SkillUnarmored", ESM::Skill::Unarmored},
{"SkillSecurity", ESM::Skill::Security},
{"SkillSneak", ESM::Skill::Sneak},
{"SkillAcrobatics", ESM::Skill::Acrobatics},
{"SkillLightArmor", ESM::Skill::LightArmor},
{"SkillShortBlade", ESM::Skill::ShortBlade},
{"SkillMarksman", ESM::Skill::Marksman},
{"SkillMercantile", ESM::Skill::Mercantile},
{"SkillSpeechcraft", ESM::Skill::Speechcraft},
{"SkillHandToHand", ESM::Skill::HandToHand},
"HBar", "MBar", "FBar", 0
};
for (size_t i = 0; i < sizeof(skillMap)/sizeof(skillMap[0]); ++i)
{
if (skillMap[i].id == id)
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
int skillId = skillMap[i].skillId;
skillValues[skillId] = value;
MyGUI::StaticTextPtr widget = skillWidgetMap[skillId];
if (widget)
switch (i)
{
float modified = value.getModified(), base = value.getBase();
std::string text = boost::lexical_cast<std::string>(std::floor(modified));
ColorStyle style = CS_Normal;
if (modified > base)
style = CS_Super;
else if (modified < base)
style = CS_Sub;
setStyledText(widget, style, text);
case 0:
health->setProgressRange (value.getModified());
health->setProgressPosition (value.getCurrent());
break;
case 1:
magicka->setProgressRange (value.getModified());
magicka->setProgressPosition (value.getCurrent());
break;
case 2:
stamina->setProgressRange (value.getModified());
stamina->setProgressPosition (value.getCurrent());
break;
}
break;
}
}
}
void StatsWindow::configureSkills (const std::vector<int>& major, const std::vector<int>& minor)
{
majorSkills = major;
minorSkills = minor;
// Update misc skills with the remaining skills not in major or minor
std::set<int> skillSet;
std::copy(major.begin(), major.end(), std::inserter(skillSet, skillSet.begin()));
std::copy(minor.begin(), minor.end(), std::inserter(skillSet, skillSet.begin()));
boost::array<ESM::Skill::SkillEnum, ESM::Skill::Length>::const_iterator end = ESM::Skill::skillIds.end();
miscSkills.clear();
for (boost::array<ESM::Skill::SkillEnum, ESM::Skill::Length>::const_iterator it = ESM::Skill::skillIds.begin(); it != end; ++it)
{
int skill = *it;
if (skillSet.find(skill) == skillSet.end())
miscSkills.push_back(skill);
}
}
void StatsWindow::setFactions (const std::vector<Faction>& factions)
{
this->factions = factions;
}
void StatsWindow::setBirthSign (const std::string& signId)
{
birthSignId = signId;
}
void StatsWindow::addSeparator(MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticImagePtr separator = skillClientWidget->createWidget<MyGUI::StaticImage>("MW_HLine", MyGUI::IntCoord(10, coord1.top, coord1.width + coord2.width - 4, 18), MyGUI::Align::Default);
skillWidgets.push_back(separator);
coord1.top += separator->getHeight();
coord2.top += separator->getHeight();
}
void StatsWindow::addGroup(const std::string &label, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr groupWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandBrightText", MyGUI::IntCoord(0, coord1.top, coord1.width + coord2.width, coord1.height), MyGUI::Align::Default);
groupWidget->setCaption(label);
skillWidgets.push_back(groupWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
}
MyGUI::StaticTextPtr StatsWindow::addValueItem(const std::string text, const std::string &value, ColorStyle style, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr skillNameWidget, skillValueWidget;
skillNameWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandText", coord1, MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillValueWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandTextRight", coord2, MyGUI::Align::Default);
setStyledText(skillValueWidget, style, value);
skillWidgets.push_back(skillNameWidget);
skillWidgets.push_back(skillValueWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
return skillValueWidget;
}
void StatsWindow::addItem(const std::string text, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr skillNameWidget;
skillNameWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandText", coord1 + MyGUI::IntSize(coord2.width, 0), MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillWidgets.push_back(skillNameWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
}
void StatsWindow::addSkills(const SkillList &skills, const std::string &titleId, const std::string &titleDefault, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
WindowManager *wm = environment.mWindowManager;
// Add a line separator if there are items above
if (!skillWidgets.empty())
{
addSeparator(coord1, coord2);
}
addGroup(wm->getGameSettingString(titleId, titleDefault), coord1, coord2);
SkillList::const_iterator end = skills.end();
for (SkillList::const_iterator it = skills.begin(); it != end; ++it)
{
int skillId = *it;
if (skillId < 0 || skillId > ESM::Skill::Length) // Skip unknown skill indexes
continue;
assert(skillId >= 0 && skillId < ESM::Skill::Length);
const std::string &skillNameId = ESMS::Skill::sSkillNameIds[skillId];
const MWMechanics::Stat<float> &stat = skillValues.find(skillId)->second;
float base = stat.getBase();
float modified = stat.getModified();
ColorStyle style = CS_Normal;
if (modified > base)
style = CS_Super;
else if (modified < base)
style = CS_Sub;
MyGUI::StaticTextPtr widget = addValueItem(wm->getGameSettingString(skillNameId, skillNameId), boost::lexical_cast<std::string>(static_cast<int>(modified)), style, coord1, coord2);
skillWidgetMap[skillId] = widget;
}
}
void StatsWindow::updateSkillArea()
{
for (std::vector<MyGUI::WidgetPtr>::iterator it = skillWidgets.begin(); it != skillWidgets.end(); ++it)
{
MyGUI::Gui::getInstance().destroyWidget(*it);
}
skillWidgets.clear();
const int valueSize = 40;
MyGUI::IntCoord coord1(10, 0, skillClientWidget->getWidth() - (10 + valueSize), 18);
MyGUI::IntCoord coord2(coord1.left + coord1.width, coord1.top, valueSize, coord1.height);
if (!majorSkills.empty())
addSkills(majorSkills, "sSkillClassMajor", "Major Skills", coord1, coord2);
if (!minorSkills.empty())
addSkills(minorSkills, "sSkillClassMinor", "Minor Skills", coord1, coord2);
if (!miscSkills.empty())
addSkills(miscSkills, "sSkillClassMisc", "Misc Skills", coord1, coord2);
WindowManager *wm = environment.mWindowManager;
ESMS::ESMStore &store = environment.mWorld->getStore();
if (!factions.empty())
{
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(wm->getGameSettingString("sFaction", "Faction"), coord1, coord2);
FactionList::const_iterator end = factions.end();
for (FactionList::const_iterator it = factions.begin(); it != end; ++it)
{
const ESM::Faction *faction = store.factions.find(it->first);
addItem(faction->name, coord1, coord2);
// TODO: Faction rank should be placed in tooltip
}
}
if (!birthSignId.empty())
{
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(wm->getGameSettingString("sSign", "Sign"), coord1, coord2);
const ESM::BirthSign *sign = store.birthSigns.find(birthSignId);
addItem(sign->name, coord1, coord2);
}
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addValueItem(wm->getGameSettingString("sReputation", "Reputation"), boost::lexical_cast<std::string>(static_cast<int>(reputation)), CS_Normal, coord1, coord2);
addValueItem(wm->getGameSettingString("sBounty", "Bounty"), boost::lexical_cast<std::string>(static_cast<int>(bounty)), CS_Normal, coord1, coord2);
clientHeight = coord1.top;
updateScroller();
}
void StatsWindow::updateScroller()
{
skillScrollerWidget->setScrollRange(std::max(clientHeight - skillClientWidget->getHeight(), 0));
skillScrollerWidget->setScrollPage(std::max(skillClientWidget->getHeight() - lineHeight, 0));
}

@ -3,9 +3,8 @@
#include <components/esm_store/store.hpp>
#include <openengine/gui/layout.hpp>
#include <boost/array.hpp>
#include <boost/lexical_cast.hpp>
#include <sstream>
#include <set>
@ -13,12 +12,10 @@
#include <utility>
#include "../mwmechanics/stat.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_base.hpp"
/*
This file contains classes corresponding to all the window layouts
This file contains classes corresponding to window layouts
defined in resources/mygui/ *.xml.
Each class inherites GUI::Layout and loads the XML file, and
@ -35,117 +32,27 @@ namespace MWGui
class HUD : public OEngine::GUI::Layout
{
public:
HUD(int width, int height)
: Layout("openmw_hud_layout.xml")
{
setCoord(0,0, width, height);
// Energy bars
getWidget(health, "Health");
getWidget(magicka, "Magicka");
getWidget(stamina, "Stamina");
// Item and spell images and status bars
getWidget(weapImage, "WeapImage");
getWidget(weapStatus, "WeapStatus");
getWidget(spellImage, "SpellImage");
getWidget(spellStatus, "SpellStatus");
getWidget(effectBox, "EffectBox");
getWidget(effect1, "Effect1");
getWidget(minimap, "MiniMap");
getWidget(compass, "Compass");
getWidget(crosshair, "Crosshair");
compass->setImageTexture("textures\\compass.dds");
crosshair->setImageTexture("textures\\target.dds");
// These are just demo values, you should replace these with
// real calls from outside the class later.
setWeapIcon("icons\\w\\tx_knife_iron.dds");
setWeapStatus(90, 100);
setSpellIcon("icons\\s\\b_tx_s_rstor_health.dds");
setSpellStatus(65, 100);
setEffect("icons\\s\\tx_s_chameleon.dds");
}
void setStats(int h, int hmax, int m, int mmax, int s, int smax)
{
health->setProgressRange(hmax);
health->setProgressPosition(h);
magicka->setProgressRange(mmax);
magicka->setProgressPosition(m);
stamina->setProgressRange(smax);
stamina->setProgressPosition(s);
}
void setWeapIcon(const char *str)
{ weapImage->setImageTexture(str); }
void setSpellIcon(const char *str)
{ spellImage->setImageTexture(str); }
void setWeapStatus(int s, int smax)
{
weapStatus->setProgressRange(smax);
weapStatus->setProgressPosition(s);
}
void setSpellStatus(int s, int smax)
{
spellStatus->setProgressRange(smax);
spellStatus->setProgressPosition(s);
}
void setEffect(const char *img)
{ effect1->setImageTexture(img); }
void setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value)
{
static const char *ids[] =
{
"HBar", "MBar", "FBar",
0
};
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
switch (i)
{
case 0:
health->setProgressRange (value.getModified());
health->setProgressPosition (value.getCurrent());
break;
case 1:
magicka->setProgressRange (value.getModified());
magicka->setProgressPosition (value.getCurrent());
break;
case 2:
stamina->setProgressRange (value.getModified());
stamina->setProgressPosition (value.getCurrent());
break;
}
}
}
HUD(int width, int height, bool fpsSwitch);
void setStats(int h, int hmax, int m, int mmax, int s, int smax);
void setWeapIcon(const char *str);
void setSpellIcon(const char *str);
void setWeapStatus(int s, int smax);
void setSpellStatus(int s, int smax);
void setEffect(const char *img);
void setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value);
void setFPS(float fps);
MyGUI::ProgressPtr health, magicka, stamina;
MyGUI::StaticImagePtr weapImage, spellImage;
MyGUI::ProgressPtr weapStatus, spellStatus;
MyGUI::WidgetPtr effectBox;
MyGUI::StaticImagePtr effect1;
MyGUI::StaticImagePtr minimap;
MyGUI::StaticImagePtr compass;
MyGUI::StaticImagePtr crosshair;
MyGUI::WidgetPtr fpsbox;
MyGUI::StaticTextPtr fpscounter;
};
class MapWindow : public OEngine::GUI::Layout
@ -178,68 +85,6 @@ namespace MWGui
}
};
class StatsWindow : public WindowBase
{
public:
typedef std::pair<std::string, int> Faction;
typedef std::vector<Faction> FactionList;
typedef std::vector<int> SkillList;
StatsWindow (MWWorld::Environment& environment);
void setBar(const std::string& name, const std::string& tname, int val, int max);
void setPlayerName(const std::string& playerName);
/// Set value for the given ID.
void setValue (const std::string& id, const MWMechanics::Stat<int>& value);
void setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value);
void setValue (const std::string& id, const std::string& value);
void setValue (const std::string& id, int value);
void setValue (const std::string& id, const MWMechanics::Stat<float>& value);
void configureSkills (const SkillList& major, const SkillList& minor);
void setFactions (const std::vector<Faction>& factions);
void setBirthSign (const std::string &signId);
void setReputation (int reputation) { this->reputation = reputation; }
void setBounty (int bounty) { this->bounty = bounty; }
void updateSkillArea();
private:
enum ColorStyle
{
CS_Sub,
CS_Normal,
CS_Super
};
void setStyledText(MyGUI::StaticTextPtr widget, ColorStyle style, const std::string &value);
void addSkills(const SkillList &skills, const std::string &titleId, const std::string &titleDefault, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addSeparator(MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addGroup(const std::string &label, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
MyGUI::StaticTextPtr addValueItem(const std::string text, const std::string &value, ColorStyle style, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addItem(const std::string text, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void updateScroller();
void onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos);
void onWindowResize(MyGUI::WidgetPtr window);
static const int lineHeight;
MyGUI::WidgetPtr skillAreaWidget, skillClientWidget;
MyGUI::VScrollPtr skillScrollerWidget;
int lastPos, clientHeight;
SkillList majorSkills, minorSkills, miscSkills;
std::map<int, MWMechanics::Stat<float> > skillValues;
std::map<int, MyGUI::StaticTextPtr> skillWidgetMap;
std::map<std::string, MyGUI::WidgetPtr> factionWidgetMap;
FactionList factions; ///< Stores a list of factions and the current rank
std::string birthSignId;
int reputation, bounty;
std::vector<MyGUI::WidgetPtr> skillWidgets; //< Skills and other information
};
#if 0
class InventoryWindow : public OEngine::GUI::Layout
{

@ -1,6 +1,4 @@
#include "race.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "widgets.hpp"
#include "components/esm_store/store.hpp"
@ -15,8 +13,8 @@
using namespace MWGui;
using namespace Widgets;
RaceDialog::RaceDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_race_layout.xml", environment)
RaceDialog::RaceDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_race_layout.xml", parWindowManager)
, genderIndex(0)
, faceIndex(0)
, hairIndex(0)
@ -29,8 +27,7 @@ RaceDialog::RaceDialog(MWWorld::Environment& environment)
// These are just demo values, you should replace these with
// real calls from outside the class later.
WindowManager *wm = environment.mWindowManager;
setText("AppearanceT", wm->getGameSettingString("sRaceMenu1", "Appearance"));
setText("AppearanceT", mWindowManager.getGameSettingString("sRaceMenu1", "Appearance"));
getWidget(appearanceBox, "AppearanceBox");
getWidget(headRotate, "HeadRotate");
@ -42,34 +39,34 @@ RaceDialog::RaceDialog(MWWorld::Environment& environment)
// Set up next/previous buttons
MyGUI::ButtonPtr prevButton, nextButton;
setText("GenderChoiceT", wm->getGameSettingString("sRaceMenu2", "Change Sex"));
setText("GenderChoiceT", mWindowManager.getGameSettingString("sRaceMenu2", "Change Sex"));
getWidget(prevButton, "PrevGenderButton");
getWidget(nextButton, "NextGenderButton");
prevButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectPreviousGender);
nextButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectNextGender);
setText("FaceChoiceT", wm->getGameSettingString("sRaceMenu3", "Change Face"));
setText("FaceChoiceT", mWindowManager.getGameSettingString("sRaceMenu3", "Change Face"));
getWidget(prevButton, "PrevFaceButton");
getWidget(nextButton, "NextFaceButton");
prevButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectPreviousFace);
nextButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectNextFace);
setText("HairChoiceT", wm->getGameSettingString("sRaceMenu3", "Change Hair"));
setText("HairChoiceT", mWindowManager.getGameSettingString("sRaceMenu3", "Change Hair"));
getWidget(prevButton, "PrevHairButton");
getWidget(nextButton, "NextHairButton");
prevButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectPreviousHair);
nextButton->eventMouseButtonClick = MyGUI::newDelegate(this, &RaceDialog::onSelectNextHair);
setText("RaceT", wm->getGameSettingString("sRaceMenu4", "Race"));
setText("RaceT", mWindowManager.getGameSettingString("sRaceMenu4", "Race"));
getWidget(raceList, "RaceList");
raceList->setScrollVisible(true);
raceList->eventListSelectAccept = MyGUI::newDelegate(this, &RaceDialog::onSelectRace);
raceList->eventListMouseItemActivate = MyGUI::newDelegate(this, &RaceDialog::onSelectRace);
raceList->eventListChangePosition = MyGUI::newDelegate(this, &RaceDialog::onSelectRace);
setText("SkillsT", wm->getGameSettingString("sBonusSkillTitle", "Skill Bonus"));
setText("SkillsT", mWindowManager.getGameSettingString("sBonusSkillTitle", "Skill Bonus"));
getWidget(skillList, "SkillList");
setText("SpellPowerT", wm->getGameSettingString("sRaceMenu7", "Specials"));
setText("SpellPowerT", mWindowManager.getGameSettingString("sRaceMenu7", "Specials"));
getWidget(spellPowerList, "SpellPowerList");
// TODO: These buttons should be managed by a Dialog class
@ -152,7 +149,7 @@ int wrap(int index, int max)
void RaceDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void RaceDialog::onBackClicked(MyGUI::Widget* _sender)
@ -215,7 +212,7 @@ void RaceDialog::updateRaces()
{
raceList->removeAllItems();
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
ESMS::RecListT<ESM::Race>::MapType::const_iterator it = store.races.list.begin();
ESMS::RecListT<ESM::Race>::MapType::const_iterator end = store.races.list.end();
@ -249,8 +246,7 @@ void RaceDialog::updateSkills()
const int lineHeight = 18;
MyGUI::IntCoord coord1(0, 0, skillList->getWidth(), 18);
WindowManager *wm = environment.mWindowManager;
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
const ESM::Race *race = store.races.find(currentRaceId);
int count = sizeof(race->data.bonus)/sizeof(race->data.bonus[0]); // TODO: Find a portable macro for this ARRAYSIZE?
for (int i = 0; i < count; ++i)
@ -261,7 +257,7 @@ void RaceDialog::updateSkills()
skillWidget = skillList->createWidget<MWSkill>("MW_StatNameValue", coord1, MyGUI::Align::Default,
std::string("Skill") + boost::lexical_cast<std::string>(i));
skillWidget->setWindowManager(wm);
skillWidget->setWindowManager(&mWindowManager);
skillWidget->setSkillNumber(skillId);
skillWidget->setSkillValue(MWSkill::SkillValue(race->data.bonus[i].bonus));
@ -286,7 +282,7 @@ void RaceDialog::updateSpellPowers()
const int lineHeight = 18;
MyGUI::IntCoord coord(0, 0, spellPowerList->getWidth(), 18);
ESMS::ESMStore &store = environment.mWorld->getStore();
ESMS::ESMStore &store = mWindowManager.getStore();
const ESM::Race *race = store.races.find(currentRaceId);
std::vector<std::string>::const_iterator it = race->powers.list.begin();
@ -295,7 +291,7 @@ void RaceDialog::updateSpellPowers()
{
const std::string &spellpower = *it;
spellPowerWidget = spellPowerList->createWidget<MWSpell>("MW_StatName", coord, MyGUI::Align::Default, std::string("SpellPower") + boost::lexical_cast<std::string>(i));
spellPowerWidget->setEnvironment(&environment);
spellPowerWidget->setWindowManager(&mWindowManager);
spellPowerWidget->setSpellId(spellpower);
spellPowerItems.push_back(spellPowerWidget);

@ -7,9 +7,9 @@
#include <boost/array.hpp>
namespace MWWorld
namespace MWGui
{
class Environment;
class WindowManager;
}
/*
@ -24,7 +24,7 @@ namespace MWGui
class RaceDialog : public WindowBase
{
public:
RaceDialog(MWWorld::Environment& environment);
RaceDialog(WindowManager& parWindowManager);
enum Gender
{
@ -53,11 +53,6 @@ namespace MWGui
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onHeadRotate(MyGUI::VScroll* _sender, size_t _position);

@ -1,6 +1,4 @@
#include "review.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "window_manager.hpp"
#include "widgets.hpp"
#include "components/esm_store/store.hpp"
@ -8,53 +6,56 @@
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <cmath>
#undef min
#undef max
using namespace MWGui;
using namespace Widgets;
const int ReviewDialog::lineHeight = 18;
ReviewDialog::ReviewDialog(MWWorld::Environment& environment)
: WindowBase("openmw_chargen_review_layout.xml", environment)
ReviewDialog::ReviewDialog(WindowManager& parWindowManager)
: WindowBase("openmw_chargen_review_layout.xml", parWindowManager)
, lastPos(0)
{
// Centre dialog
center();
WindowManager *wm = environment.mWindowManager;
// Setup static stats
ButtonPtr button;
getWidget(nameWidget, "NameText");
getWidget(button, "NameButton");
button->setCaption(wm->getGameSettingString("sName", ""));
button->setCaption(mWindowManager.getGameSettingString("sName", ""));
button->eventMouseButtonClick = MyGUI::newDelegate(this, &ReviewDialog::onNameClicked);;
getWidget(raceWidget, "RaceText");
getWidget(button, "RaceButton");
button->setCaption(wm->getGameSettingString("sRace", ""));
button->setCaption(mWindowManager.getGameSettingString("sRace", ""));
button->eventMouseButtonClick = MyGUI::newDelegate(this, &ReviewDialog::onRaceClicked);;
getWidget(classWidget, "ClassText");
getWidget(button, "ClassButton");
button->setCaption(wm->getGameSettingString("sClass", ""));
button->setCaption(mWindowManager.getGameSettingString("sClass", ""));
button->eventMouseButtonClick = MyGUI::newDelegate(this, &ReviewDialog::onClassClicked);;
getWidget(birthSignWidget, "SignText");
getWidget(button, "SignButton");
button->setCaption(wm->getGameSettingString("sBirthSign", ""));
button->setCaption(mWindowManager.getGameSettingString("sBirthSign", ""));
button->eventMouseButtonClick = MyGUI::newDelegate(this, &ReviewDialog::onBirthSignClicked);;
// Setup dynamic stats
getWidget(health, "Health");
health->setTitle(wm->getGameSettingString("sHealth", ""));
health->setTitle(mWindowManager.getGameSettingString("sHealth", ""));
health->setValue(45, 45);
getWidget(magicka, "Magicka");
magicka->setTitle(wm->getGameSettingString("sMagic", ""));
magicka->setTitle(mWindowManager.getGameSettingString("sMagic", ""));
magicka->setValue(50, 50);
getWidget(fatigue, "Fatigue");
fatigue->setTitle(wm->getGameSettingString("sFatigue", ""));
fatigue->setTitle(mWindowManager.getGameSettingString("sFatigue", ""));
fatigue->setValue(160, 160);
// Setup attributes
@ -64,7 +65,7 @@ ReviewDialog::ReviewDialog(MWWorld::Environment& environment)
{
getWidget(attribute, std::string("Attribute") + boost::lexical_cast<std::string>(idx));
attributeWidgets.insert(std::make_pair(static_cast<int>(ESM::Attribute::attributeIds[idx]), attribute));
attribute->setWindowManager(wm);
attribute->setWindowManager(&mWindowManager);
attribute->setAttributeId(ESM::Attribute::attributeIds[idx]);
attribute->setAttributeValue(MWAttribute::AttributeValue(0, 0));
}
@ -79,8 +80,8 @@ ReviewDialog::ReviewDialog(MWWorld::Environment& environment)
for (int i = 0; i < ESM::Skill::Length; ++i)
{
skillValues.insert(std::pair<int, MWMechanics::Stat<float> >(i, MWMechanics::Stat<float>()));
skillWidgetMap.insert(std::pair<int, MyGUI::StaticTextPtr>(i, (MyGUI::StaticTextPtr)nullptr));
skillValues.insert(std::make_pair(i, MWMechanics::Stat<float>()));
skillWidgetMap.insert(std::make_pair(i, static_cast<MyGUI::StaticText*> (0)));
}
static_cast<MyGUI::WindowPtr>(mMainWidget)->eventWindowChangeCoord = MyGUI::newDelegate(this, &ReviewDialog::onWindowResize);
@ -116,7 +117,7 @@ void ReviewDialog::onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos
}
}
void ReviewDialog::onWindowResize(MyGUI::WidgetPtr window)
void ReviewDialog::onWindowResize(MyGUI::Window* window)
{
updateScroller();
}
@ -129,7 +130,7 @@ void ReviewDialog::setPlayerName(const std::string &name)
void ReviewDialog::setRace(const std::string &raceId_)
{
raceId = raceId_;
const ESM::Race *race = environment.mWorld->getStore().races.search(raceId);
const ESM::Race *race = mWindowManager.getStore().races.search(raceId);
if (race)
raceWidget->setCaption(race->name);
}
@ -143,7 +144,7 @@ void ReviewDialog::setClass(const ESM::Class& class_)
void ReviewDialog::setBirthSign(const std::string& signId)
{
birthSignId = signId;
const ESM::BirthSign *sign = environment.mWorld->getStore().birthSigns.search(birthSignId);
const ESM::BirthSign *sign = mWindowManager.getStore().birthSigns.search(birthSignId);
if (sign)
birthSignWidget->setCaption(sign->name);
}
@ -273,15 +274,13 @@ void ReviewDialog::addItem(const std::string text, MyGUI::IntCoord &coord1, MyGU
void ReviewDialog::addSkills(const SkillList &skills, const std::string &titleId, const std::string &titleDefault, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
WindowManager *wm = environment.mWindowManager;
// Add a line separator if there are items above
if (!skillWidgets.empty())
{
addSeparator(coord1, coord2);
}
addGroup(wm->getGameSettingString(titleId, titleDefault), coord1, coord2);
addGroup(mWindowManager.getGameSettingString(titleId, titleDefault), coord1, coord2);
SkillList::const_iterator end = skills.end();
for (SkillList::const_iterator it = skills.begin(); it != end; ++it)
@ -300,7 +299,7 @@ void ReviewDialog::addSkills(const SkillList &skills, const std::string &titleId
style = CS_Super;
else if (modified < base)
style = CS_Sub;
MyGUI::StaticTextPtr widget = addValueItem(wm->getGameSettingString(skillNameId, skillNameId), boost::lexical_cast<std::string>(static_cast<int>(modified)), style, coord1, coord2);
MyGUI::StaticTextPtr widget = addValueItem(mWindowManager.getGameSettingString(skillNameId, skillNameId), boost::lexical_cast<std::string>(static_cast<int>(modified)), style, coord1, coord2);
skillWidgetMap[skillId] = widget;
}
}
@ -340,7 +339,7 @@ void ReviewDialog::updateScroller()
void ReviewDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void ReviewDialog::onBackClicked(MyGUI::Widget* _sender)
@ -350,20 +349,20 @@ void ReviewDialog::onBackClicked(MyGUI::Widget* _sender)
void ReviewDialog::onNameClicked(MyGUI::Widget* _sender)
{
eventNameActivated();
eventActivateDialog(NAME_DIALOG);
}
void ReviewDialog::onRaceClicked(MyGUI::Widget* _sender)
{
eventRaceActivated();
eventActivateDialog(RACE_DIALOG);
}
void ReviewDialog::onClassClicked(MyGUI::Widget* _sender)
{
eventClassActivated();
eventActivateDialog(CLASS_DIALOG);
}
void ReviewDialog::onBirthSignClicked(MyGUI::Widget* _sender)
{
eventBirthSignActivated();
eventActivateDialog(BIRTHSIGN_DIALOG);
}

@ -5,9 +5,9 @@
#include "../mwmechanics/stat.hpp"
#include "widgets.hpp"
namespace MWWorld
namespace MWGui
{
class Environment;
class WindowManager;
}
/*
@ -22,9 +22,15 @@ namespace MWGui
class ReviewDialog : public WindowBase
{
public:
enum Dialogs {
NAME_DIALOG,
RACE_DIALOG,
CLASS_DIALOG,
BIRTHSIGN_DIALOG
};
typedef std::vector<int> SkillList;
ReviewDialog(MWWorld::Environment& environment);
ReviewDialog(WindowManager& parWindowManager);
void setPlayerName(const std::string &name);
void setRace(const std::string &raceId);
@ -44,36 +50,14 @@ namespace MWGui
// Events
typedef delegates::CDelegate0 EventHandle_Void;
typedef delegates::CDelegate1<int> EventHandle_Int;
/** Event : Back button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventBack;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
/** Event : Activate name dialog.\n
signature : void method()\n
*/
EventHandle_Void eventNameActivated;
/** Event : Activate race dialog.\n
signature : void method()\n
*/
EventHandle_Void eventRaceActivated;
/** Event : Activate class dialog.\n
signature : void method()\n
*/
EventHandle_Void eventClassActivated;
/** Event : Activate birth sign dialog.\n
signature : void method()\n
*/
EventHandle_Void eventBirthSignActivated;
EventHandle_Int eventActivateDialog;
protected:
void onOkClicked(MyGUI::Widget* _sender);
@ -101,7 +85,7 @@ namespace MWGui
void updateSkillArea();
void onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos);
void onWindowResize(MyGUI::WidgetPtr window);
void onWindowResize(MyGUI::Window* window);
static const int lineHeight;

@ -0,0 +1,370 @@
#include "stats_window.hpp"
#include "../mwmechanics/mechanicsmanager.hpp"
#include "window_manager.hpp"
#include <cmath>
#include <algorithm>
#include <iterator>
#include <boost/lexical_cast.hpp>
using namespace MWGui;
const int StatsWindow::lineHeight = 18;
StatsWindow::StatsWindow (WindowManager& parWindowManager)
: WindowBase("openmw_stats_window_layout.xml", parWindowManager)
, lastPos(0)
, reputation(0)
, bounty(0)
{
setCoord(0,0,498, 342);
const char *names[][2] =
{
{ "Attrib1", "sAttributeStrength" },
{ "Attrib2", "sAttributeIntelligence" },
{ "Attrib3", "sAttributeWillpower" },
{ "Attrib4", "sAttributeAgility" },
{ "Attrib5", "sAttributeSpeed" },
{ "Attrib6", "sAttributeEndurance" },
{ "Attrib7", "sAttributePersonality" },
{ "Attrib8", "sAttributeLuck" },
{ "Health_str", "sHealth" },
{ "Magicka_str", "sMagic" },
{ "Fatigue_str", "sFatigue" },
{ "Level_str", "sLevel" },
{ "Race_str", "sRace" },
{ "Class_str", "sClass" },
{ 0, 0 }
};
const ESMS::ESMStore &store = mWindowManager.getStore();
for (int i=0; names[i][0]; ++i)
{
setText (names[i][0], store.gameSettings.find (names[i][1])->str);
}
getWidget(skillAreaWidget, "Skills");
getWidget(skillClientWidget, "SkillClient");
getWidget(skillScrollerWidget, "SkillScroller");
skillScrollerWidget->eventScrollChangePosition = MyGUI::newDelegate(this, &StatsWindow::onScrollChangePosition);
updateScroller();
for (int i = 0; i < ESM::Skill::Length; ++i)
{
skillValues.insert(std::pair<int, MWMechanics::Stat<float> >(i, MWMechanics::Stat<float>()));
skillWidgetMap.insert(std::pair<int, MyGUI::StaticTextPtr>(i, nullptr));
}
MyGUI::WindowPtr t = static_cast<MyGUI::WindowPtr>(mMainWidget);
t->eventWindowChangeCoord = MyGUI::newDelegate(this, &StatsWindow::onWindowResize);
}
void StatsWindow::onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos)
{
int diff = lastPos - pos;
// Adjust position of all widget according to difference
if (diff == 0)
return;
lastPos = pos;
std::vector<MyGUI::WidgetPtr>::const_iterator end = skillWidgets.end();
for (std::vector<MyGUI::WidgetPtr>::const_iterator it = skillWidgets.begin(); it != end; ++it)
{
(*it)->setCoord((*it)->getCoord() + MyGUI::IntPoint(0, diff));
}
}
void StatsWindow::onWindowResize(MyGUI::Window* window)
{
updateScroller();
}
void StatsWindow::setBar(const std::string& name, const std::string& tname, int val, int max)
{
MyGUI::ProgressPtr pt;
getWidget(pt, name);
pt->setProgressRange(max);
pt->setProgressPosition(val);
std::stringstream out;
out << val << "/" << max;
setText(tname, out.str().c_str());
}
void StatsWindow::setPlayerName(const std::string& playerName)
{
mMainWidget->setCaption(playerName);
}
void StatsWindow::setStyledText(MyGUI::StaticTextPtr widget, ColorStyle style, const std::string &value)
{
widget->setCaption(value);
if (style == CS_Super)
widget->setTextColour(MyGUI::Colour(0, 1, 0));
else if (style == CS_Sub)
widget->setTextColour(MyGUI::Colour(1, 0, 0));
else
widget->setTextColour(MyGUI::Colour(1, 1, 1));
}
void StatsWindow::setValue (const std::string& id, const MWMechanics::Stat<int>& value)
{
static const char *ids[] =
{
"AttribVal1", "AttribVal2", "AttribVal3", "AttribVal4", "AttribVal5",
"AttribVal6", "AttribVal7", "AttribVal8",
0
};
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
std::ostringstream valueString;
valueString << value.getModified();
setText (id, valueString.str());
if (value.getModified()>value.getBase())
setTextColor (id, 0, 1, 0);
else if (value.getModified()<value.getBase())
setTextColor (id, 1, 0, 0);
else
setTextColor (id, 1, 1, 1);
break;
}
}
void StatsWindow::setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value)
{
static const char *ids[] =
{
"HBar", "MBar", "FBar",
0
};
for (int i=0; ids[i]; ++i)
if (ids[i]==id)
{
std::string id (ids[i]);
setBar (id, id + "T", value.getCurrent(), value.getModified());
}
}
void StatsWindow::setValue (const std::string& id, const std::string& value)
{
if (id=="name")
setPlayerName (value);
else if (id=="race")
setText ("RaceText", value);
else if (id=="class")
setText ("ClassText", value);
}
void StatsWindow::setValue (const std::string& id, int value)
{
if (id=="level")
{
std::ostringstream text;
text << value;
setText("LevelText", text.str());
}
}
void StatsWindow::setValue(const ESM::Skill::SkillEnum parSkill, const MWMechanics::Stat<float>& value)
{
skillValues[parSkill] = value;
MyGUI::StaticTextPtr widget = skillWidgetMap[(int)parSkill];
if (widget)
{
float modified = value.getModified(), base = value.getBase();
std::string text = boost::lexical_cast<std::string>(std::floor(modified));
ColorStyle style = CS_Normal;
if (modified > base)
style = CS_Super;
else if (modified < base)
style = CS_Sub;
setStyledText(widget, style, text);
}
}
void StatsWindow::configureSkills (const std::vector<int>& major, const std::vector<int>& minor)
{
majorSkills = major;
minorSkills = minor;
// Update misc skills with the remaining skills not in major or minor
std::set<int> skillSet;
std::copy(major.begin(), major.end(), std::inserter(skillSet, skillSet.begin()));
std::copy(minor.begin(), minor.end(), std::inserter(skillSet, skillSet.begin()));
boost::array<ESM::Skill::SkillEnum, ESM::Skill::Length>::const_iterator end = ESM::Skill::skillIds.end();
miscSkills.clear();
for (boost::array<ESM::Skill::SkillEnum, ESM::Skill::Length>::const_iterator it = ESM::Skill::skillIds.begin(); it != end; ++it)
{
int skill = *it;
if (skillSet.find(skill) == skillSet.end())
miscSkills.push_back(skill);
}
}
void StatsWindow::setFactions (const std::vector<Faction>& factions)
{
this->factions = factions;
}
void StatsWindow::setBirthSign (const std::string& signId)
{
birthSignId = signId;
}
void StatsWindow::addSeparator(MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticImagePtr separator = skillClientWidget->createWidget<MyGUI::StaticImage>("MW_HLine", MyGUI::IntCoord(10, coord1.top, coord1.width + coord2.width - 4, 18), MyGUI::Align::Default);
skillWidgets.push_back(separator);
coord1.top += separator->getHeight();
coord2.top += separator->getHeight();
}
void StatsWindow::addGroup(const std::string &label, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr groupWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandBrightText", MyGUI::IntCoord(0, coord1.top, coord1.width + coord2.width, coord1.height), MyGUI::Align::Default);
groupWidget->setCaption(label);
skillWidgets.push_back(groupWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
}
MyGUI::StaticTextPtr StatsWindow::addValueItem(const std::string text, const std::string &value, ColorStyle style, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr skillNameWidget, skillValueWidget;
skillNameWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandText", coord1, MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillValueWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandTextRight", coord2, MyGUI::Align::Default);
setStyledText(skillValueWidget, style, value);
skillWidgets.push_back(skillNameWidget);
skillWidgets.push_back(skillValueWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
return skillValueWidget;
}
void StatsWindow::addItem(const std::string text, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
MyGUI::StaticTextPtr skillNameWidget;
skillNameWidget = skillClientWidget->createWidget<MyGUI::StaticText>("SandText", coord1 + MyGUI::IntSize(coord2.width, 0), MyGUI::Align::Default);
skillNameWidget->setCaption(text);
skillWidgets.push_back(skillNameWidget);
coord1.top += lineHeight;
coord2.top += lineHeight;
}
void StatsWindow::addSkills(const SkillList &skills, const std::string &titleId, const std::string &titleDefault, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2)
{
// Add a line separator if there are items above
if (!skillWidgets.empty())
{
addSeparator(coord1, coord2);
}
addGroup(mWindowManager.getGameSettingString(titleId, titleDefault), coord1, coord2);
SkillList::const_iterator end = skills.end();
for (SkillList::const_iterator it = skills.begin(); it != end; ++it)
{
int skillId = *it;
if (skillId < 0 || skillId > ESM::Skill::Length) // Skip unknown skill indexes
continue;
assert(skillId >= 0 && skillId < ESM::Skill::Length);
const std::string &skillNameId = ESMS::Skill::sSkillNameIds[skillId];
const MWMechanics::Stat<float> &stat = skillValues.find(skillId)->second;
float base = stat.getBase();
float modified = stat.getModified();
ColorStyle style = CS_Normal;
if (modified > base)
style = CS_Super;
else if (modified < base)
style = CS_Sub;
MyGUI::StaticTextPtr widget = addValueItem(mWindowManager.getGameSettingString(skillNameId, skillNameId), boost::lexical_cast<std::string>(static_cast<int>(modified)), style, coord1, coord2);
skillWidgetMap[skillId] = widget;
}
}
void StatsWindow::updateSkillArea()
{
for (std::vector<MyGUI::WidgetPtr>::iterator it = skillWidgets.begin(); it != skillWidgets.end(); ++it)
{
MyGUI::Gui::getInstance().destroyWidget(*it);
}
skillWidgets.clear();
const int valueSize = 40;
MyGUI::IntCoord coord1(10, 0, skillClientWidget->getWidth() - (10 + valueSize), 18);
MyGUI::IntCoord coord2(coord1.left + coord1.width, coord1.top, valueSize, coord1.height);
if (!majorSkills.empty())
addSkills(majorSkills, "sSkillClassMajor", "Major Skills", coord1, coord2);
if (!minorSkills.empty())
addSkills(minorSkills, "sSkillClassMinor", "Minor Skills", coord1, coord2);
if (!miscSkills.empty())
addSkills(miscSkills, "sSkillClassMisc", "Misc Skills", coord1, coord2);
ESMS::ESMStore &store = mWindowManager.getStore();
if (!factions.empty())
{
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(mWindowManager.getGameSettingString("sFaction", "Faction"), coord1, coord2);
FactionList::const_iterator end = factions.end();
for (FactionList::const_iterator it = factions.begin(); it != end; ++it)
{
const ESM::Faction *faction = store.factions.find(it->first);
addItem(faction->name, coord1, coord2);
// TODO: Faction rank should be placed in tooltip
}
}
if (!birthSignId.empty())
{
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addGroup(mWindowManager.getGameSettingString("sSign", "Sign"), coord1, coord2);
const ESM::BirthSign *sign = store.birthSigns.find(birthSignId);
addItem(sign->name, coord1, coord2);
}
// Add a line separator if there are items above
if (!skillWidgets.empty())
addSeparator(coord1, coord2);
addValueItem(mWindowManager.getGameSettingString("sReputation", "Reputation"), boost::lexical_cast<std::string>(static_cast<int>(reputation)), CS_Normal, coord1, coord2);
addValueItem(mWindowManager.getGameSettingString("sBounty", "Bounty"), boost::lexical_cast<std::string>(static_cast<int>(bounty)), CS_Normal, coord1, coord2);
clientHeight = coord1.top;
updateScroller();
}
void StatsWindow::updateScroller()
{
skillScrollerWidget->setScrollRange(std::max(clientHeight - skillClientWidget->getHeight(), 0));
skillScrollerWidget->setScrollPage(std::max(skillClientWidget->getHeight() - lineHeight, 0));
}

@ -0,0 +1,80 @@
#ifndef MWGUI_STATS_WINDOW_H
#define MWGUI_STATS_WINDOW_H
#include <components/esm_store/store.hpp>
#include <sstream>
#include <set>
#include <string>
#include <utility>
#include "../mwmechanics/stat.hpp"
#include "window_base.hpp"
namespace MWGui
{
class WindowManager;
class StatsWindow : public WindowBase
{
public:
typedef std::pair<std::string, int> Faction;
typedef std::vector<Faction> FactionList;
typedef std::vector<int> SkillList;
StatsWindow(WindowManager& parWindowManager);
void setBar(const std::string& name, const std::string& tname, int val, int max);
void setPlayerName(const std::string& playerName);
/// Set value for the given ID.
void setValue (const std::string& id, const MWMechanics::Stat<int>& value);
void setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value);
void setValue (const std::string& id, const std::string& value);
void setValue (const std::string& id, int value);
void setValue(const ESM::Skill::SkillEnum parSkill, const MWMechanics::Stat<float>& value);
void configureSkills (const SkillList& major, const SkillList& minor);
void setFactions (const std::vector<Faction>& factions);
void setBirthSign (const std::string &signId);
void setReputation (int reputation) { this->reputation = reputation; }
void setBounty (int bounty) { this->bounty = bounty; }
void updateSkillArea();
private:
enum ColorStyle
{
CS_Sub,
CS_Normal,
CS_Super
};
void setStyledText(MyGUI::StaticTextPtr widget, ColorStyle style, const std::string &value);
void addSkills(const SkillList &skills, const std::string &titleId, const std::string &titleDefault, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addSeparator(MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addGroup(const std::string &label, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
MyGUI::StaticTextPtr addValueItem(const std::string text, const std::string &value, ColorStyle style, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void addItem(const std::string text, MyGUI::IntCoord &coord1, MyGUI::IntCoord &coord2);
void updateScroller();
void onScrollChangePosition(MyGUI::VScrollPtr scroller, size_t pos);
void onWindowResize(MyGUI::Window* window);
static const int lineHeight;
MyGUI::WidgetPtr skillAreaWidget, skillClientWidget;
MyGUI::VScrollPtr skillScrollerWidget;
int lastPos, clientHeight;
SkillList majorSkills, minorSkills, miscSkills;
std::map<int, MWMechanics::Stat<float> > skillValues;
std::map<int, MyGUI::StaticTextPtr> skillWidgetMap;
std::map<std::string, MyGUI::WidgetPtr> factionWidgetMap;
FactionList factions; ///< Stores a list of factions and the current rank
std::string birthSignId;
int reputation, bounty;
std::vector<MyGUI::WidgetPtr> skillWidgets; //< Skills and other information
};
}
#endif

@ -1,12 +1,10 @@
#include "text_input.hpp"
#include "window_manager.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
using namespace MWGui;
TextInputDialog::TextInputDialog(MWWorld::Environment& environment)
: WindowBase("openmw_text_input_layout.xml", environment)
TextInputDialog::TextInputDialog(WindowManager& parWindowManager)
: WindowBase("openmw_text_input_layout.xml", parWindowManager)
{
// Centre dialog
center();
@ -55,10 +53,10 @@ void TextInputDialog::open()
void TextInputDialog::onOkClicked(MyGUI::Widget* _sender)
{
eventDone();
eventDone(this);
}
void TextInputDialog::onTextAccepted(MyGUI::Edit* _sender)
{
eventDone();
eventDone(this);
}

@ -3,9 +3,9 @@
#include "window_base.hpp"
namespace MWWorld
namespace MWGui
{
class Environment;
class WindowManager;
}
/*
@ -18,7 +18,7 @@ namespace MWGui
class TextInputDialog : public WindowBase
{
public:
TextInputDialog(MWWorld::Environment& environment);
TextInputDialog(WindowManager& parWindowManager);
std::string getTextInput() const { return textEdit ? textEdit->getOnlyText() : ""; }
void setTextInput(const std::string &text) { if (textEdit) textEdit->setOnlyText(text); }
@ -27,14 +27,6 @@ namespace MWGui
void setTextLabel(const std::string &label);
void open();
// Events
typedef delegates::CDelegate0 EventHandle_Void;
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_Void eventDone;
protected:
void onOkClicked(MyGUI::Widget* _sender);
void onTextAccepted(MyGUI::Edit* _sender);

@ -1,11 +1,12 @@
#include "widgets.hpp"
#include "window_manager.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "components/esm_store/store.hpp"
#include <boost/lexical_cast.hpp>
#undef min
#undef max
using namespace MWGui;
using namespace MWGui::Widgets;
@ -89,53 +90,53 @@ void MWSkill::onClicked(MyGUI::Widget* _sender)
void MWSkill::_initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name)
{
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
initialiseWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
MWSkill::~MWSkill()
{
shutdownWidgetSkin();
shutdownWidgetSkin();
}
void MWSkill::baseChangeWidgetSkin(ResourceSkin* _info)
{
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
void MWSkill::initialiseWidgetSkin(ResourceSkin* _info)
{
for (VectorWidgetPtr::iterator iter=mWidgetChildSkin.begin(); iter!=mWidgetChildSkin.end(); ++iter)
{
{
const std::string &name = *(*iter)->_getInternalData<std::string>();
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! skillNameWidget, "widget already assigned");
skillNameWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! skillValueWidget, "widget already assigned");
skillValueWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatNameButton")
{
MYGUI_DEBUG_ASSERT( ! skillNameWidget, "widget already assigned");
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! skillNameWidget, "widget already assigned");
skillNameWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! skillValueWidget, "widget already assigned");
skillValueWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatNameButton")
{
MYGUI_DEBUG_ASSERT( ! skillNameWidget, "widget already assigned");
MyGUI::ButtonPtr button = (*iter)->castType<Button>();
skillNameWidget = button;
button->eventMouseButtonClick = MyGUI::newDelegate(this, &MWSkill::onClicked);
}
else if (name == "StatValueButton")
{
MYGUI_DEBUG_ASSERT( ! skillValueWidget, "widget already assigned");
}
else if (name == "StatValueButton")
{
MYGUI_DEBUG_ASSERT( ! skillValueWidget, "widget already assigned");
MyGUI::ButtonPtr button = (*iter)->castType<Button>();
skillNameWidget = button;
button->eventMouseButtonClick = MyGUI::newDelegate(this, &MWSkill::onClicked);
}
}
}
}
}
void MWSkill::shutdownWidgetSkin()
@ -208,53 +209,53 @@ void MWAttribute::updateWidgets()
void MWAttribute::_initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name)
{
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
initialiseWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
MWAttribute::~MWAttribute()
{
shutdownWidgetSkin();
shutdownWidgetSkin();
}
void MWAttribute::baseChangeWidgetSkin(ResourceSkin* _info)
{
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
void MWAttribute::initialiseWidgetSkin(ResourceSkin* _info)
{
for (VectorWidgetPtr::iterator iter=mWidgetChildSkin.begin(); iter!=mWidgetChildSkin.end(); ++iter)
{
{
const std::string &name = *(*iter)->_getInternalData<std::string>();
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! attributeNameWidget, "widget already assigned");
attributeNameWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! attributeValueWidget, "widget already assigned");
attributeValueWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatNameButton")
{
MYGUI_DEBUG_ASSERT( ! attributeNameWidget, "widget already assigned");
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! attributeNameWidget, "widget already assigned");
attributeNameWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! attributeValueWidget, "widget already assigned");
attributeValueWidget = (*iter)->castType<StaticText>();
}
else if (name == "StatNameButton")
{
MYGUI_DEBUG_ASSERT( ! attributeNameWidget, "widget already assigned");
MyGUI::ButtonPtr button = (*iter)->castType<Button>();
attributeNameWidget = button;
button->eventMouseButtonClick = MyGUI::newDelegate(this, &MWAttribute::onClicked);
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! attributeValueWidget, "widget already assigned");
}
else if (name == "StatValue")
{
MYGUI_DEBUG_ASSERT( ! attributeValueWidget, "widget already assigned");
MyGUI::ButtonPtr button = (*iter)->castType<Button>();
attributeNameWidget = button;
button->eventMouseButtonClick = MyGUI::newDelegate(this, &MWAttribute::onClicked);
}
}
}
}
}
void MWAttribute::shutdownWidgetSkin()
@ -264,7 +265,7 @@ void MWAttribute::shutdownWidgetSkin()
/* MWSpell */
MWSpell::MWSpell()
: env(nullptr)
: mWindowManager(nullptr)
, spellNameWidget(nullptr)
{
}
@ -277,7 +278,7 @@ void MWSpell::setSpellId(const std::string &spellId)
void MWSpell::createEffectWidgets(std::vector<MyGUI::WidgetPtr> &effects, MyGUI::WidgetPtr creator, MyGUI::IntCoord &coord)
{
ESMS::ESMStore &store = env->mWorld->getStore();
ESMS::ESMStore &store = mWindowManager->getStore();
const ESM::Spell *spell = store.spells.search(id);
MYGUI_ASSERT(spell, "spell with id '" << id << "' not found");
@ -286,7 +287,7 @@ void MWSpell::createEffectWidgets(std::vector<MyGUI::WidgetPtr> &effects, MyGUI:
for (std::vector<ESM::ENAMstruct>::const_iterator it = spell->effects.list.begin(); it != end; ++it)
{
effect = creator->createWidget<MWSpellEffect>("MW_EffectImage", coord, MyGUI::Align::Default);
effect->setEnvironment(env);
effect->setWindowManager(mWindowManager);
effect->setSpellEffect(*it);
effects.push_back(effect);
coord.top += effect->getHeight();
@ -295,9 +296,9 @@ void MWSpell::createEffectWidgets(std::vector<MyGUI::WidgetPtr> &effects, MyGUI:
void MWSpell::updateWidgets()
{
if (spellNameWidget && env)
if (spellNameWidget && mWindowManager)
{
ESMS::ESMStore &store = env->mWorld->getStore();
ESMS::ESMStore &store = mWindowManager->getStore();
const ESM::Spell *spell = store.spells.search(id);
if (spell)
spellNameWidget->setCaption(spell->name);
@ -308,34 +309,34 @@ void MWSpell::updateWidgets()
void MWSpell::_initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name)
{
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
initialiseWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
MWSpell::~MWSpell()
{
shutdownWidgetSkin();
shutdownWidgetSkin();
}
void MWSpell::baseChangeWidgetSkin(ResourceSkin* _info)
{
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
void MWSpell::initialiseWidgetSkin(ResourceSkin* _info)
{
for (VectorWidgetPtr::iterator iter=mWidgetChildSkin.begin(); iter!=mWidgetChildSkin.end(); ++iter)
{
{
const std::string &name = *(*iter)->_getInternalData<std::string>();
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! spellNameWidget, "widget already assigned");
spellNameWidget = (*iter)->castType<StaticText>();
}
}
if (name == "StatName")
{
MYGUI_DEBUG_ASSERT( ! spellNameWidget, "widget already assigned");
spellNameWidget = (*iter)->castType<StaticText>();
}
}
}
void MWSpell::shutdownWidgetSkin()
@ -345,7 +346,7 @@ void MWSpell::shutdownWidgetSkin()
/* MWSpellEffect */
MWSpellEffect::MWSpellEffect()
: env(nullptr)
: mWindowManager(nullptr)
, imageWidget(nullptr)
, textWidget(nullptr)
{
@ -359,11 +360,10 @@ void MWSpellEffect::setSpellEffect(SpellEffectValue value)
void MWSpellEffect::updateWidgets()
{
if (!env)
if (!mWindowManager)
return;
ESMS::ESMStore &store = env->mWorld->getStore();
WindowManager *wm = env->mWindowManager;
ESMS::ESMStore &store = mWindowManager->getStore();
const ESM::MagicEffect *magicEffect = store.magicEffects.search(effect.effectID);
if (textWidget)
{
@ -373,7 +373,7 @@ void MWSpellEffect::updateWidgets()
std::string spellLine = "";
if (effect.skill >= 0 && effect.skill < ESM::Skill::Length)
{
spellLine += " " + wm->getGameSettingString(ESM::Skill::sSkillNameIds[effect.skill], "");
spellLine += " " + mWindowManager->getGameSettingString(ESM::Skill::sSkillNameIds[effect.skill], "");
}
if (effect.attribute >= 0 && effect.attribute < 8)
{
@ -387,7 +387,7 @@ void MWSpellEffect::updateWidgets()
"sAttributePersonality",
"sAttributeLuck"
};
spellLine += " " + wm->getGameSettingString(attributes[effect.attribute], "");
spellLine += " " + mWindowManager->getGameSettingString(attributes[effect.attribute], "");
}
if (effect.magnMin >= 0 || effect.magnMax >= 0)
{
@ -423,39 +423,39 @@ void MWSpellEffect::updateWidgets()
void MWSpellEffect::_initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name)
{
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
Base::_initialise(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name);
initialiseWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
MWSpellEffect::~MWSpellEffect()
{
shutdownWidgetSkin();
shutdownWidgetSkin();
}
void MWSpellEffect::baseChangeWidgetSkin(ResourceSkin* _info)
{
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
void MWSpellEffect::initialiseWidgetSkin(ResourceSkin* _info)
{
for (VectorWidgetPtr::iterator iter=mWidgetChildSkin.begin(); iter!=mWidgetChildSkin.end(); ++iter)
{
{
const std::string &name = *(*iter)->_getInternalData<std::string>();
if (name == "Text")
{
MYGUI_DEBUG_ASSERT( ! textWidget, "widget already assigned");
textWidget = (*iter)->castType<StaticText>();
}
else if (name == "Image")
{
MYGUI_DEBUG_ASSERT( ! imageWidget, "widget already assigned");
imageWidget = (*iter)->castType<StaticImage>();
}
}
if (name == "Text")
{
MYGUI_DEBUG_ASSERT( ! textWidget, "widget already assigned");
textWidget = (*iter)->castType<StaticText>();
}
else if (name == "Image")
{
MYGUI_DEBUG_ASSERT( ! imageWidget, "widget already assigned");
imageWidget = (*iter)->castType<StaticImage>();
}
}
}
void MWSpellEffect::shutdownWidgetSkin()

@ -7,11 +7,6 @@
#include "../mwmechanics/stat.hpp"
namespace MWWorld
{
class Environment;
}
/*
This file contains various custom widgets used in OpenMW.
*/
@ -43,7 +38,7 @@ namespace MWGui
const SkillValue& getSkillValue() const { return value; }
// Events
typedef delegates::CDelegate1<MWSkill*> EventHandle_SkillVoid;
typedef delegates::CDelegate1<MWSkill*> EventHandle_SkillVoid;
/** Event : Skill clicked.\n
signature : void method(MWSkill* _sender)\n
@ -51,18 +46,18 @@ namespace MWGui
EventHandle_SkillVoid eventClicked;
/*internal:*/
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
protected:
virtual ~MWSkill();
virtual ~MWSkill();
void baseChangeWidgetSkin(ResourceSkin* _info);
void baseChangeWidgetSkin(ResourceSkin* _info);
void onClicked(MyGUI::Widget* _sender);
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
void updateWidgets();
@ -90,7 +85,7 @@ namespace MWGui
const AttributeValue& getAttributeValue() const { return value; }
// Events
typedef delegates::CDelegate1<MWAttribute*> EventHandle_AttributeVoid;
typedef delegates::CDelegate1<MWAttribute*> EventHandle_AttributeVoid;
/** Event : Attribute clicked.\n
signature : void method(MWAttribute* _sender)\n
@ -98,18 +93,18 @@ namespace MWGui
EventHandle_AttributeVoid eventClicked;
/*internal:*/
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
protected:
virtual ~MWAttribute();
virtual ~MWAttribute();
void baseChangeWidgetSkin(ResourceSkin* _info);
void baseChangeWidgetSkin(ResourceSkin* _info);
void onClicked(MyGUI::Widget* _sender);
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
void updateWidgets();
@ -129,28 +124,27 @@ namespace MWGui
typedef MWMechanics::Stat<int> SpellValue;
void setEnvironment(MWWorld::Environment *env_) { env = env_; }
void setWindowManager(WindowManager* parWindowManager) { mWindowManager = parWindowManager; }
void setSpellId(const std::string &id);
void createEffectWidgets(std::vector<MyGUI::WidgetPtr> &effects, MyGUI::WidgetPtr creator, MyGUI::IntCoord &coord);
MWWorld::Environment *getEnvironment() const { return env; }
const std::string &getSpellId() const { return id; }
/*internal:*/
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
protected:
virtual ~MWSpell();
virtual ~MWSpell();
void baseChangeWidgetSkin(ResourceSkin* _info);
void baseChangeWidgetSkin(ResourceSkin* _info);
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
void updateWidgets();
MWWorld::Environment *env;
WindowManager* mWindowManager;
std::string id;
MyGUI::StaticTextPtr spellNameWidget;
};
@ -164,27 +158,26 @@ namespace MWGui
typedef ESM::ENAMstruct SpellEffectValue;
void setEnvironment(MWWorld::Environment *env_) { env = env_; }
void setWindowManager(WindowManager* parWindowManager) { mWindowManager = parWindowManager; }
void setSpellEffect(SpellEffectValue value);
MWWorld::Environment *getEnvironment() const { return env; }
const SpellEffectValue &getSpellEffect() const { return effect; }
/*internal:*/
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
virtual void _initialise(WidgetStyle _style, const IntCoord& _coord, Align _align, ResourceSkin* _info, Widget* _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string& _name);
protected:
virtual ~MWSpellEffect();
virtual ~MWSpellEffect();
void baseChangeWidgetSkin(ResourceSkin* _info);
void baseChangeWidgetSkin(ResourceSkin* _info);
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
private:
void initialiseWidgetSkin(ResourceSkin* _info);
void shutdownWidgetSkin();
void updateWidgets();
MWWorld::Environment *env;
WindowManager* mWindowManager;
SpellEffectValue effect;
MyGUI::StaticImagePtr imageWidget;
MyGUI::StaticTextPtr textWidget;

@ -1,12 +1,11 @@
#include "window_base.hpp"
#include "../mwworld/environment.hpp"
#include "window_manager.hpp"
using namespace MWGui;
WindowBase::WindowBase(const std::string& parLayout, MWWorld::Environment& parEnvironment)
WindowBase::WindowBase(const std::string& parLayout, WindowManager& parWindowManager)
: Layout(parLayout)
, environment(parEnvironment)
, mWindowManager(parWindowManager)
{
}
@ -17,7 +16,7 @@ void WindowBase::open()
void WindowBase::center()
{
// Centre dialog
MyGUI::IntSize gameWindowSize = environment.mWindowManager->getGui()->getViewSize();
MyGUI::IntSize gameWindowSize = mWindowManager.getGui()->getViewSize();
MyGUI::IntCoord coord = mMainWidget->getCoord();
coord.left = (gameWindowSize.width - coord.width)/2;
coord.top = (gameWindowSize.height - coord.height)/2;

@ -3,23 +3,28 @@
#include <openengine/gui/layout.hpp>
namespace MWWorld
{
class Environment;
}
namespace MWGui
{
class WindowManager;
class WindowBase: public OEngine::GUI::Layout
{
public:
WindowBase(const std::string& parLayout, MWWorld::Environment& parEnvironment);
WindowBase(const std::string& parLayout, WindowManager& parWindowManager);
// Events
typedef MyGUI::delegates::CDelegate1<WindowBase*> EventHandle_WindowBase;
virtual void open();
void center();
/** Event : Dialog finished, OK button clicked.\n
signature : void method()\n
*/
EventHandle_WindowBase eventDone;
protected:
MWWorld::Environment& environment;
WindowManager& mWindowManager;
};
}

@ -7,6 +7,7 @@
#include "review.hpp"
#include "dialogue.hpp"
#include "dialogue_history.hpp"
#include "stats_window.hpp"
#include "../mwmechanics/mechanicsmanager.hpp"
#include "../mwinput/inputmanager.hpp"
@ -20,7 +21,7 @@
using namespace MWGui;
WindowManager::WindowManager(MyGUI::Gui *_gui, MWWorld::Environment& environment,
const Compiler::Extensions& extensions, bool newGame)
const Compiler::Extensions& extensions, bool fpsSwitch, bool newGame)
: environment(environment)
, nameDialog(nullptr)
, raceDialog(nullptr)
@ -32,11 +33,6 @@ WindowManager::WindowManager(MyGUI::Gui *_gui, MWWorld::Environment& environment
, createClassDialog(nullptr)
, birthSignDialog(nullptr)
, reviewDialog(nullptr)
, nameChosen(false)
, raceChosen(false)
, classChosen(false)
, birthSignChosen(false)
, reviewNext(false)
, gui(_gui)
, mode(GM_Game)
, nextMode(GM_Game)
@ -44,65 +40,68 @@ WindowManager::WindowManager(MyGUI::Gui *_gui, MWWorld::Environment& environment
, shown(GW_ALL)
, allowed(newGame ? GW_None : GW_ALL)
{
showFPSCounter = fpsSwitch;
creationStage = NotStarted;
//Register own widgets with MyGUI
MyGUI::FactoryManager::getInstance().registerFactory<DialogeHistory>("Widget");
// Get size info from the Gui object
assert(gui);
int w = gui->getViewSize().width;
int h = gui->getViewSize().height;
// Get size info from the Gui object
assert(gui);
int w = gui->getViewSize().width;
int h = gui->getViewSize().height;
hud = new HUD(w,h);
menu = new MainMenu(w,h);
map = new MapWindow();
stats = new StatsWindow (environment);
hud = new HUD(w,h, showFPSCounter);
menu = new MainMenu(w,h);
map = new MapWindow();
stats = new StatsWindow(*this);
#if 0
inventory = new InventoryWindow ();
inventory = new InventoryWindow ();
#endif
console = new Console(w,h, environment, extensions);
console = new Console(w,h, environment, extensions);
// The HUD is always on
hud->setVisible(true);
// The HUD is always on
hud->setVisible(true);
// Setup player stats
for (int i = 0; i < ESM::Attribute::Length; ++i)
{
playerAttributes.insert(std::make_pair(ESM::Attribute::attributeIds[i], MWMechanics::Stat<int>()));
}
// Setup player stats
for (int i = 0; i < ESM::Attribute::Length; ++i)
{
playerAttributes.insert(std::make_pair(ESM::Attribute::attributeIds[i], MWMechanics::Stat<int>()));
}
for (int i = 0; i < ESM::Skill::Length; ++i)
{
playerSkillValues.insert(std::make_pair(ESM::Skill::skillIds[i], MWMechanics::Stat<float>()));
}
for (int i = 0; i < ESM::Skill::Length; ++i)
{
playerSkillValues.insert(std::make_pair(ESM::Skill::skillIds[i], MWMechanics::Stat<float>()));
}
// Set up visibility
updateVisible();
// Set up visibility
updateVisible();
}
WindowManager::~WindowManager()
{
delete console;
delete hud;
delete map;
delete menu;
delete stats;
delete console;
delete hud;
delete map;
delete menu;
delete stats;
#if 0
delete inventory;
delete inventory;
#endif
delete nameDialog;
delete raceDialog;
delete dialogueWindow;
delete classChoiceDialog;
delete generateClassQuestionDialog;
delete generateClassResultDialog;
delete pickClassDialog;
delete createClassDialog;
delete birthSignDialog;
delete reviewDialog;
delete nameDialog;
delete raceDialog;
delete dialogueWindow;
delete classChoiceDialog;
delete generateClassQuestionDialog;
delete generateClassResultDialog;
delete pickClassDialog;
delete createClassDialog;
delete birthSignDialog;
delete reviewDialog;
cleanupGarbage();
cleanupGarbage();
}
void WindowManager::cleanupGarbage()
@ -127,6 +126,10 @@ void WindowManager::update()
environment.mInputManager->setGuiMode(nextMode);
nextMode = GM_Game;
}
if (showFPSCounter)
{
hud->setFPS(mFPS);
}
}
void WindowManager::setNextMode(GuiMode newMode)
@ -142,198 +145,193 @@ void WindowManager::setGuiMode(GuiMode newMode)
void WindowManager::updateVisible()
{
// Start out by hiding everything except the HUD
map->setVisible(false);
menu->setVisible(false);
stats->setVisible(false);
// Start out by hiding everything except the HUD
map->setVisible(false);
menu->setVisible(false);
stats->setVisible(false);
#if 0
inventory->setVisible(false);
inventory->setVisible(false);
#endif
console->disable();
// Mouse is visible whenever we're not in game mode
gui->setVisiblePointer(isGuiMode());
// If in game mode, don't show anything.
if(mode == GM_Game)
{
return;
}
if(mode == GM_MainMenu)
{
// Enable the main menu
menu->setVisible(true);
return;
}
if(mode == GM_Console)
{
console->enable();
return;
}
if (mode == GM_Name)
{
if (nameDialog)
removeDialog(nameDialog);
nameDialog = new TextInputDialog(environment);
std::string sName = getGameSettingString("sName", "Name");
nameDialog->setTextLabel(sName);
nameDialog->setTextInput(playerName);
nameDialog->setNextButtonShow(nameChosen || reviewNext);
nameDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onNameDialogDone);
nameDialog->open();
return;
}
if (mode == GM_Race)
{
if (raceDialog)
removeDialog(raceDialog);
raceDialog = new RaceDialog(environment);
raceDialog->setNextButtonShow(raceChosen || reviewNext);
raceDialog->setRaceId(playerRaceId);
raceDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onRaceDialogDone);
raceDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onRaceDialogBack);
raceDialog->open();
return;
}
if (mode == GM_Class)
{
if (classChoiceDialog)
removeDialog(classChoiceDialog);
classChoiceDialog = new ClassChoiceDialog(environment);
classChoiceDialog->eventButtonSelected = MyGUI::newDelegate(this, &WindowManager::onClassChoice);
classChoiceDialog->open();
return;
}
if (mode == GM_ClassGenerate)
{
generateClassStep = 0;
generateClass = "";
generateClassSpecializations[0] = 0;
generateClassSpecializations[1] = 0;
generateClassSpecializations[2] = 0;
showClassQuestionDialog();
return;
}
if (mode == GM_ClassPick)
{
if (pickClassDialog)
removeDialog(pickClassDialog);
pickClassDialog = new PickClassDialog(environment);
pickClassDialog->setNextButtonShow(classChosen || reviewNext);
pickClassDialog->setClassId(playerClass.name);
pickClassDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onPickClassDialogDone);
pickClassDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onPickClassDialogBack);
pickClassDialog->open();
return;
}
if (mode == GM_ClassCreate)
{
if (createClassDialog)
removeDialog(createClassDialog);
createClassDialog = new CreateClassDialog(environment);
createClassDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onCreateClassDialogDone);
createClassDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onCreateClassDialogBack);
createClassDialog->open();
return;
}
if (mode == GM_Birth)
{
if (birthSignDialog)
removeDialog(birthSignDialog);
birthSignDialog = new BirthDialog(environment);
birthSignDialog->setNextButtonShow(birthSignChosen || reviewNext);
birthSignDialog->setBirthId(playerBirthSignId);
birthSignDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onBirthSignDialogDone);
birthSignDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onBirthSignDialogBack);
birthSignDialog->open();
return;
}
if (mode == GM_Review)
{
reviewNext = false;
if (reviewDialog)
removeDialog(reviewDialog);
reviewDialog = new ReviewDialog(environment);
reviewDialog->setPlayerName(playerName);
reviewDialog->setRace(playerRaceId);
reviewDialog->setClass(playerClass);
reviewDialog->setBirthSign(playerBirthSignId);
reviewDialog->setHealth(playerHealth);
reviewDialog->setMagicka(playerMagicka);
reviewDialog->setFatigue(playerFatigue);
{
std::map<ESM::Attribute::AttributeID, MWMechanics::Stat<int> >::iterator end = playerAttributes.end();
for (std::map<ESM::Attribute::AttributeID, MWMechanics::Stat<int> >::iterator it = playerAttributes.begin(); it != end; ++it)
{
reviewDialog->setAttribute(it->first, it->second);
}
}
{
std::map<ESM::Skill::SkillEnum, MWMechanics::Stat<float> >::iterator end = playerSkillValues.end();
for (std::map<ESM::Skill::SkillEnum, MWMechanics::Stat<float> >::iterator it = playerSkillValues.begin(); it != end; ++it)
{
reviewDialog->setSkillValue(it->first, it->second);
}
reviewDialog->configureSkills(playerMajorSkills, playerMinorSkills);
}
reviewDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onReviewDialogDone);
reviewDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onReviewDialogBack);
reviewDialog->eventNameActivated = MyGUI::newDelegate(this, &WindowManager::onNameDialogActivate);
reviewDialog->eventRaceActivated = MyGUI::newDelegate(this, &WindowManager::onRaceDialogActivate);
reviewDialog->eventClassActivated = MyGUI::newDelegate(this, &WindowManager::onClassDialogActivate);
reviewDialog->eventBirthSignActivated = MyGUI::newDelegate(this, &WindowManager::onBirthSignDialogActivate);
reviewDialog->open();
return;
}
if(mode == GM_Inventory)
{
// Ah, inventory mode. First, compute the effective set of
// windows to show. This is controlled both by what windows the
// user has opened/closed (the 'shown' variable) and by what
// windows we are allowed to show (the 'allowed' var.)
int eff = shown & allowed;
// Show the windows we want
map -> setVisible( (eff & GW_Map) != 0 );
stats -> setVisible( (eff & GW_Stats) != 0 );
console->disable();
// Mouse is visible whenever we're not in game mode
gui->setVisiblePointer(isGuiMode());
// If in game mode, don't show anything.
if(mode == GM_Game)
{
return;
}
if(mode == GM_MainMenu)
{
// Enable the main menu
menu->setVisible(true);
return;
}
if(mode == GM_Console)
{
console->enable();
return;
}
if (mode == GM_Name)
{
if (nameDialog)
removeDialog(nameDialog);
nameDialog = new TextInputDialog(*this);
std::string sName = getGameSettingString("sName", "Name");
nameDialog->setTextLabel(sName);
nameDialog->setTextInput(playerName);
nameDialog->setNextButtonShow(creationStage >= NameChosen);
nameDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onNameDialogDone);
nameDialog->open();
return;
}
if (mode == GM_Race)
{
if (raceDialog)
removeDialog(raceDialog);
raceDialog = new RaceDialog(*this);
raceDialog->setNextButtonShow(creationStage >= RaceChosen);
raceDialog->setRaceId(playerRaceId);
raceDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onRaceDialogDone);
raceDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onRaceDialogBack);
raceDialog->open();
return;
}
if (mode == GM_Class)
{
if (classChoiceDialog)
removeDialog(classChoiceDialog);
classChoiceDialog = new ClassChoiceDialog(*this);
classChoiceDialog->eventButtonSelected = MyGUI::newDelegate(this, &WindowManager::onClassChoice);
classChoiceDialog->open();
return;
}
if (mode == GM_ClassGenerate)
{
generateClassStep = 0;
generateClass = "";
generateClassSpecializations[0] = 0;
generateClassSpecializations[1] = 0;
generateClassSpecializations[2] = 0;
showClassQuestionDialog();
return;
}
if (mode == GM_ClassPick)
{
if (pickClassDialog)
removeDialog(pickClassDialog);
pickClassDialog = new PickClassDialog(*this);
pickClassDialog->setNextButtonShow(creationStage >= ClassChosen);
pickClassDialog->setClassId(playerClass.name);
pickClassDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onPickClassDialogDone);
pickClassDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onPickClassDialogBack);
pickClassDialog->open();
return;
}
if (mode == GM_ClassCreate)
{
if (createClassDialog)
removeDialog(createClassDialog);
createClassDialog = new CreateClassDialog(*this);
createClassDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onCreateClassDialogDone);
createClassDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onCreateClassDialogBack);
createClassDialog->open();
return;
}
if (mode == GM_Birth)
{
if (birthSignDialog)
removeDialog(birthSignDialog);
birthSignDialog = new BirthDialog(*this);
birthSignDialog->setNextButtonShow(creationStage >= BirthSignChosen);
birthSignDialog->setBirthId(playerBirthSignId);
birthSignDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onBirthSignDialogDone);
birthSignDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onBirthSignDialogBack);
birthSignDialog->open();
return;
}
if (mode == GM_Review)
{
if (reviewDialog)
removeDialog(reviewDialog);
reviewDialog = new ReviewDialog(*this);
reviewDialog->setPlayerName(playerName);
reviewDialog->setRace(playerRaceId);
reviewDialog->setClass(playerClass);
reviewDialog->setBirthSign(playerBirthSignId);
reviewDialog->setHealth(playerHealth);
reviewDialog->setMagicka(playerMagicka);
reviewDialog->setFatigue(playerFatigue);
{
std::map<ESM::Attribute::AttributeID, MWMechanics::Stat<int> >::iterator end = playerAttributes.end();
for (std::map<ESM::Attribute::AttributeID, MWMechanics::Stat<int> >::iterator it = playerAttributes.begin(); it != end; ++it)
{
reviewDialog->setAttribute(it->first, it->second);
}
}
{
std::map<ESM::Skill::SkillEnum, MWMechanics::Stat<float> >::iterator end = playerSkillValues.end();
for (std::map<ESM::Skill::SkillEnum, MWMechanics::Stat<float> >::iterator it = playerSkillValues.begin(); it != end; ++it)
{
reviewDialog->setSkillValue(it->first, it->second);
}
reviewDialog->configureSkills(playerMajorSkills, playerMinorSkills);
}
reviewDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onReviewDialogDone);
reviewDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onReviewDialogBack);
reviewDialog->eventActivateDialog = MyGUI::newDelegate(this, &WindowManager::onReviewActivateDialog);
reviewDialog->open();
return;
}
if(mode == GM_Inventory)
{
// Ah, inventory mode. First, compute the effective set of
// windows to show. This is controlled both by what windows the
// user has opened/closed (the 'shown' variable) and by what
// windows we are allowed to show (the 'allowed' var.)
int eff = shown & allowed;
// Show the windows we want
map -> setVisible( (eff & GW_Map) != 0 );
stats -> setVisible( (eff & GW_Stats) != 0 );
#if 0
// inventory -> setVisible( eff & GW_Inventory );
// inventory -> setVisible( eff & GW_Inventory );
#endif
return;
return;
}
if (mode == GM_Dialogue)
{
if (dialogueWindow)
removeDialog(dialogueWindow);
dialogueWindow = new DialogueWindow(environment);
dialogueWindow->eventBye = MyGUI::newDelegate(this, &WindowManager::onDialogueWindowBye);
dialogueWindow->open();
return;
}
if (mode == GM_Dialogue)
{
if (!dialogueWindow)
{
dialogueWindow = new DialogueWindow(*this);
dialogueWindow->eventBye = MyGUI::newDelegate(this, &WindowManager::onDialogueWindowBye);
}
dialogueWindow->open();
return;
}
// Unsupported mode, switch back to game
// Note: The call will eventually end up this method again but
// will stop at the check if(mode == GM_Game) above.
setGuiMode(GM_Game);
// Unsupported mode, switch back to game
// Note: The call will eventually end up this method again but
// will stop at the check if(mode == GM_Game) above.
setGuiMode(GM_Game);
}
void WindowManager::setValue (const std::string& id, const MWMechanics::Stat<int>& value)
@ -365,49 +363,11 @@ void WindowManager::setValue (const std::string& id, const MWMechanics::Stat<int
}
}
void WindowManager::setValue (const std::string& id, const MWMechanics::Stat<float>& value)
{
stats->setValue (id, value);
static struct {const char *id; ESM::Skill::SkillEnum skillId; } skillMap[] =
{
{"SkillBlock", ESM::Skill::Block},
{"SkillArmorer", ESM::Skill::Armorer},
{"SkillMediumArmor", ESM::Skill::MediumArmor},
{"SkillHeavyArmor", ESM::Skill::HeavyArmor},
{"SkillBluntWeapon", ESM::Skill::BluntWeapon},
{"SkillLongBlade", ESM::Skill::LongBlade},
{"SkillAxe", ESM::Skill::Axe},
{"SkillSpear", ESM::Skill::Spear},
{"SkillAthletics", ESM::Skill::Athletics},
{"SkillEnchant", ESM::Skill::Armorer},
{"SkillDestruction", ESM::Skill::Destruction},
{"SkillAlteration", ESM::Skill::Alteration},
{"SkillIllusion", ESM::Skill::Illusion},
{"SkillConjuration", ESM::Skill::Conjuration},
{"SkillMysticism", ESM::Skill::Mysticism},
{"SkillRestoration", ESM::Skill::Restoration},
{"SkillAlchemy", ESM::Skill::Alchemy},
{"SkillUnarmored", ESM::Skill::Unarmored},
{"SkillSecurity", ESM::Skill::Security},
{"SkillSneak", ESM::Skill::Sneak},
{"SkillAcrobatics", ESM::Skill::Acrobatics},
{"SkillLightArmor", ESM::Skill::LightArmor},
{"SkillShortBlade", ESM::Skill::ShortBlade},
{"SkillMarksman", ESM::Skill::Marksman},
{"SkillMercantile", ESM::Skill::Mercantile},
{"SkillSpeechcraft", ESM::Skill::Speechcraft},
{"SkillHandToHand", ESM::Skill::HandToHand},
};
for (size_t i = 0; i < sizeof(skillMap)/sizeof(skillMap[0]); ++i)
{
if (skillMap[i].id == id)
{
ESM::Skill::SkillEnum skillId = skillMap[i].skillId;
playerSkillValues[skillId] = value;
break;
}
}
void WindowManager::setValue(const ESM::Skill::SkillEnum parSkill, const MWMechanics::Stat<float>& value)
{
stats->setValue(parSkill, value);
playerSkillValues[parSkill] = value;
}
void WindowManager::setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value)
@ -504,7 +464,7 @@ const std::string &WindowManager::getGameSettingString(const std::string &id, co
return default_;
}
void WindowManager::onNameDialogDone()
void WindowManager::onNameDialogDone(WindowBase* parWindow)
{
if (nameDialog)
{
@ -513,18 +473,19 @@ void WindowManager::onNameDialogDone()
removeDialog(nameDialog);
}
bool goNext = nameChosen; // Go to next dialog if name was previously chosen
nameChosen = true;
if (reviewNext)
// Go to next dialog if name was previously chosen
if (creationStage == ReviewNext)
setGuiMode(GM_Review);
else if (goNext)
else if (creationStage >= NameChosen)
setGuiMode(GM_Race);
else
{
creationStage = NameChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onRaceDialogDone()
void WindowManager::onRaceDialogDone(WindowBase* parWindow)
{
if (raceDialog)
{
@ -534,15 +495,16 @@ void WindowManager::onRaceDialogDone()
removeDialog(raceDialog);
}
bool goNext = raceChosen; // Go to next dialog if race was previously chosen
raceChosen = true;
if (reviewNext)
// Go to next dialog if race was previously chosen
if (creationStage == ReviewNext)
setGuiMode(GM_Review);
else if (goNext)
else if(creationStage >= RaceChosen)
setGuiMode(GM_Class);
else
{
creationStage = RaceChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onDialogueWindowBye()
@ -568,29 +530,29 @@ void WindowManager::onRaceDialogBack()
setGuiMode(GM_Name);
}
void WindowManager::onClassChoice(MyGUI::WidgetPtr, int _index)
void WindowManager::onClassChoice(int _index)
{
if (classChoiceDialog)
{
removeDialog(classChoiceDialog);
}
if (_index == ClassChoiceDialog::Class_Generate)
{
setGuiMode(GM_ClassGenerate);
}
else if (_index == ClassChoiceDialog::Class_Pick)
switch(_index)
{
setGuiMode(GM_ClassPick);
}
else if (_index == ClassChoiceDialog::Class_Create)
{
setGuiMode(GM_ClassCreate);
}
else if (_index == ClassChoiceDialog::Class_Back)
{
setGuiMode(GM_Race);
}
case ClassChoiceDialog::Class_Generate:
setGuiMode(GM_ClassGenerate);
break;
case ClassChoiceDialog::Class_Pick:
setGuiMode(GM_ClassPick);
break;
case ClassChoiceDialog::Class_Create:
setGuiMode(GM_ClassCreate);
break;
case ClassChoiceDialog::Class_Back:
setGuiMode(GM_Race);
break;
};
}
namespace MWGui
@ -678,18 +640,6 @@ namespace MWGui
} };
}
namespace MWGui
{
struct ClassPoint
{
const char *id;
// Specialization points to match, in order: Stealth, Combat, Magic
// Note: Order is taken from http://www.uesp.net/wiki/Morrowind:Class_Quiz
int points[3];
};
}
void WindowManager::showClassQuestionDialog()
{
if (generateClassStep == generateClassSteps.size())
@ -753,7 +703,7 @@ void WindowManager::showClassQuestionDialog()
if (generateClassResultDialog)
removeDialog(generateClassResultDialog);
generateClassResultDialog = new GenerateClassResultDialog(environment);
generateClassResultDialog = new GenerateClassResultDialog(*this);
generateClassResultDialog->setClassId(generateClass);
generateClassResultDialog->eventBack = MyGUI::newDelegate(this, &WindowManager::onGenerateClassBack);
generateClassResultDialog->eventDone = MyGUI::newDelegate(this, &WindowManager::onGenerateClassDone);
@ -769,7 +719,7 @@ void WindowManager::showClassQuestionDialog()
if (generateClassQuestionDialog)
removeDialog(generateClassQuestionDialog);
generateClassQuestionDialog = new InfoBoxDialog(environment);
generateClassQuestionDialog = new InfoBoxDialog(*this);
InfoBoxDialog::ButtonList buttons;
generateClassQuestionDialog->setText(generateClassSteps[generateClassStep].text);
@ -781,7 +731,7 @@ void WindowManager::showClassQuestionDialog()
generateClassQuestionDialog->open();
}
void WindowManager::onClassQuestionChosen(MyGUI::Widget* _sender, int _index)
void WindowManager::onClassQuestionChosen(int _index)
{
if (generateClassQuestionDialog)
removeDialog(generateClassQuestionDialog);
@ -804,7 +754,8 @@ void WindowManager::onClassQuestionChosen(MyGUI::Widget* _sender, int _index)
void WindowManager::onGenerateClassBack()
{
classChosen = true;
if(creationStage < ClassChosen)
creationStage = ClassChosen;
if (generateClassResultDialog)
removeDialog(generateClassResultDialog);
@ -813,25 +764,26 @@ void WindowManager::onGenerateClassBack()
setGuiMode(GM_Class);
}
void WindowManager::onGenerateClassDone()
void WindowManager::onGenerateClassDone(WindowBase* parWindow)
{
bool goNext = classChosen; // Go to next dialog if class was previously chosen
classChosen = true;
if (generateClassResultDialog)
removeDialog(generateClassResultDialog);
environment.mMechanicsManager->setPlayerClass(generateClass);
if (reviewNext)
// Go to next dialog if class was previously chosen
if (creationStage == ReviewNext)
setGuiMode(GM_Review);
else if (goNext)
else if (creationStage >= ClassChosen)
setGuiMode(GM_Birth);
else
{
creationStage = ClassChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onPickClassDialogDone()
void WindowManager::onPickClassDialogDone(WindowBase* parWindow)
{
if (pickClassDialog)
{
@ -844,15 +796,16 @@ void WindowManager::onPickClassDialogDone()
removeDialog(pickClassDialog);
}
bool goNext = classChosen; // Go to next dialog if class was previously chosen
classChosen = true;
if (reviewNext)
// Go to next dialog if class was previously chosen
if (creationStage == ReviewNext)
setGuiMode(GM_Review);
else if (goNext)
else if (creationStage >= ClassChosen)
setGuiMode(GM_Birth);
else
{
creationStage = ClassChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onPickClassDialogBack()
@ -868,7 +821,7 @@ void WindowManager::onPickClassDialogBack()
setGuiMode(GM_Class);
}
void WindowManager::onCreateClassDialogDone()
void WindowManager::onCreateClassDialogDone(WindowBase* parWindow)
{
if (createClassDialog)
{
@ -898,15 +851,16 @@ void WindowManager::onCreateClassDialogDone()
removeDialog(createClassDialog);
}
bool goNext = classChosen; // Go to next dialog if class was previously chosen
classChosen = true;
if (reviewNext)
// Go to next dialog if class was previously chosen
if (creationStage == ReviewNext)
setGuiMode(GM_Review);
else if (goNext)
else if (creationStage >= ClassChosen)
setGuiMode(GM_Birth);
else
{
creationStage = ClassChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onCreateClassDialogBack()
@ -917,7 +871,7 @@ void WindowManager::onCreateClassDialogBack()
setGuiMode(GM_Class);
}
void WindowManager::onBirthSignDialogDone()
void WindowManager::onBirthSignDialogDone(WindowBase* parWindow)
{
if (birthSignDialog)
{
@ -927,13 +881,14 @@ void WindowManager::onBirthSignDialogDone()
removeDialog(birthSignDialog);
}
bool goNext = birthSignChosen; // Go to next dialog if birth sign was previously chosen
birthSignChosen = true;
if (reviewNext || goNext)
// Go to next dialog if birth sign was previously chosen
if (creationStage >= BirthSignChosen)
setGuiMode(GM_Review);
else
{
creationStage = BirthSignChosen;
setGuiMode(GM_Game);
}
}
void WindowManager::onBirthSignDialogBack()
@ -947,7 +902,7 @@ void WindowManager::onBirthSignDialogBack()
setGuiMode(GM_Class);
}
void WindowManager::onReviewDialogDone()
void WindowManager::onReviewDialogDone(WindowBase* parWindow)
{
if (reviewDialog)
removeDialog(reviewDialog);
@ -963,38 +918,29 @@ void WindowManager::onReviewDialogBack()
setGuiMode(GM_Birth);
}
void WindowManager::onNameDialogActivate()
{
if (reviewDialog)
removeDialog(reviewDialog);
reviewNext = true;
setGuiMode(GM_Name);
}
void WindowManager::onRaceDialogActivate()
void WindowManager::onReviewActivateDialog(int parDialog)
{
if (reviewDialog)
removeDialog(reviewDialog);
creationStage = ReviewNext;
reviewNext = true;
setGuiMode(GM_Race);
}
void WindowManager::onClassDialogActivate()
{
if (reviewDialog)
removeDialog(reviewDialog);
reviewNext = true;
setGuiMode(GM_Class);
switch(parDialog)
{
case ReviewDialog::NAME_DIALOG:
setGuiMode(GM_Name);
break;
case ReviewDialog::RACE_DIALOG:
setGuiMode(GM_Race);
break;
case ReviewDialog::CLASS_DIALOG:
setGuiMode(GM_Class);
break;
case ReviewDialog::BIRTHSIGN_DIALOG:
setGuiMode(GM_Birth);
};
}
void WindowManager::onBirthSignDialogActivate()
ESMS::ESMStore& WindowManager::getStore()
{
if (reviewDialog)
removeDialog(reviewDialog);
reviewNext = true;
setGuiMode(GM_Birth);
return environment.mWorld->getStore();
}

@ -44,6 +44,7 @@ namespace OEngine
namespace MWGui
{
class WindowBase;
class HUD;
class MapWindow;
class MainMenu;
@ -62,6 +63,14 @@ namespace MWGui
class BirthDialog;
class ReviewDialog;
struct ClassPoint
{
const char *id;
// Specialization points to match, in order: Stealth, Combat, Magic
// Note: Order is taken from http://www.uesp.net/wiki/Morrowind:Class_Quiz
unsigned int points[3];
};
class WindowManager
{
public:
@ -92,14 +101,6 @@ namespace MWGui
BirthDialog *birthSignDialog;
ReviewDialog *reviewDialog;
// Which dialogs have been shown, controls back/next/ok buttons
bool nameChosen;
bool raceChosen;
bool classChosen;
bool birthSignChosen;
bool reviewNext;
///< If true then any click on Next will cause the summary to be shown
// Keeps track of current step in Generate Class dialogs
unsigned generateClassStep;
// A counter for each specialization which is increased when an answer is chosen, in order: Stealth, Combat, Magic
@ -153,10 +154,13 @@ namespace MWGui
void setGuiMode(GuiMode newMode);
bool showFPSCounter;
float mFPS;
public:
/// The constructor needs the main Gui object
WindowManager(MyGUI::Gui *_gui, MWWorld::Environment& environment,
const Compiler::Extensions& extensions, bool newGame);
const Compiler::Extensions& extensions, bool fpsSwitch, bool newGame);
virtual ~WindowManager();
/**
@ -197,10 +201,12 @@ namespace MWGui
MyGUI::Gui* getGui() const { return gui; }
void wmSetFPS(float fps) { mFPS = fps; }
void setValue (const std::string& id, const MWMechanics::Stat<int>& value);
///< Set value for the given ID.
void setValue (const std::string& id, const MWMechanics::Stat<float>& value);
void setValue(const ESM::Skill::SkillEnum parSkill, const MWMechanics::Stat<float>& value);
///< Set value for the given ID.
void setValue (const std::string& id, const MWMechanics::DynamicStat<int>& value);
@ -251,45 +257,57 @@ namespace MWGui
*/
const std::string &getGameSettingString(const std::string &id, const std::string &default_);
ESMS::ESMStore& getStore();
private:
void onDialogueWindowBye();
// Character generation: Name dialog
void onNameDialogDone();
void onNameDialogDone(WindowBase* parWindow);
// Character generation: Race dialog
void onRaceDialogDone();
void onRaceDialogDone(WindowBase* parWindow);
void onRaceDialogBack();
// Character generation: Choose class process
void onClassChoice(MyGUI::Widget* _sender, int _index);
void onClassChoice(int _index);
// Character generation: Generate Class
void showClassQuestionDialog();
void onClassQuestionChosen(MyGUI::Widget* _sender, int _index);
void onClassQuestionChosen(int _index);
void onGenerateClassBack();
void onGenerateClassDone();
void onGenerateClassDone(WindowBase* parWindow);
// Character generation: Pick Class dialog
void onPickClassDialogDone();
void onPickClassDialogDone(WindowBase* parWindow);
void onPickClassDialogBack();
// Character generation: Create Class dialog
void onCreateClassDialogDone();
void onCreateClassDialogDone(WindowBase* parWindow);
void onCreateClassDialogBack();
// Character generation: Birth sign dialog
void onBirthSignDialogDone();
void onBirthSignDialogDone(WindowBase* parWindow);
void onBirthSignDialogBack();
// Character generation: Review dialog
void onReviewDialogDone();
void onReviewDialogDone(WindowBase* parWindow);
void onReviewDialogBack();
void onNameDialogActivate();
void onRaceDialogActivate();
void onClassDialogActivate();
void onBirthSignDialogActivate();
void onReviewActivateDialog(int parDialog);
enum CreationStageEnum
{
NotStarted,
NameChosen,
RaceChosen,
ClassChosen,
BirthSignChosen,
ReviewNext
};
// Which state the character creating is in, controls back/next/ok buttons
CreationStageEnum creationStage;
};
template<typename T>

@ -15,10 +15,13 @@
#include <mangle/input/filters/eventlist.hpp>
#include <libs/platform/strings.h>
#include "../mwrender/playerpos.hpp"
#include "../engine.hpp"
#include "../mwworld/player.hpp"
#include "../mwrender/player.hpp"
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <OgreRoot.h>
@ -38,13 +41,31 @@ namespace MWInput
A_MoveLeft, // Move player left / right
A_MoveRight,
A_MoveUp, // Move up / down
A_MoveDown,
A_MoveForward, // Forward / Backward
A_MoveBackward,
A_Activate,
A_Use, //Use weapon, spell, etc.
A_Jump,
A_AutoMove, //Toggle Auto-move forward
A_Rest, //Rest
A_Journal, //Journal
A_Weapon, //Draw/Sheath weapon
A_Spell, //Ready/Unready Casting
A_AlwaysRun, //Toggle Always Run
A_CycleSpellLeft, //cycling through spells
A_CycleSpellRight,
A_CycleWeaponLeft,//Cycling through weapons
A_CycleWeaponRight,
A_ToggleSneak, //Toggles Sneak, add Push-Sneak later
A_ToggleWalk, //Toggle Walking/Running
A_QuickSave,
A_QuickLoad,
A_QuickMenu,
A_GameMenu,
A_LAST // Marker for the last item
};
@ -58,18 +79,21 @@ namespace MWInput
OEngine::Input::Poller poller;
OEngine::Render::MouseLookEventPtr mouse;
OEngine::GUI::EventInjectorPtr guiEvents;
MWRender::PlayerPos &player;
MWWorld::Player &player;
MWGui::WindowManager &windows;
OMW::Engine& mEngine;
// Count screenshots.
int shotCount;
/* InputImpl Methods */
// Write screenshot to file.
void screenshot()
{
// Find the first unused filename.
//
// Find the first unused filename with a do-while
char buf[50];
do
{
@ -79,8 +103,8 @@ namespace MWInput
ogre.screenshot(buf);
}
// Called when the user presses the button to toggle the inventory
// screen.
/* toggleInventory() is called when the user presses the button to toggle the inventory screen. */
void toggleInventory()
{
using namespace MWGui;
@ -115,16 +139,26 @@ namespace MWInput
mEngine.activate();
}
void toggleAutoMove()
{
player.setAutoMove (!player.getAutoMove());
}
void toggleWalking()
{
player.toggleRunning();
}
// Exit program now button (which is disabled in GUI mode)
void exitNow()
{
if(!windows.isGuiMode())
exit.exitNow();
if(!windows.isGuiMode())
exit.exitNow();
}
public:
InputImpl(OEngine::Render::OgreRenderer &_ogre,
MWRender::PlayerPos &_player,
MWWorld::Player &_player,
MWGui::WindowManager &_windows,
bool debug,
OMW::Engine& engine)
@ -156,7 +190,10 @@ namespace MWInput
"Toggle console");
disp->funcs.bind(A_Activate, boost::bind(&InputImpl::activate, this),
"Activate");
disp->funcs.bind(A_AutoMove, boost::bind(&InputImpl::toggleAutoMove, this),
"Auto Move");
disp->funcs.bind(A_ToggleWalk, boost::bind(&InputImpl::toggleWalking, this),
"Toggle Walk/Run");
// Add the exit listener
ogre.getRoot()->addFrameListener(&exit);
@ -164,7 +201,7 @@ namespace MWInput
ogre.getRoot()->addFrameListener(this);
// Set up the mouse handler and tell it about the player camera
mouse = MouseLookEventPtr(new MouseLookEvent(player.getCamera()));
mouse = MouseLookEventPtr(new MouseLookEvent(player.getRenderer()->getCamera()));
// This event handler pumps events into MyGUI
guiEvents = EventInjectorPtr(new EventInjector(windows.getGui()));
@ -192,6 +229,7 @@ namespace MWInput
**********************************/
// Key bindings for keypress events
// NOTE: These keys do not require constant polling - use in conjuction with variables in loops.
disp->bind(A_Quit, KC_Q);
disp->bind(A_Quit, KC_ESCAPE);
@ -199,8 +237,12 @@ namespace MWInput
disp->bind(A_Inventory, KC_I);
disp->bind(A_Console, KC_F1);
disp->bind(A_Activate, KC_SPACE);
disp->bind(A_AutoMove, KC_Z);
disp->bind(A_ToggleSneak, KC_X);
disp->bind(A_ToggleWalk, KC_C);
// Key bindings for polled keys
// NOTE: These keys are constantly being polled. Only add keys that must be checked each frame.
// Arrow keys
poller.bind(A_MoveLeft, KC_LEFT);
@ -213,47 +255,54 @@ namespace MWInput
poller.bind(A_MoveRight, KC_D);
poller.bind(A_MoveForward, KC_W);
poller.bind(A_MoveBackward, KC_S);
// Use shift and ctrl for up and down
poller.bind(A_MoveUp, KC_LSHIFT);
poller.bind(A_MoveDown, KC_LCONTROL);
}
// Used to check for movement keys
//NOTE: Used to check for movement keys
bool frameStarted(const Ogre::FrameEvent &evt)
{
// Tell OIS to handle all input events
input.capture();
// Update windows/gui as a result of input events
// For instance this could mean opening a new window/dialog,
// by doing this after the input events are handled we
// ensure that window/gui changes appear quickly while
// avoiding that window/gui changes does not happen in
// event callbacks (which may crash)
windows.update();
// Disable movement in Gui mode
if(windows.isGuiMode()) return true;
float speed = 300 * evt.timeSinceLastFrame;
float moveX = 0, moveY = 0, moveZ = 0;
if(poller.isDown(A_MoveLeft)) moveX -= speed;
if(poller.isDown(A_MoveRight)) moveX += speed;
if(poller.isDown(A_MoveForward)) moveZ -= speed;
if(poller.isDown(A_MoveBackward)) moveZ += speed;
// TODO: These should be enabled for floating modes (like
// swimming and levitation) and disabled for everything else.
if(poller.isDown(A_MoveUp)) moveY += speed;
if(poller.isDown(A_MoveDown)) moveY -= speed;
if(moveX != 0 || moveY != 0 || moveZ != 0)
player.moveRel(moveX, moveY, moveZ);
// Tell OIS to handle all input events
input.capture();
// Update windows/gui as a result of input events
// For instance this could mean opening a new window/dialog,
// by doing this after the input events are handled we
// ensure that window/gui changes appear quickly while
// avoiding that window/gui changes does not happen in
// event callbacks (which may crash)
windows.update();
// Disable movement in Gui mode
if (windows.isGuiMode()) return true;
// Configure player movement according to keyboard input. Actual movement will
// be done in the physics system.
if (poller.isDown(A_MoveLeft))
{
player.setAutoMove (false);
player.setLeftRight (1);
}
else if (poller.isDown(A_MoveRight))
{
player.setAutoMove (false);
player.setLeftRight (-1);
}
else
player.setLeftRight (0);
if (poller.isDown(A_MoveForward))
{
player.setAutoMove (false);
player.setForwardBackward (1);
}
else if (poller.isDown(A_MoveBackward))
{
player.setAutoMove (false);
player.setForwardBackward (-1);
}
else
player.setForwardBackward (0);
return true;
return true;
}
// Switch between gui modes. Besides controlling the Gui windows
@ -277,7 +326,7 @@ namespace MWInput
{
// Start mouse-looking again. TODO: This should also allow
// for other ways to disable mouselook, like paralyzation.
mouse->setCamera(player.getCamera());
mouse->setCamera(player.getRenderer()->getCamera());
// Disable GUI events
guiEvents->enabled = false;
@ -285,8 +334,9 @@ namespace MWInput
}
};
/***CONSTRUCTOR***/
MWInputManager::MWInputManager(OEngine::Render::OgreRenderer &ogre,
MWRender::PlayerPos &player,
MWWorld::Player &player,
MWGui::WindowManager &windows,
bool debug,
OMW::Engine& engine)
@ -294,13 +344,14 @@ namespace MWInput
impl = new InputImpl(ogre,player,windows,debug, engine);
}
/***DESTRUCTOR***/
MWInputManager::~MWInputManager()
{
delete impl;
}
void MWInputManager::setGuiMode(MWGui::GuiMode mode)
{
{
impl->setGuiMode(mode);
}
}

@ -11,9 +11,9 @@ namespace OEngine
}
}
namespace MWRender
namespace MWWorld
{
class PlayerPos;
class Player;
}
namespace MWGui
@ -42,7 +42,7 @@ namespace MWInput
public:
MWInputManager(OEngine::Render::OgreRenderer &_ogre,
MWRender::PlayerPos &_player,
MWWorld::Player&_player,
MWGui::WindowManager &_windows,
bool debug,
OMW::Engine& engine);

@ -8,12 +8,13 @@
#include "../mwworld/class.hpp"
#include "../mwworld/environment.hpp"
#include "../mwworld/world.hpp"
#include "../mwworld/player.hpp"
namespace MWMechanics
{
void MechanicsManager::buildPlayer()
{
MWWorld::Ptr ptr = mEnvironment.mWorld->getPlayerPos().getPlayer();
MWWorld::Ptr ptr = mEnvironment.mWorld->getPlayer().getPlayer();
MWMechanics::CreatureStats& creatureStats = MWWorld::Class::get (ptr).getCreatureStats (ptr);
MWMechanics::NpcStats& npcStats = MWWorld::Class::get (ptr).getNpcStats (ptr);
@ -33,9 +34,9 @@ namespace MWMechanics
{
const ESM::Race *race =
mEnvironment.mWorld->getStore().races.find (
mEnvironment.mWorld->getPlayerPos().getRace());
mEnvironment.mWorld->getPlayer().getRace());
bool male = mEnvironment.mWorld->getPlayerPos().isMale();
bool male = mEnvironment.mWorld->getPlayer().isMale();
for (int i=0; i<8; ++i)
{
@ -75,11 +76,11 @@ namespace MWMechanics
}
// birthsign
if (!mEnvironment.mWorld->getPlayerPos().getBirthsign().empty())
if (!mEnvironment.mWorld->getPlayer().getBirthsign().empty())
{
const ESM::BirthSign *sign =
mEnvironment.mWorld->getStore().birthSigns.find (
mEnvironment.mWorld->getPlayerPos().getBirthsign());
mEnvironment.mWorld->getPlayer().getBirthsign());
for (std::vector<std::string>::const_iterator iter (sign->powers.list.begin());
iter!=sign->powers.list.end(); ++iter)
@ -91,7 +92,7 @@ namespace MWMechanics
// class
if (mClassSelected)
{
const ESM::Class& class_ = mEnvironment.mWorld->getPlayerPos().getClass();
const ESM::Class& class_ = mEnvironment.mWorld->getPlayer().getClass();
for (int i=0; i<2; ++i)
{
@ -233,11 +234,17 @@ namespace MWMechanics
void MechanicsManager::removeActor (const MWWorld::Ptr& ptr)
{
if (ptr==mWatched)
mWatched = MWWorld::Ptr();
mActors.erase (ptr);
}
void MechanicsManager::dropActors (const MWWorld::Ptr::CellStore *cellStore)
{
if (!mWatched.isEmpty() && mWatched.getCell()==cellStore)
mWatched = MWWorld::Ptr();
std::set<MWWorld::Ptr>::iterator iter = mActors.begin();
while (iter!=mActors.end())
@ -254,7 +261,7 @@ namespace MWMechanics
mWatched = ptr;
}
void MechanicsManager::update()
void MechanicsManager::update (std::vector<std::pair<std::string, Ogre::Vector3> >& movement)
{
if (!mWatched.isEmpty())
{
@ -275,17 +282,6 @@ namespace MWMechanics
"HBar", "MBar", "FBar"
};
static const char *skillNames[27] =
{
"SkillBlock", "SkillArmorer", "SkillMediumArmor", "SkillHeavyArmor",
"SkillBluntWeapon", "SkillLongBlade", "SkillAxe", "SkillSpear",
"SkillAthletics", "SkillEnchant", "SkillDestruction", "SkillAlteration",
"SkillIllusion", "SkillConjuration", "SkillMysticism", "SkillRestoration",
"SkillAlchemy", "SkillUnarmored", "SkillSecurity", "SkillSneak",
"SkillAcrobatics", "SkillLightArmor", "SkillShortBlade", "SkillMarksman",
"SkillMercantile", "SkillSpeechcraft", "SkillHandToHand",
};
for (int i=0; i<8; ++i)
{
if (stats.mAttributes[i]!=mWatchedCreature.mAttributes[i])
@ -308,16 +304,14 @@ namespace MWMechanics
bool update = false;
for (int i=0; i<27; ++i)
//Loop over ESM::Skill::SkillEnum
for(int i = 0; i < 27; ++i)
{
if (npcStats.mSkill[i]!=mWatchedNpc.mSkill[i])
if(npcStats.mSkill[i] != mWatchedNpc.mSkill[i])
{
update = true;
mWatchedNpc.mSkill[i] = npcStats.mSkill[i];
mEnvironment.mWindowManager->setValue (skillNames[i], npcStats.mSkill[i]);
mEnvironment.mWindowManager->setValue((ESM::Skill::SkillEnum)i, npcStats.mSkill[i]);
}
}
@ -330,12 +324,12 @@ namespace MWMechanics
if (mUpdatePlayer)
{
// basic player profile; should not change anymore after the creation phase is finished.
mEnvironment.mWindowManager->setValue ("name", mEnvironment.mWorld->getPlayerPos().getName());
mEnvironment.mWindowManager->setValue ("name", mEnvironment.mWorld->getPlayer().getName());
mEnvironment.mWindowManager->setValue ("race",
mEnvironment.mWorld->getStore().races.find (mEnvironment.mWorld->getPlayerPos().
mEnvironment.mWorld->getStore().races.find (mEnvironment.mWorld->getPlayer().
getRace())->name);
mEnvironment.mWindowManager->setValue ("class",
mEnvironment.mWorld->getPlayerPos().getClass().name);
mEnvironment.mWorld->getPlayer().getClass().name);
mUpdatePlayer = false;
MWGui::WindowManager::SkillList majorSkills (5);
@ -343,24 +337,33 @@ namespace MWMechanics
for (int i=0; i<5; ++i)
{
minorSkills[i] = mEnvironment.mWorld->getPlayerPos().getClass().data.skills[i][0];
majorSkills[i] = mEnvironment.mWorld->getPlayerPos().getClass().data.skills[i][1];
minorSkills[i] = mEnvironment.mWorld->getPlayer().getClass().data.skills[i][0];
majorSkills[i] = mEnvironment.mWorld->getPlayer().getClass().data.skills[i][1];
}
mEnvironment.mWindowManager->configureSkills (majorSkills, minorSkills);
}
for (std::set<MWWorld::Ptr>::iterator iter (mActors.begin()); iter!=mActors.end();
++iter)
{
Ogre::Vector3 vector = MWWorld::Class::get (*iter).getMovementVector (*iter);
if (vector!=Ogre::Vector3::ZERO)
movement.push_back (std::make_pair (iter->getRefData().getHandle(), vector));
}
}
void MechanicsManager::setPlayerName (const std::string& name)
{
mEnvironment.mWorld->getPlayerPos().setName (name);
mEnvironment.mWorld->getPlayer().setName (name);
mUpdatePlayer = true;
}
void MechanicsManager::setPlayerRace (const std::string& race, bool male)
{
mEnvironment.mWorld->getPlayerPos().setGender (male);
mEnvironment.mWorld->getPlayerPos().setRace (race);
mEnvironment.mWorld->getPlayer().setGender (male);
mEnvironment.mWorld->getPlayer().setRace (race);
mRaceSelected = true;
buildPlayer();
mUpdatePlayer = true;
@ -368,14 +371,14 @@ namespace MWMechanics
void MechanicsManager::setPlayerBirthsign (const std::string& id)
{
mEnvironment.mWorld->getPlayerPos().setBirthsign (id);
mEnvironment.mWorld->getPlayer().setBirthsign (id);
buildPlayer();
mUpdatePlayer = true;
}
void MechanicsManager::setPlayerClass (const std::string& id)
{
mEnvironment.mWorld->getPlayerPos().setClass (*mEnvironment.mWorld->getStore().classes.find (id));
mEnvironment.mWorld->getPlayer().setClass (*mEnvironment.mWorld->getStore().classes.find (id));
mClassSelected = true;
buildPlayer();
mUpdatePlayer = true;
@ -383,7 +386,7 @@ namespace MWMechanics
void MechanicsManager::setPlayerClass (const ESM::Class& class_)
{
mEnvironment.mWorld->getPlayerPos().setClass (class_);
mEnvironment.mWorld->getPlayer().setClass (class_);
mClassSelected = true;
buildPlayer();
mUpdatePlayer = true;

@ -2,12 +2,19 @@
#define GAME_MWMECHANICS_MECHANICSMANAGER_H
#include <set>
#include <vector>
#include <string>
#include "../mwworld/ptr.hpp"
#include "creaturestats.hpp"
#include "npcstats.hpp"
namespace Ogre
{
class Vector3;
}
namespace MWWorld
{
class Environment;
@ -53,8 +60,8 @@ namespace MWMechanics
///< On each update look for changes in a previously registered actor and update the
/// GUI accordingly.
void update();
///< Update actor stats
void update (std::vector<std::pair<std::string, Ogre::Vector3> >& movement);
///< Update actor stats and store desired velocity vectors in \a movement
void setPlayerName (const std::string& name);
///< Set player name.

@ -0,0 +1,16 @@
#ifndef GAME_MWMECHANICS_MOVEMENT_H
#define GAME_MWMECHANICS_MOVEMENT_H
namespace MWMechanics
{
/// Desired movement for an actor
struct Movement
{
signed char mLeftRight; // 1: wants to move left, -1: wants to move right
signed char mForwardBackward; // 1:wants to move forward, -1: wants to move backward
Movement() : mLeftRight (0), mForwardBackward (0) {}
};
}
#endif

@ -18,6 +18,15 @@ namespace MWMechanics
std::map<std::string, int> mFactionRank;
Stat<float> mSkill[27];
bool mForceRun;
bool mForceSneak;
bool mRun;
bool mSneak;
bool mCombat;
NpcStats() : mForceRun (false), mForceSneak (false), mRun (false), mSneak (false),
mCombat (false) {}
};
}

@ -1,6 +1,9 @@
#ifndef GAME_MWMECHANICS_STAT_H
#define GAME_MWMECHANICS_STAT_H
#undef min
#undef max
#include <limits>
namespace MWMechanics

@ -11,7 +11,7 @@
namespace Ogre
{
class SceneNode;
class Vector3;
class Vector3;
}
namespace ESM
@ -37,14 +37,17 @@ namespace MWRender
/// start inserting a new reference.
virtual void insertBegin (ESM::CellRef &ref) = 0;
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements) = 0;
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements) = 0;
/// insert a mesh related to the most recent insertBegin call.
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst) = 0;
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements) = 0;
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst) = 0;
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements) = 0;
virtual void insertMesh(const std::string &mesh) = 0;
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements) = 0;
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements) = 0;
virtual void insertObjectPhysics() = 0;
virtual void insertActorPhysics() = 0;
/// insert a light related to the most recent insertBegin call.
virtual void insertLight(float r, float g, float b, float radius) = 0;

@ -35,14 +35,14 @@ bool ExteriorCellRender::lightOutQuadInLin = false;
void ExteriorCellRender::insertBegin (ESM::CellRef &ref)
{
assert (!insert);
assert (!mInsert);
// Create and place scene node for this object
insert = base->createChildSceneNode();
mInsert = mBase->createChildSceneNode();
const float *f = ref.pos.pos;
insert->setPosition(f[0], f[1], f[2]);
insert->setScale(ref.scale, ref.scale, ref.scale);
mInsert->setPosition(f[0], f[1], f[2]);
mInsert->setScale(ref.scale, ref.scale, ref.scale);
// Convert MW rotation to a quaternion:
f = ref.pos.rot;
@ -57,139 +57,141 @@ void ExteriorCellRender::insertBegin (ESM::CellRef &ref)
Quaternion zr(Radian(-f[2]), Vector3::UNIT_Z);
// Rotates first around z, then y, then x
insert->setOrientation(xr*yr*zr);
mInsert->setOrientation(xr*yr*zr);
mInsertMesh.clear();
}
void ExteriorCellRender::rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements)
{
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->rotate(axis, angle);
assert(mInsert);
Ogre::SceneNode *parent = mInsert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->rotate(axis, angle);
}
/*
void ExteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements){
assert (insert);
//insert->
Ogre::SceneNode *parent = insert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
npcPart = parent->createChildSceneNode(sceneNodeName);
assert (mInsert);
//mInsert->
Ogre::SceneNode *parent = mInsert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
mNpcPart = parent->createChildSceneNode(sceneNodeName);
NIFLoader::load(mesh);
MovableObject *ent = scene.getMgr()->createEntity(mesh);
npcPart->translate(vec);
npcPart->rotate(axis, angle);
// npcPart->translate(vec);
//npcPart->rotate(axis, angle);
npcPart->attachObject(ent);
//npcPart->
MovableObject *ent = mScene.getMgr()->createEntity(mesh);
mNpcPart->translate(vec);
mNpcPart->rotate(axis, angle);
// mNpcPart->translate(vec);
//mNpcPart->rotate(axis, angle);
mNpcPart->attachObject(ent);
//mNpcPart->
}
*/
void ExteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements)
{
insertMesh(mesh, vec, axis, angle, sceneNodeName, sceneParent, elements, true);
insertMesh(mesh, vec, axis, angle, sceneNodeName, sceneParent, elements, true);
}
void ExteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst){
assert (insert);
//insert->
Ogre::SceneNode *parent = insert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
npcPart = parent->createChildSceneNode(sceneNodeName);
assert (mInsert);
//mInsert->
Ogre::SceneNode *parent = mInsert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
mNpcPart = parent->createChildSceneNode(sceneNodeName);
MeshPtr good2 = NIFLoader::load(mesh);
MovableObject *ent = scene.getMgr()->createEntity(mesh);
MovableObject *ent = mScene.getMgr()->createEntity(mesh);
if(translateFirst){
npcPart->translate(vec);
npcPart->rotate(axis, angle);
mNpcPart->translate(vec);
mNpcPart->rotate(axis, angle);
}
else{
npcPart->rotate(axis, angle);
npcPart->translate(vec);
mNpcPart->rotate(axis, angle);
mNpcPart->translate(vec);
}
npcPart->attachObject(ent);
mNpcPart->attachObject(ent);
Ogre::MeshManager *m = MeshManager::getSingletonPtr();
const std::string beast1 ="meshes\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beast2 ="meshes\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beast3 ="meshes\\b\\B_N_Argonian_F_Skins.nif";
const std::string beast4 ="meshes\\b\\B_N_Argonian_M_Skins.nif";
const std::string beasttail1 ="tail\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beasttail2 ="tail\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beasttail3 ="tail\\b\\B_N_Argonian_F_Skins.nif";
const std::string beasttail4 ="tail\\b\\B_N_Argonian_M_Skins.nif";
const std::string beastfoot1 ="foot\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beastfoot2 ="foot\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beastfoot3 ="foot\\b\\B_N_Argonian_F_Skins.nif";
const std::string beastfoot4 ="foot\\b\\B_N_Argonian_M_Skins.nif";
if(mesh.compare(beast1) == 0 && m->getByName(beasttail1).isNull())
{
//std::cout << "CLONINGKHAJIITF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail1);
good2->reload();
MeshPtr foot = good2->clone(beastfoot1);
good2->reload();
}
else if(mesh.compare(beast2) == 0 && m->getByName(beasttail2).isNull())
{
//std::cout << "CLONINGKHAJIITM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail2);
good2->reload();
MeshPtr foot = good2->clone(beastfoot2);
good2->reload();
}
else if(mesh.compare(beast3) == 0 && m->getByName(beasttail3).isNull())
{
//std::cout << "CLONINGARGONIANF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail3);
good2->reload();
MeshPtr foot = good2->clone(beastfoot3);
good2->reload();
}
else if(mesh.compare(beast4) == 0 && m->getByName(beasttail4).isNull())
{
//std::cout << "CLONINGARGONIANM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail4);
good2->reload();
MeshPtr foot = good2->clone(beastfoot4);
good2->reload();
}
const std::string beast2 ="meshes\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beast3 ="meshes\\b\\B_N_Argonian_F_Skins.nif";
const std::string beast4 ="meshes\\b\\B_N_Argonian_M_Skins.nif";
const std::string beasttail1 ="tail\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beasttail2 ="tail\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beasttail3 ="tail\\b\\B_N_Argonian_F_Skins.nif";
const std::string beasttail4 ="tail\\b\\B_N_Argonian_M_Skins.nif";
const std::string beastfoot1 ="foot\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beastfoot2 ="foot\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beastfoot3 ="foot\\b\\B_N_Argonian_F_Skins.nif";
const std::string beastfoot4 ="foot\\b\\B_N_Argonian_M_Skins.nif";
if(mesh.compare(beast1) == 0 && m->getByName(beasttail1).isNull())
{
//std::cout << "CLONINGKHAJIITF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail1);
good2->reload();
MeshPtr foot = good2->clone(beastfoot1);
good2->reload();
}
else if(mesh.compare(beast2) == 0 && m->getByName(beasttail2).isNull())
{
//std::cout << "CLONINGKHAJIITM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail2);
good2->reload();
MeshPtr foot = good2->clone(beastfoot2);
good2->reload();
}
else if(mesh.compare(beast3) == 0 && m->getByName(beasttail3).isNull())
{
//std::cout << "CLONINGARGONIANF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail3);
good2->reload();
MeshPtr foot = good2->clone(beastfoot3);
good2->reload();
}
else if(mesh.compare(beast4) == 0 && m->getByName(beasttail4).isNull())
{
//std::cout << "CLONINGARGONIANM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail4);
good2->reload();
MeshPtr foot = good2->clone(beastfoot4);
good2->reload();
}
}
// insert a mesh related to the most recent insertBegin call.
void ExteriorCellRender::scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements)
{
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->scale(axis);
assert(mInsert);
Ogre::SceneNode *parent = mInsert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->scale(axis);
}
// insert a mesh related to the most recent insertBegin call.
@ -197,19 +199,34 @@ void ExteriorCellRender::scaleMesh(Ogre::Vector3 axis, std::string sceneNodeNam
void ExteriorCellRender::insertMesh(const std::string &mesh)
{
assert (insert);
assert (mInsert);
NIFLoader::load(mesh);
MovableObject *ent = scene.getMgr()->createEntity(mesh);
insert->attachObject(ent);
MovableObject *ent = mScene.getMgr()->createEntity(mesh);
mInsert->attachObject(ent);
if (mInsertMesh.empty())
mInsertMesh = mesh;
}
void ExteriorCellRender::insertObjectPhysics()
{
if (!mInsertMesh.empty())
mScene.addObject (mInsert->getName(), mInsertMesh, mInsert->getOrientation(),
mInsert->getScale().x, mInsert->getPosition());
}
void ExteriorCellRender::insertActorPhysics()
{
mScene.addActor (mInsert->getName(), mInsertMesh, mInsert->getPosition());
}
// insert a light related to the most recent insertBegin call.
void ExteriorCellRender::insertLight(float r, float g, float b, float radius)
{
assert (insert);
assert (mInsert);
Ogre::Light *light = scene.getMgr()->createLight();
Ogre::Light *light = mScene.getMgr()->createLight();
light->setDiffuseColour (r, g, b);
float cval=0.0f, lval=0.0f, qval=0.0f;
@ -237,21 +254,21 @@ void ExteriorCellRender::insertLight(float r, float g, float b, float radius)
light->setAttenuation(10*radius, cval, lval, qval);
insert->attachObject(light);
mInsert->attachObject(light);
}
// finish inserting a new reference and return a handle to it.
std::string ExteriorCellRender::insertEnd (bool enable)
{
assert (insert);
assert (mInsert);
std::string handle = insert->getName();
std::string handle = mInsert->getName();
if (!enable)
insert->setVisible (false);
mInsert->setVisible (false);
insert = 0;
mInsert = 0;
return handle;
}
@ -260,14 +277,14 @@ std::string ExteriorCellRender::insertEnd (bool enable)
void ExteriorCellRender::configureAmbient()
{
ambientColor.setAsABGR (cell.cell->ambi.ambient);
mAmbientColor.setAsABGR (mCell.cell->ambi.ambient);
setAmbientMode();
// Create a "sun" that shines light downwards. It doesn't look
// completely right, but leave it for now.
Ogre::Light *light = scene.getMgr()->createLight();
Ogre::Light *light = mScene.getMgr()->createLight();
Ogre::ColourValue colour;
colour.setAsABGR (cell.cell->ambi.sunlight);
colour.setAsABGR (mCell.cell->ambi.sunlight);
light->setDiffuseColour (colour);
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(0,-1,0);
@ -277,74 +294,74 @@ void ExteriorCellRender::configureAmbient()
void ExteriorCellRender::configureFog()
{
Ogre::ColourValue color;
color.setAsABGR (cell.cell->ambi.fog);
color.setAsABGR (mCell.cell->ambi.fog);
float high = 4500 + 9000 * (1-cell.cell->ambi.fogDensity);
float high = 4500 + 9000 * (1-mCell.cell->ambi.fogDensity);
float low = 200;
scene.getMgr()->setFog (FOG_LINEAR, color, 0, low, high);
scene.getCamera()->setFarClipDistance (high + 10);
scene.getViewport()->setBackgroundColour (color);
mScene.getMgr()->setFog (FOG_LINEAR, color, 0, low, high);
mScene.getCamera()->setFarClipDistance (high + 10);
mScene.getViewport()->setBackgroundColour (color);
}
void ExteriorCellRender::setAmbientMode()
{
switch (ambientMode)
switch (mAmbientMode)
{
case 0:
scene.getMgr()->setAmbientLight(ambientColor);
mScene.getMgr()->setAmbientLight(mAmbientColor);
break;
case 1:
scene.getMgr()->setAmbientLight(0.7f*ambientColor + 0.3f*ColourValue(1,1,1));
mScene.getMgr()->setAmbientLight(0.7f*mAmbientColor + 0.3f*ColourValue(1,1,1));
break;
case 2:
scene.getMgr()->setAmbientLight(ColourValue(1,1,1));
mScene.getMgr()->setAmbientLight(ColourValue(1,1,1));
break;
}
}
void ExteriorCellRender::show()
{
base = scene.getRoot()->createChildSceneNode();
mBase = mScene.getRoot()->createChildSceneNode();
configureAmbient();
configureFog();
insertCell(cell, mEnvironment);
insertCell(mCell, mEnvironment);
}
void ExteriorCellRender::hide()
{
if(base)
base->setVisible(false);
if(mBase)
mBase->setVisible(false);
}
void ExteriorCellRender::destroy()
{
if(base)
if(mBase)
{
base->removeAndDestroyAllChildren();
scene.getMgr()->destroySceneNode(base);
mBase->removeAndDestroyAllChildren();
mScene.getMgr()->destroySceneNode(mBase);
}
base = NULL;
mBase = NULL;
}
// Switch through lighting modes.
void ExteriorCellRender::toggleLight()
{
if (ambientMode==2)
ambientMode = 0;
if (mAmbientMode==2)
mAmbientMode = 0;
else
++ambientMode;
++mAmbientMode;
switch (ambientMode)
switch (mAmbientMode)
{
case 0: std::cout << "Setting lights to normal\n"; break;
case 1: std::cout << "Turning the lights up\n"; break;
@ -357,21 +374,21 @@ void ExteriorCellRender::toggleLight()
void ExteriorCellRender::enable (const std::string& handle)
{
if (!handle.empty())
scene.getMgr()->getSceneNode (handle)->setVisible (true);
mScene.getMgr()->getSceneNode (handle)->setVisible (true);
}
void ExteriorCellRender::disable (const std::string& handle)
{
if (!handle.empty())
scene.getMgr()->getSceneNode (handle)->setVisible (false);
mScene.getMgr()->getSceneNode (handle)->setVisible (false);
}
void ExteriorCellRender::deleteObject (const std::string& handle)
{
if (!handle.empty())
{
Ogre::SceneNode *node = scene.getMgr()->getSceneNode (handle);
Ogre::SceneNode *node = mScene.getMgr()->getSceneNode (handle);
node->removeAndDestroyAllChildren();
scene.getMgr()->destroySceneNode (node);
mScene.getMgr()->destroySceneNode (node);
}
}

@ -45,32 +45,37 @@ namespace MWRender
static bool lightOutQuadInLin;
ESMS::CellStore<MWWorld::RefData> &cell;
ESMS::CellStore<MWWorld::RefData> &mCell;
MWWorld::Environment &mEnvironment;
MWScene &scene;
MWScene &mScene;
/// The scene node that contains all objects belonging to this
/// cell.
Ogre::SceneNode *base;
Ogre::SceneNode *mBase;
Ogre::SceneNode *insert;
Ogre::SceneNode *npcPart;
Ogre::SceneNode *mInsert;
std::string mInsertMesh;
Ogre::SceneNode *mNpcPart;
// 0 normal, 1 more bright, 2 max
int ambientMode;
int mAmbientMode;
Ogre::ColourValue ambientColor;
Ogre::ColourValue mAmbientColor;
/// start inserting a new reference.
virtual void insertBegin (ESM::CellRef &ref);
/// insert a mesh related to the most recent insertBegin call.
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst);
virtual void insertMesh(const std::string &mesh);
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements);
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
virtual void insertMesh(const std::string &mesh);
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements);
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
virtual void insertObjectPhysics();
virtual void insertActorPhysics();
/// insert a light related to the most recent insertBegin call.
virtual void insertLight(float r, float g, float b, float radius);
@ -85,13 +90,13 @@ namespace MWRender
void configureFog();
void setAmbientMode();
public:
ExteriorCellRender(ESMS::CellStore<MWWorld::RefData> &_cell, MWWorld::Environment& environment,
MWScene &_scene)
: cell(_cell), mEnvironment (environment), scene(_scene), base(NULL), insert(NULL), ambientMode (0) {}
: mCell(_cell), mEnvironment (environment), mScene(_scene), mBase(NULL), mInsert(NULL), mAmbientMode (0) {}
virtual ~ExteriorCellRender() { destroy(); }

@ -60,57 +60,59 @@ void InteriorCellRender::insertBegin (ESM::CellRef &ref)
// Rotates first around z, then y, then x
insert->setOrientation(xr*yr*zr);
mInsertMesh.clear();
}
// insert a mesh related to the most recent insertBegin call.
void InteriorCellRender::rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements)
{
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->rotate(axis, angle);
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->rotate(axis, angle);
}
// insert a mesh related to the most recent insertBegin call.
void InteriorCellRender::scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements)
{
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->scale(axis);
assert(insert);
Ogre::SceneNode *parent = insert;
//std::cout << "ELEMENTS:" << elements;
for (int i = 0; i < elements; i++){
if(sceneNodeName[i] != "" && parent->getChild(sceneNodeName[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneNodeName[i]));
}
parent->scale(axis);
}
void InteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements)
{
insertMesh(mesh, vec, axis, angle, sceneNodeName, sceneParent, elements, true);
insertMesh(mesh, vec, axis, angle, sceneNodeName, sceneParent, elements, true);
}
void InteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst){
assert (insert);
//insert->
Ogre::SceneNode *parent = insert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
npcPart = parent->createChildSceneNode(sceneNodeName);
//npcPart->showBoundingBox(true);
assert (insert);
//insert->
Ogre::SceneNode *parent = insert;
for (int i = 0; i < elements; i++){
if(sceneParent[i] != "" && parent->getChild(sceneParent[i]))
parent = dynamic_cast<Ogre::SceneNode*> (parent->getChild(sceneParent[i]));
}
npcPart = parent->createChildSceneNode(sceneNodeName);
//npcPart->showBoundingBox(true);
MeshPtr good2 = NIFLoader::load(mesh);
MovableObject *ent = scene.getMgr()->createEntity(mesh);
//ent->extr
// MovableObject *ent2 = scene.getMgr()->createEntity(bounds
// );
// MovableObject *ent2 = scene.getMgr()->createEntity(bounds
// );
//ent->
//std::cout << mesh << bounds << "\n";
@ -119,7 +121,7 @@ void InteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec,
npcPart->rotate(axis, angle);
}
else{
npcPart->rotate(axis, angle);
npcPart->translate(vec);
}
@ -127,55 +129,55 @@ void InteriorCellRender::insertMesh(const std::string &mesh, Ogre::Vector3 vec,
npcPart->attachObject(ent);
Ogre::MeshManager *m = MeshManager::getSingletonPtr();
const std::string beast1 ="meshes\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beast2 ="meshes\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beast3 ="meshes\\b\\B_N_Argonian_F_Skins.nif";
const std::string beast4 ="meshes\\b\\B_N_Argonian_M_Skins.nif";
const std::string beasttail1 ="tail\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beasttail2 ="tail\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beasttail3 ="tail\\b\\B_N_Argonian_F_Skins.nif";
const std::string beasttail4 ="tail\\b\\B_N_Argonian_M_Skins.nif";
const std::string beastfoot1 ="foot\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beastfoot2 ="foot\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beastfoot3 ="foot\\b\\B_N_Argonian_F_Skins.nif";
const std::string beastfoot4 ="foot\\b\\B_N_Argonian_M_Skins.nif";
if(mesh.compare(beast1) == 0 && m->getByName(beasttail1).isNull())
{
//std::cout << "CLONINGKHAJIITF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail1);
good2->reload();
MeshPtr foot = good2->clone(beastfoot1);
good2->reload();
}
else if(mesh.compare(beast2) == 0 && m->getByName(beasttail2).isNull())
{
//std::cout << "CLONINGKHAJIITM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail2);
good2->reload();
MeshPtr foot = good2->clone(beastfoot2);
good2->reload();
}
else if(mesh.compare(beast3) == 0 && m->getByName(beasttail3).isNull())
{
//std::cout << "CLONINGARGONIANF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail3);
good2->reload();
MeshPtr foot = good2->clone(beastfoot3);
good2->reload();
}
else if(mesh.compare(beast4) == 0 && m->getByName(beasttail4).isNull())
{
//std::cout << "CLONINGARGONIANM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail4);
good2->reload();
MeshPtr foot = good2->clone(beastfoot4);
good2->reload();
}
const std::string beast2 ="meshes\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beast3 ="meshes\\b\\B_N_Argonian_F_Skins.nif";
const std::string beast4 ="meshes\\b\\B_N_Argonian_M_Skins.nif";
const std::string beasttail1 ="tail\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beasttail2 ="tail\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beasttail3 ="tail\\b\\B_N_Argonian_F_Skins.nif";
const std::string beasttail4 ="tail\\b\\B_N_Argonian_M_Skins.nif";
const std::string beastfoot1 ="foot\\b\\B_N_Khajiit_F_Skins.nif";
const std::string beastfoot2 ="foot\\b\\B_N_Khajiit_M_Skins.nif";
const std::string beastfoot3 ="foot\\b\\B_N_Argonian_F_Skins.nif";
const std::string beastfoot4 ="foot\\b\\B_N_Argonian_M_Skins.nif";
if(mesh.compare(beast1) == 0 && m->getByName(beasttail1).isNull())
{
//std::cout << "CLONINGKHAJIITF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail1);
good2->reload();
MeshPtr foot = good2->clone(beastfoot1);
good2->reload();
}
else if(mesh.compare(beast2) == 0 && m->getByName(beasttail2).isNull())
{
//std::cout << "CLONINGKHAJIITM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail2);
good2->reload();
MeshPtr foot = good2->clone(beastfoot2);
good2->reload();
}
else if(mesh.compare(beast3) == 0 && m->getByName(beasttail3).isNull())
{
//std::cout << "CLONINGARGONIANF\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail3);
good2->reload();
MeshPtr foot = good2->clone(beastfoot3);
good2->reload();
}
else if(mesh.compare(beast4) == 0 && m->getByName(beasttail4).isNull())
{
//std::cout << "CLONINGARGONIANM\n";
good2->reload();
MeshPtr tail = good2->clone(beasttail4);
good2->reload();
MeshPtr foot = good2->clone(beastfoot4);
good2->reload();
}
}
void InteriorCellRender::insertMesh(const std::string &mesh)
@ -185,6 +187,21 @@ void InteriorCellRender::insertMesh(const std::string &mesh)
NIFLoader::load(mesh);
MovableObject *ent = scene.getMgr()->createEntity(mesh);
insert->attachObject(ent);
if (mInsertMesh.empty())
mInsertMesh = mesh;
}
void InteriorCellRender::insertObjectPhysics()
{
if (!mInsertMesh.empty())
scene.addObject (insert->getName(), mInsertMesh, insert->getOrientation(),
insert->getScale().x, insert->getPosition());
}
void InteriorCellRender::insertActorPhysics()
{
scene.addActor (insert->getName(), mInsertMesh, insert->getPosition());
}
// insert a light related to the most recent insertBegin call.

@ -29,7 +29,7 @@ namespace MWRender
class InteriorCellRender : public CellRender, private CellRenderImp
{
//static bool isChest;
//static bool isChest;
static bool lightConst;
static float lightConstValue;
@ -54,7 +54,8 @@ namespace MWRender
Ogre::SceneNode *base;
Ogre::SceneNode *insert;
Ogre::SceneNode *npcPart;
std::string mInsertMesh;
Ogre::SceneNode *npcPart;
// 0 normal, 1 more bright, 2 max
int ambientMode;
@ -63,12 +64,17 @@ namespace MWRender
/// start inserting a new reference.
virtual void insertBegin (ESM::CellRef &ref);
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements);
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
virtual void rotateMesh(Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName[], int elements);
virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
/// insert a mesh related to the most recent insertBegin call.
virtual void insertMesh(const std::string &mesh);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements);
virtual void insertMesh(const std::string &mesh, Ogre::Vector3 vec, Ogre::Vector3 axis, Ogre::Radian angle, std::string sceneNodeName, std::string sceneParent[], int elements, bool translateFirst);
virtual void insertObjectPhysics();
virtual void insertActorPhysics();
/// insert a light related to the most recent insertBegin call.
virtual void insertLight(float r, float g, float b, float radius);
@ -93,7 +99,7 @@ namespace MWRender
virtual ~InteriorCellRender() { destroy(); }
/// Make the cell visible. Load the cell if necessary.
//virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
//virtual void scaleMesh(Ogre::Vector3 axis, std::string sceneNodeName[], int elements);
virtual void show();
/// Remove the cell from rendering, but don't remove it from

@ -11,80 +11,218 @@
#include "../mwworld/world.hpp" // these includes can be removed once the static-hack is gone
#include "../mwworld/ptr.hpp"
#include "../mwworld/doingphysics.hpp"
#include <components/esm/loadstat.hpp>
#include "player.hpp"
using namespace MWRender;
using namespace Ogre;
MWScene::MWScene(OEngine::Render::OgreRenderer &_rend)
: rend(_rend)
MWScene::MWScene(OEngine::Render::OgreRenderer &_rend , OEngine::Physic::PhysicEngine* physEng)
: rend(_rend)
{
rend.createScene("PlayerCam", 55, 5);
eng = physEng;
rend.createScene("PlayerCam", 55, 5);
// Set default mipmap level (NB some APIs ignore this)
TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Load resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// Turn the entire scene (represented by the 'root' node) -90
// degrees around the x axis. This makes Z go upwards, and Y go into
// the screen (when x is to the right.) This is the orientation that
// Morrowind uses, and it automagically makes everything work as it
// should.
SceneNode *rt = rend.getScene()->getRootSceneNode();
mwRoot = rt->createChildSceneNode();
mwRoot->pitch(Degree(-90));
// Set default mipmap level (NB some APIs ignore this)
TextureManager::getSingleton().setDefaultNumMipmaps(5);
//used to obtain ingame information of ogre objects (which are faced or selected)
mRaySceneQuery = rend.getScene()->createRayQuery(Ray());
// Load resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
Ogre::SceneNode *playerNode = mwRoot->createChildSceneNode();
playerNode->pitch(Degree(90));
Ogre::SceneNode *cameraYawNode = playerNode->createChildSceneNode();
Ogre::SceneNode *cameraPitchNode = cameraYawNode->createChildSceneNode();
cameraPitchNode->attachObject(getCamera());
// Turn the entire scene (represented by the 'root' node) -90
// degrees around the x axis. This makes Z go upwards, and Y go into
// the screen (when x is to the right.) This is the orientation that
// Morrowind uses, and it automagically makes everything work as it
// should.
SceneNode *rt = rend.getScene()->getRootSceneNode();
mwRoot = rt->createChildSceneNode();
mwRoot->pitch(Degree(-90));
//used to obtain ingame information of ogre objects (which are faced or selected)
mRaySceneQuery = rend.getScene()->createRayQuery(Ray());
mPlayer = new MWRender::Player (getCamera(), playerNode->getName());
mFreeFly = true;
}
MWScene::~MWScene()
{
delete mPlayer;
}
std::pair<std::string, float> MWScene::getFacedHandle (MWWorld::World& world)
{
std::string handle = "";
float distance = -1;
//get a ray pointing to the center of the viewport
Ray centerRay = getCamera()->getCameraToViewportRay(
getViewport()->getWidth()/2,
getViewport()->getHeight()/2);
//let's avoid the capsule shape of the player.
centerRay.setOrigin(centerRay.getOrigin() + 20*centerRay.getDirection());
btVector3 from(centerRay.getOrigin().x,-centerRay.getOrigin().z,centerRay.getOrigin().y);
btVector3 to(centerRay.getPoint(500).x,-centerRay.getPoint(500).z,centerRay.getPoint(500).y);
// get all objects touched by the ray
getRaySceneQuery()->setRay (centerRay );
RaySceneQueryResult &result = getRaySceneQuery()->execute();
return eng->rayTest(from,to);
}
void MWScene::doPhysics (float duration, MWWorld::World& world,
const std::vector<std::pair<std::string, Ogre::Vector3> >& actors)
{
// stop changes to world from being reported back to the physics system
MWWorld::DoingPhysics scopeGuard;
RaySceneQueryResult::iterator nearest = result.end();
//set the DebugRenderingMode. To disable it,set it to 0
//eng->setDebugRenderingMode(1);
for (RaySceneQueryResult::iterator itr = result.begin();
itr != result.end(); itr++ )
//set the walkdirection to 0 (no movement) for every actor)
for(std::map<std::string,OEngine::Physic::PhysicActor*>::iterator it = eng->PhysicActorMap.begin(); it != eng->PhysicActorMap.end();it++)
{
// there seem to be omnipresent objects like the caelum sky dom,
// the distance of these objects is always 0 so this if excludes these
if ( itr->movable && itr->distance >= 0.1)
OEngine::Physic::PhysicActor* act = it->second;
act->setWalkDirection(btVector3(0,0,0));
}
for (std::vector<std::pair<std::string, Ogre::Vector3> >::const_iterator iter (actors.begin());
iter!=actors.end(); ++iter)
{
OEngine::Physic::PhysicActor* act = eng->getCharacter(iter->first);
//dirty stuff to get the camera orientation. Must be changed!
Ogre::SceneNode *sceneNode = rend.getScene()->getSceneNode (iter->first);
Ogre::Vector3 dir;
Ogre::Node* yawNode = sceneNode->getChildIterator().getNext();
Ogre::Node* pitchNode = yawNode->getChildIterator().getNext();
if(mFreeFly)
{
Ogre::Quaternion yawQuat = yawNode->getOrientation();
Ogre::Quaternion pitchQuat = pitchNode->getOrientation();
Ogre::Vector3 dir1(iter->second.x,iter->second.z,-iter->second.y);
dir = 0.07*(yawQuat*pitchQuat*dir1);
}
else
{
// horrible hack to exclude statics. this must be removed as soon as a replacement for the
// AABB raycasting is implemented (we should not ignore statics)
MWWorld::Ptr ptr = world.getPtrViaHandle (itr->movable->getParentSceneNode()->getName());
if (ptr.getType()==typeid (ESM::Static))
break;
if ( nearest == result.end() ) //if no object is set
{
nearest = itr;
}
else if ( itr->distance < nearest->distance )
{
nearest = itr;
}
Ogre::Quaternion quat = yawNode->getOrientation();
Ogre::Vector3 dir1(iter->second.x,iter->second.z,-iter->second.y);
dir = 0.025*(quat*dir1);
}
//set the walk direction
act->setWalkDirection(btVector3(dir.x,-dir.z,dir.y));
}
eng->stepSimulation(duration);
if ( nearest != result.end() )
for(std::map<std::string,OEngine::Physic::PhysicActor*>::iterator it = eng->PhysicActorMap.begin(); it != eng->PhysicActorMap.end();it++)
{
handle = nearest->movable->getParentSceneNode()->getName();
distance = nearest->distance;
OEngine::Physic::PhysicActor* act = it->second;
btVector3 newPos = act->getPosition();
MWWorld::Ptr ptr = world.getPtrViaHandle (it->first);
world.moveObject (ptr, newPos.x(), newPos.y(), newPos.z());
}
}
void MWScene::addObject (const std::string& handle, const std::string& mesh,
const Ogre::Quaternion& rotation, float scale, const Ogre::Vector3& position)
{
OEngine::Physic::RigidBody* body = eng->createRigidBody(mesh,handle);
eng->addRigidBody(body);
btTransform tr;
tr.setOrigin(btVector3(position.x,position.y,position.z));
tr.setRotation(btQuaternion(rotation.x,rotation.y,rotation.z,rotation.w));
body->setWorldTransform(tr);
}
return std::pair<std::string, float>(handle, distance);
void MWScene::addActor (const std::string& handle, const std::string& mesh,
const Ogre::Vector3& position)
{
//TODO:optimize this. Searching the std::map isn't very efficient i think.
eng->addCharacter(handle);
OEngine::Physic::PhysicActor* act = eng->getCharacter(handle);
act->setPosition(btVector3(position.x,position.y,position.z));
}
void MWScene::removeObject (const std::string& handle)
{
//TODO:check if actor???
eng->removeCharacter(handle);
eng->removeRigidBody(handle);
eng->deleteRigidBody(handle);
}
void MWScene::moveObject (const std::string& handle, const Ogre::Vector3& position, bool updatePhysics)
{
rend.getScene()->getSceneNode(handle)->setPosition(position);
if(updatePhysics)//TODO: is it an actor? Done?
{
if (OEngine::Physic::RigidBody* body = eng->getRigidBody(handle))
{
// TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
// start positions others than 0, 0, 0
btTransform tr = body->getWorldTransform();
tr.setOrigin(btVector3(position.x,position.y,position.z));
body->setWorldTransform(tr);
}
if (OEngine::Physic::PhysicActor* act = eng->getCharacter(handle))
{
// TODO very dirty hack to avoid crash during setup -> needs cleaning up to allow
// start positions others than 0, 0, 0
act->setPosition(btVector3(position.x,position.y,position.z));
}
}
}
void MWScene::rotateObject (const std::string& handle, const Ogre::Quaternion& rotation)
{
}
void MWScene::scaleObject (const std::string& handle, float scale)
{
}
void MWScene::toggleCollisionMode()
{
for(std::map<std::string,OEngine::Physic::PhysicActor*>::iterator it = eng->PhysicActorMap.begin(); it != eng->PhysicActorMap.end();it++)
{
OEngine::Physic::PhysicActor* act = it->second;
bool cmode = act->getCollisionMode();
if(cmode)
{
act->enableCollisions(false);
act->setGravity(0.);
act->setVerticalVelocity(0);
mFreeFly = true;
}
else
{
mFreeFly = false;
act->enableCollisions(true);
act->setGravity(4.);
act->setVerticalVelocity(0);
}
}
}
void MWScene::toggleRenderMode (int mode)
{
switch (mode)
{
case MWWorld::World::Render_CollisionDebug:
// TODO use a proper function instead of accessing the member variable
// directly.
eng->setDebugRenderingMode (!eng->isDebugCreated);
break;
}
}

@ -3,6 +3,10 @@
#include <utility>
#include <openengine/ogre/renderer.hpp>
#include <openengine/bullet/physic.hpp>
#include <vector>
#include <string>
namespace Ogre
{
@ -11,6 +15,8 @@ namespace Ogre
class SceneManager;
class SceneNode;
class RaySceneQuery;
class Quaternion;
class Vector3;
}
namespace MWWorld
@ -20,36 +26,78 @@ namespace MWWorld
namespace MWRender
{
/** Class responsible for Morrowind-specific interfaces to OGRE.
This might be refactored partially into a non-mw specific
counterpart in ogre/ at some point.
*/
class MWScene
{
OEngine::Render::OgreRenderer &rend;
// Root node for all objects added to the scene. This is rotated so
// that the OGRE coordinate system matches that used internally in
// Morrowind.
Ogre::SceneNode *mwRoot;
Ogre::RaySceneQuery *mRaySceneQuery;
public:
MWScene(OEngine::Render::OgreRenderer &_rend);
Ogre::Camera *getCamera() { return rend.getCamera(); }
Ogre::SceneNode *getRoot() { return mwRoot; }
Ogre::SceneManager *getMgr() { return rend.getScene(); }
Ogre::Viewport *getViewport() { return rend.getViewport(); }
Ogre::RaySceneQuery *getRaySceneQuery() { return mRaySceneQuery; }
//gets the handle of the object the player is looking at
//pair<name, distance>
//name is empty and distance = -1 if there is no object which
//can be faced
std::pair<std::string, float> getFacedHandle (MWWorld::World& world);
};
class Player;
/// \brief 3D-scene (rendering and physics)
class MWScene
{
OEngine::Render::OgreRenderer &rend;
/// Root node for all objects added to the scene. This is rotated so
/// that the OGRE coordinate system matches that used internally in
/// Morrowind.
Ogre::SceneNode *mwRoot;
Ogre::RaySceneQuery *mRaySceneQuery;
OEngine::Physic::PhysicEngine* eng;
MWRender::Player *mPlayer;
bool mFreeFly;
public:
MWScene (OEngine::Render::OgreRenderer &_rend , OEngine::Physic::PhysicEngine* physEng);
~MWScene();
Ogre::Camera *getCamera() { return rend.getCamera(); }
Ogre::SceneNode *getRoot() { return mwRoot; }
Ogre::SceneManager *getMgr() { return rend.getScene(); }
Ogre::Viewport *getViewport() { return rend.getViewport(); }
Ogre::RaySceneQuery *getRaySceneQuery() { return mRaySceneQuery; }
MWRender::Player *getPlayer() { return mPlayer; }
/// Gets the handle of the object the player is looking at
/// pair<name, distance>
/// name is empty and distance = -1 if there is no object which
/// can be faced
std::pair<std::string, float> getFacedHandle (MWWorld::World& world);
/// Run physics simulation and modify \a world accordingly.
void doPhysics (float duration, MWWorld::World& world,
const std::vector<std::pair<std::string, Ogre::Vector3> >& actors);
/// Add object to physics system.
void addObject (const std::string& handle, const std::string& mesh,
const Ogre::Quaternion& rotation, float scale, const Ogre::Vector3& position);
/// Add actor to physics system.
void addActor (const std::string& handle, const std::string& mesh,
const Ogre::Vector3& position);
/// Remove object from physic systems.
void removeObject (const std::string& handle);
/// Move object.
void moveObject (const std::string& handle, const Ogre::Vector3& position, bool updatePhysics);
/// Change object's orientation.
void rotateObject (const std::string& handle, const Ogre::Quaternion& rotation);
/// Change object's scale.
void scaleObject (const std::string& handle, float scale);
/// Toggle collision mode for player. If disabled player object should ignore
/// collisions and gravity.
void toggleCollisionMode();
/// Toggle render mode
/// \todo Using an int instead of a enum here to avoid cyclic includes. Will be fixed
/// when the mw*-refactoring is done.
void toggleRenderMode (int mode);
};
}
#endif

@ -0,0 +1,9 @@
#include "player.hpp"
namespace MWRender
{
Player::Player (Ogre::Camera *camera, const std::string& handle)
: mCamera (camera), mHandle (handle)
{}
}

@ -0,0 +1,29 @@
#ifndef GAME_MWRENDER_PLAYER_H
#define GAME_MWRENDER_PLAYER_H
#include <iostream>
namespace Ogre
{
class Camera;
}
namespace MWRender
{
/// \brief Player character rendering and camera control
class Player
{
Ogre::Camera *mCamera;
std::string mHandle;
public:
Player (Ogre::Camera *camera, const std::string& handle);
Ogre::Camera *getCamera() { return mCamera; }
std::string getHandle() const { return mHandle; }
};
}
#endif

@ -1,41 +0,0 @@
#include "playerpos.hpp"
#include "../mwworld/world.hpp"
namespace MWRender
{
PlayerPos::PlayerPos (Ogre::Camera *cam, const ESM::NPC *player, MWWorld::World& world) :
mCellStore (0), camera(cam), mWorld (world), mClass (0)
{
mPlayer.base = player;
mName = player->name;
mMale = !(player->flags & ESM::NPC::Female);
mRace = player->race;
mPlayer.ref.pos.pos[0] = mPlayer.ref.pos.pos[1] = mPlayer.ref.pos.pos[2] = 0;
mClass = new ESM::Class (*world.getStore().classes.find (player->cls));
}
PlayerPos::~PlayerPos()
{
delete mClass;
}
void PlayerPos::setPos(float x, float y, float z, bool updateCamera)
{
mWorld.moveObject (getPlayer(), x, y, z);
if (updateCamera)
camera->setPosition (Ogre::Vector3 (
mPlayer.ref.pos.pos[0],
mPlayer.ref.pos.pos[2],
-mPlayer.ref.pos.pos[1]));
}
void PlayerPos::setClass (const ESM::Class& class_)
{
ESM::Class *new_class = new ESM::Class (class_);
delete mClass;
mClass = new_class;
}
}

@ -1,128 +0,0 @@
#ifndef _MWRENDER_PLAYERPOS_H
#define _MWRENDER_PLAYERPOS_H
#include "OgreCamera.h"
#include <components/esm_store/cell_store.hpp>
#include "../mwworld/refdata.hpp"
#include "../mwworld/ptr.hpp"
namespace MWWorld
{
class World;
}
namespace MWRender
{
// This class keeps track of the player position. It takes care of
// camera movement, sound listener updates, and collision handling
// (to be done).
class PlayerPos
{
ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> mPlayer;
MWWorld::Ptr::CellStore *mCellStore;
Ogre::Camera *camera;
MWWorld::World& mWorld;
std::string mName;
bool mMale;
std::string mRace;
std::string mBirthsign;
ESM::Class *mClass;
public:
PlayerPos(Ogre::Camera *cam, const ESM::NPC *player, MWWorld::World& world);
~PlayerPos();
// Set the player position. Uses Morrowind coordinates.
void setPos(float _x, float _y, float _z, bool updateCamera = false);
void setCell (MWWorld::Ptr::CellStore *cellStore)
{
mCellStore = cellStore;
}
Ogre::Camera *getCamera() { return camera; }
// Move the player relative to her own position and
// orientation. After the call, the new position is returned.
void moveRel(float &relX, float &relY, float &relZ)
{
using namespace Ogre;
// Move camera relative to its own direction
camera->moveRelative(Vector3(relX,0,relZ));
// Up/down movement is always done relative the world axis.
camera->move(Vector3(0,relY,0));
// Get new camera position, converting back to MW coords.
Vector3 pos = camera->getPosition();
relX = pos[0];
relY = -pos[2];
relZ = pos[1];
// TODO: Collision detection must be used to find the REAL new
// position.
// Set the position
setPos(relX, relY, relZ);
}
MWWorld::Ptr getPlayer()
{
MWWorld::Ptr ptr (&mPlayer, mCellStore);
return ptr;
}
void setName (const std::string& name)
{
mName = name;
}
void setGender (bool male)
{
mMale = male;
}
void setRace (const std::string& race)
{
mRace = race;
}
void setBirthsign (const std::string& birthsign)
{
mBirthsign = birthsign;
}
void setClass (const ESM::Class& class_);
std::string getName() const
{
return mName;
}
bool isMale() const
{
return mMale;
}
std::string getRace() const
{
return mRace;
}
std::string getBirthsign() const
{
return mBirthsign;
}
const ESM::Class& getClass() const
{
return *mClass;
}
};
}
#endif

@ -19,7 +19,8 @@ namespace MWRender
public:
CaelumManager (Ogre::RenderWindow* pRenderWindow,
Ogre::Camera* pCamera);
Ogre::Camera* pCamera,
const boost::filesystem::path& resDir);
virtual ~CaelumManager ();
virtual void enable() {}
@ -44,7 +45,8 @@ namespace MWRender
};
CaelumManager::CaelumManager (Ogre::RenderWindow* pRenderWindow,
Ogre::Camera* pCamera)
Ogre::Camera* pCamera,
const boost::filesystem::path& resDir)
: mpCaelumSystem (NULL)
{
using namespace Ogre;
@ -55,7 +57,7 @@ namespace MWRender
// Load the Caelum resources
//
ResourceGroupManager::getSingleton().addResourceLocation("resources/caelum", "FileSystem", "Caelum");
ResourceGroupManager::getSingleton().addResourceLocation((resDir / "caelum").string(), "FileSystem", "Caelum");
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// Load the Caelum resources
@ -89,13 +91,14 @@ namespace MWRender
/// \return NULL on failure.
///
SkyManager* SkyManager::create (Ogre::RenderWindow* pRenderWindow,
Ogre::Camera* pCamera)
Ogre::Camera* pCamera,
const boost::filesystem::path& resDir)
{
SkyManager* pSkyManager = NULL;
try
{
pSkyManager = new CaelumManager(pRenderWindow, pCamera);
pSkyManager = new CaelumManager(pRenderWindow, pCamera, resDir);
}
catch (Ogre::Exception& e)
{

@ -1,6 +1,8 @@
#ifndef _GAME_RENDER_SKY_H
#define _GAME_RENDER_SKY_H
#include <boost/filesystem.hpp>
namespace Ogre
{
class RenderWindow;
@ -16,7 +18,8 @@ namespace MWRender
{
public:
static SkyManager* create (Ogre::RenderWindow* pRenderWindow,
Ogre::Camera* pCamera);
Ogre::Camera* pCamera,
const boost::filesystem::path& resDir);
virtual ~SkyManager() {}
virtual void enable() = 0;

@ -8,6 +8,7 @@
#include <components/interpreter/opcodes.hpp>
#include "interpretercontext.hpp"
#include "ref.hpp"
#include <iostream>
@ -15,46 +16,14 @@ namespace MWScript
{
namespace Ai
{
template<class R>
class OpAiTravel : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
Interpreter::Type_Float x = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mInteger;
runtime.pop();
// discard additional arguments (reset), because we have no idea what they mean.
for (unsigned int i=0; i<arg0; ++i) runtime.pop();
std::cout << "AiTravel: " << x << ", " << y << ", " << z << std::endl;
}
};
class OpAiTravelExplicit : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Float x = runtime[0].mInteger;
runtime.pop();
@ -72,56 +41,14 @@ namespace MWScript
}
};
template<class R>
class OpAiEscort : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
std::string actor = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float duration = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float x = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float y = runtime[0].mInteger;
runtime.pop();
Interpreter::Type_Float z = runtime[0].mInteger;
runtime.pop();
// discard additional arguments (reset), because we have no idea what they mean.
for (unsigned int i=0; i<arg0; ++i) runtime.pop();
std::cout << "AiEscort: " << x << ", " << y << ", " << z << ", " << duration
<< std::endl;
}
};
class OpAiEscortExplicit : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
std::string actor = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
@ -146,16 +73,14 @@ namespace MWScript
}
};
template<class R>
class OpGetAiPackageDone : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = 0;
@ -163,25 +88,6 @@ namespace MWScript
}
};
class OpGetAiPackageDoneExplicit : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
Interpreter::Type_Integer value = 0;
runtime.push (value);
}
};
const int opcodeAiTravel = 0x20000;
@ -204,12 +110,13 @@ namespace MWScript
void installOpcodes (Interpreter::Interpreter& interpreter)
{
interpreter.installSegment3 (opcodeAiTravel, new OpAiTravel);
interpreter.installSegment3 (opcodeAiTravelExplicit, new OpAiTravelExplicit);
interpreter.installSegment3 (opcodeAiEscort, new OpAiEscort);
interpreter.installSegment3 (opcodeAiEscortExplicit, new OpAiEscortExplicit);
interpreter.installSegment5 (opcodeGetAiPackageDone, new OpGetAiPackageDone);
interpreter.installSegment5 (opcodeGetAiPackageDoneExplicit, new OpGetAiPackageDoneExplicit);
interpreter.installSegment3 (opcodeAiTravel, new OpAiTravel<ImplicitRef>);
interpreter.installSegment3 (opcodeAiTravelExplicit, new OpAiTravel<ExplicitRef>);
interpreter.installSegment3 (opcodeAiEscort, new OpAiEscort<ImplicitRef>);
interpreter.installSegment3 (opcodeAiEscortExplicit, new OpAiEscort<ExplicitRef>);
interpreter.installSegment5 (opcodeGetAiPackageDone, new OpGetAiPackageDone<ImplicitRef>);
interpreter.installSegment5 (opcodeGetAiPackageDoneExplicit,
new OpGetAiPackageDone<ExplicitRef>);
}
}
}

@ -8,6 +8,7 @@
#include <components/interpreter/opcodes.hpp>
#include "../mwworld/world.hpp"
#include "../mwworld/player.hpp"
#include "interpretercontext.hpp"
@ -53,7 +54,7 @@ namespace MWScript
else
{
pos.pos[0] = pos.pos[1] = 0;
context.getWorld().changeCell (cell, pos);
context.getWorld().changeToInteriorCell (cell, pos);
}
}
};
@ -84,9 +85,27 @@ namespace MWScript
}
};
class OpGetInterior : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
InterpreterContext& context
= static_cast<InterpreterContext&> (runtime.getContext());
bool interior =
context.getWorld().getPlayer().getPlayer().getCell()->cell->data.flags &
ESM::Cell::Interior;
runtime.push (interior ? 1 : 0);
}
};
const int opcodeCellChanged = 0x2000000;
const int opcodeCOC = 0x2000026;
const int opcodeCOE = 0x200008e;
const int opcodeGetInterior = 0x2000131;
void registerExtensions (Compiler::Extensions& extensions)
{
@ -95,6 +114,7 @@ namespace MWScript
extensions.registerInstruction ("centeroncell", "S", opcodeCOC);
extensions.registerInstruction ("coe", "ll", opcodeCOE);
extensions.registerInstruction ("centeronexterior", "ll", opcodeCOE);
extensions.registerFunction ("getinterior", 'l', "", opcodeGetInterior);
}
void installOpcodes (Interpreter::Interpreter& interpreter)
@ -102,6 +122,7 @@ namespace MWScript
interpreter.installSegment5 (opcodeCellChanged, new OpCellChanged);
interpreter.installSegment5 (opcodeCOC, new OpCOC);
interpreter.installSegment5 (opcodeCOE, new OpCOE);
interpreter.installSegment5 (opcodeGetInterior, new OpGetInterior);
}
}
}

@ -14,52 +14,24 @@
#include "../mwworld/containerutil.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Container
{
template<class R>
class OpAddItem : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer count = runtime[0].mInteger;
runtime.pop();
if (count<0)
throw std::runtime_error ("second argument for AddItem must be non-negative");
MWWorld::Ptr ptr = context.getReference();
MWWorld::ManualRef ref (context.getWorld().getStore(), item);
MWWorld::Ptr ptr = R()(runtime);
ref.getPtr().getRefData().setCount (count);
MWWorld::Class::get (ref.getPtr()).insertIntoContainer (ref.getPtr(),
MWWorld::Class::get (ptr).getContainerStore (ptr));
}
};
class OpAddItemExplicit : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
@ -69,8 +41,6 @@ namespace MWScript
if (count<0)
throw std::runtime_error ("second argument for AddItem must be non-negative");
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::ManualRef ref (context.getWorld().getStore(), item);
ref.getPtr().getRefData().setCount (count);
@ -80,55 +50,21 @@ namespace MWScript
}
};
template<class R>
class OpGetItemCount : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
std::vector<MWWorld::Ptr> list;
MWWorld::listItemsInContainer (item,
MWWorld::Class::get (ptr).getContainerStore (ptr),
context.getWorld().getStore(), list);
Interpreter::Type_Integer sum = 0;
for (std::vector<MWWorld::Ptr>::iterator iter (list.begin()); iter!=list.end();
++iter)
{
sum += iter->getRefData().getCount();
}
runtime.push (sum);
}
};
class OpGetItemCountExplicit : public Interpreter::Opcode0
{
public:
MWWorld::Ptr ptr = R()(runtime);
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
std::vector<MWWorld::Ptr> list;
MWWorld::listItemsInContainer (item,
@ -147,65 +83,18 @@ namespace MWScript
}
};
template<class R>
class OpRemoveItem : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer count = runtime[0].mInteger;
runtime.pop();
if (count<0)
throw std::runtime_error ("second argument for RemoveItem must be non-negative");
MWWorld::Ptr ptr = context.getReference();
std::vector<MWWorld::Ptr> list;
MWWorld::listItemsInContainer (item,
MWWorld::Class::get (ptr).getContainerStore (ptr),
context.getWorld().getStore(), list);
for (std::vector<MWWorld::Ptr>::iterator iter (list.begin());
iter!=list.end() && count;
++iter)
{
if (iter->getRefData().getCount()<=count)
{
count -= iter->getRefData().getCount();
iter->getRefData().setCount (0);
}
else
{
iter->getRefData().setCount (iter->getRefData().getCount()-count);
count = 0;
}
}
MWWorld::Ptr ptr = R()(runtime);
// To be fully compatible with original Morrowind, we would need to check if
// count is >= 0 here and throw an exception. But let's be tollerant instead.
}
};
class OpRemoveItemExplicit : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string item = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
@ -215,8 +104,6 @@ namespace MWScript
if (count<0)
throw std::runtime_error ("second argument for RemoveItem must be non-negative");
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
std::vector<MWWorld::Ptr> list;
MWWorld::listItemsInContainer (item,
@ -262,12 +149,12 @@ namespace MWScript
void installOpcodes (Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5 (opcodeAddItem, new OpAddItem);
interpreter.installSegment5 (opcodeAddItemExplicit, new OpAddItemExplicit);
interpreter.installSegment5 (opcodeGetItemCount, new OpGetItemCount);
interpreter.installSegment5 (opcodeGetItemCountExplicit, new OpGetItemCountExplicit);
interpreter.installSegment5 (opcodeRemoveItem, new OpRemoveItem);
interpreter.installSegment5 (opcodeRemoveItemExplicit, new OpRemoveItemExplicit);
interpreter.installSegment5 (opcodeAddItem, new OpAddItem<ImplicitRef>);
interpreter.installSegment5 (opcodeAddItemExplicit, new OpAddItem<ExplicitRef>);
interpreter.installSegment5 (opcodeGetItemCount, new OpGetItemCount<ImplicitRef>);
interpreter.installSegment5 (opcodeGetItemCountExplicit, new OpGetItemCount<ExplicitRef>);
interpreter.installSegment5 (opcodeRemoveItem, new OpRemoveItem<ImplicitRef>);
interpreter.installSegment5 (opcodeRemoveItemExplicit, new OpRemoveItem<ExplicitRef>);
}
}
}

@ -7,6 +7,8 @@
#include <components/interpreter/runtime.hpp>
#include <components/interpreter/opcodes.hpp>
#include "../mwworld/player.hpp"
#include "interpretercontext.hpp"
#include <iostream>
@ -35,10 +37,24 @@ namespace MWScript
}
};
class OpToggleCollision : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
InterpreterContext& context
= static_cast<InterpreterContext&> (runtime.getContext());
context.getWorld().toggleCollisionMode();
}
};
const int numberOfControls = 7;
const int opcodeEnable = 0x200007e;
const int opcodeDisable = 0x2000085;
const int opcodeToggleCollision = 0x2000130;
const char *controls[numberOfControls] =
{
@ -56,6 +72,8 @@ namespace MWScript
extensions.registerInstruction (enable + controls[i], "", opcodeEnable+i);
extensions.registerInstruction (disable + controls[i], "", opcodeDisable+i);
}
extensions.registerInstruction ("togglecollision", "", opcodeToggleCollision);
}
void installOpcodes (Interpreter::Interpreter& interpreter)
@ -65,6 +83,8 @@ namespace MWScript
interpreter.installSegment5 (opcodeEnable+i, new OpSetControl (controls[i], true));
interpreter.installSegment5 (opcodeDisable+i, new OpSetControl (controls[i], false));
}
interpreter.installSegment5 (opcodeToggleCollision, new OpToggleCollision);
}
}
}

@ -101,4 +101,7 @@ op 0x20000c4-0x20000de: SetSkill
op 0x20000df-0x20000f9: SetSkill, explicit reference
op 0x20000fa-0x2000114: ModSkill
op 0x2000115-0x200012f: ModSKill, explicit reference
opcodes 0x2000130-0x3ffffff unused
op 0x2000130: ToggleCollision
op 0x2000131: GetInterior
op 0x2000132: ToggleCollsionDebug
opcodes 0x2000133-0x3ffffff unused

@ -7,10 +7,11 @@
#include <components/interpreter/runtime.hpp>
#include <components/interpreter/opcodes.hpp>
#include "interpretercontext.hpp"
#include "../mwworld/class.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Misc
@ -55,42 +56,14 @@ namespace MWScript
}
};
template<class R>
class OpLock : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
InterpreterContext& context =
static_cast<InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
Interpreter::Type_Integer lockLevel = 100;
if (arg0==1)
{
lockLevel = runtime[0].mInteger;
runtime.pop();
}
MWWorld::Class::get (ptr).lock (ptr, lockLevel);
}
};
class OpLockExplicit : public Interpreter::Opcode1
{
public:
virtual void execute (Interpreter::Runtime& runtime, unsigned int arg0)
{
InterpreterContext& context =
static_cast<InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer lockLevel = 100;
@ -104,22 +77,20 @@ namespace MWScript
}
};
template<class R>
class OpUnlock : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
InterpreterContext& context =
static_cast<InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
MWWorld::Ptr ptr = R()(runtime);
MWWorld::Class::get (ptr).unlock (ptr);
}
};
class OpUnlockExplicit : public Interpreter::Opcode0
class OpToggleCollisionDebug : public Interpreter::Opcode0
{
public:
@ -128,16 +99,10 @@ namespace MWScript
InterpreterContext& context =
static_cast<InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Class::get (ptr).unlock (ptr);
context.getWorld().toggleRenderMode (MWWorld::World::Render_CollisionDebug);
}
};
const int opcodeXBox = 0x200000c;
const int opcodeOnActivate = 0x200000d;
const int opcodeActivate = 0x2000075;
@ -145,6 +110,7 @@ namespace MWScript
const int opcodeLockExplicit = 0x20005;
const int opcodeUnlock = 0x200008c;
const int opcodeUnlockExplicit = 0x200008d;
const int opcodeToggleCollisionDebug = 0x2000132;
void registerExtensions (Compiler::Extensions& extensions)
{
@ -153,6 +119,10 @@ namespace MWScript
extensions.registerInstruction ("activate", "", opcodeActivate);
extensions.registerInstruction ("lock", "/l", opcodeLock, opcodeLockExplicit);
extensions.registerInstruction ("unlock", "", opcodeUnlock, opcodeUnlockExplicit);
extensions.registerInstruction ("togglecollisionboxes", "", opcodeToggleCollisionDebug);
extensions.registerInstruction ("togglecollisiongrid", "", opcodeToggleCollisionDebug);
extensions.registerInstruction ("tcb", "", opcodeToggleCollisionDebug);
extensions.registerInstruction ("tcg", "", opcodeToggleCollisionDebug);
}
void installOpcodes (Interpreter::Interpreter& interpreter)
@ -160,10 +130,11 @@ namespace MWScript
interpreter.installSegment5 (opcodeXBox, new OpXBox);
interpreter.installSegment5 (opcodeOnActivate, new OpOnActivate);
interpreter.installSegment5 (opcodeActivate, new OpActivate);
interpreter.installSegment3 (opcodeLock, new OpLock);
interpreter.installSegment3 (opcodeLockExplicit, new OpLockExplicit);
interpreter.installSegment5 (opcodeUnlock, new OpUnlock);
interpreter.installSegment5 (opcodeUnlockExplicit, new OpUnlockExplicit);
interpreter.installSegment3 (opcodeLock, new OpLock<ImplicitRef>);
interpreter.installSegment3 (opcodeLockExplicit, new OpLock<ExplicitRef>);
interpreter.installSegment5 (opcodeUnlock, new OpUnlock<ImplicitRef>);
interpreter.installSegment5 (opcodeUnlockExplicit, new OpUnlock<ExplicitRef>);
interpreter.installSegment5 (opcodeToggleCollisionDebug, new OpToggleCollisionDebug);
}
}
}

@ -0,0 +1,41 @@
#ifndef GAME_MWSCRIPT_REF_H
#define GAME_MWSCRIPT_REF_H
#include <string>
#include <components/interpreter/runtime.hpp>
#include "../mwworld/ptr.hpp"
#include "../mwworld/world.hpp"
#include "interpretercontext.hpp"
namespace MWScript
{
struct ExplicitRef
{
MWWorld::Ptr operator() (Interpreter::Runtime& runtime) const
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
return context.getWorld().getPtr (id, false);
}
};
struct ImplicitRef
{
MWWorld::Ptr operator() (Interpreter::Runtime& runtime) const
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
return context.getReference();
}
};
}
#endif

@ -7,22 +7,26 @@
#include <components/interpreter/runtime.hpp>
#include <components/interpreter/opcodes.hpp>
#include "interpretercontext.hpp"
#include "../mwworld/world.hpp"
#include "../mwsound/soundmanager.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Sound
{
template<class R>
class OpSay : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
@ -32,296 +36,173 @@ namespace MWScript
std::string text = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().say (context.getReference(), file);
context.getSoundManager().say (ptr, file);
context.messageBox (text);
}
};
}
};
template<class R>
class OpSayDone : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
runtime.push (context.getSoundManager().sayDone (context.getReference()));
}
};
runtime.push (context.getSoundManager().sayDone (ptr));
}
};
class OpStreamMusic : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().streamMusic (sound);
}
};
}
};
class OpPlaySound : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().playSound (sound, 1.0, 1.0);
}
};
}
};
class OpPlaySoundVP : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float volume = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float pitch = runtime[0].mFloat;
runtime.pop();
context.getSoundManager().playSound (sound, volume, pitch);
}
};
}
};
template<class R>
class OpPlaySound3D : public Interpreter::Opcode0
{
bool mLoop;
public:
OpPlaySound3D (bool loop) : mLoop (loop) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().playSound3D (context.getReference(), sound,
1.0, 1.0, mLoop);
}
};
context.getSoundManager().playSound3D (ptr, sound, 1.0, 1.0, mLoop);
}
};
template<class R>
class OpPlaySoundVP3D : public Interpreter::Opcode0
{
bool mLoop;
public:
OpPlaySoundVP3D (bool loop) : mLoop (loop) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float volume = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float pitch = runtime[0].mFloat;
runtime.pop();
context.getSoundManager().playSound3D (context.getReference(), sound, volume,
pitch, mLoop);
}
};
context.getSoundManager().playSound3D (ptr, sound, volume, pitch, mLoop);
class OpStopSound : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().stopSound3D (context.getReference(), sound);
}
};
class OpGetSoundPlaying : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
int index = runtime[0].mInteger;
runtime.pop();
runtime.push (context.getSoundManager().getSoundPlaying (
context.getReference(), runtime.getStringLiteral (index)));
}
}
};
class OpSayExplicit : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string file = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string text = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().say (context.getWorld().getPtr (id, true),
file);
}
};
class OpSayDoneExplicit : public Interpreter::Opcode0
template<class R>
class OpStopSound : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
runtime.push (context.getSoundManager().sayDone (
context.getWorld().getPtr (id, true)));
}
};
class OpPlaySound3DExplicit : public Interpreter::Opcode0
{
bool mLoop;
public:
OpPlaySound3DExplicit (bool loop) : mLoop (loop) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().playSound3D (
context.getWorld().getPtr (id, true), sound, 1.0, 1.0, mLoop);
}
};
class OpPlaySoundVP3DExplicit : public Interpreter::Opcode0
{
bool mLoop;
public:
OpPlaySoundVP3DExplicit (bool loop) : mLoop (loop) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Float volume = runtime[0].mFloat;
runtime.pop();
Interpreter::Type_Float pitch = runtime[0].mFloat;
runtime.pop();
context.getSoundManager().playSound3D (
context.getWorld().getPtr (id, true), sound, volume, pitch, mLoop);
}
};
context.getSoundManager().stopSound3D (ptr, sound);
}
};
class OpStopSoundExplicit : public Interpreter::Opcode0
template<class R>
class OpGetSoundPlaying : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
std::string sound = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
context.getSoundManager().stopSound3D (
context.getWorld().getPtr (id, true), sound);
}
};
class OpGetSoundPlayingExplicit : public Interpreter::Opcode0
{
public:
virtual void execute (Interpreter::Runtime& runtime)
{
MWWorld::Ptr ptr = R()(runtime);
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
int index = runtime[0].mInteger;
runtime.pop();
runtime.push (context.getSoundManager().getSoundPlaying (
context.getWorld().getPtr (id, true),
runtime.getStringLiteral (index)));
}
};
ptr, runtime.getStringLiteral (index)));
}
};
const int opcodeSay = 0x2000001;
const int opcodeSayDone = 0x2000002;
const int opcodeStreamMusic = 0x2000003;
@ -342,7 +223,7 @@ namespace MWScript
const int opcodePlayLoopSound3DVPExplicit = 0x200001e;
const int opcodeStopSoundExplicit = 0x200001f;
const int opcodeGetSoundPlayingExplicit = 0x2000020;
void registerExtensions (Compiler::Extensions& extensions)
{
extensions.registerInstruction ("say", "SS", opcodeSay, opcodeSayExplicit);
@ -361,37 +242,37 @@ namespace MWScript
extensions.registerInstruction ("stopsound", "c", opcodeStopSound,
opcodeStopSoundExplicit);
extensions.registerFunction ("getsoundplaying", 'l', "c", opcodeGetSoundPlaying,
opcodeGetSoundPlayingExplicit);
opcodeGetSoundPlayingExplicit);
}
void installOpcodes (Interpreter::Interpreter& interpreter)
{
interpreter.installSegment5 (opcodeSay, new OpSay);
interpreter.installSegment5 (opcodeSayDone, new OpSayDone);
interpreter.installSegment5 (opcodeSay, new OpSay<ImplicitRef>);
interpreter.installSegment5 (opcodeSayDone, new OpSayDone<ImplicitRef>);
interpreter.installSegment5 (opcodeStreamMusic, new OpStreamMusic);
interpreter.installSegment5 (opcodePlaySound, new OpPlaySound);
interpreter.installSegment5 (opcodePlaySoundVP, new OpPlaySoundVP);
interpreter.installSegment5 (opcodePlaySound3D, new OpPlaySound3D (false));
interpreter.installSegment5 (opcodePlaySound3DVP, new OpPlaySoundVP3D (false));
interpreter.installSegment5 (opcodePlayLoopSound3D, new OpPlaySound3D (true));
interpreter.installSegment5 (opcodePlayLoopSound3DVP, new OpPlaySoundVP3D (true));
interpreter.installSegment5 (opcodeStopSound, new OpStopSound);
interpreter.installSegment5 (opcodeGetSoundPlaying, new OpGetSoundPlaying);
interpreter.installSegment5 (opcodeSayExplicit, new OpSayExplicit);
interpreter.installSegment5 (opcodeSayDoneExplicit, new OpSayDoneExplicit);
interpreter.installSegment5 (opcodePlaySound3D, new OpPlaySound3D<ImplicitRef> (false));
interpreter.installSegment5 (opcodePlaySound3DVP, new OpPlaySoundVP3D<ImplicitRef> (false));
interpreter.installSegment5 (opcodePlayLoopSound3D, new OpPlaySound3D<ImplicitRef> (true));
interpreter.installSegment5 (opcodePlayLoopSound3DVP,
new OpPlaySoundVP3D<ImplicitRef> (true));
interpreter.installSegment5 (opcodeStopSound, new OpStopSound<ImplicitRef>);
interpreter.installSegment5 (opcodeGetSoundPlaying, new OpGetSoundPlaying<ImplicitRef>);
interpreter.installSegment5 (opcodeSayExplicit, new OpSay<ExplicitRef>);
interpreter.installSegment5 (opcodeSayDoneExplicit, new OpSayDone<ExplicitRef>);
interpreter.installSegment5 (opcodePlaySound3DExplicit,
new OpPlaySound3DExplicit (false));
new OpPlaySound3D<ExplicitRef> (false));
interpreter.installSegment5 (opcodePlaySound3DVPExplicit,
new OpPlaySoundVP3DExplicit (false));
new OpPlaySoundVP3D<ExplicitRef> (false));
interpreter.installSegment5 (opcodePlayLoopSound3DExplicit,
new OpPlaySound3DExplicit (true));
new OpPlaySound3D<ExplicitRef> (true));
interpreter.installSegment5 (opcodePlayLoopSound3DVPExplicit,
new OpPlaySoundVP3DExplicit (true));
interpreter.installSegment5 (opcodeStopSoundExplicit, new OpStopSoundExplicit);
new OpPlaySoundVP3D<ExplicitRef> (true));
interpreter.installSegment5 (opcodeStopSoundExplicit, new OpStopSound<ExplicitRef>);
interpreter.installSegment5 (opcodeGetSoundPlayingExplicit,
new OpGetSoundPlayingExplicit);
new OpGetSoundPlaying<ExplicitRef>);
}
}
}
}

@ -12,11 +12,13 @@
#include "../mwmechanics/creaturestats.hpp"
#include "interpretercontext.hpp"
#include "ref.hpp"
namespace MWScript
{
namespace Stats
{
template<class R>
class OpGetAttribute : public Interpreter::Opcode0
{
int mIndex;
@ -27,36 +29,7 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
getModified();
runtime.push (value);
}
};
class OpGetAttributeExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpGetAttributeExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
@ -66,6 +39,7 @@ namespace MWScript
}
};
template<class R>
class OpSetAttribute : public Interpreter::Opcode0
{
int mIndex;
@ -76,45 +50,17 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
setModified (value, 0);
}
};
class OpSetAttributeExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpSetAttributeExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
setModified (value, 0);
}
};
template<class R>
class OpModAttribute : public Interpreter::Opcode0
{
int mIndex;
@ -125,14 +71,11 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
value += MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
getModified();
@ -141,36 +84,7 @@ namespace MWScript
}
};
class OpModAttributeExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpModAttributeExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
value +=
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
getModified();
MWWorld::Class::get (ptr).getCreatureStats (ptr).mAttributes[mIndex].
setModified (value, 0, 100);
}
};
template<class R>
class OpGetDynamic : public Interpreter::Opcode0
{
int mIndex;
@ -181,46 +95,7 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
if (mIndex==0 && MWWorld::Class::get (ptr).hasItemHealth (ptr))
{
// health is a special case
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getItemMaxHealth (ptr);
runtime.push (value);
return;
}
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getCreatureStats (ptr).mDynamic[mIndex].
getCurrent();
runtime.push (value);
}
};
class OpGetDynamicExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpGetDynamicExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
if (mIndex==0 && MWWorld::Class::get (ptr).hasItemHealth (ptr))
{
@ -240,6 +115,7 @@ namespace MWScript
}
};
template<class R>
class OpSetDynamic : public Interpreter::Opcode0
{
int mIndex;
@ -250,45 +126,17 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
MWWorld::Class::get (ptr).getCreatureStats (ptr).mDynamic[mIndex].
setModified (value, 0);
}
};
class OpSetDynamicExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpSetDynamicExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Class::get (ptr).getCreatureStats (ptr).mDynamic[mIndex].
setModified (value, 0);
}
};
template<class R>
class OpModDynamic : public Interpreter::Opcode0
{
int mIndex;
@ -299,14 +147,11 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer diff = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
MWMechanics::CreatureStats& stats = MWWorld::Class::get (ptr).getCreatureStats (ptr);
Interpreter::Type_Integer current = stats.mDynamic[mIndex].getCurrent();
@ -318,40 +163,7 @@ namespace MWScript
}
};
class OpModDynamicExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpModDynamicExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer diff = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWMechanics::CreatureStats& stats =
MWWorld::Class::get (ptr).getCreatureStats (ptr);
Interpreter::Type_Integer current = stats.mDynamic[mIndex].getCurrent();
stats.mDynamic[mIndex].setModified (
diff + stats.mDynamic[mIndex].getModified(), 0);
stats.mDynamic[mIndex].setCurrent (diff + current);
}
};
template<class R>
class OpModCurrentDynamic : public Interpreter::Opcode0
{
int mIndex;
@ -362,14 +174,11 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer diff = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
MWMechanics::CreatureStats& stats = MWWorld::Class::get (ptr).getCreatureStats (ptr);
Interpreter::Type_Integer current = stats.mDynamic[mIndex].getCurrent();
@ -378,36 +187,7 @@ namespace MWScript
}
};
class OpModCurrentDynamicExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpModCurrentDynamicExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer diff = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWMechanics::CreatureStats& stats =
MWWorld::Class::get (ptr).getCreatureStats (ptr);
Interpreter::Type_Integer current = stats.mDynamic[mIndex].getCurrent();
stats.mDynamic[mIndex].setCurrent (diff + current);
}
};
template<class R>
class OpGetDynamicGetRatio : public Interpreter::Opcode0
{
int mIndex;
@ -418,10 +198,7 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
MWWorld::Ptr ptr = R()(runtime);
MWMechanics::CreatureStats& stats = MWWorld::Class::get (ptr).getCreatureStats (ptr);
@ -436,38 +213,7 @@ namespace MWScript
}
};
class OpGetDynamicGetRatioExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpGetDynamicGetRatioExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWMechanics::CreatureStats& stats =
MWWorld::Class::get (ptr).getCreatureStats (ptr);
Interpreter::Type_Float value = 0;
Interpreter::Type_Float max = stats.mDynamic[mIndex].getModified();
if (max>0)
value = stats.mDynamic[mIndex].getCurrent() / max;
runtime.push (value);
}
};
template<class R>
class OpGetSkill : public Interpreter::Opcode0
{
int mIndex;
@ -478,36 +224,7 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = context.getReference();
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
getModified();
runtime.push (value);
}
};
class OpGetSkillExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpGetSkillExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value =
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
@ -517,6 +234,7 @@ namespace MWScript
}
};
template<class R>
class OpSetSkill : public Interpreter::Opcode0
{
int mIndex;
@ -527,45 +245,17 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
setModified (value, 0);
}
};
class OpSetSkillExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpSetSkillExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
setModified (value, 0);
}
};
template<class R>
class OpModSkill : public Interpreter::Opcode0
{
int mIndex;
@ -576,14 +266,11 @@ namespace MWScript
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
MWWorld::Ptr ptr = R()(runtime);
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getReference();
value += MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
getModified();
@ -592,36 +279,6 @@ namespace MWScript
}
};
class OpModSkillExplicit : public Interpreter::Opcode0
{
int mIndex;
public:
OpModSkillExplicit (int index) : mIndex (index) {}
virtual void execute (Interpreter::Runtime& runtime)
{
MWScript::InterpreterContext& context
= static_cast<MWScript::InterpreterContext&> (runtime.getContext());
std::string id = runtime.getStringLiteral (runtime[0].mInteger);
runtime.pop();
Interpreter::Type_Integer value = runtime[0].mInteger;
runtime.pop();
MWWorld::Ptr ptr = context.getWorld().getPtr (id, false);
value +=
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
getModified();
MWWorld::Class::get (ptr).getNpcStats (ptr).mSkill[mIndex].
setModified (value, 0, 100);
}
};
const int numberOfAttributes = 8;
const int opcodeGetAttribute = 0x2000027;
@ -729,53 +386,54 @@ namespace MWScript
{
for (int i=0; i<numberOfAttributes; ++i)
{
interpreter.installSegment5 (opcodeGetAttribute+i, new OpGetAttribute (i));
interpreter.installSegment5 (opcodeGetAttribute+i, new OpGetAttribute<ImplicitRef> (i));
interpreter.installSegment5 (opcodeGetAttributeExplicit+i,
new OpGetAttributeExplicit (i));
new OpGetAttribute<ExplicitRef> (i));
interpreter.installSegment5 (opcodeSetAttribute+i, new OpSetAttribute (i));
interpreter.installSegment5 (opcodeSetAttribute+i, new OpSetAttribute<ImplicitRef> (i));
interpreter.installSegment5 (opcodeSetAttributeExplicit+i,
new OpSetAttributeExplicit (i));
new OpSetAttribute<ExplicitRef> (i));
interpreter.installSegment5 (opcodeModAttribute+i, new OpModAttribute (i));
interpreter.installSegment5 (opcodeModAttribute+i, new OpModAttribute<ImplicitRef> (i));
interpreter.installSegment5 (opcodeModAttributeExplicit+i,
new OpModAttributeExplicit (i));
new OpModAttribute<ExplicitRef> (i));
}
for (int i=0; i<numberOfDynamics; ++i)
{
interpreter.installSegment5 (opcodeGetDynamic+i, new OpGetDynamic (i));
interpreter.installSegment5 (opcodeGetDynamic+i, new OpGetDynamic<ImplicitRef> (i));
interpreter.installSegment5 (opcodeGetDynamicExplicit+i,
new OpGetDynamicExplicit (i));
new OpGetDynamic<ExplicitRef> (i));
interpreter.installSegment5 (opcodeSetDynamic+i, new OpSetDynamic (i));
interpreter.installSegment5 (opcodeSetDynamic+i, new OpSetDynamic<ImplicitRef> (i));
interpreter.installSegment5 (opcodeSetDynamicExplicit+i,
new OpSetDynamicExplicit (i));
new OpSetDynamic<ExplicitRef> (i));
interpreter.installSegment5 (opcodeModDynamic+i, new OpModDynamic (i));
interpreter.installSegment5 (opcodeModDynamic+i, new OpModDynamic<ImplicitRef> (i));
interpreter.installSegment5 (opcodeModDynamicExplicit+i,
new OpModDynamicExplicit (i));
new OpModDynamic<ExplicitRef> (i));
interpreter.installSegment5 (opcodeModCurrentDynamic+i, new OpModCurrentDynamic (i));
interpreter.installSegment5 (opcodeModCurrentDynamic+i,
new OpModCurrentDynamic<ImplicitRef> (i));
interpreter.installSegment5 (opcodeModCurrentDynamicExplicit+i,
new OpModCurrentDynamicExplicit (i));
new OpModCurrentDynamic<ExplicitRef> (i));
interpreter.installSegment5 (opcodeGetDynamicGetRatio+i,
new OpGetDynamicGetRatio (i));
new OpGetDynamicGetRatio<ImplicitRef> (i));
interpreter.installSegment5 (opcodeGetDynamicGetRatioExplicit+i,
new OpGetDynamicGetRatioExplicit (i));
new OpGetDynamicGetRatio<ExplicitRef> (i));
}
for (int i=0; i<numberOfSkills; ++i)
{
interpreter.installSegment5 (opcodeGetSkill+i, new OpGetSkill (i));
interpreter.installSegment5 (opcodeGetSkillExplicit+i, new OpGetSkillExplicit (i));
interpreter.installSegment5 (opcodeGetSkill+i, new OpGetSkill<ImplicitRef> (i));
interpreter.installSegment5 (opcodeGetSkillExplicit+i, new OpGetSkill<ExplicitRef> (i));
interpreter.installSegment5 (opcodeSetSkill+i, new OpSetSkill (i));
interpreter.installSegment5 (opcodeSetSkillExplicit+i, new OpSetSkillExplicit (i));
interpreter.installSegment5 (opcodeSetSkill+i, new OpSetSkill<ImplicitRef> (i));
interpreter.installSegment5 (opcodeSetSkillExplicit+i, new OpSetSkill<ExplicitRef> (i));
interpreter.installSegment5 (opcodeModSkill+i, new OpModSkill (i));
interpreter.installSegment5 (opcodeModSkillExplicit+i, new OpModSkillExplicit (i));
interpreter.installSegment5 (opcodeModSkill+i, new OpModSkill<ImplicitRef> (i));
interpreter.installSegment5 (opcodeModSkillExplicit+i, new OpModSkill<ExplicitRef> (i));
}
}
}

@ -62,7 +62,7 @@ namespace MWSound
sounds based on the sound factory it is given.
*/
OEManagerPtr mgr;
SoundPtr music;
SoundPtr music;
/* This class calls update() on the sound manager each frame
using and Ogre::FrameListener
@ -310,9 +310,9 @@ namespace MWSound
bool useSound)
: mData(NULL)
{
MP3Lookup(dataDir / "Music/Explore/");
MP3Lookup(dataDir / "Music/Explore/");
if(useSound)
mData = new SoundImpl(root, camera, store, (dataDir / "Sound").file_string());
mData = new SoundImpl(root, camera, store, (dataDir / "Sound").string());
}
SoundManager::~SoundManager()
@ -323,60 +323,64 @@ namespace MWSound
void SoundManager::MP3Lookup(boost::filesystem::path dir)
{
boost::filesystem::directory_iterator dir_iter(dir), dir_end;
std::string mp3extension = ".mp3";
for(;dir_iter != dir_end; dir_iter++)
{
if(boost::filesystem::extension(*dir_iter) == mp3extension)
{
files.push_back(*dir_iter);
}
}
boost::filesystem::directory_iterator dir_iter(dir), dir_end;
std::string mp3extension = ".mp3";
for(;dir_iter != dir_end; dir_iter++)
{
if(boost::filesystem::extension(*dir_iter) == mp3extension)
{
files.push_back(*dir_iter);
}
}
}
void SoundManager::startRandomTitle()
{
std::vector<boost::filesystem::path>::iterator fileIter;
if(files.size() > 0)
{
fileIter = files.begin();
srand ( time(NULL) );
int r = rand() % files.size() + 1; //old random code
for(int i = 1; i < r; i++)
{
fileIter++;
}
std::string music = fileIter->file_string();
try
{
std::cout << "Playing " << music << "\n";
streamMusic(music);
}
catch(std::exception &e)
{
std::cout << " Music Error: " << e.what() << "\n";
}
}
std::vector<boost::filesystem::path>::iterator fileIter;
if(files.size() > 0)
{
fileIter = files.begin();
srand ( time(NULL) );
int r = rand() % files.size() + 1; //old random code
for(int i = 1; i < r; i++)
{
fileIter++;
}
std::string music = fileIter->string();
try
{
std::cout << "Playing " << music << "\n";
streamMusic(music);
}
catch(std::exception &e)
{
std::cout << " Music Error: " << e.what() << "\n";
}
}
}
bool SoundManager::isMusicPlaying()
{
bool test = mData->music->isPlaying();
return test;
}
{
bool test = false;
if(mData && mData->music)
{
test = mData->music->isPlaying();
}
return test;
}
SoundManager::SoundImpl SoundManager::getMData()
{
// bool test = mData->music->isPlaying();
return *mData;
// bool test = mData->music->isPlaying();
return *mData;
}
void SoundManager::say (MWWorld::Ptr ptr, const std::string& filename)
{
// The range values are not tested
@ -400,8 +404,8 @@ namespace MWSound
// Play the sound and tell it to stream, if possible. TODO:
// Store the reference, the jukebox will need to check status,
// control volume etc.
if (mData->music)
mData->music->stop();
if (mData->music)
mData->music->stop();
mData->music = mData->mgr->load(filename);
mData->music->setStreaming(true);
mData->music->setVolume(0.4);

@ -21,28 +21,28 @@ namespace ESMS
namespace MWSound
{
//SoundPtr *music;
//SoundPtr *music;
class SoundManager
{
// Hide implementation details - engine.cpp is compiling
// enough as it is.
struct SoundImpl;
SoundImpl *mData;
std::vector<boost::filesystem::path> files;
std::vector<boost::filesystem::path> files;
public:
SoundManager(Ogre::Root*, Ogre::Camera*, const ESMS::ESMStore &store,
boost::filesystem::path dataDir, bool useSound);
~SoundManager();
void startRandomTitle();
void MP3Lookup(boost::filesystem::path dir);
//struct SoundImpl;
bool isMusicPlaying();
void startRandomTitle();
void MP3Lookup(boost::filesystem::path dir);
//struct SoundImpl;
bool isMusicPlaying();
SoundImpl getMData();
SoundImpl getMData();
void say (MWWorld::Ptr reference, const std::string& filename);
///< Make an actor say some text.

@ -16,6 +16,6 @@ namespace MWWorld
if (mCellName.empty())
environment.mWorld->changeToExteriorCell (mPosition);
else
environment.mWorld->changeCell (mCellName, mPosition);
environment.mWorld->changeToInteriorCell (mCellName, mPosition);
}
}

@ -0,0 +1,31 @@
#ifndef GAME_MWWORLD_CELLFUNCTORS_H
#define GAME_MWWORLD_CELLFUNCTORS_H
#include <vector>
#include <string>
#include "refdata.hpp"
namespace ESM
{
class CellRef;
}
namespace MWWorld
{
/// List all (Ogre-)handles.
struct ListHandles
{
std::vector<std::string> mHandles;
bool operator() (ESM::CellRef& ref, RefData& data)
{
std::string handle = data.getHandle();
if (!handle.empty())
mHandles.push_back (handle);
return true;
}
};
}
#endif

@ -3,6 +3,8 @@
#include <stdexcept>
#include <OgreVector3.h>
#include "ptr.hpp"
#include "nullaction.hpp"
@ -92,6 +94,36 @@ namespace MWWorld
return "";
}
void Class::setForceStance (const Ptr& ptr, Stance stance, bool force) const
{
throw std::runtime_error ("stance not supported by class");
}
void Class::setStance (const Ptr& ptr, Stance stance, bool set) const
{
throw std::runtime_error ("stance not supported by class");
}
bool Class::getStance (const Ptr& ptr, Stance stance, bool ignoreForce) const
{
return false;
}
float Class::getSpeed (const Ptr& ptr) const
{
return 0;
}
MWMechanics::Movement& Class::getMovementSettings (const Ptr& ptr) const
{
throw std::runtime_error ("movement settings not supported by class");
}
Ogre::Vector3 Class::getMovementVector (const Ptr& ptr) const
{
return Ogre::Vector3 (0, 0, 0);
}
const Class& Class::get (const std::string& key)
{
std::map<std::string, boost::shared_ptr<Class> >::const_iterator iter = sClasses.find (key);

@ -10,6 +10,11 @@
#include "containerstore.hpp"
#include "refdata.hpp"
namespace Ogre
{
class Vector3;
}
namespace MWRender
{
class CellRenderImp;
@ -19,6 +24,7 @@ namespace MWMechanics
{
struct CreatureStats;
struct NpcStats;
struct Movement;
}
namespace MWWorld
@ -41,6 +47,12 @@ namespace MWWorld
public:
/// NPC-stances.
enum Stance
{
Run, Sneak, Combat
};
virtual ~Class();
virtual std::string getId (const Ptr& ptr) const;
@ -108,6 +120,25 @@ namespace MWWorld
///< Return name of the script attached to ptr (default implementation: return an empty
/// string).
virtual void setForceStance (const Ptr& ptr, Stance stance, bool force) const;
///< Force or unforce a stance.
virtual void setStance (const Ptr& ptr, Stance stance, bool set) const;
///< Set or unset a stance.
virtual bool getStance (const Ptr& ptr, Stance stance, bool ignoreForce = false) const;
////< Check if a stance is active or not.
virtual float getSpeed (const Ptr& ptr) const;
///< Return movement speed.
virtual MWMechanics::Movement& getMovementSettings (const Ptr& ptr) const;
///< Return desired movement.
virtual Ogre::Vector3 getMovementVector (const Ptr& ptr) const;
///< Return desired movement vector (determined based on movement settings,
/// stance and stats).
static const Class& get (const std::string& key);
///< If there is no class for this \a key, an exception is thrown.

@ -0,0 +1,33 @@
#include "doingphysics.hpp"
namespace MWWorld
{
int DoingPhysics::sCounter = 0;
int DoingPhysics::sSuppress = 0;
DoingPhysics::DoingPhysics()
{
++sCounter;
}
DoingPhysics::~DoingPhysics()
{
--sCounter;
}
bool DoingPhysics::isDoingPhysics()
{
return sCounter>0 && sSuppress==0;
}
SuppressDoingPhysics::SuppressDoingPhysics()
{
++DoingPhysics::sSuppress;
}
SuppressDoingPhysics::~SuppressDoingPhysics()
{
--DoingPhysics::sSuppress;
}
}

@ -0,0 +1,46 @@
#ifndef GAME_MWWORLD_DOINGPHYSICS_H
#define GAME_MWWORLD_DOINGPHYSICS_H
namespace MWWorld
{
class SuppressDoingPhysics;
/// Scope guard for blocking physics updates during physics simulation.
class DoingPhysics
{
static int sCounter;
static int sSuppress;
private:
DoingPhysics (const DoingPhysics&);
DoingPhysics& operator= (const DoingPhysics&);
public:
DoingPhysics();
~DoingPhysics();
static bool isDoingPhysics();
friend class SuppressDoingPhysics;
};
/// Scope guard for temporarily lifting the block issues by DoingPhysics
class SuppressDoingPhysics
{
private:
SuppressDoingPhysics (const SuppressDoingPhysics&);
SuppressDoingPhysics& operator= (const SuppressDoingPhysics&);
public:
SuppressDoingPhysics();
~SuppressDoingPhysics();
};
}
#endif

@ -0,0 +1,88 @@
#include "player.hpp"
#include "../mwrender/player.hpp"
#include "world.hpp"
#include "class.hpp"
namespace MWWorld
{
Player::Player (MWRender::Player *renderer, const ESM::NPC *player, MWWorld::World& world) :
mCellStore (0), mRenderer (renderer), mWorld (world), mClass (0),
mAutoMove (false), mForwardBackward (0)
{
mPlayer.base = player;
mName = player->name;
mMale = !(player->flags & ESM::NPC::Female);
mRace = player->race;
mPlayer.ref.pos.pos[0] = mPlayer.ref.pos.pos[1] = mPlayer.ref.pos.pos[2] = 0;
mPlayer.mData.setHandle (renderer->getHandle());
mClass = new ESM::Class (*world.getStore().classes.find (player->cls));
}
Player::~Player()
{
delete mClass;
}
void Player::setPos(float x, float y, float z, bool updateCamera)
{
mWorld.moveObject (getPlayer(), x, y, z);
if (updateCamera)
mRenderer->getCamera()->setPosition (Ogre::Vector3 (
mPlayer.ref.pos.pos[0],
mPlayer.ref.pos.pos[2],
-mPlayer.ref.pos.pos[1]));
}
void Player::setClass (const ESM::Class& class_)
{
ESM::Class *new_class = new ESM::Class (class_);
delete mClass;
mClass = new_class;
}
void Player::setAutoMove (bool enable)
{
MWWorld::Ptr ptr = getPlayer();
mAutoMove = enable;
int value = mForwardBackward;
if (mAutoMove)
value = 1;
MWWorld::Class::get (ptr).getMovementSettings (ptr).mForwardBackward = value;
}
void Player::setLeftRight (int value)
{
MWWorld::Ptr ptr = getPlayer();
MWWorld::Class::get (ptr).getMovementSettings (ptr).mLeftRight = value;
}
void Player::setForwardBackward (int value)
{
MWWorld::Ptr ptr = getPlayer();
mForwardBackward = value;
if (mAutoMove)
value = 1;
MWWorld::Class::get (ptr).getMovementSettings (ptr).mForwardBackward = value;
}
void Player::toggleRunning()
{
MWWorld::Ptr ptr = getPlayer();
bool running = MWWorld::Class::get (ptr).getStance (ptr, MWWorld::Class::Run, true);
MWWorld::Class::get (ptr).setStance (ptr, MWWorld::Class::Run, !running);
}
}

@ -0,0 +1,118 @@
#ifndef GAME_MWWORLD_PLAYER_H
#define GAME_MWWORLD_PLAYER_H
#include "OgreCamera.h"
#include <components/esm_store/cell_store.hpp>
#include "../mwworld/refdata.hpp"
#include "../mwworld/ptr.hpp"
namespace MWRender
{
class Player;
}
namespace MWWorld
{
class World;
/// \brief NPC object representing the player and additional player data
class Player
{
ESMS::LiveCellRef<ESM::NPC, MWWorld::RefData> mPlayer;
MWWorld::Ptr::CellStore *mCellStore;
MWRender::Player *mRenderer;
MWWorld::World& mWorld;
std::string mName;
bool mMale;
std::string mRace;
std::string mBirthsign;
ESM::Class *mClass;
bool mAutoMove;
int mForwardBackward;
public:
Player(MWRender::Player *renderer, const ESM::NPC *player, MWWorld::World& world);
~Player();
/// Set the player position. Uses Morrowind coordinates.
void setPos(float _x, float _y, float _z, bool updateCamera = false);
void setCell (MWWorld::Ptr::CellStore *cellStore)
{
mCellStore = cellStore;
}
MWWorld::Ptr getPlayer()
{
MWWorld::Ptr ptr (&mPlayer, mCellStore);
return ptr;
}
MWRender::Player *getRenderer() { return mRenderer; }
void setName (const std::string& name)
{
mName = name;
}
void setGender (bool male)
{
mMale = male;
}
void setRace (const std::string& race)
{
mRace = race;
}
void setBirthsign (const std::string& birthsign)
{
mBirthsign = birthsign;
}
void setClass (const ESM::Class& class_);
std::string getName() const
{
return mName;
}
bool isMale() const
{
return mMale;
}
std::string getRace() const
{
return mRace;
}
std::string getBirthsign() const
{
return mBirthsign;
}
const ESM::Class& getClass() const
{
return *mClass;
}
bool getAutoMove()
{
return mAutoMove;
}
void setAutoMove (bool enable);
void setLeftRight (int value);
void setForwardBackward (int value);
void toggleRunning();
};
}
#endif

@ -9,6 +9,7 @@
#include "../mwmechanics/creaturestats.hpp"
#include "../mwmechanics/npcstats.hpp"
#include "../mwmechanics/movement.hpp"
#include "containerstore.hpp"
@ -36,6 +37,7 @@ namespace MWWorld
// are never copied outside of container operations.
boost::shared_ptr<MWMechanics::CreatureStats> mCreatureStats;
boost::shared_ptr<MWMechanics::NpcStats> mNpcStats;
boost::shared_ptr<MWMechanics::Movement> mMovement;
boost::shared_ptr<ContainerStore<RefData> > mContainerStore;
@ -102,6 +104,11 @@ namespace MWWorld
return mNpcStats;
}
boost::shared_ptr<MWMechanics::Movement>& getMovement()
{
return mMovement;
}
boost::shared_ptr<ContainerStore<RefData> >& getContainerStore()
{
return mContainerStore;

@ -17,10 +17,12 @@
#include "ptr.hpp"
#include "environment.hpp"
#include "class.hpp"
#include "player.hpp"
#include "refdata.hpp"
#include "globals.hpp"
#include "doingphysics.hpp"
#include "cellfunctors.hpp"
namespace
{
@ -270,6 +272,15 @@ namespace MWWorld
void World::unloadCell (CellRenderCollection::iterator iter)
{
ListHandles functor;
iter->first->forEach<ListHandles>(functor);
{ // silence annoying g++ warning
for (std::vector<std::string>::const_iterator iter (functor.mHandles.begin());
iter!=functor.mHandles.end(); ++iter)
mScene.removeObject (*iter);
}
removeScripts (iter->first);
mEnvironment.mMechanicsManager->dropActors (iter->first);
iter->second->destroy();
@ -294,14 +305,16 @@ namespace MWWorld
}
}
void World::playerCellChange (Ptr::CellStore *cell, const ESM::Position& position)
void World::playerCellChange (Ptr::CellStore *cell, const ESM::Position& position,
bool adjustPlayerPos)
{
mPlayerPos->setPos (position.pos[0], position.pos[1], position.pos[2], true);
mPlayerPos->setCell (cell);
// TODO orientation
if (adjustPlayerPos)
mPlayer->setPos (position.pos[0], position.pos[1], position.pos[2], false);
mEnvironment.mMechanicsManager->addActor (mPlayerPos->getPlayer());
mEnvironment.mMechanicsManager->watchActor (mPlayerPos->getPlayer());
mPlayer->setCell (cell);
// TODO orientation
mEnvironment.mMechanicsManager->addActor (mPlayer->getPlayer());
mEnvironment.mMechanicsManager->watchActor (mPlayer->getPlayer());
}
@ -315,21 +328,102 @@ namespace MWWorld
}
}
World::World (OEngine::Render::OgreRenderer& renderer, const boost::filesystem::path& dataDir,
const std::string& master, bool newGame, Environment& environment)
: mSkyManager (0), mScene (renderer), mPlayerPos (0), mCurrentCell (0), mGlobalVariables (0),
void World::changeCell (int X, int Y, const ESM::Position& position, bool adjustPlayerPos)
{
SuppressDoingPhysics scopeGuard;
// remove active
mEnvironment.mMechanicsManager->removeActor (mPlayer->getPlayer());
CellRenderCollection::iterator active = mActiveCells.begin();
while (active!=mActiveCells.end())
{
if (!(active->first->cell->data.flags & ESM::Cell::Interior))
{
if (std::abs (X-active->first->cell->data.gridX)<=1 &&
std::abs (Y-active->first->cell->data.gridY)<=1)
{
// keep cells within the new 3x3 grid
++active;
continue;
}
}
unloadCell (active++);
}
// Load cells
for (int x=X-1; x<=X+1; ++x)
for (int y=Y-1; y<=Y+1; ++y)
{
CellRenderCollection::iterator iter = mActiveCells.begin();
while (iter!=mActiveCells.end())
{
assert (!(iter->first->cell->data.flags & ESM::Cell::Interior));
if (x==iter->first->cell->data.gridX &&
y==iter->first->cell->data.gridY)
break;
++iter;
}
if (iter==mActiveCells.end())
{
mExteriors[std::make_pair (x, y)].loadExt (x, y, mStore, mEsm);
Ptr::CellStore *cell = &mExteriors[std::make_pair (x, y)];
loadCell (cell, new MWRender::ExteriorCellRender (*cell, mEnvironment, mScene));
}
}
// find current cell
CellRenderCollection::iterator iter = mActiveCells.begin();
while (iter!=mActiveCells.end())
{
assert (!(iter->first->cell->data.flags & ESM::Cell::Interior));
if (X==iter->first->cell->data.gridX &&
Y==iter->first->cell->data.gridY)
break;
++iter;
}
assert (iter!=mActiveCells.end());
mCurrentCell = iter->first;
// adjust player
playerCellChange (&mExteriors[std::make_pair (X, Y)], position, adjustPlayerPos);
// Sky system
adjustSky();
mCellChanged = true;
}
World::World (OEngine::Render::OgreRenderer& renderer, OEngine::Physic::PhysicEngine* physEng, const boost::filesystem::path& dataDir,
const std::string& master, const boost::filesystem::path& resDir,
bool newGame, Environment& environment)
: mSkyManager (0), mScene (renderer,physEng), mPlayer (0), mCurrentCell (0), mGlobalVariables (0),
mSky (false), mCellChanged (false), mEnvironment (environment)
{
mPhysEngine = physEng;
boost::filesystem::path masterPath (dataDir);
masterPath /= master;
std::cout << "Loading ESM " << masterPath.string() << "\n";
// This parses the ESM file and loads a sample cell
mEsm.open (masterPath.file_string());
mEsm.open (masterPath.string());
mStore.load (mEsm);
mPlayerPos = new MWRender::PlayerPos (mScene.getCamera(), mStore.npcs.find ("player"), *this);
mPlayer = new MWWorld::Player (mScene.getPlayer(), mStore.npcs.find ("player"), *this);
mScene.addActor (mPlayer->getPlayer().getRefData().getHandle(), "", Ogre::Vector3 (0, 0, 0));
// global variables
mGlobalVariables = new Globals (mStore);
@ -341,7 +435,9 @@ namespace MWWorld
}
mSkyManager =
MWRender::SkyManager::create(renderer.getWindow(), mScene.getCamera());
MWRender::SkyManager::create(renderer.getWindow(), mScene.getCamera(), resDir);
mPhysEngine = physEng;
}
World::~World()
@ -354,14 +450,14 @@ namespace MWWorld
iter!=mBufferedCells.end(); ++iter)
delete iter->second;
delete mPlayerPos;
delete mPlayer;
delete mSkyManager;
delete mGlobalVariables;
}
MWRender::PlayerPos& World::getPlayerPos()
MWWorld::Player& World::getPlayer()
{
return *mPlayerPos;
return *mPlayer;
}
ESMS::ESMStore& World::getStore()
@ -394,7 +490,7 @@ namespace MWWorld
// the player is always in an active cell.
if (name=="player")
{
return mPlayerPos->getPlayer();
return mPlayer->getPlayer();
}
// active cells
@ -417,7 +513,8 @@ namespace MWWorld
Ptr World::getPtrViaHandle (const std::string& handle)
{
// TODO player
if (mPlayer->getPlayer().getRefData().getHandle()==handle)
return mPlayer->getPlayer();
for (CellRenderCollection::iterator iter (mActiveCells.begin());
iter!=mActiveCells.end(); ++iter)
@ -586,8 +683,10 @@ namespace MWWorld
return mGlobalVariables->getInt ("timescale");
}
void World::changeCell (const std::string& cellName, const ESM::Position& position)
void World::changeToInteriorCell (const std::string& cellName, const ESM::Position& position)
{
SuppressDoingPhysics scopeGuard;
// remove active
CellRenderCollection::iterator active = mActiveCells.begin();
@ -610,92 +709,17 @@ namespace MWWorld
adjustSky();
mCellChanged = true;
//currentRegion->name = "";
//currentRegion->name = "";
}
void World::changeCell (int X, int Y, const ESM::Position& position)
{
// remove active
CellRenderCollection::iterator active = mActiveCells.begin();
while (active!=mActiveCells.end())
{
if (!(active->first->cell->data.flags & ESM::Cell::Interior))
{
if (std::abs (X-active->first->cell->data.gridX)<=1 &&
std::abs (Y-active->first->cell->data.gridY)<=1)
{
// keep cells within the new 3x3 grid
++active;
continue;
}
}
unloadCell (active++);
}
// Load cells
for (int x=X-1; x<=X+1; ++x)
for (int y=Y-1; y<=Y+1; ++y)
{
CellRenderCollection::iterator iter = mActiveCells.begin();
while (iter!=mActiveCells.end())
{
assert (!(iter->first->cell->data.flags & ESM::Cell::Interior));
if (x==iter->first->cell->data.gridX &&
y==iter->first->cell->data.gridY)
break;
++iter;
}
if (iter==mActiveCells.end())
{
mExteriors[std::make_pair (x, y)].loadExt (x, y, mStore, mEsm);
Ptr::CellStore *cell = &mExteriors[std::make_pair (x, y)];
loadCell (cell, new MWRender::ExteriorCellRender (*cell, mEnvironment, mScene));
}
}
// find current cell
CellRenderCollection::iterator iter = mActiveCells.begin();
while (iter!=mActiveCells.end())
{
assert (!(iter->first->cell->data.flags & ESM::Cell::Interior));
if (X==iter->first->cell->data.gridX &&
Y==iter->first->cell->data.gridY)
break;
++iter;
}
assert (iter!=mActiveCells.end());
mCurrentCell = iter->first;
// adjust player
playerCellChange (&mExteriors[std::make_pair (X, Y)], position);
// Sky system
adjustSky();
mCellChanged = true;
}
void World::changeToExteriorCell (const ESM::Position& position)
void World::changeToExteriorCell (const ESM::Position& position)
{
int x = 0;
int y = 0;
positionToIndex (position.pos[0], position.pos[1], x, y);
changeCell (x, y, position);
changeCell (x, y, position, true);
}
const ESM::Cell *World::getExterior (const std::string& cellName) const
@ -721,6 +745,7 @@ namespace MWWorld
return 0;
}
void World::markCellAsUnchanged()
{
mCellChanged = false;
@ -745,14 +770,17 @@ namespace MWWorld
if (MWRender::CellRender *render = searchRender (ptr.getCell()))
{
render->deleteObject (ptr.getRefData().getHandle());
ptr.getRefData().setHandle ("");
if (mActiveCells.find (ptr.getCell())!=mActiveCells.end())
{
Class::get (ptr).disable (ptr, mEnvironment);
mEnvironment.mSoundManager->stopSound3D (ptr);
if (!DoingPhysics::isDoingPhysics())
mScene.removeObject (ptr.getRefData().getHandle());
}
render->deleteObject (ptr.getRefData().getHandle());
ptr.getRefData().setHandle ("");
}
}
}
@ -763,7 +791,7 @@ namespace MWWorld
ptr.getCellRef().pos.pos[1] = y;
ptr.getCellRef().pos.pos[2] = z;
if (ptr==mPlayerPos->getPlayer())
if (ptr==mPlayer->getPlayer())
{
if (mCurrentCell)
{
@ -777,12 +805,16 @@ namespace MWWorld
if (mCurrentCell->cell->data.gridX!=cellX || mCurrentCell->cell->data.gridY!=cellY)
{
changeCell (cellX, cellY, mPlayerPos->getPlayer().getCellRef().pos);
changeCell (cellX, cellY, mPlayer->getPlayer().getCellRef().pos, false);
}
}
}
}
mScene.moveObject (ptr.getRefData().getHandle(), Ogre::Vector3 (x, y, z),
!DoingPhysics::isDoingPhysics());
// TODO cell change for non-player ref
}
@ -800,8 +832,6 @@ namespace MWWorld
}
}
void World::positionToIndex (float x, float y, int &cellX, int &cellY) const
{
const int cellSize = 8192;
@ -816,4 +846,20 @@ namespace MWWorld
if (y<0)
--cellY;
}
void World::doPhysics (const std::vector<std::pair<std::string, Ogre::Vector3> >& actors,
float duration)
{
mScene.doPhysics (duration, *this, actors);
}
void World::toggleCollisionMode()
{
mScene.toggleCollisionMode();
}
void World::toggleRenderMode (RenderMode mode)
{
mScene.toggleRenderMode (mode);
}
}

@ -8,13 +8,19 @@
#include <components/esm_store/cell_store.hpp>
#include "../mwrender/playerpos.hpp"
#include "../mwrender/mwscene.hpp"
#include "refdata.hpp"
#include "ptr.hpp"
#include "globals.hpp"
#include <openengine/bullet/physic.hpp>
namespace Ogre
{
class Vector3;
}
namespace ESM
{
struct Position;
@ -34,23 +40,29 @@ namespace MWRender
namespace MWWorld
{
class Environment;
class Player;
/// \brief The game world and its visual representation
class World
{
public:
typedef std::list<std::pair<std::string, Ptr> > ScriptList;
enum RenderMode
{
Render_CollisionDebug
};
private:
typedef std::map<Ptr::CellStore *, MWRender::CellRender *> CellRenderCollection;
MWRender::SkyManager* mSkyManager;
MWRender::MWScene mScene;
MWRender::PlayerPos *mPlayerPos;
Ptr::CellStore *mCurrentCell; // the cell, the player is in
MWWorld::Player *mPlayer;
Ptr::CellStore *mCurrentCell; // the cell, the player is in
CellRenderCollection mActiveCells;
CellRenderCollection mBufferedCells; // loaded, but not active (buffering not implementd yet)
ESM::ESMReader mEsm;
@ -63,6 +75,8 @@ namespace MWWorld
bool mCellChanged;
Environment& mEnvironment;
OEngine::Physic::PhysicEngine* mPhysEngine;
// not implemented
World (const World&);
World& operator= (const World&);
@ -83,20 +97,25 @@ namespace MWWorld
void loadCell (Ptr::CellStore *cell, MWRender::CellRender *render);
void playerCellChange (Ptr::CellStore *cell, const ESM::Position& position);
void playerCellChange (Ptr::CellStore *cell, const ESM::Position& position,
bool adjustPlayerPos = true);
void adjustSky();
void changeCell (int X, int Y, const ESM::Position& position, bool adjustPlayerPos);
///< Move from exterior to interior or from interior cell to a different
/// interior cell.
public:
World (OEngine::Render::OgreRenderer& renderer, const boost::filesystem::path& master,
const std::string& dataDir, bool newGame, Environment& environment);
World (OEngine::Render::OgreRenderer& renderer, OEngine::Physic::PhysicEngine* physEng, const boost::filesystem::path& dataDir,
const std::string& master, const boost::filesystem::path& resDir, bool newGame,
Environment& environment);
~World();
MWRender::PlayerPos& getPlayerPos();
MWWorld::Player& getPlayer();
ESMS::ESMStore& getStore();
ESMS::ESMStore& getStore();
const ScriptList& getLocalScripts() const;
///< Names and local variable state of all local scripts in active cells.
@ -138,12 +157,11 @@ namespace MWWorld
float getTimeScaleFactor() const;
void changeCell (const std::string& cellName, const ESM::Position& position);
///< works only for interior cells currently.
void changeCell (int X, int Y, const ESM::Position& position);
void changeToInteriorCell (const std::string& cellName, const ESM::Position& position);
///< Move to interior cell.
void changeToExteriorCell (const ESM::Position& position);
///< Move to exterior cell.
const ESM::Cell *getExterior (const std::string& cellName) const;
///< Return a cell matching the given name or a 0-pointer, if there is no such cell.
@ -162,6 +180,17 @@ namespace MWWorld
void positionToIndex (float x, float y, int &cellX, int &cellY) const;
///< Convert position to cell numbers
void doPhysics (const std::vector<std::pair<std::string, Ogre::Vector3> >& actors,
float duration);
///< Run physics simulation and modify \a world accordingly.
void toggleCollisionMode();
///< Toggle collision mode for player. If disabled player object should ignore
/// collisions and gravity.
void toggleRenderMode (RenderMode mode);
///< Toggle a render mode.
};
}

@ -0,0 +1,56 @@
#include "path.hpp"
#include <boost/filesystem.hpp>
#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX
#include <stdlib.h> //getenv
#endif
std::string OMW::Path::getPath(PathTypeEnum parType, const std::string parApp, const std::string parFile)
{
std::string theBasePath;
if(parType == GLOBAL_CFG_PATH)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
theBasePath = Ogre::macBundlePath() + "/Contents/MacOS/"; //FIXME do we have global/local with OSX?
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
theBasePath = "/etc/"+parApp+"/";
#else
theBasePath = "";
#endif
}
else
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
theBasePath = Ogre::macBundlePath() + "/Contents/MacOS/"; //FIXME do we have global/local with OSX?
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
const char* theDir;
if ((theDir = getenv("OPENMW_HOME")) != NULL)
{
theBasePath = std::string(theDir)+"/";
}
else
{
if ((theDir = getenv("XDG_CONFIG_HOME")))
{
theBasePath = std::string(theDir)+"/"+parApp+"/";
}
else
{
if ((theDir = getenv("HOME")) == NULL)
return parFile;
theBasePath = std::string(theDir)+"/.config/"+parApp+"/";
}
}
boost::filesystem::create_directories(boost::filesystem::path(theBasePath));
#else
theBasePath = "";
#endif
}
theBasePath.append(parFile);
return theBasePath;
}

@ -0,0 +1,25 @@
#ifndef PATH__HPP
#define PATH__HPP
#include <OgrePlatform.h>
#include <string>
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include <OSX/macUtils.h>
#endif
namespace OMW
{
class Path
{
public:
enum PathTypeEnum
{
USER_CFG_PATH,
GLOBAL_CFG_PATH
};
static std::string getPath(PathTypeEnum parType, const std::string parApp, const std::string parFile);
};
}
#endif

@ -0,0 +1,76 @@
# - Try to find the Bullet physics engine
#
# This module defines the following variables
#
# BULLET_FOUND - Was bullet found
# BULLET_INCLUDE_DIRS - the Bullet include directories
# BULLET_LIBRARIES - Link to this, by default it includes
# all bullet components (Dynamics,
# Collision, LinearMath, & SoftBody)
#
# This module accepts the following variables
#
# BULLET_ROOT - Can be set to bullet install path or Windows build path
#
# Copyright (c) 2009, Philip Lowman <philip at yhbt.com>
#
# Redistribution AND use is allowed according to the terms of the New
# BSD license.
# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
macro(_FIND_BULLET_LIBRARY _var)
find_library(${_var}
NAMES
${ARGN}
PATHS
${BULLET_ROOT}
${BULLET_ROOT}/out/release8/libs
${BULLET_ROOT}/out/debug8/libs
PATH_SUFFIXES lib
)
mark_as_advanced(${_var})
endmacro()
macro(_BULLET_APPEND_LIBRARIES _list _release)
set(_debug ${_release}_DEBUG)
if(${_debug})
set(${_list} ${${_list}} optimized ${${_release}} debug ${${_debug}})
else()
set(${_list} ${${_list}} ${${_release}})
endif()
endmacro()
find_path(BULLET_INCLUDE_DIR NAMES btBulletCollisionCommon.h
PATHS
${BULLET_ROOT}/include
${BULLET_ROOT}/src
PATH_SUFFIXES bullet
)
# Find the libraries
_FIND_BULLET_LIBRARY(BULLET_DYNAMICS_LIBRARY BulletDynamics)
_FIND_BULLET_LIBRARY(BULLET_DYNAMICS_LIBRARY_DEBUG BulletDynamics_d)
_FIND_BULLET_LIBRARY(BULLET_COLLISION_LIBRARY BulletCollision)
_FIND_BULLET_LIBRARY(BULLET_COLLISION_LIBRARY_DEBUG BulletCollision_d)
_FIND_BULLET_LIBRARY(BULLET_MATH_LIBRARY LinearMath BulletMath)
_FIND_BULLET_LIBRARY(BULLET_MATH_LIBRARY_DEBUG LinearMath_d BulletMath_d)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY BulletSoftBody)
_FIND_BULLET_LIBRARY(BULLET_SOFTBODY_LIBRARY_DEBUG BulletSoftBody_d)
# handle the QUIETLY and REQUIRED arguments and set BULLET_FOUND to TRUE if
# all listed variables are TRUE
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(Bullet DEFAULT_MSG
BULLET_DYNAMICS_LIBRARY BULLET_COLLISION_LIBRARY BULLET_MATH_LIBRARY
BULLET_SOFTBODY_LIBRARY BULLET_INCLUDE_DIR)
set(BULLET_INCLUDE_DIRS ${BULLET_INCLUDE_DIR})
if(BULLET_FOUND)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_DYNAMICS_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_COLLISION_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_MATH_LIBRARY)
_BULLET_APPEND_LIBRARIES(BULLET_LIBRARIES BULLET_SOFTBODY_LIBRARY)
endif()

@ -38,10 +38,13 @@ ENDIF (WIN32)
IF (UNIX AND NOT APPLE)
CMAKE_MINIMUM_REQUIRED(VERSION 2.4.7 FATAL_ERROR)
FIND_PACKAGE(PkgConfig REQUIRED)
PKG_SEARCH_MODULE(OGRE REQUIRED OGRE)
# Don't mark REQUIRED, but use PKG_CHECK_MODULES below (otherwise PkgConfig
# complains even if OGRE_* are set by hand).
PKG_SEARCH_MODULE(OGRE OGRE)
SET(OGRE_INCLUDE_DIR ${OGRE_INCLUDE_DIRS})
SET(OGRE_LIB_DIR ${OGRE_LIBDIR})
SET(OGRE_LIBRARIES ${OGRE_LIBRARIES} CACHE STRING "")
PKG_CHECK_MODULES(OGRE OGRE)
ENDIF (UNIX AND NOT APPLE)
IF (APPLE)
@ -66,6 +69,14 @@ SET(OGRE_INCLUDE_DIR ${OGRE_INCLUDE_DIR} CACHE PATH "")
SET(OGRE_LIBRARIES ${OGRE_LIBRARIES} CACHE STRING "")
SET(OGRE_LIB_DIR ${OGRE_LIB_DIR} CACHE PATH "")
if(OGRE_LIB_DIR)
CMAKE_POLICY(SET CMP0009 NEW)
FILE(GLOB_RECURSE OGRE_PLUGINS "${OGRE_LIB_DIR}/Plugin_*.so")
FOREACH (OGRE_PLUGINS_FILE ${OGRE_PLUGINS})
STRING(REGEX REPLACE "/[^/]*$" "" OGRE_PLUGIN_DIR ${OGRE_PLUGINS_FILE})
ENDFOREACH(OGRE_PLUGINS_FILE)
endif()
IF (OGRE_INCLUDE_DIR AND OGRE_LIBRARIES)
SET(OGRE_FOUND TRUE)
ENDIF (OGRE_INCLUDE_DIR AND OGRE_LIBRARIES)

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save