Torus

A quite famous torus.
I have combined code from @flockaroo (turtletoy.net/turtle/2dc4806767) and the cleaned-up version of my own occlusion code by @ge1doot (turtletoy.net/turtle/c2cf454d80).

Log in to post a comment.

// Torus. Created by Reinder Nijhoff 2019
// @reindernijhoff
//
// https://turtletoy.net/turtle/90e6288a6b
//
// I have combined code from @flockaroo (https://turtletoy.net/turtle/2dc4806767)
// and the cleaned up version of my own occlusion code by @ge1doot
// (https://turtletoy.net/turtle/c2cf454d80).
//

const turtle = new Turtle();
const polygons = Polygons();
const faces = [];
const nth = 120;
const nph = 40;
const radius_0 = 70;
const radius_1 = 55;
const radius_2 = 55;
const proj_xy_scale = 80;
const camera_z = 65;
const near = 5;

class Face {
    constructor (p0, p1, p2, p3, d) {
        this.p0 = p0;
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
        this.dark = d;
    }
	draw () {
		const p = polygons.create();
		p.addPoints(this.p0, this.p1, this.p3, this.p2);
		p.addSegments(
		    this.p0, this.p1,
		    this.p2, this.p3
	    );
		if (this.dark) {
			p.addHatching(-Math.PI / 4, 1);
		}
		polygons.draw(turtle, p);
	}
};

for (let i = 0; i < nth; i++) {
	for (let j = 0; j < nph; j++) {
		let p0 = getTorusPoint(i, j, radius_0, radius_1, radius_2, nph, nth);
		let p1 = getTorusPoint(i + 1, j, radius_0, radius_1, radius_2, nph, nth);
		let p2 = getTorusPoint(i, j + 1, radius_0, radius_1, radius_2, nph, nth);
		let p3 = getTorusPoint(i + 1, j + 1, radius_0, radius_1, radius_2, nph, nth);

		p0 = project(p0);
		p1 = project(p1);
		p2 = project(p2);
		p3 = project(p3);

		if (p0[2] > near && p1[2] > near && p2[2] > near && p3[2] > near) {
			const face = new Face(p0, p1, p2, p3, j & 1);
			faces.push(face);
		}
	}
}

faces.sort((a, b) => a.p0[2] - b.p0[2]);

function walk(i) {
	faces[i].draw();
	return i < faces.length - 1;
}

function project(p) {
	p[1] += camera_z;
	return [p[0] / p[1] * proj_xy_scale, p[2] / p[1] * proj_xy_scale, p[1]];
}

function getTorusPoint(i, j, R, r1, r2, nph, nth) {
	const th = i / nth * Math.PI * 2.0;
	const ph = j / nph * Math.PI * 2.0 + th;
	return [
		(R + r1 * Math.cos(th)) * Math.cos(ph),
		(R + r1 * Math.cos(th)) * Math.sin(ph),
		r2 * Math.sin(th)
	];
}

////////////////////////////////////////////////////////////////
// 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) {
		    points.forEach(p => this.cp.push(p));
		    this.aabb = this.AABB();
		}
		addSegments(...points) {
		    points.forEach(p => this.dp.push(p));
		}
		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], d1 = this.dp[i + 1];
				const line_hash = 'h' +
					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.jump(d0);
					t.goto(d1);
					linesDrawn[line_hash] = true;
				}
			}
		}
		AABB() {
			let xmin = 1e5, xmax = -1e5, ymin = 1e5, ymax = -1e5;
			this.cp.forEach( p => {
				const x = p[0];
				const y = p[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)*.5, (ymin + ymax)*.5, (xmax - xmin)*.5, (ymax - ymin)*.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);
			tp.dp.forEach(dp => this.dp.push(dp));
		}
		inside(p) {
			// find number of i ntersection points from p to far away
			// if even your outside
			const p1 = [0.1, -1000];
			let int = 0;
			for (let i = 0, l = this.cp.length; i < l; i++) {
				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 (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.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 {
		list() {
			return polygonList;
		},
		create() {
			return new Polygon();
		},
		draw(turtle, p, addToVisList=true) {
			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);
				if (addToVisList) polygonList.push(p);
			}
		}
	};
}