Signed Distance Fields WIP

Rendering SDFs in canvas + Basic libraries WORK IN PROGRESS

by MisterSirCode

HTML

<canvas class="mainObject"></canvas>

CSS

* {
	overflow: hidden;
	padding: 0;
	margin: 0;
}

/* .mainObject {
	border: 1px solid black;
} */

JavaScript

const cvs = document.querySelector('.mainObject');

Math.clamp = function(val, min, max) {
	return Math.min(Math.max(val, min), max);
}

Math.lerp = function(start, end, fac) {
	return (1 - fac) * start + fac * end;
}

const filters = {
  "gsn": [1, 2, 1, 2, 4, 2, 1, 2, 1]
};

class Vector {
	constructor(x, y, z) {
		this.x = x;
		this.y = y;
		this.z = z || 0;
	}
	
	get length() {
		return Math.cbrt(this.x ** 2 + this.y ** 2 + this.z ** 2);
	}
	
	abs(vec) {
		if (typeof vec == "number")
			this.x = this.y = this.z = Math.abs(vec);
		else {
			this.x = Math.abs(this.x);
			this.y = Math.abs(this.y);
			this.z = Math.abs(this.z);
		}
		return this;
	}
	
	add(vec) {
		if (typeof vec == "number") {
			this.x += vec;
			this.y += vec;
			this.z += vec;
		} else {
			this.x += vec.x;
			this.y += vec.y;
			this.z += vec.z;
		}
		return this;
	}
	
	sub(vec) {
		if (typeof vec == "number") {
			this.x -= vec;
			this.y -= vec;
			this.z -= vec;
		} else {
			this.x -= vec.x;
			this.y -= vec.y;
			this.z -= vec.z;
		}
		return this;
	}
	
	div(vec) {
		if (typeof vec == "number") {
			this.x /= vec;
			this.y /= vec;
			this.z /= vec;
		} else {
			this.x /= vec.x;
			this.y /= vec.y;
			this.z /= vec.z;
		}
		return this;
	}
	
	mul(vec) {
		if (typeof vec == "number") {
			this.x *= vec;
			this.y *= vec;
			this.z *= vec;
		} else {
			this.x *= vec.x;
			this.y *= vec.y;
			this.z *= vec.z;
		}
		return this;
	}
	
	max(vec) {
		if (typeof vec == "number") {
			this.x = Math.max(this.x, vec);
			this.y = Math.max(this.y, vec);
			this.z = Math.max(this.z, vec);
		} else {
			this.x = Math.max(this.x, vec.x);
			this.y = Math.max(this.y, vec.y);
			this.z = Math.max(this.z, vec.z);
		}
		return this;
	}
	
	get copy() {
		return new Vector(this.x, this.y, this.z);
	}
}

const SDF = {
	sphere: (map, radius) => { 
		// These returners send an SDF activator 
		// (simply call it as a function, input renderer coords as Vector)
		return (pos) => (pos.sub(map)).length -...