xxxxxxxxxx
83
// Marching Hexagons
// Author: Christian Manderla
// adaptation of Marching Cubes algorithm to an underlying grid of hexagons
// possible use: map generation for role playing games
// each corner of each hexagon is connected to a perlin noise value on a basis
// of their x/y-position
// those values are rounded to 0 or 1.
// corners associated to 1 are enclosed in dark areas.
// for animation a third offset in the noise space is incremented
// known weaknesses:
// * no interpolation
// * hex-grid must have the same number of cells in every line
// * ineffective due to redundancy. Most cornervalues are calculated 3 times
// due to beeing seen as e.g. south corner of 1 tile, northeast corner of 1 tile
// and northwest corner of a third tile
// Benefits over usual marching swuares
// * underlying hexgrid is wanted in some circumstances
// * slightly softer/more organic looking than marching squares
// Variables for customizing the result
// higher smooting leads to less but bigger structures
let smoothing = 60;
// speed of change
let speed = 0.01;
// "diameter" of the hexagons; less cellsize leads to more cells aka higher resolution
const cellsize = 20;
const nodes = [];
let cols;
let rows;
const xstep = cellsize;
const ystep = cellsize * (Math.sqrt(3) / 2);
let offset = 0;
function setup() {
createCanvas(800, 450);
cols = floor((width - cellsize/2) / cellsize);
rows = floor(height / ystep);
buildGrid(rows, cols);
}
function draw() {
background(100);
for (let n of nodes) {
n.show();
n.marchingHexes();
n.updateCornerValues();
}
offset += speed;
}
function buildGrid(rows, cols) {
let indent = false;
let x = xstep / 2;
let y = (ystep / 5) * 4;
for (let j = 0; j < rows; j++) {
for (let i = 0; i < cols; i++) {
nodes.push(new HexField(x, y, xstep / sqrt(3), nodes.length));
x += xstep;
}
y += ystep;
if (indent) {
x = xstep / 2;
} else {
x = xstep;
}
indent = !indent;
}
}