From fa7a45db86c71b419f2dd0f059717941db574ce6 Mon Sep 17 00:00:00 2001 From: Wynell <65278392+uWynell@users.noreply.github.com> Date: Sat, 27 Feb 2021 14:06:33 +0300 Subject: [PATCH 1/2] Improve algorithm --- quadtree.js | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/quadtree.js b/quadtree.js index e3cb3ae..2c0eb08 100644 --- a/quadtree.js +++ b/quadtree.js @@ -234,7 +234,7 @@ class QuadTree { this.southeast = new QuadTree(se, this.capacity); let sw = new Rectangle(x - w, y + h, w, h); this.southwest = new QuadTree(sw, this.capacity); - + this.divided = true; } @@ -243,13 +243,16 @@ class QuadTree { return false; } - if (this.points.length < this.capacity) { - this.points.push(point); - return true; - } - if (!this.divided) { + if (this.points.length < this.capacity) { + this.points.push(point); + return true; + } + this.subdivide(); + + let point; + while (point = this.points.shift()) this.insert(point); } return (this.northeast.insert(point) || this.northwest.insert(point) || @@ -265,16 +268,17 @@ class QuadTree { return found; } - for (let p of this.points) { - if (range.contains(p)) { - found.push(p); - } - } if (this.divided) { this.northwest.query(range, found); this.northeast.query(range, found); this.southwest.query(range, found); this.southeast.query(range, found); + } else { + for (let p of this.points) { + if (range.contains(p)) { + found.push(p); + } + } } return found; From 7ad7f212ca507e74a6838a99f01f4873ded3a749 Mon Sep 17 00:00:00 2001 From: Wynell <65278392+uWynell@users.noreply.github.com> Date: Sat, 27 Feb 2021 14:19:09 +0300 Subject: [PATCH 2/2] Fix the bug with the same variable names --- quadtree.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/quadtree.js b/quadtree.js index 2c0eb08..04701a5 100644 --- a/quadtree.js +++ b/quadtree.js @@ -251,8 +251,8 @@ class QuadTree { this.subdivide(); - let point; - while (point = this.points.shift()) this.insert(point); + let p; + while (p = this.points.shift()) this.insert(p); } return (this.northeast.insert(point) || this.northwest.insert(point) ||