truchet dissolve

a first pass, plenty more ideas to play with here

Created by base12 on 2018/12/17
206
0

Log in to post a comment.

// much cleanup necessary; fix alignments of curves on grid
// polygon code pulled from: https://turtletoy.net/turtle/789cce3829
// core truchet code pulled from: https://turtletoy.net/turtle/1dc2d96bc9

const maxOffset = 0.25
const cpFactor = 1 / 3
const angle = (3 / 8) * (Math.PI * 2)
const dist = 1
const drawCurves = true
const crossHatch = true

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)
    }

    sub(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
    }
    
    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)
    }    

    static lerp(a, b, fract) {
        return new Vec2(lerp(a.x, b.x, fract), lerp(a.y, b.y, fract))
    }
}

// class LineSegment {
//     constructor(a, b) {
//         this.a = a
//         this.b = b
//     }
// }

Canvas.setpenopacity(1);

const turtle = new Turtle();
turtle.penup();
turtle.goto(-50,-20);
turtle.pendown();

const size = 20
const tileIndexes = [...Array(size * size)].map((v, i) => i)
const points = [[0, 0], [10, 0], [10, 10], [0, 10]].map(([x, y]) => new Vec2(x, y));
const order1 = [0, 1, 2, 3]
const order2 = [1, 0, 3, 2]

function walk(i) {
    for (let j = 0; j < 10 && tileIndexes.length > 0; j++) {
        const listIndex = Math.floor(Math.random() * tileIndexes.length)
        const tileIndex = tileIndexes[listIndex]
        tileIndexes.splice(listIndex, 1)
        
        const y = Math.floor(tileIndex / size) - size / 2
        const x = (tileIndex % size) - size / 2
        const p2 = points.map(pt => pt.add(new Vec2(10 * x, 10 * y)))
        const flip = Math.random() < 0.5
        const order = flip ? order1 : order2
        const p3 = reorder(p2, order)
        drawTruch(p3, 0, x, y, flip)
    }

    return tileIndexes.length > 0
}

function reorder(p, order) {
    const ps = []
    order.forEach(i => ps.push(p[i]))
    return ps
}

function drawTruch(pi, r, x, y, flip) {
    var i0=Math.floor(0.0+r)%4;
    var i1=Math.floor(1.0+r)%4;
    var i2=Math.floor(3.0+r)%4;
    var i3=Math.floor(2.0+r)%4;

    let tl_dark = !!(((Math.abs(x) % 2) + ((Math.abs(y) + 1) % 2) + (flip ? 0 : 1)) % 2)
    let t = 0.5 + map(x, -10, 9, -maxOffset, maxOffset) * (tl_dark ? 1 : -1)
    let tl_s = Vec2.lerp(pi[0], pi[1], t)
    let tl_e = Vec2.lerp(pi[0], pi[3], t)
    let tl_a = tl_s.addY((pi[3].y - pi[0].y) * t * cpFactor)
    let tl_b = tl_e.addX((pi[1].x - pi[0].x) * t * cpFactor)
    // drawCurve([tl_s, tl_a, tl_b, tl_e])

    let tl = pi[0]
    let tr = pi[1]

    let br_s = Vec2.lerp(pi[2], pi[3], t)
    let br_e = Vec2.lerp(pi[2], pi[1], t)
    let br_a = br_s.addY((pi[1].y - pi[2].y) * t * cpFactor)
    let br_b = br_e.addX((pi[3].x - pi[2].x) * t * cpFactor)
    // drawCurve([br_s, br_a, br_b, br_e])
    
    let br = pi[2]
    let bl = pi[3]
    
    if (tl_dark) {
        const tl_curve = bezierCurve([tl_e, tl_b, tl_a, tl_s])
        const br_curve = bezierCurve([br_e, br_b, br_a, br_s])

        let poly = new Polygon()
        poly.cp = [
            ...tl_curve,
            tr,
            ...br_curve,
            bl
        ].map(pt => [pt.x, pt.y])
        hatch(poly)
        if (drawCurves) {
            addOutline(poly, tl_curve)
            addOutline(poly, br_curve)
        }
        poly.draw(turtle)
    }
    else {
        const tl_curve = bezierCurve([tl_s, tl_a, tl_b, tl_e])
        const br_curve = bezierCurve([br_s, br_a, br_b, br_e])

        let poly = new Polygon()
        poly.cp = [
            tl,
            ...tl_curve,
        ].map(pt => [pt.x, pt.y])
        hatch(poly)
        if (drawCurves) {
            addOutline(poly, tl_curve)
        }
        poly.draw(turtle)

        poly = new Polygon()
        poly.cp = [
            br,
            ...br_curve,
        ].map(pt => [pt.x, pt.y])
        hatch(poly)
        if (drawCurves) {
            addOutline(poly, br_curve)
        }
        poly.draw(turtle)
    }
}

let hatching

function setupHatching() {
    let a = angle
    const d = dist
    const tp = new Polygon()
    tp.createPoly(0,0,4,200,Math.PI*.5);
    {
        const dx = Math.sin(a)*d, dy = Math.cos(a)*d;
        const cx = Math.sin(a)*200, cy = Math.cos(a)*200;
        for (let i = .5; i<150/d; i++) {
            tp.dp.push(new LineSegment([dx*i+cy,dy*i-cx], [dx*i-cy,dy*i+cx]));
            tp.dp.push(new LineSegment([-dx*i+cy,-dy*i-cx], [-dx*i-cy,-dy*i+cx]));
        }
    }

    if (crossHatch) {
        a += Math.PI / 2
        const dx = Math.sin(a)*d, dy = Math.cos(a)*d;
        const cx = Math.sin(a)*200, cy = Math.cos(a)*200;
        for (let i = .5; i<150/d; i++) {
            tp.dp.push(new LineSegment([dx*i+cy,dy*i-cx], [dx*i-cy,dy*i+cx]));
            tp.dp.push(new LineSegment([-dx*i+cy,-dy*i-cx], [-dx*i-cy,-dy*i+cx]));
        }
    }

    hatching = tp
}

function hatch(poly) {
    const h = hatching.clone()
    h.boolean(poly, false)
    poly.dp = poly.dp.concat(h.dp)
}

function bezierCurve(p) {
    const cp = [p[0]]
    for (var i = 1; i <= 6; i++) {
        cp.push(bezierCurvePos(p, i / 6))
    }
    return cp
}

function drawCurve(p) {
    const cp = [p[0]]
    for (var i = 1; i <= 6; i++) {
        cp.push(bezierCurvePos(p, i / 6))
    } 
    const dp = addOutline(cp)
    drawLines(dp)
}

// cubic bezier curve in 2 dimensions
// equivalent to the function above, just in a more intuitive form
function bezierCurvePos(p, t) {
    // combination of 2 quadric beziers
    var q=[]; 
    var r=[]; 
    for(var i=0;i<3;i++) q.push(Vec2.lerp(p[i],p[i+1],t))
    for(var i=0;i<2;i++) r.push(Vec2.lerp(q[i],q[i+1],t))
    return Vec2.lerp(r[0],r[1],t)
}

function addOutline(poly, p) {
    for (let i = 0, l = p.length; i < l - 1; i++) {
        poly.dp.push(new LineSegment([p[i].x, p[i].y], [p[i + 1].x, p[i + 1].y]))
    }
}

const inp = 0

function drawLines(p) {
    if (p.length === 0) {
        return
    }
    for (let i = 0, l = p.length; i < l; i++) {
        const d = p[i]
        const last = turtle.pos()
        if (!d.a.equals(new Vec2(...last))) {
            turtle.penup()
            turtle.goto([d.a.x + inp * (Math.random() - 0.5), d.a.y + inp * (Math.random() - 0.5)])
            turtle.pendown()
        }
        turtle.goto([d.b.x + inp * (Math.random() - 0.5), d.b.y + inp * (Math.random() - 0.5)])
    }
}

// helpers

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(Math.random() * arr.length)]
}

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

// the following is copied from: https://turtletoy.net/turtle/789cce3829

let lineSegmentsDrawn = []

// polygon functions
function LineSegment(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
}
LineSegment.prototype.unique = function() {
    for (let i=0, l=lineSegmentsDrawn.length; i<l; i++) {
        const ls = lineSegmentsDrawn[i];
        if ( (equal2(this.p1, ls.p1) && equal2(this.p2, ls.p2)) ||
             (equal2(this.p1, ls.p2) && equal2(this.p2, ls.p1)) ){
            return false;
        }
    }
    lineSegmentsDrawn.push(this);
    return true;
}

function Polygon() {
    this.cp = []; // clip path: array of [x,y] pairs
    this.dp = []; // 2d line to draw: array of linesegments
}
Polygon.prototype.clone = function() {
    const p = new Polygon()
    p.cp = [...this.cp]
    p.dp = [...this.dp]
    return p
}
Polygon.prototype.addOutline = function(s=0) {
    for (let i=s, l=this.cp.length; i<l; i++) {
        this.dp.push(new LineSegment(this.cp[i], this.cp[(i+1)%l]));
    }
}
Polygon.prototype.createPoly = function(x,y,c,r,a) {
    this.cp = [];
    for (let i=0; i<c; i++) {
        this.cp.push( [x + Math.sin(i*Math.PI*2/c+a) * r, y + Math.cos(i*Math.PI*2/c+a) * r] );
    }
}
Polygon.prototype.addHatching = function(a,d) {
    // todo, create a tight bounding polygon, for now fill screen
    const tp = new Polygon();
    tp.createPoly(0,0,4,200,Math.PI*.5);
    const dx = Math.sin(a)*d, dy = Math.cos(a)*d;
    const cx = Math.sin(a)*200, cy = Math.cos(a)*200;
    for (let i = .5; i<150/d; i++) {
        tp.dp.push(new LineSegment([dx*i+cy,dy*i-cx], [dx*i-cy,dy*i+cx]));
        tp.dp.push(new LineSegment([-dx*i+cy,-dy*i-cx], [-dx*i-cy,-dy*i+cx]));
    }
    tp.boolean(this, false);
    this.dp = this.dp.concat(tp.dp);
}
Polygon.prototype.draw = function(t) {
    if (this.dp.length ==0) {
        return;
    }
    for (let i=0, l=this.dp.length; i<l; i++) {
        const d = this.dp[i];
        if (d.unique()) {
            if (!equal2(d.p1, t.pos())) {
                t.penup();
                t.goto(d.p1);
                t.pendown();   
            }
            t.goto(d.p2);
        }
    }
}
Polygon.prototype.inside = function(p) {
    // find number of intersections from p to far away - if even you're outside
    const p1 = [0, -1000];
    let int = 0;
    for (let i=0, l=this.cp.length; i<l; i++) {
        if (segment_intersect2(p, p1, this.cp[i], this.cp[(i+1)%l])) {
            int ++;
        }    
    }
    return int & 1;
}
Polygon.prototype.boolean = function(p, diff = true) {
    // very naive polygon diff algorithm - made this up myself
    const ndp = [];
    for (let i=0, l=this.dp.length; i<l; i++) {
        const ls = this.dp[i];
        
        // find all intersections with clip path
        const int = [];
        for (let j=0, cl=p.cp.length; j<cl; j++) {
            const pint = segment_intersect2(ls.p1,ls.p2,p.cp[j],p.cp[(j+1)%cl]);
            if (pint) {
                int.push(pint);
            }
        }
        if (int.length == 0) { // 0 intersections, inside or outside?
            if (diff != p.inside(ls.p1)) {
                ndp.push(ls);
            }
        } else {
            int.push(ls.p1); int.push(ls.p2);
            // order intersection points on line ls.p1 to ls.p2
            const cmp = sub2(ls.p2,ls.p1);
            int.sort((a,b) => dot2(sub2(a,ls.p1),cmp)-dot2(sub2(b,ls.p1),cmp));
            
            for (let j=0; j<int.length-1; j++) {
                if (!equal2(int[j], int[j+1]) && 
                    diff != p.inside(scale2(add2(int[j],int[j+1]),.5))) {
                    ndp.push(new LineSegment(int[j], int[j+1]));
                }
            }
        }
    }
    this.dp = ndp;
    return this.dp.length > 0;
}

// vec2 functions
const equal2=(a,b)=>0.001>dist_sqr2(a,b);
const scale2=(a,b)=>[a[0]*b,a[1]*b];
const add2=(a,b)=>[a[0]+b[0],a[1]+b[1]];
const sub2=(a,b)=>[a[0]-b[0],a[1]-b[1]];
const dot2=(a,b)=>a[0]*b[0]+a[1]*b[1];
const dist_sqr2=(a,b)=>(a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1]);
const segment_intersect2=(a,b,d,c)=>{
    const e=(c[1]-d[1])*(b[0]-a[0])-(c[0]-d[0])*(b[1]-a[1]);
    if(0==e)return false;
    c=((c[0]-d[0])*(a[1]-d[1])-(c[1]-d[1])*(a[0]-d[0]))/e;
    d=((b[0]-a[0])*(a[1]-d[1])-(b[1]-a[1])*(a[0]-d[0]))/e;
    return 0<=c&&1>=c&&0<=d&&1>=d?[a[0]+c*(b[0]-a[0]),a[1]+c*(b[1]-a[1])]:false;
}

setupHatching()