UNPKG

@timohausmann/quadtree-ts

Version:
3 lines (2 loc) 2.74 kB
/* https://github.com/timohausmann/quadtree-ts.git v2.3.0 */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Quadtree=e()}(this,function(){"use strict";return Object.assign(class{constructor(t,e=0){if(this.bounds={x:t.x||0,y:t.y||0,width:t.width,height:t.height},this.maxObjects="number"==typeof t.maxObjects?t.maxObjects:10,this.minLevels="number"==typeof t.minLevels?t.minLevels:0,this.maxLevels="number"==typeof t.maxLevels?t.maxLevels:4,this.level=e,this.minLevels>this.maxLevels)throw new Error(`minLevels (${this.minLevels}) must be less than maxLevels (${this.maxLevels})`);this.objects=[],this.nodes=[],this.level<this.minLevels&&this.split()}getIndex(t){return t.qtIndex(this.bounds)}split(){const t=this.level+1,e=this.bounds.width/2,s=this.bounds.height/2,i=this.bounds.x,h=this.bounds.y,n=[{x:i+e,y:h},{x:i,y:h},{x:i,y:h+s},{x:i+e,y:h+s}],o=this.constructor;for(let i=0;i<4;i++)this.nodes[i]=new o({x:n[i].x,y:n[i].y,width:e,height:s,maxObjects:this.maxObjects,minLevels:this.minLevels,maxLevels:this.maxLevels},t)}insert(t){if(this.nodes.length){const e=this.getIndex(t);for(let s=0;s<e.length;s++)this.nodes[e[s]].insert(t);return}if(this.objects.push(t),this.objects.length>this.maxObjects&&this.level<this.maxLevels){this.split();for(let t=0;t<this.objects.length;t++){const e=this.getIndex(this.objects[t]);for(let s=0;s<e.length;s++)this.nodes[e[s]].insert(this.objects[t])}this.objects=[]}}retrieve(t){const e=this.getIndex(t);let s=this.objects;if(this.nodes.length)for(let i=0;i<e.length;i++)s=s.concat(this.nodes[e[i]].retrieve(t));return 0===this.level?Array.from(new Set(s)):s}remove(t,e=!1){const s=this.objects.indexOf(t);s>-1&&this.objects.splice(s,1);for(let e=0;e<this.nodes.length;e++)this.nodes[e].remove(t);return 0!==this.level||e||this.join(),-1!==s}update(t,e=!1){this.remove(t,e),this.insert(t)}join(){let t=Array.from(this.objects);for(let e=0;e<this.nodes.length;e++){const s=this.nodes[e].join();t=t.concat(s)}const e=Array.from(new Set(t));if(e.length<=this.maxObjects&&this.level>=this.minLevels){this.objects=e;for(let t=0;t<this.nodes.length;t++)this.nodes[t].objects=[];this.nodes=[]}return t}clear(){this.objects=[];for(let t=0;t<this.nodes.length;t++)this.nodes.length&&this.nodes[t].clear();this.level>=this.minLevels&&(this.nodes=[])}},{Rectangle:class{constructor(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this.data=t.data}qtIndex(t){const e=[],s=t.x+t.width/2,i=t.y+t.height/2,h=this.y<i,n=this.x<s,o=this.x+this.width>s,l=this.y+this.height>i;return h&&o&&e.push(0),n&&h&&e.push(1),n&&l&&e.push(2),o&&l&&e.push(3),e}}})});