Skip to content

Instantly share code, notes, and snippets.

@zhenjl
Created July 24, 2013 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhenjl/6074935 to your computer and use it in GitHub Desktop.
Save zhenjl/6074935 to your computer and use it in GitHub Desktop.
Generates 1d perlin noise in Go
/*
* Based on algorithm given at http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
*
* Borrowed heavily from https://github.com/iand/perlin/blob/master/perlin.go
*
* MIT License http://opensource.org/licenses/MIT
*/
package main
import (
"math"
"fmt"
)
func noise(x int64) float64 {
fn := (x << 13) ^ x
return (1.0 - float64((fn*(fn*fn*15731+789221)+1376312589)&0x7fffffff)/1073741824.0)
}
func smoothed_noise(x float64) float64 {
//return Noise(x)/2 + Noise(x-1)/4 + Noise(x+1)/4
xint := int64(math.Trunc(x));
return noise(xint)/2 + noise(xint-1)/4 + noise(xint+1)/4;
}
func interpolate(a, b, x float64) float64 {
/*
ft = x * 3.1415927
f = (1 - cos(ft)) * .5
return a*(1-f) + b*f
*/
ft := x * math.Pi
f := (1 - math.Cos(ft)) * 0.5
return a*(1-f) + b*f
}
func interpolate_noise(x float64) float64 {
/*
integer_X = int(x)
fractional_X = x - integer_X
v1 = SmoothedNoise1(integer_X)
v2 = SmoothedNoise1(integer_X + 1)
return Interpolate(v1 , v2 , fractional_X)
*/
xint := math.Trunc(x);
xfrac := x - xint;
v1 := smoothed_noise(xint)
v2 := smoothed_noise(xint+1)
return interpolate(v1, v2, xfrac);
}
func perlin_noise_1d(x float64) (value float64) {
/*
total = 0
p = persistence
n = Number_Of_Octaves - 1
loop i from 0 to n
frequency = 2i
amplitude = p^i
total = total + InterpolatedNoisei(x * frequency) * amplitude
end of i loop
return total
*/
var frequency float64 = 0.1;
var amplitude float64 = 1;
octaves := 6;
for i := 0; i < octaves; i++ {
value += interpolate_noise(x * frequency) * amplitude;
frequency *= 2;
amplitude /= 2;
}
return
}
// generate a json data structure of 360 data points
func main() {
fmt.Println("var noiseData = [");
for i := 0; i < 360; i++ {
p := perlin_noise_1d(float64(i))
fmt.Println("{x:",i,",y:",p,"},");
}
fmt.Println("];");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment