1 | (function (factory) {
|
2 | if (typeof module === "object" && typeof module.exports === "object") {
|
3 | var v = factory(require, exports);
|
4 | if (v !== undefined) module.exports = v;
|
5 | }
|
6 | else if (typeof define === "function" && define.amd) {
|
7 | define(["require", "exports", "./Circle", "./Rectangle", "../../Utils/NumberUtils"], factory);
|
8 | }
|
9 | })(function (require, exports) {
|
10 | "use strict";
|
11 | Object.defineProperty(exports, "__esModule", { value: true });
|
12 | exports.QuadTree = void 0;
|
13 | const Circle_1 = require("./Circle");
|
14 | const Rectangle_1 = require("./Rectangle");
|
15 | const NumberUtils_1 = require("../../Utils/NumberUtils");
|
16 | class QuadTree {
|
17 | constructor(rectangle, capacity) {
|
18 | this.rectangle = rectangle;
|
19 | this.capacity = capacity;
|
20 | this._subdivide = () => {
|
21 | const { x, y } = this.rectangle.position, { width, height } = this.rectangle.size, { capacity } = this;
|
22 | for (let i = 0; i < 4; i++) {
|
23 | this._subs.push(new QuadTree(new Rectangle_1.Rectangle(x + (width / 2) * (i % 2), y + (height / 2) * (Math.round(i / 2) - (i % 2)), width / 2, height / 2), capacity));
|
24 | }
|
25 | this._divided = true;
|
26 | };
|
27 | this._points = [];
|
28 | this._divided = false;
|
29 | this._subs = [];
|
30 | }
|
31 | insert(point) {
|
32 | if (!this.rectangle.contains(point.position)) {
|
33 | return false;
|
34 | }
|
35 | if (this._points.length < this.capacity) {
|
36 | this._points.push(point);
|
37 | return true;
|
38 | }
|
39 | if (!this._divided) {
|
40 | this._subdivide();
|
41 | }
|
42 | return this._subs.some((sub) => sub.insert(point));
|
43 | }
|
44 | query(range, check, found) {
|
45 | const res = found || [];
|
46 | if (!range.intersects(this.rectangle)) {
|
47 | return [];
|
48 | }
|
49 | for (const p of this._points) {
|
50 | if (!range.contains(p.position) &&
|
51 | (0, NumberUtils_1.getDistance)(range.position, p.position) > p.particle.getRadius() &&
|
52 | (!check || check(p.particle))) {
|
53 | continue;
|
54 | }
|
55 | res.push(p.particle);
|
56 | }
|
57 | if (this._divided) {
|
58 | for (const sub of this._subs) {
|
59 | sub.query(range, check, res);
|
60 | }
|
61 | }
|
62 | return res;
|
63 | }
|
64 | queryCircle(position, radius, check) {
|
65 | return this.query(new Circle_1.Circle(position.x, position.y, radius), check);
|
66 | }
|
67 | queryRectangle(position, size, check) {
|
68 | return this.query(new Rectangle_1.Rectangle(position.x, position.y, size.width, size.height), check);
|
69 | }
|
70 | }
|
71 | exports.QuadTree = QuadTree;
|
72 | });
|