Code Monkey home page Code Monkey logo

quadtree-js's Introduction

quadtree-js

This is a JavaScript Quadtree implementation based on the Java Methods described on gamedevelopment.tutsplus.com by Steven Lambert:

Many games require the use of collision detection algorithms to determine when two objects have collided, but these algorithms are often expensive operations and can greatly slow down a game. One way to speed things up is to reduce the number of checks that have to be made. Two objects that are at opposite ends of the screen can not possibly collide, so there is no need to check for a collision between them. This is where a quadtree comes into play.

This implementation can store and retrieve rectangles in a recursive 2D Quadtree. Every Quadtree node can hold a maximum number of objects before it splits into four subnodes. Objects are only stored on leaf nodes (the lowest level). If an object overlaps into multiple leaf nodes, a reference to the object is stored in each node.

Only 639 Bytes! (Compressed + Gzipped)


checkout "2.0": quadtree-ts with multiple primitives, Typescript and more.


Demos

Install

Install this module via npm and import or require it:

npm i -D @timohausmann/quadtree-js
import Quadtree from '@timohausmann/quadtree-js';
const Quadtree = require('@timohausmann/quadtree-js');

Alternatively, download the source and include it the old-fashioned way:

<script src="quadtree.min.js"></script>

Or use an awesome CDN like jsdelivr or unpkg:

<script src="https://cdn.jsdelivr.net/npm/@timohausmann/quadtree-js/quadtree.min.js"></script>
<script src="https://unpkg.com/@timohausmann/quadtree-js/quadtree.min.js"></script>

How to use

Create a new Quadtree (with default values for max_objects (10) and max_levels (4)).

var myTree = new Quadtree({
    x: 0,
    y: 0,
    width: 400,
    height: 300
});

MAX_OBJECTS defines how many objects a node can hold before it splits and MAX_LEVELS defines the deepest level subnode.

If you want to specify max_objects and max_levels on your own, you can pass them as a 2nd and 3rd argument. I recommend using low values for max_levels because each level will quadruple the possible amount of nodes. Using lower values for max_levels increases performance but may return more candidates. Finetuning these values depends on your 2D space, the amount and size of the objects and your retrieving areas.

var myTree = new Quadtree({
    x: 0,
    y: 0,
    width: 800,
    height: 600
}, 15, 6);

Insert an element in the Quadtree

myTree.insert({
    x: 100,
    y: 100,
    width: 100,
    height: 100
});

Retrieve elements from nodes that intersect with the given bounds

var elements = myTree.retrieve({
    x: 150,
    y: 150,
    width: 100,
    height: 100
});

Clear the Quadtree

myTree.clear();

Check out the examples for more information.

Typescript

Type definitions are included. Inserted objects need to conform to the Quadtree.Rect interface.

import Quadtree, { Rect } from '@timohausmann/quadtree-js';

/*
 * interface Rect {
 *     x: number
 *     y: number
 *     width: number
 *     height: number
 * }
 */

interface Player extends Rect {
    name: string;
    health: number;
}

const hero:Player = {
    name: 'Shiffman',
    health: 100,
    x: 100,
    y: 100,
    width: 32,
    height: 32
}

myTree.insert(hero);

Update single objects

This was often requested and is now supported in quadtree-ts. This might be handy when most of the objects in your Quadtree are static.

Browser Support

This library is supported in all modern browsers and runtimes. 2023 Update: now using ES6 (new Set()) which breaks IE9 compatibility. For IE9 support, use 1.2.5.

Development scripts

  • npm run build to minify the source

Changelog

1.2.6

  • Performance improvement of retrieve() (was O(n^2), now O(n)) (thanks to xixileng) Pushing the retrieval on a tree with 1.000.000 objects from ~160ms to ~5ms (MacBook M1 Pro).
  • New example: test-retrieve
  • Local copy of quadtree.min.js for the docs folder so it's always up to date

1.2.5

Typescript Definition File Bugfix (thanks to pietrovismara)

1.2.4

Added definition files for Typescript support

JSDoc Fixes

1.2.3

Using github.io for examples (docs), CDN URLs

1.2.2

Removed grunt dev dependency, now using uglify-js to minifiy

1.2.1

Allow float boundaries for Quads

Simplified getIndex function

1.2.0

This implementation now stores objects exclusively on leaf nodes and thus differs from the tutorial it's based on. Objects, that overlap into multiple subnodes are now referenced in each matching subnode instead of their parent node. This drastically reduces the collision candidates. Prior to 1.2.0, overlapping objects were stored in parent nodes.

1.1.3

Support for npm and module.exports

quadtree-js's People

Contributors

charlespwd avatar jesstelford avatar pietrovismara avatar timohausmann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quadtree-js's Issues

Rounding sub quad bounds

While using your quadtree implementation with geographic data I noticed in the split method the bounds are being rounded.

quadtree-js/quadtree.js

Lines 60 to 63 in 1cabf50

subWidth = Math.round( this.bounds.width / 2 ),
subHeight = Math.round( this.bounds.height / 2 ),
x = Math.round( this.bounds.x ),
y = Math.round( this.bounds.y );

In my case it rounds latitude and longitude.

For example:

https://www.google.com/maps/@37.8113896,-119.7013997,9.98z

rounds to

https://www.google.com/maps/@37,-119,9.98z

I could transform all of my coordinates to some intermediate values but before I do that I wanted to just check in with you. Thanks.

update elements?

As pointed out in the README, well, I think that updating points is a great feature to maintain.

The usual thing for this is the typical collision detector for games.

It just doesn't work?

I add random tiles of width 64,64 to my entire window and after adding 1 and doing a collision check at the other side of the window, I still get the first object returned.

Insert / Retrieve seems to be wrong

I tried to use this quadtree to organise a set of tiles in the range from (0 / 0) to (4000 / 4000). There were 16 tiles in total, each 1000 wide and 1000 high. Each sub division of the tree should hold only one tile, so i specified a maximum of 1 element per division. After I inserted all my tiles the quad tree generated 4 sub divisions with 4 elements in each sub division (?). Ok, in doubt, I can live with that but then I tried to retrieve all elements in the given region: x 0 y 0 w 1000 h 1000. That is the upper left sector. I'd expected a result of up to 4 tiles. The function returned 13 of 16 tiles. If you number my 16 tiles (4 x 4 rows and cols) from 0 to 15 (0 upper left, 3 upper right) I'd expected the tiles 0, 1, 4 and 5. In fact I got 0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13. The same strange behaviour occures in your example. But there I thought it might have something to do with javascript runtime and the movement in the scene. The quadtree seems broken to me. Maybe you could have a look on it...

Adding a licence file

Hello Timo,

First of all great work with the library.

I am writing to you as I noticed that your awesome library is missing a proper LICENCE file. I would be great if we could add it here.
If you're out of time atm, can also prepare a PR for you 🙂

Best,
Maciej

retrieving node from object

Hi,
I'm looking for a quick way to retrieve the node an object belongs to?
When I use retrieve(), it returns the object for given bounds, but if I want to know which node or node path is leading to the object,
is there a way other than manually traversing the tree from top to bottom?
Thanks,

Infinite loop issue

I've tried using this library - seems like it ends up in an infinite loop here:

            while( i < this.objects.length ) {

                index = this.getIndex( this.objects[ i ] );

                if( index !== -1 ) {                    
                    this.nodes[index].insert( this.objects.splice(i, 1)[0] );
                } else {
                    i = i + 1;
                }
            }

TypeError: t is Undefined

I include the javascript library like so, as described in the tutorial.

<script src="/static/quadtree.min.js"></script>

And the code which attempts to use the quadtree:

        // Clear the quadtree of all entities.
        this.quadTree.clear();

        // Re-insert soldiers into quadtree.
        for(i = 0; i < this.troops.length; i++){
            var object = {
                x: this.troops[i].x,
                y: this.troops[i].y,
                width: this.troops[i].width,
                height: this.troops[i].height
            }
            
            // this.quadTree.insert(this.troops[i]);
            this.quadTree.insert(this.object);
        }

And the code which creates the quadtree:

    this.quadTree = new Quadtree({
        x: 0, y: 0, width: 1800, height: 1350
    }, 5);

When attempting to load the page in Firefox, I receive a TypeError exception: 't' is undefined. What on earth is going on?

Best method to check all players against all players in the quadtree?

I have a case where I am using this on the server side and I need to loop through all players, and, on each players loop iteration, I would do a tree retrieve with player object and then insert the player etc etc for up to 500 players. In your opinion is this the right approach? Each player has the x, y, width, and height, and unique id properties.

Pseudo-code:
tree.clear()
tree.insert(allBullets)
for each player in players {
player.update; // update this player position
var objs = tree.retrieve(player) // first retrieve against this player
// do coll checks with objs if any are found

tree.insert(player) // do this after so this player won't be in his own retrieve
}

This way we only loop through the players once and each one is checked against all bullets and the previous players already inserted so all player to player checks are covered.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.