Menger Sponge

Menger Sponge fractal. I use a slightly modified version of the Voxel Ray Caster to collect all partially visible faces of the fractal. A bounding box is added to speed up rendering a bit.

#voxels #fractal #MengerSponge

Log in to post a comment.

//  Menger Sponge. Created by Reinder Nijhoff 2020
// @reindernijhoff
//
// https://turtletoy.net/turtle/79240332e3
// 

const iterations = 4; // min=1, max=5, step=1
const cameraFOV = 3; // min=0.5, max=3, step=0.05
const cameraDist = 3; // min=.1, max=3, step=0.1
const cameraYRot = 2.5; // min=0, max=3, step=0.01
const cameraXRot = 0.45; // min=0, max=3, step=0.01
const addHatching = 1; // min=0, max=1, step=1 (No, Yes)
const drawCubeEdges = 0; // min=0, max=1, step=1 (No, Yes)
const useBarrelDistortion = 0; // min=0, max=1, step=1 (No, Yes)
const radius = Math.pow(3, iterations) * cameraDist, cosRot = Math.cos(cameraXRot);
const ro = [radius * Math.cos(cameraYRot)*cosRot +.5,Math.sin(cameraXRot)*radius + .5,radius * -Math.sin(cameraYRot)*cosRot+.5]; // camera origin
const ta = [.5,.5,.5];        // camera target

const voxelCaster = new MengerSpongeCaster(ro, ta, 0, cameraFOV);


let turtle;

if (useBarrelDistortion) {
    turtle = new Tortoise();
    function Barrel(b) { return p => { let s = (1+(p[0]**2 + p[1]**2)*b/1e4); return [p[0]*s, p[1]*s]; } }
    function Scale(s) { return p => [p[0]*s, p[1]*s]; }
    turtle.addTransform(Barrel(-0.12));
    turtle.addTransform(Scale(1.1));
} else {
    turtle = new Slowpoke();
}

function walk(i) {
    const tiles = Math.max(1, iterations**2 - 1);
    const x = i % tiles, y = (i/tiles)|0;
    
    const lt = [x*200/tiles-100, y*200/tiles-100];           // Left top of tile
    const rb = [(x+1)*200/tiles-100, (y+1)*200/tiles-100];   // Right bottom of tile
    
    const faces = voxelCaster.collectFaces(lt, rb, Math.pow(3, iterations)*10, Math.pow(0.6, iterations));
    const polys = new Polygons();
    
    // Create a polygon for this tile to clip all faces
    const viewPort = polys.create();    
    viewPort.addPoints(lt, [lt[0], rb[1]], rb, [rb[0], lt[1]]);
    
    faces.forEach(face => {
        const p = polys.create();
        p.addPoints(...face.points);

        if (drawCubeEdges) {
            p.addOutline();
        } else {
            face.edges.forEach((e, i) => e && p.addSegments(p.cp[i], p.cp[(i+1)%4]));
        }

        if (addHatching && Math.abs(face.normal[2]) > .5) {
            p.addHatching(-Math.PI/3, .5);
        }
        
        // Clip face against viewport of this tile
        p.boolean(viewPort, false);
        
        // Draw face
        polys.draw(turtle, p);
    });

    return i < tiles*tiles - 1;
}

////////////////////////////////////////////////////////////////
// Voxel Ray Caster utility code. Created by Reinder Nijhoff 2020
// https://turtletoy.net/turtle/d9ae1fb0bd
// Based on: https://turtletoy.net/turtle/d9ae1fb0bd
////////////////////////////////////////////////////////////////
function MengerSpongeCaster(ro, ta, cr=0, w=1.5) {
    const faceId = (p, n) => p[0].toFixed(0) + '_' + p[1].toFixed(0) + '_' + p[2].toFixed(0)
                           + n[0].toFixed(0) + '_' + n[1].toFixed(0) + '_' + n[2].toFixed(0);
    const neg   = (a) => [-a[0], -a[1], -a[2]];
    const scale = (a,b) => [a[0]*b, a[1]*b, a[2]*b];
    const mul   = (a,b) => [a[0]*b[0], a[1]*b[1], a[2]*b[2]];
    const len   = (a) => Math.sqrt(a[0]**2 + a[1]**2 + a[2]**2);
    const norm  = (a) => scale(a,1/len(a));
    const add   = (a,b) => [a[0]+b[0], a[1]+b[1], a[2]+b[2]];
    const sub   = (a,b) => [a[0]-b[0], a[1]-b[1], a[2]-b[2]];
    const cross = (a,b) => [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]];
    const trans = (a,b) => a.map((e, c) => b[c]*a[0] + b[c+3]*a[1] + b[c+6]*a[2]);
    const transInv = (a,b) => a.map((e, c) => b[c*3+0]*a[0] + b[c*3+1]*a[1] + b[c*3+2]*a[2]);
    
    class VoxelFace {
        constructor(p, n, dist, map) {
            this.id = faceId(p,n);
            
            this.pos = p;
            this.normal = n;
            this.b = [n[1],n[2],n[0]];
            this.t = cross(this.normal, this.b);
            this.dist = dist;
            this.center = add(this.pos, [.5,.5,.5]);
        }
        projectVertex(p, ca) {
            const cp = transInv(p, ca), s = w * 100 / cp[2];
            return [cp[0] * s, cp[1] * -s];
        }
        projectVertices(ro, ca) {
            const nh = scale(this.normal, .5), t=scale(this.t, .5), b=scale(this.b, .5);
            this.points = [add(neg(t), neg(b)), add(t, neg(b)), add(t, b), add(neg(t), b)]
                    .map(c => this.projectVertex(sub(add(add(c, nh), this.center), ro), ca));
        }
        calculateEdges(map) {
            const t=this.t, b=this.b, p=this.pos, n=this.normal;
            this.edges = [neg(b), t, b, neg(t)].map(o => !map(add(p, o)) || map(add(add(p, o), n)));
        }
    }
    class MengerSpongeCaster {
        constructor(ro, ta, cr=0, w=1.5) {
            this.ro = ro;
            this.ta = ta;
            this.w = w;
            this.ca = this.setupCamera(ro, ta, cr);
            this.boxSize = Math.pow(3, iterations) / 2;
        }
        setupCamera(ro, ta, cr) {
        	const cw = norm(sub(ta, ro));
        	const cp = [Math.sin(cr), Math.cos(cr), 0];
        	const cu = norm(cross(cw,cp));
        	const cv =     (cross(cu,cw));
            return [...cu, ...cv, ...cw];
        }
        mengerSponge(p) {
            let x = Math.abs(p[0]), y = Math.abs(p[1]), z = Math.abs(p[2]);
            if (x <= this.boxSize && y <= this.boxSize && z <= this.boxSize) {
                for (let i=0; i<iterations; i++) {
                    if ((x%3 != 0) + (y%3 != 0) + (z%3 != 0) <= 1) return false;
                    x = ((x + 1)/3)|0;
                    y = ((y + 1)/3)|0;
                    z = ((z + 1)/3)|0;
                }
                return true;
            }
            return false;
        }
        castRay(ro, rd, maxSteps) {
        	const ri = rd.map(e => Math.abs(e) > 1e-16 ? 1/e : 1e32);
        	const rs = ri.map(e => Math.sign(e));
        	const ra = ri.map(e => Math.abs(e));
        	
        	// Bounding box check for early return
        	const p1 = sub(mul([-this.boxSize-.5,-this.boxSize-.5,-this.boxSize-.5], ra), mul(ro, ri));
        	const p2 = sub(mul([ this.boxSize+.5, this.boxSize+.5, this.boxSize+.5], ra), mul(ro, ri));
        
        	const t1 = Math.max(Math.max(p1[0], p1[1]), p1[2]);
        	const t2 = Math.min(Math.min(p2[0], p2[1]), p2[2]);
        	
        	if (t2 < 0 || t1 > t2) {
        	    return false;
        	}
        	
        	// move ray to bounding box
        	if (t1 > 1) ro = add(ro, scale(rd, t1-1));
        	
        	const ps = ro.map(e => Math.floor(e));
        	const ds = ps.map((p, i) => (p-ro[i]+.5+.5*rs[i]) * ri[i]);
        	
        	for (let j=0; j<maxSteps; j++) {
        	    const i = ds[0] <= ds[1] && ds[0] <= ds[2] ? 0 : 
        	              ds[1] <= ds[0] && ds[1] <= ds[2] ? 1 : 2;
        		ds[i] += ra[i];
                ps[i] += rs[i];
        		if (this.mengerSponge(ps)) {
        		    const n = [0,0,0]; n[i] = -rs[i];
        		    return [ps, n];
        		}
        	}
        	return false;
        }
        collectFaces(tl=[-100,-100], br=[100,100], maxSteps=200, res=0.25) {
            const faces = [];
            for (let x=tl[0]; x<=br[0]; x+=res) {
                for (let y=tl[1]; y<=br[1]; y+=res) {
                    const rd = trans(norm([x/100, -y/100, this.w]), this.ca);
                    const hit = this.castRay(ro, rd, maxSteps);
                    if (hit) {
                        const id = faceId(hit[0], hit[1]);
                        if (!faces.find(a => a.id === id)) {
                            const face = new VoxelFace(hit[0], hit[1], len(sub(hit[0], this.ro)));
                            face.projectVertices(this.ro, this.ca);
                            face.calculateEdges((p) => this.mengerSponge(p));
                            faces.push(face);
                        }
                    }
                }
            }
            return faces.sort((a, b) => a.dist - b.dist);
        }
    }
    return new MengerSpongeCaster(ro, ta, cr, w);
}

////////////////////////////////////////////////////////////////
// Slowpoke utility code. Created by Reinder Nijhoff 2019
// https://turtletoy.net/turtle/cfe9091ad8
////////////////////////////////////////////////////////////////

function Slowpoke(x, y) {
    const linesDrawn = {};
    class Slowpoke extends Turtle {
        goto(x, y) {
            const p = Array.isArray(x) ? [...x] : [x, y];
            if (this.isdown()) {
                const o = [this.x(), this.y()];
                const h1 = o[0].toFixed(8)+'_'+p[0].toFixed(8)+o[1].toFixed(8)+'_'+p[1].toFixed(8);
                const h2 = p[0].toFixed(8)+'_'+o[0].toFixed(8)+p[1].toFixed(8)+'_'+o[1].toFixed(8);
                if (linesDrawn[h1] || linesDrawn[h2]) {
                    super.up();
                    super.goto(p);
                    super.down();
                    return;
                }
                linesDrawn[h1] = linesDrawn[h2] = true;
            } 
            super.goto(p);
        }
    }
    return new Slowpoke(x,y);
}

////////////////////////////////////////////////////////////////
// Tortoise utility code. Created by Reinder Nijhoff 2019
// https://turtletoy.net/turtle/102cbd7c4d
////////////////////////////////////////////////////////////////

function Tortoise(x, y) {
    class Tortoise extends Turtle {
        constructor(x, y) {
            super(x, y);
            this.ps = Array.isArray(x) ? [...x] : [x || 0, y || 0];
            this.transforms = [];
        }
        addTransform(t) {
            this.transforms.push(t);
            this.jump(this.ps);
            return this;
        }
        applyTransforms(p) {
            if (!this.transforms) return p;
            let pt = [...p];
            this.transforms.map(t => { pt = t(pt); });
            return pt;
        }
        goto(x, y) {
            const p = Array.isArray(x) ? [...x] : [x, y];
            const pt = this.applyTransforms(p);
            if (this.isdown() && (this.pt[0]-pt[0])**2 + (this.pt[1]-pt[1])**2 > 4) {
               this.goto((this.ps[0]+p[0])/2, (this.ps[1]+p[1])/2);
               this.goto(p);
            } else {
                super.goto(pt);
                this.ps = p;
                this.pt = pt;
            }
        }
        position() { return this.ps; }
    }
    return new Tortoise(x,y);
}

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

function Polygons() {
	let   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.13, -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 (diff && 
		        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);
		}
	};
}