Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # b_perlin_noise_2D.py
- import random
- def perlin_noise_2D(x, y, num_octaves=1, persistence=0.5, lacunarity=2.0, seed=0):
- # Initialize the values for the first octave
- octave_x = x
- octave_y = y
- frequency = 1.0
- amplitude = 1.0
- noise = 0.0
- # Initialize the random number generator with the provided seed
- random.seed(seed)
- # Add together successively smaller, higher-frequency octaves of noise
- for i in range(num_octaves):
- # Generate a smooth noise value using the input coordinates
- noise += amplitude * smooth_noise_2D(octave_x, octave_y)
- # Increase the frequency and decrease the amplitude for the next octave
- frequency *= lacunarity
- amplitude *= persistence
- # Update the x and y coordinates for the next octave
- octave_x *= lacunarity
- octave_y *= lacunarity
- # Return the final noise value
- return noise
- def smooth_noise_2D(x, y):
- # Get the fractional part of the x and y coordinates
- frac_x = x - int(x)
- frac_y = y - int(y)
- # Wrap the integer coordinates to generate smooth noise across the borders
- x1 = (int(x) + random.randint(0, 10000)) % 10000
- y1 = (int(y) + random.randint(0, 10000)) % 10000
- x2 = (x1 + 1) % 10000
- y2 = (y1 + 1) % 10000
- # Calculate the interpolation weights
- sx = frac_x * frac_x * (3 - 2 * frac_x)
- sy = frac_y * frac_y * (3 - 2 * frac_y)
- # Interpolate the four neighboring noise values
- n1 = noise(x1, y1)
- n2 = noise(x2, y1)
- n3 = noise(x1, y2)
- n4 = noise(x2, y2)
- i1 = lerp(n1, n2, sx)
- i2 = lerp(n3, n4, sx)
- return lerp(i1, i2, sy)
- def noise(x, y):
- # Generate a random value at the given coordinates
- # You can use a different noise function here if desired
- return random.random()
- def lerp(a, b, t):
- # Linearly interpolate between two values
- return a + t * (b - a)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement