Permalink
Browse files

Refactor rnd/rndscale/dtrnd to be proper functions

Before this they were macros. Macros are evil.
  • Loading branch information...
koraa authored and a-teammate committed Jun 12, 2015
1 parent d100d3d commit 6a1e4d686a3a4d7c21828a97712486101038f4f7
Showing with 33 additions and 6 deletions.
  1. +17 −0 inexor/shared/tools.cpp
  2. +16 −6 inexor/shared/tools.h
@@ -5,6 +5,9 @@
#include <unistd.h>
#endif
#include <cstdlib>
#include <limits>
////////////////////////// strings ////////////////////////////////////////
static string tmpstr[4];
@@ -57,6 +60,20 @@ uint randomMT()
return y;
}
int rnd(const int x) {
return abs((int)randomMT()) % x;
}
float rndscale(const double x) {
double int_max = std::numeric_limits<int>::max();
return abs((int)randomMT()) * x / int_max;
}
int detrnd(const uint seed, const int x) {
return ( (seed*1103515245 + 12345) >>16) %x;
}
///////////////////////// network ///////////////////////
// all network traffic is in 32bit ints, which are then compressed using the following simple scheme (assumes that most values are small).
@@ -67,12 +67,22 @@ static inline int bitscan(uint mask)
#endif
#endif
extern void seedMT(uint seed);
extern uint randomMT();
#define rnd(x) ((int)(randomMT()&0x7FFFFFFF)%(x))
#define rndscale(x) (float((randomMT()&0x7FFFFFFF)*double(x)/double(0x7FFFFFFF)))
#define detrnd(s, x) ((int)(((((uint)(s))*1103515245+12345)>>16)%(x)))
/// Generate a random integer between 0 and x, excluding x
///
/// ```rnd(2) // can producd 0 and 1```
extern int rnd(const int x);
/// Generate a random float between 0 and x
///
/// ```rndscale(1) // min: 0, max: 0.99...```
extern float rndscale(const double x);
/// Generate a deterministic pseudo-random number
///
/// This means, that given the same seed and the same
/// maximum value (`x`) this function will always return the
/// same.
extern int detrnd(const uint seed, const int x);
/// "for"-loop macro definitions
/// DEPRECATED: Use c++ range based loops instead

0 comments on commit 6a1e4d6

Please sign in to comment.