Back to projects
Procedural Generation
Programmer2022· Solo

Procedural Generation

UnityC#Marching CubesShadersRuntime Mesh Manipulation

Overview

Procedural generation is a topic that has always fascinated me. This little project was an opportunity to dive into how procedural generation could be used to generate terrain and planets.

Hello World

The end result was a procedurally generated planet, complete with a water and atmosphere shader that interacts with the sun.

Hexapawn game board

Noise Map

The starting point was to generate a mesh with height displacement. The height was determined by layers and layers of noise to generate the details of the peaks and valleys. A simple height-based shader was used to add colour to the terrain.

Hexapawn game board

Marching Cubes

Height displacement wasn't enough though! I wanted caves and overhangs. This was achievable by an algorithm known as Marching Cubes. This allows us to populate a 3D array of cubes with shapes specified by coherent noise functions that define what's solid and what's not.

In addition to the layers of noise that define the large and small detail, we have additional parameters that define things like plateaus, so we get plat surfaces at specific elevations.

Hexapawn game board

Off By One

Next, I wanted to turn that flat shaded terrain into smooth shading. That required indexing the generated vertices so they could be reused when generating the triangles of the mesh.

The indexing is very specific. In this image, the index was off by one.

Hexapawn game board

Smooth Shading

With the vertices indexed properly, the final mesh could be generated with reused vertices along adjacent cubes that contained the triangles. This allows the normals to be averaged along edges, producing that smooth shaded look.

Hexapawn game board

Planets

The last part was to make the flat terrain spherical. This was very simple, as the marching cubes algorithm already generates a 3D volume containing a set of cubes. The main change was to reduce the weight of solid area as we get further away from a center point.