JSFiddle - React, Tailwind, and code Playground
by szivak009
JavaScript
/*
* Dynamic quadtree
*
* Items are stored in nodes. Nodes in eachother. Nodes have a root they start from called root node.
* Every node contains items. If there are too much items in one, nodes are divided to 4 subnodes and the
* items moved into them.
*
* Objects added to the tree represented as an item class. A list of all items stored in the root
* node. Every item has a ref variable what is used for storing reference to the original object.
* The class also has a nodeRef variable what references to the container node.
*
*/
/* is_boundary, limit, */
function QuadTree(obj) {
/* Does it contain boundaries instead of points? */
this.is_boundary = !!obj.is_boundary;
/* After how many items should a node get subdivided */
var limit = obj.limit || 4;
/* How many levels can a tree contain */
var maxLevels = obj.maxLevels || 4;
this.bounds = obj.bounds || {x:0, y:0, w:100, h:100};
var TOP_LEFT = 0;
var TOP_RIGHT = 1;
var BOTTOM_LEFT = 2;
var BOTTOM_RIGHT = 3;
/* obj: { bounds : {x,y,w,h}, level :0, }*/
function node(obj) {
this.level = !!obj.level ? obj.level : 0;
this._bounds = obj.bounds;
this._subdivided = false;
this._items = [];
this._nodes = [];
/* Insert a new item to the node */
this.insert = function(item) {
item.refNode = this;
if( (this._items.length+1) > limit) {
this.subdivide();
this._items.length = 0;
}
if(this._subdivided) {
var index = this.findNodeIndex(item);
this._nodes[index].insert(item);
return;
}
this._items.push(item);
}
this.retrieve = function() {
}
this.subdivide = function() {
...