Voxel Worlds

Different voxel worlds, rendered using my utility class Voxel Ray Caster.

#voxels

Log in to post a comment.

// Voxel Worlds. Created by Reinder Nijhoff 2020
// @reindernijhoff
//
// https://turtletoy.net/turtle/dba20f00f6
// 

const worldType = 0; // min=0, max=2, step=1 (Cubic Space Division, Cubes, Minecraft)
const cameraFOV = 0.5; // min=0.5, max=2, step=0.05
const addHatching = 1; // min=0, max=1, step=1 (No, Yes)
const drawCubeEdges = 0; // min=0, max=1, step=1 (No, Yes)
const useBarrelDistortion = 1; // min=0, max=1, step=1 (No, Yes)

const ro = [ 43.2, worldType === 2 ? 37 : 40,-41.1]; // camera origin
const ta = [-4, worldType === 2 ? -20 : -4.5,2];     // camera target

const voxelRayCaster = new VoxelRayCaster(ro, ta, worldType === 2 ? 0.1 : 0.3, 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();
}

// The voxel caster will cast rays into a scene that is defined by a function that 
// returns true for all solid cells ([x,y,z]):
function map0(p) {
    const x = Math.abs(p[0]), y = Math.abs(p[1]), z = Math.abs(p[2]);
    return (x%15 === 0 && (y%15 === 0 || z%15 === 0)) || (y%15 === 0 && z%15 === 0) ||
           ((x%15 < 2 || x%15 > 13) && (y%15 < 2 || y%15 > 13) && (z%15 < 2 || z%15 > 13));        
}

function map1(p) {
    const x = Math.abs(p[0]), y = Math.abs(p[1]), z = Math.abs(p[2]);
    return x % 4 == 0 && y % 6 == 0 && z % 8 == 0;       
}

function map2(p) {   
    // find nearest tree position:
    const t = [Math.floor(p[0]/15) * 15 + 7, 0, Math.floor(p[2]/15) * 15 + 7];
    t[0] += Math.floor(Math.sin(t[0]*3.3+t[2])*5);
    t[2] += Math.floor(Math.sin(t[2]*.9+t[0])*5);
    return p[1] < heightFunc(p) || treeFunc(p, t);
}
function treeFunc(p, t) {
    const h = heightFunc(t);
    const trunk = p[0] === t[0] && p[2] === t[2] && p[1] < h + 6;
    const leaves = Math.sqrt((p[0]-t[0])**2 + (p[1]-h-6)**2 + (p[2]-t[2])**2) < 3.5;
    return trunk || leaves;
}
function heightFunc(p) { return Math.sin(p[0]*0.02 - .5)*20 + Math.cos(p[2]*0.03)*20 + 10; }

function walk(i) {
    const tiles = 10;
    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 = voxelRayCaster.collectFaces(
        worldType == 0 ? map0 : worldType == 1 ? map1 : map2, 
        lt, rb, worldType === 2 ? 500 : 2000, 0.3);
    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 VoxelRayCaster(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 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 VoxelRayCaster {
        constructor(ro, ta, cr=0, w=1.5) {
            this.ro = ro;
            this.ta = ta;
            this.w = w;
            this.ca = this.setupCamera(ro, ta, cr);
        }
        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];
        }
        castRay(ro, rd, map, maxSteps) {
        	const ps = ro.map(e => Math.floor(e));
        	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));
        	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 (map(ps)) {
        		    const n = [0,0,0]; n[i] = -rs[i];
        		    return [ps, n];
        		}
        	}
        	return false;
        }
        collectFaces(map, 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, map, 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(map);
                            faces.push(face);
                        }
                    }
                }
            }
            return faces.sort((a, b) => a.dist - b.dist);
        }
    }
    return new VoxelRayCaster(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);
		}
	};
}