diff --git a/source/graphics/ObjectBase.cpp b/source/graphics/ObjectBase.cpp index 8cbafbf17c..1d4e6b1e60 100644 --- a/source/graphics/ObjectBase.cpp +++ b/source/graphics/ObjectBase.cpp @@ -279,9 +279,7 @@ void CObjectBase::CalculateVariation(std::set& strings, variation_key& cho // Choose a random number in the interval [0..totalFreq). // (It shouldn't be necessary to use a network-synchronised RNG, // since actors are meant to have purely visual manifestations.) - int randNum = (int)( ((float)rand() / RAND_MAX) * totalFreq ); - - debug_assert(randNum < totalFreq); + int randNum = rand(0, totalFreq); // and use that to choose one of the variants for (Iter it = matches.begin(); it != matches.end(); ++it) diff --git a/source/lib/lib.cpp b/source/lib/lib.cpp index e95996bfa2..f91b294455 100755 --- a/source/lib/lib.cpp +++ b/source/lib/lib.cpp @@ -382,17 +382,6 @@ u16 fp_to_u16(double in) -// return random integer in [0, limit). -// does not use poorly distributed lower bits of rand(). -int rand_up_to(int limit) -{ - // (i64 avoids overflowing in multiply) - const i64 ret = ((i64)limit * rand()) / (RAND_MAX+1); - debug_assert(0 <= ret && ret < limit); - return (int)ret; -} - - // big endian! void base32(const int len, const u8* in, u8* out) { @@ -524,6 +513,8 @@ int match_wildcardw(const wchar_t* s, const wchar_t* w) } + + // return random integer in [min, max). // avoids several common pitfalls; see discussion at // http://www.azillionmonkeys.com/qed/random.html diff --git a/source/lib/lib.h b/source/lib/lib.h index de4ec5e5e5..407e3f21a8 100755 --- a/source/lib/lib.h +++ b/source/lib/lib.h @@ -303,9 +303,6 @@ inline bool feq(float f1, float f2) extern u16 fp_to_u16(double in); -// return random integer in [0, limit). -// does not use poorly distributed lower bits of rand(). -extern int rand_up_to(int limit); // big endian! extern void base32(const int len, const u8* in, u8* out); diff --git a/source/lib/lockfree.cpp b/source/lib/lockfree.cpp index 7d8f1caf53..cff6f4a295 100644 --- a/source/lib/lockfree.cpp +++ b/source/lib/lockfree.cpp @@ -842,9 +842,9 @@ static void* thread_func(void* arg) { void* user_data; - const int action = rand_up_to(4); - const uintptr_t key = rand_up_to(100); - const int sleep_duration_ms = rand_up_to(100); + const int action = rand(0, 4); + const uintptr_t key = rand(0, 100); + const int sleep_duration_ms = rand(0, 100); debug_printf("thread %d: %s\n", thread_number, action_strings[action]); //