Merge branch 'clamp' into 'master'

Make better use of std::clamp

See merge request OpenMW/openmw!1357
pull/3222/head
Evil Eye 3 years ago
commit 5fbfbb3d84

@ -308,7 +308,7 @@ osg::ref_ptr<osg::Node> CSVRender::Object::makeRotateMarker (int axis)
const float OuterRadius = InnerRadius + MarkerShaftWidth; const float OuterRadius = InnerRadius + MarkerShaftWidth;
const float SegmentDistance = 100.f; const float SegmentDistance = 100.f;
const size_t SegmentCount = std::min(64, std::max(24, (int)(OuterRadius * 2 * osg::PI / SegmentDistance))); const size_t SegmentCount = std::clamp<int>(OuterRadius * 2 * osg::PI / SegmentDistance, 24, 64);
const size_t VerticesPerSegment = 4; const size_t VerticesPerSegment = 4;
const size_t IndicesPerSegment = 24; const size_t IndicesPerSegment = 24;

@ -421,7 +421,7 @@ namespace MWDialogue
// Clamp permanent disposition change so that final disposition doesn't go below 0 (could happen with intimidate) // Clamp permanent disposition change so that final disposition doesn't go below 0 (could happen with intimidate)
npcStats.setBaseDisposition(0); npcStats.setBaseDisposition(0);
int zero = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor, false); int zero = MWBase::Environment::get().getMechanicsManager()->getDerivedDisposition(mActor, false);
int disposition = std::min(100 - zero, std::max(mOriginalDisposition + mPermanentDispositionChange, -zero)); int disposition = std::clamp(mOriginalDisposition + mPermanentDispositionChange, -zero, 100 - zero);
npcStats.setBaseDisposition(disposition); npcStats.setBaseDisposition(disposition);
} }

@ -347,8 +347,7 @@ namespace MWGui
{ {
if (!mScrollBar->getVisible()) if (!mScrollBar->getVisible())
return; return;
mScrollBar->setScrollPosition(std::min(static_cast<int>(mScrollBar->getScrollRange()-1), mScrollBar->setScrollPosition(std::clamp<int>(mScrollBar->getScrollPosition() - _rel*0.3, 0, mScrollBar->getScrollRange() - 1));
std::max(0, static_cast<int>(mScrollBar->getScrollPosition() - _rel*0.3))));
onScrollbarMoved(mScrollBar, mScrollBar->getScrollPosition()); onScrollbarMoved(mScrollBar, mScrollBar->getScrollPosition());
} }

@ -109,7 +109,7 @@ namespace MWGui
{ {
mEnchantmentPoints->setCaption(std::to_string(static_cast<int>(mEnchanting.getEnchantPoints(false))) + " / " + std::to_string(mEnchanting.getMaxEnchantValue())); mEnchantmentPoints->setCaption(std::to_string(static_cast<int>(mEnchanting.getEnchantPoints(false))) + " / " + std::to_string(mEnchanting.getMaxEnchantValue()));
mCharge->setCaption(std::to_string(mEnchanting.getGemCharge())); mCharge->setCaption(std::to_string(mEnchanting.getGemCharge()));
mSuccessChance->setCaption(std::to_string(std::max(0, std::min(100, mEnchanting.getEnchantChance())))); mSuccessChance->setCaption(std::to_string(std::clamp(mEnchanting.getEnchantChance(), 0, 100)));
mCastCost->setCaption(std::to_string(mEnchanting.getEffectiveCastCost())); mCastCost->setCaption(std::to_string(mEnchanting.getEffectiveCastCost()));
mPrice->setCaption(std::to_string(mEnchanting.getEnchantPrice())); mPrice->setCaption(std::to_string(mEnchanting.getEnchantPrice()));

@ -610,7 +610,7 @@ namespace MWGui
static const float fNPCHealthBarFade = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fNPCHealthBarFade")->mValue.getFloat(); static const float fNPCHealthBarFade = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fNPCHealthBarFade")->mValue.getFloat();
if (fNPCHealthBarFade > 0.f) if (fNPCHealthBarFade > 0.f)
mEnemyHealth->setAlpha(std::max(0.f, std::min(1.f, mEnemyHealthTimer/fNPCHealthBarFade))); mEnemyHealth->setAlpha(std::clamp(mEnemyHealthTimer / fNPCHealthBarFade, 0.f, 1.f));
} }

@ -273,7 +273,7 @@ bool KeyboardNavigation::switchFocus(int direction, bool wrap)
if (wrap) if (wrap)
index = (index + keyFocusList.size())%keyFocusList.size(); index = (index + keyFocusList.size())%keyFocusList.size();
else else
index = std::min(std::max(0, index), static_cast<int>(keyFocusList.size())-1); index = std::clamp<int>(index, 0, keyFocusList.size() - 1);
MyGUI::Widget* next = keyFocusList[index]; MyGUI::Widget* next = keyFocusList[index];
int vertdiff = next->getTop() - focus->getTop(); int vertdiff = next->getTop() - focus->getTop();

@ -171,7 +171,7 @@ namespace MWGui
else else
valueStr = MyGUI::utility::toString(int(value)); valueStr = MyGUI::utility::toString(int(value));
value = std::max(min, std::min(value, max)); value = std::clamp(value, min, max);
value = (value-min)/(max-min); value = (value-min)/(max-min);
scroll->setScrollPosition(static_cast<size_t>(value * (scroll->getScrollRange() - 1))); scroll->setScrollPosition(static_cast<size_t>(value * (scroll->getScrollRange() - 1)));
@ -306,7 +306,7 @@ namespace MWGui
mWaterTextureSize->setIndexSelected(2); mWaterTextureSize->setIndexSelected(2);
int waterReflectionDetail = Settings::Manager::getInt("reflection detail", "Water"); int waterReflectionDetail = Settings::Manager::getInt("reflection detail", "Water");
waterReflectionDetail = std::min(5, std::max(0, waterReflectionDetail)); waterReflectionDetail = std::clamp(waterReflectionDetail, 0, 5);
mWaterReflectionDetail->setIndexSelected(waterReflectionDetail); mWaterReflectionDetail->setIndexSelected(waterReflectionDetail);
updateMaxLightsComboBox(mMaxLights); updateMaxLightsComboBox(mMaxLights);

@ -599,8 +599,7 @@ namespace MWGui
text += "\n#{fontcolourhtml=normal}#{sExpelled}"; text += "\n#{fontcolourhtml=normal}#{sExpelled}";
else else
{ {
int rank = factionPair.second; const int rank = std::clamp(factionPair.second, 0, 9);
rank = std::max(0, std::min(9, rank));
text += std::string("\n#{fontcolourhtml=normal}") + faction->mRanks[rank]; text += std::string("\n#{fontcolourhtml=normal}") + faction->mRanks[rank];
if (rank < 9) if (rank < 9)

@ -70,7 +70,7 @@ namespace MWInput
} }
float deadZoneRadius = Settings::Manager::getFloat("joystick dead zone", "Input"); float deadZoneRadius = Settings::Manager::getFloat("joystick dead zone", "Input");
deadZoneRadius = std::min(std::max(deadZoneRadius, 0.0f), 0.5f); deadZoneRadius = std::clamp(deadZoneRadius, 0.f, 0.5f);
mBindingsManager->setJoystickDeadZone(deadZoneRadius); mBindingsManager->setJoystickDeadZone(deadZoneRadius);
} }

@ -245,8 +245,8 @@ namespace MWInput
mMouseWheel += mouseWheelMove; mMouseWheel += mouseWheelMove;
const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize(); const MyGUI::IntSize& viewSize = MyGUI::RenderManager::getInstance().getViewSize();
mGuiCursorX = std::max(0.f, std::min(mGuiCursorX, float(viewSize.width - 1))); mGuiCursorX = std::clamp<float>(mGuiCursorX, 0.f, viewSize.width - 1);
mGuiCursorY = std::max(0.f, std::min(mGuiCursorY, float(viewSize.height - 1))); mGuiCursorY = std::clamp<float>(mGuiCursorY, 0.f, viewSize.height - 1);
MyGUI::InputManager::getInstance().injectMouseMove(static_cast<int>(mGuiCursorX), static_cast<int>(mGuiCursorY), static_cast<int>(mMouseWheel)); MyGUI::InputManager::getInstance().injectMouseMove(static_cast<int>(mGuiCursorX), static_cast<int>(mGuiCursorY), static_cast<int>(mMouseWheel));
} }

@ -1013,13 +1013,10 @@ namespace MWMechanics
void Actors::updateProcessingRange() void Actors::updateProcessingRange()
{ {
// We have to cap it since using high values (larger than 7168) will make some quests harder or impossible to complete (bug #1876) // We have to cap it since using high values (larger than 7168) will make some quests harder or impossible to complete (bug #1876)
static const float maxProcessingRange = 7168.f; static const float maxRange = 7168.f;
static const float minProcessingRange = maxProcessingRange / 2.f; static const float minRange = maxRange / 2.f;
float actorsProcessingRange = Settings::Manager::getFloat("actors processing range", "Game"); mActorsProcessingRange = std::clamp(Settings::Manager::getFloat("actors processing range", "Game"), minRange, maxRange);
actorsProcessingRange = std::min(actorsProcessingRange, maxProcessingRange);
actorsProcessingRange = std::max(actorsProcessingRange, minProcessingRange);
mActorsProcessingRange = actorsProcessingRange;
} }
void Actors::addActor (const MWWorld::Ptr& ptr, bool updateImmediately) void Actors::addActor (const MWWorld::Ptr& ptr, bool updateImmediately)
@ -1315,7 +1312,7 @@ namespace MWMechanics
angleToApproachingActor = std::atan2(deltaPos.x(), deltaPos.y()); angleToApproachingActor = std::atan2(deltaPos.x(), deltaPos.y());
osg::Vec2f posAtT = relPos + relSpeed * t; osg::Vec2f posAtT = relPos + relSpeed * t;
float coef = (posAtT.x() * relSpeed.x() + posAtT.y() * relSpeed.y()) / (collisionDist * collisionDist * maxSpeed); float coef = (posAtT.x() * relSpeed.x() + posAtT.y() * relSpeed.y()) / (collisionDist * collisionDist * maxSpeed);
coef *= osg::clampBetween((maxDistForPartialAvoiding - dist) / (maxDistForPartialAvoiding - maxDistForStrictAvoiding), 0.f, 1.f); coef *= std::clamp((maxDistForPartialAvoiding - dist) / (maxDistForPartialAvoiding - maxDistForStrictAvoiding), 0.f, 1.f);
movementCorrection = posAtT * coef; movementCorrection = posAtT * coef;
if (otherPtr.getClass().getCreatureStats(otherPtr).isDead()) if (otherPtr.getClass().getCreatureStats(otherPtr).isDead())
// In case of dead body still try to go around (it looks natural), but reduce the correction twice. // In case of dead body still try to go around (it looks natural), but reduce the correction twice.

@ -2044,7 +2044,7 @@ void CharacterController::update(float duration)
mIsMovingBackward = vec.y() < 0; mIsMovingBackward = vec.y() < 0;
float maxDelta = osg::PI * duration * (2.5f - cosDelta); float maxDelta = osg::PI * duration * (2.5f - cosDelta);
delta = osg::clampBetween(delta, -maxDelta, maxDelta); delta = std::clamp(delta, -maxDelta, maxDelta);
stats.setSideMovementAngle(stats.getSideMovementAngle() + delta); stats.setSideMovementAngle(stats.getSideMovementAngle() + delta);
effectiveRotation += delta; effectiveRotation += delta;
} }
@ -2286,7 +2286,7 @@ void CharacterController::update(float duration)
float swimmingPitch = mAnimation->getBodyPitchRadians(); float swimmingPitch = mAnimation->getBodyPitchRadians();
float targetSwimmingPitch = -mPtr.getRefData().getPosition().rot[0]; float targetSwimmingPitch = -mPtr.getRefData().getPosition().rot[0];
float maxSwimPitchDelta = 3.0f * duration; float maxSwimPitchDelta = 3.0f * duration;
swimmingPitch += osg::clampBetween(targetSwimmingPitch - swimmingPitch, -maxSwimPitchDelta, maxSwimPitchDelta); swimmingPitch += std::clamp(targetSwimmingPitch - swimmingPitch, -maxSwimPitchDelta, maxSwimPitchDelta);
mAnimation->setBodyPitchRadians(swimmingPitch); mAnimation->setBodyPitchRadians(swimmingPitch);
} }
else else
@ -2522,7 +2522,7 @@ void CharacterController::unpersistAnimationState()
{ {
float start = mAnimation->getTextKeyTime(anim.mGroup+": start"); float start = mAnimation->getTextKeyTime(anim.mGroup+": start");
float stop = mAnimation->getTextKeyTime(anim.mGroup+": stop"); float stop = mAnimation->getTextKeyTime(anim.mGroup+": stop");
float time = std::max(start, std::min(stop, anim.mTime)); float time = std::clamp(anim.mTime, start, stop);
complete = (time - start) / (stop - start); complete = (time - start) / (stop - start);
} }
@ -2746,7 +2746,7 @@ void CharacterController::setVisibility(float visibility)
float chameleon = mPtr.getClass().getCreatureStats(mPtr).getMagicEffects().get(ESM::MagicEffect::Chameleon).getMagnitude(); float chameleon = mPtr.getClass().getCreatureStats(mPtr).getMagicEffects().get(ESM::MagicEffect::Chameleon).getMagnitude();
if (chameleon) if (chameleon)
{ {
alpha *= std::min(0.75f, std::max(0.25f, (100.f - chameleon)/100.f)); alpha *= std::clamp(1.f - chameleon / 100.f, 0.25f, 0.75f);
} }
visibility = std::min(visibility, alpha); visibility = std::min(visibility, alpha);
@ -2965,8 +2965,8 @@ void CharacterController::updateHeadTracking(float duration)
const double xLimit = osg::DegreesToRadians(40.0); const double xLimit = osg::DegreesToRadians(40.0);
const double zLimit = osg::DegreesToRadians(30.0); const double zLimit = osg::DegreesToRadians(30.0);
double zLimitOffset = mAnimation->getUpperBodyYawRadians(); double zLimitOffset = mAnimation->getUpperBodyYawRadians();
xAngleRadians = osg::clampBetween(xAngleRadians, -xLimit, xLimit); xAngleRadians = std::clamp(xAngleRadians, -xLimit, xLimit);
zAngleRadians = osg::clampBetween(zAngleRadians, -zLimit + zLimitOffset, zLimit + zLimitOffset); zAngleRadians = std::clamp(zAngleRadians, -zLimit + zLimitOffset, zLimit + zLimitOffset);
float factor = duration*5; float factor = duration*5;
factor = std::min(factor, 1.f); factor = std::min(factor, 1.f);

@ -113,10 +113,9 @@ namespace MWMechanics
+ 0.1f * attackerStats.getAttribute(ESM::Attribute::Luck).getModified(); + 0.1f * attackerStats.getAttribute(ESM::Attribute::Luck).getModified();
attackerTerm *= attackerStats.getFatigueTerm(); attackerTerm *= attackerStats.getFatigueTerm();
int x = int(blockerTerm - attackerTerm); const int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger();
int iBlockMaxChance = gmst.find("iBlockMaxChance")->mValue.getInteger(); const int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger();
int iBlockMinChance = gmst.find("iBlockMinChance")->mValue.getInteger(); int x = std::clamp<int>(blockerTerm - attackerTerm, iBlockMinChance, iBlockMaxChance);
x = std::min(iBlockMaxChance, std::max(iBlockMinChance, x));
if (Misc::Rng::roll0to99() < x) if (Misc::Rng::roll0to99() < x)
{ {

@ -13,9 +13,7 @@ float scaleDamage(float damage, const MWWorld::Ptr& attacker, const MWWorld::Ptr
const MWWorld::Ptr& player = MWMechanics::getPlayer(); const MWWorld::Ptr& player = MWMechanics::getPlayer();
// [-500, 500] // [-500, 500]
int difficultySetting = Settings::Manager::getInt("difficulty", "Game"); const int difficultySetting = std::clamp(Settings::Manager::getInt("difficulty", "Game"), -500, 500);
difficultySetting = std::min(difficultySetting, 500);
difficultySetting = std::max(difficultySetting, -500);
static const float fDifficultyMult = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fDifficultyMult")->mValue.getFloat(); static const float fDifficultyMult = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>().find("fDifficultyMult")->mValue.getFloat();

@ -356,10 +356,10 @@ namespace MWMechanics
ESM::WeaponType::Class weapclass = MWMechanics::getWeaponType(mWeaponType)->mWeaponClass; ESM::WeaponType::Class weapclass = MWMechanics::getWeaponType(mWeaponType)->mWeaponClass;
if (weapclass == ESM::WeaponType::Thrown || weapclass == ESM::WeaponType::Ammo) if (weapclass == ESM::WeaponType::Thrown || weapclass == ESM::WeaponType::Ammo)
{ {
static const float multiplier = std::max(0.f, std::min(1.0f, Settings::Manager::getFloat("projectiles enchant multiplier", "Game"))); static const float multiplier = std::clamp(Settings::Manager::getFloat("projectiles enchant multiplier", "Game"), 0.f, 1.f);
MWWorld::Ptr player = getPlayer(); MWWorld::Ptr player = getPlayer();
int itemsInInventoryCount = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId()); count = player.getClass().getContainerStore(player).count(mOldItemPtr.getCellRef().getRefId());
count = std::min(itemsInInventoryCount, std::max(1, int(getGemCharge() * multiplier / enchantPoints))); count = std::clamp<int>(getGemCharge() * multiplier / enchantPoints, 1, count);
} }
} }

@ -545,9 +545,9 @@ namespace MWMechanics
x += ptr.getClass().getCreatureStats(ptr).getMagicEffects().get(ESM::MagicEffect::Charm).getMagnitude(); x += ptr.getClass().getCreatureStats(ptr).getMagicEffects().get(ESM::MagicEffect::Charm).getMagnitude();
if(clamp) if (clamp)
return std::max(0,std::min(int(x),100));//, normally clamped to [0..100] when used return std::clamp<int>(x, 0, 100);//, normally clamped to [0..100] when used
return int(x); return static_cast<int>(x);
} }
int MechanicsManager::getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying) int MechanicsManager::getBarterOffer(const MWWorld::Ptr& ptr,int basePrice, bool buying)
@ -649,9 +649,9 @@ namespace MWMechanics
int flee = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Flee).getBase(); int flee = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Flee).getBase();
int fight = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Fight).getBase(); int fight = npcStats.getAiSetting(MWMechanics::CreatureStats::AI_Fight).getBase();
npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Flee, npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Flee,
std::max(0, std::min(100, flee + int(std::max(iPerMinChange, s))))); std::clamp(flee + int(std::max(iPerMinChange, s)), 0, 100));
npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Fight, npcStats.setAiSetting (MWMechanics::CreatureStats::AI_Fight,
std::max(0, std::min(100, fight + int(std::min(-iPerMinChange, -s))))); std::clamp(fight + int(std::min(-iPerMinChange, -s)), 0, 100));
} }
float c = -std::abs(floor(r * fPerDieRollMult)); float c = -std::abs(floor(r * fPerDieRollMult));
@ -689,10 +689,10 @@ namespace MWMechanics
float s = c * fPerDieRollMult * fPerTempMult; float s = c * fPerDieRollMult * fPerTempMult;
int flee = npcStats.getAiSetting (CreatureStats::AI_Flee).getBase(); int flee = npcStats.getAiSetting (CreatureStats::AI_Flee).getBase();
int fight = npcStats.getAiSetting (CreatureStats::AI_Fight).getBase(); int fight = npcStats.getAiSetting (CreatureStats::AI_Fight).getBase();
npcStats.setAiSetting (CreatureStats::AI_Flee, npcStats.setAiSetting(CreatureStats::AI_Flee,
std::max(0, std::min(100, flee + std::min(-int(iPerMinChange), int(-s))))); std::clamp(flee + std::min(-int(iPerMinChange), int(-s)), 0, 100));
npcStats.setAiSetting (CreatureStats::AI_Fight, npcStats.setAiSetting(CreatureStats::AI_Fight,
std::max(0, std::min(100, fight + std::max(int(iPerMinChange), int(s))))); std::clamp(fight + std::max(int(iPerMinChange), int(s)), 0, 100));
} }
x = floor(-c * fPerDieRollMult); x = floor(-c * fPerDieRollMult);

@ -371,7 +371,7 @@ int MWMechanics::NpcStats::getReputation() const
void MWMechanics::NpcStats::setReputation(int reputation) void MWMechanics::NpcStats::setReputation(int reputation)
{ {
// Reputation is capped in original engine // Reputation is capped in original engine
mReputation = std::min(255, std::max(0, reputation)); mReputation = std::clamp(reputation, 0, 255);
} }
int MWMechanics::NpcStats::getCrimeId() const int MWMechanics::NpcStats::getCrimeId() const

@ -631,7 +631,7 @@ void applyMagicEffect(const MWWorld::Ptr& target, const MWWorld::Ptr& caster, co
if (!target.isInCell() || !target.getCell()->isExterior() || godmode) if (!target.isInCell() || !target.getCell()->isExterior() || godmode)
break; break;
float time = world->getTimeStamp().getHour(); float time = world->getTimeStamp().getHour();
float timeDiff = std::min(7.f, std::max(0.f, std::abs(time - 13))); float timeDiff = std::clamp(std::abs(time - 13.f), 0.f, 7.f);
float damageScale = 1.f - timeDiff / 7.f; float damageScale = 1.f - timeDiff / 7.f;
// When cloudy, the sun damage effect is halved // When cloudy, the sun damage effect is halved
static float fMagicSunBlockedMult = world->getStore().get<ESM::GameSetting>().find("fMagicSunBlockedMult")->mValue.getFloat(); static float fMagicSunBlockedMult = world->getStore().get<ESM::GameSetting>().find("fMagicSunBlockedMult")->mValue.getFloat();

@ -162,7 +162,10 @@ namespace MWMechanics
float castChance = baseChance + castBonus; float castChance = baseChance + castBonus;
castChance *= stats.getFatigueTerm(); castChance *= stats.getFatigueTerm();
return std::max(0.f, cap ? std::min(100.f, castChance) : castChance); if (cap)
return std::clamp(castChance, 0.f, 100.f);
return std::max(castChance, 0.f);
} }
float getSpellSuccessChance (const std::string& spellId, const MWWorld::Ptr& actor, int* effectiveSchool, bool cap, bool checkMagicka) float getSpellSuccessChance (const std::string& spellId, const MWWorld::Ptr& actor, int* effectiveSchool, bool cap, bool checkMagicka)

@ -128,8 +128,7 @@ namespace MWMechanics
} }
// Take hit chance in account, but do not allow rating become negative. // Take hit chance in account, but do not allow rating become negative.
float chance = getHitChance(actor, enemy, value) / 100.f; rating *= std::clamp(getHitChance(actor, enemy, value) / 100.f, 0.01f, 1.f);
rating *= std::min(1.f, std::max(0.01f, chance));
if (weapclass != ESM::WeaponType::Ammo) if (weapclass != ESM::WeaponType::Ammo)
rating *= weapon->mData.mSpeed; rating *= weapon->mData.mSpeed;

@ -15,9 +15,9 @@ namespace MWPhysics
const btVector3& position, const btScalar radius) const btVector3& position, const btScalar radius)
{ {
const btVector3 nearest( const btVector3 nearest(
std::max(aabbMin.x(), std::min(aabbMax.x(), position.x())), std::clamp(position.x(), aabbMin.x(), aabbMax.x()),
std::max(aabbMin.y(), std::min(aabbMax.y(), position.y())), std::clamp(position.y(), aabbMin.y(), aabbMax.y()),
std::max(aabbMin.z(), std::min(aabbMax.z(), position.z())) std::clamp(position.z(), aabbMin.z(), aabbMax.z())
); );
return nearest.distance(position) < radius; return nearest.distance(position) < radius;
} }

@ -718,7 +718,7 @@ namespace MWPhysics
physicActor->setCanWaterWalk(waterCollision); physicActor->setCanWaterWalk(waterCollision);
// Slow fall reduces fall speed by a factor of (effect magnitude / 200) // Slow fall reduces fall speed by a factor of (effect magnitude / 200)
const float slowFall = 1.f - std::max(0.f, std::min(1.f, effects.get(ESM::MagicEffect::SlowFall).getMagnitude() * 0.005f)); const float slowFall = 1.f - std::clamp(effects.get(ESM::MagicEffect::SlowFall).getMagnitude() * 0.005f, 0.f, 1.f);
const bool godmode = ptr == world->getPlayerConstPtr() && world->getGodModeState(); const bool godmode = ptr == world->getPlayerConstPtr() && world->getGodModeState();
const bool inert = stats.isDead() || (!godmode && stats.getMagicEffects().get(ESM::MagicEffect::Paralyze).getModifier() > 0); const bool inert = stats.isDead() || (!godmode && stats.getMagicEffects().get(ESM::MagicEffect::Paralyze).getModifier() > 0);

@ -236,7 +236,7 @@ namespace MWRender
mTotalMovement += speed * duration; mTotalMovement += speed * duration;
speed /= (1.f + speed / 500.f); speed /= (1.f + speed / 500.f);
float maxDelta = 300.f * duration; float maxDelta = 300.f * duration;
mSmoothedSpeed += osg::clampBetween(speed - mSmoothedSpeed, -maxDelta, maxDelta); mSmoothedSpeed += std::clamp(speed - mSmoothedSpeed, -maxDelta, maxDelta);
mMaxNextCameraDistance = mCameraDistance + duration * (100.f + mBaseCameraDistance); mMaxNextCameraDistance = mCameraDistance + duration * (100.f + mBaseCameraDistance);
updateStandingPreviewMode(); updateStandingPreviewMode();
@ -434,7 +434,7 @@ namespace MWRender
{ {
const float epsilon = 0.000001f; const float epsilon = 0.000001f;
float limit = static_cast<float>(osg::PI_2) - epsilon; float limit = static_cast<float>(osg::PI_2) - epsilon;
mPitch = osg::clampBetween(angle, -limit, limit); mPitch = std::clamp(angle, -limit, limit);
} }
float Camera::getCameraDistance() const float Camera::getCameraDistance() const
@ -460,7 +460,7 @@ namespace MWRender
} }
mIsNearest = mBaseCameraDistance <= mNearest; mIsNearest = mBaseCameraDistance <= mNearest;
mBaseCameraDistance = osg::clampBetween(mBaseCameraDistance, mNearest, mFurthest); mBaseCameraDistance = std::clamp(mBaseCameraDistance, mNearest, mFurthest);
Settings::Manager::setFloat("third person camera distance", "Camera", mBaseCameraDistance); Settings::Manager::setFloat("third person camera distance", "Camera", mBaseCameraDistance);
} }

@ -562,8 +562,8 @@ bool LocalMap::isPositionExplored (float nX, float nY, int x, int y)
if (!segment.mFogOfWarImage) if (!segment.mFogOfWarImage)
return false; return false;
nX = std::max(0.f, std::min(1.f, nX)); nX = std::clamp(nX, 0.f, 1.f);
nY = std::max(0.f, std::min(1.f, nY)); nY = std::clamp(nY, 0.f, 1.f);
int texU = static_cast<int>((sFogOfWarResolution - 1) * nX); int texU = static_cast<int>((sFogOfWarResolution - 1) * nX);
int texV = static_cast<int>((sFogOfWarResolution - 1) * nY); int texV = static_cast<int>((sFogOfWarResolution - 1) * nY);
@ -648,7 +648,7 @@ void LocalMap::updatePlayer (const osg::Vec3f& position, const osg::Quat& orient
uint32_t clr = *(uint32_t*)data; uint32_t clr = *(uint32_t*)data;
uint8_t alpha = (clr >> 24); uint8_t alpha = (clr >> 24);
alpha = std::min( alpha, (uint8_t) (std::max(0.f, std::min(1.f, (sqrDist/sqrExploreRadius)))*255) ); alpha = std::min( alpha, (uint8_t) (std::clamp((sqrDist/sqrExploreRadius)*255, 0.f, 1.f)));
uint32_t val = (uint32_t) (alpha << 24); uint32_t val = (uint32_t) (alpha << 24);
if ( *data != val) if ( *data != val)
{ {

@ -733,12 +733,8 @@ namespace MWRender
} }
void clampToCell(osg::Vec3f& cellPos) void clampToCell(osg::Vec3f& cellPos)
{ {
osg::Vec2i min (mCell.x(), mCell.y()); cellPos.x() = std::clamp<float>(cellPos.x(), mCell.x(), mCell.x() + 1);
osg::Vec2i max (mCell.x()+1, mCell.y()+1); cellPos.y() = std::clamp<float>(cellPos.y(), mCell.y(), mCell.y() + 1);
if (cellPos.x() < min.x()) cellPos.x() = min.x();
if (cellPos.x() > max.x()) cellPos.x() = max.x();
if (cellPos.y() < min.y()) cellPos.y() = min.y();
if (cellPos.y() > max.y()) cellPos.y() = max.y();
} }
osg::Vec3f mPosition; osg::Vec3f mPosition;
osg::Vec2i mCell; osg::Vec2i mCell;

@ -297,7 +297,8 @@ namespace MWRender
, mViewDistance(Settings::Manager::getFloat("viewing distance", "Camera")) , mViewDistance(Settings::Manager::getFloat("viewing distance", "Camera"))
, mFieldOfViewOverridden(false) , mFieldOfViewOverridden(false)
, mFieldOfViewOverride(0.f) , mFieldOfViewOverride(0.f)
, mFieldOfView(std::min(std::max(1.f, Settings::Manager::getFloat("field of view", "Camera")), 179.f)) , mFieldOfView(std::clamp(Settings::Manager::getFloat("field of view", "Camera"), 1.f, 179.f))
, mFirstPersonFieldOfView(std::clamp(Settings::Manager::getFloat("first person field of view", "Camera"), 1.f, 179.f))
{ {
bool reverseZ = SceneUtil::getReverseZ(); bool reverseZ = SceneUtil::getReverseZ();
@ -517,8 +518,6 @@ namespace MWRender
NifOsg::Loader::setIntersectionDisabledNodeMask(Mask_Effect); NifOsg::Loader::setIntersectionDisabledNodeMask(Mask_Effect);
Nif::NIFFile::setLoadUnsupportedFiles(Settings::Manager::getBool("load unsupported nif files", "Models")); Nif::NIFFile::setLoadUnsupportedFiles(Settings::Manager::getBool("load unsupported nif files", "Models"));
float firstPersonFov = Settings::Manager::getFloat("first person field of view", "Camera");
mFirstPersonFieldOfView = std::min(std::max(1.f, firstPersonFov), 179.f);
mStateUpdater->setFogEnd(mViewDistance); mStateUpdater->setFogEnd(mViewDistance);
mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("simpleWater", false)); mRootNode->getOrCreateStateSet()->addUniform(new osg::Uniform("simpleWater", false));

@ -305,8 +305,7 @@ public:
void setWaterLevel(float waterLevel) void setWaterLevel(float waterLevel)
{ {
const float refractionScale = std::min(1.0f, std::max(0.0f, const float refractionScale = std::clamp(Settings::Manager::getFloat("refraction scale", "Water"), 0.f, 1.f);
Settings::Manager::getFloat("refraction scale", "Water")));
mViewMatrix = osg::Matrix::scale(1, 1, refractionScale) * mViewMatrix = osg::Matrix::scale(1, 1, refractionScale) *
osg::Matrix::translate(0, 0, (1.0 - refractionScale) * waterLevel); osg::Matrix::translate(0, 0, (1.0 - refractionScale) * waterLevel);
@ -400,7 +399,7 @@ private:
unsigned int calcNodeMask() unsigned int calcNodeMask()
{ {
int reflectionDetail = Settings::Manager::getInt("reflection detail", "Water"); int reflectionDetail = Settings::Manager::getInt("reflection detail", "Water");
reflectionDetail = std::min(5, std::max(mInterior ? 2 : 0, reflectionDetail)); reflectionDetail = std::clamp(reflectionDetail, mInterior ? 2 : 0, 5);
unsigned int extraMask = 0; unsigned int extraMask = 0;
if(reflectionDetail >= 1) extraMask |= Mask_Terrain; if(reflectionDetail >= 1) extraMask |= Mask_Terrain;
if(reflectionDetail >= 2) extraMask |= Mask_Static; if(reflectionDetail >= 2) extraMask |= Mask_Static;
@ -583,7 +582,7 @@ void Water::createSimpleWaterStateSet(osg::Node* node, float alpha)
// Add animated textures // Add animated textures
std::vector<osg::ref_ptr<osg::Texture2D> > textures; std::vector<osg::ref_ptr<osg::Texture2D> > textures;
int frameCount = std::max(0, std::min(Fallback::Map::getInt("Water_SurfaceFrameCount"), 320)); const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320);
const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture"); const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture");
for (int i=0; i<frameCount; ++i) for (int i=0; i<frameCount; ++i)
{ {
@ -724,7 +723,7 @@ Water::~Water()
void Water::listAssetsToPreload(std::vector<std::string> &textures) void Water::listAssetsToPreload(std::vector<std::string> &textures)
{ {
int frameCount = std::max(0, std::min(Fallback::Map::getInt("Water_SurfaceFrameCount"), 320)); const int frameCount = std::clamp(Fallback::Map::getInt("Water_SurfaceFrameCount"), 0, 320);
const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture"); const std::string& texture = Fallback::Map::getString("Water_SurfaceTexture");
for (int i=0; i<frameCount; ++i) for (int i=0; i<frameCount; ++i)
{ {

@ -208,8 +208,7 @@ namespace MWScript
{ {
if(!repeat) if(!repeat)
repeat = true; repeat = true;
Interpreter::Type_Integer idleValue = runtime[0].mInteger; Interpreter::Type_Integer idleValue = std::clamp(runtime[0].mInteger, 0, 255);
idleValue = std::min(255, std::max(0, idleValue));
idleList.push_back(idleValue); idleList.push_back(idleValue);
runtime.pop(); runtime.pop();
--arg0; --arg0;

@ -108,7 +108,7 @@ namespace MWScript
chances.reserve(10); chances.reserve(10);
while(arg0 > 0) while(arg0 > 0)
{ {
chances.push_back(std::max(0, std::min(127, runtime[0].mInteger))); chances.push_back(std::clamp(runtime[0].mInteger, 0, 127));
runtime.pop(); runtime.pop();
arg0--; arg0--;
} }

@ -40,7 +40,7 @@ void Sound_Loudness::analyzeLoudness(const std::vector< char >& data)
else if (mSampleType == SampleType_Float32) else if (mSampleType == SampleType_Float32)
{ {
value = *reinterpret_cast<const float*>(&mQueue[sample*advance]); value = *reinterpret_cast<const float*>(&mQueue[sample*advance]);
value = std::max(-1.f, std::min(1.f, value)); // Float samples *should* be scaled to [-1,1] already. value = std::clamp(value, -1.f, 1.f); // Float samples *should* be scaled to [-1,1] already.
} }
sum += value*value; sum += value*value;
@ -64,8 +64,7 @@ float Sound_Loudness::getLoudnessAtTime(float sec) const
if(mSamplesPerSec <= 0.0f || mSamples.empty() || sec < 0.0f) if(mSamplesPerSec <= 0.0f || mSamples.empty() || sec < 0.0f)
return 0.0f; return 0.0f;
size_t index = static_cast<size_t>(sec * mSamplesPerSec); size_t index = std::clamp<size_t>(sec * mSamplesPerSec, 0, mSamples.size() - 1);
index = std::max<size_t>(0, std::min(index, mSamples.size()-1));
return mSamples[index]; return mSamples[index];
} }

@ -10,7 +10,7 @@ namespace MWSound
{ {
float clamp(float value) float clamp(float value)
{ {
return std::max(0.0f, std::min(1.0f, value)); return std::clamp(value, 0.f, 1.f);
} }
} }

@ -1334,7 +1334,7 @@ namespace MWWorld
* currently it's done so for rotating the camera, which needs * currently it's done so for rotating the camera, which needs
* clamping. * clamping.
*/ */
objRot[0] = osg::clampBetween<float>(objRot[0], -osg::PI_2, osg::PI_2); objRot[0] = std::clamp<float>(objRot[0], -osg::PI_2, osg::PI_2);
objRot[1] = Misc::normalizeAngle(objRot[1]); objRot[1] = Misc::normalizeAngle(objRot[1]);
objRot[2] = Misc::normalizeAngle(objRot[2]); objRot[2] = Misc::normalizeAngle(objRot[2]);
} }
@ -1901,7 +1901,7 @@ namespace MWWorld
const auto& magicEffects = player.getClass().getCreatureStats(player).getMagicEffects(); const auto& magicEffects = player.getClass().getCreatureStats(player).getMagicEffects();
if (!mGodMode) if (!mGodMode)
blind = static_cast<int>(magicEffects.get(ESM::MagicEffect::Blind).getMagnitude()); blind = static_cast<int>(magicEffects.get(ESM::MagicEffect::Blind).getMagnitude());
MWBase::Environment::get().getWindowManager()->setBlindness(std::max(0, std::min(100, blind))); MWBase::Environment::get().getWindowManager()->setBlindness(std::clamp(blind, 0, 100));
int nightEye = static_cast<int>(magicEffects.get(ESM::MagicEffect::NightEye).getMagnitude()); int nightEye = static_cast<int>(magicEffects.get(ESM::MagicEffect::NightEye).getMagnitude());
mRendering->setNightEyeFactor(std::min(1.f, (nightEye/100.f))); mRendering->setNightEyeFactor(std::min(1.f, (nightEye/100.f)));

@ -169,7 +169,7 @@ namespace ESM
{ {
float height = mLandData->mHeights[int(row * vertMult) * ESM::Land::LAND_SIZE + int(col * vertMult)]; float height = mLandData->mHeights[int(row * vertMult) * ESM::Land::LAND_SIZE + int(col * vertMult)];
height /= height > 0 ? 128.f : 16.f; height /= height > 0 ? 128.f : 16.f;
height = std::min(max, std::max(min, height)); height = std::clamp(height, min, max);
wnam[row * LAND_GLOBAL_MAP_LOD_SIZE_SQRT + col] = static_cast<signed char>(height); wnam[row * LAND_GLOBAL_MAP_LOD_SIZE_SQRT + col] = static_cast<signed char>(height);
} }
} }

@ -145,7 +145,7 @@ namespace Gui
FontLoader::FontLoader(ToUTF8::FromType encoding, const VFS::Manager* vfs, const std::string& userDataPath, float scalingFactor) FontLoader::FontLoader(ToUTF8::FromType encoding, const VFS::Manager* vfs, const std::string& userDataPath, float scalingFactor)
: mVFS(vfs) : mVFS(vfs)
, mUserDataPath(userDataPath) , mUserDataPath(userDataPath)
, mFontHeight(16) , mFontHeight(std::clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20))
, mScalingFactor(scalingFactor) , mScalingFactor(scalingFactor)
{ {
if (encoding == ToUTF8::WINDOWS_1252) if (encoding == ToUTF8::WINDOWS_1252)
@ -153,9 +153,6 @@ namespace Gui
else else
mEncoding = encoding; mEncoding = encoding;
int fontSize = Settings::Manager::getInt("font size", "GUI");
mFontHeight = std::min(std::max(12, fontSize), 20);
MyGUI::ResourceManager::getInstance().unregisterLoadXmlDelegate("Resource"); MyGUI::ResourceManager::getInstance().unregisterLoadXmlDelegate("Resource");
MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("Resource") = MyGUI::newDelegate(this, &FontLoader::loadFontFromXml); MyGUI::ResourceManager::getInstance().registerLoadXmlDelegate("Resource") = MyGUI::newDelegate(this, &FontLoader::loadFontFromXml);
} }
@ -549,7 +546,7 @@ namespace Gui
// to allow to configure font size via config file, without need to edit XML files. // to allow to configure font size via config file, without need to edit XML files.
// Also we should take UI scaling factor in account. // Also we should take UI scaling factor in account.
int resolution = Settings::Manager::getInt("ttf resolution", "GUI"); int resolution = Settings::Manager::getInt("ttf resolution", "GUI");
resolution = std::min(960, std::max(48, resolution)) * mScalingFactor; resolution = std::clamp(resolution, 48, 960) * mScalingFactor;
MyGUI::xml::ElementPtr resolutionNode = resourceNode->createChild("Property"); MyGUI::xml::ElementPtr resolutionNode = resourceNode->createChild("Property");
resolutionNode->addAttribute("key", "Resolution"); resolutionNode->addAttribute("key", "Resolution");
@ -591,7 +588,7 @@ namespace Gui
// setup separate fonts with different Resolution to fit these windows. // setup separate fonts with different Resolution to fit these windows.
// These fonts have an internal prefix. // These fonts have an internal prefix.
int resolution = Settings::Manager::getInt("ttf resolution", "GUI"); int resolution = Settings::Manager::getInt("ttf resolution", "GUI");
resolution = std::min(960, std::max(48, resolution)); resolution = std::clamp(resolution, 48, 960);
float currentX = Settings::Manager::getInt("resolution x", "Video"); float currentX = Settings::Manager::getInt("resolution x", "Video");
float currentY = Settings::Manager::getInt("resolution y", "Video"); float currentY = Settings::Manager::getInt("resolution y", "Video");

@ -57,7 +57,7 @@ float ControllerFunction::calculate(float value) const
} }
case Constant: case Constant:
default: default:
return std::min(mStopTime, std::max(mStartTime, time)); return std::clamp(time, mStartTime, mStopTime);
} }
} }

@ -27,8 +27,7 @@ namespace SceneUtil
mShadowSettings->setLightNum(0); mShadowSettings->setLightNum(0);
mShadowSettings->setReceivesShadowTraversalMask(~0u); mShadowSettings->setReceivesShadowTraversalMask(~0u);
int numberOfShadowMapsPerLight = Settings::Manager::getInt("number of shadow maps", "Shadows"); const int numberOfShadowMapsPerLight = std::clamp(Settings::Manager::getInt("number of shadow maps", "Shadows"), 1, 8);
numberOfShadowMapsPerLight = std::max(1, std::min(numberOfShadowMapsPerLight, 8));
mShadowSettings->setNumShadowMapsPerLight(numberOfShadowMapsPerLight); mShadowSettings->setNumShadowMapsPerLight(numberOfShadowMapsPerLight);
mShadowSettings->setBaseShadowTextureUnit(8 - numberOfShadowMapsPerLight); mShadowSettings->setBaseShadowTextureUnit(8 - numberOfShadowMapsPerLight);
@ -36,7 +35,7 @@ namespace SceneUtil
const float maximumShadowMapDistance = Settings::Manager::getFloat("maximum shadow map distance", "Shadows"); const float maximumShadowMapDistance = Settings::Manager::getFloat("maximum shadow map distance", "Shadows");
if (maximumShadowMapDistance > 0) if (maximumShadowMapDistance > 0)
{ {
const float shadowFadeStart = std::min(std::max(0.f, Settings::Manager::getFloat("shadow fade start", "Shadows")), 1.f); const float shadowFadeStart = std::clamp(Settings::Manager::getFloat("shadow fade start", "Shadows"), 0.f, 1.f);
mShadowSettings->setMaximumShadowMapDistance(maximumShadowMapDistance); mShadowSettings->setMaximumShadowMapDistance(maximumShadowMapDistance);
mShadowTechnique->setShadowFadeStart(maximumShadowMapDistance * shadowFadeStart); mShadowTechnique->setShadowFadeStart(maximumShadowMapDistance * shadowFadeStart);
} }
@ -78,8 +77,7 @@ namespace SceneUtil
if (!Settings::Manager::getBool("enable shadows", "Shadows")) if (!Settings::Manager::getBool("enable shadows", "Shadows"))
return; return;
int numberOfShadowMapsPerLight = Settings::Manager::getInt("number of shadow maps", "Shadows"); const int numberOfShadowMapsPerLight = std::clamp(Settings::Manager::getInt("number of shadow maps", "Shadows"), 1, 8);
numberOfShadowMapsPerLight = std::max(1, std::min(numberOfShadowMapsPerLight, 8));
int baseShadowTextureUnit = 8 - numberOfShadowMapsPerLight; int baseShadowTextureUnit = 8 - numberOfShadowMapsPerLight;

@ -31,15 +31,11 @@ namespace Gui
} }
private: private:
static int clamp(const int& value, const int& lowBound, const int& highBound)
{
return std::min(std::max(lowBound, value), highBound);
}
std::string getFontSize() std::string getFontSize()
{ {
// Note: we can not use the FontLoader here, so there is a code duplication a bit. // Note: we can not use the FontLoader here, so there is a code duplication a bit.
static const std::string fontSize = std::to_string(clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20)); static const std::string fontSize = std::to_string(std::clamp(Settings::Manager::getInt("font size", "GUI"), 12, 20));
return fontSize; return fontSize;
} }
}; };

@ -31,7 +31,7 @@ namespace Gui
try try
{ {
mValue = std::stoi(newCaption); mValue = std::stoi(newCaption);
int capped = std::min(mMaxValue, std::max(mValue, mMinValue)); int capped = std::clamp(mValue, mMinValue, mMaxValue);
if (capped != mValue) if (capped != mValue)
{ {
mValue = capped; mValue = capped;

Loading…
Cancel
Save