summaryrefslogtreecommitdiff
path: root/Random.h
blob: 7e0df3fa45d95db9b2ef3661e6a68ab7f8516d10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#pragma once

#include "Types.h"

//-----------------------------------------------------------------------------
// Xorshift RNG based on code by George Marsaglia
// http://en.wikipedia.org/wiki/Xorshift

struct Rand
{
  uint32_t x;
  uint32_t y;
  uint32_t z;
  uint32_t w;

  Rand()
  {
    reseed(uint32_t(0));
  }

  Rand( uint32_t seed )
  {
    reseed(seed);
  }

  void reseed ( uint32_t seed )
  {
    x = 0x498b3bc5 ^ seed;
    y = 0;
    z = 0;
    w = 0;

    for(int i = 0; i < 10; i++) mix();
  }

  void reseed ( uint64_t seed )
  {
    x = 0x498b3bc5 ^ (uint32_t)(seed >>  0);
    y = 0x5a05089a ^ (uint32_t)(seed >> 32);
    z = 0;
    w = 0;

    for(int i = 0; i < 10; i++) mix();
  }

  //-----------------------------------------------------------------------------

  void mix ( void )
  {
    uint32_t t = x ^ (x << 11);
    x = y; y = z; z = w;
    w = w ^ (w >> 19) ^ t ^ (t >> 8); 
  }

  uint32_t rand_u32 ( void )
  {
    mix();

    return x;
  }

  uint64_t rand_u64 ( void ) 
  {
    mix();

    uint64_t a = x;
    uint64_t b = y;

    return (a << 32) | b;
  }

  void rand_p ( void * blob, int bytes )
  {
    uint32_t * blocks = reinterpret_cast<uint32_t*>(blob);

    while(bytes >= 4)
    {
      blocks[0] = rand_u32();
      blocks++;
      bytes -= 4;
    }

    uint8_t * tail = reinterpret_cast<uint8_t*>(blocks);

    for(int i = 0; i < bytes; i++)
    {
      tail[i] = (uint8_t)rand_u32();
    }
  }
};

//-----------------------------------------------------------------------------

extern Rand g_rand1;

inline uint32_t rand_u32 ( void ) { return g_rand1.rand_u32(); }
inline uint64_t rand_u64 ( void ) { return g_rand1.rand_u64(); }

inline void rand_p ( void * blob, int bytes )
{
  uint32_t * blocks = (uint32_t*)blob;

  while(bytes >= 4)
  {
    *blocks++ = rand_u32();
    bytes -= 4;
  }

  uint8_t * tail = (uint8_t*)blocks;

  for(int i = 0; i < bytes; i++)
  {
    tail[i] = (uint8_t)rand_u32();
  }
}

//-----------------------------------------------------------------------------