FastRandom.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using Microsoft.Xna.Framework;
  4. namespace MonoGame.Extended
  5. {
  6. /// <summary>
  7. /// Represents a pseudo-random number generator using a linear congruential generator algorithm.
  8. /// </summary>
  9. /// <remarks>
  10. /// <para>
  11. /// This implementation uses the same constants as Microsoft Visual C++ rand() function:
  12. ///
  13. /// a=214013
  14. /// c=2531011
  15. /// m=2^31
  16. /// </para>
  17. /// <para>
  18. /// It provides high performance and speed, but comes at the price of having lower statistical quality, or true
  19. /// 'randomness' compared to modern algorithms. The algorithm is deterministic based on the initial seed
  20. /// value, making it suitable for reproducible sequences.
  21. ///</para>
  22. ///<para>
  23. /// Note: This pseudo-random number generator exhibits noticeable patterns and should not be used for
  24. /// cryptographic purposes or when a high-quality random distribution is critical. Consider using
  25. /// <see cref="System.Random"/> for better statistical properties.
  26. /// </para>
  27. /// </remarks>
  28. public class FastRandom
  29. {
  30. private readonly IFastRandomImpl _impl;
  31. /// <summary>
  32. /// Provides a thread-safe <see cref="FastRandom"/> instance that may be used concurrently from any thread.
  33. /// </summary>
  34. public static FastRandom Shared { get; } = new FastRandom(new ThreadSafeFastRandomImpl());
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="FastRandom"/> class using the default seed value.
  37. /// </summary>
  38. public FastRandom() : this(1)
  39. {
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="FastRandom"/> class using the specified seed value.
  43. /// </summary>
  44. /// <param name="seed">A number used to calculate a starting value for the pseudo-random number sequence.</param>
  45. public FastRandom(int seed)
  46. {
  47. _impl = new LinearCongruentialGeneratorImpl(seed);
  48. }
  49. private FastRandom(IFastRandomImpl impl)
  50. {
  51. ArgumentNullException.ThrowIfNull(impl);
  52. _impl = impl;
  53. }
  54. /// <summary>
  55. /// Returns a non-negative random integer.
  56. /// </summary>
  57. /// <returns>A 32-bit signed integer that is greater than or equal to 0 and less than 32768.</returns>
  58. public int Next()
  59. {
  60. return _impl.Next();
  61. }
  62. /// <summary>
  63. /// Returns a non-negative random integer that is less than or equal to the specified maximum.
  64. /// </summary>
  65. /// <param name="max">The inclusive upper bound of the random number to be generated.</param>
  66. /// <returns>
  67. /// A 32-bit signed integer that is greater than or equal to 0 and less than or equal to <paramref name="max"/>.
  68. /// </returns>
  69. public int Next(int max)
  70. {
  71. return _impl.Next(max);
  72. }
  73. /// <summary>
  74. /// Returns a random integer that is within a specified range.
  75. /// </summary>
  76. /// <param name="min">The inclusive lower bound of the random number returned.</param>
  77. /// <param name="max">The inclusive upper bound of the random number returned.</param>
  78. /// <returns>
  79. /// A 32-bit signed integer that is greater than or equal to <paramref name="min"/> and less than or equal to
  80. /// <paramref name="max"/>.
  81. /// </returns>
  82. public int Next(int min, int max)
  83. {
  84. return _impl.Next(min, max);
  85. }
  86. /// <summary>
  87. /// Returns a random integer that is within a specified range.
  88. /// </summary>
  89. /// <param name="range">
  90. /// A range representing the inclusive lower and upper bound of the random number to return.
  91. /// </param>
  92. /// <returns>
  93. /// A 32-bit signed integer that is greater than or equal to the <see cref="Range{T}.Min"/> and less than or
  94. /// equal to the <see cref="Range{T}.Max"/> value of <paramref name="range"/>.
  95. /// </returns>
  96. [Obsolete("Use Next(Interval<int>). Range<T> will be removed in 6.0")]
  97. public int Next(Range<int> range)
  98. {
  99. return _impl.Next(range);
  100. }
  101. /// <summary>
  102. /// Returns a random integer that is within a closed interval.
  103. /// </summary>
  104. /// <param name="interval">
  105. /// A closed interval representing the lower and upper bounds of the random number to return.
  106. /// </param>
  107. /// <returns>
  108. /// A 32-bit signed integer that is greater than or equal to the <see cref="Interval{T}.Min"/> value and less
  109. /// than or equal to the <see cref="Interval{T}.Max"/> value of <paramref name="interval"/>.
  110. /// </returns>
  111. public int Next(Interval<int> interval)
  112. {
  113. return _impl.Next(interval);
  114. }
  115. /// <summary>
  116. /// Returns a random floating-point number that is greater than or equal to 0.0 and less than 1.0.
  117. /// </summary>
  118. /// <returns>
  119. /// A single-precision floating point number that is greater than or equal to 0.0 and less than 1.0.
  120. /// </returns>
  121. public float NextSingle()
  122. {
  123. return _impl.NextSingle();
  124. }
  125. /// <summary>
  126. /// Returns a random floating-point number that is greater than or equal to 0.0 and less than the
  127. /// specified maximum.
  128. /// </summary>
  129. /// <param name="max">The exclusive upper bond of the random number generated.</param>
  130. /// <returns>
  131. /// A single precision floating-point number that is greater than or equal to 0.0 and less than
  132. /// <paramref name="max"/>.
  133. /// </returns>
  134. public float NextSingle(float max)
  135. {
  136. return _impl.NextSingle(max);
  137. }
  138. /// <summary>
  139. /// Returns a random floating-point number that is within a specified range.
  140. /// </summary>
  141. /// <param name="min">The inclusive lower bound of the random number returned.</param>
  142. /// <param name="max">The exclusive upper bound of the random number returned.</param>
  143. /// <returns>
  144. /// A single-precision floating point number that is greater than or equal to <paramref name="min"/> and
  145. /// less than <paramref name="max"/>.
  146. /// </returns>
  147. public float NextSingle(float min, float max)
  148. {
  149. return _impl.NextSingle(min, max);
  150. }
  151. /// <summary>
  152. /// Returns a random floating-point number that is within a specified range.
  153. /// </summary>
  154. /// <param name="range">
  155. /// A range representing the inclusive lower and exclusive upper bound of the random number returned.
  156. /// </param>
  157. /// <returns>
  158. /// A single-precision floating point number that is greater than or equal to the <see cref="Range{T}.Min"/>
  159. /// and less than the <see cref="Range{T}.Max"/> value of <paramref name="range"/>
  160. /// </returns>
  161. [Obsolete("Use Next(Interval<float>). Range<T> will be removed in 6.0")]
  162. public float NextSingle(Range<float> range)
  163. {
  164. return _impl.NextSingle(range);
  165. }
  166. /// <summary>
  167. /// Returns a random floating-point number that is within a closed interval.
  168. /// </summary>
  169. /// <param name="interval">
  170. /// A closed interval representing the lower and upper bounds of the random number to return.
  171. /// </param>
  172. /// <returns>
  173. /// A single-precision floating point number that is greater than or equal to the <see cref="Interval{T}.Min"/>
  174. /// value and less than or equal to the <see cref="Interval{T}.Max"/> value of <paramref name="interval"/>.
  175. /// </returns>
  176. public float NextSingle(Interval<float> interval)
  177. {
  178. return _impl.NextSingle(interval);
  179. }
  180. /// <summary>
  181. /// Returns a random angle between -π and π.
  182. /// </summary>
  183. /// <returns>
  184. /// A random angle value in radians.
  185. /// </returns>
  186. public float NextAngle()
  187. {
  188. return _impl.NextAngle();
  189. }
  190. /// <summary>
  191. /// Gets a random unit vector.
  192. /// </summary>
  193. /// <param name="vector">When this method returns, contains a unit vector with a random direction.</param>
  194. public void NextUnitVector(out Vector2 vector)
  195. {
  196. _impl.NextUnitVector(out vector);
  197. }
  198. /// <summary>
  199. /// Gets a random unit vector.
  200. /// </summary>
  201. /// <param name="vector">A pointer to the Vector2 where the random unit vector will be stored.</param>
  202. public unsafe void NextUnitVector(Vector2* vector)
  203. {
  204. _impl.NextUnitVector(vector);
  205. }
  206. #region IFastRandomImplementation
  207. private interface IFastRandomImpl
  208. {
  209. int Next();
  210. int Next(int max);
  211. int Next(int min, int max);
  212. [Obsolete("Use Next(Interval<int>). Range<T> will be removed in 6.0")]
  213. int Next(Range<int> range);
  214. int Next(Interval<int> interval);
  215. float NextSingle();
  216. float NextSingle(float max);
  217. float NextSingle(float min, float max);
  218. [Obsolete("Use Next(Interval<float>). Range<T> will be removed in 6.0")]
  219. float NextSingle(Range<float> range);
  220. float NextSingle(Interval<float> interval);
  221. float NextAngle();
  222. void NextUnitVector(out Vector2 vector);
  223. unsafe void NextUnitVector(Vector2* vector);
  224. }
  225. #endregion
  226. #region Linear Congruential Generator
  227. private sealed class LinearCongruentialGeneratorImpl : IFastRandomImpl
  228. {
  229. private const int MULTIPLIER = 214013;
  230. private const int INCREMENT = 2531011;
  231. private int _state;
  232. public LinearCongruentialGeneratorImpl() : this(1)
  233. {
  234. }
  235. public LinearCongruentialGeneratorImpl(int seed)
  236. {
  237. ArgumentOutOfRangeException.ThrowIfNegativeOrZero(seed);
  238. _state = seed;
  239. }
  240. public int Next()
  241. {
  242. _state = MULTIPLIER * _state + INCREMENT;
  243. return (_state >> 16) & 0x7FFF;
  244. }
  245. public int Next(int max)
  246. {
  247. return (int)(max * NextSingle() + 0.5f);
  248. }
  249. public int Next(int min, int max)
  250. {
  251. return (int)((max - min) * NextSingle() + 0.5f) + min;
  252. }
  253. [Obsolete("Use Next(Interval<int>). Range<T> will be removed in 6.0")]
  254. public int Next(Range<int> range)
  255. {
  256. return Next(range.Min, range.Max);
  257. }
  258. public int Next(Interval<int> interval)
  259. {
  260. return Next(interval.Min, interval.Max);
  261. }
  262. public float NextSingle()
  263. {
  264. return Next() / (float)short.MaxValue;
  265. }
  266. public float NextSingle(float max)
  267. {
  268. return max * NextSingle();
  269. }
  270. public float NextSingle(float min, float max)
  271. {
  272. return (max - min) * NextSingle() + min;
  273. }
  274. [Obsolete("Use Next(Interval<float>). Range<T> will be removed in 6.0")]
  275. public float NextSingle(Range<float> range)
  276. {
  277. return NextSingle(range.Min, range.Max);
  278. }
  279. public float NextSingle(Interval<float> interval)
  280. {
  281. return NextSingle(interval.Min, interval.Max);
  282. }
  283. public float NextAngle()
  284. {
  285. return NextSingle(-MathHelper.Pi, MathHelper.Pi);
  286. }
  287. public void NextUnitVector(out Vector2 vector)
  288. {
  289. float angle = NextAngle();
  290. vector.X = MathF.Cos(angle);
  291. vector.Y = MathF.Sin(angle);
  292. }
  293. public unsafe void NextUnitVector(Vector2* vector)
  294. {
  295. float angle = NextAngle();
  296. vector->X = MathF.Cos(angle);
  297. vector->Y = MathF.Sin(angle);
  298. }
  299. }
  300. #endregion
  301. #region ThreadSafeImpl
  302. private sealed class ThreadSafeFastRandomImpl : IFastRandomImpl
  303. {
  304. [ThreadStatic]
  305. private static LinearCongruentialGeneratorImpl t_random;
  306. private static LinearCongruentialGeneratorImpl LocalRandom => t_random ?? Create();
  307. [MethodImpl(MethodImplOptions.NoInlining)]
  308. private static LinearCongruentialGeneratorImpl Create()
  309. {
  310. t_random = new LinearCongruentialGeneratorImpl();
  311. return t_random;
  312. }
  313. public int Next()
  314. {
  315. return LocalRandom.Next();
  316. }
  317. public int Next(int max)
  318. {
  319. return LocalRandom.Next(max);
  320. }
  321. public int Next(int min, int max)
  322. {
  323. return LocalRandom.Next(min, max);
  324. }
  325. [Obsolete("Use Next(Interval<int>). Range<T> will be removed in 6.0")]
  326. public int Next(Range<int> range)
  327. {
  328. return LocalRandom.Next(range.Min, range.Max);
  329. }
  330. public int Next(Interval<int> interval)
  331. {
  332. return LocalRandom.Next(interval.Min, interval.Max);
  333. }
  334. public float NextSingle()
  335. {
  336. return LocalRandom.NextSingle();
  337. }
  338. public float NextSingle(float max)
  339. {
  340. return LocalRandom.NextSingle(max);
  341. }
  342. public float NextSingle(float min, float max)
  343. {
  344. return LocalRandom.NextSingle(min, max);
  345. }
  346. [Obsolete("Use Next(Interval<float>). Range<T> will be removed in 6.0")]
  347. public float NextSingle(Range<float> range)
  348. {
  349. return LocalRandom.NextSingle(range.Min, range.Max);
  350. }
  351. public float NextSingle(Interval<float> interval)
  352. {
  353. return LocalRandom.NextSingle(interval.Min, interval.Max);
  354. }
  355. public float NextAngle()
  356. {
  357. return LocalRandom.NextAngle();
  358. }
  359. public void NextUnitVector(out Vector2 vector)
  360. {
  361. LocalRandom.NextUnitVector(out vector);
  362. }
  363. public unsafe void NextUnitVector(Vector2* vector)
  364. {
  365. LocalRandom.NextUnitVector(vector);
  366. }
  367. }
  368. #endregion
  369. }
  370. }