npc.cpp 45.2 KB
Newer Older
1 2 3

#include "npc.hpp"

4 5
#include <memory>

scrawl's avatar
scrawl committed
6 7
#include <boost/algorithm/string.hpp>

8 9
#include <OgreSceneNode.h>

Emanuel Guevel's avatar
Emanuel Guevel committed
10
#include <components/esm/loadmgef.hpp>
11 12
#include <components/esm/loadnpc.hpp>

13 14
#include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp"
15
#include "../mwbase/mechanicsmanager.hpp"
16
#include "../mwbase/windowmanager.hpp"
17
#include "../mwbase/dialoguemanager.hpp"
18
#include "../mwbase/soundmanager.hpp"
19

Marc Zinnschlag's avatar
Marc Zinnschlag committed
20
#include "../mwmechanics/creaturestats.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
21
#include "../mwmechanics/npcstats.hpp"
22
#include "../mwmechanics/movement.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
23

24
#include "../mwworld/ptr.hpp"
25
#include "../mwworld/actiontalk.hpp"
scrawl's avatar
scrawl committed
26
#include "../mwworld/actionopen.hpp"
27
#include "../mwworld/failedaction.hpp"
28
#include "../mwworld/inventorystore.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
29
#include "../mwworld/customdata.hpp"
30
#include "../mwworld/physicssystem.hpp"
31

32
#include "../mwrender/actors.hpp"
33
#include "../mwrender/renderinginterface.hpp"
34

35
#include "../mwgui/tooltips.hpp"
36

Marc Zinnschlag's avatar
Marc Zinnschlag committed
37
namespace
38 39 40
{
    const Ogre::Radian kOgrePi (Ogre::Math::PI);
    const Ogre::Radian kOgrePiOverTwo (Ogre::Math::PI / Ogre::Real(2.0));
41 42 43 44

    struct CustomData : public MWWorld::CustomData
    {
        MWMechanics::NpcStats mNpcStats;
45
        MWMechanics::Movement mMovement;
46
        MWWorld::InventoryStore mInventoryStore;
47 48 49 50 51 52 53 54

        virtual MWWorld::CustomData *clone() const;
    };

    MWWorld::CustomData *CustomData::clone() const
    {
        return new CustomData (*this);
    }
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

    void autoCalculateAttributes (const ESM::NPC* npc, MWMechanics::CreatureStats& creatureStats)
    {
        // race bonus
        const ESM::Race *race =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(npc->mRace);

        bool male = (npc->mFlags & ESM::NPC::Female) == 0;

        int level = creatureStats.getLevel();

        for (int i=0; i<ESM::Attribute::Length; ++i)
        {
            const ESM::Race::MaleFemale& attribute = race->mData.mAttributeValues[i];
            creatureStats.getAttribute(i).setBase (male ? attribute.mMale : attribute.mFemale);
        }

        // class bonus
        const ESM::Class *class_ =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Class>().find(npc->mClass);

        for (int i=0; i<2; ++i)
        {
            int attribute = class_->mData.mAttribute[i];
            if (attribute>=0 && attribute<8)
            {
                creatureStats.getAttribute(attribute).setBase (
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
        for (int attribute=0; attribute<ESM::Attribute::Length; ++attribute)
        {
            float modifierSum = 0;

            for (int j=0; j<ESM::Skill::Length; ++j)
            {
                const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>().find(j);

                if (skill->mData.mAttribute != attribute)
                    continue;

                // is this a minor or major skill?
                float add=0.2;
                for (int k=0; k<5; ++k)
                {
                    if (class_->mData.mSkills[k][0] == j)
                        add=0.5;
                }
                for (int k=0; k<5; ++k)
                {
                    if (class_->mData.mSkills[k][1] == j)
                        add=1.0;
                }
                modifierSum += add;
            }
            creatureStats.getAttribute(attribute).setBase ( std::min(creatureStats.getAttribute(attribute).getBase()
                + static_cast<int>((level-1) * modifierSum+0.5), 100) );
        }
115

116
        // initial health
117 118
        int strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
        int endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
119 120 121 122 123 124 125 126 127 128 129 130 131

        int multiplier = 3;

        if (class_->mData.mSpecialization == ESM::Class::Combat)
            multiplier += 2;
        else if (class_->mData.mSpecialization == ESM::Class::Stealth)
            multiplier += 1;

        if (class_->mData.mAttribute[0] == ESM::Attribute::Endurance
            || class_->mData.mAttribute[1] == ESM::Attribute::Endurance)
            multiplier += 1;

        creatureStats.setHealth(static_cast<int> (0.5 * (strength + endurance)) + multiplier * (creatureStats.getLevel() - 1));
132
    }
133 134
}

135
namespace MWClass
136
{
137 138
    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
        static bool inited = false;
        if(!inited)
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
            const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

            fMinWalkSpeed = gmst.find("fMinWalkSpeed");
            fMaxWalkSpeed = gmst.find("fMaxWalkSpeed");
            fEncumberedMoveEffect = gmst.find("fEncumberedMoveEffect");
            fSneakSpeedMultiplier = gmst.find("fSneakSpeedMultiplier");
            fAthleticsRunBonus = gmst.find("fAthleticsRunBonus");
            fBaseRunMultiplier = gmst.find("fBaseRunMultiplier");
            fMinFlySpeed = gmst.find("fMinFlySpeed");
            fMaxFlySpeed = gmst.find("fMaxFlySpeed");
            fSwimRunBase = gmst.find("fSwimRunBase");
            fSwimRunAthleticsMult = gmst.find("fSwimRunAthleticsMult");
155 156 157 158 159
            fJumpEncumbranceBase = gmst.find("fJumpEncumbranceBase");
            fJumpEncumbranceMultiplier = gmst.find("fJumpEncumbranceMultiplier");
            fJumpAcrobaticsBase = gmst.find("fJumpAcrobaticsBase");
            fJumpAcroMultiplier = gmst.find("fJumpAcroMultiplier");
            fJumpRunMultiplier = gmst.find("fJumpRunMultiplier");
160
            fWereWolfRunMult = gmst.find("fWereWolfRunMult");
161 162 163

            inited = true;
        }
164 165
        if (!ptr.getRefData().getCustomData())
        {
166
            std::auto_ptr<CustomData> data(new CustomData);
167

168
            MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
169

170
            // NPC stats
greye's avatar
greye committed
171
            if (!ref->mBase->mFaction.empty())
172
            {
greye's avatar
greye committed
173
                std::string faction = ref->mBase->mFaction;
eduard's avatar
eduard committed
174
                Misc::StringUtils::toLower(faction);
greye's avatar
greye committed
175
                if(ref->mBase->mNpdt52.mGold != -10)
176
                {
greye's avatar
greye committed
177
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank;
178 179 180
                }
                else
                {
greye's avatar
greye committed
181
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank;
182
                }
183 184
            }

185
            // creature stats
greye's avatar
greye committed
186
            if(ref->mBase->mNpdt52.mGold != -10)
187 188
            {
                for (int i=0; i<27; ++i)
greye's avatar
greye committed
189 190
                    data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]);

191 192 193 194 195 196 197 198 199 200 201 202 203
                data->mNpcStats.getAttribute(0).set (ref->mBase->mNpdt52.mStrength);
                data->mNpcStats.getAttribute(1).set (ref->mBase->mNpdt52.mIntelligence);
                data->mNpcStats.getAttribute(2).set (ref->mBase->mNpdt52.mWillpower);
                data->mNpcStats.getAttribute(3).set (ref->mBase->mNpdt52.mAgility);
                data->mNpcStats.getAttribute(4).set (ref->mBase->mNpdt52.mSpeed);
                data->mNpcStats.getAttribute(5).set (ref->mBase->mNpdt52.mEndurance);
                data->mNpcStats.getAttribute(6).set (ref->mBase->mNpdt52.mPersonality);
                data->mNpcStats.getAttribute(7).set (ref->mBase->mNpdt52.mLuck);
                data->mNpcStats.setHealth (ref->mBase->mNpdt52.mHealth);
                data->mNpcStats.setMagicka (ref->mBase->mNpdt52.mMana);
                data->mNpcStats.setFatigue (ref->mBase->mNpdt52.mFatigue);

                data->mNpcStats.setLevel(ref->mBase->mNpdt52.mLevel);
scrawl's avatar
scrawl committed
204
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
205
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
206 207 208
            }
            else
            {
209
                for (int i=0; i<3; ++i)
210
                    data->mNpcStats.setDynamic (i, 10);
211

212
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
213 214
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
215

216
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
217
            }
218

219
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
220

221 222 223 224
            data->mNpcStats.setAiSetting (0, ref->mBase->mAiData.mHello);
            data->mNpcStats.setAiSetting (1, ref->mBase->mAiData.mFight);
            data->mNpcStats.setAiSetting (2, ref->mBase->mAiData.mFlee);
            data->mNpcStats.setAiSetting (3, ref->mBase->mAiData.mAlarm);
225

226
            // spells
greye's avatar
greye committed
227 228
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
229
                data->mNpcStats.getSpells().add (*iter);
230

231 232 233 234
            // inventory
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr),
                                       MWBase::Environment::get().getWorld()->getStore());

235
            // store
236
            ptr.getRefData().setCustomData (data.release());
237 238

            getInventoryStore(ptr).autoEquip(ptr);
239 240 241
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
242 243
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
244
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
245 246
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
247
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
248 249
    }

250 251 252 253 254
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
255
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
256
    {
257
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
258
    }
Jason Hooks's avatar
Jason Hooks committed
259

260
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
261
    {
262
        physics.addActor(ptr);
263
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
greye's avatar
greye committed
264
    }
Jason Hooks's avatar
Jason Hooks committed
265

scrawl's avatar
scrawl committed
266 267 268 269 270 271
    bool Npc::isPersistent(const MWWorld::Ptr &actor) const
    {
        MWWorld::LiveCellRef<ESM::NPC>* ref = actor.get<ESM::NPC>();
        return ref->mBase->mPersistent;
    }

greye's avatar
greye committed
272 273
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
274
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
275
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
276
        assert(ref->mBase != NULL);
277

scrawl's avatar
scrawl committed
278
        //std::string headID = ref->mBase->mHead;
279

scrawl's avatar
scrawl committed
280 281
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
282 283

        std::string model = "meshes\\base_anim.nif";
284 285
        const ESM::Race* race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(ref->mBase->mRace);
        if(race->mData.mFlags & ESM::Race::Beast)
greye's avatar
greye committed
286
            model = "meshes\\base_animkna.nif";
287

greye's avatar
greye committed
288
        return model;
289 290 291

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
292 293
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
294 295 296 297 298 299 300
        if(getNpcStats(ptr).isWerewolf())
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
            const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

            return gmst.find("sWerewolfPopup")->getString();
        }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
301

302
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
303
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
304 305
    }

306
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
307
    {
308
        ensureCustomData (ptr);
309

310
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
311 312
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
313 314
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
315
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
316

317
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
318 319
    }

Chris Robinson's avatar
Chris Robinson committed
320

321
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
322
    {
323 324 325
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

326 327
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
328 329 330 331
        MWWorld::ContainerStoreIterator weaponslot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight);
        MWWorld::Ptr weapon = ((weaponslot != inv.end()) ? *weaponslot : MWWorld::Ptr());
        if(!weapon.isEmpty() && weapon.getTypeName() != typeid(ESM::Weapon).name())
            weapon = MWWorld::Ptr();
332

333 334
        float dist = 100.0f * (!weapon.isEmpty() ?
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
335
                               gmst.find("fHandToHandReach")->getFloat());
336 337
        // TODO: Use second to work out the hit angle and where to spawn the blood effect
        MWWorld::Ptr victim = world->getHitContact(ptr, dist).first;
Chris Robinson's avatar
Chris Robinson committed
338 339 340 341
        if(victim.isEmpty()) // Didn't hit anything
            return;

        const MWWorld::Class &othercls = MWWorld::Class::get(victim);
342 343
        if(!othercls.isActor()) // Can't hit non-actors
            return;
344
        MWMechanics::CreatureStats &otherstats = victim.getClass().getCreatureStats(victim);
345
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
346 347
            return;

scrawl's avatar
scrawl committed
348
        if(ptr.getRefData().getHandle() == "player")
scrawl's avatar
scrawl committed
349
            MWBase::Environment::get().getWindowManager()->setEnemy(victim);
scrawl's avatar
scrawl committed
350

351
        int weapskill = ESM::Skill::HandToHand;
352
        if(!weapon.isEmpty())
353
            weapskill = get(weapon).getEquipmentSkill(weapon);
354

355 356 357 358 359 360
        MWMechanics::NpcStats &stats = getNpcStats(ptr);
        const MWMechanics::MagicEffects &mageffects = stats.getMagicEffects();
        float hitchance = stats.getSkill(weapskill).getModified() +
                          (stats.getAttribute(ESM::Attribute::Agility).getModified() / 5.0f) +
                          (stats.getAttribute(ESM::Attribute::Luck).getModified() / 10.0f);
        hitchance *= stats.getFatigueTerm();
361 362
        hitchance += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::FortifyAttack)).mMagnitude -
                     mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Blind)).mMagnitude;
363
        hitchance -= otherstats.getEvasion();
364

Chris Robinson's avatar
Chris Robinson committed
365
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
366
        {
367
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
368 369
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
370

371
        bool healthdmg;
372 373
        float damage = 0.0f;
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
374
        {
375
            const bool weaphashealth = get(weapon).hasItemHealth(weapon);
376
            const unsigned char *attack = NULL;
Chris Robinson's avatar
Chris Robinson committed
377
            if(type == MWMechanics::CreatureStats::AT_Chop)
378
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
Chris Robinson's avatar
Chris Robinson committed
379
            else if(type == MWMechanics::CreatureStats::AT_Slash)
380
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
Chris Robinson's avatar
Chris Robinson committed
381
            else if(type == MWMechanics::CreatureStats::AT_Thrust)
382
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
383
            if(attack)
384
            {
385 386
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
                damage *= 0.5f + (stats.getAttribute(ESM::Attribute::Luck).getModified() / 100.0f);
387 388 389 390 391 392 393
                if(weaphashealth)
                {
                    int weapmaxhealth = weapon.get<ESM::Weapon>()->mBase->mData.mHealth;
                    if(weapon.getCellRef().mCharge == -1)
                        weapon.getCellRef().mCharge = weapmaxhealth;
                    damage *= float(weapon.getCellRef().mCharge) / weapmaxhealth;
                }
394 395 396 397
                if(!othercls.hasDetected(victim, ptr))
                {
                    damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
                    MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
398
                    MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
399
                }
400 401 402 403
                
                if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    weapon.getCellRef().mCharge -= std::min(std::max(1,
                        (int)(damage * gmst.find("fWeaponDamageMult")->getFloat())), weapon.getCellRef().mCharge);
404
            }
405 406 407 408 409 410 411 412 413
            healthdmg = true;
        }
        else
        {
            // Note: MCP contains an option to include Strength in hand-to-hand damage
            // calculations. Some mods recommend using it, so we may want to include am
            // option for it.
            float minstrike = gmst.find("fMinHandToHandMult")->getFloat();
            float maxstrike = gmst.find("fMaxHandToHandMult")->getFloat();
414 415
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
416 417 418 419 420 421 422
            if(!othercls.hasDetected(victim, ptr))
            {
                damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
                MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
                MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
            }

423
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f);
424
            if(stats.isWerewolf())
425 426 427 428 429 430
            {
                healthdmg = true;
                // GLOB instead of GMST because it gets updated during a quest
                const MWWorld::Store<ESM::Global> &glob = world->getStore().get<ESM::Global>();
                damage *= glob.find("WerewolfClawMult")->mValue.getFloat();
            }
431
            if(healthdmg)
432
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
433 434 435 436

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
437 438 439
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
440 441 442
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
443
        }
444 445
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
446

447
        // Apply "On hit" enchanted weapons
448
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
                // Check if we have enough charges
                const float enchantCost = enchantment->mData.mCost;
                int eSkill = stats.getSkill(ESM::Skill::Enchant).getModified();
                const float castCost = enchantCost - (enchantCost / 100) * (eSkill - 10);

                if (weapon.getCellRef().mEnchantmentCharge == -1)
                    weapon.getCellRef().mEnchantmentCharge = enchantment->mData.mCharge;
                if (weapon.getCellRef().mEnchantmentCharge < castCost)
                {
                    if (ptr.getRefData().getHandle() == "player")
                        MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicInsufficientCharge}");
                }
                else
                {
                    weapon.getCellRef().mEnchantmentCharge -= castCost;
470
                    // Touch
scrawl's avatar
scrawl committed
471
                    othercls.getCreatureStats(victim).getActiveSpells().addSpell(enchantmentName, victim, ptr, ESM::RT_Touch, weapon.getClass().getName(weapon));
472
                    // Self
scrawl's avatar
scrawl committed
473
                    getCreatureStats(ptr).getActiveSpells().addSpell(enchantmentName, ptr, ptr, ESM::RT_Self, weapon.getClass().getName(weapon));
474 475
                    // Target
                    MWBase::Environment::get().getWorld()->launchProjectile(enchantmentName, enchantment->mEffects, ptr, weapon.getClass().getName(weapon));
476 477 478 479
                }
            }
        }

480
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
481 482
    }

483
    void Npc::onHit(const MWWorld::Ptr &ptr, float damage, bool ishealth, const MWWorld::Ptr &object, const MWWorld::Ptr &attacker, bool successful) const
Chris Robinson's avatar
Chris Robinson committed
484
    {
485 486
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

487 488 489 490 491 492 493
        // NOTE: 'object' and/or 'attacker' may be empty.

        if(!successful)
        {
            // TODO: Handle HitAttemptOnMe script function

            // Missed
494
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
495 496
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
497

498
        if(!object.isEmpty())
499
            getCreatureStats(ptr).setLastHitObject(get(object).getId(object));
500 501 502 503 504 505 506 507

        if(!attacker.isEmpty() && attacker.getRefData().getHandle() == "player")
        {
            const std::string &script = ptr.get<ESM::NPC>()->mBase->mScript;
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
508 509

        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
510 511 512
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
513 514

            MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
515

516
            if(object.isEmpty())
517 518
            {
                if(ishealth)
519
                    damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
520 521
            }
            else if(ishealth)
522
            {
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
                // Hit percentages:
                // cuirass = 30%
                // shield, helmet, greaves, boots, pauldrons = 10% each
                // guantlets = 5% each
                static const int hitslots[20] = {
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_Cuirass,
                    MWWorld::InventoryStore::Slot_CarriedLeft, MWWorld::InventoryStore::Slot_CarriedLeft,
                    MWWorld::InventoryStore::Slot_Helmet, MWWorld::InventoryStore::Slot_Helmet,
                    MWWorld::InventoryStore::Slot_Greaves, MWWorld::InventoryStore::Slot_Greaves,
                    MWWorld::InventoryStore::Slot_Boots, MWWorld::InventoryStore::Slot_Boots,
                    MWWorld::InventoryStore::Slot_LeftPauldron, MWWorld::InventoryStore::Slot_LeftPauldron,
                    MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron,
                    MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet
                };
                int hitslot = hitslots[(int)(::rand()/(RAND_MAX+1.0)*20.0)];

541 542 543 544
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

545 546 547 548
                MWWorld::InventoryStore &inv = getInventoryStore(ptr);
                MWWorld::ContainerStoreIterator armorslot = inv.getSlot(hitslot);
                MWWorld::Ptr armor = ((armorslot != inv.end()) ? *armorslot : MWWorld::Ptr());
                if(!armor.isEmpty() && armor.getTypeName() == typeid(ESM::Armor).name())
549
                {
550 551 552 553 554
                    ESM::CellRef &armorref = armor.getCellRef();
                    if(armorref.mCharge == -1)
                        armorref.mCharge = armor.get<ESM::Armor>()->mBase->mData.mHealth;
                    armorref.mCharge -= std::min(std::max(1, (int)damagediff),
                                                 armorref.mCharge);
555 556 557 558 559 560 561 562 563 564 565 566
                    switch(get(armor).getEquipmentSkill(armor))
                    {
                        case ESM::Skill::LightArmor:
                            sndMgr->playSound3D(ptr, "Light Armor Hit", 1.0f, 1.0f);
                            break;
                        case ESM::Skill::MediumArmor:
                            sndMgr->playSound3D(ptr, "Medium Armor Hit", 1.0f, 1.0f);
                            break;
                        case ESM::Skill::HeavyArmor:
                            sndMgr->playSound3D(ptr, "Heavy Armor Hit", 1.0f, 1.0f);
                            break;
                    }
567 568
                }
            }
Chris Robinson's avatar
Chris Robinson committed
569 570
        }

571 572 573 574 575 576 577 578 579 580 581 582 583
        if(ishealth)
        {
            if(damage > 0.0f)
                sndMgr->playSound3D(ptr, "Health Damage", 1.0f, 1.0f);
            float health = getCreatureStats(ptr).getHealth().getCurrent() - damage;
            setActorHealth(ptr, health, attacker);
        }
        else
        {
            MWMechanics::DynamicStat<float> fatigue(getCreatureStats(ptr).getFatigue());
            fatigue.setCurrent(fatigue.getCurrent() - damage);
            getCreatureStats(ptr).setFatigue(fatigue);
        }
584 585 586 587 588
    }

    void Npc::setActorHealth(const MWWorld::Ptr& ptr, float health, const MWWorld::Ptr& attacker) const
    {
        MWMechanics::CreatureStats &crstats = getCreatureStats(ptr);
Chris Robinson's avatar
Chris Robinson committed
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
        bool wasDead = crstats.isDead();

        MWMechanics::DynamicStat<float> stat(crstats.getHealth());
        stat.setCurrent(health);
        crstats.setHealth(stat);

        if(!wasDead && crstats.isDead())
        {
            // actor was just killed
        }
        else if(wasDead && !crstats.isDead())
        {
            // actor was just resurrected
        }
    }


606
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
607
        const MWWorld::Ptr& actor) const
608
    {
609 610
        if(get(actor).isNpc() && get(actor).getNpcStats(actor).isWerewolf())
        {
611 612 613
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

614
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
615 616
            if(sound) action->setSound(sound->mId);

617 618 619 620 621 622 623
            return action;
        }
        if(getCreatureStats(ptr).isDead())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr, true));
        if(get(actor).getStance(actor, MWWorld::Class::Sneak))
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr)); // stealing
        return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionTalk(ptr));
624
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
625

626
    MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr)
627
        const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
628
    {
629
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
630

631 632 633 634 635 636 637 638 639
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mInventoryStore;
    }

    MWWorld::InventoryStore& Npc::getInventoryStore (const MWWorld::Ptr& ptr)
        const
    {
        ensureCustomData (ptr);

        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mInventoryStore;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
640 641
    }

642 643
    std::string Npc::getScript (const MWWorld::Ptr& ptr) const
    {
644
        MWWorld::LiveCellRef<ESM::NPC> *ref =
645 646
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
647
        return ref->mBase->mScript;
648 649
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
650 651 652 653 654 655 656 657
    void Npc::setForceStance (const MWWorld::Ptr& ptr, Stance stance, bool force) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

658
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceRun, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
659 660 661 662
                break;

            case Sneak:

663
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak, force);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
                break;

            case Combat:

                throw std::runtime_error ("combat stance not enforcable for NPCs");
        }
    }

    void Npc::setStance (const MWWorld::Ptr& ptr, Stance stance, bool set) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

680
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Run, set);
681
                break;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
682 683 684

            case Sneak:

685
                stats.setMovementFlag (MWMechanics::NpcStats::Flag_Sneak, set);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
686 687 688 689
                break;

            case Combat:

690 691
                // Combat stance ignored for now; need to be determined based on draw state instead of
                // being maunally set.
Marc Zinnschlag's avatar
Marc Zinnschlag committed
692 693 694 695 696 697 698 699 700 701 702 703
                break;
        }
    }

    bool Npc::getStance (const MWWorld::Ptr& ptr, Stance stance, bool ignoreForce) const
    {
        MWMechanics::NpcStats& stats = getNpcStats (ptr);

        switch (stance)
        {
            case Run:

704
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceRun))
705 706
                    return true;

707
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Run);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
708 709 710

            case Sneak:

711
                if (!ignoreForce && stats.getMovementFlag (MWMechanics::NpcStats::Flag_ForceSneak))
Marc Zinnschlag's avatar
Marc Zinnschlag committed
712 713
                    return true;

714
                return stats.getMovementFlag (MWMechanics::NpcStats::Flag_Sneak);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
715 716 717

            case Combat:

718
                return false;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
719 720 721 722 723
        }

        return false;
    }

724
    float Npc::getSpeed(const MWWorld::Ptr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
725
    {
726 727
        const MWBase::World *world = MWBase::Environment::get().getWorld();
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
728
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
729

730 731
        const float normalizedEncumbrance = Npc::getEncumbrance(ptr) / Npc::getCapacity(ptr);

732
        float walkSpeed = fMinWalkSpeed->getFloat() + 0.01f*npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified()*
733 734 735 736 737
                                                      (fMaxWalkSpeed->getFloat() - fMinWalkSpeed->getFloat());
        walkSpeed *= 1.0f - fEncumberedMoveEffect->getFloat()*normalizedEncumbrance;
        walkSpeed = std::max(0.0f, walkSpeed);
        if(Npc::getStance(ptr, Sneak, false))
            walkSpeed *= fSneakSpeedMultiplier->getFloat();
738

739 740
        float runSpeed = walkSpeed*(0.01f * npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified() *
                                    fAthleticsRunBonus->getFloat() + fBaseRunMultiplier->getFloat());
741 742
        if(npcdata->mNpcStats.isWerewolf())
            runSpeed *= fWereWolfRunMult->getFloat();
743 744

        float moveSpeed;
745
        if(normalizedEncumbrance >= 1.0f)
746
            moveSpeed = 0.0f;
747
        else if(mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude > 0)
748
        {
749
            float flySpeed = 0.01f*(npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified() +
750
                                    mageffects.get(MWMechanics::EffectKey(10/*levitate*/)).mMagnitude);
751 752 753 754 755 756 757 758 759 760
            flySpeed = fMinFlySpeed->getFloat() + flySpeed*(fMaxFlySpeed->getFloat() - fMinFlySpeed->getFloat());
            flySpeed *= 1.0f - fEncumberedMoveEffect->getFloat() * normalizedEncumbrance;
            flySpeed = std::max(0.0f, flySpeed);
            moveSpeed = flySpeed;
        }
        else if(world->isSwimming(ptr))
        {
            float swimSpeed = walkSpeed;
            if(Npc::getStance(ptr, Run, false))
                swimSpeed = runSpeed;
761
            swimSpeed *= 1.0f + 0.01f * mageffects.get(MWMechanics::EffectKey(1/*swift swim*/)).mMagnitude;
762 763 764 765
            swimSpeed *= fSwimRunBase->getFloat() + 0.01f*npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified()*
                                                    fSwimRunAthleticsMult->getFloat();
            moveSpeed = swimSpeed;
        }
scrawl's avatar
scrawl committed
766
        else if(Npc::getStance(ptr, Run, false) && !Npc::getStance(ptr, Sneak, false))
767 768 769
            moveSpeed = runSpeed;
        else
            moveSpeed = walkSpeed;
770
        if(getMovementSettings(ptr).mPosition[0] != 0 && getMovementSettings(ptr).mPosition[1] == 0)
771 772 773
            moveSpeed *= 0.75f;

        return moveSpeed;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
774 775
    }

776 777 778
    float Npc::getJump(const MWWorld::Ptr &ptr) const
    {
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
779
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
780 781
        const float encumbranceTerm = fJumpEncumbranceBase->getFloat() +
                                          fJumpEncumbranceMultiplier->getFloat() *
782
                                          (1.0f - Npc::getEncumbrance(ptr)/Npc::getCapacity(ptr));
783 784 785 786 787 788 789 790 791 792 793

        float a = npcdata->mNpcStats.getSkill(ESM::Skill::Acrobatics).getModified();
        float b = 0.0f;
        if(a > 50.0f)
        {
            b = a - 50.0f;
            a = 50.0f;
        }

        float x = fJumpAcrobaticsBase->getFloat() +
                  std::pow(a / 15.0f, fJumpAcroMultiplier->getFloat());
794 795
        x += 3.0f * b * fJumpAcroMultiplier->getFloat();
        x += mageffects.get(MWMechanics::EffectKey(ESM::MagicEffect::Jump)).mMagnitude * 64;
796 797 798 799
        x *= encumbranceTerm;

        if(Npc::getStance(ptr, Run, false))
            x *= fJumpRunMultiplier->getFloat();
800
        x *= npcdata->mNpcStats.getFatigueTerm();
801 802
        x -= -627.2f;/*gravity constant*/
        x /= 3.0f;
803 804 805 806

        return x;
    }

807 808
    float Npc::getFallDamage(const MWWorld::Ptr &ptr, float fallHeight) const
    {
Emanuel Guevel's avatar
Emanuel Guevel committed
809 810 811 812
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

        const float fallDistanceMin = gmst.find("fFallDamageDistanceMin")->getFloat();
813

Emanuel Guevel's avatar
Emanuel Guevel committed
814
        if (fallHeight >= fallDistanceMin)
815 816 817
        {
            const float acrobaticsSkill = MWWorld::Class::get(ptr).getNpcStats (ptr).getSkill(ESM::Skill::Acrobatics).getModified();
            const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
Emanuel Guevel's avatar
Emanuel Guevel committed
818 819 820 821 822
            const float jumpSpellBonus = npcdata->mNpcStats.getMagicEffects().get(MWMechanics::EffectKey(ESM::MagicEffect::Jump)).mMagnitude;
            const float fallAcroBase = gmst.find("fFallAcroBase")->getFloat();
            const float fallAcroMult = gmst.find("fFallAcroMult")->getFloat();
            const float fallDistanceBase = gmst.find("fFallDistanceBase")->getFloat();
            const float fallDistanceMult = gmst.find("fFallDistanceMult")->getFloat();
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

            float x = fallHeight - fallDistanceMin;
            x -= (1.5 * acrobaticsSkill) + jumpSpellBonus;
            x = std::max(0.0f, x);

            float a = fallAcroBase + fallAcroMult * (100 - acrobaticsSkill);
            x = fallDistanceBase + fallDistanceMult * x;
            x *= a;

            return x;
        }

        return 0;
    }

838 839
    MWMechanics::Movement& Npc::getMovementSettings (const MWWorld::Ptr& ptr) const
    {
840
        ensureCustomData (ptr);
841

842
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mMovement;
843 844 845 846
    }

    Ogre::Vector3 Npc::getMovementVector (const MWWorld::Ptr& ptr) const
    {
847 848 849 850 851 852
        MWMechanics::Movement &movement = getMovementSettings(ptr);
        Ogre::Vector3 vec(movement.mPosition);
        movement.mPosition[0] = 0.0f;
        movement.mPosition[1] = 0.0f;
        movement.mPosition[2] = 0.0f;
        return vec;
853
    }
854 855 856

    Ogre::Vector3 Npc::getRotationVector (const MWWorld::Ptr& ptr) const
    {
857 858 859 860 861 862
        MWMechanics::Movement &movement = getMovementSettings(ptr);
        Ogre::Vector3 vec(movement.mRotation);
        movement.mRotation[0] = 0.0f;
        movement.mRotation[1] = 0.0f;
        movement.mRotation[2] = 0.0f;
        return vec;