Skip to content

Instantly share code, notes, and snippets.

@s-l-teichmann
Created October 22, 2012 23:49
Show Gist options
  • Save s-l-teichmann/3935604 to your computer and use it in GitHub Desktop.
Save s-l-teichmann/3935604 to your computer and use it in GitHub Desktop.
Example using 3D Simplex noise
// Copyright 2012 by Sascha L. Teichmann. All rights reserved.
//
// Simple example how to use 3D Simplex noise.
// $ go get bitbucket.org/s_l_teichmann/simplexnoise
// $ go build tilegen3d.go
//
package main
import (
"bitbucket.org/s_l_teichmann/simplexnoise"
"bufio"
"flag"
"fmt"
"log"
"os"
)
func main() {
var (
seed int64
size int
xofs int
yofs int
zofs int
step float64
pt float64
pb float64
thresh float64
output string
)
flag.Int64Var(&seed, "seed", 1, "random seed")
flag.IntVar(&size, "size", 64, "tile size")
flag.IntVar(&xofs, "xofs", 0, "xofs")
flag.IntVar(&yofs, "yofs", 0, "yofs")
flag.IntVar(&zofs, "zofs", 0, "yofs")
flag.Float64Var(&pt, "pt", 1.0, "probalility top")
flag.Float64Var(&pb, "pb", 1.0, "probalility bottom")
flag.Float64Var(&thresh, "thresh", 1.0, "threshhold")
flag.Float64Var(&step, "step", 1.0/256.0, "step")
flag.StringVar(&output, "output", "", "file to store the tile")
flag.Parse()
sn := simplexnoise.NewSimplexNoise(seed)
x_start := float64(xofs*size) * step
y_start := float64(yofs*size) * step
z_start := float64(zofs*size) * step
// pt = 0*m + b <=> b = pt
// pb = (size-1)*m + pt
// m = (pb-pt)/(size-1)
b := float64(pt)
var m float64
if size == 1 {
m = 0
} else {
m = float64(pb-pt) / float64(size-1)
}
if output == "" {
output = fmt.Sprintf("%d-%d-%d.raw", xofs, yofs, zofs)
}
file, err := os.Create(output)
if err != nil {
log.Printf("Cannot open '%s'", output)
os.Exit(1)
}
defer file.Close()
buf := bufio.NewWriter(file)
z_pos := z_start
for z := 0; z < size; z++ {
y_pos := y_start
for y := 0; y < size; y++ {
yp := m*float64(y) + b
x_pos := x_start
for x := 0; x < size; x++ {
n := (sn.Noise3D(x_pos, y_pos, z_pos) + 1.0) * 0.5 * yp
if n < thresh {
n = 0.0
}
if err := buf.WriteByte(byte(n * 255.0)); err != nil {
log.Printf("Write to '%s' failed", output)
os.Exit(1)
}
x_pos += step
}
y_pos += step
}
z_pos += step
}
buf.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment