id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
35,323
creaturestats.cpp
OpenMW_openmw/apps/openmw/mwmechanics/creaturestats.cpp
#include "creaturestats.hpp" #include <algorithm> #include <type_traits> #include <components/esm3/creaturestats.hpp> #include <components/esm3/esmreader.hpp> #include <components/esm3/esmwriter.hpp> #include <components/esm3/loadmgef.hpp> #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/player.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" namespace MWMechanics { int CreatureStats::sActorId = 0; CreatureStats::CreatureStats() { for (const ESM::Attribute& attribute : MWBase::Environment::get().getESMStore()->get<ESM::Attribute>()) { mAttributes.emplace(attribute.mId, AttributeValue{}); } } const AiSequence& CreatureStats::getAiSequence() const { return mAiSequence; } AiSequence& CreatureStats::getAiSequence() { return mAiSequence; } float CreatureStats::getFatigueTerm() const { float max = getFatigue().getModified(); float current = getFatigue().getCurrent(); float normalised = std::floor(max) == 0 ? 1 : std::max(0.0f, current / max); const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fFatigueBase = gmst.find("fFatigueBase")->mValue.getFloat(); static const float fFatigueMult = gmst.find("fFatigueMult")->mValue.getFloat(); return fFatigueBase - fFatigueMult * (1 - normalised); } const AttributeValue& CreatureStats::getAttribute(ESM::RefId id) const { return mAttributes.at(id); } const DynamicStat<float>& CreatureStats::getHealth() const { return mDynamic[0]; } const DynamicStat<float>& CreatureStats::getMagicka() const { return mDynamic[1]; } const DynamicStat<float>& CreatureStats::getFatigue() const { return mDynamic[2]; } const Spells& CreatureStats::getSpells() const { return mSpells; } const ActiveSpells& CreatureStats::getActiveSpells() const { return mActiveSpells; } const MagicEffects& CreatureStats::getMagicEffects() const { return mMagicEffects; } int CreatureStats::getLevel() const { return mLevel; } Stat<int> CreatureStats::getAiSetting(AiSetting index) const { return mAiSettings[static_cast<std::underlying_type_t<AiSetting>>(index)]; } const DynamicStat<float>& CreatureStats::getDynamic(int index) const { if (index < 0 || index > 2) { throw std::runtime_error("dynamic stat index is out of range"); } return mDynamic[index]; } Spells& CreatureStats::getSpells() { return mSpells; } ActiveSpells& CreatureStats::getActiveSpells() { return mActiveSpells; } MagicEffects& CreatureStats::getMagicEffects() { return mMagicEffects; } void CreatureStats::setAttribute(ESM::RefId id, float base) { AttributeValue current = getAttribute(id); current.setBase(base); setAttribute(id, current); } void CreatureStats::setAttribute(ESM::RefId id, const AttributeValue& value) { const AttributeValue& currentValue = mAttributes.at(id); if (value != currentValue) { mAttributes[id] = value; if (id == ESM::Attribute::Intelligence) recalculateMagicka(); else if (id == ESM::Attribute::Strength || id == ESM::Attribute::Willpower || id == ESM::Attribute::Agility || id == ESM::Attribute::Endurance) { float strength = getAttribute(ESM::Attribute::Strength).getModified(); float willpower = getAttribute(ESM::Attribute::Willpower).getModified(); float agility = getAttribute(ESM::Attribute::Agility).getModified(); float endurance = getAttribute(ESM::Attribute::Endurance).getModified(); DynamicStat<float> fatigue = getFatigue(); float currentToBaseRatio = fatigue.getBase() > 0 ? (fatigue.getCurrent() / fatigue.getBase()) : 0; fatigue.setBase(std::max(0.f, strength + willpower + agility + endurance)); fatigue.setCurrent(fatigue.getBase() * currentToBaseRatio, false, true); setFatigue(fatigue); } } } void CreatureStats::setHealth(const DynamicStat<float>& value) { setDynamic(0, value); } void CreatureStats::setMagicka(const DynamicStat<float>& value) { setDynamic(1, value); } void CreatureStats::setFatigue(const DynamicStat<float>& value) { setDynamic(2, value); } void CreatureStats::setDynamic(int index, const DynamicStat<float>& value) { if (index < 0 || index > 2) throw std::runtime_error("dynamic stat index is out of range"); mDynamic[index] = value; if (index == 0 && mDynamic[index].getCurrent() < 1) { if (!mDead) mTimeOfDeath = MWBase::Environment::get().getWorld()->getTimeStamp(); mDead = true; mDynamic[index].setCurrent(0); } } void CreatureStats::setLevel(int level) { mLevel = level; } void CreatureStats::modifyMagicEffects(const MagicEffects& effects) { bool recalc = effects.getOrDefault(ESM::MagicEffect::FortifyMaximumMagicka).getModifier() != mMagicEffects.getOrDefault(ESM::MagicEffect::FortifyMaximumMagicka).getModifier(); mMagicEffects.setModifiers(effects); if (recalc) recalculateMagicka(); } void CreatureStats::setAiSetting(AiSetting index, Stat<int> value) { mAiSettings[static_cast<std::underlying_type_t<AiSetting>>(index)] = value; } void CreatureStats::setAiSetting(AiSetting index, int base) { Stat<int> stat = getAiSetting(index); stat.setBase(base); setAiSetting(index, stat); } bool CreatureStats::isParalyzed() const { MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::Ptr player = world->getPlayerPtr(); if (world->getGodModeState() && this == &player.getClass().getCreatureStats(player)) return false; return mMagicEffects.getOrDefault(ESM::MagicEffect::Paralyze).getMagnitude() > 0; } bool CreatureStats::isDead() const { return mDead; } bool CreatureStats::isDeathAnimationFinished() const { return mDeathAnimationFinished; } void CreatureStats::setDeathAnimationFinished(bool finished) { mDeathAnimationFinished = finished; } void CreatureStats::notifyDied() { mDied = true; } bool CreatureStats::hasDied() const { return mDied; } void CreatureStats::clearHasDied() { mDied = false; } bool CreatureStats::hasBeenMurdered() const { return mMurdered; } void CreatureStats::notifyMurder() { mMurdered = true; } void CreatureStats::clearHasBeenMurdered() { mMurdered = false; } void CreatureStats::resurrect() { if (mDead) { mDynamic[0].setCurrent(mDynamic[0].getBase()); mDead = false; mDeathAnimationFinished = false; } } bool CreatureStats::hasCommonDisease() const { return mSpells.hasCommonDisease(); } bool CreatureStats::hasBlightDisease() const { return mSpells.hasBlightDisease(); } int CreatureStats::getFriendlyHits() const { return mFriendlyHits; } void CreatureStats::friendlyHit() { ++mFriendlyHits; } void CreatureStats::resetFriendlyHits() { mFriendlyHits = 0; } bool CreatureStats::hasTalkedToPlayer() const { return mTalkedTo; } void CreatureStats::talkedToPlayer() { mTalkedTo = true; } bool CreatureStats::isAlarmed() const { return mAlarmed; } void CreatureStats::setAlarmed(bool alarmed) { mAlarmed = alarmed; } bool CreatureStats::getAttacked() const { return mAttacked; } void CreatureStats::setAttacked(bool attacked) { mAttacked = attacked; } float CreatureStats::getEvasion() const { float evasion = (getAttribute(ESM::Attribute::Agility).getModified() / 5.0f) + (getAttribute(ESM::Attribute::Luck).getModified() / 10.0f); evasion *= getFatigueTerm(); evasion += std::min(100.f, mMagicEffects.getOrDefault(ESM::MagicEffect::Sanctuary).getMagnitude()); return evasion; } void CreatureStats::setLastHitObject(const ESM::RefId& objectid) { mLastHitObject = objectid; } void CreatureStats::clearLastHitObject() { mLastHitObject = ESM::RefId(); } const ESM::RefId& CreatureStats::getLastHitObject() const { return mLastHitObject; } void CreatureStats::setLastHitAttemptObject(const ESM::RefId& objectid) { mLastHitAttemptObject = objectid; } void CreatureStats::clearLastHitAttemptObject() { mLastHitAttemptObject = ESM::RefId(); } const ESM::RefId& CreatureStats::getLastHitAttemptObject() const { return mLastHitAttemptObject; } void CreatureStats::setHitAttemptActorId(int actorId) { mHitAttemptActorId = actorId; } int CreatureStats::getHitAttemptActorId() const { return mHitAttemptActorId; } void CreatureStats::addToFallHeight(float height) { mFallHeight += height; } float CreatureStats::getFallHeight() const { return mFallHeight; } float CreatureStats::land(bool isPlayer) { if (isPlayer) MWBase::Environment::get().getWorld()->getPlayer().setJumping(false); float height = mFallHeight; mFallHeight = 0; return height; } void CreatureStats::recalculateMagicka() { auto world = MWBase::Environment::get().getWorld(); float intelligence = getAttribute(ESM::Attribute::Intelligence).getModified(); float base = 1.f; const auto& player = world->getPlayerPtr(); if (this == &player.getClass().getCreatureStats(player)) base = world->getStore().get<ESM::GameSetting>().find("fPCbaseMagickaMult")->mValue.getFloat(); else base = world->getStore().get<ESM::GameSetting>().find("fNPCbaseMagickaMult")->mValue.getFloat(); double magickaFactor = base + mMagicEffects.getOrDefault(EffectKey(ESM::MagicEffect::FortifyMaximumMagicka)).getMagnitude() * 0.1; DynamicStat<float> magicka = getMagicka(); float currentToBaseRatio = magicka.getBase() > 0 ? magicka.getCurrent() / magicka.getBase() : 0; magicka.setBase(magickaFactor * intelligence); magicka.setCurrent(magicka.getBase() * currentToBaseRatio, false, true); setMagicka(magicka); } void CreatureStats::setKnockedDown(bool value) { mKnockdown = value; if (!value) // Resets the "OverOneFrame" flag setKnockedDownOverOneFrame(false); } bool CreatureStats::getKnockedDown() const { return mKnockdown; } void CreatureStats::setKnockedDownOneFrame(bool value) { mKnockdownOneFrame = value; } bool CreatureStats::getKnockedDownOneFrame() const { return mKnockdownOneFrame; } void CreatureStats::setKnockedDownOverOneFrame(bool value) { mKnockdownOverOneFrame = value; } bool CreatureStats::getKnockedDownOverOneFrame() const { return mKnockdownOverOneFrame; } void CreatureStats::setHitRecovery(bool value) { mHitRecovery = value; } bool CreatureStats::getHitRecovery() const { return mHitRecovery; } void CreatureStats::setBlock(bool value) { mBlock = value; } bool CreatureStats::getBlock() const { return mBlock; } bool CreatureStats::getMovementFlag(Flag flag) const { return (mMovementFlags & flag) != 0; } void CreatureStats::setMovementFlag(Flag flag, bool state) { if (state) mMovementFlags |= flag; else mMovementFlags &= ~flag; } bool CreatureStats::getStance(Stance flag) const { switch (flag) { case Stance_Run: return getMovementFlag(Flag_Run) || getMovementFlag(Flag_ForceRun); case Stance_Sneak: return getMovementFlag(Flag_Sneak) || getMovementFlag(Flag_ForceSneak); default: return false; } } DrawState CreatureStats::getDrawState() const { return mDrawState; } void CreatureStats::setDrawState(DrawState state) { mDrawState = state; } void CreatureStats::writeState(ESM::CreatureStats& state) const { for (size_t i = 0; i < state.mAttributes.size(); ++i) getAttribute(ESM::Attribute::indexToRefId(i)).writeState(state.mAttributes[i]); for (size_t i = 0; i < state.mDynamic.size(); ++i) mDynamic[i].writeState(state.mDynamic[i]); state.mTradeTime = mLastRestock.toEsm(); state.mGoldPool = mGoldPool; state.mDead = mDead; state.mDeathAnimationFinished = mDeathAnimationFinished; state.mDied = mDied; state.mMurdered = mMurdered; // The vanilla engine does not store friendly hits in the save file. Since there's no other mechanism // that ever resets the friendly hits (at least not to my knowledge) this should be regarded a feature // rather than a bug. // state.mFriendlyHits = mFriendlyHits; state.mTalkedTo = mTalkedTo; state.mAlarmed = mAlarmed; state.mAttacked = mAttacked; // TODO: rewrite. does this really need 3 separate bools? state.mKnockdown = mKnockdown; state.mKnockdownOneFrame = mKnockdownOneFrame; state.mKnockdownOverOneFrame = mKnockdownOverOneFrame; state.mHitRecovery = mHitRecovery; state.mBlock = mBlock; state.mMovementFlags = mMovementFlags; state.mFallHeight = mFallHeight; // TODO: vertical velocity (move from PhysicActor to CreatureStats?) state.mLastHitObject = mLastHitObject; state.mLastHitAttemptObject = mLastHitAttemptObject; state.mRecalcDynamicStats = false; state.mDrawState = static_cast<int>(mDrawState); state.mLevel = mLevel; state.mActorId = mActorId; state.mDeathAnimation = mDeathAnimation; state.mTimeOfDeath = mTimeOfDeath.toEsm(); // state.mHitAttemptActorId = mHitAttemptActorId; mSpells.writeState(state.mSpells); mActiveSpells.writeState(state.mActiveSpells); mAiSequence.writeState(state.mAiSequence); mMagicEffects.writeState(state.mMagicEffects); state.mSummonedCreatures = mSummonedCreatures; state.mSummonGraveyard = mSummonGraveyard; state.mHasAiSettings = true; for (size_t i = 0; i < state.mAiSettings.size(); ++i) mAiSettings[i].writeState(state.mAiSettings[i]); state.mMissingACDT = false; } void CreatureStats::readState(const ESM::CreatureStats& state) { if (!state.mMissingACDT) { for (size_t i = 0; i < state.mAttributes.size(); ++i) mAttributes[ESM::Attribute::indexToRefId(i)].readState(state.mAttributes[i]); for (size_t i = 0; i < state.mDynamic.size(); ++i) mDynamic[i].readState(state.mDynamic[i]); mGoldPool = state.mGoldPool; mTalkedTo = state.mTalkedTo; mAttacked = state.mAttacked; } mLastRestock = MWWorld::TimeStamp(state.mTradeTime); mDead = state.mDead; mDeathAnimationFinished = state.mDeathAnimationFinished; mDied = state.mDied; mMurdered = state.mMurdered; mAlarmed = state.mAlarmed; // TODO: rewrite. does this really need 3 separate bools? mKnockdown = state.mKnockdown; mKnockdownOneFrame = state.mKnockdownOneFrame; mKnockdownOverOneFrame = state.mKnockdownOverOneFrame; mHitRecovery = state.mHitRecovery; mBlock = state.mBlock; mMovementFlags = state.mMovementFlags; mFallHeight = state.mFallHeight; mLastHitObject = state.mLastHitObject; mLastHitAttemptObject = state.mLastHitAttemptObject; mDrawState = DrawState(state.mDrawState); mLevel = state.mLevel; mActorId = state.mActorId; mDeathAnimation = state.mDeathAnimation; mTimeOfDeath = MWWorld::TimeStamp(state.mTimeOfDeath); // mHitAttemptActorId = state.mHitAttemptActorId; mSpells.readState(state.mSpells, this); mActiveSpells.readState(state.mActiveSpells); mAiSequence.readState(state.mAiSequence); mMagicEffects.readState(state.mMagicEffects); mSummonedCreatures = state.mSummonedCreatures; mSummonGraveyard = state.mSummonGraveyard; if (state.mHasAiSettings) for (size_t i = 0; i < state.mAiSettings.size(); ++i) mAiSettings[i].readState(state.mAiSettings[i]); if (state.mRecalcDynamicStats) recalculateMagicka(); } void CreatureStats::setLastRestockTime(MWWorld::TimeStamp tradeTime) { mLastRestock = tradeTime; } MWWorld::TimeStamp CreatureStats::getLastRestockTime() const { return mLastRestock; } void CreatureStats::setGoldPool(int pool) { mGoldPool = pool; } int CreatureStats::getGoldPool() const { return mGoldPool; } int CreatureStats::getActorId() { if (mActorId == -1) mActorId = sActorId++; return mActorId; } bool CreatureStats::matchesActorId(int id) const { return mActorId != -1 && id == mActorId; } void CreatureStats::cleanup() { sActorId = 0; } void CreatureStats::writeActorIdCounter(ESM::ESMWriter& esm) { esm.startRecord(ESM::REC_ACTC); esm.writeHNT("COUN", sActorId); esm.endRecord(ESM::REC_ACTC); } void CreatureStats::readActorIdCounter(ESM::ESMReader& esm) { esm.getHNT(sActorId, "COUN"); } signed char CreatureStats::getDeathAnimation() const { return mDeathAnimation; } void CreatureStats::setDeathAnimation(signed char index) { mDeathAnimation = index; } MWWorld::TimeStamp CreatureStats::getTimeOfDeath() const { return mTimeOfDeath; } std::multimap<int, int>& CreatureStats::getSummonedCreatureMap() { return mSummonedCreatures; } std::vector<int>& CreatureStats::getSummonedCreatureGraveyard() { return mSummonGraveyard; } }
19,310
C++
.cpp
571
26.234676
119
0.645766
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,324
aifollow.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aifollow.cpp
#include "aifollow.hpp" #include <components/esm3/aisequence.hpp> #include <components/esm3/loadcell.hpp> #include <components/misc/algorithm.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/datetimemanager.hpp" #include "character.hpp" #include "creaturestats.hpp" #include "steering.hpp" namespace { osg::Vec3f::value_type getHalfExtents(const MWWorld::ConstPtr& actor) { if (actor.getClass().isNpc()) return 64; return MWBase::Environment::get().getWorld()->getHalfExtents(actor).y(); } } namespace MWMechanics { int AiFollow::mFollowIndexCounter = 0; AiFollow::AiFollow(const ESM::RefId& actorId, float duration, float x, float y, float z, bool repeat) : TypedAiPackage<AiFollow>(repeat) , mAlwaysFollow(false) , mDuration(duration) , mRemainingDuration(duration) , mX(x) , mY(y) , mZ(z) , mActive(false) , mFollowIndex(mFollowIndexCounter++) { mTargetActorRefId = actorId; } AiFollow::AiFollow( const ESM::RefId& actorId, std::string_view cellId, float duration, float x, float y, float z, bool repeat) : TypedAiPackage<AiFollow>(repeat) , mAlwaysFollow(false) , mDuration(duration) , mRemainingDuration(duration) , mX(x) , mY(y) , mZ(z) , mCellId(cellId) , mActive(false) , mFollowIndex(mFollowIndexCounter++) { mTargetActorRefId = actorId; } AiFollow::AiFollow(const MWWorld::Ptr& actor, bool commanded) : TypedAiPackage<AiFollow>(makeDefaultOptions().withShouldCancelPreviousAi(!commanded)) , mAlwaysFollow(true) , mDuration(0) , mRemainingDuration(0) , mX(0) , mY(0) , mZ(0) , mActive(false) , mFollowIndex(mFollowIndexCounter++) { mTargetActorRefId = actor.getCellRef().getRefId(); mTargetActorId = actor.getClass().getCreatureStats(actor).getActorId(); } AiFollow::AiFollow(const ESM::AiSequence::AiFollow* follow) : TypedAiPackage<AiFollow>( makeDefaultOptions().withShouldCancelPreviousAi(!follow->mCommanded).withRepeat(follow->mRepeat)) , mAlwaysFollow(follow->mAlwaysFollow) , mDuration(follow->mData.mDuration) , mRemainingDuration(follow->mRemainingDuration) , mX(follow->mData.mX) , mY(follow->mData.mY) , mZ(follow->mData.mZ) , mCellId(follow->mCellId) , mActive(follow->mActive) , mFollowIndex(mFollowIndexCounter++) { mTargetActorRefId = follow->mTargetId; mTargetActorId = follow->mTargetActorId; } bool AiFollow::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { const MWWorld::Ptr target = getTarget(); // Target is not here right now, wait for it to return // Really we should be checking whether the target is currently registered with the MechanicsManager if (target == MWWorld::Ptr() || !target.getCellRef().getCount() || !target.getRefData().isEnabled()) return false; actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Nothing); AiFollowStorage& storage = state.get<AiFollowStorage>(); bool& rotate = storage.mTurnActorToTarget; if (rotate) { if (zTurn(actor, storage.mTargetAngleRadians)) rotate = false; return false; } const osg::Vec3f actorPos(actor.getRefData().getPosition().asVec3()); const osg::Vec3f targetPos(target.getRefData().getPosition().asVec3()); const osg::Vec3f targetDir = targetPos - actorPos; // In the original engine the first follower stays closer to the player than any subsequent followers. // Followers beyond the first usually attempt to stand inside each other. osg::Vec3f::value_type floatingDistance = 0; auto followers = MWBase::Environment::get().getMechanicsManager()->getActorsFollowingByIndex(target); if (followers.size() >= 2 && followers.cbegin()->first != mFollowIndex) { for (auto& follower : followers) { auto halfExtent = getHalfExtents(follower.second); if (halfExtent > floatingDistance) floatingDistance = halfExtent; } floatingDistance += 128; } floatingDistance += getHalfExtents(target) + 64; floatingDistance += getHalfExtents(actor) * 2; short followDistance = static_cast<short>(floatingDistance); // AiFollow requires the target to be in range and within sight for the initial activation if (!mActive) { storage.mTimer -= duration; if (storage.mTimer < 0) { float activeRange = followDistance + 384.f; if (targetDir.length2() < activeRange * activeRange && MWBase::Environment::get().getWorld()->getLOS(actor, target)) mActive = true; storage.mTimer = 0.5f; } } if (!mActive) return false; if (!mAlwaysFollow) // Update if you only follow for a bit { // Check if we've run out of time if (mDuration > 0) { mRemainingDuration -= ((duration * MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale()) / 3600); if (mRemainingDuration <= 0) { mRemainingDuration = mDuration; return true; } } osg::Vec3f finalPos(mX, mY, mZ); if ((actorPos - finalPos).length2() < followDistance * followDistance) // Close-ish to final position { if (actor.getCell()->isExterior()) // Outside? { if (mCellId.empty()) // No cell to travel to { mRemainingDuration = mDuration; return true; } } else if (mCellId == actor.getCell()->getCell()->getWorldSpace()) // Cell to travel to { mRemainingDuration = mDuration; return true; } } } short baseFollowDistance = followDistance; short threshold = 30; // to avoid constant switching between moving/stopping if (storage.mMoving) followDistance -= threshold; else followDistance += threshold; if (targetDir.length2() <= followDistance * followDistance) { float faceAngleRadians = std::atan2(targetDir.x(), targetDir.y()); if (!zTurn(actor, faceAngleRadians, osg::DegreesToRadians(45.f))) { storage.mTargetAngleRadians = faceAngleRadians; storage.mTurnActorToTarget = true; } return false; } // Go to the destination storage.mMoving = !pathTo( actor, targetPos, duration, characterController.getSupportedMovementDirections(), baseFollowDistance); if (storage.mMoving) { // Check if you're far away if (targetDir.length2() > 450 * 450) actor.getClass().getCreatureStats(actor).setMovementFlag( MWMechanics::CreatureStats::Flag_Run, true); // Make NPC run else if (targetDir.length2() < 325 * 325) // Have a bit of a dead zone, otherwise npc will constantly flip between running and not // when right on the edge of the running threshold actor.getClass().getCreatureStats(actor).setMovementFlag( MWMechanics::CreatureStats::Flag_Run, false); // make NPC walk } return false; } ESM::RefId AiFollow::getFollowedActor() { return mTargetActorRefId; } bool AiFollow::isCommanded() const { return !mOptions.mShouldCancelPreviousAi; } void AiFollow::writeState(ESM::AiSequence::AiSequence& sequence) const { auto follow = std::make_unique<ESM::AiSequence::AiFollow>(); follow->mData.mX = mX; follow->mData.mY = mY; follow->mData.mZ = mZ; follow->mData.mDuration = mDuration; follow->mTargetId = mTargetActorRefId; follow->mTargetActorId = mTargetActorId; follow->mRemainingDuration = mRemainingDuration; follow->mCellId = mCellId; follow->mAlwaysFollow = mAlwaysFollow; follow->mCommanded = isCommanded(); follow->mActive = mActive; follow->mRepeat = getRepeat(); ESM::AiSequence::AiPackageContainer package; package.mType = ESM::AiSequence::Ai_Follow; package.mPackage = std::move(follow); sequence.mPackages.push_back(std::move(package)); } int AiFollow::getFollowIndex() const { return mFollowIndex; } void AiFollow::fastForward(const MWWorld::Ptr& actor, AiState& state) { // Update duration counter if this package has a duration if (mDuration > 0) mRemainingDuration--; } }
9,614
C++
.cpp
239
30.066946
117
0.602527
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,325
obstacle.cpp
OpenMW_openmw/apps/openmw/mwmechanics/obstacle.cpp
#include "obstacle.hpp" #include <array> #include <span> #include <components/detournavigator/agentbounds.hpp> #include <components/esm3/loaddoor.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "movement.hpp" namespace MWMechanics { namespace { // NOTE: determined empirically but probably need further tweaking constexpr float distanceSameSpot = 0.5f; constexpr float durationSameSpot = 1.5f; constexpr float durationToEvade = 1; struct EvadeDirection { float mMovementX; float mMovementY; MWWorld::MovementDirectionFlag mRequiredAnimation; }; constexpr EvadeDirection evadeDirections[] = { { 1.0f, 1.0f, MWWorld::MovementDirectionFlag_Forward }, // move to right and forward { 1.0f, 0.0f, MWWorld::MovementDirectionFlag_Right }, // move to right { 1.0f, -1.0f, MWWorld::MovementDirectionFlag_Back }, // move to right and backwards { 0.0f, -1.0f, MWWorld::MovementDirectionFlag_Back }, // move backwards { -1.0f, -1.0f, MWWorld::MovementDirectionFlag_Back }, // move to left and backwards { -1.0f, 0.0f, MWWorld::MovementDirectionFlag_Left }, // move to left { -1.0f, 1.0f, MWWorld::MovementDirectionFlag_Forward }, // move to left and forward }; } bool proximityToDoor(const MWWorld::Ptr& actor, float minDist) { if (getNearbyDoor(actor, minDist).isEmpty()) return false; else return true; } struct GetNearbyDoorVisitor { MWWorld::Ptr mResult; GetNearbyDoorVisitor(const MWWorld::Ptr& actor, const float minDist) : mPos(actor.getRefData().getPosition().asVec3()) , mDir(actor.getRefData().getBaseNode()->getAttitude() * osg::Vec3f(0, 1, 0)) , mMinDist(minDist) { mPos.z() = 0; mDir.normalize(); } bool operator()(const MWWorld::Ptr& ptr) { MWWorld::LiveCellRef<ESM::Door>& ref = *static_cast<MWWorld::LiveCellRef<ESM::Door>*>(ptr.getBase()); if (!ptr.getRefData().isEnabled() || ref.isDeleted()) return true; if (ptr.getClass().getDoorState(ptr) != MWWorld::DoorState::Idle) return true; const float doorRot = ref.mData.getPosition().rot[2] - ptr.getCellRef().getPosition().rot[2]; if (doorRot != 0) return true; osg::Vec3f doorPos(ref.mData.getPosition().asVec3()); doorPos.z() = 0; osg::Vec3f actorToDoor = doorPos - mPos; // Door is not close enough if (actorToDoor.length2() > mMinDist * mMinDist) return true; actorToDoor.normalize(); const float angle = std::acos(mDir * actorToDoor); // Allow 60 degrees angle between actor and door if (angle < -osg::PI / 3 || angle > osg::PI / 3) return true; mResult = ptr; return false; // found, stop searching } private: osg::Vec3f mPos, mDir; float mMinDist; }; const MWWorld::Ptr getNearbyDoor(const MWWorld::Ptr& actor, float minDist) { GetNearbyDoorVisitor visitor(actor, minDist); actor.getCell()->forEachType<ESM::Door>(visitor); return visitor.mResult; } bool isAreaOccupiedByOtherActor(const MWWorld::ConstPtr& actor, const osg::Vec3f& destination, bool ignorePlayer, std::vector<MWWorld::Ptr>* occupyingActors) { const auto world = MWBase::Environment::get().getWorld(); const osg::Vec3f halfExtents = world->getPathfindingAgentBounds(actor).mHalfExtents; const auto maxHalfExtent = std::max(halfExtents.x(), std::max(halfExtents.y(), halfExtents.z())); if (ignorePlayer) { const std::array ignore{ actor, world->getPlayerConstPtr() }; return world->isAreaOccupiedByOtherActor(destination, 2 * maxHalfExtent, ignore, occupyingActors); } const std::array ignore{ actor }; return world->isAreaOccupiedByOtherActor(destination, 2 * maxHalfExtent, ignore, occupyingActors); } ObstacleCheck::ObstacleCheck() : mEvadeDirectionIndex(std::size(evadeDirections) - 1) { } void ObstacleCheck::clear() { mWalkState = WalkState::Initial; } bool ObstacleCheck::isEvading() const { return mWalkState == WalkState::Evade; } /* * input - actor, duration (time since last check) * output - true if evasive action needs to be taken * * Walking state transitions (player greeting check not shown): * * Initial ----> Norm <--------> CheckStuck -------> Evade ---+ * ^ ^ | f ^ | t ^ | | * | | | | | | | | * | +-+ +---+ +---+ | u * | any < t < u | * +---------------------------------------------+ * * f = one reaction time * t = how long before considered stuck * u = how long to move sideways * */ void ObstacleCheck::update(const MWWorld::Ptr& actor, const osg::Vec3f& destination, float duration, MWWorld::MovementDirectionFlags supportedMovementDirection) { const auto position = actor.getRefData().getPosition().asVec3(); if (mWalkState == WalkState::Initial) { mWalkState = WalkState::Norm; mStateDuration = 0; mPrev = position; mInitialDistance = (destination - position).length(); mDestination = destination; return; } if (mWalkState != WalkState::Evade) { if (mDestination != destination) { mInitialDistance = (destination - mPrev).length(); mDestination = destination; } const float distSameSpot = distanceSameSpot * actor.getClass().getCurrentSpeed(actor) * duration; const float prevDistance = (destination - mPrev).length(); const float currentDistance = (destination - position).length(); const float movedDistance = prevDistance - currentDistance; const float movedFromInitialDistance = mInitialDistance - currentDistance; mPrev = position; if (movedDistance >= distSameSpot && movedFromInitialDistance >= distSameSpot) { mWalkState = WalkState::Norm; mStateDuration = 0; return; } if (mWalkState == WalkState::Norm) { mWalkState = WalkState::CheckStuck; mStateDuration = duration; mInitialDistance = (destination - position).length(); return; } mStateDuration += duration; if (mStateDuration < durationSameSpot) { return; } mWalkState = WalkState::Evade; mStateDuration = 0; std::size_t newEvadeDirectionIndex = mEvadeDirectionIndex; do { ++newEvadeDirectionIndex; if (newEvadeDirectionIndex == std::size(evadeDirections)) newEvadeDirectionIndex = 0; if ((evadeDirections[newEvadeDirectionIndex].mRequiredAnimation & supportedMovementDirection) != 0) break; } while (mEvadeDirectionIndex != newEvadeDirectionIndex); return; } mStateDuration += duration; if (mStateDuration >= durationToEvade) { // tried to evade, assume all is ok and start again mWalkState = WalkState::Norm; mStateDuration = 0; mPrev = position; } } void ObstacleCheck::takeEvasiveAction(MWMechanics::Movement& actorMovement) const { actorMovement.mPosition[0] = evadeDirections[mEvadeDirectionIndex].mMovementX; actorMovement.mPosition[1] = evadeDirections[mEvadeDirectionIndex].mMovementY; } }
8,494
C++
.cpp
203
31.876847
117
0.581516
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,326
activespells.cpp
OpenMW_openmw/apps/openmw/mwmechanics/activespells.cpp
#include "activespells.hpp" #include <optional> #include <components/debug/debuglog.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/strings/algorithm.hpp> #include <components/esm/generatedrefid.hpp> #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadstat.hpp> #include <components/settings/values.hpp> #include "actorutil.hpp" #include "creaturestats.hpp" #include "spellcasting.hpp" #include "spelleffects.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwrender/animation.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/manualref.hpp" namespace { bool merge(std::vector<ESM::ActiveEffect>& present, const std::vector<ESM::ActiveEffect>& queued) { // Can't merge if we already have an effect with the same effect index auto problem = std::find_if(queued.begin(), queued.end(), [&](const auto& qEffect) { return std::find_if(present.begin(), present.end(), [&](const auto& pEffect) { return pEffect.mEffectIndex == qEffect.mEffectIndex; }) != present.end(); }); if (problem != queued.end()) return false; present.insert(present.end(), queued.begin(), queued.end()); return true; } void addEffects( std::vector<ESM::ActiveEffect>& effects, const ESM::EffectList& list, bool ignoreResistances = false) { for (const auto& enam : list.mList) { if (enam.mData.mRange != ESM::RT_Self) continue; ESM::ActiveEffect effect; effect.mEffectId = enam.mData.mEffectID; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mMagnitude = 0.f; effect.mMinMagnitude = enam.mData.mMagnMin; effect.mMaxMagnitude = enam.mData.mMagnMax; effect.mEffectIndex = enam.mIndex; effect.mFlags = ESM::ActiveEffect::Flag_None; if (ignoreResistances) effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Resistances; effect.mDuration = -1; effect.mTimeLeft = -1; effects.emplace_back(effect); } } } namespace MWMechanics { ActiveSpells::IterationGuard::IterationGuard(ActiveSpells& spells) : mActiveSpells(spells) { mActiveSpells.mIterating = true; } ActiveSpells::IterationGuard::~IterationGuard() { mActiveSpells.mIterating = false; } ActiveSpells::ActiveSpellParams::ActiveSpellParams( const MWWorld::Ptr& caster, const ESM::RefId& id, std::string_view sourceName, ESM::RefNum item) : mSourceSpellId(id) , mDisplayName(sourceName) , mCasterActorId(-1) , mItem(item) , mFlags() , mWorsenings(-1) { if (!caster.isEmpty() && caster.getClass().isActor()) mCasterActorId = caster.getClass().getCreatureStats(caster).getActorId(); } ActiveSpells::ActiveSpellParams::ActiveSpellParams( const ESM::Spell* spell, const MWWorld::Ptr& actor, bool ignoreResistances) : mSourceSpellId(spell->mId) , mDisplayName(spell->mName) , mCasterActorId(actor.getClass().getCreatureStats(actor).getActorId()) , mFlags() , mWorsenings(-1) { assert(spell->mData.mType != ESM::Spell::ST_Spell && spell->mData.mType != ESM::Spell::ST_Power); setFlag(ESM::ActiveSpells::Flag_SpellStore); if (spell->mData.mType == ESM::Spell::ST_Ability) setFlag(ESM::ActiveSpells::Flag_AffectsBaseValues); addEffects(mEffects, spell->mEffects, ignoreResistances); } ActiveSpells::ActiveSpellParams::ActiveSpellParams( const MWWorld::ConstPtr& item, const ESM::Enchantment* enchantment, const MWWorld::Ptr& actor) : mSourceSpellId(item.getCellRef().getRefId()) , mDisplayName(item.getClass().getName(item)) , mCasterActorId(actor.getClass().getCreatureStats(actor).getActorId()) , mItem(item.getCellRef().getRefNum()) , mFlags() , mWorsenings(-1) { assert(enchantment->mData.mType == ESM::Enchantment::ConstantEffect); addEffects(mEffects, enchantment->mEffects); setFlag(ESM::ActiveSpells::Flag_Equipment); } ActiveSpells::ActiveSpellParams::ActiveSpellParams(const ESM::ActiveSpells::ActiveSpellParams& params) : mActiveSpellId(params.mActiveSpellId) , mSourceSpellId(params.mSourceSpellId) , mEffects(params.mEffects) , mDisplayName(params.mDisplayName) , mCasterActorId(params.mCasterActorId) , mItem(params.mItem) , mFlags(params.mFlags) , mWorsenings(params.mWorsenings) , mNextWorsening({ params.mNextWorsening }) { } ActiveSpells::ActiveSpellParams::ActiveSpellParams(const ActiveSpellParams& params, const MWWorld::Ptr& actor) : mSourceSpellId(params.mSourceSpellId) , mDisplayName(params.mDisplayName) , mCasterActorId(actor.getClass().getCreatureStats(actor).getActorId()) , mItem(params.mItem) , mFlags(params.mFlags) , mWorsenings(-1) { } ESM::ActiveSpells::ActiveSpellParams ActiveSpells::ActiveSpellParams::toEsm() const { ESM::ActiveSpells::ActiveSpellParams params; params.mActiveSpellId = mActiveSpellId; params.mSourceSpellId = mSourceSpellId; params.mEffects = mEffects; params.mDisplayName = mDisplayName; params.mCasterActorId = mCasterActorId; params.mItem = mItem; params.mFlags = mFlags; params.mWorsenings = mWorsenings; params.mNextWorsening = mNextWorsening.toEsm(); return params; } void ActiveSpells::ActiveSpellParams::setFlag(ESM::ActiveSpells::Flags flag) { mFlags = static_cast<ESM::ActiveSpells::Flags>(mFlags | flag); } void ActiveSpells::ActiveSpellParams::worsen() { ++mWorsenings; if (!mWorsenings) mNextWorsening = MWBase::Environment::get().getWorld()->getTimeStamp(); mNextWorsening += CorprusStats::sWorseningPeriod; } bool ActiveSpells::ActiveSpellParams::shouldWorsen() const { return mWorsenings >= 0 && MWBase::Environment::get().getWorld()->getTimeStamp() >= mNextWorsening; } void ActiveSpells::ActiveSpellParams::resetWorsenings() { mWorsenings = -1; } ESM::RefId ActiveSpells::ActiveSpellParams::getEnchantment() const { // Enchantment id is not stored directly. Instead the enchanted item is stored. const auto& store = MWBase::Environment::get().getESMStore(); switch (store->find(mSourceSpellId)) { case ESM::REC_ARMO: return store->get<ESM::Armor>().find(mSourceSpellId)->mEnchant; case ESM::REC_BOOK: return store->get<ESM::Book>().find(mSourceSpellId)->mEnchant; case ESM::REC_CLOT: return store->get<ESM::Clothing>().find(mSourceSpellId)->mEnchant; case ESM::REC_WEAP: return store->get<ESM::Weapon>().find(mSourceSpellId)->mEnchant; default: return {}; } } const ESM::Spell* ActiveSpells::ActiveSpellParams::getSpell() const { return MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(getSourceSpellId()); } bool ActiveSpells::ActiveSpellParams::hasFlag(ESM::ActiveSpells::Flags flags) const { return static_cast<ESM::ActiveSpells::Flags>(mFlags & flags) == flags; } void ActiveSpells::update(const MWWorld::Ptr& ptr, float duration) { if (mIterating) return; auto& creatureStats = ptr.getClass().getCreatureStats(ptr); assert(&creatureStats.getActiveSpells() == this); IterationGuard guard{ *this }; // Erase no longer active spells and effects for (auto spellIt = mSpells.begin(); spellIt != mSpells.end();) { if (!spellIt->hasFlag(ESM::ActiveSpells::Flag_Temporary)) { ++spellIt; continue; } bool removedSpell = false; for (auto effectIt = spellIt->mEffects.begin(); effectIt != spellIt->mEffects.end();) { if (effectIt->mFlags & ESM::ActiveEffect::Flag_Remove && effectIt->mTimeLeft <= 0.f) { auto effect = *effectIt; effectIt = spellIt->mEffects.erase(effectIt); onMagicEffectRemoved(ptr, *spellIt, effect); removedSpell = applyPurges(ptr, &spellIt, &effectIt); if (removedSpell) break; } else { ++effectIt; } } if (removedSpell) continue; if (spellIt->mEffects.empty()) spellIt = mSpells.erase(spellIt); else ++spellIt; } for (const auto& spell : mQueue) addToSpells(ptr, spell); mQueue.clear(); // Vanilla only does this on cell change I think const auto& spells = creatureStats.getSpells(); for (const ESM::Spell* spell : spells) { if (spell->mData.mType != ESM::Spell::ST_Spell && spell->mData.mType != ESM::Spell::ST_Power && !isSpellActive(spell->mId)) { mSpells.emplace_back(ActiveSpellParams{ spell, ptr }); mSpells.back().setActiveSpellId(MWBase::Environment::get().getESMStore()->generateId()); } } bool updateSpellWindow = false; if (ptr.getClass().hasInventoryStore(ptr) && !(creatureStats.isDead() && !creatureStats.isDeathAnimationFinished())) { auto& store = ptr.getClass().getInventoryStore(ptr); if (store.getInvListener() != nullptr) { bool playNonLooping = !store.isFirstEquip(); const auto world = MWBase::Environment::get().getWorld(); for (int slotIndex = 0; slotIndex < MWWorld::InventoryStore::Slots; slotIndex++) { auto slot = store.getSlot(slotIndex); if (slot == store.end()) continue; const ESM::RefId& enchantmentId = slot->getClass().getEnchantment(*slot); if (enchantmentId.empty()) continue; const ESM::Enchantment* enchantment = world->getStore().get<ESM::Enchantment>().find(enchantmentId); if (enchantment->mData.mType != ESM::Enchantment::ConstantEffect) continue; if (std::find_if(mSpells.begin(), mSpells.end(), [&](const ActiveSpellParams& params) { return params.mItem == slot->getCellRef().getRefNum() && params.hasFlag(ESM::ActiveSpells::Flag_Equipment) && params.mSourceSpellId == slot->getCellRef().getRefId(); }) != mSpells.end()) continue; // world->breakInvisibility leads to a stack overflow as it calls this method so just break // invisibility manually purgeEffect(ptr, ESM::MagicEffect::Invisibility); applyPurges(ptr); ActiveSpellParams& params = mSpells.emplace_back(ActiveSpellParams{ *slot, enchantment, ptr }); params.setActiveSpellId(MWBase::Environment::get().getESMStore()->generateId()); for (const auto& effect : params.mEffects) MWMechanics::playEffects( ptr, *world->getStore().get<ESM::MagicEffect>().find(effect.mEffectId), playNonLooping); updateSpellWindow = true; } } } const MWWorld::Ptr player = MWMechanics::getPlayer(); bool updatedHitOverlay = false; bool updatedEnemy = false; // Update effects for (auto spellIt = mSpells.begin(); spellIt != mSpells.end();) { const auto caster = MWBase::Environment::get().getWorld()->searchPtrViaActorId( spellIt->mCasterActorId); // Maybe make this search outside active grid? bool removedSpell = false; std::optional<ActiveSpellParams> reflected; for (auto it = spellIt->mEffects.begin(); it != spellIt->mEffects.end();) { auto result = applyMagicEffect(ptr, caster, *spellIt, *it, duration); if (result.mType == MagicApplicationResult::Type::REFLECTED) { if (!reflected) { if (Settings::game().mClassicReflectedAbsorbSpellsBehavior) reflected = { *spellIt, caster }; else reflected = { *spellIt, ptr }; } auto& reflectedEffect = reflected->mEffects.emplace_back(*it); reflectedEffect.mFlags = ESM::ActiveEffect::Flag_Ignore_Reflect | ESM::ActiveEffect::Flag_Ignore_SpellAbsorption; it = spellIt->mEffects.erase(it); } else if (result.mType == MagicApplicationResult::Type::REMOVED) it = spellIt->mEffects.erase(it); else { ++it; if (!updatedEnemy && result.mShowHealth && caster == player && ptr != player) { MWBase::Environment::get().getWindowManager()->setEnemy(ptr); updatedEnemy = true; } if (!updatedHitOverlay && result.mShowHit && ptr == player) { MWBase::Environment::get().getWindowManager()->activateHitOverlay(false); updatedHitOverlay = true; } } removedSpell = applyPurges(ptr, &spellIt, &it); if (removedSpell) break; } if (reflected) { const ESM::Static* reflectStatic = MWBase::Environment::get().getESMStore()->get<ESM::Static>().find( ESM::RefId::stringRefId("VFX_Reflect")); MWRender::Animation* animation = MWBase::Environment::get().getWorld()->getAnimation(ptr); if (animation && !reflectStatic->mModel.empty()) animation->addEffect(Misc::ResourceHelpers::correctMeshPath(reflectStatic->mModel), ESM::MagicEffect::indexToName(ESM::MagicEffect::Reflect), false); caster.getClass().getCreatureStats(caster).getActiveSpells().addSpell(*reflected); } if (removedSpell) continue; bool remove = false; if (spellIt->hasFlag(ESM::ActiveSpells::Flag_SpellStore)) { try { remove = !spells.hasSpell(spellIt->mSourceSpellId); } catch (const std::runtime_error& e) { remove = true; Log(Debug::Error) << "Removing active effect: " << e.what(); } } else if (spellIt->hasFlag(ESM::ActiveSpells::Flag_Equipment)) { // Remove effects tied to equipment that has been unequipped const auto& store = ptr.getClass().getInventoryStore(ptr); remove = true; for (int slotIndex = 0; slotIndex < MWWorld::InventoryStore::Slots; slotIndex++) { auto slot = store.getSlot(slotIndex); if (slot != store.end() && slot->getCellRef().getRefNum().isSet() && slot->getCellRef().getRefNum() == spellIt->mItem) { remove = false; break; } } } if (remove) { auto params = *spellIt; spellIt = mSpells.erase(spellIt); for (const auto& effect : params.mEffects) onMagicEffectRemoved(ptr, params, effect); applyPurges(ptr, &spellIt); updateSpellWindow = true; continue; } ++spellIt; } if (Settings::game().mClassicCalmSpellsBehavior) { ESM::MagicEffect::Effects effect = ptr.getClass().isNpc() ? ESM::MagicEffect::CalmHumanoid : ESM::MagicEffect::CalmCreature; if (creatureStats.getMagicEffects().getOrDefault(effect).getMagnitude() > 0.f) creatureStats.getAiSequence().stopCombat(); } if (ptr == player && updateSpellWindow) { // Something happened with the spell list -- possibly while the game is paused, // so we want to make the spell window get the memo. // We don't normally want to do this, so this targets constant enchantments. MWBase::Environment::get().getWindowManager()->updateSpellWindow(); } } void ActiveSpells::addToSpells(const MWWorld::Ptr& ptr, const ActiveSpellParams& spell) { if (!spell.hasFlag(ESM::ActiveSpells::Flag_Stackable)) { auto found = std::find_if(mSpells.begin(), mSpells.end(), [&](const auto& existing) { return spell.mSourceSpellId == existing.mSourceSpellId && spell.mCasterActorId == existing.mCasterActorId && spell.mItem == existing.mItem; }); if (found != mSpells.end()) { if (merge(found->mEffects, spell.mEffects)) return; auto params = *found; mSpells.erase(found); for (const auto& effect : params.mEffects) onMagicEffectRemoved(ptr, params, effect); } } mSpells.emplace_back(spell); mSpells.back().setActiveSpellId(MWBase::Environment::get().getESMStore()->generateId()); } ActiveSpells::ActiveSpells() : mIterating(false) { } ActiveSpells::TIterator ActiveSpells::begin() const { return mSpells.begin(); } ActiveSpells::TIterator ActiveSpells::end() const { return mSpells.end(); } ActiveSpells::TIterator ActiveSpells::getActiveSpellById(const ESM::RefId& id) { for (TIterator it = begin(); it != end(); it++) if (it->getActiveSpellId() == id) return it; return end(); } bool ActiveSpells::isSpellActive(const ESM::RefId& id) const { return std::find_if(mSpells.begin(), mSpells.end(), [&](const auto& spell) { return spell.mSourceSpellId == id; }) != mSpells.end(); } bool ActiveSpells::isEnchantmentActive(const ESM::RefId& id) const { const auto& store = MWBase::Environment::get().getESMStore(); if (store->get<ESM::Enchantment>().search(id) == nullptr) return false; return std::find_if(mSpells.begin(), mSpells.end(), [&](const auto& spell) { return spell.getEnchantment() == id; }) != mSpells.end(); } void ActiveSpells::addSpell(const ActiveSpellParams& params) { mQueue.emplace_back(params); } void ActiveSpells::addSpell(const ESM::Spell* spell, const MWWorld::Ptr& actor) { mQueue.emplace_back(ActiveSpellParams{ spell, actor, true }); } void ActiveSpells::purge(ParamsPredicate predicate, const MWWorld::Ptr& ptr) { assert(&ptr.getClass().getCreatureStats(ptr).getActiveSpells() == this); mPurges.emplace(predicate); if (!mIterating) { IterationGuard guard{ *this }; applyPurges(ptr); } } void ActiveSpells::purge(EffectPredicate predicate, const MWWorld::Ptr& ptr) { assert(&ptr.getClass().getCreatureStats(ptr).getActiveSpells() == this); mPurges.emplace(predicate); if (!mIterating) { IterationGuard guard{ *this }; applyPurges(ptr); } } bool ActiveSpells::applyPurges(const MWWorld::Ptr& ptr, std::list<ActiveSpellParams>::iterator* currentSpell, std::vector<ActiveEffect>::iterator* currentEffect) { bool removedCurrentSpell = false; while (!mPurges.empty()) { auto predicate = mPurges.front(); mPurges.pop(); for (auto spellIt = mSpells.begin(); spellIt != mSpells.end();) { bool isCurrentSpell = currentSpell && *currentSpell == spellIt; std::visit( [&](auto&& variant) { using T = std::decay_t<decltype(variant)>; if constexpr (std::is_same_v<T, ParamsPredicate>) { if (variant(*spellIt)) { auto params = *spellIt; spellIt = mSpells.erase(spellIt); if (isCurrentSpell) { *currentSpell = spellIt; removedCurrentSpell = true; } for (const auto& effect : params.mEffects) onMagicEffectRemoved(ptr, params, effect); } else ++spellIt; } else { static_assert(std::is_same_v<T, EffectPredicate>, "Non-exhaustive visitor"); for (auto effectIt = spellIt->mEffects.begin(); effectIt != spellIt->mEffects.end();) { if (variant(*spellIt, *effectIt)) { auto effect = *effectIt; if (isCurrentSpell && currentEffect) { auto distance = std::distance(spellIt->mEffects.begin(), *currentEffect); if (effectIt <= *currentEffect) distance--; effectIt = spellIt->mEffects.erase(effectIt); *currentEffect = spellIt->mEffects.begin() + distance; } else effectIt = spellIt->mEffects.erase(effectIt); onMagicEffectRemoved(ptr, *spellIt, effect); } else ++effectIt; } ++spellIt; } }, predicate); } } return removedCurrentSpell; } void ActiveSpells::removeEffectsBySourceSpellId(const MWWorld::Ptr& ptr, const ESM::RefId& id) { purge([=](const ActiveSpellParams& params) { return params.mSourceSpellId == id; }, ptr); } void ActiveSpells::removeEffectsByActiveSpellId(const MWWorld::Ptr& ptr, const ESM::RefId& id) { purge([=](const ActiveSpellParams& params) { return params.mActiveSpellId == id; }, ptr); } void ActiveSpells::purgeEffect(const MWWorld::Ptr& ptr, int effectId, ESM::RefId effectArg) { purge( [=](const ActiveSpellParams&, const ESM::ActiveEffect& effect) { if (effectArg.empty()) return effect.mEffectId == effectId; return effect.mEffectId == effectId && effect.getSkillOrAttribute() == effectArg; }, ptr); } void ActiveSpells::purge(const MWWorld::Ptr& ptr, int casterActorId) { purge([=](const ActiveSpellParams& params) { return params.mCasterActorId == casterActorId; }, ptr); } void ActiveSpells::clear(const MWWorld::Ptr& ptr) { mQueue.clear(); purge([](const ActiveSpellParams& params) { return true; }, ptr); } void ActiveSpells::skipWorsenings(double hours) { for (auto& spell : mSpells) { if (spell.mWorsenings >= 0) spell.mNextWorsening += hours; } } void ActiveSpells::writeState(ESM::ActiveSpells& state) const { for (const auto& spell : mSpells) state.mSpells.emplace_back(spell.toEsm()); for (const auto& spell : mQueue) state.mQueue.emplace_back(spell.toEsm()); } void ActiveSpells::readState(const ESM::ActiveSpells& state) { for (const ESM::ActiveSpells::ActiveSpellParams& spell : state.mSpells) { mSpells.emplace_back(ActiveSpellParams{ spell }); // Generate ID for older saves that didn't have any. if (mSpells.back().getActiveSpellId().empty()) mSpells.back().setActiveSpellId(MWBase::Environment::get().getESMStore()->generateId()); } for (const ESM::ActiveSpells::ActiveSpellParams& spell : state.mQueue) mQueue.emplace_back(ActiveSpellParams{ spell }); } void ActiveSpells::unloadActor(const MWWorld::Ptr& ptr) { purge([](const auto& spell) { return spell.hasFlag(ESM::ActiveSpells::Flag_Temporary); }, ptr); mQueue.clear(); } }
26,500
C++
.cpp
604
30.740066
120
0.554472
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,327
aiescort.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aiescort.cpp
#include "aiescort.hpp" #include <components/esm/util.hpp> #include <components/esm3/aisequence.hpp> #include <components/esm3/loadcell.hpp> #include <components/misc/algorithm.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/datetimemanager.hpp" #include "character.hpp" #include "creaturestats.hpp" #include "movement.hpp" /* TODO: Different behavior for AIEscort a d x y z and AIEscortCell a c d x y z. TODO: Take account for actors being in different cells. */ namespace MWMechanics { AiEscort::AiEscort(const ESM::RefId& actorId, int duration, float x, float y, float z, bool repeat) : TypedAiPackage<AiEscort>(repeat) , mX(x) , mY(y) , mZ(z) , mDuration(duration) , mRemainingDuration(static_cast<float>(duration)) { mTargetActorRefId = actorId; } AiEscort::AiEscort( const ESM::RefId& actorId, std::string_view cellId, int duration, float x, float y, float z, bool repeat) : TypedAiPackage<AiEscort>(repeat) , mCellId(cellId) , mX(x) , mY(y) , mZ(z) , mDuration(duration) , mRemainingDuration(static_cast<float>(duration)) { mTargetActorRefId = actorId; } AiEscort::AiEscort(const ESM::AiSequence::AiEscort* escort) : TypedAiPackage<AiEscort>(escort->mRepeat) , mCellId(escort->mCellId) , mX(escort->mData.mX) , mY(escort->mData.mY) , mZ(escort->mData.mZ) , mDuration(escort->mData.mDuration) , mRemainingDuration(escort->mRemainingDuration) { mTargetActorRefId = escort->mTargetId; mTargetActorId = escort->mTargetActorId; } bool AiEscort::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { // If AiEscort has ran for as long or longer then the duration specified // and the duration is not infinite, the package is complete. if (mDuration > 0) { mRemainingDuration -= ((duration * MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale()) / 3600); if (mRemainingDuration <= 0) { mRemainingDuration = mDuration; return true; } } if (!mCellId.empty() && !Misc::StringUtils::ciEqual(mCellId, actor.getCell()->getCell()->getNameId())) return false; // Not in the correct cell, pause and rely on the player to go back through a teleport door actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Nothing); actor.getClass().getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, false); const MWWorld::Ptr follower = MWBase::Environment::get().getWorld()->getPtr(mTargetActorRefId, false); const osg::Vec3f leaderPos = actor.getRefData().getPosition().asVec3(); const osg::Vec3f followerPos = follower.getRefData().getPosition().asVec3(); const osg::Vec3f halfExtents = MWBase::Environment::get().getWorld()->getHalfExtents(actor); const float maxHalfExtent = std::max(halfExtents.x(), std::max(halfExtents.y(), halfExtents.z())); if ((leaderPos - followerPos).length2() <= mMaxDist * mMaxDist) { // TESCS allows the creation of Escort packages without a specific destination constexpr float nowhere = std::numeric_limits<float>::max(); if (mX == nowhere || mY == nowhere) return true; if (mZ == nowhere) { if (mCellId.empty() && ESM::positionToExteriorCellLocation(mX, mY) == actor.getCell()->getCell()->getExteriorCellLocation()) return false; return true; } const osg::Vec3f dest(mX, mY, mZ); if (pathTo(actor, dest, duration, characterController.getSupportedMovementDirections(), maxHalfExtent)) { mRemainingDuration = mDuration; return true; } mMaxDist = maxHalfExtent + 450.0f; } else { // Stop moving if the player is too far away MWBase::Environment::get().getMechanicsManager()->playAnimationGroup(actor, "idle3", 0, 1); actor.getClass().getMovementSettings(actor).mPosition[1] = 0; mMaxDist = maxHalfExtent + 250.0f; } return false; } void AiEscort::writeState(ESM::AiSequence::AiSequence& sequence) const { auto escort = std::make_unique<ESM::AiSequence::AiEscort>(); escort->mData.mX = mX; escort->mData.mY = mY; escort->mData.mZ = mZ; escort->mData.mDuration = mDuration; escort->mTargetId = mTargetActorRefId; escort->mTargetActorId = mTargetActorId; escort->mRemainingDuration = mRemainingDuration; escort->mCellId = mCellId; escort->mRepeat = getRepeat(); ESM::AiSequence::AiPackageContainer package; package.mType = ESM::AiSequence::Ai_Escort; package.mPackage = std::move(escort); sequence.mPackages.push_back(std::move(package)); } void AiEscort::fastForward(const MWWorld::Ptr& actor, AiState& state) { // Update duration counter if this package has a duration if (mDuration > 0) mRemainingDuration--; } }
5,623
C++
.cpp
133
33.473684
117
0.629934
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,328
autocalcspell.cpp
OpenMW_openmw/apps/openmw/mwmechanics/autocalcspell.cpp
#include "autocalcspell.hpp" #include <limits> #include <components/esm/attr.hpp> #include <components/esm/refid.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadrace.hpp> #include <components/esm3/loadspel.hpp> #include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "spellutil.hpp" namespace MWMechanics { struct SchoolCaps { int mCount; int mLimit; bool mReachedLimit; int mMinCost; ESM::RefId mWeakestSpell; }; std::vector<ESM::RefId> autoCalcNpcSpells(const std::map<ESM::RefId, SkillValue>& actorSkills, const std::map<ESM::RefId, AttributeValue>& actorAttributes, const ESM::Race* race) { const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fNPCbaseMagickaMult = gmst.find("fNPCbaseMagickaMult")->mValue.getFloat(); float baseMagicka = fNPCbaseMagickaMult * actorAttributes.at(ESM::Attribute::Intelligence).getBase(); std::map<ESM::RefId, SchoolCaps> schoolCaps; for (const ESM::Skill& skill : MWBase::Environment::get().getESMStore()->get<ESM::Skill>()) { if (!skill.mSchool) continue; SchoolCaps caps; caps.mCount = 0; caps.mLimit = skill.mSchool->mAutoCalcMax; caps.mReachedLimit = skill.mSchool->mAutoCalcMax <= 0; caps.mMinCost = std::numeric_limits<int>::max(); caps.mWeakestSpell = ESM::RefId(); schoolCaps[skill.mId] = caps; } std::vector<ESM::RefId> selectedSpells; const MWWorld::Store<ESM::Spell>& spells = MWBase::Environment::get().getESMStore()->get<ESM::Spell>(); // Note: the algorithm heavily depends on the traversal order of the spells. For vanilla-compatible results the // Store must preserve the record ordering as it was in the content files. for (const ESM::Spell& spell : spells) { if (spell.mData.mType != ESM::Spell::ST_Spell) continue; if (!(spell.mData.mFlags & ESM::Spell::F_Autocalc)) continue; static const int iAutoSpellTimesCanCast = gmst.find("iAutoSpellTimesCanCast")->mValue.getInteger(); int spellCost = MWMechanics::calcSpellCost(spell); if (baseMagicka < iAutoSpellTimesCanCast * spellCost) continue; if (race && race->mPowers.exists(spell.mId)) continue; if (!attrSkillCheck(&spell, actorSkills, actorAttributes)) continue; ESM::RefId school; float skillTerm; calcWeakestSchool(&spell, actorSkills, school, skillTerm); if (school.empty()) continue; SchoolCaps& cap = schoolCaps[school]; if (cap.mReachedLimit && spellCost <= cap.mMinCost) continue; static const float fAutoSpellChance = gmst.find("fAutoSpellChance")->mValue.getFloat(); if (calcAutoCastChance(&spell, actorSkills, actorAttributes, school) < fAutoSpellChance) continue; selectedSpells.push_back(spell.mId); if (cap.mReachedLimit) { auto found = std::find(selectedSpells.begin(), selectedSpells.end(), cap.mWeakestSpell); if (found != selectedSpells.end()) selectedSpells.erase(found); cap.mMinCost = std::numeric_limits<int>::max(); for (const ESM::RefId& testSpellName : selectedSpells) { const ESM::Spell* testSpell = spells.find(testSpellName); int testSpellCost = MWMechanics::calcSpellCost(*testSpell); // int testSchool; // float dummySkillTerm; // calcWeakestSchool(testSpell, actorSkills, testSchool, dummySkillTerm); // Note: if there are multiple spells with the same cost, we pick the first one we found. // So the algorithm depends on the iteration order of the outer loop. if ( // There is a huge bug here. It is not checked that weakestSpell is of the correct school. // As result multiple SchoolCaps could have the same mWeakestSpell. Erasing the weakest spell // would then fail if another school already erased it, and so the number of spells would often // exceed the sum of limits. This bug cannot be fixed without significantly changing the results // of the spell autocalc, which will not have been playtested. // testSchool == school && testSpellCost < cap.mMinCost) { cap.mMinCost = testSpellCost; cap.mWeakestSpell = testSpell->mId; } } } else { cap.mCount += 1; if (cap.mCount == cap.mLimit) cap.mReachedLimit = true; if (spellCost < cap.mMinCost) { cap.mWeakestSpell = spell.mId; cap.mMinCost = spellCost; } } } return selectedSpells; } std::vector<ESM::RefId> autoCalcPlayerSpells(const std::map<ESM::RefId, SkillValue>& actorSkills, const std::map<ESM::RefId, AttributeValue>& actorAttributes, const ESM::Race* race) { const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); static const float fPCbaseMagickaMult = esmStore.get<ESM::GameSetting>().find("fPCbaseMagickaMult")->mValue.getFloat(); float baseMagicka = fPCbaseMagickaMult * actorAttributes.at(ESM::Attribute::Intelligence).getBase(); bool reachedLimit = false; const ESM::Spell* weakestSpell = nullptr; int minCost = std::numeric_limits<int>::max(); std::vector<ESM::RefId> selectedSpells; const MWWorld::Store<ESM::Spell>& spells = esmStore.get<ESM::Spell>(); for (const ESM::Spell& spell : spells) { if (spell.mData.mType != ESM::Spell::ST_Spell) continue; if (!(spell.mData.mFlags & ESM::Spell::F_PCStart)) continue; int spellCost = MWMechanics::calcSpellCost(spell); if (reachedLimit && spellCost <= minCost) continue; if (race && std::find(race->mPowers.mList.begin(), race->mPowers.mList.end(), spell.mId) != race->mPowers.mList.end()) continue; if (baseMagicka < spellCost) continue; static const float fAutoPCSpellChance = esmStore.get<ESM::GameSetting>().find("fAutoPCSpellChance")->mValue.getFloat(); if (calcAutoCastChance(&spell, actorSkills, actorAttributes, {}) < fAutoPCSpellChance) continue; if (!attrSkillCheck(&spell, actorSkills, actorAttributes)) continue; selectedSpells.push_back(spell.mId); if (reachedLimit) { std::vector<ESM::RefId>::iterator it = std::find(selectedSpells.begin(), selectedSpells.end(), weakestSpell->mId); if (it != selectedSpells.end()) selectedSpells.erase(it); minCost = std::numeric_limits<int>::max(); for (const ESM::RefId& testSpellName : selectedSpells) { const ESM::Spell* testSpell = esmStore.get<ESM::Spell>().find(testSpellName); int testSpellCost = MWMechanics::calcSpellCost(*testSpell); if (testSpellCost < minCost) { minCost = testSpellCost; weakestSpell = testSpell; } } } else { if (spellCost < minCost) { weakestSpell = &spell; minCost = MWMechanics::calcSpellCost(*weakestSpell); } static const unsigned int iAutoPCSpellMax = esmStore.get<ESM::GameSetting>().find("iAutoPCSpellMax")->mValue.getInteger(); if (selectedSpells.size() == iAutoPCSpellMax) reachedLimit = true; } } return selectedSpells; } bool attrSkillCheck(const ESM::Spell* spell, const std::map<ESM::RefId, SkillValue>& actorSkills, const std::map<ESM::RefId, AttributeValue>& actorAttributes) { for (const auto& spellEffect : spell->mEffects.mList) { const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(spellEffect.mData.mEffectID); static const int iAutoSpellAttSkillMin = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("iAutoSpellAttSkillMin") ->mValue.getInteger(); if ((magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill)) { ESM::RefId skill = ESM::Skill::indexToRefId(spellEffect.mData.mSkill); auto found = actorSkills.find(skill); if (found == actorSkills.end() || found->second.getBase() < iAutoSpellAttSkillMin) return false; } if ((magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute)) { ESM::RefId attribute = ESM::Attribute::indexToRefId(spellEffect.mData.mAttribute); auto found = actorAttributes.find(attribute); if (found == actorAttributes.end() || found->second.getBase() < iAutoSpellAttSkillMin) return false; } } return true; } void calcWeakestSchool(const ESM::Spell* spell, const std::map<ESM::RefId, SkillValue>& actorSkills, ESM::RefId& effectiveSchool, float& skillTerm) { // Morrowind for some reason uses a formula slightly different from magicka cost calculation float minChance = std::numeric_limits<float>::max(); for (const ESM::IndexedENAMstruct& effect : spell->mEffects.mList) { const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effect.mData.mEffectID); int minMagn = 1; int maxMagn = 1; if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)) { minMagn = effect.mData.mMagnMin; maxMagn = effect.mData.mMagnMax; } int duration = 0; if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration)) duration = effect.mData.mDuration; if (!(magicEffect->mData.mFlags & ESM::MagicEffect::AppliedOnce)) duration = std::max(1, duration); static const float fEffectCostMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fEffectCostMult") ->mValue.getFloat(); float x = 0.5 * (std::max(1, minMagn) + std::max(1, maxMagn)); x *= 0.1 * magicEffect->mData.mBaseCost; x *= 1 + duration; x += 0.05 * std::max(1, effect.mData.mArea) * magicEffect->mData.mBaseCost; x *= fEffectCostMult; if (effect.mData.mRange == ESM::RT_Target) x *= 1.5f; float s = 0.f; auto found = actorSkills.find(magicEffect->mData.mSchool); if (found != actorSkills.end()) s = 2.f * found->second.getBase(); if (s - x < minChance) { minChance = s - x; effectiveSchool = magicEffect->mData.mSchool; skillTerm = s; } } } float calcAutoCastChance(const ESM::Spell* spell, const std::map<ESM::RefId, SkillValue>& actorSkills, const std::map<ESM::RefId, AttributeValue>& actorAttributes, ESM::RefId effectiveSchool) { if (spell->mData.mType != ESM::Spell::ST_Spell) return 100.f; if (spell->mData.mFlags & ESM::Spell::F_Always) return 100.f; float skillTerm = 0; if (!effectiveSchool.empty()) { auto found = actorSkills.find(effectiveSchool); if (found != actorSkills.end()) skillTerm = 2.f * found->second.getBase(); } else calcWeakestSchool( spell, actorSkills, effectiveSchool, skillTerm); // Note effectiveSchool is unused after this float castChance = skillTerm - MWMechanics::calcSpellCost(*spell) + 0.2f * actorAttributes.at(ESM::Attribute::Willpower).getBase() + 0.1f * actorAttributes.at(ESM::Attribute::Luck).getBase(); return castChance; } }
13,722
C++
.cpp
277
34.851986
120
0.556294
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
35,329
aitravel.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aitravel.cpp
#include "aitravel.hpp" #include <algorithm> #include <components/esm3/aisequence.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "character.hpp" #include "creaturestats.hpp" #include "movement.hpp" namespace { constexpr float TRAVEL_FINISH_TIME = 2.f; bool isWithinMaxRange(const osg::Vec3f& pos1, const osg::Vec3f& pos2) { // Maximum travel distance for vanilla compatibility. // Was likely meant to prevent NPCs walking into non-loaded exterior cells, but for some reason is used in // interior cells as well. We can make this configurable at some point, but the default *must* be the below // value. Anything else will break shoddily-written content (*cough* MW *cough*) in bizarre ways. return (pos1 - pos2).length2() <= 7168 * 7168; } } namespace MWMechanics { AiTravel::AiTravel(float x, float y, float z, bool repeat, AiTravel*) : TypedAiPackage<AiTravel>(repeat) , mX(x) , mY(y) , mZ(z) , mHidden(false) , mDestinationTimer(TRAVEL_FINISH_TIME) { } AiTravel::AiTravel(float x, float y, float z, AiInternalTravel* derived) : TypedAiPackage<AiTravel>(derived) , mX(x) , mY(y) , mZ(z) , mHidden(true) , mDestinationTimer(TRAVEL_FINISH_TIME) { } AiTravel::AiTravel(float x, float y, float z, bool repeat) : AiTravel(x, y, z, repeat, this) { } AiTravel::AiTravel(const ESM::AiSequence::AiTravel* travel) : TypedAiPackage<AiTravel>(travel->mRepeat) , mX(travel->mData.mX) , mY(travel->mData.mY) , mZ(travel->mData.mZ) , mHidden(false) , mDestinationTimer(TRAVEL_FINISH_TIME) { // Hidden ESM::AiSequence::AiTravel package should be converted into MWMechanics::AiInternalTravel type assert(!travel->mHidden); } bool AiTravel::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { MWBase::MechanicsManager* mechMgr = MWBase::Environment::get().getMechanicsManager(); auto& stats = actor.getClass().getCreatureStats(actor); if (!stats.getMovementFlag(CreatureStats::Flag_ForceJump) && !stats.getMovementFlag(CreatureStats::Flag_ForceSneak) && (mechMgr->isTurningToPlayer(actor) || mechMgr->getGreetingState(actor) == Greet_InProgress)) return false; const osg::Vec3f actorPos(actor.getRefData().getPosition().asVec3()); const osg::Vec3f targetPos(mX, mY, mZ); stats.setMovementFlag(CreatureStats::Flag_Run, false); stats.setDrawState(DrawState::Nothing); // Note: we should cancel internal "return after combat" package, if original location is too far away if (!isWithinMaxRange(targetPos, actorPos)) return mHidden; if (pathTo(actor, targetPos, duration, characterController.getSupportedMovementDirections())) { actor.getClass().getMovementSettings(actor).mPosition[1] = 0; return true; } // If we've been close enough to the destination for some time give up like Morrowind. // The end condition should be pretty much accurate. // FIXME: But the timing isn't. Right now we're being very generous, // but Morrowind might stop the actor prematurely under unclear conditions. // Note Morrowind uses the halved eye level, but this is close enough. float dist = distanceIgnoreZ(actorPos, targetPos) - MWBase::Environment::get().getWorld()->getHalfExtents(actor).z(); const float endTolerance = std::max(64.f, actor.getClass().getCurrentSpeed(actor) * duration); // Even if we have entered the threshold, we might have been pushed away. Reset the timer if we're currently too // far. if (dist > endTolerance) { mDestinationTimer = TRAVEL_FINISH_TIME; return false; } mDestinationTimer -= duration; if (mDestinationTimer > 0) return false; actor.getClass().getMovementSettings(actor).mPosition[1] = 0; return true; } void AiTravel::fastForward(const MWWorld::Ptr& actor, AiState& state) { osg::Vec3f pos(mX, mY, mZ); if (!isWithinMaxRange(pos, actor.getRefData().getPosition().asVec3())) return; // does not do any validation on the travel target (whether it's in air, inside collision geometry, etc), // that is the user's responsibility MWBase::Environment::get().getWorld()->moveObject(actor, pos); actor.getClass().adjustPosition(actor, false); reset(); } void AiTravel::writeState(ESM::AiSequence::AiSequence& sequence) const { auto travel = std::make_unique<ESM::AiSequence::AiTravel>(); travel->mData.mX = mX; travel->mData.mY = mY; travel->mData.mZ = mZ; travel->mHidden = mHidden; travel->mRepeat = getRepeat(); ESM::AiSequence::AiPackageContainer package; package.mType = ESM::AiSequence::Ai_Travel; package.mPackage = std::move(travel); sequence.mPackages.push_back(std::move(package)); } AiInternalTravel::AiInternalTravel(float x, float y, float z) : AiTravel(x, y, z, this) { } AiInternalTravel::AiInternalTravel(const ESM::AiSequence::AiTravel* travel) : AiTravel(travel->mData.mX, travel->mData.mY, travel->mData.mZ, this) { } std::unique_ptr<AiPackage> AiInternalTravel::clone() const { return std::make_unique<AiInternalTravel>(*this); } }
5,816
C++
.cpp
136
35.161765
120
0.65646
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,330
spells.cpp
OpenMW_openmw/apps/openmw/mwmechanics/spells.cpp
#include "spells.hpp" #include <components/debug/debuglog.hpp> #include <components/esm3/loadspel.hpp> #include <components/esm3/spellstate.hpp> #include <components/esm3/loadmgef.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "actorutil.hpp" #include "creaturestats.hpp" #include "stat.hpp" namespace MWMechanics { Spells::Spells() {} Spells::Spells(const Spells& spells) : mSpellList(spells.mSpellList) , mSpells(spells.mSpells) , mSelectedSpell(spells.mSelectedSpell) , mUsedPowers(spells.mUsedPowers) { if (mSpellList) mSpellList->addListener(this); } Spells::Spells(Spells&& spells) : mSpellList(std::move(spells.mSpellList)) , mSpells(std::move(spells.mSpells)) , mSelectedSpell(std::move(spells.mSelectedSpell)) , mUsedPowers(std::move(spells.mUsedPowers)) { if (mSpellList) mSpellList->updateListener(&spells, this); } std::vector<const ESM::Spell*>::const_iterator Spells::begin() const { return mSpells.begin(); } std::vector<const ESM::Spell*>::const_iterator Spells::end() const { return mSpells.end(); } bool Spells::hasSpell(const ESM::RefId& spell) const { return hasSpell(SpellList::getSpell(spell)); } bool Spells::hasSpell(const ESM::Spell* spell) const { return std::find(mSpells.begin(), mSpells.end(), spell) != mSpells.end(); } void Spells::add(const ESM::Spell* spell, bool modifyBase) { if (modifyBase) mSpellList->add(spell); else addSpell(spell); } void Spells::add(const ESM::RefId& spellId, bool modifyBase) { add(SpellList::getSpell(spellId), modifyBase); } void Spells::addSpell(const ESM::Spell* spell) { if (!hasSpell(spell)) mSpells.emplace_back(spell); } void Spells::remove(const ESM::RefId& spellId, bool modifyBase) { remove(SpellList::getSpell(spellId), modifyBase); } void Spells::remove(const ESM::Spell* spell, bool modifyBase) { removeSpell(spell); if (modifyBase) mSpellList->remove(spell); if (spell->mId == mSelectedSpell) mSelectedSpell = ESM::RefId(); } void Spells::removeSpell(const ESM::Spell* spell) { const auto it = std::find(mSpells.begin(), mSpells.end(), spell); if (it != mSpells.end()) mSpells.erase(it); } void Spells::removeAllSpells() { mSpells.clear(); } void Spells::clear(bool modifyBase) { removeAllSpells(); if (modifyBase) mSpellList->clear(); } void Spells::setSelectedSpell(const ESM::RefId& spellId) { mSelectedSpell = spellId; } const ESM::RefId& Spells::getSelectedSpell() const { return mSelectedSpell; } bool Spells::hasSpellType(const ESM::Spell::SpellType type) const { auto it = std::find_if(std::begin(mSpells), std::end(mSpells), [=](const ESM::Spell* spell) { return spell->mData.mType == type; }); return it != std::end(mSpells); } bool Spells::hasCommonDisease() const { return hasSpellType(ESM::Spell::ST_Disease); } bool Spells::hasBlightDisease() const { return hasSpellType(ESM::Spell::ST_Blight); } void Spells::purge(const SpellFilter& filter) { std::vector<ESM::RefId> purged; for (auto iter = mSpells.begin(); iter != mSpells.end();) { const ESM::Spell* spell = *iter; if (filter(spell)) { iter = mSpells.erase(iter); purged.push_back(spell->mId); } else ++iter; } if (!purged.empty()) mSpellList->removeAll(purged); } void Spells::purgeCommonDisease() { purge([](auto spell) { return spell->mData.mType == ESM::Spell::ST_Disease; }); } void Spells::purgeBlightDisease() { purge([](auto spell) { return spell->mData.mType == ESM::Spell::ST_Blight && !hasCorprusEffect(spell); }); } void Spells::purgeCorprusDisease() { purge(&hasCorprusEffect); } void Spells::purgeCurses() { purge([](auto spell) { return spell->mData.mType == ESM::Spell::ST_Curse; }); } bool Spells::hasCorprusEffect(const ESM::Spell* spell) { for (const auto& effectIt : spell->mEffects.mList) { if (effectIt.mData.mEffectID == ESM::MagicEffect::Corprus) { return true; } } return false; } bool Spells::canUsePower(const ESM::Spell* spell) const { const auto it = std::find_if( std::begin(mUsedPowers), std::end(mUsedPowers), [&](auto& pair) { return pair.first == spell; }); return it == mUsedPowers.end() || it->second + 24 <= MWBase::Environment::get().getWorld()->getTimeStamp(); } void Spells::usePower(const ESM::Spell* spell) { // Updates or inserts a new entry with the current timestamp. const auto it = std::find_if( std::begin(mUsedPowers), std::end(mUsedPowers), [&](auto& pair) { return pair.first == spell; }); const auto timestamp = MWBase::Environment::get().getWorld()->getTimeStamp(); if (it == mUsedPowers.end()) mUsedPowers.emplace_back(spell, timestamp); else it->second = timestamp; } void Spells::readState(const ESM::SpellState& state, CreatureStats* creatureStats) { const auto& baseSpells = mSpellList->getSpells(); for (const ESM::RefId& id : state.mSpells) { // Discard spells that are no longer available due to changed content files const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(id); if (spell) { addSpell(spell); if (id == state.mSelectedSpell) mSelectedSpell = id; } } // Add spells from the base record for (const ESM::RefId& id : baseSpells) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(id); if (spell) addSpell(spell); } for (auto it = state.mUsedPowers.begin(); it != state.mUsedPowers.end(); ++it) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(it->first); if (!spell) continue; mUsedPowers.emplace_back(spell, MWWorld::TimeStamp(it->second)); } // Permanent effects are used only to keep the custom magnitude of corprus spells effects (after cure too), and // only in old saves. Convert data to the new approach. for (auto it = state.mPermanentSpellEffects.begin(); it != state.mPermanentSpellEffects.end(); ++it) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(it->first); if (!spell) continue; // Import data only for player, other actors should not suffer from corprus worsening. MWWorld::Ptr player = getPlayer(); if (creatureStats->getActorId() != player.getClass().getCreatureStats(player).getActorId()) return; // Note: if target actor has the Restore attribute effects, stats will be restored. for (const ESM::SpellState::PermanentSpellEffectInfo& info : it->second) { // Applied corprus effects are already in loaded stats modifiers if (info.mId == ESM::MagicEffect::FortifyAttribute) { auto id = ESM::Attribute::indexToRefId(info.mArg); AttributeValue attr = creatureStats->getAttribute(id); attr.setModifier(attr.getModifier() - info.mMagnitude); attr.damage(-info.mMagnitude); creatureStats->setAttribute(id, attr); } else if (info.mId == ESM::MagicEffect::DrainAttribute) { auto id = ESM::Attribute::indexToRefId(info.mArg); AttributeValue attr = creatureStats->getAttribute(id); attr.setModifier(attr.getModifier() + info.mMagnitude); attr.damage(info.mMagnitude); creatureStats->setAttribute(id, attr); } } } } void Spells::writeState(ESM::SpellState& state) const { const auto& baseSpells = mSpellList->getSpells(); for (const auto spell : mSpells) { // Don't save spells and powers stored in the base record if ((spell->mData.mType != ESM::Spell::ST_Spell && spell->mData.mType != ESM::Spell::ST_Power) || std::find(baseSpells.begin(), baseSpells.end(), spell->mId) == baseSpells.end()) { state.mSpells.emplace_back(spell->mId); } } state.mSelectedSpell = mSelectedSpell; for (const auto& it : mUsedPowers) state.mUsedPowers[it.first->mId] = it.second.toEsm(); } bool Spells::setSpells(const ESM::RefId& actorId) { bool result; std::tie(mSpellList, result) = MWBase::Environment::get().getESMStore()->getSpellList(actorId); mSpellList->addListener(this); addAllToInstance(mSpellList->getSpells()); return result; } void Spells::addAllToInstance(const std::vector<ESM::RefId>& spells) { for (const ESM::RefId& id : spells) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(id); if (spell) addSpell(spell); else Log(Debug::Warning) << "Warning: ignoring nonexistent spell " << id; } } Spells::~Spells() { if (mSpellList) mSpellList->removeListener(this); } }
10,385
C++
.cpp
279
28.071685
119
0.586581
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,331
aiface.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aiface.cpp
#include "aiface.hpp" #include "../mwworld/ptr.hpp" #include "steering.hpp" MWMechanics::AiFace::AiFace(float targetX, float targetY) : mTargetX(targetX) , mTargetY(targetY) { } bool MWMechanics::AiFace::execute(const MWWorld::Ptr& actor, MWMechanics::CharacterController& /*characterController*/, MWMechanics::AiState& /*state*/, float /*duration*/) { osg::Vec3f dir = osg::Vec3f(mTargetX, mTargetY, 0) - actor.getRefData().getPosition().asVec3(); return zTurn(actor, std::atan2(dir.x(), dir.y()), osg::DegreesToRadians(3.f)); }
554
C++
.cpp
14
36.857143
119
0.718284
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,332
aipursue.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aipursue.cpp
#include "aipursue.hpp" #include <components/esm3/aisequence.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "actorutil.hpp" #include "character.hpp" #include "creaturestats.hpp" #include "npcstats.hpp" namespace MWMechanics { AiPursue::AiPursue(const MWWorld::Ptr& actor) { mTargetActorId = actor.getClass().getCreatureStats(actor).getActorId(); } AiPursue::AiPursue(const ESM::AiSequence::AiPursue* pursue) { mTargetActorId = pursue->mTargetActorId; } bool AiPursue::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { if (actor.getClass().getCreatureStats(actor).isDead()) return true; const MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId); // The target to follow // Stop if the target doesn't exist // Really we should be checking whether the target is currently registered with the MechanicsManager if (target == MWWorld::Ptr() || !target.getCellRef().getCount() || !target.getRefData().isEnabled()) return true; if (isTargetMagicallyHidden(target) && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(target, actor)) return false; if (target.getClass().getCreatureStats(target).isDead()) return true; if (target.getClass().getNpcStats(target).getBounty() <= 0) return true; actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Nothing); // Set the target destination const osg::Vec3f dest = target.getRefData().getPosition().asVec3(); const osg::Vec3f actorPos = actor.getRefData().getPosition().asVec3(); const float pathTolerance = 100.f; // check the true distance in case the target is far away in Z-direction bool reached = pathTo(actor, dest, duration, characterController.getSupportedMovementDirections(), pathTolerance, (actorPos - dest).length(), PathType::Partial) && std::abs(dest.z() - actorPos.z()) < pathTolerance; if (reached) { if (!MWBase::Environment::get().getWorld()->getLOS(target, actor)) return false; MWBase::Environment::get().getWindowManager()->pushGuiMode( MWGui::GM_Dialogue, actor); // Arrest player when reached return true; } actor.getClass().getCreatureStats(actor).setMovementFlag( MWMechanics::CreatureStats::Flag_Run, true); // Make NPC run return false; } MWWorld::Ptr AiPursue::getTarget() const { if (!mCachedTarget.isEmpty()) { if (mCachedTarget.mRef->isDeleted() || !mCachedTarget.getRefData().isEnabled()) mCachedTarget = MWWorld::Ptr(); else return mCachedTarget; } mCachedTarget = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId); return mCachedTarget; } void AiPursue::writeState(ESM::AiSequence::AiSequence& sequence) const { auto pursue = std::make_unique<ESM::AiSequence::AiPursue>(); pursue->mTargetActorId = mTargetActorId; ESM::AiSequence::AiPackageContainer package; package.mType = ESM::AiSequence::Ai_Pursue; package.mPackage = std::move(pursue); sequence.mPackages.push_back(std::move(package)); } } // namespace MWMechanics
3,712
C++
.cpp
82
36.768293
113
0.655297
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,333
combat.cpp
OpenMW_openmw/apps/openmw/mwmechanics/combat.cpp
#include "combat.hpp" #include <components/misc/rng.hpp> #include <components/settings/values.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadsoun.hpp> #include "../mwbase/dialoguemanager.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/globals.hpp" #include "../mwworld/inventorystore.hpp" #include "actorutil.hpp" #include "difficultyscaling.hpp" #include "movement.hpp" #include "npcstats.hpp" #include "pathfinding.hpp" #include "spellcasting.hpp" #include "spellresistance.hpp" namespace { float signedAngleRadians(const osg::Vec3f& v1, const osg::Vec3f& v2, const osg::Vec3f& normal) { return std::atan2((normal * (v1 ^ v2)), (v1 * v2)); } } namespace MWMechanics { bool applyOnStrikeEnchantment(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim, const MWWorld::Ptr& object, const osg::Vec3f& hitPosition, const bool fromProjectile) { const ESM::RefId enchantmentName = !object.isEmpty() ? object.getClass().getEnchantment(object) : ESM::RefId(); if (!enchantmentName.empty()) { const ESM::Enchantment* enchantment = MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().find(enchantmentName); if (enchantment->mData.mType == ESM::Enchantment::WhenStrikes) { MWMechanics::CastSpell cast(attacker, victim, fromProjectile); cast.mHitPosition = hitPosition; cast.cast(object, false); // Apply magic effects directly instead of waiting a frame to allow soul trap to work on one-hit kills if (!victim.isEmpty() && victim.getClass().isActor()) MWBase::Environment::get().getMechanicsManager()->updateMagicEffects(victim); return true; } } return false; } bool blockMeleeAttack(const MWWorld::Ptr& attacker, const MWWorld::Ptr& blocker, const MWWorld::Ptr& weapon, float damage, float attackStrength) { if (!blocker.getClass().hasInventoryStore(blocker)) return false; MWMechanics::CreatureStats& blockerStats = blocker.getClass().getCreatureStats(blocker); if (blockerStats.getKnockedDown() // Used for both knockout or knockdown || blockerStats.getHitRecovery() || blockerStats.isParalyzed()) return false; if (!MWBase::Environment::get().getMechanicsManager()->isReadyToBlock(blocker)) return false; MWWorld::InventoryStore& inv = blocker.getClass().getInventoryStore(blocker); MWWorld::ContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (shield == inv.end() || shield->getType() != ESM::Armor::sRecordId) return false; if (!blocker.getRefData().getBaseNode()) return false; // shouldn't happen float angleDegrees = osg::RadiansToDegrees(signedAngleRadians( (attacker.getRefData().getPosition().asVec3() - blocker.getRefData().getPosition().asVec3()), blocker.getRefData().getBaseNode()->getAttitude() * osg::Vec3f(0, 1, 0), osg::Vec3f(0, 0, 1))); const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fCombatBlockLeftAngle = gmst.find("fCombatBlockLeftAngle")->mValue.getFloat(); if (angleDegrees < fCombatBlockLeftAngle) return false; static const float fCombatBlockRightAngle = gmst.find("fCombatBlockRightAngle")->mValue.getFloat(); if (angleDegrees > fCombatBlockRightAngle) return false; MWMechanics::CreatureStats& attackerStats = attacker.getClass().getCreatureStats(attacker); float blockTerm = blocker.getClass().getSkill(blocker, ESM::Skill::Block) + 0.2f * blockerStats.getAttribute(ESM::Attribute::Agility).getModified() + 0.1f * blockerStats.getAttribute(ESM::Attribute::Luck).getModified(); float enemySwing = attackStrength; static const float fSwingBlockMult = gmst.find("fSwingBlockMult")->mValue.getFloat(); static const float fSwingBlockBase = gmst.find("fSwingBlockBase")->mValue.getFloat(); float swingTerm = enemySwing * fSwingBlockMult + fSwingBlockBase; float blockerTerm = blockTerm * swingTerm; if (blocker.getClass().getMovementSettings(blocker).mPosition[1] <= 0) { static const float fBlockStillBonus = gmst.find("fBlockStillBonus")->mValue.getFloat(); blockerTerm *= fBlockStillBonus; } blockerTerm *= blockerStats.getFatigueTerm(); float attackerSkill = 0; if (weapon.isEmpty()) attackerSkill = attacker.getClass().getSkill(attacker, ESM::Skill::HandToHand); else attackerSkill = attacker.getClass().getSkill(attacker, weapon.getClass().getEquipmentSkill(weapon)); float attackerTerm = attackerSkill + 0.2f * attackerStats.getAttribute(ESM::Attribute::Agility).getModified() + 0.1f * attackerStats.getAttribute(ESM::Attribute::Luck).getModified(); attackerTerm *= attackerStats.getFatigueTerm(); static const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger(); static const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger(); int x = std::clamp<int>(blockerTerm - attackerTerm, iBlockMinChance, iBlockMaxChance); auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (Misc::Rng::roll0to99(prng) < x) { MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); const ESM::RefId skill = shield->getClass().getEquipmentSkill(*shield); if (skill == ESM::Skill::LightArmor) sndMgr->playSound3D(blocker, ESM::RefId::stringRefId("Light Armor Hit"), 1.0f, 1.0f); else if (skill == ESM::Skill::MediumArmor) sndMgr->playSound3D(blocker, ESM::RefId::stringRefId("Medium Armor Hit"), 1.0f, 1.0f); else if (skill == ESM::Skill::HeavyArmor) sndMgr->playSound3D(blocker, ESM::RefId::stringRefId("Heavy Armor Hit"), 1.0f, 1.0f); // Reduce shield durability by incoming damage int shieldhealth = shield->getClass().getItemHealth(*shield); shieldhealth -= std::min(shieldhealth, int(damage)); shield->getCellRef().setCharge(shieldhealth); if (shieldhealth == 0) inv.unequipItem(*shield); // Reduce blocker fatigue static const float fFatigueBlockBase = gmst.find("fFatigueBlockBase")->mValue.getFloat(); static const float fFatigueBlockMult = gmst.find("fFatigueBlockMult")->mValue.getFloat(); static const float fWeaponFatigueBlockMult = gmst.find("fWeaponFatigueBlockMult")->mValue.getFloat(); MWMechanics::DynamicStat<float> fatigue = blockerStats.getFatigue(); float normalizedEncumbrance = blocker.getClass().getNormalizedEncumbrance(blocker); normalizedEncumbrance = std::min(1.f, normalizedEncumbrance); float fatigueLoss = fFatigueBlockBase + normalizedEncumbrance * fFatigueBlockMult; if (!weapon.isEmpty()) fatigueLoss += weapon.getClass().getWeight(weapon) * attackStrength * fWeaponFatigueBlockMult; fatigue.setCurrent(fatigue.getCurrent() - fatigueLoss); blockerStats.setFatigue(fatigue); blockerStats.setBlock(true); if (blocker == getPlayer()) blocker.getClass().skillUsageSucceeded(blocker, ESM::Skill::Block, ESM::Skill::Block_Success); return true; } return false; } bool isNormalWeapon(const MWWorld::Ptr& weapon) { if (weapon.isEmpty()) return false; const int flags = weapon.get<ESM::Weapon>()->mBase->mData.mFlags; bool isSilver = flags & ESM::Weapon::Silver; bool isMagical = flags & ESM::Weapon::Magical; bool isEnchanted = !weapon.getClass().getEnchantment(weapon).empty(); return !isSilver && !isMagical && (!isEnchanted || !Settings::game().mEnchantedWeaponsAreMagical); } void resistNormalWeapon( const MWWorld::Ptr& actor, const MWWorld::Ptr& attacker, const MWWorld::Ptr& weapon, float& damage) { if (weapon.isEmpty() || !isNormalWeapon(weapon)) return; const MWMechanics::MagicEffects& effects = actor.getClass().getCreatureStats(actor).getMagicEffects(); const float resistance = effects.getOrDefault(ESM::MagicEffect::ResistNormalWeapons).getMagnitude() / 100.f; const float weakness = effects.getOrDefault(ESM::MagicEffect::WeaknessToNormalWeapons).getMagnitude() / 100.f; damage *= 1.f - std::min(1.f, resistance - weakness); if (resistance - weakness >= 1.f && attacker == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicTargetResistsWeapons}"); } void applyWerewolfDamageMult(const MWWorld::Ptr& actor, const MWWorld::Ptr& weapon, float& damage) { if (damage == 0 || weapon.isEmpty() || !actor.getClass().isNpc()) return; const int flags = weapon.get<ESM::Weapon>()->mBase->mData.mFlags; bool isSilver = flags & ESM::Weapon::Silver; if (isSilver && actor.getClass().getNpcStats(actor).isWerewolf()) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); damage *= store.get<ESM::GameSetting>().find("fWereWolfSilverWeaponDamageMult")->mValue.getFloat(); } } void projectileHit(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim, MWWorld::Ptr weapon, const MWWorld::Ptr& projectile, const osg::Vec3f& hitPosition, float attackStrength) { MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::Store<ESM::GameSetting>& gmst = world->getStore().get<ESM::GameSetting>(); bool validVictim = !victim.isEmpty() && victim.getClass().isActor(); ESM::RefId weaponSkill = ESM::Skill::Marksman; if (!weapon.isEmpty()) weaponSkill = weapon.getClass().getEquipmentSkill(weapon); float damage = 0.f; if (validVictim) { if (attacker == getPlayer()) MWBase::Environment::get().getWindowManager()->setEnemy(victim); int skillValue = attacker.getClass().getSkill(attacker, weaponSkill); if (Misc::Rng::roll0to99(world->getPrng()) >= getHitChance(attacker, victim, skillValue)) { victim.getClass().onHit(victim, damage, false, projectile, attacker, osg::Vec3f(), false, MWMechanics::DamageSourceType::Ranged); MWMechanics::reduceWeaponCondition(damage, false, weapon, attacker); return; } { const auto& attack = weapon.get<ESM::Weapon>()->mBase->mData.mChop; damage = attack[0] + ((attack[1] - attack[0]) * attackStrength); // Bow/crossbow damage } { // Arrow/bolt damage // NB in case of thrown weapons, we are applying the damage twice since projectile == weapon const auto& attack = projectile.get<ESM::Weapon>()->mBase->mData.mChop; damage += attack[0] + ((attack[1] - attack[0]) * attackStrength); } adjustWeaponDamage(damage, weapon, attacker); } reduceWeaponCondition(damage, validVictim, weapon, attacker); if (validVictim) { if (weapon == projectile || Settings::game().mOnlyAppropriateAmmunitionBypassesResistance || isNormalWeapon(weapon)) resistNormalWeapon(victim, attacker, projectile, damage); applyWerewolfDamageMult(victim, projectile, damage); if (attacker == getPlayer()) attacker.getClass().skillUsageSucceeded(attacker, weaponSkill, ESM::Skill::Weapon_SuccessfulHit); const MWMechanics::AiSequence& sequence = victim.getClass().getCreatureStats(victim).getAiSequence(); bool unaware = attacker == getPlayer() && !sequence.isInCombat() && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(attacker, victim); bool knockedDown = victim.getClass().getCreatureStats(victim).getKnockedDown(); if (knockedDown || unaware) { static const float fCombatKODamageMult = gmst.find("fCombatKODamageMult")->mValue.getFloat(); damage *= fCombatKODamageMult; if (!knockedDown) MWBase::Environment::get().getSoundManager()->playSound3D( victim, ESM::RefId::stringRefId("critical damage"), 1.0f, 1.0f); } } // Apply "On hit" effect of the projectile bool appliedEnchantment = applyOnStrikeEnchantment(attacker, victim, projectile, hitPosition, true); if (validVictim) { // Non-enchanted arrows shot at enemies have a chance to turn up in their inventory if (victim != getPlayer() && !appliedEnchantment) { static const float fProjectileThrownStoreChance = gmst.find("fProjectileThrownStoreChance")->mValue.getFloat(); if (Misc::Rng::rollProbability(world->getPrng()) < fProjectileThrownStoreChance / 100.f) victim.getClass().getContainerStore(victim).add(projectile, 1); } victim.getClass().onHit( victim, damage, true, projectile, attacker, hitPosition, true, MWMechanics::DamageSourceType::Ranged); } } float getHitChance(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim, int skillValue) { MWMechanics::CreatureStats& stats = attacker.getClass().getCreatureStats(attacker); const MWMechanics::MagicEffects& mageffects = stats.getMagicEffects(); MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::Store<ESM::GameSetting>& gmst = world->getStore().get<ESM::GameSetting>(); float defenseTerm = 0; MWMechanics::CreatureStats& victimStats = victim.getClass().getCreatureStats(victim); if (victimStats.getFatigue().getCurrent() >= 0) { // Maybe we should keep an aware state for actors updated every so often instead of testing every time bool unaware = (!victimStats.getAiSequence().isInCombat()) && (attacker == getPlayer()) && (!MWBase::Environment::get().getMechanicsManager()->awarenessCheck(attacker, victim)); if (!(victimStats.getKnockedDown() || victimStats.isParalyzed() || unaware)) { defenseTerm = victimStats.getEvasion(); } static const float fCombatInvisoMult = gmst.find("fCombatInvisoMult")->mValue.getFloat(); defenseTerm += std::min(100.f, fCombatInvisoMult * victimStats.getMagicEffects().getOrDefault(ESM::MagicEffect::Chameleon).getMagnitude()); defenseTerm += std::min(100.f, fCombatInvisoMult * victimStats.getMagicEffects().getOrDefault(ESM::MagicEffect::Invisibility).getMagnitude()); } float attackTerm = skillValue + (stats.getAttribute(ESM::Attribute::Agility).getModified() / 5.0f) + (stats.getAttribute(ESM::Attribute::Luck).getModified() / 10.0f); attackTerm *= stats.getFatigueTerm(); attackTerm += mageffects.getOrDefault(ESM::MagicEffect::FortifyAttack).getMagnitude() - mageffects.getOrDefault(ESM::MagicEffect::Blind).getMagnitude(); return round(attackTerm - defenseTerm); } void applyElementalShields(const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim) { // Don't let elemental shields harm the player in god mode. bool godmode = attacker == getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState(); if (godmode) return; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); for (int i = 0; i < 3; ++i) { float magnitude = victim.getClass() .getCreatureStats(victim) .getMagicEffects() .getOrDefault(ESM::MagicEffect::FireShield + i) .getMagnitude(); if (!magnitude) continue; CreatureStats& attackerStats = attacker.getClass().getCreatureStats(attacker); float saveTerm = attacker.getClass().getSkill(attacker, ESM::Skill::Destruction) + 0.2f * attackerStats.getAttribute(ESM::Attribute::Willpower).getModified() + 0.1f * attackerStats.getAttribute(ESM::Attribute::Luck).getModified(); float fatigueMax = attackerStats.getFatigue().getModified(); float fatigueCurrent = attackerStats.getFatigue().getCurrent(); float normalisedFatigue = floor(fatigueMax) == 0 ? 1 : std::max(0.0f, (fatigueCurrent / fatigueMax)); saveTerm *= 1.25f * normalisedFatigue; float x = std::max(0.f, saveTerm - Misc::Rng::roll0to99(prng)); int element = ESM::MagicEffect::FireDamage; if (i == 1) element = ESM::MagicEffect::ShockDamage; if (i == 2) element = ESM::MagicEffect::FrostDamage; float elementResistance = MWMechanics::getEffectResistanceAttribute(element, &attackerStats.getMagicEffects()); x = std::min(100.f, x + elementResistance); static const float fElementalShieldMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fElementalShieldMult") ->mValue.getFloat(); x = fElementalShieldMult * magnitude * (1.f - 0.01f * x); // Note swapped victim and attacker, since the attacker takes the damage here. x = scaleDamage(x, victim, attacker); MWMechanics::DynamicStat<float> health = attackerStats.getHealth(); health.setCurrent(health.getCurrent() - x); attackerStats.setHealth(health); MWBase::Environment::get().getSoundManager()->playSound3D( attacker, ESM::RefId::stringRefId("Health Damage"), 1.0f, 1.0f); } } void reduceWeaponCondition(float damage, bool hit, MWWorld::Ptr& weapon, const MWWorld::Ptr& attacker) { if (weapon.isEmpty()) return; if (!hit) damage = 0.f; const bool weaphashealth = weapon.getClass().hasItemHealth(weapon); if (weaphashealth) { int weaphealth = weapon.getClass().getItemHealth(weapon); bool godmode = attacker == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState(); // weapon condition does not degrade when godmode is on if (!godmode) { const float fWeaponDamageMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fWeaponDamageMult") ->mValue.getFloat(); float x = std::max(1.f, fWeaponDamageMult * damage); weaphealth -= std::min(int(x), weaphealth); weapon.getCellRef().setCharge(weaphealth); } // Weapon broken? unequip it if (weaphealth == 0) weapon = *attacker.getClass().getInventoryStore(attacker).unequipItem(weapon); } } void adjustWeaponDamage(float& damage, const MWWorld::Ptr& weapon, const MWWorld::Ptr& attacker) { if (weapon.isEmpty()) return; const bool weaphashealth = weapon.getClass().hasItemHealth(weapon); if (weaphashealth) { damage *= weapon.getClass().getItemNormalizedHealth(weapon); } static const float fDamageStrengthBase = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fDamageStrengthBase") ->mValue.getFloat(); static const float fDamageStrengthMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fDamageStrengthMult") ->mValue.getFloat(); damage *= fDamageStrengthBase + (attacker.getClass().getCreatureStats(attacker).getAttribute(ESM::Attribute::Strength).getModified() * fDamageStrengthMult * 0.1f); } void getHandToHandDamage( const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim, float& damage, bool& healthdmg, float attackStrength) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); static const float minstrike = store.get<ESM::GameSetting>().find("fMinHandToHandMult")->mValue.getFloat(); static const float maxstrike = store.get<ESM::GameSetting>().find("fMaxHandToHandMult")->mValue.getFloat(); damage = static_cast<float>(attacker.getClass().getSkill(attacker, ESM::Skill::HandToHand)); damage *= minstrike + ((maxstrike - minstrike) * attackStrength); MWMechanics::CreatureStats& otherstats = victim.getClass().getCreatureStats(victim); healthdmg = otherstats.isParalyzed() || otherstats.getKnockedDown(); bool isWerewolf = (attacker.getClass().isNpc() && attacker.getClass().getNpcStats(attacker).isWerewolf()); // Options in the launcher's combo box: unarmedFactorsStrengthComboBox // 0 = Do not factor strength into hand-to-hand combat. // 1 = Factor into werewolf hand-to-hand combat. // 2 = Ignore werewolves. const int factorStrength = Settings::game().mStrengthInfluencesHandToHand; if (factorStrength == 1 || (factorStrength == 2 && !isWerewolf)) { damage *= attacker.getClass().getCreatureStats(attacker).getAttribute(ESM::Attribute::Strength).getModified() / 40.0f; } if (isWerewolf) { healthdmg = true; // GLOB instead of GMST because it gets updated during a quest damage *= MWBase::Environment::get().getWorld()->getGlobalFloat(MWWorld::Globals::sWerewolfClawMult); } if (healthdmg) { static const float fHandtoHandHealthPer = store.get<ESM::GameSetting>().find("fHandtoHandHealthPer")->mValue.getFloat(); damage *= fHandtoHandHealthPer; } MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); if (isWerewolf) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); const ESM::Sound* sound = store.get<ESM::Sound>().searchRandom("WolfHit", prng); if (sound) sndMgr->playSound3D(victim, sound->mId, 1.0f, 1.0f); } else if (!healthdmg) sndMgr->playSound3D(victim, ESM::RefId::stringRefId("Hand To Hand Hit"), 1.0f, 1.0f); } void applyFatigueLoss(const MWWorld::Ptr& attacker, const MWWorld::Ptr& weapon, float attackStrength) { // somewhat of a guess, but using the weapon weight makes sense const MWWorld::Store<ESM::GameSetting>& store = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fFatigueAttackBase = store.find("fFatigueAttackBase")->mValue.getFloat(); static const float fFatigueAttackMult = store.find("fFatigueAttackMult")->mValue.getFloat(); static const float fWeaponFatigueMult = store.find("fWeaponFatigueMult")->mValue.getFloat(); CreatureStats& stats = attacker.getClass().getCreatureStats(attacker); MWMechanics::DynamicStat<float> fatigue = stats.getFatigue(); const float normalizedEncumbrance = attacker.getClass().getNormalizedEncumbrance(attacker); bool godmode = attacker == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState(); if (!godmode) { float fatigueLoss = fFatigueAttackBase + normalizedEncumbrance * fFatigueAttackMult; if (!weapon.isEmpty()) fatigueLoss += weapon.getClass().getWeight(weapon) * attackStrength * fWeaponFatigueMult; fatigue.setCurrent(fatigue.getCurrent() - fatigueLoss); stats.setFatigue(fatigue); } } float getFightDistanceBias(const MWWorld::Ptr& actor1, const MWWorld::Ptr& actor2) { osg::Vec3f pos1(actor1.getRefData().getPosition().asVec3()); osg::Vec3f pos2(actor2.getRefData().getPosition().asVec3()); float d = getAggroDistance(actor1, pos1, pos2); static const int iFightDistanceBase = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("iFightDistanceBase") ->mValue.getInteger(); static const float fFightDistanceMultiplier = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fFightDistanceMultiplier") ->mValue.getFloat(); return (iFightDistanceBase - fFightDistanceMultiplier * d); } float getAggroDistance(const MWWorld::Ptr& actor, const osg::Vec3f& lhs, const osg::Vec3f& rhs) { if (canActorMoveByZAxis(actor)) return distanceIgnoreZ(lhs, rhs); return distance(lhs, rhs); } float getDistanceToBounds(const MWWorld::Ptr& actor, const MWWorld::Ptr& target) { osg::Vec3f actorPos(actor.getRefData().getPosition().asVec3()); osg::Vec3f targetPos(target.getRefData().getPosition().asVec3()); MWBase::World* world = MWBase::Environment::get().getWorld(); float dist = (targetPos - actorPos).length(); dist -= world->getHalfExtents(actor).y(); dist -= world->getHalfExtents(target).y(); return dist; } std::pair<MWWorld::Ptr, osg::Vec3f> getHitContact(const MWWorld::Ptr& actor, float reach) { // Lasciate ogne speranza, voi ch'entrate MWWorld::Ptr result; osg::Vec3f hitPos; float minDist = std::numeric_limits<float>::max(); MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::Store<ESM::GameSetting>& store = world->getStore().get<ESM::GameSetting>(); // These GMSTs are not in degrees. They're tolerance angle sines multiplied by 90. // With the default values of 60, the actual tolerance angles are roughly 41.8 degrees. // Don't think too hard about it. In this place, thinking can cause permanent damage to your mental health. const float fCombatAngleXY = store.find("fCombatAngleXY")->mValue.getFloat() / 90.f; const float fCombatAngleZ = store.find("fCombatAngleZ")->mValue.getFloat() / 90.f; const ESM::Position& posdata = actor.getRefData().getPosition(); const osg::Vec3f actorPos(posdata.asVec3()); const osg::Vec3f actorDirXY = osg::Quat(posdata.rot[2], osg::Vec3(0, 0, -1)) * osg::Vec3f(0, 1, 0); // Only the player can look up, apparently. const float actorVerticalAngle = actor == getPlayer() ? -std::sin(posdata.rot[0]) : 0.f; const float actorEyeLevel = world->getHalfExtents(actor, true).z() * 2.f * 0.85f; const osg::Vec3f actorEyePos{ actorPos.x(), actorPos.y(), actorPos.z() + actorEyeLevel }; const bool canMoveByZ = canActorMoveByZAxis(actor); // The player can target any active actor, non-playable actors only target their targets std::vector<MWWorld::Ptr> targets; if (actor != getPlayer()) actor.getClass().getCreatureStats(actor).getAiSequence().getCombatTargets(targets); else MWBase::Environment::get().getMechanicsManager()->getActorsInRange( actorPos, Settings::game().mActorsProcessingRange, targets); for (MWWorld::Ptr& target : targets) { if (actor == target || target.getClass().getCreatureStats(target).isDead()) continue; const float dist = getDistanceToBounds(actor, target); const osg::Vec3f targetPos(target.getRefData().getPosition().asVec3()); if (dist >= reach || dist >= minDist || std::abs(targetPos.z() - actorPos.z()) >= reach) continue; // Horizontal angle checks. osg::Vec2f actorToTargetXY{ targetPos.x() - actorPos.x(), targetPos.y() - actorPos.y() }; actorToTargetXY.normalize(); // Use dot product to check if the target is behind first... if (actorToTargetXY.x() * actorDirXY.x() + actorToTargetXY.y() * actorDirXY.y() <= 0.f) continue; // And then perp dot product to calculate the hit angle sine. // This gives us a horizontal hit range of [-asin(fCombatAngleXY / 90); asin(fCombatAngleXY / 90)] if (std::abs(actorToTargetXY.x() * actorDirXY.y() - actorToTargetXY.y() * actorDirXY.x()) > fCombatAngleXY) continue; // Vertical angle checks. Nice cliff racer hack, Todd. if (!canMoveByZ) { // The idea is that the body should always be possible to hit. // fCombatAngleZ is the tolerance for hitting the target's feet or head. osg::Vec3f actorToTargetFeet = targetPos - actorEyePos; osg::Vec3f actorToTargetHead = actorToTargetFeet; actorToTargetFeet.normalize(); actorToTargetHead.z() += world->getHalfExtents(target, true).z() * 2.f; actorToTargetHead.normalize(); if (actorVerticalAngle - actorToTargetHead.z() > fCombatAngleZ || actorVerticalAngle - actorToTargetFeet.z() < -fCombatAngleZ) continue; } // Gotta use physics somehow! if (!world->getLOS(actor, target)) continue; minDist = dist; result = target; } // This hit position is currently used for spawning the blood effect. // Morrowind does this elsewhere, but roughly at the same time // and it would be hard to track the original hit results outside of this function // without code duplication // The idea is to use a random point on a plane in front of the target // that is defined by its width and height if (!result.isEmpty()) { osg::Vec3f resultPos(result.getRefData().getPosition().asVec3()); osg::Vec3f dirToActor = actorPos - resultPos; dirToActor.normalize(); hitPos = resultPos + dirToActor * world->getHalfExtents(result).y(); // -25% to 25% of width float xOffset = Misc::Rng::deviate(0.f, 0.25f, world->getPrng()); // 20% to 100% of height float zOffset = Misc::Rng::deviate(0.6f, 0.4f, world->getPrng()); hitPos.x() += world->getHalfExtents(result).x() * 2.f * xOffset; hitPos.z() += world->getHalfExtents(result).z() * 2.f * zOffset; } return std::make_pair(result, hitPos); } bool friendlyHit(const MWWorld::Ptr& attacker, const MWWorld::Ptr& target, bool complain) { const MWWorld::Ptr& player = getPlayer(); if (attacker != player) return false; std::set<MWWorld::Ptr> followersAttacker; MWBase::Environment::get().getMechanicsManager()->getActorsSidingWith(attacker, followersAttacker); if (followersAttacker.find(target) == followersAttacker.end()) return false; MWMechanics::CreatureStats& statsTarget = target.getClass().getCreatureStats(target); if (statsTarget.getAiSequence().isInCombat()) return true; statsTarget.friendlyHit(); if (statsTarget.getFriendlyHits() >= 4) return false; if (complain) MWBase::Environment::get().getDialogueManager()->say(target, ESM::RefId::stringRefId("hit")); return true; } }
34,020
C++
.cpp
588
45.017007
120
0.614907
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,334
spellcasting.cpp
OpenMW_openmw/apps/openmw/mwmechanics/spellcasting.cpp
#include "spellcasting.hpp" #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadstat.hpp> #include <components/misc/constants.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/rng.hpp> #include <components/misc/strings/format.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwrender/animation.hpp" #include "actorutil.hpp" #include "creaturestats.hpp" #include "spelleffects.hpp" #include "spellutil.hpp" #include "weapontype.hpp" namespace MWMechanics { CastSpell::CastSpell( const MWWorld::Ptr& caster, const MWWorld::Ptr& target, const bool fromProjectile, const bool scriptedSpell) : mCaster(caster) , mTarget(target) , mFromProjectile(fromProjectile) , mScriptedSpell(scriptedSpell) { } void CastSpell::explodeSpell( const ESM::EffectList& effects, const MWWorld::Ptr& ignore, ESM::RangeType rangeType) const { const auto world = MWBase::Environment::get().getWorld(); std::map<MWWorld::Ptr, std::vector<ESM::IndexedENAMstruct>> toApply; for (const ESM::IndexedENAMstruct& effectInfo : effects.mList) { const ESM::MagicEffect* effect = world->getStore().get<ESM::MagicEffect>().find(effectInfo.mData.mEffectID); if (effectInfo.mData.mRange != rangeType || (effectInfo.mData.mArea <= 0 && !ignore.isEmpty() && ignore.getClass().isActor())) continue; // Not right range type, or not area effect and hit an actor if (mFromProjectile && effectInfo.mData.mArea <= 0) continue; // Don't play explosion for projectiles with 0-area effects if (!mFromProjectile && effectInfo.mData.mRange == ESM::RT_Touch && !ignore.isEmpty() && !ignore.getClass().isActor() && !ignore.getClass().hasToolTip(ignore) && (mCaster.isEmpty() || mCaster.getClass().isActor())) continue; // Don't play explosion for touch spells on non-activatable objects except when spell is from // a projectile enchantment or ExplodeSpell // Spawn the explosion orb effect const ESM::Static* areaStatic; if (!effect->mArea.empty()) areaStatic = world->getStore().get<ESM::Static>().find(effect->mArea); else areaStatic = world->getStore().get<ESM::Static>().find(ESM::RefId::stringRefId("VFX_DefaultArea")); const std::string& texture = effect->mParticle; if (effectInfo.mData.mArea <= 0) { if (effectInfo.mData.mRange == ESM::RT_Target) world->spawnEffect( VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(areaStatic->mModel)), texture, mHitPosition, 1.0f); continue; } else world->spawnEffect(VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(areaStatic->mModel)), texture, mHitPosition, static_cast<float>(effectInfo.mData.mArea * 2)); // Play explosion sound (make sure to use NoTrack, since we will delete the projectile now) { MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); if (!effect->mAreaSound.empty()) sndMgr->playSound3D(mHitPosition, effect->mAreaSound, 1.0f, 1.0f); else sndMgr->playSound3D(mHitPosition, world->getStore().get<ESM::Skill>().find(effect->mData.mSchool)->mSchool->mAreaSound, 1.0f, 1.0f); } // Get the actors in range of the effect std::vector<MWWorld::Ptr> objects; static const int unitsPerFoot = ceil(Constants::UnitsPerFoot); MWBase::Environment::get().getMechanicsManager()->getObjectsInRange( mHitPosition, static_cast<float>(effectInfo.mData.mArea * unitsPerFoot), objects); for (const MWWorld::Ptr& affected : objects) { // Ignore actors without collisions here, otherwise it will be possible to hit actors outside processing // range. if (affected.getClass().isActor() && !world->isActorCollisionEnabled(affected)) continue; auto& list = toApply[affected]; list.push_back(effectInfo); } } // Now apply the appropriate effects to each actor in range for (auto& applyPair : toApply) { // Vanilla-compatible behaviour of never applying the spell to the caster // (could be changed by mods later) if (applyPair.first == mCaster) continue; if (applyPair.first == ignore) continue; ESM::EffectList effectsToApply; effectsToApply.mList = applyPair.second; inflict(applyPair.first, effectsToApply, rangeType, true); } } void CastSpell::launchMagicBolt() const { osg::Vec3f fallbackDirection(0, 1, 0); osg::Vec3f offset(0, 0, 0); if (!mTarget.isEmpty() && mTarget.getClass().isActor()) offset.z() = MWBase::Environment::get().getWorld()->getHalfExtents(mTarget).z(); // Fall back to a "caster to target" direction if we have no other means of determining it // (e.g. when cast by a non-actor) if (!mTarget.isEmpty()) fallbackDirection = (mTarget.getRefData().getPosition().asVec3() + offset) - (mCaster.getRefData().getPosition().asVec3()); MWBase::Environment::get().getWorld()->launchMagicBolt(mId, mCaster, fallbackDirection, mItem); } void CastSpell::inflict( const MWWorld::Ptr& target, const ESM::EffectList& effects, ESM::RangeType range, bool exploded) const { bool targetIsDeadActor = false; const bool targetIsActor = !target.isEmpty() && target.getClass().isActor(); if (targetIsActor) { const auto& stats = target.getClass().getCreatureStats(target); if (stats.isDead() && stats.isDeathAnimationFinished()) targetIsDeadActor = true; } // If none of the effects need to apply, we can early-out bool found = false; bool containsRecastable = false; const auto& store = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>(); for (const ESM::IndexedENAMstruct& effect : effects.mList) { if (effect.mData.mRange == range) { found = true; const ESM::MagicEffect* magicEffect = store.find(effect.mData.mEffectID); if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NonRecastable)) containsRecastable = true; } } if (!found) return; ActiveSpells::ActiveSpellParams params(mCaster, mId, mSourceName, mItem); params.setFlag(mFlags); bool castByPlayer = (!mCaster.isEmpty() && mCaster == getPlayer()); const ActiveSpells* targetSpells = nullptr; if (targetIsActor) targetSpells = &target.getClass().getCreatureStats(target).getActiveSpells(); // Re-casting a bound equipment effect has no effect if the spell is still active if (!containsRecastable && targetSpells && targetSpells->isSpellActive(mId)) { if (castByPlayer) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicCannotRecast}"); return; } for (auto& enam : effects.mList) { if (target.isEmpty()) break; if (enam.mData.mRange != range) continue; const ESM::MagicEffect* magicEffect = store.find(enam.mData.mEffectID); if (!magicEffect) continue; // caster needs to be an actor for linked effects (e.g. Absorb) if (magicEffect->mData.mFlags & ESM::MagicEffect::CasterLinked && (mCaster.isEmpty() || !mCaster.getClass().isActor())) continue; ActiveSpells::ActiveEffect effect; effect.mEffectId = enam.mData.mEffectID; effect.mArg = MWMechanics::EffectKey(enam.mData).mArg; effect.mMagnitude = 0.f; effect.mMinMagnitude = enam.mData.mMagnMin; effect.mMaxMagnitude = enam.mData.mMagnMax; effect.mTimeLeft = 0.f; effect.mEffectIndex = enam.mIndex; effect.mFlags = ESM::ActiveEffect::Flag_None; if (mScriptedSpell) effect.mFlags |= ESM::ActiveEffect::Flag_Ignore_Reflect; bool hasDuration = !(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration); effect.mDuration = hasDuration ? static_cast<float>(enam.mData.mDuration) : 1.f; bool appliedOnce = magicEffect->mData.mFlags & ESM::MagicEffect::AppliedOnce; if (!appliedOnce) effect.mDuration = std::max(1.f, effect.mDuration); effect.mTimeLeft = effect.mDuration; // add to list of active effects, to apply in next frame params.getEffects().emplace_back(effect); bool effectAffectsHealth = magicEffect->mData.mFlags & ESM::MagicEffect::Harmful || enam.mData.mEffectID == ESM::MagicEffect::RestoreHealth; if (castByPlayer && target != mCaster && targetIsActor && !targetIsDeadActor && effectAffectsHealth) { // If player is attempting to cast a harmful spell on or is healing a living target, show the target's // HP bar. MWBase::Environment::get().getWindowManager()->setEnemy(target); } if (!targetIsActor && magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration) { playEffects(target, *magicEffect); } } if (!exploded) explodeSpell(effects, target, range); if (!target.isEmpty()) { if (!params.getEffects().empty()) { if (targetIsActor) { if (!targetIsDeadActor) target.getClass().getCreatureStats(target).getActiveSpells().addSpell(params); } else { // Apply effects instantly. We can ignore effect deletion since the entire params object gets // deleted afterwards anyway and we can ignore reflection since non-actors cannot reflect spells for (auto& effect : params.getEffects()) applyMagicEffect(target, mCaster, params, effect, 0.f); } } } } bool CastSpell::cast(const ESM::RefId& id) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); if (const auto spell = store.get<ESM::Spell>().search(id)) return cast(spell); if (const auto potion = store.get<ESM::Potion>().search(id)) return cast(potion); if (const auto ingredient = store.get<ESM::Ingredient>().search(id)) return cast(ingredient); throw std::runtime_error("ID type cannot be casted"); } bool CastSpell::cast(const MWWorld::Ptr& item, bool launchProjectile) { const ESM::RefId& enchantmentName = item.getClass().getEnchantment(item); if (enchantmentName.empty()) throw std::runtime_error("can't cast an item without an enchantment"); mSourceName = item.getClass().getName(item); mId = item.getCellRef().getRefId(); const auto& store = MWBase::Environment::get().getESMStore(); const ESM::Enchantment* enchantment = store->get<ESM::Enchantment>().find(enchantmentName); // CastOnce enchantments (i.e. scrolls) never stack and the item is immediately destroyed, // so don't track the source item. if (enchantment->mData.mType != ESM::Enchantment::CastOnce) mItem = item.getCellRef().getRefNum(); bool godmode = mCaster == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState(); bool isProjectile = false; if (item.getType() == ESM::Weapon::sRecordId) { int type = item.get<ESM::Weapon>()->mBase->mData.mType; ESM::WeaponType::Class weapclass = MWMechanics::getWeaponType(type)->mWeaponClass; isProjectile = (weapclass == ESM::WeaponType::Thrown || weapclass == ESM::WeaponType::Ammo); } int type = enchantment->mData.mType; // Check if there's enough charge left if (!godmode && (type == ESM::Enchantment::WhenUsed || (!isProjectile && type == ESM::Enchantment::WhenStrikes))) { int castCost = getEffectiveEnchantmentCastCost(*enchantment, mCaster); if (item.getCellRef().getEnchantmentCharge() == -1) item.getCellRef().setEnchantmentCharge( static_cast<float>(MWMechanics::getEnchantmentCharge(*enchantment))); if (item.getCellRef().getEnchantmentCharge() < castCost) { if (mCaster == getPlayer()) { MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicInsufficientCharge}"); // Failure sound ESM::RefId school = ESM::Skill::Alteration; if (!enchantment->mEffects.mList.empty()) { short effectId = enchantment->mEffects.mList.front().mData.mEffectID; const ESM::MagicEffect* magicEffect = store->get<ESM::MagicEffect>().find(effectId); school = magicEffect->mData.mSchool; } MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); sndMgr->playSound3D( mCaster, store->get<ESM::Skill>().find(school)->mSchool->mFailureSound, 1.0f, 1.0f); } return false; } // Reduce charge item.getCellRef().setEnchantmentCharge(item.getCellRef().getEnchantmentCharge() - castCost); } if (type == ESM::Enchantment::WhenUsed) { if (mCaster == getPlayer()) mCaster.getClass().skillUsageSucceeded(mCaster, ESM::Skill::Enchant, ESM::Skill::Enchant_UseMagicItem); } else if (type == ESM::Enchantment::CastOnce) { if (!godmode) item.getContainerStore()->remove(item, 1); } else if (type == ESM::Enchantment::WhenStrikes) { if (mCaster == getPlayer()) mCaster.getClass().skillUsageSucceeded(mCaster, ESM::Skill::Enchant, ESM::Skill::Enchant_CastOnStrike); } if (isProjectile) inflict(mTarget, enchantment->mEffects, ESM::RT_Self); else inflict(mCaster, enchantment->mEffects, ESM::RT_Self); if (isProjectile || !mTarget.isEmpty()) inflict(mTarget, enchantment->mEffects, ESM::RT_Touch); if (launchProjectile) launchMagicBolt(); else if (isProjectile || !mTarget.isEmpty()) inflict(mTarget, enchantment->mEffects, ESM::RT_Target); return true; } bool CastSpell::cast(const ESM::Potion* potion) { mSourceName = potion->mName; mId = potion->mId; mFlags = static_cast<ESM::ActiveSpells::Flags>( ESM::ActiveSpells::Flag_Temporary | ESM::ActiveSpells::Flag_Stackable); // Ignore range and don't apply area of effect inflict(mCaster, potion->mEffects, ESM::RT_Self, true); inflict(mCaster, potion->mEffects, ESM::RT_Touch, true); inflict(mCaster, potion->mEffects, ESM::RT_Target, true); return true; } bool CastSpell::cast(const ESM::Spell* spell) { mSourceName = spell->mName; mId = spell->mId; ESM::RefId school = ESM::Skill::Alteration; bool godmode = mCaster == MWMechanics::getPlayer() && MWBase::Environment::get().getWorld()->getGodModeState(); if (mCaster.getClass().isActor() && !mAlwaysSucceed && !mScriptedSpell) { school = getSpellSchool(spell, mCaster); CreatureStats& stats = mCaster.getClass().getCreatureStats(mCaster); if (!godmode) { bool fail = false; // Check success float successChance = getSpellSuccessChance(spell, mCaster, nullptr, true, false); auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (Misc::Rng::roll0to99(prng) >= successChance) { if (mCaster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicSkillFail}"); fail = true; } if (fail) { // Failure sound MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); const ESM::Skill* skill = MWBase::Environment::get().getESMStore()->get<ESM::Skill>().find(school); sndMgr->playSound3D(mCaster, skill->mSchool->mFailureSound, 1.0f, 1.0f); return false; } } // A power can be used once per 24h if (spell->mData.mType == ESM::Spell::ST_Power) stats.getSpells().usePower(spell); } if (!mScriptedSpell && mCaster == getPlayer() && spellIncreasesSkill(spell)) mCaster.getClass().skillUsageSucceeded(mCaster, school, ESM::Skill::Spellcast_Success); // A non-actor doesn't play its spell cast effects from a character controller, so play them here if (!mCaster.getClass().isActor()) playSpellCastingEffects(spell->mEffects.mList); inflict(mCaster, spell->mEffects, ESM::RT_Self); if (!mTarget.isEmpty()) inflict(mTarget, spell->mEffects, ESM::RT_Touch); launchMagicBolt(); return true; } bool CastSpell::cast(const ESM::Ingredient* ingredient) { mId = ingredient->mId; mFlags = static_cast<ESM::ActiveSpells::Flags>( ESM::ActiveSpells::Flag_Temporary | ESM::ActiveSpells::Flag_Stackable); mSourceName = ingredient->mName; auto effect = rollIngredientEffect(mCaster, ingredient, mCaster != getPlayer()); if (effect) inflict(mCaster, *effect, ESM::RT_Self); else { // "X has no effect on you" std::string message = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("sNotifyMessage50") ->mValue.getString(); message = Misc::StringUtils::format(message, ingredient->mName); MWBase::Environment::get().getWindowManager()->messageBox(message); return false; } return true; } void CastSpell::playSpellCastingEffects(const ESM::Enchantment* enchantment) const { playSpellCastingEffects(enchantment->mEffects.mList); } void CastSpell::playSpellCastingEffects(const ESM::Spell* spell) const { playSpellCastingEffects(spell->mEffects.mList); } void CastSpell::playSpellCastingEffects(const std::vector<ESM::IndexedENAMstruct>& effects) const { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); std::vector<std::string> addedEffects; for (const ESM::IndexedENAMstruct& effectData : effects) { const auto effect = store.get<ESM::MagicEffect>().find(effectData.mData.mEffectID); const ESM::Static* castStatic; if (!effect->mCasting.empty()) castStatic = store.get<ESM::Static>().find(effect->mCasting); else castStatic = store.get<ESM::Static>().find(ESM::RefId::stringRefId("VFX_DefaultCast")); // check if the effect was already added if (std::find(addedEffects.begin(), addedEffects.end(), Misc::ResourceHelpers::correctMeshPath(castStatic->mModel)) != addedEffects.end()) continue; MWRender::Animation* animation = MWBase::Environment::get().getWorld()->getAnimation(mCaster); if (animation) { animation->addEffect(Misc::ResourceHelpers::correctMeshPath(castStatic->mModel), ESM::MagicEffect::indexToName(effect->mIndex), false, {}, effect->mParticle); } else { // If the caster has no animation, add the effect directly to the effectManager // We must scale and position it manually float scale = mCaster.getCellRef().getScale(); osg::Vec3f pos(mCaster.getRefData().getPosition().asVec3()); if (!mCaster.getClass().isNpc()) { osg::Vec3f bounds(MWBase::Environment::get().getWorld()->getHalfExtents(mCaster) * 2.f); scale *= std::max({ bounds.x(), bounds.y(), bounds.z() / 2.f }) / 64.f; float offset = 0.f; if (bounds.z() < 128.f) offset = bounds.z() - 128.f; else if (bounds.z() < bounds.x() + bounds.y()) offset = 128.f - bounds.z(); if (MWBase::Environment::get().getWorld()->isFlying(mCaster)) offset /= 20.f; pos.z() += offset * scale; } else { // Additionally use the NPC's height osg::Vec3f npcScaleVec(1.f, 1.f, 1.f); mCaster.getClass().adjustScale(mCaster, npcScaleVec, true); scale *= npcScaleVec.z(); } scale = std::max(scale, 1.f); MWBase::Environment::get().getWorld()->spawnEffect( VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(castStatic->mModel)), effect->mParticle, pos, scale); } if (animation && !mCaster.getClass().isActor()) animation->addSpellCastGlow(effect->getColor()); addedEffects.push_back(Misc::ResourceHelpers::correctMeshPath(castStatic->mModel)); MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); if (!effect->mCastSound.empty()) sndMgr->playSound3D(mCaster, effect->mCastSound, 1.0f, 1.0f); else sndMgr->playSound3D( mCaster, store.get<ESM::Skill>().find(effect->mData.mSchool)->mSchool->mCastSound, 1.0f, 1.0f); } } void playEffects(const MWWorld::Ptr& target, const ESM::MagicEffect& magicEffect, bool playNonLooping) { const auto& store = MWBase::Environment::get().getESMStore(); if (playNonLooping) { MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); if (!magicEffect.mHitSound.empty()) sndMgr->playSound3D(target, magicEffect.mHitSound, 1.0f, 1.0f); else sndMgr->playSound3D( target, store->get<ESM::Skill>().find(magicEffect.mData.mSchool)->mSchool->mHitSound, 1.0f, 1.0f); } // Add VFX const ESM::Static* castStatic; if (!magicEffect.mHit.empty()) castStatic = store->get<ESM::Static>().find(magicEffect.mHit); else castStatic = store->get<ESM::Static>().find(ESM::RefId::stringRefId("VFX_DefaultHit")); bool loop = (magicEffect.mData.mFlags & ESM::MagicEffect::ContinuousVfx) != 0; MWRender::Animation* anim = MWBase::Environment::get().getWorld()->getAnimation(target); if (anim && !castStatic->mModel.empty()) { // Don't play particle VFX unless the effect is new or it should be looping. if (playNonLooping || loop) anim->addEffect(Misc::ResourceHelpers::correctMeshPath(castStatic->mModel), ESM::MagicEffect::indexToName(magicEffect.mIndex), loop, {}, magicEffect.mParticle); } } }
25,236
C++
.cpp
499
37.769539
120
0.585758
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,335
spelleffects.cpp
OpenMW_openmw/apps/openmw/mwmechanics/spelleffects.cpp
#include "spelleffects.hpp" #include <algorithm> #include <array> #include <components/esm3/loadcrea.hpp> #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadstat.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/rng.hpp> #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/aifollow.hpp" #include "../mwmechanics/npcstats.hpp" #include "../mwmechanics/spellresistance.hpp" #include "../mwmechanics/spellutil.hpp" #include "../mwmechanics/summoning.hpp" #include "../mwrender/animation.hpp" #include "../mwworld/actionequip.hpp" #include "../mwworld/actionteleport.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/player.hpp" namespace { float roll(const ESM::ActiveEffect& effect) { if (effect.mMinMagnitude == effect.mMaxMagnitude) return effect.mMinMagnitude; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); return effect.mMinMagnitude + Misc::Rng::rollDice(effect.mMaxMagnitude - effect.mMinMagnitude + 1, prng); } void modifyAiSetting(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, ESM::MagicEffect::Effects creatureEffect, MWMechanics::AiSetting setting, float magnitude, bool& invalid) { if (target == MWMechanics::getPlayer() || (effect.mEffectId == creatureEffect) == target.getClass().isNpc()) invalid = true; else { auto& creatureStats = target.getClass().getCreatureStats(target); auto stat = creatureStats.getAiSetting(setting); stat.setModifier(static_cast<int>(stat.getModifier() + magnitude)); creatureStats.setAiSetting(setting, stat); } } void adjustDynamicStat(const MWWorld::Ptr& target, int index, float magnitude, bool allowDecreaseBelowZero = false, bool allowIncreaseAboveModified = false) { auto& creatureStats = target.getClass().getCreatureStats(target); auto stat = creatureStats.getDynamic(index); stat.setCurrent(stat.getCurrent() + magnitude, allowDecreaseBelowZero, allowIncreaseAboveModified); creatureStats.setDynamic(index, stat); } void modDynamicStat(const MWWorld::Ptr& target, int index, float magnitude) { auto& creatureStats = target.getClass().getCreatureStats(target); auto stat = creatureStats.getDynamic(index); float current = stat.getCurrent(); stat.setBase(std::max(0.f, stat.getBase() + magnitude)); stat.setCurrent(current + magnitude); creatureStats.setDynamic(index, stat); } void damageAttribute(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& creatureStats = target.getClass().getCreatureStats(target); auto attribute = effect.getSkillOrAttribute(); auto attr = creatureStats.getAttribute(attribute); if (effect.mEffectId == ESM::MagicEffect::DamageAttribute) magnitude = std::min(attr.getModified(), magnitude); attr.damage(magnitude); creatureStats.setAttribute(attribute, attr); } void restoreAttribute(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& creatureStats = target.getClass().getCreatureStats(target); auto attribute = effect.getSkillOrAttribute(); auto attr = creatureStats.getAttribute(attribute); attr.restore(magnitude); creatureStats.setAttribute(attribute, attr); } void fortifyAttribute(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& creatureStats = target.getClass().getCreatureStats(target); auto attribute = effect.getSkillOrAttribute(); auto attr = creatureStats.getAttribute(attribute); attr.setModifier(attr.getModifier() + magnitude); creatureStats.setAttribute(attribute, attr); } void damageSkill(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& npcStats = target.getClass().getNpcStats(target); auto& skill = npcStats.getSkill(effect.getSkillOrAttribute()); if (effect.mEffectId == ESM::MagicEffect::DamageSkill) magnitude = std::min(skill.getModified(), magnitude); skill.damage(magnitude); } void restoreSkill(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& npcStats = target.getClass().getNpcStats(target); auto& skill = npcStats.getSkill(effect.getSkillOrAttribute()); skill.restore(magnitude); } void fortifySkill(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect, float magnitude) { auto& npcStats = target.getClass().getNpcStats(target); auto& skill = npcStats.getSkill(effect.getSkillOrAttribute()); skill.setModifier(skill.getModifier() + magnitude); } bool disintegrateSlot(const MWWorld::Ptr& ptr, int slot, float disintegrate) { MWWorld::InventoryStore& inv = ptr.getClass().getInventoryStore(ptr); MWWorld::ContainerStoreIterator item = inv.getSlot(slot); if (item != inv.end() && (item.getType() == MWWorld::ContainerStore::Type_Armor || item.getType() == MWWorld::ContainerStore::Type_Weapon)) { if (!item->getClass().hasItemHealth(*item)) return false; int charge = item->getClass().getItemHealth(*item); if (charge == 0) return false; // Store remainder of disintegrate amount (automatically subtracted if > 1) item->getCellRef().applyChargeRemainderToBeSubtracted(disintegrate - std::floor(disintegrate)); charge = item->getClass().getItemHealth(*item); charge -= std::min(static_cast<int>(disintegrate), charge); item->getCellRef().setCharge(charge); if (charge == 0) { // Will unequip the broken item and try to find a replacement if (ptr != MWMechanics::getPlayer()) inv.autoEquip(); else inv.unequipItem(*item); } return true; } return false; } int getBoundItemSlot(const MWWorld::Ptr& boundPtr) { const auto [slots, _] = boundPtr.getClass().getEquipmentSlots(boundPtr); if (!slots.empty()) return slots[0]; return -1; } void addBoundItem(const ESM::RefId& itemId, const MWWorld::Ptr& actor) { MWWorld::InventoryStore& store = actor.getClass().getInventoryStore(actor); MWWorld::Ptr boundPtr = *store.MWWorld::ContainerStore::add(itemId, 1); int slot = getBoundItemSlot(boundPtr); auto prevItem = slot >= 0 ? store.getSlot(slot) : store.end(); MWWorld::ActionEquip action(boundPtr); action.execute(actor); if (actor != MWMechanics::getPlayer()) return; MWWorld::Ptr newItem; auto it = slot >= 0 ? store.getSlot(slot) : store.end(); // Equip can fail because beast races cannot equip boots/helmets if (it != store.end()) newItem = *it; if (newItem.isEmpty() || boundPtr != newItem) return; MWWorld::Player& player = MWBase::Environment::get().getWorld()->getPlayer(); // change draw state only if the item is in player's right hand if (slot == MWWorld::InventoryStore::Slot_CarriedRight) player.setDrawState(MWMechanics::DrawState::Weapon); if (prevItem != store.end()) player.setPreviousItem(itemId, prevItem->getCellRef().getRefId()); } void removeBoundItem(const ESM::RefId& itemId, const MWWorld::Ptr& actor) { MWWorld::InventoryStore& store = actor.getClass().getInventoryStore(actor); auto item = std::find_if( store.begin(), store.end(), [&](const auto& it) { return it.getCellRef().getRefId() == itemId; }); if (item == store.end()) return; int slot = getBoundItemSlot(*item); auto currentItem = store.getSlot(slot); bool wasEquipped = currentItem != store.end() && currentItem->getCellRef().getRefId() == itemId; if (wasEquipped) store.remove(*currentItem, 1); else store.remove(itemId, 1); if (actor != MWMechanics::getPlayer()) { // Equip a replacement if (!wasEquipped) return; auto type = currentItem->getType(); if (type != ESM::Weapon::sRecordId && type != ESM::Armor::sRecordId && type != ESM::Clothing::sRecordId) return; if (actor.getClass().getCreatureStats(actor).isDead()) return; if (!actor.getClass().hasInventoryStore(actor)) return; if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf()) return; actor.getClass().getInventoryStore(actor).autoEquip(); return; } MWWorld::Player& player = MWBase::Environment::get().getWorld()->getPlayer(); ESM::RefId prevItemId = player.getPreviousItem(itemId); player.erasePreviousItem(itemId); if (!prevItemId.empty() && wasEquipped) { // Find previous item (or its replacement) by id. // we should equip previous item only if expired bound item was equipped. MWWorld::Ptr prevItem = store.findReplacement(prevItemId); if (!prevItem.isEmpty()) { MWWorld::ActionEquip action(prevItem); action.execute(actor); } } } bool isCorprusEffect(const MWMechanics::ActiveSpells::ActiveEffect& effect, bool harmfulOnly = false) { if (effect.mFlags & ESM::ActiveEffect::Flag_Applied && effect.mEffectId != ESM::MagicEffect::Corprus) { const auto* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effect.mEffectId); if (magicEffect->mData.mFlags & ESM::MagicEffect::Flags::AppliedOnce && (!harmfulOnly || magicEffect->mData.mFlags & ESM::MagicEffect::Flags::Harmful)) return true; } return false; } void absorbSpell(const MWMechanics::ActiveSpells::ActiveSpellParams& spellParams, const MWWorld::Ptr& caster, const MWWorld::Ptr& target) { const auto& esmStore = *MWBase::Environment::get().getESMStore(); const ESM::Static* absorbStatic = esmStore.get<ESM::Static>().find(ESM::RefId::stringRefId("VFX_Absorb")); MWRender::Animation* animation = MWBase::Environment::get().getWorld()->getAnimation(target); if (animation && !absorbStatic->mModel.empty()) animation->addEffect(Misc::ResourceHelpers::correctMeshPath(absorbStatic->mModel), ESM::MagicEffect::indexToName(ESM::MagicEffect::SpellAbsorption), false); int spellCost = 0; if (const ESM::Spell* spell = esmStore.get<ESM::Spell>().search(spellParams.getSourceSpellId())) { spellCost = MWMechanics::calcSpellCost(*spell); } else { const ESM::Enchantment* enchantment = esmStore.get<ESM::Enchantment>().search(spellParams.getEnchantment()); if (enchantment) spellCost = MWMechanics::getEffectiveEnchantmentCastCost(*enchantment, caster); } // Magicka is increased by the cost of the spell auto& stats = target.getClass().getCreatureStats(target); auto magicka = stats.getMagicka(); magicka.setCurrent(magicka.getCurrent() + spellCost); stats.setMagicka(magicka); } MWMechanics::MagicApplicationResult::Type applyProtections(const MWWorld::Ptr& target, const MWWorld::Ptr& caster, const MWMechanics::ActiveSpells::ActiveSpellParams& spellParams, ESM::ActiveEffect& effect, const ESM::MagicEffect* magicEffect) { auto& stats = target.getClass().getCreatureStats(target); auto& magnitudes = stats.getMagicEffects(); // Apply reflect and spell absorption if (target != caster && spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary)) { bool canReflect = !(magicEffect->mData.mFlags & ESM::MagicEffect::Unreflectable) && !(effect.mFlags & ESM::ActiveEffect::Flag_Ignore_Reflect) && magnitudes.getOrDefault(ESM::MagicEffect::Reflect).getMagnitude() > 0.f && !caster.isEmpty(); bool canAbsorb = !(effect.mFlags & ESM::ActiveEffect::Flag_Ignore_SpellAbsorption) && magnitudes.getOrDefault(ESM::MagicEffect::SpellAbsorption).getMagnitude() > 0.f; if (canReflect || canAbsorb) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); for (const auto& activeParam : stats.getActiveSpells()) { for (const auto& activeEffect : activeParam.getEffects()) { if (!(activeEffect.mFlags & ESM::ActiveEffect::Flag_Applied)) continue; if (activeEffect.mEffectId == ESM::MagicEffect::Reflect) { if (canReflect && Misc::Rng::roll0to99(prng) < activeEffect.mMagnitude) { return MWMechanics::MagicApplicationResult::Type::REFLECTED; } } else if (activeEffect.mEffectId == ESM::MagicEffect::SpellAbsorption) { if (canAbsorb && Misc::Rng::roll0to99(prng) < activeEffect.mMagnitude) { absorbSpell(spellParams, caster, target); return MWMechanics::MagicApplicationResult::Type::REMOVED; } } } } } } // Notify the target actor they've been hit bool isHarmful = magicEffect->mData.mFlags & ESM::MagicEffect::Harmful; if (target.getClass().isActor() && target != caster && !caster.isEmpty() && isHarmful) target.getClass().onHit( target, 0.0f, true, MWWorld::Ptr(), caster, osg::Vec3f(), true, MWMechanics::DamageSourceType::Magical); // Apply resistances if (!(effect.mFlags & ESM::ActiveEffect::Flag_Ignore_Resistances)) { const ESM::Spell* spell = spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary) ? spellParams.getSpell() : nullptr; float magnitudeMult = MWMechanics::getEffectMultiplier(effect.mEffectId, target, caster, spell, &magnitudes); if (magnitudeMult == 0) { // Fully resisted, show message if (target == MWMechanics::getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicPCResisted}"); else if (caster == MWMechanics::getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicTargetResisted}"); return MWMechanics::MagicApplicationResult::Type::REMOVED; } effect.mMinMagnitude *= magnitudeMult; effect.mMaxMagnitude *= magnitudeMult; } return MWMechanics::MagicApplicationResult::Type::APPLIED; } static const std::map<int, std::string> sBoundItemsMap{ { ESM::MagicEffect::BoundBattleAxe, "sMagicBoundBattleAxeID" }, { ESM::MagicEffect::BoundBoots, "sMagicBoundBootsID" }, { ESM::MagicEffect::BoundCuirass, "sMagicBoundCuirassID" }, { ESM::MagicEffect::BoundDagger, "sMagicBoundDaggerID" }, { ESM::MagicEffect::BoundGloves, "sMagicBoundLeftGauntletID" }, { ESM::MagicEffect::BoundHelm, "sMagicBoundHelmID" }, { ESM::MagicEffect::BoundLongbow, "sMagicBoundLongbowID" }, { ESM::MagicEffect::BoundLongsword, "sMagicBoundLongswordID" }, { ESM::MagicEffect::BoundMace, "sMagicBoundMaceID" }, { ESM::MagicEffect::BoundShield, "sMagicBoundShieldID" }, { ESM::MagicEffect::BoundSpear, "sMagicBoundSpearID" }, }; } namespace MWMechanics { void applyMagicEffect(const MWWorld::Ptr& target, const MWWorld::Ptr& caster, const ActiveSpells::ActiveSpellParams& spellParams, ESM::ActiveEffect& effect, bool& invalid, bool& receivedMagicDamage, bool& affectedHealth, bool& recalculateMagicka) { const auto world = MWBase::Environment::get().getWorld(); bool godmode = target == getPlayer() && world->getGodModeState(); switch (effect.mEffectId) { case ESM::MagicEffect::CureCommonDisease: target.getClass().getCreatureStats(target).getSpells().purgeCommonDisease(); break; case ESM::MagicEffect::CureBlightDisease: target.getClass().getCreatureStats(target).getSpells().purgeBlightDisease(); break; case ESM::MagicEffect::RemoveCurse: target.getClass().getCreatureStats(target).getSpells().purgeCurses(); break; case ESM::MagicEffect::CureCorprusDisease: target.getClass().getCreatureStats(target).getActiveSpells().purgeEffect( target, ESM::MagicEffect::Corprus); break; case ESM::MagicEffect::CurePoison: target.getClass().getCreatureStats(target).getActiveSpells().purgeEffect( target, ESM::MagicEffect::Poison); break; case ESM::MagicEffect::CureParalyzation: target.getClass().getCreatureStats(target).getActiveSpells().purgeEffect( target, ESM::MagicEffect::Paralyze); break; case ESM::MagicEffect::Dispel: // Dispel removes entire spells at once target.getClass().getCreatureStats(target).getActiveSpells().purge( [magnitude = effect.mMagnitude](const ActiveSpells::ActiveSpellParams& params) { if (params.hasFlag(ESM::ActiveSpells::Flag_Temporary)) { const ESM::Spell* spell = params.getSpell(); if (spell && spell->mData.mType == ESM::Spell::ST_Spell) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); return Misc::Rng::roll0to99(prng) < magnitude; } } return false; }, target); break; case ESM::MagicEffect::AlmsiviIntervention: case ESM::MagicEffect::DivineIntervention: if (target != getPlayer()) invalid = true; else if (world->isTeleportingEnabled()) { std::string_view marker = (effect.mEffectId == ESM::MagicEffect::DivineIntervention) ? "divinemarker" : "templemarker"; world->teleportToClosestMarker(target, ESM::RefId::stringRefId(marker)); if (!caster.isEmpty()) { MWRender::Animation* anim = world->getAnimation(caster); anim->removeEffect(ESM::MagicEffect::indexToName(effect.mEffectId)); const ESM::Static* fx = world->getStore().get<ESM::Static>().search(ESM::RefId::stringRefId("VFX_Summon_end")); if (fx) anim->addEffect(Misc::ResourceHelpers::correctMeshPath(fx->mModel), ""); } } else if (caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sTeleportDisabled}"); break; case ESM::MagicEffect::Mark: if (target != getPlayer()) invalid = true; else if (world->isTeleportingEnabled()) world->getPlayer().markPosition(target.getCell(), target.getRefData().getPosition()); else if (caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sTeleportDisabled}"); break; case ESM::MagicEffect::Recall: if (target != getPlayer()) invalid = true; else if (world->isTeleportingEnabled()) { MWWorld::CellStore* markedCell = nullptr; ESM::Position markedPosition; world->getPlayer().getMarkedPosition(markedCell, markedPosition); if (markedCell) { ESM::RefId dest = markedCell->getCell()->getId(); MWWorld::ActionTeleport action(dest, markedPosition, false); action.execute(target); if (!caster.isEmpty()) { MWRender::Animation* anim = world->getAnimation(caster); anim->removeEffect(ESM::MagicEffect::indexToName(effect.mEffectId)); } } } else if (caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sTeleportDisabled}"); break; case ESM::MagicEffect::CommandCreature: case ESM::MagicEffect::CommandHumanoid: if (caster.isEmpty() || !caster.getClass().isActor() || target == getPlayer() || (effect.mEffectId == ESM::MagicEffect::CommandCreature) == target.getClass().isNpc()) invalid = true; else if (effect.mMagnitude >= target.getClass().getCreatureStats(target).getLevel()) { MWMechanics::AiFollow package(caster, true); target.getClass().getCreatureStats(target).getAiSequence().stack(package, target); } break; case ESM::MagicEffect::ExtraSpell: if (target.getClass().hasInventoryStore(target)) { auto& store = target.getClass().getInventoryStore(target); store.unequipAll(); } else invalid = true; break; case ESM::MagicEffect::TurnUndead: if (target.getClass().isNpc() || target.get<ESM::Creature>()->mBase->mData.mType != ESM::Creature::Undead) invalid = true; else { auto& creatureStats = target.getClass().getCreatureStats(target); Stat<int> stat = creatureStats.getAiSetting(AiSetting::Flee); stat.setModifier(static_cast<int>(stat.getModifier() + effect.mMagnitude)); creatureStats.setAiSetting(AiSetting::Flee, stat); } break; case ESM::MagicEffect::FrenzyCreature: case ESM::MagicEffect::FrenzyHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::FrenzyCreature, AiSetting::Fight, effect.mMagnitude, invalid); break; case ESM::MagicEffect::CalmCreature: case ESM::MagicEffect::CalmHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::CalmCreature, AiSetting::Fight, -effect.mMagnitude, invalid); if (!invalid && effect.mMagnitude > 0) { auto& creatureStats = target.getClass().getCreatureStats(target); creatureStats.getAiSequence().stopCombat(); } break; case ESM::MagicEffect::DemoralizeCreature: case ESM::MagicEffect::DemoralizeHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::DemoralizeCreature, AiSetting::Flee, effect.mMagnitude, invalid); break; case ESM::MagicEffect::RallyCreature: case ESM::MagicEffect::RallyHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::RallyCreature, AiSetting::Flee, -effect.mMagnitude, invalid); break; case ESM::MagicEffect::Charm: if (!target.getClass().isNpc()) invalid = true; break; case ESM::MagicEffect::Sound: if (target == getPlayer()) { const auto& magnitudes = target.getClass().getCreatureStats(target).getMagicEffects(); float volume = std::clamp( (magnitudes.getOrDefault(effect.mEffectId).getModifier() + effect.mMagnitude) / 100.f, 0.f, 1.f); MWBase::Environment::get().getSoundManager()->playSound3D(target, ESM::RefId::stringRefId("magic sound"), volume, 1.f, MWSound::Type::Sfx, MWSound::PlayMode::LoopNoEnv); } break; case ESM::MagicEffect::SummonScamp: case ESM::MagicEffect::SummonClannfear: case ESM::MagicEffect::SummonDaedroth: case ESM::MagicEffect::SummonDremora: case ESM::MagicEffect::SummonAncestralGhost: case ESM::MagicEffect::SummonSkeletalMinion: case ESM::MagicEffect::SummonBonewalker: case ESM::MagicEffect::SummonGreaterBonewalker: case ESM::MagicEffect::SummonBonelord: case ESM::MagicEffect::SummonWingedTwilight: case ESM::MagicEffect::SummonHunger: case ESM::MagicEffect::SummonGoldenSaint: case ESM::MagicEffect::SummonFlameAtronach: case ESM::MagicEffect::SummonFrostAtronach: case ESM::MagicEffect::SummonStormAtronach: case ESM::MagicEffect::SummonCenturionSphere: case ESM::MagicEffect::SummonFabricant: case ESM::MagicEffect::SummonWolf: case ESM::MagicEffect::SummonBear: case ESM::MagicEffect::SummonBonewolf: case ESM::MagicEffect::SummonCreature04: case ESM::MagicEffect::SummonCreature05: if (!target.isInCell()) invalid = true; else effect.mArg = summonCreature(effect.mEffectId, target); break; case ESM::MagicEffect::BoundGloves: if (!target.getClass().hasInventoryStore(target)) { invalid = true; break; } addBoundItem(ESM::RefId::stringRefId(world->getStore() .get<ESM::GameSetting>() .find("sMagicBoundRightGauntletID") ->mValue.getString()), target); // left gauntlet added below [[fallthrough]]; case ESM::MagicEffect::BoundDagger: case ESM::MagicEffect::BoundLongsword: case ESM::MagicEffect::BoundMace: case ESM::MagicEffect::BoundBattleAxe: case ESM::MagicEffect::BoundSpear: case ESM::MagicEffect::BoundLongbow: case ESM::MagicEffect::BoundCuirass: case ESM::MagicEffect::BoundHelm: case ESM::MagicEffect::BoundBoots: case ESM::MagicEffect::BoundShield: if (!target.getClass().hasInventoryStore(target)) invalid = true; else { const std::string& item = sBoundItemsMap.at(effect.mEffectId); addBoundItem(ESM::RefId::stringRefId( world->getStore().get<ESM::GameSetting>().find(item)->mValue.getString()), target); } break; case ESM::MagicEffect::FireDamage: case ESM::MagicEffect::ShockDamage: case ESM::MagicEffect::FrostDamage: case ESM::MagicEffect::DamageHealth: case ESM::MagicEffect::Poison: case ESM::MagicEffect::DamageMagicka: case ESM::MagicEffect::DamageFatigue: if (!godmode) { int index = 0; if (effect.mEffectId == ESM::MagicEffect::DamageMagicka) index = 1; else if (effect.mEffectId == ESM::MagicEffect::DamageFatigue) index = 2; // Damage "Dynamic" abilities reduce the base value if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) modDynamicStat(target, index, -effect.mMagnitude); else { adjustDynamicStat( target, index, -effect.mMagnitude, index == 2 && Settings::game().mUncappedDamageFatigue); if (index == 0) receivedMagicDamage = affectedHealth = true; } } break; case ESM::MagicEffect::DamageAttribute: if (!godmode) damageAttribute(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::DamageSkill: if (!target.getClass().isNpc()) invalid = true; else if (!godmode) { // Damage Skill abilities reduce base skill :todd: if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) { auto& npcStats = target.getClass().getNpcStats(target); SkillValue& skill = npcStats.getSkill(effect.getSkillOrAttribute()); // Damage Skill abilities reduce base skill :todd: skill.setBase(std::max(skill.getBase() - effect.mMagnitude, 0.f)); } else damageSkill(target, effect, effect.mMagnitude); } break; case ESM::MagicEffect::RestoreAttribute: restoreAttribute(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::RestoreSkill: if (!target.getClass().isNpc()) invalid = true; else restoreSkill(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::RestoreHealth: affectedHealth = true; [[fallthrough]]; case ESM::MagicEffect::RestoreMagicka: case ESM::MagicEffect::RestoreFatigue: adjustDynamicStat(target, effect.mEffectId - ESM::MagicEffect::RestoreHealth, effect.mMagnitude); break; case ESM::MagicEffect::SunDamage: { // isInCell shouldn't be needed, but updateActor called during game start if (!target.isInCell() || !(target.getCell()->isExterior() || target.getCell()->isQuasiExterior()) || godmode) break; const float sunRisen = world->getSunPercentage(); static float fMagicSunBlockedMult = world->getStore().get<ESM::GameSetting>().find("fMagicSunBlockedMult")->mValue.getFloat(); const float damageScale = std::clamp( std::max(world->getSunVisibility() * sunRisen, fMagicSunBlockedMult * sunRisen), 0.f, 1.f); float damage = effect.mMagnitude * damageScale; adjustDynamicStat(target, 0, -damage); if (damage > 0.f) receivedMagicDamage = affectedHealth = true; } break; case ESM::MagicEffect::DrainHealth: case ESM::MagicEffect::DrainMagicka: case ESM::MagicEffect::DrainFatigue: if (!godmode) { int index = effect.mEffectId - ESM::MagicEffect::DrainHealth; // Unlike Absorb and Damage effects Drain effects can bring stats below zero adjustDynamicStat(target, index, -effect.mMagnitude, true); if (index == 0) receivedMagicDamage = affectedHealth = true; } break; case ESM::MagicEffect::FortifyHealth: case ESM::MagicEffect::FortifyMagicka: case ESM::MagicEffect::FortifyFatigue: if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) modDynamicStat(target, effect.mEffectId - ESM::MagicEffect::FortifyHealth, effect.mMagnitude); else adjustDynamicStat( target, effect.mEffectId - ESM::MagicEffect::FortifyHealth, effect.mMagnitude, false, true); break; case ESM::MagicEffect::DrainAttribute: if (!godmode) damageAttribute(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::FortifyAttribute: // Abilities affect base stats, but not for drain if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) { auto& creatureStats = target.getClass().getCreatureStats(target); auto attribute = effect.getSkillOrAttribute(); AttributeValue attr = creatureStats.getAttribute(attribute); attr.setBase(attr.getBase() + effect.mMagnitude); creatureStats.setAttribute(attribute, attr); } else fortifyAttribute(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::DrainSkill: if (!target.getClass().isNpc()) invalid = true; else if (!godmode) damageSkill(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::FortifySkill: if (!target.getClass().isNpc()) invalid = true; else if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) { // Abilities affect base stats, but not for drain auto& npcStats = target.getClass().getNpcStats(target); auto& skill = npcStats.getSkill(effect.getSkillOrAttribute()); skill.setBase(skill.getBase() + effect.mMagnitude); } else fortifySkill(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::FortifyMaximumMagicka: recalculateMagicka = true; break; case ESM::MagicEffect::AbsorbHealth: case ESM::MagicEffect::AbsorbMagicka: case ESM::MagicEffect::AbsorbFatigue: if (!godmode) { int index = effect.mEffectId - ESM::MagicEffect::AbsorbHealth; adjustDynamicStat(target, index, -effect.mMagnitude); if (!caster.isEmpty()) adjustDynamicStat(caster, index, effect.mMagnitude); if (index == 0) receivedMagicDamage = affectedHealth = true; } break; case ESM::MagicEffect::AbsorbAttribute: if (!godmode) { damageAttribute(target, effect, effect.mMagnitude); if (!caster.isEmpty()) fortifyAttribute(caster, effect, effect.mMagnitude); } break; case ESM::MagicEffect::AbsorbSkill: if (!target.getClass().isNpc()) invalid = true; else if (!godmode) { damageSkill(target, effect, effect.mMagnitude); if (!caster.isEmpty()) fortifySkill(caster, effect, effect.mMagnitude); } break; case ESM::MagicEffect::DisintegrateArmor: { if (!target.getClass().hasInventoryStore(target)) { invalid = true; break; } if (godmode) break; static const std::array<int, 9> priorities{ MWWorld::InventoryStore::Slot_CarriedLeft, MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_LeftPauldron, MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet, MWWorld::InventoryStore::Slot_Helmet, MWWorld::InventoryStore::Slot_Greaves, MWWorld::InventoryStore::Slot_Boots, }; for (const int priority : priorities) { if (disintegrateSlot(target, priority, effect.mMagnitude)) break; } break; } case ESM::MagicEffect::DisintegrateWeapon: if (!target.getClass().hasInventoryStore(target)) { invalid = true; break; } if (!godmode) disintegrateSlot(target, MWWorld::InventoryStore::Slot_CarriedRight, effect.mMagnitude); break; } } bool shouldRemoveEffect(const MWWorld::Ptr& target, const ESM::ActiveEffect& effect) { const auto world = MWBase::Environment::get().getWorld(); switch (effect.mEffectId) { case ESM::MagicEffect::Levitate: { if (!world->isLevitationEnabled()) { if (target == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sLevitateDisabled}"); return true; } break; } case ESM::MagicEffect::Recall: case ESM::MagicEffect::DivineIntervention: case ESM::MagicEffect::AlmsiviIntervention: { return effect.mFlags & ESM::ActiveEffect::Flag_Applied; } case ESM::MagicEffect::WaterWalking: { if (target.getClass().isPureWaterCreature(target) && world->isSwimming(target)) return true; if (effect.mFlags & ESM::ActiveEffect::Flag_Applied) break; if (!world->isWaterWalkingCastableOnTarget(target)) { if (target == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicInvalidEffect}"); return true; } break; } } return false; } MagicApplicationResult applyMagicEffect(const MWWorld::Ptr& target, const MWWorld::Ptr& caster, ActiveSpells::ActiveSpellParams& spellParams, ESM::ActiveEffect& effect, float dt) { const auto world = MWBase::Environment::get().getWorld(); bool invalid = false; bool receivedMagicDamage = false; bool recalculateMagicka = false; bool affectedHealth = false; if (effect.mEffectId == ESM::MagicEffect::Corprus && spellParams.shouldWorsen()) { spellParams.worsen(); for (auto& otherEffect : spellParams.getEffects()) { if (isCorprusEffect(otherEffect)) applyMagicEffect(target, caster, spellParams, otherEffect, invalid, receivedMagicDamage, affectedHealth, recalculateMagicka); } if (target == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicCorprusWorsens}"); return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; } else if (shouldRemoveEffect(target, effect)) { onMagicEffectRemoved(target, spellParams, effect); return { MagicApplicationResult::Type::REMOVED, receivedMagicDamage, affectedHealth }; } const auto* magicEffect = world->getStore().get<ESM::MagicEffect>().find(effect.mEffectId); if (effect.mFlags & ESM::ActiveEffect::Flag_Applied) { if (magicEffect->mData.mFlags & ESM::MagicEffect::Flags::AppliedOnce) { effect.mTimeLeft -= dt; return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; } else if (!dt) return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; } if (effect.mEffectId == ESM::MagicEffect::Lock) { if (target.getClass().canLock(target)) { MWRender::Animation* animation = world->getAnimation(target); if (animation) animation->addSpellCastGlow(magicEffect->getColor()); int magnitude = static_cast<int>(roll(effect)); if (target.getCellRef().getLockLevel() < magnitude) // If the door is not already locked to a higher value, lock it to spell magnitude { MWBase::Environment::get().getSoundManager()->playSound3D( target, ESM::RefId::stringRefId("Open Lock"), 1.f, 1.f); if (caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicLockSuccess}"); target.getCellRef().lock(magnitude); } } else invalid = true; } else if (effect.mEffectId == ESM::MagicEffect::Open) { if (target.getClass().canLock(target)) { // Use the player instead of the caster for vanilla crime compatibility MWBase::Environment::get().getMechanicsManager()->unlockAttempted(getPlayer(), target); MWRender::Animation* animation = world->getAnimation(target); if (animation) animation->addSpellCastGlow(magicEffect->getColor()); int magnitude = static_cast<int>(roll(effect)); if (target.getCellRef().getLockLevel() <= magnitude) { if (target.getCellRef().isLocked()) { MWBase::Environment::get().getSoundManager()->playSound3D( target, ESM::RefId::stringRefId("Open Lock"), 1.f, 1.f); if (caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicOpenSuccess}"); target.getCellRef().unlock(); } } else { MWBase::Environment::get().getSoundManager()->playSound3D( target, ESM::RefId::stringRefId("Open Lock Fail"), 1.f, 1.f); } } else invalid = true; } else if (!target.getClass().isActor()) { invalid = true; } else { // Morrowind.exe doesn't apply magic effects while the menu is open, we do because we like to see stats // updated instantly. We don't want to teleport instantly though if (!dt && (effect.mEffectId == ESM::MagicEffect::Recall || effect.mEffectId == ESM::MagicEffect::DivineIntervention || effect.mEffectId == ESM::MagicEffect::AlmsiviIntervention)) return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; auto& stats = target.getClass().getCreatureStats(target); auto& magnitudes = stats.getMagicEffects(); if (!spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues) && !(effect.mFlags & ESM::ActiveEffect::Flag_Applied)) { MagicApplicationResult::Type result = applyProtections(target, caster, spellParams, effect, magicEffect); if (result != MagicApplicationResult::Type::APPLIED) return { result, receivedMagicDamage, affectedHealth }; } float oldMagnitude = 0.f; if (effect.mFlags & ESM::ActiveEffect::Flag_Applied) oldMagnitude = effect.mMagnitude; else { if (!spellParams.hasFlag(ESM::ActiveSpells::Flag_Equipment) && !spellParams.hasFlag(ESM::ActiveSpells::Flag_Lua)) playEffects(target, *magicEffect, spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary)); if (effect.mEffectId == ESM::MagicEffect::Soultrap && !target.getClass().isNpc() && target.getType() == ESM::Creature::sRecordId && target.get<ESM::Creature>()->mBase->mData.mSoul == 0 && caster == getPlayer()) MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicInvalidTarget}"); } float magnitude = roll(effect); // Note that there's an early out for Flag_Applied AppliedOnce effects so we don't have to exclude them here effect.mMagnitude = magnitude; if (!(magicEffect->mData.mFlags & (ESM::MagicEffect::Flags::NoMagnitude | ESM::MagicEffect::Flags::AppliedOnce))) { if (effect.mDuration != 0) { float mult = dt; if (spellParams.hasFlag(ESM::ActiveSpells::Flag_Temporary)) mult = std::min(effect.mTimeLeft, dt); effect.mMagnitude *= mult; } if (effect.mMagnitude == 0) { effect.mMagnitude = oldMagnitude; effect.mFlags |= ESM::ActiveEffect::Flag_Applied | ESM::ActiveEffect::Flag_Remove; effect.mTimeLeft -= dt; return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; } } if (effect.mEffectId == ESM::MagicEffect::Corprus) spellParams.worsen(); else applyMagicEffect(target, caster, spellParams, effect, invalid, receivedMagicDamage, affectedHealth, recalculateMagicka); effect.mMagnitude = magnitude; magnitudes.add(EffectKey(effect.mEffectId, effect.getSkillOrAttribute()), EffectParam(effect.mMagnitude - oldMagnitude)); } effect.mTimeLeft -= dt; if (invalid) { effect.mTimeLeft = 0; effect.mFlags |= ESM::ActiveEffect::Flag_Remove; auto anim = world->getAnimation(target); if (anim) anim->removeEffect(ESM::MagicEffect::indexToName(effect.mEffectId)); } else effect.mFlags |= ESM::ActiveEffect::Flag_Applied | ESM::ActiveEffect::Flag_Remove; if (recalculateMagicka) target.getClass().getCreatureStats(target).recalculateMagicka(); return { MagicApplicationResult::Type::APPLIED, receivedMagicDamage, affectedHealth }; } void removeMagicEffect( const MWWorld::Ptr& target, ActiveSpells::ActiveSpellParams& spellParams, const ESM::ActiveEffect& effect) { const auto world = MWBase::Environment::get().getWorld(); auto& magnitudes = target.getClass().getCreatureStats(target).getMagicEffects(); bool invalid; switch (effect.mEffectId) { case ESM::MagicEffect::CommandCreature: case ESM::MagicEffect::CommandHumanoid: if (magnitudes.getOrDefault(effect.mEffectId).getMagnitude() <= 0.f) { auto& seq = target.getClass().getCreatureStats(target).getAiSequence(); seq.erasePackageIf([&](const auto& package) { return package->getTypeId() == MWMechanics::AiPackageTypeId::Follow && static_cast<const MWMechanics::AiFollow*>(package.get())->isCommanded(); }); } break; case ESM::MagicEffect::ExtraSpell: if (magnitudes.getOrDefault(effect.mEffectId).getMagnitude() <= 0.f) target.getClass().getInventoryStore(target).autoEquip(); break; case ESM::MagicEffect::TurnUndead: { auto& creatureStats = target.getClass().getCreatureStats(target); Stat<int> stat = creatureStats.getAiSetting(AiSetting::Flee); stat.setModifier(static_cast<int>(stat.getModifier() - effect.mMagnitude)); creatureStats.setAiSetting(AiSetting::Flee, stat); } break; case ESM::MagicEffect::FrenzyCreature: case ESM::MagicEffect::FrenzyHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::FrenzyCreature, AiSetting::Fight, -effect.mMagnitude, invalid); break; case ESM::MagicEffect::CalmCreature: case ESM::MagicEffect::CalmHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::CalmCreature, AiSetting::Fight, effect.mMagnitude, invalid); break; case ESM::MagicEffect::DemoralizeCreature: case ESM::MagicEffect::DemoralizeHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::DemoralizeCreature, AiSetting::Flee, -effect.mMagnitude, invalid); break; case ESM::MagicEffect::NightEye: { const MWMechanics::EffectParam nightEye = magnitudes.getOrDefault(effect.mEffectId); if (nightEye.getMagnitude() < 0.f && nightEye.getBase() < 0) { // The PCVisionBonus functions are different from every other magic effect function in that they // clamp the value to [0, 1]. Morrowind.exe applies the same clamping to the night-eye effect, which // can create situations where an effect is still active (i.e. shown in the menu) but the screen is // no longer bright. Modifying the base value here should prevent that while preserving their // function. float delta = std::clamp(-nightEye.getMagnitude(), 0.f, -static_cast<float>(nightEye.getBase())); magnitudes.modifyBase(effect.mEffectId, static_cast<int>(delta)); } } break; case ESM::MagicEffect::RallyCreature: case ESM::MagicEffect::RallyHumanoid: modifyAiSetting( target, effect, ESM::MagicEffect::RallyCreature, AiSetting::Flee, effect.mMagnitude, invalid); break; case ESM::MagicEffect::Sound: if (magnitudes.getOrDefault(effect.mEffectId).getModifier() <= 0.f && target == getPlayer()) MWBase::Environment::get().getSoundManager()->stopSound3D( target, ESM::RefId::stringRefId("magic sound")); break; case ESM::MagicEffect::SummonScamp: case ESM::MagicEffect::SummonClannfear: case ESM::MagicEffect::SummonDaedroth: case ESM::MagicEffect::SummonDremora: case ESM::MagicEffect::SummonAncestralGhost: case ESM::MagicEffect::SummonSkeletalMinion: case ESM::MagicEffect::SummonBonewalker: case ESM::MagicEffect::SummonGreaterBonewalker: case ESM::MagicEffect::SummonBonelord: case ESM::MagicEffect::SummonWingedTwilight: case ESM::MagicEffect::SummonHunger: case ESM::MagicEffect::SummonGoldenSaint: case ESM::MagicEffect::SummonFlameAtronach: case ESM::MagicEffect::SummonFrostAtronach: case ESM::MagicEffect::SummonStormAtronach: case ESM::MagicEffect::SummonCenturionSphere: case ESM::MagicEffect::SummonFabricant: case ESM::MagicEffect::SummonWolf: case ESM::MagicEffect::SummonBear: case ESM::MagicEffect::SummonBonewolf: case ESM::MagicEffect::SummonCreature04: case ESM::MagicEffect::SummonCreature05: { int actorId = effect.getActorId(); if (actorId != -1) MWBase::Environment::get().getMechanicsManager()->cleanupSummonedCreature(target, actorId); auto& summons = target.getClass().getCreatureStats(target).getSummonedCreatureMap(); auto [begin, end] = summons.equal_range(effect.mEffectId); for (auto it = begin; it != end; ++it) { if (it->second == actorId) { summons.erase(it); break; } } } break; case ESM::MagicEffect::BoundGloves: removeBoundItem(ESM::RefId::stringRefId(world->getStore() .get<ESM::GameSetting>() .find("sMagicBoundRightGauntletID") ->mValue.getString()), target); [[fallthrough]]; case ESM::MagicEffect::BoundDagger: case ESM::MagicEffect::BoundLongsword: case ESM::MagicEffect::BoundMace: case ESM::MagicEffect::BoundBattleAxe: case ESM::MagicEffect::BoundSpear: case ESM::MagicEffect::BoundLongbow: case ESM::MagicEffect::BoundCuirass: case ESM::MagicEffect::BoundHelm: case ESM::MagicEffect::BoundBoots: case ESM::MagicEffect::BoundShield: { const std::string& item = sBoundItemsMap.at(effect.mEffectId); removeBoundItem( ESM::RefId::stringRefId(world->getStore().get<ESM::GameSetting>().find(item)->mValue.getString()), target); } break; case ESM::MagicEffect::DrainHealth: case ESM::MagicEffect::DrainMagicka: case ESM::MagicEffect::DrainFatigue: adjustDynamicStat(target, effect.mEffectId - ESM::MagicEffect::DrainHealth, effect.mMagnitude); break; case ESM::MagicEffect::FortifyHealth: case ESM::MagicEffect::FortifyMagicka: case ESM::MagicEffect::FortifyFatigue: if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) modDynamicStat(target, effect.mEffectId - ESM::MagicEffect::FortifyHealth, -effect.mMagnitude); else adjustDynamicStat( target, effect.mEffectId - ESM::MagicEffect::FortifyHealth, -effect.mMagnitude, true); break; case ESM::MagicEffect::DrainAttribute: restoreAttribute(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::FortifyAttribute: // Abilities affect base stats, but not for drain if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) { auto& creatureStats = target.getClass().getCreatureStats(target); auto attribute = effect.getSkillOrAttribute(); AttributeValue attr = creatureStats.getAttribute(attribute); attr.setBase(attr.getBase() - effect.mMagnitude); creatureStats.setAttribute(attribute, attr); } else fortifyAttribute(target, effect, -effect.mMagnitude); break; case ESM::MagicEffect::DrainSkill: restoreSkill(target, effect, effect.mMagnitude); break; case ESM::MagicEffect::FortifySkill: // Abilities affect base stats, but not for drain if (spellParams.hasFlag(ESM::ActiveSpells::Flag_AffectsBaseValues)) { auto& npcStats = target.getClass().getNpcStats(target); auto& skill = npcStats.getSkill(effect.getSkillOrAttribute()); skill.setBase(skill.getBase() - effect.mMagnitude); } else fortifySkill(target, effect, -effect.mMagnitude); break; case ESM::MagicEffect::FortifyMaximumMagicka: target.getClass().getCreatureStats(target).recalculateMagicka(); break; case ESM::MagicEffect::AbsorbAttribute: { const auto caster = world->searchPtrViaActorId(spellParams.getCasterActorId()); restoreAttribute(target, effect, effect.mMagnitude); if (!caster.isEmpty()) fortifyAttribute(caster, effect, -effect.mMagnitude); } break; case ESM::MagicEffect::AbsorbSkill: { const auto caster = world->searchPtrViaActorId(spellParams.getCasterActorId()); restoreSkill(target, effect, effect.mMagnitude); if (!caster.isEmpty()) fortifySkill(caster, effect, -effect.mMagnitude); } break; case ESM::MagicEffect::Corprus: { int worsenings = spellParams.getWorsenings(); spellParams.resetWorsenings(); if (worsenings > 0) { for (const auto& otherEffect : spellParams.getEffects()) { if (isCorprusEffect(otherEffect, true)) { for (int i = 0; i < worsenings; i++) removeMagicEffect(target, spellParams, otherEffect); } } } // Note that we remove the effects, but keep the params target.getClass().getCreatureStats(target).getActiveSpells().purge( [&spellParams]( const ActiveSpells::ActiveSpellParams& params, const auto&) { return &spellParams == &params; }, target); } break; } } void onMagicEffectRemoved( const MWWorld::Ptr& target, ActiveSpells::ActiveSpellParams& spellParams, const ESM::ActiveEffect& effect) { if (!(effect.mFlags & ESM::ActiveEffect::Flag_Applied)) return; auto& magnitudes = target.getClass().getCreatureStats(target).getMagicEffects(); magnitudes.add(EffectKey(effect.mEffectId, effect.getSkillOrAttribute()), EffectParam(-effect.mMagnitude)); removeMagicEffect(target, spellParams, effect); if (magnitudes.getOrDefault(effect.mEffectId).getMagnitude() <= 0.f) { auto anim = MWBase::Environment::get().getWorld()->getAnimation(target); if (anim) anim->removeEffect(ESM::MagicEffect::indexToName(effect.mEffectId)); } } }
61,687
C++
.cpp
1,227
35.036675
120
0.562668
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,336
alchemy.cpp
OpenMW_openmw/apps/openmw/mwmechanics/alchemy.cpp
#include "alchemy.hpp" #include <cassert> #include <cmath> #include <algorithm> #include <map> #include <stdexcept> #include <components/misc/rng.hpp> #include <components/esm3/loadappa.hpp> #include <components/esm3/loadgmst.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadskil.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "creaturestats.hpp" #include "magiceffects.hpp" namespace { constexpr size_t sNumEffects = 4; std::optional<MWMechanics::EffectKey> toKey(const ESM::Ingredient& ingredient, size_t i) { if (ingredient.mData.mEffectID[i] < 0) return {}; ESM::RefId arg = ESM::Skill::indexToRefId(ingredient.mData.mSkills[i]); if (arg.empty()) arg = ESM::Attribute::indexToRefId(ingredient.mData.mAttributes[i]); return MWMechanics::EffectKey(ingredient.mData.mEffectID[i], arg); } bool containsEffect(const ESM::Ingredient& ingredient, const MWMechanics::EffectKey& effect) { for (size_t j = 0; j < sNumEffects; ++j) { if (toKey(ingredient, j) == effect) return true; } return false; } } MWMechanics::Alchemy::Alchemy() : mValue(0) { } std::vector<MWMechanics::EffectKey> MWMechanics::Alchemy::listEffects() const { // We care about the order of these effects as each effect can affect the next when applied. // The player can affect effect order by placing ingredients into different slots std::vector<EffectKey> effects; for (size_t slotI = 0; slotI < mIngredients.size() - 1; ++slotI) { if (mIngredients[slotI].isEmpty()) continue; const ESM::Ingredient* ingredient = mIngredients[slotI].get<ESM::Ingredient>()->mBase; for (size_t slotJ = slotI + 1; slotJ < mIngredients.size(); ++slotJ) { if (mIngredients[slotJ].isEmpty()) continue; const ESM::Ingredient* ingredient2 = mIngredients[slotJ].get<ESM::Ingredient>()->mBase; for (size_t i = 0; i < sNumEffects; ++i) { if (const auto key = toKey(*ingredient, i)) { if (std::find(effects.begin(), effects.end(), *key) != effects.end()) continue; if (containsEffect(*ingredient2, *key)) effects.push_back(*key); } } } } return effects; } void MWMechanics::Alchemy::applyTools(int flags, float& value) const { bool magnitude = !(flags & ESM::MagicEffect::NoMagnitude); bool duration = !(flags & ESM::MagicEffect::NoDuration); bool negative = (flags & ESM::MagicEffect::Harmful) != 0; int tool = negative ? ESM::Apparatus::Alembic : ESM::Apparatus::Retort; int setup = 0; if (!mTools[tool].isEmpty() && !mTools[ESM::Apparatus::Calcinator].isEmpty()) setup = 1; else if (!mTools[tool].isEmpty()) setup = 2; else if (!mTools[ESM::Apparatus::Calcinator].isEmpty()) setup = 3; else return; float toolQuality = setup == 1 || setup == 2 ? mTools[tool].get<ESM::Apparatus>()->mBase->mData.mQuality : 0; float calcinatorQuality = setup == 1 || setup == 3 ? mTools[ESM::Apparatus::Calcinator].get<ESM::Apparatus>()->mBase->mData.mQuality : 0; float quality = 1; switch (setup) { case 1: quality = negative ? 2 * toolQuality + 3 * calcinatorQuality : (magnitude && duration ? 2 * toolQuality + calcinatorQuality : 2 / 3.0f * (toolQuality + calcinatorQuality) + 0.5f); break; case 2: quality = negative ? 1 + toolQuality : (magnitude && duration ? toolQuality : toolQuality + 0.5f); break; case 3: quality = magnitude && duration ? calcinatorQuality : calcinatorQuality + 0.5f; break; } if (setup == 3 || !negative) { value += quality; } else { if (quality == 0) throw std::runtime_error("invalid derived alchemy apparatus quality"); value /= quality; } } void MWMechanics::Alchemy::updateEffects() { mEffects.clear(); mValue = 0; if (countIngredients() < 2 || mAlchemist.isEmpty() || mTools[ESM::Apparatus::MortarPestle].isEmpty()) return; // find effects std::vector<EffectKey> effects = listEffects(); // general alchemy factor float x = getAlchemyFactor(); x *= mTools[ESM::Apparatus::MortarPestle].get<ESM::Apparatus>()->mBase->mData.mQuality; x *= MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fPotionStrengthMult") ->mValue.getFloat(); // value mValue = static_cast<int>( x * MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>().find("iAlchemyMod")->mValue.getFloat()); // build quantified effect list for (const auto& effectKey : effects) { const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effectKey.mId); if (magicEffect->mData.mBaseCost <= 0) { const std::string os = "invalid base cost for magic effect " + std::to_string(effectKey.mId); throw std::runtime_error(os); } float fPotionT1MagMul = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fPotionT1MagMult") ->mValue.getFloat(); if (fPotionT1MagMul <= 0) throw std::runtime_error("invalid gmst: fPotionT1MagMul"); float fPotionT1DurMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fPotionT1DurMult") ->mValue.getFloat(); if (fPotionT1DurMult <= 0) throw std::runtime_error("invalid gmst: fPotionT1DurMult"); float magnitude = (magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude) ? 1.0f : (x / fPotionT1MagMul) / magicEffect->mData.mBaseCost; float duration = (magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration) ? 1.0f : (x / fPotionT1DurMult) / magicEffect->mData.mBaseCost; if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)) applyTools(magicEffect->mData.mFlags, magnitude); if (!(magicEffect->mData.mFlags & ESM::MagicEffect::NoDuration)) applyTools(magicEffect->mData.mFlags, duration); duration = roundf(duration); magnitude = roundf(magnitude); if (magnitude > 0 && duration > 0) { ESM::ENAMstruct effect; effect.mEffectID = effectKey.mId; effect.mAttribute = -1; effect.mSkill = -1; if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetSkill) effect.mSkill = ESM::Skill::refIdToIndex(effectKey.mArg); else if (magicEffect->mData.mFlags & ESM::MagicEffect::TargetAttribute) effect.mAttribute = ESM::Attribute::refIdToIndex(effectKey.mArg); effect.mRange = 0; effect.mArea = 0; effect.mDuration = static_cast<int>(duration); effect.mMagnMin = effect.mMagnMax = static_cast<int>(magnitude); mEffects.push_back(effect); } } } const ESM::Potion* MWMechanics::Alchemy::getRecord(const ESM::Potion& toFind) const { const MWWorld::Store<ESM::Potion>& potions = MWBase::Environment::get().getESMStore()->get<ESM::Potion>(); MWWorld::Store<ESM::Potion>::iterator iter = potions.begin(); for (; iter != potions.end(); ++iter) { if (iter->mEffects.mList.size() != mEffects.size()) continue; if (iter->mName != toFind.mName || iter->mScript != toFind.mScript || iter->mData.mWeight != toFind.mData.mWeight || iter->mData.mValue != toFind.mData.mValue || iter->mData.mFlags != toFind.mData.mFlags) continue; // Don't choose an ID that came from the content files, would have unintended side effects // where alchemy can be used to produce quest-relevant items if (!potions.isDynamic(iter->mId)) continue; bool mismatch = false; for (size_t i = 0; i < iter->mEffects.mList.size(); ++i) { const ESM::IndexedENAMstruct& first = iter->mEffects.mList[i]; const ESM::ENAMstruct& second = mEffects[i]; if (first.mData.mEffectID != second.mEffectID || first.mData.mArea != second.mArea || first.mData.mRange != second.mRange || first.mData.mSkill != second.mSkill || first.mData.mAttribute != second.mAttribute || first.mData.mMagnMin != second.mMagnMin || first.mData.mMagnMax != second.mMagnMax || first.mData.mDuration != second.mDuration) { mismatch = true; break; } } if (!mismatch) return &(*iter); } return nullptr; } void MWMechanics::Alchemy::removeIngredients() { for (TIngredientsContainer::iterator iter(mIngredients.begin()); iter != mIngredients.end(); ++iter) if (!iter->isEmpty()) { iter->getContainerStore()->remove(*iter, 1); if (iter->getCellRef().getCount() < 1) *iter = MWWorld::Ptr(); } updateEffects(); } void MWMechanics::Alchemy::addPotion(const std::string& name) { ESM::Potion newRecord; newRecord.mData.mWeight = 0; for (TIngredientsIterator iter(beginIngredients()); iter != endIngredients(); ++iter) if (!iter->isEmpty()) newRecord.mData.mWeight += iter->get<ESM::Ingredient>()->mBase->mData.mWeight; if (countIngredients() > 0) newRecord.mData.mWeight /= countIngredients(); newRecord.mData.mValue = mValue; newRecord.mData.mFlags = 0; newRecord.mRecordFlags = 0; newRecord.mName = name; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); int index = Misc::Rng::rollDice(6, prng); assert(index >= 0 && index < 6); static const char* meshes[] = { "standard", "bargain", "cheap", "fresh", "exclusive", "quality" }; newRecord.mModel = "m\\misc_potion_" + std::string(meshes[index]) + "_01.nif"; newRecord.mIcon = "m\\tx_potion_" + std::string(meshes[index]) + "_01.dds"; newRecord.mEffects.populate(mEffects); const ESM::Potion* record = getRecord(newRecord); if (!record) record = MWBase::Environment::get().getESMStore()->insert(newRecord); mAlchemist.getClass().getContainerStore(mAlchemist).add(record->mId, 1); } void MWMechanics::Alchemy::increaseSkill() { mAlchemist.getClass().skillUsageSucceeded(mAlchemist, ESM::Skill::Alchemy, ESM::Skill::Alchemy_CreatePotion); } float MWMechanics::Alchemy::getAlchemyFactor() const { const CreatureStats& creatureStats = mAlchemist.getClass().getCreatureStats(mAlchemist); return (mAlchemist.getClass().getSkill(mAlchemist, ESM::Skill::Alchemy) + 0.1f * creatureStats.getAttribute(ESM::Attribute::Intelligence).getModified() + 0.1f * creatureStats.getAttribute(ESM::Attribute::Luck).getModified()); } int MWMechanics::Alchemy::countIngredients() const { int ingredients = 0; for (TIngredientsIterator iter(beginIngredients()); iter != endIngredients(); ++iter) if (!iter->isEmpty()) ++ingredients; return ingredients; } int MWMechanics::Alchemy::countPotionsToBrew() const { Result readyStatus = getReadyStatus(); if (readyStatus != Result_Success) return 0; int toBrew = -1; for (TIngredientsIterator iter(beginIngredients()); iter != endIngredients(); ++iter) if (!iter->isEmpty()) { int count = iter->getCellRef().getCount(); if ((count > 0 && count < toBrew) || toBrew < 0) toBrew = count; } return toBrew; } void MWMechanics::Alchemy::setAlchemist(const MWWorld::Ptr& npc) { mAlchemist = npc; mIngredients.resize(4); std::fill(mIngredients.begin(), mIngredients.end(), MWWorld::Ptr()); mTools.resize(4); std::vector<MWWorld::Ptr> prevTools(mTools); std::fill(mTools.begin(), mTools.end(), MWWorld::Ptr()); mEffects.clear(); MWWorld::ContainerStore& store = npc.getClass().getContainerStore(npc); for (MWWorld::ContainerStoreIterator iter(store.begin(MWWorld::ContainerStore::Type_Apparatus)); iter != store.end(); ++iter) { MWWorld::LiveCellRef<ESM::Apparatus>* ref = iter->get<ESM::Apparatus>(); int type = ref->mBase->mData.mType; if (type < 0 || type >= static_cast<int>(mTools.size())) throw std::runtime_error("invalid apparatus type"); if (prevTools[type] == *iter) mTools[type] = *iter; // prefer the previous tool if still in the container if (!mTools[type].isEmpty() && !prevTools[type].isEmpty() && mTools[type] == prevTools[type]) continue; if (!mTools[type].isEmpty()) if (ref->mBase->mData.mQuality <= mTools[type].get<ESM::Apparatus>()->mBase->mData.mQuality) continue; mTools[type] = *iter; } } MWMechanics::Alchemy::TToolsIterator MWMechanics::Alchemy::beginTools() const { return mTools.begin(); } MWMechanics::Alchemy::TToolsIterator MWMechanics::Alchemy::endTools() const { return mTools.end(); } MWMechanics::Alchemy::TIngredientsIterator MWMechanics::Alchemy::beginIngredients() const { return mIngredients.begin(); } MWMechanics::Alchemy::TIngredientsIterator MWMechanics::Alchemy::endIngredients() const { return mIngredients.end(); } void MWMechanics::Alchemy::clear() { mAlchemist = MWWorld::Ptr(); mIngredients.clear(); mEffects.clear(); setPotionName(""); } void MWMechanics::Alchemy::setPotionName(const std::string& name) { mPotionName = name; } int MWMechanics::Alchemy::addIngredient(const MWWorld::Ptr& ingredient) { // find a free slot int slot = -1; for (int i = 0; i < static_cast<int>(mIngredients.size()); ++i) if (mIngredients[i].isEmpty()) { slot = i; break; } if (slot == -1) return -1; for (TIngredientsIterator iter(mIngredients.begin()); iter != mIngredients.end(); ++iter) if (!iter->isEmpty() && ingredient.getCellRef().getRefId() == iter->getCellRef().getRefId()) return -1; mIngredients[slot] = ingredient; updateEffects(); return slot; } void MWMechanics::Alchemy::removeIngredient(size_t index) { if (index < mIngredients.size()) { mIngredients[index] = MWWorld::Ptr(); updateEffects(); } } void MWMechanics::Alchemy::addApparatus(const MWWorld::Ptr& apparatus) { int32_t slot = apparatus.get<ESM::Apparatus>()->mBase->mData.mType; mTools[slot] = apparatus; updateEffects(); } void MWMechanics::Alchemy::removeApparatus(size_t index) { if (index < mTools.size()) { mTools[index] = MWWorld::Ptr(); updateEffects(); } } MWMechanics::Alchemy::TEffectsIterator MWMechanics::Alchemy::beginEffects() const { return mEffects.begin(); } MWMechanics::Alchemy::TEffectsIterator MWMechanics::Alchemy::endEffects() const { return mEffects.end(); } bool MWMechanics::Alchemy::knownEffect(unsigned int potionEffectIndex, const MWWorld::Ptr& npc) { float alchemySkill = npc.getClass().getSkill(npc, ESM::Skill::Alchemy); static const float fWortChanceValue = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>().find("fWortChanceValue")->mValue.getFloat(); return (potionEffectIndex <= 1 && alchemySkill >= fWortChanceValue) || (potionEffectIndex <= 3 && alchemySkill >= fWortChanceValue * 2) || (potionEffectIndex <= 5 && alchemySkill >= fWortChanceValue * 3) || (potionEffectIndex <= 7 && alchemySkill >= fWortChanceValue * 4); } MWMechanics::Alchemy::Result MWMechanics::Alchemy::getReadyStatus() const { if (mTools[ESM::Apparatus::MortarPestle].isEmpty()) return Result_NoMortarAndPestle; if (countIngredients() < 2) return Result_LessThanTwoIngredients; if (mPotionName.empty()) return Result_NoName; if (listEffects().empty()) return Result_NoEffects; return Result_Success; } MWMechanics::Alchemy::Result MWMechanics::Alchemy::create(const std::string& name, int& count) { setPotionName(name); Result readyStatus = getReadyStatus(); if (readyStatus == Result_NoEffects) removeIngredients(); if (readyStatus != Result_Success) return readyStatus; MWBase::Environment::get().getWorld()->breakInvisibility(mAlchemist); Result result = Result_RandomFailure; int brewedCount = 0; for (int i = 0; i < count; ++i) { if (createSingle() == Result_Success) { result = Result_Success; brewedCount++; } } count = brewedCount; return result; } MWMechanics::Alchemy::Result MWMechanics::Alchemy::createSingle() { if (beginEffects() == endEffects()) { // all effects were nullified due to insufficient skill removeIngredients(); return Result_RandomFailure; } auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (getAlchemyFactor() < Misc::Rng::roll0to99(prng)) { removeIngredients(); return Result_RandomFailure; } addPotion(mPotionName); removeIngredients(); increaseSkill(); return Result_Success; } std::string MWMechanics::Alchemy::suggestPotionName() { std::vector<MWMechanics::EffectKey> effects = listEffects(); if (effects.empty()) return {}; return effects.begin()->toString(); } std::vector<std::string> MWMechanics::Alchemy::effectsDescription(const MWWorld::ConstPtr& ptr, const int alchemySkill) { std::vector<std::string> effects; const auto& item = ptr.get<ESM::Ingredient>()->mBase; const auto& store = MWBase::Environment::get().getESMStore(); const auto& mgef = store->get<ESM::MagicEffect>(); const static auto fWortChanceValue = store->get<ESM::GameSetting>().find("fWortChanceValue")->mValue.getFloat(); const auto& data = item->mData; for (size_t i = 0; i < sNumEffects; ++i) { const auto effectID = data.mEffectID[i]; if (alchemySkill < fWortChanceValue * static_cast<int>(i + 1)) break; if (effectID != -1) { const ESM::Attribute* attribute = store->get<ESM::Attribute>().search(ESM::Attribute::indexToRefId(data.mAttributes[i])); const ESM::Skill* skill = store->get<ESM::Skill>().search(ESM::Skill::indexToRefId(data.mSkills[i])); std::string effect = getMagicEffectString(*mgef.find(effectID), attribute, skill); effects.push_back(effect); } } return effects; }
19,582
C++
.cpp
493
32.03854
120
0.626801
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,337
spelllist.cpp
OpenMW_openmw/apps/openmw/mwmechanics/spelllist.cpp
#include "spelllist.hpp" #include <algorithm> #include <components/esm3/loadcrea.hpp> #include <components/esm3/loadnpc.hpp> #include <components/esm3/loadspel.hpp> #include "spells.hpp" #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" namespace { template <class T> const std::vector<ESM::RefId> getSpellList(const ESM::RefId& id) { return MWBase::Environment::get().getESMStore()->get<T>().find(id)->mSpells.mList; } template <class T> bool withBaseRecord(const ESM::RefId& id, const std::function<bool(std::vector<ESM::RefId>&)>& function) { T copy = *MWBase::Environment::get().getESMStore()->get<T>().find(id); bool changed = function(copy.mSpells.mList); if (changed) MWBase::Environment::get().getESMStore()->overrideRecord(copy); return changed; } } namespace MWMechanics { SpellList::SpellList(const ESM::RefId& id, int type) : mId(id) , mType(type) { } bool SpellList::withBaseRecord(const std::function<bool(std::vector<ESM::RefId>&)>& function) { switch (mType) { case ESM::REC_CREA: return ::withBaseRecord<ESM::Creature>(mId, function); case ESM::REC_NPC_: return ::withBaseRecord<ESM::NPC>(mId, function); default: throw std::logic_error("failed to update base record for " + mId.toDebugString()); } } const std::vector<ESM::RefId> SpellList::getSpells() const { switch (mType) { case ESM::REC_CREA: return getSpellList<ESM::Creature>(mId); case ESM::REC_NPC_: return getSpellList<ESM::NPC>(mId); default: throw std::logic_error("failed to get spell list for " + mId.toDebugString()); } } const ESM::Spell* SpellList::getSpell(const ESM::RefId& id) { return MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(id); } void SpellList::add(const ESM::Spell* spell) { auto& id = spell->mId; bool changed = withBaseRecord([&](auto& spells) { for (const auto& it : spells) { if (id == it) return false; } spells.push_back(id); return true; }); if (changed) { for (auto listener : mListeners) listener->addSpell(spell); } } void SpellList::remove(const ESM::Spell* spell) { auto& id = spell->mId; bool changed = withBaseRecord([&](auto& spells) { for (auto it = spells.begin(); it != spells.end(); it++) { if (id == *it) { spells.erase(it); return true; } } return false; }); if (changed) { for (auto listener : mListeners) listener->removeSpell(spell); } } void SpellList::removeAll(const std::vector<ESM::RefId>& ids) { bool changed = withBaseRecord([&](auto& spells) { const auto it = std::remove_if(spells.begin(), spells.end(), [&](const auto& spell) { const auto isSpell = [&](const auto& id) { return spell == id; }; return ids.end() != std::find_if(ids.begin(), ids.end(), isSpell); }); if (it == spells.end()) return false; spells.erase(it, spells.end()); return true; }); if (changed) { for (auto listener : mListeners) { for (auto& id : ids) { const auto spell = getSpell(id); listener->removeSpell(spell); } } } } void SpellList::clear() { bool changed = withBaseRecord([](auto& spells) { if (spells.empty()) return false; spells.clear(); return true; }); if (changed) { for (auto listener : mListeners) listener->removeAllSpells(); } } void SpellList::addListener(Spells* spells) { if (std::find(mListeners.begin(), mListeners.end(), spells) != mListeners.end()) return; mListeners.push_back(spells); } void SpellList::removeListener(Spells* spells) { const auto it = std::find(mListeners.begin(), mListeners.end(), spells); if (it != mListeners.end()) mListeners.erase(it); } void SpellList::updateListener(Spells* before, Spells* after) { const auto it = std::find(mListeners.begin(), mListeners.end(), before); if (it == mListeners.end()) return mListeners.push_back(after); *it = after; } }
4,994
C++
.cpp
156
22.410256
108
0.529876
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,338
security.cpp
OpenMW_openmw/apps/openmw/mwmechanics/security.cpp
#include "security.hpp" #include <components/misc/rng.hpp> #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "creaturestats.hpp" namespace MWMechanics { Security::Security(const MWWorld::Ptr& actor) : mActor(actor) { CreatureStats& creatureStats = actor.getClass().getCreatureStats(actor); mAgility = creatureStats.getAttribute(ESM::Attribute::Agility).getModified(); mLuck = creatureStats.getAttribute(ESM::Attribute::Luck).getModified(); mSecuritySkill = static_cast<float>(actor.getClass().getSkill(actor, ESM::Skill::Security)); mFatigueTerm = creatureStats.getFatigueTerm(); } void Security::pickLock(const MWWorld::Ptr& lock, const MWWorld::Ptr& lockpick, std::string_view& resultMessage, std::string_view& resultSound) { // If it's unlocked or can not be unlocked back out immediately. Note that we're not strictly speaking checking // if the ref is locked, lock levels <= 0 can exist but they cannot be picked if (lock.getCellRef().getLockLevel() <= 0 || !lock.getClass().hasToolTip(lock)) return; int uses = lockpick.getClass().getItemHealth(lockpick); if (uses == 0) return; int lockStrength = lock.getCellRef().getLockLevel(); float pickQuality = lockpick.get<ESM::Lockpick>()->mBase->mData.mQuality; float fPickLockMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fPickLockMult") ->mValue.getFloat(); float x = 0.2f * mAgility + 0.1f * mLuck + mSecuritySkill; x *= pickQuality * mFatigueTerm; x += fPickLockMult * lockStrength; MWBase::Environment::get().getMechanicsManager()->unlockAttempted(mActor, lock); resultSound = "Open Lock Fail"; if (x <= 0) resultMessage = "#{sLockImpossible}"; else { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (Misc::Rng::roll0to99(prng) <= x) { lock.getCellRef().unlock(); resultMessage = "#{sLockSuccess}"; resultSound = "Open Lock"; mActor.getClass().skillUsageSucceeded(mActor, ESM::Skill::Security, ESM::Skill::Security_PickLock); } else resultMessage = "#{sLockFail}"; } lockpick.getCellRef().setCharge(--uses); if (!uses) lockpick.getContainerStore()->remove(lockpick, 1); } void Security::probeTrap(const MWWorld::Ptr& trap, const MWWorld::Ptr& probe, std::string_view& resultMessage, std::string_view& resultSound) { if (trap.getCellRef().getTrap().empty()) return; int uses = probe.getClass().getItemHealth(probe); if (uses == 0) return; float probeQuality = probe.get<ESM::Probe>()->mBase->mData.mQuality; const ESM::Spell* trapSpell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(trap.getCellRef().getTrap()); int trapSpellPoints = trapSpell->mData.mCost; float fTrapCostMult = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fTrapCostMult") ->mValue.getFloat(); float x = 0.2f * mAgility + 0.1f * mLuck + mSecuritySkill; x += fTrapCostMult * trapSpellPoints; x *= probeQuality * mFatigueTerm; MWBase::Environment::get().getMechanicsManager()->unlockAttempted(mActor, trap); resultSound = "Disarm Trap Fail"; if (x <= 0) resultMessage = "#{sTrapImpossible}"; else { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); if (Misc::Rng::roll0to99(prng) <= x) { trap.getCellRef().setTrap(ESM::RefId()); resultSound = "Disarm Trap"; resultMessage = "#{sTrapSuccess}"; mActor.getClass().skillUsageSucceeded(mActor, ESM::Skill::Security, ESM::Skill::Security_DisarmTrap); } else resultMessage = "#{sTrapFail}"; } probe.getCellRef().setCharge(--uses); if (!uses) probe.getContainerStore()->remove(probe, 1); } }
4,731
C++
.cpp
103
34.427184
119
0.581921
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,339
recharge.cpp
OpenMW_openmw/apps/openmw/mwmechanics/recharge.cpp
#include "recharge.hpp" #include <components/esm3/loadcrea.hpp> #include <components/esm3/loadench.hpp> #include <components/misc/rng.hpp> #include <components/misc/strings/format.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "actorutil.hpp" #include "creaturestats.hpp" #include "spellutil.hpp" namespace MWMechanics { bool rechargeItem(const MWWorld::Ptr& item, const float maxCharge, const float duration) { float charge = item.getCellRef().getEnchantmentCharge(); if (charge == -1 || charge == maxCharge) return false; static const float fMagicItemRechargePerSecond = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fMagicItemRechargePerSecond") ->mValue.getFloat(); item.getCellRef().setEnchantmentCharge(std::min(charge + fMagicItemRechargePerSecond * duration, maxCharge)); return true; } bool rechargeItem(const MWWorld::Ptr& item, const MWWorld::Ptr& gem) { if (!gem.getCellRef().getCount()) return false; MWWorld::Ptr player = MWMechanics::getPlayer(); MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player); MWBase::Environment::get().getWorld()->breakInvisibility(player); float luckTerm = 0.1f * stats.getAttribute(ESM::Attribute::Luck).getModified(); if (luckTerm < 1 || luckTerm > 10) luckTerm = 1; float intelligenceTerm = 0.2f * stats.getAttribute(ESM::Attribute::Intelligence).getModified(); if (intelligenceTerm > 20) intelligenceTerm = 20; if (intelligenceTerm < 1) intelligenceTerm = 1; float x = (player.getClass().getSkill(player, ESM::Skill::Enchant) + intelligenceTerm + luckTerm) * stats.getFatigueTerm(); auto& prng = MWBase::Environment::get().getWorld()->getPrng(); int roll = Misc::Rng::roll0to99(prng); if (roll < x) { const ESM::RefId& soul = gem.getCellRef().getSoul(); const ESM::Creature* creature = MWBase::Environment::get().getESMStore()->get<ESM::Creature>().find(soul); float restored = creature->mData.mSoul * (roll / x); const ESM::Enchantment* enchantment = MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().find( item.getClass().getEnchantment(item)); const int maxCharge = MWMechanics::getEnchantmentCharge(*enchantment); item.getCellRef().setEnchantmentCharge( std::min(item.getCellRef().getEnchantmentCharge() + restored, static_cast<float>(maxCharge))); MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Enchant Success")); player.getClass().getContainerStore(player).restack(item); } else { MWBase::Environment::get().getWindowManager()->playSound(ESM::RefId::stringRefId("Enchant Fail")); } player.getClass().skillUsageSucceeded(player, ESM::Skill::Enchant, ESM::Skill::Enchant_Recharge); gem.getContainerStore()->remove(gem, 1); if (gem.getCellRef().getCount() == 0) { std::string message = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("sNotifyMessage51") ->mValue.getString(); message = Misc::StringUtils::format(message, gem.getClass().getName(gem)); MWBase::Environment::get().getWindowManager()->messageBox(message); const ESM::RefId soulGemAzura = ESM::RefId::stringRefId("Misc_SoulGem_Azura"); // special case: readd Azura's Star if (gem.get<ESM::Miscellaneous>()->mBase->mId == soulGemAzura) player.getClass().getContainerStore(player).add(soulGemAzura, 1); } return true; } }
4,443
C++
.cpp
85
39.541176
118
0.595892
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,340
aipackage.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aipackage.cpp
#include "aipackage.hpp" #include <components/detournavigator/agentbounds.hpp> #include <components/detournavigator/navigator.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm3/loadland.hpp> #include <components/misc/coordinateconverter.hpp> #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/luamanager.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwphysics/raycasting.hpp" #include "actorutil.hpp" #include "creaturestats.hpp" #include "movement.hpp" #include "pathgrid.hpp" #include "steering.hpp" #include <osg/Quat> namespace { float divOrMax(float dividend, float divisor) { return divisor == 0 ? std::numeric_limits<float>::max() * std::numeric_limits<float>::epsilon() : dividend / divisor; } float getPointTolerance(float speed, float duration, const osg::Vec3f& halfExtents) { const float actorTolerance = 2 * speed * duration + 1.2 * std::max(halfExtents.x(), halfExtents.y()); return std::max(MWMechanics::MIN_TOLERANCE, actorTolerance); } bool canOpenDoors(const MWWorld::Ptr& ptr) { return ptr.getClass().isBipedal(ptr) || ptr.getClass().hasInventoryStore(ptr); } } MWMechanics::AiPackage::AiPackage(AiPackageTypeId typeId, const Options& options) : mTypeId(typeId) , mOptions(options) , mReaction(MWBase::Environment::get().getWorld()->getPrng()) , mTargetActorId(-1) , mCachedTarget() , mRotateOnTheRunChecks(0) , mIsShortcutting(false) , mShortcutProhibited(false) , mShortcutFailPos() { } MWWorld::Ptr MWMechanics::AiPackage::getTarget() const { if (!mCachedTarget.isEmpty()) { if (mCachedTarget.mRef->isDeleted() || !mCachedTarget.getRefData().isEnabled()) mCachedTarget = MWWorld::Ptr(); else return mCachedTarget; } if (mTargetActorId == -2) return MWWorld::Ptr(); if (mTargetActorId == -1) { if (mTargetActorRefId.empty()) { mTargetActorId = -2; return MWWorld::Ptr(); } mCachedTarget = MWBase::Environment::get().getWorld()->searchPtr(mTargetActorRefId, false); if (mCachedTarget.isEmpty()) { mTargetActorId = -2; return mCachedTarget; } else mTargetActorId = mCachedTarget.getClass().getCreatureStats(mCachedTarget).getActorId(); } if (mTargetActorId != -1) mCachedTarget = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId); else return MWWorld::Ptr(); return mCachedTarget; } bool MWMechanics::AiPackage::targetIs(const MWWorld::Ptr& ptr) const { if (mTargetActorId == -2) return ptr.isEmpty(); else if (mTargetActorId == -1) { if (mTargetActorRefId.empty()) { mTargetActorId = -2; return ptr.isEmpty(); } if (!ptr.isEmpty() && ptr.getCellRef().getRefId() == mTargetActorRefId) return getTarget() == ptr; return false; } if (ptr.isEmpty() || !ptr.getClass().isActor()) return false; return ptr.getClass().getCreatureStats(ptr).getActorId() == mTargetActorId; } void MWMechanics::AiPackage::reset() { // reset all members mReaction.reset(); mIsShortcutting = false; mShortcutProhibited = false; mShortcutFailPos = osg::Vec3f(); mCachedTarget = MWWorld::Ptr(); mPathFinder.clearPath(); mObstacleCheck.clear(); } bool MWMechanics::AiPackage::pathTo(const MWWorld::Ptr& actor, const osg::Vec3f& dest, float duration, MWWorld::MovementDirectionFlags supportedMovementDirections, float destTolerance, float endTolerance, PathType pathType) { const Misc::TimerStatus timerStatus = mReaction.update(duration); const osg::Vec3f position = actor.getRefData().getPosition().asVec3(); // position of the actor MWBase::World* world = MWBase::Environment::get().getWorld(); const DetourNavigator::AgentBounds agentBounds = world->getPathfindingAgentBounds(actor); /// Stops the actor when it gets too close to a unloaded cell or when the actor is playing a scripted animation //... At current time, the first test is unnecessary. AI shuts down when actor is more than //... "actors processing range" setting value units from player, and exterior cells are 8192 units long and wide. //... But AI processing distance may increase in the future. if (isNearInactiveCell(position) || MWBase::Environment::get().getMechanicsManager()->checkScriptedAnimationPlaying(actor)) { actor.getClass().getMovementSettings(actor).mPosition[0] = 0; actor.getClass().getMovementSettings(actor).mPosition[1] = 0; world->updateActorPath(actor, mPathFinder.getPath(), agentBounds, position, dest); return false; } mLastDestinationTolerance = destTolerance; const float distToTarget = distance(position, dest); const bool isDestReached = (distToTarget <= destTolerance); const bool actorCanMoveByZ = canActorMoveByZAxis(actor); if (!isDestReached && timerStatus == Misc::TimerStatus::Elapsed) { if (canOpenDoors(actor)) openDoors(actor); const bool wasShortcutting = mIsShortcutting; bool destInLOS = false; // Prohibit shortcuts for AiWander, if the actor can not move in 3 dimensions. mIsShortcutting = actorCanMoveByZ && shortcutPath(position, dest, actor, &destInLOS, actorCanMoveByZ); // try to shortcut first if (!mIsShortcutting) { if (wasShortcutting || doesPathNeedRecalc(dest, actor)) // if need to rebuild path { const ESM::Pathgrid* pathgrid = world->getStore().get<ESM::Pathgrid>().search(*actor.getCell()->getCell()); const DetourNavigator::Flags navigatorFlags = getNavigatorFlags(actor); const DetourNavigator::AreaCosts areaCosts = getAreaCosts(actor, navigatorFlags); mPathFinder.buildLimitedPath(actor, position, dest, actor.getCell(), getPathGridGraph(pathgrid), agentBounds, navigatorFlags, areaCosts, endTolerance, pathType); mRotateOnTheRunChecks = 3; // give priority to go directly on target if there is minimal opportunity if (destInLOS && mPathFinder.getPath().size() > 1) { // get point just before dest auto pPointBeforeDest = mPathFinder.getPath().rbegin() + 1; // if start point is closer to the target then last point of path (excluding target itself) then go // straight on the target if (distance(position, dest) <= distance(dest, *pPointBeforeDest)) { mPathFinder.clearPath(); mPathFinder.addPointToPath(dest); } } } if (!mPathFinder.getPath().empty()) // Path has points in it { const osg::Vec3f& lastPos = mPathFinder.getPath().back(); // Get the end of the proposed path if (distance(dest, lastPos) > 100) // End of the path is far from the destination mPathFinder.addPointToPath( dest); // Adds the final destination to the path, to try to get to where you want to go } } } const float pointTolerance = getPointTolerance(actor.getClass().getMaxSpeed(actor), duration, world->getHalfExtents(actor)); const bool smoothMovement = Settings::game().mSmoothMovement; PathFinder::UpdateFlags updateFlags{}; if (actorCanMoveByZ) updateFlags |= PathFinder::UpdateFlag_CanMoveByZ; if (timerStatus == Misc::TimerStatus::Elapsed && smoothMovement) updateFlags |= PathFinder::UpdateFlag_ShortenIfAlmostStraight; if (timerStatus == Misc::TimerStatus::Elapsed) updateFlags |= PathFinder::UpdateFlag_RemoveLoops; mPathFinder.update(position, pointTolerance, DEFAULT_TOLERANCE, updateFlags, agentBounds, getNavigatorFlags(actor)); if (isDestReached || mPathFinder.checkPathCompleted()) // if path is finished { // turn to destination point zTurn(actor, getZAngleToPoint(position, dest)); smoothTurn(actor, getXAngleToPoint(position, dest), 0); world->removeActorPath(actor); return true; } else if (mPathFinder.getPath().empty()) return false; world->updateActorPath(actor, mPathFinder.getPath(), agentBounds, position, dest); if (mRotateOnTheRunChecks == 0 || isReachableRotatingOnTheRun( actor, *mPathFinder.getPath().begin())) // to prevent circling around a path point { actor.getClass().getMovementSettings(actor).mPosition[1] = 1; // move to the target if (mRotateOnTheRunChecks > 0) mRotateOnTheRunChecks--; } // turn to next path point by X,Z axes float zAngleToNext = mPathFinder.getZAngleToNext(position.x(), position.y()); zTurn(actor, zAngleToNext); smoothTurn(actor, mPathFinder.getXAngleToNext(position.x(), position.y(), position.z()), 0); const auto destination = getNextPathPoint(dest); mObstacleCheck.update(actor, destination, duration, supportedMovementDirections); if (smoothMovement) { const float smoothTurnReservedDist = 150; auto& movement = actor.getClass().getMovementSettings(actor); float distToNextSqr = osg::Vec2f(destination.x() - position.x(), destination.y() - position.y()).length2(); float diffAngle = zAngleToNext - actor.getRefData().getPosition().rot[2]; if (std::cos(diffAngle) < -0.1) movement.mPosition[0] = movement.mPosition[1] = 0; else if (distToNextSqr > smoothTurnReservedDist * smoothTurnReservedDist) { // Go forward (and slowly turn towards the next path point) movement.mPosition[0] = 0; movement.mPosition[1] = 1; } else { // Next path point is near, so use diagonal movement to follow the path precisely. movement.mPosition[0] = std::sin(diffAngle); movement.mPosition[1] = std::max(std::cos(diffAngle), 0.f); } } // handle obstacles on the way evadeObstacles(actor); return false; } void MWMechanics::AiPackage::evadeObstacles(const MWWorld::Ptr& actor) { // check if stuck due to obstacles if (!mObstacleCheck.isEvading()) return; // first check if obstacle is a door float distance = MWBase::Environment::get().getWorld()->getMaxActivationDistance(); const MWWorld::Ptr door = getNearbyDoor(actor, distance); if (!door.isEmpty() && canOpenDoors(actor)) { openDoors(actor); } else { mObstacleCheck.takeEvasiveAction(actor.getClass().getMovementSettings(actor)); } } namespace { bool isDoorOnTheWay(const MWWorld::Ptr& actor, const MWWorld::Ptr& door, const osg::Vec3f& nextPathPoint) { const auto world = MWBase::Environment::get().getWorld(); const auto halfExtents = world->getHalfExtents(actor); const auto position = actor.getRefData().getPosition().asVec3() + osg::Vec3f(0, 0, halfExtents.z()); const auto destination = nextPathPoint + osg::Vec3f(0, 0, halfExtents.z()); return world->hasCollisionWithDoor(door, position, destination); } } void MWMechanics::AiPackage::openDoors(const MWWorld::Ptr& actor) { // note: AiWander currently does not open doors if (getTypeId() == AiPackageTypeId::Wander) return; if (mPathFinder.getPathSize() == 0) return; float distance = MWBase::Environment::get().getWorld()->getMaxActivationDistance(); const MWWorld::Ptr door = getNearbyDoor(actor, distance); if (door == MWWorld::Ptr()) return; if (!door.getCellRef().getTeleport() && door.getClass().getDoorState(door) == MWWorld::DoorState::Idle) { if (!isDoorOnTheWay(actor, door, mPathFinder.getPath().front())) return; if (door.getCellRef().getTrap().empty() && !door.getCellRef().isLocked()) { MWBase::Environment::get().getLuaManager()->objectActivated(door, actor); return; } const ESM::RefId& keyId = door.getCellRef().getKey(); if (keyId.empty()) return; MWWorld::ContainerStore& invStore = actor.getClass().getContainerStore(actor); MWWorld::Ptr keyPtr = invStore.search(keyId); if (!keyPtr.isEmpty()) MWBase::Environment::get().getLuaManager()->objectActivated(door, actor); } } const MWMechanics::PathgridGraph& MWMechanics::AiPackage::getPathGridGraph(const ESM::Pathgrid* pathgrid) const { if (!pathgrid || pathgrid->mPoints.empty()) return PathgridGraph::sEmpty; // static cache is OK for now, pathgrids can never change during runtime static std::map<const ESM::Pathgrid*, std::unique_ptr<MWMechanics::PathgridGraph>> cache; auto found = cache.find(pathgrid); if (found == cache.end()) found = cache.emplace(pathgrid, std::make_unique<MWMechanics::PathgridGraph>(*pathgrid)).first; return *found->second.get(); } bool MWMechanics::AiPackage::shortcutPath(const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const MWWorld::Ptr& actor, bool* destInLOS, bool isPathClear) { if (!mShortcutProhibited || (mShortcutFailPos - startPoint).length() >= PATHFIND_SHORTCUT_RETRY_DIST) { // check if target is clearly visible isPathClear = !MWBase::Environment::get() .getWorld() ->getRayCasting() ->castRay(startPoint, endPoint, MWPhysics::CollisionType_World | MWPhysics::CollisionType_Door) .mHit; if (destInLOS != nullptr) *destInLOS = isPathClear; if (!isPathClear) return false; // check if an actor can move along the shortcut path isPathClear = checkWayIsClearForActor(startPoint, endPoint, actor); } if (isPathClear) // can shortcut the path { mPathFinder.clearPath(); mPathFinder.addPointToPath(endPoint); return true; } return false; } bool MWMechanics::AiPackage::checkWayIsClearForActor( const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const MWWorld::Ptr& actor) { if (canActorMoveByZAxis(actor)) return true; const float actorSpeed = actor.getClass().getMaxSpeed(actor); const float maxAvoidDist = AI_REACTION_TIME * actorSpeed + actorSpeed / getAngularVelocity(actorSpeed) * 2; // *2 - for reliability const float distToTarget = osg::Vec2f(endPoint.x(), endPoint.y()).length(); const float offsetXY = distToTarget > maxAvoidDist * 1.5 ? maxAvoidDist : maxAvoidDist / 2; // update shortcut prohibit state if (checkWayIsClear(startPoint, endPoint, offsetXY)) { if (mShortcutProhibited) { mShortcutProhibited = false; mShortcutFailPos = osg::Vec3f(); } return true; } else { if (mShortcutFailPos == osg::Vec3f()) { mShortcutProhibited = true; mShortcutFailPos = startPoint; } } return false; } bool MWMechanics::AiPackage::doesPathNeedRecalc(const osg::Vec3f& newDest, const MWWorld::Ptr& actor) const { return mPathFinder.getPath().empty() || getPathDistance(actor, mPathFinder.getPath().back(), newDest) > 10 || mPathFinder.getPathCell() != actor.getCell(); } bool MWMechanics::AiPackage::isNearInactiveCell(osg::Vec3f position) { const MWWorld::Cell* playerCell = getPlayer().getCell()->getCell(); if (playerCell->isExterior()) { // get actor's distance from origin of center cell Misc::makeCoordinateConverter(*playerCell).toLocal(position); // currently assumes 3 x 3 grid for exterior cells, with player at center cell. // AI shuts down actors before they reach edges of 3 x 3 grid. const float distanceFromEdge = 200.0; float minThreshold = (-1.0f * ESM::Land::REAL_SIZE) + distanceFromEdge; float maxThreshold = (2.0f * ESM::Land::REAL_SIZE) - distanceFromEdge; return (position.x() < minThreshold) || (maxThreshold < position.x()) || (position.y() < minThreshold) || (maxThreshold < position.y()); } else { return false; } } bool MWMechanics::AiPackage::isReachableRotatingOnTheRun(const MWWorld::Ptr& actor, const osg::Vec3f& dest) { // get actor's shortest radius for moving in circle float speed = actor.getClass().getMaxSpeed(actor); speed += speed * 0.1f; // 10% real speed inaccuracy float radius = speed / getAngularVelocity(speed); // get radius direction to the center const float* rot = actor.getRefData().getPosition().rot; osg::Quat quatRot(rot[0], -osg::X_AXIS, rot[1], -osg::Y_AXIS, rot[2], -osg::Z_AXIS); osg::Vec3f dir = quatRot * osg::Y_AXIS; // actor's orientation direction is a tangent to circle osg::Vec3f radiusDir = dir ^ osg::Z_AXIS; // radius is perpendicular to a tangent radiusDir.normalize(); radiusDir *= radius; // pick up the nearest center candidate osg::Vec3f pos = actor.getRefData().getPosition().asVec3(); osg::Vec3f center1 = pos - radiusDir; osg::Vec3f center2 = pos + radiusDir; osg::Vec3f center = (center1 - dest).length2() < (center2 - dest).length2() ? center1 : center2; float distToDest = (center - dest).length(); // if pathpoint is reachable for the actor rotating on the run: // no points of actor's circle should be farther from the center than destination point return (radius <= distToDest); } DetourNavigator::Flags MWMechanics::AiPackage::getNavigatorFlags(const MWWorld::Ptr& actor) const { const MWWorld::Class& actorClass = actor.getClass(); DetourNavigator::Flags result = DetourNavigator::Flag_none; if ((actorClass.isPureWaterCreature(actor) || (getTypeId() != AiPackageTypeId::Wander && ((Settings::game().mAllowActorsToFollowOverWaterSurface && getTypeId() == AiPackageTypeId::Follow) || actorClass.canSwim(actor) || hasWaterWalking(actor)))) && actorClass.getSwimSpeed(actor) > 0) result |= DetourNavigator::Flag_swim; if (actorClass.canWalk(actor) && actor.getClass().getWalkSpeed(actor) > 0) result |= DetourNavigator::Flag_walk | DetourNavigator::Flag_usePathgrid; if (canOpenDoors(actor) && getTypeId() != AiPackageTypeId::Wander) result |= DetourNavigator::Flag_openDoor; return result; } DetourNavigator::AreaCosts MWMechanics::AiPackage::getAreaCosts( const MWWorld::Ptr& actor, DetourNavigator::Flags flags) const { DetourNavigator::AreaCosts costs; const MWWorld::Class& actorClass = actor.getClass(); const float walkSpeed = [&] { if ((flags & DetourNavigator::Flag_walk) == 0) return 0.0f; if (getTypeId() == AiPackageTypeId::Wander) return actorClass.getWalkSpeed(actor); return actorClass.getRunSpeed(actor); }(); const float swimSpeed = [&] { if ((flags & DetourNavigator::Flag_swim) == 0) return 0.0f; if (hasWaterWalking(actor)) return walkSpeed; return actorClass.getSwimSpeed(actor); }(); const float maxSpeed = std::max(swimSpeed, walkSpeed); if (maxSpeed == 0) return costs; const float swimFactor = swimSpeed / maxSpeed; const float walkFactor = walkSpeed / maxSpeed; costs.mWater = divOrMax(costs.mWater, swimFactor); costs.mDoor = divOrMax(costs.mDoor, walkFactor); costs.mPathgrid = divOrMax(costs.mPathgrid, walkFactor); costs.mGround = divOrMax(costs.mGround, walkFactor); return costs; } osg::Vec3f MWMechanics::AiPackage::getNextPathPoint(const osg::Vec3f& destination) const { return mPathFinder.getPath().empty() ? destination : mPathFinder.getPath().front(); } float MWMechanics::AiPackage::getNextPathPointTolerance( float speed, float duration, const osg::Vec3f& halfExtents) const { if (mPathFinder.getPathSize() <= 1) return std::max(DEFAULT_TOLERANCE, mLastDestinationTolerance); return getPointTolerance(speed, duration, halfExtents); }
20,771
C++
.cpp
470
36.906383
120
0.667689
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,341
aibreathe.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aibreathe.cpp
#include "aibreathe.hpp" #include "../mwbase/environment.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "npcstats.hpp" #include "movement.hpp" #include "steering.hpp" bool MWMechanics::AiBreathe::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { static const float fHoldBreathTime = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>().find("fHoldBreathTime")->mValue.getFloat(); const MWWorld::Class& actorClass = actor.getClass(); if (actorClass.isNpc()) { if (actorClass.getNpcStats(actor).getTimeToStartDrowning() < fHoldBreathTime / 2) { actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true); actorClass.getMovementSettings(actor).mPosition[1] = 1; smoothTurn(actor, static_cast<float>(-osg::PI_2), 0); return false; } } return true; }
995
C++
.cpp
25
34.12
119
0.69615
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,342
pathfinding.cpp
OpenMW_openmw/apps/openmw/mwmechanics/pathfinding.cpp
#include "pathfinding.hpp" #include <iterator> #include <limits> #include <osg/io_utils> #include <components/debug/debuglog.hpp> #include <components/detournavigator/debug.hpp> #include <components/detournavigator/navigatorutils.hpp> #include <components/misc/coordinateconverter.hpp> #include <components/misc/math.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwphysics/raycasting.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "actorutil.hpp" #include "pathgrid.hpp" namespace { // Chooses a reachable end pathgrid point. start is assumed reachable. std::pair<int, bool> getClosestReachablePoint( const ESM::Pathgrid* grid, const MWMechanics::PathgridGraph* graph, const osg::Vec3f& pos, int start) { assert(grid && !grid->mPoints.empty()); float closestDistanceBetween = std::numeric_limits<float>::max(); float closestDistanceReachable = std::numeric_limits<float>::max(); int closestIndex = 0; int closestReachableIndex = 0; // TODO: if this full scan causes performance problems mapping pathgrid // points to a quadtree may help for (size_t counter = 0; counter < grid->mPoints.size(); counter++) { float potentialDistBetween = MWMechanics::PathFinder::distanceSquared(grid->mPoints[counter], pos); if (potentialDistBetween < closestDistanceReachable) { // found a closer one if (graph->isPointConnected(start, counter)) { closestDistanceReachable = potentialDistBetween; closestReachableIndex = counter; } if (potentialDistBetween < closestDistanceBetween) { closestDistanceBetween = potentialDistBetween; closestIndex = counter; } } } // post-condition: start and endpoint must be connected assert(graph->isPointConnected(start, closestReachableIndex)); // AiWander has logic that depends on whether a path was created, deleting // allowed nodes if not. Hence a path needs to be created even if the start // and the end points are the same. return std::pair<int, bool>(closestReachableIndex, closestReachableIndex == closestIndex); } float sqrDistance(const osg::Vec2f& lhs, const osg::Vec2f& rhs) { return (lhs - rhs).length2(); } float sqrDistanceIgnoreZ(const osg::Vec3f& lhs, const osg::Vec3f& rhs) { return sqrDistance(osg::Vec2f(lhs.x(), lhs.y()), osg::Vec2f(rhs.x(), rhs.y())); } float getHeight(const MWWorld::ConstPtr& actor) { const auto world = MWBase::Environment::get().getWorld(); const auto halfExtents = world->getHalfExtents(actor); return 2.0 * halfExtents.z(); } // Returns true if turn in `p2` is less than 10 degrees and all the 3 points are almost on one line. bool isAlmostStraight(const osg::Vec3f& p1, const osg::Vec3f& p2, const osg::Vec3f& p3, float pointTolerance) { osg::Vec3f v1 = p1 - p2; osg::Vec3f v3 = p3 - p2; v1.z() = v3.z() = 0; float dotProduct = v1.x() * v3.x() + v1.y() * v3.y(); float crossProduct = v1.x() * v3.y() - v1.y() * v3.x(); // Check that the angle between v1 and v3 is less or equal than 5 degrees. static const float cos175 = std::cos(osg::PI * (175.0 / 180)); bool checkAngle = dotProduct <= cos175 * v1.length() * v3.length(); // Check that distance from p2 to the line (p1, p3) is less or equal than `pointTolerance`. bool checkDist = std::abs(crossProduct) <= pointTolerance * (p3 - p1).length(); return checkAngle && checkDist; } struct IsValidShortcut { const DetourNavigator::Navigator* mNavigator; const DetourNavigator::AgentBounds mAgentBounds; const DetourNavigator::Flags mFlags; bool operator()(const osg::Vec3f& start, const osg::Vec3f& end) const { const auto position = DetourNavigator::raycast(*mNavigator, mAgentBounds, start, end, mFlags); return position.has_value() && std::abs((position.value() - start).length2() - (end - start).length2()) <= 1; } }; } namespace MWMechanics { float getPathDistance(const MWWorld::Ptr& actor, const osg::Vec3f& lhs, const osg::Vec3f& rhs) { if (std::abs(lhs.z() - rhs.z()) > getHeight(actor) || canActorMoveByZAxis(actor)) return distance(lhs, rhs); return distanceIgnoreZ(lhs, rhs); } bool checkWayIsClear(const osg::Vec3f& from, const osg::Vec3f& to, float offsetXY) { osg::Vec3f dir = to - from; dir.z() = 0; dir.normalize(); float verticalOffset = 200; // instead of '200' here we want the height of the actor osg::Vec3f _from = from + dir * offsetXY + osg::Z_AXIS * verticalOffset; // cast up-down ray and find height of hit in world space float h = _from.z() - MWBase::Environment::get().getWorld()->getDistToNearestRayHit( _from, -osg::Z_AXIS, verticalOffset + PATHFIND_Z_REACH + 1); return (std::abs(from.z() - h) <= PATHFIND_Z_REACH); } /* * NOTE: This method may fail to find a path. The caller must check the * result before using it. If there is no path the AI routies need to * implement some other heuristics to reach the target. * * NOTE: It may be desirable to simply go directly to the endPoint if for * example there are no pathgrids in this cell. * * NOTE: startPoint & endPoint are in world coordinates * * Updates mPath using aStarSearch() or ray test (if shortcut allowed). * mPath consists of pathgrid points, except the last element which is * endPoint. This may be useful where the endPoint is not on a pathgrid * point (e.g. combat). However, if the caller has already chosen a * pathgrid point (e.g. wander) then it may be worth while to call * pop_back() to remove the redundant entry. * * NOTE: coordinates must be converted prior to calling getClosestPoint() * * | * | cell * | +-----------+ * | | | * | | | * | | @ | * | i | j | * |<--->|<---->| | * | +-----------+ * | k * |<---------->| world * +----------------------------- * * i = x value of cell itself (multiply by ESM::Land::REAL_SIZE to convert) * j = @.x in local coordinates (i.e. within the cell) * k = @.x in world coordinates */ void PathFinder::buildPathByPathgridImpl(const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const PathgridGraph& pathgridGraph, std::back_insert_iterator<std::deque<osg::Vec3f>> out) { const auto pathgrid = pathgridGraph.getPathgrid(); // Refer to AiWander research topic on openmw forums for some background. // Maybe there is no pathgrid for this cell. Just go to destination and let // physics take care of any blockages. if (!pathgrid || pathgrid->mPoints.empty()) return; // NOTE: getClosestPoint expects local coordinates const Misc::CoordinateConverter converter = Misc::makeCoordinateConverter(*mCell->getCell()); // NOTE: It is possible that getClosestPoint returns a pathgrind point index // that is unreachable in some situations. e.g. actor is standing // outside an area enclosed by walls, but there is a pathgrid // point right behind the wall that is closer than any pathgrid // point outside the wall osg::Vec3f startPointInLocalCoords(converter.toLocalVec3(startPoint)); int startNode = getClosestPoint(pathgrid, startPointInLocalCoords); osg::Vec3f endPointInLocalCoords(converter.toLocalVec3(endPoint)); std::pair<int, bool> endNode = getClosestReachablePoint(pathgrid, &pathgridGraph, endPointInLocalCoords, startNode); // if it's shorter for actor to travel from start to end, than to travel from either // start or end to nearest pathgrid point, just travel from start to end. float startToEndLength2 = (endPointInLocalCoords - startPointInLocalCoords).length2(); float endTolastNodeLength2 = distanceSquared(pathgrid->mPoints[endNode.first], endPointInLocalCoords); float startTo1stNodeLength2 = distanceSquared(pathgrid->mPoints[startNode], startPointInLocalCoords); if ((startToEndLength2 < startTo1stNodeLength2) || (startToEndLength2 < endTolastNodeLength2)) { *out++ = endPoint; return; } // AiWander has logic that depends on whether a path was created, // deleting allowed nodes if not. Hence a path needs to be created // even if the start and the end points are the same. // NOTE: aStarSearch will return an empty path if the start and end // nodes are the same if (startNode == endNode.first) { ESM::Pathgrid::Point temp(pathgrid->mPoints[startNode]); converter.toWorld(temp); *out++ = makeOsgVec3(temp); } else { auto path = pathgridGraph.aStarSearch(startNode, endNode.first); // If nearest path node is in opposite direction from second, remove it from path. // Especially useful for wandering actors, if the nearest node is blocked for some reason. if (path.size() > 1) { ESM::Pathgrid::Point secondNode = *(++path.begin()); osg::Vec3f firstNodeVec3f = makeOsgVec3(pathgrid->mPoints[startNode]); osg::Vec3f secondNodeVec3f = makeOsgVec3(secondNode); osg::Vec3f toSecondNodeVec3f = secondNodeVec3f - firstNodeVec3f; osg::Vec3f toStartPointVec3f = startPointInLocalCoords - firstNodeVec3f; if (toSecondNodeVec3f * toStartPointVec3f > 0) { ESM::Pathgrid::Point temp(secondNode); converter.toWorld(temp); // Add Z offset since path node can overlap with other objects. // Also ignore doors in raytesting. const int mask = MWPhysics::CollisionType_World; bool isPathClear = !MWBase::Environment::get() .getWorld() ->getRayCasting() ->castRay(osg::Vec3f(startPoint.x(), startPoint.y(), startPoint.z() + 16), osg::Vec3f(temp.mX, temp.mY, temp.mZ + 16), mask) .mHit; if (isPathClear) path.pop_front(); } } // convert supplied path to world coordinates std::transform(path.begin(), path.end(), out, [&](ESM::Pathgrid::Point& point) { converter.toWorld(point); return makeOsgVec3(point); }); } // If endNode found is NOT the closest PathGrid point to the endPoint, // assume endPoint is not reachable from endNode. In which case, // path ends at endNode. // // So only add the destination (which may be different to the closest // pathgrid point) when endNode was the closest point to endPoint. // // This logic can fail in the opposite situate, e.g. endPoint may // have been reachable but happened to be very close to an // unreachable pathgrid point. // // The AI routines will have to deal with such situations. if (endNode.second) *out++ = endPoint; } float PathFinder::getZAngleToNext(float x, float y) const { // This should never happen (programmers should have an if statement checking // isPathConstructed that prevents this call if otherwise). if (mPath.empty()) return 0.; const auto& nextPoint = mPath.front(); const float directionX = nextPoint.x() - x; const float directionY = nextPoint.y() - y; return std::atan2(directionX, directionY); } float PathFinder::getXAngleToNext(float x, float y, float z) const { // This should never happen (programmers should have an if statement checking // isPathConstructed that prevents this call if otherwise). if (mPath.empty()) return 0.; const osg::Vec3f dir = mPath.front() - osg::Vec3f(x, y, z); return getXAngleToDir(dir); } void PathFinder::update(const osg::Vec3f& position, float pointTolerance, float destinationTolerance, UpdateFlags updateFlags, const DetourNavigator::AgentBounds& agentBounds, DetourNavigator::Flags pathFlags) { if (mPath.empty()) return; while (mPath.size() > 1 && sqrDistanceIgnoreZ(mPath.front(), position) < pointTolerance * pointTolerance) mPath.pop_front(); const IsValidShortcut isValidShortcut{ MWBase::Environment::get().getWorld()->getNavigator(), agentBounds, pathFlags }; if ((updateFlags & UpdateFlag_ShortenIfAlmostStraight) != 0) { while (mPath.size() > 2 && isAlmostStraight(mPath[0], mPath[1], mPath[2], pointTolerance) && isValidShortcut(mPath[0], mPath[2])) mPath.erase(mPath.begin() + 1); if (mPath.size() > 1 && isAlmostStraight(position, mPath[0], mPath[1], pointTolerance) && isValidShortcut(position, mPath[1])) mPath.pop_front(); } if ((updateFlags & UpdateFlag_RemoveLoops) != 0 && mPath.size() > 1) { std::size_t begin = 0; for (std::size_t i = 1; i < mPath.size(); ++i) { const float sqrDistance = Misc::getVectorToLine(position, mPath[i - 1], mPath[i]).length2(); if (sqrDistance < pointTolerance * pointTolerance && isValidShortcut(position, mPath[i])) begin = i; } for (std::size_t i = 0; i < begin; ++i) mPath.pop_front(); } if (mPath.size() == 1) { float distSqr; if ((updateFlags & UpdateFlag_CanMoveByZ) != 0) distSqr = (mPath.front() - position).length2(); else distSqr = sqrDistanceIgnoreZ(mPath.front(), position); if (distSqr < destinationTolerance * destinationTolerance) mPath.pop_front(); } } void PathFinder::buildStraightPath(const osg::Vec3f& endPoint) { mPath.clear(); mPath.push_back(endPoint); mConstructed = true; } void PathFinder::buildPathByPathgrid(const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const MWWorld::CellStore* cell, const PathgridGraph& pathgridGraph) { mPath.clear(); mCell = cell; buildPathByPathgridImpl(startPoint, endPoint, pathgridGraph, std::back_inserter(mPath)); mConstructed = !mPath.empty(); } void PathFinder::buildPathByNavMesh(const MWWorld::ConstPtr& actor, const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const DetourNavigator::AgentBounds& agentBounds, const DetourNavigator::Flags flags, const DetourNavigator::AreaCosts& areaCosts, float endTolerance, PathType pathType) { mPath.clear(); // If it's not possible to build path over navmesh due to disabled navmesh generation fallback to straight path DetourNavigator::Status status = buildPathByNavigatorImpl(actor, startPoint, endPoint, agentBounds, flags, areaCosts, endTolerance, pathType, std::back_inserter(mPath)); if (status != DetourNavigator::Status::Success) mPath.clear(); if (status == DetourNavigator::Status::NavMeshNotFound) mPath.push_back(endPoint); mConstructed = !mPath.empty(); } void PathFinder::buildPath(const MWWorld::ConstPtr& actor, const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const MWWorld::CellStore* cell, const PathgridGraph& pathgridGraph, const DetourNavigator::AgentBounds& agentBounds, const DetourNavigator::Flags flags, const DetourNavigator::AreaCosts& areaCosts, float endTolerance, PathType pathType) { mPath.clear(); mCell = cell; DetourNavigator::Status status = DetourNavigator::Status::NavMeshNotFound; if (!actor.getClass().isPureWaterCreature(actor) && !actor.getClass().isPureFlyingCreature(actor)) { status = buildPathByNavigatorImpl(actor, startPoint, endPoint, agentBounds, flags, areaCosts, endTolerance, pathType, std::back_inserter(mPath)); if (status != DetourNavigator::Status::Success) mPath.clear(); } if (status != DetourNavigator::Status::NavMeshNotFound && mPath.empty() && (flags & DetourNavigator::Flag_usePathgrid) == 0) { status = buildPathByNavigatorImpl(actor, startPoint, endPoint, agentBounds, flags | DetourNavigator::Flag_usePathgrid, areaCosts, endTolerance, pathType, std::back_inserter(mPath)); if (status != DetourNavigator::Status::Success) mPath.clear(); } if (mPath.empty()) buildPathByPathgridImpl(startPoint, endPoint, pathgridGraph, std::back_inserter(mPath)); if (status == DetourNavigator::Status::NavMeshNotFound && mPath.empty()) mPath.push_back(endPoint); mConstructed = !mPath.empty(); } DetourNavigator::Status PathFinder::buildPathByNavigatorImpl(const MWWorld::ConstPtr& actor, const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const DetourNavigator::AgentBounds& agentBounds, const DetourNavigator::Flags flags, const DetourNavigator::AreaCosts& areaCosts, float endTolerance, PathType pathType, std::back_insert_iterator<std::deque<osg::Vec3f>> out) { const auto world = MWBase::Environment::get().getWorld(); const auto navigator = world->getNavigator(); const auto status = DetourNavigator::findPath( *navigator, agentBounds, startPoint, endPoint, flags, areaCosts, endTolerance, out); if (pathType == PathType::Partial && status == DetourNavigator::Status::PartialPath) return DetourNavigator::Status::Success; if (status != DetourNavigator::Status::Success) { Log(Debug::Debug) << "Build path by navigator error: \"" << DetourNavigator::getMessage(status) << "\" for \"" << actor.getClass().getName(actor) << "\" (" << actor.getBase() << ") from " << startPoint << " to " << endPoint << " with flags (" << DetourNavigator::WriteFlags{ flags } << ")"; } return status; } void PathFinder::buildLimitedPath(const MWWorld::ConstPtr& actor, const osg::Vec3f& startPoint, const osg::Vec3f& endPoint, const MWWorld::CellStore* cell, const PathgridGraph& pathgridGraph, const DetourNavigator::AgentBounds& agentBounds, const DetourNavigator::Flags flags, const DetourNavigator::AreaCosts& areaCosts, float endTolerance, PathType pathType) { const auto navigator = MWBase::Environment::get().getWorld()->getNavigator(); const auto maxDistance = std::min(navigator->getMaxNavmeshAreaRealRadius(), static_cast<float>(Constants::CellSizeInUnits)); const auto startToEnd = endPoint - startPoint; const auto distance = startToEnd.length(); if (distance <= maxDistance) return buildPath(actor, startPoint, endPoint, cell, pathgridGraph, agentBounds, flags, areaCosts, endTolerance, pathType); const auto end = startPoint + startToEnd * maxDistance / distance; buildPath(actor, startPoint, end, cell, pathgridGraph, agentBounds, flags, areaCosts, endTolerance, pathType); } }
20,619
C++
.cpp
401
41.239401
120
0.621092
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,343
levelledlist.cpp
OpenMW_openmw/apps/openmw/mwmechanics/levelledlist.cpp
#include <components/debug/debuglog.hpp> #include <components/esm3/loadlevlist.hpp> #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/manualref.hpp" #include "../mwworld/ptr.hpp" #include "../mwbase/environment.hpp" #include "actorutil.hpp" #include "creaturestats.hpp" #include "levelledlist.hpp" namespace MWMechanics { ESM::RefId getLevelledItem( const ESM::LevelledListBase* levItem, bool creature, Misc::Rng::Generator& prng, std::optional<int> level) { const std::vector<ESM::LevelledListBase::LevelItem>& items = levItem->mList; int playerLevel; if (level.has_value()) playerLevel = *level; else { const MWWorld::Ptr& player = getPlayer(); playerLevel = player.getClass().getCreatureStats(player).getLevel(); level = playerLevel; } if (Misc::Rng::roll0to99(prng) < levItem->mChanceNone) return ESM::RefId(); std::vector<const ESM::RefId*> candidates; int highestLevel = 0; for (const auto& levelledItem : items) { if (levelledItem.mLevel > highestLevel && levelledItem.mLevel <= playerLevel) highestLevel = levelledItem.mLevel; } // For levelled creatures, the flags are swapped. This file format just makes so much sense. bool allLevels = (levItem->mFlags & ESM::ItemLevList::AllLevels) != 0; if (creature) allLevels = levItem->mFlags & ESM::CreatureLevList::AllLevels; for (const auto& levelledItem : items) { if (playerLevel >= levelledItem.mLevel && (allLevels || levelledItem.mLevel == highestLevel)) candidates.push_back(&levelledItem.mId); } if (candidates.empty()) return ESM::RefId(); const ESM::RefId& item = *candidates[Misc::Rng::rollDice(candidates.size(), prng)]; // Vanilla doesn't fail on nonexistent items in levelled lists if (!MWBase::Environment::get().getESMStore()->find(item)) { Log(Debug::Warning) << "Warning: ignoring nonexistent item " << item << " in levelled list " << levItem->mId; return ESM::RefId(); } // Is this another levelled item or a real item? MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), item, 1); if (ref.getPtr().getType() != ESM::ItemLevList::sRecordId && ref.getPtr().getType() != ESM::CreatureLevList::sRecordId) { return item; } else { if (ref.getPtr().getType() == ESM::ItemLevList::sRecordId) return getLevelledItem(ref.getPtr().get<ESM::ItemLevList>()->mBase, false, prng, level); else return getLevelledItem(ref.getPtr().get<ESM::CreatureLevList>()->mBase, true, prng, level); } } }
2,964
C++
.cpp
69
33.782609
114
0.610128
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,344
aicombataction.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aicombataction.cpp
#include "aicombataction.hpp" #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/actionequip.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "actorutil.hpp" #include "combat.hpp" #include "npcstats.hpp" #include "spellpriority.hpp" #include "spellutil.hpp" #include "weaponpriority.hpp" #include "weapontype.hpp" namespace MWMechanics { float suggestCombatRange(int rangeTypes) { static const float fCombatDistance = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fCombatDistance") ->mValue.getFloat(); static float fHandToHandReach = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fHandToHandReach") ->mValue.getFloat(); // This distance is a possible distance of melee attack static float distance = fCombatDistance * std::max(2.f, fHandToHandReach); if (rangeTypes & RangeTypes::Touch) { return fCombatDistance; } return distance * 4; } void ActionSpell::prepare(const MWWorld::Ptr& actor) { actor.getClass().getCreatureStats(actor).getSpells().setSelectedSpell(mSpellId); actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Spell); if (actor.getClass().hasInventoryStore(actor)) { MWWorld::InventoryStore& inv = actor.getClass().getInventoryStore(actor); inv.setSelectedEnchantItem(inv.end()); } const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(mSpellId); MWBase::Environment::get().getWorld()->preloadEffects(&spell->mEffects); } float ActionSpell::getCombatRange(bool& isRanged) const { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(mSpellId); int types = getRangeTypes(spell->mEffects); isRanged = (types & RangeTypes::Target) | (types & RangeTypes::Self); return suggestCombatRange(types); } void ActionEnchantedItem::prepare(const MWWorld::Ptr& actor) { actor.getClass().getCreatureStats(actor).getSpells().setSelectedSpell(ESM::RefId()); actor.getClass().getInventoryStore(actor).setSelectedEnchantItem(mItem); actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Spell); } float ActionEnchantedItem::getCombatRange(bool& isRanged) const { const ESM::Enchantment* enchantment = MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().find( mItem->getClass().getEnchantment(*mItem)); int types = getRangeTypes(enchantment->mEffects); isRanged = (types & RangeTypes::Target) | (types & RangeTypes::Self); return suggestCombatRange(types); } float ActionPotion::getCombatRange(bool& isRanged) const { // Distance doesn't matter since this action has no animation // If we want to back away slightly to avoid enemy hits, we should set isRanged to "true" return 600.f; } void ActionPotion::prepare(const MWWorld::Ptr& actor) { actor.getClass().consume(mPotion, actor); } void ActionWeapon::prepare(const MWWorld::Ptr& actor) { if (actor.getClass().hasInventoryStore(actor)) { if (mWeapon.isEmpty()) actor.getClass().getInventoryStore(actor).unequipSlot(MWWorld::InventoryStore::Slot_CarriedRight); else { MWWorld::ActionEquip equip(mWeapon); equip.execute(actor); } if (!mAmmunition.isEmpty()) { MWWorld::ActionEquip equip(mAmmunition); equip.execute(actor); } } actor.getClass().getCreatureStats(actor).setDrawState(DrawState::Weapon); } float ActionWeapon::getCombatRange(bool& isRanged) const { isRanged = false; static const float fCombatDistance = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fCombatDistance") ->mValue.getFloat(); static const float fProjectileMaxSpeed = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fProjectileMaxSpeed") ->mValue.getFloat(); if (mWeapon.isEmpty()) { static float fHandToHandReach = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fHandToHandReach") ->mValue.getFloat(); return fHandToHandReach * fCombatDistance; } const ESM::Weapon* weapon = mWeapon.get<ESM::Weapon>()->mBase; if (MWMechanics::getWeaponType(weapon->mData.mType)->mWeaponClass != ESM::WeaponType::Melee) { isRanged = true; return fProjectileMaxSpeed; } else return weapon->mData.mReach * fCombatDistance; } const ESM::Weapon* ActionWeapon::getWeapon() const { if (mWeapon.isEmpty()) return nullptr; return mWeapon.get<ESM::Weapon>()->mBase; } std::unique_ptr<Action> prepareNextAction(const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { Spells& spells = actor.getClass().getCreatureStats(actor).getSpells(); float bestActionRating = 0.f; float antiFleeRating = 0.f; // Default to hand-to-hand combat std::unique_ptr<Action> bestAction = std::make_unique<ActionWeapon>(MWWorld::Ptr()); if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf()) { bestAction->prepare(actor); return bestAction; } const bool hasInventoryStore = actor.getClass().hasInventoryStore(actor); MWWorld::ContainerStore& store = actor.getClass().getContainerStore(actor); for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it) { if (it->getType() == ESM::Potion::sRecordId) { float rating = ratePotion(*it, actor); if (rating > bestActionRating) { bestActionRating = rating; bestAction = std::make_unique<ActionPotion>(*it); antiFleeRating = std::numeric_limits<float>::max(); } } // TODO remove inventory store check, creatures should be able to use enchanted items they cannot equip else if (hasInventoryStore && !it->getClass().getEnchantment(*it).empty()) { float rating = rateMagicItem(*it, actor, enemy); if (rating > bestActionRating) { bestActionRating = rating; bestAction = std::make_unique<ActionEnchantedItem>(it); antiFleeRating = std::numeric_limits<float>::max(); } } } if (hasInventoryStore) { MWWorld::Ptr bestArrow; float bestArrowRating = rateAmmo(actor, enemy, bestArrow, ESM::Weapon::Arrow); MWWorld::Ptr bestBolt; float bestBoltRating = rateAmmo(actor, enemy, bestBolt, ESM::Weapon::Bolt); for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it) { float rating = rateWeapon(*it, actor, enemy, -1, bestArrowRating, bestBoltRating); if (rating > bestActionRating) { const ESM::Weapon* weapon = it->get<ESM::Weapon>()->mBase; int ammotype = getWeaponType(weapon->mData.mType)->mAmmoType; MWWorld::Ptr ammo; if (ammotype == ESM::Weapon::Arrow) ammo = bestArrow; else if (ammotype == ESM::Weapon::Bolt) ammo = bestBolt; bestActionRating = rating; bestAction = std::make_unique<ActionWeapon>(*it, ammo); antiFleeRating = vanillaRateWeaponAndAmmo(*it, ammo, actor, enemy); } } } for (const ESM::Spell* spell : spells) { float rating = rateSpell(spell, actor, enemy); if (rating > bestActionRating) { bestActionRating = rating; bestAction = std::make_unique<ActionSpell>(spell->mId); antiFleeRating = vanillaRateSpell(spell, actor, enemy); } } if (makeFleeDecision(actor, enemy, antiFleeRating)) bestAction = std::make_unique<ActionFlee>(); if (bestAction.get()) bestAction->prepare(actor); return bestAction; } float getBestActionRating(const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { Spells& spells = actor.getClass().getCreatureStats(actor).getSpells(); float bestActionRating = 0.f; // Default to hand-to-hand combat if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf()) { return bestActionRating; } if (actor.getClass().hasInventoryStore(actor)) { MWWorld::InventoryStore& store = actor.getClass().getInventoryStore(actor); for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it) { float rating = rateMagicItem(*it, actor, enemy); if (rating > bestActionRating) { bestActionRating = rating; } } float bestArrowRating = rateAmmo(actor, enemy, ESM::Weapon::Arrow); float bestBoltRating = rateAmmo(actor, enemy, ESM::Weapon::Bolt); for (MWWorld::ContainerStoreIterator it = store.begin(); it != store.end(); ++it) { float rating = rateWeapon(*it, actor, enemy, -1, bestArrowRating, bestBoltRating); if (rating > bestActionRating) { bestActionRating = rating; } } } for (const ESM::Spell* spell : spells) { float rating = rateSpell(spell, actor, enemy); if (rating > bestActionRating) { bestActionRating = rating; } } return bestActionRating; } float getDistanceMinusHalfExtents(const MWWorld::Ptr& actor1, const MWWorld::Ptr& actor2, bool minusZDist) { osg::Vec3f actor1Pos = actor1.getRefData().getPosition().asVec3(); osg::Vec3f actor2Pos = actor2.getRefData().getPosition().asVec3(); float dist = (actor1Pos - actor2Pos).length(); if (minusZDist) dist -= std::abs(actor1Pos.z() - actor2Pos.z()); return (dist - MWBase::Environment::get().getWorld()->getHalfExtents(actor1).y() - MWBase::Environment::get().getWorld()->getHalfExtents(actor2).y()); } float getMaxAttackDistance(const MWWorld::Ptr& actor) { const CreatureStats& stats = actor.getClass().getCreatureStats(actor); const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); const ESM::RefId& selectedSpellId = stats.getSpells().getSelectedSpell(); MWWorld::Ptr selectedEnchItem; MWWorld::Ptr activeWeapon, activeAmmo; if (actor.getClass().hasInventoryStore(actor)) { MWWorld::InventoryStore& invStore = actor.getClass().getInventoryStore(actor); MWWorld::ContainerStoreIterator item = invStore.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (item != invStore.end() && item.getType() == MWWorld::ContainerStore::Type_Weapon) activeWeapon = *item; item = invStore.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (item != invStore.end() && item.getType() == MWWorld::ContainerStore::Type_Weapon) activeAmmo = *item; if (invStore.getSelectedEnchantItem() != invStore.end()) selectedEnchItem = *invStore.getSelectedEnchantItem(); } float dist = 1.0f; if (activeWeapon.isEmpty() && !selectedSpellId.empty() && !selectedEnchItem.isEmpty()) { static const float fHandToHandReach = gmst.find("fHandToHandReach")->mValue.getFloat(); dist = fHandToHandReach; } else if (stats.getDrawState() == MWMechanics::DrawState::Spell) { dist = 1.0f; if (!selectedSpellId.empty()) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(selectedSpellId); for (std::vector<ESM::IndexedENAMstruct>::const_iterator effectIt = spell->mEffects.mList.begin(); effectIt != spell->mEffects.mList.end(); ++effectIt) { if (effectIt->mData.mRange == ESM::RT_Target) { const ESM::MagicEffect* effect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find( effectIt->mData.mEffectID); dist = effect->mData.mSpeed; break; } } } else if (!selectedEnchItem.isEmpty()) { const ESM::RefId& enchId = selectedEnchItem.getClass().getEnchantment(selectedEnchItem); if (!enchId.empty()) { const ESM::Enchantment* ench = MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().find(enchId); for (std::vector<ESM::IndexedENAMstruct>::const_iterator effectIt = ench->mEffects.mList.begin(); effectIt != ench->mEffects.mList.end(); ++effectIt) { if (effectIt->mData.mRange == ESM::RT_Target) { const ESM::MagicEffect* effect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find( effectIt->mData.mEffectID); dist = effect->mData.mSpeed; break; } } } } static const float fTargetSpellMaxSpeed = gmst.find("fTargetSpellMaxSpeed")->mValue.getFloat(); dist *= std::max(1000.0f, fTargetSpellMaxSpeed); } else if (!activeWeapon.isEmpty()) { const ESM::Weapon* esmWeap = activeWeapon.get<ESM::Weapon>()->mBase; if (MWMechanics::getWeaponType(esmWeap->mData.mType)->mWeaponClass != ESM::WeaponType::Melee) { static const float fTargetSpellMaxSpeed = gmst.find("fProjectileMaxSpeed")->mValue.getFloat(); dist = fTargetSpellMaxSpeed; if (!activeAmmo.isEmpty()) { const ESM::Weapon* esmAmmo = activeAmmo.get<ESM::Weapon>()->mBase; dist *= esmAmmo->mData.mSpeed; } } else if (esmWeap->mData.mReach > 1) { dist = esmWeap->mData.mReach; } } dist = (dist > 0.f) ? dist : 1.0f; static const float fCombatDistance = gmst.find("fCombatDistance")->mValue.getFloat(); static const float fCombatDistanceWerewolfMod = gmst.find("fCombatDistanceWerewolfMod")->mValue.getFloat(); float combatDistance = fCombatDistance; if (actor.getClass().isNpc() && actor.getClass().getNpcStats(actor).isWerewolf()) combatDistance *= (fCombatDistanceWerewolfMod + 1.0f); if (dist < combatDistance) dist *= combatDistance; return dist; } bool canFight(const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { ESM::Position actorPos = actor.getRefData().getPosition(); ESM::Position enemyPos = enemy.getRefData().getPosition(); if (isTargetMagicallyHidden(enemy) && !MWBase::Environment::get().getMechanicsManager()->awarenessCheck(enemy, actor)) { return false; } if (actor.getClass().isPureWaterCreature(actor)) { if (!MWBase::Environment::get().getWorld()->isWading(enemy)) return false; } float atDist = getMaxAttackDistance(actor); if (atDist > getDistanceMinusHalfExtents(actor, enemy) && atDist > std::abs(actorPos.pos[2] - enemyPos.pos[2])) { if (MWBase::Environment::get().getWorld()->getLOS(actor, enemy)) return true; } if (actor.getClass().isPureLandCreature(actor) && MWBase::Environment::get().getWorld()->isWalkingOnWater(enemy)) { return false; } if (actor.getClass().isPureFlyingCreature(actor) || actor.getClass().isPureLandCreature(actor)) { if (MWBase::Environment::get().getWorld()->isSwimming(enemy)) return false; } if (actor.getClass().isBipedal(actor) || !actor.getClass().canFly(actor)) { if (enemy.getClass() .getCreatureStats(enemy) .getMagicEffects() .getOrDefault(ESM::MagicEffect::Levitate) .getMagnitude() > 0) { float attackDistance = getMaxAttackDistance(actor); if ((attackDistance + actorPos.pos[2]) < enemyPos.pos[2]) { if (enemy.getCell()->isExterior()) { if (attackDistance < (enemyPos.pos[2] - MWBase::Environment::get().getWorld()->getTerrainHeightAt( enemyPos.asVec3(), enemy.getCell()->getCell()->getWorldSpace()))) return false; } } } } if (!actor.getClass().canWalk(actor) && !actor.getClass().isBipedal(actor)) return true; if (actor.getClass() .getCreatureStats(actor) .getMagicEffects() .getOrDefault(ESM::MagicEffect::Levitate) .getMagnitude() > 0) return true; if (MWBase::Environment::get().getWorld()->isSwimming(actor)) return true; if (getDistanceMinusHalfExtents(actor, enemy, true) <= 0.0f) return false; return true; } float vanillaRateFlee(const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { const CreatureStats& stats = actor.getClass().getCreatureStats(actor); const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); const int flee = stats.getAiSetting(AiSetting::Flee).getModified(); if (flee >= 100) return flee; static const float fAIFleeHealthMult = gmst.find("fAIFleeHealthMult")->mValue.getFloat(); static const float fAIFleeFleeMult = gmst.find("fAIFleeFleeMult")->mValue.getFloat(); float healthPercentage = stats.getHealth().getRatio(false); float rating = (1.0f - healthPercentage) * fAIFleeHealthMult + flee * fAIFleeFleeMult; static const int iWereWolfLevelToAttack = gmst.find("iWereWolfLevelToAttack")->mValue.getInteger(); if (actor.getClass().isNpc() && enemy.getClass().isNpc()) { if (enemy.getClass().getNpcStats(enemy).isWerewolf() && stats.getLevel() < iWereWolfLevelToAttack) { static const int iWereWolfFleeMod = gmst.find("iWereWolfFleeMod")->mValue.getInteger(); rating = iWereWolfFleeMod; } } if (rating != 0.0f) rating += getFightDistanceBias(actor, enemy); return rating; } bool makeFleeDecision(const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy, float antiFleeRating) { float fleeRating = vanillaRateFlee(actor, enemy); if (fleeRating < 100.0f) fleeRating = 0.0f; if (fleeRating > antiFleeRating) return true; // Run away after summoning a creature if we have nothing to use but fists. if (antiFleeRating == 0.0f && !actor.getClass().getCreatureStats(actor).getSummonedCreatureMap().empty()) return true; return false; } }
21,995
C++
.cpp
471
32.934183
119
0.557841
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,345
spellpriority.cpp
OpenMW_openmw/apps/openmw/mwmechanics/spellpriority.cpp
#include "spellpriority.hpp" #include "weaponpriority.hpp" #include <cmath> #include <components/esm3/loadench.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadrace.hpp> #include <components/esm3/loadspel.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "creaturestats.hpp" #include "spellresistance.hpp" #include "spellutil.hpp" #include "summoning.hpp" #include "weapontype.hpp" namespace { int numEffectsToDispel(const MWWorld::Ptr& actor, int effectFilter = -1, bool negative = true) { int toCure = 0; const MWMechanics::ActiveSpells& activeSpells = actor.getClass().getCreatureStats(actor).getActiveSpells(); for (MWMechanics::ActiveSpells::TIterator it = activeSpells.begin(); it != activeSpells.end(); ++it) { // if the effect filter is not specified, take in account only spells effects. Leave potions, enchanted // items etc. if (effectFilter == -1) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().search(it->getSourceSpellId()); if (!spell || spell->mData.mType != ESM::Spell::ST_Spell) continue; } const MWMechanics::ActiveSpells::ActiveSpellParams& params = *it; for (const auto& effect : params.getEffects()) { int effectId = effect.mEffectId; if (effectFilter != -1 && effectId != effectFilter) continue; const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effectId); if (effect.mDuration <= 3) // Don't attempt to dispel if effect runs out shortly anyway continue; if (negative && magicEffect->mData.mFlags & ESM::MagicEffect::Harmful) ++toCure; if (!negative && !(magicEffect->mData.mFlags & ESM::MagicEffect::Harmful)) ++toCure; } } return toCure; } float getSpellDuration(const MWWorld::Ptr& actor, const ESM::RefId& spellId) { float duration = 0; const MWMechanics::ActiveSpells& activeSpells = actor.getClass().getCreatureStats(actor).getActiveSpells(); for (MWMechanics::ActiveSpells::TIterator it = activeSpells.begin(); it != activeSpells.end(); ++it) { if (it->getSourceSpellId() != spellId) continue; const MWMechanics::ActiveSpells::ActiveSpellParams& params = *it; for (const auto& effect : params.getEffects()) { if (effect.mDuration > duration) duration = effect.mDuration; } } return duration; } bool isSpellActive(const MWWorld::Ptr& caster, const MWWorld::Ptr& target, const ESM::RefId& id) { int actorId = caster.getClass().getCreatureStats(caster).getActorId(); const auto& active = target.getClass().getCreatureStats(target).getActiveSpells(); return std::find_if(active.begin(), active.end(), [&](const auto& spell) { return spell.getCasterActorId() == actorId && spell.getSourceSpellId() == id; }) != active.end(); } float getRestoreMagickaPriority(const MWWorld::Ptr& actor) { const MWMechanics::CreatureStats& stats = actor.getClass().getCreatureStats(actor); const MWMechanics::DynamicStat<float>& current = stats.getMagicka(); for (const ESM::Spell* spell : stats.getSpells()) { if (spell->mData.mType != ESM::Spell::ST_Spell) continue; int cost = MWMechanics::calcSpellCost(*spell); if (cost > current.getCurrent() && cost < current.getModified()) return 2.f; } return 0.f; } } namespace MWMechanics { int getRangeTypes(const ESM::EffectList& effects) { int types = 0; for (const ESM::IndexedENAMstruct& effect : effects.mList) { if (effect.mData.mRange == ESM::RT_Self) types |= RangeTypes::Self; else if (effect.mData.mRange == ESM::RT_Touch) types |= RangeTypes::Touch; else if (effect.mData.mRange == ESM::RT_Target) types |= RangeTypes::Target; } return types; } float ratePotion(const MWWorld::Ptr& item, const MWWorld::Ptr& actor) { if (item.getType() != ESM::Potion::sRecordId) return 0.f; const ESM::Potion* potion = item.get<ESM::Potion>()->mBase; return rateEffects(potion->mEffects, actor, MWWorld::Ptr()); } float rateSpell(const ESM::Spell* spell, const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy, bool checkMagicka) { float successChance = MWMechanics::getSpellSuccessChance(spell, actor, nullptr, true, checkMagicka); if (successChance == 0.f) return 0.f; if (spell->mData.mType != ESM::Spell::ST_Spell) return 0.f; // Don't make use of racial bonus spells, like MW. Can be made optional later if (actor.getClass().isNpc()) { const ESM::RefId& raceid = actor.get<ESM::NPC>()->mBase->mRace; const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(raceid); if (race->mPowers.exists(spell->mId)) return 0.f; } // Spells don't stack, so early out if the spell is still active on the target int types = getRangeTypes(spell->mEffects); if ((types & Self) && isSpellActive(actor, actor, spell->mId)) return 0.f; if (((types & Touch) || (types & Target)) && !enemy.isEmpty() && isSpellActive(actor, enemy, spell->mId)) return 0.f; return rateEffects(spell->mEffects, actor, enemy) * (successChance / 100.f); } float rateMagicItem(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { if (ptr.getClass().getEnchantment(ptr).empty()) return 0.f; const ESM::Enchantment* enchantment = MWBase::Environment::get().getESMStore()->get<ESM::Enchantment>().find( ptr.getClass().getEnchantment(ptr)); // Spells don't stack, so early out if the spell is still active on the target int types = getRangeTypes(enchantment->mEffects); if ((types & Self) && actor.getClass().getCreatureStats(actor).getActiveSpells().isSpellActive(ptr.getCellRef().getRefId())) return 0.f; if (types & (Touch | Target) && getSpellDuration(enemy, ptr.getCellRef().getRefId()) > 3) return 0.f; if (enchantment->mData.mType == ESM::Enchantment::CastOnce) { return rateEffects(enchantment->mEffects, actor, enemy); } else if (enchantment->mData.mType == ESM::Enchantment::WhenUsed) { MWWorld::InventoryStore& store = actor.getClass().getInventoryStore(actor); // Creatures can not wear armor/clothing, so allow creatures to use non-equipped items, if (actor.getClass().isNpc() && !store.isEquipped(ptr)) return 0.f; int castCost = getEffectiveEnchantmentCastCost(*enchantment, actor); if (ptr.getCellRef().getEnchantmentCharge() != -1 && ptr.getCellRef().getEnchantmentCharge() < castCost) return 0.f; float rating = rateEffects(enchantment->mEffects, actor, enemy); rating *= 1.25f; // prefer rechargeable magic items over spells return rating; } return 0.f; } float rateEffect(const ESM::ENAMstruct& effect, const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { // NOTE: enemy may be empty float rating = 1; switch (effect.mEffectID) { case ESM::MagicEffect::Soultrap: case ESM::MagicEffect::AlmsiviIntervention: case ESM::MagicEffect::DivineIntervention: case ESM::MagicEffect::CalmHumanoid: case ESM::MagicEffect::CalmCreature: case ESM::MagicEffect::FrenzyHumanoid: case ESM::MagicEffect::FrenzyCreature: case ESM::MagicEffect::DemoralizeHumanoid: case ESM::MagicEffect::DemoralizeCreature: case ESM::MagicEffect::RallyHumanoid: case ESM::MagicEffect::RallyCreature: case ESM::MagicEffect::Charm: case ESM::MagicEffect::DetectAnimal: case ESM::MagicEffect::DetectEnchantment: case ESM::MagicEffect::DetectKey: case ESM::MagicEffect::Telekinesis: case ESM::MagicEffect::Mark: case ESM::MagicEffect::Recall: case ESM::MagicEffect::Jump: case ESM::MagicEffect::WaterBreathing: case ESM::MagicEffect::SwiftSwim: case ESM::MagicEffect::WaterWalking: case ESM::MagicEffect::SlowFall: case ESM::MagicEffect::Light: case ESM::MagicEffect::Lock: case ESM::MagicEffect::Open: case ESM::MagicEffect::TurnUndead: case ESM::MagicEffect::WeaknessToCommonDisease: case ESM::MagicEffect::WeaknessToBlightDisease: case ESM::MagicEffect::WeaknessToCorprusDisease: case ESM::MagicEffect::CureCommonDisease: case ESM::MagicEffect::CureBlightDisease: case ESM::MagicEffect::CureCorprusDisease: case ESM::MagicEffect::ResistBlightDisease: case ESM::MagicEffect::ResistCommonDisease: case ESM::MagicEffect::ResistCorprusDisease: case ESM::MagicEffect::Invisibility: case ESM::MagicEffect::Chameleon: case ESM::MagicEffect::NightEye: case ESM::MagicEffect::Vampirism: case ESM::MagicEffect::StuntedMagicka: case ESM::MagicEffect::ExtraSpell: case ESM::MagicEffect::RemoveCurse: case ESM::MagicEffect::CommandCreature: case ESM::MagicEffect::CommandHumanoid: return 0.f; case ESM::MagicEffect::Blind: { if (enemy.isEmpty()) return 0.f; const CreatureStats& stats = enemy.getClass().getCreatureStats(enemy); // Enemy can't attack if (stats.isParalyzed() || stats.getKnockedDown()) return 0.f; // Enemy doesn't attack if (stats.getDrawState() != MWMechanics::DrawState::Weapon) return 0.f; break; } case ESM::MagicEffect::Sound: { if (enemy.isEmpty()) return 0.f; const CreatureStats& stats = enemy.getClass().getCreatureStats(enemy); // Enemy can't cast spells if (stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Silence).getMagnitude() > 0) return 0.f; if (stats.isParalyzed() || stats.getKnockedDown()) return 0.f; // Enemy doesn't cast spells if (stats.getDrawState() != MWMechanics::DrawState::Spell) return 0.f; break; } case ESM::MagicEffect::Silence: { if (enemy.isEmpty()) return 0.f; const CreatureStats& stats = enemy.getClass().getCreatureStats(enemy); // Enemy can't cast spells if (stats.isParalyzed() || stats.getKnockedDown()) return 0.f; // Enemy doesn't cast spells if (stats.getDrawState() != MWMechanics::DrawState::Spell) return 0.f; break; } case ESM::MagicEffect::RestoreAttribute: return 0.f; // TODO: implement based on attribute damage case ESM::MagicEffect::RestoreSkill: return 0.f; // TODO: implement based on skill damage case ESM::MagicEffect::ResistFire: case ESM::MagicEffect::ResistFrost: case ESM::MagicEffect::ResistMagicka: case ESM::MagicEffect::ResistNormalWeapons: case ESM::MagicEffect::ResistParalysis: case ESM::MagicEffect::ResistPoison: case ESM::MagicEffect::ResistShock: case ESM::MagicEffect::SpellAbsorption: case ESM::MagicEffect::Reflect: return 0.f; // probably useless since we don't know in advance what the enemy will cast // don't cast these for now as they would make the NPC cast the same effect over and over again, especially // when they have potions case ESM::MagicEffect::FortifyAttribute: case ESM::MagicEffect::FortifyHealth: case ESM::MagicEffect::FortifyMagicka: case ESM::MagicEffect::FortifyFatigue: case ESM::MagicEffect::FortifySkill: case ESM::MagicEffect::FortifyMaximumMagicka: case ESM::MagicEffect::FortifyAttack: return 0.f; case ESM::MagicEffect::Burden: { if (enemy.isEmpty()) return 0.f; // Ignore enemy without inventory if (!enemy.getClass().hasInventoryStore(enemy)) return 0.f; // burden makes sense only to overburden an enemy float burden = enemy.getClass().getEncumbrance(enemy) - enemy.getClass().getCapacity(enemy); if (burden > 0) return 0.f; if ((effect.mMagnMin + effect.mMagnMax) / 2.f > -burden) rating *= 3; else return 0.f; break; } case ESM::MagicEffect::Feather: { // Ignore actors without inventory if (!actor.getClass().hasInventoryStore(actor)) return 0.f; // feather makes sense only for overburden actors float burden = actor.getClass().getEncumbrance(actor) - actor.getClass().getCapacity(actor); if (burden <= 0) return 0.f; if ((effect.mMagnMin + effect.mMagnMax) / 2.f >= burden) rating *= 3; else return 0.f; break; } case ESM::MagicEffect::Levitate: return 0.f; // AI isn't designed to take advantage of this, and could be perceived as unfair anyway case ESM::MagicEffect::BoundBoots: case ESM::MagicEffect::BoundHelm: if (actor.getClass().isNpc()) { // Beast races can't wear helmets or boots const ESM::RefId& raceid = actor.get<ESM::NPC>()->mBase->mRace; const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(raceid); if (race->mData.mFlags & ESM::Race::Beast) return 0.f; } else return 0.f; break; case ESM::MagicEffect::BoundShield: if (!actor.getClass().hasInventoryStore(actor)) return 0.f; else if (!actor.getClass().isNpc()) { // If the actor is an NPC they can benefit from the armor rating, otherwise check if we've got a // one-handed weapon to use with the shield const auto& store = actor.getClass().getInventoryStore(actor); auto oneHanded = std::find_if(store.cbegin(MWWorld::ContainerStore::Type_Weapon), store.cend(), [](const MWWorld::ConstPtr& weapon) { if (weapon.getClass().getItemHealth(weapon) <= 0.f) return false; short type = weapon.get<ESM::Weapon>()->mBase->mData.mType; return !(MWMechanics::getWeaponType(type)->mFlags & ESM::WeaponType::TwoHanded); }); if (oneHanded == store.cend()) return 0.f; } break; // Creatures can not wear armor case ESM::MagicEffect::BoundCuirass: case ESM::MagicEffect::BoundGloves: if (!actor.getClass().isNpc()) return 0.f; break; case ESM::MagicEffect::AbsorbMagicka: if (!enemy.isEmpty() && enemy.getClass().getCreatureStats(enemy).getMagicka().getCurrent() <= 0.f) { rating = 0.5f; rating *= getRestoreMagickaPriority(actor); } break; case ESM::MagicEffect::RestoreHealth: case ESM::MagicEffect::RestoreMagicka: case ESM::MagicEffect::RestoreFatigue: if (effect.mRange == ESM::RT_Self) { const MWMechanics::CreatureStats& stats = actor.getClass().getCreatureStats(actor); const DynamicStat<float>& current = stats.getDynamic(effect.mEffectID - ESM::MagicEffect::RestoreHealth); // NB: this currently assumes the hardcoded magic effect flags are used const float magnitude = (effect.mMagnMin + effect.mMagnMax) / 2.f; const float toHeal = magnitude * std::max(1, effect.mDuration); const float damage = std::max(current.getModified() - current.getCurrent(), 0.f); float priority = 0.f; if (effect.mEffectID == ESM::MagicEffect::RestoreHealth) priority = 4.f; else if (effect.mEffectID == ESM::MagicEffect::RestoreMagicka) priority = getRestoreMagickaPriority(actor); else if (effect.mEffectID == ESM::MagicEffect::RestoreFatigue) priority = 2.f; float overheal = 0.f; float heal = toHeal; if (damage < toHeal && current.getCurrent() > current.getModified() * 0.5) { overheal = toHeal - damage; heal = damage; } priority = (priority - 1.f) / 2.f * std::pow((damage / current.getModified() + 0.6f), priority * 2) + priority * (heal - 2.f * overheal) / current.getModified() - 0.5f; rating = priority; } break; case ESM::MagicEffect::Dispel: { int numPositive = 0; int numNegative = 0; int diff = 0; if (effect.mRange == ESM::RT_Self) { numPositive = numEffectsToDispel(actor, -1, false); numNegative = numEffectsToDispel(actor); diff = numNegative - numPositive; } else { if (enemy.isEmpty()) return 0.f; numPositive = numEffectsToDispel(enemy, -1, false); numNegative = numEffectsToDispel(enemy); diff = numPositive - numNegative; // if rating < 0 here, the spell will be considered as negative later rating *= -1; } if (diff <= 0) return 0.f; rating *= (diff) / 5.f; break; } // Prefer Cure effects over Dispel, because Dispel also removes positive effects case ESM::MagicEffect::CureParalyzation: return 1001.f * numEffectsToDispel(actor, ESM::MagicEffect::Paralyze); case ESM::MagicEffect::CurePoison: return 1001.f * numEffectsToDispel(actor, ESM::MagicEffect::Poison); case ESM::MagicEffect::DisintegrateArmor: { if (enemy.isEmpty()) return 0.f; // Ignore enemy without inventory if (!enemy.getClass().hasInventoryStore(enemy)) return 0.f; MWWorld::InventoryStore& inv = enemy.getClass().getInventoryStore(enemy); // According to UESP static const int armorSlots[] = { MWWorld::InventoryStore::Slot_CarriedLeft, MWWorld::InventoryStore::Slot_Cuirass, MWWorld::InventoryStore::Slot_LeftPauldron, MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet, MWWorld::InventoryStore::Slot_Helmet, MWWorld::InventoryStore::Slot_Greaves, MWWorld::InventoryStore::Slot_Boots, }; bool enemyHasArmor = false; // Ignore enemy without armor for (unsigned int i = 0; i < sizeof(armorSlots) / sizeof(int); ++i) { MWWorld::ContainerStoreIterator item = inv.getSlot(armorSlots[i]); if (item != inv.end() && (item.getType() == MWWorld::ContainerStore::Type_Armor)) { enemyHasArmor = true; break; } } if (!enemyHasArmor) return 0.f; break; } case ESM::MagicEffect::DisintegrateWeapon: { if (enemy.isEmpty()) return 0.f; // Ignore enemy without inventory if (!enemy.getClass().hasInventoryStore(enemy)) return 0.f; MWWorld::InventoryStore& inv = enemy.getClass().getInventoryStore(enemy); MWWorld::ContainerStoreIterator item = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); // Ignore enemy without weapons if (item == inv.end() || (item.getType() != MWWorld::ContainerStore::Type_Weapon)) return 0.f; break; } case ESM::MagicEffect::AbsorbAttribute: case ESM::MagicEffect::DamageAttribute: case ESM::MagicEffect::DrainAttribute: if (!enemy.isEmpty() && enemy.getClass() .getCreatureStats(enemy) .getAttribute(ESM::Attribute::indexToRefId(effect.mAttribute)) .getModified() <= 0) return 0.f; { if (effect.mAttribute >= 0 && effect.mAttribute < ESM::Attribute::Length) { const float attributePriorities[ESM::Attribute::Length] = { 1.0f, // Strength 0.5f, // Intelligence 0.6f, // Willpower 0.7f, // Agility 0.5f, // Speed 0.8f, // Endurance 0.7f, // Personality 0.3f // Luck }; rating *= attributePriorities[effect.mAttribute]; } } break; case ESM::MagicEffect::AbsorbSkill: case ESM::MagicEffect::DamageSkill: case ESM::MagicEffect::DrainSkill: if (enemy.isEmpty() || !enemy.getClass().isNpc()) return 0.f; if (enemy.getClass().getSkill(enemy, ESM::Skill::indexToRefId(effect.mSkill)) <= 0) return 0.f; break; default: break; } // Allow only one summoned creature at time if (isSummoningEffect(effect.mEffectID)) { MWMechanics::CreatureStats& creatureStats = actor.getClass().getCreatureStats(actor); if (!creatureStats.getSummonedCreatureMap().empty()) return 0.f; // But rate summons higher than other effects rating = 3.f; } if (effect.mEffectID >= ESM::MagicEffect::BoundDagger && effect.mEffectID <= ESM::MagicEffect::BoundGloves) { // Prefer casting bound items over other spells rating = 2.f; // While rateSpell prevents actors from recasting the same spell, it doesn't prevent them from casting // different spells with the same effect. Multiple instances of the same bound item don't stack so if the // effect is already active, rate it as useless. Likewise, if the actor already has a bound weapon, don't // summon another of a different kind unless what we have is a bow and the actor is out of ammo. // FIXME: This code assumes the summoned item is of the usual type (i.e. a mod hasn't changed Bound Bow to // summon an Axe instead) if (effect.mEffectID <= ESM::MagicEffect::BoundLongbow) { for (int e = ESM::MagicEffect::BoundDagger; e <= ESM::MagicEffect::BoundLongbow; ++e) if (actor.getClass().getCreatureStats(actor).getMagicEffects().getOrDefault(e).getMagnitude() > 0.f && (e != ESM::MagicEffect::BoundLongbow || effect.mEffectID == e || rateAmmo(actor, enemy, getWeaponType(ESM::Weapon::MarksmanBow)->mAmmoType) <= 0.f)) return 0.f; ESM::RefId skill = ESM::Skill::ShortBlade; if (effect.mEffectID == ESM::MagicEffect::BoundLongsword) skill = ESM::Skill::LongBlade; else if (effect.mEffectID == ESM::MagicEffect::BoundMace) skill = ESM::Skill::BluntWeapon; else if (effect.mEffectID == ESM::MagicEffect::BoundBattleAxe) skill = ESM::Skill::Axe; else if (effect.mEffectID == ESM::MagicEffect::BoundSpear) skill = ESM::Skill::Spear; else if (effect.mEffectID == ESM::MagicEffect::BoundLongbow) { // AI should not summon the bow if there is no suitable ammo. if (rateAmmo(actor, enemy, getWeaponType(ESM::Weapon::MarksmanBow)->mAmmoType) <= 0.f) return 0.f; skill = ESM::Skill::Marksman; } // Prefer summoning items we know how to use rating *= (50.f + actor.getClass().getSkill(actor, skill)) / 100.f; } else if (actor.getClass() .getCreatureStats(actor) .getMagicEffects() .getOrDefault(effect.mEffectID) .getMagnitude() > 0.f) return 0.f; } // Underwater casting not possible if (effect.mRange == ESM::RT_Target) { if (MWBase::Environment::get().getWorld()->isUnderwater(MWWorld::ConstPtr(actor), 0.75f)) return 0.f; if (enemy.isEmpty()) return 0.f; if (MWBase::Environment::get().getWorld()->isUnderwater(MWWorld::ConstPtr(enemy), 0.75f)) return 0.f; } const ESM::MagicEffect* magicEffect = MWBase::Environment::get().getESMStore()->get<ESM::MagicEffect>().find(effect.mEffectID); if (magicEffect->mData.mFlags & ESM::MagicEffect::Harmful) { rating *= -1.f; if (enemy.isEmpty()) return 0.f; // Check resistance for harmful effects CreatureStats& stats = enemy.getClass().getCreatureStats(enemy); float resistance = MWMechanics::getEffectResistanceAttribute(effect.mEffectID, &stats.getMagicEffects()); rating *= (1.f - std::min(resistance, 100.f) / 100.f); } // for harmful no-magnitude effects (e.g. silence) check if enemy is already has them // for non-harmful no-magnitude effects (e.g. bound items) check if actor is already has them if (magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude) { if (magicEffect->mData.mFlags & ESM::MagicEffect::Harmful) { CreatureStats& stats = enemy.getClass().getCreatureStats(enemy); if (stats.getMagicEffects().getOrDefault(effect.mEffectID).getMagnitude() > 0) return 0.f; } else { CreatureStats& stats = actor.getClass().getCreatureStats(actor); if (stats.getMagicEffects().getOrDefault(effect.mEffectID).getMagnitude() > 0) return 0.f; } } rating *= calcEffectCost(effect, magicEffect); // Currently treating all "on target" or "on touch" effects to target the enemy actor. // Combat AI is egoistic, so doesn't consider applying positive effects to friendly actors. if (effect.mRange != ESM::RT_Self) rating *= -1.f; return rating; } float rateEffects( const ESM::EffectList& list, const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy, bool useSpellMult) { // NOTE: enemy may be empty float rating = 0.f; const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fAIMagicSpellMult = gmst.find("fAIMagicSpellMult")->mValue.getFloat(); static const float fAIRangeMagicSpellMult = gmst.find("fAIRangeMagicSpellMult")->mValue.getFloat(); for (const ESM::IndexedENAMstruct& effect : list.mList) { float effectRating = rateEffect(effect.mData, actor, enemy); if (useSpellMult) { if (effect.mData.mRange == ESM::RT_Target) effectRating *= fAIRangeMagicSpellMult; else effectRating *= fAIMagicSpellMult; } rating += effectRating; } return rating; } float vanillaRateSpell(const ESM::Spell* spell, const MWWorld::Ptr& actor, const MWWorld::Ptr& enemy) { const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); static const float fAIMagicSpellMult = gmst.find("fAIMagicSpellMult")->mValue.getFloat(); static const float fAIRangeMagicSpellMult = gmst.find("fAIRangeMagicSpellMult")->mValue.getFloat(); float mult = fAIMagicSpellMult; for (std::vector<ESM::IndexedENAMstruct>::const_iterator effectIt = spell->mEffects.mList.begin(); effectIt != spell->mEffects.mList.end(); ++effectIt) { if (effectIt->mData.mRange == ESM::RT_Target) { if (!MWBase::Environment::get().getWorld()->isSwimming(enemy)) mult = fAIRangeMagicSpellMult; else mult = 0.0f; break; } } return MWMechanics::getSpellSuccessChance(spell, actor) * mult; } }
32,241
C++
.cpp
659
34.086495
119
0.548722
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,346
difficultyscaling.cpp
OpenMW_openmw/apps/openmw/mwmechanics/difficultyscaling.cpp
#include "difficultyscaling.hpp" #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/ptr.hpp" #include "actorutil.hpp" float scaleDamage(float damage, const MWWorld::Ptr& attacker, const MWWorld::Ptr& victim) { const MWWorld::Ptr& player = MWMechanics::getPlayer(); static const float fDifficultyMult = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>().find("fDifficultyMult")->mValue.getFloat(); const float difficultyTerm = 0.01f * Settings::game().mDifficulty; float x = 0; if (victim == player) { if (difficultyTerm > 0) x = fDifficultyMult * difficultyTerm; else x = difficultyTerm / fDifficultyMult; } else if (attacker == player) { if (difficultyTerm > 0) x = -difficultyTerm / fDifficultyMult; else x = fDifficultyMult * (-difficultyTerm); } damage *= 1 + x; return damage; }
1,027
C++
.cpp
30
28.433333
119
0.65723
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,347
aicombat.cpp
OpenMW_openmw/apps/openmw/mwmechanics/aicombat.cpp
#include "aicombat.hpp" #include <components/misc/coordinateconverter.hpp> #include <components/misc/rng.hpp> #include <components/esm3/aisequence.hpp> #include <components/misc/mathutil.hpp> #include <components/detournavigator/navigatorutils.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include "../mwphysics/raycasting.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwbase/dialoguemanager.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "actorutil.hpp" #include "aicombataction.hpp" #include "character.hpp" #include "combat.hpp" #include "creaturestats.hpp" #include "movement.hpp" #include "pathgrid.hpp" #include "steering.hpp" #include "weapontype.hpp" namespace { // chooses an attack depending on probability to avoid uniformity std::string_view chooseBestAttack(const ESM::Weapon* weapon); osg::Vec3f AimDirToMovingTarget(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, const osg::Vec3f& vLastTargetPos, float duration, int weapType, float strength); } namespace MWMechanics { AiCombat::AiCombat(const MWWorld::Ptr& actor) { mTargetActorId = actor.getClass().getCreatureStats(actor).getActorId(); } AiCombat::AiCombat(const ESM::AiSequence::AiCombat* combat) { mTargetActorId = combat->mTargetActorId; } void AiCombat::init() {} /* * Current AiCombat movement states (as of 0.29.0), ignoring the details of the * attack states such as CombatMove, Strike and ReadyToAttack: * * +----(within strike range)----->attack--(beyond strike range)-->follow * | | ^ | | * | | | | | * pursue<---(beyond follow range)-----+ +----(within strike range)---+ | * ^ | * | | * +-------------------------(beyond follow range)--------------------+ * * * Below diagram is high level only, the code detail is a little different * (but including those detail will just complicate the diagram w/o adding much) * * +----------(same)-------------->attack---------(same)---------->follow * | |^^ ||| * | ||| ||| * | +--(same)-----------------+|+----------(same)------------+|| * | | | || * | | | (in range) || * | <---+ (too far) | || * pursue<-------------------------[door open]<-----+ || * ^^^ | || * ||| | || * ||+----------evade-----+ | || * || | [closed door] | || * |+----> maybe stuck, check --------------> back up, check door || * | ^ | ^ | ^ || * | | | | | | || * | | +---+ +---+ || * | +-------------------------------------------------------+| * | | * +---------------------------(same)---------------------------------+ * * FIXME: * * The new scheme is way too complicated, should really be implemented as a * proper state machine. * * TODO: * * Use the observer pattern to coordinate attacks, provide intelligence on * whether the target was hit, etc. */ bool AiCombat::execute( const MWWorld::Ptr& actor, CharacterController& characterController, AiState& state, float duration) { // get or create temporary storage AiCombatStorage& storage = state.get<AiCombatStorage>(); // General description if (actor.getClass().getCreatureStats(actor).isDead()) return true; MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId); if (target.isEmpty()) return true; if (!target.getCellRef().getCount() || !target.getRefData().isEnabled() // Really we should be checking whether the target is currently // registered with the MechanicsManager || target.getClass().getCreatureStats(target).isDead()) return true; if (actor == target) // This should never happen. return true; if (!storage.isFleeing()) { if (storage.mCurrentAction.get()) // need to wait to init action with its attack range { // Update every frame. UpdateLOS uses a timer, so the LOS check does not happen every frame. updateLOS(actor, target, duration, storage); const float targetReachedTolerance = storage.mLOS && !storage.mUseCustomDestination ? storage.mAttackRange : 0.0f; const osg::Vec3f destination = storage.mUseCustomDestination ? storage.mCustomDestination : target.getRefData().getPosition().asVec3(); const bool is_target_reached = pathTo(actor, destination, duration, characterController.getSupportedMovementDirections(), targetReachedTolerance); if (is_target_reached) storage.mReadyToAttack = true; } storage.updateCombatMove(duration); storage.mRotateMove = false; if (storage.mReadyToAttack) updateActorsMovement(actor, duration, storage); if (storage.mRotateMove) return false; storage.updateAttack(actor, characterController); } else { updateFleeing(actor, target, duration, characterController.getSupportedMovementDirections(), storage); } storage.mActionCooldown -= duration; if (storage.mReaction.update(duration) == Misc::TimerStatus::Waiting) return false; return attack(actor, target, storage, characterController); } bool AiCombat::attack(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, AiCombatStorage& storage, CharacterController& characterController) { const MWWorld::CellStore*& currentCell = storage.mCell; bool cellChange = currentCell && (actor.getCell() != currentCell); if (!currentCell || cellChange) { currentCell = actor.getCell(); } bool forceFlee = false; if (!canFight(actor, target)) { storage.stopAttack(); actor.getClass().getCreatureStats(actor).setAttackingOrSpell(false); storage.mActionCooldown = 0.f; // Continue combat if target is player or player follower/escorter and an attack has been attempted const auto& playerFollowersAndEscorters = MWBase::Environment::get().getMechanicsManager()->getActorsSidingWith(MWMechanics::getPlayer()); bool targetSidesWithPlayer = (std::find(playerFollowersAndEscorters.begin(), playerFollowersAndEscorters.end(), target) != playerFollowersAndEscorters.end()); if ((target == MWMechanics::getPlayer() || targetSidesWithPlayer) && ((actor.getClass().getCreatureStats(actor).getHitAttemptActorId() == target.getClass().getCreatureStats(target).getActorId()) || (target.getClass().getCreatureStats(target).getHitAttemptActorId() == actor.getClass().getCreatureStats(actor).getActorId()))) forceFlee = true; else // Otherwise end combat return true; } const MWWorld::Class& actorClass = actor.getClass(); actorClass.getCreatureStats(actor).setMovementFlag(CreatureStats::Flag_Run, true); float& actionCooldown = storage.mActionCooldown; std::unique_ptr<Action>& currentAction = storage.mCurrentAction; if (!forceFlee) { if (actionCooldown > 0) return false; if (characterController.readyToPrepareAttack()) { currentAction = prepareNextAction(actor, target); actionCooldown = currentAction->getActionCooldown(); } } else { currentAction = std::make_unique<ActionFlee>(); actionCooldown = currentAction->getActionCooldown(); } if (!currentAction) return false; if (storage.isFleeing() != currentAction->isFleeing()) { if (currentAction->isFleeing()) { storage.startFleeing(); MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("flee")); return false; } else storage.stopFleeing(); } bool isRangedCombat = false; float& rangeAttack = storage.mAttackRange; rangeAttack = currentAction->getCombatRange(isRangedCombat); // Get weapon characteristics const ESM::Weapon* weapon = currentAction->getWeapon(); ESM::Position pos = actor.getRefData().getPosition(); const osg::Vec3f vActorPos(pos.asVec3()); const osg::Vec3f vTargetPos(target.getRefData().getPosition().asVec3()); float distToTarget = getDistanceToBounds(actor, target); storage.mReadyToAttack = (currentAction->isAttackingOrSpell() && distToTarget <= rangeAttack && storage.mLOS); if (isRangedCombat) { // rotate actor taking into account target movement direction and projectile speed osg::Vec3f vAimDir = AimDirToMovingTarget(actor, target, storage.mLastTargetPos, AI_REACTION_TIME, (weapon ? weapon->mData.mType : 0), storage.mStrength); storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir); storage.mMovement.mRotation[2] = getZAngleToDir(vAimDir); } else { osg::Vec3f vAimDir = MWBase::Environment::get().getWorld()->aimToTarget(actor, target, false); storage.mMovement.mRotation[0] = getXAngleToDir(vAimDir); storage.mMovement.mRotation[2] = getZAngleToDir( (vTargetPos - vActorPos)); // using vAimDir results in spastic movements since the head is animated } storage.mLastTargetPos = vTargetPos; if (storage.mReadyToAttack) { storage.startCombatMove(isRangedCombat, distToTarget, rangeAttack, actor, target); // start new attack bool canShout = true; ESM::RefId spellId = storage.mCurrentAction->getSpell(); if (!spellId.empty()) { const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(spellId); if (spell->mEffects.mList.empty() || spell->mEffects.mList[0].mData.mRange != ESM::RT_Target) canShout = false; } storage.startAttackIfReady(actor, characterController, weapon, isRangedCombat, canShout); } // If actor uses custom destination it has to try to rebuild path because environment can change // (door is opened between actor and target) or target position has changed and current custom destination // is not good enough to attack target. if (storage.mCurrentAction->isAttackingOrSpell() && ((!storage.mReadyToAttack && !mPathFinder.isPathConstructed()) || (storage.mUseCustomDestination && (storage.mCustomDestination - vTargetPos).length() > rangeAttack))) { const MWBase::World* world = MWBase::Environment::get().getWorld(); // Try to build path to the target. const auto agentBounds = world->getPathfindingAgentBounds(actor); const DetourNavigator::Flags navigatorFlags = getNavigatorFlags(actor); const DetourNavigator::AreaCosts areaCosts = getAreaCosts(actor, navigatorFlags); const ESM::Pathgrid* pathgrid = world->getStore().get<ESM::Pathgrid>().search(*actor.getCell()->getCell()); const auto& pathGridGraph = getPathGridGraph(pathgrid); mPathFinder.buildPath(actor, vActorPos, vTargetPos, actor.getCell(), pathGridGraph, agentBounds, navigatorFlags, areaCosts, storage.mAttackRange, PathType::Full); if (!mPathFinder.isPathConstructed()) { // If there is no path, try to find a point on a line from the actor position to target projected // on navmesh to attack the target from there. const auto navigator = world->getNavigator(); const auto hit = DetourNavigator::raycast(*navigator, agentBounds, vActorPos, vTargetPos, navigatorFlags); if (hit.has_value() && (*hit - vTargetPos).length() <= rangeAttack) { // If the point is close enough, try to find a path to that point. mPathFinder.buildPath(actor, vActorPos, *hit, actor.getCell(), pathGridGraph, agentBounds, navigatorFlags, areaCosts, storage.mAttackRange, PathType::Full); if (mPathFinder.isPathConstructed()) { // If path to that point is found use it as custom destination. storage.mCustomDestination = *hit; storage.mUseCustomDestination = true; } } if (!mPathFinder.isPathConstructed()) { storage.mUseCustomDestination = false; storage.stopAttack(); actor.getClass().getCreatureStats(actor).setAttackingOrSpell(false); currentAction = std::make_unique<ActionFlee>(); actionCooldown = currentAction->getActionCooldown(); storage.startFleeing(); MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("flee")); } } else { storage.mUseCustomDestination = false; } } return false; } void MWMechanics::AiCombat::updateLOS( const MWWorld::Ptr& actor, const MWWorld::Ptr& target, float duration, MWMechanics::AiCombatStorage& storage) { static const float LOS_UPDATE_DURATION = 0.5f; if (storage.mUpdateLOSTimer <= 0.f) { storage.mLOS = MWBase::Environment::get().getWorld()->getLOS(actor, target); storage.mUpdateLOSTimer = LOS_UPDATE_DURATION; } else storage.mUpdateLOSTimer -= duration; } void MWMechanics::AiCombat::updateFleeing(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, float duration, MWWorld::MovementDirectionFlags supportedMovementDirections, AiCombatStorage& storage) { static const float BLIND_RUN_DURATION = 1.0f; updateLOS(actor, target, duration, storage); AiCombatStorage::FleeState& state = storage.mFleeState; switch (state) { case AiCombatStorage::FleeState_None: return; case AiCombatStorage::FleeState_Idle: { float triggerDist = getMaxAttackDistance(target); const MWWorld::Cell* cellVariant = storage.mCell->getCell(); if (storage.mLOS && (triggerDist >= 1000 || getDistanceMinusHalfExtents(actor, target) <= triggerDist)) { const ESM::Pathgrid* pathgrid = MWBase::Environment::get().getESMStore()->get<ESM::Pathgrid>().search(*cellVariant); bool runFallback = true; if (pathgrid != nullptr && !pathgrid->mPoints.empty() && !actor.getClass().isPureWaterCreature(actor)) { ESM::Pathgrid::PointList points; const Misc::CoordinateConverter coords = Misc::makeCoordinateConverter(*storage.mCell->getCell()); osg::Vec3f localPos = actor.getRefData().getPosition().asVec3(); coords.toLocal(localPos); int closestPointIndex = PathFinder::getClosestPoint(pathgrid, localPos); for (int i = 0; i < static_cast<int>(pathgrid->mPoints.size()); i++) { if (i != closestPointIndex && getPathGridGraph(pathgrid).isPointConnected(closestPointIndex, i)) { points.push_back(pathgrid->mPoints[static_cast<size_t>(i)]); } } if (!points.empty()) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); ESM::Pathgrid::Point dest = points[Misc::Rng::rollDice(points.size(), prng)]; coords.toWorld(dest); state = AiCombatStorage::FleeState_RunToDestination; storage.mFleeDest = ESM::Pathgrid::Point(dest.mX, dest.mY, dest.mZ); runFallback = false; } } if (runFallback) { state = AiCombatStorage::FleeState_RunBlindly; storage.mFleeBlindRunTimer = 0.0f; } } } break; case AiCombatStorage::FleeState_RunBlindly: { // timer to prevent twitchy movement that can be observed in vanilla MW if (storage.mFleeBlindRunTimer < BLIND_RUN_DURATION) { storage.mFleeBlindRunTimer += duration; storage.mMovement.mRotation[0] = -actor.getRefData().getPosition().rot[0]; storage.mMovement.mRotation[2] = osg::PI + getZAngleToDir( target.getRefData().getPosition().asVec3() - actor.getRefData().getPosition().asVec3()); storage.mMovement.mPosition[1] = 1; updateActorsMovement(actor, duration, storage); } else state = AiCombatStorage::FleeState_Idle; } break; case AiCombatStorage::FleeState_RunToDestination: { static const float fFleeDistance = MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fFleeDistance") ->mValue.getFloat(); float dist = (actor.getRefData().getPosition().asVec3() - target.getRefData().getPosition().asVec3()).length(); if ((dist > fFleeDistance && !storage.mLOS) || pathTo(actor, PathFinder::makeOsgVec3(storage.mFleeDest), duration, supportedMovementDirections)) { state = AiCombatStorage::FleeState_Idle; } } break; }; } void AiCombat::updateActorsMovement(const MWWorld::Ptr& actor, float duration, AiCombatStorage& storage) { // apply combat movement float deltaAngle = storage.mMovement.mRotation[2] - actor.getRefData().getPosition().rot[2]; osg::Vec2f movement = Misc::rotateVec2f( osg::Vec2f(storage.mMovement.mPosition[0], storage.mMovement.mPosition[1]), -deltaAngle); MWMechanics::Movement& actorMovementSettings = actor.getClass().getMovementSettings(actor); actorMovementSettings.mPosition[0] = movement.x(); actorMovementSettings.mPosition[1] = movement.y(); actorMovementSettings.mPosition[2] = storage.mMovement.mPosition[2]; rotateActorOnAxis(actor, 2, actorMovementSettings, storage); rotateActorOnAxis(actor, 0, actorMovementSettings, storage); } void AiCombat::rotateActorOnAxis( const MWWorld::Ptr& actor, int axis, MWMechanics::Movement& actorMovementSettings, AiCombatStorage& storage) { actorMovementSettings.mRotation[axis] = 0; bool isRangedCombat = false; storage.mCurrentAction->getCombatRange(isRangedCombat); float eps = isRangedCombat ? osg::DegreesToRadians(0.5) : osg::DegreesToRadians(3.f); float targetAngleRadians = storage.mMovement.mRotation[axis]; storage.mRotateMove = !smoothTurn(actor, targetAngleRadians, axis, eps); } MWWorld::Ptr AiCombat::getTarget() const { if (mCachedTarget.isEmpty() || mCachedTarget.mRef->isDeleted() || !mCachedTarget.getRefData().isEnabled()) { mCachedTarget = MWBase::Environment::get().getWorld()->searchPtrViaActorId(mTargetActorId); } return mCachedTarget; } void AiCombat::writeState(ESM::AiSequence::AiSequence& sequence) const { auto combat = std::make_unique<ESM::AiSequence::AiCombat>(); combat->mTargetActorId = mTargetActorId; ESM::AiSequence::AiPackageContainer package; package.mType = ESM::AiSequence::Ai_Combat; package.mPackage = std::move(combat); sequence.mPackages.push_back(std::move(package)); } AiCombatStorage::AiCombatStorage() : mAttackCooldown(0.0f) , mReaction(MWBase::Environment::get().getWorld()->getPrng()) , mTimerCombatMove(0.0f) , mReadyToAttack(false) , mAttack(false) , mAttackRange(0.0f) , mCombatMove(false) , mRotateMove(false) , mLastTargetPos(0, 0, 0) , mCell(nullptr) , mCurrentAction() , mActionCooldown(0.0f) , mStrength() , mForceNoShortcut(false) , mShortcutFailPos() , mMovement() , mFleeState(FleeState_None) , mLOS(false) , mUpdateLOSTimer(0.0f) , mFleeBlindRunTimer(0.0f) , mUseCustomDestination(false) , mCustomDestination() { } void AiCombatStorage::startCombatMove(bool isDistantCombat, float distToTarget, float rangeAttack, const MWWorld::Ptr& actor, const MWWorld::Ptr& target) { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); // get the range of the target's weapon MWWorld::Ptr targetWeapon = MWWorld::Ptr(); const MWWorld::Class& targetClass = target.getClass(); if (targetClass.hasInventoryStore(target)) { int weapType = ESM::Weapon::None; MWWorld::ContainerStoreIterator weaponSlot = MWMechanics::getActiveWeapon(target, &weapType); if (weapType > ESM::Weapon::None) targetWeapon = *weaponSlot; } bool targetUsesRanged = false; float rangeAttackOfTarget = ActionWeapon(targetWeapon).getCombatRange(targetUsesRanged); if (mMovement.mPosition[0]) { mTimerCombatMove = 0.1f + 0.1f * Misc::Rng::rollClosedProbability(prng); mCombatMove = true; } // dodge movements (for NPCs and bipedal creatures) // Note: do not use for ranged combat yet since in couple with back up behaviour can move actor out of cliff else if (actor.getClass().isBipedal(actor) && !isDistantCombat) { float moveDuration = 0; float angleToTarget = Misc::normalizeAngle(mMovement.mRotation[2] - actor.getRefData().getPosition().rot[2]); // Apply a big side step if enemy tries to get around and come from behind. // Otherwise apply a random side step (kind of dodging) with some probability // if actor is within range of target's weapon. if (std::abs(angleToTarget) > osg::PI / 4) moveDuration = 0.2f; else if (distToTarget <= rangeAttackOfTarget && Misc::Rng::rollClosedProbability(prng) < 0.25) moveDuration = 0.1f + 0.1f * Misc::Rng::rollClosedProbability(prng); if (moveDuration > 0) { mMovement.mPosition[0] = Misc::Rng::rollProbability(prng) < 0.5 ? 1.0f : -1.0f; // to the left/right mTimerCombatMove = moveDuration; mCombatMove = true; } } mMovement.mPosition[1] = 0; if (isDistantCombat) { // Backing up behaviour // Actor backs up slightly further away than opponent's weapon range // (in vanilla - only as far as opponent's weapon range), // or not at all if opponent is using a ranged weapon if (targetUsesRanged || distToTarget > rangeAttackOfTarget * 1.5) // Don't back up if the target is wielding ranged weapon return; // actor should not back up into water if (MWBase::Environment::get().getWorld()->isUnderwater(MWWorld::ConstPtr(actor), 0.5f)) return; int mask = MWPhysics::CollisionType_World | MWPhysics::CollisionType_HeightMap | MWPhysics::CollisionType_Door; // Actor can not back up if there is no free space behind // Currently we take the 35% of actor's height from the ground as vector height. // This approach allows us to detect small obstacles (e.g. crates) and curved walls. osg::Vec3f halfExtents = MWBase::Environment::get().getWorld()->getHalfExtents(actor); osg::Vec3f pos = actor.getRefData().getPosition().asVec3(); osg::Vec3f source = pos + osg::Vec3f(0, 0, 0.75f * halfExtents.z()); osg::Vec3f fallbackDirection = actor.getRefData().getBaseNode()->getAttitude() * osg::Vec3f(0, -1, 0); osg::Vec3f destination = source + fallbackDirection * (halfExtents.y() + 16); const auto* rayCasting = MWBase::Environment::get().getWorld()->getRayCasting(); bool isObstacleDetected = rayCasting->castRay(source, destination, mask).mHit; if (isObstacleDetected) return; // Check if there is nothing behind - probably actor is near cliff. // A current approach: cast ray 1.5-yard ray down in 1.5 yard behind actor from 35% of actor's height. // If we did not hit anything, there is a cliff behind actor. source = pos + osg::Vec3f(0, 0, 0.75f * halfExtents.z()) + fallbackDirection * (halfExtents.y() + 96); destination = source - osg::Vec3f(0, 0, 0.75f * halfExtents.z() + 96); bool isCliffDetected = !rayCasting->castRay(source, destination, mask).mHit; if (isCliffDetected) return; mMovement.mPosition[1] = -1; } } void AiCombatStorage::updateCombatMove(float duration) { if (mCombatMove) { mTimerCombatMove -= duration; if (mTimerCombatMove <= 0) { stopCombatMove(); } } } void AiCombatStorage::stopCombatMove() { mTimerCombatMove = 0; mMovement.mPosition[0] = 0; mCombatMove = false; } void AiCombatStorage::startAttackIfReady(const MWWorld::Ptr& actor, CharacterController& characterController, const ESM::Weapon* weapon, bool distantCombat, bool canShout) { if (mReadyToAttack && characterController.readyToStartAttack()) { if (mAttackCooldown <= 0) { mAttack = true; // attack starts just now actor.getClass().getCreatureStats(actor).setAttackingOrSpell(true); if (!distantCombat) characterController.setAIAttackType(chooseBestAttack(weapon)); auto& prng = MWBase::Environment::get().getWorld()->getPrng(); mStrength = Misc::Rng::rollClosedProbability(prng); const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); float baseDelay = store.get<ESM::GameSetting>().find("fCombatDelayCreature")->mValue.getFloat(); if (actor.getClass().isNpc()) { baseDelay = store.get<ESM::GameSetting>().find("fCombatDelayNPC")->mValue.getFloat(); } if (canShout) { // Say a provoking combat phrase const int iVoiceAttackOdds = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->mValue.getInteger(); if (Misc::Rng::roll0to99(prng) < iVoiceAttackOdds) { MWBase::Environment::get().getDialogueManager()->say(actor, ESM::RefId::stringRefId("attack")); } } mAttackCooldown = std::min(baseDelay + 0.01 * Misc::Rng::roll0to99(prng), baseDelay + 0.9); } else mAttackCooldown -= AI_REACTION_TIME; } } void AiCombatStorage::updateAttack(const MWWorld::Ptr& actor, CharacterController& characterController) { if (mAttack) { float attackStrength = characterController.calculateWindUp(); mAttack = !characterController.readyToPrepareAttack() && attackStrength < mStrength && attackStrength != -1.f; } actor.getClass().getCreatureStats(actor).setAttackingOrSpell(mAttack); } void AiCombatStorage::stopAttack() { mMovement.mPosition[0] = 0; mMovement.mPosition[1] = 0; mMovement.mPosition[2] = 0; mReadyToAttack = false; mAttack = false; } void AiCombatStorage::startFleeing() { stopFleeing(); mFleeState = FleeState_Idle; } void AiCombatStorage::stopFleeing() { mMovement.mPosition[0] = 0; mMovement.mPosition[1] = 0; mMovement.mPosition[2] = 0; mFleeState = FleeState_None; mFleeDest = ESM::Pathgrid::Point(0, 0, 0); } bool AiCombatStorage::isFleeing() const { return mFleeState != FleeState_None; } } namespace { std::string_view chooseBestAttack(const ESM::Weapon* weapon) { if (weapon != nullptr) { // the more damage attackType deals the more probability it has int slash = (weapon->mData.mSlash[0] + weapon->mData.mSlash[1]) / 2; int chop = (weapon->mData.mChop[0] + weapon->mData.mChop[1]) / 2; int thrust = (weapon->mData.mThrust[0] + weapon->mData.mThrust[1]) / 2; auto& prng = MWBase::Environment::get().getWorld()->getPrng(); float roll = Misc::Rng::rollClosedProbability(prng) * (slash + chop + thrust); if (roll <= slash) return "slash"; else if (roll <= (slash + thrust)) return "thrust"; else return "chop"; } return MWMechanics::CharacterController::getRandomAttackType(); } osg::Vec3f AimDirToMovingTarget(const MWWorld::Ptr& actor, const MWWorld::Ptr& target, const osg::Vec3f& vLastTargetPos, float duration, int weapType, float strength) { float projSpeed; const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); // get projectile speed (depending on weapon type) if (MWMechanics::getWeaponType(weapType)->mWeaponClass == ESM::WeaponType::Thrown) { static float fThrownWeaponMinSpeed = gmst.find("fThrownWeaponMinSpeed")->mValue.getFloat(); static float fThrownWeaponMaxSpeed = gmst.find("fThrownWeaponMaxSpeed")->mValue.getFloat(); projSpeed = fThrownWeaponMinSpeed + (fThrownWeaponMaxSpeed - fThrownWeaponMinSpeed) * strength; } else if (weapType != 0) { static float fProjectileMinSpeed = gmst.find("fProjectileMinSpeed")->mValue.getFloat(); static float fProjectileMaxSpeed = gmst.find("fProjectileMaxSpeed")->mValue.getFloat(); projSpeed = fProjectileMinSpeed + (fProjectileMaxSpeed - fProjectileMinSpeed) * strength; } else // weapType is 0 ==> it's a target spell projectile { projSpeed = gmst.find("fTargetSpellMaxSpeed")->mValue.getFloat(); } // idea: perpendicular to dir to target speed components of target move vector and projectile vector should be // the same osg::Vec3f vTargetPos = target.getRefData().getPosition().asVec3(); osg::Vec3f vDirToTarget = MWBase::Environment::get().getWorld()->aimToTarget(actor, target, true); float distToTarget = vDirToTarget.length(); osg::Vec3f vTargetMoveDir = vTargetPos - vLastTargetPos; vTargetMoveDir /= duration; // |vTargetMoveDir| is target real speed in units/sec now osg::Vec3f vPerpToDir = vDirToTarget ^ osg::Vec3f(0, 0, 1); // cross product vPerpToDir.normalize(); osg::Vec3f vDirToTargetNormalized = vDirToTarget; vDirToTargetNormalized.normalize(); // dot product float velPerp = vTargetMoveDir * vPerpToDir; float velDir = vTargetMoveDir * vDirToTargetNormalized; // time to collision between target and projectile float t_collision; float projVelDirSquared = projSpeed * projSpeed - velPerp * velPerp; if (projVelDirSquared > 0) { osg::Vec3f vTargetMoveDirNormalized = vTargetMoveDir; vTargetMoveDirNormalized.normalize(); float projDistDiff = vDirToTarget * vTargetMoveDirNormalized; // dot product projDistDiff = std::sqrt(distToTarget * distToTarget - projDistDiff * projDistDiff); t_collision = projDistDiff / (std::sqrt(projVelDirSquared) - velDir); } else t_collision = 0; // speed of projectile is not enough to reach moving target return vDirToTarget + vTargetMoveDir * t_collision; } }
35,360
C++
.cpp
701
38.323823
120
0.574344
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,348
loudness.cpp
OpenMW_openmw/apps/openmw/mwsound/loudness.cpp
#include "loudness.hpp" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> namespace MWSound { void Sound_Loudness::analyzeLoudness(const std::vector<char>& data) { mQueue.insert(mQueue.end(), data.begin(), data.end()); if (!mQueue.size()) return; int samplesPerSegment = static_cast<int>(mSampleRate / mSamplesPerSec); std::size_t numSamples = bytesToFrames(mQueue.size(), mChannelConfig, mSampleType); std::size_t advance = framesToBytes(1, mChannelConfig, mSampleType); std::size_t segment = 0; std::size_t sample = 0; while (segment < numSamples / samplesPerSegment) { float sum = 0; int samplesAdded = 0; while (sample < numSamples && sample < (segment + 1) * samplesPerSegment) { // get sample on a scale from -1 to 1 float value = 0; if (mSampleType == SampleType_UInt8) value = ((char)(mQueue[sample * advance] ^ 0x80)) / 128.f; else if (mSampleType == SampleType_Int16) { value = *reinterpret_cast<const int16_t*>(&mQueue[sample * advance]); value /= float(std::numeric_limits<int16_t>::max()); } else if (mSampleType == SampleType_Float32) { value = *reinterpret_cast<const float*>(&mQueue[sample * advance]); value = std::clamp(value, -1.f, 1.f); // Float samples *should* be scaled to [-1,1] already. } sum += value * value; ++samplesAdded; ++sample; } float rms = 0; // root mean square if (samplesAdded > 0) rms = std::sqrt(sum / samplesAdded); mSamples.push_back(rms); ++segment; } mQueue.erase(mQueue.begin(), mQueue.begin() + sample * advance); } float Sound_Loudness::getLoudnessAtTime(float sec) const { if (mSamplesPerSec <= 0.0f || mSamples.empty() || sec < 0.0f) return 0.0f; size_t index = std::min(static_cast<size_t>(sec * mSamplesPerSec), mSamples.size() - 1); return mSamples[index]; } }
2,326
C++
.cpp
57
29.508772
112
0.54163
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,349
watersoundupdater.cpp
OpenMW_openmw/apps/openmw/mwsound/watersoundupdater.cpp
#include "watersoundupdater.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/ptr.hpp" #include <components/esm3/loadcell.hpp> #include <osg/Vec3f> namespace MWSound { WaterSoundUpdater::WaterSoundUpdater(const WaterSoundUpdaterSettings& settings) : mSettings(settings) { } WaterSoundUpdate WaterSoundUpdater::update(const MWWorld::ConstPtr& player, const MWBase::World& world) const { WaterSoundUpdate result; result.mId = player.getCell()->isExterior() ? mSettings.mNearWaterOutdoorID : mSettings.mNearWaterIndoorID; result.mVolume = std::min(1.0f, getVolume(player, world)); return result; } float WaterSoundUpdater::getVolume(const MWWorld::ConstPtr& player, const MWBase::World& world) const { if (mListenerUnderwater) return 1.0f; const MWWorld::CellStore& cell = *player.getCell(); if (!cell.getCell()->hasWater()) return 0.0f; const osg::Vec3f pos = player.getRefData().getPosition().asVec3(); const float dist = std::abs(cell.getWaterLevel() - pos.z()); if (cell.isExterior() && dist < mSettings.mNearWaterOutdoorTolerance) { if (mSettings.mNearWaterPoints <= 1) return (mSettings.mNearWaterOutdoorTolerance - dist) / mSettings.mNearWaterOutdoorTolerance; const float step = mSettings.mNearWaterRadius * 2.0f / (mSettings.mNearWaterPoints - 1); int underwaterPoints = 0; for (int x = 0; x < mSettings.mNearWaterPoints; x++) { for (int y = 0; y < mSettings.mNearWaterPoints; y++) { const float terrainX = pos.x() - mSettings.mNearWaterRadius + x * step; const float terrainY = pos.y() - mSettings.mNearWaterRadius + y * step; const float height = world.getTerrainHeightAt( osg::Vec3f(terrainX, terrainY, 0.0f), cell.getCell()->getWorldSpace()); if (height < 0) underwaterPoints++; } } return underwaterPoints * 2.0f / (mSettings.mNearWaterPoints * mSettings.mNearWaterPoints); } if (!cell.isExterior() && dist < mSettings.mNearWaterIndoorTolerance) return (mSettings.mNearWaterIndoorTolerance - dist) / mSettings.mNearWaterIndoorTolerance; return 0.0f; } }
2,495
C++
.cpp
53
36.886792
115
0.63021
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,350
soundmanagerimp.cpp
OpenMW_openmw/apps/openmw/mwsound/soundmanagerimp.cpp
#include "soundmanagerimp.hpp" #include <algorithm> #include <map> #include <numeric> #include <sstream> #include <osg/Matrixf> #include <components/debug/debuglog.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/rng.hpp> #include <components/settings/values.hpp> #include <components/vfs/manager.hpp> #include <components/vfs/pathutil.hpp> #include <components/vfs/recursivedirectoryiterator.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/statemanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwmechanics/actorutil.hpp" #include "constants.hpp" #include "ffmpeg_decoder.hpp" #include "openal_output.hpp" #include "sound.hpp" #include "sound_buffer.hpp" #include "sound_decoder.hpp" #include "sound_output.hpp" namespace MWSound { namespace { constexpr float sMinUpdateInterval = 1.0f / 30.0f; constexpr float sSfxFadeInDuration = 1.0f; constexpr float sSfxFadeOutDuration = 1.0f; constexpr float sSoundCullDistance = 2000.f; WaterSoundUpdaterSettings makeWaterSoundUpdaterSettings() { WaterSoundUpdaterSettings settings; settings.mNearWaterRadius = Fallback::Map::getInt("Water_NearWaterRadius"); settings.mNearWaterPoints = Fallback::Map::getInt("Water_NearWaterPoints"); settings.mNearWaterIndoorTolerance = Fallback::Map::getFloat("Water_NearWaterIndoorTolerance"); settings.mNearWaterOutdoorTolerance = Fallback::Map::getFloat("Water_NearWaterOutdoorTolerance"); settings.mNearWaterIndoorID = ESM::RefId::stringRefId(Fallback::Map::getString("Water_NearWaterIndoorID")); settings.mNearWaterOutdoorID = ESM::RefId::stringRefId(Fallback::Map::getString("Water_NearWaterOutdoorID")); return settings; } float initialFadeVolume(float squaredDist, Sound_Buffer* sfx, Type type, PlayMode mode) { // If a sound is farther away than its maximum distance, start playing it with a zero fade volume. // It can still become audible once the player moves closer. const float maxDist = sfx->getMaxDist(); if (squaredDist > (maxDist * maxDist)) return 0.0f; // This is a *heuristic* that causes environment sounds to fade in. The idea is the following: // - Only looped sounds playing through the effects channel are environment sounds // - Do not fade in sounds if the player is already so close that the sound plays at maximum volume const float minDist = sfx->getMinDist(); if ((squaredDist > (minDist * minDist)) && (type == Type::Sfx) && (mode & PlayMode::Loop)) return 0.0f; return 1.0; } // Gets the combined volume settings for the given sound type float volumeFromType(Type type) { float volume = Settings::sound().mMasterVolume; switch (type) { case Type::Sfx: volume *= Settings::sound().mSfxVolume; break; case Type::Voice: volume *= Settings::sound().mVoiceVolume; break; case Type::Foot: volume *= Settings::sound().mFootstepsVolume; break; case Type::Music: volume *= Settings::sound().mMusicVolume; break; case Type::Movie: case Type::Mask: break; } return volume; } } // For combining PlayMode and Type flags inline int operator|(PlayMode a, Type b) { return static_cast<int>(a) | static_cast<int>(b); } SoundManager::SoundManager(const VFS::Manager* vfs, bool useSound) : mVFS(vfs) , mOutput(std::make_unique<OpenAL_Output>(*this)) , mWaterSoundUpdater(makeWaterSoundUpdaterSettings()) , mSoundBuffers(*mOutput) , mMusicType(MWSound::MusicType::Normal) , mListenerUnderwater(false) , mListenerPos(0, 0, 0) , mListenerDir(1, 0, 0) , mListenerUp(0, 0, 1) , mUnderwaterSound(nullptr) , mNearWaterSound(nullptr) , mPlaybackPaused(false) , mTimePassed(0.f) , mLastCell(nullptr) , mCurrentRegionSound(nullptr) { if (!useSound) { Log(Debug::Info) << "Sound disabled."; return; } if (!mOutput->init(Settings::sound().mDevice, Settings::sound().mHrtf, Settings::sound().mHrtfEnable)) { Log(Debug::Error) << "Failed to initialize audio output, sound disabled"; return; } std::vector<std::string> names = mOutput->enumerate(); std::stringstream stream; stream << "Enumerated output devices:\n"; for (const std::string& name : names) stream << " " << name; Log(Debug::Info) << stream.str(); stream.str(""); names = mOutput->enumerateHrtf(); if (!names.empty()) { stream << "Enumerated HRTF names:\n"; for (const std::string& name : names) stream << " " << name; Log(Debug::Info) << stream.str(); } } SoundManager::~SoundManager() { SoundManager::clear(); mSoundBuffers.clear(); mOutput.reset(); } // Return a new decoder instance, used as needed by the output implementations DecoderPtr SoundManager::getDecoder() { return std::make_shared<FFmpeg_Decoder>(mVFS); } DecoderPtr SoundManager::loadVoice(VFS::Path::NormalizedView voicefile) { try { DecoderPtr decoder = getDecoder(); decoder->open(Misc::ResourceHelpers::correctSoundPath(voicefile, *decoder->mResourceMgr)); return decoder; } catch (std::exception& e) { Log(Debug::Error) << "Failed to load audio from " << voicefile << ": " << e.what(); } return nullptr; } SoundPtr SoundManager::getSoundRef() { return mSounds.get(); } StreamPtr SoundManager::getStreamRef() { return mStreams.get(); } StreamPtr SoundManager::playVoice(DecoderPtr decoder, const osg::Vec3f& pos, bool playlocal) { MWBase::World* world = MWBase::Environment::get().getWorld(); static const float fAudioMinDistanceMult = world->getStore().get<ESM::GameSetting>().find("fAudioMinDistanceMult")->mValue.getFloat(); static const float fAudioMaxDistanceMult = world->getStore().get<ESM::GameSetting>().find("fAudioMaxDistanceMult")->mValue.getFloat(); static const float fAudioVoiceDefaultMinDistance = world->getStore().get<ESM::GameSetting>().find("fAudioVoiceDefaultMinDistance")->mValue.getFloat(); static const float fAudioVoiceDefaultMaxDistance = world->getStore().get<ESM::GameSetting>().find("fAudioVoiceDefaultMaxDistance")->mValue.getFloat(); static float minDistance = std::max(fAudioVoiceDefaultMinDistance * fAudioMinDistanceMult, 1.0f); static float maxDistance = std::max(fAudioVoiceDefaultMaxDistance * fAudioMaxDistanceMult, minDistance); bool played; float basevol = volumeFromType(Type::Voice); StreamPtr sound = getStreamRef(); if (playlocal) { sound->init([&] { SoundParams params; params.mBaseVolume = basevol; params.mFlags = PlayMode::NoEnv | Type::Voice | Play_2D; return params; }()); played = mOutput->streamSound(std::move(decoder), sound.get(), true); } else { sound->init([&] { SoundParams params; params.mPos = pos; params.mBaseVolume = basevol; params.mMinDistance = minDistance; params.mMaxDistance = maxDistance; params.mFlags = PlayMode::Normal | Type::Voice | Play_3D; return params; }()); played = mOutput->streamSound3D(std::move(decoder), sound.get(), true); } if (!played) return nullptr; return sound; } void SoundManager::stopMusic() { if (mMusic) { mOutput->finishStream(mMusic.get()); mMusic = nullptr; } } void SoundManager::streamMusicFull(VFS::Path::NormalizedView filename) { if (!mOutput->isInitialized()) return; stopMusic(); if (filename.value().empty()) return; Log(Debug::Info) << "Playing \"" << filename << "\""; DecoderPtr decoder = getDecoder(); try { decoder->open(filename); } catch (const std::exception& e) { Log(Debug::Error) << "Failed to load audio from \"" << filename << "\": " << e.what(); return; } mMusic = getStreamRef(); mMusic->init([&] { SoundParams params; params.mBaseVolume = volumeFromType(Type::Music); params.mFlags = PlayMode::NoEnvNoScaling | Type::Music | Play_2D; return params; }()); mOutput->streamSound(std::move(decoder), mMusic.get()); } void SoundManager::advanceMusic(VFS::Path::NormalizedView filename, float fadeOut) { if (!isMusicPlaying()) { streamMusicFull(filename); return; } mNextMusic = filename; mMusic->setFadeout(fadeOut); } bool SoundManager::isMusicPlaying() { return mMusic && mOutput->isStreamPlaying(mMusic.get()); } void SoundManager::streamMusic(VFS::Path::NormalizedView filename, MusicType type, float fade) { // Can not interrupt scripted music by built-in playlists if (mMusicType == MusicType::MWScript && type != MusicType::MWScript) return; mMusicType = type; advanceMusic(filename, fade); } void SoundManager::say(const MWWorld::ConstPtr& ptr, VFS::Path::NormalizedView filename) { if (!mOutput->isInitialized()) return; DecoderPtr decoder = loadVoice(filename); if (!decoder) return; MWBase::World* world = MWBase::Environment::get().getWorld(); const osg::Vec3f pos = world->getActorHeadTransform(ptr).getTrans(); stopSay(ptr); StreamPtr sound = playVoice(std::move(decoder), pos, (ptr == MWMechanics::getPlayer())); if (!sound) return; mSaySoundsQueue.emplace(ptr.mRef, SaySound{ ptr.mCell, std::move(sound) }); } float SoundManager::getSaySoundLoudness(const MWWorld::ConstPtr& ptr) const { SaySoundMap::const_iterator snditer = mActiveSaySounds.find(ptr.mRef); if (snditer != mActiveSaySounds.end()) { Stream* sound = snditer->second.mStream.get(); return mOutput->getStreamLoudness(sound); } return 0.0f; } void SoundManager::say(VFS::Path::NormalizedView filename) { if (!mOutput->isInitialized()) return; DecoderPtr decoder = loadVoice(filename); if (!decoder) return; stopSay(MWWorld::ConstPtr()); StreamPtr sound = playVoice(std::move(decoder), osg::Vec3f(), true); if (!sound) return; mActiveSaySounds.emplace(nullptr, SaySound{ nullptr, std::move(sound) }); } bool SoundManager::sayDone(const MWWorld::ConstPtr& ptr) const { SaySoundMap::const_iterator snditer = mActiveSaySounds.find(ptr.mRef); if (snditer != mActiveSaySounds.end()) { if (mOutput->isStreamPlaying(snditer->second.mStream.get())) return false; return true; } return true; } bool SoundManager::sayActive(const MWWorld::ConstPtr& ptr) const { SaySoundMap::const_iterator snditer = mSaySoundsQueue.find(ptr.mRef); if (snditer != mSaySoundsQueue.end()) { if (mOutput->isStreamPlaying(snditer->second.mStream.get())) return true; return false; } snditer = mActiveSaySounds.find(ptr.mRef); if (snditer != mActiveSaySounds.end()) { if (mOutput->isStreamPlaying(snditer->second.mStream.get())) return true; return false; } return false; } void SoundManager::stopSay(const MWWorld::ConstPtr& ptr) { SaySoundMap::iterator snditer = mSaySoundsQueue.find(ptr.mRef); if (snditer != mSaySoundsQueue.end()) { mOutput->finishStream(snditer->second.mStream.get()); mSaySoundsQueue.erase(snditer); } snditer = mActiveSaySounds.find(ptr.mRef); if (snditer != mActiveSaySounds.end()) { mOutput->finishStream(snditer->second.mStream.get()); mActiveSaySounds.erase(snditer); } } Stream* SoundManager::playTrack(const DecoderPtr& decoder, Type type) { if (!mOutput->isInitialized()) return nullptr; StreamPtr track = getStreamRef(); track->init([&] { SoundParams params; params.mBaseVolume = volumeFromType(type); params.mFlags = PlayMode::NoEnvNoScaling | type | Play_2D; return params; }()); if (!mOutput->streamSound(decoder, track.get())) return nullptr; Stream* result = track.get(); const auto it = std::lower_bound(mActiveTracks.begin(), mActiveTracks.end(), track); mActiveTracks.insert(it, std::move(track)); return result; } void SoundManager::stopTrack(Stream* stream) { mOutput->finishStream(stream); TrackList::iterator iter = std::lower_bound(mActiveTracks.begin(), mActiveTracks.end(), stream, [](const StreamPtr& lhs, Stream* rhs) { return lhs.get() < rhs; }); if (iter != mActiveTracks.end() && iter->get() == stream) mActiveTracks.erase(iter); } double SoundManager::getTrackTimeDelay(Stream* stream) { return mOutput->getStreamDelay(stream); } bool SoundManager::remove3DSoundAtDistance(PlayMode mode, const MWWorld::ConstPtr& ptr) const { if (!mOutput->isInitialized()) return true; const osg::Vec3f objpos(ptr.getRefData().getPosition().asVec3()); const float squaredDist = (mListenerPos - objpos).length2(); if ((mode & PlayMode::RemoveAtDistance) && squaredDist > sSoundCullDistance * sSoundCullDistance) return true; return false; } Sound* SoundManager::playSound(Sound_Buffer* sfx, float volume, float pitch, Type type, PlayMode mode, float offset) { if (!mOutput->isInitialized()) return nullptr; // Only one copy of given sound can be played at time, so stop previous copy stopSound(sfx, MWWorld::ConstPtr()); SoundPtr sound = getSoundRef(); sound->init([&] { SoundParams params; params.mVolume = volume * sfx->getVolume(); params.mBaseVolume = volumeFromType(type); params.mPitch = pitch; params.mFlags = mode | type | Play_2D; return params; }()); if (!mOutput->playSound(sound.get(), sfx->getHandle(), offset)) return nullptr; Sound* result = sound.get(); mActiveSounds[nullptr].mList.emplace_back(std::move(sound), sfx); mSoundBuffers.use(*sfx); return result; } Sound* SoundManager::playSound( std::string_view fileName, float volume, float pitch, Type type, PlayMode mode, float offset) { if (!mOutput->isInitialized()) return nullptr; std::string normalizedName = VFS::Path::normalizeFilename(fileName); if (!mVFS->exists(normalizedName)) return nullptr; Sound_Buffer* sfx = mSoundBuffers.load(normalizedName); if (!sfx) return nullptr; return playSound(sfx, volume, pitch, type, mode, offset); } Sound* SoundManager::playSound( const ESM::RefId& soundId, float volume, float pitch, Type type, PlayMode mode, float offset) { if (!mOutput->isInitialized()) return nullptr; Sound_Buffer* sfx = mSoundBuffers.load(soundId); if (!sfx) return nullptr; return playSound(sfx, volume, pitch, type, mode, offset); } Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, Sound_Buffer* sfx, float volume, float pitch, Type type, PlayMode mode, float offset) { if (!mOutput->isInitialized()) return nullptr; // Only one copy of given sound can be played at time on ptr, so stop previous copy stopSound(sfx, ptr); const osg::Vec3f objpos(ptr.getRefData().getPosition().asVec3()); const float squaredDist = (mListenerPos - objpos).length2(); bool played; SoundPtr sound = getSoundRef(); if (!(mode & PlayMode::NoPlayerLocal) && ptr == MWMechanics::getPlayer()) { sound->init([&] { SoundParams params; params.mVolume = volume * sfx->getVolume(); params.mBaseVolume = volumeFromType(type); params.mPitch = pitch; params.mFlags = mode | type | Play_2D; return params; }()); played = mOutput->playSound(sound.get(), sfx->getHandle(), offset); } else { sound->init([&] { SoundParams params; params.mPos = objpos; params.mVolume = volume * sfx->getVolume(); params.mBaseVolume = volumeFromType(type); params.mFadeVolume = initialFadeVolume(squaredDist, sfx, type, mode); params.mPitch = pitch; params.mMinDistance = sfx->getMinDist(); params.mMaxDistance = sfx->getMaxDist(); params.mFlags = mode | type | Play_3D; return params; }()); played = mOutput->playSound3D(sound.get(), sfx->getHandle(), offset); } if (!played) return nullptr; Sound* result = sound.get(); auto it = mActiveSounds.find(ptr.mRef); if (it == mActiveSounds.end()) it = mActiveSounds.emplace(ptr.mRef, ActiveSound{ ptr.mCell, {} }).first; it->second.mList.emplace_back(std::move(sound), sfx); mSoundBuffers.use(*sfx); return result; } Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId, float volume, float pitch, Type type, PlayMode mode, float offset) { if (remove3DSoundAtDistance(mode, ptr)) return nullptr; // Look up the sound in the ESM data Sound_Buffer* sfx = mSoundBuffers.load(soundId); if (!sfx) return nullptr; return playSound3D(ptr, sfx, volume, pitch, type, mode, offset); } Sound* SoundManager::playSound3D(const MWWorld::ConstPtr& ptr, std::string_view fileName, float volume, float pitch, Type type, PlayMode mode, float offset) { if (remove3DSoundAtDistance(mode, ptr)) return nullptr; // Look up the sound std::string normalizedName = VFS::Path::normalizeFilename(fileName); if (!mVFS->exists(normalizedName)) return nullptr; Sound_Buffer* sfx = mSoundBuffers.load(normalizedName); if (!sfx) return nullptr; return playSound3D(ptr, sfx, volume, pitch, type, mode, offset); } Sound* SoundManager::playSound3D(const osg::Vec3f& initialPos, const ESM::RefId& soundId, float volume, float pitch, Type type, PlayMode mode, float offset) { if (!mOutput->isInitialized()) return nullptr; // Look up the sound in the ESM data Sound_Buffer* sfx = mSoundBuffers.load(soundId); if (!sfx) return nullptr; const float squaredDist = (mListenerPos - initialPos).length2(); SoundPtr sound = getSoundRef(); sound->init([&] { SoundParams params; params.mPos = initialPos; params.mVolume = volume * sfx->getVolume(); params.mBaseVolume = volumeFromType(type); params.mFadeVolume = initialFadeVolume(squaredDist, sfx, type, mode); params.mPitch = pitch; params.mMinDistance = sfx->getMinDist(); params.mMaxDistance = sfx->getMaxDist(); params.mFlags = mode | type | Play_3D; return params; }()); if (!mOutput->playSound3D(sound.get(), sfx->getHandle(), offset)) return nullptr; Sound* result = sound.get(); mActiveSounds[nullptr].mList.emplace_back(std::move(sound), sfx); mSoundBuffers.use(*sfx); return result; } void SoundManager::stopSound(Sound* sound) { if (sound) mOutput->finishSound(sound); } void SoundManager::stopSound(Sound_Buffer* sfx, const MWWorld::ConstPtr& ptr) { SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef); if (snditer != mActiveSounds.end()) { for (SoundBufferRefPair& snd : snditer->second.mList) { if (snd.second == sfx) mOutput->finishSound(snd.first.get()); } } } void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId) { if (!mOutput->isInitialized()) return; Sound_Buffer* sfx = mSoundBuffers.lookup(soundId); if (!sfx) return; stopSound(sfx, ptr); } void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr, std::string_view fileName) { if (!mOutput->isInitialized()) return; std::string normalizedName = VFS::Path::normalizeFilename(fileName); Sound_Buffer* sfx = mSoundBuffers.lookup(normalizedName); if (!sfx) return; stopSound(sfx, ptr); } void SoundManager::stopSound3D(const MWWorld::ConstPtr& ptr) { SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef); if (snditer != mActiveSounds.end()) { for (SoundBufferRefPair& snd : snditer->second.mList) mOutput->finishSound(snd.first.get()); } SaySoundMap::iterator sayiter = mSaySoundsQueue.find(ptr.mRef); if (sayiter != mSaySoundsQueue.end()) mOutput->finishStream(sayiter->second.mStream.get()); sayiter = mActiveSaySounds.find(ptr.mRef); if (sayiter != mActiveSaySounds.end()) mOutput->finishStream(sayiter->second.mStream.get()); } void SoundManager::stopSound(const MWWorld::CellStore* cell) { for (auto& [ref, sound] : mActiveSounds) { if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell) { for (SoundBufferRefPair& sndbuf : sound.mList) mOutput->finishSound(sndbuf.first.get()); } } for (const auto& [ref, sound] : mSaySoundsQueue) { if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell) mOutput->finishStream(sound.mStream.get()); } for (const auto& [ref, sound] : mActiveSaySounds) { if (ref != nullptr && ref != MWMechanics::getPlayer().mRef && sound.mCell == cell) mOutput->finishStream(sound.mStream.get()); } } void SoundManager::fadeOutSound3D(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId, float duration) { SoundMap::iterator snditer = mActiveSounds.find(ptr.mRef); if (snditer != mActiveSounds.end()) { Sound_Buffer* sfx = mSoundBuffers.lookup(soundId); if (sfx == nullptr) return; for (SoundBufferRefPair& sndbuf : snditer->second.mList) { if (sndbuf.second == sfx) sndbuf.first->setFadeout(duration); } } } bool SoundManager::getSoundPlaying(const MWWorld::ConstPtr& ptr, std::string_view fileName) const { std::string normalizedName = VFS::Path::normalizeFilename(fileName); SoundMap::const_iterator snditer = mActiveSounds.find(ptr.mRef); if (snditer != mActiveSounds.end()) { Sound_Buffer* sfx = mSoundBuffers.lookup(normalizedName); if (!sfx) return false; return std::find_if(snditer->second.mList.cbegin(), snditer->second.mList.cend(), [this, sfx](const SoundBufferRefPair& snd) -> bool { return snd.second == sfx && mOutput->isSoundPlaying(snd.first.get()); }) != snditer->second.mList.cend(); } return false; } bool SoundManager::getSoundPlaying(const MWWorld::ConstPtr& ptr, const ESM::RefId& soundId) const { SoundMap::const_iterator snditer = mActiveSounds.find(ptr.mRef); if (snditer != mActiveSounds.end()) { Sound_Buffer* sfx = mSoundBuffers.lookup(soundId); if (!sfx) return false; return std::find_if(snditer->second.mList.cbegin(), snditer->second.mList.cend(), [this, sfx](const SoundBufferRefPair& snd) -> bool { return snd.second == sfx && mOutput->isSoundPlaying(snd.first.get()); }) != snditer->second.mList.cend(); } return false; } void SoundManager::pauseSounds(BlockerType blocker, int types) { if (mOutput->isInitialized()) { if (mPausedSoundTypes[blocker] != 0) resumeSounds(blocker); types = types & Type::Mask; mOutput->pauseSounds(types); mPausedSoundTypes[blocker] = types; } } void SoundManager::resumeSounds(BlockerType blocker) { if (mOutput->isInitialized()) { mPausedSoundTypes[blocker] = 0; int types = int(Type::Mask); for (int currentBlocker = 0; currentBlocker < BlockerType::MaxCount; currentBlocker++) { if (currentBlocker != blocker) types &= ~mPausedSoundTypes[currentBlocker]; } mOutput->resumeSounds(types); } } void SoundManager::pausePlayback() { if (mPlaybackPaused) return; mPlaybackPaused = true; mOutput->pauseActiveDevice(); } void SoundManager::resumePlayback() { if (!mPlaybackPaused) return; mPlaybackPaused = false; mOutput->resumeActiveDevice(); } void SoundManager::updateRegionSound(float duration) { MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::ConstPtr player = world->getPlayerPtr(); auto cell = player.getCell()->getCell(); if (!cell->isExterior() && !cell->isQuasiExterior()) return; if (mCurrentRegionSound && mOutput->isSoundPlaying(mCurrentRegionSound)) return; ESM::RefId next = mRegionSoundSelector.getNextRandom(duration, cell->getRegion()); if (!next.empty()) mCurrentRegionSound = playSound(next, 1.0f, 1.0f); } void SoundManager::updateWaterSound() { MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::ConstPtr player = world->getPlayerPtr(); const MWWorld::Cell* curcell = player.getCell()->getCell(); const auto update = mWaterSoundUpdater.update(player, *world); WaterSoundAction action; Sound_Buffer* sfx; std::tie(action, sfx) = getWaterSoundAction(update, curcell); switch (action) { case WaterSoundAction::DoNothing: break; case WaterSoundAction::SetVolume: mNearWaterSound->setVolume(update.mVolume * sfx->getVolume()); mNearWaterSound->setFade(sSfxFadeInDuration, 1.0f, Play_FadeExponential); break; case WaterSoundAction::FinishSound: mNearWaterSound->setFade(sSfxFadeOutDuration, 0.0f, Play_FadeExponential | Play_StopAtFadeEnd); break; case WaterSoundAction::PlaySound: if (mNearWaterSound) mOutput->finishSound(mNearWaterSound); mNearWaterSound = playSound(update.mId, update.mVolume, 1.0f, Type::Sfx, PlayMode::Loop); break; } mLastCell = curcell; } std::pair<SoundManager::WaterSoundAction, Sound_Buffer*> SoundManager::getWaterSoundAction( const WaterSoundUpdate& update, const MWWorld::Cell* cell) const { if (mNearWaterSound) { if (update.mVolume == 0.0f) return { WaterSoundAction::FinishSound, nullptr }; bool soundIdChanged = false; Sound_Buffer* sfx = mSoundBuffers.lookup(update.mId); if (mLastCell != cell) { const auto snditer = mActiveSounds.find(nullptr); if (snditer != mActiveSounds.end()) { const auto pairiter = std::find_if(snditer->second.mList.begin(), snditer->second.mList.end(), [this](const SoundBufferRefPairList::value_type& item) -> bool { return mNearWaterSound == item.first.get(); }); if (pairiter != snditer->second.mList.end() && pairiter->second != sfx) soundIdChanged = true; } } if (soundIdChanged) return { WaterSoundAction::PlaySound, nullptr }; if (sfx) return { WaterSoundAction::SetVolume, sfx }; } else if (update.mVolume > 0.0f) return { WaterSoundAction::PlaySound, nullptr }; return { WaterSoundAction::DoNothing, nullptr }; } void SoundManager::cull3DSound(SoundBase* sound) { // Hard-coded distance is from an original engine const float maxDist = sound->getDistanceCull() ? sSoundCullDistance : sound->getMaxDistance(); const float squaredMaxDist = maxDist * maxDist; const osg::Vec3f pos = sound->getPosition(); const float squaredDist = (mListenerPos - pos).length2(); if (squaredDist > squaredMaxDist) { // If getDistanceCull() is set, delete the sound after it has faded out sound->setFade( sSfxFadeOutDuration, 0.0f, Play_FadeExponential | (sound->getDistanceCull() ? Play_StopAtFadeEnd : 0)); } else { // Fade sounds back in once they are in range sound->setFade(sSfxFadeInDuration, 1.0f, Play_FadeExponential); } } void SoundManager::updateSounds(float duration) { // We update active say sounds map for specific actors here // because for vanilla compatibility we can't do it immediately. SaySoundMap::iterator queuesayiter = mSaySoundsQueue.begin(); while (queuesayiter != mSaySoundsQueue.end()) { const auto dst = mActiveSaySounds.find(queuesayiter->first); if (dst == mActiveSaySounds.end()) mActiveSaySounds.emplace(queuesayiter->first, std::move(queuesayiter->second)); else dst->second = std::move(queuesayiter->second); mSaySoundsQueue.erase(queuesayiter++); } mTimePassed += duration; if (mTimePassed < sMinUpdateInterval) return; duration = mTimePassed; mTimePassed = 0.0f; Environment env = Env_Normal; if (mListenerUnderwater) env = Env_Underwater; else if (mUnderwaterSound) { mOutput->finishSound(mUnderwaterSound); mUnderwaterSound = nullptr; } mOutput->startUpdate(); mOutput->updateListener(mListenerPos, mListenerDir, mListenerUp, env); updateMusic(duration); // Check if any sounds are finished playing, and trash them SoundMap::iterator snditer = mActiveSounds.begin(); while (snditer != mActiveSounds.end()) { MWWorld::ConstPtr ptr = snditer->first; SoundBufferRefPairList::iterator sndidx = snditer->second.mList.begin(); while (sndidx != snditer->second.mList.end()) { Sound* sound = sndidx->first.get(); if (sound->getIs3D()) { if (!ptr.isEmpty()) sound->setPosition(ptr.getRefData().getPosition().asVec3()); cull3DSound(sound); } if (!sound->updateFade(duration) || !mOutput->isSoundPlaying(sound)) { mOutput->finishSound(sound); if (sound == mUnderwaterSound) mUnderwaterSound = nullptr; if (sound == mNearWaterSound) mNearWaterSound = nullptr; mSoundBuffers.release(*sndidx->second); sndidx = snditer->second.mList.erase(sndidx); } else { mOutput->updateSound(sound); ++sndidx; } } if (snditer->second.mList.empty()) snditer = mActiveSounds.erase(snditer); else ++snditer; } SaySoundMap::iterator sayiter = mActiveSaySounds.begin(); while (sayiter != mActiveSaySounds.end()) { MWWorld::ConstPtr ptr = sayiter->first; Stream* sound = sayiter->second.mStream.get(); if (sound->getIs3D()) { if (!ptr.isEmpty()) { MWBase::World* world = MWBase::Environment::get().getWorld(); sound->setPosition(world->getActorHeadTransform(ptr).getTrans()); } cull3DSound(sound); } if (!sound->updateFade(duration) || !mOutput->isStreamPlaying(sound)) { mOutput->finishStream(sound); sayiter = mActiveSaySounds.erase(sayiter); } else { mOutput->updateStream(sound); ++sayiter; } } TrackList::iterator trkiter = mActiveTracks.begin(); while (trkiter != mActiveTracks.end()) { Stream* sound = trkiter->get(); if (!mOutput->isStreamPlaying(sound)) { mOutput->finishStream(sound); trkiter = mActiveTracks.erase(trkiter); } else { sound->updateFade(duration); mOutput->updateStream(sound); ++trkiter; } } if (mListenerUnderwater) { // Play underwater sound (after updating sounds) if (!mUnderwaterSound) mUnderwaterSound = playSound(ESM::RefId::stringRefId("Underwater"), 1.0f, 1.0f, Type::Sfx, PlayMode::LoopNoEnv); } mOutput->finishUpdate(); } void SoundManager::updateMusic(float duration) { if (!mMusic || !mMusic->updateFade(duration) || !mOutput->isStreamPlaying(mMusic.get())) { stopMusic(); if (!mNextMusic.value().empty()) { streamMusicFull(mNextMusic); mNextMusic = VFS::Path::Normalized(); } else mMusicType = MusicType::Normal; } else { mOutput->updateStream(mMusic.get()); } } void SoundManager::update(float duration) { if (!mOutput->isInitialized() || mPlaybackPaused) return; MWBase::StateManager::State state = MWBase::Environment::get().getStateManager()->getState(); bool isMainMenu = MWBase::Environment::get().getWindowManager()->containsMode(MWGui::GM_MainMenu) && state == MWBase::StateManager::State_NoGame; if (isMainMenu && !isMusicPlaying()) { if (mVFS->exists(MWSound::titleMusic)) streamMusic(MWSound::titleMusic, MWSound::MusicType::Normal); } updateSounds(duration); if (state != MWBase::StateManager::State_NoGame) { updateRegionSound(duration); updateWaterSound(); } } void SoundManager::processChangedSettings(const Settings::CategorySettingVector& settings) { if (!mOutput->isInitialized()) return; mOutput->startUpdate(); for (SoundMap::value_type& snd : mActiveSounds) { for (SoundBufferRefPair& sndbuf : snd.second.mList) { Sound* sound = sndbuf.first.get(); sound->setBaseVolume(volumeFromType(sound->getPlayType())); mOutput->updateSound(sound); } } for (SaySoundMap::value_type& snd : mActiveSaySounds) { Stream* sound = snd.second.mStream.get(); sound->setBaseVolume(volumeFromType(sound->getPlayType())); mOutput->updateStream(sound); } for (SaySoundMap::value_type& snd : mSaySoundsQueue) { Stream* sound = snd.second.mStream.get(); sound->setBaseVolume(volumeFromType(sound->getPlayType())); mOutput->updateStream(sound); } for (const StreamPtr& sound : mActiveTracks) { sound->setBaseVolume(volumeFromType(sound->getPlayType())); mOutput->updateStream(sound.get()); } if (mMusic) { mMusic->setBaseVolume(volumeFromType(mMusic->getPlayType())); mOutput->updateStream(mMusic.get()); } mOutput->finishUpdate(); } void SoundManager::setListenerPosDir( const osg::Vec3f& pos, const osg::Vec3f& dir, const osg::Vec3f& up, bool underwater) { mListenerPos = pos; mListenerDir = dir; mListenerUp = up; mListenerUnderwater = underwater; mWaterSoundUpdater.setUnderwater(underwater); } void SoundManager::updatePtr(const MWWorld::ConstPtr& old, const MWWorld::ConstPtr& updated) { SoundMap::iterator snditer = mActiveSounds.find(old.mRef); if (snditer != mActiveSounds.end()) snditer->second.mCell = updated.mCell; if (const auto it = mSaySoundsQueue.find(old.mRef); it != mSaySoundsQueue.end()) it->second.mCell = updated.mCell; if (const auto it = mActiveSaySounds.find(old.mRef); it != mActiveSaySounds.end()) it->second.mCell = updated.mCell; } // Default readAll implementation, for decoders that can't do anything // better void Sound_Decoder::readAll(std::vector<char>& output) { size_t total = output.size(); size_t got; output.resize(total + 32768); while ((got = read(&output[total], output.size() - total)) > 0) { total += got; output.resize(total * 2); } output.resize(total); } const char* getSampleTypeName(SampleType type) { switch (type) { case SampleType_UInt8: return "U8"; case SampleType_Int16: return "S16"; case SampleType_Float32: return "Float32"; } return "(unknown sample type)"; } const char* getChannelConfigName(ChannelConfig config) { switch (config) { case ChannelConfig_Mono: return "Mono"; case ChannelConfig_Stereo: return "Stereo"; case ChannelConfig_Quad: return "Quad"; case ChannelConfig_5point1: return "5.1 Surround"; case ChannelConfig_7point1: return "7.1 Surround"; } return "(unknown channel config)"; } size_t framesToBytes(size_t frames, ChannelConfig config, SampleType type) { switch (config) { case ChannelConfig_Mono: frames *= 1; break; case ChannelConfig_Stereo: frames *= 2; break; case ChannelConfig_Quad: frames *= 4; break; case ChannelConfig_5point1: frames *= 6; break; case ChannelConfig_7point1: frames *= 8; break; } switch (type) { case SampleType_UInt8: frames *= 1; break; case SampleType_Int16: frames *= 2; break; case SampleType_Float32: frames *= 4; break; } return frames; } size_t bytesToFrames(size_t bytes, ChannelConfig config, SampleType type) { return bytes / framesToBytes(1, config, type); } void SoundManager::clear() { stopMusic(); mMusicType = MusicType::Normal; for (SoundMap::value_type& snd : mActiveSounds) { for (SoundBufferRefPair& sndbuf : snd.second.mList) { mOutput->finishSound(sndbuf.first.get()); mSoundBuffers.release(*sndbuf.second); } } mActiveSounds.clear(); mUnderwaterSound = nullptr; mNearWaterSound = nullptr; for (SaySoundMap::value_type& snd : mSaySoundsQueue) mOutput->finishStream(snd.second.mStream.get()); mSaySoundsQueue.clear(); for (SaySoundMap::value_type& snd : mActiveSaySounds) mOutput->finishStream(snd.second.mStream.get()); mActiveSaySounds.clear(); for (StreamPtr& sound : mActiveTracks) mOutput->finishStream(sound.get()); mActiveTracks.clear(); mPlaybackPaused = false; std::fill(std::begin(mPausedSoundTypes), std::end(mPausedSoundTypes), 0); } }
43,391
C++
.cpp
1,109
28.41569
120
0.579769
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,351
sound_buffer.cpp
OpenMW_openmw/apps/openmw/mwsound/sound_buffer.cpp
#include "sound_buffer.hpp" #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" #include <components/debug/debuglog.hpp> #include <components/esm3/loadsoun.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/settings/values.hpp> #include <components/vfs/pathutil.hpp> #include <algorithm> #include <cmath> namespace MWSound { namespace { struct AudioParams { float mAudioDefaultMinDistance; float mAudioDefaultMaxDistance; float mAudioMinDistanceMult; float mAudioMaxDistanceMult; }; AudioParams makeAudioParams(const MWWorld::Store<ESM::GameSetting>& settings) { AudioParams params; params.mAudioDefaultMinDistance = settings.find("fAudioDefaultMinDistance")->mValue.getFloat(); params.mAudioDefaultMaxDistance = settings.find("fAudioDefaultMaxDistance")->mValue.getFloat(); params.mAudioMinDistanceMult = settings.find("fAudioMinDistanceMult")->mValue.getFloat(); params.mAudioMaxDistanceMult = settings.find("fAudioMaxDistanceMult")->mValue.getFloat(); return params; } } SoundBufferPool::SoundBufferPool(Sound_Output& output) : mOutput(&output) , mBufferCacheMax(Settings::sound().mBufferCacheMax * 1024 * 1024) , mBufferCacheMin( std::min(static_cast<std::size_t>(Settings::sound().mBufferCacheMin) * 1024 * 1024, mBufferCacheMax)) { } SoundBufferPool::~SoundBufferPool() { clear(); } Sound_Buffer* SoundBufferPool::lookup(const ESM::RefId& soundId) const { const auto it = mBufferNameMap.find(soundId); if (it != mBufferNameMap.end()) { Sound_Buffer* sfx = it->second; if (sfx->getHandle() != nullptr) return sfx; } return nullptr; } Sound_Buffer* SoundBufferPool::lookup(std::string_view fileName) const { const auto it = mBufferFileNameMap.find(std::string(fileName)); if (it != mBufferFileNameMap.end()) { Sound_Buffer* sfx = it->second; if (sfx->getHandle() != nullptr) return sfx; } return nullptr; } Sound_Buffer* SoundBufferPool::loadSfx(Sound_Buffer* sfx) { if (sfx->getHandle() != nullptr) return sfx; auto [handle, size] = mOutput->loadSound(sfx->getResourceName()); if (handle == nullptr) return {}; sfx->mHandle = handle; mBufferCacheSize += size; if (mBufferCacheSize > mBufferCacheMax) { unloadUnused(); if (!mUnusedBuffers.empty() && mBufferCacheSize > mBufferCacheMax) Log(Debug::Warning) << "No unused sound buffers to free, using " << mBufferCacheSize << " bytes!"; } mUnusedBuffers.push_front(sfx); return sfx; } Sound_Buffer* SoundBufferPool::load(const ESM::RefId& soundId) { if (mBufferNameMap.empty()) { for (const ESM::Sound& sound : MWBase::Environment::get().getESMStore()->get<ESM::Sound>()) insertSound(sound.mId, sound); } Sound_Buffer* sfx; const auto it = mBufferNameMap.find(soundId); if (it != mBufferNameMap.end()) sfx = it->second; else { const ESM::Sound* sound = MWBase::Environment::get().getESMStore()->get<ESM::Sound>().search(soundId); if (sound == nullptr) return {}; sfx = insertSound(soundId, *sound); } return loadSfx(sfx); } Sound_Buffer* SoundBufferPool::load(std::string_view fileName) { Sound_Buffer* sfx; const auto it = mBufferFileNameMap.find(std::string(fileName)); if (it != mBufferFileNameMap.end()) sfx = it->second; else { sfx = insertSound(fileName); } return loadSfx(sfx); } void SoundBufferPool::clear() { for (auto& sfx : mSoundBuffers) { if (sfx.mHandle) mOutput->unloadSound(sfx.mHandle); sfx.mHandle = nullptr; } mBufferFileNameMap.clear(); mBufferNameMap.clear(); mUnusedBuffers.clear(); } Sound_Buffer* SoundBufferPool::insertSound(std::string_view fileName) { static const AudioParams audioParams = makeAudioParams(MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>()); float volume = 1.f; float min = std::max(audioParams.mAudioDefaultMinDistance * audioParams.mAudioMinDistanceMult, 1.f); float max = std::max(min, audioParams.mAudioDefaultMaxDistance * audioParams.mAudioMaxDistanceMult); min = std::max(min, 1.0f); max = std::max(min, max); Sound_Buffer& sfx = mSoundBuffers.emplace_back(fileName, volume, min, max); mBufferFileNameMap.emplace(fileName, &sfx); return &sfx; } Sound_Buffer* SoundBufferPool::insertSound(const ESM::RefId& soundId, const ESM::Sound& sound) { static const AudioParams audioParams = makeAudioParams(MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>()); float volume = static_cast<float>(std::pow(10.0, (sound.mData.mVolume / 255.0 * 3348.0 - 3348.0) / 2000.0)); float min = sound.mData.mMinRange; float max = sound.mData.mMaxRange; if (min == 0 && max == 0) { min = audioParams.mAudioDefaultMinDistance; max = audioParams.mAudioDefaultMaxDistance; } min *= audioParams.mAudioMinDistanceMult; max *= audioParams.mAudioMaxDistanceMult; min = std::max(min, 1.0f); max = std::max(min, max); Sound_Buffer& sfx = mSoundBuffers.emplace_back( Misc::ResourceHelpers::correctSoundPath(VFS::Path::Normalized(sound.mSound)), volume, min, max); mBufferNameMap.emplace(soundId, &sfx); return &sfx; } void SoundBufferPool::unloadUnused() { while (!mUnusedBuffers.empty() && mBufferCacheSize > mBufferCacheMin) { Sound_Buffer* const unused = mUnusedBuffers.back(); mBufferCacheSize -= mOutput->unloadSound(unused->getHandle()); unused->mHandle = nullptr; mUnusedBuffers.pop_back(); } } }
6,498
C++
.cpp
171
29.093567
116
0.615446
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,352
openal_output.cpp
OpenMW_openmw/apps/openmw/mwsound/openal_output.cpp
#include <algorithm> #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <cstring> #include <memory> #include <string_view> #include <thread> #include <vector> #include <cstdint> #include <components/debug/debuglog.hpp> #include <components/misc/constants.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/thread.hpp> #include <components/vfs/manager.hpp> #include "loudness.hpp" #include "openal_output.hpp" #include "sound.hpp" #include "sound_decoder.hpp" #include "soundmanagerimp.hpp" #include "efx-presets.h" #ifndef ALC_ALL_DEVICES_SPECIFIER #define ALC_ALL_DEVICES_SPECIFIER 0x1013 #endif #define MAKE_PTRID(id) ((void*)(uintptr_t)id) #define GET_PTRID(ptr) ((ALuint)(uintptr_t)ptr) namespace { const int sLoudnessFPS = 20; // loudness values per second of audio ALCenum checkALCError(ALCdevice* device, const char* func, int line) { ALCenum err = alcGetError(device); if (err != ALC_NO_ERROR) Log(Debug::Error) << "ALC error " << alcGetString(device, err) << " (" << err << ") @ " << func << ":" << line; return err; } #define getALCError(d) checkALCError((d), __FUNCTION__, __LINE__) ALenum checkALError(const char* func, int line) { ALenum err = alGetError(); if (err != AL_NO_ERROR) Log(Debug::Error) << "AL error " << alGetString(err) << " (" << err << ") @ " << func << ":" << line; return err; } #define getALError() checkALError(__FUNCTION__, __LINE__) // Helper to get an OpenAL extension function template <typename T, typename R> void convertPointer(T& dest, R src) { memcpy(&dest, &src, sizeof(src)); } template <typename T> void getALCFunc(T& func, ALCdevice* device, const char* name) { void* funcPtr = alcGetProcAddress(device, name); convertPointer(func, funcPtr); } template <typename T> void getALFunc(T& func, const char* name) { void* funcPtr = alGetProcAddress(name); convertPointer(func, funcPtr); } // Effect objects LPALGENEFFECTS alGenEffects; LPALDELETEEFFECTS alDeleteEffects; LPALISEFFECT alIsEffect; LPALEFFECTI alEffecti; LPALEFFECTIV alEffectiv; LPALEFFECTF alEffectf; LPALEFFECTFV alEffectfv; LPALGETEFFECTI alGetEffecti; LPALGETEFFECTIV alGetEffectiv; LPALGETEFFECTF alGetEffectf; LPALGETEFFECTFV alGetEffectfv; // Filter objects LPALGENFILTERS alGenFilters; LPALDELETEFILTERS alDeleteFilters; LPALISFILTER alIsFilter; LPALFILTERI alFilteri; LPALFILTERIV alFilteriv; LPALFILTERF alFilterf; LPALFILTERFV alFilterfv; LPALGETFILTERI alGetFilteri; LPALGETFILTERIV alGetFilteriv; LPALGETFILTERF alGetFilterf; LPALGETFILTERFV alGetFilterfv; // Auxiliary slot objects LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots; LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots; LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot; LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti; LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv; LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf; LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv; LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti; LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv; LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf; LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv; LPALEVENTCONTROLSOFT alEventControlSOFT; LPALEVENTCALLBACKSOFT alEventCallbackSOFT; LPALCREOPENDEVICESOFT alcReopenDeviceSOFT; void LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES& props) { ALint type = AL_NONE; alGetEffecti(effect, AL_EFFECT_TYPE, &type); if (type == AL_EFFECT_EAXREVERB) { alEffectf(effect, AL_EAXREVERB_DIFFUSION, props.flDiffusion); alEffectf(effect, AL_EAXREVERB_DENSITY, props.flDensity); alEffectf(effect, AL_EAXREVERB_GAIN, props.flGain); alEffectf(effect, AL_EAXREVERB_GAINHF, props.flGainHF); alEffectf(effect, AL_EAXREVERB_GAINLF, props.flGainLF); alEffectf(effect, AL_EAXREVERB_DECAY_TIME, props.flDecayTime); alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, props.flDecayHFRatio); alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, props.flDecayLFRatio); alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, props.flReflectionsGain); alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, props.flReflectionsDelay); alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, props.flReflectionsPan); alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, props.flLateReverbGain); alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, props.flLateReverbDelay); alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, props.flLateReverbPan); alEffectf(effect, AL_EAXREVERB_ECHO_TIME, props.flEchoTime); alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, props.flEchoDepth); alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, props.flModulationTime); alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, props.flModulationDepth); alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, props.flAirAbsorptionGainHF); alEffectf(effect, AL_EAXREVERB_HFREFERENCE, props.flHFReference); alEffectf(effect, AL_EAXREVERB_LFREFERENCE, props.flLFReference); alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, props.flRoomRolloffFactor); alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, props.iDecayHFLimit ? AL_TRUE : AL_FALSE); } else if (type == AL_EFFECT_REVERB) { alEffectf(effect, AL_REVERB_DIFFUSION, props.flDiffusion); alEffectf(effect, AL_REVERB_DENSITY, props.flDensity); alEffectf(effect, AL_REVERB_GAIN, props.flGain); alEffectf(effect, AL_REVERB_GAINHF, props.flGainHF); alEffectf(effect, AL_REVERB_DECAY_TIME, props.flDecayTime); alEffectf(effect, AL_REVERB_DECAY_HFRATIO, props.flDecayHFRatio); alEffectf(effect, AL_REVERB_REFLECTIONS_GAIN, props.flReflectionsGain); alEffectf(effect, AL_REVERB_REFLECTIONS_DELAY, props.flReflectionsDelay); alEffectf(effect, AL_REVERB_LATE_REVERB_GAIN, props.flLateReverbGain); alEffectf(effect, AL_REVERB_LATE_REVERB_DELAY, props.flLateReverbDelay); alEffectf(effect, AL_REVERB_AIR_ABSORPTION_GAINHF, props.flAirAbsorptionGainHF); alEffectf(effect, AL_REVERB_ROOM_ROLLOFF_FACTOR, props.flRoomRolloffFactor); alEffecti(effect, AL_REVERB_DECAY_HFLIMIT, props.iDecayHFLimit ? AL_TRUE : AL_FALSE); } getALError(); } std::basic_string_view<ALCchar> getDeviceName(ALCdevice* device) { const ALCchar* name = nullptr; if (alcIsExtensionPresent(device, "ALC_ENUMERATE_ALL_EXT")) name = alcGetString(device, ALC_ALL_DEVICES_SPECIFIER); if (alcGetError(device) != AL_NO_ERROR || !name) name = alcGetString(device, ALC_DEVICE_SPECIFIER); if (name == nullptr) // Prevent assigning nullptr to std::string return {}; return name; } } namespace MWSound { static ALenum getALFormat(ChannelConfig chans, SampleType type) { struct FormatEntry { ALenum format; ChannelConfig chans; SampleType type; }; struct FormatEntryExt { const char name[32]; ChannelConfig chans; SampleType type; }; static const std::array<FormatEntry, 4> fmtlist{ { { AL_FORMAT_MONO16, ChannelConfig_Mono, SampleType_Int16 }, { AL_FORMAT_MONO8, ChannelConfig_Mono, SampleType_UInt8 }, { AL_FORMAT_STEREO16, ChannelConfig_Stereo, SampleType_Int16 }, { AL_FORMAT_STEREO8, ChannelConfig_Stereo, SampleType_UInt8 }, } }; for (auto& fmt : fmtlist) { if (fmt.chans == chans && fmt.type == type) return fmt.format; } if (alIsExtensionPresent("AL_EXT_MCFORMATS")) { static const std::array<FormatEntryExt, 6> mcfmtlist{ { { "AL_FORMAT_QUAD16", ChannelConfig_Quad, SampleType_Int16 }, { "AL_FORMAT_QUAD8", ChannelConfig_Quad, SampleType_UInt8 }, { "AL_FORMAT_51CHN16", ChannelConfig_5point1, SampleType_Int16 }, { "AL_FORMAT_51CHN8", ChannelConfig_5point1, SampleType_UInt8 }, { "AL_FORMAT_71CHN16", ChannelConfig_7point1, SampleType_Int16 }, { "AL_FORMAT_71CHN8", ChannelConfig_7point1, SampleType_UInt8 }, } }; for (auto& fmt : mcfmtlist) { if (fmt.chans == chans && fmt.type == type) { ALenum format = alGetEnumValue(fmt.name); if (format != 0 && format != -1) return format; } } } if (alIsExtensionPresent("AL_EXT_FLOAT32")) { static const std::array<FormatEntryExt, 2> fltfmtlist{ { { "AL_FORMAT_MONO_FLOAT32", ChannelConfig_Mono, SampleType_Float32 }, { "AL_FORMAT_STEREO_FLOAT32", ChannelConfig_Stereo, SampleType_Float32 }, } }; for (auto& fmt : fltfmtlist) { if (fmt.chans == chans && fmt.type == type) { ALenum format = alGetEnumValue(fmt.name); if (format != 0 && format != -1) return format; } } if (alIsExtensionPresent("AL_EXT_MCFORMATS")) { static const std::array<FormatEntryExt, 3> fltmcfmtlist{ { { "AL_FORMAT_QUAD32", ChannelConfig_Quad, SampleType_Float32 }, { "AL_FORMAT_51CHN32", ChannelConfig_5point1, SampleType_Float32 }, { "AL_FORMAT_71CHN32", ChannelConfig_7point1, SampleType_Float32 }, } }; for (auto& fmt : fltmcfmtlist) { if (fmt.chans == chans && fmt.type == type) { ALenum format = alGetEnumValue(fmt.name); if (format != 0 && format != -1) return format; } } } } Log(Debug::Warning) << "Unsupported sound format (" << getChannelConfigName(chans) << ", " << getSampleTypeName(type) << ")"; return AL_NONE; } // // A streaming OpenAL sound. // class OpenAL_SoundStream { static const ALfloat sBufferLength; private: ALuint mSource; std::array<ALuint, 6> mBuffers; ALint mCurrentBufIdx; ALenum mFormat; ALsizei mSampleRate; ALuint mBufferSize; ALuint mFrameSize; ALint mSilence; DecoderPtr mDecoder; std::unique_ptr<Sound_Loudness> mLoudnessAnalyzer; std::atomic<bool> mIsFinished; void updateAll(bool local); OpenAL_SoundStream(const OpenAL_SoundStream& rhs); OpenAL_SoundStream& operator=(const OpenAL_SoundStream& rhs); friend class OpenAL_Output; public: OpenAL_SoundStream(ALuint src, DecoderPtr decoder); ~OpenAL_SoundStream(); bool init(bool getLoudnessData = false); bool isPlaying(); double getStreamDelay() const; double getStreamOffset() const; float getCurrentLoudness() const; bool process(); ALint refillQueue(); }; const ALfloat OpenAL_SoundStream::sBufferLength = 0.125f; // // A background streaming thread (keeps active streams processed) // struct OpenAL_Output::StreamThread { std::vector<OpenAL_SoundStream*> mStreams; std::atomic<bool> mQuitNow; std::mutex mMutex; std::condition_variable mCondVar; std::thread mThread; StreamThread() : mQuitNow(false) , mThread([this] { run(); }) { } ~StreamThread() { mQuitNow = true; mMutex.lock(); mMutex.unlock(); mCondVar.notify_all(); mThread.join(); } // thread entry point void run() { std::unique_lock<std::mutex> lock(mMutex); while (!mQuitNow) { auto iter = mStreams.begin(); while (iter != mStreams.end()) { if ((*iter)->process() == false) iter = mStreams.erase(iter); else ++iter; } mCondVar.wait_for(lock, std::chrono::milliseconds(50)); } } void add(OpenAL_SoundStream* stream) { std::lock_guard<std::mutex> lock(mMutex); if (std::find(mStreams.begin(), mStreams.end(), stream) == mStreams.end()) { mStreams.push_back(stream); mCondVar.notify_all(); } } void remove(OpenAL_SoundStream* stream) { std::lock_guard<std::mutex> lock(mMutex); auto iter = std::find(mStreams.begin(), mStreams.end(), stream); if (iter != mStreams.end()) mStreams.erase(iter); } void removeAll() { std::lock_guard<std::mutex> lock(mMutex); mStreams.clear(); } StreamThread(const StreamThread& rhs) = delete; StreamThread& operator=(const StreamThread& rhs) = delete; }; class OpenAL_Output::DefaultDeviceThread { public: std::basic_string<ALCchar> mCurrentName; private: OpenAL_Output& mOutput; std::atomic<bool> mQuitNow; std::mutex mMutex; std::condition_variable mCondVar; std::thread mThread; DefaultDeviceThread(const DefaultDeviceThread&) = delete; DefaultDeviceThread& operator=(const DefaultDeviceThread&) = delete; void run() { Misc::setCurrentThreadIdlePriority(); std::unique_lock<std::mutex> lock(mMutex); while (!mQuitNow) { { const std::lock_guard<std::mutex> openLock(mOutput.mReopenMutex); auto defaultName = getDeviceName(nullptr); if (mCurrentName != defaultName) { Log(Debug::Info) << "Default audio device changed"; ALCboolean reopened = alcReopenDeviceSOFT(mOutput.mDevice, nullptr, mOutput.mContextAttributes.data()); if (reopened == AL_FALSE) { mCurrentName = defaultName; Log(Debug::Warning) << "Failed to switch to new audio device"; } else mCurrentName = getDeviceName(mOutput.mDevice); } } mCondVar.wait_for(lock, std::chrono::seconds(2)); } } public: DefaultDeviceThread(OpenAL_Output& output, std::basic_string_view<ALCchar> name = {}) : mCurrentName(name) , mOutput(output) , mQuitNow(false) , mThread([this] { run(); }) { } ~DefaultDeviceThread() { mQuitNow = true; mMutex.lock(); mMutex.unlock(); mCondVar.notify_all(); mThread.join(); } }; OpenAL_SoundStream::OpenAL_SoundStream(ALuint src, DecoderPtr decoder) : mSource(src) , mCurrentBufIdx(0) , mFormat(AL_NONE) , mSampleRate(0) , mBufferSize(0) , mFrameSize(0) , mSilence(0) , mDecoder(std::move(decoder)) , mLoudnessAnalyzer(nullptr) , mIsFinished(true) { mBuffers.fill(0); } OpenAL_SoundStream::~OpenAL_SoundStream() { if (mBuffers[0] && alIsBuffer(mBuffers[0])) alDeleteBuffers(mBuffers.size(), mBuffers.data()); alGetError(); mDecoder->close(); } bool OpenAL_SoundStream::init(bool getLoudnessData) { alGenBuffers(mBuffers.size(), mBuffers.data()); ALenum err = getALError(); if (err != AL_NO_ERROR) return false; ChannelConfig chans; SampleType type; try { mDecoder->getInfo(&mSampleRate, &chans, &type); mFormat = getALFormat(chans, type); } catch (std::exception& e) { Log(Debug::Error) << "Failed to get stream info: " << e.what(); return false; } switch (type) { case SampleType_UInt8: mSilence = 0x80; break; case SampleType_Int16: mSilence = 0x00; break; case SampleType_Float32: mSilence = 0x00; break; } mFrameSize = framesToBytes(1, chans, type); mBufferSize = static_cast<ALuint>(sBufferLength * mSampleRate); mBufferSize *= mFrameSize; if (getLoudnessData) mLoudnessAnalyzer = std::make_unique<Sound_Loudness>(sLoudnessFPS, mSampleRate, chans, type); mIsFinished = false; return true; } bool OpenAL_SoundStream::isPlaying() { ALint state; alGetSourcei(mSource, AL_SOURCE_STATE, &state); getALError(); if (state == AL_PLAYING || state == AL_PAUSED) return true; return !mIsFinished; } double OpenAL_SoundStream::getStreamDelay() const { ALint state = AL_STOPPED; double d = 0.0; ALint offset; alGetSourcei(mSource, AL_SAMPLE_OFFSET, &offset); alGetSourcei(mSource, AL_SOURCE_STATE, &state); if (state == AL_PLAYING || state == AL_PAUSED) { ALint queued; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); ALint inqueue = mBufferSize / mFrameSize * queued - offset; d = (double)inqueue / (double)mSampleRate; } getALError(); return d; } double OpenAL_SoundStream::getStreamOffset() const { ALint state = AL_STOPPED; ALint offset; double t; alGetSourcei(mSource, AL_SAMPLE_OFFSET, &offset); alGetSourcei(mSource, AL_SOURCE_STATE, &state); if (state == AL_PLAYING || state == AL_PAUSED) { ALint queued; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); ALint inqueue = mBufferSize / mFrameSize * queued - offset; t = (double)(mDecoder->getSampleOffset() - inqueue) / (double)mSampleRate; } else { /* Underrun, or not started yet. The decoder offset is where we'll play * next. */ t = (double)mDecoder->getSampleOffset() / (double)mSampleRate; } getALError(); return t; } float OpenAL_SoundStream::getCurrentLoudness() const { if (!mLoudnessAnalyzer.get()) return 0.f; float time = getStreamOffset(); return mLoudnessAnalyzer->getLoudnessAtTime(time); } bool OpenAL_SoundStream::process() { try { if (refillQueue() > 0) { ALint state; alGetSourcei(mSource, AL_SOURCE_STATE, &state); if (state != AL_PLAYING && state != AL_PAUSED) { // Ensure all processed buffers are removed so we don't replay them. refillQueue(); alSourcePlay(mSource); } } } catch (const std::exception& e) { Log(Debug::Error) << "Error updating stream \"" << mDecoder->getName() << "\": " << e.what(); mIsFinished = true; } return !mIsFinished; } ALint OpenAL_SoundStream::refillQueue() { ALint processed; alGetSourcei(mSource, AL_BUFFERS_PROCESSED, &processed); while (processed > 0) { ALuint buf; alSourceUnqueueBuffers(mSource, 1, &buf); --processed; } ALint queued; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); if (!mIsFinished && (ALuint)queued < mBuffers.size()) { std::vector<char> data(mBufferSize); for (; !mIsFinished && (ALuint)queued < mBuffers.size(); ++queued) { size_t got = mDecoder->read(data.data(), data.size()); if (got < data.size()) { mIsFinished = true; std::fill(data.begin() + got, data.end(), mSilence); } if (got > 0) { if (mLoudnessAnalyzer.get()) mLoudnessAnalyzer->analyzeLoudness(data); ALuint bufid = mBuffers[mCurrentBufIdx]; alBufferData(bufid, mFormat, data.data(), data.size(), mSampleRate); alSourceQueueBuffers(mSource, 1, &bufid); mCurrentBufIdx = (mCurrentBufIdx + 1) % mBuffers.size(); } } } return queued; } // // An OpenAL output device // std::vector<std::string> OpenAL_Output::enumerate() { std::vector<std::string> devlist; const ALCchar* devnames; if (alcIsExtensionPresent(nullptr, "ALC_ENUMERATE_ALL_EXT")) devnames = alcGetString(nullptr, ALC_ALL_DEVICES_SPECIFIER); else devnames = alcGetString(nullptr, ALC_DEVICE_SPECIFIER); while (devnames && *devnames) { devlist.emplace_back(devnames); devnames += strlen(devnames) + 1; } return devlist; } void OpenAL_Output::eventCallback( ALenum eventType, ALuint object, ALuint param, ALsizei length, const ALchar* message, void* userParam) { if (eventType == AL_EVENT_TYPE_DISCONNECTED_SOFT) static_cast<OpenAL_Output*>(userParam)->onDisconnect(); } void OpenAL_Output::onDisconnect() { if (!mInitialized || !alcReopenDeviceSOFT) return; const std::lock_guard<std::mutex> lock(mReopenMutex); Log(Debug::Warning) << "Audio device disconnected, attempting to reopen..."; ALCboolean reopened = alcReopenDeviceSOFT(mDevice, mDeviceName.c_str(), mContextAttributes.data()); if (reopened == AL_FALSE && !mDeviceName.empty()) { reopened = alcReopenDeviceSOFT(mDevice, nullptr, mContextAttributes.data()); if (reopened == AL_TRUE && !mDefaultDeviceThread) mDefaultDeviceThread = std::make_unique<DefaultDeviceThread>(*this); } if (reopened == AL_FALSE) Log(Debug::Error) << "Failed to reopen audio device"; else { Log(Debug::Info) << "Reopened audio device"; if (mDefaultDeviceThread) mDefaultDeviceThread->mCurrentName = getDeviceName(mDevice); } } bool OpenAL_Output::init(const std::string& devname, const std::string& hrtfname, HrtfMode hrtfmode) { deinit(); std::lock_guard<std::mutex> lock(mReopenMutex); Log(Debug::Info) << "Initializing OpenAL..."; mDeviceName = devname; mDevice = alcOpenDevice(devname.c_str()); if (!mDevice && !devname.empty()) { Log(Debug::Warning) << "Failed to open \"" << devname << "\", trying default"; mDevice = alcOpenDevice(nullptr); mDeviceName.clear(); } if (!mDevice) { Log(Debug::Error) << "Failed to open default audio device"; return false; } auto name = getDeviceName(mDevice); Log(Debug::Info) << "Opened \"" << name << "\""; ALCint major = 0, minor = 0; alcGetIntegerv(mDevice, ALC_MAJOR_VERSION, 1, &major); alcGetIntegerv(mDevice, ALC_MINOR_VERSION, 1, &minor); Log(Debug::Info) << " ALC Version: " << major << "." << minor << "\n" << " ALC Extensions: " << alcGetString(mDevice, ALC_EXTENSIONS); ALC.EXT_EFX = alcIsExtensionPresent(mDevice, "ALC_EXT_EFX"); ALC.SOFT_HRTF = alcIsExtensionPresent(mDevice, "ALC_SOFT_HRTF"); mContextAttributes.clear(); mContextAttributes.reserve(15); if (ALC.SOFT_HRTF) { LPALCGETSTRINGISOFT alcGetStringiSOFT = nullptr; getALCFunc(alcGetStringiSOFT, mDevice, "alcGetStringiSOFT"); mContextAttributes.push_back(ALC_HRTF_SOFT); mContextAttributes.push_back(hrtfmode == HrtfMode::Disable ? ALC_FALSE : hrtfmode == HrtfMode::Enable ? ALC_TRUE : /*hrtfmode == HrtfMode::Auto ?*/ ALC_DONT_CARE_SOFT); if (!hrtfname.empty()) { ALCint index = -1; ALCint num_hrtf; alcGetIntegerv(mDevice, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf); for (ALCint i = 0; i < num_hrtf; ++i) { const ALCchar* entry = alcGetStringiSOFT(mDevice, ALC_HRTF_SPECIFIER_SOFT, i); if (hrtfname == entry) { index = i; break; } } if (index < 0) Log(Debug::Warning) << "Failed to find HRTF \"" << hrtfname << "\", using default"; else { mContextAttributes.push_back(ALC_HRTF_ID_SOFT); mContextAttributes.push_back(index); } } } mContextAttributes.push_back(0); mContext = alcCreateContext(mDevice, mContextAttributes.data()); if (!mContext || alcMakeContextCurrent(mContext) == ALC_FALSE) { Log(Debug::Error) << "Failed to setup audio context: " << alcGetString(mDevice, alcGetError(mDevice)); if (mContext) alcDestroyContext(mContext); mContext = nullptr; alcCloseDevice(mDevice); mDevice = nullptr; return false; } Log(Debug::Info) << " Vendor: " << alGetString(AL_VENDOR) << "\n" << " Renderer: " << alGetString(AL_RENDERER) << "\n" << " Version: " << alGetString(AL_VERSION) << "\n" << " Extensions: " << alGetString(AL_EXTENSIONS); if (alIsExtensionPresent("AL_SOFT_events")) { getALFunc(alEventControlSOFT, "alEventControlSOFT"); getALFunc(alEventCallbackSOFT, "alEventCallbackSOFT"); } if (alcIsExtensionPresent(mDevice, "ALC_SOFT_reopen_device")) getALFunc(alcReopenDeviceSOFT, "alcReopenDeviceSOFT"); if (alEventControlSOFT) { static const std::array<ALenum, 1> events{ { AL_EVENT_TYPE_DISCONNECTED_SOFT } }; alEventControlSOFT(events.size(), events.data(), AL_TRUE); alEventCallbackSOFT(&OpenAL_Output::eventCallback, this); } else Log(Debug::Warning) << "Cannot detect audio device changes"; if (mDeviceName.empty() && !name.empty()) { // If we opened the default device, switch devices if a new default is selected if (alcReopenDeviceSOFT) mDefaultDeviceThread = std::make_unique<DefaultDeviceThread>(*this, name); else Log(Debug::Warning) << "Cannot switch audio devices if the default changes"; } if (!ALC.SOFT_HRTF) Log(Debug::Warning) << "HRTF status unavailable"; else { ALCint hrtf_state; alcGetIntegerv(mDevice, ALC_HRTF_SOFT, 1, &hrtf_state); if (!hrtf_state) Log(Debug::Info) << "HRTF disabled"; else { const ALCchar* hrtf = alcGetString(mDevice, ALC_HRTF_SPECIFIER_SOFT); Log(Debug::Info) << "Enabled HRTF " << hrtf; } } AL.SOFT_source_spatialize = alIsExtensionPresent("AL_SOFT_source_spatialize"); ALCuint maxtotal; ALCint maxmono = 0, maxstereo = 0; alcGetIntegerv(mDevice, ALC_MONO_SOURCES, 1, &maxmono); alcGetIntegerv(mDevice, ALC_STEREO_SOURCES, 1, &maxstereo); if (getALCError(mDevice) != ALC_NO_ERROR) maxtotal = 256; else { maxtotal = std::min<ALCuint>(maxmono + maxstereo, 256); if (maxtotal == 0) // workaround for broken implementations maxtotal = 256; } for (size_t i = 0; i < maxtotal; i++) { ALuint src = 0; alGenSources(1, &src); if (alGetError() != AL_NO_ERROR) break; mFreeSources.push_back(src); } if (mFreeSources.empty()) { Log(Debug::Warning) << "Could not allocate any sound sourcess"; alcMakeContextCurrent(nullptr); alcDestroyContext(mContext); mContext = nullptr; alcCloseDevice(mDevice); mDevice = nullptr; return false; } Log(Debug::Info) << "Allocated " << mFreeSources.size() << " sound sources"; if (ALC.EXT_EFX) { #define LOAD_FUNC(x) getALFunc(x, #x) LOAD_FUNC(alGenEffects); LOAD_FUNC(alDeleteEffects); LOAD_FUNC(alIsEffect); LOAD_FUNC(alEffecti); LOAD_FUNC(alEffectiv); LOAD_FUNC(alEffectf); LOAD_FUNC(alEffectfv); LOAD_FUNC(alGetEffecti); LOAD_FUNC(alGetEffectiv); LOAD_FUNC(alGetEffectf); LOAD_FUNC(alGetEffectfv); LOAD_FUNC(alGenFilters); LOAD_FUNC(alDeleteFilters); LOAD_FUNC(alIsFilter); LOAD_FUNC(alFilteri); LOAD_FUNC(alFilteriv); LOAD_FUNC(alFilterf); LOAD_FUNC(alFilterfv); LOAD_FUNC(alGetFilteri); LOAD_FUNC(alGetFilteriv); LOAD_FUNC(alGetFilterf); LOAD_FUNC(alGetFilterfv); LOAD_FUNC(alGenAuxiliaryEffectSlots); LOAD_FUNC(alDeleteAuxiliaryEffectSlots); LOAD_FUNC(alIsAuxiliaryEffectSlot); LOAD_FUNC(alAuxiliaryEffectSloti); LOAD_FUNC(alAuxiliaryEffectSlotiv); LOAD_FUNC(alAuxiliaryEffectSlotf); LOAD_FUNC(alAuxiliaryEffectSlotfv); LOAD_FUNC(alGetAuxiliaryEffectSloti); LOAD_FUNC(alGetAuxiliaryEffectSlotiv); LOAD_FUNC(alGetAuxiliaryEffectSlotf); LOAD_FUNC(alGetAuxiliaryEffectSlotfv); #undef LOAD_FUNC if (getALError() != AL_NO_ERROR) { ALC.EXT_EFX = false; goto skip_efx; } alGenFilters(1, &mWaterFilter); if (alGetError() == AL_NO_ERROR) { alFilteri(mWaterFilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS); if (alGetError() == AL_NO_ERROR) { Log(Debug::Info) << "Low-pass filter supported"; alFilterf(mWaterFilter, AL_LOWPASS_GAIN, 0.9f); alFilterf(mWaterFilter, AL_LOWPASS_GAINHF, 0.125f); } else { alDeleteFilters(1, &mWaterFilter); mWaterFilter = 0; } alGetError(); } alGenAuxiliaryEffectSlots(1, &mEffectSlot); alGetError(); alGenEffects(1, &mDefaultEffect); if (alGetError() == AL_NO_ERROR) { alEffecti(mDefaultEffect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB); if (alGetError() == AL_NO_ERROR) Log(Debug::Info) << "EAX Reverb supported"; else { alEffecti(mDefaultEffect, AL_EFFECT_TYPE, AL_EFFECT_REVERB); if (alGetError() == AL_NO_ERROR) Log(Debug::Info) << "Standard Reverb supported"; } EFXEAXREVERBPROPERTIES props = EFX_REVERB_PRESET_LIVINGROOM; props.flGain = 0.0f; LoadEffect(mDefaultEffect, props); } alGenEffects(1, &mWaterEffect); if (alGetError() == AL_NO_ERROR) { alEffecti(mWaterEffect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB); if (alGetError() != AL_NO_ERROR) { alEffecti(mWaterEffect, AL_EFFECT_TYPE, AL_EFFECT_REVERB); alGetError(); } LoadEffect(mWaterEffect, EFX_REVERB_PRESET_UNDERWATER); } alListenerf(AL_METERS_PER_UNIT, 1.0f / Constants::UnitsPerMeter); } skip_efx: alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); // Speed of sound is in units per second. Take the sound speed in air (assumed // meters per second), multiply by the units per meter to get the speed in u/s. alSpeedOfSound(Constants::SoundSpeedInAir * Constants::UnitsPerMeter); alGetError(); mInitialized = true; return true; } void OpenAL_Output::deinit() { mStreamThread->removeAll(); mDefaultDeviceThread.reset(); for (ALuint source : mFreeSources) alDeleteSources(1, &source); mFreeSources.clear(); if (mEffectSlot) alDeleteAuxiliaryEffectSlots(1, &mEffectSlot); mEffectSlot = 0; if (mDefaultEffect) alDeleteEffects(1, &mDefaultEffect); mDefaultEffect = 0; if (mWaterEffect) alDeleteEffects(1, &mWaterEffect); mWaterEffect = 0; if (mWaterFilter) alDeleteFilters(1, &mWaterFilter); mWaterFilter = 0; if (alEventCallbackSOFT) alEventCallbackSOFT(nullptr, nullptr); alcMakeContextCurrent(nullptr); if (mContext) alcDestroyContext(mContext); mContext = nullptr; if (mDevice) alcCloseDevice(mDevice); mDevice = nullptr; mInitialized = false; } std::vector<std::string> OpenAL_Output::enumerateHrtf() { std::vector<std::string> ret; if (!mDevice || !ALC.SOFT_HRTF) return ret; LPALCGETSTRINGISOFT alcGetStringiSOFT = nullptr; getALCFunc(alcGetStringiSOFT, mDevice, "alcGetStringiSOFT"); ALCint num_hrtf; alcGetIntegerv(mDevice, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf); ret.reserve(num_hrtf); for (ALCint i = 0; i < num_hrtf; ++i) { const ALCchar* entry = alcGetStringiSOFT(mDevice, ALC_HRTF_SPECIFIER_SOFT, i); ret.emplace_back(entry); } return ret; } std::pair<Sound_Handle, size_t> OpenAL_Output::loadSound(VFS::Path::NormalizedView fname) { getALError(); std::vector<char> data; ALenum format = AL_NONE; int srate = 0; try { DecoderPtr decoder = mManager.getDecoder(); decoder->open(Misc::ResourceHelpers::correctSoundPath(fname, *decoder->mResourceMgr)); ChannelConfig chans; SampleType type; decoder->getInfo(&srate, &chans, &type); format = getALFormat(chans, type); if (format) decoder->readAll(data); } catch (std::exception& e) { Log(Debug::Error) << "Failed to load audio from " << fname << ": " << e.what(); } if (data.empty()) { // If we failed to get any usable audio, substitute with silence. format = AL_FORMAT_MONO8; srate = 8000; data.assign(8000, -128); } ALint size; ALuint buf = 0; alGenBuffers(1, &buf); alBufferData(buf, format, data.data(), data.size(), srate); alGetBufferi(buf, AL_SIZE, &size); if (getALError() != AL_NO_ERROR) { if (buf && alIsBuffer(buf)) alDeleteBuffers(1, &buf); getALError(); return std::make_pair(nullptr, 0); } return std::make_pair(MAKE_PTRID(buf), size); } size_t OpenAL_Output::unloadSound(Sound_Handle data) { ALuint buffer = GET_PTRID(data); if (!buffer) return 0; // Make sure no sources are playing this buffer before unloading it. SoundVec::const_iterator iter = mActiveSounds.begin(); for (; iter != mActiveSounds.end(); ++iter) { if (!(*iter)->mHandle) continue; ALuint source = GET_PTRID((*iter)->mHandle); ALint srcbuf; alGetSourcei(source, AL_BUFFER, &srcbuf); if ((ALuint)srcbuf == buffer) { alSourceStop(source); alSourcei(source, AL_BUFFER, 0); } } ALint size = 0; alGetBufferi(buffer, AL_SIZE, &size); alDeleteBuffers(1, &buffer); getALError(); return size; } void OpenAL_Output::initCommon2D( ALuint source, const osg::Vec3f& pos, ALfloat gain, ALfloat pitch, bool loop, bool useenv) { alSourcef(source, AL_REFERENCE_DISTANCE, 1.0f); alSourcef(source, AL_MAX_DISTANCE, 1000.0f); alSourcef(source, AL_ROLLOFF_FACTOR, 0.0f); alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE); alSourcei(source, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); if (AL.SOFT_source_spatialize) alSourcei(source, AL_SOURCE_SPATIALIZE_SOFT, AL_FALSE); if (useenv) { if (mWaterFilter) alSourcei(source, AL_DIRECT_FILTER, (mListenerEnv == Env_Underwater) ? mWaterFilter : AL_FILTER_NULL); else if (mListenerEnv == Env_Underwater) { gain *= 0.9f; pitch *= 0.7f; } if (mEffectSlot) alSource3i(source, AL_AUXILIARY_SEND_FILTER, mEffectSlot, 0, AL_FILTER_NULL); } else { if (mWaterFilter) alSourcei(source, AL_DIRECT_FILTER, AL_FILTER_NULL); if (mEffectSlot) alSource3i(source, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, 0, AL_FILTER_NULL); } alSourcef(source, AL_GAIN, gain); alSourcef(source, AL_PITCH, pitch); alSourcefv(source, AL_POSITION, pos.ptr()); alSource3f(source, AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSource3f(source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); } void OpenAL_Output::initCommon3D(ALuint source, const osg::Vec3f& pos, ALfloat mindist, ALfloat maxdist, ALfloat gain, ALfloat pitch, bool loop, bool useenv) { alSourcef(source, AL_REFERENCE_DISTANCE, mindist); alSourcef(source, AL_MAX_DISTANCE, maxdist); alSourcef(source, AL_ROLLOFF_FACTOR, 1.0f); alSourcei(source, AL_SOURCE_RELATIVE, AL_FALSE); alSourcei(source, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); if (AL.SOFT_source_spatialize) alSourcei(source, AL_SOURCE_SPATIALIZE_SOFT, AL_TRUE); if ((pos - mListenerPos).length2() > maxdist * maxdist) gain = 0.0f; if (useenv) { if (mWaterFilter) alSourcei(source, AL_DIRECT_FILTER, (mListenerEnv == Env_Underwater) ? mWaterFilter : AL_FILTER_NULL); else if (mListenerEnv == Env_Underwater) { gain *= 0.9f; pitch *= 0.7f; } if (mEffectSlot) alSource3i(source, AL_AUXILIARY_SEND_FILTER, mEffectSlot, 0, AL_FILTER_NULL); } else { if (mWaterFilter) alSourcei(source, AL_DIRECT_FILTER, AL_FILTER_NULL); if (mEffectSlot) alSource3i(source, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, 0, AL_FILTER_NULL); } alSourcef(source, AL_GAIN, gain); alSourcef(source, AL_PITCH, pitch); alSourcefv(source, AL_POSITION, pos.ptr()); alSource3f(source, AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSource3f(source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); } void OpenAL_Output::updateCommon( ALuint source, const osg::Vec3f& pos, ALfloat maxdist, ALfloat gain, ALfloat pitch, bool useenv) { if (useenv && mListenerEnv == Env_Underwater && !mWaterFilter) { gain *= 0.9f; pitch *= 0.7f; } alSourcef(source, AL_GAIN, gain); alSourcef(source, AL_PITCH, pitch); alSourcefv(source, AL_POSITION, pos.ptr()); alSource3f(source, AL_DIRECTION, 0.0f, 0.0f, 0.0f); alSource3f(source, AL_VELOCITY, 0.0f, 0.0f, 0.0f); } bool OpenAL_Output::playSound(Sound* sound, Sound_Handle data, float offset) { ALuint source; if (mFreeSources.empty()) { Log(Debug::Warning) << "No free sources!"; return false; } source = mFreeSources.front(); initCommon2D(source, sound->getPosition(), sound->getRealVolume(), getTimeScaledPitch(sound), sound->getIsLooping(), sound->getUseEnv()); alSourcei(source, AL_BUFFER, GET_PTRID(data)); alSourcef(source, AL_SEC_OFFSET, offset); if (getALError() != AL_NO_ERROR) { alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); alGetError(); return false; } alSourcePlay(source); if (getALError() != AL_NO_ERROR) { alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); alGetError(); return false; } mFreeSources.pop_front(); sound->mHandle = MAKE_PTRID(source); mActiveSounds.push_back(sound); return true; } bool OpenAL_Output::playSound3D(Sound* sound, Sound_Handle data, float offset) { ALuint source; if (mFreeSources.empty()) { Log(Debug::Warning) << "No free sources!"; return false; } source = mFreeSources.front(); initCommon3D(source, sound->getPosition(), sound->getMinDistance(), sound->getMaxDistance(), sound->getRealVolume(), getTimeScaledPitch(sound), sound->getIsLooping(), sound->getUseEnv()); alSourcei(source, AL_BUFFER, GET_PTRID(data)); alSourcef(source, AL_SEC_OFFSET, offset); if (getALError() != AL_NO_ERROR) { alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); alGetError(); return false; } alSourcePlay(source); if (getALError() != AL_NO_ERROR) { alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); alGetError(); return false; } mFreeSources.pop_front(); sound->mHandle = MAKE_PTRID(source); mActiveSounds.push_back(sound); return true; } void OpenAL_Output::finishSound(Sound* sound) { if (!sound->mHandle) return; ALuint source = GET_PTRID(sound->mHandle); sound->mHandle = nullptr; // Rewind the stream to put the source back into an AL_INITIAL state, for // the next time it's used. alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); getALError(); mFreeSources.push_back(source); mActiveSounds.erase(std::find(mActiveSounds.begin(), mActiveSounds.end(), sound)); } bool OpenAL_Output::isSoundPlaying(Sound* sound) { if (!sound->mHandle) return false; ALuint source = GET_PTRID(sound->mHandle); ALint state = AL_STOPPED; alGetSourcei(source, AL_SOURCE_STATE, &state); getALError(); return state == AL_PLAYING || state == AL_PAUSED; } void OpenAL_Output::updateSound(Sound* sound) { if (!sound->mHandle) return; ALuint source = GET_PTRID(sound->mHandle); updateCommon(source, sound->getPosition(), sound->getMaxDistance(), sound->getRealVolume(), getTimeScaledPitch(sound), sound->getUseEnv()); getALError(); } bool OpenAL_Output::streamSound(DecoderPtr decoder, Stream* sound, bool getLoudnessData) { if (mFreeSources.empty()) { Log(Debug::Warning) << "No free sources!"; return false; } ALuint source = mFreeSources.front(); if (sound->getIsLooping()) Log(Debug::Warning) << "Warning: cannot loop stream \"" << decoder->getName() << "\""; initCommon2D( source, sound->getPosition(), sound->getRealVolume(), getTimeScaledPitch(sound), false, sound->getUseEnv()); if (getALError() != AL_NO_ERROR) return false; OpenAL_SoundStream* stream = new OpenAL_SoundStream(source, std::move(decoder)); if (!stream->init(getLoudnessData)) { delete stream; return false; } mStreamThread->add(stream); mFreeSources.pop_front(); sound->mHandle = stream; mActiveStreams.push_back(sound); return true; } bool OpenAL_Output::streamSound3D(DecoderPtr decoder, Stream* sound, bool getLoudnessData) { if (mFreeSources.empty()) { Log(Debug::Warning) << "No free sources!"; return false; } ALuint source = mFreeSources.front(); if (sound->getIsLooping()) Log(Debug::Warning) << "Warning: cannot loop stream \"" << decoder->getName() << "\""; initCommon3D(source, sound->getPosition(), sound->getMinDistance(), sound->getMaxDistance(), sound->getRealVolume(), getTimeScaledPitch(sound), false, sound->getUseEnv()); if (getALError() != AL_NO_ERROR) return false; OpenAL_SoundStream* stream = new OpenAL_SoundStream(source, std::move(decoder)); if (!stream->init(getLoudnessData)) { delete stream; return false; } mStreamThread->add(stream); mFreeSources.pop_front(); sound->mHandle = stream; mActiveStreams.push_back(sound); return true; } void OpenAL_Output::finishStream(Stream* sound) { if (!sound->mHandle) return; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); ALuint source = stream->mSource; sound->mHandle = nullptr; mStreamThread->remove(stream); // Rewind the stream to put the source back into an AL_INITIAL state, for // the next time it's used. alSourceRewind(source); alSourcei(source, AL_BUFFER, 0); getALError(); mFreeSources.push_back(source); mActiveStreams.erase(std::find(mActiveStreams.begin(), mActiveStreams.end(), sound)); delete stream; } double OpenAL_Output::getStreamDelay(Stream* sound) { if (!sound->mHandle) return 0.0; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); return stream->getStreamDelay(); } double OpenAL_Output::getStreamOffset(Stream* sound) { if (!sound->mHandle) return 0.0; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); std::lock_guard<std::mutex> lock(mStreamThread->mMutex); return stream->getStreamOffset(); } float OpenAL_Output::getStreamLoudness(Stream* sound) { if (!sound->mHandle) return 0.0; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); std::lock_guard<std::mutex> lock(mStreamThread->mMutex); return stream->getCurrentLoudness(); } bool OpenAL_Output::isStreamPlaying(Stream* sound) { if (!sound->mHandle) return false; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); std::lock_guard<std::mutex> lock(mStreamThread->mMutex); return stream->isPlaying(); } void OpenAL_Output::updateStream(Stream* sound) { if (!sound->mHandle) return; OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); ALuint source = stream->mSource; updateCommon(source, sound->getPosition(), sound->getMaxDistance(), sound->getRealVolume(), getTimeScaledPitch(sound), sound->getUseEnv()); getALError(); } void OpenAL_Output::startUpdate() { alcSuspendContext(alcGetCurrentContext()); } void OpenAL_Output::finishUpdate() { alcProcessContext(alcGetCurrentContext()); } void OpenAL_Output::updateListener( const osg::Vec3f& pos, const osg::Vec3f& atdir, const osg::Vec3f& updir, Environment env) { if (mContext) { ALfloat orient[6] = { atdir.x(), atdir.y(), atdir.z(), updir.x(), updir.y(), updir.z() }; alListenerfv(AL_POSITION, pos.ptr()); alListenerfv(AL_ORIENTATION, orient); if (env != mListenerEnv) { alSpeedOfSound(((env == Env_Underwater) ? Constants::SoundSpeedUnderwater : Constants::SoundSpeedInAir) * Constants::UnitsPerMeter); // Update active sources with the environment's direct filter if (mWaterFilter) { ALuint filter = (env == Env_Underwater) ? mWaterFilter : AL_FILTER_NULL; for (Sound* sound : mActiveSounds) { if (sound->getUseEnv()) alSourcei(GET_PTRID(sound->mHandle), AL_DIRECT_FILTER, filter); } for (Stream* sound : mActiveStreams) { if (sound->getUseEnv()) alSourcei(reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle)->mSource, AL_DIRECT_FILTER, filter); } } // Update the environment effect if (mEffectSlot) alAuxiliaryEffectSloti( mEffectSlot, AL_EFFECTSLOT_EFFECT, (env == Env_Underwater) ? mWaterEffect : mDefaultEffect); } getALError(); } mListenerPos = pos; mListenerEnv = env; } void OpenAL_Output::pauseSounds(int types) { std::vector<ALuint> sources; for (Sound* sound : mActiveSounds) { if ((types & sound->getPlayType())) sources.push_back(GET_PTRID(sound->mHandle)); } for (Stream* sound : mActiveStreams) { if ((types & sound->getPlayType())) { OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); sources.push_back(stream->mSource); } } if (!sources.empty()) { alSourcePausev(sources.size(), sources.data()); getALError(); } } void OpenAL_Output::pauseActiveDevice() { if (mDevice == nullptr) return; if (alcIsExtensionPresent(mDevice, "ALC_SOFT_PAUSE_DEVICE")) { LPALCDEVICEPAUSESOFT alcDevicePauseSOFT = nullptr; getALCFunc(alcDevicePauseSOFT, mDevice, "alcDevicePauseSOFT"); alcDevicePauseSOFT(mDevice); getALCError(mDevice); } alListenerf(AL_GAIN, 0.0f); } void OpenAL_Output::resumeActiveDevice() { if (mDevice == nullptr) return; if (alcIsExtensionPresent(mDevice, "ALC_SOFT_PAUSE_DEVICE")) { LPALCDEVICERESUMESOFT alcDeviceResumeSOFT = nullptr; getALCFunc(alcDeviceResumeSOFT, mDevice, "alcDeviceResumeSOFT"); alcDeviceResumeSOFT(mDevice); getALCError(mDevice); } alListenerf(AL_GAIN, 1.0f); } void OpenAL_Output::resumeSounds(int types) { std::vector<ALuint> sources; for (Sound* sound : mActiveSounds) { if ((types & sound->getPlayType())) sources.push_back(GET_PTRID(sound->mHandle)); } for (Stream* sound : mActiveStreams) { if ((types & sound->getPlayType())) { OpenAL_SoundStream* stream = reinterpret_cast<OpenAL_SoundStream*>(sound->mHandle); sources.push_back(stream->mSource); } } if (!sources.empty()) { alSourcePlayv(sources.size(), sources.data()); getALError(); } } OpenAL_Output::OpenAL_Output(SoundManager& mgr) : Sound_Output(mgr) , mDevice(nullptr) , mContext(nullptr) , mListenerPos(0.0f, 0.0f, 0.0f) , mListenerEnv(Env_Normal) , mWaterFilter(0) , mWaterEffect(0) , mDefaultEffect(0) , mEffectSlot(0) , mStreamThread(std::make_unique<StreamThread>()) { } OpenAL_Output::~OpenAL_Output() { OpenAL_Output::deinit(); } float OpenAL_Output::getTimeScaledPitch(SoundBase* sound) { const bool shouldScale = !(sound->mParams.mFlags & PlayMode::NoScaling); return shouldScale ? sound->getPitch() * mManager.getSimulationTimeScale() : sound->getPitch(); } }
54,944
C++
.cpp
1,415
27.837456
120
0.571075
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,353
movieaudiofactory.cpp
OpenMW_openmw/apps/openmw/mwsound/movieaudiofactory.cpp
#include "movieaudiofactory.hpp" #include <extern/osg-ffmpeg-videoplayer/audiodecoder.hpp> #include <extern/osg-ffmpeg-videoplayer/libavutildefines.hpp> #include <extern/osg-ffmpeg-videoplayer/videostate.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/soundmanager.hpp" #include "sound_decoder.hpp" namespace MWSound { class MovieAudioDecoder; class MWSoundDecoderBridge final : public Sound_Decoder { public: MWSoundDecoderBridge(MWSound::MovieAudioDecoder* decoder) : Sound_Decoder(nullptr) , mDecoder(decoder) { } private: MWSound::MovieAudioDecoder* mDecoder; void open(VFS::Path::NormalizedView fname) override { throw std::runtime_error("Method not implemented"); } void close() override {} std::string getName() override; void getInfo(int* samplerate, ChannelConfig* chans, SampleType* type) override; size_t read(char* buffer, size_t bytes) override; size_t getSampleOffset() override; }; class MovieAudioDecoder : public Video::MovieAudioDecoder { public: MovieAudioDecoder(Video::VideoState* videoState) : Video::MovieAudioDecoder(videoState) , mAudioTrack(nullptr) , mDecoderBridge(std::make_shared<MWSoundDecoderBridge>(this)) { } size_t getSampleOffset() { #if OPENMW_FFMPEG_5_OR_GREATER ssize_t clock_delay = (mFrameSize - mFramePos) / mOutputChannelLayout.nb_channels #else ssize_t clock_delay = (mFrameSize - mFramePos) / av_get_channel_layout_nb_channels(mOutputChannelLayout) #endif / av_get_bytes_per_sample(mOutputSampleFormat); return (size_t)(mAudioClock * mAudioContext->sample_rate) - clock_delay; } std::string getStreamName() { return std::string(); } private: // MovieAudioDecoder overrides double getAudioClock() override { return (double)getSampleOffset() / (double)mAudioContext->sample_rate - MWBase::Environment::get().getSoundManager()->getTrackTimeDelay(mAudioTrack); } void adjustAudioSettings(AVSampleFormat& sampleFormat, uint64_t& channelLayout, int& sampleRate) override { if (sampleFormat == AV_SAMPLE_FMT_U8P || sampleFormat == AV_SAMPLE_FMT_U8) sampleFormat = AV_SAMPLE_FMT_U8; // else if (sampleFormat == AV_SAMPLE_FMT_S16P || sampleFormat == AV_SAMPLE_FMT_S16) // sampleFormat = AV_SAMPLE_FMT_S16; // FIXME: check for AL_EXT_FLOAT32 support // else if (sampleFormat == AV_SAMPLE_FMT_FLTP || sampleFormat == AV_SAMPLE_FMT_FLT) // sampleFormat = AV_SAMPLE_FMT_S16; else sampleFormat = AV_SAMPLE_FMT_S16; if (channelLayout == AV_CH_LAYOUT_5POINT1 || channelLayout == AV_CH_LAYOUT_7POINT1 || channelLayout == AV_CH_LAYOUT_QUAD) // FIXME: check for AL_EXT_MCFORMATS support channelLayout = AV_CH_LAYOUT_STEREO; else if (channelLayout != AV_CH_LAYOUT_MONO && channelLayout != AV_CH_LAYOUT_STEREO) channelLayout = AV_CH_LAYOUT_STEREO; } public: ~MovieAudioDecoder() { if (mAudioTrack) MWBase::Environment::get().getSoundManager()->stopTrack(mAudioTrack); mAudioTrack = nullptr; mDecoderBridge.reset(); } MWBase::SoundStream* mAudioTrack; std::shared_ptr<MWSoundDecoderBridge> mDecoderBridge; }; std::string MWSoundDecoderBridge::getName() { return mDecoder->getStreamName(); } void MWSoundDecoderBridge::getInfo(int* samplerate, ChannelConfig* chans, SampleType* type) { *samplerate = mDecoder->getOutputSampleRate(); uint64_t outputChannelLayout = mDecoder->getOutputChannelLayout(); if (outputChannelLayout == AV_CH_LAYOUT_MONO) *chans = ChannelConfig_Mono; else if (outputChannelLayout == AV_CH_LAYOUT_5POINT1) *chans = ChannelConfig_5point1; else if (outputChannelLayout == AV_CH_LAYOUT_7POINT1) *chans = ChannelConfig_7point1; else if (outputChannelLayout == AV_CH_LAYOUT_STEREO) *chans = ChannelConfig_Stereo; else if (outputChannelLayout == AV_CH_LAYOUT_QUAD) *chans = ChannelConfig_Quad; else throw std::runtime_error("Unsupported channel layout: " + std::to_string(outputChannelLayout)); AVSampleFormat outputSampleFormat = mDecoder->getOutputSampleFormat(); if (outputSampleFormat == AV_SAMPLE_FMT_U8) *type = SampleType_UInt8; else if (outputSampleFormat == AV_SAMPLE_FMT_FLT) *type = SampleType_Float32; else if (outputSampleFormat == AV_SAMPLE_FMT_S16) *type = SampleType_Int16; else { char str[1024]; av_get_sample_fmt_string(str, sizeof(str), outputSampleFormat); throw std::runtime_error(std::string("Unsupported sample format: ") + str); } } size_t MWSoundDecoderBridge::read(char* buffer, size_t bytes) { return mDecoder->read(buffer, bytes); } size_t MWSoundDecoderBridge::getSampleOffset() { return mDecoder->getSampleOffset(); } std::unique_ptr<Video::MovieAudioDecoder> MovieAudioFactory::createDecoder(Video::VideoState* videoState) { auto decoder = std::make_unique<MWSound::MovieAudioDecoder>(videoState); decoder->setupFormat(); MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); MWBase::SoundStream* sound = sndMgr->playTrack(decoder->mDecoderBridge, MWSound::Type::Movie); if (!sound) { decoder.reset(); return decoder; } decoder->mAudioTrack = sound; return decoder; } }
6,045
C++
.cpp
142
33.401408
116
0.64017
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,354
regionsoundselector.cpp
OpenMW_openmw/apps/openmw/mwsound/regionsoundselector.cpp
#include "regionsoundselector.hpp" #include <components/esm3/loadregn.hpp> #include <components/fallback/fallback.hpp> #include <components/misc/rng.hpp> #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" namespace MWSound { RegionSoundSelector::RegionSoundSelector() : mMinTimeBetweenSounds(Fallback::Map::getFloat("Weather_Minimum_Time_Between_Environmental_Sounds")) , mMaxTimeBetweenSounds(Fallback::Map::getFloat("Weather_Maximum_Time_Between_Environmental_Sounds")) { } ESM::RefId RegionSoundSelector::getNextRandom(float duration, const ESM::RefId& regionName) { mTimePassed += duration; if (mTimePassed < mTimeToNextEnvSound) return {}; const float a = Misc::Rng::rollClosedProbability(); mTimeToNextEnvSound = mMinTimeBetweenSounds + (mMaxTimeBetweenSounds - mMinTimeBetweenSounds) * a; mTimePassed = 0; const ESM::Region* const region = MWBase::Environment::get().getESMStore()->get<ESM::Region>().search(regionName); if (region == nullptr) return {}; for (const ESM::Region::SoundRef& sound : region->mSoundList) { if (Misc::Rng::roll0to99() < sound.mChance) return sound.mSound; } return {}; } }
1,330
C++
.cpp
33
33.212121
109
0.674689
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,355
ffmpeg_decoder.cpp
OpenMW_openmw/apps/openmw/mwsound/ffmpeg_decoder.cpp
#include "ffmpeg_decoder.hpp" #include <algorithm> #include <memory> #include <stdexcept> #include <utility> #include <components/debug/debuglog.hpp> #include <components/vfs/manager.hpp> #include <extern/osg-ffmpeg-videoplayer/libavformatdefines.hpp> #include <extern/osg-ffmpeg-videoplayer/libavutildefines.hpp> #if OPENMW_FFMPEG_5_OR_GREATER #include <libavutil/channel_layout.h> #endif namespace MWSound { void AVIOContextDeleter::operator()(AVIOContext* ptr) const { if (ptr->buffer != nullptr) av_freep(&ptr->buffer); #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 80, 100) avio_context_free(&ptr); #else av_free(ptr); #endif } void AVFormatContextDeleter::operator()(AVFormatContext* ptr) const { avformat_close_input(&ptr); } void AVCodecContextDeleter::operator()(AVCodecContext* ptr) const { avcodec_free_context(&ptr); } void AVFrameDeleter::operator()(AVFrame* ptr) const { av_frame_free(&ptr); } int FFmpeg_Decoder::readPacket(void* user_data, uint8_t* buf, int buf_size) { try { std::istream& stream = *static_cast<FFmpeg_Decoder*>(user_data)->mDataStream; stream.clear(); stream.read((char*)buf, buf_size); std::streamsize count = stream.gcount(); if (count == 0) return AVERROR_EOF; if (count > std::numeric_limits<int>::max()) return AVERROR_BUG; return static_cast<int>(count); } catch (std::exception&) { return AVERROR_UNKNOWN; } } #if OPENMW_FFMPEG_CONST_WRITEPACKET int FFmpeg_Decoder::writePacket(void*, const uint8_t*, int) #else int FFmpeg_Decoder::writePacket(void*, uint8_t*, int) #endif { Log(Debug::Error) << "can't write to read-only stream"; return -1; } int64_t FFmpeg_Decoder::seek(void* user_data, int64_t offset, int whence) { std::istream& stream = *static_cast<FFmpeg_Decoder*>(user_data)->mDataStream; whence &= ~AVSEEK_FORCE; stream.clear(); if (whence == AVSEEK_SIZE) { size_t prev = stream.tellg(); stream.seekg(0, std::ios_base::end); size_t size = stream.tellg(); stream.seekg(prev, std::ios_base::beg); return size; } if (whence == SEEK_SET) stream.seekg(offset, std::ios_base::beg); else if (whence == SEEK_CUR) stream.seekg(offset, std::ios_base::cur); else if (whence == SEEK_END) stream.seekg(offset, std::ios_base::end); else return -1; return stream.tellg(); } /* Used by getAV*Data to search for more compressed data, and buffer it in the * correct stream. It won't buffer data for streams that the app doesn't have a * handle for. */ bool FFmpeg_Decoder::getNextPacket() { if (!mStream) return false; std::ptrdiff_t stream_idx = mStream - mFormatCtx->streams; while (av_read_frame(mFormatCtx.get(), &mPacket) >= 0) { /* Check if the packet belongs to this stream */ if (stream_idx == mPacket.stream_index) { if (mPacket.pts != (int64_t)AV_NOPTS_VALUE) mNextPts = av_q2d((*mStream)->time_base) * mPacket.pts; return true; } /* Free the packet and look for another */ av_packet_unref(&mPacket); } return false; } bool FFmpeg_Decoder::getAVAudioData() { bool got_frame = false; if (mCodecCtx->codec_type != AVMEDIA_TYPE_AUDIO) return false; do { /* Decode some data, and check for errors */ int ret = avcodec_receive_frame(mCodecCtx.get(), mFrame.get()); if (ret == AVERROR(EAGAIN)) { if (mPacket.size == 0 && !getNextPacket()) return false; ret = avcodec_send_packet(mCodecCtx.get(), &mPacket); av_packet_unref(&mPacket); if (ret == 0) continue; } if (ret != 0) return false; av_packet_unref(&mPacket); if (mFrame->nb_samples == 0) continue; got_frame = true; if (mSwr) { if (!mDataBuf || mDataBufLen < mFrame->nb_samples) { av_freep(&mDataBuf); #if OPENMW_FFMPEG_5_OR_GREATER if (av_samples_alloc(&mDataBuf, nullptr, mOutputChannelLayout.nb_channels, #else if (av_samples_alloc(&mDataBuf, nullptr, av_get_channel_layout_nb_channels(mOutputChannelLayout), #endif mFrame->nb_samples, mOutputSampleFormat, 0) < 0) return false; else mDataBufLen = mFrame->nb_samples; } if (swr_convert(mSwr, (uint8_t**)&mDataBuf, mFrame->nb_samples, (const uint8_t**)mFrame->extended_data, mFrame->nb_samples) < 0) { return false; } mFrameData = &mDataBuf; } else mFrameData = &mFrame->data[0]; } while (!got_frame); mNextPts += (double)mFrame->nb_samples / mCodecCtx->sample_rate; return true; } size_t FFmpeg_Decoder::readAVAudioData(void* data, size_t length) { size_t dec = 0; while (dec < length) { /* If there's no decoded data, find some */ if (mFramePos >= mFrameSize) { if (!getAVAudioData()) break; mFramePos = 0; #if OPENMW_FFMPEG_5_OR_GREATER mFrameSize = mFrame->nb_samples * mOutputChannelLayout.nb_channels #else mFrameSize = mFrame->nb_samples * av_get_channel_layout_nb_channels(mOutputChannelLayout) #endif * av_get_bytes_per_sample(mOutputSampleFormat); } /* Get the amount of bytes remaining to be written, and clamp to * the amount of decoded data we have */ size_t rem = std::min<size_t>(length - dec, mFrameSize - mFramePos); /* Copy the data to the app's buffer and increment */ memcpy(data, mFrameData[0] + mFramePos, rem); data = (char*)data + rem; dec += rem; mFramePos += rem; } /* Return the number of bytes we were able to get */ return dec; } void FFmpeg_Decoder::open(VFS::Path::NormalizedView fname) { close(); mDataStream = mResourceMgr->get(fname); AVIOContextPtr ioCtx(avio_alloc_context(nullptr, 0, 0, this, readPacket, writePacket, seek)); if (ioCtx == nullptr) throw std::runtime_error("Failed to allocate AVIO context"); AVFormatContext* formatCtx = avformat_alloc_context(); if (formatCtx == nullptr) throw std::runtime_error("Failed to allocate context"); formatCtx->pb = ioCtx.get(); // avformat_open_input frees user supplied AVFormatContext on failure if (avformat_open_input(&formatCtx, fname.value().data(), nullptr, nullptr) != 0) throw std::runtime_error("Failed to open input"); AVFormatContextPtr formatCtxPtr(std::exchange(formatCtx, nullptr)); if (avformat_find_stream_info(formatCtxPtr.get(), nullptr) < 0) throw std::runtime_error("Failed to find stream info"); AVStream** stream = nullptr; for (size_t j = 0; j < formatCtxPtr->nb_streams; j++) { if (formatCtxPtr->streams[j]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { stream = &formatCtxPtr->streams[j]; break; } } if (stream == nullptr) throw std::runtime_error("No audio streams"); const AVCodec* codec = avcodec_find_decoder((*stream)->codecpar->codec_id); if (codec == nullptr) throw std::runtime_error("No codec found for id " + std::to_string((*stream)->codecpar->codec_id)); AVCodecContext* codecCtx = avcodec_alloc_context3(codec); if (codecCtx == nullptr) throw std::runtime_error("Failed to allocate codec context"); avcodec_parameters_to_context(codecCtx, (*stream)->codecpar); // This is not needed anymore above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_codec_set_pkt_timebase(avctx, (*stream)->time_base); #endif AVCodecContextPtr codecCtxPtr(std::exchange(codecCtx, nullptr)); if (avcodec_open2(codecCtxPtr.get(), codec, nullptr) < 0) throw std::runtime_error(std::string("Failed to open audio codec ") + codec->long_name); AVFramePtr frame(av_frame_alloc()); if (frame == nullptr) throw std::runtime_error("Failed to allocate frame"); if (codecCtxPtr->sample_fmt == AV_SAMPLE_FMT_U8P) mOutputSampleFormat = AV_SAMPLE_FMT_U8; // FIXME: Check for AL_EXT_FLOAT32 support // else if (codecCtxPtr->sample_fmt == AV_SAMPLE_FMT_FLT || codecCtxPtr->sample_fmt == AV_SAMPLE_FMT_FLTP) // mOutputSampleFormat = AV_SAMPLE_FMT_S16; else mOutputSampleFormat = AV_SAMPLE_FMT_S16; #if OPENMW_FFMPEG_5_OR_GREATER mOutputChannelLayout = (*stream)->codecpar->ch_layout; // sefault if (mOutputChannelLayout.u.mask == 0) av_channel_layout_default(&mOutputChannelLayout, codecCtxPtr->ch_layout.nb_channels); codecCtxPtr->ch_layout = mOutputChannelLayout; #else mOutputChannelLayout = (*stream)->codecpar->channel_layout; if (mOutputChannelLayout == 0) mOutputChannelLayout = av_get_default_channel_layout(codecCtxPtr->channels); codecCtxPtr->channel_layout = mOutputChannelLayout; #endif mIoCtx = std::move(ioCtx); mFrame = std::move(frame); mFormatCtx = std::move(formatCtxPtr); mCodecCtx = std::move(codecCtxPtr); mStream = stream; } void FFmpeg_Decoder::close() { mStream = nullptr; mCodecCtx.reset(); av_packet_unref(&mPacket); av_freep(&mDataBuf); mFrame.reset(); swr_free(&mSwr); mFormatCtx.reset(); mIoCtx.reset(); mDataStream.reset(); } std::string FFmpeg_Decoder::getName() { // In the FFMpeg 4.0 a "filename" field was replaced by "url" #if LIBAVCODEC_VERSION_INT < 3805796 return mFormatCtx->filename; #else return mFormatCtx->url; #endif } void FFmpeg_Decoder::getInfo(int* samplerate, ChannelConfig* chans, SampleType* type) { if (!mStream) throw std::runtime_error("No audio stream info"); if (mOutputSampleFormat == AV_SAMPLE_FMT_U8) *type = SampleType_UInt8; else if (mOutputSampleFormat == AV_SAMPLE_FMT_S16) *type = SampleType_Int16; else if (mOutputSampleFormat == AV_SAMPLE_FMT_FLT) *type = SampleType_Float32; else { mOutputSampleFormat = AV_SAMPLE_FMT_S16; *type = SampleType_Int16; } #if OPENMW_FFMPEG_5_OR_GREATER switch (mOutputChannelLayout.u.mask) #else switch (mOutputChannelLayout) #endif { case AV_CH_LAYOUT_MONO: *chans = ChannelConfig_Mono; break; case AV_CH_LAYOUT_STEREO: *chans = ChannelConfig_Stereo; break; case AV_CH_LAYOUT_QUAD: *chans = ChannelConfig_Quad; break; case AV_CH_LAYOUT_5POINT1: *chans = ChannelConfig_5point1; break; case AV_CH_LAYOUT_7POINT1: *chans = ChannelConfig_7point1; break; default: char str[1024]; #if OPENMW_FFMPEG_5_OR_GREATER av_channel_layout_describe(&mCodecCtx->ch_layout, str, sizeof(str)); Log(Debug::Error) << "Unsupported channel layout: " << str; if (mCodecCtx->ch_layout.nb_channels == 1) { mOutputChannelLayout = AV_CHANNEL_LAYOUT_MONO; *chans = ChannelConfig_Mono; } else { mOutputChannelLayout = AV_CHANNEL_LAYOUT_STEREO; *chans = ChannelConfig_Stereo; } #else av_get_channel_layout_string(str, sizeof(str), mCodecCtx->channels, mCodecCtx->channel_layout); Log(Debug::Error) << "Unsupported channel layout: " << str; if (mCodecCtx->channels == 1) { mOutputChannelLayout = AV_CH_LAYOUT_MONO; *chans = ChannelConfig_Mono; } else { mOutputChannelLayout = AV_CH_LAYOUT_STEREO; *chans = ChannelConfig_Stereo; } #endif break; } *samplerate = mCodecCtx->sample_rate; #if OPENMW_FFMPEG_5_OR_GREATER AVChannelLayout ch_layout = mCodecCtx->ch_layout; if (ch_layout.u.mask == 0) av_channel_layout_default(&ch_layout, mCodecCtx->ch_layout.nb_channels); if (mOutputSampleFormat != mCodecCtx->sample_fmt || mOutputChannelLayout.u.mask != ch_layout.u.mask) #else int64_t ch_layout = mCodecCtx->channel_layout; if (ch_layout == 0) ch_layout = av_get_default_channel_layout(mCodecCtx->channels); if (mOutputSampleFormat != mCodecCtx->sample_fmt || mOutputChannelLayout != ch_layout) #endif { #if OPENMW_FFMPEG_5_OR_GREATER swr_alloc_set_opts2(&mSwr, // SwrContext &mOutputChannelLayout, // output ch layout mOutputSampleFormat, // output sample format mCodecCtx->sample_rate, // output sample rate &ch_layout, // input ch layout mCodecCtx->sample_fmt, // input sample format mCodecCtx->sample_rate, // input sample rate 0, // logging level offset nullptr); // log context #else mSwr = swr_alloc_set_opts(mSwr, // SwrContext mOutputChannelLayout, // output ch layout mOutputSampleFormat, // output sample format mCodecCtx->sample_rate, // output sample rate ch_layout, // input ch layout mCodecCtx->sample_fmt, // input sample format mCodecCtx->sample_rate, // input sample rate 0, // logging level offset nullptr); // log context #endif if (!mSwr) throw std::runtime_error("Couldn't allocate SwrContext"); int init = swr_init(mSwr); if (init < 0) throw std::runtime_error("Couldn't initialize SwrContext: " + std::to_string(init)); } } size_t FFmpeg_Decoder::read(char* buffer, size_t bytes) { if (!mStream) { Log(Debug::Error) << "No audio stream"; return 0; } return readAVAudioData(buffer, bytes); } void FFmpeg_Decoder::readAll(std::vector<char>& output) { if (!mStream) { Log(Debug::Error) << "No audio stream"; return; } while (getAVAudioData()) { #if OPENMW_FFMPEG_5_OR_GREATER size_t got = mFrame->nb_samples * mOutputChannelLayout.nb_channels #else size_t got = mFrame->nb_samples * av_get_channel_layout_nb_channels(mOutputChannelLayout) #endif * av_get_bytes_per_sample(mOutputSampleFormat); const char* inbuf = reinterpret_cast<char*>(mFrameData[0]); output.insert(output.end(), inbuf, inbuf + got); } } size_t FFmpeg_Decoder::getSampleOffset() { #if OPENMW_FFMPEG_5_OR_GREATER std::size_t delay = (mFrameSize - mFramePos) / mOutputChannelLayout.nb_channels #else std::size_t delay = (mFrameSize - mFramePos) / av_get_channel_layout_nb_channels(mOutputChannelLayout) #endif / av_get_bytes_per_sample(mOutputSampleFormat); return static_cast<std::size_t>(mNextPts * mCodecCtx->sample_rate) - delay; } FFmpeg_Decoder::FFmpeg_Decoder(const VFS::Manager* vfs) : Sound_Decoder(vfs) , mStream(nullptr) , mFrameSize(0) , mFramePos(0) , mNextPts(0.0) , mSwr(nullptr) , mOutputSampleFormat(AV_SAMPLE_FMT_NONE) #if OPENMW_FFMPEG_5_OR_GREATER , mOutputChannelLayout({}) #else , mOutputChannelLayout(0) #endif , mDataBuf(nullptr) , mFrameData(nullptr) , mDataBufLen(0) { memset(&mPacket, 0, sizeof(mPacket)); /* We need to make sure ffmpeg is initialized. Optionally silence warning * output from the lib */ static bool done_init = false; if (!done_init) { // This is not needed anymore above FFMpeg version 4.0 #if LIBAVCODEC_VERSION_INT < 3805796 av_register_all(); #endif av_log_set_level(AV_LOG_ERROR); done_init = true; } } FFmpeg_Decoder::~FFmpeg_Decoder() { close(); } }
17,737
C++
.cpp
465
27.810753
119
0.57211
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,356
statemanagerimp.cpp
OpenMW_openmw/apps/openmw/mwstate/statemanagerimp.cpp
#include "statemanagerimp.hpp" #include <filesystem> #include <SDL_clipboard.h> #include <components/debug/debuglog.hpp> #include <components/esm3/esmreader.hpp> #include <components/esm3/esmwriter.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm3/loadclas.hpp> #include <components/l10n/manager.hpp> #include <components/loadinglistener/loadinglistener.hpp> #include <components/files/conversion.hpp> #include <components/misc/algorithm.hpp> #include <components/settings/values.hpp> #include <osg/Image> #include <osgDB/Registry> #include "../mwbase/dialoguemanager.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/inputmanager.hpp" #include "../mwbase/journal.hpp" #include "../mwbase/luamanager.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/scriptmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/datetimemanager.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/globals.hpp" #include "../mwworld/scene.hpp" #include "../mwworld/worldmodel.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/npcstats.hpp" #include "../mwscript/globalscripts.hpp" #include "quicksavemanager.hpp" void MWState::StateManager::cleanup(bool force) { if (mState != State_NoGame || force) { MWBase::Environment::get().getSoundManager()->clear(); MWBase::Environment::get().getDialogueManager()->clear(); MWBase::Environment::get().getJournal()->clear(); MWBase::Environment::get().getScriptManager()->clear(); MWBase::Environment::get().getWindowManager()->clear(); MWBase::Environment::get().getWorld()->clear(); MWBase::Environment::get().getInputManager()->clear(); MWBase::Environment::get().getMechanicsManager()->clear(); mCharacterManager.setCurrentCharacter(nullptr); mTimePlayed = 0; mLastSavegame.clear(); MWMechanics::CreatureStats::cleanup(); mState = State_NoGame; MWBase::Environment::get().getLuaManager()->noGame(); } else { // TODO: do we need this cleanup? MWBase::Environment::get().getLuaManager()->clear(); } } std::map<int, int> MWState::StateManager::buildContentFileIndexMap(const ESM::ESMReader& reader) const { const std::vector<std::string>& current = MWBase::Environment::get().getWorld()->getContentFiles(); const std::vector<ESM::Header::MasterData>& prev = reader.getGameFiles(); std::map<int, int> map; for (int iPrev = 0; iPrev < static_cast<int>(prev.size()); ++iPrev) { for (int iCurrent = 0; iCurrent < static_cast<int>(current.size()); ++iCurrent) if (Misc::StringUtils::ciEqual(prev[iPrev].name, current[iCurrent])) { map.insert(std::make_pair(iPrev, iCurrent)); break; } } return map; } MWState::StateManager::StateManager(const std::filesystem::path& saves, const std::vector<std::string>& contentFiles) : mQuitRequest(false) , mAskLoadRecent(false) , mState(State_NoGame) , mCharacterManager(saves, contentFiles) , mTimePlayed(0) { } void MWState::StateManager::requestQuit() { mQuitRequest = true; } bool MWState::StateManager::hasQuitRequest() const { return mQuitRequest; } void MWState::StateManager::askLoadRecent() { if (MWBase::Environment::get().getWindowManager()->getMode() == MWGui::GM_MainMenu) return; if (!mAskLoadRecent) { if (mLastSavegame.empty()) // no saves { MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_MainMenu); } else { std::string saveName = Files::pathToUnicodeString(mLastSavegame.filename()); // Assume the last saved game belongs to the current character's slot list. const Character* character = getCurrentCharacter(); if (character) { for (const auto& slot : *character) { if (slot.mPath == mLastSavegame) { saveName = slot.mProfile.mDescription; break; } } } std::vector<std::string> buttons; buttons.emplace_back("#{Interface:Yes}"); buttons.emplace_back("#{Interface:No}"); std::string message = MWBase::Environment::get().getL10nManager()->getMessage("OMWEngine", "AskLoadLastSave"); std::string_view tag = "%s"; size_t pos = message.find(tag); message.replace(pos, tag.length(), saveName); MWBase::Environment::get().getWindowManager()->interactiveMessageBox(message, buttons); mAskLoadRecent = true; } } } MWState::StateManager::State MWState::StateManager::getState() const { return mState; } void MWState::StateManager::newGame(bool bypass) { cleanup(); if (!bypass) MWBase::Environment::get().getWindowManager()->setNewGame(true); try { Log(Debug::Info) << "Starting a new game"; MWBase::Environment::get().getScriptManager()->getGlobalScripts().addStartup(); MWBase::Environment::get().getWorld()->startNewGame(bypass); mState = State_Running; MWBase::Environment::get().getLuaManager()->gameLoaded(); MWBase::Environment::get().getWindowManager()->fadeScreenOut(0); MWBase::Environment::get().getWindowManager()->fadeScreenIn(1); } catch (std::exception& e) { std::stringstream error; error << "Failed to start new game: " << e.what(); Log(Debug::Error) << error.str(); cleanup(true); MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_MainMenu); std::vector<std::string> buttons; buttons.emplace_back("#{Interface:OK}"); MWBase::Environment::get().getWindowManager()->interactiveMessageBox(error.str(), buttons); } } void MWState::StateManager::endGame() { mState = State_Ended; MWBase::Environment::get().getLuaManager()->gameEnded(); } void MWState::StateManager::resumeGame() { mState = State_Running; MWBase::Environment::get().getLuaManager()->gameLoaded(); } void MWState::StateManager::saveGame(std::string_view description, const Slot* slot) { MWBase::Environment::get().getLuaManager()->applyDelayedActions(); MWState::Character* character = getCurrentCharacter(); try { const auto start = std::chrono::steady_clock::now(); MWBase::Environment::get().getWindowManager()->asyncPrepareSaveMap(); if (!character) { MWWorld::ConstPtr player = MWMechanics::getPlayer(); const std::string& name = player.get<ESM::NPC>()->mBase->mName; character = mCharacterManager.createCharacter(name); mCharacterManager.setCurrentCharacter(character); } ESM::SavedGame profile; MWBase::World& world = *MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world.getPlayerPtr(); profile.mContentFiles = world.getContentFiles(); profile.mPlayerName = player.get<ESM::NPC>()->mBase->mName; profile.mPlayerLevel = player.getClass().getNpcStats(player).getLevel(); const ESM::RefId& classId = player.get<ESM::NPC>()->mBase->mClass; if (world.getStore().get<ESM::Class>().isDynamic(classId)) profile.mPlayerClassName = world.getStore().get<ESM::Class>().find(classId)->mName; else profile.mPlayerClassId = classId; const MWMechanics::CreatureStats& stats = player.getClass().getCreatureStats(player); profile.mPlayerCellName = world.getCellName(); profile.mInGameTime = world.getTimeManager()->getEpochTimeStamp(); profile.mTimePlayed = mTimePlayed; profile.mDescription = description; profile.mCurrentDay = world.getTimeManager()->getTimeStamp().getDay(); profile.mCurrentHealth = stats.getHealth().getCurrent(); profile.mMaximumHealth = stats.getHealth().getModified(); Log(Debug::Info) << "Making a screenshot for saved game '" << description << "'"; writeScreenshot(profile.mScreenshot); if (!slot) slot = character->createSlot(profile); else slot = character->updateSlot(slot, profile); // Make sure the animation state held by references is up to date before saving the game. MWBase::Environment::get().getMechanicsManager()->persistAnimationStates(); Log(Debug::Info) << "Writing saved game '" << description << "' for character '" << profile.mPlayerName << "'"; // Write to a memory stream first. If there is an exception during the save process, we don't want to trash the // existing save file we are overwriting. std::stringstream stream; ESM::ESMWriter writer; for (const std::string& contentFile : MWBase::Environment::get().getWorld()->getContentFiles()) writer.addMaster(contentFile, 0); // not using the size information anyway -> use value of 0 writer.setFormatVersion(ESM::CurrentSaveGameFormatVersion); // all unused writer.setVersion(0); writer.setType(0); writer.setAuthor(""); writer.setDescription(""); int recordCount = 1 // saved game header + MWBase::Environment::get().getJournal()->countSavedGameRecords() + MWBase::Environment::get().getLuaManager()->countSavedGameRecords() + MWBase::Environment::get().getWorld()->countSavedGameRecords() + MWBase::Environment::get().getScriptManager()->getGlobalScripts().countSavedGameRecords() + MWBase::Environment::get().getDialogueManager()->countSavedGameRecords() + MWBase::Environment::get().getMechanicsManager()->countSavedGameRecords() + MWBase::Environment::get().getInputManager()->countSavedGameRecords() + MWBase::Environment::get().getWindowManager()->countSavedGameRecords(); writer.setRecordCount(recordCount); writer.save(stream); Loading::Listener& listener = *MWBase::Environment::get().getWindowManager()->getLoadingScreen(); // Using only Cells for progress information, since they typically have the largest records by far listener.setProgressRange(MWBase::Environment::get().getWorld()->countSavedGameCells()); listener.setLabel("#{OMWEngine:SavingInProgress}", true); Loading::ScopedLoad load(&listener); writer.startRecord(ESM::REC_SAVE); slot->mProfile.save(writer); writer.endRecord(ESM::REC_SAVE); MWBase::Environment::get().getJournal()->write(writer, listener); MWBase::Environment::get().getDialogueManager()->write(writer, listener); // LuaManager::write should be called before World::write because world also saves // local scripts that depend on LuaManager. MWBase::Environment::get().getLuaManager()->write(writer, listener); MWBase::Environment::get().getWorld()->write(writer, listener); MWBase::Environment::get().getScriptManager()->getGlobalScripts().write(writer, listener); MWBase::Environment::get().getMechanicsManager()->write(writer, listener); MWBase::Environment::get().getInputManager()->write(writer, listener); MWBase::Environment::get().getWindowManager()->write(writer, listener); // Ensure we have written the number of records that was estimated if (writer.getRecordCount() != recordCount + 1) // 1 extra for TES3 record Log(Debug::Warning) << "Warning: number of written savegame records does not match. Estimated: " << recordCount + 1 << ", written: " << writer.getRecordCount(); writer.close(); if (stream.fail()) throw std::runtime_error("Write operation failed (memory stream)"); // All good, write to file std::ofstream filestream(slot->mPath, std::ios::binary); filestream << stream.rdbuf(); if (filestream.fail()) throw std::runtime_error("Write operation failed (file stream)"); Settings::saves().mCharacter.set(Files::pathToUnicodeString(slot->mPath.parent_path().filename())); mLastSavegame = slot->mPath; const auto finish = std::chrono::steady_clock::now(); Log(Debug::Info) << '\'' << description << "' is saved in " << std::chrono::duration_cast<std::chrono::duration<float, std::milli>>(finish - start).count() << "ms"; } catch (const std::exception& e) { std::stringstream error; error << "Failed to save game: " << e.what(); Log(Debug::Error) << error.str(); std::vector<std::string> buttons; buttons.emplace_back("#{Interface:OK}"); MWBase::Environment::get().getWindowManager()->interactiveMessageBox(error.str(), buttons); // If no file was written, clean up the slot if (character && slot && !std::filesystem::exists(slot->mPath)) { character->deleteSlot(slot); character->cleanup(); } } } void MWState::StateManager::quickSave(std::string name) { if (!(mState == State_Running && MWBase::Environment::get().getWorld()->getGlobalInt(MWWorld::Globals::sCharGenState) == -1 // char gen && MWBase::Environment::get().getWindowManager()->isSavingAllowed())) { // You can not save your game right now MWBase::Environment::get().getWindowManager()->messageBox("#{OMWEngine:SaveGameDenied}"); return; } Character* currentCharacter = getCurrentCharacter(); // Get current character QuickSaveManager saveFinder(name, Settings::saves().mMaxQuicksaves); if (currentCharacter) { for (auto& save : *currentCharacter) { // Visiting slots allows the quicksave finder to find the oldest quicksave saveFinder.visitSave(&save); } } // Once all the saves have been visited, the save finder can tell us which // one to replace (or create) saveGame(name, saveFinder.getNextQuickSaveSlot()); } void MWState::StateManager::loadGame(const std::filesystem::path& filepath) { for (const auto& character : mCharacterManager) { for (const auto& slot : character) { if (slot.mPath == filepath) { loadGame(&character, slot.mPath); return; } } } MWState::Character* character = getCurrentCharacter(); loadGame(character, filepath); } struct SaveFormatVersionError : public std::exception { using std::exception::exception; SaveFormatVersionError(ESM::FormatVersion savegameFormat, const std::string& message) : mSavegameFormat(savegameFormat) , mErrorMessage(message) { } const char* what() const noexcept override { return mErrorMessage.c_str(); } ESM::FormatVersion getFormatVersion() const { return mSavegameFormat; } protected: ESM::FormatVersion mSavegameFormat = ESM::DefaultFormatVersion; std::string mErrorMessage; }; struct SaveVersionTooOldError : SaveFormatVersionError { SaveVersionTooOldError(ESM::FormatVersion savegameFormat) : SaveFormatVersionError(savegameFormat, "format version " + std::to_string(savegameFormat) + " is too old") { } }; struct SaveVersionTooNewError : SaveFormatVersionError { SaveVersionTooNewError(ESM::FormatVersion savegameFormat) : SaveFormatVersionError(savegameFormat, "format version " + std::to_string(savegameFormat) + " is too new") { } }; void MWState::StateManager::loadGame(const Character* character, const std::filesystem::path& filepath) { try { cleanup(); Log(Debug::Info) << "Reading save file " << filepath.filename(); ESM::ESMReader reader; reader.open(filepath); ESM::FormatVersion version = reader.getFormatVersion(); if (version > ESM::CurrentSaveGameFormatVersion) throw SaveVersionTooNewError(version); else if (version < ESM::MinSupportedSaveGameFormatVersion) throw SaveVersionTooOldError(version); std::map<int, int> contentFileMap = buildContentFileIndexMap(reader); reader.setContentFileMapping(&contentFileMap); MWBase::Environment::get().getLuaManager()->setContentFileMapping(contentFileMap); Loading::Listener& listener = *MWBase::Environment::get().getWindowManager()->getLoadingScreen(); listener.setProgressRange(100); listener.setLabel("#{OMWEngine:LoadingInProgress}"); Loading::ScopedLoad load(&listener); bool firstPersonCam = false; size_t total = reader.getFileSize(); int currentPercent = 0; while (reader.hasMoreRecs()) { ESM::NAME n = reader.getRecName(); reader.getRecHeader(); switch (n.toInt()) { case ESM::REC_SAVE: { ESM::SavedGame profile; profile.load(reader); const auto& selectedContentFiles = MWBase::Environment::get().getWorld()->getContentFiles(); auto missingFiles = profile.getMissingContentFiles(selectedContentFiles); if (!missingFiles.empty() && !confirmLoading(missingFiles)) { cleanup(true); MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_MainMenu); return; } mTimePlayed = profile.mTimePlayed; Log(Debug::Info) << "Loading saved game '" << profile.mDescription << "' for character '" << profile.mPlayerName << "'"; } break; case ESM::REC_JOUR: case ESM::REC_QUES: MWBase::Environment::get().getJournal()->readRecord(reader, n.toInt()); break; case ESM::REC_DIAS: MWBase::Environment::get().getDialogueManager()->readRecord(reader, n.toInt()); break; case ESM::REC_ALCH: case ESM::REC_MISC: case ESM::REC_ACTI: case ESM::REC_ARMO: case ESM::REC_BOOK: case ESM::REC_CLAS: case ESM::REC_CLOT: case ESM::REC_ENCH: case ESM::REC_NPC_: case ESM::REC_SPEL: case ESM::REC_WEAP: case ESM::REC_GLOB: case ESM::REC_PLAY: case ESM::REC_CSTA: case ESM::REC_WTHR: case ESM::REC_DYNA: case ESM::REC_ACTC: case ESM::REC_PROJ: case ESM::REC_MPRJ: case ESM::REC_ENAB: case ESM::REC_LEVC: case ESM::REC_LEVI: case ESM::REC_LIGH: case ESM::REC_CREA: case ESM::REC_CONT: case ESM::REC_RAND: MWBase::Environment::get().getWorld()->readRecord(reader, n.toInt()); break; case ESM::REC_CAM_: reader.getHNT(firstPersonCam, "FIRS"); break; case ESM::REC_GSCR: MWBase::Environment::get().getScriptManager()->getGlobalScripts().readRecord(reader, n.toInt()); break; case ESM::REC_GMAP: case ESM::REC_KEYS: case ESM::REC_ASPL: case ESM::REC_MARK: MWBase::Environment::get().getWindowManager()->readRecord(reader, n.toInt()); break; case ESM::REC_DCOU: case ESM::REC_STLN: MWBase::Environment::get().getMechanicsManager()->readRecord(reader, n.toInt()); break; case ESM::REC_INPU: MWBase::Environment::get().getInputManager()->readRecord(reader, n.toInt()); break; case ESM::REC_LUAM: MWBase::Environment::get().getLuaManager()->readRecord(reader, n.toInt()); break; default: // ignore invalid records Log(Debug::Warning) << "Warning: Ignoring unknown record: " << n.toStringView(); reader.skipRecord(); } int progressPercent = static_cast<int>(float(reader.getFileOffset()) / total * 100); if (progressPercent > currentPercent) { listener.increaseProgress(progressPercent - currentPercent); currentPercent = progressPercent; } } mCharacterManager.setCurrentCharacter(character); mState = State_Running; if (character) Settings::saves().mCharacter.set(Files::pathToUnicodeString(character->getPath().filename())); mLastSavegame = filepath; MWBase::Environment::get().getWindowManager()->setNewGame(false); MWBase::Environment::get().getWorld()->saveLoaded(); MWBase::Environment::get().getWorld()->setupPlayer(); MWBase::Environment::get().getWorld()->renderPlayer(); MWBase::Environment::get().getWindowManager()->updatePlayer(); MWBase::Environment::get().getMechanicsManager()->playerLoaded(); MWBase::Environment::get().getWorld()->toggleVanityMode(false); if (firstPersonCam != MWBase::Environment::get().getWorld()->isFirstPerson()) MWBase::Environment::get().getWorld()->togglePOV(); MWWorld::ConstPtr ptr = MWMechanics::getPlayer(); if (ptr.isInCell()) { const ESM::RefId cellId = ptr.getCell()->getCell()->getId(); // Use detectWorldSpaceChange=false, otherwise some of the data we just loaded would be cleared again MWBase::Environment::get().getWorld()->changeToCell(cellId, ptr.getRefData().getPosition(), false, false); } else { // Cell no longer exists (i.e. changed game files), choose a default cell Log(Debug::Warning) << "Player character's cell no longer exists, changing to the default cell"; ESM::ExteriorCellLocation cellIndex(0, 0, ESM::Cell::sDefaultWorldspaceId); MWWorld::CellStore& cell = MWBase::Environment::get().getWorldModel()->getExterior(cellIndex); const osg::Vec2f posFromIndex = ESM::indexToPosition(cellIndex, false); ESM::Position pos; pos.pos[0] = posFromIndex.x(); pos.pos[1] = posFromIndex.y(); pos.pos[2] = 0; // should be adjusted automatically (adjustPlayerPos=true) pos.rot[0] = 0; pos.rot[1] = 0; pos.rot[2] = 0; MWBase::Environment::get().getWorld()->changeToCell(cell.getCell()->getId(), pos, true, false); } MWBase::Environment::get().getWorld()->updateProjectilesCasters(); // Vanilla MW will restart startup scripts when a save game is loaded. This is unintuitive, // but some mods may be using it as a reload detector. MWBase::Environment::get().getScriptManager()->getGlobalScripts().addStartup(); // Since we passed "changeEvent=false" to changeCell, we shouldn't have triggered the cell change flag. // But make sure the flag is cleared anyway in case it was set from an earlier game. MWBase::Environment::get().getWorldScene()->markCellAsUnchanged(); MWBase::Environment::get().getLuaManager()->gameLoaded(); } catch (const SaveVersionTooNewError& e) { std::string error = "#{OMWEngine:LoadingRequiresNewVersionError}"; printSavegameFormatError(e.what(), error); } catch (const SaveVersionTooOldError& e) { const char* release; // Report the last version still capable of reading this save if (e.getFormatVersion() <= ESM::OpenMW0_48SaveGameFormatVersion) release = "OpenMW 0.48.0"; else { // Insert additional else if statements above to cover future releases static_assert(ESM::MinSupportedSaveGameFormatVersion <= ESM::OpenMW0_49SaveGameFormatVersion); release = "OpenMW 0.49.0"; } auto l10n = MWBase::Environment::get().getL10nManager()->getContext("OMWEngine"); std::string error = l10n->formatMessage("LoadingRequiresOldVersionError", { "version" }, { release }); printSavegameFormatError(e.what(), error); } catch (const std::exception& e) { std::string error = "#{OMWEngine:LoadingFailed}: " + std::string(e.what()); printSavegameFormatError(e.what(), error); } } void MWState::StateManager::printSavegameFormatError( const std::string& exceptionText, const std::string& messageBoxText) { Log(Debug::Error) << "Failed to load saved game: " << exceptionText; cleanup(true); MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_MainMenu); std::vector<std::string> buttons; buttons.emplace_back("#{Interface:OK}"); MWBase::Environment::get().getWindowManager()->interactiveMessageBox(messageBoxText, buttons); } void MWState::StateManager::quickLoad() { if (Character* currentCharacter = getCurrentCharacter()) { if (currentCharacter->begin() == currentCharacter->end()) return; // use requestLoad, otherwise we can crash by loading during the wrong part of the frame requestLoad(currentCharacter->begin()->mPath); } } void MWState::StateManager::deleteGame(const MWState::Character* character, const MWState::Slot* slot) { const std::filesystem::path savePath = slot->mPath; mCharacterManager.deleteSlot(character, slot); if (mLastSavegame == savePath) { if (character->begin() != character->end()) mLastSavegame = character->begin()->mPath; else mLastSavegame.clear(); } } MWState::Character* MWState::StateManager::getCurrentCharacter() { return mCharacterManager.getCurrentCharacter(); } MWState::StateManager::CharacterIterator MWState::StateManager::characterBegin() { return mCharacterManager.begin(); } MWState::StateManager::CharacterIterator MWState::StateManager::characterEnd() { return mCharacterManager.end(); } void MWState::StateManager::update(float duration) { mTimePlayed += duration; // Note: It would be nicer to trigger this from InputManager, i.e. the very beginning of the frame update. if (mAskLoadRecent) { int iButton = MWBase::Environment::get().getWindowManager()->readPressedButton(); MWState::Character* curCharacter = getCurrentCharacter(); if (iButton == 0 && curCharacter) { mAskLoadRecent = false; // Load last saved game for current character // loadGame resets the game state along with mLastSavegame so we want to preserve it const std::filesystem::path filePath = std::move(mLastSavegame); loadGame(curCharacter, filePath); } else if (iButton == 1) { mAskLoadRecent = false; MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_MainMenu); } } if (mNewGameRequest) { newGame(); mNewGameRequest = false; } if (mLoadRequest) { loadGame(*mLoadRequest); mLoadRequest = std::nullopt; } } bool MWState::StateManager::confirmLoading(const std::vector<std::string_view>& missingFiles) const { std::ostringstream stream; for (auto& contentFile : missingFiles) { Log(Debug::Warning) << "Warning: Saved game dependency " << contentFile << " is missing."; stream << contentFile << "\n"; } auto fullList = stream.str(); if (!fullList.empty()) fullList.pop_back(); constexpr size_t missingPluginsDisplayLimit = 12; std::vector<std::string> buttons; buttons.emplace_back("#{Interface:Yes}"); buttons.emplace_back("#{Interface:Copy}"); buttons.emplace_back("#{Interface:No}"); std::string message = "#{OMWEngine:MissingContentFilesConfirmation}"; auto l10n = MWBase::Environment::get().getL10nManager()->getContext("OMWEngine"); message += l10n->formatMessage("MissingContentFilesList", { "files" }, { static_cast<int>(missingFiles.size()) }); auto cappedSize = std::min(missingFiles.size(), missingPluginsDisplayLimit); if (cappedSize == missingFiles.size()) { message += fullList; } else { for (size_t i = 0; i < cappedSize - 1; ++i) { message += missingFiles[i]; message += "\n"; } message += "..."; } message += l10n->formatMessage("MissingContentFilesListCopy", { "files" }, { static_cast<int>(missingFiles.size()) }); int selectedButton = -1; while (true) { auto windowManager = MWBase::Environment::get().getWindowManager(); windowManager->interactiveMessageBox(message, buttons, true, selectedButton); selectedButton = windowManager->readPressedButton(); if (selectedButton == 0) break; if (selectedButton == 1) { SDL_SetClipboardText(fullList.c_str()); continue; } return false; } return true; } void MWState::StateManager::writeScreenshot(std::vector<char>& imageData) const { int screenshotW = 259 * 2, screenshotH = 133 * 2; // *2 to get some nice antialiasing osg::ref_ptr<osg::Image> screenshot(new osg::Image); MWBase::Environment::get().getWorld()->screenshot(screenshot.get(), screenshotW, screenshotH); osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("jpg"); if (!readerwriter) { Log(Debug::Error) << "Error: Unable to write screenshot, can't find a jpg ReaderWriter"; return; } std::ostringstream ostream; osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(*screenshot, ostream); if (!result.success()) { Log(Debug::Error) << "Error: Unable to write screenshot: " << result.message() << " code " << result.status(); return; } std::string data = ostream.str(); imageData = std::vector<char>(data.begin(), data.end()); }
31,042
C++
.cpp
698
35.484241
120
0.63115
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,357
quicksavemanager.cpp
OpenMW_openmw/apps/openmw/mwstate/quicksavemanager.cpp
#include "quicksavemanager.hpp" MWState::QuickSaveManager::QuickSaveManager(std::string& saveName, unsigned int maxSaves) : mSaveName(saveName) , mMaxSaves(maxSaves) , mSlotsVisited(0) , mOldestSlotVisited(nullptr) { } void MWState::QuickSaveManager::visitSave(const Slot* saveSlot) { if (mSaveName == saveSlot->mProfile.mDescription) { ++mSlotsVisited; if (isOldestSave(saveSlot)) mOldestSlotVisited = saveSlot; } } bool MWState::QuickSaveManager::isOldestSave(const Slot* compare) const { if (mOldestSlotVisited == nullptr) return true; return (compare->mTimeStamp <= mOldestSlotVisited->mTimeStamp); } bool MWState::QuickSaveManager::shouldCreateNewSlot() const { return (mSlotsVisited < mMaxSaves); } const MWState::Slot* MWState::QuickSaveManager::getNextQuickSaveSlot() { if (shouldCreateNewSlot()) return nullptr; return mOldestSlotVisited; }
947
C++
.cpp
33
24.757576
89
0.738174
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,358
character.cpp
OpenMW_openmw/apps/openmw/mwstate/character.cpp
#include "character.hpp" #include <algorithm> #include <cctype> #include <filesystem> #include <sstream> #include <tuple> #include <utility> #include <components/debug/debuglog.hpp> #include <components/esm/defs.hpp> #include <components/esm3/esmreader.hpp> #include <components/misc/strings/algorithm.hpp> #include <components/misc/utf8stream.hpp> bool MWState::operator<(const Slot& left, const Slot& right) { return left.mTimeStamp < right.mTimeStamp; } std::string MWState::getFirstGameFile(const std::vector<std::string>& contentFiles) { for (const std::string& c : contentFiles) { if (Misc::StringUtils::ciEndsWith(c, ".esm") || Misc::StringUtils::ciEndsWith(c, ".omwgame")) return c; } return ""; } void MWState::Character::addSlot(const std::filesystem::path& path, const std::string& game) { Slot slot; slot.mPath = path; slot.mTimeStamp = std::filesystem::last_write_time(path); ESM::ESMReader reader; reader.open(slot.mPath); if (reader.getRecName() != ESM::REC_SAVE) return; // invalid save file -> ignore reader.getRecHeader(); slot.mProfile.load(reader); if (!Misc::StringUtils::ciEqual(getFirstGameFile(slot.mProfile.mContentFiles), game)) return; // this file is for a different game -> ignore mSlots.push_back(slot); } void MWState::Character::addSlot(const ESM::SavedGame& profile) { Slot slot; std::ostringstream stream; // The profile description is user-supplied, so we need to escape the path Utf8Stream description(profile.mDescription); while (!description.eof()) { auto c = description.consume(); if (c <= 0x7F && std::isalnum(c)) // Ignore multibyte characters and non alphanumeric characters stream << static_cast<char>(c); else stream << '_'; } const std::string ext = ".omwsave"; slot.mPath = mPath / (stream.str() + ext); // Append an index if necessary to ensure a unique file int i = 0; while (std::filesystem::exists(slot.mPath)) { const std::string test = stream.str() + " - " + std::to_string(++i); slot.mPath = mPath / (test + ext); } slot.mProfile = profile; slot.mTimeStamp = std::filesystem::file_time_type::clock::now(); mSlots.push_back(slot); } MWState::Character::Character(const std::filesystem::path& saves, const std::string& game) : mPath(saves) { if (!std::filesystem::is_directory(mPath)) { std::filesystem::create_directories(mPath); } else { for (const auto& iter : std::filesystem::directory_iterator(mPath)) { try { addSlot(iter, game); } catch (const std::exception& e) { Log(Debug::Warning) << "Failed to add slot for game \"" << game << "\" save " << iter << ": " << e.what(); } } std::sort(mSlots.begin(), mSlots.end()); } } void MWState::Character::cleanup() { if (mSlots.empty()) { // All slots are gone, no need to keep the empty directory if (std::filesystem::is_directory(mPath)) { // Extra safety check to make sure the directory is empty (e.g. slots failed to parse header) std::filesystem::directory_iterator it(mPath); if (it == std::filesystem::directory_iterator()) std::filesystem::remove_all(mPath); } } } const MWState::Slot* MWState::Character::createSlot(const ESM::SavedGame& profile) { addSlot(profile); return &mSlots.back(); } void MWState::Character::deleteSlot(const Slot* slot) { std::ptrdiff_t index = slot - mSlots.data(); if (index < 0 || static_cast<std::size_t>(index) >= mSlots.size()) { // sanity check; not entirely reliable throw std::logic_error("slot not found"); } std::filesystem::remove(slot->mPath); mSlots.erase(mSlots.begin() + index); } const MWState::Slot* MWState::Character::updateSlot(const Slot* slot, const ESM::SavedGame& profile) { std::ptrdiff_t index = slot - mSlots.data(); if (index < 0 || static_cast<std::size_t>(index) >= mSlots.size()) { // sanity check; not entirely reliable throw std::logic_error("slot not found"); } Slot newSlot = *slot; newSlot.mProfile = profile; newSlot.mTimeStamp = std::filesystem::file_time_type::clock::now(); mSlots.erase(mSlots.begin() + index); mSlots.push_back(newSlot); return &mSlots.back(); } MWState::Character::SlotIterator MWState::Character::begin() const { return mSlots.rbegin(); } MWState::Character::SlotIterator MWState::Character::end() const { return mSlots.rend(); } const ESM::SavedGame& MWState::Character::getSignature() const { if (mSlots.empty()) throw std::logic_error("character signature not available"); const auto tiePlayerLevelAndTimeStamp = [](const Slot& v) { return std::tie(v.mProfile.mPlayerLevel, v.mTimeStamp); }; const auto lessByPlayerLevelAndTimeStamp = [&](const Slot& l, const Slot& r) { return tiePlayerLevelAndTimeStamp(l) < tiePlayerLevelAndTimeStamp(r); }; return std::max_element(mSlots.begin(), mSlots.end(), lessByPlayerLevelAndTimeStamp)->mProfile; } const std::filesystem::path& MWState::Character::getPath() const { return mPath; }
5,455
C++
.cpp
158
28.917722
118
0.648088
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,359
charactermanager.cpp
OpenMW_openmw/apps/openmw/mwstate/charactermanager.cpp
#include "charactermanager.hpp" #include <cctype> #include <filesystem> #include <sstream> #include <utility> #include <components/misc/utf8stream.hpp> MWState::CharacterManager::CharacterManager(std::filesystem::path saves, const std::vector<std::string>& contentFiles) : mPath(std::move(saves)) , mCurrent(nullptr) , mGame(getFirstGameFile(contentFiles)) { if (!std::filesystem::is_directory(mPath)) { std::filesystem::create_directories(mPath); } else { for (std::filesystem::directory_iterator iter(mPath); iter != std::filesystem::directory_iterator(); ++iter) { std::filesystem::path characterDir = *iter; if (std::filesystem::is_directory(characterDir)) { Character character(characterDir, mGame); if (character.begin() != character.end()) mCharacters.push_back(character); } } } } MWState::Character* MWState::CharacterManager::getCurrentCharacter() { return mCurrent; } void MWState::CharacterManager::deleteSlot(const MWState::Character* character, const MWState::Slot* slot) { std::list<Character>::iterator it = findCharacter(character); it->deleteSlot(slot); if (character->begin() == character->end()) { // All slots deleted, cleanup and remove this character it->cleanup(); if (character == mCurrent) mCurrent = nullptr; mCharacters.erase(it); } } MWState::Character* MWState::CharacterManager::createCharacter(const std::string& name) { std::ostringstream stream; // The character name is user-supplied, so we need to escape the path Utf8Stream nameStream(name); while (!nameStream.eof()) { auto c = nameStream.consume(); if (c <= 0x7F && std::isalnum(c)) // Ignore multibyte characters and non alphanumeric characters stream << static_cast<char>(c); else stream << '_'; } std::filesystem::path path = mPath / stream.str(); // Append an index if necessary to ensure a unique directory int i = 0; while (std::filesystem::exists(path)) { std::ostringstream test; test << stream.str(); test << " - " << ++i; path = mPath / test.str(); } mCharacters.emplace_back(path, mGame); return &mCharacters.back(); } std::list<MWState::Character>::iterator MWState::CharacterManager::findCharacter(const MWState::Character* character) { std::list<Character>::iterator it = mCharacters.begin(); for (; it != mCharacters.end(); ++it) { if (&*it == character) break; } if (it == mCharacters.end()) throw std::logic_error("invalid character"); return it; } void MWState::CharacterManager::setCurrentCharacter(const Character* character) { if (!character) mCurrent = nullptr; else { std::list<Character>::iterator it = findCharacter(character); mCurrent = &*it; } } std::list<MWState::Character>::const_iterator MWState::CharacterManager::begin() const { return mCharacters.begin(); } std::list<MWState::Character>::const_iterator MWState::CharacterManager::end() const { return mCharacters.end(); }
3,288
C++
.cpp
102
26.421569
118
0.648879
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,360
stepper.cpp
OpenMW_openmw/apps/openmw/mwphysics/stepper.cpp
#include "stepper.hpp" #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <components/misc/constants.hpp> #include "collisiontype.hpp" #include "constants.hpp" #include "movementsolver.hpp" namespace MWPhysics { static bool canStepDown(const ActorTracer& stepper) { if (!stepper.mHitObject) return false; static const float sMaxSlopeCos = std::cos(osg::DegreesToRadians(Constants::sMaxSlope)); if (stepper.mPlaneNormal.z() <= sMaxSlopeCos) return false; return stepper.mHitObject->getBroadphaseHandle()->m_collisionFilterGroup != CollisionType_Actor; } Stepper::Stepper(const btCollisionWorld* colWorld, const btCollisionObject* colObj) : mColWorld(colWorld) , mColObj(colObj) { } bool Stepper::step( osg::Vec3f& position, osg::Vec3f& velocity, float& remainingTime, const bool& onGround, bool firstIteration) { if (velocity.x() == 0.0 && velocity.y() == 0.0) return false; // Stairstepping algorithms work by moving up to avoid the step, moving forwards, then moving back down onto the // ground. This algorithm has a couple of minor problems, but they don't cause problems for sane geometry, and // just prevent stepping on insane geometry. mUpStepper.doTrace( mColObj, position, position + osg::Vec3f(0.0f, 0.0f, Constants::sStepSizeUp), mColWorld, onGround); float upDistance = 0; if (!mUpStepper.mHitObject) upDistance = Constants::sStepSizeUp; else if (mUpStepper.mFraction * Constants::sStepSizeUp > sCollisionMargin) upDistance = mUpStepper.mFraction * Constants::sStepSizeUp - sCollisionMargin; else { return false; } auto toMove = velocity * remainingTime; osg::Vec3f tracerPos = position + osg::Vec3f(0.0f, 0.0f, upDistance); osg::Vec3f tracerDest; auto normalMove = toMove; auto moveDistance = normalMove.normalize(); // attempt 1: normal movement // attempt 2: fixed distance movement, only happens on the first movement solver iteration/bounce each frame to // avoid a glitch attempt 3: further, less tall fixed distance movement, same as above If you're making a full // conversion you should purge the logic for attempts 2 and 3. Attempts 2 and 3 just try to work around problems // with vanilla Morrowind assets. int attempt = 0; float downStepSize = 0; while (attempt < 3) { attempt++; if (attempt == 1) tracerDest = tracerPos + toMove; else if (!sDoExtraStairHacks) // early out if we have extra hacks disabled { return false; } else if (attempt == 2) { moveDistance = sMinStep; tracerDest = tracerPos + normalMove * sMinStep; } else if (attempt == 3) { if (upDistance > Constants::sStepSizeUp) { upDistance = Constants::sStepSizeUp; tracerPos = position + osg::Vec3f(0.0f, 0.0f, upDistance); } moveDistance = sMinStep2; tracerDest = tracerPos + normalMove * sMinStep2; } mTracer.doTrace(mColObj, tracerPos, tracerDest, mColWorld); if (mTracer.mHitObject) { // map against what we hit, minus the safety margin moveDistance *= mTracer.mFraction; if (moveDistance <= sCollisionMargin) // didn't move enough to accomplish anything { return false; } moveDistance -= sCollisionMargin; tracerDest = tracerPos + normalMove * moveDistance; // safely eject from what we hit by the safety margin auto tempDest = tracerDest + mTracer.mPlaneNormal * sCollisionMargin * 2; ActorTracer tempTracer; tempTracer.doTrace(mColObj, tracerDest, tempDest, mColWorld); if (tempTracer.mFraction > 0.5f) // distance to any object is greater than sCollisionMargin (we checked // sCollisionMargin*2 distance) { auto effectiveFraction = tempTracer.mFraction * 2.0f - 1.0f; tracerDest += mTracer.mPlaneNormal * sCollisionMargin * effectiveFraction; } } if (attempt > 2) // do not allow stepping down below original height for attempt 3 downStepSize = upDistance; else downStepSize = moveDistance + upDistance + sStepSizeDown; mDownStepper.doTrace( mColObj, tracerDest, tracerDest + osg::Vec3f(0.0f, 0.0f, -downStepSize), mColWorld, onGround); // can't step down onto air, non-walkable-slopes, or actors // NOTE: using a capsule causes isWalkableSlope (used in canStepDown) to fail on certain geometry that were // intended to be valid at the bottoms of stairs (like the bottoms of the staircases in aldruhn's guild of // mages) The old code worked around this by trying to do mTracer again with a fixed distance of sMinStep // (10.0) but it caused all sorts of other problems. Switched back to cylinders to avoid that and similer // problems. if (canStepDown(mDownStepper)) { break; } else { // do not try attempt 3 if we just tried attempt 2 and the horizontal distance was rather large // (forces actor to get snug against the defective ledge for attempt 3 to be tried) if (attempt == 2 && moveDistance > upDistance - (mDownStepper.mFraction * downStepSize)) { return false; } // do next attempt if first iteration of movement solver and not out of attempts if (firstIteration && attempt < 3) { continue; } return false; } } // note: can't downstep onto actors so no need to pick safety margin float downDistance = 0; if (mDownStepper.mFraction * downStepSize > sCollisionMargin) downDistance = mDownStepper.mFraction * downStepSize - sCollisionMargin; if (downDistance - sCollisionMargin - sGroundOffset > upDistance && !onGround) return false; auto newpos = tracerDest + osg::Vec3f(0.0f, 0.0f, -downDistance); if ((position - newpos).length2() < sCollisionMargin * sCollisionMargin) return false; if (mTracer.mHitObject) { auto planeNormal = mTracer.mPlaneNormal; if (onGround && !isWalkableSlope(planeNormal) && planeNormal.z() != 0) { planeNormal.z() = 0; planeNormal.normalize(); } velocity = reject(velocity, planeNormal); } velocity = reject(velocity, mDownStepper.mPlaneNormal); position = newpos; remainingTime *= (1.0f - mTracer.mFraction); // remaining time is proportional to remaining distance return true; } }
7,589
C++
.cpp
157
35.961783
120
0.599892
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,361
mtphysics.cpp
OpenMW_openmw/apps/openmw/mwphysics/mtphysics.cpp
#include "mtphysics.hpp" #include <cassert> #include <functional> #include <mutex> #include <optional> #include <shared_mutex> #include <stdexcept> #include <variant> #include <BulletCollision/BroadphaseCollision/btDbvtBroadphase.h> #include <BulletCollision/CollisionShapes/btCollisionShape.h> #include <LinearMath/btThreads.h> #include <osg/Stats> #include "components/debug/debuglog.hpp" #include "components/misc/convert.hpp" #include <components/misc/barrier.hpp> #include <components/settings/values.hpp> #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwrender/bulletdebugdraw.hpp" #include "../mwworld/class.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "actor.hpp" #include "contacttestwrapper.h" #include "movementsolver.hpp" #include "object.hpp" #include "physicssystem.hpp" #include "projectile.hpp" namespace MWPhysics { namespace { template <class Mutex> std::optional<std::unique_lock<Mutex>> makeExclusiveLock(Mutex& mutex, LockingPolicy lockingPolicy) { if (lockingPolicy == LockingPolicy::NoLocks) return {}; return std::unique_lock(mutex); } /// @brief A scoped lock that is either exclusive or inexistent depending on configuration template <class Mutex> class MaybeExclusiveLock { public: /// @param mutex a mutex /// @param threadCount decide wether the excluse lock will be taken explicit MaybeExclusiveLock(Mutex& mutex, LockingPolicy lockingPolicy) : mImpl(makeExclusiveLock(mutex, lockingPolicy)) { } private: std::optional<std::unique_lock<Mutex>> mImpl; }; template <class Mutex> std::optional<std::shared_lock<Mutex>> makeSharedLock(Mutex& mutex, LockingPolicy lockingPolicy) { if (lockingPolicy == LockingPolicy::NoLocks) return {}; return std::shared_lock(mutex); } /// @brief A scoped lock that is either shared or inexistent depending on configuration template <class Mutex> class MaybeSharedLock { public: /// @param mutex a shared mutex /// @param threadCount decide wether the shared lock will be taken explicit MaybeSharedLock(Mutex& mutex, LockingPolicy lockingPolicy) : mImpl(makeSharedLock(mutex, lockingPolicy)) { } private: std::optional<std::shared_lock<Mutex>> mImpl; }; template <class Mutex> std::variant<std::monostate, std::unique_lock<Mutex>, std::shared_lock<Mutex>> makeLock( Mutex& mutex, LockingPolicy lockingPolicy) { switch (lockingPolicy) { case LockingPolicy::NoLocks: return std::monostate{}; case LockingPolicy::ExclusiveLocksOnly: return std::unique_lock(mutex); case LockingPolicy::AllowSharedLocks: return std::shared_lock(mutex); }; throw std::runtime_error("Unsupported LockingPolicy: " + std::to_string(static_cast<std::underlying_type_t<LockingPolicy>>(lockingPolicy))); } /// @brief A scoped lock that is either shared, exclusive or inexistent depending on configuration template <class Mutex> class MaybeLock { public: /// @param mutex a shared mutex /// @param threadCount decide wether the lock will be shared, exclusive or inexistent explicit MaybeLock(Mutex& mutex, LockingPolicy lockingPolicy) : mImpl(makeLock(mutex, lockingPolicy)) { } private: std::variant<std::monostate, std::unique_lock<Mutex>, std::shared_lock<Mutex>> mImpl; }; } } namespace { bool isUnderWater(const MWPhysics::ActorFrameData& actorData) { return actorData.mPosition.z() < actorData.mSwimLevel; } osg::Vec3f interpolateMovements(const MWPhysics::PtrHolder& ptr, float timeAccum, float physicsDt) { const float interpolationFactor = std::clamp(timeAccum / physicsDt, 0.0f, 1.0f); return ptr.getPosition() * interpolationFactor + ptr.getPreviousPosition() * (1.f - interpolationFactor); } using LockedActorSimulation = std::pair<std::shared_ptr<MWPhysics::Actor>, std::reference_wrapper<MWPhysics::ActorFrameData>>; using LockedProjectileSimulation = std::pair<std::shared_ptr<MWPhysics::Projectile>, std::reference_wrapper<MWPhysics::ProjectileFrameData>>; namespace Visitors { template <class Impl, template <class> class Lock> struct WithLockedPtr { const Impl& mImpl; std::shared_mutex& mCollisionWorldMutex; const MWPhysics::LockingPolicy mLockingPolicy; template <class Ptr, class FrameData> void operator()(MWPhysics::SimulationImpl<Ptr, FrameData>& sim) const { auto locked = sim.lock(); if (!locked.has_value()) return; auto&& [ptr, frameData] = *std::move(locked); // Locked shared_ptr has to be destructed after releasing mCollisionWorldMutex to avoid // possible deadlock. Ptr destructor also acquires mCollisionWorldMutex. const std::pair arg(std::move(ptr), frameData); const Lock<std::shared_mutex> lock(mCollisionWorldMutex, mLockingPolicy); mImpl(arg); } }; struct InitPosition { const btCollisionWorld* mCollisionWorld; void operator()(MWPhysics::ActorSimulation& sim) const { auto locked = sim.lock(); if (!locked.has_value()) return; auto& [actor, frameDataRef] = *locked; auto& frameData = frameDataRef.get(); frameData.mPosition = actor->applyOffsetChange(); if (frameData.mWaterCollision && frameData.mPosition.z() < frameData.mWaterlevel && actor->canMoveToWaterSurface(frameData.mWaterlevel, mCollisionWorld)) { const auto offset = osg::Vec3f(0, 0, frameData.mWaterlevel - frameData.mPosition.z()); MWBase::Environment::get().getWorld()->moveObjectBy(actor->getPtr(), offset, false); frameData.mPosition = actor->applyOffsetChange(); } actor->updateCollisionObjectPosition(); frameData.mOldHeight = frameData.mPosition.z(); const auto rotation = actor->getPtr().getRefData().getPosition().asRotationVec3(); frameData.mRotation = osg::Vec2f(rotation.x(), rotation.z()); frameData.mInertia = actor->getInertialForce(); frameData.mStuckFrames = actor->getStuckFrames(); frameData.mLastStuckPosition = actor->getLastStuckPosition(); } void operator()(MWPhysics::ProjectileSimulation& /*sim*/) const {} }; struct PreStep { btCollisionWorld* mCollisionWorld; void operator()(const LockedActorSimulation& sim) const { MWPhysics::MovementSolver::unstuck(sim.second, mCollisionWorld); } void operator()(const LockedProjectileSimulation& /*sim*/) const {} }; struct UpdatePosition { btCollisionWorld* mCollisionWorld; void operator()(const LockedActorSimulation& sim) const { auto& [actor, frameDataRef] = sim; auto& frameData = frameDataRef.get(); if (actor->setPosition(frameData.mPosition)) { frameData.mPosition = actor->getPosition(); // account for potential position change made by script actor->updateCollisionObjectPosition(); mCollisionWorld->updateSingleAabb(actor->getCollisionObject()); } } void operator()(const LockedProjectileSimulation& sim) const { auto& [proj, frameDataRef] = sim; auto& frameData = frameDataRef.get(); proj->setPosition(frameData.mPosition); proj->updateCollisionObjectPosition(); mCollisionWorld->updateSingleAabb(proj->getCollisionObject()); } }; struct Move { const float mPhysicsDt; const btCollisionWorld* mCollisionWorld; const MWPhysics::WorldFrameData& mWorldFrameData; void operator()(const LockedActorSimulation& sim) const { MWPhysics::MovementSolver::move(sim.second, mPhysicsDt, mCollisionWorld, mWorldFrameData); } void operator()(const LockedProjectileSimulation& sim) const { if (sim.first->isActive()) MWPhysics::MovementSolver::move(sim.second, mPhysicsDt, mCollisionWorld); } }; struct Sync { const bool mAdvanceSimulation; const float mTimeAccum; const float mPhysicsDt; const MWPhysics::PhysicsTaskScheduler* scheduler; void operator()(MWPhysics::ActorSimulation& sim) const { auto locked = sim.lock(); if (!locked.has_value()) return; auto& [actor, frameDataRef] = *locked; auto& frameData = frameDataRef.get(); auto ptr = actor->getPtr(); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); const float heightDiff = frameData.mPosition.z() - frameData.mOldHeight; const bool isStillOnGround = (mAdvanceSimulation && frameData.mWasOnGround && frameData.mIsOnGround); if (isStillOnGround || frameData.mFlying || isUnderWater(frameData) || frameData.mSlowFall < 1) stats.land(ptr == MWMechanics::getPlayer() && (frameData.mFlying || isUnderWater(frameData))); else if (heightDiff < 0) stats.addToFallHeight(-heightDiff); actor->setSimulationPosition(::interpolateMovements(*actor, mTimeAccum, mPhysicsDt)); actor->setLastStuckPosition(frameData.mLastStuckPosition); actor->setStuckFrames(frameData.mStuckFrames); if (mAdvanceSimulation) { MWWorld::Ptr standingOn; if (frameData.mStandingOn != nullptr) { auto* const ptrHolder = static_cast<MWPhysics::PtrHolder*>(scheduler->getUserPointer(frameData.mStandingOn)); if (ptrHolder != nullptr) standingOn = ptrHolder->getPtr(); } actor->setStandingOnPtr(standingOn); // the "on ground" state of an actor might have been updated by a traceDown, don't overwrite the // change if (actor->getOnGround() == frameData.mWasOnGround) actor->setOnGround(frameData.mIsOnGround); actor->setOnSlope(frameData.mIsOnSlope); actor->setWalkingOnWater(frameData.mWalkingOnWater); actor->setInertialForce(frameData.mInertia); } } void operator()(MWPhysics::ProjectileSimulation& sim) const { auto locked = sim.lock(); if (!locked.has_value()) return; auto& [proj, frameData] = *locked; proj->setSimulationPosition(::interpolateMovements(*proj, mTimeAccum, mPhysicsDt)); } }; } } namespace MWPhysics { namespace { unsigned getMaxBulletSupportedThreads() { auto broad = std::make_unique<btDbvtBroadphase>(); assert(BT_MAX_THREAD_COUNT > 0); return std::min<unsigned>(broad->m_rayTestStacks.size(), BT_MAX_THREAD_COUNT - 1); } LockingPolicy detectLockingPolicy() { if (Settings::physics().mAsyncNumThreads < 1) return LockingPolicy::NoLocks; if (getMaxBulletSupportedThreads() > 1) return LockingPolicy::AllowSharedLocks; Log(Debug::Warning) << "Bullet was not compiled with multithreading support, 1 async thread will be used"; return LockingPolicy::ExclusiveLocksOnly; } unsigned getNumThreads(LockingPolicy lockingPolicy) { switch (lockingPolicy) { case LockingPolicy::NoLocks: return 0; case LockingPolicy::ExclusiveLocksOnly: return 1; case LockingPolicy::AllowSharedLocks: return static_cast<unsigned>(std::clamp<int>( Settings::physics().mAsyncNumThreads, 0, static_cast<int>(getMaxBulletSupportedThreads()))); } throw std::runtime_error("Unsupported LockingPolicy: " + std::to_string(static_cast<std::underlying_type_t<LockingPolicy>>(lockingPolicy))); } } class PhysicsTaskScheduler::WorkersSync { public: void waitForWorkers() { std::unique_lock lock(mWorkersDoneMutex); if (mFrameCounter != mWorkersFrameCounter) mWorkersDone.wait(lock); } void wakeUpWorkers() { const std::lock_guard lock(mHasJobMutex); ++mFrameCounter; mHasJob.notify_all(); } void stopWorkers() { const std::lock_guard lock(mHasJobMutex); mShouldStop = true; mHasJob.notify_all(); } void workIsDone() { const std::lock_guard lock(mWorkersDoneMutex); ++mWorkersFrameCounter; mWorkersDone.notify_all(); } template <class F> void runWorker(F&& f) noexcept { std::size_t lastFrame = 0; std::unique_lock lock(mHasJobMutex); while (!mShouldStop) { mHasJob.wait(lock, [&] { return mShouldStop || mFrameCounter != lastFrame; }); lastFrame = mFrameCounter; lock.unlock(); f(); lock.lock(); } } private: std::size_t mWorkersFrameCounter = 0; std::condition_variable mWorkersDone; std::mutex mWorkersDoneMutex; std::condition_variable mHasJob; bool mShouldStop = false; std::size_t mFrameCounter = 0; std::mutex mHasJobMutex; }; PhysicsTaskScheduler::PhysicsTaskScheduler( float physicsDt, btCollisionWorld* collisionWorld, MWRender::DebugDrawer* debugDrawer) : mDefaultPhysicsDt(physicsDt) , mPhysicsDt(physicsDt) , mTimeAccum(0.f) , mCollisionWorld(collisionWorld) , mDebugDrawer(debugDrawer) , mLockingPolicy(detectLockingPolicy()) , mNumThreads(getNumThreads(mLockingPolicy)) , mNumJobs(0) , mRemainingSteps(0) , mLOSCacheExpiry(Settings::physics().mLineofsightKeepInactiveCache) , mAdvanceSimulation(false) , mNextJob(0) , mNextLOS(0) , mFrameNumber(0) , mTimer(osg::Timer::instance()) , mPrevStepCount(1) , mBudget(physicsDt) , mAsyncBudget(0.0f) , mBudgetCursor(0) , mAsyncStartTime(0) , mTimeBegin(0) , mTimeEnd(0) , mFrameStart(0) , mWorkersSync(mNumThreads >= 1 ? std::make_unique<WorkersSync>() : nullptr) { if (mNumThreads >= 1) { Log(Debug::Info) << "Using " << mNumThreads << " async physics threads"; for (unsigned i = 0; i < mNumThreads; ++i) mThreads.emplace_back([&] { worker(); }); } else { mLOSCacheExpiry = 0; } mPreStepBarrier = std::make_unique<Misc::Barrier>(mNumThreads); mPostStepBarrier = std::make_unique<Misc::Barrier>(mNumThreads); mPostSimBarrier = std::make_unique<Misc::Barrier>(mNumThreads); } PhysicsTaskScheduler::~PhysicsTaskScheduler() { waitForWorkers(); { MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy); mNumJobs = 0; mRemainingSteps = 0; } if (mWorkersSync != nullptr) mWorkersSync->stopWorkers(); for (auto& thread : mThreads) thread.join(); } std::tuple<int, float> PhysicsTaskScheduler::calculateStepConfig(float timeAccum) const { int maxAllowedSteps = 2; int numSteps = timeAccum / mDefaultPhysicsDt; // adjust maximum step count based on whether we're likely physics bottlenecked or not // if maxAllowedSteps ends up higher than numSteps, we will not invoke delta time // if it ends up lower than numSteps, but greater than 1, we will run a number of true delta time physics steps // that we expect to be within budget if it ends up lower than numSteps and also 1, we will run a single delta // time physics step if we did not do this, and had a fixed step count limit, we would have an unnecessarily low // render framerate if we were only physics bottlenecked, and we would be unnecessarily invoking true delta time // if we were only render bottlenecked // get physics timing stats float budgetMeasurement = std::max(mBudget.get(), mAsyncBudget.get()); // time spent per step in terms of the intended physics framerate budgetMeasurement /= mDefaultPhysicsDt; // ensure sane minimum value budgetMeasurement = std::max(0.00001f, budgetMeasurement); // we're spending almost or more than realtime per physics frame; limit to a single step if (budgetMeasurement > 0.95) maxAllowedSteps = 1; // physics is fairly cheap; limit based on expense if (budgetMeasurement < 0.5) maxAllowedSteps = std::ceil(1.0 / budgetMeasurement); // limit to a reasonable amount maxAllowedSteps = std::min(10, maxAllowedSteps); // fall back to delta time for this frame if fixed timestep physics would fall behind float actualDelta = mDefaultPhysicsDt; if (numSteps > maxAllowedSteps) { numSteps = maxAllowedSteps; // ensure that we do not simulate a frame ahead when doing delta time; this reduces stutter and latency // this causes interpolation to 100% use the most recent physics result when true delta time is happening // and we deliberately simulate up to exactly the timestamp that we want to render actualDelta = timeAccum / float(numSteps + 1); // actually: if this results in a per-step delta less than the target physics steptime, clamp it // this might reintroduce some stutter, but only comes into play in obscure cases // (because numSteps is originally based on mDefaultPhysicsDt, this won't cause us to overrun) actualDelta = std::max(actualDelta, mDefaultPhysicsDt); } return std::make_tuple(numSteps, actualDelta); } void PhysicsTaskScheduler::applyQueuedMovements(float& timeAccum, std::vector<Simulation>& simulations, osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats) { assert(mSimulations != &simulations); waitForWorkers(); prepareWork(timeAccum, simulations, frameStart, frameNumber, stats); if (mWorkersSync != nullptr) mWorkersSync->wakeUpWorkers(); } void PhysicsTaskScheduler::prepareWork(float& timeAccum, std::vector<Simulation>& simulations, osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats) { // This function run in the main thread. // While the mSimulationMutex is held, background physics threads can't run. MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy); double timeStart = mTimer->tick(); // start by finishing previous background computation if (mNumThreads != 0) { syncWithMainThread(); if (mAdvanceSimulation) mAsyncBudget.update(mTimer->delta_s(mAsyncStartTime, mTimeEnd), mPrevStepCount, mBudgetCursor); updateStats(frameStart, frameNumber, stats); } auto [numSteps, newDelta] = calculateStepConfig(timeAccum); timeAccum -= numSteps * newDelta; // init const Visitors::InitPosition vis{ mCollisionWorld }; for (auto& sim : simulations) { std::visit(vis, sim); } mPrevStepCount = numSteps; mRemainingSteps = numSteps; mTimeAccum = timeAccum; mPhysicsDt = newDelta; mSimulations = &simulations; mAdvanceSimulation = (mRemainingSteps != 0); mNumJobs = mSimulations->size(); mNextLOS.store(0, std::memory_order_relaxed); mNextJob.store(0, std::memory_order_release); if (mAdvanceSimulation) mWorldFrameData = std::make_unique<WorldFrameData>(); if (mAdvanceSimulation) mBudgetCursor += 1; if (mNumThreads == 0) { doSimulation(); syncWithMainThread(); if (mAdvanceSimulation) mBudget.update(mTimer->delta_s(timeStart, mTimer->tick()), numSteps, mBudgetCursor); return; } mAsyncStartTime = mTimer->tick(); if (mAdvanceSimulation) mBudget.update(mTimer->delta_s(timeStart, mTimer->tick()), 1, mBudgetCursor); } void PhysicsTaskScheduler::resetSimulation(const ActorMap& actors) { waitForWorkers(); MaybeExclusiveLock lock(mSimulationMutex, mLockingPolicy); mBudget.reset(mDefaultPhysicsDt); mAsyncBudget.reset(0.0f); if (mSimulations != nullptr) { mSimulations->clear(); mSimulations = nullptr; } for (const auto& [_, actor] : actors) { actor->updatePosition(); actor->updateCollisionObjectPosition(); } } void PhysicsTaskScheduler::rayTest(const btVector3& rayFromWorld, const btVector3& rayToWorld, btCollisionWorld::RayResultCallback& resultCallback) const { MaybeLock lock(mCollisionWorldMutex, mLockingPolicy); mCollisionWorld->rayTest(rayFromWorld, rayToWorld, resultCallback); } void PhysicsTaskScheduler::convexSweepTest(const btConvexShape* castShape, const btTransform& from, const btTransform& to, btCollisionWorld::ConvexResultCallback& resultCallback) const { MaybeLock lock(mCollisionWorldMutex, mLockingPolicy); mCollisionWorld->convexSweepTest(castShape, from, to, resultCallback); } void PhysicsTaskScheduler::contactTest( btCollisionObject* colObj, btCollisionWorld::ContactResultCallback& resultCallback) { MaybeSharedLock lock(mCollisionWorldMutex, mLockingPolicy); ContactTestWrapper::contactTest(mCollisionWorld, colObj, resultCallback); } std::optional<btVector3> PhysicsTaskScheduler::getHitPoint(const btTransform& from, btCollisionObject* target) { MaybeLock lock(mCollisionWorldMutex, mLockingPolicy); // target the collision object's world origin, this should be the center of the collision object btTransform rayTo; rayTo.setIdentity(); rayTo.setOrigin(target->getWorldTransform().getOrigin()); btCollisionWorld::ClosestRayResultCallback cb(from.getOrigin(), rayTo.getOrigin()); mCollisionWorld->rayTestSingle( from, rayTo, target, target->getCollisionShape(), target->getWorldTransform(), cb); if (!cb.hasHit()) // didn't hit the target. this could happen if point is already inside the collision box return std::nullopt; return { cb.m_hitPointWorld }; } void PhysicsTaskScheduler::aabbTest( const btVector3& aabbMin, const btVector3& aabbMax, btBroadphaseAabbCallback& callback) { MaybeSharedLock lock(mCollisionWorldMutex, mLockingPolicy); mCollisionWorld->getBroadphase()->aabbTest(aabbMin, aabbMax, callback); } void PhysicsTaskScheduler::getAabb(const btCollisionObject* obj, btVector3& min, btVector3& max) { MaybeSharedLock lock(mCollisionWorldMutex, mLockingPolicy); obj->getCollisionShape()->getAabb(obj->getWorldTransform(), min, max); } void PhysicsTaskScheduler::setCollisionFilterMask(btCollisionObject* collisionObject, int collisionFilterMask) { MaybeExclusiveLock lock(mCollisionWorldMutex, mLockingPolicy); collisionObject->getBroadphaseHandle()->m_collisionFilterMask = collisionFilterMask; } void PhysicsTaskScheduler::addCollisionObject( btCollisionObject* collisionObject, int collisionFilterGroup, int collisionFilterMask) { MaybeExclusiveLock lock(mCollisionWorldMutex, mLockingPolicy); mCollisionObjects.insert(collisionObject); mCollisionWorld->addCollisionObject(collisionObject, collisionFilterGroup, collisionFilterMask); } void PhysicsTaskScheduler::removeCollisionObject(btCollisionObject* collisionObject) { MaybeExclusiveLock lock(mCollisionWorldMutex, mLockingPolicy); mCollisionObjects.erase(collisionObject); mCollisionWorld->removeCollisionObject(collisionObject); } void PhysicsTaskScheduler::updateSingleAabb(const std::shared_ptr<PtrHolder>& ptr, bool immediate) { if (immediate || mNumThreads == 0) { updatePtrAabb(ptr); } else { MaybeExclusiveLock lock(mUpdateAabbMutex, mLockingPolicy); mUpdateAabb.insert(ptr); } } bool PhysicsTaskScheduler::getLineOfSight( const std::shared_ptr<Actor>& actor1, const std::shared_ptr<Actor>& actor2) { MaybeExclusiveLock lock(mLOSCacheMutex, mLockingPolicy); auto req = LOSRequest(actor1, actor2); auto result = std::find(mLOSCache.begin(), mLOSCache.end(), req); if (result == mLOSCache.end()) { req.mResult = hasLineOfSight(actor1.get(), actor2.get()); mLOSCache.push_back(req); return req.mResult; } result->mAge = 0; return result->mResult; } void PhysicsTaskScheduler::refreshLOSCache() { MaybeSharedLock lock(mLOSCacheMutex, mLockingPolicy); int job = 0; int numLOS = mLOSCache.size(); while ((job = mNextLOS.fetch_add(1, std::memory_order_relaxed)) < numLOS) { auto& req = mLOSCache[job]; auto actorPtr1 = req.mActors[0].lock(); auto actorPtr2 = req.mActors[1].lock(); if (req.mAge++ > mLOSCacheExpiry || !actorPtr1 || !actorPtr2) req.mStale = true; else req.mResult = hasLineOfSight(actorPtr1.get(), actorPtr2.get()); } } void PhysicsTaskScheduler::updateAabbs() { MaybeExclusiveLock lock(mUpdateAabbMutex, mLockingPolicy); std::for_each(mUpdateAabb.begin(), mUpdateAabb.end(), [this](const std::weak_ptr<PtrHolder>& ptr) { auto p = ptr.lock(); if (p != nullptr) updatePtrAabb(p); }); mUpdateAabb.clear(); } void PhysicsTaskScheduler::updatePtrAabb(const std::shared_ptr<PtrHolder>& ptr) { MaybeExclusiveLock lock(mCollisionWorldMutex, mLockingPolicy); if (const auto actor = std::dynamic_pointer_cast<Actor>(ptr)) { actor->updateCollisionObjectPosition(); mCollisionWorld->updateSingleAabb(actor->getCollisionObject()); } else if (const auto object = std::dynamic_pointer_cast<Object>(ptr)) { object->commitPositionChange(); mCollisionWorld->updateSingleAabb(object->getCollisionObject()); } else if (const auto projectile = std::dynamic_pointer_cast<Projectile>(ptr)) { projectile->updateCollisionObjectPosition(); mCollisionWorld->updateSingleAabb(projectile->getCollisionObject()); } } void PhysicsTaskScheduler::worker() { mWorkersSync->runWorker([this] { std::shared_lock lock(mSimulationMutex); doSimulation(); }); } void PhysicsTaskScheduler::updateActorsPositions() { const Visitors::UpdatePosition impl{ mCollisionWorld }; const Visitors::WithLockedPtr<Visitors::UpdatePosition, MaybeExclusiveLock> vis{ impl, mCollisionWorldMutex, mLockingPolicy }; for (Simulation& sim : *mSimulations) std::visit(vis, sim); } bool PhysicsTaskScheduler::hasLineOfSight(const Actor* actor1, const Actor* actor2) { btVector3 pos1 = Misc::Convert::toBullet( actor1->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor1->getHalfExtents().z() * 0.9)); // eye level btVector3 pos2 = Misc::Convert::toBullet( actor2->getCollisionObjectPosition() + osg::Vec3f(0, 0, actor2->getHalfExtents().z() * 0.9)); btCollisionWorld::ClosestRayResultCallback resultCallback(pos1, pos2); resultCallback.m_collisionFilterGroup = CollisionType_AnyPhysical; resultCallback.m_collisionFilterMask = CollisionType_World | CollisionType_HeightMap | CollisionType_Door; MaybeLock lockColWorld(mCollisionWorldMutex, mLockingPolicy); mCollisionWorld->rayTest(pos1, pos2, resultCallback); return !resultCallback.hasHit(); } void PhysicsTaskScheduler::doSimulation() { while (mRemainingSteps) { mPreStepBarrier->wait([this] { afterPreStep(); }); int job = 0; const Visitors::Move impl{ mPhysicsDt, mCollisionWorld, *mWorldFrameData }; const Visitors::WithLockedPtr<Visitors::Move, MaybeLock> vis{ impl, mCollisionWorldMutex, mLockingPolicy }; while ((job = mNextJob.fetch_add(1, std::memory_order_relaxed)) < mNumJobs) std::visit(vis, (*mSimulations)[job]); mPostStepBarrier->wait([this] { afterPostStep(); }); } refreshLOSCache(); mPostSimBarrier->wait([this] { afterPostSim(); }); } void PhysicsTaskScheduler::updateStats(osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats) { if (!stats.collectStats("engine")) return; if (mFrameNumber == frameNumber - 1) { stats.setAttribute(mFrameNumber, "physicsworker_time_begin", mTimer->delta_s(mFrameStart, mTimeBegin)); stats.setAttribute(mFrameNumber, "physicsworker_time_taken", mTimer->delta_s(mTimeBegin, mTimeEnd)); stats.setAttribute(mFrameNumber, "physicsworker_time_end", mTimer->delta_s(mFrameStart, mTimeEnd)); } mFrameStart = frameStart; mTimeBegin = mTimer->tick(); mFrameNumber = frameNumber; } void PhysicsTaskScheduler::debugDraw() { MaybeSharedLock lock(mCollisionWorldMutex, mLockingPolicy); mDebugDrawer->step(); } void* PhysicsTaskScheduler::getUserPointer(const btCollisionObject* object) const { auto it = mCollisionObjects.find(object); if (it == mCollisionObjects.end()) return nullptr; return (*it)->getUserPointer(); } void PhysicsTaskScheduler::releaseSharedStates() { waitForWorkers(); std::scoped_lock lock(mSimulationMutex, mUpdateAabbMutex); if (mSimulations != nullptr) { mSimulations->clear(); mSimulations = nullptr; } mUpdateAabb.clear(); } void PhysicsTaskScheduler::afterPreStep() { updateAabbs(); if (!mRemainingSteps) return; const Visitors::PreStep impl{ mCollisionWorld }; const Visitors::WithLockedPtr<Visitors::PreStep, MaybeExclusiveLock> vis{ impl, mCollisionWorldMutex, mLockingPolicy }; for (auto& sim : *mSimulations) std::visit(vis, sim); } void PhysicsTaskScheduler::afterPostStep() { if (mRemainingSteps) { --mRemainingSteps; updateActorsPositions(); } mNextJob.store(0, std::memory_order_release); } void PhysicsTaskScheduler::afterPostSim() { { MaybeExclusiveLock lock(mLOSCacheMutex, mLockingPolicy); mLOSCache.erase( std::remove_if(mLOSCache.begin(), mLOSCache.end(), [](const LOSRequest& req) { return req.mStale; }), mLOSCache.end()); } mTimeEnd = mTimer->tick(); if (mWorkersSync != nullptr) mWorkersSync->workIsDone(); } void PhysicsTaskScheduler::syncWithMainThread() { if (mSimulations == nullptr) return; const Visitors::Sync vis{ mAdvanceSimulation, mTimeAccum, mPhysicsDt, this }; for (auto& sim : *mSimulations) std::visit(vis, sim); mSimulations->clear(); mSimulations = nullptr; } // Attempt to acquire unique lock on mSimulationMutex while not all worker // threads are holding shared lock but will have to may lead to a deadlock because // C++ standard does not guarantee priority for exclusive and shared locks // for std::shared_mutex. For example microsoft STL implementation points out // for the absence of such priority: // https://docs.microsoft.com/en-us/windows/win32/sync/slim-reader-writer--srw--locks void PhysicsTaskScheduler::waitForWorkers() { if (mWorkersSync != nullptr) mWorkersSync->waitForWorkers(); } }
34,635
C++
.cpp
795
33.059119
120
0.626119
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,362
physicssystem.cpp
OpenMW_openmw/apps/openmw/mwphysics/physicssystem.cpp
#include "physicssystem.hpp" #include <algorithm> #include <memory> #include <vector> #include <osg/Group> #include <osg/Stats> #include <osg/Timer> #include <BulletCollision/BroadphaseCollision/btDbvtBroadphase.h> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h> #include <BulletCollision/CollisionShapes/btConeShape.h> #include <BulletCollision/CollisionShapes/btSphereShape.h> #include <BulletCollision/CollisionShapes/btStaticPlaneShape.h> #include <LinearMath/btQuickprof.h> #include <LinearMath/btVector3.h> #include <components/debug/debuglog.hpp> #include <components/esm3/loadgmst.hpp> #include <components/esm3/loadmgef.hpp> #include <components/misc/convert.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/strings/conversion.hpp> #include <components/resource/bulletshapemanager.hpp> #include <components/resource/resourcesystem.hpp> #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/movement.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/player.hpp" #include "../mwrender/bulletdebugdraw.hpp" #include "../mwworld/class.hpp" #include "actor.hpp" #include "collisiontype.hpp" #include "closestnotmerayresultcallback.hpp" #include "contacttestresultcallback.hpp" #include "hasspherecollisioncallback.hpp" #include "heightfield.hpp" #include "movementsolver.hpp" #include "mtphysics.hpp" #include "object.hpp" #include "projectile.hpp" namespace { void handleJump(const MWWorld::Ptr& ptr) { if (!ptr.getClass().isActor()) return; if (ptr.getClass().getMovementSettings(ptr).mPosition[2] == 0) return; const bool isPlayer = (ptr == MWMechanics::getPlayer()); // Advance acrobatics and set flag for GetPCJumping if (isPlayer) { ptr.getClass().skillUsageSucceeded(ptr, ESM::Skill::Acrobatics, ESM::Skill::Acrobatics_Jump); MWBase::Environment::get().getWorld()->getPlayer().setJumping(true); } // Decrease fatigue if (!isPlayer || !MWBase::Environment::get().getWorld()->getGodModeState()) { const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); const float fFatigueJumpBase = gmst.find("fFatigueJumpBase")->mValue.getFloat(); const float fFatigueJumpMult = gmst.find("fFatigueJumpMult")->mValue.getFloat(); const float normalizedEncumbrance = std::min(1.f, ptr.getClass().getNormalizedEncumbrance(ptr)); const float fatigueDecrease = fFatigueJumpBase + normalizedEncumbrance * fFatigueJumpMult; MWMechanics::DynamicStat<float> fatigue = ptr.getClass().getCreatureStats(ptr).getFatigue(); fatigue.setCurrent(fatigue.getCurrent() - fatigueDecrease); ptr.getClass().getCreatureStats(ptr).setFatigue(fatigue); } ptr.getClass().getMovementSettings(ptr).mPosition[2] = 0; } } namespace MWPhysics { PhysicsSystem::PhysicsSystem(Resource::ResourceSystem* resourceSystem, osg::ref_ptr<osg::Group> parentNode) : mShapeManager( std::make_unique<Resource::BulletShapeManager>(resourceSystem->getVFS(), resourceSystem->getSceneManager(), resourceSystem->getNifFileManager(), Settings::cells().mCacheExpiryDelay)) , mResourceSystem(resourceSystem) , mDebugDrawEnabled(false) , mTimeAccum(0.0f) , mProjectileId(0) , mWaterHeight(0) , mWaterEnabled(false) , mParentNode(std::move(parentNode)) , mPhysicsDt(1.f / 60.f) { mResourceSystem->addResourceManager(mShapeManager.get()); mCollisionConfiguration = std::make_unique<btDefaultCollisionConfiguration>(); mDispatcher = std::make_unique<btCollisionDispatcher>(mCollisionConfiguration.get()); mBroadphase = std::make_unique<btDbvtBroadphase>(); mCollisionWorld = std::make_unique<btCollisionWorld>(mDispatcher.get(), mBroadphase.get(), mCollisionConfiguration.get()); // Don't update AABBs of all objects every frame. Most objects in MW are static, so we don't need this. // Should a "static" object ever be moved, we have to update its AABB manually using // DynamicsWorld::updateSingleAabb. mCollisionWorld->setForceUpdateAllAabbs(false); // Check if a user decided to override a physics system FPS if (const char* env = getenv("OPENMW_PHYSICS_FPS")) { if (const auto physFramerate = Misc::StringUtils::toNumeric<float>(env); physFramerate.has_value() && *physFramerate > 0) { mPhysicsDt = 1.f / *physFramerate; Log(Debug::Warning) << "Warning: using custom physics framerate (" << *physFramerate << " FPS)."; } } mDebugDrawer = std::make_unique<MWRender::DebugDrawer>(mParentNode, mCollisionWorld.get(), mDebugDrawEnabled); mTaskScheduler = std::make_unique<PhysicsTaskScheduler>(mPhysicsDt, mCollisionWorld.get(), mDebugDrawer.get()); } PhysicsSystem::~PhysicsSystem() { mResourceSystem->removeResourceManager(mShapeManager.get()); if (mWaterCollisionObject) mTaskScheduler->removeCollisionObject(mWaterCollisionObject.get()); mTaskScheduler->releaseSharedStates(); mHeightFields.clear(); mObjects.clear(); mActors.clear(); mProjectiles.clear(); } Resource::BulletShapeManager* PhysicsSystem::getShapeManager() { return mShapeManager.get(); } bool PhysicsSystem::toggleDebugRendering() { mDebugDrawEnabled = !mDebugDrawEnabled; mCollisionWorld->setDebugDrawer(mDebugDrawEnabled ? mDebugDrawer.get() : nullptr); mDebugDrawer->setDebugMode(mDebugDrawEnabled); return mDebugDrawEnabled; } void PhysicsSystem::markAsNonSolid(const MWWorld::ConstPtr& ptr) { ObjectMap::iterator found = mObjects.find(ptr.mRef); if (found == mObjects.end()) return; found->second->setSolid(false); } bool PhysicsSystem::isOnSolidGround(const MWWorld::Ptr& actor) const { const Actor* physactor = getActor(actor); if (!physactor || !physactor->getOnGround() || !physactor->getCollisionMode()) return false; const auto obj = physactor->getStandingOnPtr(); if (obj.isEmpty()) return true; // assume standing on terrain (which is a non-object, so not collision tracked) ObjectMap::const_iterator foundObj = mObjects.find(obj.mRef); if (foundObj == mObjects.end()) return false; if (!foundObj->second->isSolid()) return false; return true; } RayCastingResult PhysicsSystem::castRay(const osg::Vec3f& from, const osg::Vec3f& to, const std::vector<MWWorld::ConstPtr>& ignore, const std::vector<MWWorld::Ptr>& targets, int mask, int group) const { if (from == to) { RayCastingResult result; result.mHit = false; return result; } btVector3 btFrom = Misc::Convert::toBullet(from); btVector3 btTo = Misc::Convert::toBullet(to); std::vector<const btCollisionObject*> ignoreList; std::vector<const btCollisionObject*> targetCollisionObjects; for (const auto& ptr : ignore) { if (!ptr.isEmpty()) { const Actor* actor = getActor(ptr); if (actor) ignoreList.push_back(actor->getCollisionObject()); else { const Object* object = getObject(ptr); if (object) ignoreList.push_back(object->getCollisionObject()); } } } if (!targets.empty()) { for (const MWWorld::Ptr& target : targets) { const Actor* actor = getActor(target); if (actor) targetCollisionObjects.push_back(actor->getCollisionObject()); } } ClosestNotMeRayResultCallback resultCallback(ignoreList, targetCollisionObjects, btFrom, btTo); resultCallback.m_collisionFilterGroup = group; resultCallback.m_collisionFilterMask = mask; mTaskScheduler->rayTest(btFrom, btTo, resultCallback); RayCastingResult result; result.mHit = resultCallback.hasHit(); if (resultCallback.hasHit()) { result.mHitPos = Misc::Convert::toOsg(resultCallback.m_hitPointWorld); result.mHitNormal = Misc::Convert::toOsg(resultCallback.m_hitNormalWorld); if (PtrHolder* ptrHolder = static_cast<PtrHolder*>(resultCallback.m_collisionObject->getUserPointer())) result.mHitObject = ptrHolder->getPtr(); } return result; } RayCastingResult PhysicsSystem::castSphere( const osg::Vec3f& from, const osg::Vec3f& to, float radius, int mask, int group) const { btCollisionWorld::ClosestConvexResultCallback callback( Misc::Convert::toBullet(from), Misc::Convert::toBullet(to)); callback.m_collisionFilterGroup = group; callback.m_collisionFilterMask = mask; btSphereShape shape(radius); const btQuaternion btrot = btQuaternion::getIdentity(); btTransform from_(btrot, Misc::Convert::toBullet(from)); btTransform to_(btrot, Misc::Convert::toBullet(to)); mTaskScheduler->convexSweepTest(&shape, from_, to_, callback); RayCastingResult result; result.mHit = callback.hasHit(); if (result.mHit) { result.mHitPos = Misc::Convert::toOsg(callback.m_hitPointWorld); result.mHitNormal = Misc::Convert::toOsg(callback.m_hitNormalWorld); if (auto* ptrHolder = static_cast<PtrHolder*>(callback.m_hitCollisionObject->getUserPointer())) result.mHitObject = ptrHolder->getPtr(); } return result; } bool PhysicsSystem::getLineOfSight(const MWWorld::ConstPtr& actor1, const MWWorld::ConstPtr& actor2) const { if (actor1 == actor2) return true; const auto it1 = mActors.find(actor1.mRef); const auto it2 = mActors.find(actor2.mRef); if (it1 == mActors.end() || it2 == mActors.end()) return false; return mTaskScheduler->getLineOfSight(it1->second, it2->second); } bool PhysicsSystem::isOnGround(const MWWorld::Ptr& actor) { Actor* physactor = getActor(actor); return physactor && physactor->getOnGround() && physactor->getCollisionMode(); } bool PhysicsSystem::canMoveToWaterSurface(const MWWorld::ConstPtr& actor, const float waterlevel) { const auto* physactor = getActor(actor); return physactor && physactor->canMoveToWaterSurface(waterlevel, mCollisionWorld.get()); } osg::Vec3f PhysicsSystem::getHalfExtents(const MWWorld::ConstPtr& actor) const { const Actor* physactor = getActor(actor); if (physactor) return physactor->getHalfExtents(); else return osg::Vec3f(); } osg::Vec3f PhysicsSystem::getOriginalHalfExtents(const MWWorld::ConstPtr& actor) const { if (const Actor* physactor = getActor(actor)) return physactor->getOriginalHalfExtents(); else return osg::Vec3f(); } osg::Vec3f PhysicsSystem::getRenderingHalfExtents(const MWWorld::ConstPtr& actor) const { const Actor* physactor = getActor(actor); if (physactor) return physactor->getRenderingHalfExtents(); else return osg::Vec3f(); } osg::BoundingBox PhysicsSystem::getBoundingBox(const MWWorld::ConstPtr& object) const { const Object* physobject = getObject(object); if (!physobject) return osg::BoundingBox(); btVector3 min, max; mTaskScheduler->getAabb(physobject->getCollisionObject(), min, max); return osg::BoundingBox(Misc::Convert::toOsg(min), Misc::Convert::toOsg(max)); } osg::Vec3f PhysicsSystem::getCollisionObjectPosition(const MWWorld::ConstPtr& actor) const { const Actor* physactor = getActor(actor); if (physactor) return physactor->getCollisionObjectPosition(); else return osg::Vec3f(); } std::vector<ContactPoint> PhysicsSystem::getCollisionsPoints( const MWWorld::ConstPtr& ptr, int collisionGroup, int collisionMask) const { btCollisionObject* me = nullptr; auto found = mObjects.find(ptr.mRef); if (found != mObjects.end()) me = found->second->getCollisionObject(); else return {}; ContactTestResultCallback resultCallback(me); resultCallback.m_collisionFilterGroup = collisionGroup; resultCallback.m_collisionFilterMask = collisionMask; mTaskScheduler->contactTest(me, resultCallback); return resultCallback.mResult; } std::vector<MWWorld::Ptr> PhysicsSystem::getCollisions( const MWWorld::ConstPtr& ptr, int collisionGroup, int collisionMask) const { std::vector<MWWorld::Ptr> actors; for (auto& [actor, point, normal] : getCollisionsPoints(ptr, collisionGroup, collisionMask)) actors.emplace_back(actor); return actors; } osg::Vec3f PhysicsSystem::traceDown(const MWWorld::Ptr& ptr, const osg::Vec3f& position, float maxHeight) { ActorMap::iterator found = mActors.find(ptr.mRef); if (found == mActors.end()) return ptr.getRefData().getPosition().asVec3(); return MovementSolver::traceDown(ptr, position, found->second.get(), mCollisionWorld.get(), maxHeight); } void PhysicsSystem::addHeightField( const float* heights, int x, int y, int size, int verts, float minH, float maxH, const osg::Object* holdObject) { mHeightFields[std::make_pair(x, y)] = std::make_unique<HeightField>(heights, x, y, size, verts, minH, maxH, holdObject, mTaskScheduler.get()); } void PhysicsSystem::removeHeightField(int x, int y) { HeightFieldMap::iterator heightfield = mHeightFields.find(std::make_pair(x, y)); if (heightfield != mHeightFields.end()) mHeightFields.erase(heightfield); } const HeightField* PhysicsSystem::getHeightField(int x, int y) const { const auto heightField = mHeightFields.find(std::make_pair(x, y)); if (heightField == mHeightFields.end()) return nullptr; return heightField->second.get(); } void PhysicsSystem::addObject( const MWWorld::Ptr& ptr, VFS::Path::NormalizedView mesh, osg::Quat rotation, int collisionType) { if (ptr.mRef->mData.mPhysicsPostponed) return; const VFS::Path::Normalized animationMesh = ptr.getClass().useAnim() ? Misc::ResourceHelpers::correctActorModelPath(mesh, mResourceSystem->getVFS()) : VFS::Path::Normalized(mesh); osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(animationMesh); if (!shapeInstance || !shapeInstance->mCollisionShape) return; assert(!getObject(ptr)); // Override collision type based on shape content. switch (shapeInstance->mVisualCollisionType) { case Resource::VisualCollisionType::None: break; case Resource::VisualCollisionType::Default: collisionType = CollisionType_VisualOnly; break; case Resource::VisualCollisionType::Camera: collisionType = CollisionType_CameraOnly; break; } auto obj = std::make_shared<Object>(ptr, shapeInstance, rotation, collisionType, mTaskScheduler.get()); mObjects.emplace(ptr.mRef, obj); if (obj->isAnimated()) mAnimatedObjects.emplace(obj.get(), false); } void PhysicsSystem::remove(const MWWorld::Ptr& ptr) { if (auto foundObject = mObjects.find(ptr.mRef); foundObject != mObjects.end()) { mAnimatedObjects.erase(foundObject->second.get()); mObjects.erase(foundObject); } else if (auto foundActor = mActors.find(ptr.mRef); foundActor != mActors.end()) { mActors.erase(foundActor); } } void PhysicsSystem::removeProjectile(const int projectileId) { ProjectileMap::iterator foundProjectile = mProjectiles.find(projectileId); if (foundProjectile != mProjectiles.end()) mProjectiles.erase(foundProjectile); } void PhysicsSystem::updatePtr(const MWWorld::Ptr& old, const MWWorld::Ptr& updated) { if (auto foundObject = mObjects.find(old.mRef); foundObject != mObjects.end()) foundObject->second->updatePtr(updated); else if (auto foundActor = mActors.find(old.mRef); foundActor != mActors.end()) foundActor->second->updatePtr(updated); for (auto& [_, actor] : mActors) { if (actor->getStandingOnPtr() == old) actor->setStandingOnPtr(updated); } for (auto& [_, projectile] : mProjectiles) { if (projectile->getCaster() == old) projectile->setCaster(updated); } } Actor* PhysicsSystem::getActor(const MWWorld::Ptr& ptr) { ActorMap::iterator found = mActors.find(ptr.mRef); if (found != mActors.end()) return found->second.get(); return nullptr; } const Actor* PhysicsSystem::getActor(const MWWorld::ConstPtr& ptr) const { ActorMap::const_iterator found = mActors.find(ptr.mRef); if (found != mActors.end()) return found->second.get(); return nullptr; } const Object* PhysicsSystem::getObject(const MWWorld::ConstPtr& ptr) const { ObjectMap::const_iterator found = mObjects.find(ptr.mRef); if (found != mObjects.end()) return found->second.get(); return nullptr; } Projectile* PhysicsSystem::getProjectile(int projectileId) const { ProjectileMap::const_iterator found = mProjectiles.find(projectileId); if (found != mProjectiles.end()) return found->second.get(); return nullptr; } void PhysicsSystem::updateScale(const MWWorld::Ptr& ptr) { if (auto foundObject = mObjects.find(ptr.mRef); foundObject != mObjects.end()) { float scale = ptr.getCellRef().getScale(); foundObject->second->setScale(scale); mTaskScheduler->updateSingleAabb(foundObject->second); } else if (auto foundActor = mActors.find(ptr.mRef); foundActor != mActors.end()) { foundActor->second->updateScale(); mTaskScheduler->updateSingleAabb(foundActor->second); } } void PhysicsSystem::updateRotation(const MWWorld::Ptr& ptr, osg::Quat rotate) { if (auto foundObject = mObjects.find(ptr.mRef); foundObject != mObjects.end()) { foundObject->second->setRotation(rotate); mTaskScheduler->updateSingleAabb(foundObject->second); } else if (auto foundActor = mActors.find(ptr.mRef); foundActor != mActors.end()) { if (!foundActor->second->isRotationallyInvariant()) { foundActor->second->setRotation(rotate); mTaskScheduler->updateSingleAabb(foundActor->second); } } } void PhysicsSystem::updatePosition(const MWWorld::Ptr& ptr) { if (auto foundObject = mObjects.find(ptr.mRef); foundObject != mObjects.end()) { foundObject->second->updatePosition(); mTaskScheduler->updateSingleAabb(foundObject->second); } else if (auto foundActor = mActors.find(ptr.mRef); foundActor != mActors.end()) { foundActor->second->updatePosition(); mTaskScheduler->updateSingleAabb(foundActor->second, true); } } void PhysicsSystem::addActor(const MWWorld::Ptr& ptr, VFS::Path::NormalizedView mesh) { const VFS::Path::Normalized animationMesh = Misc::ResourceHelpers::correctActorModelPath(mesh, mResourceSystem->getVFS()); osg::ref_ptr<const Resource::BulletShape> shape = mShapeManager->getShape(animationMesh); // Try to get shape from basic model as fallback for creatures if (!ptr.getClass().isNpc() && shape && shape->mCollisionBox.mExtents.length2() == 0) { if (animationMesh != mesh) { shape = mShapeManager->getShape(VFS::Path::toNormalized(mesh)); } } if (!shape) return; // check if Actor should spawn above water const MWMechanics::MagicEffects& effects = ptr.getClass().getCreatureStats(ptr).getMagicEffects(); const bool canWaterWalk = effects.getOrDefault(ESM::MagicEffect::WaterWalking).getMagnitude() > 0; auto actor = std::make_shared<Actor>( ptr, shape, mTaskScheduler.get(), canWaterWalk, Settings::game().mActorCollisionShapeType); mActors.emplace(ptr.mRef, std::move(actor)); } int PhysicsSystem::addProjectile( const MWWorld::Ptr& caster, const osg::Vec3f& position, VFS::Path::NormalizedView mesh, bool computeRadius) { osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance = mShapeManager->getInstance(VFS::Path::toNormalized(mesh)); assert(shapeInstance); float radius = computeRadius ? shapeInstance->mCollisionBox.mExtents.length() / 2.f : 1.f; mProjectileId++; auto projectile = std::make_shared<Projectile>(caster, position, radius, mTaskScheduler.get(), this); mProjectiles.emplace(mProjectileId, std::move(projectile)); return mProjectileId; } void PhysicsSystem::setCaster(int projectileId, const MWWorld::Ptr& caster) { const auto foundProjectile = mProjectiles.find(projectileId); assert(foundProjectile != mProjectiles.end()); auto* projectile = foundProjectile->second.get(); projectile->setCaster(caster); } bool PhysicsSystem::toggleCollisionMode() { ActorMap::iterator found = mActors.find(MWMechanics::getPlayer().mRef); if (found != mActors.end()) { bool cmode = found->second->getCollisionMode(); cmode = !cmode; found->second->enableCollisionMode(cmode); // NB: Collision body isn't disabled for vanilla TCL compatibility return cmode; } return false; } void PhysicsSystem::queueObjectMovement(const MWWorld::Ptr& ptr, const osg::Vec3f& velocity) { ActorMap::iterator found = mActors.find(ptr.mRef); if (found != mActors.end()) found->second->setVelocity(velocity); } void PhysicsSystem::clearQueuedMovement() { for (const auto& [_, actor] : mActors) { actor->setVelocity(osg::Vec3f()); actor->setInertialForce(osg::Vec3f()); } } void PhysicsSystem::prepareSimulation(bool willSimulate, std::vector<Simulation>& simulations) { assert(simulations.empty()); simulations.reserve(mActors.size() + mProjectiles.size()); const MWBase::World* world = MWBase::Environment::get().getWorld(); for (const auto& [ref, physicActor] : mActors) { if (!physicActor->isActive()) continue; auto ptr = physicActor->getPtr(); if (!ptr.getClass().isMobile(ptr)) continue; float waterlevel = -std::numeric_limits<float>::max(); const MWWorld::CellStore* cell = ptr.getCell(); if (cell->getCell()->hasWater()) waterlevel = cell->getWaterLevel(); const auto& stats = ptr.getClass().getCreatureStats(ptr); const MWMechanics::MagicEffects& effects = stats.getMagicEffects(); bool waterCollision = false; if (cell->getCell()->hasWater() && effects.getOrDefault(ESM::MagicEffect::WaterWalking).getMagnitude()) { if (physicActor->getCollisionMode() || !world->isUnderwater(ptr.getCell(), ptr.getRefData().getPosition().asVec3())) waterCollision = true; } physicActor->setCanWaterWalk(waterCollision); // Slow fall reduces fall speed by a factor of (effect magnitude / 200) const float slowFall = 1.f - std::clamp(effects.getOrDefault(ESM::MagicEffect::SlowFall).getMagnitude() * 0.005f, 0.f, 1.f); const bool isPlayer = ptr == world->getPlayerConstPtr(); const bool godmode = isPlayer && world->getGodModeState(); const bool inert = stats.isDead() || (!godmode && stats.getMagicEffects().getOrDefault(ESM::MagicEffect::Paralyze).getModifier() > 0); simulations.emplace_back(ActorSimulation{ physicActor, ActorFrameData{ *physicActor, inert, waterCollision, slowFall, waterlevel, isPlayer } }); // if the simulation will run, a jump request will be fulfilled. Update mechanics accordingly. if (willSimulate) handleJump(ptr); } for (const auto& [id, projectile] : mProjectiles) { simulations.emplace_back(ProjectileSimulation{ projectile, ProjectileFrameData{ *projectile } }); } } void PhysicsSystem::stepSimulation( float dt, bool skipSimulation, osg::Timer_t frameStart, unsigned int frameNumber, osg::Stats& stats) { for (auto& [animatedObject, changed] : mAnimatedObjects) { if (animatedObject->animateCollisionShapes()) { auto obj = mObjects.find(animatedObject->getPtr().mRef); assert(obj != mObjects.end()); mTaskScheduler->updateSingleAabb(obj->second); changed = true; } else { changed = false; } } for (auto& [_, object] : mObjects) object->resetCollisions(); #ifndef BT_NO_PROFILE CProfileManager::Reset(); CProfileManager::Increment_Frame_Counter(); #endif mTimeAccum += dt; if (skipSimulation) mTaskScheduler->resetSimulation(mActors); else { std::vector<Simulation>& simulations = mSimulations[mSimulationsCounter++ % mSimulations.size()]; prepareSimulation(mTimeAccum >= mPhysicsDt, simulations); // modifies mTimeAccum mTaskScheduler->applyQueuedMovements(mTimeAccum, simulations, frameStart, frameNumber, stats); } } void PhysicsSystem::moveActors() { auto* player = getActor(MWMechanics::getPlayer()); const auto world = MWBase::Environment::get().getWorld(); // copy new ptr position in temporary vector. player is handled separately as its movement might change active // cell. mActorsPositions.clear(); if (!mActors.empty()) mActorsPositions.reserve(mActors.size() - 1); for (const auto& [ptr, physicActor] : mActors) { if (physicActor.get() == player) continue; mActorsPositions.emplace_back(physicActor->getPtr(), physicActor->getSimulationPosition()); } for (const auto& [ptr, pos] : mActorsPositions) world->moveObject(ptr, pos, false, false); if (player != nullptr) world->moveObject(player->getPtr(), player->getSimulationPosition(), false, false); } void PhysicsSystem::updateAnimatedCollisionShape(const MWWorld::Ptr& object) { ObjectMap::iterator found = mObjects.find(object.mRef); if (found != mObjects.end()) if (found->second->animateCollisionShapes()) mTaskScheduler->updateSingleAabb(found->second); } void PhysicsSystem::debugDraw() { if (mDebugDrawEnabled) mTaskScheduler->debugDraw(); } bool PhysicsSystem::isActorStandingOn(const MWWorld::Ptr& actor, const MWWorld::ConstPtr& object) const { const auto physActor = mActors.find(actor.mRef); if (physActor != mActors.end()) return physActor->second->getStandingOnPtr() == object; return false; } void PhysicsSystem::getActorsStandingOn(const MWWorld::ConstPtr& object, std::vector<MWWorld::Ptr>& out) const { for (const auto& [_, actor] : mActors) { if (actor->getStandingOnPtr() == object) out.emplace_back(actor->getPtr()); } } bool PhysicsSystem::isObjectCollidingWith(const MWWorld::ConstPtr& object, ScriptedCollisionType type) const { auto found = mObjects.find(object.mRef); if (found != mObjects.end()) return found->second->collidedWith(type); return false; } void PhysicsSystem::getActorsCollidingWith(const MWWorld::ConstPtr& object, std::vector<MWWorld::Ptr>& out) const { std::vector<MWWorld::Ptr> collisions = getCollisions(object, CollisionType_World, CollisionType_Actor); out.insert(out.end(), collisions.begin(), collisions.end()); } void PhysicsSystem::disableWater() { if (mWaterEnabled) { mWaterEnabled = false; updateWater(); } } void PhysicsSystem::enableWater(float height) { if (!mWaterEnabled || mWaterHeight != height) { mWaterEnabled = true; mWaterHeight = height; updateWater(); } } void PhysicsSystem::setWaterHeight(float height) { if (mWaterHeight != height) { mWaterHeight = height; updateWater(); } } void PhysicsSystem::updateWater() { if (mWaterCollisionObject) { mTaskScheduler->removeCollisionObject(mWaterCollisionObject.get()); } if (!mWaterEnabled) { mWaterCollisionObject.reset(); return; } mWaterCollisionObject = std::make_unique<btCollisionObject>(); mWaterCollisionShape = std::make_unique<btStaticPlaneShape>(btVector3(0, 0, 1), mWaterHeight); mWaterCollisionObject->setCollisionShape(mWaterCollisionShape.get()); mTaskScheduler->addCollisionObject( mWaterCollisionObject.get(), CollisionType_Water, CollisionType_Actor | CollisionType_Projectile); } bool PhysicsSystem::isAreaOccupiedByOtherActor(const osg::Vec3f& position, const float radius, std::span<const MWWorld::ConstPtr> ignore, std::vector<MWWorld::Ptr>* occupyingActors) const { std::vector<const btCollisionObject*> ignoredObjects; ignoredObjects.reserve(ignore.size()); for (const auto& v : ignore) if (const auto it = mActors.find(v.mRef); it != mActors.end()) ignoredObjects.push_back(it->second->getCollisionObject()); std::sort(ignoredObjects.begin(), ignoredObjects.end()); ignoredObjects.erase(std::unique(ignoredObjects.begin(), ignoredObjects.end()), ignoredObjects.end()); const auto ignoreFilter = [&](const btCollisionObject* v) { return std::binary_search(ignoredObjects.begin(), ignoredObjects.end(), v); }; const auto bulletPosition = Misc::Convert::toBullet(position); const auto aabbMin = bulletPosition - btVector3(radius, radius, radius); const auto aabbMax = bulletPosition + btVector3(radius, radius, radius); const int mask = MWPhysics::CollisionType_Actor; const int group = MWPhysics::CollisionType_AnyPhysical; if (occupyingActors == nullptr) { HasSphereCollisionCallback callback(bulletPosition, radius, mask, group, ignoreFilter, static_cast<void (*)(const btCollisionObject*)>(nullptr)); mTaskScheduler->aabbTest(aabbMin, aabbMax, callback); return callback.getResult(); } const auto onCollision = [&](const btCollisionObject* object) { if (PtrHolder* holder = static_cast<PtrHolder*>(object->getUserPointer())) occupyingActors->push_back(holder->getPtr()); }; HasSphereCollisionCallback callback(bulletPosition, radius, mask, group, ignoreFilter, &onCollision); mTaskScheduler->aabbTest(aabbMin, aabbMax, callback); return callback.getResult(); } void PhysicsSystem::reportStats(unsigned int frameNumber, osg::Stats& stats) const { stats.setAttribute(frameNumber, "Physics Actors", mActors.size()); stats.setAttribute(frameNumber, "Physics Objects", mObjects.size()); stats.setAttribute(frameNumber, "Physics Projectiles", mProjectiles.size()); stats.setAttribute(frameNumber, "Physics HeightFields", mHeightFields.size()); } void PhysicsSystem::reportCollision(const btVector3& position, const btVector3& normal) { if (mDebugDrawEnabled) mDebugDrawer->addCollision(position, normal); } ActorFrameData::ActorFrameData( Actor& actor, bool inert, bool waterCollision, float slowFall, float waterlevel, bool isPlayer) : mPosition() , mStandingOn(nullptr) , mIsOnGround(actor.getOnGround()) , mIsOnSlope(actor.getOnSlope()) , mWalkingOnWater(false) , mInert(inert) , mCollisionObject(actor.getCollisionObject()) , mSwimLevel(waterlevel - (actor.getRenderingHalfExtents().z() * 2 * MWBase::Environment::get() .getESMStore() ->get<ESM::GameSetting>() .find("fSwimHeightScale") ->mValue.getFloat())) , mSlowFall(slowFall) , mRotation() , mMovement(actor.velocity()) , mWaterlevel(waterlevel) , mHalfExtentsZ(actor.getHalfExtents().z()) , mOldHeight(0) , mStuckFrames(0) , mFlying(MWBase::Environment::get().getWorld()->isFlying(actor.getPtr())) , mWasOnGround(actor.getOnGround()) , mIsAquatic(actor.getPtr().getClass().isPureWaterCreature(actor.getPtr())) , mWaterCollision(waterCollision) , mSkipCollisionDetection(!actor.getCollisionMode()) , mIsPlayer(isPlayer) { } ProjectileFrameData::ProjectileFrameData(Projectile& projectile) : mPosition(projectile.getPosition()) , mMovement(projectile.velocity()) , mCaster(projectile.getCasterCollisionObject()) , mCollisionObject(projectile.getCollisionObject()) , mProjectile(&projectile) { } WorldFrameData::WorldFrameData() : mIsInStorm(MWBase::Environment::get().getWorld()->isInStorm()) , mStormDirection(MWBase::Environment::get().getWorld()->getStormDirection()) { } LOSRequest::LOSRequest(const std::weak_ptr<Actor>& a1, const std::weak_ptr<Actor>& a2) : mResult(false) , mStale(false) , mAge(0) { // we use raw actor pointer pair to uniquely identify request // sort the pointer value in ascending order to not duplicate equivalent requests, eg. getLOS(A, B) and // getLOS(B, A) auto* raw1 = a1.lock().get(); auto* raw2 = a2.lock().get(); assert(raw1 != raw2); if (raw1 < raw2) { mActors = { a1, a2 }; mRawActors = { raw1, raw2 }; } else { mActors = { a2, a1 }; mRawActors = { raw2, raw1 }; } } bool operator==(const LOSRequest& lhs, const LOSRequest& rhs) noexcept { return lhs.mRawActors == rhs.mRawActors; } }
36,753
C++
.cpp
841
34.487515
119
0.641296
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,363
object.cpp
OpenMW_openmw/apps/openmw/mwphysics/object.cpp
#include "object.hpp" #include "mtphysics.hpp" #include <components/bullethelpers/collisionobject.hpp> #include <components/debug/debuglog.hpp> #include <components/misc/convert.hpp> #include <components/nifosg/particle.hpp> #include <components/resource/bulletshape.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <BulletCollision/CollisionShapes/btCompoundShape.h> #include <LinearMath/btTransform.h> namespace MWPhysics { Object::Object(const MWWorld::Ptr& ptr, osg::ref_ptr<Resource::BulletShapeInstance> shapeInstance, osg::Quat rotation, int collisionType, PhysicsTaskScheduler* scheduler) : PtrHolder(ptr, osg::Vec3f()) , mShapeInstance(std::move(shapeInstance)) , mSolid(true) , mScale(ptr.getCellRef().getScale(), ptr.getCellRef().getScale(), ptr.getCellRef().getScale()) , mPosition(ptr.getRefData().getPosition().asVec3()) , mRotation(rotation) , mTaskScheduler(scheduler) , mCollidedWith(ScriptedCollisionType_None) { mCollisionObject = BulletHelpers::makeCollisionObject(mShapeInstance->mCollisionShape.get(), Misc::Convert::toBullet(mPosition), Misc::Convert::toBullet(rotation)); mCollisionObject->setUserPointer(this); mShapeInstance->setLocalScaling(mScale); mTaskScheduler->addCollisionObject(mCollisionObject.get(), collisionType, CollisionType_Actor | CollisionType_HeightMap | CollisionType_Projectile); } Object::~Object() { mTaskScheduler->removeCollisionObject(mCollisionObject.get()); } const Resource::BulletShapeInstance* Object::getShapeInstance() const { return mShapeInstance.get(); } void Object::setScale(float scale) { std::unique_lock<std::mutex> lock(mPositionMutex); mScale = { scale, scale, scale }; mScaleUpdatePending = true; } void Object::setRotation(osg::Quat quat) { std::unique_lock<std::mutex> lock(mPositionMutex); mRotation = quat; mTransformUpdatePending = true; } void Object::updatePosition() { std::unique_lock<std::mutex> lock(mPositionMutex); mPosition = mPtr.getRefData().getPosition().asVec3(); mTransformUpdatePending = true; } void Object::commitPositionChange() { std::unique_lock<std::mutex> lock(mPositionMutex); if (mScaleUpdatePending) { mShapeInstance->setLocalScaling(mScale); mScaleUpdatePending = false; } if (mTransformUpdatePending) { btTransform trans; trans.setOrigin(Misc::Convert::toBullet(mPosition)); trans.setRotation(Misc::Convert::toBullet(mRotation)); mCollisionObject->setWorldTransform(trans); mTransformUpdatePending = false; } } btTransform Object::getTransform() const { std::unique_lock<std::mutex> lock(mPositionMutex); btTransform trans; trans.setOrigin(Misc::Convert::toBullet(mPosition)); trans.setRotation(Misc::Convert::toBullet(mRotation)); return trans; } bool Object::isSolid() const { return mSolid; } void Object::setSolid(bool solid) { mSolid = solid; } bool Object::isAnimated() const { return mShapeInstance->isAnimated(); } bool Object::animateCollisionShapes() { if (mShapeInstance->mAnimatedShapes.empty()) return false; if (!mPtr.getRefData().getBaseNode()) return false; assert(mShapeInstance->mCollisionShape->isCompound()); btCompoundShape* compound = static_cast<btCompoundShape*>(mShapeInstance->mCollisionShape.get()); bool result = false; for (const auto& [recIndex, shapeIndex] : mShapeInstance->mAnimatedShapes) { auto nodePathFound = mRecIndexToNodePath.find(recIndex); if (nodePathFound == mRecIndexToNodePath.end()) { NifOsg::FindGroupByRecIndex visitor(recIndex); mPtr.getRefData().getBaseNode()->accept(visitor); if (!visitor.mFound) { Log(Debug::Warning) << "Warning: animateCollisionShapes can't find node " << recIndex << " for " << mPtr.getCellRef().getRefId(); // Remove nonexistent nodes from animated shapes map and early out mShapeInstance->mAnimatedShapes.erase(recIndex); return false; } osg::NodePath nodePath = visitor.mFoundPath; nodePath.erase(nodePath.begin()); nodePathFound = mRecIndexToNodePath.emplace(recIndex, nodePath).first; } osg::NodePath& nodePath = nodePathFound->second; osg::Matrixf matrix = osg::computeLocalToWorld(nodePath); btVector3 scale = Misc::Convert::toBullet(matrix.getScale()); matrix.orthoNormalize(matrix); btTransform transform; transform.setOrigin(Misc::Convert::toBullet(matrix.getTrans()) * compound->getLocalScaling()); for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) transform.getBasis()[i][j] = matrix(j, i); // NB column/row major difference btCollisionShape* childShape = compound->getChildShape(shapeIndex); btVector3 newScale = compound->getLocalScaling() * scale; if (childShape->getLocalScaling() != newScale) { childShape->setLocalScaling(newScale); result = true; } if (!(transform == compound->getChildTransform(shapeIndex))) { compound->updateChildTransform(shapeIndex, transform); result = true; } } return result; } bool Object::collidedWith(ScriptedCollisionType type) const { return mCollidedWith & type; } void Object::addCollision(ScriptedCollisionType type) { std::unique_lock<std::mutex> lock(mPositionMutex); mCollidedWith |= type; } void Object::resetCollisions() { mCollidedWith = ScriptedCollisionType_None; } }
6,367
C++
.cpp
159
30.672956
116
0.634687
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,364
projectile.cpp
OpenMW_openmw/apps/openmw/mwphysics/projectile.cpp
#include <memory> #include <BulletCollision/CollisionShapes/btSphereShape.h> #include <components/misc/convert.hpp> #include "actor.hpp" #include "collisiontype.hpp" #include "mtphysics.hpp" #include "object.hpp" #include "projectile.hpp" namespace MWPhysics { Projectile::Projectile(const MWWorld::Ptr& caster, const osg::Vec3f& position, float radius, PhysicsTaskScheduler* scheduler, PhysicsSystem* physicssystem) : PtrHolder(MWWorld::Ptr(), position) , mHitWater(false) , mActive(true) , mHitTarget(nullptr) , mPhysics(physicssystem) , mTaskScheduler(scheduler) { mShape = std::make_unique<btSphereShape>(radius); mConvexShape = static_cast<btConvexShape*>(mShape.get()); mCollisionObject = std::make_unique<btCollisionObject>(); mCollisionObject->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); mCollisionObject->setActivationState(DISABLE_DEACTIVATION); mCollisionObject->setCollisionShape(mShape.get()); mCollisionObject->setUserPointer(this); mPosition = position; mPreviousPosition = position; mSimulationPosition = position; setCaster(caster); const int collisionMask = CollisionType_World | CollisionType_HeightMap | CollisionType_Actor | CollisionType_Door | CollisionType_Water | CollisionType_Projectile; mTaskScheduler->addCollisionObject(mCollisionObject.get(), CollisionType_Projectile, collisionMask); updateCollisionObjectPosition(); } Projectile::~Projectile() { if (!mActive) mPhysics->reportCollision(mHitPosition, mHitNormal); mTaskScheduler->removeCollisionObject(mCollisionObject.get()); } void Projectile::updateCollisionObjectPosition() { std::scoped_lock lock(mMutex); auto& trans = mCollisionObject->getWorldTransform(); trans.setOrigin(Misc::Convert::toBullet(mPosition)); mCollisionObject->setWorldTransform(trans); } void Projectile::hit(const btCollisionObject* target, btVector3 pos, btVector3 normal) { bool active = true; if (!mActive.compare_exchange_strong(active, false, std::memory_order_relaxed) || !active) return; mHitTarget = target; mHitPosition = pos; mHitNormal = normal; } MWWorld::Ptr Projectile::getTarget() const { assert(!mActive); auto* target = static_cast<PtrHolder*>(mHitTarget->getUserPointer()); return target ? target->getPtr() : MWWorld::Ptr(); } MWWorld::Ptr Projectile::getCaster() const { return mCaster; } void Projectile::setCaster(const MWWorld::Ptr& caster) { mCaster = caster; mCasterColObj = [this, &caster]() -> const btCollisionObject* { const Actor* actor = mPhysics->getActor(caster); if (actor) return actor->getCollisionObject(); const Object* object = mPhysics->getObject(caster); if (object) return object->getCollisionObject(); return nullptr; }(); } void Projectile::setValidTargets(const std::vector<MWWorld::Ptr>& targets) { std::scoped_lock lock(mMutex); mValidTargets.clear(); for (const auto& ptr : targets) { const auto* physicActor = mPhysics->getActor(ptr); if (physicActor) mValidTargets.push_back(physicActor->getCollisionObject()); } } bool Projectile::isValidTarget(const btCollisionObject* target) const { assert(target); std::scoped_lock lock(mMutex); if (mCasterColObj == target) return false; if (mValidTargets.empty()) return true; return std::any_of(mValidTargets.begin(), mValidTargets.end(), [target](const btCollisionObject* actor) { return target == actor; }); } }
4,000
C++
.cpp
103
30.815534
108
0.659618
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,365
actor.cpp
OpenMW_openmw/apps/openmw/mwphysics/actor.cpp
#include "actor.hpp" #include <BulletCollision/CollisionShapes/btCylinderShape.h> #include <components/debug/debuglog.hpp> #include <components/misc/convert.hpp> #include <components/resource/bulletshape.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include "../mwmechanics/creaturestats.hpp" #include "../mwworld/class.hpp" #include "collisiontype.hpp" #include "mtphysics.hpp" #include "trace.h" #include <cmath> namespace MWPhysics { Actor::Actor(const MWWorld::Ptr& ptr, const Resource::BulletShape* shape, PhysicsTaskScheduler* scheduler, bool canWaterWalk, DetourNavigator::CollisionShapeType collisionShapeType) : PtrHolder(ptr, ptr.getRefData().getPosition().asVec3()) , mStandingOnPtr(nullptr) , mCanWaterWalk(canWaterWalk) , mWalkingOnWater(false) , mMeshTranslation(shape->mCollisionBox.mCenter) , mOriginalHalfExtents(shape->mCollisionBox.mExtents) , mStuckFrames(0) , mLastStuckPosition{ 0, 0, 0 } , mForce(0.f, 0.f, 0.f) , mOnGround(ptr.getClass().getCreatureStats(ptr).getFallHeight() == 0) , mOnSlope(false) , mInternalCollisionMode(true) , mExternalCollisionMode(true) , mActive(false) , mTaskScheduler(scheduler) { // We can not create actor without collisions - he will fall through the ground. // In this case we should autogenerate collision box based on mesh shape // (NPCs have bodyparts and use a different approach) if (!ptr.getClass().isNpc() && mOriginalHalfExtents.length2() == 0.f) { if (shape->mCollisionShape) { btTransform transform; transform.setIdentity(); btVector3 min; btVector3 max; shape->mCollisionShape->getAabb(transform, min, max); mOriginalHalfExtents.x() = (max[0] - min[0]) / 2.f; mOriginalHalfExtents.y() = (max[1] - min[1]) / 2.f; mOriginalHalfExtents.z() = (max[2] - min[2]) / 2.f; mMeshTranslation = osg::Vec3f(0.f, 0.f, mOriginalHalfExtents.z()); } if (mOriginalHalfExtents.length2() == 0.f) Log(Debug::Error) << "Error: Failed to calculate bounding box for actor \"" << ptr.getCellRef().getRefId() << "\"."; } const btVector3 halfExtents = Misc::Convert::toBullet(mOriginalHalfExtents); if ((mMeshTranslation.x() == 0.0 && mMeshTranslation.y() == 0.0) && std::fabs(mOriginalHalfExtents.x() - mOriginalHalfExtents.y()) < 2.2) { switch (collisionShapeType) { case DetourNavigator::CollisionShapeType::Aabb: mShape = std::make_unique<btBoxShape>(halfExtents); mRotationallyInvariant = true; break; case DetourNavigator::CollisionShapeType::RotatingBox: mShape = std::make_unique<btBoxShape>(halfExtents); mRotationallyInvariant = false; break; case DetourNavigator::CollisionShapeType::Cylinder: mShape = std::make_unique<btCylinderShapeZ>(halfExtents); mRotationallyInvariant = true; break; } mCollisionShapeType = collisionShapeType; } else { mShape = std::make_unique<btBoxShape>(halfExtents); mRotationallyInvariant = false; mCollisionShapeType = DetourNavigator::CollisionShapeType::RotatingBox; } mConvexShape = static_cast<btConvexShape*>(mShape.get()); mConvexShape->setMargin(0.001); // make sure bullet isn't using the huge default convex shape margin of 0.04 mCollisionObject = std::make_unique<btCollisionObject>(); mCollisionObject->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); mCollisionObject->setActivationState(DISABLE_DEACTIVATION); mCollisionObject->setCollisionShape(mShape.get()); mCollisionObject->setUserPointer(this); updateScaleUnsafe(); if (!mRotationallyInvariant) { const SceneUtil::PositionAttitudeTransform* baseNode = mPtr.getRefData().getBaseNode(); if (baseNode) mRotation = baseNode->getAttitude(); } addCollisionMask(getCollisionMask()); updateCollisionObjectPositionUnsafe(); } Actor::~Actor() { mTaskScheduler->removeCollisionObject(mCollisionObject.get()); } void Actor::enableCollisionMode(bool collision) { mInternalCollisionMode = collision; } void Actor::enableCollisionBody(bool collision) { if (mExternalCollisionMode != collision) { mExternalCollisionMode = collision; updateCollisionMask(); } } void Actor::addCollisionMask(int collisionMask) { mTaskScheduler->addCollisionObject(mCollisionObject.get(), CollisionType_Actor, collisionMask); } void Actor::updateCollisionMask() { mTaskScheduler->setCollisionFilterMask(mCollisionObject.get(), getCollisionMask()); } int Actor::getCollisionMask() const { int collisionMask = CollisionType_World | CollisionType_HeightMap; if (mExternalCollisionMode) collisionMask |= CollisionType_Actor | CollisionType_Projectile | CollisionType_Door; if (mCanWaterWalk) collisionMask |= CollisionType_Water; return collisionMask; } void Actor::updatePosition() { std::scoped_lock lock(mPositionMutex); const auto worldPosition = mPtr.getRefData().getPosition().asVec3(); mPreviousPosition = worldPosition; mPosition = worldPosition; mSimulationPosition = worldPosition; mPositionOffset = osg::Vec3f(); mStandingOnPtr = nullptr; mSkipSimulation = true; } void Actor::setSimulationPosition(const osg::Vec3f& position) { if (!std::exchange(mSkipSimulation, false)) mSimulationPosition = position; } osg::Vec3f Actor::getScaledMeshTranslation() const { return mRotation * osg::componentMultiply(mMeshTranslation, mScale); } void Actor::updateCollisionObjectPosition() { std::scoped_lock lock(mPositionMutex); updateCollisionObjectPositionUnsafe(); } void Actor::updateCollisionObjectPositionUnsafe() { mShape->setLocalScaling(Misc::Convert::toBullet(mScale)); osg::Vec3f newPosition = getScaledMeshTranslation() + mPosition; auto& trans = mCollisionObject->getWorldTransform(); trans.setOrigin(Misc::Convert::toBullet(newPosition)); trans.setRotation(Misc::Convert::toBullet(mRotation)); mCollisionObject->setWorldTransform(trans); } osg::Vec3f Actor::getCollisionObjectPosition() const { std::scoped_lock lock(mPositionMutex); return getScaledMeshTranslation() + mPosition; } bool Actor::setPosition(const osg::Vec3f& position) { std::scoped_lock lock(mPositionMutex); const bool worldPositionChanged = mPositionOffset.length2() != 0; applyOffsetChange(); if (worldPositionChanged || mSkipSimulation) return true; mPreviousPosition = mPosition; mPosition = position; return mPreviousPosition != mPosition; } void Actor::adjustPosition(const osg::Vec3f& offset) { std::scoped_lock lock(mPositionMutex); mPositionOffset += offset; } osg::Vec3f Actor::applyOffsetChange() { if (mPositionOffset.length2() != 0) { mPosition += mPositionOffset; mPreviousPosition += mPositionOffset; mSimulationPosition += mPositionOffset; mPositionOffset = osg::Vec3f(); } return mPosition; } void Actor::setRotation(osg::Quat quat) { std::scoped_lock lock(mPositionMutex); mRotation = quat; } bool Actor::isRotationallyInvariant() const { return mRotationallyInvariant; } void Actor::updateScale() { std::scoped_lock lock(mPositionMutex); updateScaleUnsafe(); } void Actor::updateScaleUnsafe() { float scale = mPtr.getCellRef().getScale(); osg::Vec3f scaleVec(scale, scale, scale); mPtr.getClass().adjustScale(mPtr, scaleVec, false); mScale = scaleVec; mHalfExtents = osg::componentMultiply(mOriginalHalfExtents, scaleVec); scaleVec = osg::Vec3f(scale, scale, scale); mPtr.getClass().adjustScale(mPtr, scaleVec, true); mRenderingHalfExtents = osg::componentMultiply(mOriginalHalfExtents, scaleVec); } osg::Vec3f Actor::getHalfExtents() const { return mHalfExtents; } osg::Vec3f Actor::getOriginalHalfExtents() const { return mOriginalHalfExtents; } osg::Vec3f Actor::getRenderingHalfExtents() const { return mRenderingHalfExtents; } void Actor::setInertialForce(const osg::Vec3f& force) { mForce = force; } void Actor::setOnGround(bool grounded) { mOnGround = grounded; } void Actor::setOnSlope(bool slope) { mOnSlope = slope; } bool Actor::isWalkingOnWater() const { return mWalkingOnWater; } void Actor::setWalkingOnWater(bool walkingOnWater) { mWalkingOnWater = walkingOnWater; } void Actor::setCanWaterWalk(bool waterWalk) { if (waterWalk != mCanWaterWalk) { mCanWaterWalk = waterWalk; updateCollisionMask(); } } MWWorld::Ptr Actor::getStandingOnPtr() const { std::scoped_lock lock(mPositionMutex); return mStandingOnPtr; } void Actor::setStandingOnPtr(const MWWorld::Ptr& ptr) { std::scoped_lock lock(mPositionMutex); mStandingOnPtr = ptr; } bool Actor::canMoveToWaterSurface(float waterlevel, const btCollisionWorld* world) const { const float halfZ = getHalfExtents().z(); const osg::Vec3f actorPosition = getPosition(); const osg::Vec3f startingPosition(actorPosition.x(), actorPosition.y(), actorPosition.z() + halfZ); const osg::Vec3f destinationPosition(actorPosition.x(), actorPosition.y(), waterlevel + halfZ); MWPhysics::ActorTracer tracer; tracer.doTrace(getCollisionObject(), startingPosition, destinationPosition, world); return (tracer.mFraction >= 1.0f); } }
10,771
C++
.cpp
282
29.560284
116
0.646197
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,366
actorconvexcallback.cpp
OpenMW_openmw/apps/openmw/mwphysics/actorconvexcallback.cpp
#include "actorconvexcallback.hpp" #include "collisiontype.hpp" #include "contacttestwrapper.h" #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <components/misc/convert.hpp> #include "projectile.hpp" namespace MWPhysics { namespace { struct ActorOverlapTester : public btCollisionWorld::ContactResultCallback { bool mOverlapping = false; btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* /*colObj0Wrap*/, int /*partId0*/, int /*index0*/, const btCollisionObjectWrapper* /*colObj1Wrap*/, int /*partId1*/, int /*index1*/) override { if (cp.getDistance() <= 0.0f) mOverlapping = true; return 1; } }; } btScalar ActorConvexCallback::addSingleResult( btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace) { if (convexResult.m_hitCollisionObject == mMe) return 1; // override data for actor-actor collisions // vanilla Morrowind seems to make overlapping actors collide as though they are both cylinders with a diameter // of the distance between them For some reason this doesn't work as well as it should when using capsules, but // it still helps a lot. if (convexResult.m_hitCollisionObject->getBroadphaseHandle()->m_collisionFilterGroup == CollisionType_Actor) { ActorOverlapTester isOverlapping; // FIXME: This is absolutely terrible and bullet should feel terrible for not making contactPairTest // const-correct. ContactTestWrapper::contactPairTest(const_cast<btCollisionWorld*>(mWorld), const_cast<btCollisionObject*>(mMe), const_cast<btCollisionObject*>(convexResult.m_hitCollisionObject), isOverlapping); if (isOverlapping.mOverlapping) { auto originA = Misc::Convert::toOsg(mMe->getWorldTransform().getOrigin()); auto originB = Misc::Convert::toOsg(convexResult.m_hitCollisionObject->getWorldTransform().getOrigin()); osg::Vec3f motion = Misc::Convert::toOsg(mMotion); osg::Vec3f normal = (originA - originB); normal.z() = 0; normal.normalize(); // only collide if horizontally moving towards the hit actor (note: the motion vector appears to be // inverted) // FIXME: This kinda screws with standing on actors that walk up slopes for some reason. Makes you fall // through them. It happens in vanilla Morrowind too, but much less often. I tried hunting down why but // couldn't figure it out. Possibly a stair stepping or ground ejection bug. if (normal * motion > 0.0f) { convexResult.m_hitFraction = 0.0f; convexResult.m_hitNormalLocal = Misc::Convert::toBullet(normal); return ClosestConvexResultCallback::addSingleResult(convexResult, true); } else { return 1; } } } if (convexResult.m_hitCollisionObject->getBroadphaseHandle()->m_collisionFilterGroup == CollisionType_Projectile) { auto* projectileHolder = static_cast<Projectile*>(convexResult.m_hitCollisionObject->getUserPointer()); if (!projectileHolder->isActive()) return 1; if (projectileHolder->isValidTarget(mMe)) projectileHolder->hit(mMe, convexResult.m_hitPointLocal, convexResult.m_hitNormalLocal); return 1; } btVector3 hitNormalWorld; if (normalInWorldSpace) hitNormalWorld = convexResult.m_hitNormalLocal; else { /// need to transform normal into worldspace hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis() * convexResult.m_hitNormalLocal; } // dot product of the motion vector against the collision contact normal btScalar dotCollision = mMotion.dot(hitNormalWorld); if (dotCollision <= mMinCollisionDot) return 1; return ClosestConvexResultCallback::addSingleResult(convexResult, normalInWorldSpace); } }
4,489
C++
.cpp
91
37.406593
120
0.631495
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,367
heightfield.cpp
OpenMW_openmw/apps/openmw/mwphysics/heightfield.cpp
#include "heightfield.hpp" #include "mtphysics.hpp" #include <components/bullethelpers/heightfield.hpp> #include <osg/Object> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <BulletCollision/CollisionShapes/btHeightfieldTerrainShape.h> #include <LinearMath/btTransform.h> #include <type_traits> #if BT_BULLET_VERSION < 310 // Older Bullet versions only support `btScalar` heightfields. // Our heightfield data is `float`. // // These functions handle conversion from `float` to `double` when // `btScalar` is `double` (`BT_USE_DOUBLE_PRECISION`). namespace { template <class T> auto makeHeights(const T* heights, int verts) -> std::enable_if_t<std::is_same<btScalar, T>::value, std::vector<btScalar>> { return {}; } template <class T> auto makeHeights(const T* heights, int verts) -> std::enable_if_t<!std::is_same<btScalar, T>::value, std::vector<btScalar>> { return std::vector<btScalar>(heights, heights + static_cast<std::ptrdiff_t>(verts * verts)); } template <class T> auto getHeights(const T* floatHeights, const std::vector<btScalar>&) -> std::enable_if_t<std::is_same<btScalar, T>::value, const btScalar*> { return floatHeights; } template <class T> auto getHeights(const T*, const std::vector<btScalar>& btScalarHeights) -> std::enable_if_t<!std::is_same<btScalar, T>::value, const btScalar*> { return btScalarHeights.data(); } } #endif namespace MWPhysics { HeightField::HeightField(const float* heights, int x, int y, int size, int verts, float minH, float maxH, const osg::Object* holdObject, PhysicsTaskScheduler* scheduler) : mHoldObject(holdObject) #if BT_BULLET_VERSION < 310 , mHeights(makeHeights(heights, verts)) #endif , mTaskScheduler(scheduler) { #if BT_BULLET_VERSION < 310 mShape = std::make_unique<btHeightfieldTerrainShape>( verts, verts, getHeights(heights, mHeights), 1, minH, maxH, 2, PHY_FLOAT, false); #else mShape = std::make_unique<btHeightfieldTerrainShape>(verts, verts, heights, minH, maxH, 2, false); #endif mShape->setUseDiamondSubdivision(true); const float scaling = static_cast<float>(size) / static_cast<float>(verts - 1); mShape->setLocalScaling(btVector3(scaling, scaling, 1)); #if BT_BULLET_VERSION >= 289 // Accelerates some collision tests. // // Note: The accelerator data structure in Bullet is only used // in some operations. This could be improved, see: // https://github.com/bulletphysics/bullet3/issues/3276 mShape->buildAccelerator(); #endif const btTransform transform( btQuaternion::getIdentity(), BulletHelpers::getHeightfieldShift(x, y, size, minH, maxH)); mCollisionObject = std::make_unique<btCollisionObject>(); mCollisionObject->setCollisionShape(mShape.get()); mCollisionObject->setWorldTransform(transform); mTaskScheduler->addCollisionObject( mCollisionObject.get(), CollisionType_HeightMap, CollisionType_Actor | CollisionType_Projectile); } HeightField::~HeightField() { mTaskScheduler->removeCollisionObject(mCollisionObject.get()); } btCollisionObject* HeightField::getCollisionObject() { return mCollisionObject.get(); } const btCollisionObject* HeightField::getCollisionObject() const { return mCollisionObject.get(); } const btHeightfieldTerrainShape* HeightField::getShape() const { return mShape.get(); } }
3,643
C++
.cpp
94
33.138298
109
0.694704
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,368
contacttestwrapper.cpp
OpenMW_openmw/apps/openmw/mwphysics/contacttestwrapper.cpp
#include <mutex> #include "contacttestwrapper.h" namespace MWPhysics { // Concurrent calls to contactPairTest (and by extension contactTest) are forbidden. static std::mutex contactMutex; void ContactTestWrapper::contactTest(btCollisionWorld* collisionWorld, btCollisionObject* colObj, btCollisionWorld::ContactResultCallback& resultCallback) { std::unique_lock lock(contactMutex); collisionWorld->contactTest(colObj, resultCallback); } void ContactTestWrapper::contactPairTest(btCollisionWorld* collisionWorld, btCollisionObject* colObjA, btCollisionObject* colObjB, btCollisionWorld::ContactResultCallback& resultCallback) { std::unique_lock lock(contactMutex); collisionWorld->contactPairTest(colObjA, colObjB, resultCallback); } }
819
C++
.cpp
19
37.684211
106
0.771357
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,369
movementsolver.cpp
OpenMW_openmw/apps/openmw/mwphysics/movementsolver.cpp
#include "movementsolver.hpp" #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <BulletCollision/CollisionShapes/btConvexShape.h> #include <components/esm3/loadgmst.hpp> #include <components/misc/convert.hpp> #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" #include "actor.hpp" #include "collisiontype.hpp" #include "constants.hpp" #include "contacttestwrapper.h" #include "object.hpp" #include "physicssystem.hpp" #include "projectile.hpp" #include "projectileconvexcallback.hpp" #include "stepper.hpp" #include "trace.h" #include <cmath> namespace MWPhysics { static bool isActor(const btCollisionObject* obj) { assert(obj); return obj->getBroadphaseHandle()->m_collisionFilterGroup == CollisionType_Actor; } namespace { class ContactCollectionCallback : public btCollisionWorld::ContactResultCallback { public: explicit ContactCollectionCallback(const btCollisionObject& me, const osg::Vec3f& velocity) : mVelocity(Misc::Convert::toBullet(velocity)) { m_collisionFilterGroup = me.getBroadphaseHandle()->m_collisionFilterGroup; m_collisionFilterMask = me.getBroadphaseHandle()->m_collisionFilterMask & ~CollisionType_Projectile; } btScalar addSingleResult(btManifoldPoint& contact, const btCollisionObjectWrapper* colObj0Wrap, int /*partId0*/, int /*index0*/, const btCollisionObjectWrapper* colObj1Wrap, int /*partId1*/, int /*index1*/) override { if (isActor(colObj0Wrap->getCollisionObject()) && isActor(colObj1Wrap->getCollisionObject())) return 0.0; // ignore overlap if we're moving in the same direction as it would push us out (don't change this to // >=, that would break detection when not moving) if (contact.m_normalWorldOnB.dot(mVelocity) > 0.0) return 0.0; auto delta = contact.m_normalWorldOnB * -contact.m_distance1; mContactSum += delta; mMaxX = std::max(std::abs(delta.x()), mMaxX); mMaxY = std::max(std::abs(delta.y()), mMaxY); mMaxZ = std::max(std::abs(delta.z()), mMaxZ); if (contact.m_distance1 < mDistance) { mDistance = contact.m_distance1; mNormal = contact.m_normalWorldOnB; mDelta = delta; return mDistance; } else { return 0.0; } } btScalar mMaxX = 0.0; btScalar mMaxY = 0.0; btScalar mMaxZ = 0.0; btVector3 mContactSum{ 0.0, 0.0, 0.0 }; btVector3 mNormal{ 0.0, 0.0, 0.0 }; // points towards "me" btVector3 mDelta{ 0.0, 0.0, 0.0 }; // points towards "me" btScalar mDistance = 0.0; // negative or zero protected: btVector3 mVelocity; }; } osg::Vec3f MovementSolver::traceDown(const MWWorld::Ptr& ptr, const osg::Vec3f& position, Actor* actor, btCollisionWorld* collisionWorld, float maxHeight) { osg::Vec3f offset = actor->getCollisionObjectPosition() - ptr.getRefData().getPosition().asVec3(); ActorTracer tracer; tracer.findGround(actor, position + offset, position + offset - osg::Vec3f(0, 0, maxHeight), collisionWorld); if (tracer.mFraction >= 1.0f) { actor->setOnGround(false); return position; } actor->setOnGround(true); // Check if we actually found a valid spawn point (use an infinitely thin ray this time). // Required for some broken door destinations in Morrowind.esm, where the spawn point // intersects with other geometry if the actor's base is taken into account btVector3 from = Misc::Convert::toBullet(position); btVector3 to = from - btVector3(0, 0, maxHeight); btCollisionWorld::ClosestRayResultCallback resultCallback1(from, to); resultCallback1.m_collisionFilterGroup = CollisionType_AnyPhysical; resultCallback1.m_collisionFilterMask = CollisionType_World | CollisionType_HeightMap; collisionWorld->rayTest(from, to, resultCallback1); if (resultCallback1.hasHit() && ((Misc::Convert::toOsg(resultCallback1.m_hitPointWorld) - tracer.mEndPos + offset).length2() > 35 * 35 || !isWalkableSlope(tracer.mPlaneNormal))) { actor->setOnSlope(!isWalkableSlope(resultCallback1.m_hitNormalWorld)); return Misc::Convert::toOsg(resultCallback1.m_hitPointWorld) + osg::Vec3f(0.f, 0.f, sGroundOffset); } actor->setOnSlope(!isWalkableSlope(tracer.mPlaneNormal)); return tracer.mEndPos - offset + osg::Vec3f(0.f, 0.f, sGroundOffset); } void MovementSolver::move( ActorFrameData& actor, float time, const btCollisionWorld* collisionWorld, const WorldFrameData& worldData) { // Reset per-frame data actor.mWalkingOnWater = false; // Anything to collide with? if (actor.mSkipCollisionDetection) { actor.mPosition += (osg::Quat(actor.mRotation.x(), osg::Vec3f(-1, 0, 0)) * osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1))) * actor.mMovement * time; return; } // Adjust for collision mesh offset relative to actor's "location" // (doTrace doesn't take local/interior collision shape translation into account, so we have to do it on our // own) for compatibility with vanilla assets, we have to derive this from the vertical half extent instead of // from internal hull translation if not for this hack, the "correct" collision hull position would be // physicActor->getScaledMeshTranslation() actor.mPosition.z() += actor.mHalfExtentsZ; // vanilla-accurate float swimlevel = actor.mSwimLevel + actor.mHalfExtentsZ; ActorTracer tracer; osg::Vec3f velocity; // Dead and paralyzed actors underwater will float to the surface, // if the CharacterController tells us to do so if (actor.mMovement.z() > 0 && actor.mInert && actor.mPosition.z() < swimlevel) { velocity = osg::Vec3f(0, 0, 1) * 25; } else if (actor.mPosition.z() < swimlevel || actor.mFlying) { velocity = (osg::Quat(actor.mRotation.x(), osg::Vec3f(-1, 0, 0)) * osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1))) * actor.mMovement; } else { velocity = (osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1))) * actor.mMovement; if ((velocity.z() > 0.f && actor.mIsOnGround && !actor.mIsOnSlope) || (velocity.z() > 0.f && velocity.z() + actor.mInertia.z() <= -velocity.z() && actor.mIsOnSlope)) actor.mInertia = velocity; else if (!actor.mIsOnGround || actor.mIsOnSlope) velocity = velocity + actor.mInertia; } // Now that we have the effective movement vector, apply wind forces to it if (worldData.mIsInStorm && velocity.length() > 0) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); const float fStromWalkMult = store.get<ESM::GameSetting>().find("fStromWalkMult")->mValue.getFloat(); const float angleCos = worldData.mStormDirection * velocity / velocity.length(); velocity *= 1.f + fStromWalkMult * angleCos; } Stepper stepper(collisionWorld, actor.mCollisionObject); osg::Vec3f origVelocity = velocity; osg::Vec3f newPosition = actor.mPosition; /* * A loop to find newPosition using tracer, if successful different from the starting position. * nextpos is the local variable used to find potential newPosition, using velocity and remainingTime * The initial velocity was set earlier (see above). */ float remainingTime = time; int numTimesSlid = 0; osg::Vec3f lastSlideNormal(0, 0, 1); osg::Vec3f lastSlideNormalFallback(0, 0, 1); bool forceGroundTest = false; for (int iterations = 0; iterations < sMaxIterations && remainingTime > 0.0001f; ++iterations) { osg::Vec3f nextpos = newPosition + velocity * remainingTime; bool underwater = newPosition.z() < swimlevel; // If not able to fly, don't allow to swim up into the air if (!actor.mFlying && nextpos.z() > swimlevel && underwater) { const osg::Vec3f down(0, 0, -1); velocity = reject(velocity, down); // NOTE: remainingTime is unchanged before the loop continues continue; // velocity updated, calculate nextpos again } if ((newPosition - nextpos).length2() > 0.0001) { // trace to where character would go if there were no obstructions tracer.doTrace(actor.mCollisionObject, newPosition, nextpos, collisionWorld, actor.mIsOnGround); // check for obstructions if (tracer.mFraction >= 1.0f) { newPosition = tracer.mEndPos; // ok to move, so set newPosition break; } } else { // The current position and next position are nearly the same, so just exit. // Note: Bullet can trigger an assert in debug modes if the positions // are the same, since that causes it to attempt to normalize a zero // length vector (which can also happen with nearly identical vectors, since // precision can be lost due to any math Bullet does internally). Since we // aren't performing any collision detection, we want to reject the next // position, so that we don't slowly move inside another object. break; } bool seenGround = !actor.mFlying && !underwater && ((actor.mIsOnGround && !actor.mIsOnSlope) || isWalkableSlope(tracer.mPlaneNormal)); // We hit something. Check if we can step up. float hitHeight = tracer.mHitPoint.z() - tracer.mEndPos.z() + actor.mHalfExtentsZ; osg::Vec3f oldPosition = newPosition; bool usedStepLogic = false; if (!isActor(tracer.mHitObject)) { if (hitHeight < Constants::sStepSizeUp) { // Try to step up onto it. // NOTE: this modifies newPosition and velocity on its own if successful usedStepLogic = stepper.step(newPosition, velocity, remainingTime, seenGround, iterations == 0); } auto* ptrHolder = static_cast<PtrHolder*>(tracer.mHitObject->getUserPointer()); if (Object* hitObject = dynamic_cast<Object*>(ptrHolder)) { hitObject->addCollision( actor.mIsPlayer ? ScriptedCollisionType_Player : ScriptedCollisionType_Actor); } } if (usedStepLogic) { if (actor.mIsAquatic && newPosition.z() + actor.mHalfExtentsZ > actor.mWaterlevel) newPosition = oldPosition; else if (!actor.mFlying && actor.mPosition.z() >= swimlevel) forceGroundTest = true; } else { // Can't step up, so slide against what we ran into remainingTime *= (1.0f - tracer.mFraction); auto planeNormal = tracer.mPlaneNormal; // need to know the unadjusted normal to handle certain types of seams properly const auto origPlaneNormal = planeNormal; // If we touched the ground this frame, and whatever we ran into is a wall of some sort, // pretend that its collision normal is pointing horizontally // (fixes snagging on slightly downward-facing walls, and crawling up the bases of very steep walls // because of the collision margin) if (seenGround && !isWalkableSlope(planeNormal) && planeNormal.z() != 0) { planeNormal.z() = 0; planeNormal.normalize(); } // Move up to what we ran into (with a bit of a collision margin) if ((newPosition - tracer.mEndPos).length2() > sCollisionMargin * sCollisionMargin) { auto direction = velocity; direction.normalize(); newPosition = tracer.mEndPos; newPosition -= direction * sCollisionMargin; } osg::Vec3f newVelocity = (velocity * planeNormal <= 0.0) ? reject(velocity, planeNormal) : velocity; bool usedSeamLogic = false; // check for the current and previous collision planes forming an acute angle; slide along the seam if // they do for this, we want to use the original plane normal, or else certain types of geometry will // snag if (numTimesSlid > 0) { auto dotA = lastSlideNormal * origPlaneNormal; auto dotB = lastSlideNormalFallback * origPlaneNormal; if (numTimesSlid <= 1) // ignore fallback normal if this is only the first or second slide dotB = 1.0; if (dotA <= 0.0 || dotB <= 0.0) { osg::Vec3f bestNormal = lastSlideNormal; // use previous-to-previous collision plane if it's acute with current plane but actual previous // plane isn't if (dotB < dotA) { bestNormal = lastSlideNormalFallback; lastSlideNormal = lastSlideNormalFallback; } auto constraintVector = bestNormal ^ origPlaneNormal; // cross product if (constraintVector.length2() > 0) // only if it's not zero length { constraintVector.normalize(); newVelocity = project(velocity, constraintVector); // version of surface rejection for acute crevices/seams auto averageNormal = bestNormal + origPlaneNormal; averageNormal.normalize(); tracer.doTrace(actor.mCollisionObject, newPosition, newPosition + averageNormal * (sCollisionMargin * 2.0), collisionWorld); newPosition = (newPosition + tracer.mEndPos) / 2.0; usedSeamLogic = true; } } } // otherwise just keep the normal vector rejection // move away from the collision plane slightly, if possible // this reduces getting stuck in some concave geometry, like the gaps above the railings in some // ald'ruhn buildings this is different from the normal collision margin, because the normal collision // margin is along the movement path, but this is along the collision normal if (!usedSeamLogic) { tracer.doTrace(actor.mCollisionObject, newPosition, newPosition + planeNormal * (sCollisionMargin * 2.0), collisionWorld); newPosition = (newPosition + tracer.mEndPos) / 2.0; } // short circuit if we went backwards, but only if it was mostly horizontal and we're on the ground if (seenGround && newVelocity * origVelocity <= 0.0f) { auto perpendicular = newVelocity ^ origVelocity; if (perpendicular.length2() > 0.0f) { perpendicular.normalize(); if (std::abs(perpendicular.z()) > 0.7071f) break; } } // Do not allow sliding up steep slopes if there is gravity. // The purpose of this is to prevent air control from letting you slide up tall, unwalkable slopes. // For that purpose, it is not necessary to do it when trying to slide along acute seams/crevices (i.e. // usedSeamLogic) and doing so would actually break air control in some situations where vanilla allows // air control. Vanilla actually allows you to slide up slopes as long as you're in the "walking" // animation, which can be true even in the air, so allowing this for seams isn't a compatibility break. if (newPosition.z() >= swimlevel && !actor.mFlying && !isWalkableSlope(planeNormal) && !usedSeamLogic) newVelocity.z() = std::min(newVelocity.z(), velocity.z()); numTimesSlid += 1; lastSlideNormalFallback = lastSlideNormal; lastSlideNormal = origPlaneNormal; velocity = newVelocity; } } bool isOnGround = false; bool isOnSlope = false; if (forceGroundTest || (actor.mInertia.z() <= 0.f && newPosition.z() >= swimlevel)) { osg::Vec3f from = newPosition; auto dropDistance = 2 * sGroundOffset + (actor.mIsOnGround ? sStepSizeDown : 0); osg::Vec3f to = newPosition - osg::Vec3f(0, 0, dropDistance); tracer.doTrace(actor.mCollisionObject, from, to, collisionWorld, actor.mIsOnGround); if (tracer.mFraction < 1.0f) { if (!isActor(tracer.mHitObject)) { isOnGround = true; isOnSlope = !isWalkableSlope(tracer.mPlaneNormal); actor.mStandingOn = tracer.mHitObject; if (actor.mStandingOn->getBroadphaseHandle()->m_collisionFilterGroup == CollisionType_Water) actor.mWalkingOnWater = true; if (!actor.mFlying && !isOnSlope) { if (tracer.mFraction * dropDistance > sGroundOffset) newPosition.z() = tracer.mEndPos.z() + sGroundOffset; else { newPosition.z() = tracer.mEndPos.z(); tracer.doTrace(actor.mCollisionObject, newPosition, newPosition + osg::Vec3f(0, 0, 2 * sGroundOffset), collisionWorld); newPosition = (newPosition + tracer.mEndPos) / 2.0; } } } else { // Vanilla allows actors to float on top of other actors. Do not push them off. if (!actor.mFlying && isWalkableSlope(tracer.mPlaneNormal) && tracer.mEndPos.z() + sGroundOffset <= newPosition.z()) newPosition.z() = tracer.mEndPos.z() + sGroundOffset; isOnGround = false; } } // forcibly treat stuck actors as if they're on flat ground because buggy collisions when inside of things // can/will break ground detection if (actor.mStuckFrames > 0) { isOnGround = true; isOnSlope = false; } } if ((isOnGround && !isOnSlope) || newPosition.z() < swimlevel || actor.mFlying) actor.mInertia = osg::Vec3f(0.f, 0.f, 0.f); else { actor.mInertia.z() -= time * Constants::GravityConst * Constants::UnitsPerMeter; if (actor.mInertia.z() < 0) actor.mInertia.z() *= actor.mSlowFall; if (actor.mSlowFall < 1.f) { actor.mInertia.x() *= actor.mSlowFall; actor.mInertia.y() *= actor.mSlowFall; } } actor.mIsOnGround = isOnGround; actor.mIsOnSlope = isOnSlope; actor.mPosition = newPosition; // remove what was added earlier in compensating for doTrace not taking interior transformation into account actor.mPosition.z() -= actor.mHalfExtentsZ; // vanilla-accurate } void MovementSolver::move(ProjectileFrameData& projectile, float time, const btCollisionWorld* collisionWorld) { btVector3 btFrom = Misc::Convert::toBullet(projectile.mPosition); btVector3 btTo = Misc::Convert::toBullet(projectile.mPosition + projectile.mMovement * time); if (btFrom == btTo) return; assert(projectile.mProjectile != nullptr); ProjectileConvexCallback resultCallback( projectile.mCaster, projectile.mCollisionObject, btFrom, btTo, *projectile.mProjectile); resultCallback.m_collisionFilterMask = CollisionType_AnyPhysical; resultCallback.m_collisionFilterGroup = CollisionType_Projectile; const btQuaternion btrot = btQuaternion::getIdentity(); btTransform from_(btrot, btFrom); btTransform to_(btrot, btTo); const btCollisionShape* shape = projectile.mCollisionObject->getCollisionShape(); assert(shape->isConvex()); collisionWorld->convexSweepTest(static_cast<const btConvexShape*>(shape), from_, to_, resultCallback); projectile.mPosition = Misc::Convert::toOsg(projectile.mProjectile->isActive() ? btTo : resultCallback.m_hitPointWorld); } btVector3 addMarginToDelta(btVector3 delta) { if (delta.length2() == 0.0) return delta; return delta + delta.normalized() * sCollisionMargin; } void MovementSolver::unstuck(ActorFrameData& actor, const btCollisionWorld* collisionWorld) { if (actor.mSkipCollisionDetection) // noclipping/tcl return; if (actor.mMovement.length2() == 0) // no AI nor player attempted to move, current position is assumed correct return; auto tempPosition = actor.mPosition; if (actor.mStuckFrames >= 10) { if ((actor.mLastStuckPosition - actor.mPosition).length2() < 100) return; else { actor.mStuckFrames = 0; actor.mLastStuckPosition = { 0, 0, 0 }; } } // use vanilla-accurate collision hull position hack (do same hitbox offset hack as movement solver) // if vanilla compatibility didn't matter, the "correct" collision hull position would be // physicActor->getScaledMeshTranslation() const auto verticalHalfExtent = osg::Vec3f(0.0, 0.0, actor.mHalfExtentsZ); // use a 3d approximation of the movement vector to better judge player intent auto velocity = (osg::Quat(actor.mRotation.x(), osg::Vec3f(-1, 0, 0)) * osg::Quat(actor.mRotation.y(), osg::Vec3f(0, 0, -1))) * actor.mMovement; // try to pop outside of the world before doing anything else if we're inside of it if (!actor.mIsOnGround || actor.mIsOnSlope) velocity += actor.mInertia; // because of the internal collision box offset hack, and the fact that we're moving the collision box manually, // we need to replicate part of the collision box's transform process from scratch osg::Vec3f refPosition = tempPosition + verticalHalfExtent; osg::Vec3f goodPosition = refPosition; const btTransform oldTransform = actor.mCollisionObject->getWorldTransform(); btTransform newTransform = oldTransform; auto gatherContacts = [&](btVector3 newOffset) -> ContactCollectionCallback { goodPosition = refPosition + Misc::Convert::toOsg(addMarginToDelta(newOffset)); newTransform.setOrigin(Misc::Convert::toBullet(goodPosition)); actor.mCollisionObject->setWorldTransform(newTransform); ContactCollectionCallback callback(*actor.mCollisionObject, velocity); ContactTestWrapper::contactTest( const_cast<btCollisionWorld*>(collisionWorld), actor.mCollisionObject, callback); return callback; }; // check whether we're inside the world with our collision box with manually-derived offset auto contactCallback = gatherContacts({ 0.0, 0.0, 0.0 }); if (contactCallback.mDistance < -sAllowedPenetration) { ++actor.mStuckFrames; actor.mLastStuckPosition = actor.mPosition; // we are; try moving it out of the world auto positionDelta = contactCallback.mContactSum; // limit rejection delta to the largest known individual rejections if (std::abs(positionDelta.x()) > contactCallback.mMaxX) positionDelta *= contactCallback.mMaxX / std::abs(positionDelta.x()); if (std::abs(positionDelta.y()) > contactCallback.mMaxY) positionDelta *= contactCallback.mMaxY / std::abs(positionDelta.y()); if (std::abs(positionDelta.z()) > contactCallback.mMaxZ) positionDelta *= contactCallback.mMaxZ / std::abs(positionDelta.z()); auto contactCallback2 = gatherContacts(positionDelta); // successfully moved further out from contact (does not have to be in open space, just less inside of // things) if (contactCallback2.mDistance > contactCallback.mDistance) tempPosition = goodPosition - verticalHalfExtent; // try again but only upwards (fixes some bad coc floors) else { // upwards-only offset auto contactCallback3 = gatherContacts({ 0.0, 0.0, std::abs(positionDelta.z()) }); // success if (contactCallback3.mDistance > contactCallback.mDistance) tempPosition = goodPosition - verticalHalfExtent; else // try again but fixed distance up { auto contactCallback4 = gatherContacts({ 0.0, 0.0, 10.0 }); // success if (contactCallback4.mDistance > contactCallback.mDistance) tempPosition = goodPosition - verticalHalfExtent; } } } else { actor.mStuckFrames = 0; actor.mLastStuckPosition = { 0, 0, 0 }; } actor.mCollisionObject->setWorldTransform(oldTransform); actor.mPosition = tempPosition; } }
27,496
C++
.cpp
510
39.739216
120
0.587114
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,370
contacttestresultcallback.cpp
OpenMW_openmw/apps/openmw/mwphysics/contacttestresultcallback.cpp
#include "contacttestresultcallback.hpp" #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include "components/misc/convert.hpp" #include "ptrholder.hpp" namespace MWPhysics { btScalar ContactTestResultCallback::addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* col0Wrap, int /*partId0*/, int /*index0*/, const btCollisionObjectWrapper* col1Wrap, int /*partId1*/, int /*index1*/) { const btCollisionObject* collisionObject = col0Wrap->m_collisionObject; if (collisionObject == mTestedAgainst) collisionObject = col1Wrap->m_collisionObject; PtrHolder* holder = static_cast<PtrHolder*>(collisionObject->getUserPointer()); if (holder) mResult.emplace_back(ContactPoint{ holder->getPtr(), Misc::Convert::toOsg(cp.m_positionWorldOnB), Misc::Convert::toOsg(cp.m_normalWorldOnB) }); return 0.f; } }
932
C++
.cpp
19
42.526316
118
0.723568
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,371
projectileconvexcallback.cpp
OpenMW_openmw/apps/openmw/mwphysics/projectileconvexcallback.cpp
#include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include "collisiontype.hpp" #include "projectile.hpp" #include "projectileconvexcallback.hpp" namespace MWPhysics { btScalar ProjectileConvexCallback::addSingleResult( btCollisionWorld::LocalConvexResult& result, bool normalInWorldSpace) { const auto* hitObject = result.m_hitCollisionObject; // don't hit the caster if (hitObject == mCaster) return 1.f; // don't hit the projectile if (hitObject == mMe) return 1.f; btCollisionWorld::ClosestConvexResultCallback::addSingleResult(result, normalInWorldSpace); switch (hitObject->getBroadphaseHandle()->m_collisionFilterGroup) { case CollisionType_Actor: { if (!mProjectile.isValidTarget(hitObject)) return 1.f; break; } case CollisionType_Projectile: { auto* target = static_cast<Projectile*>(hitObject->getUserPointer()); if (!mProjectile.isValidTarget(target->getCasterCollisionObject())) return 1.f; target->hit(mMe, m_hitPointWorld, m_hitNormalWorld); break; } case CollisionType_Water: { mProjectile.setHitWater(); break; } } mProjectile.hit(hitObject, m_hitPointWorld, m_hitNormalWorld); return result.m_hitFraction; } }
1,556
C++
.cpp
43
25.55814
99
0.603185
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,372
trace.cpp
OpenMW_openmw/apps/openmw/mwphysics/trace.cpp
#include "trace.h" #include <components/misc/convert.hpp> #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <BulletCollision/CollisionShapes/btConvexShape.h> #include "actor.hpp" #include "actorconvexcallback.hpp" #include "collisiontype.hpp" namespace MWPhysics { ActorConvexCallback sweepHelper(const btCollisionObject* actor, const btVector3& from, const btVector3& to, const btCollisionWorld* world, bool actorFilter) { const btTransform& trans = actor->getWorldTransform(); btTransform transFrom(trans); btTransform transTo(trans); transFrom.setOrigin(from); transTo.setOrigin(to); const btCollisionShape* shape = actor->getCollisionShape(); assert(shape->isConvex()); const btVector3 motion = from - to; // FIXME: this is backwards; means ActorConvexCallback is doing dot product tests backwards too ActorConvexCallback traceCallback(actor, motion, btScalar(0.0), world); // Inherit the actor's collision group and mask traceCallback.m_collisionFilterGroup = actor->getBroadphaseHandle()->m_collisionFilterGroup; traceCallback.m_collisionFilterMask = actor->getBroadphaseHandle()->m_collisionFilterMask; if (actorFilter) traceCallback.m_collisionFilterMask &= ~CollisionType_Actor; world->convexSweepTest(static_cast<const btConvexShape*>(shape), transFrom, transTo, traceCallback); return traceCallback; } void ActorTracer::doTrace(const btCollisionObject* actor, const osg::Vec3f& start, const osg::Vec3f& end, const btCollisionWorld* world, bool attempt_short_trace) { const btVector3 btstart = Misc::Convert::toBullet(start); btVector3 btend = Misc::Convert::toBullet(end); // Because Bullet's collision trace tests touch *all* geometry in its path, a lot of long collision tests // will unnecessarily test against complex meshes that are dozens of units away. This wouldn't normally be // a problem, but bullet isn't the fastest in the world when it comes to doing tests against triangle meshes. // Therefore, we try out a short trace first, then only fall back to the full length trace if needed. // This trace needs to be at least a couple units long, but there's no one particular ideal length. // The length of 2.1 chosen here is a "works well in practice after testing a few random lengths" value. // (Also, we only do this short test if the intended collision trace is long enough for it to make sense.) const float fallback_length = 2.1f; bool doing_short_trace = false; // For some reason, typical scenes perform a little better if we increase the threshold length for the length // test. (Multiplying by 2 in 'square distance' units gives us about 1.4x the threshold length. In benchmarks // this was // slightly better for the performance of normal scenes than 4.0, and just plain better than 1.0.) if (attempt_short_trace && (btend - btstart).length2() > fallback_length * fallback_length * 2.0) { btend = btstart + (btend - btstart).normalized() * fallback_length; doing_short_trace = true; } const auto traceCallback = sweepHelper(actor, btstart, btend, world, false); // Copy the hit data over to our trace results struct: if (traceCallback.hasHit()) { mFraction = traceCallback.m_closestHitFraction; // ensure fraction is correct (covers intended distance traveled instead of actual distance traveled) if (doing_short_trace && (end - start).length2() > 0.0) mFraction *= (btend - btstart).length() / (end - start).length(); mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; mHitPoint = Misc::Convert::toOsg(traceCallback.m_hitPointWorld); mHitObject = traceCallback.m_hitCollisionObject; } else { if (doing_short_trace) { btend = Misc::Convert::toBullet(end); const auto newTraceCallback = sweepHelper(actor, btstart, btend, world, false); if (newTraceCallback.hasHit()) { mFraction = newTraceCallback.m_closestHitFraction; mPlaneNormal = Misc::Convert::toOsg(newTraceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; mHitPoint = Misc::Convert::toOsg(newTraceCallback.m_hitPointWorld); mHitObject = newTraceCallback.m_hitCollisionObject; return; } } // fallthrough mEndPos = end; mPlaneNormal = osg::Vec3f(0.0f, 0.0f, 1.0f); mFraction = 1.0f; mHitPoint = end; mHitObject = nullptr; } } void ActorTracer::findGround( const Actor* actor, const osg::Vec3f& start, const osg::Vec3f& end, const btCollisionWorld* world) { const auto traceCallback = sweepHelper( actor->getCollisionObject(), Misc::Convert::toBullet(start), Misc::Convert::toBullet(end), world, true); if (traceCallback.hasHit()) { mFraction = traceCallback.m_closestHitFraction; mPlaneNormal = Misc::Convert::toOsg(traceCallback.m_hitNormalWorld); mEndPos = (end - start) * mFraction + start; } else { mEndPos = end; mPlaneNormal = osg::Vec3f(0.0f, 0.0f, 1.0f); mFraction = 1.0f; } } }
5,783
C++
.cpp
109
42.889908
120
0.650292
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,373
closestnotmerayresultcallback.cpp
OpenMW_openmw/apps/openmw/mwphysics/closestnotmerayresultcallback.cpp
#include "closestnotmerayresultcallback.hpp" #include <algorithm> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include "collisiontype.hpp" namespace MWPhysics { btScalar ClosestNotMeRayResultCallback::addSingleResult( btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace) { const auto* hitObject = rayResult.m_collisionObject; if (std::find(mIgnoreList.begin(), mIgnoreList.end(), hitObject) != mIgnoreList.end()) return 1.f; if (hitObject->getBroadphaseHandle()->m_collisionFilterGroup == CollisionType_Actor && !mTargets.empty()) { if ((std::find(mTargets.begin(), mTargets.end(), hitObject) == mTargets.end())) return 1.f; } return btCollisionWorld::ClosestRayResultCallback::addSingleResult(rayResult, normalInWorldSpace); } }
882
C++
.cpp
20
37.4
113
0.712617
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,376
precipitationocclusion.cpp
OpenMW_openmw/apps/openmw/mwrender/precipitationocclusion.cpp
#include "precipitationocclusion.hpp" #include <cassert> #include <osgUtil/CullVisitor> #include <components/misc/constants.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/util.hpp> #include <components/settings/values.hpp> #include <components/shader/shadermanager.hpp> #include "../mwbase/environment.hpp" #include "vismask.hpp" namespace { class PrecipitationOcclusionUpdater : public SceneUtil::StateSetUpdater { public: PrecipitationOcclusionUpdater(osg::ref_ptr<osg::Texture2D> depthTexture) : mDepthTexture(std::move(depthTexture)) { } private: void setDefaults(osg::StateSet* stateset) override { stateset->setTextureAttributeAndModes(3, mDepthTexture); stateset->addUniform(new osg::Uniform("orthoDepthMap", 3)); stateset->addUniform(new osg::Uniform("depthSpaceMatrix", mDepthSpaceMatrix)); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { osg::Camera* camera = nv->asCullVisitor()->getCurrentCamera(); stateset->getUniform("depthSpaceMatrix")->set(camera->getViewMatrix() * camera->getProjectionMatrix()); } osg::Matrixf mDepthSpaceMatrix; osg::ref_ptr<osg::Texture2D> mDepthTexture; }; class DepthCameraUpdater : public SceneUtil::StateSetUpdater { public: DepthCameraUpdater() : mDummyTexture(new osg::Texture2D) { mDummyTexture->setInternalFormat(GL_RGB); mDummyTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mDummyTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mDummyTexture->setTextureSize(1, 1); Shader::ShaderManager& shaderMgr = MWBase::Environment::get().getResourceSystem()->getSceneManager()->getShaderManager(); mProgram = shaderMgr.getProgram("depthclipped"); } private: void setDefaults(osg::StateSet* stateset) override { stateset->addUniform(new osg::Uniform("projectionMatrix", osg::Matrixf())); stateset->setAttributeAndModes(mProgram, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setTextureAttributeAndModes(0, mDummyTexture); stateset->setRenderBinDetails( osg::StateSet::OPAQUE_BIN, "RenderBin", osg::StateSet::OVERRIDE_PROTECTED_RENDERBIN_DETAILS); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { osg::Camera* camera = nv->asCullVisitor()->getCurrentCamera(); stateset->getUniform("projectionMatrix")->set(camera->getProjectionMatrix()); } osg::Matrixf mProjectionMatrix; osg::ref_ptr<osg::Texture2D> mDummyTexture; osg::ref_ptr<osg::Program> mProgram; }; } namespace MWRender { PrecipitationOccluder::PrecipitationOccluder( osg::Group* skyNode, osg::Group* sceneNode, osg::Group* rootNode, osg::Camera* camera) : mSkyNode(skyNode) , mSceneNode(sceneNode) , mRootNode(rootNode) , mSceneCamera(camera) { constexpr int rttSize = 256; mDepthTexture = new osg::Texture2D; mDepthTexture->setTextureSize(rttSize, rttSize); mDepthTexture->setSourceFormat(GL_DEPTH_COMPONENT); mDepthTexture->setInternalFormat(GL_DEPTH_COMPONENT24); mDepthTexture->setSourceType(GL_UNSIGNED_INT); mDepthTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER); mDepthTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER); mDepthTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); mDepthTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); mDepthTexture->setBorderColor( SceneUtil::AutoDepth::isReversed() ? osg::Vec4(0, 0, 0, 0) : osg::Vec4(1, 1, 1, 1)); mCamera = new osg::Camera; mCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); mCamera->setRenderOrder(osg::Camera::PRE_RENDER); mCamera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); mCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT); mCamera->setNodeMask(Mask_RenderToTexture); mCamera->setCullMask(Mask_Scene | Mask_Object | Mask_Static); mCamera->setViewport(0, 0, rttSize, rttSize); mCamera->attach(osg::Camera::DEPTH_BUFFER, mDepthTexture); mCamera->addChild(mSceneNode); mCamera->setSmallFeatureCullingPixelSize( Settings::shaders().mWeatherParticleOcclusionSmallFeatureCullingPixelSize); SceneUtil::setCameraClearDepth(mCamera); } void PrecipitationOccluder::update() { if (!mRange.has_value()) return; const osg::Vec3 pos = mSceneCamera->getInverseViewMatrix().getTrans(); const float zmin = pos.z() - mRange->z() - Constants::CellSizeInUnits; const float zmax = pos.z() + mRange->z() + Constants::CellSizeInUnits; const float near = 0; const float far = zmax - zmin; const float left = -mRange->x() / 2; const float right = -left; const float top = mRange->y() / 2; const float bottom = -top; if (SceneUtil::AutoDepth::isReversed()) { mCamera->setProjectionMatrix( SceneUtil::getReversedZProjectionMatrixAsOrtho(left, right, bottom, top, near, far)); } else { mCamera->setProjectionMatrix(osg::Matrixf::ortho(left, right, bottom, top, near, far)); } mCamera->setViewMatrixAsLookAt( osg::Vec3(pos.x(), pos.y(), zmax), osg::Vec3(pos.x(), pos.y(), zmin), osg::Vec3(0, 1, 0)); } void PrecipitationOccluder::enable() { mSkyCullCallback = new PrecipitationOcclusionUpdater(mDepthTexture); mSkyNode->addCullCallback(mSkyCullCallback); mCamera->setCullCallback(new DepthCameraUpdater); mRootNode->removeChild(mCamera); mRootNode->addChild(mCamera); } void PrecipitationOccluder::disable() { mSkyNode->removeCullCallback(mSkyCullCallback); mCamera->setCullCallback(nullptr); mSkyCullCallback = nullptr; mRootNode->removeChild(mCamera); mRange = std::nullopt; } void PrecipitationOccluder::updateRange(const osg::Vec3f range) { assert(range.x() != 0); assert(range.y() != 0); assert(range.z() != 0); const osg::Vec3f margin = { -50, -50, 0 }; mRange = range - margin; } }
6,899
C++
.cpp
155
36.16129
115
0.663391
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,377
postprocessor.cpp
OpenMW_openmw/apps/openmw/mwrender/postprocessor.cpp
#include "postprocessor.hpp" #include <SDL_opengl_glext.h> #include <algorithm> #include <chrono> #include <thread> #include <osg/Texture1D> #include <osg/Texture2D> #include <osg/Texture2DArray> #include <osg/Texture2DMultisample> #include <osg/Texture3D> #include <components/files/conversion.hpp> #include <components/misc/strings/algorithm.hpp> #include <components/misc/strings/lower.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/color.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/settings/values.hpp> #include <components/shader/shadermanager.hpp> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include <components/vfs/manager.hpp> #include <components/vfs/recursivedirectoryiterator.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwgui/postprocessorhud.hpp" #include "distortion.hpp" #include "pingpongcull.hpp" #include "renderbin.hpp" #include "renderingmanager.hpp" #include "sky.hpp" #include "transparentpass.hpp" #include "vismask.hpp" namespace { struct ResizedCallback : osg::GraphicsContext::ResizedCallback { ResizedCallback(MWRender::PostProcessor* postProcessor) : mPostProcessor(postProcessor) { } void resizedImplementation(osg::GraphicsContext* gc, int x, int y, int width, int height) override { gc->resizedImplementation(x, y, width, height); mPostProcessor->setRenderTargetSize(width, height); mPostProcessor->resize(); } MWRender::PostProcessor* mPostProcessor; }; class HUDCullCallback : public SceneUtil::NodeCallback<HUDCullCallback, osg::Camera*, osgUtil::CullVisitor*> { public: void operator()(osg::Camera* camera, osgUtil::CullVisitor* cv) { osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet; auto& sm = Stereo::Manager::instance(); auto* fullViewport = camera->getViewport(); if (sm.getEye(cv) == Stereo::Eye::Left) stateset->setAttributeAndModes( new osg::Viewport(0, 0, fullViewport->width() / 2, fullViewport->height())); if (sm.getEye(cv) == Stereo::Eye::Right) stateset->setAttributeAndModes( new osg::Viewport(fullViewport->width() / 2, 0, fullViewport->width() / 2, fullViewport->height())); cv->pushStateSet(stateset); traverse(camera, cv); cv->popStateSet(); } }; enum class Usage { RENDER_BUFFER, TEXTURE, }; static osg::FrameBufferAttachment createFrameBufferAttachmentFromTemplate( Usage usage, int width, int height, osg::Texture* template_, int samples) { if (usage == Usage::RENDER_BUFFER && !Stereo::getMultiview()) { osg::ref_ptr<osg::RenderBuffer> attachment = new osg::RenderBuffer(width, height, template_->getInternalFormat(), samples); return osg::FrameBufferAttachment(attachment); } auto texture = Stereo::createMultiviewCompatibleTexture(width, height, samples); texture->setSourceFormat(template_->getSourceFormat()); texture->setSourceType(template_->getSourceType()); texture->setInternalFormat(template_->getInternalFormat()); texture->setFilter(osg::Texture2D::MIN_FILTER, template_->getFilter(osg::Texture2D::MIN_FILTER)); texture->setFilter(osg::Texture2D::MAG_FILTER, template_->getFilter(osg::Texture2D::MAG_FILTER)); texture->setWrap(osg::Texture::WRAP_S, template_->getWrap(osg::Texture2D::WRAP_S)); texture->setWrap(osg::Texture::WRAP_T, template_->getWrap(osg::Texture2D::WRAP_T)); return Stereo::createMultiviewCompatibleAttachment(texture); } constexpr float DistortionRatio = 0.25; } namespace MWRender { PostProcessor::PostProcessor( RenderingManager& rendering, osgViewer::Viewer* viewer, osg::Group* rootNode, const VFS::Manager* vfs) : osg::Group() , mRootNode(rootNode) , mHUDCamera(new osg::Camera) , mRendering(rendering) , mViewer(viewer) , mVFS(vfs) , mUsePostProcessing(Settings::postProcessing().mEnabled) , mSamples(Settings::video().mAntialiasing) , mPingPongCull(new PingPongCull(this)) , mDistortionCallback(new DistortionCallback) { auto& shaderManager = mRendering.getResourceSystem()->getSceneManager()->getShaderManager(); std::shared_ptr<LuminanceCalculator> luminanceCalculator = std::make_shared<LuminanceCalculator>(shaderManager); for (auto& canvas : mCanvases) canvas = new PingPongCanvas(shaderManager, luminanceCalculator); mHUDCamera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); mHUDCamera->setRenderOrder(osg::Camera::POST_RENDER); mHUDCamera->setClearColor(osg::Vec4(0.45, 0.45, 0.14, 1.0)); mHUDCamera->setClearMask(0); mHUDCamera->setProjectionMatrix(osg::Matrix::ortho2D(0, 1, 0, 1)); mHUDCamera->setAllowEventFocus(false); mHUDCamera->setViewport(0, 0, mWidth, mHeight); mHUDCamera->setNodeMask(Mask_RenderToTexture); mHUDCamera->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); mHUDCamera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); mHUDCamera->addChild(mCanvases[0]); mHUDCamera->addChild(mCanvases[1]); mHUDCamera->setCullCallback(new HUDCullCallback); mViewer->getCamera()->addCullCallback(mPingPongCull); // resolves the multisampled depth buffer and optionally draws an additional depth postpass mTransparentDepthPostPass = new TransparentDepthBinCallback(mRendering.getResourceSystem()->getSceneManager()->getShaderManager(), Settings::postProcessing().mTransparentPostpass); osgUtil::RenderBin::getRenderBinPrototype("DepthSortedBin")->setDrawCallback(mTransparentDepthPostPass); osg::ref_ptr<osgUtil::RenderBin> distortionRenderBin = new osgUtil::RenderBin(osgUtil::RenderBin::SORT_BACK_TO_FRONT); // This is silly to have to do, but if nothing is drawn then the drawcallback is never called and the distortion // texture will never be cleared osg::ref_ptr<osg::Node> dummyNodeToClear = new osg::Node; dummyNodeToClear->setCullingActive(false); dummyNodeToClear->getOrCreateStateSet()->setRenderBinDetails(RenderBin_Distortion, "Distortion"); rootNode->addChild(dummyNodeToClear); distortionRenderBin->setDrawCallback(mDistortionCallback); distortionRenderBin->getStateSet()->setDefine("DISTORTION", "1", osg::StateAttribute::ON); // Give the renderbin access to the opaque depth sampler so it can write its occlusion // Distorted geometry is drawn with ALWAYS depth function and depths writes disbled. const int unitSoftEffect = shaderManager.reserveGlobalTextureUnits(Shader::ShaderManager::Slot::OpaqueDepthTexture); distortionRenderBin->getStateSet()->addUniform(new osg::Uniform("opaqueDepthTex", unitSoftEffect)); osgUtil::RenderBin::addRenderBinPrototype("Distortion", distortionRenderBin); auto defines = shaderManager.getGlobalDefines(); defines["distorionRTRatio"] = std::to_string(DistortionRatio); shaderManager.setGlobalDefines(defines); createObjectsForFrame(0); createObjectsForFrame(1); populateTechniqueFiles(); auto distortion = loadTechnique("internal_distortion"); distortion->setInternal(true); distortion->setLocked(true); mInternalTechniques.push_back(distortion); osg::GraphicsContext* gc = viewer->getCamera()->getGraphicsContext(); osg::GLExtensions* ext = gc->getState()->get<osg::GLExtensions>(); mWidth = gc->getTraits()->width; mHeight = gc->getTraits()->height; if (!ext->glDisablei && ext->glDisableIndexedEXT) ext->glDisablei = ext->glDisableIndexedEXT; #ifdef ANDROID ext->glDisablei = nullptr; #endif if (ext->glDisablei) mNormalsSupported = true; else Log(Debug::Error) << "'glDisablei' unsupported, pass normals will not be available to shaders."; mGLSLVersion = ext->glslLanguageVersion * 100; mUBO = ext->isUniformBufferObjectSupported && mGLSLVersion >= 330; mStateUpdater = new fx::StateUpdater(mUBO); addChild(mHUDCamera); addChild(mRootNode); mViewer->setSceneData(this); mViewer->getCamera()->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); mViewer->getCamera()->getGraphicsContext()->setResizedCallback(new ResizedCallback(this)); mViewer->getCamera()->setUserData(this); setCullCallback(mStateUpdater); if (mUsePostProcessing) enable(); } PostProcessor::~PostProcessor() { if (auto* bin = osgUtil::RenderBin::getRenderBinPrototype("DepthSortedBin")) bin->setDrawCallback(nullptr); } void PostProcessor::resize() { mHUDCamera->resize(mWidth, mHeight); mViewer->getCamera()->resize(mWidth, mHeight); if (Stereo::getStereo()) Stereo::Manager::instance().screenResolutionChanged(); size_t frameId = frame() % 2; createObjectsForFrame(frameId); mRendering.updateProjectionMatrix(); mRendering.setScreenRes(renderWidth(), renderHeight()); dirtyTechniques(true); mDirty = true; mDirtyFrameId = !frameId; } void PostProcessor::populateTechniqueFiles() { for (const auto& name : mVFS->getRecursiveDirectoryIterator(fx::Technique::sSubdir)) { std::filesystem::path path = Files::pathFromUnicodeString(name); std::string fileExt = Misc::StringUtils::lowerCase(Files::pathToUnicodeString(path.extension())); if (!path.parent_path().has_parent_path() && fileExt == fx::Technique::sExt) { const auto absolutePath = mVFS->getAbsoluteFileName(path); mTechniqueFileMap[Files::pathToUnicodeString(absolutePath.stem())] = absolutePath; } } } void PostProcessor::enable() { mReload = true; mUsePostProcessing = true; } void PostProcessor::disable() { mUsePostProcessing = false; mRendering.getSkyManager()->setSunglare(true); } void PostProcessor::traverse(osg::NodeVisitor& nv) { size_t frameId = nv.getTraversalNumber() % 2; if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) cull(frameId, static_cast<osgUtil::CullVisitor*>(&nv)); else if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR) update(frameId); osg::Group::traverse(nv); } void PostProcessor::cull(size_t frameId, osgUtil::CullVisitor* cv) { if (const auto& fbo = getFbo(FBO_Intercept, frameId)) { osgUtil::RenderStage* rs = cv->getRenderStage(); if (rs && rs->getMultisampleResolveFramebufferObject()) rs->setMultisampleResolveFramebufferObject(fbo); } mCanvases[frameId]->setPostProcessing(mUsePostProcessing); mCanvases[frameId]->setTextureNormals(mNormals ? getTexture(Tex_Normal, frameId) : nullptr); mCanvases[frameId]->setMask(mUnderwater, mExteriorFlag); mCanvases[frameId]->setCalculateAvgLum(mHDR); mCanvases[frameId]->setTextureScene(getTexture(Tex_Scene, frameId)); mCanvases[frameId]->setTextureDepth(getTexture(Tex_OpaqueDepth, frameId)); mCanvases[frameId]->setTextureDistortion(getTexture(Tex_Distortion, frameId)); mTransparentDepthPostPass->mFbo[frameId] = mFbos[frameId][FBO_Primary]; mTransparentDepthPostPass->mMsaaFbo[frameId] = mFbos[frameId][FBO_Multisample]; mTransparentDepthPostPass->mOpaqueFbo[frameId] = mFbos[frameId][FBO_OpaqueDepth]; mDistortionCallback->setFBO(mFbos[frameId][FBO_Distortion], frameId); mDistortionCallback->setOriginalFBO(mFbos[frameId][FBO_Primary], frameId); size_t frame = cv->getTraversalNumber(); mStateUpdater->setResolution(osg::Vec2f(cv->getViewport()->width(), cv->getViewport()->height())); // per-frame data if (frame != mLastFrameNumber) { mLastFrameNumber = frame; auto stamp = cv->getFrameStamp(); mStateUpdater->setSimulationTime(static_cast<float>(stamp->getSimulationTime())); mStateUpdater->setDeltaSimulationTime(static_cast<float>(stamp->getSimulationTime() - mLastSimulationTime)); // Use a signed int because 'uint' type is not supported in GLSL 120 without extensions mStateUpdater->setFrameNumber(static_cast<int>(stamp->getFrameNumber())); mLastSimulationTime = stamp->getSimulationTime(); for (const auto& dispatchNode : mCanvases[frameId]->getPasses()) { for (auto& uniform : dispatchNode.mHandle->getUniformMap()) { if (uniform->getType().has_value() && !uniform->mSamplerType) if (auto* u = dispatchNode.mRootStateSet->getUniform(uniform->mName)) uniform->setUniform(u); } } } } void PostProcessor::updateLiveReload() { if (!mEnableLiveReload && !mTriggerShaderReload) return; mTriggerShaderReload = false; // Done only once for (auto& technique : mTechniques) { if (!technique || technique->getStatus() == fx::Technique::Status::File_Not_exists) continue; const auto lastWriteTime = std::filesystem::last_write_time(mTechniqueFileMap[technique->getName()]); const bool isDirty = technique->setLastModificationTime(lastWriteTime); if (!isDirty) continue; // TODO: Temporary workaround to avoid conflicts with external programs saving the file, especially // problematic on Windows. // If we move to a file watcher using native APIs this should be removed. std::this_thread::sleep_for(std::chrono::milliseconds(5)); if (technique->compile()) Log(Debug::Info) << "Reloaded technique : " << mTechniqueFileMap[technique->getName()]; mReload = technique->isValid(); } } void PostProcessor::reloadIfRequired() { if (!mReload) return; mReload = false; loadChain(); resize(); } void PostProcessor::update(size_t frameId) { while (!mQueuedTemplates.empty()) { mTemplates.push_back(std::move(mQueuedTemplates.back())); mQueuedTemplates.pop_back(); } updateLiveReload(); reloadIfRequired(); mCanvases[frameId]->setNodeMask(~0u); mCanvases[!frameId]->setNodeMask(0); if (mDirty && mDirtyFrameId == frameId) { createObjectsForFrame(frameId); mDirty = false; mCanvases[frameId]->setPasses(fx::DispatchArray(mTemplateData)); } if ((mNormalsSupported && mNormals != mPrevNormals) || (mPassLights != mPrevPassLights)) { mPrevNormals = mNormals; mPrevPassLights = mPassLights; mViewer->stopThreading(); if (mNormalsSupported) { auto& shaderManager = MWBase::Environment::get().getResourceSystem()->getSceneManager()->getShaderManager(); auto defines = shaderManager.getGlobalDefines(); defines["disableNormals"] = mNormals ? "0" : "1"; shaderManager.setGlobalDefines(defines); } mRendering.getLightRoot()->setCollectPPLights(mPassLights); mStateUpdater->bindPointLights(mPassLights ? mRendering.getLightRoot()->getPPLightsBuffer() : nullptr); mStateUpdater->reset(); mViewer->startThreading(); createObjectsForFrame(frameId); mDirty = true; mDirtyFrameId = !frameId; } } void PostProcessor::createObjectsForFrame(size_t frameId) { auto& textures = mTextures[frameId]; int width = renderWidth(); int height = renderHeight(); for (osg::ref_ptr<osg::Texture>& texture : textures) { if (!texture) { if (Stereo::getMultiview()) texture = new osg::Texture2DArray; else texture = new osg::Texture2D; } Stereo::setMultiviewCompatibleTextureSize(texture, width, height); texture->setSourceFormat(GL_RGBA); texture->setSourceType(GL_UNSIGNED_BYTE); texture->setInternalFormat(GL_RGBA); texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture::LINEAR); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); texture->setResizeNonPowerOfTwoHint(false); Stereo::setMultiviewCompatibleTextureSize(texture, width, height); texture->dirtyTextureObject(); } textures[Tex_Normal]->setSourceFormat(GL_RGB); textures[Tex_Normal]->setInternalFormat(GL_RGB); textures[Tex_Distortion]->setSourceFormat(GL_RGB); textures[Tex_Distortion]->setInternalFormat(GL_RGB); Stereo::setMultiviewCompatibleTextureSize( textures[Tex_Distortion], width * DistortionRatio, height * DistortionRatio); textures[Tex_Distortion]->dirtyTextureObject(); auto setupDepth = [](osg::Texture* tex) { tex->setSourceFormat(GL_DEPTH_STENCIL_EXT); tex->setSourceType(SceneUtil::AutoDepth::depthSourceType()); tex->setInternalFormat(SceneUtil::AutoDepth::depthInternalFormat()); }; setupDepth(textures[Tex_Depth]); setupDepth(textures[Tex_OpaqueDepth]); textures[Tex_OpaqueDepth]->setName("opaqueTexMap"); auto& fbos = mFbos[frameId]; fbos[FBO_Primary] = new osg::FrameBufferObject; fbos[FBO_Primary]->setAttachment( osg::Camera::COLOR_BUFFER0, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Scene])); if (mNormals && mNormalsSupported) fbos[FBO_Primary]->setAttachment( osg::Camera::COLOR_BUFFER1, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Normal])); fbos[FBO_Primary]->setAttachment( osg::Camera::PACKED_DEPTH_STENCIL_BUFFER, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Depth])); fbos[FBO_FirstPerson] = new osg::FrameBufferObject; auto fpDepthRb = createFrameBufferAttachmentFromTemplate( Usage::RENDER_BUFFER, width, height, textures[Tex_Depth], mSamples); fbos[FBO_FirstPerson]->setAttachment(osg::FrameBufferObject::BufferComponent::PACKED_DEPTH_STENCIL_BUFFER, osg::FrameBufferAttachment(fpDepthRb)); if (mSamples > 1) { fbos[FBO_Multisample] = new osg::FrameBufferObject; auto colorRB = createFrameBufferAttachmentFromTemplate( Usage::RENDER_BUFFER, width, height, textures[Tex_Scene], mSamples); if (mNormals && mNormalsSupported) { auto normalRB = createFrameBufferAttachmentFromTemplate( Usage::RENDER_BUFFER, width, height, textures[Tex_Normal], mSamples); fbos[FBO_Multisample]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER1, normalRB); fbos[FBO_FirstPerson]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER1, normalRB); } auto depthRB = createFrameBufferAttachmentFromTemplate( Usage::RENDER_BUFFER, width, height, textures[Tex_Depth], mSamples); fbos[FBO_Multisample]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, colorRB); fbos[FBO_Multisample]->setAttachment( osg::FrameBufferObject::BufferComponent::PACKED_DEPTH_STENCIL_BUFFER, depthRB); fbos[FBO_FirstPerson]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, colorRB); fbos[FBO_Intercept] = new osg::FrameBufferObject; fbos[FBO_Intercept]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Scene])); fbos[FBO_Intercept]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER1, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Normal])); } else { fbos[FBO_FirstPerson]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Scene])); if (mNormals && mNormalsSupported) fbos[FBO_FirstPerson]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER1, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Normal])); } fbos[FBO_OpaqueDepth] = new osg::FrameBufferObject; fbos[FBO_OpaqueDepth]->setAttachment(osg::FrameBufferObject::BufferComponent::PACKED_DEPTH_STENCIL_BUFFER, Stereo::createMultiviewCompatibleAttachment(textures[Tex_OpaqueDepth])); fbos[FBO_Distortion] = new osg::FrameBufferObject; fbos[FBO_Distortion]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, Stereo::createMultiviewCompatibleAttachment(textures[Tex_Distortion])); #ifdef __APPLE__ if (textures[Tex_OpaqueDepth]) fbos[FBO_OpaqueDepth]->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER, osg::FrameBufferAttachment(new osg::RenderBuffer(textures[Tex_OpaqueDepth]->getTextureWidth(), textures[Tex_OpaqueDepth]->getTextureHeight(), textures[Tex_Scene]->getInternalFormat()))); #endif mCanvases[frameId]->dirty(); } void PostProcessor::dirtyTechniques(bool dirtyAttachments) { size_t frameId = frame() % 2; mDirty = true; mDirtyFrameId = !frameId; mTemplateData = {}; bool sunglare = true; mHDR = false; mNormals = false; mPassLights = false; std::vector<fx::Types::RenderTarget> attachmentsToDirty; for (const auto& technique : mTechniques) { if (!technique || !technique->isValid()) continue; if (technique->getGLSLVersion() > mGLSLVersion) { Log(Debug::Warning) << "Technique " << technique->getName() << " requires GLSL version " << technique->getGLSLVersion() << " which is unsupported by your hardware."; continue; } fx::DispatchNode node; node.mFlags = technique->getFlags(); if (technique->getHDR()) mHDR = true; if (technique->getNormals()) mNormals = true; if (technique->getLights()) mPassLights = true; if (node.mFlags & fx::Technique::Flag_Disable_SunGlare) sunglare = false; // required default samplers available to every shader pass node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerLastShader", Unit_LastShader)); node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerLastPass", Unit_LastPass)); node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerDepth", Unit_Depth)); node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerDistortion", Unit_Distortion)); if (mNormals) node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerNormals", Unit_Normals)); if (technique->getHDR()) node.mRootStateSet->addUniform(new osg::Uniform("omw_EyeAdaptation", Unit_EyeAdaptation)); node.mRootStateSet->addUniform(new osg::Uniform("omw_SamplerDistortion", Unit_Distortion)); int texUnit = Unit_NextFree; // user-defined samplers for (const osg::Texture* texture : technique->getTextures()) { if (const auto* tex1D = dynamic_cast<const osg::Texture1D*>(texture)) node.mRootStateSet->setTextureAttribute(texUnit, new osg::Texture1D(*tex1D)); else if (const auto* tex2D = dynamic_cast<const osg::Texture2D*>(texture)) node.mRootStateSet->setTextureAttribute(texUnit, new osg::Texture2D(*tex2D)); else if (const auto* tex3D = dynamic_cast<const osg::Texture3D*>(texture)) node.mRootStateSet->setTextureAttribute(texUnit, new osg::Texture3D(*tex3D)); node.mRootStateSet->addUniform(new osg::Uniform(texture->getName().c_str(), texUnit++)); } // user-defined uniforms for (auto& uniform : technique->getUniformMap()) { if (uniform->mSamplerType) continue; if (auto type = uniform->getType()) uniform->setUniform(node.mRootStateSet->getOrCreateUniform( uniform->mName.c_str(), *type, uniform->getNumElements())); } for (const auto& pass : technique->getPasses()) { int subTexUnit = texUnit; fx::DispatchNode::SubPass subPass; pass->prepareStateSet(subPass.mStateSet, technique->getName()); node.mHandle = technique; if (!pass->getTarget().empty()) { auto& renderTarget = technique->getRenderTargetsMap()[pass->getTarget()]; subPass.mSize = renderTarget.mSize; subPass.mRenderTexture = renderTarget.mTarget; subPass.mMipMap = renderTarget.mMipMap; const auto [w, h] = renderTarget.mSize.get(renderWidth(), renderHeight()); subPass.mStateSet->setAttributeAndModes(new osg::Viewport(0, 0, w, h)); subPass.mRenderTexture->setTextureSize(w, h); subPass.mRenderTexture->dirtyTextureObject(); subPass.mRenderTarget = new osg::FrameBufferObject; subPass.mRenderTarget->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(subPass.mRenderTexture)); if (std::find_if(attachmentsToDirty.cbegin(), attachmentsToDirty.cend(), [renderTarget](const auto& rt) { return renderTarget.mTarget == rt.mTarget; }) == attachmentsToDirty.cend()) { attachmentsToDirty.push_back(fx::Types::RenderTarget(renderTarget)); } } for (const auto& name : pass->getRenderTargets()) { if (name.empty()) { continue; } auto& renderTarget = technique->getRenderTargetsMap()[name]; subPass.mStateSet->setTextureAttribute(subTexUnit, renderTarget.mTarget); subPass.mStateSet->addUniform(new osg::Uniform(name.c_str(), subTexUnit)); if (std::find_if(attachmentsToDirty.cbegin(), attachmentsToDirty.cend(), [renderTarget](const auto& rt) { return renderTarget.mTarget == rt.mTarget; }) == attachmentsToDirty.cend()) { attachmentsToDirty.push_back(fx::Types::RenderTarget(renderTarget)); } subTexUnit++; } node.mPasses.emplace_back(std::move(subPass)); } node.compile(); mTemplateData.emplace_back(std::move(node)); } mCanvases[frameId]->setPasses(fx::DispatchArray(mTemplateData)); if (auto hud = MWBase::Environment::get().getWindowManager()->getPostProcessorHud()) hud->updateTechniques(); mRendering.getSkyManager()->setSunglare(sunglare); if (dirtyAttachments) mCanvases[frameId]->setDirtyAttachments(attachmentsToDirty); } PostProcessor::Status PostProcessor::enableTechnique( std::shared_ptr<fx::Technique> technique, std::optional<int> location) { if (!technique || technique->getLocked() || (location.has_value() && location.value() < 0)) return Status_Error; disableTechnique(technique, false); int pos = std::min<int>(location.value_or(mTechniques.size()) + mInternalTechniques.size(), mTechniques.size()); mTechniques.insert(mTechniques.begin() + pos, technique); dirtyTechniques(Settings::ShaderManager::get().getMode() == Settings::ShaderManager::Mode::Debug); return Status_Toggled; } PostProcessor::Status PostProcessor::disableTechnique(std::shared_ptr<fx::Technique> technique, bool dirty) { if (!technique || technique->getLocked()) return Status_Error; auto it = std::find(mTechniques.begin(), mTechniques.end(), technique); if (it == std::end(mTechniques)) return Status_Unchanged; mTechniques.erase(it); if (dirty) dirtyTechniques(); return Status_Toggled; } bool PostProcessor::isTechniqueEnabled(const std::shared_ptr<fx::Technique>& technique) const { if (!technique) return false; if (auto it = std::find(mTechniques.begin(), mTechniques.end(), technique); it == mTechniques.end()) return false; return technique->isValid(); } std::shared_ptr<fx::Technique> PostProcessor::loadTechnique(const std::string& name, bool loadNextFrame) { for (const auto& technique : mTemplates) if (Misc::StringUtils::ciEqual(technique->getName(), name)) return technique; for (const auto& technique : mQueuedTemplates) if (Misc::StringUtils::ciEqual(technique->getName(), name)) return technique; auto technique = std::make_shared<fx::Technique>(*mVFS, *mRendering.getResourceSystem()->getImageManager(), name, renderWidth(), renderHeight(), mUBO, mNormalsSupported); technique->compile(); if (technique->getStatus() != fx::Technique::Status::File_Not_exists) technique->setLastModificationTime( std::filesystem::last_write_time(mTechniqueFileMap[technique->getName()])); if (loadNextFrame) { mQueuedTemplates.push_back(technique); return technique; } mTemplates.push_back(std::move(technique)); return mTemplates.back(); } void PostProcessor::loadChain() { mTechniques.clear(); for (const auto& technique : mInternalTechniques) { mTechniques.push_back(technique); } for (const std::string& techniqueName : Settings::postProcessing().mChain.get()) { if (techniqueName.empty()) continue; mTechniques.push_back(loadTechnique(techniqueName)); } dirtyTechniques(); } void PostProcessor::saveChain() { std::vector<std::string> chain; for (const auto& technique : mTechniques) { if (!technique || technique->getDynamic() || technique->getInternal()) continue; chain.push_back(technique->getName()); } Settings::postProcessing().mChain.set(chain); } void PostProcessor::toggleMode() { for (auto& technique : mTemplates) technique->compile(); dirtyTechniques(true); } void PostProcessor::disableDynamicShaders() { for (auto& technique : mTechniques) if (technique && technique->getDynamic()) disableTechnique(technique); } int PostProcessor::renderWidth() const { if (Stereo::getStereo()) return Stereo::Manager::instance().eyeResolution().x(); return mWidth; } int PostProcessor::renderHeight() const { if (Stereo::getStereo()) return Stereo::Manager::instance().eyeResolution().y(); return mHeight; } void PostProcessor::triggerShaderReload() { mTriggerShaderReload = true; } }
33,488
C++
.cpp
673
38.787519
120
0.638712
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,378
weaponanimation.cpp
OpenMW_openmw/apps/openmw/mwrender/weaponanimation.cpp
#include "weaponanimation.hpp" #include <osg/MatrixTransform> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwmechanics/combat.hpp" #include "../mwmechanics/weapontype.hpp" #include "animation.hpp" #include "rotatecontroller.hpp" namespace MWRender { float WeaponAnimationTime::getValue(osg::NodeVisitor*) { if (mWeaponGroup.empty()) return 0; float current = mAnimation->getCurrentTime(mWeaponGroup); if (current == -1) return 0; return current - mStartTime; } void WeaponAnimationTime::setGroup(const std::string& group, bool relativeTime) { mWeaponGroup = group; mRelativeTime = relativeTime; if (mRelativeTime) mStartTime = mAnimation->getStartTime(mWeaponGroup); else mStartTime = 0; } void WeaponAnimationTime::updateStartTime() { setGroup(mWeaponGroup, mRelativeTime); } WeaponAnimation::WeaponAnimation() : mPitchFactor(0) { } WeaponAnimation::~WeaponAnimation() {} void WeaponAnimation::attachArrow(const MWWorld::Ptr& actor) { const MWWorld::InventoryStore& inv = actor.getClass().getInventoryStore(actor); MWWorld::ConstContainerStoreIterator weaponSlot = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weaponSlot == inv.end()) return; if (weaponSlot->getType() != ESM::Weapon::sRecordId) return; int type = weaponSlot->get<ESM::Weapon>()->mBase->mData.mType; ESM::WeaponType::Class weapclass = MWMechanics::getWeaponType(type)->mWeaponClass; if (weapclass == ESM::WeaponType::Thrown) { const auto& soundid = weaponSlot->getClass().getUpSoundId(*weaponSlot); if (!soundid.empty()) { MWBase::SoundManager* sndMgr = MWBase::Environment::get().getSoundManager(); sndMgr->playSound3D(actor, soundid, 1.0f, 1.0f); } showWeapon(true); } else if (weapclass == ESM::WeaponType::Ranged) { osg::Group* parent = getArrowBone(); if (!parent) return; MWWorld::ConstContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo == inv.end()) return; VFS::Path::Normalized model(ammo->getClass().getCorrectedModel(*ammo)); osg::ref_ptr<osg::Node> arrow = getResourceSystem()->getSceneManager()->getInstance(model, parent); mAmmunition = std::make_unique<PartHolder>(arrow); } } void WeaponAnimation::detachArrow(MWWorld::Ptr actor) { mAmmunition.reset(); } void WeaponAnimation::releaseArrow(MWWorld::Ptr actor, float attackStrength) { MWWorld::InventoryStore& inv = actor.getClass().getInventoryStore(actor); MWWorld::ContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end()) return; if (weapon->getType() != ESM::Weapon::sRecordId) return; // The orientation of the launched projectile. Always the same as the actor orientation, even if the ArrowBone's // orientation dictates otherwise. osg::Quat orient = osg::Quat(actor.getRefData().getPosition().rot[0], osg::Vec3f(-1, 0, 0)) * osg::Quat(actor.getRefData().getPosition().rot[2], osg::Vec3f(0, 0, -1)); const MWWorld::Store<ESM::GameSetting>& gmst = MWBase::Environment::get().getESMStore()->get<ESM::GameSetting>(); MWMechanics::applyFatigueLoss(actor, *weapon, attackStrength); if (MWMechanics::getWeaponType(weapon->get<ESM::Weapon>()->mBase->mData.mType)->mWeaponClass == ESM::WeaponType::Thrown) { // Thrown weapons get detached now osg::Node* weaponNode = getWeaponNode(); if (!weaponNode) return; osg::NodePathList nodepaths = weaponNode->getParentalNodePaths(); if (nodepaths.empty()) return; osg::Vec3f launchPos = osg::computeLocalToWorld(nodepaths[0]).getTrans(); float fThrownWeaponMinSpeed = gmst.find("fThrownWeaponMinSpeed")->mValue.getFloat(); float fThrownWeaponMaxSpeed = gmst.find("fThrownWeaponMaxSpeed")->mValue.getFloat(); float speed = fThrownWeaponMinSpeed + (fThrownWeaponMaxSpeed - fThrownWeaponMinSpeed) * attackStrength; MWWorld::Ptr weaponPtr = *weapon; MWBase::Environment::get().getWorld()->launchProjectile( actor, weaponPtr, launchPos, orient, weaponPtr, speed, attackStrength); showWeapon(false); inv.remove(*weapon, 1); } else { // With bows and crossbows only the used arrow/bolt gets detached MWWorld::ContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo == inv.end()) return; if (!mAmmunition) return; osg::ref_ptr<osg::Node> ammoNode = mAmmunition->getNode(); osg::NodePathList nodepaths = ammoNode->getParentalNodePaths(); if (nodepaths.empty()) return; osg::Vec3f launchPos = osg::computeLocalToWorld(nodepaths[0]).getTrans(); float fProjectileMinSpeed = gmst.find("fProjectileMinSpeed")->mValue.getFloat(); float fProjectileMaxSpeed = gmst.find("fProjectileMaxSpeed")->mValue.getFloat(); float speed = fProjectileMinSpeed + (fProjectileMaxSpeed - fProjectileMinSpeed) * attackStrength; MWWorld::Ptr weaponPtr = *weapon; MWWorld::Ptr ammoPtr = *ammo; MWBase::Environment::get().getWorld()->launchProjectile( actor, ammoPtr, launchPos, orient, weaponPtr, speed, attackStrength); inv.remove(ammoPtr, 1); mAmmunition.reset(); } } void WeaponAnimation::addControllers(const Animation::NodeMap& nodes, std::vector<std::pair<osg::ref_ptr<osg::Node>, osg::ref_ptr<osg::Callback>>>& map, osg::Node* objectRoot) { for (int i = 0; i < 2; ++i) { mSpineControllers[i] = nullptr; Animation::NodeMap::const_iterator found = nodes.find(i == 0 ? "bip01 spine1" : "bip01 spine2"); if (found != nodes.end()) { osg::Node* node = found->second; mSpineControllers[i] = new RotateController(objectRoot); node->addUpdateCallback(mSpineControllers[i]); map.emplace_back(node, mSpineControllers[i]); } } } void WeaponAnimation::deleteControllers() { for (int i = 0; i < 2; ++i) mSpineControllers[i] = nullptr; } void WeaponAnimation::configureControllers(float characterPitchRadians) { if (mPitchFactor == 0.f || characterPitchRadians == 0.f) { setControllerEnabled(false); return; } float pitch = characterPitchRadians * mPitchFactor; osg::Quat rotate(pitch / 2, osg::Vec3f(-1, 0, 0)); setControllerRotate(rotate); setControllerEnabled(true); } void WeaponAnimation::setControllerRotate(const osg::Quat& rotate) { for (int i = 0; i < 2; ++i) if (mSpineControllers[i]) mSpineControllers[i]->setRotate(rotate); } void WeaponAnimation::setControllerEnabled(bool enabled) { for (int i = 0; i < 2; ++i) if (mSpineControllers[i]) mSpineControllers[i]->setEnabled(enabled); } }
8,083
C++
.cpp
185
33.924324
120
0.621945
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,379
pingpongcull.cpp
OpenMW_openmw/apps/openmw/mwrender/pingpongcull.cpp
#include "pingpongcull.hpp" #include <osg/Camera> #include <osg/FrameBufferObject> #include <osg/Texture2DArray> #include <osg/Texture> #include <osgUtil/CullVisitor> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include "postprocessor.hpp" namespace MWRender { PingPongCull::PingPongCull(PostProcessor* pp) : mViewportStateset(nullptr) , mPostProcessor(pp) { if (Stereo::getStereo()) { mViewportStateset = new osg::StateSet(); mViewport = new osg::Viewport; mViewportStateset->setAttribute(mViewport); } } PingPongCull::~PingPongCull() { // Instantiate osg::ref_ptr<> destructor } void PingPongCull::operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osgUtil::RenderStage* renderStage = cv->getCurrentRenderStage(); size_t frame = cv->getTraversalNumber(); size_t frameId = frame % 2; if (Stereo::getStereo()) { auto& sm = Stereo::Manager::instance(); auto view = sm.getEye(cv); int index = view == Stereo::Eye::Right ? 1 : 0; auto projectionMatrix = sm.computeEyeProjection(index, true); mPostProcessor->getStateUpdater()->setProjectionMatrix(projectionMatrix); } mPostProcessor->getStateUpdater()->setViewMatrix(cv->getCurrentCamera()->getViewMatrix()); mPostProcessor->getStateUpdater()->setPrevViewMatrix(mLastViewMatrix[0]); mLastViewMatrix[0] = cv->getCurrentCamera()->getViewMatrix(); mPostProcessor->getStateUpdater()->setEyePos(cv->getEyePoint()); mPostProcessor->getStateUpdater()->setEyeVec(cv->getLookVectorLocal()); if (!mPostProcessor->getFbo(PostProcessor::FBO_Multisample, frameId)) { renderStage->setFrameBufferObject(mPostProcessor->getFbo(PostProcessor::FBO_Primary, frameId)); } else { renderStage->setMultisampleResolveFramebufferObject( mPostProcessor->getFbo(PostProcessor::FBO_Primary, frameId)); renderStage->setFrameBufferObject(mPostProcessor->getFbo(PostProcessor::FBO_Multisample, frameId)); // The MultiView patch has a bug where it does not update resolve layers if the resolve framebuffer is // changed. So we do blit manually in this case if (Stereo::getMultiview() && !renderStage->getDrawCallback()) Stereo::setMultiviewMSAAResolveCallback(renderStage); } if (mViewportStateset) { mViewport->setViewport(0, 0, mPostProcessor->renderWidth(), mPostProcessor->renderHeight()); renderStage->setViewport(mViewport); cv->pushStateSet(mViewportStateset.get()); traverse(node, cv); cv->popStateSet(); } else traverse(node, cv); } }
2,947
C++
.cpp
70
33.428571
114
0.655028
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,380
terrainstorage.cpp
OpenMW_openmw/apps/openmw/mwrender/terrainstorage.cpp
#include "terrainstorage.hpp" #include <components/esm3/loadland.hpp> #include <components/esm4/loadwrld.hpp> #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" #include "landmanager.hpp" namespace MWRender { TerrainStorage::TerrainStorage(Resource::ResourceSystem* resourceSystem, std::string_view normalMapPattern, std::string_view normalHeightMapPattern, bool autoUseNormalMaps, std::string_view specularMapPattern, bool autoUseSpecularMaps) : ESMTerrain::Storage(resourceSystem->getVFS(), normalMapPattern, normalHeightMapPattern, autoUseNormalMaps, specularMapPattern, autoUseSpecularMaps) , mLandManager(new LandManager( ESM::Land::DATA_VCLR | ESM::Land::DATA_VHGT | ESM::Land::DATA_VNML | ESM::Land::DATA_VTEX)) , mResourceSystem(resourceSystem) { mResourceSystem->addResourceManager(mLandManager.get()); } TerrainStorage::~TerrainStorage() { mResourceSystem->removeResourceManager(mLandManager.get()); } bool TerrainStorage::hasData(ESM::ExteriorCellLocation cellLocation) { const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); if (ESM::isEsm4Ext(cellLocation.mWorldspace)) { const ESM4::World* worldspace = esmStore.get<ESM4::World>().find(cellLocation.mWorldspace); if (!worldspace->mParent.isZeroOrUnset() && worldspace->mParentUseFlags & ESM4::World::UseFlag_Land) cellLocation.mWorldspace = worldspace->mParent; return esmStore.get<ESM4::Land>().search(cellLocation) != nullptr; } else { return esmStore.get<ESM::Land>().search(cellLocation.mX, cellLocation.mY) != nullptr; } } static void BoundUnion(float& minX, float& maxX, float& minY, float& maxY, float x, float y) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } void TerrainStorage::getBounds(float& minX, float& maxX, float& minY, float& maxY, ESM::RefId worldspace) { minX = 0; minY = 0; maxX = 0; maxY = 0; const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); if (ESM::isEsm4Ext(worldspace)) { const ESM4::World* worldRec = esmStore.get<ESM4::World>().find(worldspace); if (!worldRec->mParent.isZeroOrUnset() && worldRec->mParentUseFlags & ESM4::World::UseFlag_Land) worldspace = worldRec->mParent; const auto& lands = esmStore.get<ESM4::Land>().getLands(); for (const auto& [landPos, _] : lands) { if (landPos.mWorldspace == worldspace) { BoundUnion(minX, maxX, minY, maxY, static_cast<float>(landPos.mX), static_cast<float>(landPos.mY)); } } } else { MWWorld::Store<ESM::Land>::iterator it = esmStore.get<ESM::Land>().begin(); for (; it != esmStore.get<ESM::Land>().end(); ++it) { BoundUnion(minX, maxX, minY, maxY, static_cast<float>(it->mX), static_cast<float>(it->mY)); } } // since grid coords are at cell origin, we need to add 1 cell maxX += 1; maxY += 1; } LandManager* TerrainStorage::getLandManager() const { return mLandManager.get(); } osg::ref_ptr<const ESMTerrain::LandObject> TerrainStorage::getLand(ESM::ExteriorCellLocation cellLocation) { return mLandManager->getLand(cellLocation); } const std::string* TerrainStorage::getLandTexture(std::uint16_t index, int plugin) { const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); return esmStore.get<ESM::LandTexture>().search(index, plugin); } }
3,993
C++
.cpp
96
32.677083
119
0.620521
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,381
actorutil.cpp
OpenMW_openmw/apps/openmw/mwrender/actorutil.cpp
#include "actorutil.hpp" #include <components/settings/values.hpp> #include <components/vfs/pathutil.hpp> namespace MWRender { const std::string& getActorSkeleton(bool firstPerson, bool isFemale, bool isBeast, bool isWerewolf) { if (!firstPerson) { if (isWerewolf) return Settings::models().mWolfskin.get().value(); else if (isBeast) return Settings::models().mBaseanimkna.get().value(); else if (isFemale) return Settings::models().mBaseanimfemale.get().value(); else return Settings::models().mBaseanim.get().value(); } else { if (isWerewolf) return Settings::models().mWolfskin1st.get().value(); else if (isBeast) return Settings::models().mBaseanimkna1st.get().value(); else if (isFemale) return Settings::models().mBaseanimfemale1st.get().value(); else return Settings::models().mXbaseanim1st.get().value(); } } bool isDefaultActorSkeleton(std::string_view model) { return VFS::Path::pathEqual(Settings::models().mBaseanimkna.get(), model) || VFS::Path::pathEqual(Settings::models().mBaseanimfemale.get(), model) || VFS::Path::pathEqual(Settings::models().mBaseanim.get(), model); } std::string addSuffixBeforeExtension(const std::string& filename, const std::string& suffix) { size_t dotPos = filename.rfind('.'); // No extension found; return the original filename with suffix appended if (dotPos == std::string::npos) return filename + suffix; // Insert the suffix before the dot (extension) and return the new filename return filename.substr(0, dotPos) + suffix + filename.substr(dotPos); } }
1,900
C++
.cpp
46
31.652174
103
0.608225
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,382
pathgrid.cpp
OpenMW_openmw/apps/openmw/mwrender/pathgrid.cpp
#include "pathgrid.hpp" #include <cassert> #include <osg/Geometry> #include <osg/Group> #include <osg/PositionAttitudeTransform> #include <components/debug/debuglog.hpp> #include <components/esm3/loadpgrd.hpp> #include <components/misc/coordinateconverter.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/pathgridutil.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" // these includes can be removed once the static-hack is gone #include "../mwmechanics/pathfinding.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/esmstore.hpp" #include "vismask.hpp" namespace MWRender { Pathgrid::Pathgrid(osg::ref_ptr<osg::Group> root) : mPathgridEnabled(false) , mRootNode(std::move(root)) , mPathGridRoot(nullptr) , mInteriorPathgridNode(nullptr) { } Pathgrid::~Pathgrid() { if (mPathgridEnabled) { try { togglePathgrid(); } catch (std::exception& e) { Log(Debug::Error) << "Failed to destroy pathgrid: " << e.what(); } } } bool Pathgrid::toggleRenderMode(int mode) { switch (mode) { case Render_Pathgrid: togglePathgrid(); return mPathgridEnabled; default: return false; } return false; } void Pathgrid::addCell(const MWWorld::CellStore* store) { mActiveCells.push_back(store); if (mPathgridEnabled) enableCellPathgrid(store); } void Pathgrid::removeCell(const MWWorld::CellStore* store) { mActiveCells.erase(std::remove(mActiveCells.begin(), mActiveCells.end(), store), mActiveCells.end()); if (mPathgridEnabled) disableCellPathgrid(store); } void Pathgrid::togglePathgrid() { mPathgridEnabled = !mPathgridEnabled; if (mPathgridEnabled) { // add path grid meshes to already loaded cells mPathGridRoot = new osg::Group; mPathGridRoot->setNodeMask(Mask_Debug); mRootNode->addChild(mPathGridRoot); for (const MWWorld::CellStore* cell : mActiveCells) { enableCellPathgrid(cell); } } else { // remove path grid meshes from already loaded cells for (const MWWorld::CellStore* cell : mActiveCells) { disableCellPathgrid(cell); } if (mPathGridRoot) { mRootNode->removeChild(mPathGridRoot); mPathGridRoot = nullptr; } } } void Pathgrid::enableCellPathgrid(const MWWorld::CellStore* store) { MWBase::World* world = MWBase::Environment::get().getWorld(); const ESM::Pathgrid* pathgrid = world->getStore().get<ESM::Pathgrid>().search(*store->getCell()); if (!pathgrid) return; osg::Vec3f cellPathGridPos(0, 0, 0); Misc::makeCoordinateConverter(*store->getCell()).toWorld(cellPathGridPos); osg::ref_ptr<osg::PositionAttitudeTransform> cellPathGrid = new osg::PositionAttitudeTransform; cellPathGrid->setPosition(cellPathGridPos); osg::ref_ptr<osg::Geometry> geometry = SceneUtil::createPathgridGeometry(*pathgrid); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(geometry, "debug"); cellPathGrid->addChild(geometry); mPathGridRoot->addChild(cellPathGrid); if (store->getCell()->isExterior()) { mExteriorPathgridNodes[std::make_pair(store->getCell()->getGridX(), store->getCell()->getGridY())] = cellPathGrid; } else { assert(mInteriorPathgridNode == nullptr); mInteriorPathgridNode = cellPathGrid; } } void Pathgrid::disableCellPathgrid(const MWWorld::CellStore* store) { if (store->getCell()->isExterior()) { ExteriorPathgridNodes::iterator it = mExteriorPathgridNodes.find( std::make_pair(store->getCell()->getGridX(), store->getCell()->getGridY())); if (it != mExteriorPathgridNodes.end()) { mPathGridRoot->removeChild(it->second); mExteriorPathgridNodes.erase(it); } } else { if (mInteriorPathgridNode) { mPathGridRoot->removeChild(mInteriorPathgridNode); mInteriorPathgridNode = nullptr; } } } }
4,779
C++
.cpp
139
25.158273
110
0.603295
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,383
animblendcontroller.cpp
OpenMW_openmw/apps/openmw/mwrender/animblendcontroller.cpp
#include "animblendcontroller.hpp" #include "rotatecontroller.hpp" #include <components/debug/debuglog.hpp> #include <osgAnimation/Bone> #include <cassert> #include <string> #include <vector> namespace MWRender { namespace { // Animation Easing/Blending functions namespace Easings { float linear(float x) { return x; } float sineOut(float x) { return std::sin((x * osg::PIf) / 2.f); } float sineIn(float x) { return 1.f - std::cos((x * osg::PIf) / 2.f); } float sineInOut(float x) { return -(std::cos(osg::PIf * x) - 1.f) / 2.f; } float cubicOut(float t) { float t1 = 1.f - t; return 1.f - (t1 * t1 * t1); // (1-t)^3 } float cubicIn(float x) { return x * x * x; // x^3 } float cubicInOut(float x) { if (x < 0.5f) { return 4.f * x * x * x; // 4x^3 } else { float x2 = -2.f * x + 2.f; return 1.f - (x2 * x2 * x2) / 2.f; // (1 - (-2x + 2)^3)/2 } } float quartOut(float t) { float t1 = 1.f - t; return 1.f - (t1 * t1 * t1 * t1); // (1-t)^4 } float quartIn(float t) { return t * t * t * t; // t^4 } float quartInOut(float x) { if (x < 0.5f) { return 8.f * x * x * x * x; // 8x^4 } else { float x2 = -2.f * x + 2.f; return 1.f - (x2 * x2 * x2 * x2) / 2.f; // 1 - ((-2x + 2)^4)/2 } } float springOutGeneric(float x, float lambda) { // Higher lambda = lower swing amplitude. 1 = 150% swing amplitude. // w is the frequency of oscillation in the easing func, controls the amount of overswing const float w = 1.5f * osg::PIf; // 4.71238 return 1.f - expf(-lambda * x) * std::cos(w * x); } float springOutWeak(float x) { return springOutGeneric(x, 4.f); } float springOutMed(float x) { return springOutGeneric(x, 3.f); } float springOutStrong(float x) { return springOutGeneric(x, 2.f); } float springOutTooMuch(float x) { return springOutGeneric(x, 1.f); } const std::unordered_map<std::string, EasingFn> easingsMap = { { "linear", Easings::linear }, { "sineOut", Easings::sineOut }, { "sineIn", Easings::sineIn }, { "sineInOut", Easings::sineInOut }, { "cubicOut", Easings::cubicOut }, { "cubicIn", Easings::cubicIn }, { "cubicInOut", Easings::cubicInOut }, { "quartOut", Easings::quartOut }, { "quartIn", Easings::quartIn }, { "quartInOut", Easings::quartInOut }, { "springOutWeak", Easings::springOutWeak }, { "springOutMed", Easings::springOutMed }, { "springOutStrong", Easings::springOutStrong }, { "springOutTooMuch", Easings::springOutTooMuch }, }; } osg::Vec3f vec3fLerp(float t, const osg::Vec3f& start, const osg::Vec3f& end) { return start + (end - start) * t; } } AnimBlendController::AnimBlendController(const osg::ref_ptr<SceneUtil::KeyframeController>& keyframeTrack, const AnimBlendStateData& newState, const osg::ref_ptr<const SceneUtil::AnimBlendRules>& blendRules) : mEasingFn(&Easings::sineOut) { setKeyframeTrack(keyframeTrack, newState, blendRules); } AnimBlendController::AnimBlendController() : mEasingFn(&Easings::sineOut) { } NifAnimBlendController::NifAnimBlendController(const osg::ref_ptr<SceneUtil::KeyframeController>& keyframeTrack, const AnimBlendStateData& newState, const osg::ref_ptr<const SceneUtil::AnimBlendRules>& blendRules) : AnimBlendController(keyframeTrack, newState, blendRules) { } BoneAnimBlendController::BoneAnimBlendController(const osg::ref_ptr<SceneUtil::KeyframeController>& keyframeTrack, const AnimBlendStateData& newState, const osg::ref_ptr<const SceneUtil::AnimBlendRules>& blendRules) : AnimBlendController(keyframeTrack, newState, blendRules) { } void AnimBlendController::setKeyframeTrack(const osg::ref_ptr<SceneUtil::KeyframeController>& kft, const AnimBlendStateData& newState, const osg::ref_ptr<const SceneUtil::AnimBlendRules>& blendRules) { // If animation has changed then start blending if (newState.mGroupname != mAnimState.mGroupname || newState.mStartKey != mAnimState.mStartKey || kft != mKeyframeTrack) { // Default blend settings mBlendDuration = 0; mEasingFn = &Easings::sineOut; if (blendRules) { // Finds a matching blend rule either in this or previous ruleset auto blendRule = blendRules->findBlendingRule( mAnimState.mGroupname, mAnimState.mStartKey, newState.mGroupname, newState.mStartKey); if (blendRule) { if (const auto it = Easings::easingsMap.find(blendRule->mEasing); it != Easings::easingsMap.end()) { mEasingFn = it->second; mBlendDuration = blendRule->mDuration; } else { Log(Debug::Warning) << "Warning: animation blending rule contains invalid easing type: " << blendRule->mEasing; } } } mAnimBlendRules = blendRules; mKeyframeTrack = kft; mAnimState = newState; mBlendTrigger = true; } } void AnimBlendController::calculateInterpFactor(float time) { if (mBlendDuration != 0) mTimeFactor = std::min((time - mBlendStartTime) / mBlendDuration, 1.0f); else mTimeFactor = 1; mInterpActive = mTimeFactor < 1.0; if (mInterpActive) mInterpFactor = mEasingFn(mTimeFactor); else mInterpFactor = 1.0f; } void BoneAnimBlendController::gatherRecursiveBoneTransforms(osgAnimation::Bone* bone, bool isRoot) { // Incase group traversal encountered something that isnt a bone if (!bone) return; mBlendBoneTransforms[bone] = bone->getMatrix(); osg::Group* group = bone->asGroup(); if (group) { for (unsigned int i = 0; i < group->getNumChildren(); ++i) gatherRecursiveBoneTransforms(dynamic_cast<osgAnimation::Bone*>(group->getChild(i)), false); } } void BoneAnimBlendController::applyBoneBlend(osgAnimation::Bone* bone) { // If we are done with interpolation then we can safely skip this as the bones are correct if (!mInterpActive) return; // Shouldn't happen, but potentially an edge case where a new bone was added // between gatherRecursiveBoneTransforms and this update // currently OpenMW will never do this assert(mBlendBoneTransforms.find(bone) != mBlendBoneTransforms.end()); // Every frame the osgAnimation controller updates this // so it is ok that we update it directly below const osg::Matrixf& currentSampledMatrix = bone->getMatrix(); const osg::Matrixf& lastSampledMatrix = mBlendBoneTransforms.at(bone); const osg::Vec3f scale = currentSampledMatrix.getScale(); const osg::Quat rotation = currentSampledMatrix.getRotate(); const osg::Vec3f translation = currentSampledMatrix.getTrans(); const osg::Quat blendRotation = lastSampledMatrix.getRotate(); const osg::Vec3f blendTrans = lastSampledMatrix.getTrans(); osg::Quat lerpedRot; lerpedRot.slerp(mInterpFactor, blendRotation, rotation); osg::Matrixf lerpedMatrix; lerpedMatrix.makeRotate(lerpedRot); lerpedMatrix.setTrans(vec3fLerp(mInterpFactor, blendTrans, translation)); // Scale is not lerped based on the idea that it is much more likely that scale animation will be used to // instantly hide/show objects in which case the scale interpolation is undesirable. lerpedMatrix = osg::Matrixd::scale(scale) * lerpedMatrix; // Apply new blended matrix osgAnimation::Bone* boneParent = bone->getBoneParent(); bone->setMatrix(lerpedMatrix); if (boneParent) bone->setMatrixInSkeletonSpace(lerpedMatrix * boneParent->getMatrixInSkeletonSpace()); else bone->setMatrixInSkeletonSpace(lerpedMatrix); } void BoneAnimBlendController::operator()(osgAnimation::Bone* node, osg::NodeVisitor* nv) { // HOW THIS WORKS: This callback method is called only for bones with attached keyframe controllers // such as bip01, bip01 spine1 etc. The child bones of these controllers have their own callback wrapper // which will call this instance's applyBoneBlend for each child bone. The order of update is important // as the blending calculations expect the bone's skeleton matrix to be at the sample point float time = nv->getFrameStamp()->getSimulationTime(); assert(node != nullptr); if (mBlendTrigger) { mBlendTrigger = false; mBlendStartTime = time; } calculateInterpFactor(time); if (mInterpActive) applyBoneBlend(node); SceneUtil::NodeCallback<BoneAnimBlendController, osgAnimation::Bone*>::traverse(node, nv); } void NifAnimBlendController::operator()(NifOsg::MatrixTransform* node, osg::NodeVisitor* nv) { // HOW THIS WORKS: The actual retrieval of the bone transformation based on animation is done by the // KeyframeController (mKeyframeTrack). The KeyframeController retreives time data (playback position) every // frame from controller's input (getInputValue(nv)) which is bound to an appropriate AnimationState time value // in Animation.cpp. Animation.cpp ultimately manages animation playback via updating AnimationState objects and // determines when and what should be playing. // This controller exploits KeyframeController to get transformations and upon animation change blends from // the last known position to the new animated one. auto [translation, rotation, scale] = mKeyframeTrack->getCurrentTransformation(nv); float time = nv->getFrameStamp()->getSimulationTime(); if (mBlendTrigger) { mBlendTrigger = false; mBlendStartTime = time; // Nif mRotationScale is used here because it's unaffected by the side-effects of RotationController mBlendStartRot = node->mRotationScale.toOsgMatrix().getRotate(); mBlendStartTrans = node->getMatrix().getTrans(); mBlendStartScale = node->mScale; // Subtract any rotate controller's offset from start transform (if it appears after this callback) // this is required otherwise the blend start will be with an offset, then offset could be applied again // fixes an issue with camera jumping during first person sneak jumping camera osg::Callback* updateCb = node->getUpdateCallback()->getNestedCallback(); while (updateCb) { MWRender::RotateController* rotateController = dynamic_cast<MWRender::RotateController*>(updateCb); if (rotateController) { const osg::Quat& rotate = rotateController->getRotate(); const osg::Vec3f& offset = rotateController->getOffset(); osg::NodePathList nodepaths = node->getParentalNodePaths(rotateController->getRelativeTo()); osg::Quat worldOrient; if (!nodepaths.empty()) { osg::Matrixf worldMat = osg::computeLocalToWorld(nodepaths[0]); worldOrient = worldMat.getRotate(); } worldOrient = worldOrient * rotate.inverse(); const osg::Quat worldOrientInverse = worldOrient.inverse(); mBlendStartTrans -= worldOrientInverse * offset; } updateCb = updateCb->getNestedCallback(); } } calculateInterpFactor(time); if (mInterpActive) { if (rotation) { osg::Quat lerpedRot; lerpedRot.slerp(mInterpFactor, mBlendStartRot, *rotation); node->setRotation(lerpedRot); } else { // This is necessary to prevent first person animation glitching out node->setRotation(node->mRotationScale); } if (translation) { osg::Vec3f lerpedTrans = vec3fLerp(mInterpFactor, mBlendStartTrans, *translation); node->setTranslation(lerpedTrans); } } else { if (translation) node->setTranslation(*translation); if (rotation) node->setRotation(*rotation); else node->setRotation(node->mRotationScale); } if (scale) // Scale is not lerped based on the idea that it is much more likely that scale animation will be used to // instantly hide/show objects in which case the scale interpolation is undesirable. node->setScale(*scale); SceneUtil::NodeCallback<NifAnimBlendController, NifOsg::MatrixTransform*>::traverse(node, nv); } }
14,686
C++
.cpp
329
32.161094
120
0.577555
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,384
screenshotmanager.cpp
OpenMW_openmw/apps/openmw/mwrender/screenshotmanager.cpp
#include "screenshotmanager.hpp" #include <condition_variable> #include <mutex> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "postprocessor.hpp" namespace MWRender { class NotifyDrawCompletedCallback : public osg::Camera::DrawCallback { public: NotifyDrawCompletedCallback() : mDone(false) , mFrame(0) { } void operator()(osg::RenderInfo& renderInfo) const override { std::lock_guard<std::mutex> lock(mMutex); if (renderInfo.getState()->getFrameStamp()->getFrameNumber() >= mFrame && !mDone) { mDone = true; mCondition.notify_one(); } } void waitTillDone() { std::unique_lock<std::mutex> lock(mMutex); if (mDone) return; mCondition.wait(lock); } void reset(unsigned int frame) { std::lock_guard<std::mutex> lock(mMutex); mDone = false; mFrame = frame; } mutable std::condition_variable mCondition; mutable std::mutex mMutex; mutable bool mDone; unsigned int mFrame; }; class ReadImageFromFramebufferCallback : public osg::Drawable::DrawCallback { public: ReadImageFromFramebufferCallback(osg::Image* image, int width, int height) : mWidth(width) , mHeight(height) , mImage(image) { } void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* /*drawable*/) const override { int screenW = renderInfo.getCurrentCamera()->getViewport()->width(); int screenH = renderInfo.getCurrentCamera()->getViewport()->height(); if (Stereo::getStereo()) { auto eyeRes = Stereo::Manager::instance().eyeResolution(); screenW = eyeRes.x(); screenH = eyeRes.y(); } double imageaspect = (double)mWidth / (double)mHeight; int leftPadding = std::max(0, static_cast<int>(screenW - screenH * imageaspect) / 2); int topPadding = std::max(0, static_cast<int>(screenH - screenW / imageaspect) / 2); int width = screenW - leftPadding * 2; int height = screenH - topPadding * 2; mImage->readPixels(leftPadding, topPadding, width, height, GL_RGB, GL_UNSIGNED_BYTE); mImage->scaleImage(mWidth, mHeight, 1); } private: int mWidth; int mHeight; osg::ref_ptr<osg::Image> mImage; }; ScreenshotManager::ScreenshotManager(osgViewer::Viewer* viewer) : mViewer(viewer) , mDrawCompleteCallback(new NotifyDrawCompletedCallback) { } ScreenshotManager::~ScreenshotManager() {} void ScreenshotManager::screenshot(osg::Image* image, int w, int h) { osg::Camera* camera = MWBase::Environment::get().getWorld()->getPostProcessor()->getHUDCamera(); osg::ref_ptr<osg::Drawable> tempDrw = new osg::Drawable; tempDrw->setDrawCallback(new ReadImageFromFramebufferCallback(image, w, h)); tempDrw->setCullingActive(false); tempDrw->getOrCreateStateSet()->setRenderBinDetails(100, "RenderBin", osg::StateSet::USE_RENDERBIN_DETAILS); // so its after all scene bins but before POST_RENDER gui camera camera->addChild(tempDrw); // Ref https://gitlab.com/OpenMW/openmw/-/issues/6013 mDrawCompleteCallback->reset(mViewer->getFrameStamp()->getFrameNumber()); mViewer->getCamera()->setFinalDrawCallback(mDrawCompleteCallback); mViewer->eventTraversal(); mViewer->updateTraversal(); mViewer->renderingTraversals(); mDrawCompleteCallback->waitTillDone(); // now that we've "used up" the current frame, get a fresh frame number for the next frame() following after the // screenshot is completed mViewer->advance(mViewer->getFrameStamp()->getSimulationTime()); camera->removeChild(tempDrw); } }
4,232
C++
.cpp
105
31.057143
120
0.621562
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,385
util.cpp
OpenMW_openmw/apps/openmw/mwrender/util.cpp
#include "util.hpp" #include <osg/Node> #include <osg/ValueObject> #include <components/misc/resourcehelpers.hpp> #include <components/resource/imagemanager.hpp> #include <components/resource/resourcesystem.hpp> #include <components/sceneutil/texturetype.hpp> #include <components/sceneutil/visitor.hpp> #include <components/settings/values.hpp> namespace MWRender { namespace { class TextureOverrideVisitor : public osg::NodeVisitor { public: TextureOverrideVisitor(std::string_view texture, Resource::ResourceSystem* resourcesystem) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mTexture(texture) , mResourcesystem(resourcesystem) { } void apply(osg::Node& node) override { int index = 0; if (node.getUserValue("overrideFx", index)) { if (index == 1) overrideTexture(mTexture, mResourcesystem, node); } traverse(node); } std::string_view mTexture; Resource::ResourceSystem* mResourcesystem; }; } void overrideFirstRootTexture(std::string_view texture, Resource::ResourceSystem* resourceSystem, osg::Node& node) { TextureOverrideVisitor overrideVisitor(texture, resourceSystem); node.accept(overrideVisitor); } void overrideTexture(std::string_view texture, Resource::ResourceSystem* resourceSystem, osg::Node& node) { if (texture.empty()) return; const VFS::Path::Normalized correctedTexture = Misc::ResourceHelpers::correctTexturePath(texture, resourceSystem->getVFS()); // Not sure if wrap settings should be pulled from the overridden texture? osg::ref_ptr<osg::Texture2D> tex = new osg::Texture2D(resourceSystem->getImageManager()->getImage(correctedTexture)); tex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); tex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); osg::ref_ptr<osg::StateSet> stateset; if (const osg::StateSet* const src = node.getStateSet()) stateset = new osg::StateSet(*src, osg::CopyOp::SHALLOW_COPY); else stateset = new osg::StateSet; stateset->setTextureAttribute(0, tex, osg::StateAttribute::OVERRIDE); stateset->setTextureAttribute(0, new SceneUtil::TextureType("diffuseMap"), osg::StateAttribute::OVERRIDE); node.setStateSet(stateset); } bool shouldAddMSAAIntermediateTarget() { return Settings::shaders().mAntialiasAlphaTest && Settings::video().mAntialiasing > 1; } }
2,766
C++
.cpp
66
32.742424
118
0.647081
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,386
esm4npcanimation.cpp
OpenMW_openmw/apps/openmw/mwrender/esm4npcanimation.cpp
#include "esm4npcanimation.hpp" #include <components/esm4/loadarma.hpp> #include <components/esm4/loadarmo.hpp> #include <components/esm4/loadclot.hpp> #include <components/esm4/loadhair.hpp> #include <components/esm4/loadhdpt.hpp> #include <components/esm4/loadnpc.hpp> #include <components/esm4/loadrace.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include "../mwbase/environment.hpp" #include "../mwclass/esm4npc.hpp" #include "../mwworld/esmstore.hpp" namespace MWRender { ESM4NpcAnimation::ESM4NpcAnimation( const MWWorld::Ptr& ptr, osg::ref_ptr<osg::Group> parentNode, Resource::ResourceSystem* resourceSystem) : Animation(ptr, std::move(parentNode), resourceSystem) { setObjectRoot(mPtr.getClass().getCorrectedModel(mPtr), true, true, false); updateParts(); } void ESM4NpcAnimation::updateParts() { if (mObjectRoot == nullptr) return; const ESM4::Npc* traits = MWClass::ESM4Npc::getTraitsRecord(mPtr); if (traits == nullptr) return; if (traits->mIsTES4) updatePartsTES4(*traits); else if (traits->mIsFONV) { // Not implemented yet } else { // There is no easy way to distinguish TES5 and FO3. // In case of FO3 the function shouldn't crash the game and will // only lead to the NPC not being rendered. updatePartsTES5(*traits); } } void ESM4NpcAnimation::insertPart(std::string_view model) { if (model.empty()) return; mResourceSystem->getSceneManager()->getInstance( VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(model)), mObjectRoot.get()); } template <class Record> static std::string_view chooseTes4EquipmentModel(const Record* rec, bool isFemale) { if (isFemale && !rec->mModelFemale.empty()) return rec->mModelFemale; else if (!isFemale && !rec->mModelMale.empty()) return rec->mModelMale; else return rec->mModel; } void ESM4NpcAnimation::updatePartsTES4(const ESM4::Npc& traits) { const ESM4::Race* race = MWClass::ESM4Npc::getRace(mPtr); bool isFemale = MWClass::ESM4Npc::isFemale(mPtr); // TODO: Body and head parts are placed incorrectly, need to attach to bones for (const ESM4::Race::BodyPart& bodyPart : (isFemale ? race->mBodyPartsFemale : race->mBodyPartsMale)) insertPart(bodyPart.mesh); for (const ESM4::Race::BodyPart& bodyPart : race->mHeadParts) insertPart(bodyPart.mesh); if (!traits.mHair.isZeroOrUnset()) { const MWWorld::ESMStore* store = MWBase::Environment::get().getESMStore(); if (const ESM4::Hair* hair = store->get<ESM4::Hair>().search(traits.mHair)) insertPart(hair->mModel); else Log(Debug::Error) << "Hair not found: " << ESM::RefId(traits.mHair); } for (const ESM4::Armor* armor : MWClass::ESM4Npc::getEquippedArmor(mPtr)) insertPart(chooseTes4EquipmentModel(armor, isFemale)); for (const ESM4::Clothing* clothing : MWClass::ESM4Npc::getEquippedClothing(mPtr)) insertPart(chooseTes4EquipmentModel(clothing, isFemale)); } void ESM4NpcAnimation::insertHeadParts( const std::vector<ESM::FormId>& partIds, std::set<uint32_t>& usedHeadPartTypes) { const MWWorld::ESMStore* store = MWBase::Environment::get().getESMStore(); for (ESM::FormId partId : partIds) { if (partId.isZeroOrUnset()) continue; const ESM4::HeadPart* part = store->get<ESM4::HeadPart>().search(partId); if (!part) { Log(Debug::Error) << "Head part not found: " << ESM::RefId(partId); continue; } if (usedHeadPartTypes.emplace(part->mType).second) insertPart(part->mModel); } } void ESM4NpcAnimation::updatePartsTES5(const ESM4::Npc& traits) { const MWWorld::ESMStore* store = MWBase::Environment::get().getESMStore(); const ESM4::Race* race = MWClass::ESM4Npc::getRace(mPtr); bool isFemale = MWClass::ESM4Npc::isFemale(mPtr); std::vector<const ESM4::ArmorAddon*> armorAddons; auto findArmorAddons = [&](const ESM4::Armor* armor) { for (ESM::FormId armaId : armor->mAddOns) { if (armaId.isZeroOrUnset()) continue; const ESM4::ArmorAddon* arma = store->get<ESM4::ArmorAddon>().search(armaId); if (!arma) { Log(Debug::Error) << "ArmorAddon not found: " << ESM::RefId(armaId); continue; } bool compatibleRace = arma->mRacePrimary == traits.mRace; for (auto r : arma->mRaces) if (r == traits.mRace) compatibleRace = true; if (compatibleRace) armorAddons.push_back(arma); } }; for (const ESM4::Armor* armor : MWClass::ESM4Npc::getEquippedArmor(mPtr)) findArmorAddons(armor); if (!traits.mWornArmor.isZeroOrUnset()) { if (const ESM4::Armor* armor = store->get<ESM4::Armor>().search(traits.mWornArmor)) findArmorAddons(armor); else Log(Debug::Error) << "Worn armor not found: " << ESM::RefId(traits.mWornArmor); } if (!race->mSkin.isZeroOrUnset()) { if (const ESM4::Armor* armor = store->get<ESM4::Armor>().search(race->mSkin)) findArmorAddons(armor); else Log(Debug::Error) << "Skin not found: " << ESM::RefId(race->mSkin); } if (isFemale) std::sort(armorAddons.begin(), armorAddons.end(), [](auto x, auto y) { return x->mFemalePriority > y->mFemalePriority; }); else std::sort(armorAddons.begin(), armorAddons.end(), [](auto x, auto y) { return x->mMalePriority > y->mMalePriority; }); uint32_t usedParts = 0; for (const ESM4::ArmorAddon* arma : armorAddons) { const uint32_t covers = arma->mBodyTemplate.bodyPart; // if body is already covered, skip to avoid clipping if (covers & usedParts & ESM4::Armor::TES5_Body) continue; // if covers at least something that wasn't covered before - add model if (covers & ~usedParts) { usedParts |= covers; insertPart(isFemale ? arma->mModelFemale : arma->mModelMale); } } std::set<uint32_t> usedHeadPartTypes; if (usedParts & ESM4::Armor::TES5_Hair) usedHeadPartTypes.insert(ESM4::HeadPart::Type_Hair); insertHeadParts(traits.mHeadParts, usedHeadPartTypes); insertHeadParts(isFemale ? race->mHeadPartIdsFemale : race->mHeadPartIdsMale, usedHeadPartTypes); } }
7,308
C++
.cpp
169
32.869822
111
0.599382
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,387
localmap.cpp
OpenMW_openmw/apps/openmw/mwrender/localmap.cpp
#include "localmap.hpp" #include <cstdint> #include <osg/ComputeBoundsVisitor> #include <osg/Fog> #include <osg/LightModel> #include <osg/LightSource> #include <osg/PolygonMode> #include <osg/Texture2D> #include <osgDB/ReadFile> #include <components/debug/debuglog.hpp> #include <components/esm3/fogstate.hpp> #include <components/esm3/loadcell.hpp> #include <components/files/memorystream.hpp> #include <components/misc/constants.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/sceneutil/rtt.hpp> #include <components/sceneutil/shadow.hpp> #include <components/sceneutil/visitor.hpp> #include <components/settings/values.hpp> #include <components/stereo/multiview.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwworld/cellstore.hpp" #include "util.hpp" #include "vismask.hpp" namespace { float square(float val) { return val * val; } std::pair<int, int> divideIntoSegments(const osg::BoundingBox& bounds, float mapSize) { osg::Vec2f min(bounds.xMin(), bounds.yMin()); osg::Vec2f max(bounds.xMax(), bounds.yMax()); osg::Vec2f length = max - min; const int segsX = static_cast<int>(std::ceil(length.x() / mapSize)); const int segsY = static_cast<int>(std::ceil(length.y() / mapSize)); return { segsX, segsY }; } } namespace MWRender { class LocalMapRenderToTexture : public SceneUtil::RTTNode { public: LocalMapRenderToTexture(osg::Node* sceneRoot, int res, int mapWorldSize, float x, float y, const osg::Vec3d& upVector, float zmin, float zmax); void setDefaults(osg::Camera* camera) override; osg::Node* mSceneRoot; osg::Matrix mProjectionMatrix; osg::Matrix mViewMatrix; bool mActive; }; class CameraLocalUpdateCallback : public SceneUtil::NodeCallback<CameraLocalUpdateCallback, LocalMapRenderToTexture*> { public: void operator()(LocalMapRenderToTexture* node, osg::NodeVisitor* nv); }; LocalMap::LocalMap(osg::Group* root) : mRoot(root) , mMapResolution( Settings::map().mLocalMapResolution * MWBase::Environment::get().getWindowManager()->getScalingFactor()) , mMapWorldSize(Constants::CellSizeInUnits) , mCellDistance(Constants::CellGridRadius) , mAngle(0.f) , mInterior(false) { SceneUtil::FindByNameVisitor find("Scene Root"); mRoot->accept(find); mSceneRoot = find.mFoundNode; if (!mSceneRoot) throw std::runtime_error("no scene root found"); } LocalMap::~LocalMap() { for (auto& rtt : mLocalMapRTTs) mRoot->removeChild(rtt); } const osg::Vec2f LocalMap::rotatePoint(const osg::Vec2f& point, const osg::Vec2f& center, const float angle) { return osg::Vec2f( std::cos(angle) * (point.x() - center.x()) - std::sin(angle) * (point.y() - center.y()) + center.x(), std::sin(angle) * (point.x() - center.x()) + std::cos(angle) * (point.y() - center.y()) + center.y()); } void LocalMap::clear() { mExteriorSegments.clear(); mInteriorSegments.clear(); } void LocalMap::saveFogOfWar(MWWorld::CellStore* cell) { if (!mInterior) { const MapSegment& segment = mExteriorSegments[std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY())]; if (segment.mFogOfWarImage && segment.mHasFogState) { auto fog = std::make_unique<ESM::FogState>(); fog->mFogTextures.emplace_back(); segment.saveFogOfWar(fog->mFogTextures.back()); cell->setFog(std::move(fog)); } } else { auto segments = divideIntoSegments(mBounds, mMapWorldSize); auto fog = std::make_unique<ESM::FogState>(); fog->mBounds.mMinX = mBounds.xMin(); fog->mBounds.mMaxX = mBounds.xMax(); fog->mBounds.mMinY = mBounds.yMin(); fog->mBounds.mMaxY = mBounds.yMax(); fog->mNorthMarkerAngle = mAngle; fog->mFogTextures.reserve(segments.first * segments.second); for (int x = 0; x < segments.first; ++x) { for (int y = 0; y < segments.second; ++y) { const MapSegment& segment = mInteriorSegments[std::make_pair(x, y)]; fog->mFogTextures.emplace_back(); // saving even if !segment.mHasFogState so we don't mess up the segmenting // plus, older openmw versions can't deal with empty images segment.saveFogOfWar(fog->mFogTextures.back()); fog->mFogTextures.back().mX = x; fog->mFogTextures.back().mY = y; } } cell->setFog(std::move(fog)); } } void LocalMap::setupRenderToTexture( int segment_x, int segment_y, float left, float top, const osg::Vec3d& upVector, float zmin, float zmax) { mLocalMapRTTs.emplace_back( new LocalMapRenderToTexture(mSceneRoot, mMapResolution, mMapWorldSize, left, top, upVector, zmin, zmax)); mRoot->addChild(mLocalMapRTTs.back()); MapSegment& segment = mInterior ? mInteriorSegments[std::make_pair(segment_x, segment_y)] : mExteriorSegments[std::make_pair(segment_x, segment_y)]; segment.mMapTexture = static_cast<osg::Texture2D*>(mLocalMapRTTs.back()->getColorTexture(nullptr)); } void LocalMap::requestMap(const MWWorld::CellStore* cell) { if (!cell->isExterior()) { requestInteriorMap(cell); return; } int cellX = cell->getCell()->getGridX(); int cellY = cell->getCell()->getGridY(); MapSegment& segment = mExteriorSegments[std::make_pair(cellX, cellY)]; const std::uint8_t neighbourFlags = getExteriorNeighbourFlags(cellX, cellY); if ((segment.mLastRenderNeighbourFlags & neighbourFlags) == neighbourFlags) return; requestExteriorMap(cell, segment); segment.mLastRenderNeighbourFlags = neighbourFlags; } void LocalMap::addCell(MWWorld::CellStore* cell) { if (cell->isExterior()) mExteriorSegments.emplace( std::make_pair(cell->getCell()->getGridX(), cell->getCell()->getGridY()), MapSegment{}); } void LocalMap::removeExteriorCell(int x, int y) { mExteriorSegments.erase({ x, y }); } void LocalMap::removeCell(MWWorld::CellStore* cell) { saveFogOfWar(cell); if (cell->isExterior()) mExteriorSegments.erase({ cell->getCell()->getGridX(), cell->getCell()->getGridY() }); else mInteriorSegments.clear(); } osg::ref_ptr<osg::Texture2D> LocalMap::getMapTexture(int x, int y) { auto& segments(mInterior ? mInteriorSegments : mExteriorSegments); SegmentMap::iterator found = segments.find(std::make_pair(x, y)); if (found == segments.end()) return osg::ref_ptr<osg::Texture2D>(); else return found->second.mMapTexture; } osg::ref_ptr<osg::Texture2D> LocalMap::getFogOfWarTexture(int x, int y) { auto& segments(mInterior ? mInteriorSegments : mExteriorSegments); SegmentMap::iterator found = segments.find(std::make_pair(x, y)); if (found == segments.end()) return osg::ref_ptr<osg::Texture2D>(); else return found->second.mFogOfWarTexture; } void LocalMap::cleanupCameras() { auto it = mLocalMapRTTs.begin(); while (it != mLocalMapRTTs.end()) { if (!(*it)->mActive) { mRoot->removeChild(*it); it = mLocalMapRTTs.erase(it); } else it++; } } void LocalMap::requestExteriorMap(const MWWorld::CellStore* cell, MapSegment& segment) { mInterior = false; const int x = cell->getCell()->getGridX(); const int y = cell->getCell()->getGridY(); osg::BoundingSphere bound = mSceneRoot->getBound(); float zmin = bound.center().z() - bound.radius(); float zmax = bound.center().z() + bound.radius(); setupRenderToTexture(x, y, x * mMapWorldSize + mMapWorldSize / 2.f, y * mMapWorldSize + mMapWorldSize / 2.f, osg::Vec3d(0, 1, 0), zmin, zmax); if (segment.mFogOfWarImage != nullptr) return; if (cell->getFog()) segment.loadFogOfWar(cell->getFog()->mFogTextures.back()); else segment.initFogOfWar(); } static osg::Vec2f getNorthVector(const MWWorld::CellStore* cell) { MWWorld::ConstPtr northmarker = cell->searchConst(ESM::RefId::stringRefId("northmarker")); if (northmarker.isEmpty()) return osg::Vec2f(0, 1); osg::Quat orient(-northmarker.getRefData().getPosition().rot[2], osg::Vec3f(0, 0, 1)); osg::Vec3f dir = orient * osg::Vec3f(0, 1, 0); osg::Vec2f d(dir.x(), dir.y()); return d; } void LocalMap::requestInteriorMap(const MWWorld::CellStore* cell) { osg::ComputeBoundsVisitor computeBoundsVisitor; computeBoundsVisitor.setTraversalMask(Mask_Scene | Mask_Terrain | Mask_Object | Mask_Static); mSceneRoot->accept(computeBoundsVisitor); osg::BoundingBox bounds = computeBoundsVisitor.getBoundingBox(); // If we're in an empty cell, bail out // The operations in this function are only valid for finite bounds if (!bounds.valid() || bounds.radius2() == 0.0) return; mInterior = true; mBounds = bounds; // Get the cell's NorthMarker rotation. This is used to rotate the entire map. osg::Vec2f north = getNorthVector(cell); mAngle = std::atan2(north.x(), north.y()); // Rotate the cell and merge the rotated corners to the bounding box osg::Vec2f origCenter(bounds.center().x(), bounds.center().y()); osg::Vec3f origCorners[8]; for (int i = 0; i < 8; ++i) origCorners[i] = mBounds.corner(i); for (int i = 0; i < 8; ++i) { osg::Vec3f corner = origCorners[i]; osg::Vec2f corner2d(corner.x(), corner.y()); corner2d = rotatePoint(corner2d, origCenter, mAngle); mBounds.expandBy(osg::Vec3f(corner2d.x(), corner2d.y(), 0)); } // Do NOT change padding! This will break older savegames. // If the padding really needs to be changed, then it must be saved in the ESM::FogState and // assume the old (500) value as default for older savegames. const float padding = 500.0f; // Apply a little padding mBounds.set(mBounds._min - osg::Vec3f(padding, padding, 0.f), mBounds._max + osg::Vec3f(padding, padding, 0.f)); float zMin = mBounds.zMin(); float zMax = mBounds.zMax(); // If there is fog state in the CellStore (e.g. when it came from a savegame) we need to do some checks // to see if this state is still valid. // Both the cell bounds and the NorthMarker rotation could be changed by the content files or exchanged models. // If they changed by too much then parts of the interior might not be covered by the map anymore. // The following code detects this, and discards the CellStore's fog state if it needs to. std::vector<std::pair<int, int>> segmentMappings; if (cell->getFog()) { ESM::FogState* fog = cell->getFog(); if (std::abs(mAngle - fog->mNorthMarkerAngle) < osg::DegreesToRadians(5.f)) { // Expand mBounds so the saved textures fit the same grid int xOffset = 0; int yOffset = 0; if (fog->mBounds.mMinX < mBounds.xMin()) { mBounds.xMin() = fog->mBounds.mMinX; } else if (fog->mBounds.mMinX > mBounds.xMin()) { float diff = fog->mBounds.mMinX - mBounds.xMin(); xOffset += diff / mMapWorldSize; xOffset++; mBounds.xMin() = fog->mBounds.mMinX - xOffset * mMapWorldSize; } if (fog->mBounds.mMinY < mBounds.yMin()) { mBounds.yMin() = fog->mBounds.mMinY; } else if (fog->mBounds.mMinY > mBounds.yMin()) { float diff = fog->mBounds.mMinY - mBounds.yMin(); yOffset += diff / mMapWorldSize; yOffset++; mBounds.yMin() = fog->mBounds.mMinY - yOffset * mMapWorldSize; } if (fog->mBounds.mMaxX > mBounds.xMax()) mBounds.xMax() = fog->mBounds.mMaxX; if (fog->mBounds.mMaxY > mBounds.yMax()) mBounds.yMax() = fog->mBounds.mMaxY; if (xOffset != 0 || yOffset != 0) Log(Debug::Warning) << "Warning: expanding fog by " << xOffset << ", " << yOffset; const auto& textures = fog->mFogTextures; segmentMappings.reserve(textures.size()); osg::BoundingBox savedBounds{ fog->mBounds.mMinX, fog->mBounds.mMinY, 0, fog->mBounds.mMaxX, fog->mBounds.mMaxY, 0 }; auto segments = divideIntoSegments(savedBounds, mMapWorldSize); for (int x = 0; x < segments.first; ++x) for (int y = 0; y < segments.second; ++y) segmentMappings.emplace_back(std::make_pair(x + xOffset, y + yOffset)); mAngle = fog->mNorthMarkerAngle; } } osg::Vec2f min(mBounds.xMin(), mBounds.yMin()); osg::Vec2f center(mBounds.center().x(), mBounds.center().y()); osg::Quat cameraOrient(mAngle, osg::Vec3d(0, 0, -1)); auto segments = divideIntoSegments(mBounds, mMapWorldSize); for (int x = 0; x < segments.first; ++x) { for (int y = 0; y < segments.second; ++y) { osg::Vec2f start = min + osg::Vec2f(mMapWorldSize * x, mMapWorldSize * y); osg::Vec2f newcenter = start + osg::Vec2f(mMapWorldSize / 2.f, mMapWorldSize / 2.f); osg::Vec2f a = newcenter - center; osg::Vec3f rotatedCenter = cameraOrient * (osg::Vec3f(a.x(), a.y(), 0)); osg::Vec2f pos = osg::Vec2f(rotatedCenter.x(), rotatedCenter.y()) + center; setupRenderToTexture(x, y, pos.x(), pos.y(), osg::Vec3f(north.x(), north.y(), 0.f), zMin, zMax); auto coords = std::make_pair(x, y); MapSegment& segment = mInteriorSegments[coords]; if (!segment.mFogOfWarImage) { bool loaded = false; for (size_t index{}; index < segmentMappings.size(); index++) { if (segmentMappings[index] == coords) { ESM::FogState* fog = cell->getFog(); segment.loadFogOfWar(fog->mFogTextures[index]); loaded = true; break; } } if (!loaded) segment.initFogOfWar(); } } } } void LocalMap::worldToInteriorMapPosition(osg::Vec2f pos, float& nX, float& nY, int& x, int& y) { pos = rotatePoint(pos, osg::Vec2f(mBounds.center().x(), mBounds.center().y()), mAngle); osg::Vec2f min(mBounds.xMin(), mBounds.yMin()); x = static_cast<int>(std::ceil((pos.x() - min.x()) / mMapWorldSize) - 1); y = static_cast<int>(std::ceil((pos.y() - min.y()) / mMapWorldSize) - 1); nX = (pos.x() - min.x() - mMapWorldSize * x) / mMapWorldSize; nY = 1.0f - (pos.y() - min.y() - mMapWorldSize * y) / mMapWorldSize; } osg::Vec2f LocalMap::interiorMapToWorldPosition(float nX, float nY, int x, int y) { osg::Vec2f min(mBounds.xMin(), mBounds.yMin()); osg::Vec2f pos(mMapWorldSize * (nX + x) + min.x(), mMapWorldSize * (1.0f - nY + y) + min.y()); pos = rotatePoint(pos, osg::Vec2f(mBounds.center().x(), mBounds.center().y()), -mAngle); return pos; } bool LocalMap::isPositionExplored(float nX, float nY, int x, int y) { auto& segments(mInterior ? mInteriorSegments : mExteriorSegments); const MapSegment& segment = segments[std::make_pair(x, y)]; if (!segment.mFogOfWarImage) return false; nX = std::clamp(nX, 0.f, 1.f); nY = std::clamp(nY, 0.f, 1.f); int texU = static_cast<int>((sFogOfWarResolution - 1) * nX); int texV = static_cast<int>((sFogOfWarResolution - 1) * nY); const std::uint32_t clr = reinterpret_cast<const uint32_t*>(segment.mFogOfWarImage->data())[texV * sFogOfWarResolution + texU]; uint8_t alpha = (clr >> 24); return alpha < 200; } osg::Group* LocalMap::getRoot() { return mRoot; } void LocalMap::updatePlayer(const osg::Vec3f& position, const osg::Quat& orientation, float& u, float& v, int& x, int& y, osg::Vec3f& direction) { // retrieve the x,y grid coordinates the player is in osg::Vec2f pos(position.x(), position.y()); if (mInterior) { worldToInteriorMapPosition(pos, u, v, x, y); osg::Quat cameraOrient(mAngle, osg::Vec3(0, 0, -1)); direction = orientation * cameraOrient.inverse() * osg::Vec3f(0, 1, 0); } else { direction = orientation * osg::Vec3f(0, 1, 0); x = static_cast<int>(std::ceil(pos.x() / mMapWorldSize) - 1); y = static_cast<int>(std::ceil(pos.y() / mMapWorldSize) - 1); // convert from world coordinates to texture UV coordinates u = std::abs((pos.x() - (mMapWorldSize * x)) / mMapWorldSize); v = 1.0f - std::abs((pos.y() - (mMapWorldSize * y)) / mMapWorldSize); } // explore radius (squared) const float exploreRadius = 0.17f * (sFogOfWarResolution - 1); // explore radius from 0 to sFogOfWarResolution-1 const float sqrExploreRadius = square(exploreRadius); const float exploreRadiusUV = exploreRadius / sFogOfWarResolution; // explore radius from 0 to 1 (UV space) // change the affected fog of war textures (in a 3x3 grid around the player) for (int mx = -mCellDistance; mx <= mCellDistance; ++mx) { for (int my = -mCellDistance; my <= mCellDistance; ++my) { // is this texture affected at all? bool affected = false; if (mx == 0 && my == 0) // the player is always in the center of the 3x3 grid affected = true; else { bool affectsX = (mx > 0) ? (u + exploreRadiusUV > 1) : (u - exploreRadiusUV < 0); bool affectsY = (my > 0) ? (v + exploreRadiusUV > 1) : (v - exploreRadiusUV < 0); affected = (affectsX && (my == 0)) || (affectsY && mx == 0) || (affectsX && affectsY); } if (!affected) continue; int texX = x + mx; int texY = y + my * -1; auto& segments(mInterior ? mInteriorSegments : mExteriorSegments); MapSegment& segment = segments[std::make_pair(texX, texY)]; if (!segment.mFogOfWarImage || !segment.mMapTexture) continue; std::uint32_t* data = reinterpret_cast<std::uint32_t*>(segment.mFogOfWarImage->data()); bool changed = false; for (int texV = 0; texV < sFogOfWarResolution; ++texV) { for (int texU = 0; texU < sFogOfWarResolution; ++texU) { float sqrDist = square((texU + mx * (sFogOfWarResolution - 1)) - u * (sFogOfWarResolution - 1)) + square((texV + my * (sFogOfWarResolution - 1)) - v * (sFogOfWarResolution - 1)); const std::uint8_t alpha = std::min<std::uint8_t>( *data >> 24, std::clamp(sqrDist / sqrExploreRadius, 0.f, 1.f) * 255); std::uint32_t val = static_cast<std::uint32_t>(alpha << 24); if (*data != val) { *data = val; changed = true; } ++data; } } if (changed) { segment.mHasFogState = true; segment.mFogOfWarImage->dirty(); } } } } std::uint8_t LocalMap::getExteriorNeighbourFlags(int cellX, int cellY) const { constexpr std::tuple<NeighbourCellFlag, int, int> flags[] = { { NeighbourCellTopLeft, -1, -1 }, { NeighbourCellTopCenter, 0, -1 }, { NeighbourCellTopRight, 1, -1 }, { NeighbourCellMiddleLeft, -1, 0 }, { NeighbourCellMiddleRight, 1, 0 }, { NeighbourCellBottomLeft, -1, 1 }, { NeighbourCellBottomCenter, 0, 1 }, { NeighbourCellBottomRight, 1, 1 }, }; std::uint8_t result = 0; for (const auto& [flag, dx, dy] : flags) if (mExteriorSegments.contains(std::pair(cellX + dx, cellY + dy))) result |= flag; return result; } void LocalMap::MapSegment::createFogOfWarTexture() { if (mFogOfWarTexture) return; mFogOfWarTexture = new osg::Texture2D; // TODO: synchronize access? for now, the worst that could happen is the draw thread jumping a frame ahead. // mFogOfWarTexture->setDataVariance(osg::Object::DYNAMIC); mFogOfWarTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); mFogOfWarTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); mFogOfWarTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mFogOfWarTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mFogOfWarTexture->setUnRefImageDataAfterApply(false); mFogOfWarTexture->setImage(mFogOfWarImage); } void LocalMap::MapSegment::initFogOfWar() { mFogOfWarImage = new osg::Image; // Assign a PixelBufferObject for asynchronous transfer of data to the GPU mFogOfWarImage->setPixelBufferObject(new osg::PixelBufferObject); mFogOfWarImage->allocateImage(sFogOfWarResolution, sFogOfWarResolution, 1, GL_RGBA, GL_UNSIGNED_BYTE); assert(mFogOfWarImage->isDataContiguous()); std::vector<uint32_t> data; data.resize(sFogOfWarResolution * sFogOfWarResolution, 0xff000000); memcpy(mFogOfWarImage->data(), data.data(), data.size() * 4); createFogOfWarTexture(); } void LocalMap::MapSegment::loadFogOfWar(const ESM::FogTexture& esm) { const std::vector<char>& data = esm.mImageData; if (data.empty()) { initFogOfWar(); return; } osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("png"); if (!readerwriter) { Log(Debug::Error) << "Error: Unable to load fog, can't find a png ReaderWriter"; return; } Files::IMemStream in(data.data(), data.size()); osgDB::ReaderWriter::ReadResult result = readerwriter->readImage(in); if (!result.success()) { Log(Debug::Error) << "Error: Failed to read fog: " << result.message() << " code " << result.status(); return; } mFogOfWarImage = result.getImage(); mFogOfWarImage->flipVertical(); mFogOfWarImage->dirty(); createFogOfWarTexture(); mHasFogState = true; } void LocalMap::MapSegment::saveFogOfWar(ESM::FogTexture& fog) const { if (!mFogOfWarImage) return; std::ostringstream ostream; osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("png"); if (!readerwriter) { Log(Debug::Error) << "Error: Unable to write fog, can't find a png ReaderWriter"; return; } // extra flips are unfortunate, but required for compatibility with older versions mFogOfWarImage->flipVertical(); osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(*mFogOfWarImage, ostream); if (!result.success()) { Log(Debug::Error) << "Error: Unable to write fog: " << result.message() << " code " << result.status(); return; } mFogOfWarImage->flipVertical(); std::string data = ostream.str(); fog.mImageData = std::vector<char>(data.begin(), data.end()); } LocalMapRenderToTexture::LocalMapRenderToTexture(osg::Node* sceneRoot, int res, int mapWorldSize, float x, float y, const osg::Vec3d& upVector, float zmin, float zmax) : RTTNode(res, res, 0, false, 0, StereoAwareness::Unaware_MultiViewShaders, shouldAddMSAAIntermediateTarget()) , mSceneRoot(sceneRoot) , mActive(true) { setNodeMask(Mask_RenderToTexture); if (SceneUtil::AutoDepth::isReversed()) mProjectionMatrix = SceneUtil::getReversedZProjectionMatrixAsOrtho( -mapWorldSize / 2, mapWorldSize / 2, -mapWorldSize / 2, mapWorldSize / 2, 5, (zmax - zmin) + 10); else mProjectionMatrix.makeOrtho( -mapWorldSize / 2, mapWorldSize / 2, -mapWorldSize / 2, mapWorldSize / 2, 5, (zmax - zmin) + 10); mViewMatrix.makeLookAt(osg::Vec3d(x, y, zmax + 5), osg::Vec3d(x, y, zmin), upVector); setUpdateCallback(new CameraLocalUpdateCallback); setDepthBufferInternalFormat(GL_DEPTH24_STENCIL8); } void LocalMapRenderToTexture::setDefaults(osg::Camera* camera) { // Disable small feature culling, it's not going to be reliable for this camera osg::Camera::CullingMode cullingMode = (osg::Camera::DEFAULT_CULLING | osg::Camera::FAR_PLANE_CULLING) & ~(osg::Camera::SMALL_FEATURE_CULLING); camera->setCullingMode(cullingMode); SceneUtil::setCameraClearDepth(camera); camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT, osg::Camera::PIXEL_BUFFER_RTT); camera->setClearColor(osg::Vec4(0.f, 0.f, 0.f, 1.f)); camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); camera->setRenderOrder(osg::Camera::PRE_RENDER); camera->setCullMask(Mask_Scene | Mask_SimpleWater | Mask_Terrain | Mask_Object | Mask_Static); camera->setCullMaskLeft(Mask_Scene | Mask_SimpleWater | Mask_Terrain | Mask_Object | Mask_Static); camera->setCullMaskRight(Mask_Scene | Mask_SimpleWater | Mask_Terrain | Mask_Object | Mask_Static); camera->setNodeMask(Mask_RenderToTexture); camera->setProjectionMatrix(mProjectionMatrix); camera->setViewMatrix(mViewMatrix); auto* stateset = camera->getOrCreateStateSet(); stateset->setAttribute(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::FILL), osg::StateAttribute::OVERRIDE); stateset->addUniform(new osg::Uniform("projectionMatrix", static_cast<osg::Matrixf>(mProjectionMatrix)), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); if (Stereo::getMultiview()) Stereo::setMultiviewMatrices(stateset, { mProjectionMatrix, mProjectionMatrix }); // assign large value to effectively turn off fog // shaders don't respect glDisable(GL_FOG) osg::ref_ptr<osg::Fog> fog(new osg::Fog); fog->setStart(10000000); fog->setEnd(10000000); stateset->setAttributeAndModes(fog, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); // turn of sky blending stateset->addUniform(new osg::Uniform("far", 10000000.0f)); stateset->addUniform(new osg::Uniform("skyBlendingStart", 8000000.0f)); stateset->addUniform(new osg::Uniform("sky", 0)); stateset->addUniform(new osg::Uniform("screenRes", osg::Vec2f{ 1, 1 })); osg::ref_ptr<osg::LightModel> lightmodel = new osg::LightModel; lightmodel->setAmbientIntensity(osg::Vec4(0.3f, 0.3f, 0.3f, 1.f)); stateset->setAttributeAndModes(lightmodel, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::ref_ptr<osg::Light> light = new osg::Light; light->setPosition(osg::Vec4(-0.3f, -0.3f, 0.7f, 0.f)); light->setDiffuse(osg::Vec4(0.7f, 0.7f, 0.7f, 1.f)); light->setAmbient(osg::Vec4(0, 0, 0, 1)); light->setSpecular(osg::Vec4(0, 0, 0, 0)); light->setLightNum(0); light->setConstantAttenuation(1.f); light->setLinearAttenuation(0.f); light->setQuadraticAttenuation(0.f); osg::ref_ptr<osg::LightSource> lightSource = new osg::LightSource; lightSource->setLight(light); lightSource->setStateSetModes(*stateset, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*stateset); // override sun for local map SceneUtil::configureStateSetSunOverride(static_cast<SceneUtil::LightManager*>(mSceneRoot), light, stateset); camera->addChild(lightSource); camera->addChild(mSceneRoot); } void CameraLocalUpdateCallback::operator()(LocalMapRenderToTexture* node, osg::NodeVisitor* nv) { if (!node->mActive) node->setNodeMask(0); node->mActive = false; // Rtt-nodes do not forward update traversal to their cameras so we can traverse safely. // Traverse in case there are nested callbacks. traverse(node, nv); } }
30,983
C++
.cpp
647
36.936631
120
0.591635
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,388
actorspaths.cpp
OpenMW_openmw/apps/openmw/mwrender/actorspaths.cpp
#include "actorspaths.hpp" #include "vismask.hpp" #include <components/detournavigator/settings.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/agentpath.hpp> #include <components/sceneutil/detourdebugdraw.hpp> #include <osg/LineWidth> #include <osg/Material> #include <osg/PositionAttitudeTransform> #include <osg/StateSet> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include <algorithm> namespace MWRender { namespace { osg::ref_ptr<osg::StateSet> makeGroupStateSet() { osg::ref_ptr<osg::Material> material = new osg::Material; material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet; stateSet->setAttribute(material); return stateSet; } osg::ref_ptr<osg::StateSet> makeDebugDrawStateSet() { osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet; stateSet->setAttributeAndModes(new osg::LineWidth()); return stateSet; } } ActorsPaths::ActorsPaths(const osg::ref_ptr<osg::Group>& root, bool enabled) : mRootNode(root) , mEnabled(enabled) , mGroupStateSet(makeGroupStateSet()) , mDebugDrawStateSet(makeDebugDrawStateSet()) { } ActorsPaths::~ActorsPaths() { if (mEnabled) disable(); } bool ActorsPaths::toggle() { if (mEnabled) disable(); else enable(); return mEnabled; } void ActorsPaths::update(const MWWorld::ConstPtr& actor, const std::deque<osg::Vec3f>& path, const DetourNavigator::AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end, const DetourNavigator::Settings& settings) { if (!mEnabled) return; const auto group = mGroups.find(actor.mRef); if (group != mGroups.end()) mRootNode->removeChild(group->second.mNode); osg::ref_ptr<osg::Group> newGroup = SceneUtil::createAgentPathGroup(path, agentBounds, start, end, settings.mRecast, mDebugDrawStateSet); newGroup->setNodeMask(Mask_Debug); newGroup->setStateSet(mGroupStateSet); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(newGroup, "debug"); mRootNode->addChild(newGroup); mGroups.insert_or_assign(group, actor.mRef, Group{ actor.mCell, std::move(newGroup) }); } void ActorsPaths::remove(const MWWorld::ConstPtr& actor) { const auto group = mGroups.find(actor.mRef); if (group != mGroups.end()) { mRootNode->removeChild(group->second.mNode); mGroups.erase(group); } } void ActorsPaths::removeCell(const MWWorld::CellStore* const store) { for (auto it = mGroups.begin(); it != mGroups.end();) { if (it->second.mCell == store) { mRootNode->removeChild(it->second.mNode); it = mGroups.erase(it); } else ++it; } } void ActorsPaths::updatePtr(const MWWorld::ConstPtr& old, const MWWorld::ConstPtr& updated) { const auto it = mGroups.find(old.mRef); if (it == mGroups.end()) return; it->second.mCell = updated.mCell; } void ActorsPaths::enable() { std::for_each( mGroups.begin(), mGroups.end(), [&](const Groups::value_type& v) { mRootNode->addChild(v.second.mNode); }); mEnabled = true; } void ActorsPaths::disable() { std::for_each(mGroups.begin(), mGroups.end(), [&](const Groups::value_type& v) { mRootNode->removeChild(v.second.mNode); }); mEnabled = false; } }
3,936
C++
.cpp
112
27.1875
119
0.620363
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,389
camera.cpp
OpenMW_openmw/apps/openmw/mwrender/camera.cpp
#include "camera.hpp" #include <osg/Camera> #include <components/misc/mathutil.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/ptr.hpp" #include "../mwworld/refdata.hpp" #include "../mwmechanics/movement.hpp" #include "../mwphysics/raycasting.hpp" #include "npcanimation.hpp" namespace { class UpdateRenderCameraCallback : public SceneUtil::NodeCallback<UpdateRenderCameraCallback, osg::Camera*> { public: UpdateRenderCameraCallback(MWRender::Camera* cam) : mCamera(cam) { } void operator()(osg::Camera* cam, osg::NodeVisitor* nv) { // traverse first to update animations, in case the camera is attached to an animated node traverse(cam, nv); mCamera->updateCamera(cam); } private: MWRender::Camera* mCamera; }; } namespace MWRender { Camera::Camera(osg::Camera* camera) : mHeightScale(1.f) , mCollisionType( (MWPhysics::CollisionType::CollisionType_Default & ~MWPhysics::CollisionType::CollisionType_Actor) | MWPhysics::CollisionType_CameraOnly) , mCamera(camera) , mAnimation(nullptr) , mFirstPersonView(true) , mMode(Mode::FirstPerson) , mVanityAllowed(true) , mDeferredRotationAllowed(true) , mProcessViewChange(false) , mHeight(124.f) , mPitch(0.f) , mYaw(0.f) , mRoll(0.f) , mCameraDistance(0.f) , mPreferredCameraDistance(0.f) , mFocalPointCurrentOffset(osg::Vec2d()) , mFocalPointTargetOffset(osg::Vec2d()) , mFocalPointTransitionSpeedCoef(1.f) , mSkipFocalPointTransition(true) , mPreviousTransitionInfluence(0.f) , mShowCrosshair(false) , mDeferredRotation(osg::Vec3f()) , mDeferredRotationDisabled(false) { mUpdateCallback = new UpdateRenderCameraCallback(this); mCamera->addUpdateCallback(mUpdateCallback); } Camera::~Camera() { mCamera->removeUpdateCallback(mUpdateCallback); } osg::Vec3d Camera::calculateTrackedPosition() const { if (!mTrackingNode) return osg::Vec3d(); osg::NodePathList nodepaths = mTrackingNode->getParentalNodePaths(); if (nodepaths.empty()) return osg::Vec3d(); osg::Matrix worldMat = osg::computeLocalToWorld(nodepaths[0]); osg::Vec3d res = worldMat.getTrans(); if (mMode != Mode::FirstPerson) res.z() += mHeight * mHeightScale; return res; } osg::Vec3d Camera::getFocalPointOffset() const { osg::Vec3d offset; offset.x() = mFocalPointCurrentOffset.x() * cos(mYaw); offset.y() = mFocalPointCurrentOffset.x() * sin(mYaw); offset.z() = mFocalPointCurrentOffset.y(); return offset; } void Camera::updateCamera(osg::Camera* cam) { osg::Quat orient = getOrient(); osg::Vec3d forward = orient * osg::Vec3d(0, 1, 0); osg::Vec3d up = orient * osg::Vec3d(0, 0, 1); osg::Vec3d pos = mPosition; if (mMode == Mode::FirstPerson) { // It is a hack. Camera position depends on neck animation. // Animations are updated in OSG cull traversal and in order to avoid 1 frame delay we // recalculate the position here. Note that it becomes different from mPosition that // is used in other parts of the code. // TODO: detach camera from OSG animation and get rid of this hack. osg::Vec3d recalculatedTrackedPosition = calculateTrackedPosition(); pos = calculateFirstPersonPosition(recalculatedTrackedPosition); } cam->setViewMatrixAsLookAt(pos, pos + forward, up); mViewMatrix = cam->getViewMatrix(); mProjectionMatrix = cam->getProjectionMatrix(); } void Camera::update(float duration, bool paused) { mLockPitch = mLockYaw = false; if (mQueuedMode && mAnimation->upperBodyReady()) setMode(*mQueuedMode); if (mProcessViewChange) processViewChange(); // only show the crosshair in game mode MWBase::WindowManager* wm = MWBase::Environment::get().getWindowManager(); wm->showCrosshair(!wm->isGuiMode() && mShowCrosshair); if (!paused) updateFocalPointOffset(duration); updatePosition(); } osg::Vec3d Camera::calculateFirstPersonPosition(const osg::Vec3d& trackedPosition) const { osg::Vec3d res = trackedPosition; osg::Vec2f horizontalOffset = Misc::rotateVec2f(osg::Vec2f(mFirstPersonOffset.x(), mFirstPersonOffset.y()), mYaw); res.x() += horizontalOffset.x(); res.y() += horizontalOffset.y(); res.z() += mFirstPersonOffset.z(); return res; } void Camera::updatePosition() { mTrackedPosition = calculateTrackedPosition(); if (mMode == Mode::Static) return; if (mMode == Mode::FirstPerson) { mPosition = calculateFirstPersonPosition(mTrackedPosition); mCameraDistance = 0; return; } constexpr float cameraObstacleLimit = 5.0f; constexpr float focalObstacleLimit = 10.f; const auto* rayCasting = MWBase::Environment::get().getWorld()->getRayCasting(); // Adjust focal point to prevent clipping. osg::Vec3d focalOffset = getFocalPointOffset(); osg::Vec3d focal = mTrackedPosition + focalOffset; focalOffset.z() += 10.f; // Needed to avoid camera clipping through the ceiling because // character's head can be a bit higher than the collision area. float offsetLen = focalOffset.length(); if (offsetLen > 0) { MWPhysics::RayCastingResult result = rayCasting->castSphere(focal - focalOffset, focal, focalObstacleLimit, mCollisionType); if (result.mHit) { double adjustmentCoef = -(result.mHitPos + result.mHitNormal * focalObstacleLimit - focal).length() / offsetLen; focal += focalOffset * std::max(-1.0, adjustmentCoef); } } // Adjust camera distance. mCameraDistance = mPreferredCameraDistance; osg::Quat orient = osg::Quat(mPitch + mExtraPitch, osg::Vec3d(1, 0, 0)) * osg::Quat(mYaw + mExtraYaw, osg::Vec3d(0, 0, 1)); osg::Vec3d offset = orient * osg::Vec3d(0.f, -mCameraDistance, 0.f); MWPhysics::RayCastingResult result = rayCasting->castSphere(focal, focal + offset, cameraObstacleLimit, mCollisionType); if (result.mHit) { mCameraDistance = (result.mHitPos + result.mHitNormal * cameraObstacleLimit - focal).length(); offset = orient * osg::Vec3d(0.f, -mCameraDistance, 0.f); } mPosition = focal + offset; } osg::Quat Camera::getOrient() const { return osg::Quat(mRoll + mExtraRoll, osg::Vec3d(0, 1, 0)) * osg::Quat(mPitch + mExtraPitch, osg::Vec3d(1, 0, 0)) * osg::Quat(mYaw + mExtraYaw, osg::Vec3d(0, 0, 1)); } void Camera::setMode(Mode newMode, bool force) { if (mMode == newMode) { mQueuedMode = std::nullopt; return; } Mode oldMode = mMode; if (!force && (newMode == Mode::FirstPerson || oldMode == Mode::FirstPerson) && mAnimation && !mAnimation->upperBodyReady()) { // Changing the view will stop all playing animations, so if we are playing // anything important, queue the view change for later mQueuedMode = newMode; return; } mMode = newMode; mQueuedMode = std::nullopt; if (newMode == Mode::FirstPerson) mFirstPersonView = true; else if (newMode == Mode::ThirdPerson) mFirstPersonView = false; calculateDeferredRotation(); if (oldMode == Mode::FirstPerson || newMode == Mode::FirstPerson) { instantTransition(); mProcessViewChange = true; } } void Camera::setFocalPointTargetOffset(const osg::Vec2d& v) { mFocalPointTargetOffset = v; mPreviousTransitionSpeed = mFocalPointTransitionSpeed; mPreviousTransitionInfluence = 1.0f; } void Camera::updateFocalPointOffset(float duration) { if (duration <= 0) return; if (mSkipFocalPointTransition) { mSkipFocalPointTransition = false; mPreviousExtraOffset = osg::Vec2d(); mPreviousTransitionInfluence = 0.f; mFocalPointCurrentOffset = mFocalPointTargetOffset; } osg::Vec2d oldOffset = mFocalPointCurrentOffset; if (mPreviousTransitionInfluence > 0) { mFocalPointCurrentOffset -= mPreviousExtraOffset; mPreviousExtraOffset = mPreviousExtraOffset / mPreviousTransitionInfluence + mPreviousTransitionSpeed * duration; mPreviousTransitionInfluence = std::max(0.f, mPreviousTransitionInfluence - duration * mFocalPointTransitionSpeedCoef); mPreviousExtraOffset *= mPreviousTransitionInfluence; mFocalPointCurrentOffset += mPreviousExtraOffset; } osg::Vec2d delta = mFocalPointTargetOffset - mFocalPointCurrentOffset; if (delta.length2() > 0) { float coef = duration * (1.0 + 5.0 / delta.length()) * mFocalPointTransitionSpeedCoef * (1.0f - mPreviousTransitionInfluence); mFocalPointCurrentOffset += delta * std::min(coef, 1.0f); } else { mPreviousExtraOffset = osg::Vec2d(); mPreviousTransitionInfluence = 0.f; } mFocalPointTransitionSpeed = (mFocalPointCurrentOffset - oldOffset) / duration; } void Camera::toggleViewMode(bool force) { setMode(mFirstPersonView ? Mode::ThirdPerson : Mode::FirstPerson, force); } bool Camera::toggleVanityMode(bool enable) { if (!enable) setMode(mFirstPersonView ? Mode::FirstPerson : Mode::ThirdPerson, false); else if (mVanityAllowed) setMode(Mode::Vanity, false); return (mMode == Mode::Vanity) == enable; } void Camera::setSneakOffset(float offset) { mAnimation->setFirstPersonOffset(osg::Vec3f(0, 0, -offset)); } void Camera::setYaw(float angle, bool force) { if (!mLockYaw || force) mYaw = Misc::normalizeAngle(angle); if (force) mLockYaw = true; } void Camera::setPitch(float angle, bool force) { const float epsilon = 0.000001f; float limit = static_cast<float>(osg::PI_2) - epsilon; if (!mLockPitch || force) mPitch = std::clamp(angle, -limit, limit); if (force) mLockPitch = true; } void Camera::setStaticPosition(const osg::Vec3d& pos) { if (mMode != Mode::Static) throw std::runtime_error("setStaticPosition can be used only if camera is in Static mode"); mPosition = pos; } void Camera::setAnimation(NpcAnimation* anim) { mAnimation = anim; mProcessViewChange = true; } void Camera::processViewChange() { if (mTrackingPtr.isEmpty()) return; if (mMode == Mode::FirstPerson) { mAnimation->setViewMode(NpcAnimation::VM_FirstPerson); mTrackingNode = mAnimation->getNode("Camera"); if (!mTrackingNode) mTrackingNode = mAnimation->getNode("Head"); mHeightScale = 1.f; } else { mAnimation->setViewMode(NpcAnimation::VM_Normal); SceneUtil::PositionAttitudeTransform* transform = mTrackingPtr.getRefData().getBaseNode(); mTrackingNode = transform; if (transform) mHeightScale = transform->getScale().z(); else mHeightScale = 1.f; } mProcessViewChange = false; } void Camera::applyDeferredPreviewRotationToPlayer(float dt) { if (mMode != Mode::ThirdPerson || mTrackingPtr.isEmpty()) return; osg::Vec3f rot = mDeferredRotation; float delta = rot.normalize(); delta = std::min(delta, (delta + 1.f) * 3 * dt); rot *= delta; mDeferredRotation -= rot; if (mDeferredRotationDisabled) { mDeferredRotationDisabled = delta > 0.0001; rotateCameraToTrackingPtr(); return; } auto& movement = mTrackingPtr.getClass().getMovementSettings(mTrackingPtr); movement.mRotation[0] += rot.x(); movement.mRotation[1] += rot.y(); movement.mRotation[2] += rot.z(); if (std::abs(mDeferredRotation.z()) > 0.0001) { float s = std::sin(mDeferredRotation.z()); float c = std::cos(mDeferredRotation.z()); float x = movement.mPosition[0]; float y = movement.mPosition[1]; movement.mPosition[0] = x * c + y * s; movement.mPosition[1] = x * -s + y * c; } } void Camera::rotateCameraToTrackingPtr() { if (mMode == Mode::Static || mTrackingPtr.isEmpty()) return; setPitch(-mTrackingPtr.getRefData().getPosition().rot[0] - mDeferredRotation.x()); setYaw(-mTrackingPtr.getRefData().getPosition().rot[2] - mDeferredRotation.z()); } void Camera::instantTransition() { mSkipFocalPointTransition = true; mDeferredRotationDisabled = false; mDeferredRotation = osg::Vec3f(); rotateCameraToTrackingPtr(); } void Camera::calculateDeferredRotation() { if (mMode == Mode::Static) { mDeferredRotation = osg::Vec3f(); return; } MWWorld::Ptr ptr = mTrackingPtr; if (mMode == Mode::Preview || mMode == Mode::Vanity || ptr.isEmpty()) return; if (mFirstPersonView) { instantTransition(); return; } mDeferredRotation.x() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[0] - mPitch); mDeferredRotation.z() = Misc::normalizeAngle(-ptr.getRefData().getPosition().rot[2] - mYaw); if (!mDeferredRotationAllowed) mDeferredRotationDisabled = true; } }
14,892
C++
.cpp
386
29.401554
120
0.612318
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,390
effectmanager.cpp
OpenMW_openmw/apps/openmw/mwrender/effectmanager.cpp
#include "effectmanager.hpp" #include <osg/PositionAttitudeTransform> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/controller.hpp> #include "animation.hpp" #include "util.hpp" #include "vismask.hpp" #include <algorithm> namespace MWRender { EffectManager::EffectManager(osg::ref_ptr<osg::Group> parent, Resource::ResourceSystem* resourceSystem) : mParentNode(std::move(parent)) , mResourceSystem(resourceSystem) { } EffectManager::~EffectManager() { clear(); } void EffectManager::addEffect(VFS::Path::NormalizedView model, std::string_view textureOverride, const osg::Vec3f& worldPosition, float scale, bool isMagicVFX) { osg::ref_ptr<osg::Node> node = mResourceSystem->getSceneManager()->getInstance(model); node->setNodeMask(Mask_Effect); Effect effect; effect.mAnimTime = std::make_shared<EffectAnimationTime>(); SceneUtil::FindMaxControllerLengthVisitor findMaxLengthVisitor; node->accept(findMaxLengthVisitor); effect.mMaxControllerLength = findMaxLengthVisitor.getMaxLength(); osg::ref_ptr<osg::PositionAttitudeTransform> trans = new osg::PositionAttitudeTransform; trans->setPosition(worldPosition); trans->setScale(osg::Vec3f(scale, scale, scale)); trans->addChild(node); effect.mTransform = trans; SceneUtil::AssignControllerSourcesVisitor assignVisitor(effect.mAnimTime); node->accept(assignVisitor); if (isMagicVFX) overrideFirstRootTexture(textureOverride, mResourceSystem, *node); else overrideTexture(textureOverride, mResourceSystem, *node); mParentNode->addChild(trans); mEffects.push_back(std::move(effect)); } void EffectManager::update(float dt) { mEffects.erase(std::remove_if(mEffects.begin(), mEffects.end(), [dt, this](Effect& effect) { effect.mAnimTime->addTime(dt); const auto remove = effect.mAnimTime->getTime() >= effect.mMaxControllerLength; if (remove) mParentNode->removeChild(effect.mTransform); return remove; }), mEffects.end()); } void EffectManager::clear() { for (const auto& effect : mEffects) { mParentNode->removeChild(effect.mTransform); } mEffects.clear(); } }
2,646
C++
.cpp
65
31.123077
110
0.644922
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,391
distortion.cpp
OpenMW_openmw/apps/openmw/mwrender/distortion.cpp
#include "distortion.hpp" #include <osg/FrameBufferObject> #include "postprocessor.hpp" namespace MWRender { void DistortionCallback::drawImplementation( osgUtil::RenderBin* bin, osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous) { osg::State* state = renderInfo.getState(); size_t frameId = state->getFrameStamp()->getFrameNumber() % 2; PostProcessor* postProcessor = dynamic_cast<PostProcessor*>(renderInfo.getCurrentCamera()->getUserData()); if (!postProcessor || bin->getStage()->getFrameBufferObject() != postProcessor->getPrimaryFbo(frameId)) return; mFBO[frameId]->apply(*state); const osg::Texture* tex = mFBO[frameId]->getAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0).getTexture(); glViewport(0, 0, tex->getTextureWidth(), tex->getTextureHeight()); glClearColor(0.0, 0.0, 0.0, 1.0); glColorMask(true, true, true, true); state->haveAppliedAttribute(osg::StateAttribute::Type::COLORMASK); glClear(GL_COLOR_BUFFER_BIT); bin->drawImplementation(renderInfo, previous); tex = mOriginalFBO[frameId]->getAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0).getTexture(); glViewport(0, 0, tex->getTextureWidth(), tex->getTextureHeight()); mOriginalFBO[frameId]->apply(*state); } }
1,400
C++
.cpp
27
44.407407
120
0.693324
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,392
globalmap.cpp
OpenMW_openmw/apps/openmw/mwrender/globalmap.cpp
#include "globalmap.hpp" #include <osg/Geometry> #include <osg/Group> #include <osg/Image> #include <osg/TexEnvCombine> #include <osg/Texture2D> #include <osgDB/WriteFile> #include <components/files/memorystream.hpp> #include <components/settings/values.hpp> #include <components/debug/debuglog.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/sceneutil/workqueue.hpp> #include <components/esm3/globalmap.hpp> #include <components/esm3/loadland.hpp> #include "../mwbase/environment.hpp" #include "../mwworld/esmstore.hpp" #include "vismask.hpp" namespace { // Create a screen-aligned quad with given texture coordinates. // Assumes a top-left origin of the sampled image. osg::ref_ptr<osg::Geometry> createTexturedQuad( float leftTexCoord, float topTexCoord, float rightTexCoord, float bottomTexCoord) { osg::ref_ptr<osg::Geometry> geom = new osg::Geometry; osg::ref_ptr<osg::Vec3Array> verts = new osg::Vec3Array; verts->push_back(osg::Vec3f(-1, -1, 0)); verts->push_back(osg::Vec3f(-1, 1, 0)); verts->push_back(osg::Vec3f(1, 1, 0)); verts->push_back(osg::Vec3f(1, -1, 0)); geom->setVertexArray(verts); osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array; texcoords->push_back(osg::Vec2f(leftTexCoord, 1.f - bottomTexCoord)); texcoords->push_back(osg::Vec2f(leftTexCoord, 1.f - topTexCoord)); texcoords->push_back(osg::Vec2f(rightTexCoord, 1.f - topTexCoord)); texcoords->push_back(osg::Vec2f(rightTexCoord, 1.f - bottomTexCoord)); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1.f, 1.f, 1.f, 1.f)); geom->setColorArray(colors, osg::Array::BIND_OVERALL); geom->setTexCoordArray(0, texcoords, osg::Array::BIND_PER_VERTEX); geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4)); return geom; } class CameraUpdateGlobalCallback : public SceneUtil::NodeCallback<CameraUpdateGlobalCallback, osg::Camera*> { public: CameraUpdateGlobalCallback(MWRender::GlobalMap* parent) : mRendered(false) , mParent(parent) { } void operator()(osg::Camera* node, osg::NodeVisitor* nv) { if (mRendered) { if (mParent->copyResult(node, nv->getTraversalNumber())) { node->setNodeMask(0); mParent->markForRemoval(node); } return; } traverse(node, nv); mRendered = true; } private: bool mRendered; MWRender::GlobalMap* mParent; }; std::vector<char> writePng(const osg::Image& overlayImage) { std::ostringstream ostream; osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("png"); if (!readerwriter) { Log(Debug::Error) << "Error: Can't write map overlay: no png readerwriter found"; return std::vector<char>(); } osgDB::ReaderWriter::WriteResult result = readerwriter->writeImage(overlayImage, ostream); if (!result.success()) { Log(Debug::Warning) << "Error: Can't write map overlay: " << result.message() << " code " << result.status(); return std::vector<char>(); } std::string data = ostream.str(); return std::vector<char>(data.begin(), data.end()); } } namespace MWRender { class CreateMapWorkItem : public SceneUtil::WorkItem { public: CreateMapWorkItem(int width, int height, int minX, int minY, int maxX, int maxY, int cellSize, const MWWorld::Store<ESM::Land>& landStore) : mWidth(width) , mHeight(height) , mMinX(minX) , mMinY(minY) , mMaxX(maxX) , mMaxY(maxY) , mCellSize(cellSize) , mLandStore(landStore) { } void doWork() override { osg::ref_ptr<osg::Image> image = new osg::Image; image->allocateImage(mWidth, mHeight, 1, GL_RGB, GL_UNSIGNED_BYTE); unsigned char* data = image->data(); osg::ref_ptr<osg::Image> alphaImage = new osg::Image; alphaImage->allocateImage(mWidth, mHeight, 1, GL_ALPHA, GL_UNSIGNED_BYTE); unsigned char* alphaData = alphaImage->data(); for (int x = mMinX; x <= mMaxX; ++x) { for (int y = mMinY; y <= mMaxY; ++y) { const ESM::Land* land = mLandStore.search(x, y); for (int cellY = 0; cellY < mCellSize; ++cellY) { for (int cellX = 0; cellX < mCellSize; ++cellX) { int vertexX = static_cast<int>(float(cellX) / float(mCellSize) * 9); int vertexY = static_cast<int>(float(cellY) / float(mCellSize) * 9); int texelX = (x - mMinX) * mCellSize + cellX; int texelY = (y - mMinY) * mCellSize + cellY; unsigned char r, g, b; float y2 = 0; if (land && (land->mDataTypes & ESM::Land::DATA_WNAM)) y2 = land->mWnam[vertexY * 9 + vertexX] / 128.f; else y2 = SCHAR_MIN / 128.f; if (y2 < 0) { r = static_cast<unsigned char>(14 * y2 + 38); g = static_cast<unsigned char>(20 * y2 + 56); b = static_cast<unsigned char>(18 * y2 + 51); } else if (y2 < 0.3f) { if (y2 < 0.1f) y2 *= 8.f; else { y2 -= 0.1f; y2 += 0.8f; } r = static_cast<unsigned char>(66 - 32 * y2); g = static_cast<unsigned char>(48 - 23 * y2); b = static_cast<unsigned char>(33 - 16 * y2); } else { y2 -= 0.3f; y2 *= 1.428f; r = static_cast<unsigned char>(34 - 29 * y2); g = static_cast<unsigned char>(25 - 20 * y2); b = static_cast<unsigned char>(17 - 12 * y2); } data[texelY * mWidth * 3 + texelX * 3] = r; data[texelY * mWidth * 3 + texelX * 3 + 1] = g; data[texelY * mWidth * 3 + texelX * 3 + 2] = b; alphaData[texelY * mWidth + texelX] = (y2 < 0) ? static_cast<unsigned char>(0) : static_cast<unsigned char>(255); } } } } mBaseTexture = new osg::Texture2D; mBaseTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mBaseTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mBaseTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); mBaseTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); mBaseTexture->setImage(image); mBaseTexture->setResizeNonPowerOfTwoHint(false); mAlphaTexture = new osg::Texture2D; mAlphaTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mAlphaTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mAlphaTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); mAlphaTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); mAlphaTexture->setImage(alphaImage); mAlphaTexture->setResizeNonPowerOfTwoHint(false); mOverlayImage = new osg::Image; mOverlayImage->allocateImage(mWidth, mHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE); assert(mOverlayImage->isDataContiguous()); memset(mOverlayImage->data(), 0, mOverlayImage->getTotalSizeInBytes()); mOverlayTexture = new osg::Texture2D; mOverlayTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mOverlayTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mOverlayTexture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); mOverlayTexture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); mOverlayTexture->setResizeNonPowerOfTwoHint(false); mOverlayTexture->setInternalFormat(GL_RGBA); mOverlayTexture->setTextureSize(mWidth, mHeight); } int mWidth, mHeight; int mMinX, mMinY, mMaxX, mMaxY; int mCellSize; const MWWorld::Store<ESM::Land>& mLandStore; osg::ref_ptr<osg::Texture2D> mBaseTexture; osg::ref_ptr<osg::Texture2D> mAlphaTexture; osg::ref_ptr<osg::Image> mOverlayImage; osg::ref_ptr<osg::Texture2D> mOverlayTexture; }; struct GlobalMap::WritePng final : public SceneUtil::WorkItem { osg::ref_ptr<const osg::Image> mOverlayImage; std::vector<char> mImageData; explicit WritePng(osg::ref_ptr<const osg::Image> overlayImage) : mOverlayImage(std::move(overlayImage)) { } void doWork() override { mImageData = writePng(*mOverlayImage); } }; GlobalMap::GlobalMap(osg::Group* root, SceneUtil::WorkQueue* workQueue) : mRoot(root) , mWorkQueue(workQueue) , mWidth(0) , mHeight(0) , mMinX(0) , mMaxX(0) , mMinY(0) , mMaxY(0) { } GlobalMap::~GlobalMap() { for (auto& camera : mCamerasPendingRemoval) removeCamera(camera); for (auto& camera : mActiveCameras) removeCamera(camera); if (mWorkItem) mWorkItem->waitTillDone(); } void GlobalMap::render() { const MWWorld::ESMStore& esmStore = *MWBase::Environment::get().getESMStore(); // get the size of the world MWWorld::Store<ESM::Cell>::iterator it = esmStore.get<ESM::Cell>().extBegin(); for (; it != esmStore.get<ESM::Cell>().extEnd(); ++it) { if (it->getGridX() < mMinX) mMinX = it->getGridX(); if (it->getGridX() > mMaxX) mMaxX = it->getGridX(); if (it->getGridY() < mMinY) mMinY = it->getGridY(); if (it->getGridY() > mMaxY) mMaxY = it->getGridY(); } const int cellSize = Settings::map().mGlobalMapCellSize; mWidth = cellSize * (mMaxX - mMinX + 1); mHeight = cellSize * (mMaxY - mMinY + 1); mWorkItem = new CreateMapWorkItem(mWidth, mHeight, mMinX, mMinY, mMaxX, mMaxY, cellSize, esmStore.get<ESM::Land>()); mWorkQueue->addWorkItem(mWorkItem); } void GlobalMap::worldPosToImageSpace(float x, float z, float& imageX, float& imageY) { imageX = (float(x / float(Constants::CellSizeInUnits) - mMinX) / (mMaxX - mMinX + 1)) * getWidth(); imageY = (1.f - float(z / float(Constants::CellSizeInUnits) - mMinY) / (mMaxY - mMinY + 1)) * getHeight(); } void GlobalMap::requestOverlayTextureUpdate(int x, int y, int width, int height, osg::ref_ptr<osg::Texture2D> texture, bool clear, bool cpuCopy, float srcLeft, float srcTop, float srcRight, float srcBottom) { osg::ref_ptr<osg::Camera> camera(new osg::Camera); camera->setNodeMask(Mask_RenderToTexture); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->setViewMatrix(osg::Matrix::identity()); camera->setProjectionMatrix(osg::Matrix::identity()); camera->setProjectionResizePolicy(osg::Camera::FIXED); camera->setRenderOrder(osg::Camera::PRE_RENDER, 1); // Make sure the global map is rendered after the local map y = mHeight - y - height; // convert top-left origin to bottom-left camera->setViewport(x, y, width, height); if (clear) { camera->setClearMask(GL_COLOR_BUFFER_BIT); camera->setClearColor(osg::Vec4(0, 0, 0, 0)); } else camera->setClearMask(GL_NONE); camera->setUpdateCallback(new CameraUpdateGlobalCallback(this)); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT, osg::Camera::PIXEL_BUFFER_RTT); camera->attach(osg::Camera::COLOR_BUFFER, mOverlayTexture); // no need for a depth buffer camera->setImplicitBufferAttachmentMask(osg::DisplaySettings::IMPLICIT_COLOR_BUFFER_ATTACHMENT); if (cpuCopy) { // Attach an image to copy the render back to the CPU when finished osg::ref_ptr<osg::Image> image(new osg::Image); image->setPixelFormat(mOverlayImage->getPixelFormat()); image->setDataType(mOverlayImage->getDataType()); camera->attach(osg::Camera::COLOR_BUFFER, image); ImageDest imageDest; imageDest.mImage = image; imageDest.mX = x; imageDest.mY = y; mPendingImageDest[camera] = std::move(imageDest); } // Create a quad rendering the updated texture if (texture) { osg::ref_ptr<osg::Geometry> geom = createTexturedQuad(srcLeft, srcTop, srcRight, srcBottom); osg::ref_ptr<osg::Depth> depth = new SceneUtil::AutoDepth; depth->setWriteMask(false); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setAttribute(depth); stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); if (mAlphaTexture) { osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array; float x1 = x / static_cast<float>(mWidth); float x2 = (x + width) / static_cast<float>(mWidth); float y1 = y / static_cast<float>(mHeight); float y2 = (y + height) / static_cast<float>(mHeight); texcoords->push_back(osg::Vec2f(x1, y1)); texcoords->push_back(osg::Vec2f(x1, y2)); texcoords->push_back(osg::Vec2f(x2, y2)); texcoords->push_back(osg::Vec2f(x2, y1)); geom->setTexCoordArray(1, texcoords, osg::Array::BIND_PER_VERTEX); stateset->setTextureAttributeAndModes(1, mAlphaTexture, osg::StateAttribute::ON); osg::ref_ptr<osg::TexEnvCombine> texEnvCombine = new osg::TexEnvCombine; texEnvCombine->setCombine_RGB(osg::TexEnvCombine::REPLACE); texEnvCombine->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); stateset->setTextureAttributeAndModes(1, texEnvCombine); } camera->addChild(geom); } mRoot->addChild(camera); mActiveCameras.push_back(camera); } void GlobalMap::exploreCell(int cellX, int cellY, osg::ref_ptr<osg::Texture2D> localMapTexture) { ensureLoaded(); if (!localMapTexture) return; const int cellSize = Settings::map().mGlobalMapCellSize; const int originX = (cellX - mMinX) * cellSize; // +1 because we want the top left corner of the cell, not the bottom left const int originY = (cellY - mMinY + 1) * cellSize; if (cellX > mMaxX || cellX < mMinX || cellY > mMaxY || cellY < mMinY) return; requestOverlayTextureUpdate( originX, mHeight - originY, cellSize, cellSize, std::move(localMapTexture), false, true); } void GlobalMap::clear() { ensureLoaded(); memset(mOverlayImage->data(), 0, mOverlayImage->getTotalSizeInBytes()); mPendingImageDest.clear(); // just push a Camera to clear the FBO, instead of setImage()/dirty() // easier, since we don't need to worry about synchronizing access :) requestOverlayTextureUpdate(0, 0, mWidth, mHeight, osg::ref_ptr<osg::Texture2D>(), true, false); } void GlobalMap::write(ESM::GlobalMap& map) { ensureLoaded(); map.mBounds.mMinX = mMinX; map.mBounds.mMaxX = mMaxX; map.mBounds.mMinY = mMinY; map.mBounds.mMaxY = mMaxY; if (mWritePng != nullptr) { mWritePng->waitTillDone(); map.mImageData = std::move(mWritePng->mImageData); mWritePng = nullptr; return; } map.mImageData = writePng(*mOverlayImage); } struct Box { int mLeft, mTop, mRight, mBottom; Box(int left, int top, int right, int bottom) : mLeft(left) , mTop(top) , mRight(right) , mBottom(bottom) { } bool operator==(const Box& other) const { return mLeft == other.mLeft && mTop == other.mTop && mRight == other.mRight && mBottom == other.mBottom; } }; void GlobalMap::read(ESM::GlobalMap& map) { ensureLoaded(); const ESM::GlobalMap::Bounds& bounds = map.mBounds; if (bounds.mMaxX - bounds.mMinX < 0) return; if (bounds.mMaxY - bounds.mMinY < 0) return; if (bounds.mMinX > bounds.mMaxX || bounds.mMinY > bounds.mMaxY) throw std::runtime_error("invalid map bounds"); if (map.mImageData.empty()) return; Files::IMemStream istream(map.mImageData.data(), map.mImageData.size()); osgDB::ReaderWriter* readerwriter = osgDB::Registry::instance()->getReaderWriterForExtension("png"); if (!readerwriter) { Log(Debug::Error) << "Error: Can't read map overlay: no png readerwriter found"; return; } osgDB::ReaderWriter::ReadResult result = readerwriter->readImage(istream); if (!result.success()) { Log(Debug::Error) << "Error: Can't read map overlay: " << result.message() << " code " << result.status(); return; } osg::ref_ptr<osg::Image> image = result.getImage(); int imageWidth = image->s(); int imageHeight = image->t(); int xLength = (bounds.mMaxX - bounds.mMinX + 1); int yLength = (bounds.mMaxY - bounds.mMinY + 1); // Size of one cell in image space int cellImageSizeSrc = imageWidth / xLength; if (int(imageHeight / yLength) != cellImageSizeSrc) throw std::runtime_error("cell size must be quadratic"); // If cell bounds of the currently loaded content and the loaded savegame do not match, // we need to resize source/dest boxes to accommodate // This means nonexisting cells will be dropped silently const int cellImageSizeDst = Settings::map().mGlobalMapCellSize; // Completely off-screen? -> no need to blit anything if (bounds.mMaxX < mMinX || bounds.mMaxY < mMinY || bounds.mMinX > mMaxX || bounds.mMinY > mMaxY) return; int leftDiff = (mMinX - bounds.mMinX); int topDiff = (bounds.mMaxY - mMaxY); int rightDiff = (bounds.mMaxX - mMaxX); int bottomDiff = (mMinY - bounds.mMinY); Box srcBox(std::max(0, leftDiff * cellImageSizeSrc), std::max(0, topDiff * cellImageSizeSrc), std::min(imageWidth, imageWidth - rightDiff * cellImageSizeSrc), std::min(imageHeight, imageHeight - bottomDiff * cellImageSizeSrc)); Box destBox(std::max(0, -leftDiff * cellImageSizeDst), std::max(0, -topDiff * cellImageSizeDst), std::min(mWidth, mWidth + rightDiff * cellImageSizeDst), std::min(mHeight, mHeight + bottomDiff * cellImageSizeDst)); osg::ref_ptr<osg::Texture2D> texture(new osg::Texture2D); texture->setImage(image); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); texture->setResizeNonPowerOfTwoHint(false); if (srcBox == destBox && imageWidth == mWidth && imageHeight == mHeight) { mOverlayImage = image; requestOverlayTextureUpdate(0, 0, mWidth, mHeight, std::move(texture), true, false); } else { // Dimensions don't match. This could mean a changed map region, or a changed map resolution. // In the latter case, we'll want filtering. // Create a RTT Camera and draw the image onto mOverlayImage in the next frame. requestOverlayTextureUpdate(destBox.mLeft, destBox.mTop, destBox.mRight - destBox.mLeft, destBox.mBottom - destBox.mTop, std::move(texture), true, true, srcBox.mLeft / float(imageWidth), srcBox.mTop / float(imageHeight), srcBox.mRight / float(imageWidth), srcBox.mBottom / float(imageHeight)); } } osg::ref_ptr<osg::Texture2D> GlobalMap::getBaseTexture() { ensureLoaded(); return mBaseTexture; } osg::ref_ptr<osg::Texture2D> GlobalMap::getOverlayTexture() { ensureLoaded(); return mOverlayTexture; } void GlobalMap::ensureLoaded() { if (mWorkItem) { mWorkItem->waitTillDone(); mOverlayImage = mWorkItem->mOverlayImage; mBaseTexture = mWorkItem->mBaseTexture; mAlphaTexture = mWorkItem->mAlphaTexture; mOverlayTexture = mWorkItem->mOverlayTexture; requestOverlayTextureUpdate(0, 0, mWidth, mHeight, osg::ref_ptr<osg::Texture2D>(), true, false); mWorkItem = nullptr; } } bool GlobalMap::copyResult(osg::Camera* camera, unsigned int frame) { ImageDestMap::iterator it = mPendingImageDest.find(camera); if (it == mPendingImageDest.end()) return true; else { ImageDest& imageDest = it->second; if (imageDest.mFrameDone == 0) imageDest.mFrameDone = frame + 2; // wait an extra frame to ensure the draw thread has completed its frame. if (imageDest.mFrameDone > frame) { ++it; return false; } mOverlayImage->copySubImage(imageDest.mX, imageDest.mY, 0, imageDest.mImage); mPendingImageDest.erase(it); return true; } } void GlobalMap::markForRemoval(osg::Camera* camera) { CameraVector::iterator found = std::find(mActiveCameras.begin(), mActiveCameras.end(), camera); if (found == mActiveCameras.end()) { Log(Debug::Error) << "Error: GlobalMap trying to remove an inactive camera"; return; } mActiveCameras.erase(found); mCamerasPendingRemoval.push_back(camera); } void GlobalMap::cleanupCameras() { for (auto& camera : mCamerasPendingRemoval) removeCamera(camera); mCamerasPendingRemoval.clear(); } void GlobalMap::removeCamera(osg::Camera* cam) { cam->removeChildren(0, cam->getNumChildren()); mRoot->removeChild(cam); } void GlobalMap::asyncWritePng() { if (mOverlayImage == nullptr) return; // Use deep copy to avoid any sychronization mWritePng = new WritePng(new osg::Image(*mOverlayImage, osg::CopyOp::DEEP_COPY_ALL)); mWorkQueue->addWorkItem(mWritePng, /*front=*/true); } }
24,711
C++
.cpp
539
33.983302
119
0.575063
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,393
renderingmanager.cpp
OpenMW_openmw/apps/openmw/mwrender/renderingmanager.cpp
#include "renderingmanager.hpp" #include <cstdlib> #include <limits> #include <osg/ClipControl> #include <osg/ComputeBoundsVisitor> #include <osg/Fog> #include <osg/Group> #include <osg/Light> #include <osg/LightModel> #include <osg/Material> #include <osg/PolygonMode> #include <osg/UserDataContainer> #include <osgUtil/LineSegmentIntersector> #include <osgViewer/Viewer> #include <components/nifosg/nifloader.hpp> #include <components/debug/debuglog.hpp> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include <components/resource/imagemanager.hpp> #include <components/resource/keyframemanager.hpp> #include <components/resource/resourcesystem.hpp> #include <components/shader/removedalphafunc.hpp> #include <components/shader/shadermanager.hpp> #include <components/settings/values.hpp> #include <components/sceneutil/cullsafeboundsvisitor.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/rtt.hpp> #include <components/sceneutil/shadow.hpp> #include <components/sceneutil/statesetupdater.hpp> #include <components/sceneutil/visitor.hpp> #include <components/sceneutil/workqueue.hpp> #include <components/sceneutil/writescene.hpp> #include <components/misc/constants.hpp> #include <components/terrain/quadtreeworld.hpp> #include <components/terrain/terraingrid.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm4/loadcell.hpp> #include <components/debug/debugdraw.hpp> #include <components/detournavigator/navigator.hpp> #include <components/detournavigator/navmeshcacheitem.hpp> #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/groundcoverstore.hpp" #include "../mwworld/scene.hpp" #include "../mwgui/postprocessorhud.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "actorspaths.hpp" #include "camera.hpp" #include "effectmanager.hpp" #include "fogmanager.hpp" #include "groundcover.hpp" #include "navmesh.hpp" #include "npcanimation.hpp" #include "objectpaging.hpp" #include "pathgrid.hpp" #include "postprocessor.hpp" #include "recastmesh.hpp" #include "screenshotmanager.hpp" #include "sky.hpp" #include "terrainstorage.hpp" #include "util.hpp" #include "vismask.hpp" #include "water.hpp" namespace MWRender { class PerViewUniformStateUpdater final : public SceneUtil::StateSetUpdater { public: PerViewUniformStateUpdater(Resource::SceneManager* sceneManager) : mSceneManager(sceneManager) { mOpaqueTextureUnit = mSceneManager->getShaderManager().reserveGlobalTextureUnits( Shader::ShaderManager::Slot::OpaqueDepthTexture); } void setDefaults(osg::StateSet* stateset) override { stateset->addUniform(new osg::Uniform("projectionMatrix", osg::Matrixf{})); if (mSkyRTT) stateset->addUniform(new osg::Uniform("sky", mSkyTextureUnit)); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { stateset->getUniform("projectionMatrix")->set(mProjectionMatrix); if (mSkyRTT && nv->getVisitorType() == osg::NodeVisitor::CULL_VISITOR) { osg::Texture* skyTexture = mSkyRTT->getColorTexture(static_cast<osgUtil::CullVisitor*>(nv)); stateset->setTextureAttribute( mSkyTextureUnit, skyTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } stateset->setTextureAttribute(mOpaqueTextureUnit, mSceneManager->getOpaqueDepthTex(nv->getTraversalNumber()), osg::StateAttribute::ON); } void applyLeft(osg::StateSet* stateset, osgUtil::CullVisitor* nv) override { stateset->getUniform("projectionMatrix")->set(getEyeProjectionMatrix(0)); } void applyRight(osg::StateSet* stateset, osgUtil::CullVisitor* nv) override { stateset->getUniform("projectionMatrix")->set(getEyeProjectionMatrix(1)); } void setProjectionMatrix(const osg::Matrixf& projectionMatrix) { mProjectionMatrix = projectionMatrix; } const osg::Matrixf& getProjectionMatrix() const { return mProjectionMatrix; } void enableSkyRTT(int skyTextureUnit, SceneUtil::RTTNode* skyRTT) { mSkyTextureUnit = skyTextureUnit; mSkyRTT = skyRTT; } private: osg::Matrixf getEyeProjectionMatrix(int view) { return Stereo::Manager::instance().computeEyeProjection(view, SceneUtil::AutoDepth::isReversed()); } osg::Matrixf mProjectionMatrix; int mSkyTextureUnit = -1; SceneUtil::RTTNode* mSkyRTT = nullptr; Resource::SceneManager* mSceneManager; int mOpaqueTextureUnit = -1; }; class SharedUniformStateUpdater : public SceneUtil::StateSetUpdater { public: SharedUniformStateUpdater() : mNear(0.f) , mFar(0.f) , mWindSpeed(0.f) , mSkyBlendingStartCoef(Settings::fog().mSkyBlendingStart) { } void setDefaults(osg::StateSet* stateset) override { stateset->addUniform(new osg::Uniform("near", 0.f)); stateset->addUniform(new osg::Uniform("far", 0.f)); stateset->addUniform(new osg::Uniform("skyBlendingStart", 0.f)); stateset->addUniform(new osg::Uniform("screenRes", osg::Vec2f{})); stateset->addUniform(new osg::Uniform("isReflection", false)); stateset->addUniform(new osg::Uniform("windSpeed", 0.0f)); stateset->addUniform(new osg::Uniform("playerPos", osg::Vec3f(0.f, 0.f, 0.f))); stateset->addUniform(new osg::Uniform("useTreeAnim", false)); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { stateset->getUniform("near")->set(mNear); stateset->getUniform("far")->set(mFar); stateset->getUniform("skyBlendingStart")->set(mFar * mSkyBlendingStartCoef); stateset->getUniform("screenRes")->set(mScreenRes); stateset->getUniform("windSpeed")->set(mWindSpeed); stateset->getUniform("playerPos")->set(mPlayerPos); } void setNear(float near) { mNear = near; } void setFar(float far) { mFar = far; } void setScreenRes(float width, float height) { mScreenRes = osg::Vec2f(width, height); } void setWindSpeed(float windSpeed) { mWindSpeed = windSpeed; } void setPlayerPos(osg::Vec3f playerPos) { mPlayerPos = playerPos; } private: float mNear; float mFar; float mWindSpeed; float mSkyBlendingStartCoef; osg::Vec3f mPlayerPos; osg::Vec2f mScreenRes; }; class StateUpdater : public SceneUtil::StateSetUpdater { public: StateUpdater() : mFogStart(0.f) , mFogEnd(0.f) , mWireframe(false) { } void setDefaults(osg::StateSet* stateset) override { osg::LightModel* lightModel = new osg::LightModel; stateset->setAttribute(lightModel, osg::StateAttribute::ON); osg::Fog* fog = new osg::Fog; fog->setMode(osg::Fog::LINEAR); stateset->setAttributeAndModes(fog, osg::StateAttribute::ON); if (mWireframe) { osg::PolygonMode* polygonmode = new osg::PolygonMode; polygonmode->setMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE); stateset->setAttributeAndModes(polygonmode, osg::StateAttribute::ON); } else stateset->removeAttribute(osg::StateAttribute::POLYGONMODE); } void apply(osg::StateSet* stateset, osg::NodeVisitor*) override { osg::LightModel* lightModel = static_cast<osg::LightModel*>(stateset->getAttribute(osg::StateAttribute::LIGHTMODEL)); lightModel->setAmbientIntensity(mAmbientColor); osg::Fog* fog = static_cast<osg::Fog*>(stateset->getAttribute(osg::StateAttribute::FOG)); fog->setColor(mFogColor); fog->setStart(mFogStart); fog->setEnd(mFogEnd); } void setAmbientColor(const osg::Vec4f& col) { mAmbientColor = col; } void setFogColor(const osg::Vec4f& col) { mFogColor = col; } void setFogStart(float start) { mFogStart = start; } void setFogEnd(float end) { mFogEnd = end; } void setWireframe(bool wireframe) { if (mWireframe != wireframe) { mWireframe = wireframe; reset(); } } bool getWireframe() const { return mWireframe; } private: osg::Vec4f mAmbientColor; osg::Vec4f mFogColor; float mFogStart; float mFogEnd; bool mWireframe; }; class PreloadCommonAssetsWorkItem : public SceneUtil::WorkItem { public: PreloadCommonAssetsWorkItem(Resource::ResourceSystem* resourceSystem) : mResourceSystem(resourceSystem) { } void doWork() override { try { for (const VFS::Path::Normalized& v : mModels) mResourceSystem->getSceneManager()->getTemplate(v); for (const VFS::Path::Normalized& v : mTextures) mResourceSystem->getImageManager()->getImage(v); for (const VFS::Path::Normalized& v : mKeyframes) mResourceSystem->getKeyframeManager()->get(v); } catch (const std::exception& e) { Log(Debug::Warning) << "Failed to preload common assets: " << e.what(); } } std::vector<VFS::Path::Normalized> mModels; std::vector<VFS::Path::Normalized> mTextures; std::vector<VFS::Path::Normalized> mKeyframes; private: Resource::ResourceSystem* mResourceSystem; }; RenderingManager::RenderingManager(osgViewer::Viewer* viewer, osg::ref_ptr<osg::Group> rootNode, Resource::ResourceSystem* resourceSystem, SceneUtil::WorkQueue* workQueue, DetourNavigator::Navigator& navigator, const MWWorld::GroundcoverStore& groundcoverStore, SceneUtil::UnrefQueue& unrefQueue) : mSkyBlending(Settings::fog().mSkyBlending) , mViewer(viewer) , mRootNode(rootNode) , mResourceSystem(resourceSystem) , mWorkQueue(workQueue) , mNavigator(navigator) , mNightEyeFactor(0.f) // TODO: Near clip should not need to be bounded like this, but too small values break OSG shadow calculations // CPU-side. See issue: #6072 , mNearClip(Settings::camera().mNearClip) , mViewDistance(Settings::camera().mViewingDistance) , mFieldOfViewOverridden(false) , mFieldOfViewOverride(0.f) , mFieldOfView(Settings::camera().mFieldOfView) , mFirstPersonFieldOfView(Settings::camera().mFirstPersonFieldOfView) , mGroundCoverStore(groundcoverStore) { bool reverseZ = SceneUtil::AutoDepth::isReversed(); const SceneUtil::LightingMethod lightingMethod = Settings::shaders().mLightingMethod; resourceSystem->getSceneManager()->setParticleSystemMask(MWRender::Mask_ParticleSystem); // Figure out which pipeline must be used by default and inform the user bool forceShaders = Settings::shaders().mForceShaders; { std::vector<std::string> requesters; if (!forceShaders) { if (Settings::fog().mRadialFog) requesters.push_back("radial fog"); if (Settings::fog().mExponentialFog) requesters.push_back("exponential fog"); if (mSkyBlending) requesters.push_back("sky blending"); if (Settings::shaders().mSoftParticles) requesters.push_back("soft particles"); if (Settings::shadows().mEnableShadows) requesters.push_back("shadows"); if (lightingMethod != SceneUtil::LightingMethod::FFP) requesters.push_back("lighting method"); if (reverseZ) requesters.push_back("reverse-Z depth buffer"); if (Stereo::getMultiview()) requesters.push_back("stereo multiview"); if (!requesters.empty()) forceShaders = true; } if (forceShaders) { std::string message = "Using rendering with shaders by default"; if (requesters.empty()) { message += " (forced)"; } else { message += ", requested by:"; for (size_t i = 0; i < requesters.size(); i++) message += "\n - " + requesters[i]; } Log(Debug::Info) << message; } else { Log(Debug::Info) << "Using fixed-function rendering by default"; } } resourceSystem->getSceneManager()->setForceShaders(forceShaders); // FIXME: calling dummy method because terrain needs to know whether lighting is clamped resourceSystem->getSceneManager()->setClampLighting(Settings::shaders().mClampLighting); resourceSystem->getSceneManager()->setAutoUseNormalMaps(Settings::shaders().mAutoUseObjectNormalMaps); resourceSystem->getSceneManager()->setNormalMapPattern(Settings::shaders().mNormalMapPattern); resourceSystem->getSceneManager()->setNormalHeightMapPattern(Settings::shaders().mNormalHeightMapPattern); resourceSystem->getSceneManager()->setAutoUseSpecularMaps(Settings::shaders().mAutoUseObjectSpecularMaps); resourceSystem->getSceneManager()->setSpecularMapPattern(Settings::shaders().mSpecularMapPattern); resourceSystem->getSceneManager()->setApplyLightingToEnvMaps( Settings::shaders().mApplyLightingToEnvironmentMaps); resourceSystem->getSceneManager()->setConvertAlphaTestToAlphaToCoverage(shouldAddMSAAIntermediateTarget()); resourceSystem->getSceneManager()->setAdjustCoverageForAlphaTest( Settings::shaders().mAdjustCoverageForAlphaTest); // Let LightManager choose which backend to use based on our hint. For methods besides legacy lighting, this // depends on support for various OpenGL extensions. osg::ref_ptr<SceneUtil::LightManager> sceneRoot = new SceneUtil::LightManager(SceneUtil::LightSettings{ .mLightingMethod = lightingMethod, .mMaxLights = Settings::shaders().mMaxLights, .mMaximumLightDistance = Settings::shaders().mMaximumLightDistance, .mLightFadeStart = Settings::shaders().mLightFadeStart, .mLightBoundsMultiplier = Settings::shaders().mLightBoundsMultiplier, }); resourceSystem->getSceneManager()->setLightingMethod(sceneRoot->getLightingMethod()); resourceSystem->getSceneManager()->setSupportedLightingMethods(sceneRoot->getSupportedLightingMethods()); sceneRoot->setLightingMask(Mask_Lighting); mSceneRoot = sceneRoot; sceneRoot->setStartLight(1); sceneRoot->setNodeMask(Mask_Scene); sceneRoot->setName("Scene Root"); int shadowCastingTraversalMask = Mask_Scene; if (Settings::shadows().mActorShadows) shadowCastingTraversalMask |= Mask_Actor; if (Settings::shadows().mPlayerShadows) shadowCastingTraversalMask |= Mask_Player; int indoorShadowCastingTraversalMask = shadowCastingTraversalMask; if (Settings::shadows().mObjectShadows) shadowCastingTraversalMask |= (Mask_Object | Mask_Static); if (Settings::shadows().mTerrainShadows) shadowCastingTraversalMask |= Mask_Terrain; mShadowManager = std::make_unique<SceneUtil::ShadowManager>(sceneRoot, mRootNode, shadowCastingTraversalMask, indoorShadowCastingTraversalMask, Mask_Terrain | Mask_Object | Mask_Static, Settings::shadows(), mResourceSystem->getSceneManager()->getShaderManager()); Shader::ShaderManager::DefineMap shadowDefines = mShadowManager->getShadowDefines(Settings::shadows()); Shader::ShaderManager::DefineMap lightDefines = sceneRoot->getLightDefines(); Shader::ShaderManager::DefineMap globalDefines = mResourceSystem->getSceneManager()->getShaderManager().getGlobalDefines(); for (auto itr = shadowDefines.begin(); itr != shadowDefines.end(); itr++) globalDefines[itr->first] = itr->second; globalDefines["forcePPL"] = Settings::shaders().mForcePerPixelLighting ? "1" : "0"; globalDefines["clamp"] = Settings::shaders().mClampLighting ? "1" : "0"; globalDefines["preLightEnv"] = Settings::shaders().mApplyLightingToEnvironmentMaps ? "1" : "0"; globalDefines["classicFalloff"] = Settings::shaders().mClassicFalloff ? "1" : "0"; const bool exponentialFog = Settings::fog().mExponentialFog; globalDefines["radialFog"] = (exponentialFog || Settings::fog().mRadialFog) ? "1" : "0"; globalDefines["exponentialFog"] = exponentialFog ? "1" : "0"; globalDefines["skyBlending"] = mSkyBlending ? "1" : "0"; globalDefines["waterRefraction"] = "0"; globalDefines["useGPUShader4"] = "0"; globalDefines["useOVR_multiview"] = "0"; globalDefines["numViews"] = "1"; globalDefines["disableNormals"] = "1"; for (auto itr = lightDefines.begin(); itr != lightDefines.end(); itr++) globalDefines[itr->first] = itr->second; // Refactor this at some point - most shaders don't care about these defines const float groundcoverDistance = Settings::groundcover().mRenderingDistance; globalDefines["groundcoverFadeStart"] = std::to_string(groundcoverDistance * 0.9f); globalDefines["groundcoverFadeEnd"] = std::to_string(groundcoverDistance); globalDefines["groundcoverStompMode"] = std::to_string(Settings::groundcover().mStompMode); globalDefines["groundcoverStompIntensity"] = std::to_string(Settings::groundcover().mStompIntensity); globalDefines["reverseZ"] = reverseZ ? "1" : "0"; // It is unnecessary to stop/start the viewer as no frames are being rendered yet. mResourceSystem->getSceneManager()->getShaderManager().setGlobalDefines(globalDefines); mNavMesh = std::make_unique<NavMesh>(mRootNode, mWorkQueue, Settings::navigator().mEnableNavMeshRender, Settings::navigator().mNavMeshRenderMode); mActorsPaths = std::make_unique<ActorsPaths>(mRootNode, Settings::navigator().mEnableAgentsPathsRender); mRecastMesh = std::make_unique<RecastMesh>(mRootNode, Settings::navigator().mEnableRecastMeshRender); mPathgrid = std::make_unique<Pathgrid>(mRootNode); mObjects = std::make_unique<Objects>(mResourceSystem, sceneRoot, unrefQueue); if (getenv("OPENMW_DONT_PRECOMPILE") == nullptr) { mViewer->setIncrementalCompileOperation(new osgUtil::IncrementalCompileOperation); mViewer->getIncrementalCompileOperation()->setTargetFrameRate(Settings::cells().mTargetFramerate); } mDebugDraw = new Debug::DebugDrawer(mResourceSystem->getSceneManager()->getShaderManager()); mDebugDraw->setNodeMask(Mask_Debug); sceneRoot->addChild(mDebugDraw); mResourceSystem->getSceneManager()->setIncrementalCompileOperation(mViewer->getIncrementalCompileOperation()); mEffectManager = std::make_unique<EffectManager>(sceneRoot, mResourceSystem); const std::string& normalMapPattern = Settings::shaders().mNormalMapPattern; const std::string& heightMapPattern = Settings::shaders().mNormalHeightMapPattern; const std::string& specularMapPattern = Settings::shaders().mTerrainSpecularMapPattern; const bool useTerrainNormalMaps = Settings::shaders().mAutoUseTerrainNormalMaps; const bool useTerrainSpecularMaps = Settings::shaders().mAutoUseTerrainSpecularMaps; mTerrainStorage = std::make_unique<TerrainStorage>(mResourceSystem, normalMapPattern, heightMapPattern, useTerrainNormalMaps, specularMapPattern, useTerrainSpecularMaps); WorldspaceChunkMgr& chunkMgr = getWorldspaceChunkMgr(ESM::Cell::sDefaultWorldspaceId); mTerrain = chunkMgr.mTerrain.get(); mGroundcover = chunkMgr.mGroundcover.get(); mObjectPaging = chunkMgr.mObjectPaging.get(); mStateUpdater = new StateUpdater; sceneRoot->addUpdateCallback(mStateUpdater); mSharedUniformStateUpdater = new SharedUniformStateUpdater(); rootNode->addUpdateCallback(mSharedUniformStateUpdater); mPerViewUniformStateUpdater = new PerViewUniformStateUpdater(mResourceSystem->getSceneManager()); rootNode->addCullCallback(mPerViewUniformStateUpdater); mPostProcessor = new PostProcessor(*this, viewer, mRootNode, resourceSystem->getVFS()); resourceSystem->getSceneManager()->setOpaqueDepthTex( mPostProcessor->getTexture(PostProcessor::Tex_OpaqueDepth, 0), mPostProcessor->getTexture(PostProcessor::Tex_OpaqueDepth, 1)); resourceSystem->getSceneManager()->setSoftParticles(Settings::shaders().mSoftParticles); resourceSystem->getSceneManager()->setSupportsNormalsRT(mPostProcessor->getSupportsNormalsRT()); resourceSystem->getSceneManager()->setWeatherParticleOcclusion(Settings::shaders().mWeatherParticleOcclusion); // water goes after terrain for correct waterculling order mWater = std::make_unique<Water>( sceneRoot->getParent(0), sceneRoot, mResourceSystem, mViewer->getIncrementalCompileOperation()); mCamera = std::make_unique<Camera>(mViewer->getCamera()); mScreenshotManager = std::make_unique<ScreenshotManager>(viewer); mViewer->setLightingMode(osgViewer::View::NO_LIGHT); osg::ref_ptr<osg::LightSource> source = new osg::LightSource; source->setNodeMask(Mask_Lighting); mSunLight = new osg::Light; source->setLight(mSunLight); mSunLight->setDiffuse(osg::Vec4f(0, 0, 0, 1)); mSunLight->setAmbient(osg::Vec4f(0, 0, 0, 1)); mSunLight->setSpecular(osg::Vec4f(0, 0, 0, 0)); mSunLight->setConstantAttenuation(1.f); sceneRoot->setSunlight(mSunLight); sceneRoot->addChild(source); sceneRoot->getOrCreateStateSet()->setMode(GL_CULL_FACE, osg::StateAttribute::ON); sceneRoot->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::ON); sceneRoot->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON); osg::ref_ptr<osg::Material> defaultMat(new osg::Material); defaultMat->setColorMode(osg::Material::OFF); defaultMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); defaultMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); defaultMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 0.f)); sceneRoot->getOrCreateStateSet()->setAttribute(defaultMat); sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("emissiveMult", 1.f)); sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("specStrength", 1.f)); sceneRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("distortionStrength", 0.f)); resourceSystem->getSceneManager()->setUpNormalsRTForStateSet(sceneRoot->getOrCreateStateSet(), true); mFog = std::make_unique<FogManager>(); mSky = std::make_unique<SkyManager>( sceneRoot, mRootNode, mViewer->getCamera(), resourceSystem->getSceneManager(), mSkyBlending); if (mSkyBlending) { int skyTextureUnit = mResourceSystem->getSceneManager()->getShaderManager().reserveGlobalTextureUnits( Shader::ShaderManager::Slot::SkyTexture); mPerViewUniformStateUpdater->enableSkyRTT(skyTextureUnit, mSky->getSkyRTT()); } source->setStateSetModes(*mRootNode->getOrCreateStateSet(), osg::StateAttribute::ON); osg::Camera::CullingMode cullingMode = osg::Camera::DEFAULT_CULLING | osg::Camera::FAR_PLANE_CULLING; if (!Settings::camera().mSmallFeatureCulling) cullingMode &= ~(osg::CullStack::SMALL_FEATURE_CULLING); else { mViewer->getCamera()->setSmallFeatureCullingPixelSize(Settings::camera().mSmallFeatureCullingPixelSize); cullingMode |= osg::CullStack::SMALL_FEATURE_CULLING; } mViewer->getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); mViewer->getCamera()->setCullingMode(cullingMode); mViewer->getCamera()->setName(Constants::SceneCamera); auto mask = ~(Mask_UpdateVisitor | Mask_SimpleWater); MWBase::Environment::get().getWindowManager()->setCullMask(mask); NifOsg::Loader::setHiddenNodeMask(Mask_UpdateVisitor); NifOsg::Loader::setIntersectionDisabledNodeMask(Mask_Effect); Nif::Reader::setLoadUnsupportedFiles(Settings::models().mLoadUnsupportedNifFiles); Nif::Reader::setWriteNifDebugLog(Settings::models().mWriteNifDebugLog); mStateUpdater->setFogEnd(mViewDistance); // Hopefully, anything genuinely requiring the default alpha func of GL_ALWAYS explicitly sets it mRootNode->getOrCreateStateSet()->setAttribute(Shader::RemovedAlphaFunc::getInstance(GL_ALWAYS)); // The transparent renderbin sets alpha testing on because that was faster on old GPUs. It's now slower and // breaks things. mRootNode->getOrCreateStateSet()->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF); if (reverseZ) { osg::ref_ptr<osg::ClipControl> clipcontrol = new osg::ClipControl(osg::ClipControl::LOWER_LEFT, osg::ClipControl::ZERO_TO_ONE); mRootNode->getOrCreateStateSet()->setAttributeAndModes(new SceneUtil::AutoDepth, osg::StateAttribute::ON); mRootNode->getOrCreateStateSet()->setAttributeAndModes(clipcontrol, osg::StateAttribute::ON); } SceneUtil::setCameraClearDepth(mViewer->getCamera()); updateProjectionMatrix(); mViewer->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } RenderingManager::~RenderingManager() { // let background loading thread finish before we delete anything else mWorkQueue = nullptr; } osgUtil::IncrementalCompileOperation* RenderingManager::getIncrementalCompileOperation() { return mViewer->getIncrementalCompileOperation(); } MWRender::Objects& RenderingManager::getObjects() { return *mObjects.get(); } Resource::ResourceSystem* RenderingManager::getResourceSystem() { return mResourceSystem; } SceneUtil::WorkQueue* RenderingManager::getWorkQueue() { return mWorkQueue.get(); } Terrain::World* RenderingManager::getTerrain() { return mTerrain; } void RenderingManager::preloadCommonAssets() { osg::ref_ptr<PreloadCommonAssetsWorkItem> workItem(new PreloadCommonAssetsWorkItem(mResourceSystem)); mSky->listAssetsToPreload(workItem->mModels, workItem->mTextures); mWater->listAssetsToPreload(workItem->mTextures); workItem->mModels.push_back(Settings::models().mXbaseanim); workItem->mModels.push_back(Settings::models().mXbaseanim1st); workItem->mModels.push_back(Settings::models().mXbaseanimfemale); workItem->mModels.push_back(Settings::models().mXargonianswimkna); workItem->mKeyframes.push_back(Settings::models().mXbaseanimkf); workItem->mKeyframes.push_back(Settings::models().mXbaseanim1stkf); workItem->mKeyframes.push_back(Settings::models().mXbaseanimfemalekf); workItem->mKeyframes.push_back(Settings::models().mXargonianswimknakf); workItem->mTextures.emplace_back("textures/_land_default.dds"); mWorkQueue->addWorkItem(std::move(workItem)); } double RenderingManager::getReferenceTime() const { return mViewer->getFrameStamp()->getReferenceTime(); } SceneUtil::LightManager* RenderingManager::getLightRoot() { return mSceneRoot.get(); } void RenderingManager::setNightEyeFactor(float factor) { if (factor != mNightEyeFactor) { mNightEyeFactor = factor; updateAmbient(); } } void RenderingManager::setAmbientColour(const osg::Vec4f& colour) { mAmbientColor = colour; updateAmbient(); } int RenderingManager::skyGetMasserPhase() const { return mSky->getMasserPhase(); } int RenderingManager::skyGetSecundaPhase() const { return mSky->getSecundaPhase(); } void RenderingManager::skySetMoonColour(bool red) { mSky->setMoonColour(red); } void RenderingManager::configureAmbient(const MWWorld::Cell& cell) { bool isInterior = !cell.isExterior() && !cell.isQuasiExterior(); bool needsAdjusting = false; if (mResourceSystem->getSceneManager()->getLightingMethod() != SceneUtil::LightingMethod::FFP) needsAdjusting = isInterior && !Settings::shaders().mClassicFalloff; osg::Vec4f ambient = SceneUtil::colourFromRGB(cell.getMood().mAmbiantColor); if (needsAdjusting) { constexpr float pR = 0.2126; constexpr float pG = 0.7152; constexpr float pB = 0.0722; // we already work in linear RGB so no conversions are needed for the luminosity function float relativeLuminance = pR * ambient.r() + pG * ambient.g() + pB * ambient.b(); const float minimumAmbientLuminance = Settings::shaders().mMinimumInteriorBrightness; if (relativeLuminance < minimumAmbientLuminance) { // brighten ambient so it reaches the minimum threshold but no more, we want to mess with content data // as least we can if (ambient.r() == 0.f && ambient.g() == 0.f && ambient.b() == 0.f) ambient = osg::Vec4( minimumAmbientLuminance, minimumAmbientLuminance, minimumAmbientLuminance, ambient.a()); else ambient *= minimumAmbientLuminance / relativeLuminance; } } setAmbientColour(ambient); osg::Vec4f diffuse = SceneUtil::colourFromRGB(cell.getMood().mDirectionalColor); setSunColour(diffuse, diffuse, 1.f); // This is total nonsense but it's what Morrowind uses static const osg::Vec4f interiorSunPos = osg::Vec4f(-1.f, osg::DegreesToRadians(45.f), osg::DegreesToRadians(45.f), 0.f); mPostProcessor->getStateUpdater()->setSunPos(interiorSunPos, false); mSunLight->setPosition(interiorSunPos); } void RenderingManager::setSunColour(const osg::Vec4f& diffuse, const osg::Vec4f& specular, float sunVis) { // need to wrap this in a StateUpdater? mSunLight->setDiffuse(diffuse); mSunLight->setSpecular(osg::Vec4f(specular.x(), specular.y(), specular.z(), specular.w() * sunVis)); mPostProcessor->getStateUpdater()->setSunColor(diffuse); mPostProcessor->getStateUpdater()->setSunVis(sunVis); } void RenderingManager::setSunDirection(const osg::Vec3f& direction) { osg::Vec3 position = direction * -1; // need to wrap this in a StateUpdater? mSunLight->setPosition(osg::Vec4(position.x(), position.y(), position.z(), 0)); // The sun is not synchronized with the sunlight because sunlight origin can't reach the horizon // This is based on exterior sun orbit and won't make sense for interiors, see WeatherManager::update position.z() = 400.f - std::abs(position.x()); mSky->setSunDirection(position); mPostProcessor->getStateUpdater()->setSunPos(osg::Vec4f(position, 0.f), mNight); } void RenderingManager::addCell(const MWWorld::CellStore* store) { mPathgrid->addCell(store); mWater->changeCell(store); if (store->getCell()->isExterior()) { enableTerrain(true, store->getCell()->getWorldSpace()); mTerrain->loadCell(store->getCell()->getGridX(), store->getCell()->getGridY()); } } void RenderingManager::removeCell(const MWWorld::CellStore* store) { mPathgrid->removeCell(store); mActorsPaths->removeCell(store); mObjects->removeCell(store); if (store->getCell()->isExterior()) { getWorldspaceChunkMgr(store->getCell()->getWorldSpace()) .mTerrain->unloadCell(store->getCell()->getGridX(), store->getCell()->getGridY()); } mWater->removeCell(store); } void RenderingManager::enableTerrain(bool enable, ESM::RefId worldspace) { if (!enable) mWater->setCullCallback(nullptr); else { WorldspaceChunkMgr& newChunks = getWorldspaceChunkMgr(worldspace); if (newChunks.mTerrain.get() != mTerrain) { mTerrain->enable(false); mTerrain = newChunks.mTerrain.get(); mGroundcover = newChunks.mGroundcover.get(); mObjectPaging = newChunks.mObjectPaging.get(); } } mTerrain->enable(enable); } void RenderingManager::setSkyEnabled(bool enabled) { mSky->setEnabled(enabled); if (enabled) mShadowManager->enableOutdoorMode(); else mShadowManager->enableIndoorMode(Settings::shadows()); mPostProcessor->getStateUpdater()->setIsInterior(!enabled); } bool RenderingManager::toggleBorders() { bool borders = !mTerrain->getBordersVisible(); mTerrain->setBordersVisible(borders); return borders; } bool RenderingManager::toggleRenderMode(RenderMode mode) { if (mode == Render_CollisionDebug || mode == Render_Pathgrid) return mPathgrid->toggleRenderMode(mode); else if (mode == Render_Wireframe) { bool wireframe = !mStateUpdater->getWireframe(); mStateUpdater->setWireframe(wireframe); return wireframe; } else if (mode == Render_Water) { return mWater->toggle(); } else if (mode == Render_Scene) { const auto wm = MWBase::Environment::get().getWindowManager(); unsigned int mask = wm->getCullMask(); bool enabled = !(mask & sToggleWorldMask); if (enabled) mask |= sToggleWorldMask; else mask &= ~sToggleWorldMask; mWater->showWorld(enabled); wm->setCullMask(mask); return enabled; } else if (mode == Render_NavMesh) { return mNavMesh->toggle(); } else if (mode == Render_ActorsPaths) { return mActorsPaths->toggle(); } else if (mode == Render_RecastMesh) { return mRecastMesh->toggle(); } return false; } void RenderingManager::configureFog(const MWWorld::Cell& cell) { mFog->configure(mViewDistance, cell); } void RenderingManager::configureFog( float fogDepth, float underwaterFog, float dlFactor, float dlOffset, const osg::Vec4f& color) { mFog->configure(mViewDistance, fogDepth, underwaterFog, dlFactor, dlOffset, color); } SkyManager* RenderingManager::getSkyManager() { return mSky.get(); } void RenderingManager::update(float dt, bool paused) { reportStats(); mResourceSystem->getSceneManager()->getShaderManager().update(*mViewer); float rainIntensity = mSky->getPrecipitationAlpha(); mWater->setRainIntensity(rainIntensity); mWater->setRainRipplesEnabled(mSky->getRainRipplesEnabled()); mWater->update(dt, paused); if (!paused) { mEffectManager->update(dt); mSky->update(dt); const MWWorld::Ptr& player = mPlayerAnimation->getPtr(); osg::Vec3f playerPos(player.getRefData().getPosition().asVec3()); float windSpeed = mSky->getBaseWindSpeed(); mSharedUniformStateUpdater->setWindSpeed(windSpeed); mSharedUniformStateUpdater->setPlayerPos(playerPos); } updateNavMesh(); updateRecastMesh(); if (mUpdateProjectionMatrix) { mUpdateProjectionMatrix = false; updateProjectionMatrix(); } mCamera->update(dt, paused); bool isUnderwater = mWater->isUnderwater(mCamera->getPosition()); float fogStart = mFog->getFogStart(isUnderwater); float fogEnd = mFog->getFogEnd(isUnderwater); osg::Vec4f fogColor = mFog->getFogColor(isUnderwater); mStateUpdater->setFogStart(fogStart); mStateUpdater->setFogEnd(fogEnd); setFogColor(fogColor); auto world = MWBase::Environment::get().getWorld(); const auto& stateUpdater = mPostProcessor->getStateUpdater(); stateUpdater->setFogRange(fogStart, fogEnd); stateUpdater->setNearFar(mNearClip, mViewDistance); stateUpdater->setIsUnderwater(isUnderwater); stateUpdater->setFogColor(fogColor); stateUpdater->setGameHour(world->getTimeStamp().getHour()); stateUpdater->setWeatherId(world->getCurrentWeather()); stateUpdater->setNextWeatherId(world->getNextWeather()); stateUpdater->setWeatherTransition(world->getWeatherTransition()); stateUpdater->setWindSpeed(world->getWindSpeed()); stateUpdater->setSkyColor(mSky->getSkyColor()); mPostProcessor->setUnderwaterFlag(isUnderwater); } void RenderingManager::updatePlayerPtr(const MWWorld::Ptr& ptr) { if (mPlayerAnimation.get()) { setupPlayer(ptr); mPlayerAnimation->updatePtr(ptr); } mCamera->attachTo(ptr); } void RenderingManager::removePlayer(const MWWorld::Ptr& player) { mWater->removeEmitter(player); } void RenderingManager::rotateObject(const MWWorld::Ptr& ptr, const osg::Quat& rot) { if (ptr == mCamera->getTrackingPtr() && !mCamera->isVanityOrPreviewModeEnabled()) { mCamera->rotateCameraToTrackingPtr(); } ptr.getRefData().getBaseNode()->setAttitude(rot); } void RenderingManager::moveObject(const MWWorld::Ptr& ptr, const osg::Vec3f& pos) { ptr.getRefData().getBaseNode()->setPosition(pos); } void RenderingManager::scaleObject(const MWWorld::Ptr& ptr, const osg::Vec3f& scale) { ptr.getRefData().getBaseNode()->setScale(scale); if (ptr == mCamera->getTrackingPtr()) // update height of camera mCamera->processViewChange(); } void RenderingManager::removeObject(const MWWorld::Ptr& ptr) { mActorsPaths->remove(ptr); mObjects->removeObject(ptr); mWater->removeEmitter(ptr); } void RenderingManager::setWaterEnabled(bool enabled) { mWater->setEnabled(enabled); mSky->setWaterEnabled(enabled); mPostProcessor->getStateUpdater()->setIsWaterEnabled(enabled); } void RenderingManager::setWaterHeight(float height) { mWater->setCullCallback(mTerrain->getHeightCullCallback(height, Mask_Water)); mWater->setHeight(height); mSky->setWaterHeight(height); mPostProcessor->getStateUpdater()->setWaterHeight(height); } void RenderingManager::screenshot(osg::Image* image, int w, int h) { mScreenshotManager->screenshot(image, w, h); } osg::Vec4f RenderingManager::getScreenBounds(const osg::BoundingBox& worldbb) { if (!worldbb.valid()) return osg::Vec4f(); osg::Matrix viewProj = mViewer->getCamera()->getViewMatrix() * mViewer->getCamera()->getProjectionMatrix(); float min_x = 1.0f, max_x = 0.0f, min_y = 1.0f, max_y = 0.0f; for (int i = 0; i < 8; ++i) { osg::Vec3f corner = worldbb.corner(i); corner = corner * viewProj; float x = (corner.x() + 1.f) * 0.5f; float y = (corner.y() - 1.f) * (-0.5f); if (x < min_x) min_x = x; if (x > max_x) max_x = x; if (y < min_y) min_y = y; if (y > max_y) max_y = y; } return osg::Vec4f(min_x, min_y, max_x, max_y); } RenderingManager::RayResult getIntersectionResult(osgUtil::LineSegmentIntersector* intersector, const osg::ref_ptr<osgUtil::IntersectionVisitor>& visitor, std::span<const MWWorld::Ptr> ignoreList = {}) { constexpr auto nonObjectWorldMask = Mask_Terrain | Mask_Water; RenderingManager::RayResult result; result.mHit = false; result.mRatio = 0; if (!intersector->containsIntersections()) return result; auto test = [&](const osgUtil::LineSegmentIntersector::Intersection& intersection) { PtrHolder* ptrHolder = nullptr; std::vector<RefnumMarker*> refnumMarkers; bool hitNonObjectWorld = false; for (osg::NodePath::const_iterator it = intersection.nodePath.begin(); it != intersection.nodePath.end(); ++it) { const auto& nodeMask = (*it)->getNodeMask(); if (!hitNonObjectWorld) hitNonObjectWorld = nodeMask & nonObjectWorldMask; osg::UserDataContainer* userDataContainer = (*it)->getUserDataContainer(); if (!userDataContainer) continue; for (unsigned int i = 0; i < userDataContainer->getNumUserObjects(); ++i) { if (PtrHolder* p = dynamic_cast<PtrHolder*>(userDataContainer->getUserObject(i))) { if (std::find(ignoreList.begin(), ignoreList.end(), p->mPtr) == ignoreList.end()) { ptrHolder = p; } } if (RefnumMarker* r = dynamic_cast<RefnumMarker*>(userDataContainer->getUserObject(i))) { refnumMarkers.push_back(r); } } } if (ptrHolder) result.mHitObject = ptrHolder->mPtr; unsigned int vertexCounter = 0; for (unsigned int i = 0; i < refnumMarkers.size(); ++i) { unsigned int intersectionIndex = intersection.indexList.empty() ? 0 : intersection.indexList[0]; if (!refnumMarkers[i]->mNumVertices || (intersectionIndex >= vertexCounter && intersectionIndex < vertexCounter + refnumMarkers[i]->mNumVertices)) { auto it = std::find_if( ignoreList.begin(), ignoreList.end(), [target = refnumMarkers[i]->mRefnum](const auto& ptr) { return target == ptr.getCellRef().getRefNum(); }); if (it == ignoreList.end()) { result.mHitRefnum = refnumMarkers[i]->mRefnum; } break; } vertexCounter += refnumMarkers[i]->mNumVertices; } if (!result.mHitObject.isEmpty() || result.mHitRefnum.isSet() || hitNonObjectWorld) { result.mHit = true; result.mHitPointWorld = intersection.getWorldIntersectPoint(); result.mHitNormalWorld = intersection.getWorldIntersectNormal(); result.mRatio = intersection.ratio; } }; if (ignoreList.empty() || intersector->getIntersectionLimit() != osgUtil::LineSegmentIntersector::NO_LIMIT) { test(intersector->getFirstIntersection()); } else { for (const auto& intersection : intersector->getIntersections()) { test(intersection); if (result.mHit) { break; } } } return result; } class IntersectionVisitorWithIgnoreList : public osgUtil::IntersectionVisitor { public: bool skipTransform(osg::Transform& transform) { if (mContainsPagedRefs) return false; osg::UserDataContainer* userDataContainer = transform.getUserDataContainer(); if (!userDataContainer) return false; for (unsigned int i = 0; i < userDataContainer->getNumUserObjects(); ++i) { if (PtrHolder* p = dynamic_cast<PtrHolder*>(userDataContainer->getUserObject(i))) { if (std::find(mIgnoreList.begin(), mIgnoreList.end(), p->mPtr) != mIgnoreList.end()) { return true; } } } return false; } void apply(osg::Transform& transform) override { if (skipTransform(transform)) { return; } osgUtil::IntersectionVisitor::apply(transform); } void setIgnoreList(std::span<const MWWorld::Ptr> ignoreList) { mIgnoreList = ignoreList; } void setContainsPagedRefs(bool contains) { mContainsPagedRefs = contains; } private: std::span<const MWWorld::Ptr> mIgnoreList; bool mContainsPagedRefs = false; }; osg::ref_ptr<osgUtil::IntersectionVisitor> RenderingManager::getIntersectionVisitor( osgUtil::Intersector* intersector, bool ignorePlayer, bool ignoreActors, std::span<const MWWorld::Ptr> ignoreList) { if (!mIntersectionVisitor) mIntersectionVisitor = new IntersectionVisitorWithIgnoreList; mIntersectionVisitor->setIgnoreList(ignoreList); mIntersectionVisitor->setContainsPagedRefs(false); MWWorld::Scene* worldScene = MWBase::Environment::get().getWorldScene(); for (const auto& ptr : ignoreList) { if (worldScene->isPagedRef(ptr)) { mIntersectionVisitor->setContainsPagedRefs(true); intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::NO_LIMIT); break; } } mIntersectionVisitor->setTraversalNumber(mViewer->getFrameStamp()->getFrameNumber()); mIntersectionVisitor->setFrameStamp(mViewer->getFrameStamp()); mIntersectionVisitor->setIntersector(intersector); unsigned int mask = ~0u; mask &= ~(Mask_RenderToTexture | Mask_Sky | Mask_Debug | Mask_Effect | Mask_Water | Mask_SimpleWater | Mask_Groundcover); if (ignorePlayer) mask &= ~(Mask_Player); if (ignoreActors) mask &= ~(Mask_Actor | Mask_Player); mIntersectionVisitor->setTraversalMask(mask); return mIntersectionVisitor; } RenderingManager::RayResult RenderingManager::castRay(const osg::Vec3f& origin, const osg::Vec3f& dest, bool ignorePlayer, bool ignoreActors, std::span<const MWWorld::Ptr> ignoreList) { osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector( new osgUtil::LineSegmentIntersector(osgUtil::LineSegmentIntersector::MODEL, origin, dest)); intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::LIMIT_NEAREST); mRootNode->accept(*getIntersectionVisitor(intersector, ignorePlayer, ignoreActors, ignoreList)); return getIntersectionResult(intersector, mIntersectionVisitor, ignoreList); } RenderingManager::RayResult RenderingManager::castCameraToViewportRay( const float nX, const float nY, float maxDistance, bool ignorePlayer, bool ignoreActors) { osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector(new osgUtil::LineSegmentIntersector( osgUtil::LineSegmentIntersector::PROJECTION, nX * 2.f - 1.f, nY * (-2.f) + 1.f)); osg::Vec3d dist(0.f, 0.f, -maxDistance); dist = dist * mViewer->getCamera()->getProjectionMatrix(); osg::Vec3d end = intersector->getEnd(); end.z() = dist.z(); intersector->setEnd(end); intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::LIMIT_NEAREST); mViewer->getCamera()->accept(*getIntersectionVisitor(intersector, ignorePlayer, ignoreActors)); return getIntersectionResult(intersector, mIntersectionVisitor); } void RenderingManager::updatePtr(const MWWorld::Ptr& old, const MWWorld::Ptr& updated) { mObjects->updatePtr(old, updated); mActorsPaths->updatePtr(old, updated); } void RenderingManager::spawnEffect(VFS::Path::NormalizedView model, std::string_view texture, const osg::Vec3f& worldPosition, float scale, bool isMagicVFX) { mEffectManager->addEffect(model, texture, worldPosition, scale, isMagicVFX); } void RenderingManager::notifyWorldSpaceChanged() { mEffectManager->clear(); mWater->clearRipples(); } void RenderingManager::clear() { mSky->setMoonColour(false); notifyWorldSpaceChanged(); if (mObjectPaging) mObjectPaging->clear(); } MWRender::Animation* RenderingManager::getAnimation(const MWWorld::Ptr& ptr) { if (mPlayerAnimation.get() && ptr == mPlayerAnimation->getPtr()) return mPlayerAnimation.get(); return mObjects->getAnimation(ptr); } const MWRender::Animation* RenderingManager::getAnimation(const MWWorld::ConstPtr& ptr) const { if (mPlayerAnimation.get() && ptr == mPlayerAnimation->getPtr()) return mPlayerAnimation.get(); return mObjects->getAnimation(ptr); } PostProcessor* RenderingManager::getPostProcessor() { return mPostProcessor; } void RenderingManager::setupPlayer(const MWWorld::Ptr& player) { if (!mPlayerNode) { mPlayerNode = new SceneUtil::PositionAttitudeTransform; mPlayerNode->setNodeMask(Mask_Player); mPlayerNode->setName("Player Root"); mSceneRoot->addChild(mPlayerNode); } mPlayerNode->setUserDataContainer(new osg::DefaultUserDataContainer); mPlayerNode->getUserDataContainer()->addUserObject(new PtrHolder(player)); player.getRefData().setBaseNode(mPlayerNode); mWater->removeEmitter(player); mWater->addEmitter(player); } void RenderingManager::renderPlayer(const MWWorld::Ptr& player) { mPlayerAnimation = new NpcAnimation(player, player.getRefData().getBaseNode(), mResourceSystem, 0, NpcAnimation::VM_Normal, mFirstPersonFieldOfView); mCamera->setAnimation(mPlayerAnimation.get()); mCamera->attachTo(player); } void RenderingManager::rebuildPtr(const MWWorld::Ptr& ptr) { NpcAnimation* anim = nullptr; if (ptr == mPlayerAnimation->getPtr()) anim = mPlayerAnimation.get(); else anim = dynamic_cast<NpcAnimation*>(mObjects->getAnimation(ptr)); if (anim) { anim->rebuild(); if (mCamera->getTrackingPtr() == ptr) { mCamera->attachTo(ptr); mCamera->setAnimation(anim); } } } void RenderingManager::addWaterRippleEmitter(const MWWorld::Ptr& ptr) { mWater->addEmitter(ptr); } void RenderingManager::removeWaterRippleEmitter(const MWWorld::Ptr& ptr) { mWater->removeEmitter(ptr); } void RenderingManager::emitWaterRipple(const osg::Vec3f& pos) { mWater->emitRipple(pos); } void RenderingManager::updateProjectionMatrix() { if (mNearClip < 0.0f) throw std::runtime_error("Near clip is less than zero"); if (mViewDistance < mNearClip) throw std::runtime_error("Viewing distance is less than near clip"); const double width = Settings::video().mResolutionX; const double height = Settings::video().mResolutionY; double aspect = (height == 0.0) ? 1.0 : width / height; float fov = mFieldOfView; if (mFieldOfViewOverridden) fov = mFieldOfViewOverride; mViewer->getCamera()->setProjectionMatrixAsPerspective(fov, aspect, mNearClip, mViewDistance); if (SceneUtil::AutoDepth::isReversed()) { mPerViewUniformStateUpdater->setProjectionMatrix( SceneUtil::getReversedZProjectionMatrixAsPerspective(fov, aspect, mNearClip, mViewDistance)); } else mPerViewUniformStateUpdater->setProjectionMatrix(mViewer->getCamera()->getProjectionMatrix()); mSharedUniformStateUpdater->setNear(mNearClip); mSharedUniformStateUpdater->setFar(mViewDistance); if (Stereo::getStereo()) { auto res = Stereo::Manager::instance().eyeResolution(); mSharedUniformStateUpdater->setScreenRes(res.x(), res.y()); Stereo::Manager::instance().setMasterProjectionMatrix(mPerViewUniformStateUpdater->getProjectionMatrix()); } else { mSharedUniformStateUpdater->setScreenRes(width, height); } // Since our fog is not radial yet, we should take FOV in account, otherwise terrain near viewing distance may // disappear. Limit FOV here just for sure, otherwise viewing distance can be too high. float distanceMult = std::cos(osg::DegreesToRadians(std::min(fov, 140.f)) / 2.f); mTerrain->setViewDistance(mViewDistance * (distanceMult ? 1.f / distanceMult : 1.f)); if (mPostProcessor) { mPostProcessor->getStateUpdater()->setProjectionMatrix(mPerViewUniformStateUpdater->getProjectionMatrix()); mPostProcessor->getStateUpdater()->setFov(fov); } } void RenderingManager::setScreenRes(int width, int height) { mSharedUniformStateUpdater->setScreenRes(width, height); } void RenderingManager::updateTextureFiltering() { mViewer->stopThreading(); mResourceSystem->getSceneManager()->setFilterSettings(Settings::general().mTextureMagFilter, Settings::general().mTextureMinFilter, Settings::general().mTextureMipmap, Settings::general().mAnisotropy); mTerrain->updateTextureFiltering(); mWater->processChangedSettings({}); mViewer->startThreading(); } void RenderingManager::updateAmbient() { osg::Vec4f color = mAmbientColor; if (mNightEyeFactor > 0.f) color += osg::Vec4f(0.7, 0.7, 0.7, 0.0) * mNightEyeFactor; mPostProcessor->getStateUpdater()->setAmbientColor(color); mStateUpdater->setAmbientColor(color); } void RenderingManager::setFogColor(const osg::Vec4f& color) { mViewer->getCamera()->setClearColor(color); mStateUpdater->setFogColor(color); } RenderingManager::WorldspaceChunkMgr& RenderingManager::getWorldspaceChunkMgr(ESM::RefId worldspace) { auto existingChunkMgr = mWorldspaceChunks.find(worldspace); if (existingChunkMgr != mWorldspaceChunks.end()) return existingChunkMgr->second; RenderingManager::WorldspaceChunkMgr newChunkMgr; const float lodFactor = Settings::terrain().mLodFactor; const bool groundcover = Settings::groundcover().mEnabled && worldspace == ESM::Cell::sDefaultWorldspaceId; const bool distantTerrain = Settings::terrain().mDistantTerrain; const double expiryDelay = Settings::cells().mCacheExpiryDelay; if (distantTerrain || groundcover) { const int compMapResolution = Settings::terrain().mCompositeMapResolution; const int compMapPower = Settings::terrain().mCompositeMapLevel; const float compMapLevel = std::pow(2, compMapPower); const int vertexLodMod = Settings::terrain().mVertexLodMod; const float maxCompGeometrySize = Settings::terrain().mMaxCompositeGeometrySize; const bool debugChunks = Settings::terrain().mDebugChunks; auto quadTreeWorld = std::make_unique<Terrain::QuadTreeWorld>(mSceneRoot, mRootNode, mResourceSystem, mTerrainStorage.get(), Mask_Terrain, Mask_PreCompile, Mask_Debug, compMapResolution, compMapLevel, lodFactor, vertexLodMod, maxCompGeometrySize, debugChunks, worldspace, expiryDelay); if (Settings::terrain().mObjectPaging) { newChunkMgr.mObjectPaging = std::make_unique<ObjectPaging>(mResourceSystem->getSceneManager(), worldspace); quadTreeWorld->addChunkManager(newChunkMgr.mObjectPaging.get()); mResourceSystem->addResourceManager(newChunkMgr.mObjectPaging.get()); } if (groundcover) { const float groundcoverDistance = Settings::groundcover().mRenderingDistance; const float density = Settings::groundcover().mDensity; newChunkMgr.mGroundcover = std::make_unique<Groundcover>( mResourceSystem->getSceneManager(), density, groundcoverDistance, mGroundCoverStore); quadTreeWorld->addChunkManager(newChunkMgr.mGroundcover.get()); mResourceSystem->addResourceManager(newChunkMgr.mGroundcover.get()); } newChunkMgr.mTerrain = std::move(quadTreeWorld); } else newChunkMgr.mTerrain = std::make_unique<Terrain::TerrainGrid>(mSceneRoot, mRootNode, mResourceSystem, mTerrainStorage.get(), Mask_Terrain, worldspace, expiryDelay, Mask_PreCompile, Mask_Debug); newChunkMgr.mTerrain->setTargetFrameRate(Settings::cells().mTargetFramerate); float distanceMult = std::cos(osg::DegreesToRadians(std::min(mFieldOfView, 140.f)) / 2.f); newChunkMgr.mTerrain->setViewDistance(mViewDistance * (distanceMult ? 1.f / distanceMult : 1.f)); newChunkMgr.mTerrain->enableHeightCullCallback(Settings::terrain().mWaterCulling); return mWorldspaceChunks.emplace(worldspace, std::move(newChunkMgr)).first->second; } void RenderingManager::reportStats() const { osg::Stats* stats = mViewer->getViewerStats(); unsigned int frameNumber = mViewer->getFrameStamp()->getFrameNumber(); if (stats->collectStats("resource")) { mTerrain->reportStats(frameNumber, stats); } } void RenderingManager::processChangedSettings(const Settings::CategorySettingVector& changed) { // Only perform a projection matrix update once if a relevant setting is changed. bool updateProjection = false; for (Settings::CategorySettingVector::const_iterator it = changed.begin(); it != changed.end(); ++it) { if (it->first == "Camera" && it->second == "field of view") { mFieldOfView = Settings::camera().mFieldOfView; updateProjection = true; } else if (it->first == "Video" && (it->second == "resolution x" || it->second == "resolution y")) { updateProjection = true; } else if (it->first == "Camera" && it->second == "viewing distance") { setViewDistance(Settings::camera().mViewingDistance); } else if (it->first == "General" && (it->second == "texture filter" || it->second == "texture mipmap" || it->second == "anisotropy")) { updateTextureFiltering(); } else if (it->first == "Water") { mWater->processChangedSettings(changed); } else if (it->first == "Shaders" && it->second == "minimum interior brightness") { if (MWMechanics::getPlayer().isInCell()) configureAmbient(*MWMechanics::getPlayer().getCell()->getCell()); } else if (it->first == "Shaders" && (it->second == "force per pixel lighting" || it->second == "classic falloff")) { mViewer->stopThreading(); auto defines = mResourceSystem->getSceneManager()->getShaderManager().getGlobalDefines(); defines["forcePPL"] = Settings::shaders().mForcePerPixelLighting ? "1" : "0"; defines["classicFalloff"] = Settings::shaders().mClassicFalloff ? "1" : "0"; mResourceSystem->getSceneManager()->getShaderManager().setGlobalDefines(defines); if (MWMechanics::getPlayer().isInCell() && it->second == "classic falloff") configureAmbient(*MWMechanics::getPlayer().getCell()->getCell()); mViewer->startThreading(); } else if (it->first == "Shaders" && (it->second == "light bounds multiplier" || it->second == "maximum light distance" || it->second == "light fade start" || it->second == "max lights")) { auto* lightManager = getLightRoot(); lightManager->processChangedSettings(Settings::shaders().mLightBoundsMultiplier, Settings::shaders().mMaximumLightDistance, Settings::shaders().mLightFadeStart); if (it->second == "max lights" && !lightManager->usingFFP()) { mViewer->stopThreading(); lightManager->updateMaxLights(Settings::shaders().mMaxLights); auto defines = mResourceSystem->getSceneManager()->getShaderManager().getGlobalDefines(); for (const auto& [name, key] : lightManager->getLightDefines()) defines[name] = key; mResourceSystem->getSceneManager()->getShaderManager().setGlobalDefines(defines); mStateUpdater->reset(); mViewer->startThreading(); } } else if (it->first == "Post Processing" && it->second == "enabled") { if (Settings::postProcessing().mEnabled) mPostProcessor->enable(); else { mPostProcessor->disable(); if (auto* hud = MWBase::Environment::get().getWindowManager()->getPostProcessorHud()) hud->setVisible(false); } } } if (updateProjection) { updateProjectionMatrix(); } } void RenderingManager::setViewDistance(float distance, bool delay) { mViewDistance = distance; if (delay) { mUpdateProjectionMatrix = true; return; } updateProjectionMatrix(); } float RenderingManager::getTerrainHeightAt(const osg::Vec3f& pos, ESM::RefId worldspace) { return getWorldspaceChunkMgr(worldspace).mTerrain->getHeightAt(pos); } void RenderingManager::overrideFieldOfView(float val) { if (mFieldOfViewOverridden != true || mFieldOfViewOverride != val) { mFieldOfViewOverridden = true; mFieldOfViewOverride = val; updateProjectionMatrix(); } } void RenderingManager::setFieldOfView(float val) { mFieldOfView = val; mUpdateProjectionMatrix = true; } float RenderingManager::getFieldOfView() const { return mFieldOfViewOverridden ? mFieldOfViewOverridden : mFieldOfView; } osg::Vec3f RenderingManager::getHalfExtents(const MWWorld::ConstPtr& object) const { osg::Vec3f halfExtents(0, 0, 0); VFS::Path::Normalized modelName(object.getClass().getCorrectedModel(object)); if (modelName.empty()) return halfExtents; osg::ref_ptr<const osg::Node> node = mResourceSystem->getSceneManager()->getTemplate(modelName); osg::ComputeBoundsVisitor computeBoundsVisitor; computeBoundsVisitor.setTraversalMask(~(MWRender::Mask_ParticleSystem | MWRender::Mask_Effect)); const_cast<osg::Node*>(node.get())->accept(computeBoundsVisitor); osg::BoundingBox bounds = computeBoundsVisitor.getBoundingBox(); if (bounds.valid()) { halfExtents[0] = std::abs(bounds.xMax() - bounds.xMin()) / 2.f; halfExtents[1] = std::abs(bounds.yMax() - bounds.yMin()) / 2.f; halfExtents[2] = std::abs(bounds.zMax() - bounds.zMin()) / 2.f; } return halfExtents; } osg::BoundingBox RenderingManager::getCullSafeBoundingBox(const MWWorld::Ptr& ptr) const { if (ptr.isEmpty()) return {}; osg::ref_ptr<SceneUtil::PositionAttitudeTransform> rootNode = ptr.getRefData().getBaseNode(); // Recalculate bounds on the ptr's template when the object is not loaded or is loaded but paged MWWorld::Scene* worldScene = MWBase::Environment::get().getWorldScene(); if (!rootNode || worldScene->isPagedRef(ptr)) { const VFS::Path::Normalized model(ptr.getClass().getCorrectedModel(ptr)); if (model.empty()) return {}; rootNode = new SceneUtil::PositionAttitudeTransform; // Hack even used by osg internally, osg's NodeVisitor won't accept const qualified nodes rootNode->addChild(const_cast<osg::Node*>(mResourceSystem->getSceneManager()->getTemplate(model).get())); const float refScale = ptr.getCellRef().getScale(); rootNode->setScale({ refScale, refScale, refScale }); const auto& rotation = ptr.getCellRef().getPosition().rot; if (!ptr.getClass().isActor()) rootNode->setAttitude(osg::Quat(rotation[0], osg::Vec3(-1, 0, 0)) * osg::Quat(rotation[1], osg::Vec3(0, -1, 0)) * osg::Quat(rotation[2], osg::Vec3(0, 0, -1))); rootNode->setPosition(ptr.getCellRef().getPosition().asVec3()); osg::ref_ptr<Animation> animation = nullptr; if (ptr.getClass().isNpc()) { rootNode->setNodeMask(Mask_Actor); animation = new NpcAnimation(ptr, osg::ref_ptr<osg::Group>(rootNode), mResourceSystem); } } SceneUtil::CullSafeBoundsVisitor computeBounds; computeBounds.setTraversalMask(~(MWRender::Mask_ParticleSystem | MWRender::Mask_Effect)); rootNode->accept(computeBounds); return computeBounds.mBoundingBox; } void RenderingManager::resetFieldOfView() { if (mFieldOfViewOverridden == true) { mFieldOfViewOverridden = false; updateProjectionMatrix(); } } void RenderingManager::exportSceneGraph( const MWWorld::Ptr& ptr, const std::filesystem::path& filename, const std::string& format) { osg::Node* node = mViewer->getSceneData(); if (!ptr.isEmpty()) node = ptr.getRefData().getBaseNode(); SceneUtil::writeScene(node, filename, format); } LandManager* RenderingManager::getLandManager() const { return mTerrainStorage->getLandManager(); } void RenderingManager::updateActorPath(const MWWorld::ConstPtr& actor, const std::deque<osg::Vec3f>& path, const DetourNavigator::AgentBounds& agentBounds, const osg::Vec3f& start, const osg::Vec3f& end) const { mActorsPaths->update(actor, path, agentBounds, start, end, mNavigator.getSettings()); } void RenderingManager::removeActorPath(const MWWorld::ConstPtr& actor) const { mActorsPaths->remove(actor); } void RenderingManager::setNavMeshNumber(const std::size_t value) { mNavMeshNumber = value; } void RenderingManager::updateNavMesh() { if (!mNavMesh->isEnabled()) return; const auto navMeshes = mNavigator.getNavMeshes(); auto it = navMeshes.begin(); for (std::size_t i = 0; it != navMeshes.end() && i < mNavMeshNumber; ++i) ++it; if (it == navMeshes.end()) { mNavMesh->reset(); } else { try { mNavMesh->update(it->second, mNavMeshNumber, mNavigator.getSettings()); } catch (const std::exception& e) { Log(Debug::Error) << "NavMesh render update exception: " << e.what(); } } } void RenderingManager::updateRecastMesh() { if (!mRecastMesh->isEnabled()) return; mRecastMesh->update(mNavigator.getRecastMeshTiles(), mNavigator.getSettings()); } void RenderingManager::setActiveGrid(const osg::Vec4i& grid) { mTerrain->setActiveGrid(grid); } bool RenderingManager::pagingEnableObject(int type, const MWWorld::ConstPtr& ptr, bool enabled) { if (!ptr.isInCell() || !ptr.getCell()->isExterior() || !mObjectPaging) return false; if (mObjectPaging->enableObject(type, ptr.getCellRef().getRefNum(), ptr.getCellRef().getPosition().asVec3(), osg::Vec2i(ptr.getCell()->getCell()->getGridX(), ptr.getCell()->getCell()->getGridY()), enabled)) { mTerrain->rebuildViews(); return true; } return false; } void RenderingManager::pagingBlacklistObject(int type, const MWWorld::ConstPtr& ptr) { if (!ptr.isInCell() || !ptr.getCell()->isExterior() || !mObjectPaging) return; ESM::RefNum refnum = ptr.getCellRef().getRefNum(); if (!refnum.hasContentFile()) return; if (mObjectPaging->blacklistObject(type, refnum, ptr.getCellRef().getPosition().asVec3(), osg::Vec2i(ptr.getCell()->getCell()->getGridX(), ptr.getCell()->getCell()->getGridY()))) mTerrain->rebuildViews(); } bool RenderingManager::pagingUnlockCache() { if (mObjectPaging && mObjectPaging->unlockCache()) { mTerrain->rebuildViews(); return true; } return false; } void RenderingManager::getPagedRefnums(const osg::Vec4i& activeGrid, std::vector<ESM::RefNum>& out) { if (mObjectPaging) mObjectPaging->getPagedRefnums(activeGrid, out); } void RenderingManager::setNavMeshMode(Settings::NavMeshRenderMode value) { mNavMesh->setMode(value); } }
72,067
C++
.cpp
1,527
36.993451
120
0.641086
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,394
animation.cpp
OpenMW_openmw/apps/openmw/mwrender/animation.cpp
#include "animation.hpp" #include <algorithm> #include <iomanip> #include <limits> #include <osg/BlendFunc> #include <osg/LightModel> #include <osg/Material> #include <osg/MatrixTransform> #include <osg/Switch> #include <osgParticle/ParticleProcessor> #include <osgParticle/ParticleSystem> #include <osgAnimation/Bone> #include <osgAnimation/UpdateBone> #include <components/debug/debuglog.hpp> #include <components/resource/animblendrulesmanager.hpp> #include <components/resource/keyframemanager.hpp> #include <components/resource/scenemanager.hpp> #include <components/esm3/loadcont.hpp> #include <components/esm3/loadcrea.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadnpc.hpp> #include <components/esm3/loadrace.hpp> #include <components/esm4/loadligh.hpp> #include <components/misc/constants.hpp> #include <components/misc/pathhelpers.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/vfs/manager.hpp> #include <components/vfs/pathutil.hpp> #include <components/vfs/recursivedirectoryiterator.hpp> #include <components/sceneutil/keyframe.hpp> #include <components/sceneutil/lightcommon.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/lightutil.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/skeleton.hpp> #include <components/sceneutil/statesetupdater.hpp> #include <components/sceneutil/util.hpp> #include <components/sceneutil/visitor.hpp> #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/luamanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/containerstore.hpp" #include "../mwworld/esmstore.hpp" #include "../mwmechanics/character.hpp" // FIXME: for MWMechanics::Priority #include "../mwmechanics/weapontype.hpp" #include "actorutil.hpp" #include "rotatecontroller.hpp" #include "util.hpp" #include "vismask.hpp" namespace { class MarkDrawablesVisitor : public osg::NodeVisitor { public: MarkDrawablesVisitor(osg::Node::NodeMask mask) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mMask(mask) { } void apply(osg::Drawable& drawable) override { drawable.setNodeMask(mMask); } private: osg::Node::NodeMask mMask = 0; }; /// Removes all particle systems and related nodes in a subgraph. class RemoveParticlesVisitor : public osg::NodeVisitor { public: RemoveParticlesVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Node& node) override { if (dynamic_cast<osgParticle::ParticleProcessor*>(&node)) mToRemove.emplace_back(&node); traverse(node); } void apply(osg::Drawable& drw) override { if (osgParticle::ParticleSystem* partsys = dynamic_cast<osgParticle::ParticleSystem*>(&drw)) mToRemove.emplace_back(partsys); } void remove() { for (osg::Node* node : mToRemove) { // FIXME: a Drawable might have more than one parent if (node->getNumParents()) node->getParent(0)->removeChild(node); } mToRemove.clear(); } private: std::vector<osg::ref_ptr<osg::Node>> mToRemove; }; class DayNightCallback : public SceneUtil::NodeCallback<DayNightCallback, osg::Switch*> { public: DayNightCallback() : mCurrentState(0) { } void operator()(osg::Switch* node, osg::NodeVisitor* nv) { unsigned int state = MWBase::Environment::get().getWorld()->getNightDayMode(); const unsigned int newState = node->getNumChildren() > state ? state : 0; if (newState != mCurrentState) { mCurrentState = newState; node->setSingleChildOn(mCurrentState); } traverse(node, nv); } private: unsigned int mCurrentState; }; class AddSwitchCallbacksVisitor : public osg::NodeVisitor { public: AddSwitchCallbacksVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Switch& switchNode) override { if (switchNode.getName() == Constants::NightDayLabel) switchNode.addUpdateCallback(new DayNightCallback()); traverse(switchNode); } }; class HarvestVisitor : public osg::NodeVisitor { public: HarvestVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Switch& node) override { if (node.getName() == Constants::HerbalismLabel) { node.setSingleChildOn(1); } traverse(node); } }; bool equalsParts(std::string_view value, std::string_view s1, std::string_view s2, std::string_view s3 = {}) { if (value.starts_with(s1)) { value = value.substr(s1.size()); if (value.starts_with(s2)) return value.substr(s2.size()) == s3; } return false; } float calcAnimVelocity(const SceneUtil::TextKeyMap& keys, SceneUtil::KeyframeController* nonaccumctrl, const osg::Vec3f& accum, std::string_view groupname) { float starttime = std::numeric_limits<float>::max(); float stoptime = 0.0f; // Pick the last Loop Stop key and the last Loop Start key. // This is required because of broken text keys in AshVampire.nif. // It has *two* WalkForward: Loop Stop keys at different times, the first one is used for stopping playback // but the animation velocity calculation uses the second one. // As result the animation velocity calculation is not correct, and this incorrect velocity must be replicated, // because otherwise the Creature's Speed (dagoth uthol) would not be sufficient to move fast enough. auto keyiter = keys.rbegin(); while (keyiter != keys.rend()) { if (equalsParts(keyiter->second, groupname, ": start") || equalsParts(keyiter->second, groupname, ": loop start")) { starttime = keyiter->first; break; } ++keyiter; } keyiter = keys.rbegin(); while (keyiter != keys.rend()) { if (equalsParts(keyiter->second, groupname, ": stop")) stoptime = keyiter->first; else if (equalsParts(keyiter->second, groupname, ": loop stop")) { stoptime = keyiter->first; break; } ++keyiter; } if (stoptime > starttime) { osg::Vec3f startpos = osg::componentMultiply(nonaccumctrl->getTranslation(starttime), accum); osg::Vec3f endpos = osg::componentMultiply(nonaccumctrl->getTranslation(stoptime), accum); return (startpos - endpos).length() / (stoptime - starttime); } return 0.0f; } class GetExtendedBonesVisitor : public osg::NodeVisitor { public: GetExtendedBonesVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Node& node) override { if (SceneUtil::hasUserDescription(&node, "CustomBone")) { mFoundBones.emplace_back(&node, node.getParent(0)); return; } traverse(node); } std::vector<std::pair<osg::Node*, osg::Group*>> mFoundBones; }; class RemoveFinishedCallbackVisitor : public SceneUtil::RemoveVisitor { public: bool mHasMagicEffects; RemoveFinishedCallbackVisitor() : RemoveVisitor() , mHasMagicEffects(false) { } void apply(osg::Node& node) override { traverse(node); } void apply(osg::Group& group) override { traverse(group); osg::Callback* callback = group.getUpdateCallback(); if (callback) { // We should remove empty transformation nodes and finished callbacks here MWRender::UpdateVfxCallback* vfxCallback = dynamic_cast<MWRender::UpdateVfxCallback*>(callback); if (vfxCallback) { if (vfxCallback->mFinished) mToRemove.emplace_back(group.asNode(), group.getParent(0)); else mHasMagicEffects = true; } } } void apply(osg::MatrixTransform& node) override { traverse(node); } void apply(osg::Geometry&) override {} }; class RemoveCallbackVisitor : public SceneUtil::RemoveVisitor { public: bool mHasMagicEffects; RemoveCallbackVisitor() : RemoveVisitor() , mHasMagicEffects(false) { } RemoveCallbackVisitor(std::string_view effectId) : RemoveVisitor() , mHasMagicEffects(false) , mEffectId(effectId) { } void apply(osg::Node& node) override { traverse(node); } void apply(osg::Group& group) override { traverse(group); osg::Callback* callback = group.getUpdateCallback(); if (callback) { MWRender::UpdateVfxCallback* vfxCallback = dynamic_cast<MWRender::UpdateVfxCallback*>(callback); if (vfxCallback) { bool toRemove = mEffectId == "" || vfxCallback->mParams.mEffectId == mEffectId; if (toRemove) mToRemove.emplace_back(group.asNode(), group.getParent(0)); else mHasMagicEffects = true; } } } void apply(osg::MatrixTransform& node) override { traverse(node); } void apply(osg::Geometry&) override {} private: std::string_view mEffectId; }; class FindVfxCallbacksVisitor : public osg::NodeVisitor { public: std::vector<MWRender::UpdateVfxCallback*> mCallbacks; FindVfxCallbacksVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } FindVfxCallbacksVisitor(std::string_view effectId) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mEffectId(effectId) { } void apply(osg::Node& node) override { traverse(node); } void apply(osg::Group& group) override { osg::Callback* callback = group.getUpdateCallback(); if (callback) { MWRender::UpdateVfxCallback* vfxCallback = dynamic_cast<MWRender::UpdateVfxCallback*>(callback); if (vfxCallback) { if (mEffectId == "" || vfxCallback->mParams.mEffectId == mEffectId) { mCallbacks.push_back(vfxCallback); } } } traverse(group); } void apply(osg::MatrixTransform& node) override { traverse(node); } void apply(osg::Geometry&) override {} private: std::string_view mEffectId; }; namespace { osg::ref_ptr<osg::LightModel> makeVFXLightModelInstance() { osg::ref_ptr<osg::LightModel> lightModel = new osg::LightModel; lightModel->setAmbientIntensity({ 1, 1, 1, 1 }); return lightModel; } const osg::ref_ptr<osg::LightModel>& getVFXLightModelInstance() { static const osg::ref_ptr<osg::LightModel> lightModel = makeVFXLightModelInstance(); return lightModel; } } void assignBoneBlendCallbackRecursive(MWRender::BoneAnimBlendController* controller, osg::Node* parent, bool isRoot) { // Attempt to cast node to an osgAnimation::Bone if (!isRoot && dynamic_cast<osgAnimation::Bone*>(parent)) { // Wrapping in a custom callback object allows for nested callback chaining, otherwise it has link to self // issues we need to share the base BoneAnimBlendController as that contains blending information and is // guaranteed to update before osgAnimation::Bone* bone = static_cast<osgAnimation::Bone*>(parent); osg::ref_ptr<osg::Callback> cb = new MWRender::BoneAnimBlendControllerWrapper(controller, bone); // Ensure there is no other AnimBlendController - this can happen when using // multiple animations with different roots, such as NPC animation osg::Callback* updateCb = bone->getUpdateCallback(); while (updateCb) { if (dynamic_cast<MWRender::BoneAnimBlendController*>(updateCb)) { osg::ref_ptr<osg::Callback> nextCb = updateCb->getNestedCallback(); bone->removeUpdateCallback(updateCb); updateCb = nextCb; } else { updateCb = updateCb->getNestedCallback(); } } // Find UpdateBone callback and bind to just after that (order is important) // NOTE: if it doesn't have an UpdateBone callback, we shouldn't be doing blending! updateCb = bone->getUpdateCallback(); while (updateCb) { if (dynamic_cast<osgAnimation::UpdateBone*>(updateCb)) { // Override the immediate callback after the UpdateBone osg::ref_ptr<osg::Callback> lastCb = updateCb->getNestedCallback(); updateCb->setNestedCallback(cb); if (lastCb) cb->setNestedCallback(lastCb); break; } updateCb = updateCb->getNestedCallback(); } } // Traverse child bones if this is a group osg::Group* group = parent->asGroup(); if (group) for (unsigned int i = 0; i < group->getNumChildren(); ++i) assignBoneBlendCallbackRecursive(controller, group->getChild(i), false); } } namespace MWRender { class TransparencyUpdater : public SceneUtil::StateSetUpdater { public: TransparencyUpdater(const float alpha) : mAlpha(alpha) { } void setAlpha(const float alpha) { mAlpha = alpha; } protected: void setDefaults(osg::StateSet* stateset) override { osg::BlendFunc* blendfunc(new osg::BlendFunc); stateset->setAttributeAndModes(blendfunc, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); stateset->setRenderBinMode(osg::StateSet::OVERRIDE_RENDERBIN_DETAILS); // FIXME: overriding diffuse/ambient/emissive colors osg::Material* material = new osg::Material; material->setColorMode(osg::Material::OFF); material->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, mAlpha)); material->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); stateset->setAttributeAndModes(material, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->addUniform( new osg::Uniform("colorMode", 0), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } void apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) override { osg::Material* material = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); material->setAlpha(osg::Material::FRONT_AND_BACK, mAlpha); } private: float mAlpha; }; struct Animation::AnimSource { osg::ref_ptr<const SceneUtil::KeyframeHolder> mKeyframes; typedef std::map<std::string, osg::ref_ptr<SceneUtil::KeyframeController>> ControllerMap; ControllerMap mControllerMap[sNumBlendMasks]; const SceneUtil::TextKeyMap& getTextKeys() const; osg::ref_ptr<const SceneUtil::AnimBlendRules> mAnimBlendRules; }; void UpdateVfxCallback::operator()(osg::Node* node, osg::NodeVisitor* nv) { traverse(node, nv); if (mFinished) return; double newTime = nv->getFrameStamp()->getSimulationTime(); if (mStartingTime == 0) { mStartingTime = newTime; return; } double duration = newTime - mStartingTime; mStartingTime = newTime; mParams.mAnimTime->addTime(duration); if (mParams.mAnimTime->getTime() >= mParams.mMaxControllerLength) { if (mParams.mLoop) { // Start from the beginning again; carry over the remainder // Not sure if this is actually needed, the controller function might already handle loops float remainder = mParams.mAnimTime->getTime() - mParams.mMaxControllerLength; mParams.mAnimTime->resetTime(remainder); } else { // Hide effect immediately node->setNodeMask(0); mFinished = true; } } } class ResetAccumRootCallback : public SceneUtil::NodeCallback<ResetAccumRootCallback, osg::MatrixTransform*> { public: void operator()(osg::MatrixTransform* transform, osg::NodeVisitor* nv) { osg::Matrix mat = transform->getMatrix(); osg::Vec3f position = mat.getTrans(); position = osg::componentMultiply(mResetAxes, position); mat.setTrans(position); transform->setMatrix(mat); traverse(transform, nv); } void setAccumulate(const osg::Vec3f& accumulate) { // anything that accumulates (1.f) should be reset in the callback to (0.f) mResetAxes.x() = accumulate.x() != 0.f ? 0.f : 1.f; mResetAxes.y() = accumulate.y() != 0.f ? 0.f : 1.f; mResetAxes.z() = accumulate.z() != 0.f ? 0.f : 1.f; } private: osg::Vec3f mResetAxes; }; Animation::Animation( const MWWorld::Ptr& ptr, osg::ref_ptr<osg::Group> parentNode, Resource::ResourceSystem* resourceSystem) : mInsert(std::move(parentNode)) , mSkeleton(nullptr) , mNodeMapCreated(false) , mPtr(ptr) , mResourceSystem(resourceSystem) , mAccumulate(1.f, 1.f, 0.f) , mTextKeyListener(nullptr) , mHeadYawRadians(0.f) , mHeadPitchRadians(0.f) , mUpperBodyYawRadians(0.f) , mLegsYawRadians(0.f) , mBodyPitchRadians(0.f) , mHasMagicEffects(false) , mAlpha(1.f) , mPlayScriptedOnly(false) , mRequiresBoneMap(false) { for (size_t i = 0; i < sNumBlendMasks; i++) mAnimationTimePtr[i] = std::make_shared<AnimationTime>(); mLightListCallback = new SceneUtil::LightListCallback; } Animation::~Animation() { removeFromSceneImpl(); } void Animation::setActive(int active) { if (mSkeleton) mSkeleton->setActive(static_cast<SceneUtil::Skeleton::ActiveType>(active)); } void Animation::updatePtr(const MWWorld::Ptr& ptr) { mPtr = ptr; } void Animation::setAccumulation(const osg::Vec3f& accum) { mAccumulate = accum; if (mResetAccumRootCallback) mResetAccumRootCallback->setAccumulate(mAccumulate); } // controllerName is used for Collada animated deforming models size_t Animation::detectBlendMask(const osg::Node* node, const std::string& controllerName) const { static const std::string_view sBlendMaskRoots[sNumBlendMasks] = { "", /* Lower body / character root */ "Bip01 Spine1", /* Torso */ "Bip01 L Clavicle", /* Left arm */ "Bip01 R Clavicle", /* Right arm */ }; while (node != mObjectRoot) { const std::string& name = node->getName(); for (size_t i = 1; i < sNumBlendMasks; i++) { if (name == sBlendMaskRoots[i] || controllerName == sBlendMaskRoots[i]) return i; } assert(node->getNumParents() > 0); node = node->getParent(0); } return 0; } const SceneUtil::TextKeyMap& Animation::AnimSource::getTextKeys() const { return mKeyframes->mTextKeys; } void Animation::loadAdditionalAnimations(VFS::Path::NormalizedView model, const std::string& baseModel) { constexpr VFS::Path::NormalizedView meshes("meshes/"); if (!model.value().starts_with(meshes.value())) return; std::string path(model.value()); constexpr VFS::Path::NormalizedView animations("animations/"); path.replace(0, meshes.value().size(), animations.value()); const std::string::size_type extensionStart = path.find_last_of(VFS::Path::extensionSeparator); if (extensionStart == std::string::npos) return; path.replace(extensionStart, path.size() - extensionStart, "/"); for (const VFS::Path::Normalized& name : mResourceSystem->getVFS()->getRecursiveDirectoryIterator(path)) { if (Misc::getFileExtension(name) == "kf") { addSingleAnimSource(name, baseModel); } } } void Animation::addAnimSource(std::string_view model, const std::string& baseModel) { VFS::Path::Normalized kfname(model); if (Misc::getFileExtension(kfname) == "nif") kfname.changeExtension("kf"); addSingleAnimSource(kfname, baseModel); if (Settings::game().mUseAdditionalAnimSources) loadAdditionalAnimations(kfname, baseModel); } std::shared_ptr<Animation::AnimSource> Animation::addSingleAnimSource( const std::string& kfname, const std::string& baseModel) { if (!mResourceSystem->getVFS()->exists(kfname)) return nullptr; auto animsrc = std::make_shared<AnimSource>(); animsrc->mKeyframes = mResourceSystem->getKeyframeManager()->get(kfname); if (!animsrc->mKeyframes || animsrc->mKeyframes->mTextKeys.empty() || animsrc->mKeyframes->mKeyframeControllers.empty()) return nullptr; const NodeMap& nodeMap = getNodeMap(); const auto& controllerMap = animsrc->mKeyframes->mKeyframeControllers; for (SceneUtil::KeyframeHolder::KeyframeControllerMap::const_iterator it = controllerMap.begin(); it != controllerMap.end(); ++it) { std::string bonename = Misc::StringUtils::lowerCase(it->first); NodeMap::const_iterator found = nodeMap.find(bonename); if (found == nodeMap.end()) { Log(Debug::Warning) << "Warning: addAnimSource: can't find bone '" + bonename << "' in " << baseModel << " (referenced by " << kfname << ")"; continue; } osg::Node* node = found->second; size_t blendMask = detectBlendMask(node, it->second->getName()); // clone the controller, because each Animation needs its own ControllerSource osg::ref_ptr<SceneUtil::KeyframeController> cloned = osg::clone(it->second.get(), osg::CopyOp::SHALLOW_COPY); cloned->setSource(mAnimationTimePtr[blendMask]); animsrc->mControllerMap[blendMask].insert(std::make_pair(bonename, cloned)); } mAnimSources.push_back(animsrc); for (const std::string& group : mAnimSources.back()->getTextKeys().getGroups()) mSupportedAnimations.insert(group); SceneUtil::AssignControllerSourcesVisitor assignVisitor(mAnimationTimePtr[0]); mObjectRoot->accept(assignVisitor); // Determine the movement accumulation bone if necessary if (!mAccumRoot) { // Priority matters! bip01 is preferred. static const std::initializer_list<std::string_view> accumRootNames = { "bip01", "root bone" }; NodeMap::const_iterator found = nodeMap.end(); for (const std::string_view& name : accumRootNames) { found = nodeMap.find(name); if (found == nodeMap.end()) continue; for (SceneUtil::KeyframeHolder::KeyframeControllerMap::const_iterator it = controllerMap.begin(); it != controllerMap.end(); ++it) { if (Misc::StringUtils::ciEqual(it->first, name)) { mAccumRoot = found->second; break; } } if (mAccumRoot) break; } } // Get the blending rules if (Settings::game().mSmoothAnimTransitions) { // Note, even if the actual config is .json - we should send a .yaml path to AnimBlendRulesManager, the // manager will check for .json if it will not find a specified .yaml file. VFS::Path::Normalized blendConfigPath(kfname); blendConfigPath.changeExtension("yaml"); // globalBlendConfigPath is only used with actors! Objects have no default blending. constexpr VFS::Path::NormalizedView globalBlendConfigPath("animations/animation-config.yaml"); osg::ref_ptr<const SceneUtil::AnimBlendRules> blendRules; if (mPtr.getClass().isActor()) { blendRules = mResourceSystem->getAnimBlendRulesManager()->getRules(globalBlendConfigPath, blendConfigPath); if (blendRules == nullptr) Log(Debug::Warning) << "Unable to find animation blending rules: '" << blendConfigPath << "' or '" << globalBlendConfigPath << "'"; } else { blendRules = mResourceSystem->getAnimBlendRulesManager()->getRules(blendConfigPath, blendConfigPath); } // At this point blendRules will either be nullptr or an AnimBlendRules instance with > 0 rules inside. animsrc->mAnimBlendRules = blendRules; } return animsrc; } void Animation::clearAnimSources() { mStates.clear(); for (size_t i = 0; i < sNumBlendMasks; i++) mAnimationTimePtr[i]->setTimePtr(std::shared_ptr<float>()); mAccumCtrl = nullptr; mSupportedAnimations.clear(); mAnimSources.clear(); mAnimVelocities.clear(); } bool Animation::hasAnimation(std::string_view anim) const { return mSupportedAnimations.find(anim) != mSupportedAnimations.end(); } bool Animation::isLoopingAnimation(std::string_view group) const { // In Morrowind, a some animation groups are always considered looping, regardless // of loop start/stop keys. // To be match vanilla behavior we probably only need to check this list, but we don't // want to prevent modded animations with custom group names from looping either. static const std::unordered_set<std::string_view> loopingAnimations = { "walkforward", "walkback", "walkleft", "walkright", "swimwalkforward", "swimwalkback", "swimwalkleft", "swimwalkright", "runforward", "runback", "runleft", "runright", "swimrunforward", "swimrunback", "swimrunleft", "swimrunright", "sneakforward", "sneakback", "sneakleft", "sneakright", "turnleft", "turnright", "swimturnleft", "swimturnright", "spellturnleft", "spellturnright", "torch", "idle", "idle2", "idle3", "idle4", "idle5", "idle6", "idle7", "idle8", "idle9", "idlesneak", "idlestorm", "idleswim", "jump", "inventoryhandtohand", "inventoryweapononehand", "inventoryweapontwohand", "inventoryweapontwowide" }; static const std::vector<std::string_view> shortGroups = MWMechanics::getAllWeaponTypeShortGroups(); if (getTextKeyTime(std::string(group) + ": loop start") >= 0) return true; // Most looping animations have variants for each weapon type shortgroup. // Just remove the shortgroup instead of enumerating all of the possible animation groupnames. // Make sure we pick the longest shortgroup so e.g. "bow" doesn't get picked over "crossbow" // when the shortgroup is crossbow. std::size_t suffixLength = 0; for (std::string_view suffix : shortGroups) { if (suffix.length() > suffixLength && group.ends_with(suffix)) { suffixLength = suffix.length(); } } group.remove_suffix(suffixLength); return loopingAnimations.count(group) > 0; } float Animation::getStartTime(const std::string& groupname) const { for (AnimSourceList::const_reverse_iterator iter(mAnimSources.rbegin()); iter != mAnimSources.rend(); ++iter) { const SceneUtil::TextKeyMap& keys = (*iter)->getTextKeys(); const auto found = keys.findGroupStart(groupname); if (found != keys.end()) return found->first; } return -1.f; } float Animation::getTextKeyTime(std::string_view textKey) const { for (AnimSourceList::const_reverse_iterator iter(mAnimSources.rbegin()); iter != mAnimSources.rend(); ++iter) { const SceneUtil::TextKeyMap& keys = (*iter)->getTextKeys(); for (auto iterKey = keys.begin(); iterKey != keys.end(); ++iterKey) { if (iterKey->second.starts_with(textKey)) return iterKey->first; } } return -1.f; } void Animation::handleTextKey(AnimState& state, std::string_view groupname, SceneUtil::TextKeyMap::ConstIterator key, const SceneUtil::TextKeyMap& map) { std::string_view evt = key->second; if (evt.starts_with(groupname) && evt.substr(groupname.size()).starts_with(": ")) { size_t off = groupname.size() + 2; if (evt.substr(off) == "loop start") state.mLoopStartTime = key->first; else if (evt.substr(off) == "loop stop") state.mLoopStopTime = key->first; } try { if (mTextKeyListener != nullptr) mTextKeyListener->handleTextKey(groupname, key, map); } catch (std::exception& e) { Log(Debug::Error) << "Error handling text key " << evt << ": " << e.what(); } } void Animation::play(std::string_view groupname, const AnimPriority& priority, int blendMask, bool autodisable, float speedmult, std::string_view start, std::string_view stop, float startpoint, uint32_t loops, bool loopfallback) { if (!mObjectRoot || mAnimSources.empty()) return; if (groupname.empty()) { resetActiveGroups(); return; } AnimStateMap::iterator foundstateiter = mStates.find(groupname); if (foundstateiter != mStates.end()) { foundstateiter->second.mPriority = priority; } AnimStateMap::iterator stateiter = mStates.begin(); while (stateiter != mStates.end()) { if (stateiter->second.mPriority == priority && stateiter->first != groupname) mStates.erase(stateiter++); else ++stateiter; } if (foundstateiter != mStates.end()) { resetActiveGroups(); return; } /* Look in reverse; last-inserted source has priority. */ AnimState state; AnimSourceList::reverse_iterator iter(mAnimSources.rbegin()); for (; iter != mAnimSources.rend(); ++iter) { const SceneUtil::TextKeyMap& textkeys = (*iter)->getTextKeys(); if (reset(state, textkeys, groupname, start, stop, startpoint, loopfallback)) { state.mSource = *iter; state.mSpeedMult = speedmult; state.mLoopCount = loops; state.mPlaying = (state.getTime() < state.mStopTime); state.mPriority = priority; state.mBlendMask = blendMask; state.mAutoDisable = autodisable; state.mGroupname = groupname; state.mStartKey = start; mStates[std::string{ groupname }] = state; if (state.mPlaying) { auto textkey = textkeys.lowerBound(state.getTime()); while (textkey != textkeys.end() && textkey->first <= state.getTime()) { handleTextKey(state, groupname, textkey, textkeys); ++textkey; } } if (state.getTime() >= state.mLoopStopTime && state.mLoopCount > 0) { state.mLoopCount--; state.setTime(state.mLoopStartTime); state.mPlaying = true; if (state.getTime() >= state.mLoopStopTime) break; auto textkey = textkeys.lowerBound(state.getTime()); while (textkey != textkeys.end() && textkey->first <= state.getTime()) { handleTextKey(state, groupname, textkey, textkeys); ++textkey; } } break; } } resetActiveGroups(); } bool Animation::reset(AnimState& state, const SceneUtil::TextKeyMap& keys, std::string_view groupname, std::string_view start, std::string_view stop, float startpoint, bool loopfallback) { // Look for text keys in reverse. This normally wouldn't matter, but for some reason undeadwolf_2.nif has two // separate walkforward keys, and the last one is supposed to be used. auto groupend = keys.rbegin(); for (; groupend != keys.rend(); ++groupend) { if (groupend->second.starts_with(groupname) && groupend->second.compare(groupname.size(), 2, ": ") == 0) break; } auto startkey = groupend; while (startkey != keys.rend() && !equalsParts(startkey->second, groupname, ": ", start)) ++startkey; if (startkey == keys.rend() && start == "loop start") { startkey = groupend; while (startkey != keys.rend() && !equalsParts(startkey->second, groupname, ": start")) ++startkey; } if (startkey == keys.rend()) return false; auto stopkey = groupend; std::size_t checkLength = groupname.size() + 2 + stop.size(); while (stopkey != keys.rend() // We have to ignore extra garbage at the end. // The Scrib's idle3 animation has "Idle3: Stop." instead of "Idle3: Stop". // Why, just why? :( && !equalsParts(std::string_view{ stopkey->second }.substr(0, checkLength), groupname, ": ", stop)) ++stopkey; if (stopkey == keys.rend()) return false; if (startkey->first > stopkey->first) return false; state.mStartTime = startkey->first; if (loopfallback) { state.mLoopStartTime = startkey->first; state.mLoopStopTime = stopkey->first; } else { state.mLoopStartTime = startkey->first; state.mLoopStopTime = std::numeric_limits<float>::max(); } state.mStopTime = stopkey->first; state.setTime(state.mStartTime + ((state.mStopTime - state.mStartTime) * startpoint)); // mLoopStartTime and mLoopStopTime normally get assigned when encountering these keys while playing the // animation (see handleTextKey). But if startpoint is already past these keys, or start time is == stop time, // we need to assign them now. auto key = groupend; for (; key != startkey && key != keys.rend(); ++key) { if (key->first > state.getTime()) continue; if (equalsParts(key->second, groupname, ": loop start")) state.mLoopStartTime = key->first; else if (equalsParts(key->second, groupname, ": loop stop")) state.mLoopStopTime = key->first; } return true; } void Animation::setTextKeyListener(TextKeyListener* listener) { mTextKeyListener = listener; } const Animation::NodeMap& Animation::getNodeMap() const { if (!mNodeMapCreated && mObjectRoot) { // If the base of this animation is an osgAnimation, we should map the bones not matrix transforms if (mRequiresBoneMap) { SceneUtil::NodeMapVisitorBoneOnly visitor(mNodeMap); mObjectRoot->accept(visitor); } else { SceneUtil::NodeMapVisitor visitor(mNodeMap); mObjectRoot->accept(visitor); } mNodeMapCreated = true; } return mNodeMap; } template <typename ControllerType> inline osg::Callback* Animation::handleBlendTransform(const osg::ref_ptr<osg::Node>& node, osg::ref_ptr<SceneUtil::KeyframeController> keyframeController, std::map<osg::ref_ptr<osg::Node>, osg::ref_ptr<ControllerType>>& blendControllers, const AnimBlendStateData& stateData, const osg::ref_ptr<const SceneUtil::AnimBlendRules>& blendRules, const AnimState& active) { osg::ref_ptr<ControllerType> animController; if (blendControllers.contains(node)) { animController = blendControllers.at(node); animController->setKeyframeTrack(keyframeController, stateData, blendRules); } else { animController = new ControllerType(keyframeController, stateData, blendRules); blendControllers.emplace(node, animController); if constexpr (std::is_same_v<ControllerType, BoneAnimBlendController>) assignBoneBlendCallbackRecursive(animController, node, true); } keyframeController->mTime = active.mTime; osg::Callback* asCallback = animController->getAsCallback(); if constexpr (std::is_same_v<ControllerType, BoneAnimBlendController>) { // IMPORTANT: we must gather all transforms at point of change before next update // instead of at the root update callback because the root bone may require blending. if (animController->getBlendTrigger()) animController->gatherRecursiveBoneTransforms(static_cast<osgAnimation::Bone*>(node.get())); // Register blend callback after the initial animation callback node->addUpdateCallback(asCallback); mActiveControllers.emplace_back(node, asCallback); return keyframeController->getAsCallback(); } return asCallback; } void Animation::resetActiveGroups() { // remove all previous external controllers from the scene graph for (auto it = mActiveControllers.begin(); it != mActiveControllers.end(); ++it) { osg::Node* node = it->first; node->removeUpdateCallback(it->second); // Should be no longer needed with OSG 3.4 it->second->setNestedCallback(nullptr); } mActiveControllers.clear(); mAccumCtrl = nullptr; for (size_t blendMask = 0; blendMask < sNumBlendMasks; blendMask++) { AnimStateMap::const_iterator active = mStates.end(); AnimStateMap::const_iterator state = mStates.begin(); for (; state != mStates.end(); ++state) { if (!state->second.blendMaskContains(blendMask)) continue; if (active == mStates.end() || active->second.mPriority[(BoneGroup)blendMask] < state->second.mPriority[(BoneGroup)blendMask]) active = state; } mAnimationTimePtr[blendMask]->setTimePtr( active == mStates.end() ? std::shared_ptr<float>() : active->second.mTime); // add external controllers for the AnimSource active in this blend mask if (active != mStates.end()) { std::shared_ptr<AnimSource> animsrc = active->second.mSource; const AnimBlendStateData stateData = { .mGroupname = active->second.mGroupname, .mStartKey = active->second.mStartKey }; for (AnimSource::ControllerMap::iterator it = animsrc->mControllerMap[blendMask].begin(); it != animsrc->mControllerMap[blendMask].end(); ++it) { osg::ref_ptr<osg::Node> node = getNodeMap().at( it->first); // this should not throw, we already checked for the node existing in addAnimSource const bool useSmoothAnims = Settings::game().mSmoothAnimTransitions; osg::Callback* callback = it->second->getAsCallback(); if (useSmoothAnims) { if (dynamic_cast<NifOsg::MatrixTransform*>(node.get())) { callback = handleBlendTransform<NifAnimBlendController>(node, it->second, mAnimBlendControllers, stateData, animsrc->mAnimBlendRules, active->second); } else if (dynamic_cast<osgAnimation::Bone*>(node.get())) { callback = handleBlendTransform<BoneAnimBlendController>(node, it->second, mBoneAnimBlendControllers, stateData, animsrc->mAnimBlendRules, active->second); } } node->addUpdateCallback(callback); mActiveControllers.emplace_back(node, callback); if (blendMask == 0 && node == mAccumRoot) { mAccumCtrl = it->second; // make sure reset is last in the chain of callbacks if (!mResetAccumRootCallback) { mResetAccumRootCallback = new ResetAccumRootCallback; mResetAccumRootCallback->setAccumulate(mAccumulate); } mAccumRoot->addUpdateCallback(mResetAccumRootCallback); mActiveControllers.emplace_back(mAccumRoot, mResetAccumRootCallback); } } } } addControllers(); } void Animation::adjustSpeedMult(const std::string& groupname, float speedmult) { AnimStateMap::iterator state(mStates.find(groupname)); if (state != mStates.end()) state->second.mSpeedMult = speedmult; } bool Animation::isPlaying(std::string_view groupname) const { AnimStateMap::const_iterator state(mStates.find(groupname)); if (state != mStates.end()) return state->second.mPlaying; return false; } bool Animation::getInfo(std::string_view groupname, float* complete, float* speedmult, size_t* loopcount) const { AnimStateMap::const_iterator iter = mStates.find(groupname); if (iter == mStates.end()) { if (complete) *complete = 0.0f; if (speedmult) *speedmult = 0.0f; if (loopcount) *loopcount = 0; return false; } if (complete) { if (iter->second.mStopTime > iter->second.mStartTime) *complete = (iter->second.getTime() - iter->second.mStartTime) / (iter->second.mStopTime - iter->second.mStartTime); else *complete = (iter->second.mPlaying ? 0.0f : 1.0f); } if (speedmult) *speedmult = iter->second.mSpeedMult; if (loopcount) *loopcount = iter->second.mLoopCount; return true; } std::string_view Animation::getActiveGroup(BoneGroup boneGroup) const { if (auto timePtr = mAnimationTimePtr[boneGroup]->getTimePtr()) for (auto& state : mStates) if (state.second.mTime == timePtr) return state.first; return ""; } float Animation::getCurrentTime(std::string_view groupname) const { AnimStateMap::const_iterator iter = mStates.find(groupname); if (iter == mStates.end()) return -1.f; return iter->second.getTime(); } void Animation::disable(std::string_view groupname) { AnimStateMap::iterator iter = mStates.find(groupname); if (iter != mStates.end()) mStates.erase(iter); resetActiveGroups(); } float Animation::getVelocity(std::string_view groupname) const { if (!mAccumRoot) return 0.0f; std::map<std::string, float>::const_iterator found = mAnimVelocities.find(groupname); if (found != mAnimVelocities.end()) return found->second; // Look in reverse; last-inserted source has priority. AnimSourceList::const_reverse_iterator animsrc(mAnimSources.rbegin()); for (; animsrc != mAnimSources.rend(); ++animsrc) { const SceneUtil::TextKeyMap& keys = (*animsrc)->getTextKeys(); if (keys.hasGroupStart(groupname)) break; } if (animsrc == mAnimSources.rend()) return 0.0f; float velocity = 0.0f; const SceneUtil::TextKeyMap& keys = (*animsrc)->getTextKeys(); const AnimSource::ControllerMap& ctrls = (*animsrc)->mControllerMap[0]; for (AnimSource::ControllerMap::const_iterator it = ctrls.begin(); it != ctrls.end(); ++it) { if (Misc::StringUtils::ciEqual(it->first, mAccumRoot->getName())) { velocity = calcAnimVelocity(keys, it->second, mAccumulate, groupname); break; } } // If there's no velocity, keep looking if (!(velocity > 1.0f)) { AnimSourceList::const_reverse_iterator animiter = mAnimSources.rbegin(); while (*animiter != *animsrc) ++animiter; while (!(velocity > 1.0f) && ++animiter != mAnimSources.rend()) { const SceneUtil::TextKeyMap& keys2 = (*animiter)->getTextKeys(); const AnimSource::ControllerMap& ctrls2 = (*animiter)->mControllerMap[0]; for (AnimSource::ControllerMap::const_iterator it = ctrls2.begin(); it != ctrls2.end(); ++it) { if (Misc::StringUtils::ciEqual(it->first, mAccumRoot->getName())) { velocity = calcAnimVelocity(keys2, it->second, mAccumulate, groupname); break; } } } } mAnimVelocities.emplace(groupname, velocity); return velocity; } void Animation::updatePosition(float oldtime, float newtime, osg::Vec3f& position) { // Get the difference from the last update, and move the position osg::Vec3f off = osg::componentMultiply(mAccumCtrl->getTranslation(newtime), mAccumulate); position += off - osg::componentMultiply(mAccumCtrl->getTranslation(oldtime), mAccumulate); } osg::Vec3f Animation::runAnimation(float duration) { osg::Vec3f movement(0.f, 0.f, 0.f); AnimStateMap::iterator stateiter = mStates.begin(); while (stateiter != mStates.end()) { AnimState& state = stateiter->second; if (mPlayScriptedOnly && !state.mPriority.contains(MWMechanics::Priority_Scripted)) { ++stateiter; continue; } const SceneUtil::TextKeyMap& textkeys = state.mSource->getTextKeys(); auto textkey = textkeys.upperBound(state.getTime()); float timepassed = duration * state.mSpeedMult; while (state.mPlaying) { if (!state.shouldLoop()) { float targetTime = state.getTime() + timepassed; if (textkey == textkeys.end() || textkey->first > targetTime) { if (mAccumCtrl && state.mTime == mAnimationTimePtr[0]->getTimePtr()) updatePosition(state.getTime(), targetTime, movement); state.setTime(std::min(targetTime, state.mStopTime)); } else { if (mAccumCtrl && state.mTime == mAnimationTimePtr[0]->getTimePtr()) updatePosition(state.getTime(), textkey->first, movement); state.setTime(textkey->first); } state.mPlaying = (state.getTime() < state.mStopTime); timepassed = targetTime - state.getTime(); while (textkey != textkeys.end() && textkey->first <= state.getTime()) { handleTextKey(state, stateiter->first, textkey, textkeys); ++textkey; } } if (state.shouldLoop()) { state.mLoopCount--; state.setTime(state.mLoopStartTime); state.mPlaying = true; textkey = textkeys.lowerBound(state.getTime()); while (textkey != textkeys.end() && textkey->first <= state.getTime()) { handleTextKey(state, stateiter->first, textkey, textkeys); ++textkey; } if (state.getTime() >= state.mLoopStopTime) break; } if (timepassed <= 0.0f) break; } if (!state.mPlaying && state.mAutoDisable) { mStates.erase(stateiter++); resetActiveGroups(); } else ++stateiter; } updateEffects(); const float epsilon = 0.001f; float yawOffset = 0; if (mRootController) { bool enable = std::abs(mLegsYawRadians) > epsilon || std::abs(mBodyPitchRadians) > epsilon; mRootController->setEnabled(enable); if (enable) { osg::Quat legYaw = osg::Quat(mLegsYawRadians, osg::Vec3f(0, 0, 1)); mRootController->setRotate(legYaw * osg::Quat(mBodyPitchRadians, osg::Vec3f(1, 0, 0))); yawOffset = mLegsYawRadians; // When yawing the root, also update the accumulated movement. movement = legYaw * movement; } } if (mSpineController) { float yaw = mUpperBodyYawRadians - yawOffset; bool enable = std::abs(yaw) > epsilon; mSpineController->setEnabled(enable); if (enable) { mSpineController->setRotate(osg::Quat(yaw, osg::Vec3f(0, 0, 1))); yawOffset = mUpperBodyYawRadians; } } if (mHeadController) { float yaw = mHeadYawRadians - yawOffset; bool enable = (std::abs(mHeadPitchRadians) > epsilon || std::abs(yaw) > epsilon); mHeadController->setEnabled(enable); if (enable) mHeadController->setRotate( osg::Quat(mHeadPitchRadians, osg::Vec3f(1, 0, 0)) * osg::Quat(yaw, osg::Vec3f(0, 0, 1))); } return movement; } void Animation::setLoopingEnabled(std::string_view groupname, bool enabled) { AnimStateMap::iterator state(mStates.find(groupname)); if (state != mStates.end()) state->second.mLoopingEnabled = enabled; } void loadBonesFromFile( osg::ref_ptr<osg::Node>& baseNode, VFS::Path::NormalizedView model, Resource::ResourceSystem* resourceSystem) { const osg::Node* node = resourceSystem->getSceneManager()->getTemplate(model).get(); osg::ref_ptr<osg::Node> sheathSkeleton( const_cast<osg::Node*>(node)); // const-trickery required because there is no const version of NodeVisitor GetExtendedBonesVisitor getBonesVisitor; sheathSkeleton->accept(getBonesVisitor); for (auto& nodePair : getBonesVisitor.mFoundBones) { SceneUtil::FindByNameVisitor findVisitor(nodePair.second->getName()); baseNode->accept(findVisitor); osg::Group* sheathParent = findVisitor.mFoundNode; if (sheathParent) { osg::Node* copy = static_cast<osg::Node*>(nodePair.first->clone(osg::CopyOp::DEEP_COPY_NODES)); sheathParent->addChild(copy); } } } void injectCustomBones( osg::ref_ptr<osg::Node>& node, const std::string& model, Resource::ResourceSystem* resourceSystem) { if (model.empty()) return; std::string animationPath = model; if (animationPath.find("meshes") == 0) { animationPath.replace(0, 6, "animations"); } animationPath.replace(animationPath.size() - 4, 4, "/"); for (const VFS::Path::Normalized& name : resourceSystem->getVFS()->getRecursiveDirectoryIterator(animationPath)) { if (Misc::getFileExtension(name) == "nif") loadBonesFromFile(node, name, resourceSystem); } } osg::ref_ptr<osg::Node> getModelInstance(Resource::ResourceSystem* resourceSystem, const std::string& model, bool baseonly, bool inject, const std::string& defaultSkeleton) { Resource::SceneManager* sceneMgr = resourceSystem->getSceneManager(); if (baseonly) { typedef std::map<std::string, osg::ref_ptr<osg::Node>> Cache; static Cache cache; Cache::iterator found = cache.find(model); if (found == cache.end()) { osg::ref_ptr<osg::Node> created = sceneMgr->getInstance(VFS::Path::toNormalized(model)); if (inject) { injectCustomBones(created, defaultSkeleton, resourceSystem); injectCustomBones(created, model, resourceSystem); } SceneUtil::CleanObjectRootVisitor removeDrawableVisitor; created->accept(removeDrawableVisitor); removeDrawableVisitor.remove(); cache.insert(std::make_pair(model, created)); return sceneMgr->getInstance(created); } else return sceneMgr->getInstance(found->second); } else { osg::ref_ptr<osg::Node> created = sceneMgr->getInstance(VFS::Path::toNormalized(model)); if (inject) { injectCustomBones(created, defaultSkeleton, resourceSystem); injectCustomBones(created, model, resourceSystem); } return created; } } void Animation::setObjectRoot(const std::string& model, bool forceskeleton, bool baseonly, bool isCreature) { osg::ref_ptr<osg::StateSet> previousStateset; if (mObjectRoot) { if (mLightListCallback) mObjectRoot->removeCullCallback(mLightListCallback); if (mTransparencyUpdater) mObjectRoot->removeCullCallback(mTransparencyUpdater); previousStateset = mObjectRoot->getStateSet(); mObjectRoot->getParent(0)->removeChild(mObjectRoot); } mObjectRoot = nullptr; mSkeleton = nullptr; mNodeMap.clear(); mNodeMapCreated = false; mActiveControllers.clear(); mAccumRoot = nullptr; mAccumCtrl = nullptr; std::string defaultSkeleton; bool inject = false; if (Settings::game().mUseAdditionalAnimSources && mPtr.getClass().isActor()) { if (isCreature) { MWWorld::LiveCellRef<ESM::Creature>* ref = mPtr.get<ESM::Creature>(); if (ref->mBase->mFlags & ESM::Creature::Bipedal) { defaultSkeleton = Settings::models().mXbaseanim.get().value(); inject = true; } } else { inject = true; MWWorld::LiveCellRef<ESM::NPC>* ref = mPtr.get<ESM::NPC>(); if (!ref->mBase->mModel.empty()) { // If NPC has a custom animation model attached, we should inject bones from default skeleton for // given race and gender as well Since it is a quite rare case, there should not be a noticable // performance loss Note: consider that player and werewolves have no custom animation files // attached for now const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); const ESM::Race* race = store.get<ESM::Race>().find(ref->mBase->mRace); const bool firstPerson = false; const bool isBeast = (race->mData.mFlags & ESM::Race::Beast) != 0; const bool isFemale = !ref->mBase->isMale(); const bool werewolf = false; defaultSkeleton = Misc::ResourceHelpers::correctActorModelPath( VFS::Path::toNormalized(getActorSkeleton(firstPerson, isFemale, isBeast, werewolf)), mResourceSystem->getVFS()); } } } if (!forceskeleton) { osg::ref_ptr<osg::Node> created = getModelInstance(mResourceSystem, model, baseonly, inject, defaultSkeleton); mInsert->addChild(created); mObjectRoot = created->asGroup(); if (!mObjectRoot) { mInsert->removeChild(created); mObjectRoot = new osg::Group; mObjectRoot->addChild(created); mInsert->addChild(mObjectRoot); } osg::ref_ptr<SceneUtil::Skeleton> skel = dynamic_cast<SceneUtil::Skeleton*>(mObjectRoot.get()); if (skel) mSkeleton = skel.get(); } else { osg::ref_ptr<osg::Node> created = getModelInstance(mResourceSystem, model, baseonly, inject, defaultSkeleton); osg::ref_ptr<SceneUtil::Skeleton> skel = dynamic_cast<SceneUtil::Skeleton*>(created.get()); if (!skel) { skel = new SceneUtil::Skeleton; skel->addChild(created); } mSkeleton = skel.get(); mObjectRoot = skel; mInsert->addChild(mObjectRoot); } // osgAnimation formats with skeletons should have their nodemap be bone instances // FIXME: better way to detect osgAnimation here instead of relying on extension? mRequiresBoneMap = mSkeleton != nullptr && !Misc::StringUtils::ciEndsWith(model, ".nif"); if (previousStateset) mObjectRoot->setStateSet(previousStateset); if (isCreature) { SceneUtil::RemoveTriBipVisitor removeTriBipVisitor; mObjectRoot->accept(removeTriBipVisitor); removeTriBipVisitor.remove(); } if (!mLightListCallback) mLightListCallback = new SceneUtil::LightListCallback; mObjectRoot->addCullCallback(mLightListCallback); if (mTransparencyUpdater) mObjectRoot->addCullCallback(mTransparencyUpdater); } osg::Group* Animation::getObjectRoot() { return mObjectRoot.get(); } osg::Group* Animation::getOrCreateObjectRoot() { if (mObjectRoot) return mObjectRoot.get(); mObjectRoot = new osg::Group; mInsert->addChild(mObjectRoot); return mObjectRoot.get(); } void Animation::addSpellCastGlow(const osg::Vec4f& color, float glowDuration) { if (!mGlowUpdater || (mGlowUpdater->isDone() || (mGlowUpdater->isPermanentGlowUpdater() == true))) { if (mGlowUpdater && mGlowUpdater->isDone()) mObjectRoot->removeUpdateCallback(mGlowUpdater); if (mGlowUpdater && mGlowUpdater->isPermanentGlowUpdater()) { mGlowUpdater->setColor(color); mGlowUpdater->setDuration(glowDuration); } else mGlowUpdater = SceneUtil::addEnchantedGlow(mObjectRoot, mResourceSystem, color, glowDuration); } } void Animation::addExtraLight(osg::ref_ptr<osg::Group> parent, const SceneUtil::LightCommon& esmLight) { bool exterior = mPtr.isInCell() && mPtr.getCell()->getCell()->isExterior(); mExtraLightSource = SceneUtil::addLight(parent, esmLight, Mask_Lighting, exterior); mExtraLightSource->setActorFade(mAlpha); } void Animation::addEffect(std::string_view model, std::string_view effectId, bool loop, std::string_view bonename, std::string_view texture) { if (!mObjectRoot.get()) return; // Early out if we already have this effect FindVfxCallbacksVisitor visitor(effectId); mInsert->accept(visitor); for (std::vector<UpdateVfxCallback*>::iterator it = visitor.mCallbacks.begin(); it != visitor.mCallbacks.end(); ++it) { UpdateVfxCallback* callback = *it; if (loop && !callback->mFinished && callback->mParams.mLoop && callback->mParams.mBoneName == bonename) return; } EffectParams params; params.mModelName = model; osg::ref_ptr<osg::Group> parentNode; if (bonename.empty()) parentNode = mInsert; else { NodeMap::const_iterator found = getNodeMap().find(bonename); if (found == getNodeMap().end()) throw std::runtime_error("Can't find bone " + std::string{ bonename }); parentNode = found->second; } osg::ref_ptr<SceneUtil::PositionAttitudeTransform> trans = new SceneUtil::PositionAttitudeTransform; if (!mPtr.getClass().isNpc()) { osg::Vec3f bounds(MWBase::Environment::get().getWorld()->getHalfExtents(mPtr) * 2.f); float scale = std::max({ bounds.x(), bounds.y(), bounds.z() / 2.f }) / 64.f; if (scale > 1.f) trans->setScale(osg::Vec3f(scale, scale, scale)); float offset = 0.f; if (bounds.z() < 128.f) offset = bounds.z() - 128.f; else if (bounds.z() < bounds.x() + bounds.y()) offset = 128.f - bounds.z(); if (MWBase::Environment::get().getWorld()->isFlying(mPtr)) offset /= 20.f; trans->setPosition(osg::Vec3f(0.f, 0.f, offset * scale)); } parentNode->addChild(trans); osg::ref_ptr<osg::Node> node = mResourceSystem->getSceneManager()->getInstance(VFS::Path::toNormalized(model), trans); // Morrowind has a white ambient light attached to the root VFX node of the scenegraph node->getOrCreateStateSet()->setAttributeAndModes( getVFXLightModelInstance(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); mResourceSystem->getSceneManager()->setUpNormalsRTForStateSet(node->getOrCreateStateSet(), false); SceneUtil::FindMaxControllerLengthVisitor findMaxLengthVisitor; node->accept(findMaxLengthVisitor); node->setNodeMask(Mask_Effect); MarkDrawablesVisitor markVisitor(Mask_Effect); node->accept(markVisitor); params.mMaxControllerLength = findMaxLengthVisitor.getMaxLength(); params.mLoop = loop; params.mEffectId = effectId; params.mBoneName = bonename; params.mAnimTime = std::make_shared<EffectAnimationTime>(); trans->addUpdateCallback(new UpdateVfxCallback(params)); SceneUtil::AssignControllerSourcesVisitor assignVisitor( std::shared_ptr<SceneUtil::ControllerSource>(params.mAnimTime)); node->accept(assignVisitor); // Notify that this animation has attached magic effects mHasMagicEffects = true; overrideFirstRootTexture(texture, mResourceSystem, *node); } void Animation::removeEffect(std::string_view effectId) { RemoveCallbackVisitor visitor(effectId); mInsert->accept(visitor); visitor.remove(); mHasMagicEffects = visitor.mHasMagicEffects; } void Animation::removeEffects() { removeEffect(""); } std::vector<std::string_view> Animation::getLoopingEffects() const { if (!mHasMagicEffects) return {}; FindVfxCallbacksVisitor visitor; mInsert->accept(visitor); std::vector<std::string_view> out; for (std::vector<UpdateVfxCallback*>::iterator it = visitor.mCallbacks.begin(); it != visitor.mCallbacks.end(); ++it) { UpdateVfxCallback* callback = *it; if (callback->mParams.mLoop && !callback->mFinished) out.push_back(callback->mParams.mEffectId); } return out; } void Animation::updateEffects() { // We do not need to visit scene every frame. // We can use a bool flag to check in spellcasting effect found. if (!mHasMagicEffects) return; // TODO: objects without animation still will have // transformation nodes with finished callbacks RemoveFinishedCallbackVisitor visitor; mInsert->accept(visitor); visitor.remove(); mHasMagicEffects = visitor.mHasMagicEffects; } bool Animation::upperBodyReady() const { for (AnimStateMap::const_iterator stateiter = mStates.begin(); stateiter != mStates.end(); ++stateiter) { if (stateiter->second.mPriority.contains(int(MWMechanics::Priority_Hit)) || stateiter->second.mPriority.contains(int(MWMechanics::Priority_Weapon)) || stateiter->second.mPriority.contains(int(MWMechanics::Priority_Knockdown)) || stateiter->second.mPriority.contains(int(MWMechanics::Priority_Death))) return false; } return true; } const osg::Node* Animation::getNode(std::string_view name) const { NodeMap::const_iterator found = getNodeMap().find(name); if (found == getNodeMap().end()) return nullptr; else return found->second; } void Animation::setAlpha(float alpha) { if (alpha == mAlpha) return; mAlpha = alpha; // TODO: we use it to fade actors away too, but it would be nice to have a dithering shader instead. if (alpha != 1.f) { if (mTransparencyUpdater == nullptr) { mTransparencyUpdater = new TransparencyUpdater(alpha); mObjectRoot->addCullCallback(mTransparencyUpdater); } else mTransparencyUpdater->setAlpha(alpha); } else { mObjectRoot->removeCullCallback(mTransparencyUpdater); mTransparencyUpdater = nullptr; } if (mExtraLightSource) mExtraLightSource->setActorFade(alpha); } void Animation::setLightEffect(float effect) { if (effect == 0) { if (mGlowLight) { mInsert->removeChild(mGlowLight); mGlowLight = nullptr; } } else { // 1 pt of Light magnitude corresponds to 1 foot of radius float radius = effect * std::ceil(Constants::UnitsPerFoot); // Arbitrary multiplier used to make the obvious cut-off less obvious float cutoffMult = 3; if (!mGlowLight || (radius * cutoffMult) != mGlowLight->getRadius()) { if (mGlowLight) { mInsert->removeChild(mGlowLight); mGlowLight = nullptr; } osg::ref_ptr<osg::Light> light(new osg::Light); light->setDiffuse(osg::Vec4f(0, 0, 0, 0)); light->setSpecular(osg::Vec4f(0, 0, 0, 0)); light->setAmbient(osg::Vec4f(1.5f, 1.5f, 1.5f, 1.f)); bool isExterior = mPtr.isInCell() && mPtr.getCell()->getCell()->isExterior(); SceneUtil::configureLight(light, radius, isExterior); mGlowLight = new SceneUtil::LightSource; mGlowLight->setNodeMask(Mask_Lighting); mInsert->addChild(mGlowLight); mGlowLight->setLight(light); } mGlowLight->setRadius(radius * cutoffMult); } } void Animation::addControllers() { mHeadController = addRotateController("bip01 head"); mSpineController = addRotateController("bip01 spine1"); mRootController = addRotateController("bip01"); } osg::ref_ptr<RotateController> Animation::addRotateController(std::string_view bone) { auto iter = getNodeMap().find(bone); if (iter == getNodeMap().end()) return nullptr; osg::MatrixTransform* node = iter->second; bool foundKeyframeCtrl = false; osg::Callback* cb = node->getUpdateCallback(); while (cb) { if (dynamic_cast<NifAnimBlendController*>(cb) || dynamic_cast<BoneAnimBlendController*>(cb) || dynamic_cast<SceneUtil::KeyframeController*>(cb)) { foundKeyframeCtrl = true; break; } cb = cb->getNestedCallback(); } // Note: AnimBlendController also does the reset so if one is present - we should add the rotation node // Without KeyframeController the orientation will not be reseted each frame, so // RotateController shouldn't be used for such nodes. if (!foundKeyframeCtrl) return nullptr; osg::ref_ptr<RotateController> controller(new RotateController(mObjectRoot.get())); node->addUpdateCallback(controller); mActiveControllers.emplace_back(node, controller); return controller; } void Animation::setHeadPitch(float pitchRadians) { mHeadPitchRadians = pitchRadians; } void Animation::setHeadYaw(float yawRadians) { mHeadYawRadians = yawRadians; } float Animation::getHeadPitch() const { return mHeadPitchRadians; } float Animation::getHeadYaw() const { return mHeadYawRadians; } void Animation::removeFromScene() { removeFromSceneImpl(); } void Animation::removeFromSceneImpl() { if (mGlowLight != nullptr) mInsert->removeChild(mGlowLight); if (mObjectRoot != nullptr) mInsert->removeChild(mObjectRoot); } MWWorld::MovementDirectionFlags Animation::getSupportedMovementDirections( std::span<const std::string_view> prefixes) const { MWWorld::MovementDirectionFlags result = 0; for (const std::string_view animation : mSupportedAnimations) { if (std::find_if( prefixes.begin(), prefixes.end(), [&](std::string_view v) { return animation.starts_with(v); }) == prefixes.end()) continue; if (animation.ends_with("forward")) result |= MWWorld::MovementDirectionFlag_Forward; else if (animation.ends_with("back")) result |= MWWorld::MovementDirectionFlag_Back; else if (animation.ends_with("left")) result |= MWWorld::MovementDirectionFlag_Left; else if (animation.ends_with("right")) result |= MWWorld::MovementDirectionFlag_Right; } return result; } // ------------------------------------------------------ float Animation::AnimationTime::getValue(osg::NodeVisitor*) { if (mTimePtr) return *mTimePtr; return 0.f; } float EffectAnimationTime::getValue(osg::NodeVisitor*) { return mTime; } void EffectAnimationTime::addTime(float duration) { mTime += duration; } void EffectAnimationTime::resetTime(float time) { mTime = time; } float EffectAnimationTime::getTime() const { return mTime; } // -------------------------------------------------------------------------------- ObjectAnimation::ObjectAnimation(const MWWorld::Ptr& ptr, const std::string& model, Resource::ResourceSystem* resourceSystem, bool animated, bool allowLight) : Animation(ptr, osg::ref_ptr<osg::Group>(ptr.getRefData().getBaseNode()), resourceSystem) { if (!model.empty()) { setObjectRoot(model, false, false, false); if (animated) addAnimSource(model, model); if (!ptr.getClass().getEnchantment(ptr).empty()) mGlowUpdater = SceneUtil::addEnchantedGlow( mObjectRoot, mResourceSystem, ptr.getClass().getEnchantmentColor(ptr)); } if (ptr.getType() == ESM::Light::sRecordId && allowLight) addExtraLight(getOrCreateObjectRoot(), SceneUtil::LightCommon(*ptr.get<ESM::Light>()->mBase)); if (ptr.getType() == ESM4::Light::sRecordId && allowLight) addExtraLight(getOrCreateObjectRoot(), SceneUtil::LightCommon(*ptr.get<ESM4::Light>()->mBase)); if (!allowLight && mObjectRoot) { RemoveParticlesVisitor visitor; mObjectRoot->accept(visitor); visitor.remove(); } if (Settings::game().mDayNightSwitches && SceneUtil::hasUserDescription(mObjectRoot, Constants::NightDayLabel)) { AddSwitchCallbacksVisitor visitor; mObjectRoot->accept(visitor); } if (Settings::game().mGraphicHerbalism && ptr.getRefData().getCustomData() != nullptr && ObjectAnimation::canBeHarvested()) { const MWWorld::ContainerStore& store = ptr.getClass().getContainerStore(ptr); if (!store.hasVisibleItems()) { HarvestVisitor visitor; mObjectRoot->accept(visitor); } } } bool ObjectAnimation::canBeHarvested() const { if (mPtr.getType() != ESM::Container::sRecordId) return false; const MWWorld::LiveCellRef<ESM::Container>* ref = mPtr.get<ESM::Container>(); if (!(ref->mBase->mFlags & ESM::Container::Organic)) return false; return SceneUtil::hasUserDescription(mObjectRoot, Constants::HerbalismLabel); } // ------------------------------ PartHolder::PartHolder(osg::ref_ptr<osg::Node> node) : mNode(std::move(node)) { } PartHolder::~PartHolder() { if (mNode.get() && !mNode->getNumParents()) Log(Debug::Verbose) << "Part \"" << mNode->getName() << "\" has no parents"; if (mNode.get() && mNode->getNumParents()) { if (mNode->getNumParents() > 1) Log(Debug::Verbose) << "Part \"" << mNode->getName() << "\" has multiple (" << mNode->getNumParents() << ") parents"; mNode->getParent(0)->removeChild(mNode); } } }
77,635
C++
.cpp
1,821
31.136189
120
0.582878
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,395
creatureanimation.cpp
OpenMW_openmw/apps/openmw/mwrender/creatureanimation.cpp
#include "creatureanimation.hpp" #include <osg/MatrixTransform> #include <components/debug/debuglog.hpp> #include <components/esm3/loadcrea.hpp> #include <components/resource/resourcesystem.hpp> #include <components/sceneutil/lightcommon.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/visitor.hpp> #include <components/settings/values.hpp> #include "../mwmechanics/weapontype.hpp" #include "../mwworld/class.hpp" namespace MWRender { CreatureAnimation::CreatureAnimation( const MWWorld::Ptr& ptr, const std::string& model, Resource::ResourceSystem* resourceSystem, bool animated) : ActorAnimation(ptr, osg::ref_ptr<osg::Group>(ptr.getRefData().getBaseNode()), resourceSystem) { MWWorld::LiveCellRef<ESM::Creature>* ref = mPtr.get<ESM::Creature>(); if (!model.empty()) { setObjectRoot(model, false, false, true); if ((ref->mBase->mFlags & ESM::Creature::Bipedal)) addAnimSource(Settings::models().mXbaseanim.get(), model); if (animated) addAnimSource(model, model); } } CreatureWeaponAnimation::CreatureWeaponAnimation( const MWWorld::Ptr& ptr, const std::string& model, Resource::ResourceSystem* resourceSystem, bool animated) : ActorAnimation(ptr, osg::ref_ptr<osg::Group>(ptr.getRefData().getBaseNode()), resourceSystem) , mShowWeapons(false) , mShowCarriedLeft(false) { MWWorld::LiveCellRef<ESM::Creature>* ref = mPtr.get<ESM::Creature>(); if (!model.empty()) { setObjectRoot(model, true, false, true); if ((ref->mBase->mFlags & ESM::Creature::Bipedal)) addAnimSource(Settings::models().mXbaseanim.get(), model); if (animated) addAnimSource(model, model); mPtr.getClass().getInventoryStore(mPtr).setInvListener(this); updateParts(); } mWeaponAnimationTime = std::make_shared<WeaponAnimationTime>(this); } void CreatureWeaponAnimation::showWeapons(bool showWeapon) { if (showWeapon != mShowWeapons) { mShowWeapons = showWeapon; updateParts(); } } void CreatureWeaponAnimation::showCarriedLeft(bool show) { if (show != mShowCarriedLeft) { mShowCarriedLeft = show; updateParts(); } } void CreatureWeaponAnimation::updateParts() { mAmmunition.reset(); mWeapon.reset(); mShield.reset(); updateHolsteredWeapon(!mShowWeapons); updateQuiver(); updateHolsteredShield(mShowCarriedLeft); if (mShowWeapons) updatePart(mWeapon, MWWorld::InventoryStore::Slot_CarriedRight); if (mShowCarriedLeft) updatePart(mShield, MWWorld::InventoryStore::Slot_CarriedLeft); } void CreatureWeaponAnimation::updatePart(PartHolderPtr& scene, int slot) { if (!mObjectRoot) return; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator it = inv.getSlot(slot); if (it == inv.end()) { scene.reset(); return; } MWWorld::ConstPtr item = *it; std::string_view bonename; VFS::Path::Normalized itemModel = item.getClass().getCorrectedModel(item); if (slot == MWWorld::InventoryStore::Slot_CarriedRight) { if (item.getType() == ESM::Weapon::sRecordId) { int type = item.get<ESM::Weapon>()->mBase->mData.mType; bonename = MWMechanics::getWeaponType(type)->mAttachBone; if (bonename != "Weapon Bone") { const NodeMap& nodeMap = getNodeMap(); NodeMap::const_iterator found = nodeMap.find(bonename); if (found == nodeMap.end()) bonename = "Weapon Bone"; } } else bonename = "Weapon Bone"; } else { bonename = "Shield Bone"; if (item.getType() == ESM::Armor::sRecordId) { itemModel = getShieldMesh(item, false); } } try { osg::ref_ptr<osg::Node> attached = attach(itemModel, bonename, bonename, item.getType() == ESM::Light::sRecordId); scene = std::make_unique<PartHolder>(attached); if (!item.getClass().getEnchantment(item).empty()) mGlowUpdater = SceneUtil::addEnchantedGlow(attached, mResourceSystem, item.getClass().getEnchantmentColor(item)); // Crossbows start out with a bolt attached // FIXME: code duplicated from NpcAnimation if (slot == MWWorld::InventoryStore::Slot_CarriedRight && item.getType() == ESM::Weapon::sRecordId && item.get<ESM::Weapon>()->mBase->mData.mType == ESM::Weapon::MarksmanCrossbow) { const ESM::WeaponType* weaponInfo = MWMechanics::getWeaponType(ESM::Weapon::MarksmanCrossbow); MWWorld::ConstContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && ammo->get<ESM::Weapon>()->mBase->mData.mType == weaponInfo->mAmmoType) attachArrow(); else mAmmunition.reset(); } else mAmmunition.reset(); std::shared_ptr<SceneUtil::ControllerSource> source; if (slot == MWWorld::InventoryStore::Slot_CarriedRight) source = mWeaponAnimationTime; else source = mAnimationTimePtr[0]; SceneUtil::AssignControllerSourcesVisitor assignVisitor(std::move(source)); attached->accept(assignVisitor); if (item.getType() == ESM::Light::sRecordId) addExtraLight(scene->getNode()->asGroup(), SceneUtil::LightCommon(*item.get<ESM::Light>()->mBase)); } catch (std::exception& e) { Log(Debug::Error) << "Can not add creature part: " << e.what(); } } bool CreatureWeaponAnimation::isArrowAttached() const { return mAmmunition != nullptr; } void CreatureWeaponAnimation::detachArrow() { WeaponAnimation::detachArrow(mPtr); updateQuiver(); } void CreatureWeaponAnimation::attachArrow() { WeaponAnimation::attachArrow(mPtr); const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && !ammo->getClass().getEnchantment(*ammo).empty()) { osg::Group* bone = getArrowBone(); if (bone != nullptr && bone->getNumChildren()) SceneUtil::addEnchantedGlow( bone->getChild(0), mResourceSystem, ammo->getClass().getEnchantmentColor(*ammo)); } updateQuiver(); } void CreatureWeaponAnimation::releaseArrow(float attackStrength) { WeaponAnimation::releaseArrow(mPtr, attackStrength); updateQuiver(); } osg::Group* CreatureWeaponAnimation::getArrowBone() { if (!mWeapon) return nullptr; if (!mPtr.getClass().hasInventoryStore(mPtr)) return nullptr; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return nullptr; int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; int ammoType = MWMechanics::getWeaponType(type)->mAmmoType; if (ammoType == ESM::Weapon::None) return nullptr; // Try to find and attachment bone in actor's skeleton, otherwise fall back to the ArrowBone in weapon's mesh osg::Group* bone = getBoneByName(MWMechanics::getWeaponType(ammoType)->mAttachBone); if (bone == nullptr) { SceneUtil::FindByNameVisitor findVisitor("ArrowBone"); mWeapon->getNode()->accept(findVisitor); bone = findVisitor.mFoundNode; } return bone; } osg::Node* CreatureWeaponAnimation::getWeaponNode() { return mWeapon ? mWeapon->getNode().get() : nullptr; } Resource::ResourceSystem* CreatureWeaponAnimation::getResourceSystem() { return mResourceSystem; } void CreatureWeaponAnimation::addControllers() { Animation::addControllers(); WeaponAnimation::addControllers(mNodeMap, mActiveControllers, mObjectRoot.get()); } osg::Vec3f CreatureWeaponAnimation::runAnimation(float duration) { osg::Vec3f ret = Animation::runAnimation(duration); WeaponAnimation::configureControllers(mPtr.getRefData().getPosition().rot[0] + getBodyPitchRadians()); return ret; } }
9,333
C++
.cpp
223
31.762332
120
0.615962
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,396
landmanager.cpp
OpenMW_openmw/apps/openmw/mwrender/landmanager.cpp
#include "landmanager.hpp" #include <components/esm4/loadwrld.hpp> #include <components/resource/objectcache.hpp> #include <components/settings/values.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/esmstore.hpp" namespace MWRender { LandManager::LandManager(int loadFlags) : GenericResourceManager<ESM::ExteriorCellLocation>(nullptr, Settings::cells().mCacheExpiryDelay) , mLoadFlags(loadFlags) { } osg::ref_ptr<ESMTerrain::LandObject> LandManager::getLand(ESM::ExteriorCellLocation cellIndex) { const MWBase::World& world = *MWBase::Environment::get().getWorld(); if (ESM::isEsm4Ext(cellIndex.mWorldspace)) { const ESM4::World* worldspace = world.getStore().get<ESM4::World>().find(cellIndex.mWorldspace); if (!worldspace->mParent.isZeroOrUnset() && worldspace->mParentUseFlags & ESM4::World::UseFlag_Land) cellIndex.mWorldspace = worldspace->mParent; } if (const std::optional<osg::ref_ptr<osg::Object>> obj = mCache->getRefFromObjectCacheOrNone(cellIndex)) return static_cast<ESMTerrain::LandObject*>(obj->get()); osg::ref_ptr<ESMTerrain::LandObject> landObj = nullptr; if (ESM::isEsm4Ext(cellIndex.mWorldspace)) { const ESM4::Land* land = world.getStore().get<ESM4::Land>().search(cellIndex); if (land != nullptr) landObj = new ESMTerrain::LandObject(*land, mLoadFlags); } else { const ESM::Land* land = world.getStore().get<ESM::Land>().search(cellIndex.mX, cellIndex.mY); if (land != nullptr) landObj = new ESMTerrain::LandObject(*land, mLoadFlags); } mCache->addEntryToObjectCache(cellIndex, landObj.get()); return landObj; } void LandManager::reportStats(unsigned int frameNumber, osg::Stats* stats) const { Resource::reportStats("Land", frameNumber, mCache->getStats(), *stats); } }
2,054
C++
.cpp
46
36.804348
112
0.660491
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,397
recastmesh.cpp
OpenMW_openmw/apps/openmw/mwrender/recastmesh.cpp
#include "recastmesh.hpp" #include <algorithm> #include <components/detournavigator/recastmesh.hpp> #include <components/detournavigator/settings.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/detourdebugdraw.hpp> #include <components/sceneutil/recastmesh.hpp> #include <osg/PositionAttitudeTransform> #include "vismask.hpp" #include "../mwbase/environment.hpp" namespace MWRender { namespace { osg::ref_ptr<osg::StateSet> makeDebugDrawStateSet() { osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet; stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); return stateSet; } } RecastMesh::RecastMesh(const osg::ref_ptr<osg::Group>& root, bool enabled) : mRootNode(root) , mEnabled(enabled) , mGroupStateSet(SceneUtil::makeDetourGroupStateSet()) , mDebugDrawStateSet(makeDebugDrawStateSet()) { } RecastMesh::~RecastMesh() { if (mEnabled) disable(); } bool RecastMesh::toggle() { if (mEnabled) disable(); else enable(); return mEnabled; } void RecastMesh::update(const DetourNavigator::RecastMeshTiles& tiles, const DetourNavigator::Settings& settings) { if (!mEnabled) return; for (auto it = mGroups.begin(); it != mGroups.end();) { const auto tile = tiles.find(it->first); if (tile == tiles.end()) { mRootNode->removeChild(it->second.mValue); it = mGroups.erase(it); continue; } if (it->second.mVersion != tile->second->getVersion()) { const osg::ref_ptr<osg::Group> group = SceneUtil::createRecastMeshGroup(*tile->second, settings.mRecast, mDebugDrawStateSet); group->setNodeMask(Mask_Debug); group->setStateSet(mGroupStateSet); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(group, "debug"); mRootNode->removeChild(it->second.mValue); mRootNode->addChild(group); it->second.mValue = group; it->second.mVersion = tile->second->getVersion(); } ++it; } for (const auto& [position, mesh] : tiles) { const auto it = mGroups.find(position); if (it != mGroups.end()) { if (it->second.mVersion == mesh->getVersion()) continue; mRootNode->removeChild(it->second.mValue); } const osg::ref_ptr<osg::Group> group = SceneUtil::createRecastMeshGroup(*mesh, settings.mRecast, mDebugDrawStateSet); group->setNodeMask(Mask_Debug); group->setStateSet(mGroupStateSet); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(group, "debug"); mGroups.insert_or_assign(it, position, Group{ mesh->getVersion(), group }); mRootNode->addChild(group); } } void RecastMesh::reset() { std::for_each(mGroups.begin(), mGroups.end(), [&](const auto& v) { mRootNode->removeChild(v.second.mValue); }); mGroups.clear(); } void RecastMesh::enable() { std::for_each(mGroups.begin(), mGroups.end(), [&](const auto& v) { mRootNode->addChild(v.second.mValue); }); mEnabled = true; } void RecastMesh::disable() { std::for_each(mGroups.begin(), mGroups.end(), [&](const auto& v) { mRootNode->removeChild(v.second.mValue); }); mEnabled = false; } }
3,848
C++
.cpp
103
27.825243
119
0.592254
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,398
sky.cpp
OpenMW_openmw/apps/openmw/mwrender/sky.cpp
#include "sky.hpp" #include <osg/Depth> #include <osg/PositionAttitudeTransform> #include <osgParticle/BoxPlacer> #include <osgParticle/ModularEmitter> #include <osgParticle/ModularProgram> #include <osgParticle/Operator> #include <osgParticle/ParticleSystemUpdater> #include <components/settings/values.hpp> #include <components/sceneutil/controller.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/rtt.hpp> #include <components/sceneutil/shadow.hpp> #include <components/sceneutil/visitor.hpp> #include <components/resource/imagemanager.hpp> #include <components/resource/scenemanager.hpp> #include <components/vfs/manager.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/stereo/stereomanager.hpp> #include <components/nifosg/particle.hpp> #include "../mwworld/datetimemanager.hpp" #include "../mwworld/weather.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "renderbin.hpp" #include "skyutil.hpp" #include "util.hpp" #include "vismask.hpp" namespace { class WrapAroundOperator : public osgParticle::Operator { public: WrapAroundOperator(osg::Camera* camera, const osg::Vec3& wrapRange) : osgParticle::Operator() , mCamera(camera) , mWrapRange(wrapRange) , mHalfWrapRange(mWrapRange / 2.0) { mPreviousCameraPosition = getCameraPosition(); } osg::Object* cloneType() const override { return nullptr; } osg::Object* clone(const osg::CopyOp& op) const override { return nullptr; } void operate(osgParticle::Particle* P, double dt) override {} void operateParticles(osgParticle::ParticleSystem* ps, double dt) override { osg::Vec3 position = getCameraPosition(); osg::Vec3 positionDifference = position - mPreviousCameraPosition; osg::Matrix toWorld, toLocal; std::vector<osg::Matrix> worldMatrices = ps->getWorldMatrices(); if (!worldMatrices.empty()) { toWorld = worldMatrices[0]; toLocal.invert(toWorld); } for (int i = 0; i < ps->numParticles(); ++i) { osgParticle::Particle* p = ps->getParticle(i); p->setPosition(toWorld.preMult(p->getPosition())); p->setPosition(p->getPosition() - positionDifference); for (int j = 0; j < 3; ++j) // wrap-around in all 3 dimensions { osg::Vec3 pos = p->getPosition(); if (pos[j] < -mHalfWrapRange[j]) pos[j] = mHalfWrapRange[j] + fmod(pos[j] - mHalfWrapRange[j], mWrapRange[j]); else if (pos[j] > mHalfWrapRange[j]) pos[j] = fmod(pos[j] + mHalfWrapRange[j], mWrapRange[j]) - mHalfWrapRange[j]; p->setPosition(pos); } p->setPosition(toLocal.preMult(p->getPosition())); } mPreviousCameraPosition = position; } protected: osg::Camera* mCamera; osg::Vec3 mPreviousCameraPosition; osg::Vec3 mWrapRange; osg::Vec3 mHalfWrapRange; osg::Vec3 getCameraPosition() { return mCamera->getInverseViewMatrix().getTrans(); } }; class WeatherAlphaOperator : public osgParticle::Operator { public: WeatherAlphaOperator(float& alpha, bool rain) : mAlpha(alpha) , mIsRain(rain) { } osg::Object* cloneType() const override { return nullptr; } osg::Object* clone(const osg::CopyOp& op) const override { return nullptr; } void operate(osgParticle::Particle* particle, double dt) override { constexpr float rainThreshold = 0.6f; // Rain_Threshold? float alpha = mIsRain ? mAlpha * rainThreshold : mAlpha; particle->setAlphaRange(osgParticle::rangef(alpha, alpha)); } private: float& mAlpha; bool mIsRain; }; // Updater for alpha value on a node's StateSet. Assumes the node has an existing Material StateAttribute. class AlphaFader : public SceneUtil::StateSetUpdater { public: /// @param alpha the variable alpha value is recovered from AlphaFader(const float& alpha) : mAlpha(alpha) { } void setDefaults(osg::StateSet* stateset) override { // need to create a deep copy of StateAttributes we will modify osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); stateset->setAttribute(osg::clone(mat, osg::CopyOp::DEEP_COPY_ALL), osg::StateAttribute::ON); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, mAlpha)); } protected: const float& mAlpha; }; // Helper for adding AlphaFaders to a subgraph class SetupVisitor : public osg::NodeVisitor { public: SetupVisitor(const float& alpha) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mAlpha(alpha) { } void apply(osg::Node& node) override { if (osg::StateSet* stateset = node.getStateSet()) { if (stateset->getAttribute(osg::StateAttribute::MATERIAL)) { SceneUtil::CompositeStateSetUpdater* composite = nullptr; osg::Callback* callback = node.getUpdateCallback(); while (callback) { composite = dynamic_cast<SceneUtil::CompositeStateSetUpdater*>(callback); if (composite) break; callback = callback->getNestedCallback(); } osg::ref_ptr<AlphaFader> alphaFader = new AlphaFader(mAlpha); if (composite) composite->addController(alphaFader); else node.addUpdateCallback(alphaFader); } } traverse(node); } private: const float& mAlpha; }; class SkyRTT : public SceneUtil::RTTNode { public: SkyRTT(osg::Vec2f size, osg::Group* earlyRenderBinRoot) : RTTNode(static_cast<int>(size.x()), static_cast<int>(size.y()), 0, false, 1, StereoAwareness::Aware, MWRender::shouldAddMSAAIntermediateTarget()) , mEarlyRenderBinRoot(earlyRenderBinRoot) { setDepthBufferInternalFormat(GL_DEPTH24_STENCIL8); } void setDefaults(osg::Camera* camera) override { camera->setReferenceFrame(osg::Camera::RELATIVE_RF); camera->setName("SkyCamera"); camera->setNodeMask(MWRender::Mask_RenderToTexture); camera->setCullMask(MWRender::Mask_Sky); camera->addChild(mEarlyRenderBinRoot); SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*camera->getOrCreateStateSet()); } private: osg::ref_ptr<osg::Group> mEarlyRenderBinRoot; }; } namespace MWRender { SkyManager::SkyManager(osg::Group* parentNode, osg::Group* rootNode, osg::Camera* camera, Resource::SceneManager* sceneManager, bool enableSkyRTT) : mSceneManager(sceneManager) , mCamera(camera) , mAtmosphereNightRoll(0.f) , mCreated(false) , mIsStorm(false) , mTimescaleClouds(Fallback::Map::getBool("Weather_Timescale_Clouds")) , mCloudAnimationTimer(0.f) , mStormParticleDirection(MWWorld::Weather::defaultDirection()) , mStormDirection(MWWorld::Weather::defaultDirection()) , mClouds() , mNextClouds() , mCloudBlendFactor(0.f) , mCloudSpeed(0.f) , mStarsOpacity(0.f) , mRainSpeed(0.f) , mRainDiameter(0.f) , mRainMinHeight(0.f) , mRainMaxHeight(0.f) , mRainEntranceSpeed(1.f) , mRainMaxRaindrops(0) , mRainRipplesEnabled(Fallback::Map::getBool("Weather_Rain_Ripples")) , mSnowRipplesEnabled(Fallback::Map::getBool("Weather_Snow_Ripples")) , mWindSpeed(0.f) , mBaseWindSpeed(0.f) , mEnabled(true) , mSunglareEnabled(true) , mPrecipitationAlpha(0.f) , mDirtyParticlesEffect(false) { osg::ref_ptr<CameraRelativeTransform> skyroot = new CameraRelativeTransform; skyroot->setName("Sky Root"); // Assign empty program to specify we don't want shaders when we are rendering in FFP pipeline if (!mSceneManager->getForceShaders()) skyroot->getOrCreateStateSet()->setAttributeAndModes(new osg::Program(), osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED | osg::StateAttribute::ON); mSceneManager->setUpNormalsRTForStateSet(skyroot->getOrCreateStateSet(), false); SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*skyroot->getOrCreateStateSet()); parentNode->addChild(skyroot); mEarlyRenderBinRoot = new osg::Group; // render before the world is rendered mEarlyRenderBinRoot->getOrCreateStateSet()->setRenderBinDetails(RenderBin_Sky, "RenderBin"); // Prevent unwanted clipping by water reflection camera's clipping plane mEarlyRenderBinRoot->getOrCreateStateSet()->setMode(GL_CLIP_PLANE0, osg::StateAttribute::OFF); if (enableSkyRTT) { mSkyRTT = new SkyRTT(Settings::fog().mSkyRttResolution, mEarlyRenderBinRoot); skyroot->addChild(mSkyRTT); mRootNode = new osg::Group; skyroot->addChild(mRootNode); } else mRootNode = skyroot; mRootNode->setNodeMask(Mask_Sky); mRootNode->addChild(mEarlyRenderBinRoot); mUnderwaterSwitch = new UnderwaterSwitchCallback(skyroot); mPrecipitationOcclusion = Settings::shaders().mWeatherParticleOcclusion; mPrecipitationOccluder = std::make_unique<PrecipitationOccluder>(skyroot, parentNode, rootNode, camera); } void SkyManager::create() { assert(!mCreated); bool forceShaders = mSceneManager->getForceShaders(); mAtmosphereDay = mSceneManager->getInstance(Settings::models().mSkyatmosphere.get(), mEarlyRenderBinRoot); ModVertexAlphaVisitor modAtmosphere(ModVertexAlphaVisitor::Atmosphere); mAtmosphereDay->accept(modAtmosphere); mAtmosphereUpdater = new AtmosphereUpdater; mAtmosphereDay->addUpdateCallback(mAtmosphereUpdater); mAtmosphereNightNode = new osg::PositionAttitudeTransform; mAtmosphereNightNode->setNodeMask(0); mEarlyRenderBinRoot->addChild(mAtmosphereNightNode); osg::ref_ptr<osg::Node> atmosphereNight; if (mSceneManager->getVFS()->exists(Settings::models().mSkynight02.get())) atmosphereNight = mSceneManager->getInstance(Settings::models().mSkynight02.get(), mAtmosphereNightNode); else atmosphereNight = mSceneManager->getInstance(Settings::models().mSkynight01.get(), mAtmosphereNightNode); atmosphereNight->getOrCreateStateSet()->setAttributeAndModes( createAlphaTrackingUnlitMaterial(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); ModVertexAlphaVisitor modStars(ModVertexAlphaVisitor::Stars); atmosphereNight->accept(modStars); mAtmosphereNightUpdater = new AtmosphereNightUpdater(mSceneManager->getImageManager(), forceShaders); atmosphereNight->addUpdateCallback(mAtmosphereNightUpdater); mSun = std::make_unique<Sun>(mEarlyRenderBinRoot, *mSceneManager); mSun->setSunglare(mSunglareEnabled); mMasser = std::make_unique<Moon>( mEarlyRenderBinRoot, *mSceneManager, Fallback::Map::getFloat("Moons_Masser_Size") / 125, Moon::Type_Masser); mSecunda = std::make_unique<Moon>(mEarlyRenderBinRoot, *mSceneManager, Fallback::Map::getFloat("Moons_Secunda_Size") / 125, Moon::Type_Secunda); mCloudNode = new osg::Group; mEarlyRenderBinRoot->addChild(mCloudNode); mCloudMesh = new osg::PositionAttitudeTransform; osg::ref_ptr<osg::Node> cloudMeshChild = mSceneManager->getInstance(Settings::models().mSkyclouds.get(), mCloudMesh); mCloudUpdater = new CloudUpdater(forceShaders); mCloudUpdater->setOpacity(1.f); cloudMeshChild->addUpdateCallback(mCloudUpdater); mCloudMesh->addChild(cloudMeshChild); mNextCloudMesh = new osg::PositionAttitudeTransform; osg::ref_ptr<osg::Node> nextCloudMeshChild = mSceneManager->getInstance(Settings::models().mSkyclouds.get(), mNextCloudMesh); mNextCloudUpdater = new CloudUpdater(forceShaders); mNextCloudUpdater->setOpacity(0.f); nextCloudMeshChild->addUpdateCallback(mNextCloudUpdater); mNextCloudMesh->setNodeMask(0); mNextCloudMesh->addChild(nextCloudMeshChild); mCloudNode->addChild(mCloudMesh); mCloudNode->addChild(mNextCloudMesh); ModVertexAlphaVisitor modClouds(ModVertexAlphaVisitor::Clouds); mCloudMesh->accept(modClouds); mNextCloudMesh->accept(modClouds); if (mSceneManager->getForceShaders()) { Shader::ShaderManager::DefineMap defines = {}; Stereo::shaderStereoDefines(defines); auto program = mSceneManager->getShaderManager().getProgram("sky", defines); mEarlyRenderBinRoot->getOrCreateStateSet()->addUniform(new osg::Uniform("pass", -1)); mEarlyRenderBinRoot->getOrCreateStateSet()->setAttributeAndModes( program, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } osg::ref_ptr<osg::Depth> depth = new SceneUtil::AutoDepth; depth->setWriteMask(false); mEarlyRenderBinRoot->getOrCreateStateSet()->setAttributeAndModes(depth); mEarlyRenderBinRoot->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON); mEarlyRenderBinRoot->getOrCreateStateSet()->setMode(GL_FOG, osg::StateAttribute::OFF); mMoonScriptColor = Fallback::Map::getColour("Moons_Script_Color"); mCreated = true; } void SkyManager::createRain() { if (mRainNode) return; mRainNode = new osg::Group; mRainParticleSystem = new NifOsg::ParticleSystem; osg::Vec3 rainRange = osg::Vec3(mRainDiameter, mRainDiameter, (mRainMinHeight + mRainMaxHeight) / 2.f); mRainParticleSystem->setParticleAlignment(osgParticle::ParticleSystem::FIXED); mRainParticleSystem->setAlignVectorX(osg::Vec3f(0.1, 0, 0)); mRainParticleSystem->setAlignVectorY(osg::Vec3f(0, 0, 1)); osg::ref_ptr<osg::StateSet> stateset = mRainParticleSystem->getOrCreateStateSet(); constexpr VFS::Path::NormalizedView raindropImage("textures/tx_raindrop_01.dds"); osg::ref_ptr<osg::Texture2D> raindropTex = new osg::Texture2D(mSceneManager->getImageManager()->getImage(raindropImage)); raindropTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); raindropTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); stateset->setTextureAttributeAndModes(0, raindropTex); stateset->setNestRenderBins(false); stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF); stateset->setMode(GL_BLEND, osg::StateAttribute::ON); osg::ref_ptr<osg::Material> mat = new osg::Material; mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); stateset->setAttributeAndModes(mat); osgParticle::Particle& particleTemplate = mRainParticleSystem->getDefaultParticleTemplate(); particleTemplate.setSizeRange(osgParticle::rangef(5.f, 15.f)); particleTemplate.setAlphaRange(osgParticle::rangef(1.f, 1.f)); particleTemplate.setLifeTime(1); osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter; emitter->setParticleSystem(mRainParticleSystem); osg::ref_ptr<osgParticle::BoxPlacer> placer = new osgParticle::BoxPlacer; placer->setXRange(-rainRange.x() / 2, rainRange.x() / 2); placer->setYRange(-rainRange.y() / 2, rainRange.y() / 2); placer->setZRange(-rainRange.z() / 2, rainRange.z() / 2); emitter->setPlacer(placer); mPlacer = placer; // FIXME: vanilla engine does not use a particle system to handle rain, it uses a NIF-file with 20 raindrops in // it. It spawns the (maxRaindrops-getParticleSystem()->numParticles())*dt/rainEntranceSpeed batches every frame // (near 1-2). Since the rain is a regular geometry, it produces water ripples, also in theory it can be removed // if collides with something. osg::ref_ptr<RainCounter> counter = new RainCounter; counter->setNumberOfParticlesPerSecondToCreate(mRainMaxRaindrops / mRainEntranceSpeed * 20); emitter->setCounter(counter); mCounter = counter; osg::ref_ptr<RainShooter> shooter = new RainShooter; mRainShooter = shooter; emitter->setShooter(shooter); osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater; updater->addParticleSystem(mRainParticleSystem); osg::ref_ptr<osgParticle::ModularProgram> program = new osgParticle::ModularProgram; program->addOperator(new WrapAroundOperator(mCamera, rainRange)); program->addOperator(new WeatherAlphaOperator(mPrecipitationAlpha, true)); program->setParticleSystem(mRainParticleSystem); mRainNode->addChild(program); mRainNode->addChild(emitter); mRainNode->addChild(mRainParticleSystem); mRainNode->addChild(updater); // Note: if we ever switch to regular geometry rain, it'll need to use an AlphaFader. mRainNode->addCullCallback(mUnderwaterSwitch); mRainNode->setNodeMask(Mask_WeatherParticles); mRainParticleSystem->setUserValue("simpleLighting", true); mRainParticleSystem->setUserValue("particleOcclusion", true); mSceneManager->recreateShaders(mRainNode); mRootNode->addChild(mRainNode); if (mPrecipitationOcclusion) mPrecipitationOccluder->enable(); } void SkyManager::destroyRain() { if (!mRainNode) return; mRootNode->removeChild(mRainNode); mRainNode = nullptr; mPlacer = nullptr; mCounter = nullptr; mRainParticleSystem = nullptr; mRainShooter = nullptr; mPrecipitationOccluder->disable(); } SkyManager::~SkyManager() { if (mRootNode) { mRootNode->getParent(0)->removeChild(mRootNode); mRootNode = nullptr; } } int SkyManager::getMasserPhase() const { if (!mCreated) return 0; return mMasser->getPhaseInt(); } int SkyManager::getSecundaPhase() const { if (!mCreated) return 0; return mSecunda->getPhaseInt(); } bool SkyManager::isEnabled() { return mEnabled; } bool SkyManager::hasRain() const { return mRainNode != nullptr; } bool SkyManager::getRainRipplesEnabled() const { if (!mEnabled || mIsStorm) return false; if (hasRain()) return mRainRipplesEnabled; if (mParticleNode && mCurrentParticleEffect == Settings::models().mWeathersnow.get()) return mSnowRipplesEnabled; return false; } float SkyManager::getPrecipitationAlpha() const { if (mEnabled && !mIsStorm && (hasRain() || mParticleNode)) return mPrecipitationAlpha; return 0.f; } void SkyManager::update(float duration) { if (!mEnabled) return; switchUnderwaterRain(); if (mIsStorm && mParticleNode) { osg::Quat quat; quat.makeRotate(MWWorld::Weather::defaultDirection(), mStormParticleDirection); // Morrowind deliberately rotates the blizzard mesh, so so should we. if (mCurrentParticleEffect == Settings::models().mWeatherblizzard.get()) quat.makeRotate(osg::Vec3f(-1, 0, 0), mStormParticleDirection); mParticleNode->setAttitude(quat); } const float timeScale = MWBase::Environment::get().getWorld()->getTimeManager()->getGameTimeScale(); // UV Scroll the clouds float cloudDelta = duration * mCloudSpeed / 400.f; if (mTimescaleClouds) cloudDelta *= timeScale / 60.f; mCloudAnimationTimer += cloudDelta; if (mCloudAnimationTimer >= 4.f) mCloudAnimationTimer -= 4.f; mNextCloudUpdater->setTextureCoord(mCloudAnimationTimer); mCloudUpdater->setTextureCoord(mCloudAnimationTimer); // morrowind rotates each cloud mesh independently osg::Quat rotation; rotation.makeRotate(MWWorld::Weather::defaultDirection(), mStormDirection); mCloudMesh->setAttitude(rotation); if (mNextCloudMesh->getNodeMask()) { rotation.makeRotate(MWWorld::Weather::defaultDirection(), mNextStormDirection); mNextCloudMesh->setAttitude(rotation); } // rotate the stars by 360 degrees every 4 days mAtmosphereNightRoll += timeScale * duration * osg::DegreesToRadians(360.f) / (3600 * 96.f); if (mAtmosphereNightNode->getNodeMask() != 0) mAtmosphereNightNode->setAttitude(osg::Quat(mAtmosphereNightRoll, osg::Vec3f(0, 0, 1))); mPrecipitationOccluder->update(); } void SkyManager::setEnabled(bool enabled) { if (enabled && !mCreated) create(); const osg::Node::NodeMask mask = enabled ? Mask_Sky : 0u; mEarlyRenderBinRoot->setNodeMask(mask); mRootNode->setNodeMask(mask); if (!enabled && mParticleNode && mParticleEffect) { mCurrentParticleEffect.clear(); mDirtyParticlesEffect = true; } mEnabled = enabled; } void SkyManager::setMoonColour(bool red) { if (!mCreated) return; mSecunda->setColor(red ? mMoonScriptColor : osg::Vec4f(1, 1, 1, 1)); } void SkyManager::updateRainParameters() { if (mRainShooter) { float angle = -std::atan(mWindSpeed / 50.f); mRainShooter->setVelocity(osg::Vec3f(0, mRainSpeed * std::sin(angle), -mRainSpeed / std::cos(angle))); mRainShooter->setAngle(angle); osg::Vec3 rainRange = osg::Vec3(mRainDiameter, mRainDiameter, (mRainMinHeight + mRainMaxHeight) / 2.f); mPlacer->setXRange(-rainRange.x() / 2, rainRange.x() / 2); mPlacer->setYRange(-rainRange.y() / 2, rainRange.y() / 2); mPlacer->setZRange(-rainRange.z() / 2, rainRange.z() / 2); mCounter->setNumberOfParticlesPerSecondToCreate(mRainMaxRaindrops / mRainEntranceSpeed * 20); mPrecipitationOccluder->updateRange(rainRange); } } void SkyManager::switchUnderwaterRain() { if (!mRainParticleSystem) return; bool freeze = mUnderwaterSwitch->isUnderwater(); mRainParticleSystem->setFrozen(freeze); } void SkyManager::setWeather(const WeatherResult& weather) { if (!mCreated) return; mRainEntranceSpeed = weather.mRainEntranceSpeed; mRainMaxRaindrops = weather.mRainMaxRaindrops; mRainDiameter = weather.mRainDiameter; mRainMinHeight = weather.mRainMinHeight; mRainMaxHeight = weather.mRainMaxHeight; mRainSpeed = weather.mRainSpeed; mWindSpeed = weather.mWindSpeed; mBaseWindSpeed = weather.mBaseWindSpeed; if (mRainEffect != weather.mRainEffect) { mRainEffect = weather.mRainEffect; if (!mRainEffect.empty()) { createRain(); } else { destroyRain(); } } updateRainParameters(); mIsStorm = weather.mIsStorm; if (mIsStorm) mStormDirection = weather.mStormDirection; if (mDirtyParticlesEffect || (mCurrentParticleEffect != weather.mParticleEffect)) { mDirtyParticlesEffect = false; mCurrentParticleEffect = weather.mParticleEffect; // cleanup old particles if (mParticleEffect) { mParticleNode->removeChild(mParticleEffect); mParticleEffect = nullptr; } if (mCurrentParticleEffect.empty()) { if (mParticleNode) { mRootNode->removeChild(mParticleNode); mParticleNode = nullptr; } if (mRainEffect.empty()) { mPrecipitationOccluder->disable(); } } else { if (!mParticleNode) { mParticleNode = new osg::PositionAttitudeTransform; mParticleNode->addCullCallback(mUnderwaterSwitch); mParticleNode->setNodeMask(Mask_WeatherParticles); mRootNode->addChild(mParticleNode); } mParticleEffect = mSceneManager->getInstance(mCurrentParticleEffect, mParticleNode); SceneUtil::AssignControllerSourcesVisitor assignVisitor(std::make_shared<SceneUtil::FrameTimeSource>()); mParticleEffect->accept(assignVisitor); SetupVisitor alphaFaderSetupVisitor(mPrecipitationAlpha); mParticleEffect->accept(alphaFaderSetupVisitor); SceneUtil::FindByClassVisitor findPSVisitor("ParticleSystem"); mParticleEffect->accept(findPSVisitor); const osg::Vec3 defaultWrapRange = osg::Vec3(1024, 1024, 800); const bool occlusionEnabledForEffect = !mRainEffect.empty() || mCurrentParticleEffect == Settings::models().mWeathersnow.get(); for (unsigned int i = 0; i < findPSVisitor.mFoundNodes.size(); ++i) { osgParticle::ParticleSystem* ps = static_cast<osgParticle::ParticleSystem*>(findPSVisitor.mFoundNodes[i]); osg::ref_ptr<osgParticle::ModularProgram> program = new osgParticle::ModularProgram; if (!mIsStorm) program->addOperator(new WrapAroundOperator(mCamera, defaultWrapRange)); program->addOperator(new WeatherAlphaOperator(mPrecipitationAlpha, false)); program->setParticleSystem(ps); mParticleNode->addChild(program); for (int particleIndex = 0; particleIndex < ps->numParticles(); ++particleIndex) { ps->getParticle(particleIndex) ->setAlphaRange(osgParticle::rangef(mPrecipitationAlpha, mPrecipitationAlpha)); ps->getParticle(particleIndex)->update(0, true); } ps->setUserValue("simpleLighting", true); if (occlusionEnabledForEffect) ps->setUserValue("particleOcclusion", true); } mSceneManager->recreateShaders(mParticleNode); if (mPrecipitationOcclusion && occlusionEnabledForEffect) { mPrecipitationOccluder->enable(); mPrecipitationOccluder->updateRange(defaultWrapRange); } } } if (mClouds != weather.mCloudTexture) { mClouds = weather.mCloudTexture; const VFS::Path::Normalized texture = Misc::ResourceHelpers::correctTexturePath(mClouds, mSceneManager->getVFS()); osg::ref_ptr<osg::Texture2D> cloudTex = new osg::Texture2D(mSceneManager->getImageManager()->getImage(texture)); cloudTex->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); cloudTex->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); mCloudUpdater->setTexture(std::move(cloudTex)); } if (mStormDirection != weather.mStormDirection) mStormDirection = weather.mStormDirection; if (mNextStormDirection != weather.mNextStormDirection) mNextStormDirection = weather.mNextStormDirection; if (mNextClouds != weather.mNextCloudTexture) { mNextClouds = weather.mNextCloudTexture; if (!mNextClouds.empty()) { const VFS::Path::Normalized texture = Misc::ResourceHelpers::correctTexturePath(mNextClouds, mSceneManager->getVFS()); osg::ref_ptr<osg::Texture2D> cloudTex = new osg::Texture2D(mSceneManager->getImageManager()->getImage(texture)); cloudTex->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); cloudTex->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); mNextCloudUpdater->setTexture(std::move(cloudTex)); mNextStormDirection = weather.mStormDirection; } } if (mCloudBlendFactor != weather.mCloudBlendFactor) { mCloudBlendFactor = std::clamp(weather.mCloudBlendFactor, 0.f, 1.f); mCloudUpdater->setOpacity(1.f - mCloudBlendFactor); mNextCloudUpdater->setOpacity(mCloudBlendFactor); mNextCloudMesh->setNodeMask(mCloudBlendFactor > 0.f ? ~0u : 0); } if (mCloudColour != weather.mFogColor) { osg::Vec4f clr(weather.mFogColor); clr += osg::Vec4f(0.13f, 0.13f, 0.13f, 0.f); mCloudUpdater->setEmissionColor(clr); mNextCloudUpdater->setEmissionColor(clr); mCloudColour = weather.mFogColor; } if (mSkyColour != weather.mSkyColor) { mSkyColour = weather.mSkyColor; mAtmosphereUpdater->setEmissionColor(mSkyColour); mMasser->setAtmosphereColor(mSkyColour); mSecunda->setAtmosphereColor(mSkyColour); } if (mFogColour != weather.mFogColor) { mFogColour = weather.mFogColor; } mCloudSpeed = weather.mCloudSpeed; mMasser->adjustTransparency(weather.mGlareView); mSecunda->adjustTransparency(weather.mGlareView); mSun->setColor(weather.mSunDiscColor); mSun->adjustTransparency(weather.mGlareView * weather.mSunDiscColor.a()); float nextStarsOpacity = weather.mNightFade * weather.mGlareView; if (weather.mNight && mStarsOpacity != nextStarsOpacity) { mStarsOpacity = nextStarsOpacity; mAtmosphereNightUpdater->setFade(mStarsOpacity); } mAtmosphereNightNode->setNodeMask(weather.mNight ? ~0u : 0); mPrecipitationAlpha = weather.mPrecipitationAlpha; } float SkyManager::getBaseWindSpeed() const { if (!mCreated) return 0.f; return mBaseWindSpeed; } void SkyManager::setSunglare(bool enabled) { mSunglareEnabled = enabled; if (mSun) mSun->setSunglare(mSunglareEnabled); } void SkyManager::sunEnable() { if (!mCreated) return; mSun->setVisible(true); } void SkyManager::sunDisable() { if (!mCreated) return; mSun->setVisible(false); } void SkyManager::setStormParticleDirection(const osg::Vec3f& direction) { mStormParticleDirection = direction; } void SkyManager::setSunDirection(const osg::Vec3f& direction) { if (!mCreated) return; mSun->setDirection(direction); } void SkyManager::setMasserState(const MoonState& state) { if (!mCreated) return; mMasser->setState(state); } void SkyManager::setSecundaState(const MoonState& state) { if (!mCreated) return; mSecunda->setState(state); } void SkyManager::setGlareTimeOfDayFade(float val) { mSun->setGlareTimeOfDayFade(val); } void SkyManager::setWaterHeight(float height) { mUnderwaterSwitch->setWaterLevel(height); } void SkyManager::listAssetsToPreload( std::vector<VFS::Path::Normalized>& models, std::vector<VFS::Path::Normalized>& textures) { models.push_back(Settings::models().mSkyatmosphere); if (mSceneManager->getVFS()->exists(Settings::models().mSkynight02.get())) models.push_back(Settings::models().mSkynight02); models.push_back(Settings::models().mSkynight01); models.push_back(Settings::models().mSkyclouds); models.push_back(Settings::models().mWeatherashcloud); models.push_back(Settings::models().mWeatherblightcloud); models.push_back(Settings::models().mWeathersnow); models.push_back(Settings::models().mWeatherblizzard); textures.emplace_back("textures/tx_mooncircle_full_s.dds"); textures.emplace_back("textures/tx_mooncircle_full_m.dds"); textures.emplace_back("textures/tx_masser_new.dds"); textures.emplace_back("textures/tx_masser_one_wax.dds"); textures.emplace_back("textures/tx_masser_half_wax.dds"); textures.emplace_back("textures/tx_masser_three_wax.dds"); textures.emplace_back("textures/tx_masser_one_wan.dds"); textures.emplace_back("textures/tx_masser_half_wan.dds"); textures.emplace_back("textures/tx_masser_three_wan.dds"); textures.emplace_back("textures/tx_masser_full.dds"); textures.emplace_back("textures/tx_secunda_new.dds"); textures.emplace_back("textures/tx_secunda_one_wax.dds"); textures.emplace_back("textures/tx_secunda_half_wax.dds"); textures.emplace_back("textures/tx_secunda_three_wax.dds"); textures.emplace_back("textures/tx_secunda_one_wan.dds"); textures.emplace_back("textures/tx_secunda_half_wan.dds"); textures.emplace_back("textures/tx_secunda_three_wan.dds"); textures.emplace_back("textures/tx_secunda_full.dds"); textures.emplace_back("textures/tx_sun_05.dds"); textures.emplace_back("textures/tx_sun_flash_grey_05.dds"); textures.emplace_back("textures/tx_raindrop_01.dds"); } void SkyManager::setWaterEnabled(bool enabled) { mUnderwaterSwitch->setEnabled(enabled); } }
35,594
C++
.cpp
778
35.260925
120
0.639265
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,399
water.cpp
OpenMW_openmw/apps/openmw/mwrender/water.cpp
#include "water.hpp" #include <sstream> #include <osg/ClipNode> #include <osg/Depth> #include <osg/Fog> #include <osg/FrontFace> #include <osg/Geometry> #include <osg/Group> #include <osg/Material> #include <osg/PositionAttitudeTransform> #include <osg/ViewportIndexed> #include <osgUtil/CullVisitor> #include <osgUtil/IncrementalCompileOperation> #include <components/resource/imagemanager.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/rtt.hpp> #include <components/sceneutil/shadow.hpp> #include <components/sceneutil/waterutil.hpp> #include <components/misc/constants.hpp> #include <components/stereo/stereomanager.hpp> #include <components/nifosg/controller.hpp> #include <components/shader/shadermanager.hpp> #include <components/esm3/loadcell.hpp> #include <components/fallback/fallback.hpp> #include <components/settings/values.hpp> #include "../mwworld/cellstore.hpp" #include "renderbin.hpp" #include "ripples.hpp" #include "ripplesimulation.hpp" #include "util.hpp" #include "vismask.hpp" namespace MWRender { // -------------------------------------------------------------------------------------------------------------------------------- /// @brief Allows to cull and clip meshes that are below a plane. Useful for reflection & refraction camera effects. /// Also handles flipping of the plane when the eye point goes below it. /// To use, simply create the scene as subgraph of this node, then do setPlane(const osg::Plane& plane); class ClipCullNode : public osg::Group { class PlaneCullCallback : public SceneUtil::NodeCallback<PlaneCullCallback, osg::Node*, osgUtil::CullVisitor*> { public: /// @param cullPlane The culling plane (in world space). PlaneCullCallback(const osg::Plane* cullPlane) : mCullPlane(cullPlane) { } void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osg::Polytope::PlaneList origPlaneList = cv->getProjectionCullingStack().back().getFrustum().getPlaneList(); osg::Plane plane = *mCullPlane; plane.transform(*cv->getCurrentRenderStage()->getInitialViewMatrix()); osg::Vec3d eyePoint = cv->getEyePoint(); if (mCullPlane->intersect(osg::BoundingSphere(osg::Vec3d(0, 0, eyePoint.z()), 0)) > 0) plane.flip(); cv->getProjectionCullingStack().back().getFrustum().add(plane); traverse(node, cv); // undo cv->getProjectionCullingStack().back().getFrustum().set(origPlaneList); } private: const osg::Plane* mCullPlane; }; class FlipCallback : public SceneUtil::NodeCallback<FlipCallback, osg::Node*, osgUtil::CullVisitor*> { public: FlipCallback(const osg::Plane* cullPlane) : mCullPlane(cullPlane) { } void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osg::Vec3d eyePoint = cv->getEyePoint(); osg::RefMatrix* modelViewMatrix = new osg::RefMatrix(*cv->getModelViewMatrix()); // apply the height of the plane // we can't apply this height in the addClipPlane() since the "flip the below graph" function would // otherwise flip the height as well modelViewMatrix->preMultTranslate(mCullPlane->getNormal() * ((*mCullPlane)[3] * -1)); // flip the below graph if the eye point is above the plane if (mCullPlane->intersect(osg::BoundingSphere(osg::Vec3d(0, 0, eyePoint.z()), 0)) > 0) { modelViewMatrix->preMultScale(osg::Vec3(1, 1, -1)); } // move the plane back along its normal a little bit to prevent bleeding at the water shore float fov = Settings::camera().mFieldOfView; const float clipFudgeMin = 2.5; // minimum offset of clip plane const float clipFudgeScale = -15000.0; float clipFudge = abs(abs((*mCullPlane)[3]) - eyePoint.z()) * fov / clipFudgeScale - clipFudgeMin; modelViewMatrix->preMultTranslate(mCullPlane->getNormal() * clipFudge); cv->pushModelViewMatrix(modelViewMatrix, osg::Transform::RELATIVE_RF); traverse(node, cv); cv->popModelViewMatrix(); } private: const osg::Plane* mCullPlane; }; public: ClipCullNode() { addCullCallback(new PlaneCullCallback(&mPlane)); mClipNodeTransform = new osg::Group; mClipNodeTransform->addCullCallback(new FlipCallback(&mPlane)); osg::Group::addChild(mClipNodeTransform); mClipNode = new osg::ClipNode; mClipNodeTransform->addChild(mClipNode); } void setPlane(const osg::Plane& plane) { if (plane == mPlane) return; mPlane = plane; mClipNode->getClipPlaneList().clear(); mClipNode->addClipPlane( new osg::ClipPlane(0, osg::Plane(mPlane.getNormal(), 0))); // mPlane.d() applied in FlipCallback mClipNode->setStateSetModes(*getOrCreateStateSet(), osg::StateAttribute::ON); mClipNode->setCullingActive(false); } private: osg::ref_ptr<osg::Group> mClipNodeTransform; osg::ref_ptr<osg::ClipNode> mClipNode; osg::Plane mPlane; }; /// This callback on the Camera has the effect of a RELATIVE_RF_INHERIT_VIEWPOINT transform mode (which does not /// exist in OSG). We want to keep the View Point of the parent camera so we will not have to recreate LODs. class InheritViewPointCallback : public SceneUtil::NodeCallback<InheritViewPointCallback, osg::Node*, osgUtil::CullVisitor*> { public: InheritViewPointCallback() {} void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { osg::ref_ptr<osg::RefMatrix> modelViewMatrix = new osg::RefMatrix(*cv->getModelViewMatrix()); cv->popModelViewMatrix(); cv->pushModelViewMatrix(modelViewMatrix, osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT); traverse(node, cv); } }; /// Moves water mesh away from the camera slightly if the camera gets too close on the Z axis. /// The offset works around graphics artifacts that occurred with the GL_DEPTH_CLAMP when the camera gets extremely /// close to the mesh (seen on NVIDIA at least). Must be added as a Cull callback. class FudgeCallback : public SceneUtil::NodeCallback<FudgeCallback, osg::Node*, osgUtil::CullVisitor*> { public: void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { const float fudge = 0.2; if (std::abs(cv->getEyeLocal().z()) < fudge) { float diff = fudge - cv->getEyeLocal().z(); osg::RefMatrix* modelViewMatrix = new osg::RefMatrix(*cv->getModelViewMatrix()); if (cv->getEyeLocal().z() > 0) modelViewMatrix->preMultTranslate(osg::Vec3f(0, 0, -diff)); else modelViewMatrix->preMultTranslate(osg::Vec3f(0, 0, diff)); cv->pushModelViewMatrix(modelViewMatrix, osg::Transform::RELATIVE_RF); traverse(node, cv); cv->popModelViewMatrix(); } else traverse(node, cv); } }; class RainSettingsUpdater : public SceneUtil::StateSetUpdater { public: RainSettingsUpdater() : mRainIntensity(0.f) , mEnableRipples(false) { } void setRainIntensity(float rainIntensity) { mRainIntensity = rainIntensity; } void setRipplesEnabled(bool enableRipples) { mEnableRipples = enableRipples; } protected: void setDefaults(osg::StateSet* stateset) override { osg::ref_ptr<osg::Uniform> rainIntensityUniform = new osg::Uniform("rainIntensity", 0.0f); stateset->addUniform(rainIntensityUniform.get()); osg::ref_ptr<osg::Uniform> enableRainRipplesUniform = new osg::Uniform("enableRainRipples", false); stateset->addUniform(enableRainRipplesUniform.get()); } void apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) override { osg::ref_ptr<osg::Uniform> rainIntensityUniform = stateset->getUniform("rainIntensity"); if (rainIntensityUniform != nullptr) rainIntensityUniform->set(mRainIntensity); osg::ref_ptr<osg::Uniform> enableRainRipplesUniform = stateset->getUniform("enableRainRipples"); if (enableRainRipplesUniform != nullptr) enableRainRipplesUniform->set(mEnableRipples); } private: float mRainIntensity; bool mEnableRipples; }; class Refraction : public SceneUtil::RTTNode { public: Refraction(uint32_t rttSize) : RTTNode(rttSize, rttSize, 0, false, 1, StereoAwareness::Aware, shouldAddMSAAIntermediateTarget()) , mNodeMask(Refraction::sDefaultCullMask) { setDepthBufferInternalFormat(GL_DEPTH24_STENCIL8); mClipCullNode = new ClipCullNode; } void setDefaults(osg::Camera* camera) override { camera->setReferenceFrame(osg::Camera::RELATIVE_RF); camera->setSmallFeatureCullingPixelSize(Settings::water().mSmallFeatureCullingPixelSize); camera->setName("RefractionCamera"); camera->addCullCallback(new InheritViewPointCallback); camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); // No need for fog here, we are already applying fog on the water surface itself as well as underwater fog // assign large value to effectively turn off fog // shaders don't respect glDisable(GL_FOG) osg::ref_ptr<osg::Fog> fog(new osg::Fog); fog->setStart(10000000); fog->setEnd(10000000); camera->getOrCreateStateSet()->setAttributeAndModes( fog, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); camera->addChild(mClipCullNode); camera->setNodeMask(Mask_RenderToTexture); if (Settings::water().mRefractionScale != 1) // TODO: to be removed with issue #5709 SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*camera->getOrCreateStateSet()); } void apply(osg::Camera* camera) override { camera->setViewMatrix(mViewMatrix); camera->setCullMask(mNodeMask); } void setScene(osg::Node* scene) { if (mScene) mClipCullNode->removeChild(mScene); mScene = scene; mClipCullNode->addChild(scene); } void setWaterLevel(float waterLevel) { const float refractionScale = Settings::water().mRefractionScale; mViewMatrix = osg::Matrix::scale(1, 1, refractionScale) * osg::Matrix::translate(0, 0, (1.0 - refractionScale) * waterLevel); mClipCullNode->setPlane(osg::Plane(osg::Vec3d(0, 0, -1), osg::Vec3d(0, 0, waterLevel))); } void showWorld(bool show) { if (show) mNodeMask = Refraction::sDefaultCullMask; else mNodeMask = Refraction::sDefaultCullMask & ~sToggleWorldMask; } private: osg::ref_ptr<ClipCullNode> mClipCullNode; osg::ref_ptr<osg::Node> mScene; osg::Matrix mViewMatrix{ osg::Matrix::identity() }; unsigned int mNodeMask; static constexpr unsigned int sDefaultCullMask = Mask_Effect | Mask_Scene | Mask_Object | Mask_Static | Mask_Terrain | Mask_Actor | Mask_ParticleSystem | Mask_Sky | Mask_Sun | Mask_Player | Mask_Lighting | Mask_Groundcover; }; class Reflection : public SceneUtil::RTTNode { public: Reflection(uint32_t rttSize, bool isInterior) : RTTNode(rttSize, rttSize, 0, false, 0, StereoAwareness::Aware, shouldAddMSAAIntermediateTarget()) { setInterior(isInterior); setDepthBufferInternalFormat(GL_DEPTH24_STENCIL8); mClipCullNode = new ClipCullNode; } void setDefaults(osg::Camera* camera) override { camera->setReferenceFrame(osg::Camera::RELATIVE_RF); camera->setSmallFeatureCullingPixelSize(Settings::water().mSmallFeatureCullingPixelSize); camera->setName("ReflectionCamera"); camera->addCullCallback(new InheritViewPointCallback); // Inform the shader that we're in a reflection camera->getOrCreateStateSet()->addUniform(new osg::Uniform("isReflection", true)); // XXX: should really flip the FrontFace on each renderable instead of forcing clockwise. osg::ref_ptr<osg::FrontFace> frontFace(new osg::FrontFace); frontFace->setMode(osg::FrontFace::CLOCKWISE); camera->getOrCreateStateSet()->setAttributeAndModes(frontFace, osg::StateAttribute::ON); camera->addChild(mClipCullNode); camera->setNodeMask(Mask_RenderToTexture); SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*camera->getOrCreateStateSet()); } void apply(osg::Camera* camera) override { camera->setViewMatrix(mViewMatrix); camera->setCullMask(mNodeMask); } void setInterior(bool isInterior) { mInterior = isInterior; mNodeMask = calcNodeMask(); } void setWaterLevel(float waterLevel) { mViewMatrix = osg::Matrix::scale(1, 1, -1) * osg::Matrix::translate(0, 0, 2 * waterLevel); mClipCullNode->setPlane(osg::Plane(osg::Vec3d(0, 0, 1), osg::Vec3d(0, 0, waterLevel))); } void setScene(osg::Node* scene) { if (mScene) mClipCullNode->removeChild(mScene); mScene = scene; mClipCullNode->addChild(scene); } void showWorld(bool show) { if (show) mNodeMask = calcNodeMask(); else mNodeMask = calcNodeMask() & ~sToggleWorldMask; } private: unsigned int calcNodeMask() { int reflectionDetail = Settings::water().mReflectionDetail; reflectionDetail = std::clamp(reflectionDetail, mInterior ? 2 : 0, 5); unsigned int extraMask = 0; if (reflectionDetail >= 1) extraMask |= Mask_Terrain; if (reflectionDetail >= 2) extraMask |= Mask_Static; if (reflectionDetail >= 3) extraMask |= Mask_Effect | Mask_ParticleSystem | Mask_Object; if (reflectionDetail >= 4) extraMask |= Mask_Player | Mask_Actor; if (reflectionDetail >= 5) extraMask |= Mask_Groundcover; return Mask_Scene | Mask_Sky | Mask_Lighting | extraMask; } osg::ref_ptr<ClipCullNode> mClipCullNode; osg::ref_ptr<osg::Node> mScene; osg::Node::NodeMask mNodeMask; osg::Matrix mViewMatrix{ osg::Matrix::identity() }; bool mInterior; }; /// DepthClampCallback enables GL_DEPTH_CLAMP for the current draw, if supported. class DepthClampCallback : public osg::Drawable::DrawCallback { public: void drawImplementation(osg::RenderInfo& renderInfo, const osg::Drawable* drawable) const override { static bool supported = osg::isGLExtensionOrVersionSupported( renderInfo.getState()->getContextID(), "GL_ARB_depth_clamp", 3.3); if (!supported) { drawable->drawImplementation(renderInfo); return; } glEnable(GL_DEPTH_CLAMP); drawable->drawImplementation(renderInfo); // restore default glDisable(GL_DEPTH_CLAMP); } }; Water::Water(osg::Group* parent, osg::Group* sceneRoot, Resource::ResourceSystem* resourceSystem, osgUtil::IncrementalCompileOperation* ico) : mRainSettingsUpdater(nullptr) , mParent(parent) , mSceneRoot(sceneRoot) , mResourceSystem(resourceSystem) , mEnabled(true) , mToggled(true) , mTop(0) , mInterior(false) , mShowWorld(true) , mCullCallback(nullptr) , mShaderWaterStateSetUpdater(nullptr) { mSimulation = std::make_unique<RippleSimulation>(mSceneRoot, resourceSystem); mWaterGeom = SceneUtil::createWaterGeometry(Constants::CellSizeInUnits * 150, 40, 900); mWaterGeom->setDrawCallback(new DepthClampCallback); mWaterGeom->setNodeMask(Mask_Water); mWaterGeom->setDataVariance(osg::Object::STATIC); mWaterGeom->setName("Water Geometry"); mWaterNode = new osg::PositionAttitudeTransform; mWaterNode->setName("Water Root"); mWaterNode->addChild(mWaterGeom); mWaterNode->addCullCallback(new FudgeCallback); // simple water fallback for the local map osg::ref_ptr<osg::Geometry> geom2(osg::clone(mWaterGeom.get(), osg::CopyOp::DEEP_COPY_NODES)); createSimpleWaterStateSet(geom2, Fallback::Map::getFloat("Water_Map_Alpha")); geom2->setNodeMask(Mask_SimpleWater); geom2->setName("Simple Water Geometry"); mWaterNode->addChild(geom2); mSceneRoot->addChild(mWaterNode); setHeight(mTop); updateWaterMaterial(); if (ico) ico->add(mWaterNode); } void Water::setCullCallback(osg::Callback* callback) { if (mCullCallback) { mWaterNode->removeCullCallback(mCullCallback); if (mReflection) mReflection->removeCullCallback(mCullCallback); if (mRefraction) mRefraction->removeCullCallback(mCullCallback); } mCullCallback = callback; if (callback) { mWaterNode->addCullCallback(callback); if (mReflection) mReflection->addCullCallback(callback); if (mRefraction) mRefraction->addCullCallback(callback); } } void Water::updateWaterMaterial() { if (mShaderWaterStateSetUpdater) { mWaterNode->removeCullCallback(mShaderWaterStateSetUpdater); mShaderWaterStateSetUpdater = nullptr; } if (mReflection) { mParent->removeChild(mReflection); mReflection = nullptr; } if (mRefraction) { mParent->removeChild(mRefraction); mRefraction = nullptr; } if (mRipples) { mParent->removeChild(mRipples); mRipples = nullptr; mSimulation->setRipples(nullptr); } mWaterNode->setStateSet(nullptr); mWaterGeom->setStateSet(nullptr); mWaterGeom->setUpdateCallback(nullptr); if (Settings::water().mShader) { const unsigned int rttSize = Settings::water().mRttSize; mReflection = new Reflection(rttSize, mInterior); mReflection->setWaterLevel(mTop); mReflection->setScene(mSceneRoot); if (mCullCallback) mReflection->addCullCallback(mCullCallback); mParent->addChild(mReflection); if (Settings::water().mRefraction) { mRefraction = new Refraction(rttSize); mRefraction->setWaterLevel(mTop); mRefraction->setScene(mSceneRoot); if (mCullCallback) mRefraction->addCullCallback(mCullCallback); mParent->addChild(mRefraction); } mRipples = new Ripples(mResourceSystem); mSimulation->setRipples(mRipples); mParent->addChild(mRipples); showWorld(mShowWorld); createShaderWaterStateSet(mWaterNode); } else createSimpleWaterStateSet(mWaterGeom, Fallback::Map::getFloat("Water_World_Alpha")); updateVisible(); } osg::Vec3d Water::getPosition() const { return mWaterNode->getPosition(); } void Water::createSimpleWaterStateSet(osg::Node* node, float alpha) { osg::ref_ptr<osg::StateSet> stateset = SceneUtil::createSimpleWaterStateSet(alpha, MWRender::RenderBin_Water); node->setStateSet(stateset); node->setUpdateCallback(nullptr); mRainSettingsUpdater = nullptr; // Add animated textures std::vector<osg::ref_ptr<osg::Texture2D>> textures; const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320); std::string_view texture = Fallback::Map::getString("Water_SurfaceTexture"); for (int i = 0; i < frameCount; ++i) { std::ostringstream texname; texname << "textures/water/" << texture << std::setw(2) << std::setfill('0') << i << ".dds"; const VFS::Path::Normalized path(texname.str()); osg::ref_ptr<osg::Texture2D> tex(new osg::Texture2D(mResourceSystem->getImageManager()->getImage(path))); tex->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); tex->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); mResourceSystem->getSceneManager()->applyFilterSettings(tex); textures.push_back(tex); } if (textures.empty()) return; float fps = Fallback::Map::getFloat("Water_SurfaceFPS"); osg::ref_ptr<NifOsg::FlipController> controller(new NifOsg::FlipController(0, 1.f / fps, textures)); controller->setSource(std::make_shared<SceneUtil::FrameTimeSource>()); node->setUpdateCallback(controller); stateset->setTextureAttributeAndModes(0, textures[0], osg::StateAttribute::ON); // use a shader to render the simple water, ensuring that fog is applied per pixel as required. // this could be removed if a more detailed water mesh, using some sort of paging solution, is implemented. Resource::SceneManager* sceneManager = mResourceSystem->getSceneManager(); bool oldValue = sceneManager->getForceShaders(); sceneManager->setForceShaders(true); sceneManager->recreateShaders(node); sceneManager->setForceShaders(oldValue); } class ShaderWaterStateSetUpdater : public SceneUtil::StateSetUpdater { public: ShaderWaterStateSetUpdater(Water* water, Reflection* reflection, Refraction* refraction, Ripples* ripples, osg::ref_ptr<osg::Program> program, osg::ref_ptr<osg::Texture2D> normalMap) : mWater(water) , mReflection(reflection) , mRefraction(refraction) , mRipples(ripples) , mProgram(std::move(program)) , mNormalMap(std::move(normalMap)) { } void setDefaults(osg::StateSet* stateset) override { stateset->addUniform(new osg::Uniform("normalMap", 0)); stateset->setTextureAttributeAndModes(0, mNormalMap, osg::StateAttribute::ON); stateset->setMode(GL_CULL_FACE, osg::StateAttribute::OFF); stateset->setAttributeAndModes(mProgram, osg::StateAttribute::ON); stateset->addUniform(new osg::Uniform("reflectionMap", 1)); if (mRefraction) { stateset->addUniform(new osg::Uniform("refractionMap", 2)); stateset->addUniform(new osg::Uniform("refractionDepthMap", 3)); stateset->setRenderBinDetails(MWRender::RenderBin_Default, "RenderBin"); } else { stateset->setMode(GL_BLEND, osg::StateAttribute::ON); stateset->setRenderBinDetails(MWRender::RenderBin_Water, "RenderBin"); osg::ref_ptr<osg::Depth> depth = new SceneUtil::AutoDepth; depth->setWriteMask(false); stateset->setAttributeAndModes(depth, osg::StateAttribute::ON); } if (mRipples) { stateset->addUniform(new osg::Uniform("rippleMap", 4)); } stateset->addUniform(new osg::Uniform("nodePosition", osg::Vec3f(mWater->getPosition()))); } void apply(osg::StateSet* stateset, osg::NodeVisitor* nv) override { osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(nv); stateset->setTextureAttributeAndModes(1, mReflection->getColorTexture(cv), osg::StateAttribute::ON); if (mRefraction) { stateset->setTextureAttributeAndModes(2, mRefraction->getColorTexture(cv), osg::StateAttribute::ON); stateset->setTextureAttributeAndModes(3, mRefraction->getDepthTexture(cv), osg::StateAttribute::ON); } if (mRipples) { stateset->setTextureAttributeAndModes(4, mRipples->getColorTexture(), osg::StateAttribute::ON); } stateset->getUniform("nodePosition")->set(osg::Vec3f(mWater->getPosition())); } private: Water* mWater; Reflection* mReflection; Refraction* mRefraction; Ripples* mRipples; osg::ref_ptr<osg::Program> mProgram; osg::ref_ptr<osg::Texture2D> mNormalMap; }; void Water::createShaderWaterStateSet(osg::Node* node) { // use a define map to conditionally compile the shader std::map<std::string, std::string> defineMap; defineMap["waterRefraction"] = std::string(mRefraction ? "1" : "0"); const int rippleDetail = Settings::water().mRainRippleDetail; defineMap["rainRippleDetail"] = std::to_string(rippleDetail); defineMap["rippleMapWorldScale"] = std::to_string(RipplesSurface::sWorldScaleFactor); defineMap["rippleMapSize"] = std::to_string(RipplesSurface::sRTTSize) + ".0"; defineMap["sunlightScattering"] = Settings::water().mSunlightScattering ? "1" : "0"; defineMap["wobblyShores"] = Settings::water().mWobblyShores ? "1" : "0"; Stereo::shaderStereoDefines(defineMap); Shader::ShaderManager& shaderMgr = mResourceSystem->getSceneManager()->getShaderManager(); osg::ref_ptr<osg::Program> program = shaderMgr.getProgram("water", defineMap); constexpr VFS::Path::NormalizedView waterImage("textures/omw/water_nm.png"); osg::ref_ptr<osg::Texture2D> normalMap( new osg::Texture2D(mResourceSystem->getImageManager()->getImage(waterImage))); normalMap->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); normalMap->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT); mResourceSystem->getSceneManager()->applyFilterSettings(normalMap); mRainSettingsUpdater = new RainSettingsUpdater(); node->setUpdateCallback(mRainSettingsUpdater); mShaderWaterStateSetUpdater = new ShaderWaterStateSetUpdater( this, mReflection, mRefraction, mRipples, std::move(program), std::move(normalMap)); node->addCullCallback(mShaderWaterStateSetUpdater); } void Water::processChangedSettings(const Settings::CategorySettingVector& settings) { updateWaterMaterial(); } Water::~Water() { mParent->removeChild(mWaterNode); if (mReflection) { mParent->removeChild(mReflection); mReflection = nullptr; } if (mRefraction) { mParent->removeChild(mRefraction); mRefraction = nullptr; } if (mRipples) { mParent->removeChild(mRipples); mRipples = nullptr; mSimulation->setRipples(nullptr); } } void Water::listAssetsToPreload(std::vector<VFS::Path::Normalized>& textures) { const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320); std::string_view texture = Fallback::Map::getString("Water_SurfaceTexture"); for (int i = 0; i < frameCount; ++i) { std::ostringstream texname; texname << "textures/water/" << texture << std::setw(2) << std::setfill('0') << i << ".dds"; textures.emplace_back(texname.str()); } } void Water::setEnabled(bool enabled) { mEnabled = enabled; updateVisible(); } void Water::changeCell(const MWWorld::CellStore* store) { bool isInterior = !store->getCell()->isExterior(); bool wasInterior = mInterior; if (!isInterior) { mWaterNode->setPosition( getSceneNodeCoordinates(store->getCell()->getGridX(), store->getCell()->getGridY())); mInterior = false; } else { mWaterNode->setPosition(osg::Vec3f(0, 0, mTop)); mInterior = true; } if (mInterior != wasInterior && mReflection) mReflection->setInterior(mInterior); } void Water::setHeight(const float height) { mTop = height; mSimulation->setWaterHeight(height); osg::Vec3f pos = mWaterNode->getPosition(); pos.z() = height; mWaterNode->setPosition(pos); if (mReflection) mReflection->setWaterLevel(mTop); if (mRefraction) mRefraction->setWaterLevel(mTop); } void Water::setRainIntensity(float rainIntensity) { if (mRainSettingsUpdater) mRainSettingsUpdater->setRainIntensity(rainIntensity); } void Water::setRainRipplesEnabled(bool enableRipples) { if (mRainSettingsUpdater) mRainSettingsUpdater->setRipplesEnabled(enableRipples); } void Water::update(float dt, bool paused) { if (!paused) { mSimulation->update(dt); } if (mRipples) { mRipples->setPaused(paused); } } void Water::updateVisible() { bool visible = mEnabled && mToggled; mWaterNode->setNodeMask(visible ? ~0u : 0u); if (mRefraction) mRefraction->setNodeMask(visible ? Mask_RenderToTexture : 0u); if (mReflection) mReflection->setNodeMask(visible ? Mask_RenderToTexture : 0u); if (mRipples) mRipples->setNodeMask(visible ? Mask_RenderToTexture : 0u); } bool Water::toggle() { mToggled = !mToggled; updateVisible(); return mToggled; } bool Water::isUnderwater(const osg::Vec3f& pos) const { return pos.z() < mTop && mToggled && mEnabled; } osg::Vec3f Water::getSceneNodeCoordinates(int gridX, int gridY) { return osg::Vec3f(static_cast<float>(gridX * Constants::CellSizeInUnits + (Constants::CellSizeInUnits / 2)), static_cast<float>(gridY * Constants::CellSizeInUnits + (Constants::CellSizeInUnits / 2)), mTop); } void Water::addEmitter(const MWWorld::Ptr& ptr, float scale, float force) { mSimulation->addEmitter(ptr, scale, force); } void Water::removeEmitter(const MWWorld::Ptr& ptr) { mSimulation->removeEmitter(ptr); } void Water::updateEmitterPtr(const MWWorld::Ptr& old, const MWWorld::Ptr& ptr) { mSimulation->updateEmitterPtr(old, ptr); } void Water::emitRipple(const osg::Vec3f& pos) { mSimulation->emitRipple(pos); } void Water::removeCell(const MWWorld::CellStore* store) { mSimulation->removeCell(store); } void Water::clearRipples() { mSimulation->clear(); } void Water::showWorld(bool show) { if (mReflection) mReflection->showWorld(show); if (mRefraction) mRefraction->showWorld(show); mShowWorld = show; } }
32,644
C++
.cpp
748
33.343583
135
0.619358
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,400
skyutil.cpp
OpenMW_openmw/apps/openmw/mwrender/skyutil.cpp
#include "skyutil.hpp" #include <array> #include <cmath> #include <osg/AlphaFunc> #include <osg/BlendFunc> #include <osg/ColorMask> #include <osg/Depth> #include <osg/Geometry> #include <osg/Material> #include <osg/OcclusionQueryNode> #include <osg/PositionAttitudeTransform> #include <osg/TexEnvCombine> #include <osg/TexMat> #include <osg/Transform> #include <osg/observer_ptr> #include <osgUtil/CullVisitor> #include <osgParticle/Particle> #include <components/misc/rng.hpp> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include <components/resource/imagemanager.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/texturetype.hpp> #include <components/fallback/fallback.hpp> #include <components/sceneutil/statesetupdater.hpp> #include "../mwbase/environment.hpp" #include "renderbin.hpp" #include "vismask.hpp" namespace { enum class Pass { Atmosphere, Atmosphere_Night, Clouds, Moon, Sun, Sunflash_Query, Sunglare, }; osg::ref_ptr<osg::Geometry> createTexturedQuad(int numUvSets = 1, float scale = 1.f) { osg::ref_ptr<osg::Geometry> geom = new osg::Geometry; osg::ref_ptr<osg::Vec3Array> verts = new osg::Vec3Array; verts->push_back(osg::Vec3f(-0.5 * scale, -0.5 * scale, 0)); verts->push_back(osg::Vec3f(-0.5 * scale, 0.5 * scale, 0)); verts->push_back(osg::Vec3f(0.5 * scale, 0.5 * scale, 0)); verts->push_back(osg::Vec3f(0.5 * scale, -0.5 * scale, 0)); geom->setVertexArray(verts); osg::ref_ptr<osg::Vec2Array> texcoords = new osg::Vec2Array; texcoords->push_back(osg::Vec2f(0, 1)); texcoords->push_back(osg::Vec2f(0, 0)); texcoords->push_back(osg::Vec2f(1, 0)); texcoords->push_back(osg::Vec2f(1, 1)); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array; colors->push_back(osg::Vec4(1.f, 1.f, 1.f, 1.f)); geom->setColorArray(colors, osg::Array::BIND_OVERALL); for (int i = 0; i < numUvSets; ++i) geom->setTexCoordArray(i, texcoords, osg::Array::BIND_PER_VERTEX); geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS, 0, 4)); return geom; } struct DummyComputeBoundCallback : osg::Node::ComputeBoundingSphereCallback { osg::BoundingSphere computeBound(const osg::Node& node) const override { return osg::BoundingSphere(); } }; } namespace MWRender { osg::ref_ptr<osg::Material> createUnlitMaterial(osg::Material::ColorMode colorMode) { osg::ref_ptr<osg::Material> mat = new osg::Material; mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 1.f)); mat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 1.f)); mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(1.f, 1.f, 1.f, 1.f)); mat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 0.f)); mat->setColorMode(colorMode); return mat; } osg::ref_ptr<osg::Material> createAlphaTrackingUnlitMaterial() { return createUnlitMaterial(osg::Material::DIFFUSE); } class SunUpdater : public SceneUtil::StateSetUpdater { public: osg::Vec4f mColor; SunUpdater() : mColor(1.f, 1.f, 1.f, 1.f) { } void setDefaults(osg::StateSet* stateset) override { stateset->setAttributeAndModes(createUnlitMaterial()); } void apply(osg::StateSet* stateset, osg::NodeVisitor*) override { osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, mColor.a())); mat->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(mColor.r(), mColor.g(), mColor.b(), 1)); } }; OcclusionCallback::OcclusionCallback( osg::ref_ptr<osg::OcclusionQueryNode> oqnVisible, osg::ref_ptr<osg::OcclusionQueryNode> oqnTotal) : mOcclusionQueryVisiblePixels(std::move(oqnVisible)) , mOcclusionQueryTotalPixels(std::move(oqnTotal)) { } float OcclusionCallback::getVisibleRatio(osg::Camera* camera) { int visible = mOcclusionQueryVisiblePixels->getQueryGeometry()->getNumPixels(camera); int total = mOcclusionQueryTotalPixels->getQueryGeometry()->getNumPixels(camera); float visibleRatio = 0.f; if (total > 0) visibleRatio = static_cast<float>(visible) / static_cast<float>(total); float dt = MWBase::Environment::get().getFrameDuration(); float lastRatio = mLastRatio[osg::observer_ptr<osg::Camera>(camera)]; float change = dt * 10; if (visibleRatio > lastRatio) visibleRatio = std::min(visibleRatio, lastRatio + change); else visibleRatio = std::max(visibleRatio, lastRatio - change); mLastRatio[osg::observer_ptr<osg::Camera>(camera)] = visibleRatio; return visibleRatio; } /// SunFlashCallback handles fading/scaling of a node depending on occlusion query result. Must be attached as a /// cull callback. class SunFlashCallback : public OcclusionCallback, public SceneUtil::NodeCallback<SunFlashCallback, osg::Node*, osgUtil::CullVisitor*> { public: SunFlashCallback( osg::ref_ptr<osg::OcclusionQueryNode> oqnVisible, osg::ref_ptr<osg::OcclusionQueryNode> oqnTotal) : OcclusionCallback(std::move(oqnVisible), std::move(oqnTotal)) , mGlareView(1.f) { } void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { float visibleRatio = getVisibleRatio(cv->getCurrentCamera()); osg::ref_ptr<osg::StateSet> stateset; if (visibleRatio > 0.f) { const float fadeThreshold = 0.1; if (visibleRatio < fadeThreshold) { float fade = 1.f - (fadeThreshold - visibleRatio) / fadeThreshold; osg::ref_ptr<osg::Material> mat(createUnlitMaterial()); mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, fade * mGlareView)); stateset = new osg::StateSet; stateset->setAttributeAndModes(mat, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } else if (visibleRatio < 1.f) { const float threshold = 0.6; visibleRatio = visibleRatio * (1.f - threshold) + threshold; } } float scale = visibleRatio; if (scale == 0.f) { // no traverse return; } else if (scale == 1.f) traverse(node, cv); else { osg::Matrix modelView = *cv->getModelViewMatrix(); modelView.preMultScale(osg::Vec3f(scale, scale, scale)); if (stateset) cv->pushStateSet(stateset); cv->pushModelViewMatrix(new osg::RefMatrix(modelView), osg::Transform::RELATIVE_RF); traverse(node, cv); cv->popModelViewMatrix(); if (stateset) cv->popStateSet(); } } void setGlareView(float value) { mGlareView = value; } private: float mGlareView; }; /// SunGlareCallback controls a full-screen glare effect depending on occlusion query result and the angle between /// sun and camera. Must be attached as a cull callback to the node above the glare node. class SunGlareCallback : public OcclusionCallback, public SceneUtil::NodeCallback<SunGlareCallback, osg::Node*, osgUtil::CullVisitor*> { public: SunGlareCallback(osg::ref_ptr<osg::OcclusionQueryNode> oqnVisible, osg::ref_ptr<osg::OcclusionQueryNode> oqnTotal, osg::ref_ptr<osg::PositionAttitudeTransform> sunTransform) : OcclusionCallback(std::move(oqnVisible), std::move(oqnTotal)) , mSunTransform(std::move(sunTransform)) , mTimeOfDayFade(1.f) , mGlareView(1.f) { mColor = Fallback::Map::getColour("Weather_Sun_Glare_Fader_Color"); mSunGlareFaderMax = Fallback::Map::getFloat("Weather_Sun_Glare_Fader_Max"); mSunGlareFaderAngleMax = Fallback::Map::getFloat("Weather_Sun_Glare_Fader_Angle_Max"); // Replicating a design flaw in MW. The color was being set on both ambient and emissive properties, which // multiplies the result by two, then finally gets clamped by the fixed function pipeline. With the default // INI settings, only the red component gets clamped, so the resulting color looks more orange than red. mColor *= 2; for (int i = 0; i < 3; ++i) mColor[i] = std::min(1.f, mColor[i]); } void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { float angleRadians = getAngleToSunInRadians(*cv->getCurrentRenderStage()->getInitialViewMatrix()); float visibleRatio = getVisibleRatio(cv->getCurrentCamera()); const float angleMaxRadians = osg::DegreesToRadians(mSunGlareFaderAngleMax); float value = 1.f - std::min(1.f, angleRadians / angleMaxRadians); float fade = value * mSunGlareFaderMax; fade *= mTimeOfDayFade * mGlareView * visibleRatio; if (fade == 0.f) { // no traverse return; } else { osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet; osg::ref_ptr<osg::Material> mat = createUnlitMaterial(); mat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0, 0, 0, fade)); mat->setEmission(osg::Material::FRONT_AND_BACK, mColor); stateset->setAttributeAndModes(mat); cv->pushStateSet(stateset); traverse(node, cv); cv->popStateSet(); } } void setTimeOfDayFade(float val) { mTimeOfDayFade = val; } void setGlareView(float glareView) { mGlareView = glareView; } private: float getAngleToSunInRadians(const osg::Matrix& viewMatrix) const { osg::Vec3d eye, center, up; viewMatrix.getLookAt(eye, center, up); osg::Vec3d forward = center - eye; osg::Vec3d sun = mSunTransform->getPosition(); forward.normalize(); sun.normalize(); float angleRadians = std::acos(forward * sun); return angleRadians; } osg::ref_ptr<osg::PositionAttitudeTransform> mSunTransform; float mTimeOfDayFade; float mGlareView; osg::Vec4f mColor; float mSunGlareFaderMax; float mSunGlareFaderAngleMax; }; struct MoonUpdater : SceneUtil::StateSetUpdater { Resource::ImageManager& mImageManager; osg::ref_ptr<osg::Texture2D> mPhaseTex; osg::ref_ptr<osg::Texture2D> mCircleTex; float mTransparency; float mShadowBlend; osg::Vec4f mAtmosphereColor; osg::Vec4f mMoonColor; bool mForceShaders; MoonUpdater(Resource::ImageManager& imageManager, bool forceShaders) : mImageManager(imageManager) , mPhaseTex() , mCircleTex() , mTransparency(1.0f) , mShadowBlend(1.0f) , mAtmosphereColor(1.0f, 1.0f, 1.0f, 1.0f) , mMoonColor(1.0f, 1.0f, 1.0f, 1.0f) , mForceShaders(forceShaders) { } void setDefaults(osg::StateSet* stateset) override { if (mForceShaders) { stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Moon))); stateset->setTextureAttributeAndModes(0, mPhaseTex); stateset->setTextureAttributeAndModes(1, mCircleTex); stateset->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->addUniform(new osg::Uniform("moonBlend", osg::Vec4f{})); stateset->addUniform(new osg::Uniform("atmosphereFade", osg::Vec4f{})); stateset->addUniform(new osg::Uniform("diffuseMap", 0)); stateset->addUniform(new osg::Uniform("maskMap", 1)); stateset->setAttributeAndModes( createUnlitMaterial(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } else { stateset->setTextureAttributeAndModes(0, mPhaseTex); osg::ref_ptr<osg::TexEnvCombine> texEnv = new osg::TexEnvCombine; texEnv->setCombine_RGB(osg::TexEnvCombine::MODULATE); texEnv->setSource0_RGB(osg::TexEnvCombine::CONSTANT); texEnv->setSource1_RGB(osg::TexEnvCombine::TEXTURE); texEnv->setConstantColor(osg::Vec4f(1.f, 0.f, 0.f, 1.f)); // mShadowBlend * mMoonColor stateset->setTextureAttributeAndModes(0, texEnv); stateset->setTextureAttributeAndModes(1, mCircleTex); osg::ref_ptr<osg::TexEnvCombine> texEnv2 = new osg::TexEnvCombine; texEnv2->setCombine_RGB(osg::TexEnvCombine::ADD); texEnv2->setCombine_Alpha(osg::TexEnvCombine::MODULATE); texEnv2->setSource0_Alpha(osg::TexEnvCombine::TEXTURE); texEnv2->setSource1_Alpha(osg::TexEnvCombine::CONSTANT); texEnv2->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); texEnv2->setSource1_RGB(osg::TexEnvCombine::CONSTANT); texEnv2->setConstantColor(osg::Vec4f(0.f, 0.f, 0.f, 1.f)); // mAtmosphereColor.rgb, mTransparency stateset->setTextureAttributeAndModes(1, texEnv2); stateset->setAttributeAndModes( createUnlitMaterial(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } } void apply(osg::StateSet* stateset, osg::NodeVisitor*) override { if (mForceShaders) { stateset->setTextureAttribute(0, mPhaseTex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setTextureAttribute(1, mCircleTex, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); if (auto* uMoonBlend = stateset->getUniform("moonBlend")) uMoonBlend->set(mMoonColor * mShadowBlend); if (auto* uAtmosphereFade = stateset->getUniform("atmosphereFade")) uAtmosphereFade->set( osg::Vec4f(mAtmosphereColor.x(), mAtmosphereColor.y(), mAtmosphereColor.z(), mTransparency)); } else { osg::TexEnvCombine* texEnv = static_cast<osg::TexEnvCombine*>(stateset->getTextureAttribute(0, osg::StateAttribute::TEXENV)); texEnv->setConstantColor(mMoonColor * mShadowBlend); osg::TexEnvCombine* texEnv2 = static_cast<osg::TexEnvCombine*>(stateset->getTextureAttribute(1, osg::StateAttribute::TEXENV)); texEnv2->setConstantColor( osg::Vec4f(mAtmosphereColor.x(), mAtmosphereColor.y(), mAtmosphereColor.z(), mTransparency)); } } void setTextures(VFS::Path::NormalizedView phaseTex, VFS::Path::NormalizedView circleTex) { mPhaseTex = new osg::Texture2D(mImageManager.getImage(phaseTex)); mPhaseTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mPhaseTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mCircleTex = new osg::Texture2D(mImageManager.getImage(circleTex)); mCircleTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mCircleTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); reset(); } }; class CameraRelativeTransformCullCallback : public SceneUtil::NodeCallback<CameraRelativeTransformCullCallback, osg::Node*, osgUtil::CullVisitor*> { public: void operator()(osg::Node* node, osgUtil::CullVisitor* cv) { // XXX have to remove unwanted culling plane of the water reflection camera // Remove all planes that aren't from the standard frustum unsigned int numPlanes = 4; if (cv->getCullingMode() & osg::CullSettings::NEAR_PLANE_CULLING) ++numPlanes; if (cv->getCullingMode() & osg::CullSettings::FAR_PLANE_CULLING) ++numPlanes; unsigned int mask = 0x1; unsigned int resultMask = cv->getProjectionCullingStack().back().getFrustum().getResultMask(); for (unsigned int i = 0; i < cv->getProjectionCullingStack().back().getFrustum().getPlaneList().size(); ++i) { if (i >= numPlanes) { // turn off this culling plane resultMask &= (~mask); } mask <<= 1; } cv->getProjectionCullingStack().back().getFrustum().setResultMask(resultMask); cv->getCurrentCullingSet().getFrustum().setResultMask(resultMask); cv->getProjectionCullingStack().back().pushCurrentMask(); cv->getCurrentCullingSet().pushCurrentMask(); traverse(node, cv); cv->getProjectionCullingStack().back().popCurrentMask(); cv->getCurrentCullingSet().popCurrentMask(); } }; void AtmosphereUpdater::setEmissionColor(const osg::Vec4f& emissionColor) { mEmissionColor = emissionColor; } void AtmosphereUpdater::setDefaults(osg::StateSet* stateset) { stateset->setAttributeAndModes( createAlphaTrackingUnlitMaterial(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Atmosphere))); } void AtmosphereUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) { osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); mat->setEmission(osg::Material::FRONT_AND_BACK, mEmissionColor); } AtmosphereNightUpdater::AtmosphereNightUpdater(Resource::ImageManager* imageManager, bool forceShaders) : mColor(osg::Vec4f(0, 0, 0, 0)) , mTexture(new osg::Texture2D(imageManager->getWarningImage())) , mForceShaders(forceShaders) { mTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); mTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); } void AtmosphereNightUpdater::setFade(float fade) { mColor.a() = fade; } void AtmosphereNightUpdater::setDefaults(osg::StateSet* stateset) { if (mForceShaders) { stateset->addUniform(new osg::Uniform("opacity", 0.f)); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Atmosphere_Night))); } else { osg::ref_ptr<osg::TexEnvCombine> texEnv = new osg::TexEnvCombine; texEnv->setCombine_Alpha(osg::TexEnvCombine::MODULATE); texEnv->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS); texEnv->setSource1_Alpha(osg::TexEnvCombine::CONSTANT); texEnv->setCombine_RGB(osg::TexEnvCombine::REPLACE); texEnv->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); stateset->setTextureAttributeAndModes(1, mTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setTextureAttributeAndModes(1, texEnv, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } } void AtmosphereNightUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) { if (mForceShaders) { stateset->getUniform("opacity")->set(mColor.a()); } else { osg::TexEnvCombine* texEnv = static_cast<osg::TexEnvCombine*>(stateset->getTextureAttribute(1, osg::StateAttribute::TEXENV)); texEnv->setConstantColor(mColor); } } CloudUpdater::CloudUpdater(bool forceShaders) : mOpacity(0.f) , mForceShaders(forceShaders) { } void CloudUpdater::setTexture(osg::ref_ptr<osg::Texture2D> texture) { mTexture = texture; } void CloudUpdater::setEmissionColor(const osg::Vec4f& emissionColor) { mEmissionColor = emissionColor; } void CloudUpdater::setOpacity(float opacity) { mOpacity = opacity; } void CloudUpdater::setTextureCoord(float timer) { mTexMat = osg::Matrixf::translate(osg::Vec3f(0.f, -timer, 0.f)); } void CloudUpdater::setDefaults(osg::StateSet* stateset) { stateset->setAttribute( createAlphaTrackingUnlitMaterial(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::ref_ptr<osg::TexMat> texmat = new osg::TexMat; stateset->setTextureAttributeAndModes(0, texmat); if (mForceShaders) { stateset->setTextureAttribute(0, mTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->addUniform(new osg::Uniform("opacity", 1.f)); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Clouds))); } else { stateset->setTextureAttributeAndModes(1, texmat); // need to set opacity on a separate texture unit, diffuse alpha is used by the vertex colors already osg::ref_ptr<osg::TexEnvCombine> texEnvCombine = new osg::TexEnvCombine; texEnvCombine->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); texEnvCombine->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS); texEnvCombine->setSource1_Alpha(osg::TexEnvCombine::CONSTANT); texEnvCombine->setConstantColor(osg::Vec4f(1, 1, 1, 1)); texEnvCombine->setCombine_Alpha(osg::TexEnvCombine::MODULATE); texEnvCombine->setCombine_RGB(osg::TexEnvCombine::REPLACE); stateset->setTextureAttributeAndModes(1, texEnvCombine); stateset->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } } void CloudUpdater::apply(osg::StateSet* stateset, osg::NodeVisitor* nv) { stateset->setTextureAttribute(0, mTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::Material* mat = static_cast<osg::Material*>(stateset->getAttribute(osg::StateAttribute::MATERIAL)); mat->setEmission(osg::Material::FRONT_AND_BACK, mEmissionColor); osg::TexMat* texMat = static_cast<osg::TexMat*>(stateset->getTextureAttribute(0, osg::StateAttribute::TEXMAT)); texMat->setMatrix(mTexMat); if (mForceShaders) { stateset->getUniform("opacity")->set(mOpacity); } else { stateset->setTextureAttribute(1, mTexture, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::TexEnvCombine* texEnv = static_cast<osg::TexEnvCombine*>(stateset->getTextureAttribute(1, osg::StateAttribute::TEXENV)); texEnv->setConstantColor(osg::Vec4f(1, 1, 1, mOpacity)); } } class SkyStereoStatesetUpdater : public SceneUtil::StateSetUpdater { public: SkyStereoStatesetUpdater() {} protected: void setDefaults(osg::StateSet* stateset) override { if (!Stereo::getMultiview()) stateset->addUniform( new osg::Uniform(osg::Uniform::FLOAT_MAT4, "projectionMatrix"), osg::StateAttribute::OVERRIDE); } void apply(osg::StateSet* stateset, osg::NodeVisitor* /*nv*/) override { if (Stereo::getMultiview()) { std::array<osg::Matrix, 2> projectionMatrices; auto& sm = Stereo::Manager::instance(); for (int view : { 0, 1 }) { auto projectionMatrix = sm.computeEyeProjection(view, SceneUtil::AutoDepth::isReversed()); auto viewOffsetMatrix = sm.computeEyeViewOffset(view); for (int col : { 0, 1, 2 }) viewOffsetMatrix(3, col) = 0; projectionMatrices[view] = viewOffsetMatrix * projectionMatrix; } Stereo::setMultiviewMatrices(stateset, projectionMatrices); } } void applyLeft(osg::StateSet* stateset, osgUtil::CullVisitor* /*cv*/) override { auto& sm = Stereo::Manager::instance(); auto* projectionMatrixUniform = stateset->getUniform("projectionMatrix"); auto projectionMatrix = sm.computeEyeProjection(0, SceneUtil::AutoDepth::isReversed()); projectionMatrixUniform->set(projectionMatrix); } void applyRight(osg::StateSet* stateset, osgUtil::CullVisitor* /*cv*/) override { auto& sm = Stereo::Manager::instance(); auto* projectionMatrixUniform = stateset->getUniform("projectionMatrix"); auto projectionMatrix = sm.computeEyeProjection(1, SceneUtil::AutoDepth::isReversed()); projectionMatrixUniform->set(projectionMatrix); } private: }; CameraRelativeTransform::CameraRelativeTransform() { // Culling works in node-local space, not in camera space, so we can't cull this node correctly // That's not a problem though, children of this node can be culled just fine // Just make sure you do not place a CameraRelativeTransform deep in the scene graph setCullingActive(false); addCullCallback(new CameraRelativeTransformCullCallback); if (Stereo::getStereo()) addCullCallback(new SkyStereoStatesetUpdater); } CameraRelativeTransform::CameraRelativeTransform(const CameraRelativeTransform& copy, const osg::CopyOp& copyop) : osg::Transform(copy, copyop) { } const osg::Vec3f& CameraRelativeTransform::getLastViewPoint() const { return mViewPoint; } bool CameraRelativeTransform::computeLocalToWorldMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const { if (nv->getVisitorType() == osg::NodeVisitor::CULL_VISITOR) { mViewPoint = static_cast<osgUtil::CullVisitor*>(nv)->getViewPoint(); } if (_referenceFrame == RELATIVE_RF) { matrix.setTrans(osg::Vec3f(0.f, 0.f, 0.f)); return false; } else // absolute { matrix.makeIdentity(); return true; } } osg::BoundingSphere CameraRelativeTransform::computeBound() const { return osg::BoundingSphere(); } UnderwaterSwitchCallback::UnderwaterSwitchCallback(CameraRelativeTransform* cameraRelativeTransform) : mCameraRelativeTransform(cameraRelativeTransform) , mEnabled(true) , mWaterLevel(0.f) { } bool UnderwaterSwitchCallback::isUnderwater() { osg::Vec3f viewPoint = mCameraRelativeTransform->getLastViewPoint(); return mEnabled && viewPoint.z() < mWaterLevel; } void UnderwaterSwitchCallback::operator()(osg::Node* node, osg::NodeVisitor* nv) { if (isUnderwater()) return; traverse(node, nv); } void UnderwaterSwitchCallback::setEnabled(bool enabled) { mEnabled = enabled; } void UnderwaterSwitchCallback::setWaterLevel(float waterLevel) { mWaterLevel = waterLevel; } const float CelestialBody::mDistance = 1000.0f; CelestialBody::CelestialBody(osg::Group* parentNode, float scaleFactor, int numUvSets, unsigned int visibleMask) : mVisibleMask(visibleMask) { mGeom = createTexturedQuad(numUvSets); mGeom->getOrCreateStateSet(); mTransform = new osg::PositionAttitudeTransform; mTransform->setNodeMask(mVisibleMask); mTransform->setScale(osg::Vec3f(450, 450, 450) * scaleFactor); mTransform->addChild(mGeom); parentNode->addChild(mTransform); } void CelestialBody::setVisible(bool visible) { mTransform->setNodeMask(visible ? mVisibleMask : 0); } Sun::Sun(osg::Group* parentNode, Resource::SceneManager& sceneManager) : CelestialBody(parentNode, 1.0f, 1, Mask_Sun) , mUpdater(new SunUpdater) { mTransform->addUpdateCallback(mUpdater); Resource::ImageManager& imageManager = *sceneManager.getImageManager(); constexpr VFS::Path::NormalizedView image("textures/tx_sun_05.dds"); osg::ref_ptr<osg::Texture2D> sunTex = new osg::Texture2D(imageManager.getImage(image)); sunTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); sunTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); mGeom->getOrCreateStateSet()->setTextureAttributeAndModes(0, sunTex); mGeom->getOrCreateStateSet()->setTextureAttributeAndModes( 0, new SceneUtil::TextureType("diffuseMap"), osg::StateAttribute::ON); mGeom->getOrCreateStateSet()->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Sun))); osg::ref_ptr<osg::Group> queryNode = new osg::Group; // Need to render after the world geometry so we can correctly test for occlusions osg::StateSet* stateset = queryNode->getOrCreateStateSet(); stateset->setRenderBinDetails(RenderBin_OcclusionQuery, "RenderBin"); stateset->setNestRenderBins(false); // Set up alpha testing on the occlusion testing subgraph, that way we can get the occlusion tested fragments to // match the circular shape of the sun if (!sceneManager.getForceShaders()) { osg::ref_ptr<osg::AlphaFunc> alphaFunc = new osg::AlphaFunc; alphaFunc->setFunction(osg::AlphaFunc::GREATER, 0.8); stateset->setAttributeAndModes(alphaFunc); } stateset->setTextureAttributeAndModes(0, sunTex); stateset->setTextureAttributeAndModes(0, new SceneUtil::TextureType("diffuseMap"), osg::StateAttribute::ON); stateset->setAttributeAndModes(createUnlitMaterial()); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Sunflash_Query))); // Disable writing to the color buffer. We are using this geometry for visibility tests only. osg::ref_ptr<osg::ColorMask> colormask = new osg::ColorMask(0, 0, 0, 0); stateset->setAttributeAndModes(colormask); sceneManager.setUpNormalsRTForStateSet(stateset, false); mTransform->addChild(queryNode); mOcclusionQueryVisiblePixels = createOcclusionQueryNode(queryNode, true); mOcclusionQueryTotalPixels = createOcclusionQueryNode(queryNode, false); createSunFlash(imageManager); createSunGlare(); } Sun::~Sun() { mTransform->removeUpdateCallback(mUpdater); destroySunFlash(); destroySunGlare(); } void Sun::setColor(const osg::Vec4f& color) { mUpdater->mColor.r() = color.r(); mUpdater->mColor.g() = color.g(); mUpdater->mColor.b() = color.b(); } void Sun::adjustTransparency(const float ratio) { mUpdater->mColor.a() = ratio; if (mSunGlareCallback) mSunGlareCallback->setGlareView(ratio); if (mSunFlashCallback) mSunFlashCallback->setGlareView(ratio); } void Sun::setDirection(const osg::Vec3f& direction) { osg::Vec3f normalizedDirection = direction / direction.length(); mTransform->setPosition(normalizedDirection * mDistance); osg::Quat quat; quat.makeRotate(osg::Vec3f(0.0f, 0.0f, 1.0f), normalizedDirection); mTransform->setAttitude(quat); } void Sun::setGlareTimeOfDayFade(float val) { if (mSunGlareCallback) mSunGlareCallback->setTimeOfDayFade(val); } void Sun::setSunglare(bool enabled) { mSunGlareNode->setNodeMask(enabled ? ~0u : 0); mSunFlashNode->setNodeMask(enabled ? ~0u : 0); } osg::ref_ptr<osg::OcclusionQueryNode> Sun::createOcclusionQueryNode(osg::Group* parent, bool queryVisible) { osg::ref_ptr<osg::OcclusionQueryNode> oqn = new osg::OcclusionQueryNode; oqn->setQueriesEnabled(true); // With OSG 3.6.5, the method of providing user defined query geometry has been completely replaced osg::ref_ptr<osg::QueryGeometry> queryGeom = new osg::QueryGeometry(oqn->getName()); // Make it fast! A DYNAMIC query geometry means we can't break frame until the flare is rendered (which is // rendered after all the other geometry, so that would be pretty bad). STATIC should be safe, since our node's // local bounds are static, thus computeBounds() which modifies the queryGeometry is only called once. Note the // debug geometry setDebugDisplay(true) is always DYNAMIC and that can't be changed, not a big deal. queryGeom->setDataVariance(osg::Object::STATIC); // Set up the query geometry to match the actual sun's rendering shape. osg::OcclusionQueryNode wasn't // originally intended to allow this, normally it would automatically adjust the query geometry to match the sub // graph's bounding box. The below hack is needed to circumvent this. queryGeom->setVertexArray(mGeom->getVertexArray()); queryGeom->setTexCoordArray(0, mGeom->getTexCoordArray(0), osg::Array::BIND_PER_VERTEX); queryGeom->removePrimitiveSet(0, queryGeom->getNumPrimitiveSets()); queryGeom->addPrimitiveSet(mGeom->getPrimitiveSet(0)); // Hack to disable unwanted awful code inside OcclusionQueryNode::computeBound. oqn->setComputeBoundingSphereCallback(new DummyComputeBoundCallback); // Still need a proper bounding sphere. oqn->setInitialBound(queryGeom->getBound()); oqn->setQueryGeometry(queryGeom.release()); osg::StateSet* queryStateSet = new osg::StateSet; if (queryVisible) { osg::ref_ptr<osg::Depth> depth = new SceneUtil::AutoDepth(osg::Depth::LEQUAL); // This is a trick to make fragments written by the query always use the maximum depth value, // without having to retrieve the current far clipping distance. // We want the sun glare to be "infinitely" far away. double far = SceneUtil::AutoDepth::isReversed() ? 0.0 : 1.0; depth->setFunction(osg::Depth::LEQUAL); depth->setZNear(far); depth->setZFar(far); depth->setWriteMask(false); queryStateSet->setAttributeAndModes(depth); } else { queryStateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); } oqn->setQueryStateSet(queryStateSet); parent->addChild(oqn); return oqn; } void Sun::createSunFlash(Resource::ImageManager& imageManager) { constexpr VFS::Path::NormalizedView image("textures/tx_sun_flash_grey_05.dds"); osg::ref_ptr<osg::Texture2D> tex = new osg::Texture2D(imageManager.getImage(image)); tex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); tex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); osg::ref_ptr<osg::Group> group(new osg::Group); mTransform->addChild(group); const float scale = 2.6f; osg::ref_ptr<osg::Geometry> geom = createTexturedQuad(1, scale); group->addChild(geom); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(0, tex); stateset->setTextureAttributeAndModes(0, new SceneUtil::TextureType("diffuseMap"), osg::StateAttribute::ON); stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); stateset->setRenderBinDetails(RenderBin_SunGlare, "RenderBin"); stateset->setNestRenderBins(false); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Sun))); mSunFlashNode = group; mSunFlashCallback = new SunFlashCallback(mOcclusionQueryVisiblePixels, mOcclusionQueryTotalPixels); mSunFlashNode->addCullCallback(mSunFlashCallback); } void Sun::destroySunFlash() { if (mSunFlashNode) { mSunFlashNode->removeCullCallback(mSunFlashCallback); mSunFlashCallback = nullptr; } } void Sun::createSunGlare() { osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setProjectionMatrix(osg::Matrix::identity()); camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF); // add to skyRoot instead? camera->setViewMatrix(osg::Matrix::identity()); camera->setClearMask(0); camera->setRenderOrder(osg::Camera::NESTED_RENDER); camera->setAllowEventFocus(false); camera->getOrCreateStateSet()->addUniform( new osg::Uniform("projectionMatrix", static_cast<osg::Matrixf>(camera->getProjectionMatrix()))); SceneUtil::setCameraClearDepth(camera); osg::ref_ptr<osg::Geometry> geom = osg::createTexturedQuadGeometry(osg::Vec3f(-1, -1, 0), osg::Vec3f(2, 0, 0), osg::Vec3f(0, 2, 0)); camera->addChild(geom); osg::StateSet* stateset = geom->getOrCreateStateSet(); stateset->setRenderBinDetails(RenderBin_SunGlare, "RenderBin"); stateset->setNestRenderBins(false); stateset->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); stateset->addUniform(new osg::Uniform("pass", static_cast<int>(Pass::Sunglare))); // set up additive blending osg::ref_ptr<osg::BlendFunc> blendFunc = new osg::BlendFunc; blendFunc->setSource(osg::BlendFunc::SRC_ALPHA); blendFunc->setDestination(osg::BlendFunc::ONE); stateset->setAttributeAndModes(blendFunc); mSunGlareCallback = new SunGlareCallback(mOcclusionQueryVisiblePixels, mOcclusionQueryTotalPixels, mTransform); mSunGlareNode = camera; mSunGlareNode->addCullCallback(mSunGlareCallback); mTransform->addChild(camera); } void Sun::destroySunGlare() { if (mSunGlareNode) { mSunGlareNode->removeCullCallback(mSunGlareCallback); mSunGlareCallback = nullptr; } } Moon::Moon(osg::Group* parentNode, Resource::SceneManager& sceneManager, float scaleFactor, Type type) : CelestialBody(parentNode, scaleFactor, 2) , mType(type) , mPhase(MoonState::Phase::Unspecified) , mUpdater(new MoonUpdater(*sceneManager.getImageManager(), sceneManager.getForceShaders())) { setPhase(MoonState::Phase::Full); setVisible(true); mGeom->addUpdateCallback(mUpdater); } Moon::~Moon() { mGeom->removeUpdateCallback(mUpdater); } void Moon::adjustTransparency(const float ratio) { mUpdater->mTransparency *= ratio; } void Moon::setState(const MoonState state) { float radsX = ((state.mRotationFromHorizon) * static_cast<float>(osg::PI)) / 180.0f; float radsZ = ((state.mRotationFromNorth) * static_cast<float>(osg::PI)) / 180.0f; osg::Quat rotX(radsX, osg::Vec3f(1.0f, 0.0f, 0.0f)); osg::Quat rotZ(radsZ, osg::Vec3f(0.0f, 0.0f, 1.0f)); osg::Vec3f direction = rotX * rotZ * osg::Vec3f(0.0f, 1.0f, 0.0f); mTransform->setPosition(direction * mDistance); // The moon quad is initially oriented facing down, so we need to offset its X-axis // rotation to rotate it to face the camera when sitting at the horizon. osg::Quat attX((-static_cast<float>(osg::PI) / 2.0f) + radsX, osg::Vec3f(1.0f, 0.0f, 0.0f)); mTransform->setAttitude(attX * rotZ); setPhase(state.mPhase); mUpdater->mTransparency = state.mMoonAlpha; mUpdater->mShadowBlend = state.mShadowBlend; } void Moon::setAtmosphereColor(const osg::Vec4f& color) { mUpdater->mAtmosphereColor = color; } void Moon::setColor(const osg::Vec4f& color) { mUpdater->mMoonColor = color; } unsigned int Moon::getPhaseInt() const { switch (mPhase) { case MoonState::Phase::New: return 0; case MoonState::Phase::WaxingCrescent: return 1; case MoonState::Phase::WaningCrescent: return 1; case MoonState::Phase::FirstQuarter: return 2; case MoonState::Phase::ThirdQuarter: return 2; case MoonState::Phase::WaxingGibbous: return 3; case MoonState::Phase::WaningGibbous: return 3; case MoonState::Phase::Full: return 4; default: return 0; } } void Moon::setPhase(const MoonState::Phase& phase) { if (mPhase == phase) return; mPhase = phase; std::string textureName = "textures/tx_"; if (mType == Moon::Type_Secunda) textureName += "secunda_"; else textureName += "masser_"; switch (mPhase) { case MoonState::Phase::New: textureName += "new"; break; case MoonState::Phase::WaxingCrescent: textureName += "one_wax"; break; case MoonState::Phase::FirstQuarter: textureName += "half_wax"; break; case MoonState::Phase::WaxingGibbous: textureName += "three_wax"; break; case MoonState::Phase::WaningCrescent: textureName += "one_wan"; break; case MoonState::Phase::ThirdQuarter: textureName += "half_wan"; break; case MoonState::Phase::WaningGibbous: textureName += "three_wan"; break; case MoonState::Phase::Full: textureName += "full"; break; default: break; } textureName += ".dds"; const VFS::Path::Normalized texturePath(std::move(textureName)); if (mType == Moon::Type_Secunda) { constexpr VFS::Path::NormalizedView secunda("textures/tx_mooncircle_full_s.dds"); mUpdater->setTextures(texturePath, secunda); } else { constexpr VFS::Path::NormalizedView masser("textures/tx_mooncircle_full_m.dds"); mUpdater->setTextures(texturePath, masser); } } int RainCounter::numParticlesToCreate(double dt) const { // limit dt to avoid large particle emissions if there are jumps in the simulation time // 0.2 seconds is the same cap as used in Engine's frame loop dt = std::min(dt, 0.2); return ConstantRateCounter::numParticlesToCreate(dt); } RainShooter::RainShooter() : mAngle(0.f) { } void RainShooter::shoot(osgParticle::Particle* particle) const { particle->setVelocity(mVelocity); particle->setAngle(osg::Vec3f(-mAngle, 0, (Misc::Rng::rollProbability() * 2 - 1) * osg::PI)); } void RainShooter::setVelocity(const osg::Vec3f& velocity) { mVelocity = velocity; } void RainShooter::setAngle(float angle) { mAngle = angle; } osg::Object* RainShooter::cloneType() const { return new RainShooter; } osg::Object* RainShooter::clone(const osg::CopyOp&) const { return new RainShooter(*this); } ModVertexAlphaVisitor::ModVertexAlphaVisitor(ModVertexAlphaVisitor::MeshType type) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mType(type) { } void ModVertexAlphaVisitor::apply(osg::Geometry& geometry) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(geometry.getVertexArray()->getNumElements()); for (unsigned int i = 0; i < colors->size(); ++i) { float alpha = 1.f; switch (mType) { case ModVertexAlphaVisitor::Atmosphere: { // this is a cylinder, so every second vertex belongs to the bottom-most row alpha = (i % 2) ? 0.f : 1.f; break; } case ModVertexAlphaVisitor::Clouds: { if (i >= 49 && i <= 64) alpha = 0.f; // bottom-most row else if (i >= 33 && i <= 48) alpha = 0.25098; // second row else alpha = 1.f; break; } case ModVertexAlphaVisitor::Stars: { if (geometry.getColorArray()) { osg::Vec4Array* origColors = static_cast<osg::Vec4Array*>(geometry.getColorArray()); alpha = ((*origColors)[i].x() == 1.f) ? 1.f : 0.f; } else alpha = 1.f; break; } } (*colors)[i] = osg::Vec4f(0.f, 0.f, 0.f, alpha); } geometry.setColorArray(colors, osg::Array::BIND_PER_VERTEX); } }
46,567
C++
.cpp
1,016
35.46752
120
0.623068
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,401
pingpongcanvas.cpp
OpenMW_openmw/apps/openmw/mwrender/pingpongcanvas.cpp
#include "pingpongcanvas.hpp" #include <cassert> #include <components/shader/shadermanager.hpp> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include <osg/Texture2DArray> #include "postprocessor.hpp" namespace MWRender { PingPongCanvas::PingPongCanvas( Shader::ShaderManager& shaderManager, const std::shared_ptr<LuminanceCalculator>& luminanceCalculator) : mFallbackStateSet(new osg::StateSet) , mMultiviewResolveStateSet(new osg::StateSet) , mLuminanceCalculator(luminanceCalculator) { setUseDisplayList(false); setUseVertexBufferObjects(true); osg::ref_ptr<osg::Vec3Array> verts = new osg::Vec3Array; verts->push_back(osg::Vec3f(-1, -1, 0)); verts->push_back(osg::Vec3f(-1, 3, 0)); verts->push_back(osg::Vec3f(3, -1, 0)); setVertexArray(verts); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, 3)); mLuminanceCalculator->disable(); Shader::ShaderManager::DefineMap defines; Stereo::shaderStereoDefines(defines); mFallbackProgram = shaderManager.getProgram("fullscreen_tri"); mFallbackStateSet->setAttributeAndModes(mFallbackProgram); mFallbackStateSet->addUniform(new osg::Uniform("lastShader", 0)); mFallbackStateSet->addUniform(new osg::Uniform("scaling", osg::Vec2f(1, 1))); mMultiviewResolveProgram = shaderManager.getProgram("multiview_resolve"); mMultiviewResolveStateSet->setAttributeAndModes(mMultiviewResolveProgram); mMultiviewResolveStateSet->addUniform(new osg::Uniform("lastShader", 0)); } void PingPongCanvas::setPasses(fx::DispatchArray&& passes) { mPasses = std::move(passes); } void PingPongCanvas::setMask(bool underwater, bool exterior) { mMask = 0; mMask |= underwater ? fx::Technique::Flag_Disable_Underwater : fx::Technique::Flag_Disable_Abovewater; mMask |= exterior ? fx::Technique::Flag_Disable_Exteriors : fx::Technique::Flag_Disable_Interiors; } void PingPongCanvas::drawGeometry(osg::RenderInfo& renderInfo) const { osg::Geometry::drawImplementation(renderInfo); } static void attachCloneOfTemplate( osg::FrameBufferObject* fbo, osg::Camera::BufferComponent component, osg::Texture* tex) { osg::ref_ptr<osg::Texture> clone = static_cast<osg::Texture*>(tex->clone(osg::CopyOp::SHALLOW_COPY)); fbo->setAttachment(component, Stereo::createMultiviewCompatibleAttachment(clone)); } void PingPongCanvas::drawImplementation(osg::RenderInfo& renderInfo) const { osg::State& state = *renderInfo.getState(); osg::GLExtensions* ext = state.get<osg::GLExtensions>(); size_t frameId = state.getFrameStamp()->getFrameNumber() % 2; std::vector<size_t> filtered; filtered.reserve(mPasses.size()); for (size_t i = 0; i < mPasses.size(); ++i) { const auto& node = mPasses[i]; if (mMask & node.mFlags) continue; filtered.push_back(i); } auto* resolveViewport = state.getCurrentViewport(); if (filtered.empty() || !mPostprocessing) { state.pushStateSet(mFallbackStateSet); state.apply(); if (Stereo::getMultiview()) { state.pushStateSet(mMultiviewResolveStateSet); state.apply(); } state.applyTextureAttribute(0, mTextureScene); resolveViewport->apply(state); drawGeometry(renderInfo); state.popStateSet(); if (Stereo::getMultiview()) { state.popStateSet(); } return; } const unsigned int handle = mFbos[0] ? mFbos[0]->getHandle(state.getContextID()) : 0; if (handle == 0 || mDirty) { for (auto& fbo : mFbos) { fbo = new osg::FrameBufferObject; attachCloneOfTemplate(fbo, osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, mTextureScene); fbo->apply(state); glClearColor(0.5, 0.5, 0.5, 1); glClear(GL_COLOR_BUFFER_BIT); } if (Stereo::getMultiview()) { mMultiviewResolveFramebuffer = new osg::FrameBufferObject(); attachCloneOfTemplate(mMultiviewResolveFramebuffer, osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, mTextureScene); mMultiviewResolveFramebuffer->apply(state); glClearColor(0.5, 0.5, 0.5, 1); glClear(GL_COLOR_BUFFER_BIT); mMultiviewResolveStateSet->setTextureAttribute(PostProcessor::Unit_LastShader, (osg::Texture*)mMultiviewResolveFramebuffer->getAttachment(osg::Camera::COLOR_BUFFER0) .getTexture()); } mLuminanceCalculator->dirty(mTextureScene->getTextureWidth(), mTextureScene->getTextureHeight()); if (Stereo::getStereo()) mRenderViewport = new osg::Viewport(0, 0, mTextureScene->getTextureWidth(), mTextureScene->getTextureHeight()); else mRenderViewport = nullptr; mDirty = false; } constexpr std::array<std::array<int, 2>, 3> buffers = { { { GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT }, { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT2_EXT }, { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT } } }; (mAvgLum) ? mLuminanceCalculator->enable() : mLuminanceCalculator->disable(); // A histogram based approach is superior way to calculate scene luminance. Using mipmaps is more broadly // supported, so that's what we use for now. mLuminanceCalculator->draw(*this, renderInfo, state, ext, frameId); auto buffer = buffers[0]; int lastDraw = 0; int lastShader = 0; unsigned int lastApplied = handle; const unsigned int cid = state.getContextID(); const osg::ref_ptr<osg::FrameBufferObject>& destinationFbo = mDestinationFBO ? mDestinationFBO : nullptr; unsigned int destinationHandle = destinationFbo ? destinationFbo->getHandle(cid) : 0; auto bindDestinationFbo = [&]() { if (destinationFbo) { destinationFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); lastApplied = destinationHandle; } else if (Stereo::getMultiview()) { mMultiviewResolveFramebuffer->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); lastApplied = mMultiviewResolveFramebuffer->getHandle(cid); } else { ext->glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0); lastApplied = 0; } }; // When textures are created (or resized) we need to either dirty them and/or clear them. // Otherwise, there will be undefined behavior when reading from a texture that has yet to be written to in a // later pass. for (const auto& attachment : mDirtyAttachments) { const auto [w, h] = attachment.mSize.get(mTextureScene->getTextureWidth(), mTextureScene->getTextureHeight()); attachment.mTarget->setTextureSize(w, h); if (attachment.mMipMap) attachment.mTarget->setNumMipmapLevels(osg::Image::computeNumberOfMipmapLevels(w, h)); attachment.mTarget->dirtyTextureObject(); osg::ref_ptr<osg::FrameBufferObject> fbo = new osg::FrameBufferObject; fbo->setAttachment( osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(attachment.mTarget)); fbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); glViewport(0, 0, attachment.mTarget->getTextureWidth(), attachment.mTarget->getTextureHeight()); state.haveAppliedAttribute(osg::StateAttribute::VIEWPORT); glClearColor(attachment.mClearColor.r(), attachment.mClearColor.g(), attachment.mClearColor.b(), attachment.mClearColor.a()); glClear(GL_COLOR_BUFFER_BIT); if (attachment.mTarget->getNumMipmapLevels() > 0) { state.setActiveTextureUnit(0); state.applyTextureAttribute(0, attachment.mTarget); ext->glGenerateMipmap(GL_TEXTURE_2D); } } for (const size_t& index : filtered) { const auto& node = mPasses[index]; node.mRootStateSet->setTextureAttribute(PostProcessor::Unit_Depth, mTextureDepth); if (mAvgLum) node.mRootStateSet->setTextureAttribute(PostProcessor::TextureUnits::Unit_EyeAdaptation, mLuminanceCalculator->getLuminanceTexture(frameId)); if (mTextureNormals) node.mRootStateSet->setTextureAttribute(PostProcessor::TextureUnits::Unit_Normals, mTextureNormals); if (mTextureDistortion) node.mRootStateSet->setTextureAttribute( PostProcessor::TextureUnits::Unit_Distortion, mTextureDistortion); state.pushStateSet(node.mRootStateSet); state.apply(); for (size_t passIndex = 0; passIndex < node.mPasses.size(); ++passIndex) { if (mRenderViewport) mRenderViewport->apply(state); const auto& pass = node.mPasses[passIndex]; bool lastPass = passIndex == node.mPasses.size() - 1; // VR-TODO: This won't actually work for tex2darrays if (lastShader == 0) pass.mStateSet->setTextureAttribute(PostProcessor::Unit_LastShader, mTextureScene); else pass.mStateSet->setTextureAttribute(PostProcessor::Unit_LastShader, (osg::Texture*)mFbos[lastShader - GL_COLOR_ATTACHMENT0_EXT] ->getAttachment(osg::Camera::COLOR_BUFFER0) .getTexture()); if (lastDraw == 0) pass.mStateSet->setTextureAttribute(PostProcessor::Unit_LastPass, mTextureScene); else pass.mStateSet->setTextureAttribute(PostProcessor::Unit_LastPass, (osg::Texture*)mFbos[lastDraw - GL_COLOR_ATTACHMENT0_EXT] ->getAttachment(osg::Camera::COLOR_BUFFER0) .getTexture()); if (pass.mRenderTarget) { pass.mRenderTarget->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); if (pass.mRenderTexture->getNumMipmapLevels() > 0) { state.setActiveTextureUnit(0); state.applyTextureAttribute(0, pass.mRenderTarget->getAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0) .getTexture()); ext->glGenerateMipmap(GL_TEXTURE_2D); } lastApplied = pass.mRenderTarget->getHandle(state.getContextID()); } else if (pass.mResolve && index == filtered.back()) { bindDestinationFbo(); if (!destinationFbo && !Stereo::getMultiview()) { resolveViewport->apply(state); } } else if (lastPass) { lastDraw = buffer[0]; lastShader = buffer[0]; mFbos[buffer[0] - GL_COLOR_ATTACHMENT0_EXT]->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); buffer = buffers[lastShader - GL_COLOR_ATTACHMENT0_EXT]; lastApplied = mFbos[buffer[0] - GL_COLOR_ATTACHMENT0_EXT]->getHandle(cid); } else { mFbos[buffer[0] - GL_COLOR_ATTACHMENT0_EXT]->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); lastDraw = buffer[0]; std::swap(buffer[0], buffer[1]); lastApplied = mFbos[buffer[0] - GL_COLOR_ATTACHMENT0_EXT]->getHandle(cid); } state.pushStateSet(pass.mStateSet); state.apply(); if (!state.getLastAppliedProgramObject()) mFallbackProgram->apply(state); drawGeometry(renderInfo); state.popStateSet(); state.apply(); } state.popStateSet(); } if (Stereo::getMultiview()) { ext->glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0); lastApplied = 0; resolveViewport->apply(state); state.pushStateSet(mMultiviewResolveStateSet); state.apply(); drawGeometry(renderInfo); state.popStateSet(); state.apply(); } if (lastApplied != destinationHandle) { bindDestinationFbo(); } mDirtyAttachments.clear(); } }
13,584
C++
.cpp
277
35.418773
120
0.5925
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,402
objectpaging.cpp
OpenMW_openmw/apps/openmw/mwrender/objectpaging.cpp
#include "objectpaging.hpp" #include <unordered_map> #include <vector> #include <osg/LOD> #include <osg/Material> #include <osg/MatrixTransform> #include <osg/Sequence> #include <osg/Switch> #include <osgAnimation/BasicAnimationManager> #include <osgParticle/ParticleProcessor> #include <osgParticle/ParticleSystemUpdater> #include <osgUtil/IncrementalCompileOperation> #include <components/esm3/esmreader.hpp> #include <components/esm3/loadacti.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm3/loadcont.hpp> #include <components/esm3/loaddoor.hpp> #include <components/esm3/loadstat.hpp> #include <components/esm3/readerscache.hpp> #include <components/misc/pathhelpers.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/misc/rng.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/morphgeometry.hpp> #include <components/sceneutil/optimizer.hpp> #include <components/sceneutil/positionattitudetransform.hpp> #include <components/sceneutil/riggeometry.hpp> #include <components/sceneutil/riggeometryosgaextension.hpp> #include <components/sceneutil/util.hpp> #include <components/settings/values.hpp> #include <components/vfs/manager.hpp> #include "apps/openmw/mwbase/environment.hpp" #include "apps/openmw/mwbase/world.hpp" #include "apps/openmw/mwworld/esmstore.hpp" #include "vismask.hpp" namespace MWRender { namespace { bool typeFilter(int type, bool far) { switch (type) { case ESM::REC_STAT: case ESM::REC_ACTI: case ESM::REC_DOOR: return true; case ESM::REC_CONT: return !far; default: return false; } } std::string getModel(int type, ESM::RefId id, const MWWorld::ESMStore& store) { switch (type) { case ESM::REC_STAT: return store.get<ESM::Static>().searchStatic(id)->mModel; case ESM::REC_ACTI: return store.get<ESM::Activator>().searchStatic(id)->mModel; case ESM::REC_DOOR: return store.get<ESM::Door>().searchStatic(id)->mModel; case ESM::REC_CONT: return store.get<ESM::Container>().searchStatic(id)->mModel; default: return {}; } } } osg::ref_ptr<osg::Node> ObjectPaging::getChunk(float size, const osg::Vec2f& center, unsigned char /*lod*/, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) { if (activeGrid && !mActiveGrid) return nullptr; const ChunkId id = std::make_tuple(center, size, activeGrid); if (const osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(id)) return static_cast<osg::Node*>(obj.get()); const unsigned char lod = static_cast<unsigned char>(lodFlags >> (4 * 4)); osg::ref_ptr<osg::Node> node = createChunk(size, center, activeGrid, viewPoint, compile, lod); mCache->addEntryToObjectCache(id, node.get()); return node; } namespace { class CanOptimizeCallback : public SceneUtil::Optimizer::IsOperationPermissibleForObjectCallback { public: bool isOperationPermissibleForObjectImplementation( const SceneUtil::Optimizer* optimizer, const osg::Drawable* node, unsigned int option) const override { return true; } bool isOperationPermissibleForObjectImplementation( const SceneUtil::Optimizer* optimizer, const osg::Node* node, unsigned int option) const override { return (node->getDataVariance() != osg::Object::DYNAMIC); } }; using LODRange = osg::LOD::MinMaxPair; LODRange intersection(const LODRange& left, const LODRange& right) { return { std::max(left.first, right.first), std::min(left.second, right.second) }; } bool empty(const LODRange& r) { return r.first >= r.second; } LODRange operator/(const LODRange& r, float div) { return { r.first / div, r.second / div }; } class CopyOp : public osg::CopyOp { public: bool mOptimizeBillboards = true; LODRange mDistances = { 0.f, 0.f }; osg::Vec3f mViewVector; osg::Node::NodeMask mCopyMask = ~0u; mutable std::vector<const osg::Node*> mNodePath; void copy(const osg::Node* toCopy, osg::Group* attachTo) { const osg::Group* groupToCopy = toCopy->asGroup(); if (toCopy->getStateSet() || toCopy->asTransform() || !groupToCopy) attachTo->addChild(operator()(toCopy)); else { for (unsigned int i = 0; i < groupToCopy->getNumChildren(); ++i) attachTo->addChild(operator()(groupToCopy->getChild(i))); } } osg::Node* operator()(const osg::Node* node) const override { if (!(node->getNodeMask() & mCopyMask)) return nullptr; if (const osg::Drawable* d = node->asDrawable()) return operator()(d); if (dynamic_cast<const osgParticle::ParticleProcessor*>(node)) return nullptr; if (dynamic_cast<const osgParticle::ParticleSystemUpdater*>(node)) return nullptr; if (const osg::Switch* sw = node->asSwitch()) { osg::Group* n = new osg::Group; for (unsigned int i = 0; i < sw->getNumChildren(); ++i) if (sw->getValue(i)) n->addChild(operator()(sw->getChild(i))); n->setDataVariance(osg::Object::STATIC); return n; } if (const osg::LOD* lod = dynamic_cast<const osg::LOD*>(node)) { std::vector<std::pair<osg::ref_ptr<osg::Node>, LODRange>> children; for (unsigned int i = 0; i < lod->getNumChildren(); ++i) if (const auto r = intersection(lod->getRangeList()[i], mDistances); !empty(r)) children.emplace_back(operator()(lod->getChild(i)), lod->getRangeList()[i]); if (children.empty()) return nullptr; if (children.size() == 1) return children.front().first.release(); else { osg::LOD* n = new osg::LOD; for (const auto& [child, range] : children) n->addChild(child, range.first, range.second); n->setDataVariance(osg::Object::STATIC); return n; } } if (const osg::Sequence* sq = dynamic_cast<const osg::Sequence*>(node)) { osg::Group* n = new osg::Group; n->addChild(operator()(sq->getChild(sq->getValue() != -1 ? sq->getValue() : 0))); n->setDataVariance(osg::Object::STATIC); return n; } mNodePath.push_back(node); osg::Node* cloned = static_cast<osg::Node*>(node->clone(*this)); cloned->setDataVariance(osg::Object::STATIC); cloned->setUserDataContainer(nullptr); cloned->setName(""); mNodePath.pop_back(); handleCallbacks(node, cloned); return cloned; } void handleCallbacks(const osg::Node* node, osg::Node* cloned) const { for (const osg::Callback* callback = node->getCullCallback(); callback != nullptr; callback = callback->getNestedCallback()) { if (callback->className() == std::string("BillboardCallback")) { if (mOptimizeBillboards) { handleBillboard(cloned); continue; } else cloned->setDataVariance(osg::Object::DYNAMIC); } if (node->getCullCallback()->getNestedCallback()) { osg::Callback* clonedCallback = osg::clone(callback, osg::CopyOp::SHALLOW_COPY); clonedCallback->setNestedCallback(nullptr); cloned->addCullCallback(clonedCallback); } else cloned->addCullCallback(const_cast<osg::Callback*>(callback)); } } void handleBillboard(osg::Node* node) const { osg::Transform* transform = node->asTransform(); if (!transform) return; osg::MatrixTransform* matrixTransform = transform->asMatrixTransform(); if (!matrixTransform) return; osg::Matrix worldToLocal = osg::Matrix::identity(); for (auto pathNode : mNodePath) if (const osg::Transform* t = pathNode->asTransform()) t->computeWorldToLocalMatrix(worldToLocal, nullptr); worldToLocal = osg::Matrix::orthoNormal(worldToLocal); osg::Matrix billboardMatrix; osg::Vec3f viewVector = -(mViewVector + worldToLocal.getTrans()); viewVector.normalize(); osg::Vec3f right = viewVector ^ osg::Vec3f(0, 0, 1); right.normalize(); osg::Vec3f up = right ^ viewVector; up.normalize(); billboardMatrix.makeLookAt(osg::Vec3f(0, 0, 0), viewVector, up); billboardMatrix.invert(billboardMatrix); const osg::Matrix& oldMatrix = matrixTransform->getMatrix(); float mag[3]; // attempt to preserve scale for (int i = 0; i < 3; ++i) mag[i] = std::sqrt(oldMatrix(0, i) * oldMatrix(0, i) + oldMatrix(1, i) * oldMatrix(1, i) + oldMatrix(2, i) * oldMatrix(2, i)); osg::Matrix newMatrix; worldToLocal.setTrans(0, 0, 0); newMatrix *= worldToLocal; newMatrix.preMult(billboardMatrix); newMatrix.preMultScale(osg::Vec3f(mag[0], mag[1], mag[2])); newMatrix.setTrans(oldMatrix.getTrans()); matrixTransform->setMatrix(newMatrix); } osg::Drawable* operator()(const osg::Drawable* drawable) const override { if (!(drawable->getNodeMask() & mCopyMask)) return nullptr; if (dynamic_cast<const osgParticle::ParticleSystem*>(drawable)) return nullptr; if (dynamic_cast<const SceneUtil::OsgaRigGeometry*>(drawable)) return nullptr; if (const SceneUtil::RigGeometry* rig = dynamic_cast<const SceneUtil::RigGeometry*>(drawable)) return operator()(rig->getSourceGeometry()); if (const SceneUtil::MorphGeometry* morph = dynamic_cast<const SceneUtil::MorphGeometry*>(drawable)) return operator()(morph->getSourceGeometry()); if (getCopyFlags() & DEEP_COPY_DRAWABLES) { osg::Drawable* d = static_cast<osg::Drawable*>(drawable->clone(*this)); d->setDataVariance(osg::Object::STATIC); d->setUserDataContainer(nullptr); d->setName(""); return d; } else return const_cast<osg::Drawable*>(drawable); } osg::Callback* operator()(const osg::Callback* callback) const override { return nullptr; } }; class RefnumSet : public osg::Object { public: RefnumSet() {} RefnumSet(const RefnumSet& copy, const osg::CopyOp&) : mRefnums(copy.mRefnums) { } META_Object(MWRender, RefnumSet) std::vector<ESM::RefNum> mRefnums; }; class AnalyzeVisitor : public osg::NodeVisitor { public: AnalyzeVisitor(osg::Node::NodeMask analyzeMask) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mCurrentStateSet(nullptr) { setTraversalMask(analyzeMask); } typedef std::unordered_map<osg::StateSet*, unsigned int> StateSetCounter; struct Result { StateSetCounter mStateSetCounter; unsigned int mNumVerts = 0; }; void apply(osg::Node& node) override { if (node.getStateSet()) mCurrentStateSet = node.getStateSet(); if (osg::Switch* sw = node.asSwitch()) { for (unsigned int i = 0; i < sw->getNumChildren(); ++i) if (sw->getValue(i)) traverse(*sw->getChild(i)); return; } if (osg::LOD* lod = dynamic_cast<osg::LOD*>(&node)) { for (unsigned int i = 0; i < lod->getNumChildren(); ++i) if (const auto r = intersection(lod->getRangeList()[i], mDistances); !empty(r)) traverse(*lod->getChild(i)); return; } if (osg::Sequence* sq = dynamic_cast<osg::Sequence*>(&node)) { traverse(*sq->getChild(sq->getValue() != -1 ? sq->getValue() : 0)); return; } traverse(node); } void apply(osg::Geometry& geom) override { if (osg::Array* array = geom.getVertexArray()) mResult.mNumVerts += array->getNumElements(); ++mResult.mStateSetCounter[mCurrentStateSet]; ++mGlobalStateSetCounter[mCurrentStateSet]; } Result retrieveResult() { Result result = mResult; mResult = Result(); mCurrentStateSet = nullptr; return result; } void addInstance(const Result& result) { for (auto pair : result.mStateSetCounter) mGlobalStateSetCounter[pair.first] += pair.second; } float getMergeBenefit(const Result& result) { if (result.mStateSetCounter.empty()) return 1; float mergeBenefit = 0; for (auto pair : result.mStateSetCounter) { mergeBenefit += mGlobalStateSetCounter[pair.first]; } mergeBenefit /= result.mStateSetCounter.size(); return mergeBenefit; } Result mResult; osg::StateSet* mCurrentStateSet; StateSetCounter mGlobalStateSetCounter; LODRange mDistances = { 0.f, 0.f }; }; class DebugVisitor : public osg::NodeVisitor { public: DebugVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Drawable& node) override { osg::ref_ptr<osg::Material> m(new osg::Material); osg::Vec4f color( Misc::Rng::rollProbability(), Misc::Rng::rollProbability(), Misc::Rng::rollProbability(), 0.f); color.normalize(); m->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.1f, 0.1f, 0.1f, 1.f)); m->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.1f, 0.1f, 0.1f, 1.f)); m->setColorMode(osg::Material::OFF); m->setEmission(osg::Material::FRONT_AND_BACK, osg::Vec4f(color)); osg::ref_ptr<osg::StateSet> stateset = node.getStateSet() ? osg::clone(node.getStateSet(), osg::CopyOp::SHALLOW_COPY) : new osg::StateSet; stateset->setAttribute(m); stateset->addUniform(new osg::Uniform("colorMode", 0)); stateset->addUniform(new osg::Uniform("emissiveMult", 1.f)); stateset->addUniform(new osg::Uniform("specStrength", 1.f)); node.setStateSet(stateset); } }; class AddRefnumMarkerVisitor : public osg::NodeVisitor { public: AddRefnumMarkerVisitor(ESM::RefNum refnum) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mRefnum(refnum) { } ESM::RefNum mRefnum; void apply(osg::Geometry& node) override { osg::ref_ptr<RefnumMarker> marker(new RefnumMarker); marker->mRefnum = mRefnum; if (osg::Array* array = node.getVertexArray()) marker->mNumVertices = array->getNumElements(); node.getOrCreateUserDataContainer()->addUserObject(marker); } }; } ObjectPaging::ObjectPaging(Resource::SceneManager* sceneManager, ESM::RefId worldspace) : GenericResourceManager<ChunkId>(nullptr, Settings::cells().mCacheExpiryDelay) , Terrain::QuadTreeWorld::ChunkManager(worldspace) , mSceneManager(sceneManager) , mActiveGrid(Settings::terrain().mObjectPagingActiveGrid) , mDebugBatches(Settings::terrain().mDebugChunks) , mMergeFactor(Settings::terrain().mObjectPagingMergeFactor) , mMinSize(Settings::terrain().mObjectPagingMinSize) , mMinSizeMergeFactor(Settings::terrain().mObjectPagingMinSizeMergeFactor) , mMinSizeCostMultiplier(Settings::terrain().mObjectPagingMinSizeCostMultiplier) , mRefTrackerLocked(false) { } namespace { struct PagedCellRef { ESM::RefId mRefId; ESM::RefNum mRefNum; osg::Vec3f mPosition; osg::Vec3f mRotation; float mScale; }; PagedCellRef makePagedCellRef(const ESM::CellRef& value) { return PagedCellRef{ .mRefId = value.mRefID, .mRefNum = value.mRefNum, .mPosition = value.mPos.asVec3(), .mRotation = value.mPos.asRotationVec3(), .mScale = value.mScale, }; } std::map<ESM::RefNum, PagedCellRef> collectESM3References( float size, const osg::Vec2i& startCell, const MWWorld::ESMStore& store) { std::map<ESM::RefNum, PagedCellRef> refs; ESM::ReadersCache readers; for (int cellX = startCell.x(); cellX < startCell.x() + size; ++cellX) { for (int cellY = startCell.y(); cellY < startCell.y() + size; ++cellY) { const ESM::Cell* cell = store.get<ESM::Cell>().searchStatic(cellX, cellY); if (!cell) continue; for (size_t i = 0; i < cell->mContextList.size(); ++i) { try { const std::size_t index = static_cast<std::size_t>(cell->mContextList[i].index); const ESM::ReadersCache::BusyItem reader = readers.get(index); cell->restore(*reader, i); ESM::CellRef ref; ESM::MovedCellRef cMRef; bool deleted = false; bool moved = false; while (ESM::Cell::getNextRef( *reader, ref, deleted, cMRef, moved, ESM::Cell::GetNextRefMode::LoadOnlyNotMoved)) { if (moved) continue; if (std::find(cell->mMovedRefs.begin(), cell->mMovedRefs.end(), ref.mRefNum) != cell->mMovedRefs.end()) continue; int type = store.findStatic(ref.mRefID); if (!typeFilter(type, size >= 2)) continue; if (deleted) { refs.erase(ref.mRefNum); continue; } refs.insert_or_assign(ref.mRefNum, makePagedCellRef(ref)); } } catch (const std::exception& e) { Log(Debug::Warning) << "Failed to collect references from cell \"" << cell->getDescription() << "\": " << e.what(); continue; } } for (const auto& [ref, deleted] : cell->mLeasedRefs) { if (deleted) { refs.erase(ref.mRefNum); continue; } int type = store.findStatic(ref.mRefID); if (!typeFilter(type, size >= 2)) continue; refs.insert_or_assign(ref.mRefNum, makePagedCellRef(ref)); } } } return refs; } } osg::ref_ptr<osg::Node> ObjectPaging::createChunk(float size, const osg::Vec2f& center, bool activeGrid, const osg::Vec3f& viewPoint, bool compile, unsigned char lod) { const osg::Vec2i startCell(std::floor(center.x() - size / 2.f), std::floor(center.y() - size / 2.f)); const MWBase::World& world = *MWBase::Environment::get().getWorld(); const MWWorld::ESMStore& store = world.getStore(); std::map<ESM::RefNum, PagedCellRef> refs; if (mWorldspace == ESM::Cell::sDefaultWorldspaceId) { refs = collectESM3References(size, startCell, store); } else { // TODO } if (activeGrid && !refs.empty()) { std::lock_guard<std::mutex> lock(mRefTrackerMutex); const std::set<ESM::RefNum>& blacklist = getRefTracker().mBlacklist; if (blacklist.size() < refs.size()) { for (ESM::RefNum ref : blacklist) refs.erase(ref); } else { std::erase_if(refs, [&](const auto& ref) { return blacklist.contains(ref.first); }); } } const osg::Vec2f minBound = (center - osg::Vec2f(size / 2.f, size / 2.f)); const osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f)); const osg::Vec2i floorMinBound(std::floor(minBound.x()), std::floor(minBound.y())); const osg::Vec2i ceilMaxBound(std::ceil(maxBound.x()), std::ceil(maxBound.y())); struct InstanceList { std::vector<const PagedCellRef*> mInstances; AnalyzeVisitor::Result mAnalyzeResult; bool mNeedCompile = false; }; typedef std::map<osg::ref_ptr<const osg::Node>, InstanceList> NodeMap; NodeMap nodes; const osg::ref_ptr<RefnumSet> refnumSet = activeGrid ? new RefnumSet : nullptr; // Mask_UpdateVisitor is used in such cases in NIF loader: // 1. For collision nodes, which is not supposed to be rendered. // 2. For nodes masked via Flag_Hidden (VisController can change this flag value at runtime). // Since ObjectPaging does not handle VisController, we can just ignore both types of nodes. constexpr auto copyMask = ~Mask_UpdateVisitor; const int cellSize = getCellSize(mWorldspace); const float smallestDistanceToChunk = (size > 1 / 8.f) ? (size * cellSize) : 0.f; const float higherDistanceToChunk = activeGrid ? ((size < 1) ? 5 : 3) * cellSize * size + 1 : smallestDistanceToChunk + 1; AnalyzeVisitor analyzeVisitor(copyMask); const float minSize = mMinSizeMergeFactor ? mMinSize * mMinSizeMergeFactor : mMinSize; for (const auto& [refNum, ref] : refs) { if (size < 1.f) { const osg::Vec3f cellPos = ref.mPosition / cellSize; if ((minBound.x() > floorMinBound.x() && cellPos.x() < minBound.x()) || (minBound.y() > floorMinBound.y() && cellPos.y() < minBound.y()) || (maxBound.x() < ceilMaxBound.x() && cellPos.x() >= maxBound.x()) || (maxBound.y() < ceilMaxBound.y() && cellPos.y() >= maxBound.y())) continue; } const float dSqr = (viewPoint - ref.mPosition).length2(); if (!activeGrid) { std::lock_guard<std::mutex> lock(mSizeCacheMutex); SizeCache::iterator found = mSizeCache.find(refNum); if (found != mSizeCache.end() && found->second < dSqr * minSize * minSize) continue; } if (Misc::ResourceHelpers::isHiddenMarker(ref.mRefId)) continue; const int type = store.findStatic(ref.mRefId); VFS::Path::Normalized model = getModel(type, ref.mRefId, store); if (model.empty()) continue; model = Misc::ResourceHelpers::correctMeshPath(model); if (activeGrid && type != ESM::REC_STAT) { model = Misc::ResourceHelpers::correctActorModelPath(model, mSceneManager->getVFS()); if (Misc::getFileExtension(model) == "nif") { VFS::Path::Normalized kfname = model; kfname.changeExtension("kf"); if (mSceneManager->getVFS()->exists(kfname)) continue; } } if (!activeGrid) { std::lock_guard<std::mutex> lock(mLODNameCacheMutex); LODNameCacheKey key{ model, lod }; LODNameCache::const_iterator found = mLODNameCache.lower_bound(key); if (found != mLODNameCache.end() && found->first == key) model = found->second; else model = mLODNameCache .emplace_hint(found, std::move(key), Misc::ResourceHelpers::getLODMeshName(world.getESMVersions()[refNum.mContentFile], model, mSceneManager->getVFS(), lod)) ->second; } osg::ref_ptr<const osg::Node> cnode = mSceneManager->getTemplate(model, false); if (activeGrid) { if (cnode->getNumChildrenRequiringUpdateTraversal() > 0 || SceneUtil::hasUserDescription(cnode, Constants::NightDayLabel) || SceneUtil::hasUserDescription(cnode, Constants::HerbalismLabel) || (cnode->getName() == "Collada visual scene group" && dynamic_cast<const osgAnimation::BasicAnimationManager*>(cnode->getUpdateCallback()))) continue; else refnumSet->mRefnums.push_back(refNum); } { std::lock_guard<std::mutex> lock(mRefTrackerMutex); if (getRefTracker().mDisabled.count(refNum)) continue; } const float radius2 = cnode->getBound().radius2() * ref.mScale * ref.mScale; if (radius2 < dSqr * minSize * minSize && !activeGrid) { std::lock_guard<std::mutex> lock(mSizeCacheMutex); mSizeCache[refNum] = radius2; continue; } const auto emplaced = nodes.emplace(std::move(cnode), InstanceList()); if (emplaced.second) { analyzeVisitor.mDistances = LODRange{ smallestDistanceToChunk, higherDistanceToChunk } / ref.mScale; const osg::Node* const nodePtr = emplaced.first->first.get(); // const-trickery required because there is no const version of NodeVisitor const_cast<osg::Node*>(nodePtr)->accept(analyzeVisitor); emplaced.first->second.mAnalyzeResult = analyzeVisitor.retrieveResult(); emplaced.first->second.mNeedCompile = compile && nodePtr->referenceCount() <= 2; } else analyzeVisitor.addInstance(emplaced.first->second.mAnalyzeResult); emplaced.first->second.mInstances.push_back(&ref); } const osg::Vec3f worldCenter = osg::Vec3f(center.x(), center.y(), 0) * getCellSize(mWorldspace); osg::ref_ptr<osg::Group> group = new osg::Group; osg::ref_ptr<osg::Group> mergeGroup = new osg::Group; osg::ref_ptr<Resource::TemplateMultiRef> templateRefs = new Resource::TemplateMultiRef; osgUtil::StateToCompile stateToCompile(0, nullptr); CopyOp copyop; copyop.mCopyMask = copyMask; for (const auto& pair : nodes) { const osg::Node* cnode = pair.first; const AnalyzeVisitor::Result& analyzeResult = pair.second.mAnalyzeResult; const float mergeCost = analyzeResult.mNumVerts * size; const float mergeBenefit = analyzeVisitor.getMergeBenefit(analyzeResult) * mMergeFactor; const bool merge = mergeBenefit > mergeCost; const float factor2 = mergeBenefit > 0 ? std::min(1.f, mergeCost * mMinSizeCostMultiplier / mergeBenefit) : 1; const float minSizeMergeFactor2 = (1 - factor2) * mMinSizeMergeFactor + factor2; const float minSizeMerged = minSizeMergeFactor2 > 0 ? mMinSize * minSizeMergeFactor2 : mMinSize; unsigned int numinstances = 0; for (const PagedCellRef* refPtr : pair.second.mInstances) { const PagedCellRef& ref = *refPtr; if (!activeGrid && minSizeMerged != minSize && cnode->getBound().radius2() * ref.mScale * ref.mScale < (viewPoint - ref.mPosition).length2() * minSizeMerged * minSizeMerged) continue; const osg::Vec3f nodePos = ref.mPosition - worldCenter; const osg::Quat nodeAttitude = osg::Quat(ref.mRotation.z(), osg::Vec3f(0, 0, -1)) * osg::Quat(ref.mRotation.y(), osg::Vec3f(0, -1, 0)) * osg::Quat(ref.mRotation.x(), osg::Vec3f(-1, 0, 0)); const osg::Vec3f nodeScale(ref.mScale, ref.mScale, ref.mScale); osg::ref_ptr<osg::Group> trans; if (merge) { // Optimizer currently supports only MatrixTransforms. osg::Matrixf matrix; matrix.preMultTranslate(nodePos); matrix.preMultRotate(nodeAttitude); matrix.preMultScale(nodeScale); trans = new osg::MatrixTransform(matrix); trans->setDataVariance(osg::Object::STATIC); } else { trans = new SceneUtil::PositionAttitudeTransform; SceneUtil::PositionAttitudeTransform* pat = static_cast<SceneUtil::PositionAttitudeTransform*>(trans.get()); pat->setPosition(nodePos); pat->setScale(nodeScale); pat->setAttitude(nodeAttitude); } // DO NOT COPY AND PASTE THIS CODE. Cloning osg::Geometry without also cloning its contained Arrays is // generally unsafe. In this specific case the operation is safe under the following two assumptions: // - When Arrays are removed or replaced in the cloned geometry, the original Arrays in their place must // outlive the cloned geometry regardless. (ensured by TemplateMultiRef) // - Arrays that we add or replace in the cloned geometry must be explicitely forbidden from reusing // BufferObjects of the original geometry. (ensured by needvbo() in optimizer.cpp) copyop.setCopyFlags(merge ? osg::CopyOp::DEEP_COPY_NODES | osg::CopyOp::DEEP_COPY_DRAWABLES : osg::CopyOp::DEEP_COPY_NODES); copyop.mOptimizeBillboards = (size > 1 / 4.f); copyop.mNodePath.push_back(trans); copyop.mDistances = LODRange{ smallestDistanceToChunk, higherDistanceToChunk } / ref.mScale; copyop.mViewVector = (viewPoint - worldCenter); copyop.copy(cnode, trans); copyop.mNodePath.pop_back(); if (activeGrid) { if (merge) { AddRefnumMarkerVisitor visitor(ref.mRefNum); trans->accept(visitor); } else { osg::ref_ptr<RefnumMarker> marker = new RefnumMarker; marker->mRefnum = ref.mRefNum; trans->getOrCreateUserDataContainer()->addUserObject(marker); } } osg::Group* const attachTo = merge ? mergeGroup : group; attachTo->addChild(trans); ++numinstances; } if (numinstances > 0) { // add a ref to the original template to help verify the safety of shallow cloning operations // in addition, we hint to the cache that it's still being used and should be kept in cache templateRefs->addRef(cnode); if (pair.second.mNeedCompile) { int mode = osgUtil::GLObjectsVisitor::COMPILE_STATE_ATTRIBUTES; if (!merge) mode |= osgUtil::GLObjectsVisitor::COMPILE_DISPLAY_LISTS; stateToCompile._mode = mode; const_cast<osg::Node*>(cnode)->accept(stateToCompile); } } } const osg::Vec3f relativeViewPoint = viewPoint - worldCenter; if (mergeGroup->getNumChildren()) { SceneUtil::Optimizer optimizer; if (size > 1 / 8.f) { optimizer.setViewPoint(relativeViewPoint); optimizer.setMergeAlphaBlending(true); } optimizer.setIsOperationPermissibleForObjectCallback(new CanOptimizeCallback); const unsigned int options = SceneUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS | SceneUtil::Optimizer::REMOVE_REDUNDANT_NODES | SceneUtil::Optimizer::MERGE_GEOMETRY; optimizer.optimize(mergeGroup, options); group->addChild(mergeGroup); if (mDebugBatches) { DebugVisitor dv; mergeGroup->accept(dv); } if (compile) { stateToCompile._mode = osgUtil::GLObjectsVisitor::COMPILE_DISPLAY_LISTS; mergeGroup->accept(stateToCompile); } } osgUtil::IncrementalCompileOperation* const ico = mSceneManager->getIncrementalCompileOperation(); if (!stateToCompile.empty() && ico) { auto compileSet = new osgUtil::IncrementalCompileOperation::CompileSet(group); compileSet->buildCompileMap(ico->getContextSet(), stateToCompile); ico->add(compileSet, false); } group->getBound(); group->setNodeMask(Mask_Static); osg::UserDataContainer* udc = group->getOrCreateUserDataContainer(); if (activeGrid) { std::sort(refnumSet->mRefnums.begin(), refnumSet->mRefnums.end()); refnumSet->mRefnums.erase( std::unique(refnumSet->mRefnums.begin(), refnumSet->mRefnums.end()), refnumSet->mRefnums.end()); udc->addUserObject(refnumSet); group->addCullCallback(new SceneUtil::LightListCallback); } udc->addUserObject(templateRefs); return group; } unsigned int ObjectPaging::getNodeMask() { return Mask_Static; } namespace { osg::Vec2f clampToCell(const osg::Vec3f& cellPos, const osg::Vec2i& cell) { return osg::Vec2f(std::clamp<float>(cellPos.x(), cell.x(), cell.x() + 1), std::clamp<float>(cellPos.y(), cell.y(), cell.y() + 1)); } class CollectIntersecting { public: explicit CollectIntersecting( bool activeGridOnly, const osg::Vec3f& position, const osg::Vec2i& cell, ESM::RefId worldspace) : mActiveGridOnly(activeGridOnly) , mPosition(clampToCell(position / getCellSize(worldspace), cell)) { } void operator()(const ChunkId& id, osg::Object* /*obj*/) { if (mActiveGridOnly && !std::get<2>(id)) return; if (intersects(id)) mCollected.push_back(id); } const std::vector<ChunkId>& getCollected() const { return mCollected; } private: bool intersects(ChunkId id) const { const osg::Vec2f center = std::get<0>(id); const float halfSize = std::get<1>(id) / 2; return mPosition.x() >= center.x() - halfSize && mPosition.y() >= center.y() - halfSize && mPosition.x() <= center.x() + halfSize && mPosition.y() <= center.y() + halfSize; } bool mActiveGridOnly; osg::Vec2f mPosition; std::vector<ChunkId> mCollected; }; } bool ObjectPaging::enableObject( int type, ESM::RefNum refnum, const osg::Vec3f& pos, const osg::Vec2i& cell, bool enabled) { if (!typeFilter(type, false)) return false; { std::lock_guard<std::mutex> lock(mRefTrackerMutex); if (enabled && !getWritableRefTracker().mDisabled.erase(refnum)) return false; if (!enabled && !getWritableRefTracker().mDisabled.insert(refnum).second) return false; if (mRefTrackerLocked) return false; } CollectIntersecting ccf(false, pos, cell, mWorldspace); mCache->call(ccf); if (ccf.getCollected().empty()) return false; for (const ChunkId& chunk : ccf.getCollected()) mCache->removeFromObjectCache(chunk); return true; } bool ObjectPaging::blacklistObject(int type, ESM::RefNum refnum, const osg::Vec3f& pos, const osg::Vec2i& cell) { if (!typeFilter(type, false)) return false; { std::lock_guard<std::mutex> lock(mRefTrackerMutex); if (!getWritableRefTracker().mBlacklist.insert(refnum).second) return false; if (mRefTrackerLocked) return false; } CollectIntersecting ccf(true, pos, cell, mWorldspace); mCache->call(ccf); if (ccf.getCollected().empty()) return false; for (const ChunkId& chunk : ccf.getCollected()) mCache->removeFromObjectCache(chunk); return true; } void ObjectPaging::clear() { std::lock_guard<std::mutex> lock(mRefTrackerMutex); mRefTrackerNew.mDisabled.clear(); mRefTrackerNew.mBlacklist.clear(); mRefTrackerLocked = true; } bool ObjectPaging::unlockCache() { if (!mRefTrackerLocked) return false; { std::lock_guard<std::mutex> lock(mRefTrackerMutex); mRefTrackerLocked = false; if (mRefTracker == mRefTrackerNew) return false; else mRefTracker = mRefTrackerNew; } mCache->clear(); return true; } namespace { struct GetRefnumsFunctor { GetRefnumsFunctor(std::vector<ESM::RefNum>& output) : mOutput(output) { } void operator()(MWRender::ChunkId chunkId, osg::Object* obj) { if (!std::get<2>(chunkId)) return; const osg::Vec2f& center = std::get<0>(chunkId); const bool activeGrid = (center.x() > mActiveGrid.x() || center.y() > mActiveGrid.y() || center.x() < mActiveGrid.z() || center.y() < mActiveGrid.w()); if (!activeGrid) return; osg::UserDataContainer* udc = obj->getUserDataContainer(); if (udc && udc->getNumUserObjects()) { RefnumSet* refnums = dynamic_cast<RefnumSet*>(udc->getUserObject(0)); if (!refnums) return; mOutput.insert(mOutput.end(), refnums->mRefnums.begin(), refnums->mRefnums.end()); } } osg::Vec4i mActiveGrid; std::vector<ESM::RefNum>& mOutput; }; } void ObjectPaging::getPagedRefnums(const osg::Vec4i& activeGrid, std::vector<ESM::RefNum>& out) { GetRefnumsFunctor grf(out); grf.mActiveGrid = activeGrid; mCache->call(grf); std::sort(out.begin(), out.end()); out.erase(std::unique(out.begin(), out.end()), out.end()); } void ObjectPaging::reportStats(unsigned int frameNumber, osg::Stats* stats) const { Resource::reportStats("Object Chunk", frameNumber, mCache->getStats(), *stats); } }
43,337
C++
.cpp
936
31.208333
120
0.529652
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,403
luminancecalculator.cpp
OpenMW_openmw/apps/openmw/mwrender/luminancecalculator.cpp
#include "luminancecalculator.hpp" #include <components/misc/mathutil.hpp> #include <components/settings/values.hpp> #include <components/shader/shadermanager.hpp> #include "pingpongcanvas.hpp" namespace MWRender { LuminanceCalculator::LuminanceCalculator(Shader::ShaderManager& shaderManager) { Shader::ShaderManager::DefineMap defines = { { "hdrExposureTime", std::to_string(Settings::postProcessing().mAutoExposureSpeed) }, }; auto vertex = shaderManager.getShader("fullscreen_tri.vert", {}); auto luminanceFragment = shaderManager.getShader("luminance/luminance.frag", defines); auto resolveFragment = shaderManager.getShader("luminance/resolve.frag", defines); mResolveProgram = shaderManager.getProgram(vertex, std::move(resolveFragment)); mLuminanceProgram = shaderManager.getProgram(std::move(vertex), std::move(luminanceFragment)); for (auto& buffer : mBuffers) { buffer.mipmappedSceneLuminanceTex = new osg::Texture2D; buffer.mipmappedSceneLuminanceTex->setInternalFormat(GL_R16F); buffer.mipmappedSceneLuminanceTex->setSourceFormat(GL_RED); buffer.mipmappedSceneLuminanceTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); buffer.mipmappedSceneLuminanceTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); buffer.mipmappedSceneLuminanceTex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR_MIPMAP_NEAREST); buffer.mipmappedSceneLuminanceTex->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR); buffer.mipmappedSceneLuminanceTex->setTextureSize(mWidth, mHeight); buffer.luminanceTex = new osg::Texture2D; buffer.luminanceTex->setInternalFormat(GL_R16F); buffer.luminanceTex->setSourceFormat(GL_RED); buffer.luminanceTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); buffer.luminanceTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); buffer.luminanceTex->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST); buffer.luminanceTex->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST); buffer.luminanceTex->setTextureSize(1, 1); buffer.luminanceProxyTex = new osg::Texture2D(*buffer.luminanceTex); buffer.luminanceProxyTex->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); buffer.luminanceProxyTex->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); buffer.resolveFbo = new osg::FrameBufferObject; buffer.resolveFbo->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(buffer.luminanceTex)); buffer.luminanceProxyFbo = new osg::FrameBufferObject; buffer.luminanceProxyFbo->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(buffer.luminanceProxyTex)); buffer.sceneLumSS = new osg::StateSet; buffer.sceneLumSS->setAttributeAndModes(mLuminanceProgram); buffer.sceneLumSS->addUniform(new osg::Uniform("sceneTex", 0)); buffer.sceneLumSS->addUniform(new osg::Uniform("scaling", mScale)); buffer.resolveSS = new osg::StateSet; buffer.resolveSS->setAttributeAndModes(mResolveProgram); buffer.resolveSS->setTextureAttributeAndModes(0, buffer.luminanceProxyTex); buffer.resolveSS->addUniform(new osg::Uniform("luminanceSceneTex", 0)); buffer.resolveSS->addUniform(new osg::Uniform("prevLuminanceSceneTex", 1)); } mBuffers[0].resolveSS->setTextureAttributeAndModes(1, mBuffers[1].luminanceTex); mBuffers[1].resolveSS->setTextureAttributeAndModes(1, mBuffers[0].luminanceTex); } void LuminanceCalculator::compile() { int mipmapLevels = osg::Image::computeNumberOfMipmapLevels(mWidth, mHeight); for (auto& buffer : mBuffers) { buffer.mipmappedSceneLuminanceTex->setTextureSize(mWidth, mHeight); buffer.mipmappedSceneLuminanceTex->setNumMipmapLevels(mipmapLevels); buffer.mipmappedSceneLuminanceTex->dirtyTextureObject(); buffer.resolveSceneLumFbo = new osg::FrameBufferObject; buffer.resolveSceneLumFbo->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(buffer.mipmappedSceneLuminanceTex, mipmapLevels - 1)); buffer.sceneLumFbo = new osg::FrameBufferObject; buffer.sceneLumFbo->setAttachment(osg::FrameBufferObject::BufferComponent::COLOR_BUFFER0, osg::FrameBufferAttachment(buffer.mipmappedSceneLuminanceTex)); } mCompiled = true; } void LuminanceCalculator::draw(const PingPongCanvas& canvas, osg::RenderInfo& renderInfo, osg::State& state, osg::GLExtensions* ext, size_t frameId) { if (!mEnabled) return; bool dirty = !mCompiled; if (dirty) compile(); auto& buffer = mBuffers[frameId]; buffer.sceneLumFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); buffer.sceneLumSS->setTextureAttributeAndModes(0, canvas.getSceneTexture(frameId)); buffer.sceneLumSS->getUniform("scaling")->set(mScale); state.apply(buffer.sceneLumSS); canvas.drawGeometry(renderInfo); state.applyTextureAttribute(0, buffer.mipmappedSceneLuminanceTex); ext->glGenerateMipmap(GL_TEXTURE_2D); buffer.resolveSceneLumFbo->apply(state, osg::FrameBufferObject::READ_FRAMEBUFFER); buffer.luminanceProxyFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); ext->glBlitFramebuffer(0, 0, 1, 1, 0, 0, 1, 1, GL_COLOR_BUFFER_BIT, GL_NEAREST); if (mIsBlank) { // Use current frame data for previous frame to warm up calculations and prevent popin mBuffers[(frameId + 1) % 2].resolveFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); ext->glBlitFramebuffer(0, 0, 1, 1, 0, 0, 1, 1, GL_COLOR_BUFFER_BIT, GL_NEAREST); buffer.luminanceProxyFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); mIsBlank = false; } buffer.resolveFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); state.apply(buffer.resolveSS); canvas.drawGeometry(renderInfo); ext->glBindFramebuffer( GL_FRAMEBUFFER_EXT, state.getGraphicsContext() ? state.getGraphicsContext()->getDefaultFboId() : 0); } osg::ref_ptr<osg::Texture2D> LuminanceCalculator::getLuminanceTexture(size_t frameId) const { return mBuffers[frameId].luminanceTex; } void LuminanceCalculator::dirty(int w, int h) { constexpr int minSize = 64; mWidth = std::max(minSize, Misc::nextPowerOfTwo(w) / 2); mHeight = std::max(minSize, Misc::nextPowerOfTwo(h) / 2); mScale = osg::Vec2f(w / static_cast<float>(mWidth), h / static_cast<float>(mHeight)); mCompiled = false; } }
7,264
C++
.cpp
121
49.859504
112
0.692502
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,404
transparentpass.cpp
OpenMW_openmw/apps/openmw/mwrender/transparentpass.cpp
#include "transparentpass.hpp" #include <osg/AlphaFunc> #include <osg/BlendFunc> #include <osg/Material> #include <osg/Texture2D> #include <osg/Texture2DArray> #include <osgUtil/RenderStage> #include <components/sceneutil/depth.hpp> #include <components/shader/shadermanager.hpp> #include <components/stereo/multiview.hpp> #include <components/stereo/stereomanager.hpp> #include "vismask.hpp" namespace MWRender { TransparentDepthBinCallback::TransparentDepthBinCallback(Shader::ShaderManager& shaderManager, bool postPass) : mStateSet(new osg::StateSet) , mPostPass(postPass) { osg::ref_ptr<osg::Image> image = new osg::Image; image->allocateImage(1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE); image->setColor(osg::Vec4(1, 1, 1, 1), 0, 0); osg::ref_ptr<osg::Texture2D> dummyTexture = new osg::Texture2D(image); dummyTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); dummyTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); constexpr osg::StateAttribute::OverrideValue modeOff = osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE; constexpr osg::StateAttribute::OverrideValue modeOn = osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE; mStateSet->setTextureAttributeAndModes(0, dummyTexture); Shader::ShaderManager::DefineMap defines; Stereo::shaderStereoDefines(defines); mStateSet->setAttributeAndModes(new osg::BlendFunc, modeOff); mStateSet->setAttributeAndModes(shaderManager.getProgram("depthclipped", defines), modeOn); mStateSet->setAttributeAndModes(new SceneUtil::AutoDepth, modeOn); for (unsigned int unit = 1; unit < 8; ++unit) mStateSet->setTextureMode(unit, GL_TEXTURE_2D, modeOff); } void TransparentDepthBinCallback::drawImplementation( osgUtil::RenderBin* bin, osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous) { osg::State& state = *renderInfo.getState(); osg::GLExtensions* ext = state.get<osg::GLExtensions>(); bool validFbo = false; unsigned int frameId = state.getFrameStamp()->getFrameNumber() % 2; const auto& fbo = mFbo[frameId]; const auto& msaaFbo = mMsaaFbo[frameId]; const auto& opaqueFbo = mOpaqueFbo[frameId]; if (bin->getStage()->getMultisampleResolveFramebufferObject() && bin->getStage()->getMultisampleResolveFramebufferObject() == fbo) validFbo = true; else if (bin->getStage()->getFrameBufferObject() && (bin->getStage()->getFrameBufferObject() == fbo || bin->getStage()->getFrameBufferObject() == msaaFbo)) validFbo = true; if (!validFbo) { bin->drawImplementation(renderInfo, previous); return; } const osg::Texture* tex = opaqueFbo->getAttachment(osg::FrameBufferObject::BufferComponent::PACKED_DEPTH_STENCIL_BUFFER) .getTexture(); if (Stereo::getMultiview()) { if (!mMultiviewResolve[frameId]) { mMultiviewResolve[frameId] = std::make_unique<Stereo::MultiviewFramebufferResolve>( msaaFbo ? msaaFbo : fbo, opaqueFbo, GL_DEPTH_BUFFER_BIT); } else { mMultiviewResolve[frameId]->setResolveFbo(opaqueFbo); mMultiviewResolve[frameId]->setMsaaFbo(msaaFbo ? msaaFbo : fbo); } mMultiviewResolve[frameId]->resolveImplementation(state); } else { opaqueFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); ext->glBlitFramebuffer(0, 0, tex->getTextureWidth(), tex->getTextureHeight(), 0, 0, tex->getTextureWidth(), tex->getTextureHeight(), GL_DEPTH_BUFFER_BIT, GL_NEAREST); } msaaFbo ? msaaFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER) : fbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); // draws scene into primary attachments bin->drawImplementation(renderInfo, previous); if (!mPostPass) return; opaqueFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); // draw transparent post-pass to populate a postprocess friendly depth texture with alpha-clipped geometry unsigned int numToPop = previous ? osgUtil::StateGraph::numToPop(previous->_parent) : 0; if (numToPop > 1) numToPop--; unsigned int insertStateSetPosition = state.getStateSetStackSize() - numToPop; state.insertStateSet(insertStateSetPosition, mStateSet); for (auto rit = bin->getRenderLeafList().begin(); rit != bin->getRenderLeafList().end(); rit++) { osgUtil::RenderLeaf* rl = *rit; const osg::StateSet* ss = rl->_parent->getStateSet(); if (rl->_drawable->getNodeMask() == Mask_ParticleSystem || rl->_drawable->getNodeMask() == Mask_Effect) continue; if (ss->getAttribute(osg::StateAttribute::MATERIAL)) { const osg::Material* mat = static_cast<const osg::Material*>(ss->getAttribute(osg::StateAttribute::MATERIAL)); if (mat->getDiffuse(osg::Material::FRONT).a() < 0.5) continue; } rl->render(renderInfo, previous); previous = rl; } state.removeStateSet(insertStateSetPosition); msaaFbo ? msaaFbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER) : fbo->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); state.checkGLErrors("after TransparentDepthBinCallback::drawImplementation"); } }
5,807
C++
.cpp
114
40.964912
120
0.649894
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,405
ripples.cpp
OpenMW_openmw/apps/openmw/mwrender/ripples.cpp
#include "ripples.hpp" #include <osg/Geometry> #include <osg/Texture2D> #include <osgUtil/CullVisitor> #include <components/debug/debuglog.hpp> #include <components/resource/imagemanager.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/color.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/glextensions.hpp> #include <components/shader/shadermanager.hpp> #include "../mwworld/ptr.hpp" #include "../mwmechanics/actorutil.hpp" #include "vismask.hpp" namespace MWRender { RipplesSurface::RipplesSurface(Resource::ResourceSystem* resourceSystem) : osg::Geometry() , mResourceSystem(resourceSystem) { setUseDisplayList(false); setUseVertexBufferObjects(true); osg::ref_ptr<osg::Vec3Array> verts = new osg::Vec3Array; verts->push_back(osg::Vec3f(-1, -1, 0)); verts->push_back(osg::Vec3f(-1, 3, 0)); verts->push_back(osg::Vec3f(3, -1, 0)); setVertexArray(verts); setCullingActive(false); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES, 0, 3)); #ifdef __APPLE__ // we can not trust Apple :) mUseCompute = false; #else constexpr float minimumGLVersionRequiredForCompute = 4.4; osg::GLExtensions& exts = SceneUtil::getGLExtensions(); mUseCompute = exts.glVersion >= minimumGLVersionRequiredForCompute && exts.glslLanguageVersion >= minimumGLVersionRequiredForCompute; #endif if (mUseCompute) Log(Debug::Info) << "Initialized compute shader pipeline for water ripples"; else Log(Debug::Info) << "Initialized fallback fragment shader pipeline for water ripples"; for (size_t i = 0; i < mState.size(); ++i) { osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet; // bindings are set in the compute shader if (!mUseCompute) stateset->addUniform(new osg::Uniform("imageIn", 0)); stateset->addUniform(new osg::Uniform("offset", osg::Vec2f())); stateset->addUniform(new osg::Uniform("positionCount", 0)); stateset->addUniform(new osg::Uniform(osg::Uniform::Type::FLOAT_VEC3, "positions", 100)); stateset->setAttributeAndModes(new osg::Viewport(0, 0, RipplesSurface::sRTTSize, RipplesSurface::sRTTSize)); mState[i].mStateset = stateset; } for (size_t i = 0; i < mTextures.size(); ++i) { osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setSourceFormat(GL_RGBA); texture->setInternalFormat(GL_RGBA16F); texture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture::LINEAR); texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_BORDER); texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_BORDER); texture->setBorderColor(osg::Vec4(0, 0, 0, 0)); texture->setTextureSize(sRTTSize, sRTTSize); mTextures[i] = texture; mFBOs[i] = new osg::FrameBufferObject; mFBOs[i]->setAttachment(osg::Camera::COLOR_BUFFER0, osg::FrameBufferAttachment(mTextures[i])); } if (mUseCompute) setupComputePipeline(); else setupFragmentPipeline(); setCullCallback(new osg::NodeCallback); setUpdateCallback(new osg::NodeCallback); } void RipplesSurface::setupFragmentPipeline() { auto& shaderManager = mResourceSystem->getSceneManager()->getShaderManager(); Shader::ShaderManager::DefineMap defineMap = { { "rippleMapSize", std::to_string(sRTTSize) + ".0" } }; osg::ref_ptr<osg::Shader> vertex = shaderManager.getShader("fullscreen_tri.vert", {}, osg::Shader::VERTEX); mProgramBlobber = shaderManager.getProgram( vertex, shaderManager.getShader("ripples_blobber.frag", defineMap, osg::Shader::FRAGMENT)); mProgramSimulation = shaderManager.getProgram( std::move(vertex), shaderManager.getShader("ripples_simulate.frag", defineMap, osg::Shader::FRAGMENT)); } void RipplesSurface::setupComputePipeline() { auto& shaderManager = mResourceSystem->getSceneManager()->getShaderManager(); mProgramBlobber = shaderManager.getProgram( nullptr, shaderManager.getShader("core/ripples_blobber.comp", {}, osg::Shader::COMPUTE)); mProgramSimulation = shaderManager.getProgram( nullptr, shaderManager.getShader("core/ripples_simulate.comp", {}, osg::Shader::COMPUTE)); } void RipplesSurface::updateState(const osg::FrameStamp& frameStamp, State& state) { state.mPaused = mPaused; if (mPaused) return; constexpr double updateFrequency = 60.0; constexpr double updatePeriod = 1.0 / updateFrequency; const double simulationTime = frameStamp.getSimulationTime(); const double frameDuration = simulationTime - mLastSimulationTime; mLastSimulationTime = simulationTime; mRemainingWaveTime += frameDuration; const double ticks = std::floor(mRemainingWaveTime * updateFrequency); mRemainingWaveTime -= ticks * updatePeriod; if (ticks == 0) { state.mPaused = true; return; } const MWWorld::Ptr player = MWMechanics::getPlayer(); const ESM::Position& playerPos = player.getRefData().getPosition(); mCurrentPlayerPos = osg::Vec2f( std::floor(playerPos.pos[0] / sWorldScaleFactor), std::floor(playerPos.pos[1] / sWorldScaleFactor)); const osg::Vec2f offset = mCurrentPlayerPos - mLastPlayerPos; mLastPlayerPos = mCurrentPlayerPos; state.mStateset->getUniform("positionCount")->set(static_cast<int>(mPositionCount)); state.mStateset->getUniform("offset")->set(offset); osg::Uniform* const positions = state.mStateset->getUniform("positions"); for (std::size_t i = 0; i < mPositionCount; ++i) { osg::Vec3f pos = mPositions[i] - osg::Vec3f(mCurrentPlayerPos.x() * sWorldScaleFactor, mCurrentPlayerPos.y() * sWorldScaleFactor, 0.0) + osg::Vec3f(sRTTSize * sWorldScaleFactor / 2, sRTTSize * sWorldScaleFactor / 2, 0.0); pos /= sWorldScaleFactor; positions->setElement(i, pos); } positions->dirty(); mPositionCount = 0; } void RipplesSurface::traverse(osg::NodeVisitor& nv) { const osg::FrameStamp* const frameStamp = nv.getFrameStamp(); if (frameStamp == nullptr) return; if (nv.getVisitorType() == osg::NodeVisitor::CULL_VISITOR) updateState(*frameStamp, mState[frameStamp->getFrameNumber() % 2]); osg::Geometry::traverse(nv); } void RipplesSurface::drawImplementation(osg::RenderInfo& renderInfo) const { osg::State& state = *renderInfo.getState(); const std::size_t currentFrame = state.getFrameStamp()->getFrameNumber() % 2; const State& frameState = mState[currentFrame]; if (frameState.mPaused) { return; } osg::GLExtensions& ext = *state.get<osg::GLExtensions>(); const std::size_t contextID = state.getContextID(); const auto bindImage = [&](osg::Texture2D* texture, GLuint index, GLenum access) { osg::Texture::TextureObject* to = texture->getTextureObject(contextID); if (!to || texture->isDirty(contextID)) { state.applyTextureAttribute(index, texture); to = texture->getTextureObject(contextID); } ext.glBindImageTexture(index, to->id(), 0, GL_FALSE, 0, access, GL_RGBA16F); }; // PASS: Blot in all ripple spawners state.pushStateSet(frameState.mStateset); state.apply(); state.applyAttribute(mProgramBlobber); for (const auto& [name, stack] : state.getUniformMap()) { if (!stack.uniformVec.empty()) state.getLastAppliedProgramObject()->apply(*(stack.uniformVec.back().first)); } if (mUseCompute) { bindImage(mTextures[1], 0, GL_WRITE_ONLY_ARB); bindImage(mTextures[0], 1, GL_READ_ONLY_ARB); ext.glDispatchCompute(sRTTSize / 16, sRTTSize / 16, 1); ext.glMemoryBarrier(GL_ALL_BARRIER_BITS); } else { mFBOs[1]->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); state.applyTextureAttribute(0, mTextures[0]); osg::Geometry::drawImplementation(renderInfo); } // PASS: Wave simulation state.applyAttribute(mProgramSimulation); for (const auto& [name, stack] : state.getUniformMap()) { if (!stack.uniformVec.empty()) state.getLastAppliedProgramObject()->apply(*(stack.uniformVec.back().first)); } if (mUseCompute) { bindImage(mTextures[0], 0, GL_WRITE_ONLY_ARB); bindImage(mTextures[1], 1, GL_READ_ONLY_ARB); ext.glDispatchCompute(sRTTSize / 16, sRTTSize / 16, 1); ext.glMemoryBarrier(GL_ALL_BARRIER_BITS); } else { mFBOs[0]->apply(state, osg::FrameBufferObject::DRAW_FRAMEBUFFER); state.applyTextureAttribute(0, mTextures[1]); osg::Geometry::drawImplementation(renderInfo); } state.popStateSet(); } osg::Texture* RipplesSurface::getColorTexture() const { return mTextures[0]; } void RipplesSurface::emit(const osg::Vec3f pos, float sizeInCellUnits) { // Emitted positions are reset every frame, don't bother wrapping around when out of buffer space if (mPositionCount >= mPositions.size()) { return; } mPositions[mPositionCount] = osg::Vec3f(pos.x(), pos.y(), sizeInCellUnits); mPositionCount++; } void RipplesSurface::releaseGLObjects(osg::State* state) const { for (const auto& tex : mTextures) tex->releaseGLObjects(state); for (const auto& fbo : mFBOs) fbo->releaseGLObjects(state); if (mProgramBlobber) mProgramBlobber->releaseGLObjects(state); if (mProgramSimulation) mProgramSimulation->releaseGLObjects(state); } Ripples::Ripples(Resource::ResourceSystem* resourceSystem) : osg::Camera() , mRipples(new RipplesSurface(resourceSystem)) { getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF); getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); setRenderOrder(osg::Camera::PRE_RENDER); setReferenceFrame(osg::Camera::ABSOLUTE_RF); setNodeMask(Mask_RenderToTexture); setClearMask(GL_NONE); setViewport(0, 0, RipplesSurface::sRTTSize, RipplesSurface::sRTTSize); addChild(mRipples); setCullingActive(false); setImplicitBufferAttachmentMask(0, 0); } osg::Texture* Ripples::getColorTexture() const { return mRipples->getColorTexture(); } void Ripples::emit(const osg::Vec3f pos, float sizeInCellUnits) { mRipples->emit(pos, sizeInCellUnits); } void Ripples::setPaused(bool paused) { mRipples->setPaused(paused); } }
11,657
C++
.cpp
259
35.803089
120
0.642145
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,406
characterpreview.cpp
OpenMW_openmw/apps/openmw/mwrender/characterpreview.cpp
#include "characterpreview.hpp" #include <cmath> #include <osg/BlendFunc> #include <osg/Camera> #include <osg/Fog> #include <osg/LightModel> #include <osg/LightSource> #include <osg/Material> #include <osg/PositionAttitudeTransform> #include <osg/TexEnvCombine> #include <osg/Texture2D> #include <osg/ValueObject> #include <osgUtil/IntersectionVisitor> #include <osgUtil/LineSegmentIntersector> #include <components/debug/debuglog.hpp> #include <components/fallback/fallback.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/sceneutil/rtt.hpp> #include <components/sceneutil/shadow.hpp> #include <components/settings/values.hpp> #include <components/stereo/multiview.hpp> #include "../mwworld/class.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/weapontype.hpp" #include "npcanimation.hpp" #include "util.hpp" #include "vismask.hpp" namespace MWRender { class DrawOnceCallback : public SceneUtil::NodeCallback<DrawOnceCallback> { public: DrawOnceCallback(osg::Node* subgraph) : mRendered(false) , mLastRenderedFrame(0) , mSubgraph(subgraph) { } void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (!mRendered) { mRendered = true; mLastRenderedFrame = nv->getTraversalNumber(); osg::ref_ptr<osg::FrameStamp> previousFramestamp = const_cast<osg::FrameStamp*>(nv->getFrameStamp()); osg::FrameStamp* fs = new osg::FrameStamp(*previousFramestamp); fs->setSimulationTime(0.0); nv->setFrameStamp(fs); // Update keyframe controllers in the scene graph first... // RTTNode does not continue update traversal, so manually continue the update traversal since we need // it. mSubgraph->accept(*nv); traverse(node, nv); nv->setFrameStamp(previousFramestamp); } else { node->setNodeMask(0); } } void redrawNextFrame() { mRendered = false; } unsigned int getLastRenderedFrame() const { return mLastRenderedFrame; } private: bool mRendered; unsigned int mLastRenderedFrame; osg::ref_ptr<osg::Node> mSubgraph; }; // Set up alpha blending mode to avoid issues caused by transparent objects writing onto the alpha value of the FBO // This makes the RTT have premultiplied alpha, though, so the source blend factor must be GL_ONE when it's applied class SetUpBlendVisitor : public osg::NodeVisitor { public: SetUpBlendVisitor() : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) { } void apply(osg::Node& node) override { if (osg::ref_ptr<osg::StateSet> stateset = node.getStateSet()) { osg::ref_ptr<osg::StateSet> newStateSet; if (stateset->getAttribute(osg::StateAttribute::BLENDFUNC) || stateset->getBinNumber() == osg::StateSet::TRANSPARENT_BIN) { osg::BlendFunc* blendFunc = static_cast<osg::BlendFunc*>(stateset->getAttribute(osg::StateAttribute::BLENDFUNC)); if (blendFunc) { newStateSet = new osg::StateSet(*stateset, osg::CopyOp::SHALLOW_COPY); node.setStateSet(newStateSet); osg::ref_ptr<osg::BlendFunc> newBlendFunc = new osg::BlendFunc(*blendFunc); newStateSet->setAttribute(newBlendFunc, osg::StateAttribute::ON); // I *think* (based on some by-hand maths) that the RGB and dest alpha factors are unchanged, // and only dest determines source alpha factor This has the benefit of being idempotent if we // assume nothing used glBlendFuncSeparate before we touched it if (blendFunc->getDestination() == osg::BlendFunc::ONE_MINUS_SRC_ALPHA) newBlendFunc->setSourceAlpha(osg::BlendFunc::ONE); else if (blendFunc->getDestination() == osg::BlendFunc::ONE) newBlendFunc->setSourceAlpha(osg::BlendFunc::ZERO); // Other setups barely exist in the wild and aren't worth supporting as they're not equippable // gear else Log(Debug::Info) << "Unable to adjust blend mode for character preview. Source factor 0x" << std::hex << blendFunc->getSource() << ", destination factor 0x" << blendFunc->getDestination() << std::dec; } } if (stateset->getMode(GL_BLEND) & osg::StateAttribute::ON) { if (!newStateSet) { newStateSet = new osg::StateSet(*stateset, osg::CopyOp::SHALLOW_COPY); node.setStateSet(newStateSet); } // Disable noBlendAlphaEnv newStateSet->setTextureMode(7, GL_TEXTURE_2D, osg::StateAttribute::OFF); newStateSet->setDefine("FORCE_OPAQUE", "0", osg::StateAttribute::ON); } } traverse(node); } }; class CharacterPreviewRTTNode : public SceneUtil::RTTNode { static constexpr float fovYDegrees = 12.3f; static constexpr float znear = 4.0f; static constexpr float zfar = 10000.f; public: CharacterPreviewRTTNode(uint32_t sizeX, uint32_t sizeY) : RTTNode(sizeX, sizeY, Settings::video().mAntialiasing, false, 0, StereoAwareness::Unaware_MultiViewShaders, shouldAddMSAAIntermediateTarget()) , mAspectRatio(static_cast<float>(sizeX) / static_cast<float>(sizeY)) { if (SceneUtil::AutoDepth::isReversed()) mPerspectiveMatrix = static_cast<osg::Matrixf>( SceneUtil::getReversedZProjectionMatrixAsPerspective(fovYDegrees, mAspectRatio, znear, zfar)); else mPerspectiveMatrix = osg::Matrixf::perspective(fovYDegrees, mAspectRatio, znear, zfar); mGroup->getOrCreateStateSet()->addUniform(new osg::Uniform("projectionMatrix", mPerspectiveMatrix)); mViewMatrix = osg::Matrixf::identity(); setColorBufferInternalFormat(GL_RGBA); setDepthBufferInternalFormat(GL_DEPTH24_STENCIL8); } void setDefaults(osg::Camera* camera) override { camera->setName("CharacterPreview"); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT, osg::Camera::PIXEL_BUFFER_RTT); camera->setClearColor(osg::Vec4(0.f, 0.f, 0.f, 0.f)); camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); camera->setProjectionMatrixAsPerspective(fovYDegrees, mAspectRatio, znear, zfar); camera->setViewport(0, 0, width(), height()); camera->setRenderOrder(osg::Camera::PRE_RENDER); camera->setCullMask(~(Mask_UpdateVisitor)); camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); SceneUtil::setCameraClearDepth(camera); camera->setNodeMask(Mask_RenderToTexture); camera->addChild(mGroup); } void apply(osg::Camera* camera) override { if (mCameraStateset) camera->setStateSet(mCameraStateset); camera->setViewMatrix(mViewMatrix); if (shouldDoTextureArray()) Stereo::setMultiviewMatrices(mGroup->getOrCreateStateSet(), { mPerspectiveMatrix, mPerspectiveMatrix }); } void addChild(osg::Node* node) { mGroup->addChild(node); } void setCameraStateset(osg::StateSet* stateset) { mCameraStateset = stateset; } void setViewMatrix(const osg::Matrixf& viewMatrix) { mViewMatrix = viewMatrix; } osg::ref_ptr<osg::Group> mGroup = new osg::Group; osg::Matrixf mPerspectiveMatrix; osg::Matrixf mViewMatrix; osg::ref_ptr<osg::StateSet> mCameraStateset; float mAspectRatio; }; CharacterPreview::CharacterPreview(osg::Group* parent, Resource::ResourceSystem* resourceSystem, const MWWorld::Ptr& character, int sizeX, int sizeY, const osg::Vec3f& position, const osg::Vec3f& lookAt) : mParent(parent) , mResourceSystem(resourceSystem) , mPosition(position) , mLookAt(lookAt) , mCharacter(character) , mAnimation(nullptr) , mSizeX(sizeX) , mSizeY(sizeY) { mTextureStateSet = new osg::StateSet; mTextureStateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::ONE, osg::BlendFunc::ONE_MINUS_SRC_ALPHA)); mRTTNode = new CharacterPreviewRTTNode(sizeX, sizeY); mRTTNode->setNodeMask(Mask_RenderToTexture); osg::ref_ptr<SceneUtil::LightManager> lightManager = new SceneUtil::LightManager(SceneUtil::LightSettings{ .mLightingMethod = mResourceSystem->getSceneManager()->getLightingMethod(), .mMaxLights = Settings::shaders().mMaxLights, .mMaximumLightDistance = Settings::shaders().mMaximumLightDistance, .mLightFadeStart = Settings::shaders().mLightFadeStart, .mLightBoundsMultiplier = Settings::shaders().mLightBoundsMultiplier, }); lightManager->setStartLight(1); osg::ref_ptr<osg::StateSet> stateset = lightManager->getOrCreateStateSet(); stateset->setDefine("FORCE_OPAQUE", "1", osg::StateAttribute::ON); stateset->setMode(GL_LIGHTING, osg::StateAttribute::ON); stateset->setMode(GL_NORMALIZE, osg::StateAttribute::ON); stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON); osg::ref_ptr<osg::Material> defaultMat(new osg::Material); defaultMat->setColorMode(osg::Material::OFF); defaultMat->setAmbient(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); defaultMat->setDiffuse(osg::Material::FRONT_AND_BACK, osg::Vec4f(1, 1, 1, 1)); defaultMat->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4f(0.f, 0.f, 0.f, 0.f)); stateset->setAttribute(defaultMat); SceneUtil::ShadowManager::instance().disableShadowsForStateSet(*stateset); // assign large value to effectively turn off fog // shaders don't respect glDisable(GL_FOG) osg::ref_ptr<osg::Fog> fog(new osg::Fog); fog->setStart(10000000); fog->setEnd(10000000); stateset->setAttributeAndModes(fog, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); // TODO: Clean up this mess of loose uniforms that shaders depend on. // turn off sky blending stateset->addUniform(new osg::Uniform("far", 10000000.0f)); stateset->addUniform(new osg::Uniform("skyBlendingStart", 8000000.0f)); stateset->addUniform(new osg::Uniform("sky", 0)); stateset->addUniform(new osg::Uniform("screenRes", osg::Vec2f{ 1, 1 })); stateset->addUniform(new osg::Uniform("emissiveMult", 1.f)); // Opaque stuff must have 1 as its fragment alpha as the FBO is translucent, so having blending off isn't enough osg::ref_ptr<osg::TexEnvCombine> noBlendAlphaEnv = new osg::TexEnvCombine(); noBlendAlphaEnv->setCombine_Alpha(osg::TexEnvCombine::REPLACE); noBlendAlphaEnv->setSource0_Alpha(osg::TexEnvCombine::CONSTANT); noBlendAlphaEnv->setConstantColor(osg::Vec4(0.0, 0.0, 0.0, 1.0)); noBlendAlphaEnv->setCombine_RGB(osg::TexEnvCombine::REPLACE); noBlendAlphaEnv->setSource0_RGB(osg::TexEnvCombine::PREVIOUS); osg::ref_ptr<osg::Texture2D> dummyTexture = new osg::Texture2D(); dummyTexture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); dummyTexture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); dummyTexture->setInternalFormat(GL_DEPTH_COMPONENT); dummyTexture->setTextureSize(1, 1); // This might clash with a shadow map, so make sure it doesn't cast shadows dummyTexture->setShadowComparison(true); dummyTexture->setShadowCompareFunc(osg::Texture::ShadowCompareFunc::ALWAYS); stateset->setTextureAttributeAndModes(7, dummyTexture, osg::StateAttribute::ON); stateset->setTextureAttribute(7, noBlendAlphaEnv, osg::StateAttribute::ON); osg::ref_ptr<osg::LightModel> lightmodel = new osg::LightModel; lightmodel->setAmbientIntensity(osg::Vec4(0.0, 0.0, 0.0, 1.0)); stateset->setAttributeAndModes(lightmodel, osg::StateAttribute::ON); osg::ref_ptr<osg::Light> light = new osg::Light; float diffuseR = Fallback::Map::getFloat("Inventory_DirectionalDiffuseR"); float diffuseG = Fallback::Map::getFloat("Inventory_DirectionalDiffuseG"); float diffuseB = Fallback::Map::getFloat("Inventory_DirectionalDiffuseB"); float ambientR = Fallback::Map::getFloat("Inventory_DirectionalAmbientR"); float ambientG = Fallback::Map::getFloat("Inventory_DirectionalAmbientG"); float ambientB = Fallback::Map::getFloat("Inventory_DirectionalAmbientB"); float azimuth = osg::DegreesToRadians(Fallback::Map::getFloat("Inventory_DirectionalRotationX")); float altitude = osg::DegreesToRadians(Fallback::Map::getFloat("Inventory_DirectionalRotationY")); float positionX = -std::cos(azimuth) * std::sin(altitude); float positionY = std::sin(azimuth) * std::sin(altitude); float positionZ = std::cos(altitude); light->setPosition(osg::Vec4(positionX, positionY, positionZ, 0.0)); light->setDiffuse(osg::Vec4(diffuseR, diffuseG, diffuseB, 1)); osg::Vec4 ambientRGBA = osg::Vec4(ambientR, ambientG, ambientB, 1); if (mResourceSystem->getSceneManager()->getForceShaders()) { // When using shaders, we now skip the ambient sun calculation as this is the only place it's used. // Using the scene ambient will give identical results. lightmodel->setAmbientIntensity(ambientRGBA); light->setAmbient(osg::Vec4(0, 0, 0, 1)); } else light->setAmbient(ambientRGBA); light->setSpecular(osg::Vec4(0, 0, 0, 0)); light->setLightNum(0); light->setConstantAttenuation(1.f); light->setLinearAttenuation(0.f); light->setQuadraticAttenuation(0.f); lightManager->setSunlight(light); osg::ref_ptr<osg::LightSource> lightSource = new osg::LightSource; lightSource->setLight(light); lightSource->setStateSetModes(*stateset, osg::StateAttribute::ON); lightManager->addChild(lightSource); mRTTNode->addChild(lightManager); mNode = new osg::PositionAttitudeTransform; lightManager->addChild(mNode); mDrawOnceCallback = new DrawOnceCallback(mRTTNode->mGroup); mRTTNode->addUpdateCallback(mDrawOnceCallback); mParent->addChild(mRTTNode); mCharacter.mCell = nullptr; } CharacterPreview::~CharacterPreview() { mParent->removeChild(mRTTNode); } int CharacterPreview::getTextureWidth() const { return mSizeX; } int CharacterPreview::getTextureHeight() const { return mSizeY; } void CharacterPreview::setBlendMode() { SetUpBlendVisitor visitor; mNode->accept(visitor); } void CharacterPreview::onSetup() { setBlendMode(); } osg::ref_ptr<osg::Texture2D> CharacterPreview::getTexture() { return static_cast<osg::Texture2D*>(mRTTNode->getColorTexture(nullptr)); } void CharacterPreview::rebuild() { mAnimation = nullptr; mAnimation = new NpcAnimation(mCharacter, mNode, mResourceSystem, true, (renderHeadOnly() ? NpcAnimation::VM_HeadOnly : NpcAnimation::VM_Normal)); onSetup(); redraw(); } void CharacterPreview::redraw() { mRTTNode->setNodeMask(Mask_RenderToTexture); mDrawOnceCallback->redrawNextFrame(); } // -------------------------------------------------------------------------------------------------- InventoryPreview::InventoryPreview( osg::Group* parent, Resource::ResourceSystem* resourceSystem, const MWWorld::Ptr& character) : CharacterPreview(parent, resourceSystem, character, 512, 1024, osg::Vec3f(0, 700, 71), osg::Vec3f(0, 0, 71)) { } void InventoryPreview::setViewport(int sizeX, int sizeY) { sizeX = std::max(sizeX, 0); sizeY = std::max(sizeY, 0); // NB Camera::setViewport has threading issues osg::ref_ptr<osg::StateSet> stateset = new osg::StateSet; mViewport = new osg::Viewport(0, mSizeY - sizeY, std::min(mSizeX, sizeX), std::min(mSizeY, sizeY)); stateset->setAttributeAndModes(mViewport); mRTTNode->setCameraStateset(stateset); redraw(); } void InventoryPreview::update() { if (!mAnimation.get()) return; mAnimation->showWeapons(true); mAnimation->updateParts(); MWWorld::InventoryStore& inv = mCharacter.getClass().getInventoryStore(mCharacter); MWWorld::ContainerStoreIterator iter = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); std::string groupname = "inventoryhandtohand"; bool showCarriedLeft = true; if (iter != inv.end()) { groupname = "inventoryweapononehand"; if (iter->getType() == ESM::Weapon::sRecordId) { MWWorld::LiveCellRef<ESM::Weapon>* ref = iter->get<ESM::Weapon>(); int type = ref->mBase->mData.mType; const ESM::WeaponType* weaponInfo = MWMechanics::getWeaponType(type); showCarriedLeft = !(weaponInfo->mFlags & ESM::WeaponType::TwoHanded); std::string inventoryGroup = weaponInfo->mLongGroup; inventoryGroup = "inventory" + inventoryGroup; // We still should use one-handed animation as fallback if (mAnimation->hasAnimation(inventoryGroup)) groupname = std::move(inventoryGroup); else { static const std::string oneHandFallback = "inventory" + MWMechanics::getWeaponType(ESM::Weapon::LongBladeOneHand)->mLongGroup; static const std::string twoHandFallback = "inventory" + MWMechanics::getWeaponType(ESM::Weapon::LongBladeTwoHand)->mLongGroup; // For real two-handed melee weapons use 2h swords animations as fallback, otherwise use the 1h ones if (weaponInfo->mFlags & ESM::WeaponType::TwoHanded && weaponInfo->mWeaponClass == ESM::WeaponType::Melee) groupname = twoHandFallback; else groupname = oneHandFallback; } } } mAnimation->showCarriedLeft(showCarriedLeft); mCurrentAnimGroup = std::move(groupname); mAnimation->play(mCurrentAnimGroup, 1, BlendMask::BlendMask_All, false, 1.0f, "start", "stop", 0.0f, 0); MWWorld::ConstContainerStoreIterator torch = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (torch != inv.end() && torch->getType() == ESM::Light::sRecordId && showCarriedLeft) { if (!mAnimation->getInfo("torch")) mAnimation->play("torch", 2, BlendMask::BlendMask_LeftArm, false, 1.0f, "start", "stop", 0.0f, std::numeric_limits<uint32_t>::max(), true); } else if (mAnimation->getInfo("torch")) mAnimation->disable("torch"); mAnimation->runAnimation(0.0f); setBlendMode(); redraw(); } int InventoryPreview::getSlotSelected(int posX, int posY) { if (!mViewport) return -1; float projX = (posX / mViewport->width()) * 2 - 1.f; float projY = (posY / mViewport->height()) * 2 - 1.f; // With Intersector::WINDOW, the intersection ratios are slightly inaccurate. Seems to be a // precision issue - compiling with OSG_USE_FLOAT_MATRIX=0, Intersector::WINDOW works ok. // Using Intersector::PROJECTION results in better precision because the start/end points and the model matrices // don't go through as many transformations. osg::ref_ptr<osgUtil::LineSegmentIntersector> intersector( new osgUtil::LineSegmentIntersector(osgUtil::Intersector::PROJECTION, projX, projY)); intersector->setIntersectionLimit(osgUtil::LineSegmentIntersector::LIMIT_NEAREST); osgUtil::IntersectionVisitor visitor(intersector); visitor.setTraversalMode(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN); // Set the traversal number from the last draw, so that the frame switch used for RigGeometry double buffering // works correctly visitor.setTraversalNumber(mDrawOnceCallback->getLastRenderedFrame()); auto* camera = mRTTNode->getCamera(nullptr); osg::Node::NodeMask nodeMask = camera->getNodeMask(); camera->setNodeMask(~0u); camera->accept(visitor); camera->setNodeMask(nodeMask); if (intersector->containsIntersections()) { osgUtil::LineSegmentIntersector::Intersection intersection = intersector->getFirstIntersection(); return mAnimation->getSlot(intersection.nodePath); } return -1; } void InventoryPreview::updatePtr(const MWWorld::Ptr& ptr) { mCharacter = MWWorld::Ptr(ptr.getBase(), nullptr); } void InventoryPreview::onSetup() { CharacterPreview::onSetup(); osg::Vec3f scale(1.f, 1.f, 1.f); mCharacter.getClass().adjustScale(mCharacter, scale, true); mNode->setScale(scale); auto viewMatrix = osg::Matrixf::lookAt(mPosition * scale.z(), mLookAt * scale.z(), osg::Vec3f(0, 0, 1)); mRTTNode->setViewMatrix(viewMatrix); } // -------------------------------------------------------------------------------------------------- RaceSelectionPreview::RaceSelectionPreview(osg::Group* parent, Resource::ResourceSystem* resourceSystem) : CharacterPreview( parent, resourceSystem, MWMechanics::getPlayer(), 512, 512, osg::Vec3f(0, 125, 8), osg::Vec3f(0, 0, 8)) , mBase(*mCharacter.get<ESM::NPC>()->mBase) , mRef(ESM::makeBlankCellRef(), &mBase) , mPitchRadians(osg::DegreesToRadians(6.f)) { mCharacter = MWWorld::Ptr(&mRef, nullptr); } RaceSelectionPreview::~RaceSelectionPreview() {} void RaceSelectionPreview::setAngle(float angleRadians) { mNode->setAttitude(osg::Quat(mPitchRadians, osg::Vec3(1, 0, 0)) * osg::Quat(angleRadians, osg::Vec3(0, 0, 1))); redraw(); } void RaceSelectionPreview::setPrototype(const ESM::NPC& proto) { mBase = proto; mBase.mId = ESM::RefId::stringRefId("Player"); rebuild(); } class UpdateCameraCallback : public SceneUtil::NodeCallback<UpdateCameraCallback, CharacterPreviewRTTNode*> { public: UpdateCameraCallback( osg::ref_ptr<const osg::Node> nodeToFollow, const osg::Vec3& posOffset, const osg::Vec3& lookAtOffset) : mNodeToFollow(std::move(nodeToFollow)) , mPosOffset(posOffset) , mLookAtOffset(lookAtOffset) { } void operator()(CharacterPreviewRTTNode* node, osg::NodeVisitor* nv) { // Update keyframe controllers in the scene graph first... traverse(node, nv); // Now update camera utilizing the updated head position osg::NodePathList nodepaths = mNodeToFollow->getParentalNodePaths(); if (nodepaths.empty()) return; osg::Matrix worldMat = osg::computeLocalToWorld(nodepaths[0]); osg::Vec3 headOffset = worldMat.getTrans(); auto viewMatrix = osg::Matrixf::lookAt(headOffset + mPosOffset, headOffset + mLookAtOffset, osg::Vec3(0, 0, 1)); node->setViewMatrix(viewMatrix); } private: osg::ref_ptr<const osg::Node> mNodeToFollow; osg::Vec3 mPosOffset; osg::Vec3 mLookAtOffset; }; void RaceSelectionPreview::onSetup() { CharacterPreview::onSetup(); mAnimation->play("idle", 1, BlendMask::BlendMask_All, false, 1.0f, "start", "stop", 0.0f, 0); mAnimation->runAnimation(0.f); // attach camera to follow the head node if (mUpdateCameraCallback) mRTTNode->removeUpdateCallback(mUpdateCameraCallback); const osg::Node* head = mAnimation->getNode("Bip01 Head"); if (head) { mUpdateCameraCallback = new UpdateCameraCallback(head, mPosition, mLookAt); mRTTNode->addUpdateCallback(mUpdateCameraCallback); } else Log(Debug::Error) << "Error: Bip01 Head node not found"; } }
25,868
C++
.cpp
513
39.8577
120
0.632933
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,407
fogmanager.cpp
OpenMW_openmw/apps/openmw/mwrender/fogmanager.cpp
#include "fogmanager.hpp" #include <algorithm> #include <components/esm/esmbridge.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm4/loadcell.hpp> #include <components/fallback/fallback.hpp> #include <components/sceneutil/util.hpp> #include <components/settings/values.hpp> #include "apps/openmw/mwworld/cell.hpp" namespace MWRender { FogManager::FogManager() : mLandFogStart(0.f) , mLandFogEnd(std::numeric_limits<float>::max()) , mUnderwaterFogStart(0.f) , mUnderwaterFogEnd(std::numeric_limits<float>::max()) , mFogColor(osg::Vec4f()) , mUnderwaterColor(Fallback::Map::getColour("Water_UnderwaterColor")) , mUnderwaterWeight(Fallback::Map::getFloat("Water_UnderwaterColorWeight")) , mUnderwaterIndoorFog(Fallback::Map::getFloat("Water_UnderwaterIndoorFog")) { } void FogManager::configure(float viewDistance, const MWWorld::Cell& cell) { osg::Vec4f color = SceneUtil::colourFromRGB(cell.getMood().mFogColor); const float fogDensity = cell.getMood().mFogDensity; if (Settings::fog().mUseDistantFog) { float density = std::max(0.2f, fogDensity); mLandFogStart = Settings::fog().mDistantInteriorFogEnd * (1.0f - density) + Settings::fog().mDistantInteriorFogStart * density; mLandFogEnd = Settings::fog().mDistantInteriorFogEnd; mUnderwaterFogStart = Settings::fog().mDistantUnderwaterFogStart; mUnderwaterFogEnd = Settings::fog().mDistantUnderwaterFogEnd; mFogColor = color; } else configure(viewDistance, fogDensity, mUnderwaterIndoorFog, 1.0f, 0.0f, color); } void FogManager::configure(float viewDistance, float fogDepth, float underwaterFog, float dlFactor, float dlOffset, const osg::Vec4f& color) { if (Settings::fog().mUseDistantFog) { mLandFogStart = dlFactor * (Settings::fog().mDistantLandFogStart - dlOffset * Settings::fog().mDistantLandFogEnd); mLandFogEnd = dlFactor * (1.0f - dlOffset) * Settings::fog().mDistantLandFogEnd; mUnderwaterFogStart = Settings::fog().mDistantUnderwaterFogStart; mUnderwaterFogEnd = Settings::fog().mDistantUnderwaterFogEnd; } else { if (fogDepth == 0.0) { mLandFogStart = 0.0f; mLandFogEnd = std::numeric_limits<float>::max(); } else { mLandFogStart = viewDistance * (1 - fogDepth); mLandFogEnd = viewDistance; } mUnderwaterFogStart = std::min(viewDistance, 7168.f) * (1 - underwaterFog); mUnderwaterFogEnd = std::min(viewDistance, 7168.f); } mFogColor = color; } float FogManager::getFogStart(bool isUnderwater) const { return isUnderwater ? mUnderwaterFogStart : mLandFogStart; } float FogManager::getFogEnd(bool isUnderwater) const { return isUnderwater ? mUnderwaterFogEnd : mLandFogEnd; } osg::Vec4f FogManager::getFogColor(bool isUnderwater) const { if (isUnderwater) { return mUnderwaterColor * mUnderwaterWeight + mFogColor * (1.f - mUnderwaterWeight); } return mFogColor; } }
3,392
C++
.cpp
84
31.72619
119
0.645435
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,408
navmesh.cpp
OpenMW_openmw/apps/openmw/mwrender/navmesh.cpp
#include "navmesh.hpp" #include "vismask.hpp" #include <components/detournavigator/guardednavmeshcacheitem.hpp> #include <components/detournavigator/navmeshcacheitem.hpp> #include <components/detournavigator/settings.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/detourdebugdraw.hpp> #include <components/sceneutil/navmesh.hpp> #include <components/sceneutil/workqueue.hpp> #include <osg/BlendFunc> #include <osg/LineWidth> #include <osg/PositionAttitudeTransform> #include <osg/StateSet> #include <DetourNavMesh.h> #include "../mwbase/environment.hpp" #include <algorithm> #include <limits> namespace MWRender { namespace { osg::ref_ptr<osg::StateSet> makeDebugDrawStateSet() { const osg::ref_ptr<osg::LineWidth> lineWidth = new osg::LineWidth(); const osg::ref_ptr<osg::BlendFunc> blendFunc = new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); const osg::ref_ptr<SceneUtil::AutoDepth> depth = new SceneUtil::AutoDepth; depth->setWriteMask(false); osg::ref_ptr<osg::StateSet> stateSet = new osg::StateSet; stateSet->setMode(GL_BLEND, osg::StateAttribute::ON); stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN); stateSet->setAttributeAndModes(lineWidth); stateSet->setAttributeAndModes(blendFunc); stateSet->setAttributeAndModes(depth); return stateSet; } } struct NavMesh::LessByTilePosition { bool operator()(const DetourNavigator::TilePosition& lhs, const std::pair<DetourNavigator::TilePosition, DetourNavigator::Version>& rhs) const { return lhs < rhs.first; } bool operator()(const std::pair<DetourNavigator::TilePosition, DetourNavigator::Version>& lhs, const DetourNavigator::TilePosition& rhs) const { return lhs.first < rhs; } }; struct NavMesh::CreateNavMeshTileGroups final : SceneUtil::WorkItem { std::size_t mId; DetourNavigator::Version mVersion; const std::weak_ptr<DetourNavigator::GuardedNavMeshCacheItem> mNavMesh; const osg::ref_ptr<osg::StateSet> mGroupStateSet; const osg::ref_ptr<osg::StateSet> mDebugDrawStateSet; const DetourNavigator::Settings mSettings; std::map<DetourNavigator::TilePosition, Tile> mTiles; Settings::NavMeshRenderMode mMode; std::atomic_bool mAborted{ false }; std::mutex mMutex; bool mStarted = false; std::vector<std::pair<DetourNavigator::TilePosition, Tile>> mUpdatedTiles; std::vector<DetourNavigator::TilePosition> mRemovedTiles; explicit CreateNavMeshTileGroups(std::size_t id, DetourNavigator::Version version, std::weak_ptr<DetourNavigator::GuardedNavMeshCacheItem> navMesh, const osg::ref_ptr<osg::StateSet>& groupStateSet, const osg::ref_ptr<osg::StateSet>& debugDrawStateSet, const DetourNavigator::Settings& settings, const std::map<DetourNavigator::TilePosition, Tile>& tiles, Settings::NavMeshRenderMode mode) : mId(id) , mVersion(version) , mNavMesh(std::move(navMesh)) , mGroupStateSet(groupStateSet) , mDebugDrawStateSet(debugDrawStateSet) , mSettings(settings) , mTiles(tiles) , mMode(mode) { } void doWork() final { using DetourNavigator::TilePosition; using DetourNavigator::Version; const std::lock_guard lock(mMutex); mStarted = true; if (mAborted.load(std::memory_order_acquire)) return; const auto navMeshPtr = mNavMesh.lock(); if (navMeshPtr == nullptr) return; std::vector<std::pair<DetourNavigator::TilePosition, Version>> existingTiles; unsigned minSalt = std::numeric_limits<unsigned>::max(); unsigned maxSalt = 0; navMeshPtr->lockConst()->forEachUsedTile( [&](const TilePosition& position, const Version& version, const dtMeshTile& meshTile) { existingTiles.emplace_back(position, version); minSalt = std::min(minSalt, meshTile.salt); maxSalt = std::max(maxSalt, meshTile.salt); }); if (mAborted.load(std::memory_order_acquire)) return; std::sort(existingTiles.begin(), existingTiles.end()); std::vector<DetourNavigator::TilePosition> removedTiles; for (const auto& [position, tile] : mTiles) if (!std::binary_search(existingTiles.begin(), existingTiles.end(), position, LessByTilePosition{})) removedTiles.push_back(position); std::vector<std::pair<TilePosition, Tile>> updatedTiles; const unsigned char flags = SceneUtil::NavMeshTileDrawFlagsOffMeshConnections | SceneUtil::NavMeshTileDrawFlagsClosedList | (mMode == Settings::NavMeshRenderMode::UpdateFrequency ? SceneUtil::NavMeshTileDrawFlagsHeat : 0); for (const auto& [position, version] : existingTiles) { const auto it = mTiles.find(position); if (it != mTiles.end() && it->second.mGroup != nullptr && it->second.mVersion == version && mMode != Settings::NavMeshRenderMode::UpdateFrequency) continue; osg::ref_ptr<osg::Group> group; { const auto navMesh = navMeshPtr->lockConst(); const dtMeshTile* meshTile = DetourNavigator::getTile(navMesh->getImpl(), position); if (meshTile == nullptr) continue; if (mAborted.load(std::memory_order_acquire)) return; group = SceneUtil::createNavMeshTileGroup( navMesh->getImpl(), *meshTile, mSettings, mDebugDrawStateSet, flags, minSalt, maxSalt); } if (group == nullptr) { removedTiles.push_back(position); continue; } group->setNodeMask(Mask_Debug); group->setStateSet(mGroupStateSet); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(group, "debug"); updatedTiles.emplace_back(position, Tile{ version, std::move(group) }); } if (mAborted.load(std::memory_order_acquire)) return; mUpdatedTiles = std::move(updatedTiles); mRemovedTiles = std::move(removedTiles); } void abort() final { mAborted.store(true, std::memory_order_release); } }; struct NavMesh::DeallocateCreateNavMeshTileGroups final : SceneUtil::WorkItem { osg::ref_ptr<NavMesh::CreateNavMeshTileGroups> mWorkItem; explicit DeallocateCreateNavMeshTileGroups(osg::ref_ptr<NavMesh::CreateNavMeshTileGroups>&& workItem) : mWorkItem(std::move(workItem)) { } }; NavMesh::NavMesh(const osg::ref_ptr<osg::Group>& root, const osg::ref_ptr<SceneUtil::WorkQueue>& workQueue, bool enabled, Settings::NavMeshRenderMode mode) : mRootNode(root) , mWorkQueue(workQueue) , mGroupStateSet(SceneUtil::makeDetourGroupStateSet()) , mDebugDrawStateSet(makeDebugDrawStateSet()) , mEnabled(enabled) , mMode(mode) , mId(std::numeric_limits<std::size_t>::max()) { } NavMesh::~NavMesh() { if (mEnabled) disable(); for (const auto& workItem : mWorkItems) workItem->abort(); } bool NavMesh::toggle() { if (mEnabled) disable(); else enable(); return mEnabled; } void NavMesh::update(const std::shared_ptr<DetourNavigator::GuardedNavMeshCacheItem>& navMesh, std::size_t id, const DetourNavigator::Settings& settings) { using DetourNavigator::TilePosition; using DetourNavigator::Version; if (!mEnabled) return; { std::pair<std::size_t, Version> lastest{ 0, Version{} }; osg::ref_ptr<CreateNavMeshTileGroups> latestCandidate; for (auto it = mWorkItems.begin(); it != mWorkItems.end();) { if (!(*it)->isDone()) { ++it; continue; } const std::pair<std::size_t, Version> order{ (*it)->mId, (*it)->mVersion }; if (lastest < order) { lastest = order; std::swap(latestCandidate, *it); } if (*it != nullptr) mWorkQueue->addWorkItem(new DeallocateCreateNavMeshTileGroups(std::move(*it))); it = mWorkItems.erase(it); } if (latestCandidate != nullptr) { for (const TilePosition& position : latestCandidate->mRemovedTiles) { const auto it = mTiles.find(position); if (it == mTiles.end()) continue; mRootNode->removeChild(it->second.mGroup); mTiles.erase(it); } for (auto& [position, tile] : latestCandidate->mUpdatedTiles) { const auto it = mTiles.find(position); if (it == mTiles.end()) { mRootNode->addChild(tile.mGroup); mTiles.emplace_hint(it, position, std::move(tile)); } else { mRootNode->replaceChild(it->second.mGroup, tile.mGroup); std::swap(it->second, tile); } } mWorkQueue->addWorkItem(new DeallocateCreateNavMeshTileGroups(std::move(latestCandidate))); } } const auto version = navMesh->lock()->getVersion(); if (!mTiles.empty() && mId == id && mVersion == version) return; if (mId != id) { reset(); mId = id; } mVersion = version; for (auto& workItem : mWorkItems) { const std::unique_lock lock(workItem->mMutex, std::try_to_lock); if (!lock.owns_lock()) continue; if (workItem->mStarted) continue; workItem->mId = id; workItem->mVersion = version; workItem->mTiles = mTiles; workItem->mMode = mMode; return; } osg::ref_ptr<CreateNavMeshTileGroups> workItem = new CreateNavMeshTileGroups( id, version, navMesh, mGroupStateSet, mDebugDrawStateSet, settings, mTiles, mMode); mWorkQueue->addWorkItem(workItem); mWorkItems.push_back(std::move(workItem)); } void NavMesh::reset() { for (auto& workItem : mWorkItems) workItem->abort(); mWorkItems.clear(); for (auto& [position, tile] : mTiles) mRootNode->removeChild(tile.mGroup); mTiles.clear(); } void NavMesh::enable() { mEnabled = true; } void NavMesh::disable() { reset(); mEnabled = false; } void NavMesh::setMode(Settings::NavMeshRenderMode value) { if (mMode == value) return; reset(); mMode = value; } }
12,057
C++
.cpp
288
29.920139
116
0.579213
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,409
npcanimation.cpp
OpenMW_openmw/apps/openmw/mwrender/npcanimation.cpp
#include "npcanimation.hpp" #include <osg/Depth> #include <osg/MatrixTransform> #include <osg/UserDataContainer> #include <osgUtil/CullVisitor> #include <osgUtil/RenderBin> #include <components/debug/debuglog.hpp> #include <components/misc/rng.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/esm3/loadbody.hpp> #include <components/esm3/loadmgef.hpp> #include <components/esm3/loadrace.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/depth.hpp> #include <components/sceneutil/keyframe.hpp> #include <components/sceneutil/lightcommon.hpp> #include <components/sceneutil/visitor.hpp> #include <components/settings/values.hpp> #include <components/vfs/manager.hpp> #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/npcstats.hpp" #include "../mwmechanics/weapontype.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/world.hpp" #include "actorutil.hpp" #include "postprocessor.hpp" #include "renderbin.hpp" #include "rotatecontroller.hpp" #include "vismask.hpp" namespace { std::string getVampireHead(const ESM::RefId& race, bool female) { static std::map<std::pair<ESM::RefId, int>, const ESM::BodyPart*> sVampireMapping; std::pair<ESM::RefId, int> thisCombination = std::make_pair(race, int(female)); if (sVampireMapping.find(thisCombination) == sVampireMapping.end()) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); for (const ESM::BodyPart& bodypart : store.get<ESM::BodyPart>()) { if (!bodypart.mData.mVampire) continue; if (bodypart.mData.mType != ESM::BodyPart::MT_Skin) continue; if (bodypart.mData.mPart != ESM::BodyPart::MP_Head) continue; if (female != (bodypart.mData.mFlags & ESM::BodyPart::BPF_Female)) continue; if (!(bodypart.mRace == race)) continue; sVampireMapping[thisCombination] = &bodypart; } } sVampireMapping.emplace(thisCombination, nullptr); const ESM::BodyPart* bodyPart = sVampireMapping[thisCombination]; if (!bodyPart) return std::string(); return Misc::ResourceHelpers::correctMeshPath(bodyPart->mModel); } } namespace MWRender { class HeadAnimationTime : public SceneUtil::ControllerSource { private: MWWorld::Ptr mReference; float mTalkStart; float mTalkStop; float mBlinkStart; float mBlinkStop; float mBlinkTimer; bool mEnabled; float mValue; private: void resetBlinkTimer(); public: HeadAnimationTime(const MWWorld::Ptr& reference); void updatePtr(const MWWorld::Ptr& updated); void update(float dt); void setEnabled(bool enabled); void setTalkStart(float value); void setTalkStop(float value); void setBlinkStart(float value); void setBlinkStop(float value); float getValue(osg::NodeVisitor* nv) override; }; // -------------------------------------------------------------------------------------------------------------- HeadAnimationTime::HeadAnimationTime(const MWWorld::Ptr& reference) : mReference(reference) , mTalkStart(0) , mTalkStop(0) , mBlinkStart(0) , mBlinkStop(0) , mEnabled(true) , mValue(0) { resetBlinkTimer(); } void HeadAnimationTime::updatePtr(const MWWorld::Ptr& updated) { mReference = updated; } void HeadAnimationTime::setEnabled(bool enabled) { mEnabled = enabled; } void HeadAnimationTime::resetBlinkTimer() { auto& prng = MWBase::Environment::get().getWorld()->getPrng(); mBlinkTimer = -(2.0f + Misc::Rng::rollDice(6, prng)); } void HeadAnimationTime::update(float dt) { if (!mEnabled) return; if (dt == 0.f) return; if (!MWBase::Environment::get().getSoundManager()->sayActive(mReference)) { mBlinkTimer += dt; float duration = mBlinkStop - mBlinkStart; if (mBlinkTimer >= 0 && mBlinkTimer <= duration) { mValue = mBlinkStart + mBlinkTimer; } else mValue = mBlinkStop; if (mBlinkTimer > duration) resetBlinkTimer(); } else { // FIXME: would be nice to hold on to the SoundPtr so we don't have to retrieve it every frame mValue = mTalkStart + (mTalkStop - mTalkStart) * std::min(1.f, MWBase::Environment::get().getSoundManager()->getSaySoundLoudness(mReference) * 2); // Rescale a bit (most voices are not very loud) } } float HeadAnimationTime::getValue(osg::NodeVisitor*) { return mValue; } void HeadAnimationTime::setTalkStart(float value) { mTalkStart = value; } void HeadAnimationTime::setTalkStop(float value) { mTalkStop = value; } void HeadAnimationTime::setBlinkStart(float value) { mBlinkStart = value; } void HeadAnimationTime::setBlinkStop(float value) { mBlinkStop = value; } // ---------------------------------------------------- NpcAnimation::NpcType NpcAnimation::getNpcType() const { const MWWorld::Class& cls = mPtr.getClass(); // Dead vampires should typically stay vampires. if (mNpcType == Type_Vampire && cls.getNpcStats(mPtr).isDead() && !cls.getNpcStats(mPtr).isWerewolf()) return mNpcType; return getNpcType(mPtr); } NpcAnimation::NpcType NpcAnimation::getNpcType(const MWWorld::Ptr& ptr) { const MWWorld::Class& cls = ptr.getClass(); NpcAnimation::NpcType curType = Type_Normal; if (cls.getCreatureStats(ptr).getMagicEffects().getOrDefault(ESM::MagicEffect::Vampirism).getMagnitude() > 0) curType = Type_Vampire; if (cls.getNpcStats(ptr).isWerewolf()) curType = Type_Werewolf; return curType; } static const inline NpcAnimation::PartBoneMap createPartListMap() { return { { ESM::PRT_Head, "Head" }, { ESM::PRT_Hair, "Head" }, // note it uses "Head" as attach bone, but "Hair" as filter { ESM::PRT_Neck, "Neck" }, { ESM::PRT_Cuirass, "Chest" }, { ESM::PRT_Groin, "Groin" }, { ESM::PRT_Skirt, "Groin" }, { ESM::PRT_RHand, "Right Hand" }, { ESM::PRT_LHand, "Left Hand" }, { ESM::PRT_RWrist, "Right Wrist" }, { ESM::PRT_LWrist, "Left Wrist" }, { ESM::PRT_Shield, "Shield Bone" }, { ESM::PRT_RForearm, "Right Forearm" }, { ESM::PRT_LForearm, "Left Forearm" }, { ESM::PRT_RUpperarm, "Right Upper Arm" }, { ESM::PRT_LUpperarm, "Left Upper Arm" }, { ESM::PRT_RFoot, "Right Foot" }, { ESM::PRT_LFoot, "Left Foot" }, { ESM::PRT_RAnkle, "Right Ankle" }, { ESM::PRT_LAnkle, "Left Ankle" }, { ESM::PRT_RKnee, "Right Knee" }, { ESM::PRT_LKnee, "Left Knee" }, { ESM::PRT_RLeg, "Right Upper Leg" }, { ESM::PRT_LLeg, "Left Upper Leg" }, { ESM::PRT_RPauldron, "Right Clavicle" }, { ESM::PRT_LPauldron, "Left Clavicle" }, { ESM::PRT_Weapon, "Weapon Bone" }, // Fallback. The real node name depends on the current weapon type. { ESM::PRT_Tail, "Tail" } }; } const NpcAnimation::PartBoneMap NpcAnimation::sPartList = createPartListMap(); NpcAnimation::~NpcAnimation() { mAmmunition.reset(); } NpcAnimation::NpcAnimation(const MWWorld::Ptr& ptr, osg::ref_ptr<osg::Group> parentNode, Resource::ResourceSystem* resourceSystem, bool disableSounds, ViewMode viewMode, float firstPersonFieldOfView) : ActorAnimation(ptr, std::move(parentNode), resourceSystem) , mViewMode(viewMode) , mShowWeapons(false) , mShowCarriedLeft(true) , mNpcType(getNpcType(ptr)) , mFirstPersonFieldOfView(firstPersonFieldOfView) , mSoundsDisabled(disableSounds) , mAccurateAiming(false) , mAimingFactor(0.f) { mNpc = mPtr.get<ESM::NPC>()->mBase; mHeadAnimationTime = std::make_shared<HeadAnimationTime>(mPtr); mWeaponAnimationTime = std::make_shared<WeaponAnimationTime>(this); for (size_t i = 0; i < ESM::PRT_Count; i++) { mPartslots[i] = -1; // each slot is empty mPartPriorities[i] = 0; } std::fill(mSounds.begin(), mSounds.end(), nullptr); updateNpcBase(); } void NpcAnimation::setViewMode(NpcAnimation::ViewMode viewMode) { assert(viewMode != VM_HeadOnly); if (mViewMode == viewMode) return; // FIXME: sheathing state must be consistent if the third person skeleton doesn't have the necessary node, but // third person skeleton is unavailable in first person view. This is a hack to avoid cosmetic issues. bool viewChange = mViewMode == VM_FirstPerson || viewMode == VM_FirstPerson; mViewMode = viewMode; MWBase::Environment::get().getWorld()->scaleObject( mPtr, mPtr.getCellRef().getScale(), true); // apply race height after view change mAmmunition.reset(); rebuild(); setRenderBin(); if (viewChange && Settings::game().mShieldSheathing) { int weaptype = ESM::Weapon::None; MWMechanics::getActiveWeapon(mPtr, &weaptype); showCarriedLeft(updateCarriedLeftVisible(weaptype)); } } /// @brief A RenderBin callback to clear the depth buffer before rendering. /// Switches depth attachments to a proxy renderbuffer, reattaches original depth then redraws first person root. /// This gives a complete depth buffer which can be used for postprocessing, buffer resolves as if depth was never /// cleared. class DepthClearCallback : public osgUtil::RenderBin::DrawCallback { public: DepthClearCallback() { mDepth = new SceneUtil::AutoDepth; mDepth->setWriteMask(true); mStateSet = new osg::StateSet; mStateSet->setAttributeAndModes(new osg::ColorMask(false, false, false, false), osg::StateAttribute::ON); mStateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); } void drawImplementation( osgUtil::RenderBin* bin, osg::RenderInfo& renderInfo, osgUtil::RenderLeaf*& previous) override { osg::State* state = renderInfo.getState(); PostProcessor* postProcessor = static_cast<PostProcessor*>(renderInfo.getCurrentCamera()->getUserData()); state->applyAttribute(mDepth); unsigned int frameId = state->getFrameStamp()->getFrameNumber() % 2; postProcessor->getFbo(PostProcessor::FBO_FirstPerson, frameId)->apply(*state); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // color accumulation pass bin->drawImplementation(renderInfo, previous); auto primaryFBO = postProcessor->getPrimaryFbo(frameId); primaryFBO->apply(*state); postProcessor->getFbo(PostProcessor::FBO_OpaqueDepth, frameId)->apply(*state); // depth accumulation pass osg::ref_ptr<osg::StateSet> restore = bin->getStateSet(); bin->setStateSet(mStateSet); bin->drawImplementation(renderInfo, previous); bin->setStateSet(restore); primaryFBO->apply(*state); state->checkGLErrors("after DepthClearCallback::drawImplementation"); } osg::ref_ptr<osg::Depth> mDepth; osg::ref_ptr<osg::StateSet> mStateSet; }; /// Overrides Field of View to given value for rendering the subgraph. /// Must be added as cull callback. class OverrideFieldOfViewCallback : public osg::NodeCallback { public: OverrideFieldOfViewCallback(float fov) : mFov(fov) { } void operator()(osg::Node* node, osg::NodeVisitor* nv) override { osgUtil::CullVisitor* cv = static_cast<osgUtil::CullVisitor*>(nv); float fov, aspect, zNear, zFar; if (cv->getProjectionMatrix()->getPerspective(fov, aspect, zNear, zFar) && std::abs(fov - mFov) > 0.001) { fov = mFov; osg::ref_ptr<osg::RefMatrix> newProjectionMatrix = new osg::RefMatrix(); newProjectionMatrix->makePerspective(fov, aspect, zNear, zFar); osg::ref_ptr<osg::RefMatrix> invertedOldMatrix = cv->getProjectionMatrix(); invertedOldMatrix = new osg::RefMatrix(osg::RefMatrix::inverse(*invertedOldMatrix)); osg::ref_ptr<osg::RefMatrix> viewMatrix = new osg::RefMatrix(*cv->getModelViewMatrix()); viewMatrix->postMult(*newProjectionMatrix); viewMatrix->postMult(*invertedOldMatrix); cv->pushModelViewMatrix(viewMatrix, osg::Transform::ReferenceFrame::ABSOLUTE_RF); traverse(node, nv); cv->popModelViewMatrix(); } else traverse(node, nv); } private: float mFov; }; void NpcAnimation::setRenderBin() { if (mViewMode == VM_FirstPerson) { static bool prototypeAdded = false; if (!prototypeAdded) { osg::ref_ptr<osgUtil::RenderBin> depthClearBin(new osgUtil::RenderBin); depthClearBin->setDrawCallback(new DepthClearCallback()); osgUtil::RenderBin::addRenderBinPrototype("DepthClear", depthClearBin); prototypeAdded = true; } mObjectRoot->getOrCreateStateSet()->setRenderBinDetails( RenderBin_FirstPerson, "DepthClear", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS); } else if (osg::StateSet* stateset = mObjectRoot->getStateSet()) stateset->setRenderBinToInherit(); } void NpcAnimation::rebuild() { mScabbard.reset(); mHolsteredShield.reset(); updateNpcBase(); MWBase::Environment::get().getMechanicsManager()->forceStateUpdate(mPtr); } int NpcAnimation::getSlot(const osg::NodePath& path) const { for (int i = 0; i < ESM::PRT_Count; ++i) { const PartHolder* const part = mObjectParts[i].get(); if (part == nullptr) continue; if (std::find(path.begin(), path.end(), part->getNode().get()) != path.end()) { return mPartslots[i]; } } return -1; } void NpcAnimation::updateNpcBase() { clearAnimSources(); for (size_t i = 0; i < ESM::PRT_Count; i++) removeIndividualPart((ESM::PartReferenceType)i); const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); const ESM::Race* race = store.get<ESM::Race>().find(mNpc->mRace); NpcType curType = getNpcType(); bool isWerewolf = (curType == Type_Werewolf); bool isVampire = (curType == Type_Vampire); bool isFemale = !mNpc->isMale(); mHeadModel.clear(); mHairModel.clear(); const ESM::RefId headName = isWerewolf ? ESM::RefId::stringRefId("WerewolfHead") : mNpc->mHead; const ESM::RefId hairName = isWerewolf ? ESM::RefId::stringRefId("WerewolfHair") : mNpc->mHair; if (!headName.empty()) { const ESM::BodyPart* bp = store.get<ESM::BodyPart>().search(headName); if (bp) mHeadModel = Misc::ResourceHelpers::correctMeshPath(bp->mModel); else Log(Debug::Warning) << "Warning: Failed to load body part '" << headName << "'"; } if (!hairName.empty()) { const ESM::BodyPart* bp = store.get<ESM::BodyPart>().search(hairName); if (bp) mHairModel = Misc::ResourceHelpers::correctMeshPath(bp->mModel); else Log(Debug::Warning) << "Warning: Failed to load body part '" << hairName << "'"; } const std::string vampireHead = getVampireHead(mNpc->mRace, isFemale); if (!isWerewolf && isVampire && !vampireHead.empty()) mHeadModel = vampireHead; bool is1stPerson = mViewMode == VM_FirstPerson; bool isBeast = (race->mData.mFlags & ESM::Race::Beast) != 0; std::string_view base; if (!isWerewolf) { if (!is1stPerson) base = Settings::models().mXbaseanim.get().value(); else base = Settings::models().mXbaseanim1st.get().value(); } const std::string defaultSkeleton = Misc::ResourceHelpers::correctActorModelPath( VFS::Path::toNormalized(getActorSkeleton(is1stPerson, isFemale, isBeast, isWerewolf)), mResourceSystem->getVFS()); std::string smodel = defaultSkeleton; bool isCustomModel = false; if (!is1stPerson && !isWerewolf && !mNpc->mModel.empty()) { VFS::Path::Normalized model = Misc::ResourceHelpers::correctMeshPath(mNpc->mModel); isCustomModel = !isDefaultActorSkeleton(model); smodel = Misc::ResourceHelpers::correctActorModelPath(model, mResourceSystem->getVFS()); } setObjectRoot(smodel, true, true, false); updateParts(); if (!base.empty()) addAnimSource(base, smodel); if (defaultSkeleton != base) addAnimSource(defaultSkeleton, smodel); if (isCustomModel) addAnimSource(smodel, smodel); const bool customArgonianSwim = !is1stPerson && !isWerewolf && isBeast && mNpc->mRace.contains("argonian"); if (customArgonianSwim) addAnimSource(Settings::models().mXargonianswimkna.get().value(), smodel); if (is1stPerson) { mObjectRoot->setNodeMask(Mask_FirstPerson); mObjectRoot->addCullCallback(new OverrideFieldOfViewCallback(mFirstPersonFieldOfView)); } mWeaponAnimationTime->updateStartTime(); } std::string NpcAnimation::getSheathedShieldMesh(const MWWorld::ConstPtr& shield) const { std::string mesh = getShieldMesh(shield, !mNpc->isMale()); if (mesh.empty()) return std::string(); const VFS::Path::Normalized holsteredName(addSuffixBeforeExtension(mesh, "_sh")); if (mResourceSystem->getVFS()->exists(holsteredName)) { osg::ref_ptr<osg::Node> shieldTemplate = mResourceSystem->getSceneManager()->getInstance(holsteredName); SceneUtil::FindByNameVisitor findVisitor("Bip01 Sheath"); shieldTemplate->accept(findVisitor); osg::ref_ptr<osg::Node> sheathNode = findVisitor.mFoundNode; if (!sheathNode) return std::string(); } return mesh; } void NpcAnimation::updateParts() { if (!mObjectRoot.get()) return; NpcType curType = getNpcType(); if (curType != mNpcType) { mNpcType = curType; rebuild(); return; } static const struct { int mSlot; int mBasePriority; } slotlist[] = { // FIXME: Priority is based on the number of reserved slots. There should be a better way. { MWWorld::InventoryStore::Slot_Robe, 11 }, { MWWorld::InventoryStore::Slot_Skirt, 3 }, { MWWorld::InventoryStore::Slot_Helmet, 0 }, { MWWorld::InventoryStore::Slot_Cuirass, 0 }, { MWWorld::InventoryStore::Slot_Greaves, 0 }, { MWWorld::InventoryStore::Slot_LeftPauldron, 0 }, { MWWorld::InventoryStore::Slot_RightPauldron, 0 }, { MWWorld::InventoryStore::Slot_Boots, 0 }, { MWWorld::InventoryStore::Slot_LeftGauntlet, 0 }, { MWWorld::InventoryStore::Slot_RightGauntlet, 0 }, { MWWorld::InventoryStore::Slot_Shirt, 0 }, { MWWorld::InventoryStore::Slot_Pants, 0 }, { MWWorld::InventoryStore::Slot_CarriedLeft, 0 }, { MWWorld::InventoryStore::Slot_CarriedRight, 0 } }; static const size_t slotlistsize = sizeof(slotlist) / sizeof(slotlist[0]); bool wasArrowAttached = isArrowAttached(); mAmmunition.reset(); const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); for (size_t i = 0; i < slotlistsize && mViewMode != VM_HeadOnly; i++) { MWWorld::ConstContainerStoreIterator store = inv.getSlot(slotlist[i].mSlot); removePartGroup(slotlist[i].mSlot); if (store == inv.end()) continue; if (slotlist[i].mSlot == MWWorld::InventoryStore::Slot_Helmet) removeIndividualPart(ESM::PRT_Hair); int prio = 1; bool enchantedGlow = !store->getClass().getEnchantment(*store).empty(); osg::Vec4f glowColor = store->getClass().getEnchantmentColor(*store); if (store->getType() == ESM::Clothing::sRecordId) { prio = ((slotlist[i].mBasePriority + 1) << 1) + 0; const ESM::Clothing* clothes = store->get<ESM::Clothing>()->mBase; addPartGroup(slotlist[i].mSlot, prio, clothes->mParts.mParts, enchantedGlow, &glowColor); } else if (store->getType() == ESM::Armor::sRecordId) { prio = ((slotlist[i].mBasePriority + 1) << 1) + 1; const ESM::Armor* armor = store->get<ESM::Armor>()->mBase; addPartGroup(slotlist[i].mSlot, prio, armor->mParts.mParts, enchantedGlow, &glowColor); } if (slotlist[i].mSlot == MWWorld::InventoryStore::Slot_Robe) { ESM::PartReferenceType parts[] = { ESM::PRT_Groin, ESM::PRT_Skirt, ESM::PRT_RLeg, ESM::PRT_LLeg, ESM::PRT_RUpperarm, ESM::PRT_LUpperarm, ESM::PRT_RKnee, ESM::PRT_LKnee, ESM::PRT_RForearm, ESM::PRT_LForearm, ESM::PRT_Cuirass }; size_t parts_size = sizeof(parts) / sizeof(parts[0]); for (size_t p = 0; p < parts_size; ++p) reserveIndividualPart(parts[p], slotlist[i].mSlot, prio); } else if (slotlist[i].mSlot == MWWorld::InventoryStore::Slot_Skirt) { reserveIndividualPart(ESM::PRT_Groin, slotlist[i].mSlot, prio); reserveIndividualPart(ESM::PRT_RLeg, slotlist[i].mSlot, prio); reserveIndividualPart(ESM::PRT_LLeg, slotlist[i].mSlot, prio); } } if (mViewMode != VM_FirstPerson) { if (mPartPriorities[ESM::PRT_Head] < 1 && !mHeadModel.empty()) addOrReplaceIndividualPart(ESM::PRT_Head, -1, 1, mHeadModel); if (mPartPriorities[ESM::PRT_Hair] < 1 && mPartPriorities[ESM::PRT_Head] <= 1 && !mHairModel.empty()) addOrReplaceIndividualPart(ESM::PRT_Hair, -1, 1, mHairModel); } if (mViewMode == VM_HeadOnly) return; if (mPartPriorities[ESM::PRT_Shield] < 1) { MWWorld::ConstContainerStoreIterator store = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); MWWorld::ConstPtr part; if (store != inv.end() && (part = *store).getType() == ESM::Light::sRecordId) { const ESM::Light* light = part.get<ESM::Light>()->mBase; addOrReplaceIndividualPart(ESM::PRT_Shield, MWWorld::InventoryStore::Slot_CarriedLeft, 1, VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(light->mModel)), false, nullptr, true); if (mObjectParts[ESM::PRT_Shield]) addExtraLight(mObjectParts[ESM::PRT_Shield]->getNode()->asGroup(), SceneUtil::LightCommon(*light)); } } showWeapons(mShowWeapons); showCarriedLeft(mShowCarriedLeft); bool isWerewolf = (getNpcType() == Type_Werewolf); ESM::RefId race = (isWerewolf ? ESM::RefId::stringRefId("werewolf") : mNpc->mRace); const std::vector<const ESM::BodyPart*>& parts = getBodyParts(race, !mNpc->isMale(), mViewMode == VM_FirstPerson, isWerewolf); for (int part = ESM::PRT_Neck; part < ESM::PRT_Count; ++part) { if (mPartPriorities[part] < 1) { if (const ESM::BodyPart* bodypart = parts[part]) addOrReplaceIndividualPart(static_cast<ESM::PartReferenceType>(part), -1, 1, VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(bodypart->mModel))); } } if (wasArrowAttached) attachArrow(); } PartHolderPtr NpcAnimation::insertBoundedPart(VFS::Path::NormalizedView model, std::string_view bonename, std::string_view bonefilter, bool enchantedGlow, osg::Vec4f* glowColor, bool isLight) { osg::ref_ptr<osg::Node> attached = attach(model, bonename, bonefilter, isLight); if (enchantedGlow) mGlowUpdater = SceneUtil::addEnchantedGlow(attached, mResourceSystem, *glowColor); return std::make_unique<PartHolder>(std::move(attached)); } osg::Vec3f NpcAnimation::runAnimation(float timepassed) { osg::Vec3f ret = Animation::runAnimation(timepassed); mHeadAnimationTime->update(timepassed); if (mFirstPersonNeckController) { if (mAccurateAiming) mAimingFactor = 1.f; else mAimingFactor = std::max(0.f, mAimingFactor - timepassed * 0.5f); float rotateFactor = 0.75f + 0.25f * mAimingFactor; mFirstPersonNeckController->setRotate( osg::Quat(mPtr.getRefData().getPosition().rot[0] * rotateFactor, osg::Vec3f(-1, 0, 0))); mFirstPersonNeckController->setOffset(mFirstPersonOffset); } WeaponAnimation::configureControllers(mPtr.getRefData().getPosition().rot[0] + getBodyPitchRadians()); return ret; } void NpcAnimation::removeIndividualPart(ESM::PartReferenceType type) { mPartPriorities[type] = 0; mPartslots[type] = -1; mObjectParts[type].reset(); if (mSounds[type] != nullptr && !mSoundsDisabled) { MWBase::Environment::get().getSoundManager()->stopSound(mSounds[type]); mSounds[type] = nullptr; } } void NpcAnimation::reserveIndividualPart(ESM::PartReferenceType type, int group, int priority) { if (priority > mPartPriorities[type]) { removeIndividualPart(type); mPartPriorities[type] = priority; mPartslots[type] = group; } } void NpcAnimation::removePartGroup(int group) { for (int i = 0; i < ESM::PRT_Count; i++) { if (mPartslots[i] == group) removeIndividualPart((ESM::PartReferenceType)i); } } bool NpcAnimation::isFemalePart(const ESM::BodyPart* bodypart) { return bodypart->mData.mFlags & ESM::BodyPart::BPF_Female; } bool NpcAnimation::addOrReplaceIndividualPart(ESM::PartReferenceType type, int group, int priority, VFS::Path::NormalizedView mesh, bool enchantedGlow, osg::Vec4f* glowColor, bool isLight) { if (priority <= mPartPriorities[type]) return false; removeIndividualPart(type); mPartslots[type] = group; mPartPriorities[type] = priority; try { std::string_view bonename = sPartList.at(type); if (type == ESM::PRT_Weapon) { const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon != inv.end() && weapon->getType() == ESM::Weapon::sRecordId) { int weaponType = weapon->get<ESM::Weapon>()->mBase->mData.mType; const std::string& weaponBonename = MWMechanics::getWeaponType(weaponType)->mAttachBone; if (weaponBonename != bonename) { const NodeMap& nodeMap = getNodeMap(); NodeMap::const_iterator found = nodeMap.find(weaponBonename); if (found != nodeMap.end()) bonename = weaponBonename; } } } // PRT_Hair seems to be the only type that breaks consistency and uses a filter that's different from the // attachment bone const std::string_view bonefilter = (type == ESM::PRT_Hair) ? std::string_view{ "hair" } : bonename; mObjectParts[type] = insertBoundedPart(mesh, bonename, bonefilter, enchantedGlow, glowColor, isLight); } catch (std::exception& e) { Log(Debug::Error) << "Error adding NPC part: " << e.what(); return false; } if (!mSoundsDisabled && group == MWWorld::InventoryStore::Slot_CarriedLeft) { const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator csi = inv.getSlot(group); if (csi != inv.end()) { const auto soundId = csi->getClass().getSound(*csi); if (!soundId.empty()) { mSounds[type] = MWBase::Environment::get().getSoundManager()->playSound3D( mPtr, soundId, 1.0f, 1.0f, MWSound::Type::Sfx, MWSound::PlayMode::Loop); } } } osg::Node* node = mObjectParts[type]->getNode(); if (node->getNumChildrenRequiringUpdateTraversal() > 0) { std::shared_ptr<SceneUtil::ControllerSource> src; if (type == ESM::PRT_Head) { src = mHeadAnimationTime; if (node->getUserDataContainer()) { for (unsigned int i = 0; i < node->getUserDataContainer()->getNumUserObjects(); ++i) { osg::Object* obj = node->getUserDataContainer()->getUserObject(i); if (SceneUtil::TextKeyMapHolder* keys = dynamic_cast<SceneUtil::TextKeyMapHolder*>(obj)) { for (const auto& key : keys->mTextKeys) { if (Misc::StringUtils::ciEqual(key.second, "talk: start")) mHeadAnimationTime->setTalkStart(key.first); if (Misc::StringUtils::ciEqual(key.second, "talk: stop")) mHeadAnimationTime->setTalkStop(key.first); if (Misc::StringUtils::ciEqual(key.second, "blink: start")) mHeadAnimationTime->setBlinkStart(key.first); if (Misc::StringUtils::ciEqual(key.second, "blink: stop")) mHeadAnimationTime->setBlinkStop(key.first); } break; } } } SceneUtil::ForceControllerSourcesVisitor assignVisitor(std::move(src)); node->accept(assignVisitor); } else { if (type == ESM::PRT_Weapon) src = mWeaponAnimationTime; else src = mAnimationTimePtr[0]; SceneUtil::AssignControllerSourcesVisitor assignVisitor(std::move(src)); node->accept(assignVisitor); } } return true; } void NpcAnimation::addPartGroup(int group, int priority, const std::vector<ESM::PartReference>& parts, bool enchantedGlow, osg::Vec4f* glowColor) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); const MWWorld::Store<ESM::BodyPart>& partStore = store.get<ESM::BodyPart>(); const char* ext = (mViewMode == VM_FirstPerson) ? ".1st" : ""; for (const ESM::PartReference& part : parts) { const ESM::BodyPart* bodypart = nullptr; if (!mNpc->isMale() && !part.mFemale.empty()) { bodypart = partStore.search(ESM::RefId::stringRefId(part.mFemale.getRefIdString() + ext)); if (!bodypart && mViewMode == VM_FirstPerson) { bodypart = partStore.search(part.mFemale); if (bodypart && !(bodypart->mData.mPart == ESM::BodyPart::MP_Hand || bodypart->mData.mPart == ESM::BodyPart::MP_Wrist || bodypart->mData.mPart == ESM::BodyPart::MP_Forearm || bodypart->mData.mPart == ESM::BodyPart::MP_Upperarm)) bodypart = nullptr; } else if (!bodypart) Log(Debug::Warning) << "Warning: Failed to find body part '" << part.mFemale << "'"; } if (!bodypart && !part.mMale.empty()) { bodypart = partStore.search(ESM::RefId::stringRefId(part.mMale.getRefIdString() + ext)); if (!bodypart && mViewMode == VM_FirstPerson) { bodypart = partStore.search(part.mMale); if (bodypart && !(bodypart->mData.mPart == ESM::BodyPart::MP_Hand || bodypart->mData.mPart == ESM::BodyPart::MP_Wrist || bodypart->mData.mPart == ESM::BodyPart::MP_Forearm || bodypart->mData.mPart == ESM::BodyPart::MP_Upperarm)) bodypart = nullptr; } else if (!bodypart) Log(Debug::Warning) << "Warning: Failed to find body part '" << part.mMale << "'"; } if (bodypart) addOrReplaceIndividualPart(static_cast<ESM::PartReferenceType>(part.mPart), group, priority, VFS::Path::toNormalized(Misc::ResourceHelpers::correctMeshPath(bodypart->mModel)), enchantedGlow, glowColor); else reserveIndividualPart((ESM::PartReferenceType)part.mPart, group, priority); } } void NpcAnimation::addControllers() { Animation::addControllers(); mFirstPersonNeckController = nullptr; WeaponAnimation::deleteControllers(); if (mViewMode == VM_FirstPerson) { // If there is no active animation, then the bip01 neck node will not be updated each frame, and the // RotateController will accumulate rotations. if (mStates.size() > 0) { NodeMap::iterator found = mNodeMap.find("bip01 neck"); if (found != mNodeMap.end()) { osg::MatrixTransform* node = found->second.get(); mFirstPersonNeckController = new RotateController(mObjectRoot.get()); node->addUpdateCallback(mFirstPersonNeckController); mActiveControllers.emplace_back(node, mFirstPersonNeckController); } } } else if (mViewMode == VM_Normal) { WeaponAnimation::addControllers(mNodeMap, mActiveControllers, mObjectRoot.get()); } } void NpcAnimation::showWeapons(bool showWeapon) { mShowWeapons = showWeapon; mAmmunition.reset(); if (showWeapon) { const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon != inv.end()) { osg::Vec4f glowColor = weapon->getClass().getEnchantmentColor(*weapon); const VFS::Path::Normalized mesh = weapon->getClass().getCorrectedModel(*weapon); addOrReplaceIndividualPart(ESM::PRT_Weapon, MWWorld::InventoryStore::Slot_CarriedRight, 1, mesh, !weapon->getClass().getEnchantment(*weapon).empty(), &glowColor); // Crossbows start out with a bolt attached if (weapon->getType() == ESM::Weapon::sRecordId && weapon->get<ESM::Weapon>()->mBase->mData.mType == ESM::Weapon::MarksmanCrossbow) { int ammotype = MWMechanics::getWeaponType(ESM::Weapon::MarksmanCrossbow)->mAmmoType; MWWorld::ConstContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && ammo->get<ESM::Weapon>()->mBase->mData.mType == ammotype) attachArrow(); } } } else { removeIndividualPart(ESM::PRT_Weapon); // If we remove/hide weapon from player, we should reset attack animation as well if (mPtr == MWMechanics::getPlayer()) mPtr.getClass().getCreatureStats(mPtr).setAttackingOrSpell(false); } updateHolsteredWeapon(!mShowWeapons); updateQuiver(); } bool NpcAnimation::updateCarriedLeftVisible(const int weaptype) const { if (Settings::game().mShieldSheathing) { const MWWorld::Class& cls = mPtr.getClass(); MWMechanics::CreatureStats& stats = cls.getCreatureStats(mPtr); if (stats.getDrawState() == MWMechanics::DrawState::Nothing) { SceneUtil::FindByNameVisitor findVisitor("Bip01 AttachShield"); mObjectRoot->accept(findVisitor); if (findVisitor.mFoundNode || mViewMode == VM_FirstPerson) { const MWWorld::InventoryStore& inv = cls.getInventoryStore(mPtr); const MWWorld::ConstContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (shield != inv.end() && shield->getType() == ESM::Armor::sRecordId && !getSheathedShieldMesh(*shield).empty()) return false; } } } return !(MWMechanics::getWeaponType(weaptype)->mFlags & ESM::WeaponType::TwoHanded); } void NpcAnimation::showCarriedLeft(bool show) { mShowCarriedLeft = show; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator iter = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (show && iter != inv.end()) { osg::Vec4f glowColor = iter->getClass().getEnchantmentColor(*iter); VFS::Path::Normalized mesh = iter->getClass().getCorrectedModel(*iter); // For shields we must try to use the body part model if (iter->getType() == ESM::Armor::sRecordId) { mesh = getShieldMesh(*iter, !mNpc->isMale()); } if (mesh.empty() || addOrReplaceIndividualPart(ESM::PRT_Shield, MWWorld::InventoryStore::Slot_CarriedLeft, 1, mesh, !iter->getClass().getEnchantment(*iter).empty(), &glowColor, iter->getType() == ESM::Light::sRecordId)) { if (mesh.empty()) reserveIndividualPart(ESM::PRT_Shield, MWWorld::InventoryStore::Slot_CarriedLeft, 1); if (iter->getType() == ESM::Light::sRecordId && mObjectParts[ESM::PRT_Shield]) addExtraLight(mObjectParts[ESM::PRT_Shield]->getNode()->asGroup(), SceneUtil::LightCommon(*iter->get<ESM::Light>()->mBase)); } } else removeIndividualPart(ESM::PRT_Shield); updateHolsteredShield(mShowCarriedLeft); } void NpcAnimation::attachArrow() { WeaponAnimation::attachArrow(mPtr); const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && !ammo->getClass().getEnchantment(*ammo).empty()) { osg::Group* bone = getArrowBone(); if (bone != nullptr && bone->getNumChildren()) SceneUtil::addEnchantedGlow( bone->getChild(0), mResourceSystem, ammo->getClass().getEnchantmentColor(*ammo)); } updateQuiver(); } void NpcAnimation::detachArrow() { WeaponAnimation::detachArrow(mPtr); updateQuiver(); } void NpcAnimation::releaseArrow(float attackStrength) { WeaponAnimation::releaseArrow(mPtr, attackStrength); updateQuiver(); } osg::Group* NpcAnimation::getArrowBone() { const PartHolder* const part = mObjectParts[ESM::PRT_Weapon].get(); if (part == nullptr) return nullptr; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return nullptr; int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; int ammoType = MWMechanics::getWeaponType(type)->mAmmoType; if (ammoType == ESM::Weapon::None) return nullptr; // Try to find and attachment bone in actor's skeleton, otherwise fall back to the ArrowBone in weapon's mesh osg::Group* bone = getBoneByName(MWMechanics::getWeaponType(ammoType)->mAttachBone); if (bone == nullptr) { SceneUtil::FindByNameVisitor findVisitor("ArrowBone"); part->getNode()->accept(findVisitor); bone = findVisitor.mFoundNode; } return bone; } osg::Node* NpcAnimation::getWeaponNode() { const PartHolder* const part = mObjectParts[ESM::PRT_Weapon].get(); if (part == nullptr) return nullptr; return part->getNode(); } Resource::ResourceSystem* NpcAnimation::getResourceSystem() { return mResourceSystem; } void NpcAnimation::enableHeadAnimation(bool enable) { mHeadAnimationTime->setEnabled(enable); } void NpcAnimation::setWeaponGroup(const std::string& group, bool relativeDuration) { mWeaponAnimationTime->setGroup(group, relativeDuration); } void NpcAnimation::equipmentChanged() { if (Settings::game().mShieldSheathing) { int weaptype = ESM::Weapon::None; MWMechanics::getActiveWeapon(mPtr, &weaptype); showCarriedLeft(updateCarriedLeftVisible(weaptype)); } updateParts(); } void NpcAnimation::setVampire(bool vampire) { if (mNpcType == Type_Werewolf) // we can't have werewolf vampires, can we return; if ((mNpcType == Type_Vampire) != vampire) { if (mPtr == MWMechanics::getPlayer()) MWBase::Environment::get().getWorld()->reattachPlayerCamera(); else rebuild(); } } void NpcAnimation::setFirstPersonOffset(const osg::Vec3f& offset) { mFirstPersonOffset = offset; } void NpcAnimation::updatePtr(const MWWorld::Ptr& updated) { Animation::updatePtr(updated); mHeadAnimationTime->updatePtr(updated); } // Remember body parts so we only have to search through the store once for each race/gender/viewmode combination typedef std::map<std::pair<ESM::RefId, int>, std::vector<const ESM::BodyPart*>> RaceMapping; static RaceMapping sRaceMapping; const std::vector<const ESM::BodyPart*>& NpcAnimation::getBodyParts( const ESM::RefId& race, bool female, bool firstPerson, bool werewolf) { static const int Flag_FirstPerson = 1 << 1; static const int Flag_Female = 1 << 0; int flags = (werewolf ? -1 : 0); if (female) flags |= Flag_Female; if (firstPerson) flags |= Flag_FirstPerson; RaceMapping::iterator found = sRaceMapping.find(std::make_pair(race, flags)); if (found != sRaceMapping.end()) return found->second; else { std::vector<const ESM::BodyPart*>& parts = sRaceMapping[std::make_pair(race, flags)]; typedef std::multimap<ESM::BodyPart::MeshPart, ESM::PartReferenceType> BodyPartMapType; static const BodyPartMapType sBodyPartMap = { { ESM::BodyPart::MP_Neck, ESM::PRT_Neck }, { ESM::BodyPart::MP_Chest, ESM::PRT_Cuirass }, { ESM::BodyPart::MP_Groin, ESM::PRT_Groin }, { ESM::BodyPart::MP_Hand, ESM::PRT_RHand }, { ESM::BodyPart::MP_Hand, ESM::PRT_LHand }, { ESM::BodyPart::MP_Wrist, ESM::PRT_RWrist }, { ESM::BodyPart::MP_Wrist, ESM::PRT_LWrist }, { ESM::BodyPart::MP_Forearm, ESM::PRT_RForearm }, { ESM::BodyPart::MP_Forearm, ESM::PRT_LForearm }, { ESM::BodyPart::MP_Upperarm, ESM::PRT_RUpperarm }, { ESM::BodyPart::MP_Upperarm, ESM::PRT_LUpperarm }, { ESM::BodyPart::MP_Foot, ESM::PRT_RFoot }, { ESM::BodyPart::MP_Foot, ESM::PRT_LFoot }, { ESM::BodyPart::MP_Ankle, ESM::PRT_RAnkle }, { ESM::BodyPart::MP_Ankle, ESM::PRT_LAnkle }, { ESM::BodyPart::MP_Knee, ESM::PRT_RKnee }, { ESM::BodyPart::MP_Knee, ESM::PRT_LKnee }, { ESM::BodyPart::MP_Upperleg, ESM::PRT_RLeg }, { ESM::BodyPart::MP_Upperleg, ESM::PRT_LLeg }, { ESM::BodyPart::MP_Tail, ESM::PRT_Tail } }; parts.resize(ESM::PRT_Count, nullptr); if (werewolf) return parts; const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); for (const ESM::BodyPart& bodypart : store.get<ESM::BodyPart>()) { if (bodypart.mData.mFlags & ESM::BodyPart::BPF_NotPlayable) continue; if (bodypart.mData.mType != ESM::BodyPart::MT_Skin) continue; if (!(bodypart.mRace == race)) continue; const bool partFirstPerson = ESM::isFirstPersonBodyPart(bodypart); bool isHand = bodypart.mData.mPart == ESM::BodyPart::MP_Hand || bodypart.mData.mPart == ESM::BodyPart::MP_Wrist || bodypart.mData.mPart == ESM::BodyPart::MP_Forearm || bodypart.mData.mPart == ESM::BodyPart::MP_Upperarm; bool isSameGender = isFemalePart(&bodypart) == female; /* A fallback for the arms if 1st person is missing: 1. Try to use 3d person skin for same gender 2. Try to use 1st person skin for male, if female == true 3. Try to use 3d person skin for male, if female == true A fallback in another cases: allow to use male bodyparts, if female == true */ if (firstPerson && isHand && !partFirstPerson) { // Allow 3rd person skins as a fallback for the arms if 1st person is missing BodyPartMapType::const_iterator bIt = sBodyPartMap.lower_bound(BodyPartMapType::key_type(bodypart.mData.mPart)); while (bIt != sBodyPartMap.end() && bIt->first == bodypart.mData.mPart) { // If we have no fallback bodypart now and bodypart is for same gender (1) if (!parts[bIt->second] && isSameGender) parts[bIt->second] = &bodypart; // If we have fallback bodypart for other gender and found fallback for current gender (1) else if (isSameGender && isFemalePart(parts[bIt->second]) != female) parts[bIt->second] = &bodypart; // If we have no fallback bodypart and searching for female bodyparts (3) else if (!parts[bIt->second] && female) parts[bIt->second] = &bodypart; ++bIt; } continue; } // Don't allow to use podyparts for a different view if (partFirstPerson != firstPerson) continue; if (female && !isFemalePart(&bodypart)) { // Allow male parts as fallback for females if female parts are missing BodyPartMapType::const_iterator bIt = sBodyPartMap.lower_bound(BodyPartMapType::key_type(bodypart.mData.mPart)); while (bIt != sBodyPartMap.end() && bIt->first == bodypart.mData.mPart) { // If we have no fallback bodypart now if (!parts[bIt->second]) parts[bIt->second] = &bodypart; // If we have 3d person fallback bodypart for hand and 1st person fallback found (2) else if (isHand && !ESM::isFirstPersonBodyPart(*parts[bIt->second]) && partFirstPerson) parts[bIt->second] = &bodypart; ++bIt; } continue; } // Don't allow to use podyparts for another gender if (female != isFemalePart(&bodypart)) continue; // Use properly found bodypart, replacing fallbacks BodyPartMapType::const_iterator bIt = sBodyPartMap.lower_bound(BodyPartMapType::key_type(bodypart.mData.mPart)); while (bIt != sBodyPartMap.end() && bIt->first == bodypart.mData.mPart) { parts[bIt->second] = &bodypart; ++bIt; } } return parts; } } void NpcAnimation::setAccurateAiming(bool enabled) { mAccurateAiming = enabled; } bool NpcAnimation::isArrowAttached() const { return mAmmunition != nullptr; } }
51,693
C++
.cpp
1,093
35.234218
119
0.582789
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,410
groundcover.cpp
OpenMW_openmw/apps/openmw/mwrender/groundcover.cpp
#include "groundcover.hpp" #include <span> #include <osg/AlphaFunc> #include <osg/BlendFunc> #include <osg/ComputeBoundsVisitor> #include <osg/Geometry> #include <osg/Program> #include <osg/VertexAttribDivisor> #include <osgUtil/CullVisitor> #include <components/esm3/esmreader.hpp> #include <components/esm3/loadland.hpp> #include <components/esm3/readerscache.hpp> #include <components/misc/convert.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/nodecallback.hpp> #include <components/settings/values.hpp> #include <components/shader/shadermanager.hpp> #include <components/terrain/quadtreenode.hpp> #include "../mwworld/groundcoverstore.hpp" #include "vismask.hpp" namespace MWRender { namespace { using value_type = osgUtil::CullVisitor::value_type; // From OSG's CullVisitor.cpp inline value_type distance(const osg::Vec3& coord, const osg::Matrix& matrix) { return -((value_type)coord[0] * (value_type)matrix(0, 2) + (value_type)coord[1] * (value_type)matrix(1, 2) + (value_type)coord[2] * (value_type)matrix(2, 2) + matrix(3, 2)); } inline osg::Matrix computeInstanceMatrix( const Groundcover::GroundcoverEntry& entry, const osg::Vec3& chunkPosition) { return osg::Matrix::scale(entry.mScale, entry.mScale, entry.mScale) * osg::Matrix(Misc::Convert::makeOsgQuat(entry.mPos)) * osg::Matrix::translate(entry.mPos.asVec3() - chunkPosition); } class InstancedComputeNearFarCullCallback : public osg::DrawableCullCallback { public: explicit InstancedComputeNearFarCullCallback(std::span<const Groundcover::GroundcoverEntry> instances, const osg::Vec3& chunkPosition, const osg::BoundingBox& instanceBounds) : mInstanceMatrices() , mInstanceBounds(instanceBounds) { mInstanceMatrices.reserve(instances.size()); for (const Groundcover::GroundcoverEntry& instance : instances) mInstanceMatrices.emplace_back(computeInstanceMatrix(instance, chunkPosition)); } bool cull(osg::NodeVisitor* nv, osg::Drawable* drawable, osg::RenderInfo* renderInfo) const override { osgUtil::CullVisitor& cullVisitor = *nv->asCullVisitor(); osg::CullSettings::ComputeNearFarMode cnfMode = cullVisitor.getComputeNearFarMode(); const osg::BoundingBox& boundingBox = drawable->getBoundingBox(); osg::RefMatrix& matrix = *cullVisitor.getModelViewMatrix(); if (cnfMode != osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES && cnfMode != osg::CullSettings::COMPUTE_NEAR_USING_PRIMITIVES) return false; if (drawable->isCullingActive() && cullVisitor.isCulled(boundingBox)) return true; osg::Vec3 lookVector = cullVisitor.getLookVectorLocal(); unsigned int bbCornerFar = (lookVector.x() >= 0 ? 1 : 0) | (lookVector.y() >= 0 ? 2 : 0) | (lookVector.z() >= 0 ? 4 : 0); unsigned int bbCornerNear = (~bbCornerFar) & 7; value_type dNear = distance(boundingBox.corner(bbCornerNear), matrix); value_type dFar = distance(boundingBox.corner(bbCornerFar), matrix); if (dNear > dFar) std::swap(dNear, dFar); if (dFar < 0) return true; value_type computedZNear = cullVisitor.getCalculatedNearPlane(); value_type computedZFar = cullVisitor.getCalculatedFarPlane(); if (dNear < computedZNear || dFar > computedZFar) { osg::Polytope frustum; osg::Polytope::ClippingMask resultMask = cullVisitor.getCurrentCullingSet().getFrustum().getResultMask(); if (resultMask) { // Other objects are likely cheaper and should let us skip all but a few groundcover instances cullVisitor.computeNearPlane(); computedZNear = cullVisitor.getCalculatedNearPlane(); computedZFar = cullVisitor.getCalculatedFarPlane(); if (dNear < computedZNear) { dNear = computedZNear; for (const auto& instanceMatrix : mInstanceMatrices) { osg::Matrix fullMatrix = instanceMatrix * matrix; osg::Vec3 instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); unsigned int instanceBbCornerFar = (instanceLookVector.x() >= 0 ? 1 : 0) | (instanceLookVector.y() >= 0 ? 2 : 0) | (instanceLookVector.z() >= 0 ? 4 : 0); unsigned int instanceBbCornerNear = (~instanceBbCornerFar) & 7; value_type instanceDNear = distance(mInstanceBounds.corner(instanceBbCornerNear), fullMatrix); value_type instanceDFar = distance(mInstanceBounds.corner(instanceBbCornerFar), fullMatrix); if (instanceDNear > instanceDFar) std::swap(instanceDNear, instanceDFar); if (instanceDFar < 0 || instanceDNear > dNear) continue; frustum.setAndTransformProvidingInverse( cullVisitor.getProjectionCullingStack().back().getFrustum(), fullMatrix); osg::Polytope::PlaneList planes; osg::Polytope::ClippingMask selectorMask = 0x1; for (const auto& plane : frustum.getPlaneList()) { if (resultMask & selectorMask) planes.push_back(plane); selectorMask <<= 1; } value_type newNear = cullVisitor.computeNearestPointInFrustum(fullMatrix, planes, *drawable); dNear = std::min(dNear, newNear); } if (dNear < computedZNear) cullVisitor.setCalculatedNearPlane(dNear); } if (cnfMode == osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES && dFar > computedZFar) { dFar = computedZFar; for (const auto& instanceMatrix : mInstanceMatrices) { osg::Matrix fullMatrix = instanceMatrix * matrix; osg::Vec3 instanceLookVector(-fullMatrix(0, 2), -fullMatrix(1, 2), -fullMatrix(2, 2)); unsigned int instanceBbCornerFar = (instanceLookVector.x() >= 0 ? 1 : 0) | (instanceLookVector.y() >= 0 ? 2 : 0) | (instanceLookVector.z() >= 0 ? 4 : 0); unsigned int instanceBbCornerNear = (~instanceBbCornerFar) & 7; value_type instanceDNear = distance(mInstanceBounds.corner(instanceBbCornerNear), fullMatrix); value_type instanceDFar = distance(mInstanceBounds.corner(instanceBbCornerFar), fullMatrix); if (instanceDNear > instanceDFar) std::swap(instanceDNear, instanceDFar); if (instanceDFar < 0 || instanceDFar < dFar) continue; frustum.setAndTransformProvidingInverse( cullVisitor.getProjectionCullingStack().back().getFrustum(), fullMatrix); osg::Polytope::PlaneList planes; osg::Polytope::ClippingMask selectorMask = 0x1; for (const auto& plane : frustum.getPlaneList()) { if (resultMask & selectorMask) planes.push_back(plane); selectorMask <<= 1; } value_type newFar = cullVisitor.computeFurthestPointInFrustum( instanceMatrix * matrix, planes, *drawable); dFar = std::max(dFar, newFar); } if (dFar > computedZFar) cullVisitor.setCalculatedFarPlane(dFar); } } } return false; } private: std::vector<osg::Matrix> mInstanceMatrices; osg::BoundingBox mInstanceBounds; }; class InstancingVisitor : public osg::NodeVisitor { public: explicit InstancingVisitor( std::span<const Groundcover::GroundcoverEntry> instances, osg::Vec3f& chunkPosition) : osg::NodeVisitor(TRAVERSE_ALL_CHILDREN) , mInstances(instances) , mChunkPosition(chunkPosition) { } void apply(osg::Group& group) override { for (unsigned int i = 0; i < group.getNumChildren();) { if (group.getChild(i)->asDrawable() && !group.getChild(i)->asGeometry()) group.removeChild(i); else ++i; } traverse(group); } void apply(osg::Geometry& geom) override { for (unsigned int i = 0; i < geom.getNumPrimitiveSets(); ++i) { geom.getPrimitiveSet(i)->setNumInstances(mInstances.size()); } osg::ref_ptr<osg::Vec4Array> transforms = new osg::Vec4Array(mInstances.size()); osg::BoundingBox box; osg::BoundingBox originalBox = geom.getBoundingBox(); float radius = originalBox.radius(); for (unsigned int i = 0; i < transforms->getNumElements(); i++) { osg::Vec3f pos(mInstances[i].mPos.asVec3()); osg::Vec3f relativePos = pos - mChunkPosition; (*transforms)[i] = osg::Vec4f(relativePos, mInstances[i].mScale); // Use an additional margin due to groundcover animation float instanceRadius = radius * mInstances[i].mScale * 1.1f; osg::BoundingSphere instanceBounds(relativePos, instanceRadius); box.expandBy(instanceBounds); } geom.setInitialBound(box); osg::ref_ptr<osg::Vec3Array> rotations = new osg::Vec3Array(mInstances.size()); for (unsigned int i = 0; i < rotations->getNumElements(); i++) { (*rotations)[i] = mInstances[i].mPos.asRotationVec3(); } // Display lists do not support instancing in OSG 3.4 geom.setUseDisplayList(false); geom.setUseVertexBufferObjects(true); geom.setVertexAttribArray(6, transforms.get(), osg::Array::BIND_PER_VERTEX); geom.setVertexAttribArray(7, rotations.get(), osg::Array::BIND_PER_VERTEX); geom.addCullCallback(new InstancedComputeNearFarCullCallback(mInstances, mChunkPosition, originalBox)); } private: std::span<const Groundcover::GroundcoverEntry> mInstances; osg::Vec3f mChunkPosition; }; class DensityCalculator { public: DensityCalculator(float density) : mDensity(density) { } bool isInstanceEnabled() { if (mDensity >= 1.f) return true; mCurrentGroundcover += mDensity; if (mCurrentGroundcover < 1.f) return false; mCurrentGroundcover -= 1.f; return true; } void reset() { mCurrentGroundcover = 0.f; } private: float mCurrentGroundcover = 0.f; float mDensity = 0.f; }; class ViewDistanceCallback : public SceneUtil::NodeCallback<ViewDistanceCallback> { public: ViewDistanceCallback(float dist, const osg::BoundingBox& box) : mViewDistance(dist) , mBox(box) { } void operator()(osg::Node* node, osg::NodeVisitor* nv) { if (Terrain::distance(mBox, nv->getEyePoint()) <= mViewDistance) traverse(node, nv); } private: float mViewDistance; osg::BoundingBox mBox; }; inline bool isInChunkBorders(ESM::CellRef& ref, osg::Vec2f& minBound, osg::Vec2f& maxBound) { osg::Vec2f size = maxBound - minBound; if (size.x() >= 1 && size.y() >= 1) return true; osg::Vec3f pos = ref.mPos.asVec3(); osg::Vec3f cellPos = pos / ESM::Land::REAL_SIZE; if ((minBound.x() > std::floor(minBound.x()) && cellPos.x() < minBound.x()) || (minBound.y() > std::floor(minBound.y()) && cellPos.y() < minBound.y()) || (maxBound.x() < std::ceil(maxBound.x()) && cellPos.x() >= maxBound.x()) || (maxBound.y() < std::ceil(maxBound.y()) && cellPos.y() >= maxBound.y())) return false; return true; } } osg::ref_ptr<osg::Node> Groundcover::getChunk(float size, const osg::Vec2f& center, unsigned char lod, unsigned int lodFlags, bool activeGrid, const osg::Vec3f& viewPoint, bool compile) { if (lod > getMaxLodLevel()) return nullptr; GroundcoverChunkId id = std::make_tuple(center, size); osg::ref_ptr<osg::Object> obj = mCache->getRefFromObjectCache(id); if (obj) return static_cast<osg::Node*>(obj.get()); else { InstanceMap instances; collectInstances(instances, size, center); osg::ref_ptr<osg::Node> node = createChunk(instances, center); mCache->addEntryToObjectCache(id, node.get()); return node; } } Groundcover::Groundcover( Resource::SceneManager* sceneManager, float density, float viewDistance, const MWWorld::GroundcoverStore& store) : GenericResourceManager<GroundcoverChunkId>(nullptr, Settings::cells().mCacheExpiryDelay) , mSceneManager(sceneManager) , mDensity(density) , mStateset(new osg::StateSet) , mGroundcoverStore(store) { setViewDistance(viewDistance); // MGE uses default alpha settings for groundcover, so we can not rely on alpha properties // Force a unified alpha handling instead of data from meshes osg::ref_ptr<osg::AlphaFunc> alpha = new osg::AlphaFunc(osg::AlphaFunc::GEQUAL, 128.f / 255.f); mStateset->setAttributeAndModes(alpha.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); mStateset->setAttributeAndModes(new osg::BlendFunc, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); mStateset->setRenderBinDetails(0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS); mStateset->setAttribute(new osg::VertexAttribDivisor(6, 1)); mStateset->setAttribute(new osg::VertexAttribDivisor(7, 1)); mProgramTemplate = mSceneManager->getShaderManager().getProgramTemplate() ? Shader::ShaderManager::cloneProgram(mSceneManager->getShaderManager().getProgramTemplate()) : osg::ref_ptr<osg::Program>(new osg::Program); mProgramTemplate->addBindAttribLocation("aOffset", 6); mProgramTemplate->addBindAttribLocation("aRotation", 7); } Groundcover::~Groundcover() {} void Groundcover::collectInstances(InstanceMap& instances, float size, const osg::Vec2f& center) { if (mDensity <= 0.f) return; osg::Vec2f minBound = (center - osg::Vec2f(size / 2.f, size / 2.f)); osg::Vec2f maxBound = (center + osg::Vec2f(size / 2.f, size / 2.f)); DensityCalculator calculator(mDensity); ESM::ReadersCache readers; osg::Vec2i startCell = osg::Vec2i(std::floor(center.x() - size / 2.f), std::floor(center.y() - size / 2.f)); for (int cellX = startCell.x(); cellX < startCell.x() + size; ++cellX) { for (int cellY = startCell.y(); cellY < startCell.y() + size; ++cellY) { ESM::Cell cell; mGroundcoverStore.initCell(cell, cellX, cellY); if (cell.mContextList.empty()) continue; calculator.reset(); std::map<ESM::RefNum, ESM::CellRef> refs; for (size_t i = 0; i < cell.mContextList.size(); ++i) { const std::size_t index = static_cast<std::size_t>(cell.mContextList[i].index); const ESM::ReadersCache::BusyItem reader = readers.get(index); cell.restore(*reader, i); ESM::CellRef ref; bool deleted = false; while (cell.getNextRef(*reader, ref, deleted)) { if (!deleted && refs.find(ref.mRefNum) == refs.end() && !calculator.isInstanceEnabled()) deleted = true; if (!deleted && !isInChunkBorders(ref, minBound, maxBound)) deleted = true; if (deleted) { refs.erase(ref.mRefNum); continue; } refs[ref.mRefNum] = std::move(ref); } } for (auto& [refNum, cellRef] : refs) { const VFS::Path::NormalizedView model = mGroundcoverStore.getGroundcoverModel(cellRef.mRefID); if (model.empty()) continue; auto it = instances.find(model); if (it == instances.end()) it = instances.emplace_hint(it, VFS::Path::Normalized(model), std::vector<GroundcoverEntry>()); it->second.emplace_back(std::move(cellRef)); } } } } osg::ref_ptr<osg::Node> Groundcover::createChunk(InstanceMap& instances, const osg::Vec2f& center) { osg::ref_ptr<osg::Group> group = new osg::Group; osg::Vec3f worldCenter = osg::Vec3f(center.x(), center.y(), 0) * ESM::Land::REAL_SIZE; for (const auto& [model, entries] : instances) { const osg::Node* temp = mSceneManager->getTemplate(model); osg::ref_ptr<osg::Node> node = static_cast<osg::Node*>(temp->clone(osg::CopyOp::DEEP_COPY_NODES | osg::CopyOp::DEEP_COPY_DRAWABLES | osg::CopyOp::DEEP_COPY_USERDATA | osg::CopyOp::DEEP_COPY_ARRAYS | osg::CopyOp::DEEP_COPY_PRIMITIVES)); // Keep link to original mesh to keep it in cache group->getOrCreateUserDataContainer()->addUserObject(new Resource::TemplateRef(temp)); InstancingVisitor visitor(entries, worldCenter); node->accept(visitor); group->addChild(node); } osg::ComputeBoundsVisitor cbv; group->accept(cbv); osg::BoundingBox box = cbv.getBoundingBox(); group->addCullCallback(new ViewDistanceCallback(getViewDistance(), box)); group->setStateSet(mStateset); group->setNodeMask(Mask_Groundcover); if (mSceneManager->getLightingMethod() != SceneUtil::LightingMethod::FFP) group->addCullCallback(new SceneUtil::LightListCallback); mSceneManager->recreateShaders(group, "groundcover", true, mProgramTemplate); mSceneManager->shareState(group); group->getBound(); return group; } unsigned int Groundcover::getNodeMask() { return Mask_Groundcover; } void Groundcover::reportStats(unsigned int frameNumber, osg::Stats* stats) const { Resource::reportStats("Groundcover Chunk", frameNumber, mCache->getStats(), *stats); } }
21,434
C++
.cpp
407
35.793612
120
0.538597
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,411
bulletdebugdraw.cpp
OpenMW_openmw/apps/openmw/mwrender/bulletdebugdraw.cpp
#include <algorithm> #include <BulletCollision/CollisionDispatch/btCollisionWorld.h> #include <osg/Geometry> #include <osg/Group> #include <osg/Material> #include <components/debug/debuglog.hpp> #include <components/misc/convert.hpp> #include <components/sceneutil/depth.hpp> #include <osg/PolygonMode> #include <osg/PolygonOffset> #include <osg/ShapeDrawable> #include <osg/StateSet> #include "bulletdebugdraw.hpp" #include "vismask.hpp" #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include "../mwbase/environment.hpp" namespace MWRender { DebugDrawer::DebugDrawer(osg::ref_ptr<osg::Group> parentNode, btCollisionWorld* world, int debugMode) : mParentNode(std::move(parentNode)) , mWorld(world) { DebugDrawer::setDebugMode(debugMode); } void DebugDrawer::createGeometry() { if (!mLinesGeometry) { mLinesGeometry = new osg::Geometry; mTrisGeometry = new osg::Geometry; mLinesGeometry->setNodeMask(Mask_Debug); mTrisGeometry->setNodeMask(Mask_Debug); mLinesVertices = new osg::Vec3Array; mTrisVertices = new osg::Vec3Array; mLinesColors = new osg::Vec4Array; mLinesDrawArrays = new osg::DrawArrays(osg::PrimitiveSet::LINES); mTrisDrawArrays = new osg::DrawArrays(osg::PrimitiveSet::TRIANGLES); mLinesGeometry->setUseDisplayList(false); mLinesGeometry->setVertexArray(mLinesVertices); mLinesGeometry->setColorArray(mLinesColors); mLinesGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX); mLinesGeometry->setDataVariance(osg::Object::DYNAMIC); mLinesGeometry->addPrimitiveSet(mLinesDrawArrays); mTrisGeometry->setUseDisplayList(false); mTrisGeometry->setVertexArray(mTrisVertices); mTrisGeometry->setDataVariance(osg::Object::DYNAMIC); mTrisGeometry->addPrimitiveSet(mTrisDrawArrays); mParentNode->addChild(mLinesGeometry); mParentNode->addChild(mTrisGeometry); auto* stateSet = new osg::StateSet; stateSet->setAttributeAndModes( new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE), osg::StateAttribute::ON); stateSet->setAttributeAndModes(new osg::PolygonOffset( SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0, SceneUtil::AutoDepth::isReversed() ? 1.0 : -1.0)); osg::ref_ptr<osg::Material> material = new osg::Material; material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE); stateSet->setAttribute(material); mLinesGeometry->setStateSet(stateSet); mTrisGeometry->setStateSet(stateSet); mShapesRoot = new osg::Group; mShapesRoot->setStateSet(stateSet); mShapesRoot->setDataVariance(osg::Object::DYNAMIC); mShapesRoot->setNodeMask(Mask_Debug); mParentNode->addChild(mShapesRoot); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(mLinesGeometry, "debug"); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(mTrisGeometry, "debug"); MWBase::Environment::get().getResourceSystem()->getSceneManager()->recreateShaders(mShapesRoot, "debug"); } } void DebugDrawer::destroyGeometry() { if (mLinesGeometry) { mParentNode->removeChild(mLinesGeometry); mParentNode->removeChild(mTrisGeometry); mParentNode->removeChild(mShapesRoot); mLinesGeometry = nullptr; mLinesVertices = nullptr; mLinesColors = nullptr; mLinesDrawArrays = nullptr; mTrisGeometry = nullptr; mTrisVertices = nullptr; mTrisDrawArrays = nullptr; } } DebugDrawer::~DebugDrawer() { destroyGeometry(); } void DebugDrawer::step() { if (mDebugOn) { mLinesVertices->clear(); mTrisVertices->clear(); mLinesColors->clear(); mShapesRoot->removeChildren(0, mShapesRoot->getNumChildren()); mWorld->debugDrawWorld(); showCollisions(); mLinesDrawArrays->setCount(mLinesVertices->size()); mTrisDrawArrays->setCount(mTrisVertices->size()); mLinesVertices->dirty(); mTrisVertices->dirty(); mLinesColors->dirty(); mLinesGeometry->dirtyBound(); mTrisGeometry->dirtyBound(); } } void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) { mLinesVertices->push_back(Misc::Convert::toOsg(from)); mLinesVertices->push_back(Misc::Convert::toOsg(to)); mLinesColors->push_back({ 1, 1, 1, 1 }); mLinesColors->push_back({ 1, 1, 1, 1 }); #if BT_BULLET_VERSION < 317 size_t size = mLinesVertices->size(); if (size >= 6 && (*mLinesVertices)[size - 1] == (*mLinesVertices)[size - 6] && (*mLinesVertices)[size - 2] == (*mLinesVertices)[size - 3] && (*mLinesVertices)[size - 4] == (*mLinesVertices)[size - 5]) { mTrisVertices->push_back(mLinesVertices->back()); mLinesVertices->pop_back(); mLinesColors->pop_back(); mTrisVertices->push_back(mLinesVertices->back()); mLinesVertices->pop_back(); mLinesColors->pop_back(); mLinesVertices->pop_back(); mLinesColors->pop_back(); mTrisVertices->push_back(mLinesVertices->back()); mLinesVertices->pop_back(); mLinesColors->pop_back(); mLinesVertices->pop_back(); mLinesColors->pop_back(); mLinesVertices->pop_back(); mLinesColors->pop_back(); } #endif } void DebugDrawer::drawTriangle( const btVector3& v0, const btVector3& v1, const btVector3& v2, const btVector3& color, btScalar) { mTrisVertices->push_back(Misc::Convert::toOsg(v0)); mTrisVertices->push_back(Misc::Convert::toOsg(v1)); mTrisVertices->push_back(Misc::Convert::toOsg(v2)); } void DebugDrawer::addCollision(const btVector3& orig, const btVector3& normal) { mCollisionViews.emplace_back(orig, normal); } void DebugDrawer::showCollisions() { const auto now = std::chrono::steady_clock::now(); for (auto& [from, to, created] : mCollisionViews) { if (now - created < std::chrono::seconds(2)) { mLinesVertices->push_back(Misc::Convert::toOsg(from)); mLinesVertices->push_back(Misc::Convert::toOsg(to)); mLinesColors->push_back({ 1, 0, 0, 1 }); mLinesColors->push_back({ 1, 0, 0, 1 }); } } mCollisionViews.erase( std::remove_if(mCollisionViews.begin(), mCollisionViews.end(), [&now](const CollisionView& view) { return now - view.mCreated >= std::chrono::seconds(2); }), mCollisionViews.end()); } void DebugDrawer::drawSphere(btScalar radius, const btTransform& transform, const btVector3& color) { auto* geom = new osg::ShapeDrawable(new osg::Sphere(Misc::Convert::toOsg(transform.getOrigin()), radius)); geom->setColor(osg::Vec4(1, 1, 1, 1)); mShapesRoot->addChild(geom); } void DebugDrawer::reportErrorWarning(const char* warningString) { Log(Debug::Warning) << warningString; } void DebugDrawer::setDebugMode(int isOn) { mDebugOn = (isOn != 0); if (!mDebugOn) destroyGeometry(); else createGeometry(); } int DebugDrawer::getDebugMode() const { return mDebugOn; } }
8,025
C++
.cpp
192
32.286458
120
0.625785
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,412
actoranimation.cpp
OpenMW_openmw/apps/openmw/mwrender/actoranimation.cpp
#include "actoranimation.hpp" #include <utility> #include <osg/Group> #include <osg/Node> #include <osg/Vec4f> #include <components/esm3/loadbody.hpp> #include <components/esm3/loadcell.hpp> #include <components/esm3/loadligh.hpp> #include <components/resource/resourcesystem.hpp> #include <components/resource/scenemanager.hpp> #include <components/sceneutil/attach.hpp> #include <components/sceneutil/lightcommon.hpp> #include <components/sceneutil/lightmanager.hpp> #include <components/sceneutil/lightutil.hpp> #include <components/sceneutil/visitor.hpp> #include <components/misc/resourcehelpers.hpp> #include <components/settings/values.hpp> #include <components/vfs/manager.hpp> #include "../mwbase/environment.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/drawstate.hpp" #include "../mwmechanics/weapontype.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwworld/inventorystore.hpp" #include "../mwworld/ptr.hpp" #include "actorutil.hpp" #include "vismask.hpp" namespace MWRender { ActorAnimation::ActorAnimation( const MWWorld::Ptr& ptr, osg::ref_ptr<osg::Group> parentNode, Resource::ResourceSystem* resourceSystem) : Animation(ptr, std::move(parentNode), resourceSystem) { MWWorld::ContainerStore& store = mPtr.getClass().getContainerStore(mPtr); for (MWWorld::ConstContainerStoreIterator iter = store.cbegin(MWWorld::ContainerStore::Type_Light); iter != store.cend(); ++iter) { const ESM::Light* light = iter->get<ESM::Light>()->mBase; if (!(light->mData.mFlags & ESM::Light::Carry)) { addHiddenItemLight(*iter, light); } } // Make sure we cleaned object from effects, just in cast if we re-use node removeEffects(); } ActorAnimation::~ActorAnimation() { removeFromSceneImpl(); } PartHolderPtr ActorAnimation::attachMesh( VFS::Path::NormalizedView model, std::string_view bonename, const osg::Vec4f* glowColor) { osg::Group* parent = getBoneByName(bonename); if (!parent) return nullptr; osg::ref_ptr<osg::Node> instance = mResourceSystem->getSceneManager()->getInstance(model, parent); const NodeMap& nodeMap = getNodeMap(); NodeMap::const_iterator found = nodeMap.find(bonename); if (found == nodeMap.end()) return {}; if (glowColor != nullptr) mGlowUpdater = SceneUtil::addEnchantedGlow(instance, mResourceSystem, *glowColor); return std::make_unique<PartHolder>(instance); } osg::ref_ptr<osg::Node> ActorAnimation::attach( VFS::Path::NormalizedView model, std::string_view bonename, std::string_view bonefilter, bool isLight) { osg::ref_ptr<const osg::Node> templateNode = mResourceSystem->getSceneManager()->getTemplate(model); const NodeMap& nodeMap = getNodeMap(); auto found = nodeMap.find(bonename); if (found == nodeMap.end()) throw std::runtime_error("Can't find attachment node " + std::string{ bonename }); if (isLight) { osg::Quat rotation(osg::DegreesToRadians(-90.f), osg::Vec3f(1, 0, 0)); return SceneUtil::attach( templateNode, mObjectRoot, bonefilter, found->second, mResourceSystem->getSceneManager(), &rotation); } return SceneUtil::attach( std::move(templateNode), mObjectRoot, bonefilter, found->second, mResourceSystem->getSceneManager()); } std::string ActorAnimation::getShieldMesh(const MWWorld::ConstPtr& shield, bool female) const { const ESM::Armor* armor = shield.get<ESM::Armor>()->mBase; const std::vector<ESM::PartReference>& bodyparts = armor->mParts.mParts; // Try to recover the body part model, use ground model as a fallback otherwise. if (!bodyparts.empty()) { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); const MWWorld::Store<ESM::BodyPart>& partStore = store.get<ESM::BodyPart>(); for (const auto& part : bodyparts) { if (part.mPart != ESM::PRT_Shield) continue; const ESM::RefId* bodypartName = nullptr; if (female && !part.mFemale.empty()) bodypartName = &part.mFemale; else if (!part.mMale.empty()) bodypartName = &part.mMale; if (bodypartName && !bodypartName->empty()) { const ESM::BodyPart* bodypart = partStore.search(*bodypartName); if (bodypart == nullptr || bodypart->mData.mType != ESM::BodyPart::MT_Armor) return std::string(); if (!bodypart->mModel.empty()) return Misc::ResourceHelpers::correctMeshPath(bodypart->mModel); } } } return shield.getClass().getCorrectedModel(shield); } std::string ActorAnimation::getSheathedShieldMesh(const MWWorld::ConstPtr& shield) const { std::string mesh = getShieldMesh(shield, false); if (mesh.empty()) return mesh; const VFS::Path::Normalized holsteredName(addSuffixBeforeExtension(mesh, "_sh")); if (mResourceSystem->getVFS()->exists(holsteredName)) { osg::ref_ptr<osg::Node> shieldTemplate = mResourceSystem->getSceneManager()->getInstance(holsteredName); SceneUtil::FindByNameVisitor findVisitor("Bip01 Sheath"); shieldTemplate->accept(findVisitor); osg::ref_ptr<osg::Node> sheathNode = findVisitor.mFoundNode; if (!sheathNode) return std::string(); } return mesh; } bool ActorAnimation::updateCarriedLeftVisible(const int weaptype) const { if (Settings::game().mShieldSheathing) { const MWWorld::Class& cls = mPtr.getClass(); MWMechanics::CreatureStats& stats = cls.getCreatureStats(mPtr); if (cls.hasInventoryStore(mPtr) && stats.getDrawState() == MWMechanics::DrawState::Nothing) { SceneUtil::FindByNameVisitor findVisitor("Bip01 AttachShield"); mObjectRoot->accept(findVisitor); if (findVisitor.mFoundNode) { const MWWorld::InventoryStore& inv = cls.getInventoryStore(mPtr); const MWWorld::ConstContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (shield != inv.end() && shield->getType() == ESM::Armor::sRecordId && !getSheathedShieldMesh(*shield).empty()) return false; } } } return !(MWMechanics::getWeaponType(weaptype)->mFlags & ESM::WeaponType::TwoHanded); } void ActorAnimation::updateHolsteredShield(bool showCarriedLeft) { if (!Settings::game().mShieldSheathing) return; if (!mPtr.getClass().hasInventoryStore(mPtr)) return; mHolsteredShield.reset(); if (showCarriedLeft) return; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (shield == inv.end() || shield->getType() != ESM::Armor::sRecordId) return; // Can not show holdstered shields with two-handed weapons at all const MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end()) return; auto type = weapon->getType(); if (type == ESM::Weapon::sRecordId) { const MWWorld::LiveCellRef<ESM::Weapon>* ref = weapon->get<ESM::Weapon>(); ESM::Weapon::Type weaponType = (ESM::Weapon::Type)ref->mBase->mData.mType; if (MWMechanics::getWeaponType(weaponType)->mFlags & ESM::WeaponType::TwoHanded) return; } const VFS::Path::Normalized mesh = getSheathedShieldMesh(*shield); if (mesh.empty()) return; constexpr std::string_view boneName = "Bip01 AttachShield"; const bool isEnchanted = !shield->getClass().getEnchantment(*shield).empty(); const osg::Vec4f glowColor = isEnchanted ? shield->getClass().getEnchantmentColor(*shield) : osg::Vec4f(); const VFS::Path::Normalized holsteredName = addSuffixBeforeExtension(mesh, "_sh"); // If we have no dedicated sheath model, use basic shield model as fallback. if (!mResourceSystem->getVFS()->exists(holsteredName)) mHolsteredShield = attachMesh(mesh, boneName, isEnchanted ? &glowColor : nullptr); else mHolsteredShield = attachMesh(holsteredName, boneName, isEnchanted ? &glowColor : nullptr); if (!mHolsteredShield) return; SceneUtil::FindByNameVisitor findVisitor("Bip01 Sheath"); mHolsteredShield->getNode()->accept(findVisitor); osg::Group* shieldNode = findVisitor.mFoundNode; // If mesh author declared an empty sheath node, use transformation from this node, but use the common shield // mesh. This approach allows to tweak shield position without need to store the whole shield mesh in the _sh // file. if (shieldNode && !shieldNode->getNumChildren()) { osg::ref_ptr<osg::Node> fallbackNode = mResourceSystem->getSceneManager()->getInstance(mesh, shieldNode); if (isEnchanted) SceneUtil::addEnchantedGlow(shieldNode, mResourceSystem, glowColor); } } bool ActorAnimation::useShieldAnimations() const { if (!Settings::game().mShieldSheathing) return false; const MWWorld::Class& cls = mPtr.getClass(); if (!cls.hasInventoryStore(mPtr)) return false; if (getTextKeyTime("shield: equip attach") < 0 || getTextKeyTime("shield: unequip detach") < 0) return false; const MWWorld::InventoryStore& inv = cls.getInventoryStore(mPtr); const MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); const MWWorld::ConstContainerStoreIterator shield = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedLeft); if (weapon != inv.end() && shield != inv.end() && shield->getType() == ESM::Armor::sRecordId && !getSheathedShieldMesh(*shield).empty()) { auto type = weapon->getType(); if (type == ESM::Weapon::sRecordId) { const MWWorld::LiveCellRef<ESM::Weapon>* ref = weapon->get<ESM::Weapon>(); ESM::Weapon::Type weaponType = (ESM::Weapon::Type)ref->mBase->mData.mType; return !(MWMechanics::getWeaponType(weaponType)->mFlags & ESM::WeaponType::TwoHanded); } else if (type == ESM::Lockpick::sRecordId || type == ESM::Probe::sRecordId) return true; } return false; } osg::Group* ActorAnimation::getBoneByName(std::string_view boneName) const { if (!mObjectRoot) return nullptr; SceneUtil::FindByNameVisitor findVisitor(boneName); mObjectRoot->accept(findVisitor); return findVisitor.mFoundNode; } std::string_view ActorAnimation::getHolsteredWeaponBoneName(const MWWorld::ConstPtr& weapon) { if (weapon.isEmpty()) return {}; auto type = weapon.getClass().getType(); if (type == ESM::Weapon::sRecordId) { const MWWorld::LiveCellRef<ESM::Weapon>* ref = weapon.get<ESM::Weapon>(); int weaponType = ref->mBase->mData.mType; return MWMechanics::getWeaponType(weaponType)->mSheathingBone; } return {}; } void ActorAnimation::resetControllers(osg::Node* node) { if (node == nullptr) return; // This is used to avoid playing animations intended for equipped weapons on holstered weapons. SceneUtil::ForceControllerSourcesVisitor removeVisitor(std::make_shared<NullAnimationTime>()); node->accept(removeVisitor); } void ActorAnimation::updateHolsteredWeapon(bool showHolsteredWeapons) { if (!Settings::game().mWeaponSheathing) return; if (!mPtr.getClass().hasInventoryStore(mPtr)) return; mScabbard.reset(); const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return; // Since throwing weapons stack themselves, do not show such weapon itself int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; auto weaponClass = MWMechanics::getWeaponType(type)->mWeaponClass; if (weaponClass == ESM::WeaponType::Thrown) showHolsteredWeapons = false; const VFS::Path::Normalized mesh = weapon->getClass().getCorrectedModel(*weapon); if (mesh.empty()) return; const std::string_view boneName = getHolsteredWeaponBoneName(*weapon); if (boneName.empty()) return; // If the scabbard is not found, use the weapon mesh as fallback. const VFS::Path::Normalized scabbardName = addSuffixBeforeExtension(mesh, "_sh"); const bool isEnchanted = !weapon->getClass().getEnchantment(*weapon).empty(); if (!mResourceSystem->getVFS()->exists(scabbardName)) { if (showHolsteredWeapons) { const osg::Vec4f glowColor = isEnchanted ? weapon->getClass().getEnchantmentColor(*weapon) : osg::Vec4f(); mScabbard = attachMesh(mesh, boneName, isEnchanted ? &glowColor : nullptr); if (mScabbard && weaponClass == ESM::WeaponType::Ranged) resetControllers(mScabbard->getNode()); } return; } mScabbard = attachMesh(scabbardName, boneName); if (mScabbard && weaponClass == ESM::WeaponType::Ranged) resetControllers(mScabbard->getNode()); osg::Group* weaponNode = getBoneByName("Bip01 Weapon"); if (!weaponNode) return; // When we draw weapon, hide the Weapon node from sheath model. // Otherwise add the enchanted glow to it. if (!showHolsteredWeapons) { weaponNode->setNodeMask(0); } else { // If mesh author declared empty weapon node, use transformation from this node, but use the common weapon // mesh. This approach allows to tweak weapon position without need to store the whole weapon mesh in the // _sh file. if (!weaponNode->getNumChildren()) { osg::ref_ptr<osg::Node> fallbackNode = mResourceSystem->getSceneManager()->getInstance(mesh, weaponNode); if (weaponClass == ESM::WeaponType::Ranged) resetControllers(fallbackNode); } if (isEnchanted) { osg::Vec4f glowColor = weapon->getClass().getEnchantmentColor(*weapon); mGlowUpdater = SceneUtil::addEnchantedGlow(weaponNode, mResourceSystem, glowColor); } } } void ActorAnimation::updateQuiver() { if (!Settings::game().mWeaponSheathing) return; if (!mPtr.getClass().hasInventoryStore(mPtr)) return; const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return; std::string_view mesh = weapon->getClass().getModel(*weapon); std::string_view boneName = getHolsteredWeaponBoneName(*weapon); if (mesh.empty() || boneName.empty()) return; osg::Group* ammoNode = getBoneByName("Bip01 Ammo"); if (!ammoNode) return; // Special case for throwing weapons - they do not use ammo, but they stack themselves bool suitableAmmo = false; MWWorld::ConstContainerStoreIterator ammo = weapon; unsigned int ammoCount = 0; int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; const auto& weaponType = MWMechanics::getWeaponType(type); if (weaponType->mWeaponClass == ESM::WeaponType::Thrown) { ammoCount = ammo->getCellRef().getCount(); osg::Group* throwingWeaponNode = getBoneByName(weaponType->mAttachBone); if (throwingWeaponNode && throwingWeaponNode->getNumChildren()) ammoCount--; suitableAmmo = true; } else { ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo == inv.end()) return; ammoCount = ammo->getCellRef().getCount(); bool arrowAttached = isArrowAttached(); if (arrowAttached) ammoCount--; suitableAmmo = ammo->get<ESM::Weapon>()->mBase->mData.mType == weaponType->mAmmoType; } if (!suitableAmmo) return; // We should not show more ammo than equipped and more than quiver mesh has ammoCount = std::min(ammoCount, ammoNode->getNumChildren()); // Remove existing ammo nodes for (unsigned int i = 0; i < ammoNode->getNumChildren(); ++i) { osg::ref_ptr<osg::Group> arrowNode = ammoNode->getChild(i)->asGroup(); if (!arrowNode->getNumChildren()) continue; osg::ref_ptr<osg::Node> arrowChildNode = arrowNode->getChild(0); arrowNode->removeChild(arrowChildNode); } // Add new ones osg::Vec4f glowColor = ammo->getClass().getEnchantmentColor(*ammo); const VFS::Path::Normalized model(ammo->getClass().getCorrectedModel(*ammo)); for (unsigned int i = 0; i < ammoCount; ++i) { osg::ref_ptr<osg::Group> arrowNode = ammoNode->getChild(i)->asGroup(); osg::ref_ptr<osg::Node> arrow = mResourceSystem->getSceneManager()->getInstance(model, arrowNode); if (!ammo->getClass().getEnchantment(*ammo).empty()) mGlowUpdater = SceneUtil::addEnchantedGlow(std::move(arrow), mResourceSystem, glowColor); } } void ActorAnimation::itemAdded(const MWWorld::ConstPtr& item, int /*count*/) { if (item.getType() == ESM::Light::sRecordId) { const ESM::Light* light = item.get<ESM::Light>()->mBase; if (!(light->mData.mFlags & ESM::Light::Carry)) { addHiddenItemLight(item, light); } } if (!mPtr.getClass().hasInventoryStore(mPtr)) return; // If the count of equipped ammo or throwing weapon was changed, we should update quiver const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return; MWWorld::ConstContainerStoreIterator ammo = inv.end(); int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; if (MWMechanics::getWeaponType(type)->mWeaponClass == ESM::WeaponType::Thrown) ammo = weapon; else ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && item.getCellRef().getRefId() == ammo->getCellRef().getRefId()) updateQuiver(); } void ActorAnimation::itemRemoved(const MWWorld::ConstPtr& item, int /*count*/) { if (item.getType() == ESM::Light::sRecordId) { ItemLightMap::iterator iter = mItemLights.find(item); if (iter != mItemLights.end()) { if (!item.getCellRef().getCount()) { removeHiddenItemLight(item); } } } if (!mPtr.getClass().hasInventoryStore(mPtr)) return; // If the count of equipped ammo or throwing weapon was changed, we should update quiver const MWWorld::InventoryStore& inv = mPtr.getClass().getInventoryStore(mPtr); MWWorld::ConstContainerStoreIterator weapon = inv.getSlot(MWWorld::InventoryStore::Slot_CarriedRight); if (weapon == inv.end() || weapon->getType() != ESM::Weapon::sRecordId) return; MWWorld::ConstContainerStoreIterator ammo = inv.end(); int type = weapon->get<ESM::Weapon>()->mBase->mData.mType; if (MWMechanics::getWeaponType(type)->mWeaponClass == ESM::WeaponType::Thrown) ammo = weapon; else ammo = inv.getSlot(MWWorld::InventoryStore::Slot_Ammunition); if (ammo != inv.end() && item.getCellRef().getRefId() == ammo->getCellRef().getRefId()) updateQuiver(); } void ActorAnimation::addHiddenItemLight(const MWWorld::ConstPtr& item, const ESM::Light* esmLight) { if (mItemLights.find(item) != mItemLights.end()) return; bool exterior = mPtr.isInCell() && mPtr.getCell()->getCell()->isExterior(); osg::Vec4f ambient(1, 1, 1, 1); osg::ref_ptr<SceneUtil::LightSource> lightSource = SceneUtil::createLightSource(SceneUtil::LightCommon(*esmLight), Mask_Lighting, exterior, ambient); mInsert->addChild(lightSource); if (mLightListCallback && mPtr == MWMechanics::getPlayer()) mLightListCallback->getIgnoredLightSources().insert(lightSource.get()); mItemLights.insert(std::make_pair(item, lightSource)); } void ActorAnimation::removeHiddenItemLight(const MWWorld::ConstPtr& item) { ItemLightMap::iterator iter = mItemLights.find(item); if (iter == mItemLights.end()) return; if (mLightListCallback && mPtr == MWMechanics::getPlayer()) { std::set<SceneUtil::LightSource*>::iterator ignoredIter = mLightListCallback->getIgnoredLightSources().find(iter->second.get()); if (ignoredIter != mLightListCallback->getIgnoredLightSources().end()) mLightListCallback->getIgnoredLightSources().erase(ignoredIter); } mInsert->removeChild(iter->second); mItemLights.erase(iter); } void ActorAnimation::removeFromScene() { removeFromSceneImpl(); Animation::removeFromScene(); } void ActorAnimation::removeFromSceneImpl() { for (const auto& [k, v] : mItemLights) mInsert->removeChild(v); } }
23,515
C++
.cpp
491
37.527495
118
0.624984
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,413
rotatecontroller.cpp
OpenMW_openmw/apps/openmw/mwrender/rotatecontroller.cpp
#include "rotatecontroller.hpp" #include <osg/MatrixTransform> #include <osgAnimation/Bone> namespace MWRender { RotateController::RotateController(osg::Node* relativeTo) : mEnabled(true) , mRelativeTo(relativeTo) { } void RotateController::setEnabled(bool enabled) { mEnabled = enabled; } void RotateController::setRotate(const osg::Quat& rotate) { mRotate = rotate; } void RotateController::setOffset(const osg::Vec3f& offset) { mOffset = offset; } void RotateController::operator()(osg::MatrixTransform* node, osg::NodeVisitor* nv) { if (!mEnabled) { traverse(node, nv); return; } osg::Matrix matrix = node->getMatrix(); osg::Quat worldOrient; osg::NodePathList nodepaths = node->getParentalNodePaths(mRelativeTo); if (!nodepaths.empty()) { osg::Matrixf worldMat = osg::computeLocalToWorld(nodepaths[0]); worldOrient = worldMat.getRotate(); } osg::Quat worldOrientInverse = worldOrient.inverse(); osg::Quat orient = worldOrient * mRotate * worldOrientInverse * matrix.getRotate(); matrix.setRotate(orient); matrix.setTrans(matrix.getTrans() + worldOrientInverse * mOffset); node->setMatrix(matrix); // If we are linked to a bone we must call setMatrixInSkeletonSpace osgAnimation::Bone* b = dynamic_cast<osgAnimation::Bone*>(node); if (b) { osgAnimation::Bone* parent = b->getBoneParent(); if (parent) matrix *= parent->getMatrixInSkeletonSpace(); b->setMatrixInSkeletonSpace(matrix); } traverse(node, nv); } }
1,789
C++
.cpp
54
25.185185
91
0.625
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,414
animationextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/animationextensions.cpp
#include "animationextensions.hpp" #include <limits> #include <stdexcept> #include <components/compiler/opcodes.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "ref.hpp" namespace MWScript { namespace Animation { template <class R> class OpSkipAnim : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWBase::Environment::get().getMechanicsManager()->skipAnimation(ptr); } }; template <class R> class OpPlayAnim : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getRefData().isEnabled()) return; std::string_view group = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); Interpreter::Type_Integer mode = 0; if (arg0 == 1) { mode = runtime[0].mInteger; runtime.pop(); if (mode < 0 || mode > 2) throw std::runtime_error("animation mode out of range"); } MWBase::Environment::get().getMechanicsManager()->playAnimationGroup( ptr, group, mode, std::numeric_limits<uint32_t>::max(), true); } }; template <class R> class OpLoopAnim : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getRefData().isEnabled()) return; std::string_view group = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); Interpreter::Type_Integer loops = runtime[0].mInteger; runtime.pop(); if (loops < 0) throw std::runtime_error("number of animation loops must be non-negative"); Interpreter::Type_Integer mode = 0; if (arg0 == 1) { mode = runtime[0].mInteger; runtime.pop(); if (mode < 0 || mode > 2) throw std::runtime_error("animation mode out of range"); } MWBase::Environment::get().getMechanicsManager()->playAnimationGroup(ptr, group, mode, loops, true); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment5<OpSkipAnim<ImplicitRef>>(Compiler::Animation::opcodeSkipAnim); interpreter.installSegment5<OpSkipAnim<ExplicitRef>>(Compiler::Animation::opcodeSkipAnimExplicit); interpreter.installSegment3<OpPlayAnim<ImplicitRef>>(Compiler::Animation::opcodePlayAnim); interpreter.installSegment3<OpPlayAnim<ExplicitRef>>(Compiler::Animation::opcodePlayAnimExplicit); interpreter.installSegment3<OpLoopAnim<ImplicitRef>>(Compiler::Animation::opcodeLoopAnim); interpreter.installSegment3<OpLoopAnim<ExplicitRef>>(Compiler::Animation::opcodeLoopAnimExplicit); } } }
3,645
C++
.cpp
84
30.77381
116
0.578739
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,416
userextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/userextensions.cpp
#include "userextensions.hpp" #include <components/compiler/opcodes.hpp> #include <components/interpreter/context.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "ref.hpp" namespace MWScript { /// Temporary script extensions. /// /// \attention Do not commit changes to this file to a git repository! namespace User { class OpUser1 : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.getContext().report("user1: not in use"); } }; class OpUser2 : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.getContext().report("user2: not in use"); } }; template <class R> class OpUser3 : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { // MWWorld::Ptr ptr = R()(runtime); runtime.getContext().report("user3: not in use"); } }; template <class R> class OpUser4 : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { // MWWorld::Ptr ptr = R()(runtime); runtime.getContext().report("user4: not in use"); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment5<OpUser1>(Compiler::User::opcodeUser1); interpreter.installSegment5<OpUser2>(Compiler::User::opcodeUser2); interpreter.installSegment5<OpUser3<ImplicitRef>>(Compiler::User::opcodeUser3); interpreter.installSegment5<OpUser3<ExplicitRef>>(Compiler::User::opcodeUser3Explicit); interpreter.installSegment5<OpUser4<ImplicitRef>>(Compiler::User::opcodeUser4); interpreter.installSegment5<OpUser4<ExplicitRef>>(Compiler::User::opcodeUser4Explicit); } } }
2,201
C++
.cpp
55
31.127273
118
0.627809
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
35,417
dialogueextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/dialogueextensions.cpp
#include "dialogueextensions.hpp" #include <components/compiler/extensions.hpp> #include <components/compiler/opcodes.hpp> #include <components/debug/debuglog.hpp> #include <components/interpreter/context.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwbase/dialoguemanager.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/journal.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwmechanics/npcstats.hpp" #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "ref.hpp" namespace MWScript { namespace Dialogue { template <class R> class OpJournal : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime, false); // required=false if (ptr.isEmpty()) ptr = MWBase::Environment::get().getWorld()->getPlayerPtr(); ESM::RefId quest = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Integer index = runtime[0].mInteger; runtime.pop(); // Invoking Journal with a non-existing index is allowed, and triggers no errors. Seriously? :( try { MWBase::Environment::get().getJournal()->addEntry(quest, index, ptr); } catch (...) { if (MWBase::Environment::get().getJournal()->getJournalIndex(quest) < index) MWBase::Environment::get().getJournal()->setJournalIndex(quest, index); } } }; class OpSetJournalIndex : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId quest = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Integer index = runtime[0].mInteger; runtime.pop(); MWBase::Environment::get().getJournal()->setJournalIndex(quest, index); } }; class OpGetJournalIndex : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId quest = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); int index = MWBase::Environment::get().getJournal()->getJournalIndex(quest); runtime.push(index); } }; class OpAddTopic : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId topic = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); if (!MWBase::Environment::get().getESMStore()->get<ESM::Dialogue>().search(topic)) { runtime.getContext().report( "Failed to add topic '" + topic.getRefIdString() + "': topic record not found"); return; } MWBase::Environment::get().getDialogueManager()->addTopic(topic); } }; class OpChoice : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWBase::DialogueManager* dialogue = MWBase::Environment::get().getDialogueManager(); while (arg0 > 0) { std::string_view question = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); arg0 = arg0 - 1; Interpreter::Type_Integer choice = 1; if (arg0 > 0) { choice = runtime[0].mInteger; runtime.pop(); arg0 = arg0 - 1; } dialogue->addChoice(question, choice); } } }; template <class R> class OpForceGreeting : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getRefData().isEnabled()) return; if (!ptr.getClass().isActor()) { const std::string error = "Warning: \"forcegreeting\" command works only for actors."; runtime.getContext().report(error); Log(Debug::Warning) << error; return; } bool greetWerewolves = false; const ESM::RefId& script = ptr.getClass().getScript(ptr); if (!script.empty()) greetWerewolves = ptr.getRefData().getLocals().hasVar(script, "allowwerewolfforcegreeting"); const MWWorld::Ptr& player = MWBase::Environment::get().getWorld()->getPlayerPtr(); if (player.getClass().getNpcStats(player).isWerewolf() && !greetWerewolves) return; MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_Dialogue, ptr); } }; class OpGoodbye : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getDialogueManager()->goodbye(); } }; template <class R> class OpModReputation : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); ptr.getClass().getNpcStats(ptr).setReputation(ptr.getClass().getNpcStats(ptr).getReputation() + value); } }; template <class R> class OpSetReputation : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); ptr.getClass().getNpcStats(ptr).setReputation(value); } }; template <class R> class OpGetReputation : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); runtime.push(ptr.getClass().getNpcStats(ptr).getReputation()); } }; template <class R> class OpSameFaction : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWWorld::Ptr player = MWBase::Environment::get().getWorld()->getPlayerPtr(); runtime.push(player.getClass().getNpcStats(player).isInFaction(ptr.getClass().getPrimaryFaction(ptr))); } }; class OpModFactionReaction : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId faction1 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); ESM::RefId faction2 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); int modReaction = runtime[0].mInteger; runtime.pop(); MWBase::Environment::get().getDialogueManager()->modFactionReaction(faction1, faction2, modReaction); } }; class OpGetFactionReaction : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId faction1 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); ESM::RefId faction2 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); runtime.push(MWBase::Environment::get().getDialogueManager()->getFactionReaction(faction1, faction2)); } }; class OpSetFactionReaction : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId faction1 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); ESM::RefId faction2 = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); int newValue = runtime[0].mInteger; runtime.pop(); MWBase::Environment::get().getDialogueManager()->setFactionReaction(faction1, faction2, newValue); } }; template <class R> class OpClearInfoActor : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWBase::Environment::get().getDialogueManager()->clearInfoActor(ptr); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment5<OpJournal<ImplicitRef>>(Compiler::Dialogue::opcodeJournal); interpreter.installSegment5<OpJournal<ExplicitRef>>(Compiler::Dialogue::opcodeJournalExplicit); interpreter.installSegment5<OpSetJournalIndex>(Compiler::Dialogue::opcodeSetJournalIndex); interpreter.installSegment5<OpGetJournalIndex>(Compiler::Dialogue::opcodeGetJournalIndex); interpreter.installSegment5<OpAddTopic>(Compiler::Dialogue::opcodeAddTopic); interpreter.installSegment3<OpChoice>(Compiler::Dialogue::opcodeChoice); interpreter.installSegment5<OpForceGreeting<ImplicitRef>>(Compiler::Dialogue::opcodeForceGreeting); interpreter.installSegment5<OpForceGreeting<ExplicitRef>>(Compiler::Dialogue::opcodeForceGreetingExplicit); interpreter.installSegment5<OpGoodbye>(Compiler::Dialogue::opcodeGoodbye); interpreter.installSegment5<OpGetReputation<ImplicitRef>>(Compiler::Dialogue::opcodeGetReputation); interpreter.installSegment5<OpSetReputation<ImplicitRef>>(Compiler::Dialogue::opcodeSetReputation); interpreter.installSegment5<OpModReputation<ImplicitRef>>(Compiler::Dialogue::opcodeModReputation); interpreter.installSegment5<OpSetReputation<ExplicitRef>>(Compiler::Dialogue::opcodeSetReputationExplicit); interpreter.installSegment5<OpModReputation<ExplicitRef>>(Compiler::Dialogue::opcodeModReputationExplicit); interpreter.installSegment5<OpGetReputation<ExplicitRef>>(Compiler::Dialogue::opcodeGetReputationExplicit); interpreter.installSegment5<OpSameFaction<ImplicitRef>>(Compiler::Dialogue::opcodeSameFaction); interpreter.installSegment5<OpSameFaction<ExplicitRef>>(Compiler::Dialogue::opcodeSameFactionExplicit); interpreter.installSegment5<OpModFactionReaction>(Compiler::Dialogue::opcodeModFactionReaction); interpreter.installSegment5<OpSetFactionReaction>(Compiler::Dialogue::opcodeSetFactionReaction); interpreter.installSegment5<OpGetFactionReaction>(Compiler::Dialogue::opcodeGetFactionReaction); interpreter.installSegment5<OpClearInfoActor<ImplicitRef>>(Compiler::Dialogue::opcodeClearInfoActor); interpreter.installSegment5<OpClearInfoActor<ExplicitRef>>( Compiler::Dialogue::opcodeClearInfoActorExplicit); } } }
12,558
C++
.cpp
264
34.412879
119
0.59657
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,418
extensions.cpp
OpenMW_openmw/apps/openmw/mwscript/extensions.cpp
#include "extensions.hpp" #include <components/interpreter/installopcodes.hpp> #include <components/interpreter/interpreter.hpp> #include "aiextensions.hpp" #include "animationextensions.hpp" #include "cellextensions.hpp" #include "consoleextensions.hpp" #include "containerextensions.hpp" #include "controlextensions.hpp" #include "dialogueextensions.hpp" #include "guiextensions.hpp" #include "miscextensions.hpp" #include "skyextensions.hpp" #include "soundextensions.hpp" #include "statsextensions.hpp" #include "transformationextensions.hpp" #include "userextensions.hpp" namespace MWScript { void installOpcodes(Interpreter::Interpreter& interpreter, bool consoleOnly) { Interpreter::installOpcodes(interpreter); Cell::installOpcodes(interpreter); Misc::installOpcodes(interpreter); Gui::installOpcodes(interpreter); Sound::installOpcodes(interpreter); Sky::installOpcodes(interpreter); Stats::installOpcodes(interpreter); Container::installOpcodes(interpreter); Ai::installOpcodes(interpreter); Control::installOpcodes(interpreter); Dialogue::installOpcodes(interpreter); Animation::installOpcodes(interpreter); Transformation::installOpcodes(interpreter); if (consoleOnly) { Console::installOpcodes(interpreter); User::installOpcodes(interpreter); } } }
1,430
C++
.cpp
41
29.780488
80
0.748736
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
35,419
interpretercontext.cpp
OpenMW_openmw/apps/openmw/mwscript/interpretercontext.cpp
#include "interpretercontext.hpp" #include <cmath> #include <sstream> #include <components/compiler/locals.hpp> #include <components/esm/records.hpp> #include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/inputmanager.hpp" #include "../mwbase/scriptmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/action.hpp" #include "../mwworld/cellstore.hpp" #include "../mwworld/class.hpp" #include "../mwmechanics/npcstats.hpp" #include "globalscripts.hpp" #include "locals.hpp" namespace MWScript { const MWWorld::Ptr InterpreterContext::getReferenceImp(const ESM::RefId& id, bool activeOnly, bool doThrow) const { if (!id.empty()) { return MWBase::Environment::get().getWorld()->getPtr(id, activeOnly); } else { if (mReference.isEmpty() && mGlobalScriptDesc) mReference = mGlobalScriptDesc->getPtr(); if (mReference.isEmpty() && doThrow) throw MissingImplicitRefError(); return mReference; } } const Locals& InterpreterContext::getMemberLocals(bool global, ESM::RefId& id) const { if (global) { return MWBase::Environment::get().getScriptManager()->getGlobalScripts().getLocals(id); } else { const MWWorld::Ptr ptr = getReferenceImp(id, false); id = ptr.getClass().getScript(ptr); ptr.getRefData().setLocals(*MWBase::Environment::get().getESMStore()->get<ESM::Script>().find(id)); return ptr.getRefData().getLocals(); } } Locals& InterpreterContext::getMemberLocals(bool global, ESM::RefId& id) { if (global) { return MWBase::Environment::get().getScriptManager()->getGlobalScripts().getLocals(id); } else { const MWWorld::Ptr ptr = getReferenceImp(id, false); id = ptr.getClass().getScript(ptr); ptr.getRefData().setLocals(*MWBase::Environment::get().getESMStore()->get<ESM::Script>().find(id)); return ptr.getRefData().getLocals(); } } MissingImplicitRefError::MissingImplicitRefError() : std::runtime_error("no implicit reference") { } int InterpreterContext::findLocalVariableIndex(const ESM::RefId& scriptId, std::string_view name, char type) const { int index = MWBase::Environment::get().getScriptManager()->getLocals(scriptId).searchIndex(type, name); if (index != -1) return index; std::ostringstream stream; stream << "Failed to access "; switch (type) { case 's': stream << "short"; break; case 'l': stream << "long"; break; case 'f': stream << "float"; break; } stream << " member variable " << name << " in script " << scriptId; throw std::runtime_error(stream.str().c_str()); } InterpreterContext::InterpreterContext(MWScript::Locals* locals, const MWWorld::Ptr& reference) : mLocals(locals) , mReference(reference) { } InterpreterContext::InterpreterContext(std::shared_ptr<GlobalScriptDesc> globalScriptDesc) : mLocals(&(globalScriptDesc->mLocals)) { const MWWorld::Ptr* ptr = globalScriptDesc->getPtrIfPresent(); // A nullptr here signifies that the script's target has not yet been resolved after loading the game. // Script targets are lazily resolved to MWWorld::Ptrs (which can, upon resolution, be empty) // because scripts started through dialogue often don't use their implicit target. if (ptr) mReference = *ptr; else mGlobalScriptDesc = globalScriptDesc; } ESM::RefId InterpreterContext::getTarget() const { if (!mReference.isEmpty()) return mReference.mRef->mRef.getRefId(); else if (mGlobalScriptDesc) return mGlobalScriptDesc->getId(); return ESM::RefId(); } int InterpreterContext::getLocalShort(int index) const { if (!mLocals) throw std::runtime_error("local variables not available in this context"); return mLocals->mShorts.at(index); } int InterpreterContext::getLocalLong(int index) const { if (!mLocals) throw std::runtime_error("local variables not available in this context"); return mLocals->mLongs.at(index); } float InterpreterContext::getLocalFloat(int index) const { if (!mLocals) throw std::runtime_error("local variables not available in this context"); return mLocals->mFloats.at(index); } void InterpreterContext::setLocalShort(int index, int value) { if (!mLocals) throw std::runtime_error("local variables not available in this context"); mLocals->mShorts.at(index) = value; } void InterpreterContext::setLocalLong(int index, int value) { if (!mLocals) throw std::runtime_error("local variables not available in this context"); mLocals->mLongs.at(index) = value; } void InterpreterContext::setLocalFloat(int index, float value) { if (!mLocals) throw std::runtime_error("local variables not available in this context"); mLocals->mFloats.at(index) = value; } void InterpreterContext::messageBox(std::string_view message, const std::vector<std::string>& buttons) { if (buttons.empty()) MWBase::Environment::get().getWindowManager()->messageBox(message); else MWBase::Environment::get().getWindowManager()->interactiveMessageBox(message, buttons); } void InterpreterContext::report(const std::string& message) {} int InterpreterContext::getGlobalShort(std::string_view name) const { return MWBase::Environment::get().getWorld()->getGlobalInt(name); } int InterpreterContext::getGlobalLong(std::string_view name) const { // a global long is internally a float. return MWBase::Environment::get().getWorld()->getGlobalInt(name); } float InterpreterContext::getGlobalFloat(std::string_view name) const { return MWBase::Environment::get().getWorld()->getGlobalFloat(name); } void InterpreterContext::setGlobalShort(std::string_view name, int value) { MWBase::Environment::get().getWorld()->setGlobalInt(name, value); } void InterpreterContext::setGlobalLong(std::string_view name, int value) { MWBase::Environment::get().getWorld()->setGlobalInt(name, value); } void InterpreterContext::setGlobalFloat(std::string_view name, float value) { MWBase::Environment::get().getWorld()->setGlobalFloat(name, value); } std::vector<std::string> InterpreterContext::getGlobals() const { const MWWorld::Store<ESM::Global>& globals = MWBase::Environment::get().getESMStore()->get<ESM::Global>(); std::vector<std::string> ids; for (const auto& globalVariable : globals) { ids.emplace_back(globalVariable.mId.getRefIdString()); } return ids; } char InterpreterContext::getGlobalType(std::string_view name) const { MWBase::World* world = MWBase::Environment::get().getWorld(); return world->getGlobalVariableType(name); } std::string InterpreterContext::getActionBinding(std::string_view targetAction) const { MWBase::InputManager* input = MWBase::Environment::get().getInputManager(); const auto& actions = input->getActionKeySorting(); for (const int action : actions) { std::string_view desc = input->getActionDescription(action); if (desc.empty()) continue; if (desc == targetAction) { if (input->joystickLastUsed()) return input->getActionControllerBindingName(action); else return input->getActionKeyBindingName(action); } } return "None"; } std::string_view InterpreterContext::getActorName() const { const MWWorld::Ptr& ptr = getReferenceImp(); if (ptr.getClass().isNpc()) { const ESM::NPC* npc = ptr.get<ESM::NPC>()->mBase; return npc->mName; } const ESM::Creature* creature = ptr.get<ESM::Creature>()->mBase; return creature->mName; } std::string_view InterpreterContext::getNPCRace() const { const ESM::NPC* npc = getReferenceImp().get<ESM::NPC>()->mBase; const ESM::Race* race = MWBase::Environment::get().getESMStore()->get<ESM::Race>().find(npc->mRace); return race->mName; } std::string_view InterpreterContext::getNPCClass() const { const ESM::NPC* npc = getReferenceImp().get<ESM::NPC>()->mBase; const ESM::Class* class_ = MWBase::Environment::get().getESMStore()->get<ESM::Class>().find(npc->mClass); return class_->mName; } std::string_view InterpreterContext::getNPCFaction() const { const ESM::NPC* npc = getReferenceImp().get<ESM::NPC>()->mBase; const ESM::Faction* faction = MWBase::Environment::get().getESMStore()->get<ESM::Faction>().find(npc->mFaction); return faction->mName; } std::string_view InterpreterContext::getNPCRank() const { const MWWorld::Ptr& ptr = getReferenceImp(); const ESM::RefId& faction = ptr.getClass().getPrimaryFaction(ptr); if (faction.empty()) throw std::runtime_error("getNPCRank(): NPC is not in a faction"); int rank = ptr.getClass().getPrimaryFactionRank(ptr); if (rank < 0 || rank > 9) throw std::runtime_error("getNPCRank(): invalid rank"); MWBase::World* world = MWBase::Environment::get().getWorld(); const MWWorld::ESMStore& store = world->getStore(); const ESM::Faction* fact = store.get<ESM::Faction>().find(faction); return fact->mRanks[rank]; } std::string_view InterpreterContext::getPCName() const { MWBase::World* world = MWBase::Environment::get().getWorld(); return world->getPlayerPtr().get<ESM::NPC>()->mBase->mName; } std::string_view InterpreterContext::getPCRace() const { MWBase::World* world = MWBase::Environment::get().getWorld(); const ESM::RefId& race = world->getPlayerPtr().get<ESM::NPC>()->mBase->mRace; return world->getStore().get<ESM::Race>().find(race)->mName; } std::string_view InterpreterContext::getPCClass() const { MWBase::World* world = MWBase::Environment::get().getWorld(); const ESM::RefId& class_ = world->getPlayerPtr().get<ESM::NPC>()->mBase->mClass; return world->getStore().get<ESM::Class>().find(class_)->mName; } std::string_view InterpreterContext::getPCRank() const { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); const ESM::RefId& factionId = getReferenceImp().getClass().getPrimaryFaction(getReferenceImp()); if (factionId.empty()) throw std::runtime_error("getPCRank(): NPC is not in a faction"); const auto& ranks = player.getClass().getNpcStats(player).getFactionRanks(); auto it = ranks.find(factionId); int rank = -1; if (it != ranks.end()) rank = it->second; // If you are not in the faction, PcRank returns the first rank, for whatever reason. // This is used by the dialogue when joining the Thieves Guild in Balmora. if (rank == -1) rank = 0; const MWWorld::ESMStore& store = world->getStore(); const ESM::Faction* faction = store.get<ESM::Faction>().find(factionId); if (rank < 0 || rank > 9) // there are only 10 ranks return {}; return faction->mRanks[rank]; } std::string_view InterpreterContext::getPCNextRank() const { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); const ESM::RefId& factionId = getReferenceImp().getClass().getPrimaryFaction(getReferenceImp()); if (factionId.empty()) throw std::runtime_error("getPCNextRank(): NPC is not in a faction"); const auto& ranks = player.getClass().getNpcStats(player).getFactionRanks(); auto it = ranks.find(factionId); int rank = -1; if (it != ranks.end()) rank = it->second; ++rank; // Next rank // if we are already at max rank, there is no next rank if (rank > 9) rank = 9; const MWWorld::ESMStore& store = world->getStore(); const ESM::Faction* faction = store.get<ESM::Faction>().find(factionId); if (rank < 0) return {}; return faction->mRanks[rank]; } int InterpreterContext::getPCBounty() const { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); return player.getClass().getNpcStats(player).getBounty(); } std::string_view InterpreterContext::getCurrentCellName() const { return MWBase::Environment::get().getWorld()->getCellName(); } void InterpreterContext::executeActivation(const MWWorld::Ptr& ptr, const MWWorld::Ptr& actor) { // MWScripted activations don't go through Lua because 1-frame delay can brake mwscripts. #if 0 MWBase::Environment::get().getLuaManager()->objectActivated(ptr, actor); // TODO: Enable this branch after implementing one of the options: // 1) Pause this mwscript (or maybe all mwscripts) for one frame and continue from the same // command when the activation is processed by Lua script. // 2) Force Lua scripts to handle a zero-length extra frame right now, so when control // returns to the mwscript, the activation is already processed. #else std::unique_ptr<MWWorld::Action> action = (ptr.getClass().activate(ptr, actor)); action->execute(actor); if (action->getTarget() != MWWorld::Ptr() && action->getTarget() != ptr) { updatePtr(ptr, action->getTarget()); } #endif } int InterpreterContext::getMemberShort(ESM::RefId id, std::string_view name, bool global) const { const Locals& locals = getMemberLocals(global, id); return locals.mShorts[findLocalVariableIndex(id, name, 's')]; } int InterpreterContext::getMemberLong(ESM::RefId id, std::string_view name, bool global) const { const Locals& locals = getMemberLocals(global, id); return locals.mLongs[findLocalVariableIndex(id, name, 'l')]; } float InterpreterContext::getMemberFloat(ESM::RefId id, std::string_view name, bool global) const { const Locals& locals = getMemberLocals(global, id); return locals.mFloats[findLocalVariableIndex(id, name, 'f')]; } void InterpreterContext::setMemberShort(ESM::RefId id, std::string_view name, int value, bool global) { Locals& locals = getMemberLocals(global, id); locals.mShorts[findLocalVariableIndex(id, name, 's')] = value; } void InterpreterContext::setMemberLong(ESM::RefId id, std::string_view name, int value, bool global) { Locals& locals = getMemberLocals(global, id); locals.mLongs[findLocalVariableIndex(id, name, 'l')] = value; } void InterpreterContext::setMemberFloat(ESM::RefId id, std::string_view name, float value, bool global) { Locals& locals = getMemberLocals(global, id); locals.mFloats[findLocalVariableIndex(id, name, 'f')] = value; } MWWorld::Ptr InterpreterContext::getReference(bool required) const { return getReferenceImp({}, true, required); } void InterpreterContext::updatePtr(const MWWorld::Ptr& base, const MWWorld::Ptr& updated) { if (!mReference.isEmpty() && base == mReference) { mReference = updated; if (mLocals == &base.getRefData().getLocals()) mLocals = &mReference.getRefData().getLocals(); } } }
16,588
C++
.cpp
393
33.982188
120
0.634545
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,420
statsextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/statsextensions.cpp
#include "statsextensions.hpp" #include <cmath> #include <components/esm3/loadcrea.hpp> #include <components/esm3/loadnpc.hpp> #include "../mwworld/esmstore.hpp" #include <components/compiler/opcodes.hpp> #include <components/debug/debuglog.hpp> #include <components/esm3/loadfact.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include <components/esm3/loadmgef.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/statemanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/player.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwmechanics/npcstats.hpp" #include "ref.hpp" namespace { ESM::RefId getDialogueActorFaction(const MWWorld::ConstPtr& actor) { ESM::RefId factionId = actor.getClass().getPrimaryFaction(actor); if (factionId.empty()) throw std::runtime_error("failed to determine dialogue actors faction (because actor is factionless)"); return factionId; } void modStat(MWMechanics::AttributeValue& stat, float amount) { const float base = stat.getBase(); const float modifier = stat.getModifier() - stat.getDamage(); const float modified = base + modifier; // Clamp to 100 unless base < 100 and we have a fortification going if ((modifier <= 0.f || base >= 100.f) && amount > 0.f) amount = std::clamp(100.f - modified, 0.f, amount); // Clamp the modified value in a way that doesn't properly account for negative numbers float newModified = modified + amount; if (newModified < 0.f) { if (modified >= 0.f) newModified = 0.f; else if (newModified < modified) newModified = modified; } // Calculate damage/fortification based on the clamped base value stat.setBase(std::clamp(base + amount, 0.f, 100.f), true); stat.setModifier(newModified - stat.getBase()); } template <class T> void updateBaseRecord(MWWorld::Ptr& ptr) { const auto& store = *MWBase::Environment::get().getESMStore(); const T* base = store.get<T>().find(ptr.getCellRef().getRefId()); ptr.get<T>()->mBase = base; } } namespace MWScript { namespace Stats { template <class R> class OpGetLevel : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = -1; if (ptr.getClass().isActor()) value = ptr.getClass().getCreatureStats(ptr).getLevel(); runtime.push(value); } }; template <class R> class OpSetLevel : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); if (ptr.getClass().isActor()) ptr.getClass().getCreatureStats(ptr).setLevel(value); } }; template <class R> class OpGetAttribute : public Interpreter::Opcode0 { ESM::RefId mIndex; public: OpGetAttribute(ESM::RefId index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = 0.f; if (ptr.getClass().isActor()) value = ptr.getClass().getCreatureStats(ptr).getAttribute(mIndex).getModified(); runtime.push(value); } }; template <class R> class OpSetAttribute : public Interpreter::Opcode0 { ESM::RefId mIndex; public: OpSetAttribute(ESM::RefId index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::AttributeValue attribute = ptr.getClass().getCreatureStats(ptr).getAttribute(mIndex); attribute.setBase(value, true); ptr.getClass().getCreatureStats(ptr).setAttribute(mIndex, attribute); } }; template <class R> class OpModAttribute : public Interpreter::Opcode0 { ESM::RefId mIndex; public: OpModAttribute(ESM::RefId index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::AttributeValue attribute = ptr.getClass().getCreatureStats(ptr).getAttribute(mIndex); modStat(attribute, value); ptr.getClass().getCreatureStats(ptr).setAttribute(mIndex, attribute); } }; template <class R> class OpGetDynamic : public Interpreter::Opcode0 { int mIndex; public: OpGetDynamic(int index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = 0.f; if (mIndex == 0 && ptr.getClass().hasItemHealth(ptr)) { // health is a special case value = static_cast<Interpreter::Type_Float>(ptr.getClass().getItemMaxHealth(ptr)); } else if (ptr.getClass().isActor()) { value = ptr.getClass().getCreatureStats(ptr).getDynamic(mIndex).getCurrent(); // GetMagicka shouldn't return negative values if (mIndex == 1 && value < 0) value = 0; } runtime.push(value); } }; template <class R> class OpSetDynamic : public Interpreter::Opcode0 { int mIndex; public: OpSetDynamic(int index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::DynamicStat<float> stat(ptr.getClass().getCreatureStats(ptr).getDynamic(mIndex)); stat.setBase(value); stat.setCurrent(stat.getModified(false), true, true); ptr.getClass().getCreatureStats(ptr).setDynamic(mIndex, stat); } }; template <class R> class OpModDynamic : public Interpreter::Opcode0 { int mIndex; public: OpModDynamic(int index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { int peek = R::implicit ? 0 : runtime[0].mInteger; MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float diff = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isActor()) return; // workaround broken endgame scripts that kill dagoth ur if (!R::implicit && ptr.getCellRef().getRefId() == "dagoth_ur_1") { runtime.push(peek); if (R()(runtime, false, true).isEmpty()) { Log(Debug::Warning) << "Warning: Compensating for broken script in Morrowind.esm by " << "ignoring remote access to dagoth_ur_1"; return; } } MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); MWMechanics::DynamicStat<float> stat = stats.getDynamic(mIndex); float current = stat.getCurrent(); float base = diff + stat.getBase(); if (mIndex != 2) base = std::max(base, 0.f); stat.setBase(base); stat.setCurrent(diff + current, true, true); stats.setDynamic(mIndex, stat); } }; template <class R> class OpModCurrentDynamic : public Interpreter::Opcode0 { int mIndex; public: OpModCurrentDynamic(int index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float diff = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); Interpreter::Type_Float current = stats.getDynamic(mIndex).getCurrent(); MWMechanics::DynamicStat<float> stat(ptr.getClass().getCreatureStats(ptr).getDynamic(mIndex)); bool allowDecreaseBelowZero = false; if (mIndex == 2) // Fatigue-specific logic { // For fatigue, a negative current value is allowed and means the actor will be knocked down allowDecreaseBelowZero = true; // Knock down the actor immediately if a non-positive new value is the case if (diff + current <= 0.f) ptr.getClass().getCreatureStats(ptr).setKnockedDown(true); } stat.setCurrent(diff + current, allowDecreaseBelowZero); ptr.getClass().getCreatureStats(ptr).setDynamic(mIndex, stat); } }; template <class R> class OpGetDynamicGetRatio : public Interpreter::Opcode0 { int mIndex; public: OpGetDynamicGetRatio(int index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getClass().isActor()) { runtime.push(0.f); return; } const MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); runtime.push(stats.getDynamic(mIndex).getRatio(false)); } }; template <class R> class OpGetSkill : public Interpreter::Opcode0 { ESM::RefId mId; public: OpGetSkill(ESM::RefId id) : mId(id) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getClass().isActor()) { runtime.push(0.f); return; } Interpreter::Type_Float value = ptr.getClass().getSkill(ptr, mId); runtime.push(value); } }; template <class R> class OpSetSkill : public Interpreter::Opcode0 { ESM::RefId mId; public: OpSetSkill(ESM::RefId id) : mId(id) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isNpc()) return; MWMechanics::NpcStats& stats = ptr.getClass().getNpcStats(ptr); stats.getSkill(mId).setBase(value, true); } }; template <class R> class OpModSkill : public Interpreter::Opcode0 { ESM::RefId mId; public: OpModSkill(ESM::RefId id) : mId(id) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float value = runtime[0].mFloat; runtime.pop(); if (!ptr.getClass().isNpc()) return; MWMechanics::SkillValue& skill = ptr.getClass().getNpcStats(ptr).getSkill(mId); modStat(skill, value); } }; class OpGetPCCrimeLevel : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); runtime.push(static_cast<Interpreter::Type_Float>(player.getClass().getNpcStats(player).getBounty())); } }; class OpSetPCCrimeLevel : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); int bounty = static_cast<int>(runtime[0].mFloat); runtime.pop(); player.getClass().getNpcStats(player).setBounty(bounty); if (bounty == 0) MWBase::Environment::get().getWorld()->getPlayer().recordCrimeId(); } }; class OpModPCCrimeLevel : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::World* world = MWBase::Environment::get().getWorld(); MWWorld::Ptr player = world->getPlayerPtr(); int bounty = std::max( 0, static_cast<int>(runtime[0].mFloat) + player.getClass().getNpcStats(player).getBounty()); player.getClass().getNpcStats(player).setBounty(bounty); runtime.pop(); if (bounty == 0) MWBase::Environment::get().getWorld()->getPlayer().recordCrimeId(); } }; template <class R> class OpAddSpell : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); if (!ptr.getClass().isActor()) return; const ESM::Spell* spell = MWBase::Environment::get().getESMStore()->get<ESM::Spell>().find(id); MWMechanics::CreatureStats& creatureStats = ptr.getClass().getCreatureStats(ptr); creatureStats.getSpells().add(spell); ESM::Spell::SpellType type = static_cast<ESM::Spell::SpellType>(spell->mData.mType); if (type != ESM::Spell::ST_Spell && type != ESM::Spell::ST_Power) { // Add spell effect to *this actor's* queue immediately creatureStats.getActiveSpells().addSpell(spell, ptr); // Apply looping particles immediately for constant effects MWBase::Environment::get().getWorld()->applyLoopingParticles(ptr); } } }; template <class R> class OpRemoveSpell : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::CreatureStats& creatureStats = ptr.getClass().getCreatureStats(ptr); creatureStats.getSpells().remove(id); MWBase::WindowManager* wm = MWBase::Environment::get().getWindowManager(); if (ptr == MWMechanics::getPlayer() && id == wm->getSelectedSpell()) { wm->unsetSelectedSpell(); } } }; template <class R> class OpRemoveSpellEffects : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId spellid = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); if (ptr.getClass().isActor()) ptr.getClass().getCreatureStats(ptr).getActiveSpells().removeEffectsBySourceSpellId(ptr, spellid); } }; template <class R> class OpRemoveEffects : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer effectId = runtime[0].mInteger; runtime.pop(); if (ptr.getClass().isActor()) ptr.getClass().getCreatureStats(ptr).getActiveSpells().purgeEffect(ptr, effectId); } }; template <class R> class OpGetSpell : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Integer value = 0; if (ptr.getClass().isActor() && ptr.getClass().getCreatureStats(ptr).getSpells().hasSpell(id)) value = 1; runtime.push(value); } }; template <class R> class OpPCJoinFaction : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr actor = R()(runtime, false); ESM::RefId factionID; if (arg0 == 0) { factionID = getDialogueActorFaction(actor); } else { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } // Make sure this faction exists MWBase::Environment::get().getESMStore()->get<ESM::Faction>().find(factionID); if (!factionID.empty()) { MWWorld::Ptr player = MWMechanics::getPlayer(); player.getClass().getNpcStats(player).joinFaction(factionID); } } }; template <class R> class OpPCRaiseRank : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr actor = R()(runtime, false); ESM::RefId factionID; if (arg0 == 0) { factionID = getDialogueActorFaction(actor); } else { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } // Make sure this faction exists MWBase::Environment::get().getESMStore()->get<ESM::Faction>().find(factionID); if (!factionID.empty()) { MWWorld::Ptr player = MWMechanics::getPlayer(); if (!player.getClass().getNpcStats(player).isInFaction(factionID)) { player.getClass().getNpcStats(player).joinFaction(factionID); } else { int currentRank = player.getClass().getNpcStats(player).getFactionRank(factionID); player.getClass().getNpcStats(player).setFactionRank(factionID, currentRank + 1); } } } }; template <class R> class OpPCLowerRank : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr actor = R()(runtime, false); ESM::RefId factionID; if (arg0 == 0) { factionID = getDialogueActorFaction(actor); } else { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } // Make sure this faction exists MWBase::Environment::get().getESMStore()->get<ESM::Faction>().find(factionID); if (!factionID.empty()) { MWWorld::Ptr player = MWMechanics::getPlayer(); int currentRank = player.getClass().getNpcStats(player).getFactionRank(factionID); player.getClass().getNpcStats(player).setFactionRank(factionID, currentRank - 1); } } }; template <class R> class OpGetPCRank : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); ESM::RefId factionID; if (arg0 > 0) { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionID = ptr.getClass().getPrimaryFaction(ptr); } // Make sure this faction exists MWBase::Environment::get().getESMStore()->get<ESM::Faction>().find(factionID); if (!factionID.empty()) { MWWorld::Ptr player = MWMechanics::getPlayer(); runtime.push(player.getClass().getNpcStats(player).getFactionRank(factionID)); } else { runtime.push(-1); } } }; template <class R> class OpModDisposition : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); if (ptr.getClass().isNpc()) ptr.getClass().getNpcStats(ptr).setBaseDisposition( ptr.getClass().getNpcStats(ptr).getBaseDisposition() + value); // else: must not throw exception (used by an Almalexia dialogue script) } }; template <class R> class OpSetDisposition : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); if (ptr.getClass().isNpc()) ptr.getClass().getNpcStats(ptr).setBaseDisposition(value); } }; template <class R> class OpGetDisposition : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getClass().isNpc()) runtime.push(0); else runtime.push(MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(ptr)); } }; class OpGetDeadCount : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId id = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime[0].mInteger = MWBase::Environment::get().getMechanicsManager()->countDeaths(id); } }; template <class R> class OpGetPCFacRep : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); ESM::RefId factionId; if (arg0 == 1) { factionId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionId = getDialogueActorFaction(ptr); } if (factionId.empty()) throw std::runtime_error("failed to determine faction"); MWWorld::Ptr player = MWMechanics::getPlayer(); runtime.push(player.getClass().getNpcStats(player).getFactionReputation(factionId)); } }; template <class R> class OpSetPCFacRep : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); ESM::RefId factionId; if (arg0 == 1) { factionId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionId = getDialogueActorFaction(ptr); } if (factionId.empty()) throw std::runtime_error("failed to determine faction"); MWWorld::Ptr player = MWMechanics::getPlayer(); player.getClass().getNpcStats(player).setFactionReputation(factionId, value); } }; template <class R> class OpModPCFacRep : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); ESM::RefId factionId; if (arg0 == 1) { factionId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionId = getDialogueActorFaction(ptr); } if (factionId.empty()) throw std::runtime_error("failed to determine faction"); MWWorld::Ptr player = MWMechanics::getPlayer(); player.getClass().getNpcStats(player).setFactionReputation( factionId, player.getClass().getNpcStats(player).getFactionReputation(factionId) + value); } }; template <class R> class OpGetCommonDisease : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (ptr.getClass().isActor()) runtime.push(ptr.getClass().getCreatureStats(ptr).hasCommonDisease()); else runtime.push(0); } }; template <class R> class OpGetBlightDisease : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (ptr.getClass().isActor()) runtime.push(ptr.getClass().getCreatureStats(ptr).hasBlightDisease()); else runtime.push(0); } }; template <class R> class OpGetRace : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::ConstPtr ptr = R()(runtime); ESM::RefId race = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); if (ptr.getClass().isNpc()) { const ESM::RefId& npcRace = ptr.get<ESM::NPC>()->mBase->mRace; runtime.push(race == npcRace); } else { runtime.push(0); } } }; class OpGetWerewolfKills : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = MWBase::Environment::get().getWorld()->getPlayerPtr(); runtime.push(ptr.getClass().getNpcStats(ptr).getWerewolfKills()); } }; template <class R> class OpPcExpelled : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); ESM::RefId factionID; if (arg0 > 0) { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionID = ptr.getClass().getPrimaryFaction(ptr); } MWWorld::Ptr player = MWMechanics::getPlayer(); if (!factionID.empty()) { runtime.push(player.getClass().getNpcStats(player).getExpelled(factionID)); } else { runtime.push(0); } } }; template <class R> class OpPcExpell : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); ESM::RefId factionID; if (arg0 > 0) { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionID = ptr.getClass().getPrimaryFaction(ptr); } MWWorld::Ptr player = MWMechanics::getPlayer(); if (!factionID.empty()) { player.getClass().getNpcStats(player).expell(factionID, true); } } }; template <class R> class OpPcClearExpelled : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::ConstPtr ptr = R()(runtime, false); ESM::RefId factionID; if (arg0 > 0) { factionID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); } else { factionID = ptr.getClass().getPrimaryFaction(ptr); } MWWorld::Ptr player = MWMechanics::getPlayer(); if (!factionID.empty()) player.getClass().getNpcStats(player).clearExpelled(factionID); } }; template <class R> class OpRaiseRank : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); const ESM::RefId& factionID = ptr.getClass().getPrimaryFaction(ptr); if (factionID.empty()) return; MWWorld::Ptr player = MWMechanics::getPlayer(); // no-op when executed on the player if (ptr == player) return; // If we already changed rank for this NPC, modify current rank in the NPC stats. // Otherwise take rank from base NPC record, increase it and put it to NPC data. int currentRank = ptr.getClass().getNpcStats(ptr).getFactionRank(factionID); if (currentRank >= 0) ptr.getClass().getNpcStats(ptr).setFactionRank(factionID, currentRank + 1); else { int rank = ptr.getClass().getPrimaryFactionRank(ptr); ptr.getClass().getNpcStats(ptr).joinFaction(factionID); ptr.getClass().getNpcStats(ptr).setFactionRank(factionID, rank + 1); } } }; template <class R> class OpLowerRank : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); const ESM::RefId& factionID = ptr.getClass().getPrimaryFaction(ptr); if (factionID.empty()) return; MWWorld::Ptr player = MWMechanics::getPlayer(); // no-op when executed on the player if (ptr == player) return; // If we already changed rank for this NPC, modify current rank in the NPC stats. // Otherwise take rank from base NPC record, decrease it and put it to NPC data. int currentRank = ptr.getClass().getNpcStats(ptr).getFactionRank(factionID); if (currentRank == 0) return; else if (currentRank > 0) ptr.getClass().getNpcStats(ptr).setFactionRank(factionID, currentRank - 1); else { int rank = ptr.getClass().getPrimaryFactionRank(ptr); ptr.getClass().getNpcStats(ptr).joinFaction(factionID); ptr.getClass().getNpcStats(ptr).setFactionRank(factionID, std::max(0, rank - 1)); } } }; template <class R> class OpOnDeath : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = 0; if (ptr.getClass().isActor()) { auto& stats = ptr.getClass().getCreatureStats(ptr); value = stats.hasDied(); if (value) stats.clearHasDied(); } runtime.push(value); } }; template <class R> class OpOnMurder : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = 0; if (ptr.getClass().isActor()) { auto& stats = ptr.getClass().getCreatureStats(ptr); value = stats.hasBeenMurdered(); if (value) stats.clearHasBeenMurdered(); } runtime.push(value); } }; template <class R> class OpOnKnockout : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = 0; if (ptr.getClass().isActor()) value = ptr.getClass().getCreatureStats(ptr).getKnockedDownOneFrame(); runtime.push(value); } }; template <class R> class OpIsWerewolf : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (ptr.getClass().isNpc()) runtime.push(ptr.getClass().getNpcStats(ptr).isWerewolf()); else runtime.push(0); } }; template <class R, bool set> class OpSetWerewolf : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (ptr.getClass().isNpc()) MWBase::Environment::get().getMechanicsManager()->setWerewolf(ptr, set); } }; template <class R> class OpSetWerewolfAcrobatics : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (ptr.getClass().isNpc()) MWBase::Environment::get().getMechanicsManager()->applyWerewolfAcrobatics(ptr); } }; template <class R> class OpResurrect : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getClass().isActor()) return; if (ptr == MWMechanics::getPlayer()) { MWBase::Environment::get().getMechanicsManager()->resurrect(ptr); if (MWBase::Environment::get().getStateManager()->getState() == MWBase::StateManager::State_Ended) MWBase::Environment::get().getStateManager()->resumeGame(); } else if (ptr.getClass().getCreatureStats(ptr).isDead()) { bool wasEnabled = ptr.getRefData().isEnabled(); MWBase::Environment::get().getWorld()->undeleteObject(ptr); auto windowManager = MWBase::Environment::get().getWindowManager(); bool wasOpen = windowManager->containsMode(MWGui::GM_Container); windowManager->onDeleteCustomData(ptr); // HACK: disable/enable object to re-add it to the scene properly (need a new Animation). MWBase::Environment::get().getWorld()->disable(ptr); // The actor's base record may have changed after this specific reference was created. // So we need to update to the current version if (ptr.getClass().isNpc()) updateBaseRecord<ESM::NPC>(ptr); else updateBaseRecord<ESM::Creature>(ptr); if (wasOpen && !windowManager->containsMode(MWGui::GM_Container)) { // Reopen the loot GUI if it was closed because we resurrected the actor we were looting MWBase::Environment::get().getMechanicsManager()->resurrect(ptr); windowManager->forceLootMode(ptr); } else { MWBase::Environment::get().getWorld()->removeContainerScripts(ptr); // resets runtime state such as inventory, stats and AI. does not reset position in the world ptr.getRefData().setCustomData(nullptr); } if (wasEnabled) MWBase::Environment::get().getWorld()->enable(ptr); } } }; template <class R> class OpGetStat : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { // dummy runtime.pop(); runtime.push(0); } }; template <class R> class OpGetMagicEffect : public Interpreter::Opcode0 { int mPositiveEffect; int mNegativeEffect; public: OpGetMagicEffect(int positiveEffect, int negativeEffect) : mPositiveEffect(positiveEffect) , mNegativeEffect(negativeEffect) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); if (!ptr.getClass().isActor()) { runtime.push(0); return; } const MWMechanics::MagicEffects& effects = ptr.getClass().getCreatureStats(ptr).getMagicEffects(); float currentValue = effects.getOrDefault(mPositiveEffect).getMagnitude(); if (mNegativeEffect != -1) currentValue -= effects.getOrDefault(mNegativeEffect).getMagnitude(); // GetResist* should take in account elemental shields if (mPositiveEffect == ESM::MagicEffect::ResistFire) currentValue += effects.getOrDefault(ESM::MagicEffect::FireShield).getMagnitude(); if (mPositiveEffect == ESM::MagicEffect::ResistShock) currentValue += effects.getOrDefault(ESM::MagicEffect::LightningShield).getMagnitude(); if (mPositiveEffect == ESM::MagicEffect::ResistFrost) currentValue += effects.getOrDefault(ESM::MagicEffect::FrostShield).getMagnitude(); int ret = static_cast<int>(currentValue); runtime.push(ret); } }; template <class R> class OpSetMagicEffect : public Interpreter::Opcode0 { int mPositiveEffect; int mNegativeEffect; public: OpSetMagicEffect(int positiveEffect, int negativeEffect) : mPositiveEffect(positiveEffect) , mNegativeEffect(negativeEffect) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); int arg = runtime[0].mInteger; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::MagicEffects& effects = ptr.getClass().getCreatureStats(ptr).getMagicEffects(); float currentValue = effects.getOrDefault(mPositiveEffect).getMagnitude(); if (mNegativeEffect != -1) currentValue -= effects.getOrDefault(mNegativeEffect).getMagnitude(); // SetResist* should take in account elemental shields if (mPositiveEffect == ESM::MagicEffect::ResistFire) currentValue += effects.getOrDefault(ESM::MagicEffect::FireShield).getMagnitude(); if (mPositiveEffect == ESM::MagicEffect::ResistShock) currentValue += effects.getOrDefault(ESM::MagicEffect::LightningShield).getMagnitude(); if (mPositiveEffect == ESM::MagicEffect::ResistFrost) currentValue += effects.getOrDefault(ESM::MagicEffect::FrostShield).getMagnitude(); effects.modifyBase(mPositiveEffect, (arg - static_cast<int>(currentValue))); } }; template <class R> class OpModMagicEffect : public Interpreter::Opcode0 { int mPositiveEffect; int mNegativeEffect; public: OpModMagicEffect(int positiveEffect, int negativeEffect) : mPositiveEffect(positiveEffect) , mNegativeEffect(negativeEffect) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); int arg = runtime[0].mInteger; runtime.pop(); if (!ptr.getClass().isActor()) return; MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); stats.getMagicEffects().modifyBase(mPositiveEffect, arg); } }; class OpGetPCVisionBonus : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr player = MWMechanics::getPlayer(); MWMechanics::EffectParam nightEye = player.getClass().getCreatureStats(player).getMagicEffects().getOrDefault( ESM::MagicEffect::NightEye); runtime.push(std::clamp(nightEye.getMagnitude() / 100.f, 0.f, 1.f)); } }; class OpSetPCVisionBonus : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { float arg = runtime[0].mFloat; runtime.pop(); MWWorld::Ptr player = MWMechanics::getPlayer(); auto& effects = player.getClass().getCreatureStats(player).getMagicEffects(); float delta = std::clamp(arg * 100.f, 0.f, 100.f) - effects.getOrDefault(ESM::MagicEffect::NightEye).getMagnitude(); effects.modifyBase(ESM::MagicEffect::NightEye, static_cast<int>(delta)); } }; class OpModPCVisionBonus : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { float arg = runtime[0].mFloat; runtime.pop(); MWWorld::Ptr player = MWMechanics::getPlayer(); auto& effects = player.getClass().getCreatureStats(player).getMagicEffects(); const MWMechanics::EffectParam nightEye = effects.getOrDefault(ESM::MagicEffect::NightEye); float newBase = std::clamp(nightEye.getMagnitude() + arg * 100.f, 0.f, 100.f); newBase -= nightEye.getModifier(); float delta = std::clamp(newBase, 0.f, 100.f) - nightEye.getMagnitude(); effects.modifyBase(ESM::MagicEffect::NightEye, static_cast<int>(delta)); } }; struct MagicEffect { int mPositiveEffect; int mNegativeEffect; }; void installOpcodes(Interpreter::Interpreter& interpreter) { for (int i = 0; i < Compiler::Stats::numberOfAttributes; ++i) { ESM::RefId id = ESM::Attribute::indexToRefId(i); interpreter.installSegment5<OpGetAttribute<ImplicitRef>>(Compiler::Stats::opcodeGetAttribute + i, id); interpreter.installSegment5<OpGetAttribute<ExplicitRef>>( Compiler::Stats::opcodeGetAttributeExplicit + i, id); interpreter.installSegment5<OpSetAttribute<ImplicitRef>>(Compiler::Stats::opcodeSetAttribute + i, id); interpreter.installSegment5<OpSetAttribute<ExplicitRef>>( Compiler::Stats::opcodeSetAttributeExplicit + i, id); interpreter.installSegment5<OpModAttribute<ImplicitRef>>(Compiler::Stats::opcodeModAttribute + i, id); interpreter.installSegment5<OpModAttribute<ExplicitRef>>( Compiler::Stats::opcodeModAttributeExplicit + i, id); } for (int i = 0; i < Compiler::Stats::numberOfDynamics; ++i) { interpreter.installSegment5<OpGetDynamic<ImplicitRef>>(Compiler::Stats::opcodeGetDynamic + i, i); interpreter.installSegment5<OpGetDynamic<ExplicitRef>>( Compiler::Stats::opcodeGetDynamicExplicit + i, i); interpreter.installSegment5<OpSetDynamic<ImplicitRef>>(Compiler::Stats::opcodeSetDynamic + i, i); interpreter.installSegment5<OpSetDynamic<ExplicitRef>>( Compiler::Stats::opcodeSetDynamicExplicit + i, i); interpreter.installSegment5<OpModDynamic<ImplicitRef>>(Compiler::Stats::opcodeModDynamic + i, i); interpreter.installSegment5<OpModDynamic<ExplicitRef>>( Compiler::Stats::opcodeModDynamicExplicit + i, i); interpreter.installSegment5<OpModCurrentDynamic<ImplicitRef>>( Compiler::Stats::opcodeModCurrentDynamic + i, i); interpreter.installSegment5<OpModCurrentDynamic<ExplicitRef>>( Compiler::Stats::opcodeModCurrentDynamicExplicit + i, i); interpreter.installSegment5<OpGetDynamicGetRatio<ImplicitRef>>( Compiler::Stats::opcodeGetDynamicGetRatio + i, i); interpreter.installSegment5<OpGetDynamicGetRatio<ExplicitRef>>( Compiler::Stats::opcodeGetDynamicGetRatioExplicit + i, i); } for (int i = 0; i < Compiler::Stats::numberOfSkills; ++i) { ESM::RefId id = ESM::Skill::indexToRefId(i); interpreter.installSegment5<OpGetSkill<ImplicitRef>>(Compiler::Stats::opcodeGetSkill + i, id); interpreter.installSegment5<OpGetSkill<ExplicitRef>>(Compiler::Stats::opcodeGetSkillExplicit + i, id); interpreter.installSegment5<OpSetSkill<ImplicitRef>>(Compiler::Stats::opcodeSetSkill + i, id); interpreter.installSegment5<OpSetSkill<ExplicitRef>>(Compiler::Stats::opcodeSetSkillExplicit + i, id); interpreter.installSegment5<OpModSkill<ImplicitRef>>(Compiler::Stats::opcodeModSkill + i, id); interpreter.installSegment5<OpModSkill<ExplicitRef>>(Compiler::Stats::opcodeModSkillExplicit + i, id); } interpreter.installSegment5<OpGetPCCrimeLevel>(Compiler::Stats::opcodeGetPCCrimeLevel); interpreter.installSegment5<OpSetPCCrimeLevel>(Compiler::Stats::opcodeSetPCCrimeLevel); interpreter.installSegment5<OpModPCCrimeLevel>(Compiler::Stats::opcodeModPCCrimeLevel); interpreter.installSegment5<OpAddSpell<ImplicitRef>>(Compiler::Stats::opcodeAddSpell); interpreter.installSegment5<OpAddSpell<ExplicitRef>>(Compiler::Stats::opcodeAddSpellExplicit); interpreter.installSegment5<OpRemoveSpell<ImplicitRef>>(Compiler::Stats::opcodeRemoveSpell); interpreter.installSegment5<OpRemoveSpell<ExplicitRef>>(Compiler::Stats::opcodeRemoveSpellExplicit); interpreter.installSegment5<OpRemoveSpellEffects<ImplicitRef>>(Compiler::Stats::opcodeRemoveSpellEffects); interpreter.installSegment5<OpRemoveSpellEffects<ExplicitRef>>( Compiler::Stats::opcodeRemoveSpellEffectsExplicit); interpreter.installSegment5<OpResurrect<ImplicitRef>>(Compiler::Stats::opcodeResurrect); interpreter.installSegment5<OpResurrect<ExplicitRef>>(Compiler::Stats::opcodeResurrectExplicit); interpreter.installSegment5<OpRemoveEffects<ImplicitRef>>(Compiler::Stats::opcodeRemoveEffects); interpreter.installSegment5<OpRemoveEffects<ExplicitRef>>(Compiler::Stats::opcodeRemoveEffectsExplicit); interpreter.installSegment5<OpGetSpell<ImplicitRef>>(Compiler::Stats::opcodeGetSpell); interpreter.installSegment5<OpGetSpell<ExplicitRef>>(Compiler::Stats::opcodeGetSpellExplicit); interpreter.installSegment3<OpPCRaiseRank<ImplicitRef>>(Compiler::Stats::opcodePCRaiseRank); interpreter.installSegment3<OpPCLowerRank<ImplicitRef>>(Compiler::Stats::opcodePCLowerRank); interpreter.installSegment3<OpPCJoinFaction<ImplicitRef>>(Compiler::Stats::opcodePCJoinFaction); interpreter.installSegment3<OpPCRaiseRank<ExplicitRef>>(Compiler::Stats::opcodePCRaiseRankExplicit); interpreter.installSegment3<OpPCLowerRank<ExplicitRef>>(Compiler::Stats::opcodePCLowerRankExplicit); interpreter.installSegment3<OpPCJoinFaction<ExplicitRef>>(Compiler::Stats::opcodePCJoinFactionExplicit); interpreter.installSegment3<OpGetPCRank<ImplicitRef>>(Compiler::Stats::opcodeGetPCRank); interpreter.installSegment3<OpGetPCRank<ExplicitRef>>(Compiler::Stats::opcodeGetPCRankExplicit); interpreter.installSegment5<OpModDisposition<ImplicitRef>>(Compiler::Stats::opcodeModDisposition); interpreter.installSegment5<OpModDisposition<ExplicitRef>>(Compiler::Stats::opcodeModDispositionExplicit); interpreter.installSegment5<OpSetDisposition<ImplicitRef>>(Compiler::Stats::opcodeSetDisposition); interpreter.installSegment5<OpSetDisposition<ExplicitRef>>(Compiler::Stats::opcodeSetDispositionExplicit); interpreter.installSegment5<OpGetDisposition<ImplicitRef>>(Compiler::Stats::opcodeGetDisposition); interpreter.installSegment5<OpGetDisposition<ExplicitRef>>(Compiler::Stats::opcodeGetDispositionExplicit); interpreter.installSegment5<OpGetLevel<ImplicitRef>>(Compiler::Stats::opcodeGetLevel); interpreter.installSegment5<OpGetLevel<ExplicitRef>>(Compiler::Stats::opcodeGetLevelExplicit); interpreter.installSegment5<OpSetLevel<ImplicitRef>>(Compiler::Stats::opcodeSetLevel); interpreter.installSegment5<OpSetLevel<ExplicitRef>>(Compiler::Stats::opcodeSetLevelExplicit); interpreter.installSegment5<OpGetDeadCount>(Compiler::Stats::opcodeGetDeadCount); interpreter.installSegment3<OpGetPCFacRep<ImplicitRef>>(Compiler::Stats::opcodeGetPCFacRep); interpreter.installSegment3<OpGetPCFacRep<ExplicitRef>>(Compiler::Stats::opcodeGetPCFacRepExplicit); interpreter.installSegment3<OpSetPCFacRep<ImplicitRef>>(Compiler::Stats::opcodeSetPCFacRep); interpreter.installSegment3<OpSetPCFacRep<ExplicitRef>>(Compiler::Stats::opcodeSetPCFacRepExplicit); interpreter.installSegment3<OpModPCFacRep<ImplicitRef>>(Compiler::Stats::opcodeModPCFacRep); interpreter.installSegment3<OpModPCFacRep<ExplicitRef>>(Compiler::Stats::opcodeModPCFacRepExplicit); interpreter.installSegment5<OpGetCommonDisease<ImplicitRef>>(Compiler::Stats::opcodeGetCommonDisease); interpreter.installSegment5<OpGetCommonDisease<ExplicitRef>>( Compiler::Stats::opcodeGetCommonDiseaseExplicit); interpreter.installSegment5<OpGetBlightDisease<ImplicitRef>>(Compiler::Stats::opcodeGetBlightDisease); interpreter.installSegment5<OpGetBlightDisease<ExplicitRef>>( Compiler::Stats::opcodeGetBlightDiseaseExplicit); interpreter.installSegment5<OpGetRace<ImplicitRef>>(Compiler::Stats::opcodeGetRace); interpreter.installSegment5<OpGetRace<ExplicitRef>>(Compiler::Stats::opcodeGetRaceExplicit); interpreter.installSegment5<OpGetWerewolfKills>(Compiler::Stats::opcodeGetWerewolfKills); interpreter.installSegment3<OpPcExpelled<ImplicitRef>>(Compiler::Stats::opcodePcExpelled); interpreter.installSegment3<OpPcExpelled<ExplicitRef>>(Compiler::Stats::opcodePcExpelledExplicit); interpreter.installSegment3<OpPcExpell<ImplicitRef>>(Compiler::Stats::opcodePcExpell); interpreter.installSegment3<OpPcExpell<ExplicitRef>>(Compiler::Stats::opcodePcExpellExplicit); interpreter.installSegment3<OpPcClearExpelled<ImplicitRef>>(Compiler::Stats::opcodePcClearExpelled); interpreter.installSegment3<OpPcClearExpelled<ExplicitRef>>(Compiler::Stats::opcodePcClearExpelledExplicit); interpreter.installSegment5<OpRaiseRank<ImplicitRef>>(Compiler::Stats::opcodeRaiseRank); interpreter.installSegment5<OpRaiseRank<ExplicitRef>>(Compiler::Stats::opcodeRaiseRankExplicit); interpreter.installSegment5<OpLowerRank<ImplicitRef>>(Compiler::Stats::opcodeLowerRank); interpreter.installSegment5<OpLowerRank<ExplicitRef>>(Compiler::Stats::opcodeLowerRankExplicit); interpreter.installSegment5<OpOnDeath<ImplicitRef>>(Compiler::Stats::opcodeOnDeath); interpreter.installSegment5<OpOnDeath<ExplicitRef>>(Compiler::Stats::opcodeOnDeathExplicit); interpreter.installSegment5<OpOnMurder<ImplicitRef>>(Compiler::Stats::opcodeOnMurder); interpreter.installSegment5<OpOnMurder<ExplicitRef>>(Compiler::Stats::opcodeOnMurderExplicit); interpreter.installSegment5<OpOnKnockout<ImplicitRef>>(Compiler::Stats::opcodeOnKnockout); interpreter.installSegment5<OpOnKnockout<ExplicitRef>>(Compiler::Stats::opcodeOnKnockoutExplicit); interpreter.installSegment5<OpIsWerewolf<ImplicitRef>>(Compiler::Stats::opcodeIsWerewolf); interpreter.installSegment5<OpIsWerewolf<ExplicitRef>>(Compiler::Stats::opcodeIsWerewolfExplicit); interpreter.installSegment5<OpSetWerewolf<ImplicitRef, true>>(Compiler::Stats::opcodeBecomeWerewolf); interpreter.installSegment5<OpSetWerewolf<ExplicitRef, true>>( Compiler::Stats::opcodeBecomeWerewolfExplicit); interpreter.installSegment5<OpSetWerewolf<ImplicitRef, false>>(Compiler::Stats::opcodeUndoWerewolf); interpreter.installSegment5<OpSetWerewolf<ExplicitRef, false>>(Compiler::Stats::opcodeUndoWerewolfExplicit); interpreter.installSegment5<OpSetWerewolfAcrobatics<ImplicitRef>>( Compiler::Stats::opcodeSetWerewolfAcrobatics); interpreter.installSegment5<OpSetWerewolfAcrobatics<ExplicitRef>>( Compiler::Stats::opcodeSetWerewolfAcrobaticsExplicit); interpreter.installSegment5<OpGetStat<ImplicitRef>>(Compiler::Stats::opcodeGetStat); interpreter.installSegment5<OpGetStat<ExplicitRef>>(Compiler::Stats::opcodeGetStatExplicit); static const MagicEffect sMagicEffects[] = { { ESM::MagicEffect::ResistMagicka, ESM::MagicEffect::WeaknessToMagicka }, { ESM::MagicEffect::ResistFire, ESM::MagicEffect::WeaknessToFire }, { ESM::MagicEffect::ResistFrost, ESM::MagicEffect::WeaknessToFrost }, { ESM::MagicEffect::ResistShock, ESM::MagicEffect::WeaknessToShock }, { ESM::MagicEffect::ResistCommonDisease, ESM::MagicEffect::WeaknessToCommonDisease }, { ESM::MagicEffect::ResistBlightDisease, ESM::MagicEffect::WeaknessToBlightDisease }, { ESM::MagicEffect::ResistCorprusDisease, ESM::MagicEffect::WeaknessToCorprusDisease }, { ESM::MagicEffect::ResistPoison, ESM::MagicEffect::WeaknessToPoison }, { ESM::MagicEffect::ResistParalysis, -1 }, { ESM::MagicEffect::ResistNormalWeapons, ESM::MagicEffect::WeaknessToNormalWeapons }, { ESM::MagicEffect::WaterBreathing, -1 }, { ESM::MagicEffect::Chameleon, -1 }, { ESM::MagicEffect::WaterWalking, -1 }, { ESM::MagicEffect::SwiftSwim, -1 }, { ESM::MagicEffect::Jump, -1 }, { ESM::MagicEffect::Levitate, -1 }, { ESM::MagicEffect::Shield, -1 }, { ESM::MagicEffect::Sound, -1 }, { ESM::MagicEffect::Silence, -1 }, { ESM::MagicEffect::Blind, -1 }, { ESM::MagicEffect::Paralyze, -1 }, { ESM::MagicEffect::Invisibility, -1 }, { ESM::MagicEffect::FortifyAttack, -1 }, { ESM::MagicEffect::Sanctuary, -1 }, }; for (int i = 0; i < 24; ++i) { int positive = sMagicEffects[i].mPositiveEffect; int negative = sMagicEffects[i].mNegativeEffect; interpreter.installSegment5<OpGetMagicEffect<ImplicitRef>>( Compiler::Stats::opcodeGetMagicEffect + i, positive, negative); interpreter.installSegment5<OpGetMagicEffect<ExplicitRef>>( Compiler::Stats::opcodeGetMagicEffectExplicit + i, positive, negative); interpreter.installSegment5<OpSetMagicEffect<ImplicitRef>>( Compiler::Stats::opcodeSetMagicEffect + i, positive, negative); interpreter.installSegment5<OpSetMagicEffect<ExplicitRef>>( Compiler::Stats::opcodeSetMagicEffectExplicit + i, positive, negative); interpreter.installSegment5<OpModMagicEffect<ImplicitRef>>( Compiler::Stats::opcodeModMagicEffect + i, positive, negative); interpreter.installSegment5<OpModMagicEffect<ExplicitRef>>( Compiler::Stats::opcodeModMagicEffectExplicit + i, positive, negative); } interpreter.installSegment5<OpGetPCVisionBonus>(Compiler::Stats::opcodeGetPCVisionBonus); interpreter.installSegment5<OpSetPCVisionBonus>(Compiler::Stats::opcodeSetPCVisionBonus); interpreter.installSegment5<OpModPCVisionBonus>(Compiler::Stats::opcodeModPCVisionBonus); } } }
63,965
C++
.cpp
1,354
32.497046
120
0.561889
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,421
controlextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/controlextensions.cpp
#include "controlextensions.hpp" #include <components/compiler/opcodes.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/inputmanager.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/ptr.hpp" #include "../mwmechanics/creaturestats.hpp" #include "interpretercontext.hpp" #include "ref.hpp" namespace MWScript { namespace Control { class OpSetControl : public Interpreter::Opcode0 { std::string_view mControl; bool mEnable; public: OpSetControl(std::string_view control, bool enable) : mControl(control) , mEnable(enable) { } void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getInputManager()->toggleControlSwitch(mControl, mEnable); } }; class OpGetDisabled : public Interpreter::Opcode0 { std::string_view mControl; public: OpGetDisabled(std::string_view control) : mControl(control) { } void execute(Interpreter::Runtime& runtime) override { runtime.push(!MWBase::Environment::get().getInputManager()->getControlSwitch(mControl)); } }; class OpToggleCollision : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { bool enabled = MWBase::Environment::get().getWorld()->toggleCollisionMode(); runtime.getContext().report(enabled ? "Collision -> On" : "Collision -> Off"); } }; template <class R> class OpClearMovementFlag : public Interpreter::Opcode0 { MWMechanics::CreatureStats::Flag mFlag; public: OpClearMovementFlag(MWMechanics::CreatureStats::Flag flag) : mFlag(flag) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ptr.getClass().getCreatureStats(ptr).setMovementFlag(mFlag, false); } }; template <class R> class OpSetMovementFlag : public Interpreter::Opcode0 { MWMechanics::CreatureStats::Flag mFlag; public: OpSetMovementFlag(MWMechanics::CreatureStats::Flag flag) : mFlag(flag) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); ptr.getClass().getCreatureStats(ptr).setMovementFlag(mFlag, true); } }; template <class R> class OpGetForceRun : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); runtime.push(stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceRun)); } }; template <class R> class OpGetForceJump : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); runtime.push(stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceJump)); } }; template <class R> class OpGetForceMoveJump : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); runtime.push(stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceMoveJump)); } }; template <class R> class OpGetForceSneak : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); runtime.push(stats.getMovementFlag(MWMechanics::CreatureStats::Flag_ForceSneak)); } }; class OpGetPcRunning : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = MWBase::Environment::get().getWorld()->getPlayerPtr(); MWMechanics::CreatureStats& stats = ptr.getClass().getCreatureStats(ptr); MWBase::World* world = MWBase::Environment::get().getWorld(); bool stanceOn = stats.getStance(MWMechanics::CreatureStats::Stance_Run); bool running = MWBase::Environment::get().getMechanicsManager()->isRunning(ptr); bool inair = !world->isOnGround(ptr) && !world->isSwimming(ptr) && !world->isFlying(ptr); runtime.push(stanceOn && (running || inair)); } }; class OpGetPcSneaking : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = MWBase::Environment::get().getWorld()->getPlayerPtr(); runtime.push(MWBase::Environment::get().getMechanicsManager()->isSneaking(ptr)); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { for (int i = 0; i < Compiler::Control::numberOfControls; ++i) { interpreter.installSegment5<OpSetControl>( Compiler::Control::opcodeEnable + i, Compiler::Control::controls[i], true); interpreter.installSegment5<OpSetControl>( Compiler::Control::opcodeDisable + i, Compiler::Control::controls[i], false); interpreter.installSegment5<OpGetDisabled>( Compiler::Control::opcodeGetDisabled + i, Compiler::Control::controls[i]); } interpreter.installSegment5<OpToggleCollision>(Compiler::Control::opcodeToggleCollision); // Force Run interpreter.installSegment5<OpClearMovementFlag<ImplicitRef>>( Compiler::Control::opcodeClearForceRun, MWMechanics::CreatureStats::Flag_ForceRun); interpreter.installSegment5<OpClearMovementFlag<ExplicitRef>>( Compiler::Control::opcodeClearForceRunExplicit, MWMechanics::CreatureStats::Flag_ForceRun); interpreter.installSegment5<OpSetMovementFlag<ImplicitRef>>( Compiler::Control::opcodeForceRun, MWMechanics::CreatureStats::Flag_ForceRun); interpreter.installSegment5<OpSetMovementFlag<ExplicitRef>>( Compiler::Control::opcodeForceRunExplicit, MWMechanics::CreatureStats::Flag_ForceRun); // Force Jump interpreter.installSegment5<OpClearMovementFlag<ImplicitRef>>( Compiler::Control::opcodeClearForceJump, MWMechanics::CreatureStats::Flag_ForceJump); interpreter.installSegment5<OpClearMovementFlag<ExplicitRef>>( Compiler::Control::opcodeClearForceJumpExplicit, MWMechanics::CreatureStats::Flag_ForceJump); interpreter.installSegment5<OpSetMovementFlag<ImplicitRef>>( Compiler::Control::opcodeForceJump, MWMechanics::CreatureStats::Flag_ForceJump); interpreter.installSegment5<OpSetMovementFlag<ExplicitRef>>( Compiler::Control::opcodeForceJumpExplicit, MWMechanics::CreatureStats::Flag_ForceJump); // Force MoveJump interpreter.installSegment5<OpClearMovementFlag<ImplicitRef>>( Compiler::Control::opcodeClearForceMoveJump, MWMechanics::CreatureStats::Flag_ForceMoveJump); interpreter.installSegment5<OpClearMovementFlag<ExplicitRef>>( Compiler::Control::opcodeClearForceMoveJumpExplicit, MWMechanics::CreatureStats::Flag_ForceMoveJump); interpreter.installSegment5<OpSetMovementFlag<ImplicitRef>>( Compiler::Control::opcodeForceMoveJump, MWMechanics::CreatureStats::Flag_ForceMoveJump); interpreter.installSegment5<OpSetMovementFlag<ExplicitRef>>( Compiler::Control::opcodeForceMoveJumpExplicit, MWMechanics::CreatureStats::Flag_ForceMoveJump); // Force Sneak interpreter.installSegment5<OpClearMovementFlag<ImplicitRef>>( Compiler::Control::opcodeClearForceSneak, MWMechanics::CreatureStats::Flag_ForceSneak); interpreter.installSegment5<OpClearMovementFlag<ExplicitRef>>( Compiler::Control::opcodeClearForceSneakExplicit, MWMechanics::CreatureStats::Flag_ForceSneak); interpreter.installSegment5<OpSetMovementFlag<ImplicitRef>>( Compiler::Control::opcodeForceSneak, MWMechanics::CreatureStats::Flag_ForceSneak); interpreter.installSegment5<OpSetMovementFlag<ExplicitRef>>( Compiler::Control::opcodeForceSneakExplicit, MWMechanics::CreatureStats::Flag_ForceSneak); interpreter.installSegment5<OpGetPcRunning>(Compiler::Control::opcodeGetPcRunning); interpreter.installSegment5<OpGetPcSneaking>(Compiler::Control::opcodeGetPcSneaking); interpreter.installSegment5<OpGetForceRun<ImplicitRef>>(Compiler::Control::opcodeGetForceRun); interpreter.installSegment5<OpGetForceRun<ExplicitRef>>(Compiler::Control::opcodeGetForceRunExplicit); interpreter.installSegment5<OpGetForceJump<ImplicitRef>>(Compiler::Control::opcodeGetForceJump); interpreter.installSegment5<OpGetForceJump<ExplicitRef>>(Compiler::Control::opcodeGetForceJumpExplicit); interpreter.installSegment5<OpGetForceMoveJump<ImplicitRef>>(Compiler::Control::opcodeGetForceMoveJump); interpreter.installSegment5<OpGetForceMoveJump<ExplicitRef>>( Compiler::Control::opcodeGetForceMoveJumpExplicit); interpreter.installSegment5<OpGetForceSneak<ImplicitRef>>(Compiler::Control::opcodeGetForceSneak); interpreter.installSegment5<OpGetForceSneak<ExplicitRef>>(Compiler::Control::opcodeGetForceSneakExplicit); } } }
10,895
C++
.cpp
214
38.654206
118
0.643609
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
35,422
aiextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/aiextensions.cpp
#include "aiextensions.hpp" #include <stdexcept> #include <components/debug/debuglog.hpp> #include <components/compiler/extensions.hpp> #include <components/compiler/opcodes.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwworld/class.hpp" #include "../mwworld/esmstore.hpp" #include "../mwmechanics/actorutil.hpp" #include "../mwmechanics/aiactivate.hpp" #include "../mwmechanics/aiescort.hpp" #include "../mwmechanics/aiface.hpp" #include "../mwmechanics/aifollow.hpp" #include "../mwmechanics/aitravel.hpp" #include "../mwmechanics/aiwander.hpp" #include "../mwmechanics/creaturestats.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/soundmanager.hpp" #include "../mwbase/world.hpp" #include "interpretercontext.hpp" #include "ref.hpp" namespace MWScript { namespace Ai { template <class R> class OpAiActivate : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId objectID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiActivate activatePackage(objectID, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(activatePackage, ptr); Log(Debug::Info) << "AiActivate"; } }; template <class R> class OpAiTravel : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiTravel travelPackage(x, y, z, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(travelPackage, ptr); Log(Debug::Info) << "AiTravel: " << x << ", " << y << ", " << z; } }; template <class R> class OpAiEscort : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Float duration = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiEscort escortPackage(actorID, static_cast<int>(duration), x, y, z, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(escortPackage, ptr); Log(Debug::Info) << "AiEscort: " << x << ", " << y << ", " << z << ", " << duration; } }; template <class R> class OpAiEscortCell : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); std::string_view cellID = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); Interpreter::Type_Float duration = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; if (cellID.empty()) return; if (!MWBase::Environment::get().getESMStore()->get<ESM::Cell>().search(cellID)) return; MWMechanics::AiEscort escortPackage(actorID, cellID, static_cast<int>(duration), x, y, z, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(escortPackage, ptr); Log(Debug::Info) << "AiEscort: " << x << ", " << y << ", " << z << ", " << duration; } }; template <class R> class OpGetAiPackageDone : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); bool done = false; if (ptr.getClass().isActor()) done = ptr.getClass().getCreatureStats(ptr).getAiSequence().isPackageDone(); runtime.push(done); } }; template <class R> class OpAiWander : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer range = static_cast<Interpreter::Type_Integer>(runtime[0].mFloat); runtime.pop(); Interpreter::Type_Integer duration = static_cast<Interpreter::Type_Integer>(runtime[0].mFloat); runtime.pop(); Interpreter::Type_Integer time = static_cast<Interpreter::Type_Integer>(runtime[0].mFloat); runtime.pop(); // Chance for Idle is unused if (arg0) { --arg0; runtime.pop(); } std::vector<unsigned char> idleList; bool repeat = false; // Chances for Idle2-Idle9 for (int i = 2; i <= 9 && arg0; ++i) { if (!repeat) repeat = true; Interpreter::Type_Integer idleValue = std::clamp(runtime[0].mInteger, 0, 255); idleList.push_back(idleValue); runtime.pop(); --arg0; } if (arg0) { repeat = runtime[0].mInteger != 0; runtime.pop(); --arg0; } // discard additional arguments, because we have no idea what they mean. for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiWander wanderPackage(range, duration, time, idleList, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(wanderPackage, ptr); } }; template <class R> class OpGetAiSetting : public Interpreter::Opcode0 { MWMechanics::AiSetting mIndex; public: OpGetAiSetting(MWMechanics::AiSetting index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = 0; if (ptr.getClass().isActor()) value = ptr.getClass().getCreatureStats(ptr).getAiSetting(mIndex).getModified(false); runtime.push(value); } }; template <class R> class OpModAiSetting : public Interpreter::Opcode0 { MWMechanics::AiSetting mIndex; public: OpModAiSetting(MWMechanics::AiSetting index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); if (!ptr.getClass().isActor()) return; int modified = ptr.getClass().getCreatureStats(ptr).getAiSetting(mIndex).getBase() + value; ptr.getClass().getCreatureStats(ptr).setAiSetting(mIndex, modified); ptr.getClass().setBaseAISetting(ptr.getCellRef().getRefId(), mIndex, modified); } }; template <class R> class OpSetAiSetting : public Interpreter::Opcode0 { MWMechanics::AiSetting mIndex; public: OpSetAiSetting(MWMechanics::AiSetting index) : mIndex(index) { } void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = runtime[0].mInteger; runtime.pop(); if (ptr.getClass().isActor()) { ptr.getClass().getCreatureStats(ptr).setAiSetting(mIndex, value); ptr.getClass().setBaseAISetting(ptr.getCellRef().getRefId(), mIndex, value); } } }; template <class R> class OpAiFollow : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Float duration = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiFollow followPackage(actorID, duration, x, y, z, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(followPackage, ptr); Log(Debug::Info) << "AiFollow: " << actorID << ", " << x << ", " << y << ", " << z << ", " << duration; } }; template <class R> class OpAiFollowCell : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { MWWorld::Ptr ptr = R()(runtime); ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); std::string_view cellID = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); Interpreter::Type_Float duration = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float z = runtime[0].mFloat; runtime.pop(); // The value of the reset argument doesn't actually matter bool repeat = arg0; for (unsigned int i = 0; i < arg0; ++i) runtime.pop(); if (!ptr.getClass().isActor() || ptr == MWMechanics::getPlayer()) return; MWMechanics::AiFollow followPackage(actorID, cellID, duration, x, y, z, repeat); ptr.getClass().getCreatureStats(ptr).getAiSequence().stack(followPackage, ptr); Log(Debug::Info) << "AiFollow: " << actorID << ", " << x << ", " << y << ", " << z << ", " << duration; } }; template <class R> class OpGetCurrentAIPackage : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr ptr = R()(runtime); Interpreter::Type_Integer value = -1; if (ptr.getClass().isActor()) { const auto& stats = ptr.getClass().getCreatureStats(ptr); if (!stats.isDead() || !stats.isDeathAnimationFinished()) { value = static_cast<Interpreter::Type_Integer>(stats.getAiSequence().getLastRunTypeId()); } } runtime.push(value); } }; template <class R> class OpGetDetected : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr observer = R()(runtime, false); // required=false ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); MWWorld::Ptr actor = MWBase::Environment::get().getWorld()->searchPtr(actorID, true, false); Interpreter::Type_Integer value = 0; if (!actor.isEmpty()) value = MWBase::Environment::get().getMechanicsManager()->isActorDetected(actor, observer); runtime.push(value); } }; template <class R> class OpGetLineOfSight : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr source = R()(runtime); ESM::RefId actorID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); MWWorld::Ptr dest = MWBase::Environment::get().getWorld()->searchPtr(actorID, true, false); bool value = false; if (!dest.isEmpty() && source.getClass().isActor() && dest.getClass().isActor()) { value = MWBase::Environment::get().getWorld()->getLOS(source, dest); } runtime.push(value); } }; template <class R> class OpGetTarget : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr actor = R()(runtime); ESM::RefId testedTargetId = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); bool targetsAreEqual = false; if (actor.getClass().isActor()) { const MWMechanics::CreatureStats& creatureStats = actor.getClass().getCreatureStats(actor); MWWorld::Ptr targetPtr; if (creatureStats.getAiSequence().getCombatTarget(targetPtr)) { if (!targetPtr.isEmpty() && targetPtr.getCellRef().getRefId() == testedTargetId) targetsAreEqual = true; } else if (testedTargetId == "Player") // Currently the player ID is hardcoded { MWBase::MechanicsManager* mechMgr = MWBase::Environment::get().getMechanicsManager(); bool greeting = mechMgr->getGreetingState(actor) == MWMechanics::Greet_InProgress; bool sayActive = MWBase::Environment::get().getSoundManager()->sayActive(actor); targetsAreEqual = (greeting && sayActive) || mechMgr->isTurningToPlayer(actor); } } runtime.push(targetsAreEqual); } }; template <class R> class OpStartCombat : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr actor = R()(runtime); ESM::RefId targetID = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); MWWorld::Ptr target = MWBase::Environment::get().getWorld()->searchPtr(targetID, true, false); if (!target.isEmpty() && !target.getBase()->isDeleted() && !target.getClass().getCreatureStats(target).isDead()) MWBase::Environment::get().getMechanicsManager()->startCombat(actor, target, nullptr); } }; template <class R> class OpStopCombat : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr actor = R()(runtime); if (!actor.getClass().isActor()) return; MWBase::Environment::get().getMechanicsManager()->stopCombat(actor); } }; class OpToggleAI : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { bool enabled = MWBase::Environment::get().getMechanicsManager()->toggleAI(); runtime.getContext().report(enabled ? "AI -> On" : "AI -> Off"); } }; template <class R> class OpFace : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr actor = R()(runtime); Interpreter::Type_Float x = runtime[0].mFloat; runtime.pop(); Interpreter::Type_Float y = runtime[0].mFloat; runtime.pop(); if (!actor.getClass().isActor() || actor == MWMechanics::getPlayer()) return; MWMechanics::AiFace facePackage(x, y); actor.getClass().getCreatureStats(actor).getAiSequence().stack(facePackage, actor); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment3<OpAiActivate<ImplicitRef>>(Compiler::Ai::opcodeAIActivate); interpreter.installSegment3<OpAiActivate<ExplicitRef>>(Compiler::Ai::opcodeAIActivateExplicit); interpreter.installSegment3<OpAiTravel<ImplicitRef>>(Compiler::Ai::opcodeAiTravel); interpreter.installSegment3<OpAiTravel<ExplicitRef>>(Compiler::Ai::opcodeAiTravelExplicit); interpreter.installSegment3<OpAiEscort<ImplicitRef>>(Compiler::Ai::opcodeAiEscort); interpreter.installSegment3<OpAiEscort<ExplicitRef>>(Compiler::Ai::opcodeAiEscortExplicit); interpreter.installSegment3<OpAiEscortCell<ImplicitRef>>(Compiler::Ai::opcodeAiEscortCell); interpreter.installSegment3<OpAiEscortCell<ExplicitRef>>(Compiler::Ai::opcodeAiEscortCellExplicit); interpreter.installSegment3<OpAiWander<ImplicitRef>>(Compiler::Ai::opcodeAiWander); interpreter.installSegment3<OpAiWander<ExplicitRef>>(Compiler::Ai::opcodeAiWanderExplicit); interpreter.installSegment3<OpAiFollow<ImplicitRef>>(Compiler::Ai::opcodeAiFollow); interpreter.installSegment3<OpAiFollow<ExplicitRef>>(Compiler::Ai::opcodeAiFollowExplicit); interpreter.installSegment3<OpAiFollowCell<ImplicitRef>>(Compiler::Ai::opcodeAiFollowCell); interpreter.installSegment3<OpAiFollowCell<ExplicitRef>>(Compiler::Ai::opcodeAiFollowCellExplicit); interpreter.installSegment5<OpGetAiPackageDone<ImplicitRef>>(Compiler::Ai::opcodeGetAiPackageDone); interpreter.installSegment5<OpGetAiPackageDone<ExplicitRef>>(Compiler::Ai::opcodeGetAiPackageDoneExplicit); interpreter.installSegment5<OpGetCurrentAIPackage<ImplicitRef>>(Compiler::Ai::opcodeGetCurrentAiPackage); interpreter.installSegment5<OpGetCurrentAIPackage<ExplicitRef>>( Compiler::Ai::opcodeGetCurrentAiPackageExplicit); interpreter.installSegment5<OpGetDetected<ImplicitRef>>(Compiler::Ai::opcodeGetDetected); interpreter.installSegment5<OpGetDetected<ExplicitRef>>(Compiler::Ai::opcodeGetDetectedExplicit); interpreter.installSegment5<OpGetLineOfSight<ImplicitRef>>(Compiler::Ai::opcodeGetLineOfSight); interpreter.installSegment5<OpGetLineOfSight<ExplicitRef>>(Compiler::Ai::opcodeGetLineOfSightExplicit); interpreter.installSegment5<OpGetTarget<ImplicitRef>>(Compiler::Ai::opcodeGetTarget); interpreter.installSegment5<OpGetTarget<ExplicitRef>>(Compiler::Ai::opcodeGetTargetExplicit); interpreter.installSegment5<OpStartCombat<ImplicitRef>>(Compiler::Ai::opcodeStartCombat); interpreter.installSegment5<OpStartCombat<ExplicitRef>>(Compiler::Ai::opcodeStartCombatExplicit); interpreter.installSegment5<OpStopCombat<ImplicitRef>>(Compiler::Ai::opcodeStopCombat); interpreter.installSegment5<OpStopCombat<ExplicitRef>>(Compiler::Ai::opcodeStopCombatExplicit); interpreter.installSegment5<OpToggleAI>(Compiler::Ai::opcodeToggleAI); interpreter.installSegment5<OpSetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeSetHello, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpSetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeSetHelloExplicit, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpSetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeSetFight, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpSetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeSetFightExplicit, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpSetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeSetFlee, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpSetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeSetFleeExplicit, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpSetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeSetAlarm, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpSetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeSetAlarmExplicit, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpModAiSetting<ImplicitRef>>( Compiler::Ai::opcodeModHello, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpModAiSetting<ExplicitRef>>( Compiler::Ai::opcodeModHelloExplicit, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpModAiSetting<ImplicitRef>>( Compiler::Ai::opcodeModFight, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpModAiSetting<ExplicitRef>>( Compiler::Ai::opcodeModFightExplicit, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpModAiSetting<ImplicitRef>>( Compiler::Ai::opcodeModFlee, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpModAiSetting<ExplicitRef>>( Compiler::Ai::opcodeModFleeExplicit, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpModAiSetting<ImplicitRef>>( Compiler::Ai::opcodeModAlarm, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpModAiSetting<ExplicitRef>>( Compiler::Ai::opcodeModAlarmExplicit, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpGetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeGetHello, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpGetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeGetHelloExplicit, MWMechanics::AiSetting::Hello); interpreter.installSegment5<OpGetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeGetFight, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpGetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeGetFightExplicit, MWMechanics::AiSetting::Fight); interpreter.installSegment5<OpGetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeGetFlee, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpGetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeGetFleeExplicit, MWMechanics::AiSetting::Flee); interpreter.installSegment5<OpGetAiSetting<ImplicitRef>>( Compiler::Ai::opcodeGetAlarm, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpGetAiSetting<ExplicitRef>>( Compiler::Ai::opcodeGetAlarmExplicit, MWMechanics::AiSetting::Alarm); interpreter.installSegment5<OpFace<ImplicitRef>>(Compiler::Ai::opcodeFace); interpreter.installSegment5<OpFace<ExplicitRef>>(Compiler::Ai::opcodeFaceExplicit); } } }
27,367
C++
.cpp
532
36.992481
119
0.578193
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,423
compilercontext.cpp
OpenMW_openmw/apps/openmw/mwscript/compilercontext.cpp
#include "compilercontext.hpp" #include "../mwworld/esmstore.hpp" #include <components/compiler/locals.hpp> #include <components/esm/refid.hpp> #include <components/esm3/loadacti.hpp> #include <components/esm3/loadalch.hpp> #include <components/esm3/loadappa.hpp> #include <components/esm3/loadarmo.hpp> #include <components/esm3/loadbook.hpp> #include <components/esm3/loadclot.hpp> #include <components/esm3/loadcont.hpp> #include <components/esm3/loadcrea.hpp> #include <components/esm3/loaddoor.hpp> #include <components/esm3/loadingr.hpp> #include <components/esm3/loadlevlist.hpp> #include <components/esm3/loadligh.hpp> #include <components/esm3/loadlock.hpp> #include <components/esm3/loadmisc.hpp> #include <components/esm3/loadnpc.hpp> #include <components/esm3/loadprob.hpp> #include <components/esm3/loadrepa.hpp> #include <components/esm3/loadscpt.hpp> #include <components/esm3/loadstat.hpp> #include <components/esm3/loadweap.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/scriptmanager.hpp" #include "../mwbase/world.hpp" #include "../mwworld/class.hpp" #include "../mwworld/manualref.hpp" #include "../mwworld/ptr.hpp" namespace MWScript { CompilerContext::CompilerContext(Type type) : mType(type) { } bool CompilerContext::canDeclareLocals() const { return mType == Type_Full; } char CompilerContext::getGlobalType(const std::string& name) const { return MWBase::Environment::get().getWorld()->getGlobalVariableType(name); } std::pair<char, bool> CompilerContext::getMemberType(const std::string& name, const ESM::RefId& id) const { ESM::RefId script; bool reference = false; if (const ESM::Script* scriptRecord = MWBase::Environment::get().getESMStore()->get<ESM::Script>().search(id)) { script = scriptRecord->mId; } else { MWWorld::ManualRef ref(*MWBase::Environment::get().getESMStore(), id); script = ref.getPtr().getClass().getScript(ref.getPtr()); reference = true; } char type = ' '; if (!script.empty()) type = MWBase::Environment::get().getScriptManager()->getLocals(script).getType( Misc::StringUtils::lowerCase(name)); return std::make_pair(type, reference); } bool CompilerContext::isId(const ESM::RefId& name) const { const MWWorld::ESMStore& store = *MWBase::Environment::get().getESMStore(); return store.get<ESM::Activator>().search(name) || store.get<ESM::Potion>().search(name) || store.get<ESM::Apparatus>().search(name) || store.get<ESM::Armor>().search(name) || store.get<ESM::Book>().search(name) || store.get<ESM::Clothing>().search(name) || store.get<ESM::Container>().search(name) || store.get<ESM::Creature>().search(name) || store.get<ESM::Door>().search(name) || store.get<ESM::Ingredient>().search(name) || store.get<ESM::CreatureLevList>().search(name) || store.get<ESM::ItemLevList>().search(name) || store.get<ESM::Light>().search(name) || store.get<ESM::Lockpick>().search(name) || store.get<ESM::Miscellaneous>().search(name) || store.get<ESM::NPC>().search(name) || store.get<ESM::Probe>().search(name) || store.get<ESM::Repair>().search(name) || store.get<ESM::Static>().search(name) || store.get<ESM::Weapon>().search(name) || store.get<ESM::Script>().search(name); } }
3,540
C++
.cpp
80
38.2625
118
0.668795
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
35,424
guiextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/guiextensions.cpp
#include "guiextensions.hpp" #include <components/compiler/opcodes.hpp> #include <components/interpreter/context.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwworld/esmstore.hpp" #include "../mwbase/environment.hpp" #include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/windowmanager.hpp" #include "../mwmechanics/actorutil.hpp" #include "ref.hpp" namespace MWScript { namespace Gui { class OpEnableWindow : public Interpreter::Opcode0 { MWGui::GuiWindow mWindow; public: OpEnableWindow(MWGui::GuiWindow window) : mWindow(window) { } void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getWindowManager()->allow(mWindow); } }; class OpEnableRest : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getWindowManager()->enableRest(); } }; template <class R> class OpShowRestMenu : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWWorld::Ptr bed = R()(runtime, false); if (bed.isEmpty() || !MWBase::Environment::get().getMechanicsManager()->sleepInBed(MWMechanics::getPlayer(), bed)) MWBase::Environment::get().getWindowManager()->pushGuiMode(MWGui::GM_Rest, bed); } }; class OpShowDialogue : public Interpreter::Opcode0 { MWGui::GuiMode mDialogue; public: OpShowDialogue(MWGui::GuiMode dialogue) : mDialogue(dialogue) { } void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getWindowManager()->pushGuiMode(mDialogue); } }; class OpGetButtonPressed : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.push(MWBase::Environment::get().getWindowManager()->readPressedButton()); } }; class OpToggleFogOfWar : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.getContext().report(MWBase::Environment::get().getWindowManager()->toggleFogOfWar() ? "Fog of war -> On" : "Fog of war -> Off"); } }; class OpToggleFullHelp : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.getContext().report(MWBase::Environment::get().getWindowManager()->toggleFullHelp() ? "Full help -> On" : "Full help -> Off"); } }; class OpShowMap : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { std::string_view cell = runtime.getStringLiteral(runtime[0].mInteger); runtime.pop(); // "Will match complete or partial cells, so ShowMap, "Vivec" will show cells Vivec and Vivec, Fred's // House as well." http://www.uesp.net/wiki/Tes3Mod:ShowMap const MWWorld::Store<ESM::Cell>& cells = MWBase::Environment::get().getESMStore()->get<ESM::Cell>(); MWBase::WindowManager* winMgr = MWBase::Environment::get().getWindowManager(); for (auto it = cells.extBegin(); it != cells.extEnd(); ++it) { const auto& cellName = it->mName; if (Misc::StringUtils::ciStartsWith(cellName, cell)) winMgr->addVisitedLocation(cellName, it->getGridX(), it->getGridY()); } } }; class OpFillMap : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { const MWWorld::Store<ESM::Cell>& cells = MWBase::Environment::get().getESMStore()->get<ESM::Cell>(); for (auto it = cells.extBegin(); it != cells.extEnd(); ++it) { const std::string& name = it->mName; if (!name.empty()) MWBase::Environment::get().getWindowManager()->addVisitedLocation( name, it->getGridX(), it->getGridY()); } } }; class OpMenuTest : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { int arg = 0; if (arg0 > 0) { arg = runtime[0].mInteger; runtime.pop(); } if (arg == 0) { MWGui::GuiMode modes[] = { MWGui::GM_Inventory, MWGui::GM_Container }; for (int i = 0; i < 2; ++i) { if (MWBase::Environment::get().getWindowManager()->containsMode(modes[i])) MWBase::Environment::get().getWindowManager()->removeGuiMode(modes[i]); } } else { MWGui::GuiWindow gw = MWGui::GW_None; if (arg == 3) gw = MWGui::GW_Stats; if (arg == 4) gw = MWGui::GW_Inventory; if (arg == 5) gw = MWGui::GW_Magic; if (arg == 6) gw = MWGui::GW_Map; MWBase::Environment::get().getWindowManager()->pinWindow(gw); } } }; class OpToggleMenus : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { bool state = MWBase::Environment::get().getWindowManager()->setHudVisibility( !MWBase::Environment::get().getWindowManager()->isHudVisible()); runtime.getContext().report(state ? "GUI -> On" : "GUI -> Off"); if (!state) { while (MWBase::Environment::get().getWindowManager()->getMode() != MWGui::GM_None) // don't use isGuiMode, or we get an infinite loop for modal message boxes! MWBase::Environment::get().getWindowManager()->popGuiMode(); } } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableBirthMenu, MWGui::GM_Birth); interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableClassMenu, MWGui::GM_Class); interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableNameMenu, MWGui::GM_Name); interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableRaceMenu, MWGui::GM_Race); interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableStatsReviewMenu, MWGui::GM_Review); interpreter.installSegment5<OpShowDialogue>(Compiler::Gui::opcodeEnableLevelupMenu, MWGui::GM_Levelup); interpreter.installSegment5<OpEnableWindow>(Compiler::Gui::opcodeEnableInventoryMenu, MWGui::GW_Inventory); interpreter.installSegment5<OpEnableWindow>(Compiler::Gui::opcodeEnableMagicMenu, MWGui::GW_Magic); interpreter.installSegment5<OpEnableWindow>(Compiler::Gui::opcodeEnableMapMenu, MWGui::GW_Map); interpreter.installSegment5<OpEnableWindow>(Compiler::Gui::opcodeEnableStatsMenu, MWGui::GW_Stats); interpreter.installSegment5<OpEnableRest>(Compiler::Gui::opcodeEnableRest); interpreter.installSegment5<OpShowRestMenu<ImplicitRef>>(Compiler::Gui::opcodeShowRestMenu); interpreter.installSegment5<OpShowRestMenu<ExplicitRef>>(Compiler::Gui::opcodeShowRestMenuExplicit); interpreter.installSegment5<OpGetButtonPressed>(Compiler::Gui::opcodeGetButtonPressed); interpreter.installSegment5<OpToggleFogOfWar>(Compiler::Gui::opcodeToggleFogOfWar); interpreter.installSegment5<OpToggleFullHelp>(Compiler::Gui::opcodeToggleFullHelp); interpreter.installSegment5<OpShowMap>(Compiler::Gui::opcodeShowMap); interpreter.installSegment5<OpFillMap>(Compiler::Gui::opcodeFillMap); interpreter.installSegment3<OpMenuTest>(Compiler::Gui::opcodeMenuTest); interpreter.installSegment5<OpToggleMenus>(Compiler::Gui::opcodeToggleMenus); } } }
9,289
C++
.cpp
200
32.73
119
0.568729
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
35,425
skyextensions.cpp
OpenMW_openmw/apps/openmw/mwscript/skyextensions.cpp
#include "skyextensions.hpp" #include <algorithm> #include <components/compiler/opcodes.hpp> #include <components/esm3/loadregn.hpp> #include <components/interpreter/context.hpp> #include <components/interpreter/interpreter.hpp> #include <components/interpreter/opcodes.hpp> #include <components/interpreter/runtime.hpp> #include "../mwbase/environment.hpp" #include "../mwbase/world.hpp" #include "../mwworld/esmstore.hpp" namespace MWScript { namespace Sky { class OpToggleSky : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { bool enabled = MWBase::Environment::get().getWorld()->toggleSky(); runtime.getContext().report(enabled ? "Sky -> On" : "Sky -> Off"); } }; class OpTurnMoonWhite : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getWorld()->setMoonColour(false); } }; class OpTurnMoonRed : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { MWBase::Environment::get().getWorld()->setMoonColour(true); } }; class OpGetMasserPhase : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.push(MWBase::Environment::get().getWorld()->getMasserPhase()); } }; class OpGetSecundaPhase : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.push(MWBase::Environment::get().getWorld()->getSecundaPhase()); } }; class OpGetCurrentWeather : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { runtime.push(MWBase::Environment::get().getWorld()->getCurrentWeather()); } }; class OpChangeWeather : public Interpreter::Opcode0 { public: void execute(Interpreter::Runtime& runtime) override { ESM::RefId region = ESM::RefId::stringRefId(runtime.getStringLiteral(runtime[0].mInteger)); runtime.pop(); Interpreter::Type_Integer id = runtime[0].mInteger; runtime.pop(); const ESM::Region* reg = MWBase::Environment::get().getESMStore()->get<ESM::Region>().search(region); if (reg) MWBase::Environment::get().getWorld()->changeWeather(region, id); else runtime.getContext().report("Warning: Region \"" + region.getRefIdString() + "\" was not found"); } }; class OpModRegion : public Interpreter::Opcode1 { public: void execute(Interpreter::Runtime& runtime, unsigned int arg0) override { std::string_view region{ runtime.getStringLiteral(runtime[0].mInteger) }; runtime.pop(); std::vector<uint8_t> chances; chances.reserve(10); while (arg0 > 0) { chances.push_back(std::clamp(runtime[0].mInteger, 0, 100)); runtime.pop(); arg0--; } MWBase::Environment::get().getWorld()->modRegion(ESM::RefId::stringRefId(region), chances); } }; void installOpcodes(Interpreter::Interpreter& interpreter) { interpreter.installSegment5<OpToggleSky>(Compiler::Sky::opcodeToggleSky); interpreter.installSegment5<OpTurnMoonWhite>(Compiler::Sky::opcodeTurnMoonWhite); interpreter.installSegment5<OpTurnMoonRed>(Compiler::Sky::opcodeTurnMoonRed); interpreter.installSegment5<OpGetMasserPhase>(Compiler::Sky::opcodeGetMasserPhase); interpreter.installSegment5<OpGetSecundaPhase>(Compiler::Sky::opcodeGetSecundaPhase); interpreter.installSegment5<OpGetCurrentWeather>(Compiler::Sky::opcodeGetCurrentWeather); interpreter.installSegment5<OpChangeWeather>(Compiler::Sky::opcodeChangeWeather); interpreter.installSegment3<OpModRegion>(Compiler::Sky::opcodeModRegion); } } }
4,579
C++
.cpp
111
29.918919
117
0.596763
OpenMW/openmw
5,318
933
0
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false