// SPDX-License-Identifier: MIT
// Derived from Rough.js 4.0.4, Copyright (c) 2019 Preet Shihn.

package rough

import (
	
	
)

const twoTo31 = 2147483648.0

// jsNumberStep materializes an intermediate JavaScript Number result. Go is
// otherwise allowed to fuse adjacent floating-point operations, while the
// JavaScript evaluation model rounds after each binary operation.
//
//go:noinline
func jsNumberStep( float64) float64 { return  }

type randomState struct {
	// Rough.js stores the constructor argument as a JavaScript number and only
	// applies Math.imul's ToInt32 coercion on the first deterministic draw.
	// Retaining the raw value matters for truthy seeds such as 0.5, 2^32, and
	// Infinity: their first draw is exactly zero, and only later draws fall
	// through to Math.random.
	seed float64
}

func newRandom( float64) *randomState {
	return &randomState{seed: }
}

func ( *randomState) () float64 {
	if .seed == 0 || math.IsNaN(.seed) {
		return rand.Float64()
	}
	 := int32(jsToInt32(.seed))
	 := int32(uint32() * uint32(48271))
	.seed = float64()
	return float64(uint32()&0x7fffffff) / twoTo31
}

func jsToInt32( float64) int64 {
	if  == 0 || math.IsNaN() || math.IsInf(, 0) {
		return 0
	}
	 := math.Trunc()
	 := math.Mod(, 4294967296)
	if  < 0 {
		 += 4294967296
	}
	if  >= 2147483648 {
		 -= 4294967296
	}
	return int64()
}

// NewSeed returns a nondeterministic seed in Rough.js's supported range.
func () float64 {
	return math.Floor(rand.Float64() * twoTo31)
}

func random( *ResolvedOptions) float64 {
	if .randomizer == nil {
		.randomizer = newRandom(.Seed)
	}
	return .randomizer.next()
}

func jsRound( float64) float64 {
	if math.IsNaN() || math.IsInf(, 0) ||  == 0 || math.Abs() >= 1<<52 {
		return 
	}
	if  >= -0.5 &&  < 0 {
		return math.Copysign(0, -1)
	}
	return math.Floor( + 0.5)
}