(function(){ function clamp(n,a,b){ return n v.a) { return (this.a < v.b && v.b <= this.b) || (v.a < this.b && this.b <= v.b) } } vec2.prototype.overlaps = function(v){ if (this.a == v.a || this.b == v.b) { return true } if (this.a < v.a) { return (v.a < this.b && this.b < v.b) || (this.a < v.b && v.b < this.b) } else if (v.a < this.a) { return (this.a < v.b && v.b < this.b) || (v.a < this.b && this.b < v.b) } } vec2.prototype.adjacent = function(v){ if (this.a == v.a || this.b == v.b || this.a == v.b || this.b == v.a) { return true } return false } vec2.prototype.union = function(v){ if (this.intersects(v)) { return new vec2( Math.min(this.a,v.a), Math.max(this.b, v.b) ) } } vec2.prototype.intersection = function(v){ if (this.intersects(v)) { return new vec2( Math.max(this.a,v.a), Math.min(this.b, v.b) ) } } // given two vectors, test how they overlap // return the set of overlapping segments in the initial vector, labelled with sides vec2.prototype.split = function(v, left, right){ var intervals = [], _len if (this.eq(v)) { intervals.push([ new vec2( this.a, this.b ), left | right ]) } // a---A===b---B (rightways overlap) else if (this.contains(v.a) && v.contains(this.b)) { intervals.push([ new vec2( this.a, v.a ), left ]) intervals.push([ new vec2( v.a, this.b ), right ]) } // A---a===B---b (leftways overlap) else if (v.contains(this.a) && this.contains(v.b)) { intervals.push([ new vec2( this.a, v.b ), left ]) intervals.push([ new vec2( v.b, this.b ), right ]) } // a---A===B---b (contains v) else if (this.contains(v.a) && this.contains(v.b)) { intervals.push([ new vec2( this.a, v.a ), left ]) intervals.push([ new vec2( v.a, v.b ), 0 ]) intervals.push([ new vec2( v.b, this.b ), right ]) } // A---a===b---B (contained in v) else { // if (v.contains(this.a) && v.contains(v.b)) { intervals.push([ new vec2( this.a, this.b ), left | right ]) } // cull empty vectors _len = intervals.length if (_len > 1) { if (intervals[0][0].magnitude() == 0) { intervals[1][1] |= intervals[0][1] intervals.shift() } else if (intervals[_len-1][0].magnitude() == 0) { intervals[_len-2][1] |= intervals[_len-1][1] intervals.pop() } } return intervals } vec2.prototype.toString = function(){ return "[" + Math.round(this.a) + " " + Math.round(this.b) + "]" } vec2.prototype.exactString = function(){ return "[" + this.a + " " + this.b + "]" } vec2.prototype.serialize = function(){ return [ Math.round(this.a), Math.round(this.b) ] } vec2.prototype.deserialize = function(data){ this.a = data[0] this.b = data[1] } vec2.prototype.quantize = function(n){ n = n || 10 this.a = quantize(this.a, n) this.b = quantize(this.b, n) } if ('window' in this) { window.vec2 = vec2 } else { module.exports = vec2 } })()