Cipal

Adapted from a CFDG program contextfreeart.org/gallery2/#design/276
Cipal by Ferma, April 30th, 2006

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);
// Global code will be evaluated once.
const turtle = new Turtle();
const polygons = Polygons();
turtle.penup();
/////////////////////////////////////////////////////
const Mat2D = class {
    constructor (m) { this.m = m; }
    rotate (v) {
    	const rad = Math.PI * v / 180;
    	const cos = Math.cos(rad);
    	const sin = Math.sin(rad);
    	return new Mat2D([
    		cos * this.m[0] + sin * this.m[2],
    		cos * this.m[1] + sin * this.m[3],
    		cos * this.m[2] - sin * this.m[0],
    		cos * this.m[3] - sin * this.m[1],
    		this.m[4],
    		this.m[5]
    	]);
    } 
    translate (x, y = 0) {
    	return new Mat2D([
    		this.m[0],
    		this.m[1],
    		this.m[2],
    		this.m[3],
    		this.m[4] + x * this.m[0] + y * this.m[2],
    		this.m[5] + x * this.m[1] + y * this.m[3]
    	]);
    }
    scale (x = 1, y = x) {
        return new Mat2D([
    		this.m[0] * x,
    		this.m[1] * x,
    		this.m[2] * y,
    		this.m[3] * y,
    		this.m[4],
    		this.m[5]
    	]);
	}
	flip (v) {
		const rad = Math.PI * v / 180;
		const x = Math.cos(rad);
		const y = Math.sin(rad);
		const n = 1 / (x * x + y * y);
		const b00 = (x * x - y * y) / n;
		const b01 = 2 * x * y / n;
		const b10 = 2 * x * y / n;
		const b11 = (y * y - x * x) / n;
		return new Mat2D([
	        b00 * this.m[0] + b01 * this.m[2],
		    b00 * this.m[1] + b01 * this.m[3],
		    b10 * this.m[0] + b11 * this.m[2],
		    b10 * this.m[1] + b11 * this.m[3],
		    this.m[4],
		    this.m[5]
        ]);
	}
	tooSmall () {
    	const x = this.m[0] * this.m[0] + this.m[1] * this.m[1];
    	const y = this.m[2] * this.m[2] + this.m[3] * this.m[3];
    	return x < minSize || y < minSize;
    }
    transform (x, y) {
		const m0 = this.m[0] * zoom;
		const m1 = this.m[1] * zoom;
		const m2 = this.m[2] * zoom;
		const m3 = this.m[3] * zoom;
		const m4 = this.m[4] * zoom - ox;
		const m5 = this.m[5] * zoom - oy;
		return [
            m0 * x + m2 * y + m4, 
            m1 * x + m3 * y + m5
		];
	}
	boundingBox (box) {
        const p0 = this.transform(-0.5, -0.5);
        const p1 = this.transform(0.5, -0.5);
        const p2 = this.transform(0.5, 0.5);
        const p3 = this.transform(-0.5, 0.5);
        const minx = Math.min(p0[0], p1[0], p2[0], p3[0]);
        const maxx = Math.max(p0[0], p1[0], p2[0], p3[0]);
        const miny = Math.min(p0[1], p1[1], p2[1], p3[1]);
        const maxy = Math.max(p0[1], p1[1], p2[1], p3[1]);
    	if (minx < box[0]) box[0] = minx; else if (maxx > box[2]) box[2] = maxx;
    	if (miny < box[1]) box[1] = miny; else if (maxy > box[3]) box[3] = maxy;
    }
};
///////////////////////////////////////////////////////
const minSize = 0.01;
const shapes =  [];
let zoom = 1, ox = 0, oy = 0;
const box = [100, 100, -100, -100];
const rect = (m, a = 0, s = 0) => {
	m.boundingBox(box);
	m.m[6] = a;
	m.m[7] = s;
	shapes.push(m);
};
const draw = m => {
	const p = polygons.create();
	const p0 = m.transform(-0.5, -0.5);
	const p1 = m.transform(0.5, -0.5);
	const p2 = m.transform(0.5, 0.5);
	const p3 = m.transform(-0.5, 0.5);
	p.addPoints(p0, p1, p2, p3);
	p.addOutline(0);
	if (m.m[7] !== 0) p.addHatching(m.m[6], m.m[7]);
	polygons.draw(turtle, p);
};
const scale = (w, h, margin = 0.9) => {
	zoom = Math.min(
		margin * w / (box[2] - box[0]),
		margin * h / (box[3] - box[1])
	);
	ox = (box[0] + box[2]) * 0.5 * zoom;
	oy = (box[3] + box[1]) * 0.5 * zoom;
};
////////////////////////////////////////////////////
const branch = m => {
    if (m.tooSmall() === true) return;
    const r = Math.random() * 12.1;
	switch (true) {
		case r <= 0.4:
		    branch(m.scale(0.5).rotate(5));
		    return branch(m.scale(0.97).rotate(-0.9));
	    case r <= 1.3:
	        return branch(m.flip(50));
        case r <= 2.3:
	        return branch(m.flip(20));
	    case r <= 4.1:
            return branch(m.flip(99));
	    case r <= 8.1:
            rect(m);
            return branch(m.translate(0, -1).scale(0.99).rotate(-1));
	    default:
            rect(m, Math.atan2(-m.m[3], m.m[2]), 0.1);
            return branch(m.translate(0, -0.5).rotate(-1));
	}
}
/////////////////// render scene //////////////////////////////
branch(new Mat2D([1, 0, 0, -1, 0, 0]));
scale(200, 200, 0.95);

// The walk function will be called until it returns false.
function walk(i) {
	const m = shapes.pop();
	if (!m) return false;
	draw(m);
	return true;
}

////////////////////////////////////////////////////////////////
// reinder's occlusion code parts from "Cubic space division #2"
// Optimizations and code clean-up by ge1doot
////////////////////////////////////////////////////////////////

function Polygons() {
	const polygonList = [];
	const linesDrawn = [];
	const Polygon = class {
		constructor() {
			this.cp = [];       // clip path: array of [x,y] pairs
			this.dp = [];       // 2d line to draw
			this.aabb = [];     // AABB bounding box
		}
		addPoints(...points) {
		    for (let i = 0; i < points.length; i++) this.cp.push(points[i]);
		    this.aabb = this.AABB();
		}
		addOutline(s = 0) {
			for (let i = s, l = this.cp.length; i < l; i++) {
				this.dp.push(this.cp[i], this.cp[(i + 1) % l]);
			}
		}
		draw(t) {
			if (this.dp.length === 0) return;
			for (let i = 0, l = this.dp.length; i < l; i+=2) {
			    const d0 = this.dp[i];
				const d1 = this.dp[i + 1];
				const line_hash =
					Math.min(d0[0], d1[0]).toFixed(2) + "-" +
					Math.max(d0[0], d1[0]).toFixed(2) + "-" +
					Math.min(d0[1], d1[1]).toFixed(2) + "-" +
					Math.max(d0[1], d1[1]).toFixed(2);
				if (!linesDrawn[line_hash]) {
					t.penup();
					t.goto(d0);
					t.pendown();
					t.goto(d1);
					linesDrawn[line_hash] = true;
				}
			}
		}
		AABB() {
			let xmin = 2000;
			let xmax = -2000;
			let ymin = 2000;
			let ymax = -2000;
			for (let i = 0, l = this.cp.length; i < l; i++) {
				const x = this.cp[i][0];
				const y = this.cp[i][1];
				if (x < xmin) xmin = x;
				if (x > xmax) xmax = x;
				if (y < ymin) ymin = y;
				if (y > ymax) ymax = y;
			}
			// Bounding box: center x, center y, half w, half h
			return [
				(xmin + xmax) * 0.5,
				(ymin + ymax) * 0.5,
				(xmax - xmin) * 0.5,
				(ymax - ymin) * 0.5
			];
		}
		addHatching(a, d) {
			const tp = new Polygon();
			tp.cp.push(
			    [this.aabb[0] - this.aabb[2], this.aabb[1] - this.aabb[3]],
			    [this.aabb[0] + this.aabb[2], this.aabb[1] - this.aabb[3]],
			    [this.aabb[0] + this.aabb[2], this.aabb[1] + this.aabb[3]],
			    [this.aabb[0] - this.aabb[2], this.aabb[1] + this.aabb[3]]
			);
			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);
			for (let i = 0, l = tp.dp.length; i < l; i++) this.dp.push(tp.dp[i]);
		}
		inside(p) {
			// find number of i ntersection points from p to far away
			const p1 = [0.1, -1000];
			let int = 0;
			for (let i = 0, l = this.cp.length; i < l; i++) {
			    if ( (p[0]-this.cp[i][0])**2 +  (p[1]-this.cp[i][1])**2 <= 0.01) return false;
				if (
					this.vec2_find_segment_intersect(
						p,
						p1,
						this.cp[i],
						this.cp[(i + 1) % l]
					) !== false
				) {
					int++;
				}
			}
			return int & 1;
		}
		boolean(p, diff = true) {
			// polygon diff algorithm
			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.vec2_find_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];
					for (let i = 0, len = int.length; i < len; i++) {
					    let j = i;
					    const item = int[j];
						for (
							const db = (item[0] - ls0[0]) * cmpx + (item[1] - ls0[1]) * cmpy;
							j > 0 && (int[j - 1][0] - ls0[0]) * cmpx + (int[j - 1][1] - ls0[1]) * cmpy < db;
							j--
						) int[j] = int[j - 1];
						int[j] = item;
					}
					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.01
						) {
							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]);
							}
						}
					}
				}
			}
			this.dp = ndp;
			return this.dp.length > 0;
		}
		//port of http://paulbourke.net/geometry/pointlineplane/Helpers.cs
		vec2_find_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 {
		create() {
			return new Polygon();
		},
		draw(turtle, p) {
			let vis = true;
			for (let j = 0; j < polygonList.length; j++) {
                const p1 = polygonList[j];
				// AABB overlapping test - still O(N2) but very fast
				if (
					Math.abs(p1.aabb[0] - p.aabb[0]) - (p.aabb[2] + p1.aabb[2]) < 0 &&
					Math.abs(p1.aabb[1] - p.aabb[1]) - (p.aabb[3] + p1.aabb[3]) < 0
				) {
					if (p.boolean(p1) === false) {
						vis = false;
						break;
					}
				}
			}
			if (vis) {
				p.draw(turtle);
				polygonList.push(p);
			}
		}
	};
}