random

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 4 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package random provides deterministic, cross-platform pseudo-random streams, procedural noise generators, and helpers for verifying simulation determinism.

Each Stream implements Xoshiro256** seeded through SplitMix64 with fixed, specification-stable arithmetic, so a given seed produces the exact same sequence of bits, integers and floats on every Go version, operating system and architecture.

Noise provides deterministic 2D and 3D value and simplex noise, multi-octave fractals (FBM, ridged, billow, domain warping), and zero-allocation 2D grid-fill helpers using pure integer hashing and explicit IEEE-754 float64 arithmetic for bit-identical procedural generation across arm64, x86_64 and WebAssembly.

A game derives independent child streams by name with Fork or keeps them together in Streams, snapshots and restores generator state for saves and replays with State and SetState, and tests simulation repeatability with CompareRuns, CheckSteps and AssertDeterministic.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssertDeterministic

func AssertDeterministic[S any](t testing.TB, runs int, run func() S)

AssertDeterministic runs run runs times from scratch and fails t with both diverging states if any run produces a different result from the first.

func AssertDeterministicSteps

func AssertDeterministicSteps[S any](t testing.TB, steps int, makeSim func() func(step int) S, equal func(a, b S) bool)

AssertDeterministicSteps fails t if independent runs of makeSim diverge on any of the first steps steps, reporting the first divergent step and both states.

func CheckSteps

func CheckSteps[S any](steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)

CheckSteps creates a fresh simulation with makeSim and runs it for steps steps multiple times, returning the earliest 0-based step where two runs diverge along with both states. If equal is nil, reflect.DeepEqual is used.

When all runs match on every step (or steps <= 0), CheckSteps returns (-1, zero, zero, true).

Example

CheckSteps runs a simulation several times from scratch and reports the first step where two runs disagree, which finds hidden nondeterminism.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	makeSim := func() func(step int) int {
		s := random.New(5)
		pos := 0
		return func(int) int {
			pos += s.IntRange(-1, 1)
			return pos
		}
	}
	step, _, _, ok := random.CheckSteps(100, makeSim, nil)
	fmt.Println(step, ok)
}
Output:
-1 true

func CheckStepsRuns

func CheckStepsRuns[S any](runs, steps int, makeSim func() func(step int) S, equal func(a, b S) bool) (firstDivergentStep int, a, b S, ok bool)

CheckStepsRuns is like CheckSteps but executes runs independent runs from scratch (at least 2).

func Pick

func Pick[T any](s *Stream, items []T) T

Pick returns a uniformly chosen element of items. It panics if items is empty.

func Shuffle

func Shuffle[T any](s *Stream, items []T)

Shuffle randomly permutes items in place using the Fisher-Yates algorithm.

Example

Shuffle and Pick use a Stream, so a shuffled deck is reproducible from its seed.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	deck := []string{"A", "2", "3", "4", "5"}
	random.Shuffle(random.New(9), deck)
	again := []string{"A", "2", "3", "4", "5"}
	random.Shuffle(random.New(9), again)
	fmt.Println(deck, fmt.Sprint(deck) == fmt.Sprint(again))
}
Output:
[3 4 5 2 A] true

Types

type FractalConfig

type FractalConfig struct {
	// Octaves is the number of noise layers to combine (default 4).
	Octaves int
	// Frequency is the starting coordinate scale (default 1).
	Frequency float64
	// Lacunarity multiplies frequency on each subsequent octave (default 2).
	Lacunarity float64
	// Persistence multiplies amplitude on each subsequent octave (default 0.5).
	Persistence float64
	// Gain controls ridged multifractal weight feedback (default 2) and acts as
	// an amplitude-decay fallback for FBM/Billow when Persistence <= 0.
	Gain float64
}

FractalConfig configures multi-octave fractal noise evaluation. Zero or negative values fall back to sensible defaults: Octaves=4, Frequency=1, Lacunarity=2, Persistence=0.5 (or Gain when set for FBM/Billow), and Gain=2 for Ridged multifractal weighting.

func DefaultFractalConfig

func DefaultFractalConfig() FractalConfig

DefaultFractalConfig returns a FractalConfig populated with standard defaults suitable for terrain, clouds, and procedural textures.

type Mismatch

type Mismatch[S any] struct {
	// Run is the 0-based index of the run that diverged from run 0.
	Run int
	// First is the result produced by run 0.
	First S
	// Other is the result produced by the diverging run.
	Other S
}

Mismatch describes the first run whose result differed from the baseline run.

func CompareRuns

func CompareRuns[S any](runs int, run func() S, equal func(a, b S) bool) (Mismatch[S], bool)

CompareRuns executes run runs times from scratch and checks that every run equals the first. If equal is nil, reflect.DeepEqual is used. If runs < 2, CompareRuns runs twice.

It returns a zero Mismatch and true when all runs agree, or the first mismatch and false when a run diverges.

type Noise

type Noise struct {
	// contains filtered or unexported fields
}

Noise is a deterministic, cross-platform procedural noise generator seeded through SplitMix64.

All lookups use pure integer hashing and explicit IEEE-754 float64 arithmetic (without runtime transcendental functions or fused multiply-add contraction), producing bit-identical outputs across arm64, x86_64 and WebAssembly.

Construct a Noise instance with NewNoise. Once constructed, Noise is immutable and safe for concurrent use by multiple goroutines.

Example

Noise gives smooth coherent noise for terrain and textures, in the range [-1, 1] and the same for the same seed.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	n := random.NewNoise(1)
	cfg := random.DefaultFractalConfig()
	h := n.FBM2D(10.5, 3.25, cfg)
	fmt.Println(h >= -1 && h <= 1, h == random.NewNoise(1).FBM2D(10.5, 3.25, cfg))
	grid := make([]float64, 4*4)
	n.FillSimplex2D(grid, 4, 4, 0, 0, 0.1, 0.1)
	fmt.Println(len(grid))
}
Output:
true true
16

func NewNoise

func NewNoise(seed uint64) *Noise

NewNoise returns a deterministic Noise generator seeded with seed.

func (*Noise) Billow2D

func (n *Noise) Billow2D(x, y float64, cfg FractalConfig) float64

Billow2D evaluates normalized 2D billow fractal noise using Simplex2D, producing soft cloud-like lobes in [-1, 1].

func (*Noise) DomainWarp2D

func (n *Noise) DomainWarp2D(x, y, strength float64, cfg FractalConfig) (wx, wy float64)

DomainWarp2D displaces (x, y) by two decorrelated 2D FBM fields scaled by strength, returning the warped coordinates (wx, wy). Passing (wx, wy) to another noise method (or chaining multiple DomainWarp2D calls) creates organic swirls, marble and distorted terrain features.

func (*Noise) FBM2D

func (n *Noise) FBM2D(x, y float64, cfg FractalConfig) float64

FBM2D evaluates normalized 2D fractal Brownian motion using Simplex2D, returning a value in [-1, 1].

func (*Noise) FBM3D

func (n *Noise) FBM3D(x, y, z float64, cfg FractalConfig) float64

FBM3D evaluates normalized 3D fractal Brownian motion using Simplex3D, returning a value in [-1, 1].

func (*Noise) FillFBM2D

func (n *Noise) FillFBM2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, cfg FractalConfig)

FillFBM2D populates dst in row-major order with 2D FBM simplex noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.

func (*Noise) FillGrid2D

func (n *Noise) FillGrid2D(dst []float64, width, height int, originX, originY, stepX, stepY float64, sample func(x, y float64) float64)

FillGrid2D populates dst in row-major order (dst[gy*width+gx]) with samples produced by sample at coordinates (originX+gx*stepX, originY+gy*stepY).

It performs zero heap allocations. If width <= 0 or height <= 0, FillGrid2D is a no-op. It panics if sample is nil or len(dst) < width*height.

func (*Noise) FillSimplex2D

func (n *Noise) FillSimplex2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)

FillSimplex2D populates dst in row-major order with 2D simplex noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.

func (*Noise) FillValue2D

func (n *Noise) FillValue2D(dst []float64, width, height int, originX, originY, stepX, stepY float64)

FillValue2D populates dst in row-major order with 2D value noise samples at (originX+gx*stepX, originY+gy*stepY) without heap allocations.

func (*Noise) Fork

func (n *Noise) Fork(purpose string) *Noise

Fork derives an independent, deterministic child Noise generator for purpose (such as "elevation", "moisture" or "caves") from n's seed.

func (*Noise) Ridged2D

func (n *Noise) Ridged2D(x, y float64, cfg FractalConfig) float64

Ridged2D evaluates normalized 2D ridged multifractal noise using Simplex2D, returning a value in [0, 1] with sharp ridge crests near 1 and valleys near 0.

func (*Noise) Ridged3D

func (n *Noise) Ridged3D(x, y, z float64, cfg FractalConfig) float64

Ridged3D evaluates normalized 3D ridged multifractal noise using Simplex3D, returning a value in [0, 1] with sharp ridge crests near 1 and valleys near 0.

func (*Noise) Seed

func (n *Noise) Seed() uint64

Seed returns the seed that initialized n.

func (*Noise) Simplex2D

func (n *Noise) Simplex2D(x, y float64) float64

Simplex2D evaluates 2D simplex gradient noise at (x, y), returning a value in [-1, 1].

func (*Noise) Simplex3D

func (n *Noise) Simplex3D(x, y, z float64) float64

Simplex3D evaluates 3D simplex gradient noise at (x, y, z), returning a value in [-1, 1].

func (*Noise) Value2D

func (n *Noise) Value2D(x, y float64) float64

Value2D evaluates smooth 2D lattice value noise at (x, y), returning a value in [-1, 1].

func (*Noise) Value3D

func (n *Noise) Value3D(x, y, z float64) float64

Value3D evaluates smooth 3D lattice value noise at (x, y, z), returning a value in [-1, 1].

type State

type State struct {
	// Seed is the seed that initialized the stream.
	Seed uint64 `json:"seed"`
	// S is the internal 256-bit Xoshiro256** generator state.
	S [4]uint64 `json:"s"`
}

State is a JSON-marshalable snapshot of a Stream, suitable for save files and replays.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a deterministic pseudo-random number generator backed by Xoshiro256** seeded through SplitMix64.

Its output is identical across Go versions, operating systems and architectures. Its zero value behaves as New(0). A Stream is not safe for concurrent use by multiple goroutines; fork a separate stream for each independent consumer.

Example

A Stream gives the same sequence for the same seed on every platform, so a seeded level or replay comes out the same.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	a, b := random.New(42), random.New(42)
	fmt.Println(a.Intn(100) == b.Intn(100), a.Float64() == b.Float64())

	loot := random.New(7)
	rarity := []string{"common", "rare", "epic"}
	counts := map[string]int{}
	for range 1000 {
		counts[rarity[loot.WeightedIndex([]float64{80, 15, 5})]]++
	}
	fmt.Println(counts["common"] > counts["rare"], counts["rare"] > counts["epic"])

	st := loot.State()
	next := loot.Uint64()
	loot.SetState(st)
	fmt.Println(loot.Uint64() == next)
}
Output:
true true
true true
true

func New

func New(seed uint64) *Stream

New returns a new Stream seeded with seed.

func (*Stream) Bool

func (s *Stream) Bool() bool

Bool returns a uniformly distributed boolean.

func (*Stream) Chance

func (s *Stream) Chance(p float64) bool

Chance reports whether an event with probability p in [0, 1] occurs. It returns false when p <= 0 or p is NaN, and true when p >= 1.

func (*Stream) Float32

func (s *Stream) Float32() float32

Float32 returns a uniformly distributed float32 in [0, 1) with 24 bits of precision.

func (*Stream) Float64

func (s *Stream) Float64() float64

Float64 returns a uniformly distributed float64 in [0, 1) with 53 bits of precision.

func (*Stream) Fork

func (s *Stream) Fork(purpose string) *Stream

Fork derives an independent, deterministic child stream for purpose (such as "loot", "particles", "ai" or "level-1") from s's seed.

Fork does not advance s or perturb sibling streams, so forking names in any order always produces the same child streams.

func (*Stream) InCircle

func (s *Stream) InCircle(r float64) (x, y float64)

InCircle returns a point uniformly distributed inside the circle of radius r centered at the origin. It draws candidates from the enclosing square until one falls inside the unit circle and scales it by r, which spreads points uniformly over the area without the square-root radius and trigonometry of the polar form, whose math.Sin and math.Cos round differently across architectures. It panics if r < 0 or r is NaN.

func (*Stream) InRect

func (s *Stream) InRect(x, y, w, h float64) (px, py float64)

InRect returns a point uniformly distributed in [x, x+w) × [y, y+h). It panics if w or h is negative or any argument is NaN.

func (*Stream) IntRange

func (s *Stream) IntRange(min, max int) int

IntRange returns a uniformly distributed integer in [min, max], inclusive. It returns min when min == max and panics if min > max.

func (*Stream) Intn

func (s *Stream) Intn(n int) int

Intn returns a uniformly distributed integer in [0, n). It panics if n <= 0.

func (*Stream) Normal

func (s *Stream) Normal(mean, stddev float64) float64

Normal returns a normally distributed value with the given mean and standard deviation. It draws the sum of 12 uniform Float64 values, shifted to zero mean (an Irwin-Hall distribution, which matches the normal distribution's mean and variance), rather than a Box-Muller or ziggurat transform, because those need math.Log, math.Sin or math.Exp, whose standard library implementations round differently across architectures. The sum uses additions only and consumes a fixed 12 draws per call with no cached second value, so the output is bit-identical across architectures and fully captured by State and SetState. Values stay within ±6 standard deviations of the mean. It panics if stddev < 0 or either argument is NaN.

func (*Stream) OnCircle

func (s *Stream) OnCircle() (x, y float64)

OnCircle returns a uniformly distributed unit vector: a random direction. It draws a point inside the unit circle as InCircle does and divides it by its length, so the direction is uniform over the angle without trigonometry; only math.Sqrt and division are used, both correctly rounded by IEEE-754 on every architecture.

func (*Stream) Range

func (s *Stream) Range(min, max float64) float64

Range returns a uniformly distributed float64 in [min, max). It returns min when min == max and panics if min > max or either bound is NaN.

func (*Stream) Range32

func (s *Stream) Range32(min, max float32) float32

Range32 returns a uniformly distributed float32 in [min, max). It returns min when min == max and panics if min > max or either bound is NaN.

func (*Stream) Reset

func (s *Stream) Reset()

Reset rewinds s to the beginning of its seed's sequence.

func (*Stream) Seed

func (s *Stream) Seed() uint64

Seed returns the seed that initialized s.

func (*Stream) SetSeed

func (s *Stream) SetSeed(seed uint64)

SetSeed re-seeds s with seed and rewinds it to the beginning of seed's sequence.

func (*Stream) SetState

func (s *Stream) SetState(st State)

SetState restores s from a snapshot returned by State. If st.S is all zero, the generator state is re-derived from st.Seed.

func (*Stream) State

func (s *Stream) State() State

State returns a snapshot of s that can be serialized and passed to SetState to resume the exact same future sequence.

func (*Stream) Uint32

func (s *Stream) Uint32() uint32

Uint32 returns a uniformly distributed pseudo-random uint32 taken from the upper 32 bits of Uint64.

func (*Stream) Uint64

func (s *Stream) Uint64() uint64

Uint64 returns a uniformly distributed pseudo-random uint64.

func (*Stream) WeightedIndex

func (s *Stream) WeightedIndex(weights []float64) int

WeightedIndex returns an index into weights chosen with probability proportional to its weight. It returns -1 when weights is empty or every weight is 0, and never returns an index whose weight is 0.

It panics if any weight is negative, NaN or infinite, or if the sum overflows.

type Streams

type Streams struct {
	// contains filtered or unexported fields
}

Streams manages named child streams derived from a single master seed.

Each name always resolves to the same independent stream regardless of the order in which streams are requested or advanced.

Example

Streams derives an independent named stream per system from one master seed, so adding a draw in one system does not change another's results.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	world := random.NewStreams(1234)
	enemies, weather := world.Stream("enemies"), world.Stream("weather")
	first := weather.Uint32()

	again := random.NewStreams(1234)
	again.Stream("enemies").Uint64() // an extra draw in another system
	fmt.Println(again.Stream("weather").Uint32() == first, enemies.Seed() != weather.Seed())
}
Output:
true true

func NewStreams

func NewStreams(masterSeed uint64) *Streams

NewStreams returns a Streams manager rooted at masterSeed.

func (*Streams) Reset

func (m *Streams) Reset()

Reset rewinds the root stream and every stream already obtained from m back to its initial state.

func (*Streams) Restore

func (m *Streams) Restore(states map[string]State)

Restore restores m's streams from a snapshot returned by States. Streams present in states are created if not yet requested; existing streams missing from states are reset to their initial state.

func (*Streams) Seed

func (m *Streams) Seed() uint64

Seed returns the master seed.

func (*Streams) SetSeed

func (m *Streams) SetSeed(masterSeed uint64)

SetSeed re-seeds m with masterSeed and re-derives every named stream already obtained from m so existing references draw from the new master seed.

func (*Streams) States

func (m *Streams) States() map[string]State

States returns a JSON-marshalable snapshot of every stream currently held by m.

func (*Streams) Stream

func (m *Streams) Stream(name string) *Stream

Stream returns the named child stream, creating it on first use by forking from the master seed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL