Merge remote-tracking branch 'dteviot/Rng'

celladd
Marc Zinnschlag 10 years ago
commit 86d39cede9

@ -10,6 +10,8 @@
#include <SDL.h> #include <SDL.h>
#include <openengine/misc/rng.hpp>
#include <components/compiler/extensions0.hpp> #include <components/compiler/extensions0.hpp>
#include <components/bsa/resources.hpp> #include <components/bsa/resources.hpp>
@ -191,6 +193,7 @@ OMW::Engine::Engine(Files::ConfigurationManager& configurationManager)
, mExportFonts(false) , mExportFonts(false)
, mNewGame (false) , mNewGame (false)
{ {
OEngine::Misc::Rng::init();
std::srand ( static_cast<unsigned int>(std::time(NULL)) ); std::srand ( static_cast<unsigned int>(std::time(NULL)) );
MWClass::registerClasses(); MWClass::registerClasses();

@ -1,6 +1,8 @@
#include "creature.hpp" #include "creature.hpp"
#include <openengine/misc/rng.hpp>
#include <components/esm/loadcrea.hpp> #include <components/esm/loadcrea.hpp>
#include <components/esm/creaturestate.hpp> #include <components/esm/creaturestate.hpp>
@ -249,7 +251,7 @@ namespace MWClass
float hitchance = MWMechanics::getHitChance(ptr, victim, ref->mBase->mData.mCombat); float hitchance = MWMechanics::getHitChance(ptr, victim, ref->mBase->mData.mCombat);
if((::rand()/(RAND_MAX+1.0)) >= hitchance/100.0f) if(OEngine::Misc::Rng::rollProbability() >= hitchance/100.0f)
{ {
victim.getClass().onHit(victim, 0.0f, false, MWWorld::Ptr(), ptr, false); victim.getClass().onHit(victim, 0.0f, false, MWWorld::Ptr(), ptr, false);
MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr); MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr);
@ -375,8 +377,7 @@ namespace MWClass
float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * getGmst().fKnockDownMult->getFloat(); float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * getGmst().fKnockDownMult->getFloat();
float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified()
* getGmst().iKnockDownOddsMult->getInt() * 0.01f + getGmst().iKnockDownOddsBase->getInt(); * getGmst().iKnockDownOddsMult->getInt() * 0.01f + getGmst().iKnockDownOddsBase->getInt();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (ishealth && agilityTerm <= damage && knockdownTerm <= OEngine::Misc::Rng::roll0to99())
if (ishealth && agilityTerm <= damage && knockdownTerm <= roll)
{ {
getCreatureStats(ptr).setKnockedDown(true); getCreatureStats(ptr).setKnockedDown(true);
@ -680,7 +681,7 @@ namespace MWClass
++sound; ++sound;
} }
if(!sounds.empty()) if(!sounds.empty())
return sounds[(int)(rand()/(RAND_MAX+1.0)*sounds.size())]->mSound; return sounds[OEngine::Misc::Rng::rollDice(sounds.size())]->mSound;
} }
if (type == ESM::SoundGenerator::Land) if (type == ESM::SoundGenerator::Land)

@ -5,6 +5,8 @@
#include <OgreSceneNode.h> #include <OgreSceneNode.h>
#include <openengine/misc/rng.hpp>
#include <components/esm/loadmgef.hpp> #include <components/esm/loadmgef.hpp>
#include <components/esm/loadnpc.hpp> #include <components/esm/loadnpc.hpp>
#include <components/esm/npcstate.hpp> #include <components/esm/npcstate.hpp>
@ -513,7 +515,7 @@ namespace MWClass
float hitchance = MWMechanics::getHitChance(ptr, victim, ptr.getClass().getSkill(ptr, weapskill)); float hitchance = MWMechanics::getHitChance(ptr, victim, ptr.getClass().getSkill(ptr, weapskill));
if((::rand()/(RAND_MAX+1.0)) >= hitchance/100.0f) if (OEngine::Misc::Rng::rollProbability() >= hitchance / 100.0f)
{ {
othercls.onHit(victim, 0.0f, false, weapon, ptr, false); othercls.onHit(victim, 0.0f, false, weapon, ptr, false);
MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr); MWMechanics::reduceWeaponCondition(0.f, false, weapon, ptr);
@ -643,8 +645,7 @@ namespace MWClass
const GMST& gmst = getGmst(); const GMST& gmst = getGmst();
int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->getInt(); int chance = store.get<ESM::GameSetting>().find("iVoiceHitOdds")->getInt();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() < chance)
if (roll < chance)
{ {
MWBase::Environment::get().getDialogueManager()->say(ptr, "hit"); MWBase::Environment::get().getDialogueManager()->say(ptr, "hit");
} }
@ -653,8 +654,7 @@ namespace MWClass
float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->getFloat(); float agilityTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() * gmst.fKnockDownMult->getFloat();
float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified() float knockdownTerm = getCreatureStats(ptr).getAttribute(ESM::Attribute::Agility).getModified()
* gmst.iKnockDownOddsMult->getInt() * 0.01f + gmst.iKnockDownOddsBase->getInt(); * gmst.iKnockDownOddsMult->getInt() * 0.01f + gmst.iKnockDownOddsBase->getInt();
roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (ishealth && agilityTerm <= damage && knockdownTerm <= OEngine::Misc::Rng::roll0to99())
if (ishealth && agilityTerm <= damage && knockdownTerm <= roll)
{ {
getCreatureStats(ptr).setKnockedDown(true); getCreatureStats(ptr).setKnockedDown(true);
@ -680,7 +680,7 @@ namespace MWClass
MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron, MWWorld::InventoryStore::Slot_RightPauldron,
MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet MWWorld::InventoryStore::Slot_LeftGauntlet, MWWorld::InventoryStore::Slot_RightGauntlet
}; };
int hitslot = hitslots[(int)(::rand()/(RAND_MAX+1.0)*20.0)]; int hitslot = hitslots[OEngine::Misc::Rng::rollDice(20)];
float unmitigatedDamage = damage; float unmitigatedDamage = damage;
float x = damage / (damage + getArmorRating(ptr)); float x = damage / (damage + getArmorRating(ptr));

@ -1,5 +1,7 @@
#include <MyGUI_ScrollBar.h> #include <MyGUI_ScrollBar.h>
#include <openengine/misc/rng.hpp>
#include "../mwbase/windowmanager.hpp" #include "../mwbase/windowmanager.hpp"
#include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/mechanicsmanager.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
@ -83,7 +85,7 @@ namespace MWGui
std::set<int> skills; std::set<int> skills;
for (int day=0; day<mDays; ++day) for (int day=0; day<mDays; ++day)
{ {
int skill = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * ESM::Skill::Length); int skill = OEngine::Misc::Rng::rollDice(ESM::Skill::Length);
skills.insert(skill); skills.insert(skill);
MWMechanics::SkillValue& value = player.getClass().getNpcStats(player).getSkill(skill); MWMechanics::SkillValue& value = player.getClass().getNpcStats(player).getSkill(skill);

@ -15,6 +15,8 @@
#include <MyGUI_Gui.h> #include <MyGUI_Gui.h>
#include <MyGUI_TextBox.h> #include <MyGUI_TextBox.h>
#include <openengine/misc/rng.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
@ -146,7 +148,7 @@ namespace MWGui
if (!mResources.empty()) if (!mResources.empty())
{ {
std::string const & randomSplash = mResources.at (rand() % mResources.size()); std::string const & randomSplash = mResources.at(OEngine::Misc::Rng::rollDice(mResources.size()));
Ogre::TextureManager::getSingleton ().load (randomSplash, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); Ogre::TextureManager::getSingleton ().load (randomSplash, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);

@ -1,5 +1,7 @@
#include "pickpocketitemmodel.hpp" #include "pickpocketitemmodel.hpp"
#include <openengine/misc/rng.hpp>
#include "../mwmechanics/npcstats.hpp" #include "../mwmechanics/npcstats.hpp"
#include "../mwworld/class.hpp" #include "../mwworld/class.hpp"
@ -12,11 +14,13 @@ namespace MWGui
int chance = thief.getClass().getSkill(thief, ESM::Skill::Sneak); int chance = thief.getClass().getSkill(thief, ESM::Skill::Sneak);
mSourceModel->update(); mSourceModel->update();
// build list of items that player is unable to find when attempts to pickpocket.
if (hideItems) if (hideItems)
{ {
for (size_t i = 0; i<mSourceModel->getItemCount(); ++i) for (size_t i = 0; i<mSourceModel->getItemCount(); ++i)
{ {
if (std::rand() / static_cast<float>(RAND_MAX) * 100 > chance) if (chance <= OEngine::Misc::Rng::roll0to99())
mHiddenItems.push_back(mSourceModel->getItem(i)); mHiddenItems.push_back(mSourceModel->getItem(i));
} }
} }

@ -5,6 +5,8 @@
#include <MyGUI_ScrollView.h> #include <MyGUI_ScrollView.h>
#include <MyGUI_Gui.h> #include <MyGUI_Gui.h>
#include <openengine/misc/rng.hpp>
#include <components/esm/records.hpp> #include <components/esm/records.hpp>
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
@ -161,7 +163,7 @@ void Recharge::onItemClicked(MyGUI::Widget *sender)
intelligenceTerm = 1; intelligenceTerm = 1;
float x = (npcStats.getSkill(ESM::Skill::Enchant).getModified() + intelligenceTerm + luckTerm) * stats.getFatigueTerm(); float x = (npcStats.getSkill(ESM::Skill::Enchant).getModified() + intelligenceTerm + luckTerm) * stats.getFatigueTerm();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] int roll = OEngine::Misc::Rng::roll0to99();
if (roll < x) if (roll < x)
{ {
std::string soul = gem.getCellRef().getSoul(); std::string soul = gem.getCellRef().getSoul();

@ -4,6 +4,8 @@
#include <MyGUI_InputManager.h> #include <MyGUI_InputManager.h>
#include <MyGUI_ControllerManager.h> #include <MyGUI_ControllerManager.h>
#include <openengine/misc/rng.hpp>
#include <components/widgets/numericeditbox.hpp> #include <components/widgets/numericeditbox.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
@ -365,7 +367,7 @@ namespace MWGui
else else
x += abs(int(npcTerm - pcTerm)); x += abs(int(npcTerm - pcTerm));
int roll = std::rand()%100 + 1; int roll = OEngine::Misc::Rng::rollDice(100) + 1;
if(roll > x || (mCurrentMerchantOffer < 0) != (mCurrentBalance < 0)) //trade refused if(roll > x || (mCurrentMerchantOffer < 0) != (mCurrentBalance < 0)) //trade refused
{ {
MWBase::Environment::get().getWindowManager()-> MWBase::Environment::get().getWindowManager()->

@ -2,6 +2,8 @@
#include <MyGUI_ProgressBar.h> #include <MyGUI_ProgressBar.h>
#include <openengine/misc/rng.hpp>
#include <components/widgets/box.hpp> #include <components/widgets/box.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
@ -152,10 +154,9 @@ namespace MWGui
const ESM::Region *region = world->getStore().get<ESM::Region>().find (regionstr); const ESM::Region *region = world->getStore().get<ESM::Region>().find (regionstr);
if (!region->mSleepList.empty()) if (!region->mSleepList.empty())
{ {
// figure out if player will be woken while sleeping
float fSleepRandMod = world->getStore().get<ESM::GameSetting>().find("fSleepRandMod")->getFloat(); float fSleepRandMod = world->getStore().get<ESM::GameSetting>().find("fSleepRandMod")->getFloat();
int x = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * hoursToWait); // [0, hoursRested] if (OEngine::Misc::Rng::rollProbability() > fSleepRandMod)
float y = fSleepRandMod * hoursToWait;
if (x > y)
{ {
float fSleepRestMod = world->getStore().get<ESM::GameSetting>().find("fSleepRestMod")->getFloat(); float fSleepRestMod = world->getStore().get<ESM::GameSetting>().find("fSleepRestMod")->getFloat();
mInterruptAt = hoursToWait - int(fSleepRestMod * hoursToWait); mInterruptAt = hoursToWait - int(fSleepRestMod * hoursToWait);

@ -1,5 +1,7 @@
#include "activespells.hpp" #include "activespells.hpp"
#include <openengine/misc/rng.hpp>
#include <components/misc/stringops.hpp> #include <components/misc/stringops.hpp>
#include <components/esm/loadmgef.hpp> #include <components/esm/loadmgef.hpp>
@ -229,8 +231,7 @@ namespace MWMechanics
{ {
for (TContainer::iterator it = mSpells.begin(); it != mSpells.end(); ) for (TContainer::iterator it = mSpells.begin(); it != mSpells.end(); )
{ {
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() < chance)
if (roll < chance)
mSpells.erase(it++); mSpells.erase(it++);
else else
++it; ++it;

@ -2,6 +2,8 @@
#include <OgreMath.h> #include <OgreMath.h>
#include <openengine/misc/rng.hpp>
#include <components/esm/aisequence.hpp> #include <components/esm/aisequence.hpp>
#include "../mwworld/class.hpp" #include "../mwworld/class.hpp"
@ -393,7 +395,7 @@ namespace MWMechanics
if (!distantCombat) attackType = chooseBestAttack(weapon, movement); if (!distantCombat) attackType = chooseBestAttack(weapon, movement);
else attackType = ESM::Weapon::AT_Chop; // cause it's =0 else attackType = ESM::Weapon::AT_Chop; // cause it's =0
strength = static_cast<float>(rand()) / RAND_MAX; strength = OEngine::Misc::Rng::rollClosedProbability();
// Note: may be 0 for some animations // Note: may be 0 for some animations
timerAttack = minMaxAttackDuration[attackType][0] + timerAttack = minMaxAttackDuration[attackType][0] +
@ -404,8 +406,7 @@ namespace MWMechanics
{ {
const MWWorld::ESMStore &store = world->getStore(); const MWWorld::ESMStore &store = world->getStore();
int chance = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->getInt(); int chance = store.get<ESM::GameSetting>().find("iVoiceAttackOdds")->getInt();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() < chance)
if (roll < chance)
{ {
MWBase::Environment::get().getDialogueManager()->say(actor, "attack"); MWBase::Environment::get().getDialogueManager()->say(actor, "attack");
} }
@ -512,17 +513,17 @@ namespace MWMechanics
{ {
if(movement.mPosition[0] || movement.mPosition[1]) if(movement.mPosition[0] || movement.mPosition[1])
{ {
timerCombatMove = 0.1f + 0.1f * static_cast<float>(rand())/RAND_MAX; timerCombatMove = 0.1f + 0.1f * OEngine::Misc::Rng::rollClosedProbability();
combatMove = true; combatMove = true;
} }
// only NPCs are smart enough to use dodge movements // only NPCs are smart enough to use dodge movements
else if(actorClass.isNpc() && (!distantCombat || (distantCombat && distToTarget < rangeAttack/2))) else if(actorClass.isNpc() && (!distantCombat || (distantCombat && distToTarget < rangeAttack/2)))
{ {
//apply sideway movement (kind of dodging) with some probability //apply sideway movement (kind of dodging) with some probability
if(static_cast<float>(rand())/RAND_MAX < 0.25) if (OEngine::Misc::Rng::rollClosedProbability() < 0.25)
{ {
movement.mPosition[0] = static_cast<float>(rand())/RAND_MAX < 0.5? 1.0f : -1.0f; movement.mPosition[0] = OEngine::Misc::Rng::rollProbability() < 0.5 ? 1.0f : -1.0f;
timerCombatMove = 0.05f + 0.15f * static_cast<float>(rand())/RAND_MAX; timerCombatMove = 0.05f + 0.15f * OEngine::Misc::Rng::rollClosedProbability();
combatMove = true; combatMove = true;
} }
} }
@ -637,7 +638,7 @@ namespace MWMechanics
float s2 = speed2 * t; float s2 = speed2 * t;
float t_swing = float t_swing =
minMaxAttackDuration[ESM::Weapon::AT_Thrust][0] + minMaxAttackDuration[ESM::Weapon::AT_Thrust][0] +
(minMaxAttackDuration[ESM::Weapon::AT_Thrust][1] - minMaxAttackDuration[ESM::Weapon::AT_Thrust][0]) * static_cast<float>(rand()) / RAND_MAX; (minMaxAttackDuration[ESM::Weapon::AT_Thrust][1] - minMaxAttackDuration[ESM::Weapon::AT_Thrust][0]) * OEngine::Misc::Rng::rollClosedProbability();
if (t + s2/speed1 <= t_swing) if (t + s2/speed1 <= t_swing)
{ {
@ -761,10 +762,10 @@ ESM::Weapon::AttackType chooseBestAttack(const ESM::Weapon* weapon, MWMechanics:
if (weapon == NULL) if (weapon == NULL)
{ {
//hand-to-hand deal equal damage for each type //hand-to-hand deal equal damage for each type
float roll = static_cast<float>(rand())/RAND_MAX; float roll = OEngine::Misc::Rng::rollClosedProbability();
if(roll <= 0.333f) //side punch if(roll <= 0.333f) //side punch
{ {
movement.mPosition[0] = (static_cast<float>(rand())/RAND_MAX < 0.5f)? 1.0f : -1.0f; movement.mPosition[0] = OEngine::Misc::Rng::rollClosedProbability() ? 1.0f : -1.0f;
movement.mPosition[1] = 0; movement.mPosition[1] = 0;
attackType = ESM::Weapon::AT_Slash; attackType = ESM::Weapon::AT_Slash;
} }
@ -788,10 +789,10 @@ ESM::Weapon::AttackType chooseBestAttack(const ESM::Weapon* weapon, MWMechanics:
float total = static_cast<float>(slash + chop + thrust); float total = static_cast<float>(slash + chop + thrust);
float roll = static_cast<float>(rand())/RAND_MAX; float roll = OEngine::Misc::Rng::rollClosedProbability();
if(roll <= (slash/total)) if(roll <= (slash/total))
{ {
movement.mPosition[0] = (static_cast<float>(rand())/RAND_MAX < 0.5f)? 1.0f : -1.0f; movement.mPosition[0] = (OEngine::Misc::Rng::rollClosedProbability() < 0.5f) ? 1.0f : -1.0f;
movement.mPosition[1] = 0; movement.mPosition[1] = 0;
attackType = ESM::Weapon::AT_Slash; attackType = ESM::Weapon::AT_Slash;
} }

@ -3,6 +3,8 @@
#include <OgreVector3.h> #include <OgreVector3.h>
#include <OgreSceneNode.h> #include <OgreSceneNode.h>
#include <openengine/misc/rng.hpp>
#include <components/esm/aisequence.hpp> #include <components/esm/aisequence.hpp>
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
@ -315,7 +317,7 @@ namespace MWMechanics
static float fVoiceIdleOdds = MWBase::Environment::get().getWorld()->getStore() static float fVoiceIdleOdds = MWBase::Environment::get().getWorld()->getStore()
.get<ESM::GameSetting>().find("fVoiceIdleOdds")->getFloat(); .get<ESM::GameSetting>().find("fVoiceIdleOdds")->getFloat();
float roll = std::rand()/ (static_cast<float> (RAND_MAX) + 1) * 10000; float roll = OEngine::Misc::Rng::rollProbability() * 10000.0f;
// In vanilla MW the chance was FPS dependent, and did not allow proper changing of fVoiceIdleOdds // In vanilla MW the chance was FPS dependent, and did not allow proper changing of fVoiceIdleOdds
// due to the roll being an integer. // due to the roll being an integer.
@ -490,7 +492,7 @@ namespace MWMechanics
if(!storage.mPathFinder.isPathConstructed()) if(!storage.mPathFinder.isPathConstructed())
{ {
assert(mAllowedNodes.size()); assert(mAllowedNodes.size());
unsigned int randNode = (int)(rand() / ((double)RAND_MAX + 1) * mAllowedNodes.size()); unsigned int randNode = OEngine::Misc::Rng::rollDice(mAllowedNodes.size());
// NOTE: initially constructed with local (i.e. cell) co-ordinates // NOTE: initially constructed with local (i.e. cell) co-ordinates
Ogre::Vector3 destNodePos(PathFinder::MakeOgreVector3(mAllowedNodes[randNode])); Ogre::Vector3 destNodePos(PathFinder::MakeOgreVector3(mAllowedNodes[randNode]));
@ -637,7 +639,7 @@ namespace MWMechanics
.get<ESM::GameSetting>().find("fIdleChanceMultiplier")->getFloat(); .get<ESM::GameSetting>().find("fIdleChanceMultiplier")->getFloat();
unsigned short idleChance = static_cast<unsigned short>(fIdleChanceMultiplier * mIdle[counter]); unsigned short idleChance = static_cast<unsigned short>(fIdleChanceMultiplier * mIdle[counter]);
unsigned short randSelect = (int)(rand() / ((double)RAND_MAX + 1) * int(100 / fIdleChanceMultiplier)); unsigned short randSelect = (int)(OEngine::Misc::Rng::rollProbability() * int(100 / fIdleChanceMultiplier));
if(randSelect < idleChance && randSelect > idleRoll) if(randSelect < idleChance && randSelect > idleRoll)
{ {
playedIdle = counter+2; playedIdle = counter+2;
@ -659,7 +661,7 @@ namespace MWMechanics
state.moveIn(new AiWanderStorage()); state.moveIn(new AiWanderStorage());
int index = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * mAllowedNodes.size()); int index = OEngine::Misc::Rng::rollDice(mAllowedNodes.size());
ESM::Pathgrid::Point dest = mAllowedNodes[index]; ESM::Pathgrid::Point dest = mAllowedNodes[index];
// apply a slight offset to prevent overcrowding // apply a slight offset to prevent overcrowding

@ -8,6 +8,8 @@
#include <stdexcept> #include <stdexcept>
#include <map> #include <map>
#include <openengine/misc/rng.hpp>
#include <components/esm/loadskil.hpp> #include <components/esm/loadskil.hpp>
#include <components/esm/loadappa.hpp> #include <components/esm/loadappa.hpp>
#include <components/esm/loadgmst.hpp> #include <components/esm/loadgmst.hpp>
@ -294,7 +296,7 @@ void MWMechanics::Alchemy::addPotion (const std::string& name)
newRecord.mName = name; newRecord.mName = name;
int index = static_cast<int> (std::rand()/(static_cast<double> (RAND_MAX)+1)*6); int index = OEngine::Misc::Rng::rollDice(6);
assert (index>=0 && index<6); assert (index>=0 && index<6);
static const char *meshes[] = { "standard", "bargain", "cheap", "fresh", "exclusive", "quality" }; static const char *meshes[] = { "standard", "bargain", "cheap", "fresh", "exclusive", "quality" };
@ -467,7 +469,7 @@ MWMechanics::Alchemy::Result MWMechanics::Alchemy::create (const std::string& na
return Result_RandomFailure; return Result_RandomFailure;
} }
if (getAlchemyFactor()<std::rand()/static_cast<double> (RAND_MAX)*100) if (getAlchemyFactor() < OEngine::Misc::Rng::roll0to99())
{ {
removeIngredients(); removeIngredients();
return Result_RandomFailure; return Result_RandomFailure;

@ -27,6 +27,8 @@
#include "creaturestats.hpp" #include "creaturestats.hpp"
#include "security.hpp" #include "security.hpp"
#include <openengine/misc/rng.hpp>
#include <components/settings/settings.hpp> #include <components/settings/settings.hpp>
#include "../mwrender/animation.hpp" #include "../mwrender/animation.hpp"
@ -220,7 +222,7 @@ std::string CharacterController::chooseRandomGroup (const std::string& prefix, i
while (mAnimation->hasAnimation(prefix + Ogre::StringConverter::toString(numAnims+1))) while (mAnimation->hasAnimation(prefix + Ogre::StringConverter::toString(numAnims+1)))
++numAnims; ++numAnims;
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * numAnims) + 1; // [1, numAnims] int roll = OEngine::Misc::Rng::rollDice(numAnims) + 1; // [1, numAnims]
if (num) if (num)
*num = roll; *num = roll;
return prefix + Ogre::StringConverter::toString(roll); return prefix + Ogre::StringConverter::toString(roll);
@ -829,7 +831,7 @@ bool CharacterController::updateCreatureState()
} }
if (weapType != WeapType_Spell || !mAnimation->hasAnimation("spellcast")) // Not all creatures have a dedicated spellcast animation if (weapType != WeapType_Spell || !mAnimation->hasAnimation("spellcast")) // Not all creatures have a dedicated spellcast animation
{ {
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 3); // [0, 2] int roll = OEngine::Misc::Rng::rollDice(3); // [0, 2]
if (roll == 0) if (roll == 0)
mCurrentWeapon = "attack1"; mCurrentWeapon = "attack1";
else if (roll == 1) else if (roll == 1)
@ -1125,7 +1127,7 @@ bool CharacterController::updateWeaponState()
// most creatures don't actually have an attack wind-up animation, so use a uniform random value // most creatures don't actually have an attack wind-up animation, so use a uniform random value
// (even some creatures that can use weapons don't have a wind-up animation either, e.g. Rieklings) // (even some creatures that can use weapons don't have a wind-up animation either, e.g. Rieklings)
// Note: vanilla MW uses a random value for *all* non-player actors, but we probably don't need to go that far. // Note: vanilla MW uses a random value for *all* non-player actors, but we probably don't need to go that far.
attackStrength = std::min(1.f, 0.1f + std::rand() / float(RAND_MAX)); attackStrength = std::min(1.f, 0.1f + OEngine::Misc::Rng::rollClosedProbability());
} }
if(mWeaponType != WeapType_Crossbow && mWeaponType != WeapType_BowAndArrow) if(mWeaponType != WeapType_Crossbow && mWeaponType != WeapType_BowAndArrow)

@ -2,6 +2,8 @@
#include <OgreSceneNode.h> #include <OgreSceneNode.h>
#include <openengine/misc/rng.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
#include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/mechanicsmanager.hpp"
@ -107,8 +109,7 @@ namespace MWMechanics
int iBlockMinChance = gmst.find("iBlockMinChance")->getInt(); int iBlockMinChance = gmst.find("iBlockMinChance")->getInt();
x = std::min(iBlockMaxChance, std::max(iBlockMinChance, x)); x = std::min(iBlockMaxChance, std::max(iBlockMinChance, x));
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() < x)
if (roll < x)
{ {
// Reduce shield durability by incoming damage // Reduce shield durability by incoming damage
int shieldhealth = shield->getClass().getItemHealth(*shield); int shieldhealth = shield->getClass().getItemHealth(*shield);
@ -186,7 +187,7 @@ namespace MWMechanics
int skillValue = attacker.getClass().getSkill(attacker, int skillValue = attacker.getClass().getSkill(attacker,
weapon.getClass().getEquipmentSkill(weapon)); weapon.getClass().getEquipmentSkill(weapon));
if((::rand()/(RAND_MAX+1.0)) >= getHitChance(attacker, victim, skillValue)/100.0f) if (OEngine::Misc::Rng::rollProbability() >= getHitChance(attacker, victim, skillValue) / 100.0f)
{ {
victim.getClass().onHit(victim, 0.0f, false, projectile, attacker, false); victim.getClass().onHit(victim, 0.0f, false, projectile, attacker, false);
MWMechanics::reduceWeaponCondition(0.f, false, weapon, attacker); MWMechanics::reduceWeaponCondition(0.f, false, weapon, attacker);
@ -224,7 +225,7 @@ namespace MWMechanics
&& !appliedEnchantment) && !appliedEnchantment)
{ {
float fProjectileThrownStoreChance = gmst.find("fProjectileThrownStoreChance")->getFloat(); float fProjectileThrownStoreChance = gmst.find("fProjectileThrownStoreChance")->getFloat();
if ((::rand()/(RAND_MAX+1.0)) < fProjectileThrownStoreChance/100.f) if (OEngine::Misc::Rng::rollProbability() < fProjectileThrownStoreChance / 100.f)
victim.getClass().getContainerStore(victim).add(projectile, 1, victim); victim.getClass().getContainerStore(victim).add(projectile, 1, victim);
} }
@ -291,8 +292,7 @@ namespace MWMechanics
saveTerm *= 1.25f * normalisedFatigue; saveTerm *= 1.25f * normalisedFatigue;
float roll = std::rand()/ (static_cast<float> (RAND_MAX) + 1) * 100; // [0, 99] float x = std::max(0.f, saveTerm - OEngine::Misc::Rng::roll0to99());
float x = std::max(0.f, saveTerm - roll);
int element = ESM::MagicEffect::FireDamage; int element = ESM::MagicEffect::FireDamage;
if (i == 1) if (i == 1)

@ -1,6 +1,8 @@
#ifndef OPENMW_MECHANICS_DISEASE_H #ifndef OPENMW_MECHANICS_DISEASE_H
#define OPENMW_MECHANICS_DISEASE_H #define OPENMW_MECHANICS_DISEASE_H
#include <openengine/misc/rng.hpp>
#include "../mwbase/windowmanager.hpp" #include "../mwbase/windowmanager.hpp"
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
@ -49,9 +51,7 @@ namespace MWMechanics
continue; continue;
int x = static_cast<int>(fDiseaseXferChance * 100 * resist); int x = static_cast<int>(fDiseaseXferChance * 100 * resist);
float roll = static_cast<float>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 10000); // [0, 9999] if (OEngine::Misc::Rng::rollDice(10000) < x)
if (roll < x)
{ {
// Contracted disease! // Contracted disease!
actor.getClass().getCreatureStats(actor).getSpells().add(it->first); actor.getClass().getCreatureStats(actor).getSpells().add(it->first);

@ -1,4 +1,7 @@
#include "enchanting.hpp" #include "enchanting.hpp"
#include <openengine/misc/rng.hpp>
#include "../mwworld/manualref.hpp" #include "../mwworld/manualref.hpp"
#include "../mwworld/class.hpp" #include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp" #include "../mwworld/containerstore.hpp"
@ -67,7 +70,7 @@ namespace MWMechanics
if(mSelfEnchanting) if(mSelfEnchanting)
{ {
if(getEnchantChance()<std::rand()/static_cast<double> (RAND_MAX)*100) if(getEnchantChance() <= (OEngine::Misc::Rng::roll0to99()))
return false; return false;
mEnchanter.getClass().skillUsageSucceeded (mEnchanter, ESM::Skill::Enchant, 2); mEnchanter.getClass().skillUsageSucceeded (mEnchanter, ESM::Skill::Enchant, 2);

@ -1,6 +1,8 @@
#ifndef OPENMW_MECHANICS_LEVELLEDLIST_H #ifndef OPENMW_MECHANICS_LEVELLEDLIST_H
#define OPENMW_MECHANICS_LEVELLEDLIST_H #define OPENMW_MECHANICS_LEVELLEDLIST_H
#include <openengine/misc/rng.hpp>
#include "../mwworld/ptr.hpp" #include "../mwworld/ptr.hpp"
#include "../mwworld/esmstore.hpp" #include "../mwworld/esmstore.hpp"
#include "../mwworld/manualref.hpp" #include "../mwworld/manualref.hpp"
@ -22,8 +24,7 @@ namespace MWMechanics
failChance += levItem->mChanceNone; failChance += levItem->mChanceNone;
int random = static_cast<int>(static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100)); // [0, 99] if (OEngine::Misc::Rng::roll0to99() < failChance)
if (random < failChance)
return std::string(); return std::string();
std::vector<std::string> candidates; std::vector<std::string> candidates;
@ -52,7 +53,7 @@ namespace MWMechanics
} }
if (candidates.empty()) if (candidates.empty())
return std::string(); return std::string();
std::string item = candidates[std::rand()%candidates.size()]; std::string item = candidates[OEngine::Misc::Rng::rollDice(candidates.size())];
// Vanilla doesn't fail on nonexistent items in levelled lists // Vanilla doesn't fail on nonexistent items in levelled lists
if (!MWBase::Environment::get().getWorld()->getStore().find(Misc::StringUtils::lowerCase(item))) if (!MWBase::Environment::get().getWorld()->getStore().find(Misc::StringUtils::lowerCase(item)))

@ -2,6 +2,8 @@
#include "mechanicsmanagerimp.hpp" #include "mechanicsmanagerimp.hpp"
#include "npcstats.hpp" #include "npcstats.hpp"
#include <openengine/misc/rng.hpp>
#include <components/esm/stolenitems.hpp> #include <components/esm/stolenitems.hpp>
#include "../mwworld/esmstore.hpp" #include "../mwworld/esmstore.hpp"
@ -723,7 +725,7 @@ namespace MWMechanics
float x = 0; float x = 0;
float y = 0; float y = 0;
float roll = static_cast<float> (std::rand()) / RAND_MAX * 100; float roll = OEngine::Misc::Rng::rollClosedProbability() * 100;
if (type == PT_Admire) if (type == PT_Admire)
{ {
@ -1378,9 +1380,8 @@ namespace MWMechanics
y = obsTerm * observerStats.getFatigueTerm() * fSneakViewMult; y = obsTerm * observerStats.getFatigueTerm() * fSneakViewMult;
float target = x - y; float target = x - y;
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99]
return (roll >= target); return (OEngine::Misc::Rng::roll0to99() >= target);
} }
void MechanicsManager::startCombat(const MWWorld::Ptr &ptr, const MWWorld::Ptr &target) void MechanicsManager::startCombat(const MWWorld::Ptr &ptr, const MWWorld::Ptr &target)

@ -1,5 +1,7 @@
#include "pickpocket.hpp" #include "pickpocket.hpp"
#include <openengine/misc/rng.hpp>
#include "../mwworld/class.hpp" #include "../mwworld/class.hpp"
#include "../mwworld/esmstore.hpp" #include "../mwworld/esmstore.hpp"
@ -39,7 +41,7 @@ namespace MWMechanics
int iPickMaxChance = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>() int iPickMaxChance = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>()
.find("iPickMaxChance")->getInt(); .find("iPickMaxChance")->getInt();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] int roll = OEngine::Misc::Rng::roll0to99();
if (t < pcSneak / iPickMinChance) if (t < pcSneak / iPickMinChance)
{ {
return (roll > int(pcSneak / iPickMinChance)); return (roll > int(pcSneak / iPickMinChance));

@ -2,6 +2,8 @@
#include <boost/format.hpp> #include <boost/format.hpp>
#include <openengine/misc/rng.hpp>
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/mechanicsmanager.hpp"
@ -46,7 +48,7 @@ void Repair::repair(const MWWorld::Ptr &itemToRepair)
float x = (0.1f * pcStrength + 0.1f * pcLuck + armorerSkill) * fatigueTerm; float x = (0.1f * pcStrength + 0.1f * pcLuck + armorerSkill) * fatigueTerm;
int roll = static_cast<int>(static_cast<float> (std::rand()) / RAND_MAX * 100); int roll = OEngine::Misc::Rng::roll0to99();
if (roll <= x) if (roll <= x)
{ {
int y = static_cast<int>(fRepairAmountMult * toolQuality * roll); int y = static_cast<int>(fRepairAmountMult * toolQuality * roll);

@ -1,5 +1,7 @@
#include "security.hpp" #include "security.hpp"
#include <openengine/misc/rng.hpp>
#include "../mwworld/class.hpp" #include "../mwworld/class.hpp"
#include "../mwworld/containerstore.hpp" #include "../mwworld/containerstore.hpp"
#include "../mwworld/esmstore.hpp" #include "../mwworld/esmstore.hpp"
@ -48,8 +50,7 @@ namespace MWMechanics
else else
{ {
MWBase::Environment::get().getMechanicsManager()->objectOpened(mActor, lock); MWBase::Environment::get().getMechanicsManager()->objectOpened(mActor, lock);
int roll = static_cast<int>(static_cast<float> (std::rand()) / RAND_MAX * 100); if (OEngine::Misc::Rng::roll0to99() <= x)
if (roll <= x)
{ {
lock.getClass().unlock(lock); lock.getClass().unlock(lock);
resultMessage = "#{sLockSuccess}"; resultMessage = "#{sLockSuccess}";
@ -90,8 +91,7 @@ namespace MWMechanics
else else
{ {
MWBase::Environment::get().getMechanicsManager()->objectOpened(mActor, trap); MWBase::Environment::get().getMechanicsManager()->objectOpened(mActor, trap);
int roll = static_cast<int>(static_cast<float> (std::rand()) / RAND_MAX * 100); if (OEngine::Misc::Rng::roll0to99() <= x)
if (roll <= x)
{ {
trap.getCellRef().setTrap(""); trap.getCellRef().setTrap("");

@ -4,6 +4,8 @@
#include <boost/format.hpp> #include <boost/format.hpp>
#include <openengine/misc/rng.hpp>
#include "../mwbase/windowmanager.hpp" #include "../mwbase/windowmanager.hpp"
#include "../mwbase/soundmanager.hpp" #include "../mwbase/soundmanager.hpp"
#include "../mwbase/mechanicsmanager.hpp" #include "../mwbase/mechanicsmanager.hpp"
@ -280,7 +282,7 @@ namespace MWMechanics
if (castChance > 0) if (castChance > 0)
x *= 50 / castChance; x *= 50 / castChance;
float roll = static_cast<float>(std::rand()) / RAND_MAX * 100; float roll = OEngine::Misc::Rng::rollClosedProbability() * 100;
if (magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude) if (magicEffect->mData.mFlags & ESM::MagicEffect::NoMagnitude)
roll -= resistance; roll -= resistance;
@ -383,8 +385,7 @@ namespace MWMechanics
target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::ResistCommonDisease).getMagnitude() target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::ResistCommonDisease).getMagnitude()
: target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::ResistBlightDisease).getMagnitude(); : target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::ResistBlightDisease).getMagnitude();
int roll = static_cast<int>(std::rand()/ (static_cast<double> (RAND_MAX) + 1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() <= x)
if (roll <= x)
{ {
// Fully resisted, show message // Fully resisted, show message
if (target == MWBase::Environment::get().getWorld()->getPlayerPtr()) if (target == MWBase::Environment::get().getWorld()->getPlayerPtr())
@ -414,8 +415,7 @@ namespace MWMechanics
if (spell && caster != target && target.getClass().isActor()) if (spell && caster != target && target.getClass().isActor())
{ {
float absorb = target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::SpellAbsorption).getMagnitude(); float absorb = target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::SpellAbsorption).getMagnitude();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] absorbed = (OEngine::Misc::Rng::roll0to99() < absorb);
absorbed = (roll < absorb);
if (absorbed) if (absorbed)
{ {
const ESM::Static* absorbStatic = MWBase::Environment::get().getWorld()->getStore().get<ESM::Static>().find ("VFX_Absorb"); const ESM::Static* absorbStatic = MWBase::Environment::get().getWorld()->getStore().get<ESM::Static>().find ("VFX_Absorb");
@ -463,8 +463,7 @@ namespace MWMechanics
if (!reflected && magnitudeMult > 0 && !caster.isEmpty() && caster != target && !(magicEffect->mData.mFlags & ESM::MagicEffect::Unreflectable)) if (!reflected && magnitudeMult > 0 && !caster.isEmpty() && caster != target && !(magicEffect->mData.mFlags & ESM::MagicEffect::Unreflectable))
{ {
float reflect = target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Reflect).getMagnitude(); float reflect = target.getClass().getCreatureStats(target).getMagicEffects().get(ESM::MagicEffect::Reflect).getMagnitude();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] bool isReflected = (OEngine::Misc::Rng::roll0to99() < reflect);
bool isReflected = (roll < reflect);
if (isReflected) if (isReflected)
{ {
const ESM::Static* reflectStatic = MWBase::Environment::get().getWorld()->getStore().get<ESM::Static>().find ("VFX_Reflect"); const ESM::Static* reflectStatic = MWBase::Environment::get().getWorld()->getStore().get<ESM::Static>().find ("VFX_Reflect");
@ -492,7 +491,7 @@ namespace MWMechanics
if (magnitudeMult > 0 && !absorbed) if (magnitudeMult > 0 && !absorbed)
{ {
float random = std::rand() / static_cast<float>(RAND_MAX); float random = OEngine::Misc::Rng::rollClosedProbability();
float magnitude = effectIt->mMagnMin + (effectIt->mMagnMax - effectIt->mMagnMin) * random; float magnitude = effectIt->mMagnMin + (effectIt->mMagnMax - effectIt->mMagnMin) * random;
magnitude *= magnitudeMult; magnitude *= magnitudeMult;
@ -824,8 +823,7 @@ namespace MWMechanics
// Check success // Check success
float successChance = getSpellSuccessChance(spell, mCaster); float successChance = getSpellSuccessChance(spell, mCaster);
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] if (OEngine::Misc::Rng::roll0to99() >= successChance)
if (!fail && roll >= successChance)
{ {
if (mCaster == MWBase::Environment::get().getWorld()->getPlayerPtr()) if (mCaster == MWBase::Environment::get().getWorld()->getPlayerPtr())
MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicSkillFail}"); MWBase::Environment::get().getWindowManager()->messageBox("#{sMagicSkillFail}");
@ -903,7 +901,7 @@ namespace MWMechanics
+ 0.1f * creatureStats.getAttribute (ESM::Attribute::Luck).getModified()) + 0.1f * creatureStats.getAttribute (ESM::Attribute::Luck).getModified())
* creatureStats.getFatigueTerm(); * creatureStats.getFatigueTerm();
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 100); // [0, 99] int roll = OEngine::Misc::Rng::roll0to99();
if (roll > x) if (roll > x)
{ {
// "X has no effect on you" // "X has no effect on you"

@ -38,7 +38,7 @@ namespace MWMechanics
for (unsigned int i=0; i<spell->mEffects.mList.size();++i) for (unsigned int i=0; i<spell->mEffects.mList.size();++i)
{ {
if (spell->mEffects.mList[i].mMagnMin != spell->mEffects.mList[i].mMagnMax) if (spell->mEffects.mList[i].mMagnMin != spell->mEffects.mList[i].mMagnMax)
random[i] = static_cast<float> (std::rand()) / RAND_MAX; random[i] = OEngine::Misc::Rng::rollClosedProbability();
} }
} }

@ -12,6 +12,8 @@
#include <extern/shiny/Main/Factory.hpp> #include <extern/shiny/Main/Factory.hpp>
#include <openengine/misc/rng.hpp>
#include <components/misc/resourcehelpers.hpp> #include <components/misc/resourcehelpers.hpp>
#include "../mwworld/esmstore.hpp" #include "../mwworld/esmstore.hpp"
@ -101,7 +103,7 @@ void HeadAnimationTime::setEnabled(bool enabled)
void HeadAnimationTime::resetBlinkTimer() void HeadAnimationTime::resetBlinkTimer()
{ {
mBlinkTimer = -(2 + (std::rand() / static_cast<float>(RAND_MAX)) * 6); mBlinkTimer = -(2.0f + OEngine::Misc::Rng::rollDice(6));
} }
void HeadAnimationTime::update(float dt) void HeadAnimationTime::update(float dt)

@ -19,6 +19,8 @@
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include <openengine/misc/rng.hpp>
#include <components/nifogre/ogrenifloader.hpp> #include <components/nifogre/ogrenifloader.hpp>
#include <components/misc/resourcehelpers.hpp> #include <components/misc/resourcehelpers.hpp>
@ -464,8 +466,8 @@ void SkyManager::updateRain(float dt)
// TODO: handle rain settings from Morrowind.ini // TODO: handle rain settings from Morrowind.ini
const float rangeRandom = 100; const float rangeRandom = 100;
float xOffs = (std::rand()/(RAND_MAX+1.0f)) * rangeRandom - (rangeRandom/2); float xOffs = OEngine::Misc::Rng::rollProbability() * rangeRandom - (rangeRandom / 2);
float yOffs = (std::rand()/(RAND_MAX+1.0f)) * rangeRandom - (rangeRandom/2); float yOffs = OEngine::Misc::Rng::rollProbability() * rangeRandom - (rangeRandom / 2);
// Create a separate node to control the offset, since a node with setInheritOrientation(false) will still // Create a separate node to control the offset, since a node with setInheritOrientation(false) will still
// consider the orientation of the parent node for its position, just not for its orientation // consider the orientation of the parent node for its position, just not for its orientation

@ -4,6 +4,8 @@
#include <algorithm> #include <algorithm>
#include <map> #include <map>
#include <openengine/misc/rng.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
#include "../mwbase/world.hpp" #include "../mwbase/world.hpp"
#include "../mwbase/statemanager.hpp" #include "../mwbase/statemanager.hpp"
@ -224,7 +226,7 @@ namespace MWSound
if(!filelist.size()) if(!filelist.size())
return; return;
int i = rand()%filelist.size(); int i = OEngine::Misc::Rng::rollDice(filelist.size());
// Don't play the same music track twice in a row // Don't play the same music track twice in a row
if (filelist[i] == mLastPlayedMusic) if (filelist[i] == mLastPlayedMusic)
@ -559,7 +561,7 @@ namespace MWSound
if(!cell->isExterior() || sTimePassed < sTimeToNextEnvSound) if(!cell->isExterior() || sTimePassed < sTimeToNextEnvSound)
return; return;
float a = std::rand() / static_cast<float>(RAND_MAX); float a = OEngine::Misc::Rng::rollClosedProbability();
// NOTE: We should use the "Minimum Time Between Environmental Sounds" and // NOTE: We should use the "Minimum Time Between Environmental Sounds" and
// "Maximum Time Between Environmental Sounds" fallback settings here. // "Maximum Time Between Environmental Sounds" fallback settings here.
sTimeToNextEnvSound = 5.0f*a + 15.0f*(1.0f-a); sTimeToNextEnvSound = 5.0f*a + 15.0f*(1.0f-a);
@ -588,7 +590,7 @@ namespace MWSound
return; return;
} }
int r = (int)(rand()/((double)RAND_MAX+1) * total); int r = OEngine::Misc::Rng::rollDice(total);
int pos = 0; int pos = 0;
soundIter = regn->mSoundList.begin(); soundIter = regn->mSoundList.begin();

@ -364,7 +364,7 @@ void MWWorld::InventoryStore::updateMagicEffects(const Ptr& actor)
// Roll some dice, one for each effect // Roll some dice, one for each effect
params.resize(enchantment.mEffects.mList.size()); params.resize(enchantment.mEffects.mList.size());
for (unsigned int i=0; i<params.size();++i) for (unsigned int i=0; i<params.size();++i)
params[i].mRandom = static_cast<float> (std::rand()) / RAND_MAX; params[i].mRandom = OEngine::Misc::Rng::rollClosedProbability();
// Try resisting each effect // Try resisting each effect
int i=0; int i=0;

@ -7,6 +7,8 @@
#include <stdexcept> #include <stdexcept>
#include <sstream> #include <sstream>
#include <openengine/misc/rng.hpp>
#include <components/esm/esmwriter.hpp> #include <components/esm/esmwriter.hpp>
#include <components/loadinglistener/loadinglistener.hpp> #include <components/loadinglistener/loadinglistener.hpp>
@ -178,7 +180,7 @@ namespace MWWorld
std::vector<const T*> results; std::vector<const T*> results;
std::for_each(mShared.begin(), mShared.end(), GetRecords(id, &results)); std::for_each(mShared.begin(), mShared.end(), GetRecords(id, &results));
if(!results.empty()) if(!results.empty())
return results[int(std::rand()/((double)RAND_MAX+1)*results.size())]; return results[OEngine::Misc::Rng::rollDice(results.size())];
return NULL; return NULL;
} }

@ -3,6 +3,8 @@
#include "weather.hpp" #include "weather.hpp"
#include <openengine/misc/rng.hpp>
#include <components/esm/weatherstate.hpp> #include <components/esm/weatherstate.hpp>
#include "../mwbase/environment.hpp" #include "../mwbase/environment.hpp"
@ -526,7 +528,7 @@ void WeatherManager::update(float duration, bool paused)
if (mThunderSoundDelay <= 0) if (mThunderSoundDelay <= 0)
{ {
// pick a random sound // pick a random sound
int sound = rand() % 4; int sound = OEngine::Misc::Rng::rollDice(4);
std::string* soundName = NULL; std::string* soundName = NULL;
if (sound == 0) soundName = &mThunderSoundID0; if (sound == 0) soundName = &mThunderSoundID0;
else if (sound == 1) soundName = &mThunderSoundID1; else if (sound == 1) soundName = &mThunderSoundID1;
@ -542,7 +544,7 @@ void WeatherManager::update(float duration, bool paused)
mRendering->getSkyManager()->setLightningStrength( mThunderFlash / mThunderThreshold ); mRendering->getSkyManager()->setLightningStrength( mThunderFlash / mThunderThreshold );
else else
{ {
mThunderChanceNeeded = static_cast<float>(rand() % 100); mThunderChanceNeeded = static_cast<float>(OEngine::Misc::Rng::rollDice(100));
mThunderChance = 0; mThunderChance = 0;
mRendering->getSkyManager()->setLightningStrength( 0.f ); mRendering->getSkyManager()->setLightningStrength( 0.f );
} }
@ -624,7 +626,7 @@ std::string WeatherManager::nextWeather(const ESM::Region* region) const
* 70% will be greater than 30 (in theory). * 70% will be greater than 30 (in theory).
*/ */
int chance = (rand() % 100) + 1; // 1..100 int chance = OEngine::Misc::Rng::rollDice(100) + 1; // 1..100
int sum = 0; int sum = 0;
unsigned int i = 0; unsigned int i = 0;
for (; i < probability.size(); ++i) for (; i < probability.size(); ++i)

@ -14,6 +14,8 @@
#include <libs/openengine/bullet/trace.h> #include <libs/openengine/bullet/trace.h>
#include <libs/openengine/bullet/physic.hpp> #include <libs/openengine/bullet/physic.hpp>
#include <openengine/misc/rng.hpp>
#include <components/bsa/bsa_archive.hpp> #include <components/bsa/bsa_archive.hpp>
#include <components/files/collections.hpp> #include <components/files/collections.hpp>
#include <components/compiler/locals.hpp> #include <components/compiler/locals.hpp>
@ -3133,7 +3135,7 @@ namespace MWWorld
const ESM::CreatureLevList* list = getStore().get<ESM::CreatureLevList>().find(creatureList); const ESM::CreatureLevList* list = getStore().get<ESM::CreatureLevList>().find(creatureList);
int iNumberCreatures = getStore().get<ESM::GameSetting>().find("iNumberCreatures")->getInt(); int iNumberCreatures = getStore().get<ESM::GameSetting>().find("iNumberCreatures")->getInt();
int numCreatures = static_cast<int>(1 + std::rand() / (static_cast<double> (RAND_MAX)+1) * iNumberCreatures); // [1, iNumberCreatures] int numCreatures = 1 + OEngine::Misc::Rng::rollDice(iNumberCreatures); // [1, iNumberCreatures]
for (int i=0; i<numCreatures; ++i) for (int i=0; i<numCreatures; ++i)
{ {
@ -3184,7 +3186,7 @@ namespace MWWorld
std::stringstream modelName; std::stringstream modelName;
modelName << "Blood_Model_"; modelName << "Blood_Model_";
int roll = static_cast<int>(std::rand() / (static_cast<double> (RAND_MAX)+1) * 3); // [0, 2] int roll = OEngine::Misc::Rng::rollDice(3); // [0, 2]
modelName << roll; modelName << roll;
std::string model = "meshes\\" + getFallback()->getFallbackString(modelName.str()); std::string model = "meshes\\" + getFallback()->getFallbackString(modelName.str());

@ -160,7 +160,11 @@ include_directories(${BULLET_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
add_library(components STATIC ${COMPONENT_FILES} ${MOC_SRCS} ${ESM_UI_HDR}) add_library(components STATIC ${COMPONENT_FILES} ${MOC_SRCS} ${ESM_UI_HDR})
target_link_libraries(components ${Boost_LIBRARIES} ${OGRE_LIBRARIES}) target_link_libraries(components
${Boost_LIBRARIES}
${OGRE_LIBRARIES}
${OENGINE_LIBRARY}
)
if (GIT_CHECKOUT) if (GIT_CHECKOUT)
add_dependencies (components git-version) add_dependencies (components git-version)

@ -12,6 +12,8 @@
#include <OgreSceneNode.h> #include <OgreSceneNode.h>
#include <OgreSceneManager.h> #include <OgreSceneManager.h>
#include <openengine/misc/rng.hpp>
/* FIXME: "Nif" isn't really an appropriate emitter name. */ /* FIXME: "Nif" isn't really an appropriate emitter name. */
class NifEmitter : public Ogre::ParticleEmitter class NifEmitter : public Ogre::ParticleEmitter
{ {
@ -171,7 +173,7 @@ public:
Ogre::Real& timeToLive = particle->timeToLive; Ogre::Real& timeToLive = particle->timeToLive;
#endif #endif
Ogre::Node* emitterBone = mEmitterBones.at((int)(::rand()/(RAND_MAX+1.0)*mEmitterBones.size())); Ogre::Node* emitterBone = mEmitterBones.at(OEngine::Misc::Rng::rollDice(mEmitterBones.size()));
position = xOff + yOff + zOff + position = xOff + yOff + zOff +
mParticleBone->_getDerivedOrientation().Inverse() * (emitterBone->_getDerivedPosition() mParticleBone->_getDerivedOrientation().Inverse() * (emitterBone->_getDerivedPosition()

@ -23,7 +23,12 @@ set(OENGINE_BULLET
bullet/trace.h bullet/trace.h
) )
set(OENGINE_ALL ${OENGINE_OGRE} ${OENGINE_GUI} ${OENGINE_BULLET}) set(OENGINE_MISC
misc/rng.cpp
misc/rng.hpp
)
set(OENGINE_ALL ${OENGINE_OGRE} ${OENGINE_GUI} ${OENGINE_BULLET} ${OENGINE_MISC})
set(OENGINE_LIBRARY "oengine") set(OENGINE_LIBRARY "oengine")
set(OENGINE_LIBRARY ${OENGINE_LIBRARY} PARENT_SCOPE) set(OENGINE_LIBRARY ${OENGINE_LIBRARY} PARENT_SCOPE)

@ -0,0 +1,29 @@
#include "rng.hpp"
#include <cstdlib>
#include <ctime>
namespace OEngine {
namespace Misc {
void Rng::init()
{
std::srand(static_cast<unsigned int>(std::time(NULL)));
}
float Rng::rollProbability()
{
return static_cast<float>(std::rand() / (static_cast<double>(RAND_MAX)+1.0));
}
float Rng::rollClosedProbability()
{
return static_cast<float>(std::rand() / static_cast<double>(RAND_MAX));
}
int Rng::rollDice(int max)
{
return static_cast<int>((std::rand() / (static_cast<double>(RAND_MAX)+1.0)) * (max));
}
}
}

@ -0,0 +1,36 @@
#ifndef MISC_RNG_H
#define MISC_RNG_H
#include <cassert>
namespace OEngine {
namespace Misc
{
/*
Provides central implementation of the RNG logic
*/
class Rng
{
public:
/// seed the RNG
static void init();
/// return value in range [0.0f, 1.0f) <- note open upper range.
static float rollProbability();
/// return value in range [0.0f, 1.0f] <- note closed upper range.
static float rollClosedProbability();
/// return value in range [0, max) <- note open upper range.
static int rollDice(int max);
/// return value in range [0, 99]
static int roll0to99() { return rollDice(100); }
};
}
}
#endif

@ -10,6 +10,8 @@
#include <stdexcept> #include <stdexcept>
#include <openengine/misc/rng.hpp>
#include <extern/shiny/Main/Factory.hpp> #include <extern/shiny/Main/Factory.hpp>
namespace OEngine namespace OEngine
@ -145,7 +147,7 @@ namespace Render
void SelectionBuffer::getNextColour () void SelectionBuffer::getNextColour ()
{ {
Ogre::ARGB color = static_cast<Ogre::ARGB>((float(rand()) / float(RAND_MAX)) * std::numeric_limits<Ogre::uint32>::max()); Ogre::ARGB color = static_cast<Ogre::ARGB>(OEngine::Misc::Rng::rollClosedProbability() * std::numeric_limits<Ogre::uint32>::max());
if (mCurrentColour.getAsARGB () == color) if (mCurrentColour.getAsARGB () == color)
{ {

Loading…
Cancel
Save