1
0
Fork 1
mirror of https://github.com/TES3MP/openmw-tes3mp.git synced 2025-01-16 05:19:55 +00:00
openmw-tes3mp/apps/openmw/mwmechanics/aicombat.cpp

927 lines
36 KiB
C++
Raw Normal View History

2013-09-25 16:01:36 +00:00
#include "aicombat.hpp"
2015-04-22 15:58:55 +00:00
#include <components/misc/rng.hpp>
2014-06-12 21:27:04 +00:00
#include <components/esm/aisequence.hpp>
2013-09-25 16:01:36 +00:00
2013-10-31 08:43:12 +00:00
#include "../mwworld/class.hpp"
#include "../mwworld/timestamp.hpp"
2014-01-29 19:29:07 +00:00
#include "../mwworld/inventorystore.hpp"
2014-02-23 19:11:05 +00:00
#include "../mwworld/esmstore.hpp"
#include "../mwworld/cellstore.hpp"
2014-01-15 20:56:55 +00:00
2013-10-31 08:43:12 +00:00
#include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp"
2014-01-15 20:56:55 +00:00
#include "../mwbase/dialoguemanager.hpp"
2015-05-12 15:40:42 +00:00
#include "../mwrender/animation.hpp"
2013-09-25 16:01:36 +00:00
#include "creaturestats.hpp"
2014-01-29 19:29:07 +00:00
#include "steering.hpp"
#include "movement.hpp"
2015-05-12 15:40:42 +00:00
#include "character.hpp" // fixme: for getActiveWeapon
2013-10-27 13:03:58 +00:00
#include "aicombataction.hpp"
#include "combat.hpp"
2013-10-27 13:03:58 +00:00
namespace
{
2014-01-17 18:33:49 +00:00
//chooses an attack depending on probability to avoid uniformity
ESM::Weapon::AttackType chooseBestAttack(const ESM::Weapon* weapon, MWMechanics::Movement &movement);
void getMinMaxAttackDuration(const MWWorld::Ptr& actor, float (*fMinMaxDurations)[2]);
2015-06-03 17:41:19 +00:00
osg::Vec3f AimDirToMovingTarget(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, const osg::Vec3f& vLastTargetPos,
float duration, int weapType, float strength);
2014-04-20 16:35:07 +00:00
2015-06-03 17:41:19 +00:00
float getZAngleToDir(const osg::Vec3f& dir)
2014-04-20 16:35:07 +00:00
{
2015-06-03 17:41:19 +00:00
return osg::RadiansToDegrees(std::atan2(dir.x(), dir.y()));
2014-04-20 16:35:07 +00:00
}
2015-06-03 17:41:19 +00:00
float getXAngleToDir(const osg::Vec3f& dir, float dirLen = 0.0f)
{
2014-04-28 12:34:49 +00:00
float len = (dirLen > 0.0f)? dirLen : dir.length();
2015-06-03 17:41:19 +00:00
return osg::RadiansToDegrees(-std::asin(dir.z() / len));
}
const float PATHFIND_Z_REACH = 50.0f;
2014-04-20 16:35:07 +00:00
// distance at which actor pays more attention to decide whether to shortcut or stick to pathgrid
const float PATHFIND_CAUTION_DIST = 500.0f;
// distance after which actor (failed previously to shortcut) will try again
const float PATHFIND_SHORTCUT_RETRY_DIST = 300.0f;
// cast up-down ray with some offset from actor position to check for pits/obstacles on the way to target;
// magnitude of pits/obstacles is defined by PATHFIND_Z_REACH
2015-06-03 17:41:19 +00:00
bool checkWayIsClear(const osg::Vec3f& from, const osg::Vec3f& to, float offsetXY)
2014-04-20 16:35:07 +00:00
{
2015-06-03 17:41:19 +00:00
if((to - from).length() >= PATHFIND_CAUTION_DIST || std::abs(from.z() - to.z()) <= PATHFIND_Z_REACH)
2014-04-20 16:35:07 +00:00
{
2015-06-03 17:41:19 +00:00
osg::Vec3f dir = to - from;
dir.z() = 0;
dir.normalize();
2014-04-20 16:35:07 +00:00
float verticalOffset = 200; // instead of '200' here we want the height of the actor
2015-06-03 17:41:19 +00:00
osg::Vec3f _from = from + dir*offsetXY + osg::Vec3f(0,0,1) * verticalOffset;
2014-04-20 16:35:07 +00:00
// cast up-down ray and find height in world space of hit
2015-06-03 17:41:19 +00:00
float h = _from.z() - MWBase::Environment::get().getWorld()->getDistToNearestRayHit(_from, osg::Vec3f(0,0,-1), verticalOffset + PATHFIND_Z_REACH + 1);
2014-04-20 16:35:07 +00:00
2015-06-03 17:41:19 +00:00
if(std::abs(from.z() - h) <= PATHFIND_Z_REACH)
2014-04-20 16:35:07 +00:00
return true;
}
return false;
}
2013-10-27 13:03:58 +00:00
}
2013-09-25 16:01:36 +00:00
namespace MWMechanics
{
/// \brief This class holds the variables AiCombat needs which are deleted if the package becomes inactive.
struct AiCombatStorage : AiTemporaryBase
{
float mTimerAttack;
float mTimerReact;
float mTimerCombatMove;
bool mReadyToAttack;
bool mAttack;
bool mFollowTarget;
bool mCombatMove;
2015-06-03 17:41:19 +00:00
osg::Vec3f mLastTargetPos;
const MWWorld::CellStore* mCell;
boost::shared_ptr<Action> mCurrentAction;
float mActionCooldown;
float mStrength;
float mMinMaxAttackDuration[3][2];
bool mMinMaxAttackDurationInitialised;
bool mForceNoShortcut;
ESM::Position mShortcutFailPos;
2015-06-03 17:41:19 +00:00
osg::Vec3f mLastActorPos;
MWMechanics::Movement mMovement;
AiCombatStorage():
mTimerAttack(0),
mTimerReact(0),
mTimerCombatMove(0),
mReadyToAttack(false),
mAttack(false),
mFollowTarget(false),
mCombatMove(false),
mLastTargetPos(0,0,0),
mCell(NULL),
mCurrentAction(),
mActionCooldown(0),
mStrength(),
mMinMaxAttackDurationInitialised(false),
mForceNoShortcut(false),
mLastActorPos(0,0,0),
mMovement(){}
};
2014-01-15 20:56:55 +00:00
AiCombat::AiCombat(const MWWorld::Ptr& actor) :
2014-06-12 21:27:04 +00:00
mTargetActorId(actor.getClass().getCreatureStats(actor).getActorId())
{}
2014-06-12 21:27:04 +00:00
2014-06-14 00:31:01 +00:00
AiCombat::AiCombat(const ESM::AiSequence::AiCombat *combat)
{
mTargetActorId = combat->mTargetActorId;
}
2014-06-12 21:27:04 +00:00
void AiCombat::init()
{
2013-09-25 16:01:36 +00:00
}
/*
* Current AiCombat movement states (as of 0.29.0), ignoring the details of the
* attack states such as CombatMove, Strike and ReadyToAttack:
*
2014-04-19 22:31:02 +00:00
* +----(within strike range)----->attack--(beyond strike range)-->follow
* | | ^ | |
* | | | | |
* pursue<---(beyond follow range)-----+ +----(within strike range)---+ |
* ^ |
* | |
* +-------------------------(beyond follow range)--------------------+
*
*
2014-04-19 22:31:02 +00:00
* Below diagram is high level only, the code detail is a little different
* (but including those detail will just complicate the diagram w/o adding much)
*
2014-04-19 22:31:02 +00:00
* +----------(same)-------------->attack---------(same)---------->follow
* | |^^ |||
* | ||| |||
* | +--(same)-----------------+|+----------(same)------------+||
* | | | ||
* | | | (in range) ||
* | <---+ (too far) | ||
* pursue<-------------------------[door open]<-----+ ||
* ^^^ | ||
* ||| | ||
* ||+----------evade-----+ | ||
* || | [closed door] | ||
* |+----> maybe stuck, check --------------> back up, check door ||
* | ^ | ^ | ^ ||
* | | | | | | ||
* | | +---+ +---+ ||
* | +-------------------------------------------------------+|
* | |
* +---------------------------(same)---------------------------------+
*
* FIXME:
*
* The new scheme is way too complicated, should really be implemented as a
* proper state machine.
*
* TODO:
*
* Use the Observer Pattern to co-ordinate attacks, provide intelligence on
* whether the target was hit, etc.
*/
bool AiCombat::execute (const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration)
2013-09-25 16:01:36 +00:00
{
// get or create temporary storage
AiCombatStorage& storage = state.get<AiCombatStorage>();
2014-01-15 20:56:55 +00:00
//General description
2014-05-26 08:14:24 +00:00
if(actor.getClass().getCreatureStats(actor).isDead())
return true;
2013-09-25 16:01:36 +00:00
MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId);
if (target.isEmpty())
return false;
if(!target.getRefData().getCount() || !target.getRefData().isEnabled() // Really we should be checking whether the target is currently registered
// with the MechanicsManager
|| target.getClass().getCreatureStats(target).isDead())
2014-01-15 20:56:55 +00:00
return true;
2014-05-26 08:14:24 +00:00
const MWWorld::Class& actorClass = actor.getClass();
2014-06-09 18:37:49 +00:00
MWBase::World* world = MWBase::Environment::get().getWorld();
2014-05-26 08:14:24 +00:00
2014-01-16 20:24:05 +00:00
//Update every frame
bool& combatMove = storage.mCombatMove;
float& timerCombatMove = storage.mTimerCombatMove;
MWMechanics::Movement& movement = storage.mMovement;
if(combatMove)
2014-01-15 20:56:55 +00:00
{
timerCombatMove -= duration;
if( timerCombatMove <= 0)
2014-01-15 20:56:55 +00:00
{
timerCombatMove = 0;
movement.mPosition[1] = movement.mPosition[0] = 0;
combatMove = false;
2014-01-15 20:56:55 +00:00
}
}
2014-05-09 10:43:24 +00:00
actorClass.getMovementSettings(actor) = movement;
2014-06-09 18:37:49 +00:00
actorClass.getMovementSettings(actor).mRotation[0] = 0;
actorClass.getMovementSettings(actor).mRotation[2] = 0;
2014-01-29 19:29:07 +00:00
if(movement.mRotation[2] != 0)
2014-01-29 19:29:07 +00:00
{
2015-06-03 17:41:19 +00:00
if(zTurn(actor, osg::DegreesToRadians(movement.mRotation[2]))) movement.mRotation[2] = 0;
}
2014-05-09 10:43:24 +00:00
if(movement.mRotation[0] != 0)
{
2015-06-03 17:41:19 +00:00
if(smoothTurn(actor, osg::DegreesToRadians(movement.mRotation[0]), 0)) movement.mRotation[0] = 0;
2014-01-29 19:29:07 +00:00
}
float attacksPeriod = 1.0f;
ESM::Weapon::AttackType attackType;
bool& attack = storage.mAttack;
bool& readyToAttack = storage.mReadyToAttack;
float& timerAttack = storage.mTimerAttack;
bool& minMaxAttackDurationInitialised = storage.mMinMaxAttackDurationInitialised;
float (&minMaxAttackDuration)[3][2] = storage.mMinMaxAttackDuration;
if(readyToAttack)
{
2015-05-12 15:40:42 +00:00
if (!minMaxAttackDurationInitialised)
{
// TODO: this must be updated when a different weapon is equipped
// TODO: it would be much easier to ask the CharacterController about the current % completion of the weapon wind-up animation
getMinMaxAttackDuration(actor, minMaxAttackDuration);
minMaxAttackDurationInitialised = true;
}
if (timerAttack < 0) attack = false;
timerAttack -= duration;
}
else
{
timerAttack = -attacksPeriod;
attack = false;
}
characterController.setAttackingOrSpell(attack);
float& actionCooldown = storage.mActionCooldown;
actionCooldown -= duration;
float& timerReact = storage.mTimerReact;
2014-01-15 20:56:55 +00:00
float tReaction = 0.25f;
if(timerReact < tReaction)
2014-01-15 20:56:55 +00:00
{
timerReact += duration;
2014-01-15 20:56:55 +00:00
return false;
}
2013-09-28 10:25:37 +00:00
2014-01-16 20:24:05 +00:00
//Update with period = tReaction
2014-05-09 10:43:24 +00:00
// Stop attacking if target is not seen
if (target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Invisibility).getMagnitude() > 0
|| target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Chameleon).getMagnitude() > 75)
{
movement.mPosition[1] = movement.mPosition[0] = 0;
return false; // TODO: run away instead of doing nothing
}
timerReact = 0;
const MWWorld::CellStore*& currentCell = storage.mCell;
bool cellChange = currentCell && (actor.getCell() != currentCell);
if(!currentCell || cellChange)
2014-04-19 22:31:02 +00:00
{
currentCell = actor.getCell();
2014-04-19 22:31:02 +00:00
}
MWRender::Animation* anim = MWBase::Environment::get().getWorld()->getAnimation(actor);
if (!anim) // shouldn't happen
return false;
actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true);
if (actionCooldown > 0)
return false;
float rangeAttack = 0;
float rangeFollow = 0;
boost::shared_ptr<Action>& currentAction = storage.mCurrentAction;
// TODO: upperBodyReady() works fine for checking if we can start an attack,
// but doesn't work properly for checking if the attack is finished (as things like hit recovery or knockdown also play on the upper body)
// Only a minor problem, but can mess with the actionCooldown timer.
// To fix this the AI needs to be brought closer to the CharacterController, so we can simply check if a weapon animation is playing.
if (anim->upperBodyReady())
{
currentAction = prepareNextAction(actor, target);
actionCooldown = currentAction->getActionCooldown();
}
if (currentAction.get())
currentAction->getCombatRange(rangeAttack, rangeFollow);
// FIXME: consider moving this stuff to ActionWeapon::getCombatRange
2014-01-15 20:56:55 +00:00
const ESM::Weapon *weapon = NULL;
2014-08-28 00:09:00 +00:00
MWMechanics::WeaponType weaptype = WeapType_None;
float weapRange = 1.0f;
2014-01-16 20:24:05 +00:00
2014-04-20 16:35:07 +00:00
// Get weapon characteristics
2014-06-09 18:37:49 +00:00
if (actorClass.hasInventoryStore(actor))
2013-09-25 16:01:36 +00:00
{
// TODO: Check equipped weapon and equip a different one if we can't attack with it
// (e.g. no ammunition, or wrong type of ammunition equipped, etc. autoEquip is not very smart in this regard))
2014-01-15 20:56:55 +00:00
//Get weapon speed and range
MWWorld::ContainerStoreIterator weaponSlot =
2014-06-09 18:37:49 +00:00
MWMechanics::getActiveWeapon(actorClass.getCreatureStats(actor), actorClass.getInventoryStore(actor), &weaptype);
2014-01-15 20:56:55 +00:00
if (weaptype == WeapType_HandToHand)
{
static float fHandToHandReach =
2014-06-09 18:37:49 +00:00
world->getStore().get<ESM::GameSetting>().find("fHandToHandReach")->getFloat();
weapRange = fHandToHandReach;
2014-01-15 20:56:55 +00:00
}
2014-08-28 00:09:00 +00:00
else if (weaptype != WeapType_PickProbe && weaptype != WeapType_Spell && weaptype != WeapType_None)
2014-01-15 20:56:55 +00:00
{
// All other WeapTypes are actually weapons, so get<ESM::Weapon> is safe.
2014-01-15 20:56:55 +00:00
weapon = weaponSlot->get<ESM::Weapon>()->mBase;
weapRange = weapon->mData.mReach;
}
weapRange *= 100.0f;
}
else //is creature
{
weaptype = actorClass.getCreatureStats(actor).getDrawState() == DrawState_Spell ? WeapType_Spell : WeapType_HandToHand;
weapRange = 150.0f; //TODO: use true attack range (the same problem in Creature::hit)
}
bool distantCombat = false;
if (weaptype != WeapType_Spell)
{
// TODO: move to ActionWeapon
if (weaptype == WeapType_BowAndArrow || weaptype == WeapType_Crossbow || weaptype == WeapType_Thrown)
{
rangeAttack = 1000;
rangeFollow = 0; // not needed in ranged combat
distantCombat = true;
}
else
{
rangeAttack = weapRange;
rangeFollow = 300;
}
}
else
{
distantCombat = (rangeAttack > 500);
weapRange = 150.f;
}
float& strength = storage.mStrength;
// start new attack
if(readyToAttack)
{
if(timerAttack <= -attacksPeriod)
{
attack = true; // attack starts just now
if (!distantCombat) attackType = chooseBestAttack(weapon, movement);
else attackType = ESM::Weapon::AT_Chop; // cause it's =0
2015-04-22 15:58:55 +00:00
strength = Misc::Rng::rollClosedProbability();
// Note: may be 0 for some animations
timerAttack = minMaxAttackDuration[attackType][0] +
(minMaxAttackDuration[attackType][1] - minMaxAttackDuration[attackType][0]) * strength;
//say a provoking combat phrase
if (actor.getClass().isNpc())
{
2014-06-09 18:37:49 +00:00
const MWWorld::ESMStore &store = world->getStore();
int chance = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->getInt();
2015-04-22 15:58:55 +00:00
if (Misc::Rng::roll0to99() < chance)
{
MWBase::Environment::get().getDialogueManager()->say(actor, "attack");
}
}
}
}
2013-09-28 10:25:37 +00:00
/*
* Some notes on meanings of variables:
*
2014-04-27 18:38:04 +00:00
* rangeAttack:
*
2014-04-27 18:38:04 +00:00
* - Distance where attack using the actor's weapon is possible:
* longer for ranged weapons (obviously?) vs. melee weapons
2014-05-09 10:43:24 +00:00
* - Determined by weapon's reach parameter; hardcoded value
2014-04-27 18:38:04 +00:00
* for ranged weapon and for creatures
* - Once within this distance mFollowTarget is triggered
*
2014-04-27 18:38:04 +00:00
* rangeFollow:
*
* - Applies to melee weapons or hand to hand only (or creatures without
* weapons)
2014-04-27 18:38:04 +00:00
* - Distance a little further away than the actor's weapon reach
* i.e. rangeFollow > rangeAttack for melee weapons
* - Hardcoded value (0 for ranged weapons)
* - Once the target gets beyond this distance mFollowTarget is cleared
* and a path to the target needs to be found
*
* mFollowTarget:
*
* - Once triggered, the actor follows the target with LOS shortcut
* (the shortcut really only applies to cells where pathgrids are
* available, since the default path without pathgrids is direct to
* target even if LOS is not achieved)
*/
2014-04-27 09:49:31 +00:00
2014-04-20 16:35:07 +00:00
ESM::Position pos = actor.getRefData().getPosition();
2015-06-03 17:41:19 +00:00
osg::Vec3f vActorPos(pos.asVec3());
osg::Vec3f vTargetPos(target.getRefData().getPosition().asVec3());
osg::Vec3f vDirToTarget = vTargetPos - vActorPos;
float distToTarget = vDirToTarget.length();
2015-06-03 17:41:19 +00:00
osg::Vec3f& lastActorPos = storage.mLastActorPos;
bool& followTarget = storage.mFollowTarget;
2013-09-28 10:25:37 +00:00
2014-04-20 16:35:07 +00:00
bool isStuck = false;
float speed = 0.0f;
if(movement.mPosition[1] && (lastActorPos - vActorPos).length() < (speed = actorClass.getSpeed(actor)) * tReaction / 2)
2014-04-20 16:35:07 +00:00
isStuck = true;
2014-01-15 20:56:55 +00:00
lastActorPos = vActorPos;
2014-04-20 16:35:07 +00:00
2014-04-27 18:38:04 +00:00
// check if actor can move along z-axis
2014-06-09 18:37:49 +00:00
bool canMoveByZ = (actorClass.canSwim(actor) && world->isSwimming(actor))
|| world->isFlying(actor);
2014-04-28 12:34:49 +00:00
// for distant combat we should know if target is in LOS even if distToTarget < rangeAttack
bool inLOS = distantCombat ? world->getLOS(actor, target) : true;
// can't fight if attacker can't go where target is. E.g. A fish can't attack person on land.
if (distToTarget >= rangeAttack
&& !actorClass.isNpc() && !MWMechanics::isEnvironmentCompatible(actor, target))
{
// TODO: start fleeing?
movement.mPosition[0] = 0;
movement.mPosition[1] = 0;
movement.mPosition[2] = 0;
readyToAttack = false;
characterController.setAttackingOrSpell(false);
return false;
}
// (within attack dist) || (not quite attack dist while following)
if(inLOS && (distToTarget < rangeAttack || (distToTarget <= rangeFollow && followTarget && !isStuck)))
2014-01-15 20:56:55 +00:00
{
//Melee and Close-up combat
// getXAngleToDir determines vertical angle to target:
// if actor can move along z-axis it will control movement dir
// if can't - it will control correct aiming.
// note: in getZAngleToDir if we preserve dir.z then horizontal angle can be inaccurate
if (distantCombat)
{
2015-06-03 17:41:19 +00:00
osg::Vec3f& lastTargetPos = storage.mLastTargetPos;
osg::Vec3f vAimDir = AimDirToMovingTarget(actor, target, lastTargetPos, tReaction, weaptype, strength);
lastTargetPos = vTargetPos;
movement.mRotation[0] = getXAngleToDir(vAimDir);
movement.mRotation[2] = getZAngleToDir(vAimDir);
}
else
{
movement.mRotation[0] = getXAngleToDir(vDirToTarget, distToTarget);
movement.mRotation[2] = getZAngleToDir(vDirToTarget);
}
2014-05-26 08:14:24 +00:00
// (not quite attack dist while following)
if (followTarget && distToTarget > rangeAttack)
2014-01-15 20:56:55 +00:00
{
//Close-up combat: just run up on target
movement.mPosition[1] = 1;
2014-01-15 20:56:55 +00:00
}
else // (within attack dist)
2014-01-15 20:56:55 +00:00
{
if(movement.mPosition[0] || movement.mPosition[1])
2014-01-15 20:56:55 +00:00
{
2015-04-22 15:58:55 +00:00
timerCombatMove = 0.1f + 0.1f * Misc::Rng::rollClosedProbability();
combatMove = true;
2014-01-15 20:56:55 +00:00
}
2014-04-27 18:38:04 +00:00
// only NPCs are smart enough to use dodge movements
2014-06-09 18:37:49 +00:00
else if(actorClass.isNpc() && (!distantCombat || (distantCombat && distToTarget < rangeAttack/2)))
2014-01-15 20:56:55 +00:00
{
//apply sideway movement (kind of dodging) with some probability
2015-04-22 15:58:55 +00:00
if (Misc::Rng::rollClosedProbability() < 0.25)
2014-01-15 20:56:55 +00:00
{
2015-04-22 15:58:55 +00:00
movement.mPosition[0] = Misc::Rng::rollProbability() < 0.5 ? 1.0f : -1.0f;
timerCombatMove = 0.05f + 0.15f * Misc::Rng::rollClosedProbability();
combatMove = true;
2014-01-15 20:56:55 +00:00
}
}
2013-09-28 10:25:37 +00:00
2014-04-27 18:38:04 +00:00
if(distantCombat && distToTarget < rangeAttack/4)
2014-01-15 20:56:55 +00:00
{
movement.mPosition[1] = -1;
2014-01-15 20:56:55 +00:00
}
readyToAttack = true;
2014-01-15 20:56:55 +00:00
//only once got in melee combat, actor is allowed to use close-up shortcutting
followTarget = true;
2014-01-15 20:56:55 +00:00
}
}
2014-04-20 16:35:07 +00:00
else // remote pathfinding
{
2014-04-20 16:35:07 +00:00
bool preferShortcut = false;
if (!distantCombat) inLOS = world->getLOS(actor, target);
2014-05-26 08:14:24 +00:00
2014-04-20 16:35:07 +00:00
// check if shortcut is available
bool& forceNoShortcut = storage.mForceNoShortcut;
ESM::Position& shortcutFailPos = storage.mShortcutFailPos;
if(inLOS && (!isStuck || readyToAttack)
2015-06-03 17:41:19 +00:00
&& (!forceNoShortcut || (shortcutFailPos.asVec3() - vActorPos).length() >= PATHFIND_SHORTCUT_RETRY_DIST))
2014-04-20 16:35:07 +00:00
{
2014-06-09 18:37:49 +00:00
if(speed == 0.0f) speed = actorClass.getSpeed(actor);
2014-04-20 16:35:07 +00:00
// maximum dist before pit/obstacle for actor to avoid them depending on his speed
2015-06-03 17:41:19 +00:00
float maxAvoidDist = tReaction * speed + speed / MAX_VEL_ANGULAR_RADIANS * 2; // *2 - for reliability
preferShortcut = checkWayIsClear(vActorPos, vTargetPos, osg::Vec3f(vDirToTarget.x(), vDirToTarget.y(), 0).length() > maxAvoidDist*1.5? maxAvoidDist : maxAvoidDist/2);
2014-04-20 16:35:07 +00:00
}
// don't use pathgrid when actor can move in 3 dimensions
if(canMoveByZ) preferShortcut = true;
if(preferShortcut)
{
2014-06-17 13:25:54 +00:00
if (canMoveByZ)
movement.mRotation[0] = getXAngleToDir(vDirToTarget, distToTarget);
movement.mRotation[2] = getZAngleToDir(vDirToTarget);
forceNoShortcut = false;
shortcutFailPos.pos[0] = shortcutFailPos.pos[1] = shortcutFailPos.pos[2] = 0;
mPathFinder.clearPath();
}
else // if shortcut failed stick to path grid
2014-04-20 16:35:07 +00:00
{
if(!isStuck && shortcutFailPos.pos[0] == 0.0f && shortcutFailPos.pos[1] == 0.0f && shortcutFailPos.pos[2] == 0.0f)
2014-04-20 16:35:07 +00:00
{
forceNoShortcut = true;
shortcutFailPos = pos;
2014-04-20 16:35:07 +00:00
}
2014-01-15 20:56:55 +00:00
followTarget = false;
2014-01-15 20:56:55 +00:00
buildNewPath(actor, target); //may fail to build a path, check before use
2014-01-15 20:56:55 +00:00
2014-04-20 16:35:07 +00:00
//delete visited path node
mPathFinder.checkPathCompleted(pos.pos[0],pos.pos[1]);
2014-04-20 16:35:07 +00:00
// This works on the borders between the path grid and areas with no waypoints.
if(inLOS && mPathFinder.getPath().size() > 1)
{
// get point just before target
std::list<ESM::Pathgrid::Point>::const_iterator pntIter = --mPathFinder.getPath().end();
2014-04-20 16:35:07 +00:00
--pntIter;
2015-06-03 17:41:19 +00:00
osg::Vec3f vBeforeTarget(PathFinder::MakeOsgVec3(*pntIter));
2014-04-20 16:35:07 +00:00
// if current actor pos is closer to target then last point of path (excluding target itself) then go straight on target
if(distToTarget <= (vTargetPos - vBeforeTarget).length())
{
movement.mRotation[2] = getZAngleToDir(vDirToTarget);
2014-04-20 16:35:07 +00:00
preferShortcut = true;
}
}
// if there is no new path, then go straight on target
if(!preferShortcut)
{
if(!mPathFinder.getPath().empty())
movement.mRotation[2] = mPathFinder.getZAngleToNext(pos.pos[0], pos.pos[1]);
2014-05-09 10:43:24 +00:00
else
movement.mRotation[2] = getZAngleToDir(vDirToTarget);
2014-04-20 16:35:07 +00:00
}
2014-02-23 07:42:40 +00:00
}
movement.mPosition[1] = 1;
if (readyToAttack)
2014-06-10 10:20:29 +00:00
{
// to stop possible sideway moving after target moved out of attack range
combatMove = true;
timerCombatMove = 0;
2014-06-10 10:20:29 +00:00
}
readyToAttack = false;
2014-01-15 20:56:55 +00:00
}
if(!isStuck && distToTarget > rangeAttack && !distantCombat)
2014-01-15 20:56:55 +00:00
{
//special run attack; it shouldn't affect melee combat tactics
2014-06-09 18:37:49 +00:00
if(actorClass.getMovementSettings(actor).mPosition[1] == 1)
2013-09-28 10:25:37 +00:00
{
/* check if actor can overcome the distance = distToTarget - attackerWeapRange
less than in time of swinging with weapon (t_swing), then start attacking
*/
2014-06-09 18:37:49 +00:00
float speed1 = actorClass.getSpeed(actor);
float speed2 = target.getClass().getSpeed(target);
if(target.getClass().getMovementSettings(target).mPosition[0] == 0
&& target.getClass().getMovementSettings(target).mPosition[1] == 0)
2014-01-15 20:56:55 +00:00
speed2 = 0;
2014-04-20 16:35:07 +00:00
float s1 = distToTarget - weapRange;
2014-01-15 20:56:55 +00:00
float t = s1/speed1;
float s2 = speed2 * t;
float t_swing =
minMaxAttackDuration[ESM::Weapon::AT_Thrust][0] +
2015-04-22 15:58:55 +00:00
(minMaxAttackDuration[ESM::Weapon::AT_Thrust][1] - minMaxAttackDuration[ESM::Weapon::AT_Thrust][0]) * Misc::Rng::rollClosedProbability();
2014-01-15 20:56:55 +00:00
if (t + s2/speed1 <= t_swing)
{
readyToAttack = true;
if(timerAttack <= -attacksPeriod)
2014-01-15 20:56:55 +00:00
{
timerAttack = t_swing;
attack = true;
2014-01-15 20:56:55 +00:00
}
}
2013-09-28 10:25:37 +00:00
}
}
2013-09-28 10:25:37 +00:00
2014-04-19 22:31:02 +00:00
// TODO: Add a parameter to vary DURATION_SAME_SPOT?
if((distToTarget > rangeAttack || followTarget) &&
2014-04-19 22:31:02 +00:00
mObstacleCheck.check(actor, tReaction)) // check if evasive action needed
{
2014-06-12 21:27:04 +00:00
// probably walking into another NPC TODO: untested in combat situation
// TODO: diagonal should have same animation as walk forward
// but doesn't seem to do that?
actor.getClass().getMovementSettings(actor).mPosition[0] = 1;
actor.getClass().getMovementSettings(actor).mPosition[1] = 0.1f;
// change the angle a bit, too
if(mPathFinder.isPathConstructed())
2015-06-03 17:41:19 +00:00
zTurn(actor, osg::DegreesToRadians(mPathFinder.getZAngleToNext(pos.pos[0] + 1, pos.pos[1])));
2014-06-12 21:27:04 +00:00
if(followTarget)
followTarget = false;
2014-06-12 21:27:04 +00:00
// FIXME: can fool actors to stay behind doors, etc.
// Related to Bug#1102 and to some degree #1155 as well
}
2014-01-15 20:56:55 +00:00
return false;
}
2013-09-28 10:25:37 +00:00
bool AiCombat::doesPathNeedRecalc(ESM::Pathgrid::Point dest, const ESM::Cell *cell)
2014-01-15 20:56:55 +00:00
{
if (!mPathFinder.getPath().empty())
{
osg::Vec3f currPathTarget(PathFinder::MakeOsgVec3(mPathFinder.getPath().back()));
osg::Vec3f newPathTarget = PathFinder::MakeOsgVec3(dest);
float dist = (newPathTarget - currPathTarget).length();
float targetPosThreshold = (cell->isExterior()) ? 300.0f : 100.0f;
return dist > targetPosThreshold;
}
else
2014-02-23 07:42:40 +00:00
{
// necessarily construct a new path
return true;
2014-02-23 07:42:40 +00:00
}
}
2013-09-28 10:25:37 +00:00
void AiCombat::buildNewPath(const MWWorld::Ptr& actor, const MWWorld::Ptr& target)
{
ESM::Pathgrid::Point newPathTarget = PathFinder::MakePathgridPoint(target.getRefData().getPosition());
2014-04-20 16:35:07 +00:00
//construct new path only if target has moved away more than on [targetPosThreshold]
if (doesPathNeedRecalc(newPathTarget, actor.getCell()->getCell()))
{
ESM::Pathgrid::Point start(PathFinder::MakePathgridPoint(actor.getRefData().getPosition()));
mPathFinder.buildSyncedPath(start, newPathTarget, actor.getCell(), false);
2013-09-25 16:01:36 +00:00
}
}
int AiCombat::getTypeId() const
{
return TypeIdCombat;
}
unsigned int AiCombat::getPriority() const
{
return 1;
2013-09-25 16:01:36 +00:00
}
2014-05-17 15:20:57 +00:00
MWWorld::Ptr AiCombat::getTarget() const
{
2014-05-17 15:20:57 +00:00
return MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId);
}
2013-09-25 16:01:36 +00:00
AiCombat *MWMechanics::AiCombat::clone() const
{
return new AiCombat(*this);
}
2014-06-12 21:27:04 +00:00
void AiCombat::writeState(ESM::AiSequence::AiSequence &sequence) const
{
std::auto_ptr<ESM::AiSequence::AiCombat> combat(new ESM::AiSequence::AiCombat());
combat->mTargetActorId = mTargetActorId;
ESM::AiSequence::AiPackageContainer package;
package.mType = ESM::AiSequence::Ai_Combat;
package.mPackage = combat.release();
sequence.mPackages.push_back(package);
}
2014-01-17 18:33:49 +00:00
}
2014-01-15 20:56:55 +00:00
2014-01-27 20:38:01 +00:00
2014-01-17 18:33:49 +00:00
namespace
{
2014-01-15 20:56:55 +00:00
ESM::Weapon::AttackType chooseBestAttack(const ESM::Weapon* weapon, MWMechanics::Movement &movement)
2014-01-17 18:33:49 +00:00
{
ESM::Weapon::AttackType attackType;
2014-01-17 18:33:49 +00:00
if (weapon == NULL)
{
//hand-to-hand deal equal damage for each type
2015-04-22 15:58:55 +00:00
float roll = Misc::Rng::rollClosedProbability();
2014-01-17 18:33:49 +00:00
if(roll <= 0.333f) //side punch
2014-01-15 20:56:55 +00:00
{
2015-04-22 15:58:55 +00:00
movement.mPosition[0] = Misc::Rng::rollClosedProbability() ? 1.0f : -1.0f;
2014-01-15 20:56:55 +00:00
movement.mPosition[1] = 0;
attackType = ESM::Weapon::AT_Slash;
2014-01-15 20:56:55 +00:00
}
2014-01-17 18:33:49 +00:00
else if(roll <= 0.666f) //forward punch
{
2014-01-15 20:56:55 +00:00
movement.mPosition[1] = 1;
attackType = ESM::Weapon::AT_Thrust;
}
2014-01-23 21:14:20 +00:00
else
{
movement.mPosition[1] = movement.mPosition[0] = 0;
attackType = ESM::Weapon::AT_Chop;
2014-01-23 21:14:20 +00:00
}
}
else
{
//the more damage attackType deals the more probability it has
int slash = (weapon->mData.mSlash[0] + weapon->mData.mSlash[1])/2;
int chop = (weapon->mData.mChop[0] + weapon->mData.mChop[1])/2;
int thrust = (weapon->mData.mThrust[0] + weapon->mData.mThrust[1])/2;
float total = static_cast<float>(slash + chop + thrust);
2015-04-22 15:58:55 +00:00
float roll = Misc::Rng::rollClosedProbability();
if(roll <= (slash/total))
{
2015-04-22 15:58:55 +00:00
movement.mPosition[0] = (Misc::Rng::rollClosedProbability() < 0.5f) ? 1.0f : -1.0f;
movement.mPosition[1] = 0;
attackType = ESM::Weapon::AT_Slash;
}
else if(roll <= (slash + (thrust/total)))
{
2014-01-15 20:56:55 +00:00
movement.mPosition[1] = 1;
attackType = ESM::Weapon::AT_Thrust;
}
2014-01-23 21:14:20 +00:00
else
{
movement.mPosition[1] = movement.mPosition[0] = 0;
attackType = ESM::Weapon::AT_Chop;
2014-01-23 21:14:20 +00:00
}
}
return attackType;
}
void getMinMaxAttackDuration(const MWWorld::Ptr& actor, float (*fMinMaxDurations)[2])
{
if (!actor.getClass().hasInventoryStore(actor)) // creatures
{
fMinMaxDurations[0][0] = fMinMaxDurations[0][1] = 0.1f;
fMinMaxDurations[1][0] = fMinMaxDurations[1][1] = 0.1f;
fMinMaxDurations[2][0] = fMinMaxDurations[2][1] = 0.1f;
2014-01-17 18:33:49 +00:00
return;
}
// get weapon information: type and speed
const ESM::Weapon *weapon = NULL;
2014-08-28 14:47:54 +00:00
MWMechanics::WeaponType weaptype = MWMechanics::WeapType_None;
2014-01-17 18:33:49 +00:00
MWWorld::ContainerStoreIterator weaponSlot =
MWMechanics::getActiveWeapon(actor.getClass().getCreatureStats(actor), actor.getClass().getInventoryStore(actor), &weaptype);
float weapSpeed;
if (weaptype != MWMechanics::WeapType_HandToHand
2014-08-28 00:14:30 +00:00
&& weaptype != MWMechanics::WeapType_Spell
&& weaptype != MWMechanics::WeapType_None)
2014-01-17 18:33:49 +00:00
{
weapon = weaponSlot->get<ESM::Weapon>()->mBase;
weapSpeed = weapon->mData.mSpeed;
}
else weapSpeed = 1.0f;
MWRender::Animation *anim = MWBase::Environment::get().getWorld()->getAnimation(actor);
std::string weapGroup;
MWMechanics::getWeaponGroup(weaptype, weapGroup);
weapGroup = weapGroup + ": ";
bool bRangedWeap = (weaptype >= MWMechanics::WeapType_BowAndArrow && weaptype <= MWMechanics::WeapType_Thrown);
const char *attackType[] = {"chop ", "slash ", "thrust ", "shoot "};
std::string textKey = "start";
std::string textKey2;
// get durations for each attack type
for (int i = 0; i < (bRangedWeap ? 1 : 3); i++)
{
2014-06-10 20:20:46 +00:00
float start1 = anim->getTextKeyTime(weapGroup + (bRangedWeap ? attackType[3] : attackType[i]) + textKey);
if (start1 < 0)
{
fMinMaxDurations[i][0] = fMinMaxDurations[i][1] = 0.1f;
continue;
}
textKey2 = "min attack";
2014-06-10 20:20:46 +00:00
float start2 = anim->getTextKeyTime(weapGroup + (bRangedWeap ? attackType[3] : attackType[i]) + textKey2);
fMinMaxDurations[i][0] = (start2 - start1) / weapSpeed;
textKey2 = "max attack";
2014-06-10 20:20:46 +00:00
start1 = anim->getTextKeyTime(weapGroup + (bRangedWeap ? attackType[3] : attackType[i]) + textKey2);
fMinMaxDurations[i][1] = fMinMaxDurations[i][0] + (start1 - start2) / weapSpeed;
}
}
2014-01-17 18:33:49 +00:00
2015-06-03 17:41:19 +00:00
osg::Vec3f AimDirToMovingTarget(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, const osg::Vec3f& vLastTargetPos,
float duration, int weapType, float strength)
{
float projSpeed;
// get projectile speed (depending on weapon type)
if (weapType == ESM::Weapon::MarksmanThrown)
2014-01-17 18:33:49 +00:00
{
static float fThrownWeaponMinSpeed =
MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fThrownWeaponMinSpeed")->getFloat();
static float fThrownWeaponMaxSpeed =
MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fThrownWeaponMaxSpeed")->getFloat();
projSpeed =
fThrownWeaponMinSpeed + (fThrownWeaponMaxSpeed - fThrownWeaponMinSpeed) * strength;
2014-01-15 20:56:55 +00:00
}
2014-01-23 21:14:20 +00:00
else
{
static float fProjectileMinSpeed =
MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fProjectileMinSpeed")->getFloat();
static float fProjectileMaxSpeed =
MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fProjectileMaxSpeed")->getFloat();
projSpeed =
fProjectileMinSpeed + (fProjectileMaxSpeed - fProjectileMinSpeed) * strength;
}
// idea: perpendicular to dir to target speed components of target move vector and projectile vector should be the same
2015-06-03 17:41:19 +00:00
osg::Vec3f vActorPos = actor.getRefData().getPosition().asVec3();
osg::Vec3f vTargetPos = target.getRefData().getPosition().asVec3();
osg::Vec3f vDirToTarget = vTargetPos - vActorPos;
float distToTarget = vDirToTarget.length();
2015-06-03 17:41:19 +00:00
osg::Vec3f vTargetMoveDir = vTargetPos - vLastTargetPos;
vTargetMoveDir /= duration; // |vTargetMoveDir| is target real speed in units/sec now
2015-06-03 17:41:19 +00:00
osg::Vec3f vPerpToDir = vDirToTarget ^ osg::Vec3f(0,0,1); // cross product
2015-06-03 17:41:19 +00:00
vPerpToDir.normalize();
osg::Vec3f vDirToTargetNormalized = vDirToTarget;
vDirToTargetNormalized.normalize();
// dot product
float velPerp = vTargetMoveDir * vPerpToDir;
float velDir = vTargetMoveDir * vDirToTargetNormalized;
// time to collision between target and projectile
float t_collision;
float projVelDirSquared = projSpeed * projSpeed - velPerp * velPerp;
2015-06-03 17:41:19 +00:00
osg::Vec3f vTargetMoveDirNormalized = vTargetMoveDir;
vTargetMoveDirNormalized.normalize();
float projDistDiff = vDirToTarget * vTargetMoveDirNormalized; // dot product
projDistDiff = std::sqrt(distToTarget * distToTarget - projDistDiff * projDistDiff);
if (projVelDirSquared > 0)
2015-06-03 17:41:19 +00:00
t_collision = projDistDiff / (std::sqrt(projVelDirSquared) - velDir);
else t_collision = 0; // speed of projectile is not enough to reach moving target
return vTargetPos + vTargetMoveDir * t_collision - vActorPos;
2013-09-25 16:01:36 +00:00
}
2014-01-28 22:03:00 +00:00
}