From 51bddd4a0ff00fce883583852a2d225d5b41117c Mon Sep 17 00:00:00 2001 From: ekrctb Date: Mon, 30 Nov 2020 18:46:28 +0900 Subject: [PATCH] Rename functions, and add NextInt. --- osu.Game/Utils/StatelessRNG.cs | 42 +++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/osu.Game/Utils/StatelessRNG.cs b/osu.Game/Utils/StatelessRNG.cs index d78d55cc09..d316f718e3 100644 --- a/osu.Game/Utils/StatelessRNG.cs +++ b/osu.Game/Utils/StatelessRNG.cs @@ -1,6 +1,8 @@ // Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. +using System; + namespace osu.Game.Utils { /// @@ -22,7 +24,7 @@ private static ulong mix(ulong x) } /// - /// Compute an integer from given seed and series number. + /// Generate a random 64-bit unsigned integer from given seed. /// /// /// The seed value of this random number generator. @@ -31,11 +33,39 @@ private static ulong mix(ulong x) /// The series number. /// Different values are computed for the same seed in different series. /// - public static ulong Get(int seed, int series = 0) => - unchecked(mix(((ulong)(uint)series << 32) | ((uint)seed ^ 0x12345678))); + public static ulong NextUlong(int seed, int series = 0) + { + unchecked + { + // + var combined = ((ulong)(uint)series << 32) | (uint)seed; + // The xor operation is to not map (0, 0) to 0. + return mix(combined ^ 0x12345678); + } + } /// - /// Compute a floating point value between 0 and 1 (excluding 1) from given seed and series number. + /// Generate a random integer in range [0, maxValue) from given seed. + /// + /// + /// The number of possible results. + /// + /// + /// The seed value of this random number generator. + /// + /// + /// The series number. + /// Different values are computed for the same seed in different series. + /// + public static int NextInt(int maxValue, int seed, int series = 0) + { + if (maxValue <= 0) throw new ArgumentOutOfRangeException(nameof(maxValue)); + + return (int)(NextUlong(seed, series) % (ulong)maxValue); + } + + /// + /// Compute a random floating point value between 0 and 1 (excluding 1) from given seed and series number. /// /// /// The seed value of this random number generator. @@ -44,7 +74,7 @@ public static ulong Get(int seed, int series = 0) => /// The series number. /// Different values are computed for the same seed in different series. /// - public static float GetSingle(int seed, int series = 0) => - (float)(Get(seed, series) & ((1 << 24) - 1)) / (1 << 24); // float has 24-bit precision + public static float NextSingle(int seed, int series = 0) => + (float)(NextUlong(seed, series) & ((1 << 24) - 1)) / (1 << 24); // float has 24-bit precision } }