added optional button to restart game (door, panel and touch variants)
[rocksndiamonds.git] / src / libgame / random.c
1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // random.c
10 // ============================================================================
11
12 #include "random.h"
13
14
15 /*
16  * Copyright (c) 1983 Regents of the University of California.
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms are permitted
20  * provided that the above copyright notice and this paragraph are
21  * duplicated in all such forms and that any documentation,
22  * advertising materials, and other materials related to such
23  * distribution and use acknowledge that the software was developed
24  * by the University of California, Berkeley.  The name of the
25  * University may not be used to endorse or promote products derived
26  * from this software without specific prior written permission.
27  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
29  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
30  */
31
32 /*
33  * This is derived from the Berkeley source:
34  *      @(#)random.c    5.5 (Berkeley) 7/6/88
35  * It was reworked for the GNU C Library by Roland McGrath.
36  */
37
38 #include <errno.h>
39 #include <limits.h>
40 #include <stdlib.h>
41
42
43 /* An improved random number generation package.  In addition to the standard
44    rand()/srand() like interface, this package also has a special state info
45    interface.  The initstate() routine is called with a seed, an array of
46    bytes, and a count of how many bytes are being passed in; this array is
47    then initialized to contain information for random number generation with
48    that much state information.  Good sizes for the amount of state
49    information are 32, 64, 128, and 256 bytes.  The state can be switched by
50    calling the setstate() function with the same array as was initiallized
51    with initstate().  By default, the package runs with 128 bytes of state
52    information and generates far better random numbers than a linear
53    congruential generator.  If the amount of state information is less than
54    32 bytes, a simple linear congruential R.N.G. is used.  Internally, the
55    state information is treated as an array of longs; the zeroeth element of
56    the array is the type of R.N.G. being used (small integer); the remainder
57    of the array is the state information for the R.N.G.  Thus, 32 bytes of
58    state information will give 7 longs worth of state information, which will
59    allow a degree seven polynomial.  (Note: The zeroeth word of state
60    information also has some other information stored in it; see setstate
61    for details).  The random number generation technique is a linear feedback
62    shift register approach, employing trinomials (since there are fewer terms
63    to sum up that way).  In this approach, the least significant bit of all
64    the numbers in the state table will act as a linear feedback shift register,
65    and will have period 2^deg - 1 (where deg is the degree of the polynomial
66    being used, assuming that the polynomial is irreducible and primitive).
67    The higher order bits will have longer periods, since their values are
68    also influenced by pseudo-random carries out of the lower bits.  The
69    total period of the generator is approximately deg*(2**deg - 1); thus
70    doubling the amount of state information has a vast influence on the
71    period of the generator.  Note: The deg*(2**deg - 1) is an approximation
72    only good for large deg, when the period of the shift register is the
73    dominant factor.  With deg equal to seven, the period is actually much
74    longer than the 7*(2**7 - 1) predicted by this formula.  */
75
76
77
78 /* For each of the currently supported random number generators, we have a
79    break value on the amount of state information (you need at least thi
80    bytes of state info to support this random number generator), a degree for
81    the polynomial (actually a trinomial) that the R.N.G. is based on, and
82    separation between the two lower order coefficients of the trinomial.  */
83
84 /* Linear congruential.  */
85 #define TYPE_0          0
86 #define BREAK_0         8
87 #define DEG_0           0
88 #define SEP_0           0
89
90 /* x**7 + x**3 + 1.  */
91 #define TYPE_1          1
92 #define BREAK_1         32
93 #define DEG_1           7
94 #define SEP_1           3
95
96 /* x**15 + x + 1.  */
97 #define TYPE_2          2
98 #define BREAK_2         64
99 #define DEG_2           15
100 #define SEP_2           1
101
102 /* x**31 + x**3 + 1.  */
103 #define TYPE_3          3
104 #define BREAK_3         128
105 #define DEG_3           31
106 #define SEP_3           3
107
108 /* x**63 + x + 1.  */
109 #define TYPE_4          4
110 #define BREAK_4         256
111 #define DEG_4           63
112 #define SEP_4           1
113
114
115 /* Array versions of the above information to make code run faster.
116    Relies on fact that TYPE_i == i.  */
117
118 #define MAX_TYPES       5       /* Max number of types above.  */
119
120
121
122 /* Initially, everything is set up as if from:
123         initstate(1, randtbl, 128);
124    Note that this initialization takes advantage of the fact that srandom
125    advances the front and rear pointers 10*rand_deg times, and hence the
126    rear pointer which starts at 0 will also end up at zero; thus the zeroeth
127    element of the state information, which contains info about the current
128    position of the rear pointer is just
129         (MAX_TYPES * (rptr - state)) + TYPE_3 == TYPE_3.  */
130
131 static int randtbl_0[DEG_3 + 1] =
132 {
133   TYPE_3,
134   -851904987, -43806228, -2029755270, 1390239686, -1912102820,
135   -485608943, 1969813258, -1590463333, -1944053249, 455935928, 508023712,
136   -1714531963, 1800685987, -2015299881, 654595283, -1149023258,
137   -1470005550, -1143256056, -1325577603, -1568001885, 1275120390,
138   -607508183, -205999574, -1696891592, 1492211999, -1528267240,
139   -952028296, -189082757, 362343714, 1424981831, 2039449641,
140 };
141 static int randtbl_1[DEG_3 + 1] =
142 {
143   TYPE_3,
144   -851904987, -43806228, -2029755270, 1390239686, -1912102820,
145   -485608943, 1969813258, -1590463333, -1944053249, 455935928, 508023712,
146   -1714531963, 1800685987, -2015299881, 654595283, -1149023258,
147   -1470005550, -1143256056, -1325577603, -1568001885, 1275120390,
148   -607508183, -205999574, -1696891592, 1492211999, -1528267240,
149   -952028296, -189082757, 362343714, 1424981831, 2039449641,
150 };
151
152
153 /* FPTR and RPTR are two pointers into the state info, a front and a rear
154    pointer.  These two pointers are always rand_sep places aparts, as they
155    cycle through the state information.  (Yes, this does mean we could get
156    away with just one pointer, but the code for random is more efficient
157    this way).  The pointers are left positioned as they would be from the call:
158         initstate(1, randtbl, 128);
159    (The position of the rear pointer, rptr, is really 0 (as explained above
160    in the initialization of randtbl) because the state table pointer is set
161    to point to randtbl[1] (as explained below).)  */
162
163 static int *fptr[2] = { &randtbl_0[SEP_3 + 1], &randtbl_1[SEP_3 + 1] };
164 static int *rptr[2] = { &randtbl_0[1],         &randtbl_1[1]         };
165
166
167
168 /* The following things are the pointer to the state information table,
169    the type of the current generator, the degree of the current polynomial
170    being used, and the separation between the two pointers.
171    Note that for efficiency of random, we remember the first location of
172    the state information, not the zeroeth.  Hence it is valid to access
173    state[-1], which is used to store the type of the R.N.G.
174    Also, we remember the last location, since this is more efficient than
175    indexing every time to find the address of the last element to see if
176    the front and rear pointers have wrapped.  */
177
178 static int *state[2] = { &randtbl_0[1], &randtbl_1[1] };
179
180 static int rand_type[2] = { TYPE_3,     TYPE_3  };
181 static int rand_deg[2]  = { DEG_3,      DEG_3   };
182 static int rand_sep[2]  = { SEP_3,      SEP_3   };
183
184 static int *end_ptr[2] =
185 {
186   &randtbl_0[sizeof(randtbl_0) / sizeof(randtbl_0[0])],
187   &randtbl_1[sizeof(randtbl_1) / sizeof(randtbl_1[0])]
188 };
189
190 /* Initialize the random number generator based on the given seed.  If the
191    type is the trivial no-state-information type, just remember the seed.
192    Otherwise, initializes state[] based on the given "seed" via a linear
193    congruential generator.  Then, the pointers are set to known locations
194    that are exactly rand_sep places apart.  Lastly, it cycles the state
195    information a given number of times to get rid of any initial dependencies
196    introduced by the L.C.R.N.G.  Note that the initialization of randtbl[]
197    for default usage relies on values produced by this routine.  */
198
199 void srandom_linux_libc(int nr, unsigned int x)
200 {
201   state[nr][0] = x;
202
203   if (rand_type[nr] != TYPE_0)
204   {
205     register int i;
206
207     for (i = 1; i < rand_deg[nr]; ++i)
208       state[nr][i] = (1103515145 * state[nr][i - 1]) + 12345;
209
210     fptr[nr] = &state[nr][rand_sep[nr]];
211     rptr[nr] = &state[nr][0];
212
213     for (i = 0; i < 10 * rand_deg[nr]; ++i)
214       random_linux_libc(nr);
215   }
216 }
217
218 /* If we are using the trivial TYPE_0 R.N.G., just do the old linear
219    congruential bit.  Otherwise, we do our fancy trinomial stuff, which is the
220    same in all ther other cases due to all the global variables that have been
221    set up.  The basic operation is to add the number at the rear pointer into
222    the one at the front pointer.  Then both pointers are advanced to the next
223    location cyclically in the table.  The value returned is the sum generated,
224    reduced to 31 bits by throwing away the "least random" low bit.
225    Note: The code takes advantage of the fact that both the front and
226    rear pointers can't wrap on the same call by not testing the rear
227    pointer if the front one has wrapped.  Returns a 31-bit random number.  */
228
229 int random_linux_libc(int nr)
230 {
231   if (rand_type[nr] == TYPE_0)
232   {
233     state[nr][0] = ((state[nr][0] * 1103515245) + 12345) & INT_MAX;
234     return state[nr][0];
235   }
236   else
237   {
238     int i;
239
240     *fptr[nr] += *rptr[nr];
241
242     /* Chucking least random bit.  */
243     i = (*fptr[nr] >> 1) & INT_MAX;
244     fptr[nr]++;
245
246     if (fptr[nr] >= end_ptr[nr])
247     {
248       fptr[nr] = state[nr];
249       rptr[nr]++;
250     }
251     else
252     {
253       rptr[nr]++;
254       if (rptr[nr] >= end_ptr[nr])
255         rptr[nr] = state[nr];
256     }
257
258     return i;
259   }
260 }
261
262
263 // ============================================================================
264
265 /*
266  * prng.c - Portable, ISO C90 and C99 compliant high-quality
267  * pseudo-random number generator based on the alleged RC4
268  * cipher.  This PRNG should be suitable for most general-purpose
269  * uses.  Not recommended for cryptographic or financial
270  * purposes.  Not thread-safe.
271  */
272
273 /*
274  * Copyright (c) 2004 Ben Pfaff <blp@cs.stanford.edu>.
275  * All rights reserved.
276  *
277  * Redistribution and use in source and binary forms, with or
278  * without modification, are permitted provided that the
279  * following conditions are met:
280  *
281  * 1. Redistributions of source code must retain the above
282  * copyright notice, this list of conditions and the following
283  * disclaimer.
284  *
285  * 2. Redistributions in binary form must reproduce the above
286  * copyright notice, this list of conditions and the following
287  * disclaimer in the documentation and/or other materials
288  * provided with the distribution.
289  *
290  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS
291  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
292  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
293  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT
294  * SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
295  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
296  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
297  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
298  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
299  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
300  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
302  * OF SUCH DAMAGE.
303  *
304  */
305
306 #include <assert.h>
307 #include <float.h>
308 #include <limits.h>
309 #include <math.h>
310 #include <time.h>
311
312 /* RC4-based pseudo-random state. */
313 static unsigned char s[256];
314 static int s_i, s_j;
315
316 /* Nonzero if PRNG has been seeded. */
317 static int seeded;
318
319 /* Swap bytes that A and B point to. */
320 #define SWAP_BYTE(A, B)                         \
321         do {                                    \
322                 unsigned char swap_temp = *(A); \
323                 *(A) = *(B);                    \
324                 *(B) = swap_temp;               \
325         } while (0)
326
327 /* Seeds the pseudo-random number generator based on the current
328    time.
329
330    If the user calls neither this function nor prng_seed_bytes()
331    before any prng_get*() function, this function is called
332    automatically to obtain a time-based seed. */
333 void
334 prng_seed_time (void)
335 {
336   static time_t t;
337   if (t == 0)
338     t = time (NULL);
339   else
340     t++;
341
342   prng_seed_bytes (&t, sizeof t);
343 }
344
345 /* Retrieves one octet from the array BYTES, which is N_BYTES in
346    size, starting at an offset of OCTET_IDX octets.  BYTES is
347    treated as a circular array, so that accesses past the first
348    N_BYTES bytes wrap around to the beginning. */
349 static unsigned char
350 get_octet (const void *bytes_, size_t n_bytes, size_t octet_idx)
351 {
352   const unsigned char *bytes = bytes_;
353   if (CHAR_BIT == 8)
354     return bytes[octet_idx % n_bytes];
355   else
356     {
357       size_t first_byte = octet_idx * 8 / CHAR_BIT % n_bytes;
358       size_t start_bit = octet_idx * 8 % CHAR_BIT;
359       unsigned char c = (bytes[first_byte] >> start_bit) & 255;
360
361       size_t bits_filled = CHAR_BIT - start_bit;
362       if (CHAR_BIT % 8 != 0 && bits_filled < 8)
363         {
364           size_t bits_left = 8 - bits_filled;
365           unsigned char bits_left_mask = (1u << bits_left) - 1;
366           size_t second_byte = first_byte + 1 < n_bytes ? first_byte + 1 : 0;
367
368           c |= (bytes[second_byte] & bits_left_mask) << bits_filled;
369         }
370
371       return c;
372     }
373 }
374
375 /* Seeds the pseudo-random number based on the SIZE bytes in
376    KEY.  At most the first 2048 bits in KEY are used. */
377 void
378 prng_seed_bytes (const void *key, size_t size)
379 {
380   int i, j;
381
382   assert (key != NULL && size > 0);
383
384   for (i = 0; i < 256; i++)
385     s[i] = i;
386   for (i = j = 0; i < 256; i++)
387     {
388       j = (j + s[i] + get_octet (key, size, i)) & 255;
389       SWAP_BYTE (s + i, s + j);
390     }
391
392   s_i = s_j = 0;
393   seeded = 1;
394 }
395
396 /* Returns a pseudo-random integer in the range [0, 255]. */
397 unsigned char
398 prng_get_octet (void)
399 {
400   if (!seeded)
401     prng_seed_time ();
402
403   s_i = (s_i + 1) & 255;
404   s_j = (s_j + s[s_i]) & 255;
405   SWAP_BYTE (s + s_i, s + s_j);
406
407   return s[(s[s_i] + s[s_j]) & 255];
408 }
409
410 /* Returns a pseudo-random integer in the range [0, UCHAR_MAX]. */
411 unsigned char
412 prng_get_byte (void)
413 {
414   unsigned byte;
415   int bits;
416
417   byte = prng_get_octet ();
418   for (bits = 8; bits < CHAR_BIT; bits += 8)
419     byte = (byte << 8) | prng_get_octet ();
420   return byte;
421 }
422
423 /* Fills BUF with SIZE pseudo-random bytes. */
424 void
425 prng_get_bytes (void *buf_, size_t size)
426 {
427   unsigned char *buf;
428
429   for (buf = buf_; size-- > 0; buf++)
430     *buf = prng_get_byte ();
431 }
432
433 /* Returns a pseudo-random unsigned long in the range [0,
434    ULONG_MAX]. */
435 unsigned long
436 prng_get_ulong (void)
437 {
438   unsigned long ulng;
439   size_t bits;
440
441   ulng = prng_get_octet ();
442   for (bits = 8; bits < CHAR_BIT * sizeof ulng; bits += 8)
443     ulng = (ulng << 8) | prng_get_octet ();
444   return ulng;
445 }
446
447 /* Returns a pseudo-random long in the range [0, LONG_MAX]. */
448 long
449 prng_get_long (void)
450 {
451   return prng_get_ulong () & LONG_MAX;
452 }
453
454 /* Returns a pseudo-random unsigned int in the range [0,
455    UINT_MAX]. */
456 unsigned
457 prng_get_uint (void)
458 {
459   unsigned uint;
460   size_t bits;
461
462   uint = prng_get_octet ();
463   for (bits = 8; bits < CHAR_BIT * sizeof uint; bits += 8)
464     uint = (uint << 8) | prng_get_octet ();
465   return uint;
466 }
467
468 /* Returns a pseudo-random int in the range [0, INT_MAX]. */
469 int
470 prng_get_int (void)
471 {
472   return prng_get_uint () & INT_MAX;
473 }
474
475 /* Returns a pseudo-random floating-point number from the uniform
476    distribution with range [0,1). */
477 double
478 prng_get_double (void)
479 {
480   for (;;)
481     {
482       double dbl = prng_get_ulong () / (ULONG_MAX + 1.0);
483       if (dbl >= 0.0 && dbl < 1.0)
484         return dbl;
485     }
486 }
487
488 /* Returns a pseudo-random floating-point number from the
489    distribution with mean 0 and standard deviation 1.  (Multiply
490    the result by the desired standard deviation, then add the
491    desired mean.) */
492 double
493 prng_get_double_normal (void)
494 {
495   /* Knuth, _The Art of Computer Programming_, Vol. 2, 3.4.1C,
496      Algorithm P. */
497   static int has_next = 0;
498   static double next_normal;
499   double this_normal;
500
501   if (has_next)
502     {
503       this_normal = next_normal;
504       has_next = 0;
505     }
506   else
507     {
508       static double limit;
509       double v1, v2, s;
510
511       if (limit == 0.0)
512         limit = log (DBL_MAX / 2) / (DBL_MAX / 2);
513
514       for (;;)
515         {
516           double u1 = prng_get_double ();
517           double u2 = prng_get_double ();
518           v1 = 2.0 * u1 - 1.0;
519           v2 = 2.0 * u2 - 1.0;
520           s = v1 * v1 + v2 * v2;
521           if (s > limit && s < 1)
522             break;
523         }
524
525       this_normal = v1 * sqrt (-2. * log (s) / s);
526       next_normal = v2 * sqrt (-2. * log (s) / s);
527       has_next = 1;
528     }
529
530   return this_normal;
531 }