import math
import random
# Simple seedable random number generator to generate a random permutation table
def seeded_random(seed):
random.seed(seed)
permutation = list(range(256))
random.shuffle(permutation)
# Duplicate the permutation table for a total length of 512
return permutation + permutation
# Fade function as defined by Ken Perlin for the Perlin noise algorithm
def fade(t):
return 6 * t**5 - 15 * t**4 + 10 * t**3
# Linear interpolation (lerp)
def lerp(a, b, t):
return a + t * (b - a)
# Dot product for gradient vectors and distance vectors (2D)
def grad(hash_, x, y):
# Get the last 4 bits of the hash value to determine the gradient vector
h = hash_ & 0x03
if h == 0x00:
return x + y
elif h == 0x01:
return -x + y
elif h == 0x02:
return x - y
else:
return -x - y
# 2D Perlin noise function
def perlin_noise(x, y, seed, permutation_table=None):
if permutation_table is None:
permutation_table = seeded_random(seed)
# Calculate the integer coordinates of the (x, y) position
xi = int(x) & 0xff
yi = int(y) & 0xff
# Calculate the fractional coordinates of the (x, y) position
xf = x - int(x)
yf = y - int(y)
# Calculate the fade values for the fractional coordinates
u = fade(xf)
v = fade(yf)
# Calculate the hash values for the 4 corners of the unit square
aa = permutation_table[permutation_table[xi] + yi]
ab = permutation_table[permutation_table[xi] + yi + 1]
ba = permutation_table[permutation_table[xi + 1] + yi]
bb = permutation_table[permutation_table[xi + 1] + yi + 1]
# Calculate the gradient values for the 4 corners
x1 = grad(aa, xf, yf)
x2 = grad(ba, xf - 1, yf)
y1 = grad(ab, xf, yf - 1)
y2 = grad(bb, xf - 1, yf - 1)
# Linearly interpolate the gradient values
lerp_x1 = lerp(x1, x2, u)
lerp_x2 = lerp(y1, y2, u)
# Return the final interpolated value between the two lerp values
return lerp(lerp_x1, lerp_x2, v)
if __name__ == "__main__":
noise_seed = 0 # Change the seed value to get a different noise pattern
permutation_table = seeded_random(noise_seed)
x = 1
y = 2
print(perlin_noise(x, y, noise_seed, permutation_table))