npc.cpp 51.1 KB
Newer Older
1 2 3

#include "npc.hpp"

4 5
#include <memory>

6 7
#include <OgreSceneNode.h>

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

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

Marc Zinnschlag's avatar
Marc Zinnschlag committed
18
#include "../mwmechanics/creaturestats.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
19
#include "../mwmechanics/npcstats.hpp"
20
#include "../mwmechanics/movement.hpp"
21
#include "../mwmechanics/spellcasting.hpp"
22
#include "../mwmechanics/disease.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 41
    struct CustomData : public MWWorld::CustomData
    {
        MWMechanics::NpcStats mNpcStats;
42
        MWMechanics::Movement mMovement;
43
        MWWorld::InventoryStore mInventoryStore;
44 45 46 47 48 49 50 51

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

    MWWorld::CustomData *CustomData::clone() const
    {
        return new CustomData (*this);
    }
52 53 54 55 56 57 58 59 60 61 62 63 64

    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];
65
            creatureStats.setAttribute(i, male ? attribute.mMale : attribute.mFemale);
66 67 68 69 70 71 72 73 74 75 76
        }

        // 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)
            {
77
                creatureStats.setAttribute(attribute,
78 79 80 81 82
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
83
        for (int attribute=0; attribute < ESM::Attribute::Length; ++attribute)
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        {
            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;
            }
108
            creatureStats.setAttribute(attribute, std::min(creatureStats.getAttribute(attribute).getBase()
109 110
                + static_cast<int>((level-1) * modifierSum+0.5), 100) );
        }
111

112
        // initial health
113 114
        int strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
        int endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
115 116 117 118 119 120 121 122 123 124 125 126 127

        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));
128
    }
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

    /**
     * @brief autoCalculateSkills
     *
     * Skills are calculated with following formulae ( http://www.uesp.net/wiki/Morrowind:NPCs#Skills ):
     *
     * Skills: (Level - 1) × (Majority Multiplier + Specialization Multiplier)
     *
     *         The Majority Multiplier is 1.0 for a Major or Minor Skill, or 0.1 for a Miscellaneous Skill.
     *
     *         The Specialization Multiplier is 0.5 for a Skill in the same Specialization as the class,
     *         zero for other Skills.
     *
     * and by adding class, race, specialization bonus.
     */
144
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr)
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    {
        const ESM::Class *class_ =
            MWBase::Environment::get().getWorld()->getStore().get<ESM::Class>().find(npc->mClass);

        unsigned int level = npcStats.getLevel();

        const ESM::Race *race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(npc->mRace);


        for (int i = 0; i < 2; ++i)
        {
            int bonus = (i==0) ? 10 : 25;

            for (int i2 = 0; i2 < 5; ++i2)
            {
                int index = class_->mData.mSkills[i2][i];
                if (index >= 0 && index < ESM::Skill::Length)
                {
                    npcStats.getSkill(index).setBase (npcStats.getSkill(index).getBase() + bonus);
                }
            }
        }

        for (int skillIndex = 0; skillIndex < ESM::Skill::Length; ++skillIndex)
        {
            float majorMultiplier = 0.1f;
            float specMultiplier = 0.0f;

            int raceBonus = 0;
            int specBonus = 0;

            for (int raceSkillIndex = 0; raceSkillIndex < 7; ++raceSkillIndex)
            {
178 179 180 181 182
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
183 184 185 186
            }

            for (int k = 0; k < 5; ++k)
            {
187 188 189 190 191 192
                // is this a minor or major skill?
                if ((class_->mData.mSkills[k][0] == skillIndex) || (class_->mData.mSkills[k][1] == skillIndex))
                {
                    majorMultiplier = 1.0f;
                    break;
                }
193 194 195 196 197 198 199 200 201 202 203 204
                if (class_->mData.mSkills[k][1] == skillIndex)
                {
                    // Major skill -> add starting spells for this skill if existing
                    const MWWorld::ESMStore& store = MWBase::Environment::get().getWorld()->getStore();
                    MWWorld::Store<ESM::Spell>::iterator it = store.get<ESM::Spell>().begin();
                    for (; it != store.get<ESM::Spell>().end(); ++it)
                    {
                        if (it->mData.mFlags & ESM::Spell::F_Autocalc
                                && MWMechanics::spellSchoolToSkill(MWMechanics::getSpellSchool(&*it, ptr)) == skillIndex)
                            npcStats.getSpells().add(it->mId);
                    }
                }
205 206 207 208 209 210
            }

            // is this skill in the same Specialization as the class?
            const ESM::Skill* skill = MWBase::Environment::get().getWorld()->getStore().get<ESM::Skill>().find(skillIndex);
            if (skill->mData.mSpecialization == class_->mData.mSpecialization)
            {
211 212
                specMultiplier = 0.5f;
                specBonus = 5;
213 214 215 216 217 218 219 220
            }

            npcStats.getSkill(skillIndex).setBase(
                  std::min(
                    npcStats.getSkill(skillIndex).getBase()
                    + 5
                    + raceBonus
                    + specBonus
221
                    + static_cast<int>((level-1) * (majorMultiplier + specMultiplier)), 100));
222 223
        }
    }
224 225
}

226
namespace MWClass
227
{
228 229
    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        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");
246 247 248 249 250
            fJumpEncumbranceBase = gmst.find("fJumpEncumbranceBase");
            fJumpEncumbranceMultiplier = gmst.find("fJumpEncumbranceMultiplier");
            fJumpAcrobaticsBase = gmst.find("fJumpAcrobaticsBase");
            fJumpAcroMultiplier = gmst.find("fJumpAcroMultiplier");
            fJumpRunMultiplier = gmst.find("fJumpRunMultiplier");
251
            fWereWolfRunMult = gmst.find("fWereWolfRunMult");
252 253 254
            fKnockDownMult = gmst.find("fKnockDownMult");
            iKnockDownOddsMult = gmst.find("iKnockDownOddsMult");
            iKnockDownOddsBase = gmst.find("iKnockDownOddsBase");
255 256 257

            inited = true;
        }
258 259
        if (!ptr.getRefData().getCustomData())
        {
260
            std::auto_ptr<CustomData> data(new CustomData);
261

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

264
            // NPC stats
greye's avatar
greye committed
265
            if (!ref->mBase->mFaction.empty())
266
            {
greye's avatar
greye committed
267
                std::string faction = ref->mBase->mFaction;
eduard's avatar
eduard committed
268
                Misc::StringUtils::toLower(faction);
269
                if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
270
                {
greye's avatar
greye committed
271
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt52.mRank;
272 273 274
                }
                else
                {
greye's avatar
greye committed
275
                    data->mNpcStats.getFactionRanks()[faction] = (int)ref->mBase->mNpdt12.mRank;
276
                }
277 278
            }

279
            // creature stats
280
            int gold=0;
281
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
282
            {
283 284
                gold = ref->mBase->mNpdt52.mGold;

285
                for (unsigned int i=0; i< ESM::Skill::Length; ++i)
greye's avatar
greye committed
286 287
                    data->mNpcStats.getSkill (i).setBase (ref->mBase->mNpdt52.mSkills[i]);

288 289 290 291 292 293 294 295 296
                data->mNpcStats.setAttribute(ESM::Attribute::Strength, ref->mBase->mNpdt52.mStrength);
                data->mNpcStats.setAttribute(ESM::Attribute::Intelligence, ref->mBase->mNpdt52.mIntelligence);
                data->mNpcStats.setAttribute(ESM::Attribute::Willpower, ref->mBase->mNpdt52.mWillpower);
                data->mNpcStats.setAttribute(ESM::Attribute::Agility, ref->mBase->mNpdt52.mAgility);
                data->mNpcStats.setAttribute(ESM::Attribute::Speed, ref->mBase->mNpdt52.mSpeed);
                data->mNpcStats.setAttribute(ESM::Attribute::Endurance, ref->mBase->mNpdt52.mEndurance);
                data->mNpcStats.setAttribute(ESM::Attribute::Personality, ref->mBase->mNpdt52.mPersonality);
                data->mNpcStats.setAttribute(ESM::Attribute::Luck, ref->mBase->mNpdt52.mLuck);

297 298 299 300 301
                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
302
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
303
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
304 305 306
            }
            else
            {
307 308
                gold = ref->mBase->mNpdt12.mGold;

309
                for (int i=0; i<3; ++i)
310
                    data->mNpcStats.setDynamic (i, 10);
311

312
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
313 314
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
315

316
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
317
                autoCalculateSkills(ref->mBase, data->mNpcStats, ptr);
318
            }
319

320 321 322 323 324 325 326 327 328 329 330
            if (data->mNpcStats.getFactionRanks().size())
            {
                static const int iAutoRepFacMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
                        .find("iAutoRepFacMod")->getInt();
                static const int iAutoRepLevMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
                        .find("iAutoRepLevMod")->getInt();
                int rank = data->mNpcStats.getFactionRanks().begin()->second;

                data->mNpcStats.setReputation(iAutoRepFacMod * (rank+1) + iAutoRepLevMod * (data->mNpcStats.getLevel()-1));
            }

331
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
332

333 334 335 336
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Hello, ref->mBase->mAiData.mHello);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Fight, ref->mBase->mAiData.mFight);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Flee, ref->mBase->mAiData.mFlee);
            data->mNpcStats.setAiSetting (MWMechanics::CreatureStats::AI_Alarm, ref->mBase->mAiData.mAlarm);
337

338
            // spells
greye's avatar
greye committed
339 340
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
341
                data->mNpcStats.getSpells().add (*iter);
342

343
            // inventory
scrawl's avatar
scrawl committed
344
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr), "",
345 346
                                       MWBase::Environment::get().getWorld()->getStore());

347
            // store
348
            ptr.getRefData().setCustomData (data.release());
349

scrawl's avatar
scrawl committed
350 351
            // TODO: this is not quite correct, in vanilla the merchant's gold pool is not available in his inventory.
            // (except for gold you gave him)
352
            getContainerStore(ptr).add(MWWorld::ContainerStore::sGoldId, gold, ptr);
353

354
            getInventoryStore(ptr).autoEquip(ptr);
355 356 357
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
358 359
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
360
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
361 362
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
363
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
364 365
    }

366 367 368 369 370
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
371
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
372
    {
373
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
374
    }
Jason Hooks's avatar
Jason Hooks committed
375

376
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
377
    {
378
        physics.addActor(ptr);
379
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
greye's avatar
greye committed
380
    }
Jason Hooks's avatar
Jason Hooks committed
381

scrawl's avatar
scrawl committed
382 383 384 385 386 387
    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
388 389
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
390
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
391
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
392
        assert(ref->mBase != NULL);
393

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

scrawl's avatar
scrawl committed
396 397
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
398 399

        std::string model = "meshes\\base_anim.nif";
400 401
        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
402
            model = "meshes\\base_animkna.nif";
403

greye's avatar
greye committed
404
        return model;
405 406 407

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
408 409
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
410 411 412 413 414 415 416
        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
417

418
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
419
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
420 421
    }

422
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
423
    {
424
        ensureCustomData (ptr);
425

426
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
427 428
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
429 430
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
431
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
432

433
        return dynamic_cast<CustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
434 435
    }

Chris Robinson's avatar
Chris Robinson committed
436

437
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
438
    {
439 440 441
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

442 443
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
444 445 446 447
        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();
448

449 450 451 452 453 454 455 456 457 458 459 460 461 462
        // Reduce fatigue
        // somewhat of a guess, but using the weapon weight makes sense
        const float fFatigueAttackBase = gmst.find("fFatigueAttackBase")->getFloat();
        const float fFatigueAttackMult = gmst.find("fFatigueAttackMult")->getFloat();
        const float fWeaponFatigueMult = gmst.find("fWeaponFatigueMult")->getFloat();
        MWMechanics::DynamicStat<float> fatigue = getCreatureStats(ptr).getFatigue();
        const float normalizedEncumbrance = getEncumbrance(ptr) / getCapacity(ptr);
        float fatigueLoss = fFatigueAttackBase + normalizedEncumbrance * fFatigueAttackMult;
        if (!weapon.isEmpty())
            fatigueLoss += weapon.getClass().getWeight(weapon) * getNpcStats(ptr).getAttackStrength() * fWeaponFatigueMult;
        fatigue.setCurrent(fatigue.getCurrent() - fatigueLoss);
        getCreatureStats(ptr).setFatigue(fatigue);


463 464
        float dist = 100.0f * (!weapon.isEmpty() ?
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
465
                               gmst.find("fHandToHandReach")->getFloat());
scrawl's avatar
scrawl committed
466
        // TODO: Use second to work out the hit angle
scrawl's avatar
scrawl committed
467 468 469
        std::pair<MWWorld::Ptr, Ogre::Vector3> result = world->getHitContact(ptr, dist);
        MWWorld::Ptr victim = result.first;
        Ogre::Vector3 hitPosition = result.second;
Chris Robinson's avatar
Chris Robinson committed
470 471 472 473
        if(victim.isEmpty()) // Didn't hit anything
            return;

        const MWWorld::Class &othercls = MWWorld::Class::get(victim);
474 475
        if(!othercls.isActor()) // Can't hit non-actors
            return;
476
        MWMechanics::CreatureStats &otherstats = victim.getClass().getCreatureStats(victim);
477
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
478 479
            return;

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

483
        int weapskill = ESM::Skill::HandToHand;
484
        if(!weapon.isEmpty())
485
            weapskill = get(weapon).getEquipmentSkill(weapon);
486

487 488 489 490 491 492
        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();
scrawl's avatar
scrawl committed
493 494
        hitchance += mageffects.get(ESM::MagicEffect::FortifyAttack).mMagnitude -
                     mageffects.get(ESM::MagicEffect::Blind).mMagnitude;
495
        hitchance -= otherstats.getEvasion();
496

Chris Robinson's avatar
Chris Robinson committed
497
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
498
        {
499
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
500 501
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
502

503
        bool healthdmg;
504 505
        float damage = 0.0f;
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
506
        {
507
            const bool weaphashealth = get(weapon).hasItemHealth(weapon);
508
            const unsigned char *attack = NULL;
Chris Robinson's avatar
Chris Robinson committed
509
            if(type == MWMechanics::CreatureStats::AT_Chop)
510
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
Chris Robinson's avatar
Chris Robinson committed
511
            else if(type == MWMechanics::CreatureStats::AT_Slash)
512
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
Chris Robinson's avatar
Chris Robinson committed
513
            else if(type == MWMechanics::CreatureStats::AT_Thrust)
514
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
515
            if(attack)
516
            {
517 518
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
                damage *= 0.5f + (stats.getAttribute(ESM::Attribute::Luck).getModified() / 100.0f);
519 520 521 522 523 524 525
                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;
                }
526 527 528 529
                
                if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    weapon.getCellRef().mCharge -= std::min(std::max(1,
                        (int)(damage * gmst.find("fWeaponDamageMult")->getFloat())), weapon.getCellRef().mCharge);
530 531 532 533 534

                // Weapon broken? unequip it
                if (weapon.getCellRef().mCharge == 0)
                    weapon = *inv.unequipItem(weapon, ptr);

535
            }
536 537 538 539 540 541 542 543 544
            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();
545 546
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
547

scrawl's avatar
scrawl committed
548 549
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f)
                    || (otherstats.getMagicEffects().get(ESM::MagicEffect::Paralyze).mMagnitude > 0);
550
            if(stats.isWerewolf())
551 552 553 554 555 556
            {
                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();
            }
557
            if(healthdmg)
558
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
559 560 561 562

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
563 564 565
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
566 567 568
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
569
        }
570 571
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
572

573 574 575 576 577 578 579 580 581 582
        bool detected = MWBase::Environment::get().getMechanicsManager()->awarenessCheck(ptr, victim);
        if(!detected)
        {
            damage *= gmst.find("fCombatCriticalStrikeMult")->getFloat();
            MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
            MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
        }
        if (othercls.getCreatureStats(victim).getKnockedDown())
            damage *= gmst.find("fCombatKODamageMult")->getFloat();

583
        // Apply "On hit" enchanted weapons
584
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
585 586 587 588 589 590
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
591 592 593
                MWMechanics::CastSpell cast(ptr, victim);
                cast.mHitPosition = hitPosition;
                bool success = cast.cast(weapon);
594

595 596
                if (ptr.getRefData().getHandle() == "player" && success)
                    skillUsageSucceeded (ptr, ESM::Skill::Enchant, 3);
597 598 599
            }
        }

scrawl's avatar
scrawl committed
600
        // TODO: do not do this if the attack is blocked
601 602
        if (healthdmg)
            MWBase::Environment::get().getWorld()->spawnBloodEffect(victim, hitPosition);
scrawl's avatar
scrawl committed
603

604
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
605 606
    }

607
    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
608
    {
609 610
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

611 612
        // NOTE: 'object' and/or 'attacker' may be empty.

scrawl's avatar
scrawl committed
613 614 615 616
        // Attacking peaceful NPCs is a crime
        if (!attacker.isEmpty() && ptr.getClass().isNpc() && ptr.getClass().getCreatureStats(ptr).getAiSetting(MWMechanics::CreatureStats::AI_Fight).getModified() <= 30)
            MWBase::Environment::get().getMechanicsManager()->commitCrime(attacker, ptr, MWBase::MechanicsManager::OT_Assault);

617 618 619 620 621
        if(!successful)
        {
            // TODO: Handle HitAttemptOnMe script function

            // Missed
622
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
623 624
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
625

626
        if(!object.isEmpty())
627
            getCreatureStats(ptr).setLastHitObject(get(object).getId(object));
628 629 630

        if(!attacker.isEmpty() && attacker.getRefData().getHandle() == "player")
        {
scrawl's avatar
scrawl committed
631
            const std::string &script = ptr.getClass().getScript(ptr);
632 633 634 635
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
636

637 638 639
        if (!attacker.isEmpty())
            MWMechanics::diseaseContact(ptr, attacker);

640
        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
641 642 643
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
644

scrawl's avatar
scrawl committed
645 646 647 648 649 650 651
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->getInt();
            int roll = std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100; // [0, 99]
            if (roll < chance)
            {
                MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
            }
652 653 654 655 656 657 658 659 660 661 662 663 664 665
            getCreatureStats(ptr).setAttacked(true);

            // Check for knockdown
            float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * fKnockDownMult->getFloat();
            float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified()
                    * iKnockDownOddsMult->getInt() * 0.01 + iKnockDownOddsBase->getInt();
            roll = std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100; // [0, 99]
            if (ishealth && agilityTerm <= damage && knockdownTerm <= roll)
            {
                getCreatureStats(ptr).setKnockedDown(true);

            }
            else
                getCreatureStats(ptr).setHitRecovery(true); // Is this supposed to always occur?
666

667
            if(object.isEmpty())
668 669
            {
                if(ishealth)
670
                    damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
671 672
            }
            else if(ishealth)
673
            {
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
                // 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)];

692 693 694 695
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

696 697 698 699
                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())
700
                {
701 702 703 704 705
                    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);
706 707 708 709 710

                    // Armor broken? unequip it
                    if (armorref.mCharge == 0)
                        inv.unequipItem(armor, ptr);

711 712 713 714 715 716 717 718 719 720 721 722
                    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;
                    }
723 724
                }
            }
Chris Robinson's avatar
Chris Robinson committed
725 726
        }

727 728 729 730 731 732 733 734 735 736
        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());
737
            fatigue.setCurrent(fatigue.getCurrent() - damage, true);
738 739
            getCreatureStats(ptr).setFatigue(fatigue);
        }
740 741 742 743 744
    }

    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
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
        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
        }
    }


762
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
763
        const MWWorld::Ptr& actor) const
764
    {
765 766
        if(get(actor).isNpc() && get(actor).getNpcStats(actor).isWerewolf())
        {
767 768 769
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

770
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
771 772
            if(sound) action->setSound(sound->mId);

773 774 775 776
            return action;
        }
        if(getCreatureStats(ptr).isDead())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr, true));
777 778
        if(get(ptr).getCreatureStats(ptr).isHostile())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::FailedAction("#{sActorInCombat}"));
scrawl's avatar
scrawl committed
779 780
        if(getCreatureStats(actor).getStance(MWMechanics::CreatureStats::Stance_Sneak))
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr)); // stealing
781
        return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionTalk(ptr));
782
    }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
783

784
    MWWorld::ContainerStore& Npc::getContainerStore (const MWWorld::Ptr& ptr)
785
        const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
786
    {
787
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
788

789 790 791 792 793 794 795 796 797
        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
798 799
    }

800 801
    std::string Npc::getScript (const MWWorld::Ptr& ptr) const
    {
802
        MWWorld::LiveCellRef<ESM::NPC> *ref =
803 804
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
805
        return ref->mBase->mScript;
806 807
    }

808
    float Npc::getSpeed(const MWWorld::Ptr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
809
    {
810 811
        const MWBase::World *world = MWBase::Environment::get().getWorld();
        const CustomData *npcdata = static_cast<const CustomData*>(ptr.getRefData().getCustomData());
812
        const MWMechanics::MagicEffects &mageffects = npcdata->mNpcStats.getMagicEffects();
813

814 815
        const float normalizedEncumbrance = Npc::getEncumbrance(ptr) / Npc::getCapacity(ptr);

816 817 818
        bool sneaking = ptr.getClass().getCreatureStats(ptr).getStance(MWMechanics::CreatureStats::Stance_Sneak);
        bool running = ptr.getClass().getCreatureStats(ptr).getStance(MWMechanics::CreatureStats::Stance_Run);

819
        float walkSpeed = fMinWalkSpeed->getFloat() + 0.01f*npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified()*
820 821 822
                                                      (fMaxWalkSpeed->getFloat() - fMinWalkSpeed->getFloat());
        walkSpeed *= 1.0f - fEncumberedMoveEffect->getFloat()*normalizedEncumbrance;
        walkSpeed = std::max(0.0f, walkSpeed);
823
        if(sneaking)
824
            walkSpeed *= fSneakSpeedMultiplier->getFloat();
825

826 827
        float runSpeed = walkSpeed*(0.01f * npcdata->mNpcStats.getSkill(ESM::Skill::Athletics).getModified() *
                                    fAthleticsRunBonus->getFloat() + fBaseRunMultiplier->getFloat());
828 829
        if(npcdata->mNpcStats.isWerewolf())
            runSpeed *= fWereWolfRunMult->getFloat();
830 831

        float moveSpeed;
832
        if(normalizedEncumbrance >= 1.0f)
833
            moveSpeed = 0.0f;
scrawl's avatar
scrawl committed
834
        else if(mageffects.get(ESM::MagicEffect::Levitate).mMagnitude > 0 &&
835
                world->isLevitationEnabled())
836
        {
837
            float flySpeed = 0.01f*(npcdata->mNpcStats.getAttribute(ESM::Attribute::Speed).getModified() +
scrawl's avatar
scrawl committed
838
                                    mageffects.get(ESM::MagicEffect::Levitate).mMagnitude);
839 840 841 842 843 844 845 846
            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(