1package world 2 3import "math" 4 5type noise uint64 6 7func mix(h uint64) uint64 { 8 h ^= h >> 33 9 h *= 0xff51afd7ed558ccd 10 h ^= h >> 33 11 h *= 0xc4ceb9fe1a85ec53 12 return h ^ h>>33 13} 14 15func (n noise) hash(x, y int) uint64 { 16 return mix(uint64(n) ^ mix(uint64(x)*0x9e3779b97f4a7c15^uint64(y)*0xc2b2ae3d27d4eb4f)) 17} 18 19func (n noise) unit(x, y int) float64 { 20 return float64(n.hash(x, y)>>11)/(1<<52) - 1 21} 22 23func (n noise) grad(ix, iy int, x, y float64) float64 { 24 a := math.Pi * n.unit(ix, iy) 25 return math.Cos(a)*(x-float64(ix)) + math.Sin(a)*(y-float64(iy)) 26} 27 28func (n noise) at(x, y float64) float64 { 29 x0, y0 := math.Floor(x), math.Floor(y) 30 ix, iy := int(x0), int(y0) 31 sx, sy := fade(x-x0), fade(y-y0) 32 top := lerp(n.grad(ix, iy, x, y), n.grad(ix+1, iy, x, y), sx) 33 bottom := lerp(n.grad(ix, iy+1, x, y), n.grad(ix+1, iy+1, x, y), sx) 34 return lerp(top, bottom, sy) 35} 36 37func (n noise) fbm(x, y float64, octaves int) float64 { 38 sum, weight, total := 0.0, 1.0, 0.0 39 for i := range octaves { 40 sum += weight * noise(mix(uint64(n)+uint64(i))).at(x, y) 41 total += weight 42 weight /= 2 43 x, y = x*2, y*2 44 } 45 return sum / total 46} 47 48func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) } 49func lerp(a, b, t float64) float64 { return a + (b-a)*t }