fractal terrain

fractal terrain

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
const turtle = new Turtle();
turtle.penup();
/////////////////////////////////////
const size = 512; // try 256 or 128
const water = 4; // 0 for no water
let randomLevel = 60;
let seed = (Math.random() * 100000) | 0;
/////////////////////////////////////
console.log("seed: " + seed);
function random () {
	seed = (seed * 16807) % 2147483647;
	return (seed - 1) / 2147483646;
}
const hmap = [];
for (let i = 0; i <= size; i++) hmap[i] = new Float32Array(size + 1);
const nbits = size.toString(2).length - 1;
const rnd = () => randomLevel * (-1 + 2 * random());
let t = 1;
let x = size / 2;
for (let s = 1; s <= nbits; s++) {
    for (let v = 0; v <= size; v += 2 * x) {
        for (let n = 1; n <= t; n += 2) {
            hmap[n * x][v] = ((hmap[(n - 1) * x][v] + hmap[(n + 1) * x][v]) / 2) + rnd();
            hmap[v][n * x] = ((hmap[v][(n - 1) * x] + hmap[v][(n + 1) * x]) / 2) + rnd();
        }
    }
    for (let n = 1; n <= t; n += 2) {
        for (let m = 1; m <= t; m += 2) {
            hmap[n * x][m * x] = (0.25 * (
                hmap[n * x + x][m * x] + 
                hmap[n * x - x][m * x] + 
                hmap[n * x][m * x + x] + 
                hmap[n * x][m * x - x])
            ) + rnd();
        }
    }
    t = 2 * t + 1;
    x /= 2;
    randomLevel /= 2;
}
for (let w = 0; w <= size; w++) {
    for (let z = 0; z <= size; z++) {
        if (hmap[w][z] < 0) hmap[w][z] = 0;
    }
}
const line = new Float32Array(size + 1);
const r = 200 / size;
let pen = false;
for (let w = 0; w <= size; w++) {
    let k = 0;
    pen = false;
    for (let z = 0; z <= size; z++) {
        let xe = r * z;
        let ye = r * 0.66 * w + hmap[z][w] * 1;
        if (ye <= line[z] || (hmap[z][w] === 0 && w / water !== ((w / water)|0))) {
            if (pen === true) {
                turtle.up();
                pen = false;
            }
        } else {
            if (pen === false) {
                pen = true;
            }
            turtle.goto(-100 + xe, 100 - ye);
            turtle.down();
            line[z] = ye;
        }
    }
    turtle.up();
}