Skip to content

Commit

Permalink
Pull in changes from 5.1 for using the standard Mersenne twister rath…
Browse files Browse the repository at this point in the history
…er than a custom version.
  • Loading branch information
xwidghet committed Nov 20, 2016
1 parent de1ebe0 commit c158f80
Show file tree
Hide file tree
Showing 17 changed files with 88 additions and 135 deletions.
2 changes: 1 addition & 1 deletion src/Background.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,7 @@ void BackgroundImpl::LoadFromSong( const Song* pSong )

// Pick the same random items every time the song is played.
RandomGen rnd( GetHashForString(pSong->GetSongDir()) );
random_shuffle( vsNames.begin(), vsNames.end(), rnd );
std::shuffle( vsNames.begin(), vsNames.end(), rnd );
int iSize = min( (int)g_iNumBackgrounds, (int)vsNames.size() );
vsNames.resize( iSize );

Expand Down
20 changes: 14 additions & 6 deletions src/Course.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ static void CourseSortSongs( SongSort sort, vector<Song*> &vpPossibleSongs, Rand
{
DEFAULT_FAIL(sort);
case SongSort_Randomize:
random_shuffle( vpPossibleSongs.begin(), vpPossibleSongs.end(), rnd );
std::shuffle( vpPossibleSongs.begin(), vpPossibleSongs.end(), rnd );
break;
case SongSort_MostPlays:
if( PROFILEMAN )
Expand Down Expand Up @@ -428,7 +428,7 @@ bool Course::GetTrailUnsorted( StepsType st, CourseDifficulty cd, Trail &trail )
* will change every time it's viewed, and the displayed order will have no
* bearing on what you'll actually play. */
tmp_entries = m_vEntries;
random_shuffle( tmp_entries.begin(), tmp_entries.end(), rnd );
std::shuffle( tmp_entries.begin(), tmp_entries.end(), rnd );
}

const vector<CourseEntry> &entries = m_bShuffle ? tmp_entries:m_vEntries;
Expand Down Expand Up @@ -586,10 +586,14 @@ bool Course::GetTrailUnsorted( StepsType st, CourseDifficulty cd, Trail &trail )
iMaxDist = max( min( iMaxDist, MAX_BOTTOM_RANGE - iHighMeter ), iMinDist );

int iAdd;
if( iMaxDist == iMinDist )
if ( iMaxDist == iMinDist )
{
iAdd = iMaxDist;
}
else
iAdd = rnd( iMaxDist - iMinDist ) + iMinDist;
{
iAdd = random_up_to(rnd, iMaxDist - iMinDist) + iMinDist;
}
iLowMeter += iAdd;
iHighMeter += iAdd;
}
Expand Down Expand Up @@ -789,10 +793,14 @@ void Course::GetTrailUnsortedEndless( const vector<CourseEntry> &entries, Trail
iMaxDist = max( min( iMaxDist, MAX_BOTTOM_RANGE - iHighMeter ), iMinDist );

int iAdd;
if( iMaxDist == iMinDist )
if ( iMaxDist == iMinDist )
{
iAdd = iMaxDist;
}
else
iAdd = rnd( iMaxDist - iMinDist ) + iMinDist;
{
iAdd = random_up_to(rnd, iMaxDist - iMinDist) + iMinDist;
}
iLowMeter += iAdd;
iHighMeter += iAdd;
}
Expand Down
2 changes: 1 addition & 1 deletion src/CourseUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ void CourseUtil::AutogenOniFromArtist( const RString &sArtistName, RString sArti
* song set changes. */
{
RandomGen rng( GetHashForString( sArtistName ) + aSongs.size() );
random_shuffle( aSongs.begin(), aSongs.end(), rng );
std::shuffle( aSongs.begin(), aSongs.end(), rng );
}

// Only use up to four songs.
Expand Down
8 changes: 4 additions & 4 deletions src/GameState.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,8 @@ void GameState::Reset()

NOTESKIN->RefreshNoteSkinData( m_pCurGame );

m_iGameSeed = rand();
m_iStageSeed = rand();
m_iGameSeed = g_RandomNumberGenerator();
m_iStageSeed = g_RandomNumberGenerator();

m_AdjustTokensBySongCostForFinalStageCheck= true;

Expand Down Expand Up @@ -1242,7 +1242,7 @@ void GameState::ResetStageStatistics()

// Reset the round seed. Do this here and not in FinishStage so that players
// get new shuffle patterns if they Back out of gameplay and play again.
m_iStageSeed = rand();
m_iStageSeed = g_RandomNumberGenerator();
}

void GameState::UpdateSongPosition( float fPositionSeconds, const TimingData &timing, const RageTimer &timestamp )
Expand Down Expand Up @@ -2495,7 +2495,7 @@ Difficulty GameState::GetHardestStepsDifficulty() const

void GameState::SetNewStageSeed()
{
m_iStageSeed= rand();
m_iStageSeed = g_RandomNumberGenerator();
}

bool GameState::IsEventMode() const
Expand Down
2 changes: 1 addition & 1 deletion src/MusicWheel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1348,7 +1348,7 @@ void MusicWheel::StartRandom()
{
// Shuffle and use the roulette wheel.
RandomGen rnd;
random_shuffle( getWheelItemsData(SORT_ROULETTE).begin(), getWheelItemsData(SORT_ROULETTE).end(), rnd );
std::shuffle( getWheelItemsData(SORT_ROULETTE).begin(), getWheelItemsData(SORT_ROULETTE).end(), rnd );
GAMESTATE->m_SortOrder.Set( SORT_ROULETTE );
}
else
Expand Down
10 changes: 5 additions & 5 deletions src/NoteDataUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1489,19 +1489,19 @@ static void GetTrackMapping( StepsType st, NoteDataUtil::TrackMapping tt, int Nu
switch(st) {
case StepsType_beat_single5:
{
random_shuffle( &iTakeFromTrack[0], &iTakeFromTrack[5], rnd );
random_shuffle( &iTakeFromTrack[6], &iTakeFromTrack[11], rnd );
std::shuffle( &iTakeFromTrack[0], &iTakeFromTrack[5], rnd );
std::shuffle( &iTakeFromTrack[6], &iTakeFromTrack[11], rnd );
break;
}
case StepsType_beat_single7:
{
random_shuffle( &iTakeFromTrack[1], &iTakeFromTrack[8], rnd );
random_shuffle( &iTakeFromTrack[9], &iTakeFromTrack[16], rnd );
std::shuffle( &iTakeFromTrack[1], &iTakeFromTrack[8], rnd );
std::shuffle( &iTakeFromTrack[9], &iTakeFromTrack[16], rnd );
break;
}
default:
{
random_shuffle( &iTakeFromTrack[0], &iTakeFromTrack[NumTracks], rnd );
std::shuffle( &iTakeFromTrack[0], &iTakeFromTrack[NumTracks], rnd );
break;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/NotesLoaderBMS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ struct bmsCommandTree
while (randomStack.size() < currentNode->branchHeight + 1) // if we're on branch level N we need N+1 values.
randomStack.push_back(0);

randomStack[currentNode->branchHeight] = rand() % StringToInt(value) + 1;
randomStack[currentNode->branchHeight] = random_up_to(g_RandomNumberGenerator, StringToInt(value)) + 1;
}
else
{
Expand Down
1 change: 0 additions & 1 deletion src/Player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3368,7 +3368,6 @@ RString Player::ApplyRandomAttack()
if( GAMESTATE->m_RandomAttacks.size() < 1 )
return "";

//int iAttackToUse = rand() % GAMESTATE->m_RandomAttacks.size();
DateTime now = DateTime::GetNowDate();
int iSeed = now.tm_hour * now.tm_min * now.tm_sec * now.tm_mday;
RandomGen rnd( GAMESTATE->m_iStageSeed * iSeed );
Expand Down
85 changes: 11 additions & 74 deletions src/RageUtil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,87 +24,19 @@ void UnicodeUpperLower(wchar_t *, size_t, const unsigned char *);

RandomGen g_RandomNumberGenerator;

MersenneTwister::MersenneTwister( int iSeed ) : m_iNext(0)
{
Reset( iSeed );
}

void MersenneTwister::Reset( int iSeed )
{
if( iSeed == 0 )
iSeed = time(NULL);

m_Values[0] = iSeed;
m_iNext = 0;
for( int i = 1; i < 624; ++i )
m_Values[i] = ((69069 * m_Values[i-1]) + 1) & 0xFFFFFFFF;

GenerateValues();
}

void MersenneTwister::GenerateValues()
{
static const unsigned mask[] = { 0, 0x9908B0DF };

for( int i = 0; i < 227; ++i )
{
int iVal = (m_Values[i] & 0x80000000) | (m_Values[i+1] & 0x7FFFFFFF);
int iNext = (i + 397);

m_Values[i] = m_Values[iNext];
m_Values[i] ^= (iVal >> 1);
m_Values[i] ^= mask[iVal&1];
}

for( int i = 227; i < 623; ++i )
{
int iVal = (m_Values[i] & 0x80000000) | (m_Values[i+1] & 0x7FFFFFFF);
int iNext = (i + 397) - 624;

m_Values[i] = m_Values[iNext];
m_Values[i] ^= (iVal >> 1);
m_Values[i] ^= mask[iVal&1];
}

int iVal = (m_Values[623] & 0x80000000) + (m_Values[0] & 0x7FFFFFFF);
int iNext = (623 + 397) - 624;
m_Values[623] = m_Values[iNext] ^ (iVal>>1);
m_Values[623] ^= mask[iVal&1];
}

int MersenneTwister::Temper( int iVal )
{
iVal ^= (iVal >> 11);
iVal ^= (iVal << 7) & 0x9D2C5680;
iVal ^= (iVal << 15) & 0xEFC60000;
iVal ^= (iVal >> 18);
return iVal;
}

int MersenneTwister::operator()()
{
if( m_iNext == 624 )
{
m_iNext = 0;
GenerateValues();
}

return Temper( m_Values[m_iNext++] );
}

/* Extend MersenneTwister into Lua space. This is intended to replace
* math.randomseed and math.random, so we conform to their behavior. */

namespace
{
MersenneTwister g_LuaPRNG;
RandomGen g_LuaPRNG;

/* To map from [0..2^31-1] to [0..1), we divide by 2^31. */
const double DIVISOR = pow( double(2), double(31) );
/* To map from [0..2^32-1] to [0..1), we divide by 2^32. */
const double DIVISOR = 4294967296.0;

static int Seed( lua_State *L )
{
g_LuaPRNG.Reset( IArg(1) );
g_LuaPRNG.seed( IArg(1) );
return 0;
}

Expand All @@ -125,7 +57,7 @@ namespace
{
int upper = IArg(1);
luaL_argcheck( L, 1 <= upper, 1, "interval is empty" );
lua_pushnumber( L, g_LuaPRNG(upper) + 1 );
lua_pushnumber(L, random_up_to(g_LuaPRNG, upper) + 1);
return 1;
}
/* [l..u] */
Expand All @@ -134,7 +66,7 @@ namespace
int lower = IArg(1);
int upper = IArg(2);
luaL_argcheck( L, lower < upper, 2, "interval is empty" );
lua_pushnumber( L, (int(g_LuaPRNG()) % (upper-lower+1)) + lower );
lua_pushnumber(L, random_up_to(g_LuaPRNG, upper - lower + 1) + lower);
return 1;
}

Expand All @@ -156,6 +88,11 @@ namespace

LUA_REGISTER_NAMESPACE( MersenneTwister );

void seed_lua_prng()
{
g_LuaPRNG.seed(static_cast<unsigned int>(time(nullptr)));
}

void fapproach( float& val, float other_val, float to_move )
{
ASSERT_M( to_move >= 0, ssprintf("to_move: %f < 0", to_move) );
Expand Down
46 changes: 25 additions & 21 deletions src/RageUtil.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#define RAGE_UTIL_H

#include <map>
#include <random>
#include <vector>
#include <sstream>
class RageFileDriver;
Expand Down Expand Up @@ -238,35 +239,38 @@ inline uint32_t Swap24LE( uint32_t n ) { return Swap24( n ); }
inline uint16_t Swap16LE( uint16_t n ) { return Swap16( n ); }
#endif

struct MersenneTwister
typedef std::mt19937 RandomGen;

extern RandomGen g_RandomNumberGenerator;

void seed_lua_prng();

inline int random_up_to(RandomGen& rng, int limit)
{
MersenneTwister( int iSeed = 0 ); // 0 = time()
int operator()(); // returns [0,2^31-1]
int operator()( int n ) // returns [0,n)
RandomGen::result_type res = rng();
// Cutting off the incomplete [0,n) chunk at the max value makes the result
// more evenly distributed. -Kyz
RandomGen::result_type up_to_max = RandomGen::max() - (RandomGen::max() % limit);
while (res > up_to_max)
{
return (*this)() % n;
res = rng();
}

void Reset( int iSeed );

private:
static int Temper( int iValue );
void GenerateValues();

int m_Values[624];
int m_iNext;
};
typedef MersenneTwister RandomGen;
return int(res % limit);
}

extern RandomGen g_RandomNumberGenerator;
inline int random_up_to(int limit)
{
return random_up_to(g_RandomNumberGenerator, limit);
}

/**
* @brief Generate a random float between 0 inclusive and 1 exclusive.
* @return the random float.
*/
inline float RandomFloat()
{
return g_RandomNumberGenerator() / 2147483648.0f;
return float(g_RandomNumberGenerator() / 4294967296.0);
}

/**
Expand All @@ -281,15 +285,15 @@ inline float RandomFloat( float fLow, float fHigh )
}

// Returns an integer between nLow and nHigh inclusive
inline int RandomInt( int nLow, int nHigh )
inline int RandomInt(int low, int high)
{
return static_cast<int>( g_RandomNumberGenerator(nHigh - nLow + 1) + nLow );
return random_up_to(g_RandomNumberGenerator, high - low + 1) + low;
}

// Returns an integer between 0 and n-1 inclusive (replacement for rand() % n).
inline int RandomInt( int n )
inline int RandomInt(int n)
{
return static_cast<int>( g_RandomNumberGenerator(n) );
return random_up_to(g_RandomNumberGenerator, n);
}


Expand Down
2 changes: 1 addition & 1 deletion src/RandomSample.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ bool RandomSample::LoadSoundDir( RString sDir, int iMaxToLoad )
GetDirListing( sDir + "*.ogg", arraySoundFiles );
GetDirListing( sDir + "*.wav", arraySoundFiles );

random_shuffle( arraySoundFiles.begin(), arraySoundFiles.end() );
std::shuffle( arraySoundFiles.begin(), arraySoundFiles.end(), g_RandomNumberGenerator );
arraySoundFiles.resize( min( arraySoundFiles.size(), (unsigned)iMaxToLoad ) );

for( unsigned i=0; i<arraySoundFiles.size(); i++ )
Expand Down
12 changes: 8 additions & 4 deletions src/ScreenDebugOverlay.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -910,8 +910,10 @@ static void FillProfileStats( Profile *pProfile )
vector<Steps*> vpAllSteps = (*pSong)->GetAllSteps();
FOREACH( Steps*, vpAllSteps, pSteps )
{
if( rand() % 5 )
pProfile->IncrementStepsPlayCount( *pSong, *pSteps );
if (random_up_to(5))
{
pProfile->IncrementStepsPlayCount(*pSong, *pSteps);
}
for( int i=0; i<iCount; i++ )
{
int iIndex = 0;
Expand All @@ -928,8 +930,10 @@ static void FillProfileStats( Profile *pProfile )
(*pCourse)->GetAllTrails( vpAllTrails );
FOREACH( Trail*, vpAllTrails, pTrail )
{
if( rand() % 5 )
pProfile->IncrementCoursePlayCount( *pCourse, *pTrail );
if (random_up_to(5))
{
pProfile->IncrementCoursePlayCount(*pCourse, *pTrail);
}
for( int i=0; i<iCount; i++ )
{
int iIndex = 0;
Expand Down
Loading

0 comments on commit c158f80

Please sign in to comment.