diff --git a/apps/openmw/CMakeLists.txt b/apps/openmw/CMakeLists.txt index 5ae7d627e9..32051831fe 100644 --- a/apps/openmw/CMakeLists.txt +++ b/apps/openmw/CMakeLists.txt @@ -104,7 +104,7 @@ add_openmw_dir (mwmechanics aicast aiescort aiface aiactivate aicombat recharge repair enchanting pathfinding pathgrid security spellcasting spellresistance disease pickpocket levelledlist combat steering obstacle autocalcspell difficultyscaling aicombataction summoning character actors objects aistate weaponpriority spellpriority weapontype spellutil - spelleffects activeblock aiblock stamina hitreaction + spelleffects activeblock aiblock stamina hitreaction movementramp ) add_openmw_dir (mwstate diff --git a/apps/openmw/mwmechanics/character.cpp b/apps/openmw/mwmechanics/character.cpp index 43054eeb6a..e34417b98b 100644 --- a/apps/openmw/mwmechanics/character.cpp +++ b/apps/openmw/mwmechanics/character.cpp @@ -50,6 +50,7 @@ #include "activeblock.hpp" #include "hitreaction.hpp" +#include "movementramp.hpp" #include "actorutil.hpp" #include "aicombataction.hpp" #include "creaturestats.hpp" @@ -2071,6 +2072,7 @@ namespace MWMechanics if (cls.isActor() && cls.getCreatureStats(mPtr).wasTeleported()) { mSmoothedSpeed = osg::Vec2f(); + mRampedMovement = osg::Vec2f(); cls.getCreatureStats(mPtr).setTeleported(false); } @@ -2154,6 +2156,11 @@ namespace MWMechanics vec.normalize(); } + if (usesMovementAcceleration()) + applyMovementAcceleration(vec, movementSettings, duration, isPlayer, !onground && !inwater && !flying); + else + mRampedMovement = osg::Vec2f(); + float effectiveRotation = rot.z(); bool canMove = cls.getMaxSpeed(mPtr) > 0; const bool turnToMovementDirection = Settings::game().mTurnToMovementDirection; @@ -2199,7 +2206,10 @@ namespace MWMechanics vec.y() *= speed; if (isKnockedOut() || isKnockedDown() || isRecovery() || isScriptedAnimPlaying()) + { vec = osg::Vec3f(); + mRampedMovement = osg::Vec2f(); + } CharacterState movestate = CharState_None; CharacterState idlestate = CharState_None; @@ -3026,6 +3036,46 @@ namespace MWMechanics return mCastingScriptedSpell || mUpperBodyState == UpperBodyState::Casting; } + void CharacterController::applyMovementAcceleration( + osg::Vec3f& vec, Movement& movementSettings, float duration, bool isPlayer, bool inAir) + { + // vec is the requested direction (x right, y forward, z up for a jump), normalized together with the jump, and + // mSpeedFactor its length capped at 1. Only the horizontal part is ramped. + constexpr float eps = 1e-4f; + const osg::Vec2f horizontal(vec.x(), vec.y()); + const float horizontalLength = horizontal.length(); + osg::Vec2f target; + if (horizontalLength > eps) + { + float requested = movementSettings.mSpeedFactor; + if (vec.z() > eps) + // A jump request (z = 1 before normalizing) shortened the horizontal part; undo that. + requested = std::min(horizontalLength / vec.z(), 1.f); + else + requested *= horizontalLength; + target = horizontal * (requested / horizontalLength); + } + + if (!isPlayer && target.length2() < eps * eps) + // NPCs and creatures stop at once, so they never overshoot a path point. + mRampedMovement = osg::Vec2f(); + else + mRampedMovement = rampMovement(mRampedMovement, target, duration, getMovementRampTimes(inAir)); + + const float ramped = mRampedMovement.length(); + if (ramped < eps) + { + mRampedMovement = osg::Vec2f(); + movementSettings.mSpeedFactor = 0.f; + vec.x() = 0.f; + vec.y() = 0.f; + return; + } + movementSettings.mSpeedFactor = ramped; + vec.x() = mRampedMovement.x() / ramped; + vec.y() = mRampedMovement.y() / ramped; + } + void CharacterController::updateBlockStancePose() { // Ashlar: hold the shield raised while in the block stance. Uses the "shield" group's diff --git a/apps/openmw/mwmechanics/character.hpp b/apps/openmw/mwmechanics/character.hpp index 0e879b29da..f7cc1bd64a 100644 --- a/apps/openmw/mwmechanics/character.hpp +++ b/apps/openmw/mwmechanics/character.hpp @@ -201,6 +201,8 @@ namespace MWMechanics bool mIsMovingBackward{ false }; osg::Vec2f mSmoothedSpeed; + // Ashlar movement acceleration: the ramped movement factor in the actor's own frame. + osg::Vec2f mRampedMovement; std::string_view getMovementBasedAttackType() const; @@ -215,6 +217,10 @@ namespace MWMechanics void refreshCurrentAnims(CharacterState idle, CharacterState movement, JumpingState jump, bool force = false); void refreshHitRecoilAnims(); void updateBlockStancePose(); + /// Ashlar movement acceleration: ramps the movement direction \a vec and the speed factor in + /// \a movementSettings towards what was requested this frame. + void applyMovementAcceleration( + osg::Vec3f& vec, Movement& movementSettings, float duration, bool isPlayer, bool inAir); void refreshJumpAnims(JumpingState jump, bool force = false); void refreshMovementAnims(CharacterState movement, bool force = false); void refreshIdleAnims(CharacterState idle, bool force = false); diff --git a/apps/openmw/mwmechanics/movementramp.cpp b/apps/openmw/mwmechanics/movementramp.cpp new file mode 100644 index 0000000000..aaf1a3ec18 --- /dev/null +++ b/apps/openmw/mwmechanics/movementramp.cpp @@ -0,0 +1,124 @@ +#include "movementramp.hpp" + +#include +#include + +#include + +namespace MWMechanics +{ + namespace + { + constexpr float sEpsilon = 1e-5f; + + float rate(float time) + { + return time > 0.f ? 1.f / time : std::numeric_limits::infinity(); + } + + // Moves a non-negative length towards zero. + float shrink(float length, float rate, float dt) + { + if (rate == std::numeric_limits::infinity()) + return 0.f; + return std::max(0.f, length - rate * dt); + } + } + + osg::Vec2f rampMovement( + const osg::Vec2f& current, const osg::Vec2f& target, float dt, const MovementRampTimes& times) + { + if (dt <= 0.f) + return current; + + const float up = rate(times.mAccelerationTime); + const float down = rate(times.mDecelerationTime); + const float targetLength = target.length(); + + if (targetLength < sEpsilon) + { + const float length = current.length(); + if (length < sEpsilon) + return osg::Vec2f(); + return current * (shrink(length, down, dt) / length); + } + + const osg::Vec2f dir = target / targetLength; + float along = current * dir; + osg::Vec2f across = current - dir * along; + + // Sideways movement left over from the old direction dies away. + const float acrossLength = across.length(); + if (acrossLength < sEpsilon) + across = osg::Vec2f(); + else + across *= shrink(acrossLength, down, dt) / acrossLength; + + float remaining = dt; + if (along < 0.f) + { + // Moving away from the target direction: slow down to zero first, then use the rest of the time. + if (down == std::numeric_limits::infinity()) + along = 0.f; + else + { + const float needed = -along / down; + if (needed >= remaining) + { + along += down * remaining; + remaining = 0.f; + } + else + { + along = 0.f; + remaining -= needed; + } + } + } + + if (remaining > 0.f) + { + if (along < targetLength) + along = up == std::numeric_limits::infinity() ? targetLength + : std::min(targetLength, along + up * remaining); + else if (along > targetLength) + along = down == std::numeric_limits::infinity() + ? targetLength + : std::max(targetLength, along - down * remaining); + } + + osg::Vec2f result = dir * along + across; + const float length = result.length(); + if (length > 1.f) + result /= length; + return result; + } + + MovementRampTimes getMovementRampTimes(bool inAir) + { + MovementRampTimes times; + times.mAccelerationTime = Settings::game().mMovementAccelerationTime; + times.mDecelerationTime = Settings::game().mMovementDecelerationTime; + if (inAir) + { + const float airControl = Settings::game().mMovementAirControl; + if (airControl <= 0.f) + { + times.mAccelerationTime = std::numeric_limits::infinity(); + times.mDecelerationTime = std::numeric_limits::infinity(); + } + else + { + // A time of 0 stays instant on the ground and in the air. + times.mAccelerationTime /= airControl; + times.mDecelerationTime /= airControl; + } + } + return times; + } + + bool usesMovementAcceleration() + { + return Settings::game().mMovementAcceleration; + } +} diff --git a/apps/openmw/mwmechanics/movementramp.hpp b/apps/openmw/mwmechanics/movementramp.hpp new file mode 100644 index 0000000000..189f9d5713 --- /dev/null +++ b/apps/openmw/mwmechanics/movementramp.hpp @@ -0,0 +1,38 @@ +#ifndef OPENMW_MECHANICS_MOVEMENTRAMP_H +#define OPENMW_MECHANICS_MOVEMENTRAMP_H + +#include + +namespace MWMechanics +{ + // Ashlar movement acceleration. With [Game] movement acceleration on, an actor's movement doesn't snap to full + // speed when a movement control is pressed or stop dead when it is released. The movement the character controller + // sends to physics ramps towards the requested movement instead. Movement is ramped in the actor's own frame + // (x to the right, y forward), so turning, by the mouse or by AI steering, is never delayed. + + struct MovementRampTimes + { + /// Seconds to go from standing to full speed. 0 or less is instant. + float mAccelerationTime = 0.15f; + /// Seconds to go from full speed to standing. 0 or less is instant. + float mDecelerationTime = 0.1f; + }; + + /// Moves \a current towards \a target over \a dt seconds. Both are movement factors in the actor's frame, with a + /// length of 0 (standing) to 1 (full speed). The part of \a current along the target direction rises at + /// 1 / acceleration time and falls at 1 / deceleration time; the part across it falls at 1 / deceleration time. + /// Reversing direction therefore slows down through zero before speeding up the other way. The result doesn't + /// depend on how \a dt is split into frames while the target stays the same. + osg::Vec2f rampMovement( + const osg::Vec2f& current, const osg::Vec2f& target, float dt, const MovementRampTimes& times); + + /// Acceleration and deceleration times from [Game] movement acceleration time and movement deceleration time, + /// scaled by [Game] movement air control when \a inAir (jumping or falling). An air control of 0 keeps the + /// movement from changing in the air. + MovementRampTimes getMovementRampTimes(bool inAir); + + /// True if [Game] movement acceleration is on. + bool usesMovementAcceleration(); +} + +#endif diff --git a/apps/openmw_tests/CMakeLists.txt b/apps/openmw_tests/CMakeLists.txt index f234c28b1a..77015293af 100644 --- a/apps/openmw_tests/CMakeLists.txt +++ b/apps/openmw_tests/CMakeLists.txt @@ -26,6 +26,7 @@ file(GLOB UNITTEST_SRC_FILES mwmechanics/testaiblock.cpp mwmechanics/teststamina.cpp mwmechanics/testhitreaction.cpp + mwmechanics/testmovementramp.cpp mwmechanics/testcombat.cpp mwscript/testscripts.cpp diff --git a/apps/openmw_tests/mwmechanics/testmovementramp.cpp b/apps/openmw_tests/mwmechanics/testmovementramp.cpp new file mode 100644 index 0000000000..386bf28ea1 --- /dev/null +++ b/apps/openmw_tests/mwmechanics/testmovementramp.cpp @@ -0,0 +1,144 @@ +#include + +#include + +#include +#include + +namespace +{ + using namespace MWMechanics; + + constexpr float sTolerance = 1e-4f; + + const MovementRampTimes sTimes{ 0.15f, 0.1f }; + const osg::Vec2f sForward(0.f, 1.f); + const osg::Vec2f sBack(0.f, -1.f); + const osg::Vec2f sRight(1.f, 0.f); + + osg::Vec2f simulate(osg::Vec2f current, const osg::Vec2f& target, float seconds, float dt, + const MovementRampTimes& times = sTimes) + { + const int steps = static_cast(seconds / dt + 0.5f); + for (int i = 0; i < steps; ++i) + current = rampMovement(current, target, dt, times); + return current; + } + + TEST(MWMechanicsMovementRampTest, rampsUpLinearlyToFullSpeed) + { + const osg::Vec2f firstFrame = rampMovement(osg::Vec2f(), sForward, 1.f / 60.f, sTimes); + EXPECT_NEAR(firstFrame.y(), (1.f / 60.f) / 0.15f, sTolerance); + EXPECT_NEAR(firstFrame.x(), 0.f, sTolerance); + + EXPECT_NEAR(simulate(osg::Vec2f(), sForward, 0.075f, 1.f / 200.f).y(), 0.5f, 1e-3f); + EXPECT_NEAR(simulate(osg::Vec2f(), sForward, 0.15f, 1.f / 200.f).y(), 1.f, 1e-3f); + // Never past the requested speed. + EXPECT_NEAR(simulate(osg::Vec2f(), sForward, 1.f, 1.f / 60.f).y(), 1.f, sTolerance); + } + + TEST(MWMechanicsMovementRampTest, rampsDownToStanding) + { + EXPECT_NEAR(rampMovement(sForward, osg::Vec2f(), 0.05f, sTimes).y(), 0.5f, sTolerance); + EXPECT_EQ(rampMovement(sForward, osg::Vec2f(), 0.1f, sTimes), osg::Vec2f()); + EXPECT_EQ(rampMovement(sForward, osg::Vec2f(), 1.f, sTimes), osg::Vec2f()); + // A diagonal slows down along its own direction. + const osg::Vec2f diagonal = osg::Vec2f(1.f, 1.f) / std::sqrt(2.f); + const osg::Vec2f half = rampMovement(diagonal, osg::Vec2f(), 0.05f, sTimes); + EXPECT_NEAR(half.length(), 0.5f, sTolerance); + EXPECT_NEAR(half.x(), half.y(), sTolerance); + } + + TEST(MWMechanicsMovementRampTest, slowingToAPartialSpeedUsesTheDecelerationRate) + { + const osg::Vec2f walk = sForward * 0.4f; + EXPECT_NEAR(rampMovement(sForward, walk, 0.03f, sTimes).y(), 0.7f, sTolerance); + EXPECT_NEAR(rampMovement(sForward, walk, 1.f, sTimes).y(), 0.4f, sTolerance); + } + + TEST(MWMechanicsMovementRampTest, reversalSlowsThroughZeroThenSpeedsUp) + { + // 0.1 s to stop, then the remaining 0.03 s accelerates backwards. + const osg::Vec2f reversed = rampMovement(sForward, sBack, 0.13f, sTimes); + EXPECT_NEAR(reversed.y(), -0.03f / 0.15f, sTolerance); + EXPECT_NEAR(reversed.x(), 0.f, sTolerance); + + // The same split into frames gives the same answer. + EXPECT_NEAR(simulate(sForward, sBack, 0.13f, 0.13f / 26.f).y(), -0.03f / 0.15f, 1e-3f); + + // Halfway through stopping it is still moving forward. + EXPECT_NEAR(rampMovement(sForward, sBack, 0.05f, sTimes).y(), 0.5f, sTolerance); + EXPECT_NEAR(simulate(sForward, sBack, 0.25f, 1.f / 120.f).y(), -1.f, 1e-3f); + } + + TEST(MWMechanicsMovementRampTest, turningNinetyDegreesBlendsBothDirections) + { + const osg::Vec2f mid = rampMovement(sForward, sRight, 0.05f, sTimes); + // Forward dies away at the deceleration rate while sideways builds at the acceleration rate. + EXPECT_NEAR(mid.y(), 0.5f, sTolerance); + EXPECT_NEAR(mid.x(), 0.05f / 0.15f, sTolerance); + + const osg::Vec2f done = simulate(sForward, sRight, 0.2f, 1.f / 60.f); + EXPECT_NEAR(done.x(), 1.f, 1e-3f); + EXPECT_NEAR(done.y(), 0.f, 1e-3f); + } + + TEST(MWMechanicsMovementRampTest, neverFasterThanFullSpeed) + { + const osg::Vec2f diagonal = osg::Vec2f(1.f, 1.f) / std::sqrt(2.f); + for (float t = 0.f; t < 0.3f; t += 0.01f) + EXPECT_LE(simulate(sForward, diagonal, t, 1.f / 100.f).length(), 1.f + sTolerance); + } + + TEST(MWMechanicsMovementRampTest, standingStillStaysStill) + { + EXPECT_EQ(rampMovement(osg::Vec2f(), osg::Vec2f(), 1.f / 60.f, sTimes), osg::Vec2f()); + } + + TEST(MWMechanicsMovementRampTest, zeroOrNegativeFrameTimeChangesNothing) + { + const osg::Vec2f current(0.2f, 0.3f); + EXPECT_EQ(rampMovement(current, sForward, 0.f, sTimes), current); + EXPECT_EQ(rampMovement(current, sForward, -1.f, sTimes), current); + } + + TEST(MWMechanicsMovementRampTest, zeroTimesAreInstant) + { + const MovementRampTimes instant{ 0.f, 0.f }; + EXPECT_EQ(rampMovement(osg::Vec2f(), sForward, 1.f / 60.f, instant), sForward); + EXPECT_EQ(rampMovement(sForward, osg::Vec2f(), 1.f / 60.f, instant), osg::Vec2f()); + const osg::Vec2f reversed = rampMovement(sForward, sBack, 1.f / 60.f, instant); + EXPECT_NEAR(reversed.y(), -1.f, sTolerance); + EXPECT_NEAR(reversed.x(), 0.f, sTolerance); + } + + TEST(MWMechanicsMovementRampTest, infiniteTimesFreezeMovement) + { + const float inf = std::numeric_limits::infinity(); + const MovementRampTimes frozen{ inf, inf }; + const osg::Vec2f current(0.f, 0.6f); + EXPECT_EQ(rampMovement(current, sBack, 0.5f, frozen), current); + EXPECT_EQ(rampMovement(current, osg::Vec2f(), 0.5f, frozen), current); + } + + class MWMechanicsMovementRampFrameRateTest : public ::testing::TestWithParam + { + }; + + TEST_P(MWMechanicsMovementRampFrameRateTest, resultDoesNotDependOnFrameRate) + { + const float dt = GetParam(); + // Samples at whole multiples of 1/30 s, so every tested rate lands on them exactly. + const float frame = 1.f / 30.f; + EXPECT_NEAR(simulate(osg::Vec2f(), sForward, 3 * frame, dt).y(), 0.1f / 0.15f, 2e-3f); + EXPECT_NEAR(simulate(osg::Vec2f(), sForward, 6 * frame, dt).y(), 1.f, 2e-3f); + EXPECT_NEAR(simulate(sForward, osg::Vec2f(), frame, dt).length(), 1.f - frame / 0.1f, 2e-3f); + EXPECT_NEAR(simulate(sForward, sBack, 6 * frame, dt).y(), -0.1f / 0.15f, 2e-3f); + const osg::Vec2f turned = simulate(sForward, sRight, frame, dt); + EXPECT_NEAR(turned.y(), 1.f - frame / 0.1f, 2e-3f); + EXPECT_NEAR(turned.x(), frame / 0.15f, 2e-3f); + } + + INSTANTIATE_TEST_SUITE_P(FrameRates, MWMechanicsMovementRampFrameRateTest, + ::testing::Values(1.f / 30.f, 1.f / 60.f, 1.f / 120.f, 1.f / 240.f)); +} diff --git a/components/settings/categories/game.hpp b/components/settings/categories/game.hpp index 097dc2206a..f2c7e20dea 100644 --- a/components/settings/categories/game.hpp +++ b/components/settings/categories/game.hpp @@ -86,6 +86,13 @@ namespace Settings makeClampSanitizerFloat(0, 1) }; SettingValue mAttackFatigueCap{ mIndex, "Game", "attack fatigue cap", makeClampSanitizerFloat(0, 1) }; SettingValue mHitReactions{ mIndex, "Game", "hit reactions" }; + SettingValue mMovementAcceleration{ mIndex, "Game", "movement acceleration" }; + SettingValue mMovementAccelerationTime{ mIndex, "Game", "movement acceleration time", + makeMaxSanitizerFloat(0) }; + SettingValue mMovementDecelerationTime{ mIndex, "Game", "movement deceleration time", + makeMaxSanitizerFloat(0) }; + SettingValue mMovementAirControl{ mIndex, "Game", "movement air control", + makeClampSanitizerFloat(0, 1) }; }; } diff --git a/docker/ashlar-run.sh b/docker/ashlar-run.sh index 9c645e66c2..546ec99262 100755 --- a/docker/ashlar-run.sh +++ b/docker/ashlar-run.sh @@ -3,7 +3,8 @@ # and saves a screenshot. Run docker/ashlar-build.sh first. # # SCENARIO=combat also loads docker/scenarios/combat, our own CC0 test content: a hostile duelist with a shield -# and blade fights the player, and block events are summarized at the end. See docs/ashlar/SCENARIOS.md. +# and blade fights the player, and block events are summarized at the end. SCENARIO=movement logs the player's +# speed as it starts, stops and reverses. See docs/ashlar/SCENARIOS.md. set -euo pipefail repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -72,6 +73,11 @@ echo "Screenshot: $run/boot.png" if [ -n "$scenario" ]; then echo "Scenario $scenario:" grep -E 'ASHLAR_COMBAT|Ashlar (block|reaction|stamina):|scripts/ashlar' "$run/stdout.log" | tail -60 || true +fi +if [ "$scenario" = movement ]; then + grep -E 'ASHLAR_MOVE .*(phase|reached|stopped)' "$run/stdout.log" || true + echo "Frames logged: $(grep -c 'ASHLAR_MOVE .* applied=' "$run/stdout.log" || true)" +elif [ -n "$scenario" ]; then echo "Player blocks: $(grep -ci 'Ashlar block: "player" blocked' "$run/stdout.log" || true)" echo "Player parries: $(grep -ci 'Ashlar block: "player" blocked .* with weapon' "$run/stdout.log" || true)" echo "NPC blocks: $(grep 'Ashlar block:' "$run/stdout.log" | grep -vci 'Ashlar block: "player" blocked' || true)" diff --git a/docker/scenarios/movement/ashlarmovement.omwscripts b/docker/scenarios/movement/ashlarmovement.omwscripts new file mode 100644 index 0000000000..1f8ca5b09f --- /dev/null +++ b/docker/scenarios/movement/ashlarmovement.omwscripts @@ -0,0 +1 @@ +PLAYER: scripts/ashlarmovement/player.lua diff --git a/docker/scenarios/movement/scripts/ashlarmovement/player.lua b/docker/scenarios/movement/scripts/ashlarmovement/player.lua new file mode 100644 index 0000000000..ad0b146230 --- /dev/null +++ b/docker/scenarios/movement/scripts/ashlarmovement/player.lua @@ -0,0 +1,86 @@ +-- Ashlar headless movement scenario (CC0). The player stands still, then runs forward, stops, runs forward again +-- and reverses. Every frame it logs the speed the engine reports (types.Actor.getCurrentSpeed, which includes the +-- [Game] movement acceleration ramp) as a share of run speed, and how far the player actually moved along its +-- facing. "applied" is how long the current control has been held, counting only frames the engine has processed. +local self = require('openmw.self') +local types = require('openmw.types') +local util = require('openmw.util') +local I = require('openmw.interfaces') +local Actor = types.Actor + +local PHASES = { + { name = 'settle', at = 0, movement = 0 }, + { name = 'forward', at = 3, movement = 1 }, + { name = 'stop', at = 5, movement = 0 }, + { name = 'forward2', at = 6, movement = 1 }, + { name = 'reverse', at = 7.5, movement = -1 }, + { name = 'done', at = 9.5, movement = 0 }, +} + +local t = 0 +local phase +local applied = 0 +local lastPos +local reachedFull +local stopped + +local function log(fmt, ...) + print('ASHLAR_MOVE ' .. string.format(fmt, ...)) +end + +local function enterPhase(p) + phase = p + applied = 0 + reachedFull, stopped = nil, nil + log('phase %s', p.name) +end + +return { + engineHandlers = { + onFrame = function(dt) + if dt <= 0 or (phase and phase.name == 'done') then + return + end + if not phase then + I.Controls.overrideMovementControls(true) + enterPhase(PHASES[1]) + end + t = t + dt + + -- What the engine did in the frames up to now. + local run = Actor.getRunSpeed(self) + local ratio = run > 0 and Actor.getCurrentSpeed(self) / run or 0 + local facing = self.rotation * util.vector3(0, 1, 0) + local along = 0 + if lastPos and dt > 0 then + along = ((self.position - lastPos) * facing) / dt / math.max(run, 1) + end + lastPos = self.position + if phase.name ~= 'settle' then + log('%s applied=%.3f speed=%.3f along=%.3f', phase.name, applied, ratio, along) + if phase.movement ~= 0 and not reachedFull and ratio > 0.99 then + reachedFull = applied + log('%s reached full speed after %.3f s', phase.name, applied) + elseif phase.movement == 0 and not stopped and ratio < 0.01 then + stopped = applied + log('%s stopped after %.3f s', phase.name, applied) + end + end + + local nextPhase = phase + for _, p in ipairs(PHASES) do + if t >= p.at then + nextPhase = p + end + end + if nextPhase ~= phase then + enterPhase(nextPhase) + end + self.controls.movement = phase.movement + self.controls.sideMovement = 0 + self.controls.run = true + self.controls.jump = false + applied = applied + dt + end, + }, +} diff --git a/docs/ashlar/SCENARIOS.md b/docs/ashlar/SCENARIOS.md index 50e2117859..fc14045b03 100644 --- a/docs/ashlar/SCENARIOS.md +++ b/docs/ashlar/SCENARIOS.md @@ -87,3 +87,32 @@ Create `docker/scenarios//ashlar.omwscripts` and its scripts under `docker/scenarios//scripts/ashlar/`. Create records at runtime with `world.createRecord` instead of shipping an `.omwaddon`, use only Game Template meshes or CC0 assets, and print lines with a distinctive prefix so the run log can be filtered. + +## `movement` + +`docker/scenarios/movement/` checks `[Game] movement acceleration`. It has only a player script, which overrides +the movement controls and runs through timed phases (seconds after the first frame): + +| Phase | Time | What happens | +|---|---|---| +| `settle` | 0 to 3 | Stands still while the game finishes loading. | +| `forward` | 3 to 5 | Runs forward from standing. | +| `stop` | 5 to 6 | Releases the controls. | +| `forward2` | 6 to 7.5 | Runs forward again. | +| `reverse` | 7.5 to 9.5 | Runs backwards without stopping first. | + +Every frame it logs a line like: + +``` +ASHLAR_MOVE forward applied=0.067 speed=0.444 along=0.000 +``` + +`applied` is how long the phase's control has been held, counting only frames the engine has already processed. +`speed` is `types.Actor.getCurrentSpeed` as a share of run speed, so it includes the ramp. `along` is the player's +measured speed along its facing, also as a share of run speed; it is 0 where something blocks the way. The script +also logs when a phase reaches full speed or stops. With the default 0.15 s acceleration time, `forward` should +report full speed after about 0.15 s, not on the first frame; with the setting off it would be the first frame. + +```bash +SCENARIO=movement BOOT_SECONDS=60 docker/ashlar-run.sh +``` diff --git a/docs/source/reference/modding/settings/game.rst b/docs/source/reference/modding/settings/game.rst index df7536f1a4..7e27007cc6 100644 --- a/docs/source/reference/modding/settings/game.rst +++ b/docs/source/reference/modding/settings/game.rst @@ -608,3 +608,48 @@ Game Settings The flinch starts when the hit's stagger is applied, so Lua's ``ignoreStagger`` attack field prevents it, as does god mode. Hit animations still play when the loaded content has them; the timing works without them. + +.. omw-setting:: + :title: movement acceleration + :type: boolean + :range: true, false + :default: true + + Ashlar setting. If enabled, an actor's movement ramps up to speed when it starts moving and slows down when it stops, + instead of reaching full speed on the first frame and stopping dead. Changing direction blends through the ramp: + reversing slows down to a stop before speeding up the other way, and movement to the side of the new direction dies + away at the deceleration rate. Movement is ramped in the actor's own frame, so turning is never delayed, and turning + on the spot is unaffected. NPCs and creatures ramp up the same way but stop at once when their movement is released, + so they never overshoot a path point. If disabled, movement behaves as in OpenMW. + + Lua scripts set the requested movement through ``self.controls``; the ramp then applies to it. + ``types.Actor.getCurrentSpeed`` returns the speed after the ramp. + + If smooth movement is also on, this ramp applies after it. + +.. omw-setting:: + :title: movement acceleration time + :type: float32 + :range: >= 0 + :default: 0.15 + + Ashlar setting. Seconds it takes to go from standing to full speed with movement acceleration on. 0 is instant. + +.. omw-setting:: + :title: movement deceleration time + :type: float32 + :range: >= 0 + :default: 0.1 + + Ashlar setting. Seconds it takes the player to go from full speed to standing with movement acceleration on. 0 is + instant. NPCs and creatures always stop at once. + +.. omw-setting:: + :title: movement air control + :type: float32 + :range: [0, 1] + :default: 0.3 + + Ashlar setting. How quickly movement can change while jumping or falling, as a share of the rate on the ground. At + 0.3, reaching full speed in the air takes 0.5 seconds with the default acceleration time. 0 keeps movement from + changing until the actor lands. diff --git a/files/settings-default.cfg b/files/settings-default.cfg index b9f9497236..fcd75d36e2 100644 --- a/files/settings-default.cfg +++ b/files/settings-default.cfg @@ -425,6 +425,22 @@ attack fatigue cap = 0.5 # and a strong blocked blow staggers the attacker. hit reactions = true +# Ashlar: movement ramps up to speed when a movement control is pressed and +# slows down when it is released, instead of snapping. Set to false for the +# classic instant start and stop. +movement acceleration = true + +# Ashlar: seconds from standing to full speed with movement acceleration on. +movement acceleration time = 0.15 + +# Ashlar: seconds from full speed to standing with movement acceleration on. +# NPCs and creatures always stop at once, so they don't overshoot their path. +movement deceleration time = 0.1 + +# Ashlar: how quickly movement can change while jumping or falling, as a +# share of the ground rate. 0 keeps movement from changing in the air. +movement air control = 0.3 + [General] # Anisotropy reduces distortion in textures at low angles (e.g. 0 to 16).