SPB Git

Repository Public License

SeededRNG.swift 1.6 KB 44 lines swift

1// ORIX Arcade2// File: ArcadeCore/SeededRNG.swift3// Description: Deterministic SplitMix64 random generator with convenience helpers, for reproducible levels, terrain and traffic.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89nonisolated struct SeededRNG: RandomNumberGenerator, Sendable, Equatable {10    private(set) var state: UInt641112    init(seed: UInt64) { state = seed &+ 0x9E3779B97F4A7C15 }1314    mutating func next() -> UInt64 {15        state &+= 0x9E3779B97F4A7C1516        var z = state17        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B918        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB19        return z ^ (z >> 31)20    }2122    /// Uniform in [0, 1).23    mutating func unit() -> Double { Double(next() >> 11) / Double(1 << 53) }2425    mutating func double(in range: ClosedRange<Double>) -> Double {26        range.lowerBound + (range.upperBound - range.lowerBound) * unit()27    }2829    mutating func int(in range: ClosedRange<Int>) -> Int {30        let span = UInt64(range.upperBound - range.lowerBound + 1)31        return range.lowerBound + Int(next() % span)32    }3334    mutating func chance(_ probability: Double) -> Bool { unit() < probability }3536    mutating func pick<T>(_ items: [T]) -> T { items[int(in: 0...(items.count - 1))] }3738    /// Derives an independent stream, e.g. one per terrain chunk: `SeededRNG.derive(seed, chunkIndex)`.39    static func derive(_ seed: UInt64, _ stream: Int) -> SeededRNG {40        var mixer = SeededRNG(seed: seed ^ (UInt64(bitPattern: Int64(stream)) &* 0xD6E8FEB86659FD93))41        return SeededRNG(seed: mixer.next())42    }43}44
Files main
Menu

Theme