npc.cpp 59.2 KB
Newer Older
1
#include "npc.hpp"
2

3 4
#include <memory>

5
#include <components/misc/constants.hpp>
scrawl's avatar
scrawl committed
6
#include <components/misc/rng.hpp>
dteviot's avatar
dteviot committed
7

8
#include <components/debug/debuglog.hpp>
Emanuel Guevel's avatar
Emanuel Guevel committed
9
#include <components/esm/loadmgef.hpp>
10
#include <components/esm/loadnpc.hpp>
11
#include <components/esm/npcstate.hpp>
12
#include <components/settings/settings.hpp>
13

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

Marc Zinnschlag's avatar
Marc Zinnschlag committed
21
#include "../mwmechanics/creaturestats.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
22
#include "../mwmechanics/npcstats.hpp"
23
#include "../mwmechanics/movement.hpp"
24
#include "../mwmechanics/spellcasting.hpp"
25
#include "../mwmechanics/disease.hpp"
26
#include "../mwmechanics/combat.hpp"
27
#include "../mwmechanics/autocalcspell.hpp"
28
#include "../mwmechanics/difficultyscaling.hpp"
29
#include "../mwmechanics/character.hpp"
dteviot's avatar
dteviot committed
30
#include "../mwmechanics/actorutil.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
31

32
#include "../mwworld/ptr.hpp"
33
#include "../mwworld/actiontalk.hpp"
scrawl's avatar
scrawl committed
34
#include "../mwworld/actionopen.hpp"
35
#include "../mwworld/failedaction.hpp"
36
#include "../mwworld/inventorystore.hpp"
Marc Zinnschlag's avatar
Marc Zinnschlag committed
37
#include "../mwworld/customdata.hpp"
38
#include "../mwphysics/physicssystem.hpp"
39
#include "../mwworld/cellstore.hpp"
40
#include "../mwworld/localscripts.hpp"
41

42
#include "../mwrender/objects.hpp"
43
#include "../mwrender/renderinginterface.hpp"
scrawl's avatar
scrawl committed
44
#include "../mwrender/npcanimation.hpp"
45

46
#include "../mwgui/tooltips.hpp"
47

Marc Zinnschlag's avatar
Marc Zinnschlag committed
48
namespace
49
{
50

51 52 53 54 55 56 57 58 59 60
    int is_even(double d) {
        double int_part;
        modf(d / 2.0, &int_part);
        return 2.0 * int_part == d;
    }

    int round_ieee_754(double d) {
        double i = floor(d);
        d -= i;
        if(d < 0.5)
61
            return static_cast<int>(i);
62
        if(d > 0.5)
63
            return static_cast<int>(i) + 1;
64
        if(is_even(i))
65 66
            return static_cast<int>(i);
        return static_cast<int>(i) + 1;
67 68
    }

69 70 71 72 73 74 75 76 77 78 79 80
    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];
81
            creatureStats.setAttribute(i, male ? attribute.mMale : attribute.mFemale);
82 83 84 85 86 87 88 89 90 91 92
        }

        // 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)
            {
93
                creatureStats.setAttribute(attribute,
94 95 96 97 98
                    creatureStats.getAttribute(attribute).getBase() + 10);
            }
        }

        // skill bonus
99
        for (int attribute=0; attribute < ESM::Attribute::Length; ++attribute)
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?
111
                float add=0.2f;
112 113 114 115 116 117 118 119 120 121 122 123
                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;
            }
124 125 126
            creatureStats.setAttribute(attribute, std::min(
                                           round_ieee_754(creatureStats.getAttribute(attribute).getBase()
                + (level-1) * modifierSum), 100) );
127
        }
128

129
        // initial health
130 131
        int strength = creatureStats.getAttribute(ESM::Attribute::Strength).getBase();
        int endurance = creatureStats.getAttribute(ESM::Attribute::Endurance).getBase();
132 133 134 135 136 137 138 139 140 141 142 143

        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;

144
        creatureStats.setHealth(floor(0.5f * (strength + endurance)) + multiplier * (creatureStats.getLevel() - 1));
145
    }
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

    /**
     * @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.
     */
161
    void autoCalculateSkills(const ESM::NPC* npc, MWMechanics::NpcStats& npcStats, const MWWorld::Ptr& ptr)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    {
        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)
            {
195 196 197 198 199
                if (race->mData.mBonus[raceSkillIndex].mSkill == skillIndex)
                {
                    raceBonus = race->mData.mBonus[raceSkillIndex].mBonus;
                    break;
                }
200 201 202 203
            }

            for (int k = 0; k < 5; ++k)
            {
204 205 206 207 208 209
                // is this a minor or major skill?
                if ((class_->mData.mSkills[k][0] == skillIndex) || (class_->mData.mSkills[k][1] == skillIndex))
                {
                    majorMultiplier = 1.0f;
                    break;
                }
210 211 212 213 214 215
            }

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

            npcStats.getSkill(skillIndex).setBase(
                  std::min(
222 223
                    round_ieee_754(
                            npcStats.getSkill(skillIndex).getBase()
224 225 226
                    + 5
                    + raceBonus
                    + specBonus
scrawl's avatar
scrawl committed
227
                    +(int(level)-1) * (majorMultiplier + specMultiplier)), 100)); // Must gracefully handle level 0
228
        }
229 230 231 232 233 234 235 236 237

        int skills[ESM::Skill::Length];
        for (int i=0; i<ESM::Skill::Length; ++i)
            skills[i] = npcStats.getSkill(i).getBase();

        int attributes[ESM::Attribute::Length];
        for (int i=0; i<ESM::Attribute::Length; ++i)
            attributes[i] = npcStats.getAttribute(i).getBase();

238 239
        std::vector<std::string> spells = MWMechanics::autoCalcNpcSpells(skills, attributes, race);
        for (std::vector<std::string>::iterator it = spells.begin(); it != spells.end(); ++it)
240
            npcStats.getSpells().add(*it);
241
    }
242 243
}

244
namespace MWClass
245
{
246 247 248 249 250 251 252 253 254 255 256 257 258 259

    class NpcCustomData : public MWWorld::CustomData
    {
    public:
        MWMechanics::NpcStats mNpcStats;
        MWMechanics::Movement mMovement;
        MWWorld::InventoryStore mInventoryStore;

        virtual MWWorld::CustomData *clone() const;

        virtual NpcCustomData& asNpcCustomData()
        {
            return *this;
        }
scrawl's avatar
scrawl committed
260 261 262 263
        virtual const NpcCustomData& asNpcCustomData() const
        {
            return *this;
        }
264 265 266 267 268 269 270
    };

    MWWorld::CustomData *NpcCustomData::clone() const
    {
        return new NpcCustomData (*this);
    }

271
    const Npc::GMST& Npc::getGmst()
272
    {
273
        static GMST gmst;
274 275 276 277
        static bool inited = false;
        if(!inited)
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
            const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();

            gmst.fMinWalkSpeed = store.find("fMinWalkSpeed");
            gmst.fMaxWalkSpeed = store.find("fMaxWalkSpeed");
            gmst.fEncumberedMoveEffect = store.find("fEncumberedMoveEffect");
            gmst.fSneakSpeedMultiplier = store.find("fSneakSpeedMultiplier");
            gmst.fAthleticsRunBonus = store.find("fAthleticsRunBonus");
            gmst.fBaseRunMultiplier = store.find("fBaseRunMultiplier");
            gmst.fMinFlySpeed = store.find("fMinFlySpeed");
            gmst.fMaxFlySpeed = store.find("fMaxFlySpeed");
            gmst.fSwimRunBase = store.find("fSwimRunBase");
            gmst.fSwimRunAthleticsMult = store.find("fSwimRunAthleticsMult");
            gmst.fJumpEncumbranceBase = store.find("fJumpEncumbranceBase");
            gmst.fJumpEncumbranceMultiplier = store.find("fJumpEncumbranceMultiplier");
            gmst.fJumpAcrobaticsBase = store.find("fJumpAcrobaticsBase");
            gmst.fJumpAcroMultiplier = store.find("fJumpAcroMultiplier");
            gmst.fJumpRunMultiplier = store.find("fJumpRunMultiplier");
            gmst.fWereWolfRunMult = store.find("fWereWolfRunMult");
            gmst.fKnockDownMult = store.find("fKnockDownMult");
            gmst.iKnockDownOddsMult = store.find("iKnockDownOddsMult");
            gmst.iKnockDownOddsBase = store.find("iKnockDownOddsBase");
299
            gmst.fCombatArmorMinMult = store.find("fCombatArmorMinMult");
300 301 302

            inited = true;
        }
303 304 305 306 307
        return gmst;
    }

    void Npc::ensureCustomData (const MWWorld::Ptr& ptr) const
    {
308 309
        if (!ptr.getRefData().getCustomData())
        {
310
            std::unique_ptr<NpcCustomData> data(new NpcCustomData);
311

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

314
            // creature stats
315
            int gold=0;
316
            if(ref->mBase->mNpdtType != ESM::NPC::NPC_WITH_AUTOCALCULATED_STATS)
317
            {
318
                gold = ref->mBase->mNpdt.mGold;
319

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

323 324 325 326 327 328 329 330
                data->mNpcStats.setAttribute(ESM::Attribute::Strength, ref->mBase->mNpdt.mStrength);
                data->mNpcStats.setAttribute(ESM::Attribute::Intelligence, ref->mBase->mNpdt.mIntelligence);
                data->mNpcStats.setAttribute(ESM::Attribute::Willpower, ref->mBase->mNpdt.mWillpower);
                data->mNpcStats.setAttribute(ESM::Attribute::Agility, ref->mBase->mNpdt.mAgility);
                data->mNpcStats.setAttribute(ESM::Attribute::Speed, ref->mBase->mNpdt.mSpeed);
                data->mNpcStats.setAttribute(ESM::Attribute::Endurance, ref->mBase->mNpdt.mEndurance);
                data->mNpcStats.setAttribute(ESM::Attribute::Personality, ref->mBase->mNpdt.mPersonality);
                data->mNpcStats.setAttribute(ESM::Attribute::Luck, ref->mBase->mNpdt.mLuck);
331

332 333 334
                data->mNpcStats.setHealth (ref->mBase->mNpdt.mHealth);
                data->mNpcStats.setMagicka (ref->mBase->mNpdt.mMana);
                data->mNpcStats.setFatigue (ref->mBase->mNpdt.mFatigue);
335

336 337 338
                data->mNpcStats.setLevel(ref->mBase->mNpdt.mLevel);
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt.mReputation);
339 340

                data->mNpcStats.setNeedRecalcDynamicStats(false);
341 342 343
            }
            else
            {
344
                gold = ref->mBase->mNpdt.mGold;
345

346
                for (int i=0; i<3; ++i)
347
                    data->mNpcStats.setDynamic (i, 10);
348

349 350 351
                data->mNpcStats.setLevel(ref->mBase->mNpdt.mLevel);
                data->mNpcStats.setBaseDisposition(ref->mBase->mNpdt.mDisposition);
                data->mNpcStats.setReputation(ref->mBase->mNpdt.mReputation);
352

353
                autoCalculateAttributes(ref->mBase, data->mNpcStats);
354
                autoCalculateSkills(ref->mBase, data->mNpcStats, ptr);
355 356

                data->mNpcStats.setNeedRecalcDynamicStats(true);
357
            }
358 359

            // Persistent actors with 0 health do not play death animation
360
            if (data->mNpcStats.isDead())
361
                data->mNpcStats.setDeathAnimationFinished(isPersistent(ptr));
362

363 364 365 366 367
            // 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)
            {
scrawl's avatar
scrawl committed
368
                if (const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().get<ESM::Spell>().search(*iter))
369 370
                    data->mNpcStats.getSpells().add (spell);
                else
371
                    Log(Debug::Warning) << "Warning: ignoring nonexistent race power '" << *iter << "' on NPC '" << ref->mBase->mId << "'";
372 373
            }

scrawl's avatar
scrawl committed
374
            if (!ref->mBase->mFaction.empty())
375 376
            {
                static const int iAutoRepFacMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
377
                        .find("iAutoRepFacMod")->mValue.getInteger();
378
                static const int iAutoRepLevMod = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
379
                        .find("iAutoRepLevMod")->mValue.getInteger();
scrawl's avatar
scrawl committed
380
                int rank = ref->mBase->getFactionRank();
381 382 383 384

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

385
            data->mNpcStats.getAiSequence().fill(ref->mBase->mAiPackage);
386

387 388 389 390
            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);
391

392
            // spells
greye's avatar
greye committed
393 394
            for (std::vector<std::string>::const_iterator iter (ref->mBase->mSpells.mList.begin());
                iter!=ref->mBase->mSpells.mList.end(); ++iter)
395
            {
scrawl's avatar
scrawl committed
396
                if (const ESM::Spell* spell = MWBase::Environment::get().getWorld()->getStore().get<ESM::Spell>().search(*iter))
397 398 399 400
                    data->mNpcStats.getSpells().add (spell);
                else
                {
                    /// \todo add option to make this a fatal error message pop-up, but default to warning for vanilla compatibility
401
                    Log(Debug::Warning) << "Warning: ignoring nonexistent spell '" << *iter << "' on NPC '" << ref->mBase->mId << "'";
402 403
                }
            }
404

405
            // inventory
406
            // setting ownership is used to make the NPC auto-equip his initial equipment only, and not bartered items
scrawl's avatar
scrawl committed
407
            data->mInventoryStore.fill(ref->mBase->mInventory, ptr.getCellRef().getRefId());
408

jefhai's avatar
jefhai committed
409 410
            data->mNpcStats.setGoldPool(gold);

411
            // store
412
            ptr.getRefData().setCustomData (data.release());
413

414
            getInventoryStore(ptr).autoEquip(ptr);
415 416 417
        }
    }

418
    void Npc::insertObjectRendering (const MWWorld::Ptr& ptr, const std::string& model, MWRender::RenderingInterface& renderingInterface) const
419
    {
420
        renderingInterface.getObjects().insertNPC(ptr);
Jason Hooks's avatar
Jason Hooks committed
421
    }
Jason Hooks's avatar
Jason Hooks committed
422

scrawl's avatar
scrawl committed
423
    bool Npc::isPersistent(const MWWorld::ConstPtr &actor) const
scrawl's avatar
scrawl committed
424
    {
scrawl's avatar
scrawl committed
425
        const MWWorld::LiveCellRef<ESM::NPC>* ref = actor.get<ESM::NPC>();
scrawl's avatar
scrawl committed
426 427 428
        return ref->mBase->mPersistent;
    }

scrawl's avatar
scrawl committed
429
    std::string Npc::getModel(const MWWorld::ConstPtr &ptr) const
greye's avatar
greye committed
430
    {
scrawl's avatar
scrawl committed
431
        const MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
432

greye's avatar
greye committed
433
        std::string model = "meshes\\base_anim.nif";
434 435
        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
436
            model = "meshes\\base_animkna.nif";
437

greye's avatar
greye committed
438
        return model;
439 440
    }

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    void Npc::getModelsToPreload(const MWWorld::Ptr &ptr, std::vector<std::string> &models) const
    {
        const MWWorld::LiveCellRef<ESM::NPC> *npc = ptr.get<ESM::NPC>();
        const ESM::Race* race = MWBase::Environment::get().getWorld()->getStore().get<ESM::Race>().search(npc->mBase->mRace);
        if(race && race->mData.mFlags & ESM::Race::Beast)
            models.push_back("meshes\\base_animkna.nif");

        // keep these always loaded just in case
        models.push_back("meshes/xargonian_swimkna.nif");
        models.push_back("meshes/xbase_anim_female.nif");
        models.push_back("meshes/xbase_anim.nif");

        if (!npc->mBase->mModel.empty())
            models.push_back("meshes/"+npc->mBase->mModel);

        if (!npc->mBase->mHead.empty())
        {
            const ESM::BodyPart* head = MWBase::Environment::get().getWorld()->getStore().get<ESM::BodyPart>().search(npc->mBase->mHead);
            if (head)
                models.push_back("meshes/"+head->mModel);
        }
        if (!npc->mBase->mHair.empty())
        {
            const ESM::BodyPart* hair = MWBase::Environment::get().getWorld()->getStore().get<ESM::BodyPart>().search(npc->mBase->mHair);
            if (hair)
                models.push_back("meshes/"+hair->mModel);
        }

scrawl's avatar
scrawl committed
469 470
        bool female = (npc->mBase->mFlags & ESM::NPC::Female);

471
        // FIXME: use const version of InventoryStore functions once they are available
scrawl's avatar
scrawl committed
472
        // preload equipped items
473 474
        const MWWorld::InventoryStore& invStore = getInventoryStore(ptr);
        for (int slot = 0; slot < MWWorld::InventoryStore::Slots; ++slot)
475
        {
476 477
            MWWorld::ConstContainerStoreIterator equipped = invStore.getSlot(slot);
            if (equipped != invStore.end())
478
            {
479 480
                std::vector<ESM::PartReference> parts;
                if(equipped->getTypeName() == typeid(ESM::Clothing).name())
481
                {
482 483 484 485 486 487 488 489 490 491 492 493 494 495
                    const ESM::Clothing *clothes = equipped->get<ESM::Clothing>()->mBase;
                    parts = clothes->mParts.mParts;
                }
                else if(equipped->getTypeName() == typeid(ESM::Armor).name())
                {
                    const ESM::Armor *armor = equipped->get<ESM::Armor>()->mBase;
                    parts = armor->mParts.mParts;
                }
                else
                {
                    std::string model = equipped->getClass().getModel(*equipped);
                    if (!model.empty())
                        models.push_back(model);
                }
496

497 498 499 500 501 502 503 504
                for (std::vector<ESM::PartReference>::const_iterator it = parts.begin(); it != parts.end(); ++it)
                {
                    std::string partname = female ? it->mFemale : it->mMale;
                    if (partname.empty())
                        partname = female ? it->mMale : it->mFemale;
                    const ESM::BodyPart* part = MWBase::Environment::get().getWorld()->getStore().get<ESM::BodyPart>().search(partname);
                    if (part && !part->mModel.empty())
                        models.push_back("meshes/"+part->mModel);
505 506 507 508
                }
            }
        }

scrawl's avatar
scrawl committed
509 510 511 512 513 514 515 516 517 518 519 520
        // preload body parts
        if (race)
        {
            const std::vector<const ESM::BodyPart*>& parts = MWRender::NpcAnimation::getBodyParts(Misc::StringUtils::lowerCase(race->mId), female, false, false);
            for (std::vector<const ESM::BodyPart*>::const_iterator it = parts.begin(); it != parts.end(); ++it)
            {
                const ESM::BodyPart* part = *it;
                if (part && !part->mModel.empty())
                    models.push_back("meshes/"+part->mModel);
            }
        }

521 522
    }

scrawl's avatar
scrawl committed
523
    std::string Npc::getName (const MWWorld::ConstPtr& ptr) const
Marc Zinnschlag's avatar
Marc Zinnschlag committed
524
    {
scrawl's avatar
scrawl committed
525
        if(ptr.getRefData().getCustomData() && ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats.isWerewolf())
526 527
        {
            const MWBase::World *world = MWBase::Environment::get().getWorld();
528
            const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();
529

530
            return store.find("sWerewolfPopup")->mValue.getString();
531
        }
Marc Zinnschlag's avatar
Marc Zinnschlag committed
532

scrawl's avatar
scrawl committed
533
        const MWWorld::LiveCellRef<ESM::NPC> *ref = ptr.get<ESM::NPC>();
greye's avatar
greye committed
534
        return ref->mBase->mName;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
535 536
    }

537
    MWMechanics::CreatureStats& Npc::getCreatureStats (const MWWorld::Ptr& ptr) const
538
    {
539
        ensureCustomData (ptr);
540

541
        return ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats;
542 543
    }

Marc Zinnschlag's avatar
Marc Zinnschlag committed
544 545
    MWMechanics::NpcStats& Npc::getNpcStats (const MWWorld::Ptr& ptr) const
    {
546
        ensureCustomData (ptr);
Marc Zinnschlag's avatar
Marc Zinnschlag committed
547

548
        return ptr.getRefData().getCustomData()->asNpcCustomData().mNpcStats;
Marc Zinnschlag's avatar
Marc Zinnschlag committed
549 550
    }

Chris Robinson's avatar
Chris Robinson committed
551

552
    void Npc::hit(const MWWorld::Ptr& ptr, float attackStrength, int type) const
Chris Robinson's avatar
Chris Robinson committed
553
    {
554
        MWBase::World *world = MWBase::Environment::get().getWorld();
555 556

        const MWWorld::Store<ESM::GameSetting> &store = world->getStore().get<ESM::GameSetting>();
557

558 559
        // Get the weapon used (if hand-to-hand, weapon = inv.end())
        MWWorld::InventoryStore &inv = getInventoryStore(ptr);
560 561 562 563
        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();
564

565
        MWMechanics::applyFatigueLoss(ptr, weapon, attackStrength);
566

567
        const float fCombatDistance = store.find("fCombatDistance")->mValue.getFloat();
scrawl's avatar
scrawl committed
568
        float dist = fCombatDistance * (!weapon.isEmpty() ?
569
                               weapon.get<ESM::Weapon>()->mBase->mData.mReach :
570
                               store.find("fHandToHandReach")->mValue.getFloat());
scrawl's avatar
scrawl committed
571

572 573
        // For AI actors, get combat targets to use in the ray cast. Only those targets will return a positive hit result.
        std::vector<MWWorld::Ptr> targetActors;
574 575
        if (ptr != MWMechanics::getPlayer())
            getCreatureStats(ptr).getAiSequence().getCombatTargets(targetActors);
576

scrawl's avatar
scrawl committed
577
        // TODO: Use second to work out the hit angle
578
        std::pair<MWWorld::Ptr, osg::Vec3f> result = world->getHitContact(ptr, dist, targetActors);
scrawl's avatar
scrawl committed
579
        MWWorld::Ptr victim = result.first;
scrawl's avatar
scrawl committed
580
        osg::Vec3f hitPosition (result.second);
Chris Robinson's avatar
Chris Robinson committed
581 582 583
        if(victim.isEmpty()) // Didn't hit anything
            return;

584
        const MWWorld::Class &othercls = victim.getClass();
585 586
        if(!othercls.isActor()) // Can't hit non-actors
            return;
587
        MWMechanics::CreatureStats &otherstats = othercls.getCreatureStats(victim);
588
        if(otherstats.isDead()) // Can't hit dead actors
Chris Robinson's avatar
Chris Robinson committed
589 590
            return;

dteviot's avatar
dteviot committed
591
        if(ptr == MWMechanics::getPlayer())
scrawl's avatar
scrawl committed
592
            MWBase::Environment::get().getWindowManager()->setEnemy(victim);
scrawl's avatar
scrawl committed
593

594
        int weapskill = ESM::Skill::HandToHand;
595
        if(!weapon.isEmpty())
596
            weapskill = weapon.getClass().getEquipmentSkill(weapon);
597

598
        float hitchance = MWMechanics::getHitChance(ptr, victim, getSkill(ptr, weapskill));
599

600
        if (Misc::Rng::roll0to99() >= hitchance)
601
        {
602
            othercls.onHit(victim, 0.0f, false, weapon, ptr, osg::Vec3f(), false);
603
            MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr);
604 605
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
606

607
        bool healthdmg;
608 609
        float damage = 0.0f;
        if(!weapon.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
610
        {
Andrei Kortunov's avatar
Andrei Kortunov committed
611
            const unsigned char *attack = nullptr;
mrcheko's avatar
mrcheko committed
612
            if(type == ESM::Weapon::AT_Chop)
613
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop;
mrcheko's avatar
mrcheko committed
614
            else if(type == ESM::Weapon::AT_Slash)
615
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mSlash;
mrcheko's avatar
mrcheko committed
616
            else if(type == ESM::Weapon::AT_Thrust)
617
                attack = weapon.get<ESM::Weapon>()->mBase->mData.mThrust;
618
            if(attack)
619
            {
620
                damage  = attack[0] + ((attack[1]-attack[0])*attackStrength);
621
            }
scrawl's avatar
scrawl committed
622
            MWMechanics::adjustWeaponDamage(damage, weapon, ptr);
623
            MWMechanics::resistNormalWeapon(victim, ptr, weapon, damage);
624
            MWMechanics::applyWerewolfDamageMult(victim, weapon, damage);
625
            MWMechanics::reduceWeaponCondition(damage, true, weapon, ptr);
626 627 628 629
            healthdmg = true;
        }
        else
        {
630
            MWMechanics::getHandToHandDamage(ptr, victim, damage, healthdmg, attackStrength);
Chris Robinson's avatar
Chris Robinson committed
631
        }
dteviot's avatar
dteviot committed
632
        if(ptr == MWMechanics::getPlayer())
scrawl's avatar
scrawl committed
633
        {
634
            skillUsageSucceeded(ptr, weapskill, 0);
635

scrawl's avatar
scrawl committed
636 637 638 639 640 641
            const MWMechanics::AiSequence& seq = victim.getClass().getCreatureStats(victim).getAiSequence();

            bool unaware = !seq.isInCombat()
                    && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(ptr, victim);
            if(unaware)
            {
642
                damage *= store.find("fCombatCriticalStrikeMult")->mValue.getFloat();
scrawl's avatar
scrawl committed
643 644 645
                MWBase::Environment::get().getWindowManager()->messageBox("#{sTargetCriticalStrike}");
                MWBase::Environment::get().getSoundManager()->playSound3D(victim, "critical damage", 1.0f, 1.0f);
            }
646
        }
scrawl's avatar
scrawl committed
647

648
        if (othercls.getCreatureStats(victim).getKnockedDown())
649
            damage *= store.find("fCombatKODamageMult")->mValue.getFloat();
650

651
        // Apply "On hit" enchanted weapons
652
        MWMechanics::applyOnStrikeEnchantment(ptr, victim, weapon, hitPosition);
653

654 655
        MWMechanics::applyElementalShields(ptr, victim);

656
        if (MWMechanics::blockMeleeAttack(ptr, victim, weapon, damage, attackStrength))
657 658
            damage = 0;

659 660 661
        if (victim == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState())
            damage = 0;

662 663
        MWMechanics::diseaseContact(victim, ptr);

664
        othercls.onHit(victim, damage, healthdmg, weapon, ptr, hitPosition, true);
Chris Robinson's avatar
Chris Robinson committed
665 666
    }

Allofich's avatar
Allofich committed
667
    void Npc::onHit(const MWWorld::Ptr &ptr, float damage, bool ishealth, const MWWorld::Ptr &object, const MWWorld::Ptr &attacker, const osg::Vec3f &hitPosition, bool successful) const
Chris Robinson's avatar
Chris Robinson committed
668
    {
669
        MWBase::SoundManager *sndMgr = MWBase::Environment::get().getSoundManager();
670
        MWMechanics::CreatureStats& stats = getCreatureStats(ptr);
671
        bool wasDead = stats.isDead();
672

673 674
        // Note OnPcHitMe is not set for friendly hits.
        bool setOnPcHitMe = true;
675

676
        // NOTE: 'object' and/or 'attacker' may be empty.
677
        if (!attacker.isEmpty() && attacker.getClass().isActor() && !stats.getAiSequence().isInCombat(attacker))
678 679
        {
            stats.setAttacked(true);
680
            setOnPcHitMe = MWBase::Environment::get().getMechanicsManager()->actorAttacked(ptr, attacker);
681
        }
682

683
        // Attacker and target store each other as hitattemptactor if they have no one stored yet
684
        if (!attacker.isEmpty() && attacker.getClass().isActor())
685 686 687
        {
            MWMechanics::CreatureStats& statsAttacker = attacker.getClass().getCreatureStats(attacker);
            // First handle the attacked actor
688
            if ((stats.getHitAttemptActorId() == -1)
689 690
                && (statsAttacker.getAiSequence().isInCombat(ptr)
                    || attacker == MWMechanics::getPlayer()))
691
                stats.setHitAttemptActorId(statsAttacker.getActorId());
692 693

            // Next handle the attacking actor
694
            if ((statsAttacker.getHitAttemptActorId() == -1)
695 696
                && (statsAttacker.getAiSequence().isInCombat(ptr)
                    || attacker == MWMechanics::getPlayer()))
697
                statsAttacker.setHitAttemptActorId(stats.getActorId());
698 699
        }

700
        if (!object.isEmpty())
701
            stats.setLastHitAttemptObject(object.getCellRef().getRefId());
702

703
        if (setOnPcHitMe && !attacker.isEmpty() && attacker == MWMechanics::getPlayer())
scrawl's avatar
scrawl committed
704
        {
705
            const std::string &script = getScript(ptr);
scrawl's avatar
scrawl committed
706 707 708 709 710
            /* Set the OnPCHitMe script variable. The script is responsible for clearing it. */
            if(!script.empty())
                ptr.getRefData().getLocals().setVarByInt(script, "onpchitme", 1);
        }

711
        if (!successful)
712 713
        {
            // Missed
714 715
            if (!attacker.isEmpty() && attacker == MWMechanics::getPlayer())
                sndMgr->playSound3D(ptr, "miss", 1.0f, 1.0f);
716 717
            return;
        }
Chris Robinson's avatar
Chris Robinson committed
718

719
        if (!object.isEmpty())
720
            stats.setLastHitObject(object.getCellRef().getRefId());
721

722

723 724 725
        if (damage > 0.0f && !object.isEmpty())
            MWMechanics::resistNormalWeapon(ptr, attacker, object, damage);

726 727 728
        if (damage < 0.001f)
            damage = 0;

729 730 731 732 733
        bool godmode = ptr == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState();

        if (godmode)
            damage = 0;

734
        if (damage > 0.0f && !attacker.isEmpty())
Chris Robinson's avatar
Chris Robinson committed
735 736 737
        {
            // 'ptr' is losing health. Play a 'hit' voiced dialog entry if not already saying
            // something, alert the character controller, scripts, etc.
738

scrawl's avatar
scrawl committed
739
            const MWWorld::ESMStore &store = MWBase::Environment::get().getWorld()->getStore();
740 741
            const GMST& gmst = getGmst();

742
            int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->mValue.getInteger();
scrawl's avatar
scrawl committed
743
            if (Misc::Rng::roll0to99() < chance)
scrawl's avatar
scrawl committed
744
                MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
745 746

            // Check for knockdown
747
            float agilityTerm = stats.getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->mValue.getFloat();
748
            float knockdownTerm = stats.getAttribute(ESM::Attribute::Agility).getModified()
749
                    * gmst.iKnockDownOddsMult->mValue.getInteger() * 0.01f + gmst.iKnockDownOddsBase->mValue.getInteger();
scrawl's avatar
scrawl committed
750
            if (ishealth && agilityTerm <= damage && knockdownTerm <= Misc::Rng::roll0to99())
751
                stats.setKnockedDown(true);