diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e16aefcc1..b89b99ac8 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -57,9 +57,10 @@ variables: &cs-targets - windows before_script: - Import-Module "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1" + - choco source add -n=openmw-proxy -s="https://repo.openmw.org/repository/Chocolately/" --priority=1 - choco install git --force --params "/GitAndUnixToolsOnPath" -y - choco install 7zip -y - - choco install cmake.install --installargs 'ADD_CMAKE_TO_PATH=System' -y + - choco install cmake.install --installargs 'ADD_CMAKE_TO_PATH=System' --version=3.18.0 -y - choco install vswhere -y - choco install ninja -y - choco install python -y @@ -146,6 +147,7 @@ Windows_Ninja_CS_RelWithDebInfo: - windows before_script: - Import-Module "$env:ChocolateyInstall\helpers\chocolateyProfile.psm1" + - choco source add -n=openmw-proxy -s="https://repo.openmw.org/repository/Chocolately/" --priority=1 - choco install git --force --params "/GitAndUnixToolsOnPath" -y - choco install 7zip -y - choco install cmake.install --installargs 'ADD_CMAKE_TO_PATH=System' -y diff --git a/CHANGELOG.md b/CHANGELOG.md index 6974fd46c..c68e7b0f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ Bug #5502: Dead zone for analogue stick movement is too small Bug #5507: Sound volume is not clamped on ingame settings update Bug #5531: Actors flee using current rotation by axis x + Bug #5539: Window resize breaks when going from a lower resolution to full screen resolution Bug #5548: Certain exhausted topics can be highlighted again even though there's no new dialogue Feature #390: 3rd person look "over the shoulder" Feature #2386: Distant Statics in the form of Object Paging diff --git a/CI/activate_msvc.sh b/CI/activate_msvc.sh index 1641f6b3e..47f2c246f 100644 --- a/CI/activate_msvc.sh +++ b/CI/activate_msvc.sh @@ -1,6 +1,16 @@ #!/bin/bash -set -euo pipefail +oldSettings=$- +set -eu + +function restoreOldSettings { + if [[ $oldSettings != *e* ]]; then + set +e + fi + if [[ $oldSettings != *u* ]]; then + set +u + fi +} if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then echo "Error: Script not sourced." @@ -8,6 +18,7 @@ if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then echo "source ./activate_msvc.sh" echo "or" echo ". ./activate_msvc.sh" + restoreOldSettings exit 1 fi @@ -78,7 +89,10 @@ command -v mt >/dev/null 2>&1 || { echo "Error: mt (MS Windows Manifest Tool) mi if [ $MISSINGTOOLS -ne 0 ]; then echo "Some build tools were unavailable after activating MSVC in the shell. It's likely that your Visual Studio $MSVC_DISPLAY_YEAR installation needs repairing." + restoreOldSettings return 1 fi -IFS="$originalIFS" \ No newline at end of file +IFS="$originalIFS" + +restoreOldSettings \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 28b7a3691..a185d7fb3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,3 +1,6 @@ +project(OpenMW) +cmake_minimum_required(VERSION 3.1.0) + # Apps and tools option(BUILD_OPENMW "Build OpenMW" ON) option(BUILD_LAUNCHER "Build Launcher" ON) @@ -16,17 +19,14 @@ option(BUILD_OPENMW_MP "Build OpenMW-MP" ON) option(BUILD_BROWSER "Build tes3mp Server Browser" ON) option(BUILD_MASTER "Build tes3mp Master Server" OFF) +set(OpenGL_GL_PREFERENCE LEGACY) # Use LEGACY as we use GL2; GLNVD is for GL3 and up. + if (NOT BUILD_LAUNCHER AND NOT BUILD_BROWSER AND NOT BUILD_OPENCS AND NOT BUILD_WIZARD) set(USE_QT FALSE) else() set(USE_QT TRUE) endif() -# set the minimum required version across the board -cmake_minimum_required(VERSION 3.1.0) - -project(OpenMW) - # If the user doesn't supply a CMAKE_BUILD_TYPE via command line, choose one for them. IF(NOT CMAKE_BUILD_TYPE) SET(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING @@ -61,7 +61,7 @@ set(OPENMW_VERSION_COMMITDATE "") set(OPENMW_VERSION "${OPENMW_VERSION_MAJOR}.${OPENMW_VERSION_MINOR}.${OPENMW_VERSION_RELEASE}") -set(OPENMW_DOC_BASEURL "https://openmw.readthedocs.io/en/master/") +set(OPENMW_DOC_BASEURL "https://openmw.readthedocs.io/en/stable/") set(GIT_CHECKOUT FALSE) if(EXISTS ${PROJECT_SOURCE_DIR}/.git) diff --git a/apps/launcher/advancedpage.cpp b/apps/launcher/advancedpage.cpp index 2dd7d07c1..bc14a9269 100644 --- a/apps/launcher/advancedpage.cpp +++ b/apps/launcher/advancedpage.cpp @@ -10,37 +10,6 @@ #include - -class HorizontalTextWestTabStyle : public QProxyStyle -{ -public: - QSize sizeFromContents(ContentsType type, const QStyleOption* option, const QSize& size, const QWidget* widget) const - { - QSize s = QProxyStyle::sizeFromContents(type, option, size, widget); - if (type == QStyle::CT_TabBarTab) - { - s.transpose(); - s.setHeight(s.height() + 20); - } - return s; - } - - void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const - { - if (element == CE_TabBarTabLabel) - { - if (const QStyleOptionTab* tab = qstyleoption_cast(option)) - { - QStyleOptionTab opt(*tab); - opt.shape = QTabBar::RoundedNorth; - QProxyStyle::drawControl(element, &opt, painter, widget); - return; - } - } - QProxyStyle::drawControl(element, option, painter, widget); - } -}; - Launcher::AdvancedPage::AdvancedPage(Files::ConfigurationManager &cfg, Config::GameSettings &gameSettings, Settings::Manager &engineSettings, QWidget *parent) @@ -53,7 +22,6 @@ Launcher::AdvancedPage::AdvancedPage(Files::ConfigurationManager &cfg, setupUi(this); loadSettings(); - AdvancedTabWidget->tabBar()->setStyle(new HorizontalTextWestTabStyle); mCellNameCompleter.setModel(&mCellNameCompleterModel); startDefaultCharacterAtField->setCompleter(&mCellNameCompleter); } @@ -119,15 +87,22 @@ bool Launcher::AdvancedPage::loadSettings() loadSettingBool(requireAppropriateAmmunitionCheckBox, "only appropriate ammunition bypasses resistance", "Game"); loadSettingBool(uncappedDamageFatigueCheckBox, "uncapped damage fatigue", "Game"); loadSettingBool(normaliseRaceSpeedCheckBox, "normalise race speed", "Game"); + loadSettingBool(swimUpwardCorrectionCheckBox, "swim upward correction", "Game"); int unarmedFactorsStrengthIndex = mEngineSettings.getInt("strength influences hand to hand", "Game"); if (unarmedFactorsStrengthIndex >= 0 && unarmedFactorsStrengthIndex <= 2) unarmedFactorsStrengthComboBox->setCurrentIndex(unarmedFactorsStrengthIndex); loadSettingBool(stealingFromKnockedOutCheckBox, "always allow stealing from knocked out actors", "Game"); + loadSettingBool(enableNavigatorCheckBox, "enable", "Navigator"); } // Visuals { + loadSettingBool(autoUseObjectNormalMapsCheckBox, "auto use object normal maps", "Shaders"); + loadSettingBool(autoUseObjectSpecularMapsCheckBox, "auto use object specular maps", "Shaders"); + loadSettingBool(autoUseTerrainNormalMapsCheckBox, "auto use terrain normal maps", "Shaders"); + loadSettingBool(autoUseTerrainSpecularMapsCheckBox, "auto use terrain specular maps", "Shaders"); loadSettingBool(bumpMapLocalLightingCheckBox, "apply lighting to environment maps", "Shaders"); + loadSettingBool(radialFogCheckBox, "radial fog", "Shaders"); loadSettingBool(magicItemAnimationsCheckBox, "use magic item animations", "Game"); connect(animSourcesCheckBox, SIGNAL(toggled(bool)), this, SLOT(slotAnimSourcesToggled(bool))); loadSettingBool(animSourcesCheckBox, "use additional anim sources", "Game"); @@ -136,7 +111,6 @@ bool Launcher::AdvancedPage::loadSettings() loadSettingBool(weaponSheathingCheckBox, "weapon sheathing", "Game"); loadSettingBool(shieldSheathingCheckBox, "shield sheathing", "Game"); } - loadSettingBool(viewOverShoulderCheckBox, "view over shoulder", "Camera"); loadSettingBool(turnToMovementDirectionCheckBox, "turn to movement direction", "Game"); const bool distantTerrain = mEngineSettings.getBool("distant terrain", "Terrain"); @@ -149,6 +123,18 @@ bool Launcher::AdvancedPage::loadSettings() viewingDistanceComboBox->setValue(convertToCells(mEngineSettings.getInt("viewing distance", "Camera"))); } + // Camera + { + loadSettingBool(viewOverShoulderCheckBox, "view over shoulder", "Camera"); + connect(viewOverShoulderCheckBox, SIGNAL(toggled(bool)), this, SLOT(slotViewOverShoulderToggled(bool))); + viewOverShoulderVerticalLayout->setEnabled(viewOverShoulderCheckBox->checkState()); + loadSettingBool(autoSwitchShoulderCheckBox, "auto switch shoulder", "Camera"); + loadSettingBool(previewIfStandStillCheckBox, "preview if stand still", "Camera"); + loadSettingBool(deferredPreviewRotationCheckBox, "deferred preview rotation", "Camera"); + defaultShoulderComboBox->setCurrentIndex( + mEngineSettings.getVector2("view over shoulder offset", "Camera").x() >= 0 ? 0 : 1); + } + // Interface Changes { loadSettingBool(showEffectDurationCheckBox, "show effect duration", "Game"); @@ -213,20 +199,26 @@ void Launcher::AdvancedPage::saveSettings() saveSettingBool(requireAppropriateAmmunitionCheckBox, "only appropriate ammunition bypasses resistance", "Game"); saveSettingBool(uncappedDamageFatigueCheckBox, "uncapped damage fatigue", "Game"); saveSettingBool(normaliseRaceSpeedCheckBox, "normalise race speed", "Game"); + saveSettingBool(swimUpwardCorrectionCheckBox, "swim upward correction", "Game"); int unarmedFactorsStrengthIndex = unarmedFactorsStrengthComboBox->currentIndex(); if (unarmedFactorsStrengthIndex != mEngineSettings.getInt("strength influences hand to hand", "Game")) mEngineSettings.setInt("strength influences hand to hand", "Game", unarmedFactorsStrengthIndex); saveSettingBool(stealingFromKnockedOutCheckBox, "always allow stealing from knocked out actors", "Game"); + saveSettingBool(enableNavigatorCheckBox, "enable", "Navigator"); } // Visuals { + saveSettingBool(autoUseObjectNormalMapsCheckBox, "auto use object normal maps", "Shaders"); + saveSettingBool(autoUseObjectSpecularMapsCheckBox, "auto use object specular maps", "Shaders"); + saveSettingBool(autoUseTerrainNormalMapsCheckBox, "auto use terrain normal maps", "Shaders"); + saveSettingBool(autoUseTerrainSpecularMapsCheckBox, "auto use terrain specular maps", "Shaders"); saveSettingBool(bumpMapLocalLightingCheckBox, "apply lighting to environment maps", "Shaders"); + saveSettingBool(radialFogCheckBox, "radial fog", "Shaders"); saveSettingBool(magicItemAnimationsCheckBox, "use magic item animations", "Game"); saveSettingBool(animSourcesCheckBox, "use additional anim sources", "Game"); saveSettingBool(weaponSheathingCheckBox, "weapon sheathing", "Game"); saveSettingBool(shieldSheathingCheckBox, "shield sheathing", "Game"); - saveSettingBool(viewOverShoulderCheckBox, "view over shoulder", "Camera"); saveSettingBool(turnToMovementDirectionCheckBox, "turn to movement direction", "Game"); const bool distantTerrain = mEngineSettings.getBool("distant terrain", "Terrain"); @@ -245,6 +237,24 @@ void Launcher::AdvancedPage::saveSettings() } } + // Camera + { + saveSettingBool(viewOverShoulderCheckBox, "view over shoulder", "Camera"); + saveSettingBool(autoSwitchShoulderCheckBox, "auto switch shoulder", "Camera"); + saveSettingBool(previewIfStandStillCheckBox, "preview if stand still", "Camera"); + saveSettingBool(deferredPreviewRotationCheckBox, "deferred preview rotation", "Camera"); + + osg::Vec2f shoulderOffset = mEngineSettings.getVector2("view over shoulder offset", "Camera"); + if (defaultShoulderComboBox->currentIndex() != (shoulderOffset.x() >= 0 ? 0 : 1)) + { + if (defaultShoulderComboBox->currentIndex() == 0) + shoulderOffset.x() = std::abs(shoulderOffset.x()); + else + shoulderOffset.x() = -std::abs(shoulderOffset.x()); + mEngineSettings.setVector2("view over shoulder offset", "Camera", shoulderOffset); + } + } + // Interface Changes { saveSettingBool(showEffectDurationCheckBox, "show effect duration", "Game"); @@ -326,3 +336,8 @@ void Launcher::AdvancedPage::slotAnimSourcesToggled(bool checked) shieldSheathingCheckBox->setCheckState(Qt::Unchecked); } } + +void Launcher::AdvancedPage::slotViewOverShoulderToggled(bool checked) +{ + viewOverShoulderVerticalLayout->setEnabled(viewOverShoulderCheckBox->checkState()); +} diff --git a/apps/launcher/advancedpage.hpp b/apps/launcher/advancedpage.hpp index 25cb66d9d..bdf5af0c8 100644 --- a/apps/launcher/advancedpage.hpp +++ b/apps/launcher/advancedpage.hpp @@ -32,6 +32,7 @@ namespace Launcher void on_skipMenuCheckBox_stateChanged(int state); void on_runScriptAfterStartupBrowseButton_clicked(); void slotAnimSourcesToggled(bool checked); + void slotViewOverShoulderToggled(bool checked); private: Files::ConfigurationManager &mCfgMgr; diff --git a/apps/launcher/graphicspage.cpp b/apps/launcher/graphicspage.cpp index 45c093bee..c745332dc 100644 --- a/apps/launcher/graphicspage.cpp +++ b/apps/launcher/graphicspage.cpp @@ -65,16 +65,19 @@ bool Launcher::GraphicsPage::setupSDL() msgBox.setWindowTitle(tr("Error receiving number of screens")); msgBox.setIcon(QMessageBox::Critical); msgBox.setStandardButtons(QMessageBox::Ok); - msgBox.setText(tr("
SDL_GetNumDisplayModes failed:

") + QString::fromUtf8(SDL_GetError()) + "
"); + msgBox.setText(tr("
SDL_GetNumVideoDisplays failed:

") + QString::fromUtf8(SDL_GetError()) + "
"); msgBox.exec(); return false; } screenComboBox->clear(); + mResolutionsPerScreen.clear(); for (int i = 0; i < displays; i++) { + mResolutionsPerScreen.append(getAvailableResolutions(i)); screenComboBox->addItem(QString(tr("Screen ")) + QString::number(i + 1)); } + screenChanged(0); // Disconnect from SDL processes quitSDL(); @@ -331,7 +334,7 @@ void Launcher::GraphicsPage::screenChanged(int screen) { if (screen >= 0) { resolutionComboBox->clear(); - resolutionComboBox->addItems(getAvailableResolutions(screen)); + resolutionComboBox->addItems(mResolutionsPerScreen[screen]); } } diff --git a/apps/launcher/graphicspage.hpp b/apps/launcher/graphicspage.hpp index 4ce5b584f..3b03a72bd 100644 --- a/apps/launcher/graphicspage.hpp +++ b/apps/launcher/graphicspage.hpp @@ -38,6 +38,8 @@ namespace Launcher Files::ConfigurationManager &mCfgMgr; Settings::Manager &mEngineSettings; + QVector mResolutionsPerScreen; + static QStringList getAvailableResolutions(int screen); static QRect getMaximumResolution(); diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt index 3b8c4b033..7efe84490 100644 --- a/apps/openmw/CMakeLists.txt +++ b/apps/openmw/CMakeLists.txt @@ -73,7 +73,7 @@ add_openmw_dir (mwworld add_openmw_dir (mwphysics physicssystem trace collisiontype actor convert object heightfield closestnotmerayresultcallback contacttestresultcallback deepestnotmecontacttestresultcallback stepper movementsolver - closestnotmeconvexresultcallback + closestnotmeconvexresultcallback raycasting ) add_openmw_dir (mwclass diff --git a/apps/openmw/mwbase/world.hpp b/apps/openmw/mwbase/world.hpp index 9480e2bba..4b3606045 100644 --- a/apps/openmw/mwbase/world.hpp +++ b/apps/openmw/mwbase/world.hpp @@ -51,6 +51,11 @@ namespace ESM struct TimeStamp; } +namespace MWPhysics +{ + class RayCastingInterface; +} + namespace MWRender { class Animation; @@ -420,6 +425,8 @@ namespace MWBase virtual void updateAnimatedCollisionShape(const MWWorld::Ptr &ptr) = 0; + virtual const MWPhysics::RayCastingInterface* getRayCasting() const = 0; + virtual bool castRay (float x1, float y1, float z1, float x2, float y2, float z2, int mask) = 0; ///< cast a Ray and return true if there is an object in the ray path. @@ -541,9 +548,8 @@ namespace MWBase virtual void togglePreviewMode(bool enable) = 0; virtual bool toggleVanityMode(bool enable) = 0; virtual void allowVanityMode(bool allow) = 0; - virtual void changeVanityModeScale(float factor) = 0; virtual bool vanityRotateCamera(float * rot) = 0; - virtual void setCameraDistance(float dist, bool adjust = false, bool override = true)=0; + virtual void adjustCameraDistance(float dist) = 0; virtual void applyDeferredPreviewRotationToPlayer(float dt) = 0; virtual void disableDeferredPreviewRotation() = 0; diff --git a/apps/openmw/mwclass/actor.cpp b/apps/openmw/mwclass/actor.cpp index 4eb9728a1..61d6e7347 100644 --- a/apps/openmw/mwclass/actor.cpp +++ b/apps/openmw/mwclass/actor.cpp @@ -91,4 +91,13 @@ namespace MWClass { return true; } + + float Actor::getCurrentSpeed(const MWWorld::Ptr& ptr) const + { + const MWMechanics::Movement& movementSettings = ptr.getClass().getMovementSettings(ptr); + float moveSpeed = this->getMaxSpeed(ptr) * movementSettings.mSpeedFactor; + if (movementSettings.mIsStrafing) + moveSpeed *= 0.75f; + return moveSpeed; + } } diff --git a/apps/openmw/mwclass/actor.hpp b/apps/openmw/mwclass/actor.hpp index 7cdee8061..6ccd552f9 100644 --- a/apps/openmw/mwclass/actor.hpp +++ b/apps/openmw/mwclass/actor.hpp @@ -31,7 +31,7 @@ namespace MWClass virtual void block(const MWWorld::Ptr &ptr) const; virtual osg::Vec3f getRotationVector(const MWWorld::Ptr& ptr) const; - ///< Return desired rotations, as euler angles. + ///< Return desired rotations, as euler angles. Sets getMovementSettings(ptr).mRotation to zero. virtual float getEncumbrance(const MWWorld::Ptr& ptr) const; ///< Returns total weight of objects inside this object (including modifications from magic @@ -42,6 +42,9 @@ namespace MWClass virtual bool isActor() const; + /// Return current movement speed. + virtual float getCurrentSpeed(const MWWorld::Ptr& ptr) const; + // not implemented Actor(const Actor&); Actor& operator= (const Actor&); diff --git a/apps/openmw/mwclass/creature.cpp b/apps/openmw/mwclass/creature.cpp index 2f1a4386d..24b16bf2d 100644 --- a/apps/openmw/mwclass/creature.cpp +++ b/apps/openmw/mwclass/creature.cpp @@ -688,7 +688,7 @@ namespace MWClass registerClass (typeid (ESM::Creature).name(), instance); } - float Creature::getSpeed(const MWWorld::Ptr &ptr) const + float Creature::getMaxSpeed(const MWWorld::Ptr &ptr) const { const MWMechanics::CreatureStats& stats = getCreatureStats(ptr); @@ -720,11 +720,6 @@ namespace MWClass else moveSpeed = getWalkSpeed(ptr); - const MWMechanics::Movement& movementSettings = ptr.getClass().getMovementSettings(ptr); - if (movementSettings.mIsStrafing) - moveSpeed *= 0.75f; - moveSpeed *= movementSettings.mSpeedFactor; - return moveSpeed; } diff --git a/apps/openmw/mwclass/creature.hpp b/apps/openmw/mwclass/creature.hpp index 051174b1c..b27ab75f2 100644 --- a/apps/openmw/mwclass/creature.hpp +++ b/apps/openmw/mwclass/creature.hpp @@ -104,7 +104,7 @@ namespace MWClass virtual MWMechanics::Movement& getMovementSettings (const MWWorld::Ptr& ptr) const; ///< Return desired movement. - float getSpeed (const MWWorld::Ptr& ptr) const; + float getMaxSpeed (const MWWorld::Ptr& ptr) const; static void registerSelf(); diff --git a/apps/openmw/mwclass/npc.cpp b/apps/openmw/mwclass/npc.cpp index b7a6002ec..dcf24e104 100644 --- a/apps/openmw/mwclass/npc.cpp +++ b/apps/openmw/mwclass/npc.cpp @@ -1159,7 +1159,7 @@ namespace MWClass return ref->mBase->mScript; } - float Npc::getSpeed(const MWWorld::Ptr& ptr) const + float Npc::getMaxSpeed(const MWWorld::Ptr& ptr) const { const MWMechanics::CreatureStats& stats = getCreatureStats(ptr); if (stats.isParalyzed() || stats.getKnockedDown() || stats.isDead()) @@ -1202,11 +1202,6 @@ namespace MWClass if(npcdata->mNpcStats.isWerewolf() && running && npcdata->mNpcStats.getDrawState() == MWMechanics::DrawState_Nothing) moveSpeed *= gmst.fWereWolfRunMult->mValue.getFloat(); - const MWMechanics::Movement& movementSettings = ptr.getClass().getMovementSettings(ptr); - if (movementSettings.mIsStrafing) - moveSpeed *= 0.75f; - moveSpeed *= movementSettings.mSpeedFactor; - return moveSpeed; } diff --git a/apps/openmw/mwclass/npc.hpp b/apps/openmw/mwclass/npc.hpp index 21f23dcae..01190cd4c 100644 --- a/apps/openmw/mwclass/npc.hpp +++ b/apps/openmw/mwclass/npc.hpp @@ -94,8 +94,8 @@ namespace MWClass virtual std::string getScript (const MWWorld::ConstPtr& ptr) const; ///< Return name of the script attached to ptr - virtual float getSpeed (const MWWorld::Ptr& ptr) const; - ///< Return movement speed. + virtual float getMaxSpeed (const MWWorld::Ptr& ptr) const; + ///< Return maximal movement speed. virtual float getJump(const MWWorld::Ptr &ptr) const; ///< Return jump velocity (not accounting for movement) diff --git a/apps/openmw/mwinput/actionmanager.cpp b/apps/openmw/mwinput/actionmanager.cpp index 967afdc73..bf7a6db18 100644 --- a/apps/openmw/mwinput/actionmanager.cpp +++ b/apps/openmw/mwinput/actionmanager.cpp @@ -37,7 +37,7 @@ namespace MWInput { - const float ZOOM_SCALE = 120.f; /// Used for scrolling camera in and out + const float ZOOM_SCALE = 10.f; /// Used for scrolling camera in and out ActionManager::ActionManager(BindingsManager* bindingsManager, osgViewer::ScreenCaptureHandler::CaptureOperation* screenCaptureOperation, @@ -206,6 +206,8 @@ namespace MWInput void ActionManager::executeAction(int action) { + auto* inputManager = MWBase::Environment::get().getInputManager(); + auto* windowManager = MWBase::Environment::get().getWindowManager(); // trigger action activated switch (action) { @@ -222,7 +224,7 @@ namespace MWInput toggleConsole (); break; case A_Activate: - MWBase::Environment::get().getInputManager()->resetIdleTime(); + inputManager->resetIdleTime(); activate(); break; case A_MoveLeft: @@ -283,18 +285,18 @@ namespace MWInput showQuickKeysMenu(); break; case A_ToggleHUD: - MWBase::Environment::get().getWindowManager()->toggleHud(); + windowManager->toggleHud(); break; case A_ToggleDebug: - MWBase::Environment::get().getWindowManager()->toggleDebugWindow(); + windowManager->toggleDebugWindow(); break; case A_ZoomIn: - if (MWBase::Environment::get().getInputManager()->getControlSwitch("playerviewswitch") && MWBase::Environment::get().getInputManager()->getControlSwitch("playercontrols") && !MWBase::Environment::get().getWindowManager()->isGuiMode()) - MWBase::Environment::get().getWorld()->setCameraDistance(ZOOM_SCALE, true, true); + if (inputManager->getControlSwitch("playerviewswitch") && inputManager->getControlSwitch("playercontrols") && !windowManager->isGuiMode()) + MWBase::Environment::get().getWorld()->adjustCameraDistance(-ZOOM_SCALE); break; case A_ZoomOut: - if (MWBase::Environment::get().getInputManager()->getControlSwitch("playerviewswitch") && MWBase::Environment::get().getInputManager()->getControlSwitch("playercontrols") && !MWBase::Environment::get().getWindowManager()->isGuiMode()) - MWBase::Environment::get().getWorld()->setCameraDistance(-ZOOM_SCALE, true, true); + if (inputManager->getControlSwitch("playerviewswitch") && inputManager->getControlSwitch("playercontrols") && !windowManager->isGuiMode()) + MWBase::Environment::get().getWorld()->adjustCameraDistance(ZOOM_SCALE); break; case A_QuickSave: quickSave(); @@ -303,19 +305,19 @@ namespace MWInput quickLoad(); break; case A_CycleSpellLeft: - if (checkAllowedToUseItems() && MWBase::Environment::get().getWindowManager()->isAllowed(MWGui::GW_Magic)) + if (checkAllowedToUseItems() && windowManager->isAllowed(MWGui::GW_Magic)) MWBase::Environment::get().getWindowManager()->cycleSpell(false); break; case A_CycleSpellRight: - if (checkAllowedToUseItems() && MWBase::Environment::get().getWindowManager()->isAllowed(MWGui::GW_Magic)) + if (checkAllowedToUseItems() && windowManager->isAllowed(MWGui::GW_Magic)) MWBase::Environment::get().getWindowManager()->cycleSpell(true); break; case A_CycleWeaponLeft: - if (checkAllowedToUseItems() && MWBase::Environment::get().getWindowManager()->isAllowed(MWGui::GW_Inventory)) + if (checkAllowedToUseItems() && windowManager->isAllowed(MWGui::GW_Inventory)) MWBase::Environment::get().getWindowManager()->cycleWeapon(false); break; case A_CycleWeaponRight: - if (checkAllowedToUseItems() && MWBase::Environment::get().getWindowManager()->isAllowed(MWGui::GW_Inventory)) + if (checkAllowedToUseItems() && windowManager->isAllowed(MWGui::GW_Inventory)) MWBase::Environment::get().getWindowManager()->cycleWeapon(true); break; case A_Sneak: diff --git a/apps/openmw/mwinput/controllermanager.cpp b/apps/openmw/mwinput/controllermanager.cpp index c9941c836..48091541c 100644 --- a/apps/openmw/mwinput/controllermanager.cpp +++ b/apps/openmw/mwinput/controllermanager.cpp @@ -190,10 +190,7 @@ namespace MWInput mGamepadZoom = 0; if (mGamepadZoom) - { - MWBase::Environment::get().getWorld()->changeVanityModeScale(mGamepadZoom); - MWBase::Environment::get().getWorld()->setCameraDistance(mGamepadZoom, true, true); - } + MWBase::Environment::get().getWorld()->adjustCameraDistance(-mGamepadZoom); } return triedToMove; @@ -291,12 +288,12 @@ namespace MWInput { if (arg.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) { - mGamepadZoom = arg.value * 0.85f / 1000.f; + mGamepadZoom = arg.value * 0.85f / 1000.f / 12.f; return; // Do not propagate event. } else if (arg.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT) { - mGamepadZoom = -arg.value * 0.85f / 1000.f; + mGamepadZoom = -arg.value * 0.85f / 1000.f / 12.f; return; // Do not propagate event. } } diff --git a/apps/openmw/mwinput/mousemanager.cpp b/apps/openmw/mwinput/mousemanager.cpp index 84ab091c5..ac30d4487 100644 --- a/apps/openmw/mwinput/mousemanager.cpp +++ b/apps/openmw/mwinput/mousemanager.cpp @@ -93,6 +93,8 @@ namespace MWInput if (mMouseLookEnabled && !input->controlsDisabled()) { + MWBase::World* world = MWBase::Environment::get().getWorld(); + float x = arg.xrel * mCameraSensitivity * (mInvertX ? -1 : 1) / 256.f; float y = arg.yrel * mCameraSensitivity * (mInvertY ? -1 : 1) * mCameraYMultiplier / 256.f; @@ -102,19 +104,14 @@ namespace MWInput rot[2] = -x; // Only actually turn player when we're not in vanity mode - if (!MWBase::Environment::get().getWorld()->vanityRotateCamera(rot) && input->getControlSwitch("playerlooking")) + if (!world->vanityRotateCamera(rot) && input->getControlSwitch("playerlooking")) { - MWWorld::Player& player = MWBase::Environment::get().getWorld()->getPlayer(); + MWWorld::Player& player = world->getPlayer(); player.yaw(x); player.pitch(y); } else if (!input->getControlSwitch("playerlooking")) MWBase::Environment::get().getWorld()->disableDeferredPreviewRotation(); - - if (arg.zrel && input->getControlSwitch("playerviewswitch") && input->getControlSwitch("playercontrols")) //Check to make sure you are allowed to zoomout and there is a change - { - MWBase::Environment::get().getWorld()->changeVanityModeScale(static_cast(arg.zrel)); - } } } diff --git a/apps/openmw/mwmechanics/actors.cpp b/apps/openmw/mwmechanics/actors.cpp index 93844ead6..1772ad980 100644 --- a/apps/openmw/mwmechanics/actors.cpp +++ b/apps/openmw/mwmechanics/actors.cpp @@ -505,9 +505,6 @@ namespace MWMechanics void Actors::updateMovementSpeed(const MWWorld::Ptr& actor) { - float previousSpeedFactor = actor.getClass().getMovementSettings(actor).mSpeedFactor; - float newSpeedFactor = 1.f; - CreatureStats &stats = actor.getClass().getCreatureStats(actor); MWMechanics::AiSequence& seq = stats.getAiSequence(); @@ -517,10 +514,13 @@ namespace MWMechanics osg::Vec3f actorPos = actor.getRefData().getPosition().asVec3(); float distance = (targetPos - actorPos).length(); if (distance < DECELERATE_DISTANCE) - newSpeedFactor = std::max(0.7f, 0.1f * previousSpeedFactor * (distance/64.f + 2.f)); + { + float speedCoef = std::max(0.7f, 0.1f * (distance/64.f + 2.f)); + auto& movement = actor.getClass().getMovementSettings(actor); + movement.mPosition[0] *= speedCoef; + movement.mPosition[1] *= speedCoef; + } } - - actor.getClass().getMovementSettings(actor).mSpeedFactor = newSpeedFactor; } void Actors::updateGreetingState(const MWWorld::Ptr& actor, Actor& actorState, bool turnOnly) diff --git a/apps/openmw/mwmechanics/aiavoiddoor.cpp b/apps/openmw/mwmechanics/aiavoiddoor.cpp index ce2553756..73a638563 100644 --- a/apps/openmw/mwmechanics/aiavoiddoor.cpp +++ b/apps/openmw/mwmechanics/aiavoiddoor.cpp @@ -60,14 +60,14 @@ bool MWMechanics::AiAvoidDoor::execute (const MWWorld::Ptr& actor, CharacterCont // Make all nearby actors also avoid the door std::vector actors; MWBase::Environment::get().getMechanicsManager()->getActorsInRange(pos.asVec3(),100,actors); - for(auto& actor : actors) + for(auto& neighbor : actors) { - if (actor == getPlayer()) + if (neighbor == getPlayer()) continue; - MWMechanics::AiSequence& seq = actor.getClass().getCreatureStats(actor).getAiSequence(); + MWMechanics::AiSequence& seq = neighbor.getClass().getCreatureStats(neighbor).getAiSequence(); if (seq.getTypeId() != MWMechanics::AiPackageTypeId::AvoidDoor) - seq.stack(MWMechanics::AiAvoidDoor(mDoorPtr), actor); + seq.stack(MWMechanics::AiAvoidDoor(mDoorPtr), neighbor); } return false; diff --git a/apps/openmw/mwmechanics/aipackage.cpp b/apps/openmw/mwmechanics/aipackage.cpp index f7c07bde0..53e366579 100644 --- a/apps/openmw/mwmechanics/aipackage.cpp +++ b/apps/openmw/mwmechanics/aipackage.cpp @@ -144,7 +144,7 @@ bool MWMechanics::AiPackage::pathTo(const MWWorld::Ptr& actor, const osg::Vec3f& mTimer = 0; } - const float actorTolerance = 2 * actor.getClass().getSpeed(actor) * duration + const float actorTolerance = 2 * actor.getClass().getMaxSpeed(actor) * duration + 1.2 * std::max(halfExtents.x(), halfExtents.y()); const float pointTolerance = std::max(MIN_TOLERANCE, actorTolerance); @@ -300,7 +300,7 @@ bool MWMechanics::AiPackage::checkWayIsClearForActor(const osg::Vec3f& startPoin if (canActorMoveByZAxis(actor)) return true; - const float actorSpeed = actor.getClass().getSpeed(actor); + const float actorSpeed = actor.getClass().getMaxSpeed(actor); const float maxAvoidDist = AI_REACTION_TIME * actorSpeed + actorSpeed / getAngularVelocity(actorSpeed) * 2; // *2 - for reliability const float distToTarget = osg::Vec2f(endPoint.x(), endPoint.y()).length(); @@ -360,7 +360,7 @@ bool MWMechanics::AiPackage::isNearInactiveCell(osg::Vec3f position) bool MWMechanics::AiPackage::isReachableRotatingOnTheRun(const MWWorld::Ptr& actor, const osg::Vec3f& dest) { // get actor's shortest radius for moving in circle - float speed = actor.getClass().getSpeed(actor); + float speed = actor.getClass().getMaxSpeed(actor); speed += speed * 0.1f; // 10% real speed inaccuracy float radius = speed / getAngularVelocity(speed); diff --git a/apps/openmw/mwmechanics/aipursue.cpp b/apps/openmw/mwmechanics/aipursue.cpp index c4cae748f..45ccf2f0b 100644 --- a/apps/openmw/mwmechanics/aipursue.cpp +++ b/apps/openmw/mwmechanics/aipursue.cpp @@ -52,8 +52,7 @@ bool AiPursue::execute (const MWWorld::Ptr& actor, CharacterController& characte if (target == MWWorld::Ptr() || !target.getRefData().getCount() || !target.getRefData().isEnabled()) return true; - if (!MWBase::Environment::get().getWorld()->getLOS(target, actor) - || !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(target, actor)) + if (isTargetMagicallyHidden(target) && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(target, actor)) return false; if (target.getClass().getCreatureStats(target).isDead()) diff --git a/apps/openmw/mwmechanics/character.cpp b/apps/openmw/mwmechanics/character.cpp index 9e8494c08..0c10f3ca9 100644 --- a/apps/openmw/mwmechanics/character.cpp +++ b/apps/openmw/mwmechanics/character.cpp @@ -21,6 +21,7 @@ #include +#include #include #include @@ -68,15 +69,6 @@ namespace { -// Wraps a value to (-PI, PI] -void wrap(float& rad) -{ - if (rad>0) - rad = std::fmod(rad+osg::PI, 2.0f*osg::PI)-osg::PI; - else - rad = std::fmod(rad-osg::PI, 2.0f*osg::PI)+osg::PI; -} - std::string getBestAttack (const ESM::Weapon* weapon) { int slash = (weapon->mData.mSlash[0] + weapon->mData.mSlash[1])/2; @@ -2116,7 +2108,6 @@ void CharacterController::update(float duration, bool animationOnly) osg::Vec3f rot = cls.getRotationVector(mPtr); osg::Vec3f vec(movementSettings.asVec3()); - vec.normalize(); /* Start of tes3mp addition @@ -2150,21 +2141,18 @@ void CharacterController::update(float duration, bool animationOnly) End of tes3mp addition */ - float analogueMult = 1.0f; if (isPlayer) { // TODO: Move this code to mwinput. // Joystick analogue movement. - float xAxis = std::abs(movementSettings.mPosition[0]); - float yAxis = std::abs(movementSettings.mPosition[1]); - analogueMult = std::max(xAxis, yAxis); + movementSettings.mSpeedFactor = std::max(std::abs(vec.x()), std::abs(vec.y())); // Due to the half way split between walking/running, we multiply speed by 2 while walking, unless a keyboard was used. - if(!isrunning && !sneak && !flying && analogueMult <= 0.5f) - analogueMult *= 2.f; - - movementSettings.mSpeedFactor = analogueMult; - } + if(!isrunning && !sneak && !flying && movementSettings.mSpeedFactor <= 0.5f) + movementSettings.mSpeedFactor *= 2.f; + } else + movementSettings.mSpeedFactor = std::min(vec.length(), 1.f); + vec.normalize(); float effectiveRotation = rot.z(); static const bool turnToMovementDirection = Settings::Manager::getBool("turn to movement direction", "Game"); @@ -2197,7 +2185,7 @@ void CharacterController::update(float duration, bool animationOnly) else mAnimation->setUpperBodyYawRadians(stats.getSideMovementAngle() / 4); - speed = cls.getSpeed(mPtr); + speed = cls.getCurrentSpeed(mPtr); vec.x() *= speed; vec.y() *= speed; @@ -2267,7 +2255,7 @@ void CharacterController::update(float duration, bool animationOnly) } } fatigueLoss *= duration; - fatigueLoss *= analogueMult; + fatigueLoss *= movementSettings.mSpeedFactor; DynamicStat fatigue = cls.getCreatureStats(mPtr).getFatigue(); if (!godmode) @@ -2433,7 +2421,8 @@ void CharacterController::update(float duration, bool animationOnly) swimmingPitch += osg::clampBetween(targetSwimmingPitch - swimmingPitch, -maxSwimPitchDelta, maxSwimPitchDelta); mAnimation->setBodyPitchRadians(swimmingPitch); } - if (inwater && isPlayer && !isFirstPersonPlayer) + static const bool swimUpwardCorrection = Settings::Manager::getBool("swim upward correction", "Game"); + if (inwater && isPlayer && !isFirstPersonPlayer && swimUpwardCorrection) { static const float swimUpwardCoef = Settings::Manager::getFloat("swim upward coef", "Game"); static const float swimForwardCoef = sqrtf(1.0f - swimUpwardCoef * swimUpwardCoef); @@ -3140,13 +3129,10 @@ void CharacterController::updateHeadTracking(float duration) zAngleRadians = std::atan2(direction.x(), direction.y()) - std::atan2(actorDirection.x(), actorDirection.y()); xAngleRadians = -std::asin(direction.z()); - wrap(zAngleRadians); - wrap(xAngleRadians); - - xAngleRadians = std::min(xAngleRadians, osg::DegreesToRadians(40.f)); - xAngleRadians = std::max(xAngleRadians, osg::DegreesToRadians(-40.f)); - zAngleRadians = std::min(zAngleRadians, osg::DegreesToRadians(30.f)); - zAngleRadians = std::max(zAngleRadians, osg::DegreesToRadians(-30.f)); + const double xLimit = osg::DegreesToRadians(40.0); + const double zLimit = osg::DegreesToRadians(30.0); + zAngleRadians = osg::clampBetween(Misc::normalizeAngle(zAngleRadians), -xLimit, xLimit); + xAngleRadians = osg::clampBetween(Misc::normalizeAngle(xAngleRadians), -zLimit, zLimit); } float factor = duration*5; diff --git a/apps/openmw/mwmechanics/movement.hpp b/apps/openmw/mwmechanics/movement.hpp index 86b970e60..57e106cde 100644 --- a/apps/openmw/mwmechanics/movement.hpp +++ b/apps/openmw/mwmechanics/movement.hpp @@ -8,8 +8,14 @@ namespace MWMechanics /// Desired movement for an actor struct Movement { + // Desired movement. Direction is relative to the current orientation. + // Length of the vector controls desired speed. 0 - stay, 0.5 - half-speed, 1.0 - max speed. float mPosition[3]; + // Desired rotation delta (euler angles). float mRotation[3]; + + // Controlled by CharacterController, should not be changed from other places. + // These fields can not be private fields in CharacterController, because Actor::getCurrentSpeed uses it. float mSpeedFactor; bool mIsStrafing; diff --git a/apps/openmw/mwmechanics/obstacle.cpp b/apps/openmw/mwmechanics/obstacle.cpp index 715dfecd2..88325ee7c 100644 --- a/apps/openmw/mwmechanics/obstacle.cpp +++ b/apps/openmw/mwmechanics/obstacle.cpp @@ -122,7 +122,7 @@ namespace MWMechanics if (mWalkState != WalkState::Evade) { - const float distSameSpot = DIST_SAME_SPOT * actor.getClass().getSpeed(actor) * duration; + const float distSameSpot = DIST_SAME_SPOT * actor.getClass().getCurrentSpeed(actor) * duration; const float prevDistance = (destination - mPrev).length(); const float currentDistance = (destination - position).length(); const float movedDistance = prevDistance - currentDistance; diff --git a/apps/openmw/mwmechanics/spelllist.hpp b/apps/openmw/mwmechanics/spelllist.hpp index 87420082f..b01722fe8 100644 --- a/apps/openmw/mwmechanics/spelllist.hpp +++ b/apps/openmw/mwmechanics/spelllist.hpp @@ -26,6 +26,14 @@ namespace MWMechanics class Spells; + /// Multiple instances of the same actor share the same spell list in Morrowind. + /// The most obvious result of this is that adding a spell or ability to one instance adds it to all instances. + /// @note The original game will only update visual effects associated with any added abilities for the originally targeted actor, + /// changing cells applies the update to all actors. + /// Aside from sharing the same active spell list, changes made to this list are also written to the actor's base record. + /// Interestingly, it is not just scripted changes that are persisted to the base record. Curing one instance's disease will cure all instances. + /// @note The original game is inconsistent in persisting this example; + /// saving and loading the game might reapply the cured disease depending on which instance was cured. class SpellList { const std::string mId; diff --git a/apps/openmw/mwmechanics/spells.cpp b/apps/openmw/mwmechanics/spells.cpp index 54df81079..a90365e8a 100644 --- a/apps/openmw/mwmechanics/spells.cpp +++ b/apps/openmw/mwmechanics/spells.cpp @@ -455,8 +455,9 @@ namespace MWMechanics const auto& baseSpells = mSpellList->getSpells(); for (const auto& it : mSpells) { - //Don't save spells stored in the base record - if(std::find(baseSpells.begin(), baseSpells.end(), it.first->mId) == baseSpells.end()) + // Don't save spells and powers stored in the base record + if((it.first->mData.mType != ESM::Spell::ST_Spell && it.first->mData.mType != ESM::Spell::ST_Power) || + std::find(baseSpells.begin(), baseSpells.end(), it.first->mId) == baseSpells.end()) { ESM::SpellState::SpellParams params; params.mEffectRands = it.second.mEffectRands; @@ -476,8 +477,7 @@ namespace MWMechanics bool result; std::tie(mSpellList, result) = MWBase::Environment::get().getWorld()->getStore().getSpellList(actorId); mSpellList->addListener(this); - for(const auto& id : mSpellList->getSpells()) - addSpell(SpellList::getSpell(id)); + addAllToInstance(mSpellList->getSpells()); return result; } diff --git a/apps/openmw/mwmechanics/steering.cpp b/apps/openmw/mwmechanics/steering.cpp index b08a90220..d442085ea 100644 --- a/apps/openmw/mwmechanics/steering.cpp +++ b/apps/openmw/mwmechanics/steering.cpp @@ -32,7 +32,7 @@ bool smoothTurn(const MWWorld::Ptr& actor, float targetAngleRadians, int axis, f if (absDiff < epsilonRadians) return true; - float limit = getAngularVelocity(actor.getClass().getSpeed(actor)) * MWBase::Environment::get().getFrameDuration(); + float limit = getAngularVelocity(actor.getClass().getMaxSpeed(actor)) * MWBase::Environment::get().getFrameDuration(); if (absDiff > limit) diff = osg::sign(diff) * limit; diff --git a/apps/openmw/mwphysics/physicssystem.cpp b/apps/openmw/mwphysics/physicssystem.cpp index 707f93405..1b9682221 100644 --- a/apps/openmw/mwphysics/physicssystem.cpp +++ b/apps/openmw/mwphysics/physicssystem.cpp @@ -201,7 +201,7 @@ namespace MWPhysics { // First of all, try to hit where you aim to int hitmask = CollisionType_World | CollisionType_Door | CollisionType_HeightMap | CollisionType_Actor; - RayResult result = castRay(origin, origin + (orient * osg::Vec3f(0.0f, queryDistance, 0.0f)), actor, targets, hitmask, CollisionType_Actor); + RayCastingResult result = castRay(origin, origin + (orient * osg::Vec3f(0.0f, queryDistance, 0.0f)), actor, targets, hitmask, CollisionType_Actor); if (result.mHit) { @@ -284,7 +284,7 @@ namespace MWPhysics return (point - Misc::Convert::toOsg(cb.m_hitPointWorld)).length(); } - PhysicsSystem::RayResult PhysicsSystem::castRay(const osg::Vec3f &from, const osg::Vec3f &to, const MWWorld::ConstPtr& ignore, std::vector targets, int mask, int group) const + RayCastingResult PhysicsSystem::castRay(const osg::Vec3f &from, const osg::Vec3f &to, const MWWorld::ConstPtr& ignore, std::vector targets, int mask, int group) const { btVector3 btFrom = Misc::Convert::toBullet(from); btVector3 btTo = Misc::Convert::toBullet(to); @@ -321,7 +321,7 @@ namespace MWPhysics mCollisionWorld->rayTest(btFrom, btTo, resultCallback); - RayResult result; + RayCastingResult result; result.mHit = resultCallback.hasHit(); if (resultCallback.hasHit()) { @@ -333,7 +333,7 @@ namespace MWPhysics return result; } - PhysicsSystem::RayResult PhysicsSystem::castSphere(const osg::Vec3f &from, const osg::Vec3f &to, float radius) + RayCastingResult PhysicsSystem::castSphere(const osg::Vec3f &from, const osg::Vec3f &to, float radius) const { btCollisionWorld::ClosestConvexResultCallback callback(Misc::Convert::toBullet(from), Misc::Convert::toBullet(to)); callback.m_collisionFilterGroup = 0xff; @@ -347,7 +347,7 @@ namespace MWPhysics mCollisionWorld->convexSweepTest(&shape, from_, to_, callback); - RayResult result; + RayCastingResult result; result.mHit = callback.hasHit(); if (result.mHit) { @@ -368,7 +368,7 @@ namespace MWPhysics osg::Vec3f pos1 (physactor1->getCollisionObjectPosition() + osg::Vec3f(0,0,physactor1->getHalfExtents().z() * 0.9)); // eye level osg::Vec3f pos2 (physactor2->getCollisionObjectPosition() + osg::Vec3f(0,0,physactor2->getHalfExtents().z() * 0.9)); - RayResult result = castRay(pos1, pos2, MWWorld::ConstPtr(), std::vector(), CollisionType_World|CollisionType_HeightMap|CollisionType_Door); + RayCastingResult result = castRay(pos1, pos2, MWWorld::ConstPtr(), std::vector(), CollisionType_World|CollisionType_HeightMap|CollisionType_Door); return !result.mHit; } diff --git a/apps/openmw/mwphysics/physicssystem.hpp b/apps/openmw/mwphysics/physicssystem.hpp index d28f7d2ac..b6f6824a7 100644 --- a/apps/openmw/mwphysics/physicssystem.hpp +++ b/apps/openmw/mwphysics/physicssystem.hpp @@ -13,6 +13,7 @@ #include "../mwworld/ptr.hpp" #include "collisiontype.hpp" +#include "raycasting.hpp" namespace osg { @@ -52,11 +53,11 @@ namespace MWPhysics class Object; class Actor; - class PhysicsSystem + class PhysicsSystem : public RayCastingInterface { public: PhysicsSystem (Resource::ResourceSystem* resourceSystem, osg::ref_ptr parentNode); - ~PhysicsSystem (); + virtual ~PhysicsSystem (); void setUnrefQueue(SceneUtil::UnrefQueue* unrefQueue); @@ -108,25 +109,17 @@ namespace MWPhysics /// target vector hits the collision shape and then calculates distance from the intersection point. /// This can be used to find out how much nearer we need to move to the target for a "getHitContact" to be successful. /// \note Only Actor targets are supported at the moment. - float getHitDistance(const osg::Vec3f& point, const MWWorld::ConstPtr& target) const; - - struct RayResult - { - bool mHit; - osg::Vec3f mHitPos; - osg::Vec3f mHitNormal; - MWWorld::Ptr mHitObject; - }; + float getHitDistance(const osg::Vec3f& point, const MWWorld::ConstPtr& target) const override final; /// @param me Optional, a Ptr to ignore in the list of results. targets are actors to filter for, ignoring all other actors. - RayResult castRay(const osg::Vec3f &from, const osg::Vec3f &to, const MWWorld::ConstPtr& ignore = MWWorld::ConstPtr(), + RayCastingResult castRay(const osg::Vec3f &from, const osg::Vec3f &to, const MWWorld::ConstPtr& ignore = MWWorld::ConstPtr(), std::vector targets = std::vector(), - int mask = CollisionType_World|CollisionType_HeightMap|CollisionType_Actor|CollisionType_Door, int group=0xff) const; + int mask = CollisionType_World|CollisionType_HeightMap|CollisionType_Actor|CollisionType_Door, int group=0xff) const override final; - RayResult castSphere(const osg::Vec3f& from, const osg::Vec3f& to, float radius); + RayCastingResult castSphere(const osg::Vec3f& from, const osg::Vec3f& to, float radius) const override final; /// Return true if actor1 can see actor2. - bool getLineOfSight(const MWWorld::ConstPtr& actor1, const MWWorld::ConstPtr& actor2) const; + bool getLineOfSight(const MWWorld::ConstPtr& actor1, const MWWorld::ConstPtr& actor2) const override final; bool isOnGround (const MWWorld::Ptr& actor); diff --git a/apps/openmw/mwphysics/raycasting.hpp b/apps/openmw/mwphysics/raycasting.hpp new file mode 100644 index 000000000..7afbe9321 --- /dev/null +++ b/apps/openmw/mwphysics/raycasting.hpp @@ -0,0 +1,41 @@ +#ifndef OPENMW_MWPHYSICS_RAYCASTING_H +#define OPENMW_MWPHYSICS_RAYCASTING_H + +#include + +#include "../mwworld/ptr.hpp" + +#include "collisiontype.hpp" + +namespace MWPhysics +{ + struct RayCastingResult + { + bool mHit; + osg::Vec3f mHitPos; + osg::Vec3f mHitNormal; + MWWorld::Ptr mHitObject; + }; + + class RayCastingInterface + { + public: + /// Get distance from \a point to the collision shape of \a target. Uses a raycast to find where the + /// target vector hits the collision shape and then calculates distance from the intersection point. + /// This can be used to find out how much nearer we need to move to the target for a "getHitContact" to be successful. + /// \note Only Actor targets are supported at the moment. + virtual float getHitDistance(const osg::Vec3f& point, const MWWorld::ConstPtr& target) const = 0; + + /// @param me Optional, a Ptr to ignore in the list of results. targets are actors to filter for, ignoring all other actors. + virtual RayCastingResult castRay(const osg::Vec3f &from, const osg::Vec3f &to, const MWWorld::ConstPtr& ignore = MWWorld::ConstPtr(), + std::vector targets = std::vector(), + int mask = CollisionType_World|CollisionType_HeightMap|CollisionType_Actor|CollisionType_Door, int group=0xff) const = 0; + + virtual RayCastingResult castSphere(const osg::Vec3f& from, const osg::Vec3f& to, float radius) const = 0; + + /// Return true if actor1 can see actor2. + virtual bool getLineOfSight(const MWWorld::ConstPtr& actor1, const MWWorld::ConstPtr& actor2) const = 0; + }; +} + +#endif diff --git a/apps/openmw/mwrender/camera.cpp b/apps/openmw/mwrender/camera.cpp index 328e53a79..0d6ed262b 100644 --- a/apps/openmw/mwrender/camera.cpp +++ b/apps/openmw/mwrender/camera.cpp @@ -2,11 +2,13 @@ #include +#include #include #include #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" +#include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/ptr.hpp" @@ -16,6 +18,8 @@ #include "../mwmechanics/movement.hpp" #include "../mwmechanics/npcstats.hpp" +#include "../mwphysics/raycasting.hpp" + #include "npcanimation.hpp" namespace @@ -195,8 +199,9 @@ namespace MWRender rotateCamera(0.f, osg::DegreesToRadians(3.f * duration), true); updateFocalPointOffset(duration); + updatePosition(); - float speed = mTrackingPtr.getClass().getSpeed(mTrackingPtr); + float speed = mTrackingPtr.getClass().getCurrentSpeed(mTrackingPtr); speed /= (1.f + speed / 500.f); float maxDelta = 300.f * duration; mSmoothedSpeed += osg::clampBetween(speed - mSmoothedSpeed, -maxDelta, maxDelta); @@ -205,11 +210,47 @@ namespace MWRender updateStandingPreviewMode(); } + void Camera::updatePosition() + { + mFocalPointAdjustment = osg::Vec3d(); + if (isFirstPerson()) + return; + + const float cameraObstacleLimit = 5.0f; + const float focalObstacleLimit = 10.f; + + const auto* rayCasting = MWBase::Environment::get().getWorld()->getRayCasting(); + + // Adjust focal point to prevent clipping. + osg::Vec3d focal = getFocalPoint(); + osg::Vec3d focalOffset = getFocalPointOffset(); + float offsetLen = focalOffset.length(); + if (offsetLen > 0) + { + MWPhysics::RayCastingResult result = rayCasting->castSphere(focal - focalOffset, focal, focalObstacleLimit); + if (result.mHit) + { + double adjustmentCoef = -(result.mHitPos + result.mHitNormal * focalObstacleLimit - focal).length() / offsetLen; + mFocalPointAdjustment = focalOffset * std::max(-1.0, adjustmentCoef); + } + } + + // Calculate camera distance. + mCameraDistance = mBaseCameraDistance + getCameraDistanceCorrection(); + if (mDynamicCameraDistanceEnabled) + mCameraDistance = std::min(mCameraDistance, mMaxNextCameraDistance); + osg::Vec3d cameraPos; + getPosition(focal, cameraPos); + MWPhysics::RayCastingResult result = rayCasting->castSphere(focal, cameraPos, cameraObstacleLimit); + if (result.mHit) + mCameraDistance = (result.mHitPos + result.mHitNormal * cameraObstacleLimit - focal).length(); + } + void Camera::updateStandingPreviewMode() { if (!mStandingPreviewAllowed) return; - float speed = mTrackingPtr.getClass().getSpeed(mTrackingPtr); + float speed = mTrackingPtr.getClass().getCurrentSpeed(mTrackingPtr); bool combat = mTrackingPtr.getClass().isActor() && mTrackingPtr.getClass().getCreatureStats(mTrackingPtr).getDrawState() != MWMechanics::DrawState_Nothing; bool standingStill = speed == 0 && !combat && !mFirstPersonView; @@ -356,12 +397,7 @@ namespace MWRender void Camera::setYaw(float angle) { - if (angle > osg::PI) { - angle -= osg::PI*2; - } else if (angle < -osg::PI) { - angle += osg::PI*2; - } - mYaw = angle; + mYaw = Misc::normalizeAngle(angle); } void Camera::setPitch(float angle) @@ -378,27 +414,24 @@ namespace MWRender return mCameraDistance; } - void Camera::updateBaseCameraDistance(float dist, bool adjust) + void Camera::adjustCameraDistance(float delta) { - if (isFirstPerson()) - return; + if (!isFirstPerson()) + { + if(isNearest() && delta < 0.f && getMode() != Mode::Preview && getMode() != Mode::Vanity) + toggleViewMode(); + else + mBaseCameraDistance = std::min(mCameraDistance - getCameraDistanceCorrection(), mBaseCameraDistance) + delta; + } + else if (delta > 0.f) + { + toggleViewMode(); + mBaseCameraDistance = 0; + } - if (adjust) - dist += std::min(mCameraDistance - getCameraDistanceCorrection(), mBaseCameraDistance); - - mIsNearest = dist <= mNearest; - mBaseCameraDistance = osg::clampBetween(dist, mNearest, mFurthest); + mIsNearest = mBaseCameraDistance <= mNearest; + mBaseCameraDistance = osg::clampBetween(mBaseCameraDistance, mNearest, mFurthest); Settings::Manager::setFloat("third person camera distance", "Camera", mBaseCameraDistance); - setCameraDistance(); - } - - void Camera::setCameraDistance(float dist, bool adjust) - { - if (isFirstPerson()) - return; - if (adjust) - dist += mCameraDistance; - mCameraDistance = osg::clampBetween(dist, 10.f, mFurthest); } float Camera::getCameraDistanceCorrection() const @@ -414,16 +447,6 @@ namespace MWRender return pitchCorrection + speedCorrection; } - void Camera::setCameraDistance() - { - mFocalPointAdjustment = osg::Vec3d(); - if (isFirstPerson()) - return; - mCameraDistance = mBaseCameraDistance + getCameraDistanceCorrection(); - if (mDynamicCameraDistanceEnabled) - mCameraDistance = std::min(mCameraDistance, mMaxNextCameraDistance); - } - void Camera::setAnimation(NpcAnimation *anim) { mAnimation = anim; @@ -511,16 +534,8 @@ namespace MWRender return; } - mDeferredRotation.x() = -ptr.getRefData().getPosition().rot[0] - mPitch; - mDeferredRotation.z() = -ptr.getRefData().getPosition().rot[2] - mYaw; - if (mDeferredRotation.x() > osg::PI) - mDeferredRotation.x() -= 2 * osg::PI; - if (mDeferredRotation.x() < -osg::PI) - mDeferredRotation.x() += 2 * osg::PI; - if (mDeferredRotation.z() > osg::PI) - mDeferredRotation.z() -= 2 * osg::PI; - if (mDeferredRotation.z() < -osg::PI) - mDeferredRotation.z() += 2 * osg::PI; + mDeferredRotation.x() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[0] - mPitch); + mDeferredRotation.z() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[2] - mYaw); } } diff --git a/apps/openmw/mwrender/camera.hpp b/apps/openmw/mwrender/camera.hpp index f2e5c390d..b3f6026eb 100644 --- a/apps/openmw/mwrender/camera.hpp +++ b/apps/openmw/mwrender/camera.hpp @@ -73,6 +73,7 @@ namespace MWRender bool mShowCrosshairInThirdPersonMode; void updateFocalPointOffset(float duration); + void updatePosition(); float getCameraDistanceCorrection() const; osg::ref_ptr mUpdateCallback; @@ -135,17 +136,8 @@ namespace MWRender void update(float duration, bool paused=false); - /// Set base camera distance for current mode. Don't work on 1st person view. - /// \param adjust Indicates should distance be adjusted or set. - void updateBaseCameraDistance(float dist, bool adjust = false); - - /// Set camera distance for current mode. Don't work on 1st person view. - /// \param adjust Indicates should distance be adjusted or set. - /// Default distance can be restored with setCameraDistance(). - void setCameraDistance(float dist, bool adjust = false); - - /// Restore default camera distance and offset for current mode. - void setCameraDistance(); + /// Adds distDelta to the camera distance. Switches 3rd/1st person view if distance is less than limit. + void adjustCameraDistance(float distDelta); float getCameraDistance() const; @@ -153,7 +145,6 @@ namespace MWRender osg::Vec3d getFocalPoint() const; osg::Vec3d getFocalPointOffset() const; - void adjustFocalPoint(osg::Vec3d adjustment) { mFocalPointAdjustment = adjustment; } /// Stores focal and camera world positions in passed arguments void getPosition(osg::Vec3d &focal, osg::Vec3d &camera) const; diff --git a/apps/openmw/mwrender/renderingmanager.cpp b/apps/openmw/mwrender/renderingmanager.cpp index c6ac632e1..5c79a4d26 100644 --- a/apps/openmw/mwrender/renderingmanager.cpp +++ b/apps/openmw/mwrender/renderingmanager.cpp @@ -1316,82 +1316,6 @@ namespace MWRender return mTerrain->getHeightAt(pos); } - bool RenderingManager::vanityRotateCamera(const float *rot) - { - if(!mCamera->isVanityOrPreviewModeEnabled()) - return false; - - mCamera->rotateCamera(rot[0], rot[2], true); - return true; - } - - void RenderingManager::setCameraDistance(float dist, bool adjust, bool override) - { - if(!mCamera->isVanityOrPreviewModeEnabled() && !mCamera->isFirstPerson()) - { - if(mCamera->isNearest() && dist > 0.f) - mCamera->toggleViewMode(); - else if (override) - mCamera->updateBaseCameraDistance(-dist / 120.f * 10, adjust); - else - mCamera->setCameraDistance(-dist / 120.f * 10, adjust); - } - else if(mCamera->isFirstPerson() && dist < 0.f) - { - mCamera->toggleViewMode(); - if (override) - mCamera->updateBaseCameraDistance(0.f, false); - else - mCamera->setCameraDistance(0.f, false); - } - } - - void RenderingManager::resetCamera() - { - mCamera->reset(); - } - - float RenderingManager::getCameraDistance() const - { - return mCamera->getCameraDistance(); - } - - Camera* RenderingManager::getCamera() - { - return mCamera.get(); - } - - const osg::Vec3f &RenderingManager::getCameraPosition() const - { - return mCurrentCameraPos; - } - - void RenderingManager::togglePOV(bool force) - { - mCamera->toggleViewMode(force); - } - - void RenderingManager::togglePreviewMode(bool enable) - { - mCamera->togglePreviewMode(enable); - } - - bool RenderingManager::toggleVanityMode(bool enable) - { - return mCamera->toggleVanityMode(enable); - } - - void RenderingManager::allowVanityMode(bool allow) - { - mCamera->allowVanityMode(allow); - } - - void RenderingManager::changeVanityModeScale(float factor) - { - if(mCamera->isVanityOrPreviewModeEnabled()) - mCamera->updateBaseCameraDistance(-factor/120.f*10, true); - } - void RenderingManager::overrideFieldOfView(float val) { if (mFieldOfViewOverridden != true || mFieldOfViewOverride != val) diff --git a/apps/openmw/mwrender/renderingmanager.hpp b/apps/openmw/mwrender/renderingmanager.hpp index d6a0f89c3..1f6f25ace 100644 --- a/apps/openmw/mwrender/renderingmanager.hpp +++ b/apps/openmw/mwrender/renderingmanager.hpp @@ -209,17 +209,8 @@ namespace MWRender float getTerrainHeightAt(const osg::Vec3f& pos); // camera stuff - bool vanityRotateCamera(const float *rot); - void setCameraDistance(float dist, bool adjust, bool override); - void resetCamera(); - float getCameraDistance() const; - Camera* getCamera(); - const osg::Vec3f& getCameraPosition() const; - void togglePOV(bool force = false); - void togglePreviewMode(bool enable); - bool toggleVanityMode(bool enable); - void allowVanityMode(bool allow); - void changeVanityModeScale(float factor); + Camera* getCamera() { return mCamera.get(); } + const osg::Vec3f& getCameraPosition() const { return mCurrentCameraPos; } /// temporarily override the field of view with given value. void overrideFieldOfView(float val); diff --git a/apps/openmw/mwrender/viewovershoulder.cpp b/apps/openmw/mwrender/viewovershoulder.cpp index 39599bfea..799e34c99 100644 --- a/apps/openmw/mwrender/viewovershoulder.cpp +++ b/apps/openmw/mwrender/viewovershoulder.cpp @@ -89,17 +89,21 @@ namespace MWRender MWBase::World* world = MWBase::Environment::get().getWorld(); osg::Vec3d sideOffset = orient * osg::Vec3d(world->getHalfExtents(mCamera->getTrackingPtr()).x() - 1, 0, 0); float rayRight = world->getDistToNearestRayHit( - playerPos + sideOffset, orient * osg::Vec3d(1, 1, 0), limitToSwitchBack + 1); + playerPos + sideOffset, orient * osg::Vec3d(1, 0, 0), limitToSwitchBack + 1); float rayLeft = world->getDistToNearestRayHit( - playerPos - sideOffset, orient * osg::Vec3d(-1, 1, 0), limitToSwitchBack + 1); - float rayForward = world->getDistToNearestRayHit( - playerPos, orient * osg::Vec3d(0, 1, 0), limitToSwitchBack + 1); + playerPos - sideOffset, orient * osg::Vec3d(-1, 0, 0), limitToSwitchBack + 1); + float rayRightForward = world->getDistToNearestRayHit( + playerPos + sideOffset, orient * osg::Vec3d(1, 3, 0), limitToSwitchBack + 1); + float rayLeftForward = world->getDistToNearestRayHit( + playerPos - sideOffset, orient * osg::Vec3d(-1, 3, 0), limitToSwitchBack + 1); + float distRight = std::min(rayRight, rayRightForward); + float distLeft = std::min(rayLeft, rayLeftForward); - if (rayLeft < limitToSwitch && rayRight > limitToSwitchBack) + if (distLeft < limitToSwitch && distRight > limitToSwitchBack) mMode = Mode::RightShoulder; - else if (rayRight < limitToSwitch && rayLeft > limitToSwitchBack) + else if (distRight < limitToSwitch && distLeft > limitToSwitchBack) mMode = Mode::LeftShoulder; - else if (rayLeft > limitToSwitchBack && rayRight > limitToSwitchBack && rayForward > limitToSwitchBack) + else if (distRight > limitToSwitchBack && distLeft > limitToSwitchBack) mMode = mDefaultShoulderIsRight ? Mode::RightShoulder : Mode::LeftShoulder; } diff --git a/apps/openmw/mwscript/miscextensions.cpp b/apps/openmw/mwscript/miscextensions.cpp index f181f665d..fdded4ce9 100644 --- a/apps/openmw/mwscript/miscextensions.cpp +++ b/apps/openmw/mwscript/miscextensions.cpp @@ -735,9 +735,9 @@ namespace MWScript effects += store.getMagicEffects(); } - for (const auto& effect : effects) + for (const auto& activeEffect : effects) { - if (effect.first.mId == key && effect.second.getModifier() > 0) + if (activeEffect.first.mId == key && activeEffect.second.getModifier() > 0) { runtime.push(1); return; diff --git a/apps/openmw/mwscript/scriptmanagerimp.cpp b/apps/openmw/mwscript/scriptmanagerimp.cpp index 8ff768c2d..e1652b311 100644 --- a/apps/openmw/mwscript/scriptmanagerimp.cpp +++ b/apps/openmw/mwscript/scriptmanagerimp.cpp @@ -149,8 +149,6 @@ namespace MWScript int count = 0; int success = 0; - const MWWorld::Store& scripts = mStore.get(); - for (auto& script : mStore.get()) { if (!std::binary_search (mScriptBlacklist.begin(), mScriptBlacklist.end(), diff --git a/apps/openmw/mwworld/class.cpp b/apps/openmw/mwworld/class.cpp index 6b8a13402..142dbc310 100644 --- a/apps/openmw/mwworld/class.cpp +++ b/apps/openmw/mwworld/class.cpp @@ -194,7 +194,12 @@ namespace MWWorld return ""; } - float Class::getSpeed (const Ptr& ptr) const + float Class::getMaxSpeed (const Ptr& ptr) const + { + return 0; + } + + float Class::getCurrentSpeed (const Ptr& ptr) const { return 0; } diff --git a/apps/openmw/mwworld/class.hpp b/apps/openmw/mwworld/class.hpp index cedb471bb..6f8304420 100644 --- a/apps/openmw/mwworld/class.hpp +++ b/apps/openmw/mwworld/class.hpp @@ -183,8 +183,15 @@ namespace MWWorld ///< Return name of the script attached to ptr (default implementation: return an empty /// string). - virtual float getSpeed (const Ptr& ptr) const; - ///< Return movement speed. + virtual float getWalkSpeed(const Ptr& ptr) const; + virtual float getRunSpeed(const Ptr& ptr) const; + virtual float getSwimSpeed(const Ptr& ptr) const; + + /// Return maximal movement speed for the current state. + virtual float getMaxSpeed(const Ptr& ptr) const; + + /// Return current movement speed. + virtual float getCurrentSpeed(const Ptr& ptr) const; virtual float getJump(const MWWorld::Ptr &ptr) const; ///< Return jump velocity (not accounting for movement) @@ -193,7 +200,7 @@ namespace MWWorld ///< Return desired movement. virtual osg::Vec3f getRotationVector (const Ptr& ptr) const; - ///< Return desired rotations, as euler angles. + ///< Return desired rotations, as euler angles. Sets getMovementSettings(ptr).mRotation to zero. virtual std::pair, bool> getEquipmentSlots (const ConstPtr& ptr) const; ///< \return first: Return IDs of the slot this object can be equipped in; second: can object @@ -375,12 +382,6 @@ namespace MWWorld virtual void setBaseAISetting(const std::string& id, MWMechanics::CreatureStats::AiSetting setting, int value) const; virtual void modifyBaseInventory(const std::string& actorId, const std::string& itemId, int amount) const; - - virtual float getWalkSpeed(const Ptr& ptr) const; - - virtual float getRunSpeed(const Ptr& ptr) const; - - virtual float getSwimSpeed(const Ptr& ptr) const; }; } diff --git a/apps/openmw/mwworld/esmstore.hpp b/apps/openmw/mwworld/esmstore.hpp index ef778470b..08d8ff71c 100644 --- a/apps/openmw/mwworld/esmstore.hpp +++ b/apps/openmw/mwworld/esmstore.hpp @@ -264,8 +264,11 @@ namespace MWWorld // To be called when we are done with dynamic record loading void checkPlayer(); + /// @return The number of instances defined in the base files. Excludes changes from the save file. int getRefCount(const std::string& id) const; + /// Actors with the same ID share spells, abilities, etc. + /// @return The shared spell list to use for this actor and whether or not it has already been initialized. std::pair, bool> getSpellList(const std::string& id) const; }; diff --git a/apps/openmw/mwworld/projectilemanager.cpp b/apps/openmw/mwworld/projectilemanager.cpp index 6ace82ea1..cc906e932 100644 --- a/apps/openmw/mwworld/projectilemanager.cpp +++ b/apps/openmw/mwworld/projectilemanager.cpp @@ -424,7 +424,7 @@ namespace MWWorld // Check for impact // TODO: use a proper btRigidBody / btGhostObject? - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castRay(pos, newPos, caster, targetActors, 0xff, MWPhysics::CollisionType_Projectile); + MWPhysics::RayCastingResult result = mPhysics->castRay(pos, newPos, caster, targetActors, 0xff, MWPhysics::CollisionType_Projectile); bool hit = false; if (result.mHit) @@ -500,7 +500,7 @@ namespace MWWorld // Check for impact // TODO: use a proper btRigidBody / btGhostObject? - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castRay(pos, newPos, caster, targetActors, 0xff, MWPhysics::CollisionType_Projectile); + MWPhysics::RayCastingResult result = mPhysics->castRay(pos, newPos, caster, targetActors, 0xff, MWPhysics::CollisionType_Projectile); bool underwater = MWBase::Environment::get().getWorld()->isUnderwater(MWMechanics::getPlayer().getCell(), newPos); diff --git a/apps/openmw/mwworld/worldimp.cpp b/apps/openmw/mwworld/worldimp.cpp index cfdf0a9c2..48cd3faac 100644 --- a/apps/openmw/mwworld/worldimp.cpp +++ b/apps/openmw/mwworld/worldimp.cpp @@ -248,7 +248,7 @@ namespace MWWorld setupPlayer(); renderPlayer(); - mRendering->resetCamera(); + mRendering->getCamera()->reset(); // we don't want old weather to persist on a new game // Note that if reset later, the initial ChangeWeather that the chargen script calls will be lost. @@ -1736,6 +1736,11 @@ namespace MWWorld return mNavigator->updateObject(DetourNavigator::ObjectId(object), shapes, object->getCollisionObject()->getWorldTransform()); } + const MWPhysics::RayCastingInterface* World::getRayCasting() const + { + return mPhysics.get(); + } + bool World::castRay (float x1, float y1, float z1, float x2, float y2, float z2) { int mask = MWPhysics::CollisionType_World | MWPhysics::CollisionType_Door; @@ -1748,7 +1753,7 @@ namespace MWWorld osg::Vec3f a(x1,y1,z1); osg::Vec3f b(x2,y2,z2); - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castRay(a, b, MWWorld::Ptr(), std::vector(), mask); + MWPhysics::RayCastingResult result = mPhysics->castRay(a, b, MWWorld::Ptr(), std::vector(), mask); return result.mHit; } @@ -2062,37 +2067,6 @@ namespace MWWorld int nightEye = static_cast(player.getClass().getCreatureStats(player).getMagicEffects().get(ESM::MagicEffect::NightEye).getMagnitude()); mRendering->setNightEyeFactor(std::min(1.f, (nightEye/100.f))); - - auto* camera = mRendering->getCamera(); - camera->setCameraDistance(); - if(!mRendering->getCamera()->isFirstPerson()) - { - float cameraObstacleLimit = mRendering->getNearClipDistance() * 2.5f; - float focalObstacleLimit = std::max(cameraObstacleLimit, 10.0f); - - // Adjust focal point. - osg::Vec3d focal = camera->getFocalPoint(); - osg::Vec3d focalOffset = camera->getFocalPointOffset(); - float offsetLen = focalOffset.length(); - if (offsetLen > 0) - { - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castSphere(focal - focalOffset, focal, focalObstacleLimit); - if (result.mHit) - { - double adjustmentCoef = -(result.mHitPos + result.mHitNormal * focalObstacleLimit - focal).length() / offsetLen; - if (adjustmentCoef < -1) - adjustmentCoef = -1; - camera->adjustFocalPoint(focalOffset * adjustmentCoef); - } - } - - // Adjust camera position. - osg::Vec3d cameraPos; - camera->getPosition(focal, cameraPos); - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castSphere(focal, cameraPos, cameraObstacleLimit); - if (result.mHit) - mRendering->getCamera()->setCameraDistance((result.mHitPos + result.mHitNormal * cameraObstacleLimit - focal).length(), false); - } } void World::preloadSpells() @@ -2183,7 +2157,7 @@ namespace MWWorld MWWorld::Ptr World::getFacedObject(float maxDistance, bool ignorePlayer) { - const float camDist = mRendering->getCameraDistance(); + const float camDist = mRendering->getCamera()->getCameraDistance(); maxDistance += camDist; MWWorld::Ptr facedObject; MWRender::RenderingManager::RayResult rayToObject; @@ -2643,7 +2617,7 @@ namespace MWWorld void World::togglePOV(bool force) { - mRendering->togglePOV(force); + mRendering->getCamera()->toggleViewMode(force); } bool World::isFirstPerson() const @@ -2658,12 +2632,12 @@ namespace MWWorld void World::togglePreviewMode(bool enable) { - mRendering->togglePreviewMode(enable); + mRendering->getCamera()->togglePreviewMode(enable); } bool World::toggleVanityMode(bool enable) { - return mRendering->toggleVanityMode(enable); + return mRendering->getCamera()->toggleVanityMode(enable); } void World::disableDeferredPreviewRotation() @@ -2678,22 +2652,21 @@ namespace MWWorld void World::allowVanityMode(bool allow) { - mRendering->allowVanityMode(allow); - } - - void World::changeVanityModeScale(float factor) - { - mRendering->changeVanityModeScale(factor); + mRendering->getCamera()->allowVanityMode(allow); } bool World::vanityRotateCamera(float * rot) { - return mRendering->vanityRotateCamera(rot); + if(!mRendering->getCamera()->isVanityOrPreviewModeEnabled()) + return false; + + mRendering->getCamera()->rotateCamera(rot[0], rot[2], true); + return true; } - void World::setCameraDistance(float dist, bool adjust, bool override_) + void World::adjustCameraDistance(float dist) { - mRendering->setCameraDistance(dist, adjust, override_); + mRendering->getCamera()->adjustCameraDistance(dist); } void World::setupPlayer() @@ -3166,7 +3139,7 @@ namespace MWWorld if (includeWater) { collisionTypes |= MWPhysics::CollisionType_Water; } - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castRay(from, to, MWWorld::Ptr(), std::vector(), collisionTypes); + MWPhysics::RayCastingResult result = mPhysics->castRay(from, to, MWWorld::Ptr(), std::vector(), collisionTypes); if (!result.mHit) return maxDist; @@ -3577,7 +3550,7 @@ namespace MWWorld actor.getClass().getCreatureStats(actor).getAiSequence().getCombatTargets(targetActors); // Check for impact, if yes, handle hit, if not, launch projectile - MWPhysics::PhysicsSystem::RayResult result = mPhysics->castRay(sourcePos, worldPos, actor, targetActors, 0xff, MWPhysics::CollisionType_Projectile); + MWPhysics::RayCastingResult result = mPhysics->castRay(sourcePos, worldPos, actor, targetActors, 0xff, MWPhysics::CollisionType_Projectile); if (result.mHit) MWMechanics::projectileHit(actor, result.mHitObject, bow, projectile, result.mHitPos, attackStrength); else @@ -4087,8 +4060,11 @@ namespace MWWorld std::string World::exportSceneGraph(const Ptr &ptr) { std::string file = mUserDataPath + "/openmw.osgt"; - mRendering->pagingBlacklistObject(mStore.find(ptr.getCellRef().getRefId()), ptr); - mWorldScene->removeFromPagedRefs(ptr); + if (!ptr.isEmpty()) + { + mRendering->pagingBlacklistObject(mStore.find(ptr.getCellRef().getRefId()), ptr); + mWorldScene->removeFromPagedRefs(ptr); + } mRendering->exportSceneGraph(ptr, file, "Ascii"); return file; } diff --git a/apps/openmw/mwworld/worldimp.hpp b/apps/openmw/mwworld/worldimp.hpp index 679f4ee4f..e1f87a8fe 100644 --- a/apps/openmw/mwworld/worldimp.hpp +++ b/apps/openmw/mwworld/worldimp.hpp @@ -516,6 +516,8 @@ namespace MWWorld void updateAnimatedCollisionShape(const Ptr &ptr) override; + const MWPhysics::RayCastingInterface* getRayCasting() const override; + bool castRay (float x1, float y1, float z1, float x2, float y2, float z2, int mask) override; ///< cast a Ray and return true if there is an object in the ray path. @@ -641,11 +643,8 @@ namespace MWWorld bool toggleVanityMode(bool enable) override; void allowVanityMode(bool allow) override; - - void changeVanityModeScale(float factor) override; - bool vanityRotateCamera(float * rot) override; - void setCameraDistance(float dist, bool adjust = false, bool override = true) override; + void adjustCameraDistance(float dist) override; void applyDeferredPreviewRotationToPlayer(float dt) override; void disableDeferredPreviewRotation() override; diff --git a/components/misc/mathutil.hpp b/components/misc/mathutil.hpp new file mode 100644 index 000000000..2f7f446b5 --- /dev/null +++ b/components/misc/mathutil.hpp @@ -0,0 +1,27 @@ +#ifndef MISC_MATHUTIL_H +#define MISC_MATHUTIL_H + +#include +#include + +namespace Misc +{ + + /// Normalizes given angle to the range [-PI, PI]. E.g. PI*3/2 -> -PI/2. + inline double normalizeAngle(double angle) + { + double fullTurns = angle / (2 * osg::PI) + 0.5; + return (fullTurns - floor(fullTurns) - 0.5) * (2 * osg::PI); + } + + /// Rotates given 2d vector counterclockwise. Angle is in radians. + inline osg::Vec2f rotateVec2f(osg::Vec2f vec, float angle) + { + float s = std::sin(angle); + float c = std::cos(angle); + return osg::Vec2f(vec.x() * c + vec.y() * -s, vec.x() * s + vec.y() * c); + } + +} + +#endif diff --git a/components/nif/nifkey.hpp b/components/nif/nifkey.hpp index 333d8a7cf..4c10327e1 100644 --- a/components/nif/nifkey.hpp +++ b/components/nif/nifkey.hpp @@ -26,11 +26,11 @@ enum InterpolationType template struct KeyT { T mValue; + T mInTan; // Only for Quadratic interpolation, and never for QuaternionKeyList + T mOutTan; // Only for Quadratic interpolation, and never for QuaternionKeyList - // FIXME: Implement Quadratic and TBC interpolation + // FIXME: Implement TBC interpolation /* - T mForwardValue; // Only for Quadratic interpolation, and never for QuaternionKeyList - T mBackwardValue; // Only for Quadratic interpolation, and never for QuaternionKeyList float mTension; // Only for TBC interpolation float mBias; // Only for TBC interpolation float mContinuity; // Only for TBC interpolation @@ -136,8 +136,8 @@ private: static void readQuadratic(NIFStream &nif, KeyT &key) { readValue(nif, key); - /*key.mForwardValue = */(nif.*getValue)(); - /*key.mBackwardValue = */(nif.*getValue)(); + key.mInTan = (nif.*getValue)(); + key.mOutTan = (nif.*getValue)(); } static void readQuadratic(NIFStream &nif, KeyT &key) diff --git a/components/nifosg/controller.cpp b/components/nifosg/controller.cpp index a4db2cba3..58f1c17a7 100644 --- a/components/nifosg/controller.cpp +++ b/components/nifosg/controller.cpp @@ -197,7 +197,6 @@ void GeomMorpherController::update(osg::NodeVisitor *nv, osg::Drawable *drawable float val = 0; if (!(*it).empty()) val = it->interpKey(input); - val = std::max(0.f, std::min(1.f, val)); SceneUtil::MorphGeometry::MorphTarget& target = morphGeom->getMorphTarget(i); if (target.getWeight() != val) diff --git a/components/nifosg/controller.hpp b/components/nifosg/controller.hpp index df1086f56..be1292359 100644 --- a/components/nifosg/controller.hpp +++ b/components/nifosg/controller.hpp @@ -110,6 +110,24 @@ namespace NifOsg { case Nif::InterpolationType_Constant: return fraction > 0.5f ? b.mValue : a.mValue; + case Nif::InterpolationType_Quadratic: + { + // Using a cubic Hermite spline. + // b1(t) = 2t^3 - 3t^2 + 1 + // b2(t) = -2t^3 + 3t^2 + // b3(t) = t^3 - 2t^2 + t + // b4(t) = t^3 - t^2 + // f(t) = a.mValue * b1(t) + b.mValue * b2(t) + a.mOutTan * b3(t) + b.mInTan * b4(t) + const float t = fraction; + const float t2 = t * t; + const float t3 = t2 * t; + const float b1 = 2.f * t3 - 3.f * t2 + 1; + const float b2 = -2.f * t3 + 3.f * t2; + const float b3 = t3 - 2.f * t2 + t; + const float b4 = t3 - t2; + return a.mValue * b1 + b.mValue * b2 + a.mOutTan * b3 + b.mInTan * b4; + } + // TODO: Implement TBC interpolation default: return a.mValue + ((b.mValue - a.mValue) * fraction); } @@ -120,6 +138,7 @@ namespace NifOsg { case Nif::InterpolationType_Constant: return fraction > 0.5f ? b.mValue : a.mValue; + // TODO: Implement Quadratic and TBC interpolation default: { osg::Quat result; diff --git a/components/nifosg/nifloader.cpp b/components/nifosg/nifloader.cpp index f88800e36..21ae49975 100644 --- a/components/nifosg/nifloader.cpp +++ b/components/nifosg/nifloader.cpp @@ -625,8 +625,8 @@ namespace NifOsg bool isAnimated = false; handleNodeControllers(nifNode, node, animflags, isAnimated); hasAnimatedParents |= isAnimated; - // Make sure empty nodes are not optimized away so the physics system can find them. - if (isAnimated || (hasAnimatedParents && (skipMeshes || hasMarkers))) + // Make sure empty nodes and animated shapes are not optimized away so the physics system can find them. + if (isAnimated || (hasAnimatedParents && ((skipMeshes || hasMarkers) || isGeometry))) node->setDataVariance(osg::Object::DYNAMIC); // LOD and Switch nodes must be wrapped by a transform (the current node) to support transformations properly diff --git a/components/sceneutil/mwshadowtechnique.cpp b/components/sceneutil/mwshadowtechnique.cpp index fa38da54e..dc22d4d80 100644 --- a/components/sceneutil/mwshadowtechnique.cpp +++ b/components/sceneutil/mwshadowtechnique.cpp @@ -749,7 +749,8 @@ MWShadowTechnique::ViewDependentData::ViewDependentData(MWShadowTechnique* vdsm) _viewDependentShadowMap(vdsm) { OSG_INFO<<"ViewDependentData::ViewDependentData()"< validRegionUniform; - std::lock_guard lock(_accessUniformsAndProgramMutex); - - for (auto uniform : _uniforms) + for (auto uniform : _uniforms[cv.getTraversalNumber() % 2]) { if (uniform->getName() == validRegionUniformName) validRegionUniform = uniform; @@ -1354,7 +1353,7 @@ void MWShadowTechnique::cull(osgUtil::CullVisitor& cv) if (!validRegionUniform) { validRegionUniform = new osg::Uniform(osg::Uniform::FLOAT_MAT4, validRegionUniformName); - _uniforms.push_back(validRegionUniform); + _uniforms[cv.getTraversalNumber() % 2].push_back(validRegionUniform); } validRegionUniform->set(validRegionMatrix); @@ -1400,7 +1399,7 @@ void MWShadowTechnique::cull(osgUtil::CullVisitor& cv) if (numValidShadows>0) { - decoratorStateGraph->setStateSet(selectStateSetForRenderingShadow(*vdd)); + decoratorStateGraph->setStateSet(selectStateSetForRenderingShadow(*vdd, cv.getTraversalNumber())); } // OSG_NOTICE<<"End of shadow setup Projection matrix "<<*cv.getProjectionMatrix()< lock(_accessUniformsAndProgramMutex); - _shadowCastingStateSet = new osg::StateSet; ShadowSettings* settings = getShadowedScene()->getShadowSettings(); @@ -1501,15 +1498,20 @@ void MWShadowTechnique::createShaders() _shadowCastingStateSet->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); - _uniforms.clear(); osg::ref_ptr baseTextureSampler = new osg::Uniform("baseTexture",(int)_baseTextureUnit); - _uniforms.push_back(baseTextureSampler.get()); - osg::ref_ptr baseTextureUnit = new osg::Uniform("baseTextureUnit",(int)_baseTextureUnit); - _uniforms.push_back(baseTextureUnit.get()); - _uniforms.push_back(new osg::Uniform("maximumShadowMapDistance", (float)settings->getMaximumShadowMapDistance())); - _uniforms.push_back(new osg::Uniform("shadowFadeStart", (float)_shadowFadeStart)); + osg::ref_ptr maxDistance = new osg::Uniform("maximumShadowMapDistance", (float)settings->getMaximumShadowMapDistance()); + osg::ref_ptr fadeStart = new osg::Uniform("shadowFadeStart", (float)_shadowFadeStart); + + for (auto& perFrameUniformList : _uniforms) + { + perFrameUniformList.clear(); + perFrameUniformList.push_back(baseTextureSampler); + perFrameUniformList.push_back(baseTextureUnit.get()); + perFrameUniformList.push_back(maxDistance); + perFrameUniformList.push_back(fadeStart); + } for(unsigned int sm_i=0; sm_igetNumShadowMapsPerLight(); ++sm_i) { @@ -1517,14 +1519,16 @@ void MWShadowTechnique::createShaders() std::stringstream sstr; sstr<<"shadowTexture"< shadowTextureSampler = new osg::Uniform(sstr.str().c_str(),(int)(settings->getBaseShadowTextureUnit()+sm_i)); - _uniforms.push_back(shadowTextureSampler.get()); + for (auto& perFrameUniformList : _uniforms) + perFrameUniformList.push_back(shadowTextureSampler.get()); } { std::stringstream sstr; sstr<<"shadowTextureUnit"< shadowTextureUnit = new osg::Uniform(sstr.str().c_str(),(int)(settings->getBaseShadowTextureUnit()+sm_i)); - _uniforms.push_back(shadowTextureUnit.get()); + for (auto& perFrameUniformList : _uniforms) + perFrameUniformList.push_back(shadowTextureUnit.get()); } } @@ -2974,24 +2978,20 @@ void MWShadowTechnique::cullShadowCastingScene(osgUtil::CullVisitor* cv, osg::Ca return; } -osg::StateSet* MWShadowTechnique::selectStateSetForRenderingShadow(ViewDependentData& vdd) const +osg::StateSet* MWShadowTechnique::selectStateSetForRenderingShadow(ViewDependentData& vdd, unsigned int traversalNumber) const { - OSG_INFO<<" selectStateSetForRenderingShadow() "< stateset = vdd.getStateSet(); + osg::ref_ptr stateset = vdd.getStateSet(traversalNumber); - std::lock_guard lock(_accessUniformsAndProgramMutex); + stateset->clear(); - vdd.getStateSet()->clear(); + stateset->setTextureAttributeAndModes(0, _fallbackBaseTexture.get(), osg::StateAttribute::ON); - vdd.getStateSet()->setTextureAttributeAndModes(0, _fallbackBaseTexture.get(), osg::StateAttribute::ON); - - for(Uniforms::const_iterator itr=_uniforms.begin(); - itr!=_uniforms.end(); - ++itr) + for(const auto& uniform : _uniforms[traversalNumber % 2]) { - OSG_INFO<<"addUniform("<<(*itr)->getName()<<")"<addUniform(itr->get()); + OSG_INFO<<"addUniform("<getName()<<")"<addUniform(uniform); } if (_program.valid()) @@ -3047,7 +3047,7 @@ osg::StateSet* MWShadowTechnique::selectStateSetForRenderingShadow(ViewDependent stateset->setTextureMode(sd._textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); } - return vdd.getStateSet(); + return stateset; } void MWShadowTechnique::resizeGLObjectBuffers(unsigned int /*maxSize*/) @@ -3104,12 +3104,12 @@ SceneUtil::MWShadowTechnique::DebugHUD::DebugHUD(int numberOfShadowMapsPerLight) fragmentShader = new osg::Shader(osg::Shader::FRAGMENT, debugFrustumFragmentShaderSource); frustumProgram->addShader(fragmentShader); - for (int i = 0; i < 2; ++i) + for (auto& frustumGeometry : mFrustumGeometries) { - mFrustumGeometries.emplace_back(new osg::Geometry()); - mFrustumGeometries[i]->setCullingActive(false); + frustumGeometry = new osg::Geometry(); + frustumGeometry->setCullingActive(false); - mFrustumGeometries[i]->getOrCreateStateSet()->setAttributeAndModes(frustumProgram, osg::StateAttribute::ON); + frustumGeometry->getOrCreateStateSet()->setAttributeAndModes(frustumProgram, osg::StateAttribute::ON); } osg::ref_ptr frustumDrawElements = new osg::DrawElementsUShort(osg::PrimitiveSet::LINE_STRIP); @@ -3145,12 +3145,14 @@ void SceneUtil::MWShadowTechnique::DebugHUD::draw(osg::ref_ptr t // It might be possible to change shadow settings at runtime if (shadowMapNumber > mDebugCameras.size()) addAnotherShadowMap(); - - mFrustumUniforms[shadowMapNumber]->set(matrix); - osg::ref_ptr stateSet = mDebugGeometry[shadowMapNumber]->getOrCreateStateSet(); + osg::ref_ptr stateSet = new osg::StateSet(); stateSet->setTextureAttributeAndModes(sDebugTextureUnit, texture, osg::StateAttribute::ON); + auto frustumUniform = mFrustumUniforms[cv.getTraversalNumber() % 2][shadowMapNumber]; + frustumUniform->set(matrix); + stateSet->addUniform(frustumUniform); + // Some of these calls may be superfluous. unsigned int traversalMask = cv.getTraversalMask(); cv.setTraversalMask(mDebugGeometry[shadowMapNumber]->getNodeMask()); @@ -3205,6 +3207,6 @@ void SceneUtil::MWShadowTechnique::DebugHUD::addAnotherShadowMap() mFrustumTransforms[shadowMapNumber]->setCullingActive(false); mDebugCameras[shadowMapNumber]->addChild(mFrustumTransforms[shadowMapNumber]); - mFrustumUniforms.push_back(new osg::Uniform(osg::Uniform::FLOAT_MAT4, "transform")); - mFrustumTransforms[shadowMapNumber]->getOrCreateStateSet()->addUniform(mFrustumUniforms[shadowMapNumber]); + for(auto& uniformVector : mFrustumUniforms) + uniformVector.push_back(new osg::Uniform(osg::Uniform::FLOAT_MAT4, "transform")); } diff --git a/components/sceneutil/mwshadowtechnique.hpp b/components/sceneutil/mwshadowtechnique.hpp index 77d0bd2b2..bdfb44e46 100644 --- a/components/sceneutil/mwshadowtechnique.hpp +++ b/components/sceneutil/mwshadowtechnique.hpp @@ -19,6 +19,7 @@ #ifndef COMPONENTS_SCENEUTIL_MWSHADOWTECHNIQUE_H #define COMPONENTS_SCENEUTIL_MWSHADOWTECHNIQUE_H 1 +#include #include #include @@ -191,7 +192,7 @@ namespace SceneUtil { ShadowDataList& getShadowDataList() { return _shadowDataList; } - osg::StateSet* getStateSet() { return _stateset.get(); } + osg::StateSet* getStateSet(unsigned int traversalNumber) { return _stateset[traversalNumber % 2].get(); } virtual void releaseGLObjects(osg::State* = 0) const; @@ -200,7 +201,7 @@ namespace SceneUtil { MWShadowTechnique* _viewDependentShadowMap; - osg::ref_ptr _stateset; + std::array, 2> _stateset; LightDataList _lightDataList; ShadowDataList _shadowDataList; @@ -230,7 +231,7 @@ namespace SceneUtil { virtual void cullShadowCastingScene(osgUtil::CullVisitor* cv, osg::Camera* camera) const; - virtual osg::StateSet* selectStateSetForRenderingShadow(ViewDependentData& vdd) const; + virtual osg::StateSet* selectStateSetForRenderingShadow(ViewDependentData& vdd, unsigned int traversalNumber) const; protected: virtual ~MWShadowTechnique(); @@ -247,8 +248,7 @@ namespace SceneUtil { osg::ref_ptr _fallbackShadowMapTexture; typedef std::vector< osg::ref_ptr > Uniforms; - mutable std::mutex _accessUniformsAndProgramMutex; - Uniforms _uniforms; + std::array _uniforms; osg::ref_ptr _program; bool _enableShadows; @@ -282,8 +282,8 @@ namespace SceneUtil { osg::ref_ptr mDebugProgram; std::vector> mDebugGeometry; std::vector> mFrustumTransforms; - std::vector> mFrustumUniforms; - std::vector> mFrustumGeometries; + std::array>, 2> mFrustumUniforms; + std::array, 2> mFrustumGeometries; }; osg::ref_ptr _debugHud; diff --git a/components/sceneutil/serialize.cpp b/components/sceneutil/serialize.cpp index 62325186c..9e7aa83f6 100644 --- a/components/sceneutil/serialize.cpp +++ b/components/sceneutil/serialize.cpp @@ -143,6 +143,7 @@ void registerSerializers() "NifOsg::GeomMorpherController", "NifOsg::UpdateMorphGeometry", "NifOsg::UVController", + "NifOsg::VisController", "NifOsg::NodeIndexHolder", "osgMyGUI::Drawable", "osg::DrawCallback", diff --git a/components/sdlutil/sdlvideowrapper.cpp b/components/sdlutil/sdlvideowrapper.cpp index c2963be86..b3ba98ee3 100644 --- a/components/sdlutil/sdlvideowrapper.cpp +++ b/components/sdlutil/sdlvideowrapper.cpp @@ -88,7 +88,37 @@ namespace SDLUtil { SDL_SetWindowSize(mWindow, width, height); SDL_SetWindowBordered(mWindow, windowBorder ? SDL_TRUE : SDL_FALSE); + + centerWindow(); } } + void VideoWrapper::centerWindow() + { + // Resize breaks the sdl window in some cases; see issue: #5539 + SDL_Rect rect{}; + int x = 0; + int y = 0; + int w = 0; + int h = 0; + auto index = SDL_GetWindowDisplayIndex(mWindow); + SDL_GetDisplayBounds(index, &rect); + SDL_GetWindowSize(mWindow, &w, &h); + + x = rect.x; + y = rect.y; + + // Center dimensions that do not fill the screen + if (w < rect.w) + { + x = rect.x + rect.w / 2 - w / 2; + } + if (h < rect.h) + { + y = rect.y + rect.h / 2 - h / 2; + } + + SDL_SetWindowPosition(mWindow, x, y); + } + } diff --git a/components/sdlutil/sdlvideowrapper.hpp b/components/sdlutil/sdlvideowrapper.hpp index 77f0b8039..3866c3ec3 100644 --- a/components/sdlutil/sdlvideowrapper.hpp +++ b/components/sdlutil/sdlvideowrapper.hpp @@ -27,6 +27,8 @@ namespace SDLUtil void setVideoMode(int width, int height, bool fullscreen, bool windowBorder); + void centerWindow(); + private: SDL_Window* mWindow; osg::ref_ptr mViewer; diff --git a/docs/source/reference/modding/settings/camera.rst b/docs/source/reference/modding/settings/camera.rst index 8d7078905..1025a2fbd 100644 --- a/docs/source/reference/modding/settings/camera.rst +++ b/docs/source/reference/modding/settings/camera.rst @@ -160,7 +160,7 @@ auto switch shoulder This setting makes difference only in third person mode if 'view over shoulder' is enabled. When player is close to an obstacle, automatically switches camera to the shoulder that is farther away from the obstacle. -This setting can only be configured by editing the settings configuration file. +This setting can be controlled in Advanced tab of the launcher. zoom out when move coef ----------------------- @@ -181,9 +181,10 @@ preview if stand still :Range: True/False :Default: False +Makes difference only in third person mode. If enabled then the character rotation is not synchonized with the camera rotation while the character doesn't move and not in combat mode. -This setting can only be configured by editing the settings configuration file. +This setting can be controlled in Advanced tab of the launcher. deferred preview rotation ------------------------- @@ -196,5 +197,5 @@ Makes difference only in third person mode. If enabled then the character smoothly rotates to the view direction after exiting preview or vanity mode. If disabled then the camera rotates rather than the character. -This setting can only be configured by editing the settings configuration file. +This setting can be controlled in Advanced tab of the launcher. diff --git a/docs/source/reference/modding/settings/game.rst b/docs/source/reference/modding/settings/game.rst index 5291fb0ed..46bd22e50 100644 --- a/docs/source/reference/modding/settings/game.rst +++ b/docs/source/reference/modding/settings/game.rst @@ -327,7 +327,18 @@ Affects side and diagonal movement. Enabling this setting makes movement more re If disabled then the whole character's body is pointed to the direction of view. Diagonal movement has no special animation and causes sliding. -If enabled then the character turns lower body to the direction of movement. Upper body is turned partially. Head is always pointed to the direction of view. In combat mode it works only for diagonal movement. In non-combat mode it also changes straight right and straight left movement. +If enabled then the character turns lower body to the direction of movement. Upper body is turned partially. Head is always pointed to the direction of view. In combat mode it works only for diagonal movement. In non-combat mode it changes straight right and straight left movement as well. Also turns the whole body up or down when swimming according to the movement direction. + +This setting can be controlled in Advanced tab of the launcher. + +swim upward correction +---------------- + +:Type: boolean +:Range: True/False +:Default: False + +Makes player swim a bit upward from the line of sight. Applies only in third person mode. Intended to make simpler swimming without diving. This setting can be controlled in Advanced tab of the launcher. @@ -336,9 +347,10 @@ swim upward coef :Type: floating point :Range: -1.0 to 1.0 -:Default: 0.0 +:Default: 0.2 -Makes player swim a bit upward (or downward in case of negative value) from the line of sight. Intended to make simpler swimming without diving. Recommened range of values is from 0.0 to 0.2. +Regulates strength of the "swim upward correction" effect (if enabled). +Makes player swim a bit upward (or downward in case of negative value) from the line of sight. Recommened range of values is from 0.0 to 0.25. This setting can only be configured by editing the settings configuration file. diff --git a/files/settings-default.cfg b/files/settings-default.cfg index 65e72c177..ac5433f30 100644 --- a/files/settings-default.cfg +++ b/files/settings-default.cfg @@ -325,8 +325,11 @@ uncapped damage fatigue = false # Turn lower body to movement direction. 'true' makes diagonal movement more realistic. turn to movement direction = false -# Makes player swim a bit upward (or downward in case of negative value) from the line of sight. -swim upward coef = 0.0 +# Makes player swim a bit upward from the line of sight. +swim upward correction = false + +# Strength of the 'swim upward correction' effect (if enabled). +swim upward coef = 0.2 # Make the training skills proposed by a trainer based on its base attribute instead of its modified ones trainers training skills based on base skill = false diff --git a/files/ui/advancedpage.ui b/files/ui/advancedpage.ui index 08ffe10ce..9084a7aba 100644 --- a/files/ui/advancedpage.ui +++ b/files/ui/advancedpage.ui @@ -2,89 +2,148 @@ AdvancedPage + + + 0 + 0 + 617 + 487 + + - - QTabWidget::West - 0 - Game mechanics + Game Mechanics - - - <html><head/><body><p>This setting causes the behavior of the sneak key (bound to Ctrl by default) to toggle sneaking on and off rather than requiring the key to be held down while sneaking. Players that spend significant time sneaking may find the character easier to control with this option enabled. </p></body></html> - - - Toggle sneak - - - - - - - <html><head/><body><p>If this setting is true, the player is allowed to loot actors (e.g. summoned creatures) during death animation, if they are not in combat. In this case we have to increment death counter and run disposed actor's script instantly.</p><p>If this setting is false, player has to wait until end of death animation in all cases. Makes using of summoned creatures exploit (looting summoned Dremoras and Golden Saints for expensive weapons) a lot harder. Conflicts with mannequin mods, which use SkipAnim to prevent end of death animation.</p></body></html> - - - Can loot during death animation - - - - - - - <html><head/><body><p>Make player followers and escorters start combat with enemies who have started combat with them or the player. Otherwise they wait for the enemies or the player to do an attack first.</p></body></html> - - - Followers defend immediately - - - - - - - <html><head/><body><p>Make the value of filled soul gems dependent only on soul magnitude.</p></body></html> - - - Soulgem values rebalance - - - - - - - <html><head/><body><p>Make enchanted weaponry without Magical flag bypass normal weapons resistance, like in Morrowind.</p></body></html> - - - Enchanted weapons are magical - - - - - - - <html><head/><body><p>Make disposition change of merchants caused by trading permanent.</p></body></html> - - - Permanent barter disposition changes - - - - - - - <html><head/><body><p>Effects of reflected Absorb spells are not mirrored -- like in Morrowind.</p></body></html> - - - Classic reflected Absorb spells behavior - - + + + + + <html><head/><body><p>Make enchanted weaponry without Magical flag bypass normal weapons resistance, like in Morrowind.</p></body></html> + + + Enchanted weapons are magical + + + + + + + <html><head/><body><p>Makes player swim a bit upward from the line of sight. Applies only in third person mode. Intended to make simpler swimming without diving.</p></body></html> + + + Swim upward correction + + + + + + + <html><head/><body><p>Enable navigator. When enabled background threads are started to build nav mesh for world geometry. Pathfinding system uses nav mesh to build paths. When disabled only pathgrid is used to build paths. Single-core CPU systems may have big performance impact on exiting interior location and moving across exterior world. May slightly affect performance on multi-core CPU systems. Multi-core CPU systems may have different latency for nav mesh update depending on other settings and system performance. Moving across external world, entering/exiting location produce nav mesh update. NPC and creatures may not be able to find path before nav mesh is built around them. Try to disable this if you want to have old fashioned AI which doesn’t know where to go when you stand behind that stone and casting a firebolt.</p></body></html> + + + Build nav mesh for world geometry + + + + + + + <html><head/><body><p>This setting causes the behavior of the sneak key (bound to Ctrl by default) to toggle sneaking on and off rather than requiring the key to be held down while sneaking. Players that spend significant time sneaking may find the character easier to control with this option enabled. </p></body></html> + + + Toggle sneak + + + + + + + <html><head/><body><p>Make disposition change of merchants caused by trading permanent.</p></body></html> + + + Permanent barter disposition changes + + + + + + + <html><head/><body><p>Don't use race weight in NPC movement speed calculations.</p></body></html> + + + Racial variation in speed fix + + + + + + + <html><head/><body><p>Make Damage Fatigue magic effect uncapped like Drain Fatigue effect.</p><p>This means that unlike Morrowind you will be able to knock down actors using this effect.</p></body></html> + + + Uncapped Damage Fatigue + + + + + + + <html><head/><body><p>If this setting is true, the player is allowed to loot actors (e.g. summoned creatures) during death animation, if they are not in combat. In this case we have to increment death counter and run disposed actor's script instantly.</p><p>If this setting is false, player has to wait until end of death animation in all cases. Makes using of summoned creatures exploit (looting summoned Dremoras and Golden Saints for expensive weapons) a lot harder. Conflicts with mannequin mods, which use SkipAnim to prevent end of death animation.</p></body></html> + + + Can loot during death animation + + + + + + + <html><head/><body><p>Make the value of filled soul gems dependent only on soul magnitude.</p></body></html> + + + Soulgem values rebalance + + + + + + + <html><head/><body><p>Make player followers and escorters start combat with enemies who have started combat with them or the player. Otherwise they wait for the enemies or the player to do an attack first.</p></body></html> + + + Followers defend immediately + + + + + + + <html><head/><body><p>Effects of reflected Absorb spells are not mirrored -- like in Morrowind.</p></body></html> + + + Classic reflected Absorb spells behavior + + + + + + + <html><head/><body><p>Make stealing items from NPCs that were knocked down possible during combat.</p></body></html> + + + Always allow stealing from knocked out actors + + + + @@ -97,78 +156,62 @@ - - - <html><head/><body><p>Make Damage Fatigue magic effect uncapped like Drain Fatigue effect.</p><p>This means that unlike Morrowind you will be able to knock down actors using this effect.</p></body></html> - - - Uncapped Damage Fatigue - - - - - - - <html><head/><body><p>Don't use race weight in NPC movement speed calculations.</p></body></html> - - - Racial variation in speed fix - - - - - - - <html><head/><body><p>Factor strength into hand-to-hand damage calculations, as the MCP formula: damage * (strength / 40).</p><p>The default value is Off.</p></body></html> - - - - + + + + + Factor strength into hand-to-hand combat: + + + + + + + 0 + + - Factor strength into hand-to-hand combat: + Off - - - - - - 0 + + + + Affect werewolves - - - Off - - - - - Affect werewolves - - - - - Do not affect werewolves - - - - - - + + + + Do not affect werewolves + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + - - - <html><head/><body><p>Make stealing items from NPCs that were knocked down possible during combat.</p></body></html> - - - Always allow stealing from knocked out actors - - - - - + Qt::Vertical + + + 20 + 40 + + @@ -179,73 +222,206 @@ - - - <html><head/><body><p>Normally environment map reflections aren't affected by lighting, which makes environment-mapped (and thus bump-mapped objects) glow in the dark. + + + + + <html><head/><body><p>Affects side and diagonal movement. Enabling this setting makes movement more realistic.</p><p>If disabled then the whole character's body is pointed to the direction of view. Diagonal movement has no special animation and causes sliding.</p><p>If enabled then the character turns lower body to the direction of movement. Upper body is turned partially. Head is always pointed to the direction of view. In combat mode it works only for diagonal movement. In non-combat mode it changes straight right and straight left movement as well. Also turns the whole body up or down when swimming according to the movement direction.</p></body></html> + + + Turn to movement direction + + + + + + + <html><head/><body><p>If true, use paging and LOD algorithms to display the entire terrain. If false, only display terrain of the loaded cells.</p></body></html> + + + Distant land + + + + + + + <html><head/><body><p>See 'auto use object normal maps'. Affects terrain.</p></body></html> + + + Auto use terrain normal maps + + + + + + + <html><head/><body><p>If a file with pattern 'terrain specular map pattern' exists, use that file as a 'diffuse specular' map. The texture must contain the layer colour in the RGB channel (as usual), and a specular multiplier in the alpha channel.</p></body></html> + + + Auto use terrain specular maps + + + + + + + <html><head/><body><p>Use object paging for active cells grid.</p></body></html> + + + Active grid object paging + + + + + + + <html><head/><body><p>Use casting animations for magic items, just as for spells.</p></body></html> + + + Use magic item animation + + + + + + + <html><head/><body><p>Load per-group KF-files and skeleton files from Animations folder</p></body></html> + + + Use additional animation sources + + + + + + + <html><head/><body><p>If this option is enabled, normal maps are automatically recognized and used if they are named appropriately +(see 'normal map pattern', e.g. for a base texture foo.dds, the normal map texture would have to be named foo_n.dds). +If this option is disabled, normal maps are only used if they are explicitly listed within the mesh file (.nif or .osg file). Affects objects.</p></body></html> + + + Auto use object normal maps + + + + + + + <html><head/><body><p>Normally environment map reflections aren't affected by lighting, which makes environment-mapped (and thus bump-mapped objects) glow in the dark. Morrowind Code Patch includes an option to remedy that by doing environment-mapping before applying lighting, this is the equivalent of that option. Affected objects will use shaders. </p></body></html> - - - Bump/reflect map local lighting - - + + + Bump/reflect map local lighting + + + + + + + + + Viewing distance + + + + + + + Cells + + + 0.000000000000000 + + + 0.500000000000000 + + + + + + + + + <html><head/><body><p>If this option is enabled, specular maps are automatically recognized and used if they are named appropriately +(see 'specular map pattern', e.g. for a base texture foo.dds, +the specular map texture would have to be named foo_spec.dds). +If this option is disabled, normal maps are only used if they are explicitly listed within the mesh file +(.osg file, not supported in .nif files). Affects objects.</p></body></html> + + + Auto use object specular maps + + + + + + + <html><head/><body><p>By default, the fog becomes thicker proportionally to your distance from the clipping plane set at the clipping distance, which causes distortion at the edges of the screen. +This setting makes the fog use the actual eye point distance (or so called Euclidean distance) to calculate the fog, which makes the fog look less artificial, especially if you have a wide FOV.</p></body></html> + + + Radial fog + + + + - - - <html><head/><body><p>Use casting animations for magic items, just as for spells.</p></body></html> + + + 20 - - Use magic item animation - - + + + + false + + + <html><head/><body><p>Render holstered weapons (with quivers and scabbards), requires modded assets.</p></body></html> + + + Weapon sheathing + + + + + + + false + + + <html><head/><body><p>Render holstered shield, requires modded assets.</p></body></html> + + + Shield sheathing + + + + - - - <html><head/><body><p>Load per-group KF-files and skeleton files from Animations folder</p></body></html> + + + Qt::Vertical - - Use additional animation sources + + + 20 + 40 + - - - - - - - 20 - - - - - false - - - <html><head/><body><p>Render holstered weapons (with quivers and scabbards), requires modded assets.</p></body></html> - - - Weapon sheathing - - - - - - - false - - - <html><head/><body><p>Render holstered shield, requires modded assets.</p></body></html> - - - Shield sheathing - - - - - + + + + + + Camera + + @@ -259,80 +435,175 @@ True: In non-combat mode camera is positioned behind the character's shoulder. C - + - <html><head/><body><p>Affects side and diagonal movement. Enabling this setting makes movement more realistic.</p><p>If disabled then the whole character's body is pointed to the direction of view. Diagonal movement has no special animation and causes sliding.</p><p>If enabled then the character turns lower body to the direction of movement. Upper body is turned partially. Head is always pointed to the direction of view. In combat mode it works only for diagonal movement. In non-combat mode it also changes straight right and straight left movement.</p></body></html> + <html><head/><body><p>When player is close to an obstacle, automatically switches camera to the shoulder that is farther away from the obstacle.</p></body></html> - Turn to movement direction + Auto switch shoulder - + + + 20 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Default shoulder: + + + + + + + 0 + + + + Right + + + + + Left + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + - <html><head/><body><p>If true, use paging and LOD algorithms to display the entire terrain. If false, only display terrain of the loaded cells.</p></body></html> + <html><head/><body><p>If enabled then the character rotation is not synchonized with the camera rotation while the character doesn't move and not in combat mode.</p></body></html> - Distant land + Preview if stand still - + - <html><head/><body><p>Use object paging for active cells grid.</p></body></html> + <html><head/><body><p>If enabled then the character smoothly rotates to the view direction after exiting preview or vanity mode. If disabled then the camera rotates rather than the character.</p></body></html> - Active grid object paging + Deferred preview rotation - - - - <html><head/><body><p>This value controls the maximum visible distance (in cell units). -Larger values significantly improve rendering in exterior spaces, -but also increase the amount of rendered geometry and significantly reduce the frame rate.</p></body></html> - - - - - - Viewing distance - - - - - - - 0.0 - - - 0.5 - - - Cells - - - - - - Qt::Vertical + + + 0 + 0 + + - + - Interface changes + Interface + + + + + + Show owned: + + + + + + + 1 + + + + Off + + + + + Tool Tip Only + + + + + Crosshair Only + + + + + Tool Tip and Crosshair + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + @@ -383,61 +654,24 @@ but also increase the amount of rendered geometry and significantly reduce the f - - - - <html><head/><body><p>Enable visual clues for items owned by NPCs when the crosshair is on the object.</p><p>The default value is Off.</p></body></html> - - - - - - Show owned: - - - - - - - 1 - - - - Off - - - - - Tool Tip Only - - - - - Crosshair Only - - - - - Tool Tip and Crosshair - - - - - - - - + Qt::Vertical + + + 20 + 40 + + - Bug fixes + Bug Fixes @@ -465,6 +699,12 @@ but also increase the amount of rendered geometry and significantly reduce the f Qt::Vertical + + + 0 + 0 + + @@ -490,28 +730,23 @@ but also increase the amount of rendered geometry and significantly reduce the f - - - - <html><head/><body><p>This setting determines how many quicksave and autosave slots you can have at a time. If greater than 1, quicksaves will be sequentially created each time you quicksave. Once the maximum number of quicksaves has been reached, the oldest quicksave will be recycled the next time you perform a quicksave.</p></body></html> - - - - - - Maximum Quicksaves - - - - - - - 1 - - - - - + + + + + + Maximum Quicksaves + + + + + + + 1 + + + + @@ -522,40 +757,35 @@ but also increase the amount of rendered geometry and significantly reduce the f Other - - - - <html><head/><body><p>Specify the format for screen shots taken by pressing the screen shot key (bound to F12 by default). This setting should be the file extension commonly associated with the desired format. The formats supported will be determined at compilation, but “jpg”, “png”, and “tga” should be allowed.</p></body></html> - - - - + + + + + + Screenshot Format + + + + + + - Screenshot Format + JPG - - - - - - - JPG - - - - - PNG - - - - - TGA - - - - - - + + + + PNG + + + + + TGA + + + + + @@ -565,6 +795,12 @@ but also increase the amount of rendered geometry and significantly reduce the f Qt::Vertical + + + 0 + 0 + + @@ -618,6 +854,12 @@ but also increase the amount of rendered geometry and significantly reduce the f QSizePolicy::Fixed + + + 0 + 0 + + @@ -662,6 +904,12 @@ but also increase the amount of rendered geometry and significantly reduce the f Qt::Vertical + + + 0 + 0 + +