Skip to content
TheChatArchiveThe Chat Archive
ClaudeClaude Opus 4.5· anthropicHugging Face Frontier Reasoning Traces

Give Python code that generates realistic procedural terrain using Perlin noise.

  1. User

    Give Python code that generates realistic procedural terrain using Perlin noise.

  2. Claude Assistant

    The user is asking for Python code that generates realistic procedural terrain using Perlin noise. I'll create a comprehensive example that:

    1. Implements or uses Perlin noise (I'll use the noise library for simplicity, but also show how it can work)
    2. Uses multiple octaves (fractal Brownian motion) for more realistic terrain
    3. Visualizes the terrain both as a 2D heightmap and 3D surface
    4. Includes features like:
      • Multiple octaves for detail
      • Lacunarity and persistence controls
      • Color mapping based on elevation (water, sand, grass, rock, snow)
      • Optional erosion simulation

    Let me write a comprehensive solution:

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    
    # For Perlin noise, we can either implement it or use a library
    # I'll provide both options
    

    Let me create a full implementation that includes:

    1. A simple Perlin noise implementation (so it works without external dependencies)
    2. Fractal Brownian motion (fBm) for realistic terrain
    3. 2D and 3D visualization
    4. Terrain coloring based on height
    5. Optional: use the noise library if available for better performance

    This will be a comprehensive example that users can run and modify. # Procedural Terrain Generation with Perlin Noise

    Here's a comprehensive Python implementation that generates realistic terrain:

    Installation

    pip install numpy matplotlib noise
    

    Complete Implementation

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from matplotlib.colors import LinearSegmentedColormap
    from mpl_toolkits.mplot3d import Axes3D
    
    # Try to import the noise library, fall back to custom implementation
    try:
        from noise import pnoise2
        USE_LIBRARY = True
    except ImportError:
        USE_LIBRARY = False
        print("Using custom Perlin noise implementation")
    
    
    # ============================================
    # CUSTOM PERLIN NOISE IMPLEMENTATION
    # ============================================
    
    class PerlinNoise:
        """Custom Perlin noise implementation for when 'noise' library isn't available."""
        
        def __init__(self, seed=0):
            self.seed = seed
            np.random.seed(seed)
            # Permutation table
            self.perm = np.arange(256, dtype=int)
            np.random.shuffle(self.perm)
            self.perm = np.stack([self.perm, self.perm]).flatten()
            
            # Gradients for 2D
            self.gradients = np.array([
                [1, 1], [-1, 1], [1, -1], [-1, -1],
                [1, 0], [-1, 0], [0, 1], [0, -1]
            ], dtype=float)
        
        def _fade(self, t):
            """Smoothstep function: 6t^5 - 15t^4 + 10t^3"""
            return t * t * t * (t * (t * 6 - 15) + 10)
        
        def _lerp(self, a, b, t):
            """Linear interpolation"""
            return a + t * (b - a)
        
        def _grad(self, hash_val, x, y):
            """Calculate gradient dot product"""
            g = self.gradients[hash_val % 8]
            return g[0] * x + g[1] * y
        
        def noise2d(self, x, y):
            """Generate 2D Perlin noise value at (x, y)"""
            # Grid cell coordinates
            xi = int(np.floor(x)) & 255
            yi = int(np.floor(y)) & 255
            
            # Relative position within cell
            xf = x - np.floor(x)
            yf = y - np.floor(y)
            
            # Fade curves
            u = self._fade(xf)
            v = self._fade(yf)
            
            # Hash coordinates of corners
            aa = self.perm[self.perm[xi] + yi]
            ab = self.perm[self.perm[xi] + yi + 1]
            ba = self.perm[self.perm[xi + 1] + yi]
            bb = self.perm[self.perm[xi + 1] + yi + 1]
            
            # Gradient dot products at corners
            x1 = self._lerp(self._grad(aa, xf, yf), self._grad(ba, xf - 1, yf), u)
            x2 = self._lerp(self._grad(ab, xf, yf - 1), self._grad(bb, xf - 1, yf - 1), u)
            
            return self._lerp(x1, x2, v)
    
    
    # ============================================
    # TERRAIN GENERATOR CLASS
    # ============================================
    
    class TerrainGenerator:
        """
        Generates realistic procedural terrain using fractal Brownian motion (fBm)
        with Perlin noise as the base function.
        """
        
        def __init__(self, seed=42):
            self.seed = seed
            if not USE_LIBRARY:
                self.perlin = PerlinNoise(seed)
        
        def perlin_noise(self, x, y):
            """Get Perlin noise value at coordinates"""
            if USE_LIBRARY:
                return pnoise2(x, y, base=self.seed)
            else:
                return self.perlin.noise2d(x, y)
        
        def fbm(self, x, y, octaves=6, lacunarity=2.0, persistence=0.5):
            """
            Fractal Brownian Motion - combines multiple octaves of noise
            
            Parameters:
            -----------
            x, y : float
                Coordinates
            octaves : int
                Number of noise layers (more = more detail)
            lacunarity : float
                Frequency multiplier per octave (typically 2.0)
            persistence : float
                Amplitude multiplier per octave (typically 0.5)
            """
            value = 0.0
            amplitude = 1.0
            frequency = 1.0
            max_value = 0.0
            
            for _ in range(octaves):
                value += amplitude * self.perlin_noise(x * frequency, y * frequency)
                max_value += amplitude
                amplitude *= persistence
                frequency *= lacunarity
            
            return value / max_value  # Normalize to [-1, 1]
        
        def ridged_noise(self, x, y, octaves=6, lacunarity=2.0, persistence=0.5):
            """
            Ridged multifractal noise - creates mountain ridges and valleys
            """
            value = 0.0
            amplitude = 1.0
            frequency = 1.0
            max_value = 0.0
            
            for _ in range(octaves):
                noise_val = self.perlin_noise(x * frequency, y * frequency)
                noise_val = 1.0 - abs(noise_val)  # Create ridges
                noise_val = noise_val ** 2  # Sharpen ridges
                value += amplitude * noise_val
                max_value += amplitude
                amplitude *= persistence
                frequency *= lacunarity
            
            return value / max_value
        
        def generate_heightmap(self, width, height, scale=100.0, octaves=6,
                               lacunarity=2.0, persistence=0.5, offset_x=0, offset_y=0,
                               noise_type='fbm'):
            """
            Generate a 2D heightmap
            
            Parameters:
            -----------
            width, height : int
                Dimensions of the heightmap
            scale : float
                Zoom level (higher = more zoomed out)
            octaves : int
                Detail level
            lacunarity : float
                Frequency multiplier
            persistence : float
                Amplitude multiplier
            offset_x, offset_y : float
                Offset for exploring different areas
            noise_type : str
                'fbm' for standard terrain, 'ridged' for mountains
            """
            heightmap = np.zeros((height, width))
            
            noise_func = self.ridged_noise if noise_type == 'ridged' else self.fbm
            
            for y in range(height):
                for x in range(width):
                    nx = (x + offset_x) / scale
                    ny = (y + offset_y) / scale
                    heightmap[y][x] = noise_func(nx, ny, octaves, lacunarity, persistence)
            
            # Normalize to [0, 1]
            heightmap = (heightmap - heightmap.min()) / (heightmap.max() - heightmap.min())
            
            return heightmap
        
        def generate_terrain(self, width=256, height=256, scale=100.0):
            """
            Generate realistic terrain by combining multiple noise types
            """
            # Base terrain shape (large features)
            base = self.generate_heightmap(width, height, scale * 2, octaves=4,
                                           persistence=0.5, noise_type='fbm')
            
            # Mountain ridges
            ridges = self.generate_heightmap(width, height, scale, octaves=6,
                                             persistence=0.5, noise_type='ridged',
                                             offset_x=1000)
            
            # Fine detail
            detail = self.generate_heightmap(width, height, scale / 2, octaves=8,
                                             persistence=0.4, noise_type='fbm',
                                             offset_x=2000)
            
            # Combine layers
            terrain = base * 0.5 + ridges * 0.35 + detail * 0.15
            
            # Apply exponential redistribution for more realistic terrain
            terrain = np.power(terrain, 1.5)
            
            # Normalize
            terrain = (terrain - terrain.min()) / (terrain.max() - terrain.min())
            
            return terrain
    
    
    # ============================================
    # VISUALIZATION FUNCTIONS
    # ============================================
    
    def create_terrain_colormap():
        """Create a custom colormap for terrain visualization"""
        colors = [
            (0.0, (0.1, 0.3, 0.5)),    # Deep water
            (0.2, (0.2, 0.5, 0.7)),    # Shallow water
            (0.25, (0.9, 0.85, 0.6)),  # Beach/sand
            (0.3, (0.4, 0.7, 0.3)),    # Grass
            (0.5, (0.2, 0.5, 0.2)),    # Forest
            (0.7, (0.5, 0.4, 0.3)),    # Rock
            (0.85, (0.6, 0.6, 0.6)),   # Mountain
            (1.0, (1.0, 1.0, 1.0)),    # Snow
        ]
        
        positions = [c[0] for c in colors]
        rgb_colors = [c[1] for c in colors]
        
        cdict = {'red': [], 'green': [], 'blue': []}
        for pos, color in zip(positions, rgb_colors):
            cdict['red'].append((pos, color[0], color[0]))
            cdict['green'].append((pos, color[1], color[1]))
            cdict['blue'].append((pos, color[2], color[2]))
        
        return LinearSegmentedColormap('terrain_custom', cdict)
    
    
    def visualize_2d(heightmap, title="Terrain Heightmap"):
        """Display heightmap as 2D image with terrain colors"""
        fig, axes = plt.subplots(1, 2, figsize=(14, 6))
        
        # Grayscale heightmap
        axes[0].imshow(heightmap, cmap='gray')
        axes[0].set_title('Heightmap (Grayscale)')
        axes[0].axis('off')
        
        # Colored terrain
        terrain_cmap = create_terrain_colormap()
        axes[1].imshow(heightmap, cmap=terrain_cmap)
        axes[1].set_title('Terrain (Colored)')
        axes[1].axis('off')
        
        plt.suptitle(title, fontsize=14)
        plt.tight_layout()
        plt.show()
    
    
    def visualize_3d(heightmap, title="3D Terrain", vertical_scale=50):
        """Display heightmap as 3D surface"""
        fig = plt.figure(figsize=(14, 10))
        ax = fig.add_subplot(111, projection='3d')
        
        # Create coordinate grids
        height, width = heightmap.shape
        x = np.linspace(0, width, width)
        y = np.linspace(0, height, height)
        X, Y = np.meshgrid(x, y)
        Z = heightmap * vertical_scale
        
        # Create terrain colormap
        terrain_cmap = create_terrain_colormap()
        
        # Plot surface
        surf = ax.plot_surface(X, Y, Z, cmap=terrain_cmap, 
                               linewidth=0, antialiased=True,
                               rstride=2, cstride=2)
        
        ax.set_xlabel('X')
        ax.set_ylabel('Y')
        ax.set_zlabel('Elevation')
        ax.set_title(title)
        
        # Adjust viewing angle
        ax.view_init(elev=45, azim=45)
        
        plt.tight_layout()
        plt.show()
    
    
    def visualize_contour(heightmap, title="Contour Map"):
        """Display heightmap as contour map"""
        fig, ax = plt.subplots(figsize=(10, 8))
        
        terrain_cmap = create_terrain_colormap()
        
        # Filled contours
        contourf = ax.contourf(heightmap, levels=20, cmap=terrain_cmap)
        
        # Contour lines
        contour = ax.contour(heightmap, levels=20, colors='black', 
                             linewidths=0.3, alpha=0.5)
        
        plt.colorbar(contourf, ax=ax, label='Elevation')
        ax.set_title(title)
        ax.set_aspect('equal')
        
        plt.tight_layout()
        plt.show()
    
    
    # ============================================
    # MAIN DEMONSTRATION
    # ============================================
    
    def main():
        print("=" * 60)
        print("PROCEDURAL TERRAIN GENERATOR")
        print("=" * 60)
        
        # Initialize generator
        generator = TerrainGenerator(seed=42)
        
        # Generate different types of terrain
        print("\n1. Generating basic fBm terrain...")
        terrain_fbm = generator.generate_heightmap(
            width=256, height=256, 
            scale=80, octaves=6, 
            persistence=0.5, noise_type='fbm'
        )
        
        print("2. Generating ridged mountain terrain...")
        terrain_ridged = generator.generate_heightmap(
            width=256, height=256,
            scale=80, octaves=6,
            persistence=0.5, noise_type='ridged'
        )
        
        print("3. Generating combined realistic terrain...")
        terrain_combined = generator.generate_terrain(
            width=256, height=256, scale=80
        )
        
        # Visualizations
        print("\n4. Creating visualizations...")
        
        # 2D Views
        visualize_2d(terrain_fbm, "Basic fBm Terrain")
        visualize_2d(terrain_ridged, "Ridged Mountain Terrain")
        visualize_2d(terrain_combined, "Combined Realistic Terrain")
        
        # 3D View
        visualize_3d(terrain_combined, "3D Terrain View", vertical_scale=30)
        
        # Contour Map
        visualize_contour(terrain_combined, "Topographic Contour Map")
        
        print("\n" + "=" * 60)
        print("TERRAIN STATISTICS")
        print("=" * 60)
        print(f"Dimensions: {terrain_combined.shape}")
        print(f"Min elevation: {terrain_combined.min():.4f}")
        print(f"Max elevation: {terrain_combined.max():.4f}")
        print(f"Mean elevation: {terrain_combined.mean():.4f}")
        print(f"Std deviation: {terrain_combined.std():.4f}")
    
    
    if __name__ == "__main__":
        main()
    

    Quick Example (Minimal Code)

    import numpy as np
    import matplotlib.pyplot as plt
    from noise import pnoise2
    
    def generate_terrain(width, height, scale, octaves, seed=0):
        """Quick terrain generation function"""
        terrain = np.zeros((height, width))
        for y in range(height):
            for x in range(width):
                terrain[y][x] = pnoise2(x/scale, y/scale, 
                                         octaves=octaves, 
                                         persistence=0.5,
                                         lacunarity=2.0,
                                         base=seed)
        return terrain
    
    # Generate and display
    terrain = generate_terrain(256, 256, scale=50, octaves=6, seed=42)
    plt.imshow(terrain, cmap='terrain')
    plt.colorbar(label='Elevation')
    plt.title('Procedural Terrain')
    plt.show()
    

    Key Concepts Explained

    ParameterEffectTypical Value
    ScaleZoom level (higher = smoother)50-200
    OctavesDetail layers (more = finer detail)4-8
    PersistenceHow much each octave contributes0.4-0.6
    LacunarityFrequency increase per octave2.0

    Sample Output

    Fractal Brownian Motion (fBm):  Smooth, rolling hills
    Ridged Multifractal:            Sharp mountain ridges
    Combined Terrain:               Realistic varied landscape
    

    The code generates terrain like this:

    • Blue areas: Water (low elevation)
    • Yellow/Tan: Beaches and plains
    • Green: Grasslands and forests
    • Brown/Gray: Rocky mountains
    • White: Snow-capped peaks

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.