Initial contact

Initial contact

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(0.6);
const turtle = new Turtle();
turtle.penup();
const polygons = Polygons();
const cube = [];
///////////////////////////////////
const ax = Math.random() - 0.5;
const ay = Math.random() - 0.5;
const fov = 250;
const zoom = 0.2;
///////////////////////////////////
const angle = {
	cx: Math.cos(ax),
    sx: Math.sin(ax),
    cy: Math.cos(ay),
    sy: Math.sin(ay)
}
const Point = class {
    constructor (x, y, z) {
		this.x = x;
		this.y = y;
		this.z = z;
		this.xp = 0;
		this.yp = 0;
		this.scale = 0;
	}
    project (cube, angle) {
		const x = this.x;
		const y = this.y;
		const z = this.z;
		const xy = angle.cx * y - angle.sx * z;
		const xz = angle.sx * y + angle.cx * z;
		const yz = angle.cy * xz - angle.sy * x;
		const yx = angle.sy * xz + angle.cy * x;
		this.scale = fov / (fov + yz);
		this.xp = yx * this.scale * zoom;
		this.yp = xy * this.scale * zoom;
		if (yz < -fov) cube.visible = false;
	}
};
const Cube = class {
    constructor (x, y, z, w, h, p) {
        this.visible = true;
		this.coord = [
			new Point(x - w, y - h, z),
			new Point(x + w, y - h, z),
			new Point(x + w, y + h, z),
			new Point(x - w, y + h, z),
			new Point(x - w, y - h, z + p),
			new Point(x + w, y - h, z + p),
			new Point(x + w, y + h, z + p),
			new Point(x - w, y + h, z + p)
		];
		const c = this.coord;
		this.faces = [
			[c[0], c[1], c[2], c[3], 0],
			[c[0], c[4], c[5], c[1], 0],
			[c[3], c[2], c[6], c[7], 0],
			[c[0], c[3], c[7], c[4], 1],
			[c[1], c[5], c[6], c[2], 1],
			[c[5], c[4], c[7], c[6], 0]
		];
	}
    project () {
		for (let i = 0; i < 8; i++) {
			this.coord[i].project(this, angle);
		}
		for (let f = 0; f < 6; f++) {
			const p = this.faces[f];
			if (this.visible && ((p[1].yp - p[0].yp) / (p[1].xp - p[0].xp) < (p[2].yp - p[0].yp) / (p[2].xp - p[0].xp) ^ p[0].xp < p[1].xp == p[0].xp > p[2].xp)) {
    			const poly = polygons.create();
    			poly.addPoints([p[0].xp, p[0].yp], [p[1].xp, p[1].yp], [p[2].xp, p[2].yp], [p[3].xp, p[3].yp]);
        		if (p[4]) {
        		    const a = Math.atan2(-p[0].yp + p[1].yp, p[0].xp - p[1].xp);
        		    poly.addHatching(a, Math.min(1, Math.max(0.1, p[0].scale * 0.1)));
        		}
        		poly.addOutline(0);
        		polygons.draw(turtle, poly);
			}
		}
	}
};
// create cubes structure
const r = (d0, d1) => Math.round(Math.random() * (d1 - d0) + d0);
let w = 50;
for (let z = 400; z > -400; z -= 20) {
	cube.push(
		new Cube(
			r(-w, w), r(-w, w), z,
			r(2, 30), r(2, 30), r(2, 180)
		)
	);
	if (z > -100 && z < 100) {
		for (let i = 0; i < 4; i++) {
			cube.push(
				new Cube(
					r(-400, 400), r(-w, w), z,
					r(2, 80), r(2, 30), r(2, 30)
				)
			);
			cube.push(
				new Cube(
					r(-w, w), r(-400, 400), z,
					r(2, 30), r(2, 80), r(2, 30)
				)
			);
		}
	}
}
cube.forEach(c => c.project());

////////////////////////////////////////////////////////////////
// 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) {
    	    a += Math.PI / 2;
            const tp = new Polygon();
            const x = this.aabb[0], y = this.aabb[1];
            const w = this.aabb[2], h = this.aabb[3];
            const l = Math.sqrt((w * 2) ** 2 + (h * 2) ** 2) * 0.5;
            tp.cp.push([x - w, y - h], [x + w, y - h], [x + w, y + h], [x - w, y + h]);
            const cx = Math.sin(a) * l, cy = Math.cos(a) * l;
            let px = x - Math.cos(a) * l;
            let py = y - Math.sin(a) * l;
            for (let i = 0; i < l * 2; i += d) {
                tp.dp.push([px + cx, py - cy], [px - cx, py + cy]);
                px += Math.cos(a) * d;
                py += Math.sin(a) * d;
            }
            tp.boolean(this, false);
            for (const dp of tp.dp) this.dp.push(dp);
    	}
		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.001) 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(t, 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(t);
				polygonList.push(p);
			}
		}
	};
}