ds-heightmap

Use diamond-square algorithm to generate heightmaps.

Usage no npm install needed!

<script type="module">
  import dsHeightmap from 'https://cdn.skypack.dev/ds-heightmap';
</script>

README

ds-heightmap

Build Status npm version

Using diamond-square algorithm to generate heightmaps which stored in a 2D-array.

Demo

You can visit the online demo to try it out.

Install

npm install --save ds-heightmap

Usage

const ds = require('ds-heightmap');
ds.init(12, {
  corner: [1, 1, 5, 5], // determine the heights of four corners
  offset: -0.5,         // effect the overall height of the map
  range: 9,             // all the height values in the map will be within -range to range
  rough: 0.8            // effect the terrain variability (roughness)
});                     // pass factors
ds.run();               // generate a new heightmap base on the factors above
const data = ds.out();  // return a 2D-array of numbers

// Or call ds.gen() to do ds.run() and ds.out() together.

Or in another way:

const ds = require('ds-heightmap').ds;

const data = ds(12, {
  corner: [1, 1, 5, 5],
  offset: -0.5,
  range: 9,
  rough: 0.8
});        

Using ES6:

import heightmap, { ds } from 'ds-heightmap';

heightmap.init(9);
// or
const data = ds(7);

Or in Html:

<script src="/path/to/ds-heightmap.min.js"></script>

Render the map

Once you get the map data, you can render it into an image using an external image processing library. Here is an example with jimp:

const Jimp = require('jimp');

new Jimp(size, size, (err, image) => {
  if (err) throw err;

  data.forEach((d, x) => {
    d.forEach((v, y) => {
      image.setPixelColor(convertValueToColor(v), x, y);
    });
  });
  image.write('map.png', (err) => {
    if (err) throw err;
  });
});

API

init (power, option = {})

Init the library. Where power effects the size of the map (If power equals n, a map of 2n * 2n will be produced). For option, see below.

run ()

Manually call this function to do the diamond-square algorithm.

out () => array

Return the map data.

ds (power, option = {}) => array

Run init, run, out all together.

gen () => array

Run run, out all together.

options

Option Description Type Default
corner Determine the heights of four corners. They are initial values in diamond-square algorithm. Can be an array of four numbers or only one number which means all corners have the same height. Array, Number [1, 1, 1, 1]
offset Designed to effect the overall height of the map. Ranged from -0.9 to 0.9. Number -0.2
range All the height values in the map will be within -range to range. The min value is 1. Number 7
rough Designed to effect the terrain variability (roughness). Ranged from 0.1 to 0.9. Number 0.8