fixed compiler warning
[rocksndiamonds.git] / src / game_bd / bd_random.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * SPDX-License-Identifier: LGPL-2.1-or-later
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* Originally developed and coded by Makoto Matsumoto and Takuji
21  * Nishimura.  Please mail <matumoto@math.keio.ac.jp>, if you're using
22  * code from this file in your own programs or libraries.
23  * Further information on the Mersenne Twister can be found at
24  * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
25  * This code was adapted to glib by Sebastian Wilhelmi.
26  */
27
28 /*
29  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
30  * file for a list of people on the GLib Team.  See the ChangeLog
31  * files for a list of changes.  These files are distributed with
32  * GLib at ftp://ftp.gtk.org/pub/gtk/.
33  */
34
35 #include <math.h>
36 #include <errno.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 #include <time.h>
42
43 #include "main_bd.h"
44
45 #if defined(PLATFORM_WINDOWS)
46 #include <process.h>    // for getpid()
47 #if (defined(_MSC_VER) && _MSC_VER >= 1400) || defined(__MINGW64_VERSION_MAJOR)
48 extern errno_t rand_s (unsigned int *randomValue);
49 #endif
50 #endif
51
52
53 /**
54  * GdRand:
55  *
56  * The GdRand struct is an opaque data structure. It should only be
57  * accessed through the gd_rand_* functions.
58  **/
59
60 // Period parameters
61 #define N 624
62 #define M 397
63 #define MATRIX_A   0x9908b0df // constant vector a
64 #define UPPER_MASK 0x80000000 // most significant w-r bits
65 #define LOWER_MASK 0x7fffffff // least significant r bits
66
67 // Tempering parameters
68 #define TEMPERING_MASK_B 0x9d2c5680
69 #define TEMPERING_MASK_C 0xefc60000
70 #define TEMPERING_SHIFT_U(y)  (y >> 11)
71 #define TEMPERING_SHIFT_S(y)  (y << 7)
72 #define TEMPERING_SHIFT_T(y)  (y << 15)
73 #define TEMPERING_SHIFT_L(y)  (y >> 18)
74
75 struct _GdRand
76 {
77   unsigned int mt[N]; // the array for the state vector
78   unsigned int mti;
79 };
80
81 /**
82  * gd_rand_new_with_seed: (constructor)
83  * @seed: a value to initialize the random number generator
84  *
85  * Creates a new random number generator initialized with @seed.
86  *
87  * Returns: (transfer full): the new #GdRand
88  **/
89 GdRand *
90 gd_rand_new_with_seed (unsigned int seed)
91 {
92   GdRand *rand = checked_calloc(sizeof(GdRand));
93   gd_rand_set_seed (rand, seed);
94   return rand;
95 }
96
97 /**
98  * gd_rand_new_with_seed_array: (constructor)
99  * @seed: an array of seeds to initialize the random number generator
100  * @seed_length: an array of seeds to initialize the random number
101  *     generator
102  *
103  * Creates a new random number generator initialized with @seed.
104  *
105  * Returns: (transfer full): the new #GdRand
106  *
107  * Since: 2.4
108  */
109 GdRand *
110 gd_rand_new_with_seed_array (const unsigned int *seed, unsigned int seed_length)
111 {
112   GdRand *rand = checked_calloc(sizeof(GdRand));
113   gd_rand_set_seed_array (rand, seed, seed_length);
114
115   return rand;
116 }
117
118 /**
119  * gd_rand_new: (constructor)
120  *
121  * Creates a new random number generator initialized with a seed taken
122  * either from `/dev/urandom` (if existing) or from the current time
123  * (as a fallback).
124  *
125  * On Windows, the seed is taken from rand_s().
126  *
127  * Returns: (transfer full): the new #GdRand
128  */
129 GdRand *
130 gd_rand_new (void)
131 {
132   unsigned int seed[4];
133
134 #if defined(PLATFORM_UNIX)
135   static boolean dev_urandom_exists = TRUE;
136
137   if (dev_urandom_exists)
138   {
139     FILE *dev_urandom;
140
141     do
142     {
143       dev_urandom = fopen ("/dev/urandom", "rbe");
144     }
145     while (dev_urandom == NULL && errno == EINTR);
146
147     if (dev_urandom)
148     {
149       int r;
150
151       setvbuf (dev_urandom, NULL, _IONBF, 0);
152
153       do
154       {
155         errno = 0;
156         r = fread (seed, sizeof (seed), 1, dev_urandom);
157       }
158       while (errno == EINTR);
159
160       if (r != 1)
161         dev_urandom_exists = FALSE;
162
163       fclose (dev_urandom);
164     }
165     else
166     {
167       dev_urandom_exists = FALSE;
168     }
169   }
170
171   if (!dev_urandom_exists)
172   {
173     struct timespec now;
174
175     clock_gettime(CLOCK_REALTIME, &now);
176
177     seed[0] = now.tv_sec;
178     seed[1] = now.tv_nsec;
179     seed[2] = getpid ();
180     seed[3] = getppid ();
181   }
182 #else // PLATFORM_WINDOWS
183   /* rand_s() is only available since Visual Studio 2005 and
184    * MinGW-w64 has a wrapper that will emulate rand_s() if it's not in msvcrt
185    */
186 #if (defined(_MSC_VER) && _MSC_VER >= 1400) || defined(__MINGW64_VERSION_MAJOR)
187   size_t i;
188
189   for (i = 0; i < ARRAY_SIZE(seed); i++)
190     rand_s (&seed[i]);
191 #else
192 #warning Using insecure seed for random number generation because of missing rand_s() in Windows XP
193   GTimeVal now;
194
195   gd_get_current_time (&now);
196
197   seed[0] = now.tv_sec;
198   seed[1] = now.tv_usec;
199   seed[2] = getpid ();
200   seed[3] = 0;
201 #endif
202
203 #endif
204
205   return gd_rand_new_with_seed_array (seed, 4);
206 }
207
208 /**
209  * gd_rand_free:
210  * @rand_: a #GdRand
211  *
212  * Frees the memory allocated for the #GdRand.
213  */
214 void
215 gd_rand_free (GdRand *rand)
216 {
217   if (rand != NULL)
218     checked_free(rand);
219 }
220
221 /**
222  * gd_rand_copy:
223  * @rand_: a #GdRand
224  *
225  * Copies a #GdRand into a new one with the same exact state as before.
226  * This way you can take a snapshot of the random number generator for
227  * replaying later.
228  *
229  * Returns: (transfer full): the new #GdRand
230  *
231  * Since: 2.4
232  */
233 GdRand *
234 gd_rand_copy (GdRand *rand)
235 {
236   GdRand *new_rand;
237
238   if (rand == NULL)
239     return NULL;
240
241   new_rand = checked_calloc(sizeof(GdRand));
242   memcpy(new_rand, rand, sizeof(GdRand));
243
244   return new_rand;
245 }
246
247 /**
248  * gd_rand_set_seed:
249  * @rand_: a #GdRand
250  * @seed: a value to reinitialize the random number generator
251  *
252  * Sets the seed for the random number generator #GdRand to @seed.
253  */
254 void
255 gd_rand_set_seed (GdRand *rand, unsigned int seed)
256 {
257   if (rand == NULL)
258     return;
259
260   // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
261   // In the previous version (see above), MSBs of the
262   // seed affect only MSBs of the array mt[].
263
264   rand->mt[0] = seed;
265   for (rand->mti = 1; rand->mti < N; rand->mti++)
266     rand->mt[rand->mti] = 1812433253UL *
267       (rand->mt[rand->mti - 1] ^ (rand->mt[rand->mti - 1] >> 30)) + rand->mti;
268 }
269
270 /**
271  * gd_rand_set_seed_array:
272  * @rand_: a #GdRand
273  * @seed: array to initialize with
274  * @seed_length: length of array
275  *
276  * Initializes the random number generator by an array of longs.
277  * Array can be of arbitrary size, though only the first 624 values
278  * are taken.  This function is useful if you have many low entropy
279  * seeds, or if you require more then 32 bits of actual entropy for
280  * your application.
281  *
282  * Since: 2.4
283  */
284 void
285 gd_rand_set_seed_array (GdRand *rand, const unsigned int *seed, unsigned int seed_length)
286 {
287   unsigned int i, j, k;
288
289   if (rand == NULL || seed_length < 1)
290     return;
291
292   gd_rand_set_seed (rand, 19650218UL);
293
294   i = 1;
295   j = 0;
296   k = (N > seed_length ? N : seed_length);
297
298   for (; k; k--)
299   {
300     rand->mt[i] = ((rand->mt[i] ^ ((rand->mt[i - 1] ^ (rand->mt[i - 1] >> 30)) * 1664525UL))
301                    + seed[j] + j);      // non linear
302     rand->mt[i] &= 0xffffffffUL;        // for WORDSIZE > 32 machines
303     i++;
304     j++;
305
306     if (i >= N)
307     {
308       rand->mt[0] = rand->mt[N - 1];
309       i = 1;
310     }
311
312     if (j >= seed_length)
313       j = 0;
314   }
315
316   for (k = N - 1; k; k--)
317   {
318     rand->mt[i] = ((rand->mt[i] ^ ((rand->mt[i - 1] ^ (rand->mt[i - 1] >> 30)) * 1566083941UL))
319                    - i);                // non linear
320     rand->mt[i] &= 0xffffffffUL;        // for WORDSIZE > 32 machines
321     i++;
322
323     if (i >= N)
324     {
325       rand->mt[0] = rand->mt[N - 1];
326       i = 1;
327     }
328   }
329
330   rand->mt[0] = 0x80000000UL;           // MSB is 1; assuring non-zero initial array
331 }
332
333 /**
334  * gd_rand_boolean:
335  * @rand_: a #GdRand
336  *
337  * Returns a random #boolean from @rand_.
338  * This corresponds to an unbiased coin toss.
339  *
340  * Returns: a random #boolean
341  */
342 /**
343  * gd_rand_int:
344  * @rand_: a #GdRand
345  *
346  * Returns the next random unsigned int from @rand_ equally distributed over
347  * the range [0..2^32-1].
348  *
349  * Returns: a random number
350  */
351 unsigned int
352 gd_rand_int (GdRand *rand)
353 {
354   unsigned int y;
355   static const unsigned int mag01[2] = { 0x0, MATRIX_A };
356   // mag01[x] = x * MATRIX_A  for x=0,1
357
358   if (rand == NULL)
359     return 0;
360
361   if (rand->mti >= N)
362   {
363     // generate N words at one time
364     int kk;
365
366     for (kk = 0; kk < N - M; kk++)
367     {
368       y = (rand->mt[kk] & UPPER_MASK) | (rand->mt[kk + 1] & LOWER_MASK);
369       rand->mt[kk] = rand->mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1];
370     }
371
372     for (; kk < N - 1; kk++)
373     {
374       y = (rand->mt[kk] & UPPER_MASK) | (rand->mt[kk + 1] & LOWER_MASK);
375       rand->mt[kk] = rand->mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1];
376     }
377
378     y = (rand->mt[N - 1] & UPPER_MASK) | (rand->mt[0] & LOWER_MASK);
379     rand->mt[N - 1] = rand->mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1];
380
381     rand->mti = 0;
382   }
383
384   y = rand->mt[rand->mti++];
385   y ^= TEMPERING_SHIFT_U(y);
386   y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
387   y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
388   y ^= TEMPERING_SHIFT_L(y);
389
390   return y;
391 }
392
393 // transform [0..2^32] -> [0..1]
394 #define GD_RAND_DOUBLE_TRANSFORM 2.3283064365386962890625e-10
395
396 /**
397  * gd_rand_int_range:
398  * @rand_: a #GdRand
399  * @begin: lower closed bound of the interval
400  * @end: upper open bound of the interval
401  *
402  * Returns the next random #int from @rand_ equally distributed over
403  * the range [@begin..@end-1].
404  *
405  * Returns: a random number
406  */
407 int
408 gd_rand_int_range (GdRand *rand, int begin, int end)
409 {
410   unsigned int dist = end - begin;
411   unsigned int random = 0;
412
413   if (rand == NULL || end <= begin)
414     return begin;
415
416   if (dist == 0)
417     return begin;
418
419   /* maxvalue is set to the predecessor of the greatest
420    * multiple of dist less or equal 2^32.
421    */
422   unsigned int maxvalue;
423   if (dist <= 0x80000000u) // 2^31
424   {
425     // maxvalue = 2^32 - 1 - (2^32 % dist)
426     unsigned int leftover = (0x80000000u % dist) * 2;
427     if (leftover >= dist) leftover -= dist;
428     maxvalue = 0xffffffffu - leftover;
429   }
430   else
431   {
432     maxvalue = dist - 1;
433   }
434
435   do
436     random = gd_rand_int (rand);
437   while (random > maxvalue);
438
439   random %= dist;
440
441   return begin + random;
442 }
443
444 /**
445  * gd_rand_double:
446  * @rand_: a #GRand
447  *
448  * Returns the next random #double from @rand_ equally distributed over
449  * the range [0..1).
450  *
451  * Returns: a random number
452  */
453 double
454 gd_rand_double (GdRand *rand)
455 {
456   /* We set all 52 bits after the point for this, not only the first
457      32. That's why we need two calls to gd_rand_int */
458   double retval = gd_rand_int(rand) * GD_RAND_DOUBLE_TRANSFORM;
459   retval = (retval + gd_rand_int(rand)) * GD_RAND_DOUBLE_TRANSFORM;
460
461   /* The following might happen due to very bad rounding luck, but
462    * actually this should be more than rare, we just try again then */
463   if (retval >= 1.0)
464     return gd_rand_double (rand);
465
466   return retval;
467 }
468
469 /**
470  * gd_rand_double_range:
471  * @rand_: a #GRand
472  * @begin: lower closed bound of the interval
473  * @end: upper open bound of the interval
474  *
475  * Returns the next random #double from @rand_ equally distributed over
476  * the range [@begin..@end).
477  *
478  * Returns: a random number
479  */
480 double
481 gd_rand_double_range (GdRand *rand, double begin, double end)
482 {
483   double r;
484
485   r = gd_rand_double(rand);
486
487   return r * end - (r - 1) * begin;
488 }
489
490 static GdRand *
491 get_global_random (void)
492 {
493   static GdRand *global_random;
494
495   // called while locked
496   if (!global_random)
497     global_random = gd_rand_new();
498
499   return global_random;
500 }
501
502 /**
503  * gd_random_boolean:
504  *
505  * Returns a random #gboolean.
506  * This corresponds to an unbiased coin toss.
507  *
508  * Returns: a random #gboolean
509  */
510 /**
511  * gd_random_int:
512  *
513  * Return a random #guint32 equally distributed over the range
514  * [0..2^32-1].
515  *
516  * Returns: a random number
517  */
518 unsigned int
519 gd_random_int (void)
520 {
521   unsigned int result;
522
523   result = gd_rand_int(get_global_random());
524
525   return result;
526 }
527
528 /**
529  * gd_random_int_range:
530  * @begin: lower closed bound of the interval
531  * @end: upper open bound of the interval
532  *
533  * Returns a random #int equally distributed over the range
534  * [@begin..@end-1].
535  *
536  * Returns: a random number
537  */
538 int
539 gd_random_int_range (int begin, int end)
540 {
541   int result;
542
543   result = gd_rand_int_range (get_global_random(), begin, end);
544
545   return result;
546 }
547
548 /**
549  * gd_random_double:
550  *
551  * Returns a random #double equally distributed over the range [0..1).
552  *
553  * Returns: a random number
554  */
555 double
556 gd_random_double (void)
557 {
558   double result;
559
560   result = gd_rand_double(get_global_random());
561
562   return result;
563 }
564
565 /**
566  * gd_random_double_range:
567  * @begin: lower closed bound of the interval
568  * @end: upper open bound of the interval
569  *
570  * Returns a random #double equally distributed over the range
571  * [@begin..@end).
572  *
573  * Returns: a random number
574  */
575 double
576 gd_random_double_range (double begin, double end)
577 {
578   double result;
579
580   result = gd_rand_double_range(get_global_random(), begin, end);
581
582   return result;
583 }