Perlin Noise Terrain Generator
A Program to Generate Terrain from Perlin Noise with Exponentially Distributed Gradient Magnitude
 All Files Functions Variables Macros Pages
Macros | Functions | Variables
perlin.cpp File Reference

Code file for 2D Perlin noise with exponentially distributed gradients. More...

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

Macros

#define _USE_MATH_DEFINES
 Enable use of constant M_SQRT2 in math.h.
 
#define B   0x100
 Perlin's B, a power of 2 usually equal to 256.
 
#define BM   0xff
 A bit mask, one less than B.
 
#define N   0x1000
 Perlin's N.
 
#define lerp(t, a, b)   (a + t*(b - a))
 Linear interpolation.
 
#define s_curve(t)   (t*t*(3.0f - 2.0f*t))
 Cubic spline.
 
#define setup(i, b0, b1, r0, r1)
 Perlin's setup macro.
 
#define at2(rx, ry)   (rx*q[0] + ry*q[1])
 Perlin's dot product macro.
 

Functions

void normalize2 (float v[2])
 2D vector normalize.
 
void swap (int &x, int &y)
 Swap two integers.
 
float randomflt ()
 Get random floating point number.
 
void initPerlin2D ()
 Initialize Perlin noise.
 
float noise2 (float vec[2])
 COmpute one point of Perlin noise.
 
float PerlinNoise2D (const float x, const float y, const int n)
 Compute turbulence value.
 

Variables

const float FM_SQRT2 = (float)M_SQRT2
 Square root of 2 as a float.
 
float g_fMu
 Mu, the gradient magnitude exponent.
 

Macro Definition Documentation

#define setup (   i,
  b0,
  b1,
  r0,
  r1 
)
Value:
t = vec[i] + N;\
b0 = ((int)t) & BM;\
b1 = (b0+1) & BM;\
r0 = t - (int)t;\
r1 = r0 - 1.0f;

Function Documentation

void initPerlin2D ( )

Initialize gradient and permutation tables.

Initialize the permutation, gradient, and magnitude tables.

float noise2 ( float  vec[2])

Compute a single octave of noise at 2D noise at a single point. This is mostly taken from Perlin's original code, with a few tweaks.

Parameters
vecPoint at which to evaluate noise.
Returns
Noise value between -1.0 and 1.0.
void normalize2 ( float  v[2])

Works by side-effect on the parameter v.

Parameters
v2D vector as a 2-element array.
float PerlinNoise2D ( const float  x,
const float  y,
const int  n 
)

Generate a cell of 2D Perlin noise.

Turbulence is also known as 1/f noise.

Parameters
xX coordinate.
yY coordinate.
nNumber of octaves.
Returns
Noise value in the range -1 to 1.
float randomflt ( )

Get random floating point number between -1 and 1. Uses rand() to do the heavy lifting.

Returns
Pseudorandom floating point number between -1 and 1.
void swap ( int &  x,
int &  y 
)

Works by side-effect.

Parameters
xFirst value.
ySecond value.