The user wants Python code to generate realistic procedural terrain using Perlin noise. I need to write concise code, using the noise library. The plan is to generate a 2D heightmap with specific parameters like octaves and persistence, possibly visualizing it with matplotlib. To start, I’ll import numpy and the noise library, defining a function to create the heightmap. Additionally, I might classify heights into biomes for better visualization, though the user requested only the code.Planning terrain generation
It's important to annotate the code without relying on modules the user might not have. However, common libraries like numpy, matplotlib, and noise are easily installable via pip. I need to use the 'noise' package’s noise.pnoise2 for 2D Perlin noise and set up multiple octaves for a fractal Brownian motion effect. While considering domain warping for added realism is interesting, keeping it straightforward with multi-octave generation seems like a suitable way to achieve the "realistic" terrain the user wants.Providing terrain generation example
I need to provide an example script that uses Perlin noise to generate a heightmap and visualize it. I'll start with the essential imports: numpy, matplotlib, and the pnoise2 from the noise library.
The generate_terrain function will create the heightmap using parameters like scale, octaves, persistence, and lacunarity. After generating the height data, I’ll normalize it to a 0-1 range.
For visualization, I'll utilize matplotlib to display the 2D terrain with a color map. I should also consider adding a function to apply biome coloring, even if it involves looping through each pixel.Simplifying terrain coloring
I can use vectorization with masks for coloring based on heightmap values. For instance, I can create thresholds to categorize terrains: water for values under 0.4, sand between 0.4 and 0.45, and so on for grass, rock, and snow.
The user wants a well-commented Python script that generates heightmaps using Perlin noise and visualizes the colored terrain with minimal explanation. I think I'll include comments on how to install dependencies, but I'll keep the actual pip install commands out of the code and focus on creating the final script.Adding 3D visualization
I want to use a moderate map size of 256x256 to keep the terrain generation interactive. To enhance the visualization, I'll add a 3D view using Matplotlib’s 3D plotting capabilities.
This involves creating a meshgrid and plotting the surface of the terrain with the plot_surface function. While I recognize that 3D visualization can be resource-intensive, I think it's worth it for clarity's sake. Now I’ll focus on finalizing the answer. ```python
"""
Realistic procedural terrain in Python using Perlin noise.
import numpy as np
import matplotlib.pyplot as plt
from noise import pnoise2
---------- Heightmap generation ----------
def generate_heightmap(
width: int,
height: int,
scale: float = 100.0,
octaves: int = 6,
persistence: float = 0.5,
lacunarity: float = 2.0,
seed: int | None = None,
) -> np.ndarray:
"""
Generate a 2D heightmap using fractal Brownian motion with Perlin noise.
Returns a float32 array in [0, 1].
"""
if seed is None:
seed = np.random.randint(0, 10_000)
code
heightmap = np.zeros((height, width), dtype=np.float32)
# Avoid division by zero
if scale <= 0:
scale = 0.0001
for y in range(height):
for x in range(width):
# Scale coordinates to sample Perlin noise
nx = x / scale
ny = y / scale
# pnoise2 returns roughly in [-1, 1]
e = pnoise2(
nx,
ny,
octaves=octaves,
persistence=persistence,
lacunarity=lacunarity,
repeatx=1024, # for tileable terrain; adjust as desired
repeaty=1024,
base=seed,
)
heightmap[y, x] = e
# Normalize to [0, 1]
h_min, h_max = heightmap.min(), heightmap.max()
heightmap = (heightmap - h_min) / (h_max - h_min + 1e-8)
return heightmap
---------- Biome / color mapping (optional, for realism) ----------
def colorize_heightmap(heightmap: np.ndarray) -> np.ndarray:
"""
Map height values in [0, 1] to RGB colors for water, beach, grass, rock, snow.
Returns an (H, W, 3) float32 RGB image.
"""
h = heightmap
rgb = np.zeros((*h.shape, 3), dtype=np.float32)
code
# Simple thresholds; tweak for different styles
water_level = 0.40
beach_level = 0.45
grass_level = 0.65
rock_level = 0.85
water = h < water_level
beach = (h >= water_level) & (h < beach_level)
grass = (h >= beach_level) & (h < grass_level)
rock = (h >= grass_level) & (h < rock_level)
snow = h >= rock_level
# BGR colors are arbitrary, tweak as you like
rgb[water] = [0.0, 0.1, 0.4] # deep water
rgb[beach] = [0.9, 0.8, 0.6] # sand
rgb[grass] = [0.1, 0.6, 0.2] # grass
rgb[rock] = [0.5, 0.5, 0.5] # rock
rgb[snow] = [1.0, 1.0, 1.0] # snow
return rgb
---------- Example usage & visualization ----------