So I’m slowly working on a new game. And by slowly, I mean very slowly. Considering I have duties to running AussieGamerHub, fixing the Wurm Online client, and a large amount of gaming to occupy my time, I get a varying amount of time each day to work on this. I’d rather not divulge the main idea for the game yet, but I am going to go into detail about some pretty simple terrain generation using Simplex Noise (the successor to Perlin Noise) for the simple reason that I had a hell of a time to get it going.
When you look up Simplex Noise on the intertubes, you will get a lot of links directing to the old Perlin Noise, and a lot more links directing to the pure mathematics of it and how it works. When you’re someone like me, and prefer to look at some code to see how it works, rather than foreign mathematical equations, it can be quite a time to get some working code. I think I managed to find about 2 websites in the past day or two that had some sort of code that I could use (and later on I was pointed to the second link on Google for Simplex Noise(pdf) which was a big help).
So anyway, lets get into it.
The basic premise of Perlin/Simplex noise is to generate white noise, then zoom in far enough and smooth out all the transitions between pixels until you get a nice smooth height-map. Combine this with a 2d game, and you have a nice map generator that never ends. If you really want to know how Simplex Noise works, you can read the pdf linked to above, or just do a google search on it and read one of the many papers explaining it. For this post I’m just going to give you some code and tell you how to use it to get what you want.
So here’s the basic SimplexNoise class ripped directly from the pdf (minus all the 3D/4D stuff):
I still don’t fully understand what all of the above code does, and I don’t mind that. It has been optimized to hell to make it as fast as possible, and that makes the readability a bit hard.
All you really have to do is seed the class using SimplexNoise.genGrad(long seed), and then generate your pixels using SimplexNoise.noise(double x, double y). This returns a double in the range of -1 to 1, which is normally used as the height of the pixel to create cool looking heightmaps for other games. When you assign it to a colour and print it out, you’re almost done.
Doing that will give you something that looks like white noise, which is good. From here we just up the resolution (zoom in), and we’re done.
The way to do that, is just divide your x and y by a resolution number that you want when you pass them to SimplexNoise.noise.
Playing around with the resolution gives you different output, such as the following examples at 64 res and 128 res:
And here is a video showing the run-on continuation of a generated map (512 res)