Code archives/Algorithms/Create a heightmap using the Diamond-Square algorithm

This code has been declared by its author to be Public Domain code.

Download source code

Create a heightmap using the Diamond-Square algorithm by Zethrax2015
*** Blitz3D code ***

This code uses the Diamond-Square algorithm to create a 2D array filled with heightmap values in the range 0.0 to 1.0. This array is then used to generate an image based on the heightmap.

You can either use the heightmap data itself for whatever purpose you have in mind, or use the generated image.

The heightmap is useful for terrain heightmaps and cloud textures - amongst many other things

The code also includes an option to create rougher/smoother heightmaps, examples for filtering the heightmap data, examples of blending foreground and background colors in the resulting image, code to save the resulting image, etc.

If you're clever you could probably modify the code to generate three dimensional data. Create a 3D array with a vertical dimension. Use the existing 2D code to generate a base layer of 2D data and then use a 3D version with an extra loop for the vertical layers that extends the square and diamond steps into 3D space within the array (grabbing and factoring-in additional point source data obtained from the previously generated layer). You can also add some filtering, overlay, etc options to generate data for various effects (ore pockets, etc).

Another thing you can do if you're using the tileable version of the code is to create an endless terrain that continally wraps back onto itself. This would be a bit tricky as you would potentially need up to four versions of the terrain tile (when the player is near a corner) along with copies of all the entities placed on the tiles. There may be ways of doing this in an optimized fashion though. Something to experiment with.

REFERENCES:-
http://en.wikipedia.org/wiki/Diamond-square_algorithm
http://www.playfuljs.com/realistic-terrain-in-130-lines/
http://www.gameprogrammer.com/fractal.html
http://srchea.com/terrain-generation-the-diamond-square-algorithm-and-three-js
https://danielbeard.wordpress.com/2010/08/07/terrain-generation-and-smoothing/


Code for the tileable version



Code for the non-tileable version
The code is at: http://www.blitzbasic.com/codearcs/codearcs.php?code=3172

Comments

Blitzplotter2015
This looks very intriguing, thanks Zethrax.


Code Archives Forum