festive tree

#fakeshadows

Created by base12 on 2018/12/25
114
0

Log in to post a comment.

const treeHeight = 100
const strips = 4
const topy = -60
const dx = 12, dy = treeHeight / strips
const sdx = 7.5, sdy = 9

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

function walk(i) {
    if (i === 0) {
        drawStar()
    }
    const corners = treeStripCorners(i)
    const clip = createClip(corners)
    drawTreeStrip(i, corners, clip)
    drawShadow(i, corners, clip)
    return i < strips
}

function drawStar() {
    const star = new Polygon()
    const pt = [0, topy - 5]
    for (let j = 0; j < 10; j++) {
        const angle = j / 10 * Math.PI * 2 - Math.PI / 2
        star.cp.push(add2(pt, scale2([Math.cos(angle), Math.sin(angle)], j % 2 ? 3 : 6)))
    }
    star.addOutline()
    star.draw(turtle)
}

function treeStripCorners(i) {
    const tl = [0 - i * dx, topy + i * dy], tr = [0 + i * dx, topy + i * dy]
    return {
        tl, tr,
        bl: add2(tl, [-dx, dy]),
        br: add2(tr, [dx, dy])
    }
}

function createClip({tl, tr, br, bl}) {
    const clip = new Polygon()
    clip.cp.push(tl, tr, br, bl)
    return clip
}

function drawTreeStrip(i, {br, bl}, clip) {
    const poly = clip.clone()
    for (let j = 0; j < br[0] - bl[0]; j += i % 2 ? 2 : 4) {
        const start = i % 2
            ? add2(bl, [j, 0.01]) // offset because of clipping bug at x = 0
            : add2(br, [-j, 0.01])
        const end = i % 2
            ? add2(start, [dx, -dy])
            : add2(start, [-dx, -dy])
        poly.dp.push(new LineSegment(start, end))
    }
    poly.boolean(clip, false)
    poly.draw(turtle)
}

function shadowOffs(xoffs) {
    const lift = map(xoffs, 0, dx * 10, 0, 1)
    return scale2([sdx, sdy], lift)
}

function drawShadow(i, {tl, tr, bl, br}, clip) {
    const shadow = new Polygon()
    const topOffs = shadowOffs(tr[0] - tl[0])
    const botOffs = shadowOffs(br[0] - bl[0])
    if (i % 2) {
        shadow.cp.push(add2(tl, topOffs), add2(bl, botOffs), lerp2(bl, br, 0.5))
    }
    else {
        shadow.cp.push(tl, add2(tr, topOffs), add2(br, botOffs), lerp2(bl, br, i === strips ? 0 : 0.5))
    }
    shadow.addHatching(-Math.PI / 6, 0.75)
    shadow.boolean(clip, true)
    shadow.draw(turtle)
}

// 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;
}
function mag2([x, y]) {
    return Math.sqrt(x ** 2 + y ** 2)
}
function lerp2(a, b, f) {
    return [lerp(a[0], b[0], f), lerp(a[1], b[1], f)]
}