Simplex Port ⛴️

A port of skypack.dev/view/simplex-noise to make 2D, 3D and 4D simplex available in Turtletoy.

In this turtle I demonstrate the use of a 4D simplex noise to create tileable (toroidal) noise pattern that fluently repeats itself. This is discussed in detail at ronvalstar.nl/creating-tileable-noise-maps

Log in to post a comment.

const shadesOfGrey = 10; //min=2 max=15 step=1 Fewer shades equals faster drawing
const tileSize = 50; //min=10 max=200 step=10 The width and height of tiles
const noiseZoom = 2; //min=0 max=10 step=.1 The multiplier to the coordinates used to probe the noise field
const pixelSize = 1; //min=.3 max=5 step=.1 Bigger pixels makes drawing faster

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

// Global code will be evaluated once.
init();
const bales = Bales(shadesOfGrey);

const noise = new SquareTiledSimplex2D(Simplex().createNoise4D(), tileSize, noiseZoom);

// The walk function will be called until it returns false.
function walk(i) {
    const x = (i % Math.ceil(200/pixelSize)) * pixelSize - (100 - pixelSize / 2);
    const y = (i / Math.ceil(200/pixelSize) | 0) * pixelSize - (100 - pixelSize / 2);

    const lumination = (1+noise.sample(x,y))/2;

    drawPixel(bales[lumination*shadesOfGrey | 0], [x, y], 1, .15, pixelSize);
    return i < Math.ceil(200/pixelSize)**2-1;
}


function drawPixel(turtle, location, hatchDirection=0, hatchDistance=1, size=10) {
    const vertices = [[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]].map(pt => V.add(location, V.scale(pt, size)));

    const rot = V.rot2d(hatchDirection);
    const invRot = V.rot2d(-hatchDirection);
    
    const [from, to] = [
        vertices.map(pt => V.trans(invRot, pt))
                .reduce((a, c) => [Math.min(a[0], c[1]), Math.max(a[1], c[1])], [Number.MAX_SAFE_INTEGER, Number.MIN_SAFE_INTEGER])
    ].map(yMinMax => [Math.floor(yMinMax[0]/hatchDistance), Math.ceil(yMinMax[1]/hatchDistance)]).pop().map(v => v * hatchDistance);
    
    for(let y = from; y <= to; y += hatchDistance) {
        const line = [[-100*Math.SQRT2, y], [100*Math.SQRT2, y]].map(pt => V.trans(rot, pt));
        const is = vertices.map((e,i,a) => Intersection.segment(...line, e, a[(i+1)%a.length])).filter(v => v);
        if(is.length == 2) {
            PT.draw(turtle, is);
        }
    }
}

function SquareTiledSimplex2D(noise4D, tileSize = 200, noiseZoom = 1) {
    class SquareTiledSimplex2D {
        constructor(noise4D, tileSize, noiseZoom) {
            this.noise4D = noise4D;
            this.tileSize = tileSize;
            this.noiseZoom = noiseZoom
        }
        sample(x, y) {
            const alpha = Math.PI * 2 / 200 * (200 / this.tileSize) * x;
            const beta = Math.PI * 2 / 200 * (200 / this.tileSize) * y;
    
            return this.noise4D(
                Math.cos(alpha) * this.noiseZoom,
                Math.sin(alpha) * this.noiseZoom,
                Math.cos(beta) * this.noiseZoom,
                Math.sin(beta) * this.noiseZoom
            );
        }
    }
    return new SquareTiledSimplex2D(noise4D, tileSize, noiseZoom);
}

// Ported https://www.skypack.dev/view/simplex-noise
function Simplex() {
    const F2 = 0.5 * (Math.sqrt(3) - 1);
    const G2 = (3 - Math.sqrt(3)) / 6;
    const F3 = 1 / 3;
    const G3 = 1 / 6;
    const F4 = (Math.sqrt(5) - 1) / 4;
    const G4 = (5 - Math.sqrt(5)) / 20;
    const fastFloor = (x) => Math.floor(x) | 0;
    const grad2 = /* @__PURE__ */ new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]);
    const grad3 = /* @__PURE__ */ new Float64Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]);
    const grad4 = /* @__PURE__ */ new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);
    function createNoise2D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad2x = new Float64Array(perm).map((v) => grad2[v % 12 * 2]);
      const permGrad2y = new Float64Array(perm).map((v) => grad2[v % 12 * 2 + 1]);
      return function noise2D(x, y) {
        let n0 = 0;
        let n1 = 0;
        let n2 = 0;
        const s = (x + y) * F2;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const t = (i + j) * G2;
        const X0 = i - t;
        const Y0 = j - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        let i1, j1;
        if (x0 > y0) {
          i1 = 1;
          j1 = 0;
        } else {
          i1 = 0;
          j1 = 1;
        }
        const x1 = x0 - i1 + G2;
        const y1 = y0 - j1 + G2;
        const x2 = x0 - 1 + 2 * G2;
        const y2 = y0 - 1 + 2 * G2;
        const ii = i & 255;
        const jj = j & 255;
        let t0 = 0.5 - x0 * x0 - y0 * y0;
        if (t0 >= 0) {
          const gi0 = ii + perm[jj];
          const g0x = permGrad2x[gi0];
          const g0y = permGrad2y[gi0];
          t0 *= t0;
          n0 = t0 * t0 * (g0x * x0 + g0y * y0);
        }
        let t1 = 0.5 - x1 * x1 - y1 * y1;
        if (t1 >= 0) {
          const gi1 = ii + i1 + perm[jj + j1];
          const g1x = permGrad2x[gi1];
          const g1y = permGrad2y[gi1];
          t1 *= t1;
          n1 = t1 * t1 * (g1x * x1 + g1y * y1);
        }
        let t2 = 0.5 - x2 * x2 - y2 * y2;
        if (t2 >= 0) {
          const gi2 = ii + 1 + perm[jj + 1];
          const g2x = permGrad2x[gi2];
          const g2y = permGrad2y[gi2];
          t2 *= t2;
          n2 = t2 * t2 * (g2x * x2 + g2y * y2);
        }
        return 70 * (n0 + n1 + n2);
      };
    }
    function createNoise3D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad3x = new Float64Array(perm).map((v) => grad3[v % 12 * 3]);
      const permGrad3y = new Float64Array(perm).map((v) => grad3[v % 12 * 3 + 1]);
      const permGrad3z = new Float64Array(perm).map((v) => grad3[v % 12 * 3 + 2]);
      return function noise3D(x, y, z) {
        let n0, n1, n2, n3;
        const s = (x + y + z) * F3;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const k = fastFloor(z + s);
        const t = (i + j + k) * G3;
        const X0 = i - t;
        const Y0 = j - t;
        const Z0 = k - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        const z0 = z - Z0;
        let i1, j1, k1;
        let i2, j2, k2;
        if (x0 >= y0) {
          if (y0 >= z0) {
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
          } else if (x0 >= z0) {
            i1 = 1;
            j1 = 0;
            k1 = 0;
            i2 = 1;
            j2 = 0;
            k2 = 1;
          } else {
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 1;
            j2 = 0;
            k2 = 1;
          }
        } else {
          if (y0 < z0) {
            i1 = 0;
            j1 = 0;
            k1 = 1;
            i2 = 0;
            j2 = 1;
            k2 = 1;
          } else if (x0 < z0) {
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 0;
            j2 = 1;
            k2 = 1;
          } else {
            i1 = 0;
            j1 = 1;
            k1 = 0;
            i2 = 1;
            j2 = 1;
            k2 = 0;
          }
        }
        const x1 = x0 - i1 + G3;
        const y1 = y0 - j1 + G3;
        const z1 = z0 - k1 + G3;
        const x2 = x0 - i2 + 2 * G3;
        const y2 = y0 - j2 + 2 * G3;
        const z2 = z0 - k2 + 2 * G3;
        const x3 = x0 - 1 + 3 * G3;
        const y3 = y0 - 1 + 3 * G3;
        const z3 = z0 - 1 + 3 * G3;
        const ii = i & 255;
        const jj = j & 255;
        const kk = k & 255;
        let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
        if (t0 < 0)
          n0 = 0;
        else {
          const gi0 = ii + perm[jj + perm[kk]];
          t0 *= t0;
          n0 = t0 * t0 * (permGrad3x[gi0] * x0 + permGrad3y[gi0] * y0 + permGrad3z[gi0] * z0);
        }
        let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
        if (t1 < 0)
          n1 = 0;
        else {
          const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1]];
          t1 *= t1;
          n1 = t1 * t1 * (permGrad3x[gi1] * x1 + permGrad3y[gi1] * y1 + permGrad3z[gi1] * z1);
        }
        let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
        if (t2 < 0)
          n2 = 0;
        else {
          const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2]];
          t2 *= t2;
          n2 = t2 * t2 * (permGrad3x[gi2] * x2 + permGrad3y[gi2] * y2 + permGrad3z[gi2] * z2);
        }
        let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
        if (t3 < 0)
          n3 = 0;
        else {
          const gi3 = ii + 1 + perm[jj + 1 + perm[kk + 1]];
          t3 *= t3;
          n3 = t3 * t3 * (permGrad3x[gi3] * x3 + permGrad3y[gi3] * y3 + permGrad3z[gi3] * z3);
        }
        return 32 * (n0 + n1 + n2 + n3);
      };
    }
    function createNoise4D(random = Math.random) {
      const perm = buildPermutationTable(random);
      const permGrad4x = new Float64Array(perm).map((v) => grad4[v % 32 * 4]);
      const permGrad4y = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 1]);
      const permGrad4z = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 2]);
      const permGrad4w = new Float64Array(perm).map((v) => grad4[v % 32 * 4 + 3]);
      return function noise4D(x, y, z, w) {
        let n0, n1, n2, n3, n4;
        const s = (x + y + z + w) * F4;
        const i = fastFloor(x + s);
        const j = fastFloor(y + s);
        const k = fastFloor(z + s);
        const l = fastFloor(w + s);
        const t = (i + j + k + l) * G4;
        const X0 = i - t;
        const Y0 = j - t;
        const Z0 = k - t;
        const W0 = l - t;
        const x0 = x - X0;
        const y0 = y - Y0;
        const z0 = z - Z0;
        const w0 = w - W0;
        let rankx = 0;
        let ranky = 0;
        let rankz = 0;
        let rankw = 0;
        if (x0 > y0)
          rankx++;
        else
          ranky++;
        if (x0 > z0)
          rankx++;
        else
          rankz++;
        if (x0 > w0)
          rankx++;
        else
          rankw++;
        if (y0 > z0)
          ranky++;
        else
          rankz++;
        if (y0 > w0)
          ranky++;
        else
          rankw++;
        if (z0 > w0)
          rankz++;
        else
          rankw++;
        const i1 = rankx >= 3 ? 1 : 0;
        const j1 = ranky >= 3 ? 1 : 0;
        const k1 = rankz >= 3 ? 1 : 0;
        const l1 = rankw >= 3 ? 1 : 0;
        const i2 = rankx >= 2 ? 1 : 0;
        const j2 = ranky >= 2 ? 1 : 0;
        const k2 = rankz >= 2 ? 1 : 0;
        const l2 = rankw >= 2 ? 1 : 0;
        const i3 = rankx >= 1 ? 1 : 0;
        const j3 = ranky >= 1 ? 1 : 0;
        const k3 = rankz >= 1 ? 1 : 0;
        const l3 = rankw >= 1 ? 1 : 0;
        const x1 = x0 - i1 + G4;
        const y1 = y0 - j1 + G4;
        const z1 = z0 - k1 + G4;
        const w1 = w0 - l1 + G4;
        const x2 = x0 - i2 + 2 * G4;
        const y2 = y0 - j2 + 2 * G4;
        const z2 = z0 - k2 + 2 * G4;
        const w2 = w0 - l2 + 2 * G4;
        const x3 = x0 - i3 + 3 * G4;
        const y3 = y0 - j3 + 3 * G4;
        const z3 = z0 - k3 + 3 * G4;
        const w3 = w0 - l3 + 3 * G4;
        const x4 = x0 - 1 + 4 * G4;
        const y4 = y0 - 1 + 4 * G4;
        const z4 = z0 - 1 + 4 * G4;
        const w4 = w0 - 1 + 4 * G4;
        const ii = i & 255;
        const jj = j & 255;
        const kk = k & 255;
        const ll = l & 255;
        let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
        if (t0 < 0)
          n0 = 0;
        else {
          const gi0 = ii + perm[jj + perm[kk + perm[ll]]];
          t0 *= t0;
          n0 = t0 * t0 * (permGrad4x[gi0] * x0 + permGrad4y[gi0] * y0 + permGrad4z[gi0] * z0 + permGrad4w[gi0] * w0);
        }
        let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
        if (t1 < 0)
          n1 = 0;
        else {
          const gi1 = ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]];
          t1 *= t1;
          n1 = t1 * t1 * (permGrad4x[gi1] * x1 + permGrad4y[gi1] * y1 + permGrad4z[gi1] * z1 + permGrad4w[gi1] * w1);
        }
        let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
        if (t2 < 0)
          n2 = 0;
        else {
          const gi2 = ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]];
          t2 *= t2;
          n2 = t2 * t2 * (permGrad4x[gi2] * x2 + permGrad4y[gi2] * y2 + permGrad4z[gi2] * z2 + permGrad4w[gi2] * w2);
        }
        let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
        if (t3 < 0)
          n3 = 0;
        else {
          const gi3 = ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]];
          t3 *= t3;
          n3 = t3 * t3 * (permGrad4x[gi3] * x3 + permGrad4y[gi3] * y3 + permGrad4z[gi3] * z3 + permGrad4w[gi3] * w3);
        }
        let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
        if (t4 < 0)
          n4 = 0;
        else {
          const gi4 = ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]];
          t4 *= t4;
          n4 = t4 * t4 * (permGrad4x[gi4] * x4 + permGrad4y[gi4] * y4 + permGrad4z[gi4] * z4 + permGrad4w[gi4] * w4);
        }
        return 27 * (n0 + n1 + n2 + n3 + n4);
      };
    }
    function buildPermutationTable(random) {
      const tableSize = 512;
      const p = new Uint8Array(tableSize);
      for (let i = 0; i < tableSize / 2; i++) {
        p[i] = i;
      }
      for (let i = 0; i < tableSize / 2 - 1; i++) {
        const r = i + ~~(random() * (256 - i));
        const aux = p[i];
        p[i] = p[r];
        p[r] = aux;
      }
      for (let i = 256; i < tableSize; i++) {
        p[i] = p[i - 256];
      }
      return p;
    }
    
    class Simplex {
        buildPermutationTable(random) { return buildPermutationTable(random); }
        createNoise2D(random) { return createNoise2D(random); }
        createNoise3D(random) { return createNoise3D(random); }
        createNoise4D(random) { return createNoise4D(random); }
    }
    return new Simplex();
}


////////////////////////////////////////////////////////////////
// Bale utility code - Created by Jurgen Westerhof 2022
// https://turtletoy.net/turtle/beb59d67ae
// Abusing the opacity, usage:
//      Canvas.setpenopacity(1/paletteSize);
//      const bales = Bales(paletteSize); // Bales(count, includeFullTransparent = true, turtleClass = null)
// Then use bales[x] wherever you would use a turtle object to 'draw'
// in 'color' x (i.e Polygon hatching with a bale object and .15 interspacing)
//      bales[x].jump(0,0);
//      bales[x].goto(40,0);
////////////////////////////////////////////////////////////////
function Bale(n, turtleClass = null) {class Bale {constructor(n, turtleClass = null) { this.turtles = Array.apply(null,{length: n}).map(i => turtleClass == null? new Turtle(): new turtleClass()); }back(e)         { this.turtles.forEach(t => t.back(e)); return this; }backward(e)     { this.turtles.forEach(t => t.backward(e)); return this; }bk(e)           { this.turtles.forEach(t => t.bk(e)); return this; }fd(e)           { this.turtles.forEach(t => t.fd(e)); return this; }forward(e)      { this.turtles.forEach(t => t.forward(e)); return this; }left(e)         { this.turtles.forEach(t => t.left(e)); return this; }lt(e)           { this.turtles.forEach(t => t.lt(e)); return this; }right(e)        { this.turtles.forEach(t => t.right(e)); return this; }rt(e)           { this.turtles.forEach(t => t.rt(e)); return this; }seth(e)         { this.turtles.forEach(t => t.seth(e)); return this; }setheading(e)   { this.turtles.forEach(t => t.setheading(e)); return this; }setx(e)         { this.turtles.forEach(t => t.setx(e)); return this; }sety(e)         { this.turtles.forEach(t => t.sety(e)); return this; }setpos(x, y)        { this.turtles.forEach(t => t.setpos(x, y)); return this; }setposition(x, y)   { this.turtles.forEach(t => t.setposition(x, y)); return this; }toradians(e)    { this.turtles.forEach(t => t.toradians(e)); return this; }degrees(e)      { this.turtles.forEach(t => t.degrees(e)); return this; }goto(x, y)      { this.turtles.forEach(t => t.goto(x, y)); return this; }jmp(x, y)       { this.turtles.forEach(t => t.jmp(x, y)); return this; }jump(x, y)      { this.turtles.forEach(t => t.jump(x, y)); return this; }circle(radius, extent, steps) { this.turtles.map(t => t.circle(radius, extent, steps)); return this; }clone()         { let b = new Bale(this.turtles.length); this.turtles.forEach((t, k) => b.turtles[k] = t.clone()); return b; }h()             { return this.turtles.length == 0? null: this.turtles[0].h(); }heading()       { return this.turtles.length == 0? null: this.turtles[0].heading(); }home()          { this.turtles.forEach(t => t.home()); return this; }isdown()        { return this.turtles.length == 0? null: this.turtles[0].isdown(); }pos()           { return this.turtles.length == 0? null: this.turtles[0].pos(); }position()      { return this.turtles.length == 0? null: this.turtles[0].position(); }pd()            { this.turtles.forEach(t => t.pd()); return this; }pendown()       { this.turtles.forEach(t => t.pendown()); return this; }penup()         { this.turtles.forEach(t => t.penup()); return this; }pu()            { this.turtles.forEach(t => t.pu()); return this; }down()          { this.turtles.forEach(t => t.down()); return this; }up()            { this.turtles.forEach(t => t.up()); return this; }radians()       { this.turtles.forEach(t => t.radians()); return this; }x()             { return this.turtles.length == 0? null: this.turtles[0].x(); }xcor()          { return this.turtles.length == 0? null: this.turtles[0].xcor(); }y()             { return this.turtles.length == 0? null: this.turtles[0].y(); }ycor()          { return this.turtles.length == 0? null: this.turtles[0].ycor(); }set(key, value) { this.turtles.forEach(i => i[key] = value); return this; }get(key) { return this.turtles.length == 0? null: this.turtles[0][key]; }}return new Bale(n, turtleClass);}
function Bales(count, includeFullTransparent = true, turtleClass = null) { if(count == 1) return [new Bale(1, turtleClass)]; const getExponent = (base, target) => Math.log(target) / Math.log(base); const baleSize = count - (includeFullTransparent?1:0); const n = Array.apply(null,{length: baleSize}).map((v,k) => Math.round(getExponent(1 - 1/count, 1 - (count - k == count?.99:(baleSize - k)/baleSize)))); if(includeFullTransparent) n.push(0); return n.map(i => new Bale(i, turtleClass));}

function init() {
    ///////////////////////////////////////////////////////
    // Vector functions - Created by Jurgen Westerhof 2024
    // https://turtletoy.net/turtle/d068ad6040
    ///////////////////////////////////////////////////////
    class Vector {
        static add  (a,b) { return a.map((v,i)=>v+b[i]); }
        static sub  (a,b) { return a.map((v,i)=>v-b[i]); }
        static mul  (a,b) { return a.map((v,i)=>v*b[i]); }
        static div  (a,b) { return a.map((v,i)=>v/b[i]); }
        static scale(a,s) { return a.map(v=>v*s); }
    
        static det(m)                { return m.length == 1? m[0][0]: m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0]: m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.det(m.slice(1).map(c => c.filter((_,j) => i != j))),0); }
        static angle(a)              { return Math.PI - Math.atan2(a[1], -a[0]); } //compatible with turtletoy heading
        static rot2d(angle)          { return [[Math.cos(angle), -Math.sin(angle)], [Math.sin(angle), Math.cos(angle)]]; }
        static rot3d(yaw,pitch,roll) { return [[Math.cos(yaw)*Math.cos(pitch), Math.cos(yaw)*Math.sin(pitch)*Math.sin(roll)-Math.sin(yaw)*Math.cos(roll), Math.cos(yaw)*Math.sin(pitch)*Math.cos(roll)+Math.sin(yaw)*Math.sin(roll)],[Math.sin(yaw)*Math.cos(pitch), Math.sin(yaw)*Math.sin(pitch)*Math.sin(roll)+Math.cos(yaw)*Math.cos(roll), Math.sin(yaw)*Math.sin(pitch)*Math.cos(roll)-Math.cos(yaw)*Math.sin(roll)],[-Math.sin(pitch), Math.cos(pitch)*Math.sin(roll), Math.cos(pitch)*Math.cos(roll)]]; }
        static trans(matrix,a)       { return a.map((v,i) => a.reduce((acc, cur, ci) => acc + cur * matrix[ci][i], 0)); }
        //Mirror vector a in a ray through [0,0] with direction mirror
        static mirror2d(a,mirror)    { return [Math.atan2(...mirror)].map(angle => this.trans(this.rot2d(angle), this.mul([-1,1], this.trans(this.rot2d(-angle), a)))).pop(); }

        static approx(a,b,p) { return this.len(this.sub(a,b)) < (p === undefined? .001: p); }
        static norm  (a)     { return this.scale(a,1/this.len(a)); }
        static len   (a)     { return Math.hypot(...a); }
        static lenSq (a)     { return a.reduce((a,c)=>a+c**2,0); }
        static lerp  (a,b,t) { return a.map((v, i) => v*(1-t) + b[i]*t); }
        static dist  (a,b)   { return Math.hypot(...this.sub(a,b)); }
        
        static dot  (a,b)   { return a.reduce((a,c,i) => a+c*b[i], 0); }
        static cross(...ab) { return ab[0].map((e, i) => ab.map(v => v.filter((ee, ii) => ii != i))).map((m,i) => (i%2==0?-1:1)*this.det(m)); }
    }
    this.V = Vector;
    
    class Intersection2D {
        //a-start, a-direction, b-start, b-direction
        //returns false on no intersection or [[intersection:x,y], scalar a-direction, scalar b-direction
        static info(as, ad, bs, bd) { const d = V.sub(bs, as), det = -V.det([bd, ad]); if(det === 0) return false; const res = [V.det([d, bd]) / det, V.det([d, ad]) / det]; return [V.add(as, V.scale(ad, res[0])), ...res]; }
        static ray(a, b, c, d) { return this.info(a, b, c, d); }
        static segment(a,b,c,d, inclusiveStart = true, inclusiveEnd = true) { const i = this.info(a, V.sub(b, a), c, V.sub(d, c)); return i === false? false: ( (inclusiveStart? 0<=i[1] && 0<=i[2]: 0<i[1] && 0<i[2]) && (inclusiveEnd?   i[1]<=1 && i[2]<=1: i[1]<1 && i[2]<1) )?i[0]:false;}
        static tour(tour, segmentStart, segmentDirection) { return tour.map((e, i, a) => [i, this.info(e, V.sub(a[(i+1)%a.length], e), segmentStart, segmentDirection)]).filter(e => e[1] !== false && 0 <= e[1][1] && e[1][1] <= 1).filter(e => 0 <= e[1][2]).map(e => ({position: e[1][0],tourIndex: e[0],tourSegmentPortion: e[1][1],segmentPortion: e[1][2],}));}
        static inside(tour, pt) { return tour.map((e,i,a) => this.segment(e, a[(i+1)%a.length], pt, [Number.MAX_SAFE_INTEGER, 0], true, false)).filter(e => e !== false).length % 2 == 1; }
        static circles(centerA, radiusA, centerB, radiusB) {const result = {intersect_count: 0,intersect_occurs: true,one_is_in_other: false,are_equal: false,point_1: [null, null],point_2: [null, null],};const dx = centerB[0] - centerA[0];const dy = centerB[1] - centerA[1];const dist = Math.hypot(dy, dx);if (dist > radiusA + radiusB) {result.intersect_occurs = false;}if (dist < Math.abs(radiusA - radiusB) && !N.approx(dist, Math.abs(radiusA - radiusB))) {result.intersect_occurs = false;result.one_is_in_other = true;}if (V.approx(centerA, centerB) && radiusA === radiusB) {result.are_equal = true;}if (result.intersect_occurs) {const centroid = (radiusA**2 - radiusB**2 + dist * dist) / (2.0 * dist);const x2 = centerA[0] + (dx * centroid) / dist;const y2 = centerA[1] + (dy * centroid) / dist;const prec = 10000;const h = (Math.round(radiusA**2 * prec)/prec - Math.round(centroid**2 * prec)/prec)**.5;const rx = -dy * (h / dist);const ry = dx * (h / dist);result.point_1 = [x2 + rx, y2 + ry];result.point_2 = [x2 - rx, y2 - ry];if (result.are_equal) {result.intersect_count = null;} else if (result.point_1.x === result.point_2.x && result.point_1.y === result.point_2.y) {result.intersect_count = 1;} else {result.intersect_count = 2;}}return result;}
    }
    this.Intersection = Intersection2D;
    
    class PathTools {
        static bezier(p1, cp1, cp2, p2, steps = null) {steps = (steps === null? (V.len(V.sub(cp1, p1)) + V.len(V.sub(cp2, cp1)) + V.len(V.sub(p2, cp2))) | 0: steps) - 1;return Array.from({length: steps + 1}).map((v, i, a, f = i/steps) => [[V.lerp(p1, cp1, f),V.lerp(cp1, cp2, f),V.lerp(cp2, p2, f)]].map(v => V.lerp(V.lerp(v[0], v[1], f), V.lerp(v[1], v[2], f), f))[0]);}
        // https://stackoverflow.com/questions/18655135/divide-bezier-curve-into-two-equal-halves#18681336
        static splitBezier(p1, cp1, cp2, p2, t=.5) {const e = V.lerp(p1, cp1, t);const f = V.lerp(cp1, cp2, t);const g = V.lerp(cp2, p2, t);const h = V.lerp(e, f, t);const j = V.lerp(f, g, t);const k = V.lerp(h, j, t);return [[p1, e, h, k], [k, j, g, p2]];}
        static circular(radius,verticeCount,rotation=0) {return Array.from({length: verticeCount}).map((e,i,a,f=i*2*Math.PI/verticeCount+rotation) => [radius*Math.cos(f),radius*Math.sin(f)])}
        static circle(r){return this.circular(r,Math.max(12, r*2*Math.PI|0));}
        static arc(radius, extend = 2 * Math.PI, clockWiseStart = 0, steps = null, includeLast = false) { return [steps == null? (radius*extend+1)|0: steps].map(steps => Array.from({length: steps}).map((v, i, a) => [radius * Math.cos(clockWiseStart + extend*i/(a.length-(includeLast?1:0))), radius * Math.sin(clockWiseStart + extend*i/(a.length-(includeLast?1:0)))])).pop(); }
        static draw(turtle, path) {path.forEach((pt, i) => turtle[i==0?'jump':'goto'](pt));}
        static drawTour(turtle, path) {this.draw(turtle, path.concat([path[0]]));}
        static drawPoint(turtle, pt, r = .1) {this.drawTour(turtle, this.circle(r).map(e => V.add(e, pt)));}
        static drawArrow(turtle, s, d, width = 6, length = 3) {turtle.jump(s);const arrowHeadBase = V.add(s,d);turtle.goto(arrowHeadBase);turtle.goto(V.add(arrowHeadBase, V.trans(V.rot2d(-V.angle(d)), [-length, width/2])));turtle.jump(V.add(arrowHeadBase, V.trans(V.rot2d(-V.angle(d)), [-length, -width/2])));turtle.goto(arrowHeadBase);}
        static circlesTangents(c1_center, c1_radius, c2_center, c2_radius, internal = false) {let middle_circle = [V.scale(V.sub(c1_center, c2_center), .5)].map(hwp => [V.add(c2_center, hwp), V.len(hwp)]).pop();if(!internal && c1_radius == c2_radius) {let target = V.sub(c2_center, c1_center);let scaledTarget = V.scale(target, c1_radius/V.len(target));let partResult = [V.add(c1_center, V.trans(V.rot2d(Math.PI/2), scaledTarget)),V.add(c1_center, V.trans(V.rot2d(Math.PI/-2), scaledTarget))];return [partResult,partResult.map(pt => V.add(pt, target))]}let swap = !internal && c2_radius > c1_radius;if(swap) {let t = [[...c1_center], c1_radius];c1_center = c2_center;c1_radius = c2_radius;c2_center = t[0];c2_radius = t[1];}let internal_waypoints = intersectCircles2(c1_center, c1_radius + (internal?c2_radius:-c2_radius), ...middle_circle);if(internal_waypoints.length == 0) return [];const circlePointAtDirection2 = (circle_center, radius, direction) => V.add(circle_center, V.scale(direction, radius/V.len(direction)));const result = [[circlePointAtDirection2(c1_center, c1_radius, V.sub(internal_waypoints[0], c1_center)),circlePointAtDirection2(c1_center, c1_radius, V.sub(internal_waypoints[1], c1_center))],[circlePointAtDirection2(c2_center, c2_radius, internal? V.sub(c1_center, internal_waypoints[0]): V.sub(internal_waypoints[0], c1_center)),circlePointAtDirection2(c2_center, c2_radius, internal? V.sub(c1_center, internal_waypoints[1]): V.sub(internal_waypoints[1], c1_center))]];return swap? [[result[1][1],result[1][0]],[result[0][1],result[0][0]]]: result;}
    }

    this.PT = PathTools;
    
    class Complex {
        static add(a,b)     { return V.add(a,b); }
        static sub(a,b)     { return V.sub(a,b); }
        static scale(a,s)   { return V.scale(a,s); }
        static mult(a,b)    { return [a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]]; }
        static sqrt(a)      { return [[Math.hypot(...a)**.5, Math.atan2(...a.reverse()) / 2]].map(ra => [ra[0]*Math.cos(ra[1]), ra[0]*Math.sin(ra[1])]).pop(); }
    }
    this.C = Complex;
    
    class Numbers {
        static approx(a,b,p)        { return Math.abs(a-b) < (p === undefined? .001: p); }
        static clamp(a, min, max)   { return Math.min(Math.max(a, min), max); }
    }
    this.N = Numbers;
    
    class Matrix {
        static bayer(order) { return [...Array(1<<order)].map((_,y,a) => { const g = (k=order,x)=>k--&&4*g(k,x)|2*(x>>k)+3*(y>>k&1)&3; return a.map(g); }); }
        static rotate(m) { return m[0].map((e, i) => m.map(r => r[i]).reverse()); }
        static rotateCCW(m) { return m[0].map((e, i) => m.map(r => r[r.length-1-i])); }
        static add(a,b) { return a.map((e, c) => e.map((e, r) => a[c][r] + b[c][r])); }
        static sub(a,b) { return a.map((e, c) => e.map((e, r) => a[c][r] - b[c][r])); }
        static multiply(a,b) { return Array.from({length: b.length}, (e,resCol) => Array.from({length: a[0].length}, (e,resRow) => b[resCol].reduce((acc, c, bRow) => acc + a[bRow][resRow] * b[resCol][bRow], 0)));}
        static scale(a,s) { return a.map((e, c) => e.map((e, r) => a[c][r] * s)); }
        static random(c,r,fillFn = Math.random) { return Array.from({length: c}, (e,i) => Array.from({length: r}, e => fillFn(c, r))); }
        static identity(d) { return Array.from({length: d}, (e,c) => Array.from({length: d}, (e, r) => c==r?1:0 )); }
        static log(m, name, logFn = console.log) { if(name != undefined) logFn(name); if(m === undefined || (typeof m == 'object' && (m[0] === undefined || m[0][0] === undefined))) { return logFn(`Failed to log matrix:`, m); } logFn(m[0].map((e,r) => m.map((e,c) => m[c][r]).join(', ')).join('\n')); }
        static invert(m) { let _A = m.map(col => col.map(cell => cell));/*clone matrix*/let temp;const N = _A.length;const E = Array.from({length: N}, (e,i) => Array.from({length: _A[0].length}, (e,j) => i==j?1:0));for (let k = 0; k < N; k++) {temp = _A[k][k];for (let j = 0; j < N; j++) {_A[k][j] /= temp;E[k][j] /= temp;}for (let i = k + 1; i < N; i++) {temp = _A[i][k];for (let j = 0; j < N; j++) {_A[i][j] -= _A[k][j] * temp;E[i][j] -= E[k][j] * temp;}}}for (let k = N - 1; k > 0; k--) {for (let i = k - 1; i >= 0; i--) {temp = _A[i][k];for (let j = 0; j < N; j++) {_A[i][j] -= _A[k][j] * temp;E[i][j] -= E[k][j] * temp;}}}return E; }
        static determinant(m) { return m.length == 1 ?m[0][0] :m.length == 2 ? m[0][0]*m[1][1]-m[0][1]*m[1][0] :m[0].reduce((r,e,i) => r+(-1)**(i+2)*e*this.determinant(m.slice(1).map(c => c.filter((_,j) => i != j))), 0)}
        static flip(m) { return Array.from({length: m[0].length}, (_, r) => Array.from({length: m.length}, (e, c) => m[c][r])); }
        static sum(m) { return m.reduce((a, c) => a + c.reduce((aa, cc) => aa + cc, 0), 0); }
    }
    this.M = Matrix;
}