Sinova/Collisions

BVH insert issue

Opened this issue · 0 comments

I was getting weird crash with the BVH tree used in this project.

After some research, I realized the issue was caused by my pooling system (which use insert/remove quite intensively). Because one of the object was created through:

const poly = system.createPolygon(200, 5, [[-30, 0], [10, 20]]);
// and not 
const poly = new Polygon(200, 5, [[-30, 0], [10, 20]]);

This API underneath do an .insert() automatically, and my code was doing a second one later.
Double .insert() can completely break the tree and create infinite loop (most of the time in potentials()).

This could be nice to avoid this kind of crash by:

  • preventing this kind of behavior
  • or automatically call remove when a double insert is detected
  • or throw an error.

In my case, even if it's a bit hacky, I just added a check on the _bhv property to prevent it:

	/**
	 * Inserts bodies into the collision system
	 * @param {...Circle|...Polygon|...Point} bodies
	 */
	insert(...bodies) {
		for(const body of bodies) {
			if (body._bvh) {
				continue;
			}
			this._bvh.insert(body, false);
		}

		return this;
	}

	/**
	 * Removes bodies from the collision system
	 * @param {...Circle|...Polygon|...Point} bodies
	 */
	remove(...bodies) {
		for(const body of bodies) {
			if (!body._bvh) {
				continue;
			}
			this._bvh.remove(body, false);
		}

		return this;
	}

Apparently there is already an error to prevent a body to be in two different tree:

throw new Error('Body belongs to another collision system');