Files
claudeandClaude Opus 5.5 4e152c7c4e Add active blocking for NPCs and creatures
With real time combat and the new [Game] 'ai active blocking' setting
(on by default), NPCs and creatures block through the same stance and
arc rules as the player instead of the classic roll.

In combat, an actor with a shield ready and its weapon drawn raises the
stance when an enemy in front of it winds up a melee attack within
reach. Whether it reacts is rolled once per wind-up (10% at 0 Block
skill and agility, up to 90%, scaled by fatigue), and its reaction
delay falls from 0.6 s to 0.15 s with skill. It keeps the block up for
half a second after the wind-up ends so it catches the swing, drops it
after two seconds at most so a held wind-up can't pin it, and starts
no attacks while blocking.

The decision lives in mwmechanics/aiblock.cpp. Combat AI sets a
separate, unsaved CreatureStats flag that is cleared every frame before
AI runs, so a block never outlives the combat package and a Lua block
request is left alone. Actors without a shield never block, and a
creature blocks only if it can carry a shield.

Closes #20

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 04:31:38 -05:00

181 lines
6.5 KiB
C++

#include "aiblock.hpp"
#include <algorithm>
#include <components/esm3/loadgmst.hpp>
#include <components/esm3/loadweap.hpp>
#include <components/settings/values.hpp>
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/world.hpp"
#include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp"
#include "../mwworld/inventorystore.hpp"
#include "activeblock.hpp"
#include "combat.hpp"
#include "creaturestats.hpp"
#include "weapontype.hpp"
#include <components/misc/rng.hpp>
namespace MWMechanics
{
namespace
{
// Same weighting as the classic block roll: Block skill plus a fifth of agility, as a 0..1 fraction.
float blockTerm(float blockSkill, float agility)
{
return std::clamp((std::max(blockSkill, 0.f) + 0.2f * std::max(agility, 0.f)) / 100.f, 0.f, 1.2f);
}
// Melee threats are noticed a little before the attacker is in reach, since it may step in while swinging.
constexpr float sThreatReachMult = 1.5f;
}
float getAiBlockChance(float blockSkill, float agility, float fatigueTerm)
{
const float chance = std::min(0.1f + 0.7f * blockTerm(blockSkill, agility), 0.9f);
return chance * std::clamp(fatigueTerm, 0.f, 1.f);
}
float getAiBlockReactionTime(float blockSkill, float agility)
{
return 0.6f - 0.45f * std::min(blockTerm(blockSkill, agility), 1.f);
}
bool updateAiBlock(AiBlockState& state, bool canBlock, bool threatened, float duration,
const std::function<float()>& roll, const AiBlockParams& params)
{
state.mCooldown = std::max(0.f, state.mCooldown - duration);
if (!canBlock)
{
state.mBlocking = false;
state.mDecided = false;
state.mWillBlock = false;
return false;
}
if (state.mBlocking)
{
state.mBlockTime += duration;
if (threatened)
state.mTimer = params.mHoldTime;
else
state.mTimer -= duration;
const bool tooLong = state.mBlockTime >= params.mMaxBlockTime;
if (state.mTimer <= 0.f || tooLong)
{
state.mBlocking = false;
state.mWillBlock = false;
// Don't roll again for a wind-up that is still going on.
state.mDecided = threatened;
if (tooLong)
state.mCooldown = params.mRetryDelay;
}
return state.mBlocking;
}
if (!threatened)
{
state.mDecided = false;
state.mWillBlock = false;
return false;
}
if (!state.mDecided)
{
if (state.mCooldown > 0.f)
return false;
state.mDecided = true;
state.mWillBlock = roll() < params.mChance;
state.mTimer = params.mReactionTime;
}
else if (state.mWillBlock)
state.mTimer -= duration;
if (state.mWillBlock && state.mTimer <= 0.f)
{
state.mBlocking = true;
state.mBlockTime = 0.f;
state.mTimer = params.mHoldTime;
}
return state.mBlocking;
}
bool usesAiActiveBlocking()
{
return Settings::game().mRealTimeCombat && Settings::game().mAiActiveBlocking;
}
bool isMeleeThreat(const MWWorld::Ptr& blocker, const MWWorld::Ptr& attacker)
{
if (attacker.isEmpty() || !attacker.getClass().isActor() || !blocker.getRefData().getBaseNode())
return false;
const CreatureStats& stats = attacker.getClass().getCreatureStats(attacker);
if (stats.isDead() || stats.getDrawState() != DrawState::Weapon)
return false;
if (!MWBase::Environment::get().getMechanicsManager()->isAttackPreparing(attacker))
return false;
MWWorld::Ptr weapon;
if (attacker.getClass().hasInventoryStore(attacker))
{
MWWorld::InventoryStore& inv = attacker.getClass().getInventoryStore(attacker);
const auto item = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
if (item != inv.end() && item->getType() == ESM::Weapon::sRecordId)
{
const ESM::Weapon* record = item->get<ESM::Weapon>()->mBase;
if (getWeaponType(record->mData.mType)->mWeaponClass != ESM::WeaponType::Melee)
return false;
weapon = *item;
}
}
const float reach = getMeleeWeaponReach(attacker, weapon) * sThreatReachMult;
if (getDistanceToBounds(attacker, blocker) > reach)
return false;
const MWWorld::Store<ESM::GameSetting>& gmst
= MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>();
static const float fCombatBlockLeftAngle = gmst.find("fCombatBlockLeftAngle")->mValue.getFloat();
static const float fCombatBlockRightAngle = gmst.find("fCombatBlockRightAngle")->mValue.getFloat();
return isInBlockArc(getAttackAngleDegrees(attacker, blocker), fCombatBlockLeftAngle, fCombatBlockRightAngle);
}
bool canAiBlock(const MWWorld::Ptr& actor, bool busy)
{
if (busy || !usesAiActiveBlocking() || !actor.getClass().isActor())
return false;
const CreatureStats& stats = actor.getClass().getCreatureStats(actor);
return stats.getDrawState() == DrawState::Weapon && hasShieldReady(actor);
}
bool updateAiCombatBlock(
const MWWorld::Ptr& actor, const MWWorld::Ptr& target, AiBlockState& state, bool busy, float duration)
{
const bool canBlock = canAiBlock(actor, busy);
const bool threatened = canBlock && isMeleeThreat(actor, target);
AiBlockParams params;
if (canBlock)
{
const CreatureStats& stats = actor.getClass().getCreatureStats(actor);
const float skill = actor.getClass().getSkill(actor, ESM::Skill::Block);
const float agility = stats.getAttribute(ESM::Attribute::Agility).getModified();
params.mChance = getAiBlockChance(skill, agility, stats.getFatigueTerm());
params.mReactionTime = getAiBlockReactionTime(skill, agility);
}
auto& prng = MWBase::Environment::get().getWorld()->getPrng();
const bool blocking = updateAiBlock(
state, canBlock, threatened, duration, [&] { return Misc::Rng::rollProbability(prng); }, params);
actor.getClass().getCreatureStats(actor).setAiBlockHeld(blocking);
return blocking;
}
}