comparison semiconginev2/contrib/algorithms/noise.nim @ 1226:c8e3037aca66 compiletime-tests

add: contrib stuff
author sam <sam@basx.dev>
date Wed, 17 Jul 2024 23:41:51 +0700
parents
children
comparison
equal deleted inserted replaced
1225:27cd1c21290e 1226:c8e3037aca66
1 proc randomGradient(pos: Vec2f, seed: int32 = 0): Vec2f =
2 let randomAngle: float32 = TAU * (float32(int(hash((pos.x, pos.y, seed)))) / float32(high(int)))
3 return NewVec2f(cos(randomAngle), sin(randomAngle))
4
5 proc interpolate(a: float32, b: float32, weight: float32): float32 =
6 # with Smootherstep
7 (b - a) * ((weight * (weight * 6.0 - 15.0) + 10.0) * weight * weight * weight) + a;
8
9 proc Perlin*(pos: Vec2f, seed: int32 = 0): float32 =
10 let
11 # grid coordinates around target point
12 topleft = NewVec2f(trunc(pos.x), trunc(pos.y))
13 topright = topleft + NewVec2f(1, 0)
14 bottomleft = topleft + NewVec2f(0, 1)
15 bottomright = topleft + NewVec2f(1, 1)
16 # products for weights
17 topleft_dot = topleft.randomGradient(seed).Dot((pos - topleft))
18 topright_dot = topright.randomGradient(seed).Dot((pos - topright))
19 bottomleft_dot = bottomleft.randomGradient(seed).Dot((pos - bottomleft))
20 bottomright_dot = bottomright.randomGradient(seed).Dot((pos - bottomright))
21 xinterpol = pos.x - topleft.x
22 yinterpol = pos.y - topleft.y
23
24 return interpolate(
25 interpolate(topleft_dot, bottomleft_dot, yinterpol),
26 interpolate(topright_dot, bottomright_dot, yinterpol),
27 xinterpol
28 )