Advertisement
here2share

# b_perlin_noise_2D.py

Dec 27th, 2022
1,009
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. # b_perlin_noise_2D.py
  2.  
  3. import random
  4.  
  5. def perlin_noise_2D(x, y, num_octaves=1, persistence=0.5, lacunarity=2.0, seed=0):
  6.     # Initialize the values for the first octave
  7.     octave_x = x
  8.     octave_y = y
  9.     frequency = 1.0
  10.     amplitude = 1.0
  11.     noise = 0.0
  12.  
  13.     # Initialize the random number generator with the provided seed
  14.     random.seed(seed)
  15.  
  16.     # Add together successively smaller, higher-frequency octaves of noise
  17.     for i in range(num_octaves):
  18.         # Generate a smooth noise value using the input coordinates
  19.         noise += amplitude * smooth_noise_2D(octave_x, octave_y)
  20.  
  21.         # Increase the frequency and decrease the amplitude for the next octave
  22.         frequency *= lacunarity
  23.         amplitude *= persistence
  24.  
  25.         # Update the x and y coordinates for the next octave
  26.         octave_x *= lacunarity
  27.         octave_y *= lacunarity
  28.  
  29.     # Return the final noise value
  30.     return noise
  31.  
  32. def smooth_noise_2D(x, y):
  33.     # Get the fractional part of the x and y coordinates
  34.     frac_x = x - int(x)
  35.     frac_y = y - int(y)
  36.  
  37.     # Wrap the integer coordinates to generate smooth noise across the borders
  38.     x1 = (int(x) + random.randint(0, 10000)) % 10000
  39.     y1 = (int(y) + random.randint(0, 10000)) % 10000
  40.     x2 = (x1 + 1) % 10000
  41.     y2 = (y1 + 1) % 10000
  42.  
  43.     # Calculate the interpolation weights
  44.     sx = frac_x * frac_x * (3 - 2 * frac_x)
  45.     sy = frac_y * frac_y * (3 - 2 * frac_y)
  46.  
  47.     # Interpolate the four neighboring noise values
  48.     n1 = noise(x1, y1)
  49.     n2 = noise(x2, y1)
  50.     n3 = noise(x1, y2)
  51.     n4 = noise(x2, y2)
  52.     i1 = lerp(n1, n2, sx)
  53.     i2 = lerp(n3, n4, sx)
  54.     return lerp(i1, i2, sy)
  55.  
  56. def noise(x, y):
  57.     # Generate a random value at the given coordinates
  58.     # You can use a different noise function here if desired
  59.     return random.random()
  60.  
  61. def lerp(a, b, t):
  62.     # Linearly interpolate between two values
  63.     return a + t * (b - a)
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement