Hexagon Truchet

My first Truchet tiles experiment.

#truchet #hexagon

Log in to post a comment.

// Hexagon Truchet. Created by Reinder Nijhoff 2019 - @reindernijhoff
//
// https://turtletoy.net/turtle/e5df5b10e0
//

const turtle = new Turtle();
const scale = 5;
const lineWidth = .4; // min=0.1, max=0.4, step=0.01
const showHexagons = false;

const h0 = Math.sqrt(3)/2;
const h1 = 1/2;

function drawHexagon(t, x, y) {
    if (Math.abs(scale*x) > 100+scale ||
        Math.abs(scale*y) > 100+scale) return; // early discard
        
    const a = ((Math.random()*3)|0)*Math.PI/3; // random angle
    const poly = new Polygons();
    
    // 2 transform functions: translate-scale (for background hatching), and rotate-translate-scale
    const ts  = p => [scale*(p[0]+x),scale*(p[1]+y)];
    const rts = p => ts([Math.cos(a)*p[0]+Math.sin(a)*p[1], Math.cos(a)*p[1]-Math.sin(a)*p[0]]);
    
    // vec2 helper functions
    const add = (a, b) => [a[0]+b[0], a[1]+b[1]];
    const sub = (a, b) => [a[0]-b[0], a[1]-b[1]];
    const scl = (a, b) => [a[0]*b, a[1]*b];
    
    // 2 methods to create lines in a tile
    const line = (s, e, d) => { // line from s to e and width d
        const p = poly.create();
        p.addPoints(rts(add(s,d)), rts(add(e,d)), rts(sub(e,d)), rts(sub(s,d)));
        p.addSegments(rts(add(s,d)), rts(add(e,d)), rts(sub(e,d)), rts(sub(s,d)));
        return p;
    }
    const circle = (c, r, s, e) => { // circle around c, from angle s to e with radius r
        const p = poly.create(), c0 =[], c1 = [], f=10;
        for (let i=0; i<=f; i++) {
            c0.push(rts(add(c, [Math.cos(s+(e-s)*i/f)*(r+lineWidth), Math.sin(s+(e-s)*i/f)*(r+lineWidth)])));
            c1.push(rts(add(c, [Math.cos(e-(e-s)*i/f)*(r-lineWidth), Math.sin(e-(e-s)*i/f)*(r-lineWidth)])));
        }
        p.addPoints(...c0,...c1);
        for (let i=0; i<f; i++) p.addSegments(c0[i], c0[i+1]);
        for (let i=0; i<f; i++) p.addSegments(c1[i], c1[i+1]);
        return p;
    }
    
    // six corners of hexagon
    const c = [];
    for (let i=0; i<6; i++) {
        c.push([Math.cos(i*Math.PI/3), Math.sin(i*Math.PI/3)]);
    }
    
    // generate lines in tile
    const l = [], tileType = (Math.random()*5)|0; // 5 different tile types
    
    switch (tileType) {
        case 0:  l.push(line([0,h0], [0,-h0], [lineWidth, 0])); // 3 straight lines
                 l.push(line([1-h1/2,h0/2], [-1+h1/2,-h0/2], scl([Math.cos(Math.PI/3), -Math.sin(Math.PI/3)], lineWidth)));
                 l.push(line([1-h1/2,-h0/2], [-1+h1/2,h0/2], scl([Math.cos(-Math.PI/3), -Math.sin(-Math.PI/3)], lineWidth)));
                 break;
        case 1:  l.push(line([0,h0], [0,-h0], [lineWidth, 0])); // straight line + 2 arcs #1
                 l.push(circle(c[0], h1, Math.PI-Math.PI/3, Math.PI+Math.PI/3));
                 l.push(circle(c[3], h1, -Math.PI/3, +Math.PI/3));
                 break;
        case 2:  l.push(line([0,h0], [0,-h0], [lineWidth, 0])); // straight line + 2 arcs #2
                 l.push(circle([0,2*h0], 1+h1, -Math.PI/2-Math.PI/6, -Math.PI/2+Math.PI/6));
                 l.push(circle([0,-2*h0], 1+h1, Math.PI/2-Math.PI/6, Math.PI/2+Math.PI/6));
                 break;
        case 3:  l.push(circle(c[0], h1, Math.PI-Math.PI/3, Math.PI+Math.PI/3)); // 3 arcs #1
                 l.push(circle(c[2], h1, -2*Math.PI/3, 0));
                 l.push(circle(c[4], h1, 0, 2*Math.PI/3));
                 break;
        default: l.push(circle([0,2*h0], 1+h1, -Math.PI/2-Math.PI/6, -Math.PI/2+Math.PI/6)); // 3 arcs #2
                 l.push(circle([-1-h1, h0], 1+h1, 0, -Math.PI/3));
                 l.push(circle(c[5], h1, Math.PI/3, Math.PI));
                 break;
    }

    // shuffle lines and draw
    l.sort((a,b) => Math.random()-.5);
    l.map(p => poly.draw(t, p));

    // background
    const p0 = poly.create();
    p0.addPoints(...c.map(p => ts(p)));
    if (showHexagons) p0.addOutline();
    if (lineWidth < 0.35) p0.addHatching(Math.PI/4, 1);
    poly.draw(t, p0);
}

function walk(i) {
    const s = (100/scale|0)+10;
    const y = Math.floor(i/(s*2))-s;
    const x = (i % (s*2)) - s;
    drawHexagon(turtle, x*3 + ((y % 2 == 0)?1.5:0), y*h0);
    
    return i < s*s*4;
}




////////////////////////////////////////////////////////////////
// Polygon Clipping utility code - Created by Reinder Nijhoff 2019
// https://turtletoy.net/turtle/a5befa1f8d
////////////////////////////////////////////////////////////////

function Polygons() {
	const polygonList = [];
	const Polygon = class {
		constructor() {
			this.cp = [];       // clip path: array of [x,y] pairs
			this.dp = [];       // 2d lines [x0,y0],[x1,y1] to draw
			this.aabb = [];     // AABB bounding box
		}
		addPoints(...points) {
		    // add point to clip path and update bounding box
		    let xmin = 1e5, xmax = -1e5, ymin = 1e5, ymax = -1e5;
			(this.cp = [...this.cp, ...points]).forEach( p => {
				xmin = Math.min(xmin, p[0]), xmax = Math.max(xmax, p[0]);
				ymin = Math.min(ymin, p[1]), ymax = Math.max(ymax, p[1]);
			});
		    this.aabb = [(xmin+xmax)/2, (ymin+ymax)/2, (xmax-xmin)/2, (ymax-ymin)/2];
		}
		addSegments(...points) {
		    // add segments (each a pair of points)
		    points.forEach(p => this.dp.push(p));
		}
		addOutline() {
			for (let i = 0, l = this.cp.length; i < l; i++) {
				this.dp.push(this.cp[i], this.cp[(i + 1) % l]);
			}
		}
		draw(t) {
			for (let i = 0, l = this.dp.length; i < l; i+=2) {
				t.jump(this.dp[i]), t.goto(this.dp[i + 1]);
			}
		}
		addHatching(a, d) {
			const tp = new Polygon();
			tp.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);
			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 = 0.5; i < 150 / d; i++) {
				tp.dp.push([dx * i + cy,   dy * i - cx], [dx * i - cy,   dy * i + cx]);
				tp.dp.push([-dx * i + cy, -dy * i - cx], [-dx * i - cy, -dy * i + cx]);
			}
			tp.boolean(this, false);
			this.dp = [...this.dp, ...tp.dp];
		}
		inside(p) {
			let int = 0; // find number of i ntersection points from p to far away
			for (let i = 0, l = this.cp.length; i < l; i++) {
				if (this.segment_intersect(p, [0.1, -1000], this.cp[i], this.cp[(i + 1) % l])) {
					int++;
				}
			}
			return int & 1; // if even your outside
		}
		boolean(p, diff = true) {
		    // bouding box optimization by ge1doot.
		    if (Math.abs(this.aabb[0] - p.aabb[0]) - (p.aabb[2] + this.aabb[2]) >= 0 &&
				Math.abs(this.aabb[1] - p.aabb[1]) - (p.aabb[3] + this.aabb[3]) >= 0) return this.dp.length > 0;
				
			// polygon diff algorithm (narrow phase)
			const ndp = [];
			for (let i = 0, l = this.dp.length; i < l; i+=2) {
				const ls0 = this.dp[i];
				const ls1 = this.dp[i + 1];
				// find all intersections with clip path
				const int = [];
				for (let j = 0, cl = p.cp.length; j < cl; j++) {
					const pint = this.segment_intersect(ls0, ls1, p.cp[j], p.cp[(j + 1) % cl]);
					if (pint !== false) {
						int.push(pint);
					}
				}
				if (int.length === 0) {
					// 0 intersections, inside or outside?
					if (diff === !p.inside(ls0)) {
						ndp.push(ls0, ls1);
					}
				} else {
					int.push(ls0, ls1);
					// order intersection points on line ls.p1 to ls.p2
					const cmpx = ls1[0] - ls0[0];
					const cmpy = ls1[1] - ls0[1];
					int.sort( (a,b) =>  (a[0] - ls0[0]) * cmpx + (a[1] - ls0[1]) * cmpy - 
					                    (b[0] - ls0[0]) * cmpx - (b[1] - ls0[1]) * cmpy);
					 
					for (let j = 0; j < int.length - 1; j++) {
						if ((int[j][0] - int[j+1][0])**2 + (int[j][1] - int[j+1][1])**2 >= 0.001) {
							if (diff === !p.inside([(int[j][0]+int[j+1][0])/2,(int[j][1]+int[j+1][1])/2])) {
								ndp.push(int[j], int[j+1]);
							}
						}
					}
				}
			}
			return (this.dp = ndp).length > 0;
		}
		//port of http://paulbourke.net/geometry/pointlineplane/Helpers.cs
		segment_intersect(l1p1, l1p2, l2p1, l2p2) {
			const d   = (l2p2[1] - l2p1[1]) * (l1p2[0] - l1p1[0]) - (l2p2[0] - l2p1[0]) * (l1p2[1] - l1p1[1]);
			if (d === 0) return false;
			const n_a = (l2p2[0] - l2p1[0]) * (l1p1[1] - l2p1[1]) - (l2p2[1] - l2p1[1]) * (l1p1[0] - l2p1[0]);
			const n_b = (l1p2[0] - l1p1[0]) * (l1p1[1] - l2p1[1]) - (l1p2[1] - l1p1[1]) * (l1p1[0] - l2p1[0]);
			const ua = n_a / d;
			const ub = n_b / d;
			if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) {
				return [l1p1[0] + ua * (l1p2[0] - l1p1[0]), l1p1[1] + ua * (l1p2[1] - l1p1[1])];
			}
			return false;
		}
	};
	return {
		list: () => polygonList,
		create: () => new Polygon(),
		draw: (turtle, p, addToVisList=true) => {
			for (let j = 0; j < polygonList.length && p.boolean(polygonList[j]); j++);
			p.draw(turtle);
			if (addToVisList) polygonList.push(p);
		}
	};
}