Skip to content

Commit

Permalink
Add new Perlin struct and functions for 2D and 3D noise generation
Browse files Browse the repository at this point in the history
  • Loading branch information
ulises-jeremias committed Jan 6, 2024
1 parent 36558fe commit ec59ecb
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 2 deletions.
11 changes: 11 additions & 0 deletions noise/perlin2d.v
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@ module noise

import rand

// Perlin is a struct that hold the permutation set for perlin noise
pub struct Perlin {
mut:
perm []int = rand.shuffle_clone(permutations) or { panic(err) }
}

// new is a function that return a new Perlin struct
pub fn Perlin.new() Perlin {
return Perlin{}
}

// randomize is a function that shuffle the permutation set inside the Perlin struct
// will not shuffle if rand.seed is not changed
pub fn (mut perlin Perlin) randomize() {
Expand Down Expand Up @@ -38,10 +44,13 @@ pub fn (perlin Perlin) perlin2d(x f64, y f64) f64 {
return (lerp(x1, x2, v) + 1) / 2
}

// fade is a function that return a fade value for a given value
@[inline]
fn fade(t f64) f64 {
return t * t * t * (t * (t * 6.0 - 15.0) + 10.0)
}

// grad2d is a function that return a gradient value for a given hash and 2d position
fn grad2d(hash int, x f64, y f64) f64 {
match hash & 0xF {
0x0 { return x + y }
Expand All @@ -64,6 +73,8 @@ fn grad2d(hash int, x f64, y f64) f64 {
}
}

// lerp is a function that return a linear interpolation value for a given 2 values and a factor
@[inline]
fn lerp(a f64, b f64, x f64) f64 {
return a + x * (b - a)
}
3 changes: 2 additions & 1 deletion noise/perlin2d_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import vsl.float.float64

fn test_perlin2d() {
rand.seed([u32(3155200429), u32(3208395956)])
mut gen := Perlin{}

mut gen := Perlin.new()
gen.randomize()

result := gen.perlin2d(0.125, 0.125)
Expand Down
1 change: 1 addition & 0 deletions noise/perlin3d.v
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub fn (perlin Perlin) perlin3d(x f64, y f64, z f64) f64 {
return (lerp(y1, y2, w) + 1) / 2
}

// grad3d is a function that returns a single value of gradient noise for a given 3d position
fn grad3d(hash int, x f64, y f64, z f64) f64 {
match hash & 0xF {
0x0 { return x + y }
Expand Down
3 changes: 2 additions & 1 deletion noise/perlin3d_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import vsl.float.float64

fn test_perlin3d() {
rand.seed([u32(3155200429), u32(3208395956)])
mut gen := Perlin{}

mut gen := Perlin.new()
gen.randomize()

result := gen.perlin3d(0.125, 0.125, 0.125)
Expand Down

0 comments on commit ec59ecb

Please sign in to comment.