1/*
2 * LegacyClonk
3 *
4 * Copyright (c) 1998-2000, Matthes Bender (RedWolf Design)
5 * Copyright (c) 2017-2020, The LegacyClonk Team and contributors
6 *
7 * Distributed under the terms of the ISC license; see accompanying file
8 * "COPYING" for details.
9 *
10 * "Clonk" is a registered trademark of Matthes Bender, used with permission.
11 * See accompanying file "TRADEMARK" for details.
12 *
13 * To redistribute this file separately, substitute the full license texts
14 * for the above references.
15 */
16
17/* Buffered fast and network-safe random */
18
19#pragma once
20
21#ifdef DEBUGREC
22#include <C4Record.h>
23#endif
24
25#include <cstdint>
26#include <cstdlib>
27#include <ctime>
28
29inline int RandomCount{0};
30inline unsigned int RandomHold{0};
31
32inline void FixedRandom(uint32_t dwSeed)
33{
34 // for SafeRandom
35 srand(seed: static_cast<unsigned>(time(timer: nullptr)));
36 RandomHold = dwSeed;
37 RandomCount = 0;
38}
39
40inline int Random(int iRange)
41{
42 // next pseudorandom value
43 RandomCount++;
44#ifdef DEBUGREC
45 C4RCRandom rc;
46 rc.Cnt = RandomCount;
47 rc.Range = iRange;
48 if (iRange == 0)
49 rc.Val = 0;
50 else
51 {
52 RandomHold = RandomHold * 214013L + 2531011L;
53 rc.Val = (RandomHold >> 16) % iRange;
54 }
55 AddDbgRec(RCT_Random, &rc, sizeof(rc));
56 return rc.Val;
57#else
58 if (iRange == 0) return 0;
59 RandomHold = RandomHold * 214013L + 2531011L;
60 return (RandomHold >> 16) % iRange;
61#endif
62}
63
64inline unsigned int SeededRandom(unsigned int iSeed, unsigned int iRange)
65{
66 if (!iRange) return 0;
67 iSeed = iSeed * 214013L + 2531011L;
68 return (iSeed >> 16) % iRange;
69}
70
71inline int SafeRandom(int range)
72{
73 if (!range) return 0;
74 return rand() % range;
75}
76
77void Randomize3();
78int Rnd3();
79