npc.cpp 57.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
#include <components/esm/loadnpc.hpp>
10
#include <components/esm/npcstate.hpp>
11

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

Marc Zinnschlag's avatar
Marc Zinnschlag committed
19
#include "../mwmechanics/creaturestats.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
20
#include "../mwmechanics/npcstats.hpp"
21
#include "../mwmechanics/movement.hpp"
22
#include "../mwmechanics/spellcasting.hpp"
23
#include "../mwmechanics/disease.hpp"
24
#include "../mwmechanics/combat.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
25

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

35
#include "../mwrender/actors.hpp"
36
#include "../mwrender/renderinginterface.hpp"
37

38
#include "../mwgui/tooltips.hpp"
39

Marc Zinnschlag's avatar
Marc Zinnschlag committed
40
namespace
41
{
42
    struct NpcCustomData : public MWWorld::CustomData
43 44
    {
        MWMechanics::NpcStats mNpcStats;
45
        MWMechanics::Movement mMovement;
46
        MWWorld::InventoryStore mInventoryStore;
47 48 49 50

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

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

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

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

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

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

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

    /**
     * @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.
     */
147
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr)
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 178 179 180
    {
        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)
            {
181 182 183 184 185
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
186 187 188 189
            }

            for (int k = 0; k < 5; ++k)
            {
190 191 192 193 194 195
                // is this a minor or major skill?
                if ((class_->mData.mSkills[k][0] == skillIndex) || (class_->mData.mSkills[k][1] == skillIndex))
                {
                    majorMultiplier = 1.0f;
                    break;
                }
196 197 198 199 200 201 202 203 204 205 206 207
                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);
                    }
                }
208 209 210 211 212 213
            }

            // 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)
            {
214 215
                specMultiplier = 0.5f;
                specBonus = 5;
216 217 218 219 220 221 222 223
            }

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

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

            inited = true;
        }
263 264
        if (!ptr.getRefData().getCustomData())
        {
265
            std::auto_ptr<NpcCustomData> data(new NpcCustomData);
266

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

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

284
            // creature stats
285
            int gold=0;
286
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
287
            {
288 289
                gold = ref->mBase->mNpdt52.mGold;

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

293 294 295 296 297 298 299 300 301
                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);

302 303 304 305 306
                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
307
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt52.mDisposition);
308
                data->mNpcStats.setReputation(ref->mBase->mNpdt52.mReputation);
309 310 311
            }
            else
            {
312 313
                gold = ref->mBase->mNpdt12.mGold;

314
                for (int i=0; i<3; ++i)
315
                    data->mNpcStats.setDynamic (i, 10);
316

317
                data->mNpcStats.setLevel(ref->mBase->mNpdt12.mLevel);
318 319
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt12.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt12.mReputation);
320

321
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
322
                autoCalculateSkills(ref->mBase, data->mNpcStats, ptr);
323
            }
324

325 326 327 328 329 330 331 332
            // race powers
            const ESM::Race *race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().find(ref->mBase->mRace);
            for (std::vector<std::string>::const_iterator iter (race->mPowers.mList.begin());
                iter!=race->mPowers.mList.end(); ++iter)
            {
                data->mNpcStats.getSpells().add (*iter);
            }

333 334 335 336 337 338 339 340 341 342 343
            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));
            }

344
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
345

346 347 348 349
            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);
350

351
            // spells
greye's avatar
greye committed
352 353
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
354
                data->mNpcStats.getSpells().add (*iter);
355

356
            // inventory
scrawl's avatar
scrawl committed
357
            data->mInventoryStore.fill(ref->mBase->mInventory, getId(ptr), "",
358 359
                                       MWBase::Environment::get().getWorld()->getStore());

jefhai's avatar
jefhai committed
360 361
            data->mNpcStats.setGoldPool(gold);

362
            // store
363
            ptr.getRefData().setCustomData (data.release());
364

365
            getInventoryStore(ptr).autoEquip(ptr); 
366 367 368
        }
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
369 370
    std::string Npc::getId (const MWWorld::Ptr& ptr) const
    {
371
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Marc Zinnschlag's avatar
Marc Zinnschlag committed
372 373
            ptr.get<ESM::NPC>();

greye's avatar
greye committed
374
        return ref->mBase->mId;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
375 376
    }

377 378 379 380 381
    void Npc::adjustPosition(const MWWorld::Ptr& ptr) const
    {
        MWBase::Environment::get().getWorld()->adjustPosition(ptr);
    }

Jason Hooks's avatar
Jason Hooks committed
382
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, MWRender::RenderingInterface& renderingInterface) const
383
    {
384
        renderingInterface.getActors().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
385
    }
Jason Hooks's avatar
Jason Hooks committed
386

387
    void Npc::insertObject(const MWWorld::Ptr& ptr, MWWorld::PhysicsSystem& physics) const
Jason Hooks's avatar
Jason Hooks committed
388
    {
389
        physics.addActor(ptr);
390
        MWBase::Environment::get().getMechanicsManager()->add(ptr);
391 392
        if (getCreatureStats(ptr).isDead())
            MWBase::Environment::get().getWorld()->enableActorCollision(ptr, false);
greye's avatar
greye committed
393
    }
Jason Hooks's avatar
Jason Hooks committed
394

scrawl's avatar
scrawl committed
395 396 397 398 399 400
    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
401 402
    std::string Npc::getModel(const MWWorld::Ptr &ptr) const
    {
403
        MWWorld::LiveCellRef<ESM::NPC> *ref =
Jason Hooks's avatar
Jason Hooks committed
404
            ptr.get<ESM::NPC>();
greye's avatar
greye committed
405
        assert(ref->mBase != NULL);
406

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

scrawl's avatar
scrawl committed
409 410
        //int end = headID.find_last_of("head_") - 4;
        //std::string bodyRaceID = headID.substr(0, end);
greye's avatar
greye committed
411 412

        std::string model = "meshes\\base_anim.nif";
413 414
        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
415
            model = "meshes\\base_animkna.nif";
416

greye's avatar
greye committed
417
        return model;
418 419 420

    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
421 422
    std::string Npc::getName (const MWWorld::Ptr& ptr) const
    {
423 424 425 426 427 428 429
        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
430

431
        MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
432
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
433 434
    }

435
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
436
    {
437
        ensureCustomData (ptr);
438

439
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
440 441
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
442 443
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
444
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
445

446
        return dynamic_cast<NpcCustomData&> (*ptr.getRefData().getCustomData()).mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
447 448
    }

Chris Robinson's avatar
Chris Robinson committed
449

450
    void Npc::hit(const MWWorld::Ptr& ptr, int type) const
Chris Robinson's avatar
Chris Robinson committed
451
    {
452 453 454
        MWBase::World *world = MWBase::Environment::get().getWorld();
        const MWWorld::Store<ESM::GameSetting> &gmst = world->getStore().get<ESM::GameSetting>();

455 456
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
457 458 459 460
        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();
461

462 463 464 465 466 467 468 469 470 471 472 473 474
        // 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);

scrawl's avatar
scrawl committed
475 476
        const float fCombatDistance = gmst.find("fCombatDistance")->getFloat();
        float dist = fCombatDistance * (!weapon.isEmpty() ?
477
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
478
                               gmst.find("fHandToHandReach")->getFloat());
scrawl's avatar
scrawl committed
479

scrawl's avatar
scrawl committed
480
        // TODO: Use second to work out the hit angle
scrawl's avatar
scrawl committed
481 482 483
        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
484 485 486
        if(victim.isEmpty()) // Didn't hit anything
            return;

487
        const MWWorld::Class &othercls = victim.getClass();
488 489
        if(!othercls.isActor()) // Can't hit non-actors
            return;
490
        MWMechanics::CreatureStats &otherstats = othercls.getCreatureStats(victim);
491
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
492 493
            return;

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

497
        int weapskill = ESM::Skill::HandToHand;
498
        if(!weapon.isEmpty())
499
            weapskill = weapon.getClass().getEquipmentSkill(weapon);
500

501
        float hitchance = MWMechanics::getHitChance(ptr, victim, ptr.getClass().getSkill(ptr, weapskill));
502

Chris Robinson's avatar
Chris Robinson committed
503
        if((::rand()/(RAND_MAX+1.0)) > hitchance/100.0f)
504
        {
505
            othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
506 507
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
508

509
        bool healthdmg;
510
        float damage = 0.0f;
511
        MWMechanics::NpcStats &stats = getNpcStats(ptr);
512
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
513
        {
514
            const bool weaphashealth = weapon.getClass().hasItemHealth(weapon);
515
            const unsigned char *attack = NULL;
mrcheko's avatar
mrcheko committed
516
            if(type == ESM::Weapon::AT_Chop)
517
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
mrcheko's avatar
mrcheko committed
518
            else if(type == ESM::Weapon::AT_Slash)
519
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
mrcheko's avatar
mrcheko committed
520
            else if(type == ESM::Weapon::AT_Thrust)
521
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
522
            if(attack)
523
            {
524
                damage  = attack[0] + ((attack[1]-attack[0])*stats.getAttackStrength());
525 526
                damage *= fDamageStrengthBase->getFloat() +
                        (stats.getAttribute(ESM::Attribute::Strength).getModified() * fDamageStrengthMult->getFloat() * 0.1);
527 528
                if(weaphashealth)
                {
529 530
                    int weapmaxhealth = weapon.getClass().getItemMaxHealth(weapon);
                    int weaphealth = weapon.getClass().getItemHealth(weapon);
531

532
                    damage *= float(weaphealth) / weapmaxhealth;
533

534 535 536 537 538
                    if (!MWBase::Environment::get().getWorld()->getGodModeState())
                    {
                        // Reduce weapon charge by at least one, but cap at 0
                        weaphealth -= std::min(std::max(1,
                                    (int)(damage * gmst.find("fWeaponDamageMult")->getFloat())), weaphealth);
539

540 541 542 543 544 545 546
                        weapon.getCellRef().setCharge(weaphealth);
                    }

                    // Weapon broken? unequip it
                    if (weaphealth == 0)
                        weapon = *inv.unequipItem(weapon, ptr);
                }
547
            }
548 549 550 551 552 553 554 555 556
            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();
557 558
            damage  = stats.getSkill(weapskill).getModified();
            damage *= minstrike + ((maxstrike-minstrike)*stats.getAttackStrength());
559

scrawl's avatar
scrawl committed
560 561
            healthdmg = (otherstats.getFatigue().getCurrent() < 1.0f)
                    || (otherstats.getMagicEffects().get(ESM::MagicEffect::Paralyze).mMagnitude > 0);
562
            if(stats.isWerewolf())
563 564 565 566 567 568
            {
                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();
            }
569
            if(healthdmg)
570
                damage *= gmst.find("fHandtoHandHealthPer")->getFloat();
571 572 573 574

            MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
            if(stats.isWerewolf())
            {
575 576 577
                const ESM::Sound *sound = world->getStore().get<ESM::Sound>().searchRandom("WolfHit");
                if(sound)
                    sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f);
578 579 580
            }
            else
                sndMgr->playSound3D(victim, "Hand To Hand Hit", 1.0f, 1.0f);
Chris Robinson's avatar
Chris Robinson committed
581
        }
582 583
        if(ptr.getRefData().getHandle() == "player")
            skillUsageSucceeded(ptr, weapskill, 0);
584

585 586 587 588 589 590 591 592 593 594
        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();

595
        // Apply "On hit" enchanted weapons
596
        std::string enchantmentName = !weapon.isEmpty() ? weapon.getClass().getEnchantment(weapon) : "";
597 598 599 600 601 602
        if (!enchantmentName.empty())
        {
            const ESM::Enchantment* enchantment = MWBase::Environment::get().getWorld()->getStore().get<ESM::Enchantment>().find(
                        enchantmentName);
            if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes)
            {
603 604
                MWMechanics::CastSpell cast(ptr, victim);
                cast.mHitPosition = hitPosition;
605
                cast.cast(weapon);
606 607 608
            }
        }

609 610 611 612
        if (!weapon.isEmpty() && MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage))
            damage = 0;

        if (healthdmg && damage > 0)
613
            MWBase::Environment::get().getWorld()->spawnBloodEffect(victim, hitPosition);
scrawl's avatar
scrawl committed
614

615 616
        MWMechanics::diseaseContact(victim, ptr);

617
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, true);
Chris Robinson's avatar
Chris Robinson committed
618 619
    }

620
    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
621
    {
622 623
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();

624 625
        // NOTE: 'object' and/or 'attacker' may be empty.

scrawl's avatar
scrawl committed
626
        // Attacking peaceful NPCs is a crime
627
        if (!attacker.isEmpty() && !ptr.getClass().getCreatureStats(ptr).isHostile() &&
628
                !MWBase::Environment::get().getMechanicsManager()->isAggressive(ptr, attacker))
scrawl's avatar
scrawl committed
629 630
            MWBase::Environment::get().getMechanicsManager()->commitCrime(attacker, ptr, MWBase::MechanicsManager::OT_Assault);

631 632
        bool wasDead = getCreatureStats(ptr).isDead();

633 634
        getCreatureStats(ptr).setAttacked(true);

635 636 637 638 639
        if(!successful)
        {
            // TODO: Handle HitAttemptOnMe script function

            // Missed
640
            sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
641 642
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
643

644
        if(!object.isEmpty())
645
            getCreatureStats(ptr).setLastHitObject(object.getClass().getId(object));
646 647 648

        if(!attacker.isEmpty() && attacker.getRefData().getHandle() == "player")
        {
scrawl's avatar
scrawl committed
649
            const std::string &script = ptr.getClass().getScript(ptr);
650 651 652 653
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }
654

655 656 657
        if (damage > 0.0f && !object.isEmpty())
            MWMechanics::resistNormalWeapon(ptr, attacker, object, damage);

658
        if(damage > 0.0f)
Chris Robinson's avatar
Chris Robinson committed
659 660 661
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
662

scrawl's avatar
scrawl committed
663 664 665 666 667 668 669
            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");
            }
670 671 672 673 674 675 676 677 678 679 680 681 682

            // 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?
683

684
            if(ishealth && !attacker.isEmpty()) // Don't use armor mitigation for fall damage
685
            {
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
                // 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)];

704 705 706 707
                float damagediff = damage;
                damage /= std::min(1.0f + getArmorRating(ptr)/std::max(1.0f, damage), 4.0f);
                damagediff -= damage;

708 709 710 711
                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())
712
                {
713 714 715 716
                    int armorhealth = armor.getClass().getItemHealth(armor);
                    armorhealth -= std::min(std::max(1, (int)damagediff),
                                                 armorhealth);
                    armor.getCellRef().setCharge(armorhealth);
717 718

                    // Armor broken? unequip it
719
                    if (armorhealth == 0)
720 721
                        inv.unequipItem(armor, ptr);

722
                    if (ptr.getRefData().getHandle() == "player")
723
                        skillUsageSucceeded(ptr, armor.getClass().getEquipmentSkill(armor), 0);
724

725
                    switch(armor.getClass().getEquipmentSkill(armor))
726 727 728 729 730 731 732 733 734 735 736
                    {
                        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;
                    }
737
                }
738 739
                else if(ptr.getRefData().getHandle() == "player")
                    skillUsageSucceeded(ptr, ESM::Skill::Unarmored, 0);
740
            }
Chris Robinson's avatar
Chris Robinson committed
741 742
        }

743 744 745 746 747 748 749 750 751 752
        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());
753
            fatigue.setCurrent(fatigue.getCurrent() - damage, true);
754 755
            getCreatureStats(ptr).setFatigue(fatigue);
        }
756 757 758 759

        if (!wasDead && getCreatureStats(ptr).isDead())
        {
            // NPC was killed
scrawl's avatar
scrawl committed
760 761 762 763 764
            if (!attacker.isEmpty() && attacker.getClass().isNpc() && attacker.getClass().getNpcStats(attacker).isWerewolf())
            {
                attacker.getClass().getNpcStats(attacker).addWerewolfKill();
            }

765 766 767 768
            // Simple check for who attacked first: if the player attacked first, a crimeId should be set
            // Doesn't handle possible edge case where no one reported the assault, but in such a case,
            // for bystanders it is not possible to tell who attacked first, anyway.
            MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr();
scrawl's avatar
scrawl committed
769
            if (attacker == player && ptr.getClass().getNpcStats(ptr).getCrimeId() != -1 && ptr != player)
770 771
                MWBase::Environment::get().getMechanicsManager()->commitCrime(player, ptr, MWBase::MechanicsManager::OT_Murder);
        }
772 773
    }

774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    void Npc::block(const MWWorld::Ptr &ptr) const
    {
        MWWorld::InventoryStore& inv = getInventoryStore(ptr);
        MWWorld::ContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft);
        if (shield == inv.end())
            return;

        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
        switch(shield->getClass().getEquipmentSkill(*shield))
        {
            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;
            default:
                return;
        }
    }

798 799 800
    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
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
        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
        }
    }


818
    boost::shared_ptr<MWWorld::Action> Npc::activate (const MWWorld::Ptr& ptr,
819
        const MWWorld::Ptr& actor) const
820
    {
821 822 823 824
        // player got activated by another NPC
        if(ptr.getRefData().getHandle() == "player")
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionTalk(actor));

825
        if(actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf())
826
        {
827 828 829
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
            const ESM::Sound *sound = store.get<ESM::Sound>().searchRandom("WolfNPC");

830
            boost::shared_ptr<MWWorld::Action> action(new MWWorld::FailedAction("#{sWerewolfRefusal}"));
831 832
            if(sound) action->setSound(sound->mId);

833 834 835 836
            return action;
        }
        if(getCreatureStats(ptr).isDead())
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen(ptr, true));
837
        if(ptr.getClass().getCreatureStats(ptr).isHostile())
838
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::FailedAction("#{sActorInCombat}"));
scrawl's avatar
scrawl committed
839 840
        if(getCreatureStats(actor).getStance(MWMechanics::CreatureStats::Stance_Sneak))
            return boost::shared_ptr<MWWorld::Action>(new MWWorld::ActionOpen