Debian Codegraph @

src/engine/rand.h

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2026 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2009 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #pragma once
25
26 #include <algorithm>
27 #include <array>
28 #include <cassert>
29 #include <cstdint>
30 #include <cstdlib>
31 // IWYU issue workaround. When <exception> is included IWYU will remove it and require <string>.
32 // When <string> is included it'll remove it and require <exception>
33 // IWYU pragma: no_include <exception>
34 #include <functional>
35 #include <iterator>
36 #include <limits>
37 #include <type_traits>
38 #include <utility>
39 #include <vector>
40
41 namespace Rand
42 {
43 class PCG32
44 {
45 public:
46 static constexpr uint32_t min()
47 {
48 return std::numeric_limits<uint32_t>::min();
49 }
50
51 static constexpr uint32_t max()
52 {
53 return std::numeric_limits<uint32_t>::max();
54 }
55
56 template <typename Random, typename = std::enable_if_t<std::is_invocable_v<Random>>>
57 explicit constexpr PCG32( Random & gen )
58 : PCG32( generateUInt64( gen ), generateUInt64( gen ) )
59 {}
60
61 explicit constexpr PCG32( const uint64_t seed = defaultSeed, const uint64_t stream = defaultStream )
62 : _state( 0 )
63 , _increment( stream )
64 {
65 advanceState();
66 _state += seed;
67 advanceState();
68 }
69
70 constexpr uint32_t operator()()
71 {
72 const uint64_t prevState = _state;
73 advanceState();
74
75 const uint32_t xorShifted = static_cast<uint32_t>( ( ( prevState >> 18U ) ^ prevState ) >> 27U );
76 const uint32_t rotations = prevState >> 59U;
77 return rotateRight( xorShifted, rotations );
78 }
79
80 constexpr uint64_t getStream() const
81 {
82 return _increment;
83 }
84
85 constexpr void setStream( const uint64_t stream )
86 {
87 _increment = stream;
88 }
89
90 private:
91 static constexpr uint64_t multiplier = 6364136223846793005ULL;
92 static constexpr uint64_t defaultStream = 54ULL;
93 static constexpr uint64_t defaultSeed = 42ULL;
94
95 static constexpr uint32_t rotateRight( const uint32_t value, const uint32_t rotations )
96 {
97 return ( value >> rotations ) | ( value << ( ( ~( rotations - 1 ) ) & 31 ) );
98 }
99
100 // Defines a new templated false value to be used in static_assert
101 // See https://devblogs.microsoft.com/oldnewthing/20200311-00/?p=103553
102 template <typename T>
103 static constexpr bool alwaysFalseValue = false;
104
105 template <typename Random>
106 static uint64_t generateUInt64( Random & gen )
107 {
108 static_assert( Random::min() == std::numeric_limits<uint32_t>::min() );
109 if constexpr ( Random::max() == std::numeric_limits<uint32_t>::max() ) {
110 return static_cast<uint64_t>( gen() ) << 32 | static_cast<uint64_t>( gen() );
111 }
112 else if constexpr ( Random::max() == std::numeric_limits<uint64_t>::max() ) {
113 return gen();
114 }
115 else {
116 // Using alwaysFalseValue because static_assert( false ) is ill-formed in c++17
117 static_assert( alwaysFalseValue<Random>, "Unsupported random generator type" );
118 }
119 }
120
121 constexpr void advanceState()
122 {
123 _state = _state * multiplier + ( _increment | 1 );
124 }
125
126 uint64_t _state;
127 uint64_t _increment;
128 };
129
130 uint32_t uniformIntDistribution( const uint32_t from, const uint32_t to, PCG32 & gen );
131
132 // Fisher-Yates shuffle AKA Knuth shuffle, probably the same as std::shuffle.
133 // NOTE: we can't use std::shuffle here because it uses std::uniform_int_distribution which behaves differently on different platforms.
134 template <class Iter>
135 void shuffle( Iter first, Iter last, PCG32 & gen )
136 {
137 if ( first == last ) {
138 return;
139 }
140
141 assert( first < last );
142
143 // Change last from once-past-the-end to last element
144 --last;
145 const typename std::iterator_traits<Iter>::difference_type interval = last - first;
146
147 // Our implementation doesn't work for intervals bigger than 2**32 - 1
148 if constexpr ( sizeof( interval ) > sizeof( uint32_t ) ) {
149 assert( interval <= static_cast<typename std::iterator_traits<Iter>::difference_type>( std::numeric_limits<uint32_t>::max() ) );
150 }
151
152 uint32_t remainingSwaps = static_cast<uint32_t>( interval );
153 while ( remainingSwaps > 0 ) {
154 // Allow argument-dependant lookup (ADL) for swap: first try in the namespace of the type, then in the std namespace.
155 using std::swap;
156 const uint32_t index = uniformIntDistribution( 0, remainingSwaps, gen );
157 swap( *last, *( first + index ) );
158 --last;
159 --remainingSwaps;
160 }
161 }
162
163 PCG32 & CurrentThreadRandomDevice();
164
165 uint32_t Get( uint32_t from, uint32_t to = 0 );
166
167 template <typename T, std::enable_if_t<std::is_enum_v<T>, bool> = true>
168 T Get( const T from, const T to )
169 {
170 return static_cast<T>( Get( static_cast<uint32_t>( from ), static_cast<uint32_t>( to ) ) );
171 }
172
173 uint32_t GetWithSeed( uint32_t from, uint32_t to, uint32_t seed );
174
175 template <typename T, std::enable_if_t<std::is_enum_v<T>, bool> = true>
176 T GetWithSeed( const T from, const T to, const uint32_t seed )
177 {
178 return static_cast<T>( GetWithSeed( static_cast<uint32_t>( from ), static_cast<uint32_t>( to ), seed ) );
179 }
180
181 uint32_t GetWithGen( uint32_t from, uint32_t to, PCG32 & gen );
182
183 template <typename T>
184 void Shuffle( std::vector<T> & vec )
185 {
186 Rand::shuffle( vec.begin(), vec.end(), CurrentThreadRandomDevice() );
187 }
188
189 template <typename T>
190 void ShuffleWithGen( std::vector<T> & vec, PCG32 & gen )
191 {
192 Rand::shuffle( vec.begin(), vec.end(), gen );
193 }
194
195 template <typename T>
196 const T & Get( const std::vector<T> & vec )
197 {
198 assert( !vec.empty() );
199
200 const uint32_t id = Get( static_cast<uint32_t>( vec.size() - 1 ) );
201 return vec[id];
202 }
203
204 template <typename T>
205 const T & GetWithGen( const std::vector<T> & vec, PCG32 & gen )
206 {
207 assert( !vec.empty() );
208
209 const uint32_t id = GetWithGen( 0, static_cast<uint32_t>( vec.size() - 1 ), gen );
210 return vec[id];
211 }
212
213 template <typename T, size_t N>
214 const T & GetWithGen( const std::array<T, N> & arr, PCG32 & gen )
215 {
216 assert( N > 0 );
217
218 const uint32_t id = GetWithGen( 0, static_cast<uint32_t>( N - 1 ), gen );
219 return arr[id];
220 }
221
222 using ValueWeight = std::pair<int32_t, uint32_t>;
223
224 class Queue : private std::vector<ValueWeight>
225 {
226 public:
227 explicit Queue( uint32_t size = 0 )
228 {
229 reserve( size );
230 }
231
232 void Push( const int32_t value, const uint32_t weight )
233 {
234 if ( weight == 0 ) {
235 return;
236 }
237
238 emplace_back( value, weight );
239 }
240
241 size_t Size() const
242 {
243 return size();
244 }
245
246 int32_t Get() const
247 {
248 return Get( []( const uint32_t max ) { return Rand::Get( 0, max ); } );
249 }
250
251 int32_t GetWithSeed( const uint32_t seed ) const
252 {
253 return Get( [seed]( const uint32_t max ) { return Rand::GetWithSeed( 0, max, seed ); } );
254 }
255
256 private:
257 int32_t Get( const std::function<uint32_t( uint32_t )> & randomFunc ) const;
258 };
259
260 template <typename Seed, typename Value, std::enable_if_t<std::is_same_v<Seed, uint32_t> || std::is_same_v<Seed, uint64_t>, bool> = true>
261 void combineSeedWithValueHash( Seed & seed, const Value & v )
262 {
263 std::hash<Value> hasher;
264 seed ^= hasher( v ) + 0x9e3779b9 + ( seed << 6 ) + ( seed >> 2 );
265 }
266 }