// TODO:
// fix buggy marching squares
// add compass

// const randomSeed = 'abcdef'
const randomSeed = 1 // min=1, max=10, step=0.01

class Vec2 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    rotate(angle) {
        return new Vec2(
            this.x * Math.cos(angle) - this.y * Math.sin(angle),
            this.x * Math.sin(angle) + this.y * Math.cos(angle)
        )
    }
    
    multn(n) {
        return new Vec2(this.x * n, this.y * n)
    }

    add(pt) {
        return new Vec2(this.x + pt.x, this.y + pt.y)
    }
    
    index(size) {
        return Math.floor(this.x) + Math.floor(this.y) * size
    }

    equals(pt) {
        return this.x === pt.x && this.y === pt.y
    }
    
    lerp(pt, fract) {
        return new Vec2(lerp(this.x, pt.x, fract), lerp(this.y, pt.y, fract))
    }
    
    distance(pt) {
        return Math.sqrt((this.x - pt.x) ** 2 + (this.y - pt.y) ** 2)
    }
    
    floor(pt) {
        return new Vec2(Math.floor(this.x), Math.floor(this.y))
    }

    addX(x) {
        return new Vec2(this.x + x, this.y)
    }

    addY(y) {
        return new Vec2(this.x, this.y + y)
    }    
}

// heightmap
const size = 192
const heights = [...Array(size * size)].map(i => 0)

Canvas.setpenopacity(1)
const turtle = new Turtle()

// render scale
const scale = 1

// drawing helpers

function transformPoint(pt, height) {
    return new Vec2((pt.x - size / 2) * scale, (pt.y - size / 2) * scale - height * 10)
}

function goto(pt, height) {
    const coord = transformPoint(pt, height)
    turtle.goto(coord.x, coord.y)
}

function line(a, aHeight, b, bHeight) {
    turtle.penup()
    goto(a, aHeight)
    turtle.pendown()
    goto(b, bHeight)
}

let patternedLineState = {
    segmentLength: 1,
    down: true,
    last: null,
    segmentCount: -1
}

const waterLinePattern = [[1, 2, 3], [5, 10, 3]]
const shorelineWavesLinePattern = [[4, 6, 8], [6, 8, 10]]
const shorelineLinePattern = [[12, 14, 16], [14, 16, 18]]

function drawPatternedLine(points, height, pattern) {
    if (points.length === 0) return

    patternedLineState = {
        segmentLength: 1,
        down: false,
        last: null,
        segmentCount: -1
    }

    turtle.penup()
    goto(points[0], getHeight(points[0]))
    points.forEach(pt => drawPatternedLineSegment(pt, height, pattern))
}

function drawPatternedLineSegment(pt, height, pattern) {
    let toPt = transformPoint(pt, height)
    if (!patternedLineState.last) {
        patternedLineState.last = toPt
    }

    const dist = toPt.distance(patternedLineState.last)
    let distLeft = dist
    let drawn = 0
    while (distLeft > patternedLineState.segmentLength) {
        distLeft -= patternedLineState.segmentLength
        drawn += patternedLineState.segmentLength
        const partwayPt = patternedLineState.last.lerp(toPt, drawn / dist)
        turtle.goto(partwayPt.x, partwayPt.y)
        patternedLineState.down = !patternedLineState.down
        if (patternedLineState.down) {
            turtle.pendown()
        }
        else {
            turtle.penup()
        }
        if (patternedLineState.segmentCount === -1 || patternedLineState.segmentCount > 0) {
            patternedLineState.segmentLength = randomFrom(pattern[patternedLineState.down ? 1 : 0])
            if (patternedLineState.segmentCount > 0) patternedLineState.segmentCount -= 1
        }
        if (patternedLineState.segmentCount === 0) {
            break
        }
    }
    turtle.goto(toPt.x, toPt.y)
    patternedLineState.segmentLength -= distLeft
    patternedLineState.last = toPt
}

// marching squares / isoline

function findIsolines(height) {
    const visited = {}
    const lines = []
    let x = 1, y = 1
    while (y < size) {
        let [pt, line] = march(x, y, visited, height)
        if (pt) {
            lines.push(line)
            x = pt.x
            y = pt.y
        }
        else {
            break
        }
        x += 1
        if (x >= size) {
            x = 1
            y += 1
        }
    }
    return lines
}

function march(x, y, visited, height) {
    let first
    let isOnBorder = false
    const line = []

    // find the starting point
    while (y < size) {
        const index = x + y * size
        if (heights[index] >= height && !visited[index]) {
            first = new Vec2(x, y)
            break
        }
        x += 1
        if (x >= size) {
            x = 1
            y += 1
        }
    }

    // if no starting point, return an empty line
    if (!first) {
        return [first, line]
    }

    let i = 0
    let pt = first
    let index = pt.index(size)
    visited[index] = true

    loop: while (i < 9999) {
        // we  have looped back to the beginning of the line
        if (line.length > 1 && pt.equals(first)) {
            break
        }

        index = pt.index(size)

        let isoPt
        switch(marchStep(pt, height)) {
            case 0: // up
                isoPt = new Vec2(
                    map(height, heights[index - size - 1], heights[index - size], pt.x - 1, pt.x),
                    pt.y - 1
                )
                pt = pt.addY(-1)
                break
            case 1: // right
                isoPt = new Vec2(
                    pt.x,
                    map(height, heights[index - size], heights[index], pt.y - 1, pt.y)
                )
                pt = pt.addX(1)
                break
            case 2: // down
                isoPt = new Vec2(
                    map(height, heights[index - 1], heights[index], pt.x - 1, pt.x),
                    pt.y
                )
                pt = pt.addY(1)
                break
            case 3: // left
                isoPt = new Vec2(
                    pt.x - 1,
                    map(height, heights[index - size - 1], heights[index - 1], pt.y - 1, pt.y)
                )
                pt = pt.addX(-1)
                break
            default:
                break loop
        }
        visited[pt.index(size)] = true
        line.push(isoPt)
        i++
    }
    return [first, line]
}

let savedState
function marchStep(pt, height) {
    const prevState = savedState
    const index = pt.index(size)
    const indexes = [index - size - 1, index - size, index - 1, index]
    const accums = indexes.map(i => heights[i] >= height)
    const state = accums.reduce((acc, curr, index) => acc + (curr ? (1 << index) : 0), 0)
    savedState = state
    switch (state) {
        case 1:
            return 0 // up
        case 2:
        case 3:
            return 1 // right
        case 4:
            return 3 // left
        case 5:
            return 0
        case 6:
            return prevState === 0 ? 3 : 1
        case 7:
            return 1
        case 8:
            return 2 // down
        case 9:
            return prevState === 1 ? 0 : 2
        case 10:
        case 11:
            return 2
        case 12:
            return 3
        case 13:
            return 0
        case 14:
            return 3
        default:
            return
    }
}

// land generation

function createLand() {
    buildLand()
    smoothLand()
    normalizeLand()
    emphasizeMountains()
}

function buildLand() {
    const halfSize = size / 2
    const allowedSize = halfSize * 0.85
	const center = new Vec2(halfSize, halfSize)
    const possibleMoves = [-0.5, 0, 0.5]
    const count = 2 ** 16
    let pt = new Vec2(size / 2, size / 2)
    for (let i = 0; i < count; i++) {
		heights[pt.index(size)] += 1
		pt = pt.add(new Vec2(randomFrom(possibleMoves), randomFrom(possibleMoves)))
        if (
            !isWithin(pt.x, center.x - allowedSize, center.x + allowedSize) ||
            !isWithin(pt.y, center.y - allowedSize, center.y + allowedSize)
        ) {
			pt = center.add(new Vec2(halfSize * (Random.random() - 0.5), halfSize * (Random.random() - 0.5)))
		}
	}
}

function smoothLand() {
    for (let i = 0; i < 10; i++) {
        for (let y = 1; y < size - 1; y++) {
            for (let x = 1; x < size - 1; x++) {
                const pt = new Vec2(x, y)
                const points = [
                    pt,
                    pt,
                    pt.addX(-1),
                    pt.addX(1),
                    pt.addY(-1),
                    pt.addY(1)
                ]
                heights[pt.index(size)] = avg(points.map(pt => getHeight(pt)))
            }
        }
    }
}

function normalizeLand() {
    const max = heights.reduce((acc, curr) => Math.max(acc, curr), 0)
    for (let i = 0; i < heights.length; i++) {
        heights[i] = heights[i] / max
    }
}

function emphasizeMountains() {
    for (let i = 0; i < heights.length; i++) {
        if (heights[i] > 0.6) {
            heights[i] *= map(Random.random(), 0, 1, 1, 1.35)
        }
    }
}

// helpers

function getHeight(pt) {
    return heights[pt.index(size)]
}

function avg(items) {
    return items.reduce((acc, curr) => acc + curr, 0) / items.length
}

function map(v, min, max, omin, omax) {
    return omin + (v - min) / (max - min) * (omax - omin)
}

function clamp(v, min, max) {
    return Math.max(Math.min(v, max), min)
}

function lerp(a, b, fract) {
    return a + (b - a) * fract
}

function randomFrom(arr) {
    return arr[Math.floor(Random.random() * arr.length)]
}

function isWithin(x, min, max) {
    return min <= x && x <= max
}

// main loop

function walk(i) {
    switch (i) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
            renderGrid(i)
            break
        case 5: 
            renderShoreline()
            break
        case 6:
            renderShorelineWaves()
            break
        case 7:
            return false
    }
    return true
}

// rendering

function renderGrid(i) {
    for (let y = 0; y < size; y++) {
        let drawingWater = false
        for (let x = 0; x < size; x++) {
            const ptA = new Vec2(x - 1, y)
            const ptB = new Vec2(x, y)
            const heightA = getHeight(ptA)
            const heightB = getHeight(ptB)
            
            switch (i) {
                case 0:
                    drawingWater = renderWater(ptB, heightB, drawingWater)
                    break
                case 1:
                    renderBeach(ptA, heightA, ptB, heightB)
                    break
                case 2:
                    renderHills(ptA, heightA, ptB, heightB)
                    break
                case 3:
                    renderTrees(ptA, heightA, ptB, heightB)
                    break
                case 4:
                    renderMountains(ptA, heightA, ptB, heightB)
                    break
            }
        }
    }
}

function renderWater(pt, height, drawingWater) {
    if (height < 0.001) {
        if (!drawingWater && Random.random() < 0.00125) {
            drawingWater = true
            turtle.penup()
            patternedLineState = {
                segmentLength: randomFrom(waterLinePattern[0]),
                segmentCount: 5,
                last: null,
                down: false
            }
        }
        if (drawingWater) {
            drawPatternedLineSegment(pt, 0, waterLinePattern)
            if (patternedLineState.segmentCount === 0) {
                drawingWater = false
            }
        }
    }
    else {
        drawingWater = false
    }
    return drawingWater
}

function renderBeach(ptA, heightA, ptB, heightB) {
    const min = 0.05
    const max = 0.1
    const isBeach = min <= heightB && heightA <= max || min <= heightA && heightB <= max
    if (!isBeach) return

    const sfract = clamp(map(min, heightA, heightB, 0, 1), 0, 1)
    const efract = clamp(map(max, heightA, heightB, 0, 1), 0, 1)
    const fract1 = lerp(sfract, efract, Random.random())
    const fract2 = fract1 + 0.2
    const saccum = map(fract1, 0, 1, heightA, heightB)
    const eaccum = map(fract2, 0, 1, heightA, heightB)
    const spt = ptA.lerp(ptB, fract1)
    const ept = ptA.lerp(ptB, fract2)
    line(spt, saccum, ept, eaccum)
}

function renderHills(ptA, heightA, ptB, heightB) {
    const min = 0.1
    const max = 0.25
    const isHills = heightA <= max && heightB >= min || heightA >= min && heightB <= max
    if (!isHills) return

    if (Random.random() < 0.75) {
        const sfract = clamp(map(min, heightA, heightB, 0, 1), 0, 1)
        const efract = clamp(map(max, heightA, heightB, 0, 1), 0, 1)
        const saccum = map(sfract, 0, 1, heightA, heightB)
        const eaccum = map(efract, 0, 1, heightA, heightB)
        const spt = ptA.lerp(ptB, sfract)
        const ept = ptA.lerp(ptB, efract)
        line(spt, saccum, ept, eaccum)
    }
}

function renderTrees(ptA, heightA, ptB, heightB) {
    const min = 0.25
    const max = 0.6
    const isTrees = heightA <= max && heightB >= min || heightA >= min && heightB <= max
    if (!isTrees) return

    const sfract = clamp(map(min, heightA, heightB, 0, 1), 0, 1)
    const efract = clamp(map(max, heightA, heightB, 0, 1), 0, 1)

    // Don't draw trees if there is a mountain down from us
    const ptDown = ptB.addY(1)
    const heightDown = getHeight(ptDown)
    if (heightDown > 0.6) return

    const treeCount = map(Math.abs(0.5 - heightA), 0, 0.2, 5, 1)
    for (let i = 0; i < treeCount; i++) {
        const fract = lerp(sfract, efract, Random.random())
        const accum = map(fract, 0, 1, heightA, heightB)
        const offs = new Vec2(Random.random() - 0.5, Random.random() - 0.5).multn(2)
        const pt = ptA.lerp(ptB, fract).add(offs)
        const treeHeight = 0.125 * Random.random()
        line(pt, accum, pt, accum + treeHeight)
    }
}

function renderMountains(ptA, heightA, ptB, heightB) {
    const min = 0.6
    const isMountain = heightA >= min || heightB >= min
    if (!isMountain) return

    if (Random.random() < 0.5) {
        const leftPt = ptB.addX(-1)
        const leftHeight = getHeight(leftPt)
        const rightPt = ptB.addX(1)
        const rightHeight = getHeight(rightPt)
        
        if (leftHeight < heightB && rightHeight < heightB) {
            line(leftPt, leftHeight, ptB, heightB)
            line(ptB, heightB, rightPt, rightHeight)
        }
    }
}

function renderShoreline() {
    const lines = findIsolines(0.05)
    lines.forEach(line => drawPatternedLine(line, 0.05, shorelineLinePattern))
}

function renderShorelineWaves() {
    const lines = findIsolines(0.03)
    lines.forEach(line => drawPatternedLine(line, 0.03, shorelineWavesLinePattern))
}

const lib = {}
;(function(lib) {
    /*
  I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  so it's better encapsulated. Now you can have multiple random number generators
  and they won't stomp all over eachother's state.
  
  If you want to use this as a substitute for Math.random(), use the random()
  method like so:
  
  var m = new MersenneTwister();
  var randomNumber = m.random();
  
  You can also call the other genrand_{foo}() methods on the instance.
  If you want to use a specific seed in order to get a repeatable random
  sequence, pass an integer into the constructor:
  var m = new MersenneTwister(123);
  and that will always produce the same random sequence.
  Sean McCullough (banksean@gmail.com)
*/

/* 
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.
 
   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).
 
   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          
 
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
 
     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
 
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
 
     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.
 
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

var MersenneTwister = function(seed) {
  if (seed == undefined) {
    seed = new Date().getTime();
  } 
  /* Period parameters */  
  this.N = 624;
  this.M = 397;
  this.MATRIX_A = 0x9908b0df;   /* constant vector a */
  this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
 
  this.mt = new Array(this.N); /* the array for the state vector */
  this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */

  this.init_genrand(seed);
}  
 
/* initializes mt[N] with a seed */
MersenneTwister.prototype.init_genrand = function(s) {
  this.mt[0] = s >>> 0;
  for (this.mti=1; this.mti<this.N; this.mti++) {
      var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
   this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  + this.mti;
      /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
      /* In the previous versions, MSBs of the seed affect   */
      /* only MSBs of the array mt[].                        */
      /* 2002/01/09 modified by Makoto Matsumoto             */
      this.mt[this.mti] >>>= 0;
      /* for >32 bit machines */
  }
}
 
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  var i, j, k;
  this.init_genrand(19650218);
  i=1; j=0;
  k = (this.N>key_length ? this.N : key_length);
  for (; k; k--) {
    var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
    this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
      + init_key[j] + j; /* non linear */
    this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
    i++; j++;
    if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
    if (j>=key_length) j=0;
  }
  for (k=this.N-1; k; k--) {
    var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
    this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
      - i; /* non linear */
    this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
    i++;
    if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  }

  this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ 
}
 
/* generates a random number on [0,0xffffffff]-interval */
MersenneTwister.prototype.genrand_int32 = function() {
  var y;
  var mag01 = new Array(0x0, this.MATRIX_A);
  /* mag01[x] = x * MATRIX_A  for x=0,1 */

  if (this.mti >= this.N) { /* generate N words at one time */
    var kk;

    if (this.mti == this.N+1)   /* if init_genrand() has not been called, */
      this.init_genrand(5489); /* a default initial seed is used */

    for (kk=0;kk<this.N-this.M;kk++) {
      y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
      this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
    }
    for (;kk<this.N-1;kk++) {
      y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
      this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
    }
    y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
    this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];

    this.mti = 0;
  }

  y = this.mt[this.mti++];

  /* Tempering */
  y ^= (y >>> 11);
  y ^= (y << 7) & 0x9d2c5680;
  y ^= (y << 15) & 0xefc60000;
  y ^= (y >>> 18);

  return y >>> 0;
}
 
/* generates a random number on [0,0x7fffffff]-interval */
MersenneTwister.prototype.genrand_int31 = function() {
  return (this.genrand_int32()>>>1);
}
 
/* generates a random number on [0,1]-real-interval */
MersenneTwister.prototype.genrand_real1 = function() {
  return this.genrand_int32()*(1.0/4294967295.0); 
  /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
MersenneTwister.prototype.random = function() {
  return this.genrand_int32()*(1.0/4294967296.0); 
  /* divided by 2^32 */
}
 
/* generates a random number on (0,1)-real-interval */
MersenneTwister.prototype.genrand_real3 = function() {
  return (this.genrand_int32() + 0.5)*(1.0/4294967296.0); 
  /* divided by 2^32 */
}
 
/* generates a random number on [0,1) with 53-bit resolution*/
MersenneTwister.prototype.genrand_res53 = function() { 
  var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6; 
  return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 

lib.MersenneTwister = MersenneTwister

/* These real versions are due to Isaku Wada, 2002/01/09 added */
})(lib)
const { MersenneTwister } = lib

const Random = new MersenneTwister(randomSeed)
createLand()