• Stars
    star
    225
  • Rank 170,590 (Top 4 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created almost 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Two-dimensional recursive spatial subdivision.

d3-quadtree

A quadtree recursively partitions two-dimensional space into squares, dividing each square into four equally-sized squares. Each distinct point exists in a unique leaf node; coincident points are represented by a linked list. Quadtrees can accelerate various spatial operations, such as the Barnes–Hut approximation for computing many-body forces, collision detection, and searching for nearby points.

Installing

If you use npm, npm install d3-quadtree. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import d3-quadtree from Skypack:

<script type="module">

import {quadtree} from "https://cdn.skypack.dev/d3-quadtree@3";

const tree = quadtree();

</script>

For legacy environments, you can load d3-quadtree’s UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-quadtree@3"></script>
<script>

const tree = d3.quadtree();

</script>

API Reference

# d3.quadtree([data[, x, y]]) <>

Creates a new, empty quadtree with an empty extent and the default x- and y-accessors. If data is specified, adds the specified iterable of data to the quadtree. This is equivalent to:

const tree = d3.quadtree()
    .addAll(data);

If x and y are also specified, sets the x- and y- accessors to the specified functions before adding the specified iterable of data to the quadtree, equivalent to:

const tree = d3.quadtree()
    .x(x)
    .y(y)
    .addAll(data);

# quadtree.x([x]) <>

If x is specified, sets the current x-coordinate accessor and returns the quadtree. If x is not specified, returns the current x-accessor, which defaults to:

function x(d) {
  return d[0];
}

The x-acccessor is used to derive the x-coordinate of data when adding to and removing from the tree. It is also used when finding to re-access the coordinates of data previously added to the tree; therefore, the x- and y-accessors must be consistent, returning the same value given the same input.

# quadtree.y([y]) <>

If y is specified, sets the current y-coordinate accessor and returns the quadtree. If y is not specified, returns the current y-accessor, which defaults to:

function y(d) {
  return d[1];
}

The y-acccessor is used to derive the y-coordinate of data when adding to and removing from the tree. It is also used when finding to re-access the coordinates of data previously added to the tree; therefore, the x- and y-accessors must be consistent, returning the same value given the same input.

# quadtree.extent([extent]) <>

If extent is specified, expands the quadtree to cover the specified points [[x0, y0], [x1, y1]] and returns the quadtree. If extent is not specified, returns the quadtree’s current extent [[x0, y0], [x1, y1]], where x0 and y0 are the inclusive lower bounds and x1 and y1 are the inclusive upper bounds, or undefined if the quadtree has no extent. The extent may also be expanded by calling quadtree.cover or quadtree.add.

# quadtree.cover(x, y) <>

Expands the quadtree to cover the specified point ⟨x,y⟩, and returns the quadtree. If the quadtree’s extent already covers the specified point, this method does nothing. If the quadtree has an extent, the extent is repeatedly doubled to cover the specified point, wrapping the root node as necessary; if the quadtree is empty, the extent is initialized to the extent [[⌊x⌋, ⌊y⌋], [⌈x⌉, ⌈y⌉]]. (Rounding is necessary such that if the extent is later doubled, the boundaries of existing quadrants do not change due to floating point error.)

# quadtree.add(datum) <>

Adds the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. If the new point is outside the current extent of the quadtree, the quadtree is automatically expanded to cover the new point.

# quadtree.addAll(data) <>

Adds the specified iterable of data to the quadtree, deriving each element’s coordinates ⟨x,y⟩ using the current x- and y-accessors, and return this quadtree. This is approximately equivalent to calling quadtree.add repeatedly:

for (let i = 0, n = data.length; i < n; ++i) {
  quadtree.add(data[i]);
}

However, this method results in a more compact quadtree because the extent of the data is computed first before adding the data.

# quadtree.remove(datum) <>

Removes the specified datum from the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. If the specified datum does not exist in this quadtree, this method does nothing.

# quadtree.removeAll(data) <>

Removes the specified data from the quadtree, deriving their coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree. If a specified datum does not exist in this quadtree, it is ignored.

# quadtree.copy()

Returns a copy of the quadtree. All nodes in the returned quadtree are identical copies of the corresponding node in the quadtree; however, any data in the quadtree is shared by reference and not copied.

# quadtree.root() <>

Returns the root node of the quadtree.

# quadtree.data() <>

Returns an array of all data in the quadtree.

# quadtree.size() <>

Returns the total number of data in the quadtree.

# quadtree.find(x, y[, radius]) <>

Returns the datum closest to the position ⟨x,y⟩ with the given search radius. If radius is not specified, it defaults to infinity. If there is no datum within the search area, returns undefined.

# quadtree.visit(callback) <>

Visits each node in the quadtree in pre-order traversal, invoking the specified callback with arguments node, x0, y0, x1, y1 for each node, where node is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree. (Assuming that positive x is right and positive y is down, as is typically the case in Canvas and SVG, ⟨x0, y0⟩ is the top-left corner and ⟨x1, y1⟩ is the lower-right corner; however, the coordinate system is arbitrary, so more formally x0 <= x1 and y0 <= y1.)

If the callback returns true for a given node, then the children of that node are not visited; otherwise, all child nodes are visited. This can be used to quickly visit only parts of the tree, for example when using the Barnes–Hut approximation. Note, however, that child quadrants are always visited in sibling order: top-left, top-right, bottom-left, bottom-right. In cases such as search, visiting siblings in a specific order may be faster.

As an example, the following visits the quadtree and returns all the nodes within a rectangular extent [xmin, ymin, xmax, ymax], ignoring quads that cannot possibly contain any such node:

function search(quadtree, xmin, ymin, xmax, ymax) {
  const results = [];
  quadtree.visit((node, x1, y1, x2, y2) => {
    if (!node.length) {
      do {
        let d = node.data;
        if (d[0] >= xmin && d[0] < xmax && d[1] >= ymin && d[1] < ymax) {
          results.push(d);
        }
      } while (node = node.next);
    }
    return x1 >= xmax || y1 >= ymax || x2 < xmin || y2 < ymin;
  });
  return results;
}

# quadtree.visitAfter(callback) <>

Visits each node in the quadtree in post-order traversal, invoking the specified callback with arguments node, x0, y0, x1, y1 for each node, where node is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree. (Assuming that positive x is right and positive y is down, as is typically the case in Canvas and SVG, ⟨x0, y0⟩ is the top-left corner and ⟨x1, y1⟩ is the lower-right corner; however, the coordinate system is arbitrary, so more formally x0 <= x1 and y0 <= y1.) Returns root.

Nodes

Internal nodes of the quadtree are represented as four-element arrays in left-to-right, top-to-bottom order:

  • 0 - the top-left quadrant, if any.
  • 1 - the top-right quadrant, if any.
  • 2 - the bottom-left quadrant, if any.
  • 3 - the bottom-right quadrant, if any.

A child quadrant may be undefined if it is empty.

Leaf nodes are represented as objects with the following properties:

  • data - the data associated with this point, as passed to quadtree.add.
  • next - the next datum in this leaf, if any.

The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes. For example, to iterate over all data in a leaf node:

if (!node.length) do console.log(node.data); while (node = node.next);

The point’s x- and y-coordinates must not be modified while the point is in the quadtree. To update a point’s position, remove the point and then re-add it to the quadtree at the new position. Alternatively, you may discard the existing quadtree entirely and create a new one from scratch; this may be more efficient if many of the points have moved.

More Repositories

1

d3

Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript
106,311
star
2

d3-shape

Graphical primitives for visualization, such as lines and areas.
JavaScript
2,458
star
3

d3-plugins

[DEPRECATED] A repository for sharing D3.js V3 plugins.
JavaScript
1,808
star
4

d3-force

Force-directed graph layout using velocity Verlet integration.
JavaScript
1,702
star
5

d3-scale

Encodings that map abstract data to visual representation.
JavaScript
1,567
star
6

d3-queue

Evaluate asynchronous tasks with configurable concurrency.
JavaScript
1,411
star
7

d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
JavaScript
1,064
star
8

d3-geo-projection

Extended geographic projections for d3-geo.
JavaScript
1,058
star
9

d3-geo

Geographic projections, spherical shapes and spherical trigonometry.
JavaScript
988
star
10

d3-scale-chromatic

Sequential, diverging and categorical color scales.
JavaScript
787
star
11

d3-sankey

Visualize flow between nodes in a directed acyclic network.
JavaScript
763
star
12

d3-format

Format numbers for human consumption.
JavaScript
611
star
13

d3-ease

Easing functions for smooth animation.
JavaScript
604
star
14

d3-delaunay

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
588
star
15

d3-selection

Transform the DOM by selecting elements and joining to data.
JavaScript
547
star
16

d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
JavaScript
495
star
17

d3-contour

Compute contour polygons using marching squares.
JavaScript
487
star
18

d3-interpolate

Interpolate numbers, colors, strings, arrays, objects, whatever!
JavaScript
482
star
19

d3-array

Array manipulation, ordering, searching, summarizing, etc.
JavaScript
452
star
20

d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.
JavaScript
416
star
21

d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
JavaScript
389
star
22

d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
JavaScript
328
star
23

d3-time-format

Parse and format times, inspired by strptime and strftime.
JavaScript
324
star
24

d3-voronoi

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
250
star
25

d3-hexbin

Group two-dimensional points into hexagonal bins.
JavaScript
231
star
26

d3-time

A calculator for humanity’s peculiar conventions of time.
JavaScript
227
star
27

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
28

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
29

d3-axis

Human-readable reference marks for scales.
JavaScript
204
star
30

d3.github.com

The D3 website.
JavaScript
195
star
31

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
32

d3-timer

An efficient queue for managing thousands of concurrent animations.
JavaScript
159
star
33

d3-brush

Select a one- or two-dimensional region using the mouse or touch.
JavaScript
154
star
34

d3-3.x-api-reference

An archive of the D3 3.x API Reference.
153
star
35

d3-random

Generate random numbers from various distributions.
JavaScript
136
star
36

d3-chord

Visualizations relationships or network flow with a circular layout.
JavaScript
122
star
37

d3-tile

Compute the quadtree tiles to display in a rectangular viewport.
JavaScript
120
star
38

d3-collection

Handy data structures for elements keyed by string.
JavaScript
111
star
39

d3-request

A convenient alternative to XMLHttpRequest.
JavaScript
109
star
40

d3-geo-polygon

Clipping and geometric operations for spherical polygons.
JavaScript
102
star
41

d3-polygon

Geometric operations for two-dimensional polygons.
JavaScript
97
star
42

d3-require

A minimal, promise-based implementation to require asynchronous module definitions.
JavaScript
78
star
43

d3-selection-multi

Multi-value syntax for d3-selection and d3-transition.
JavaScript
75
star
44

d3-dispatch

Register named callbacks and call them with arguments.
JavaScript
75
star
45

versor

a home for Mike Bostock's versor.js
JavaScript
34
star
46

d3-bundler

DEPRECATED; use rollup/rollup.
JavaScript
34
star
47

d3-hsv

The HSV (Hue, Saturation, Value) color space.
JavaScript
26
star
48

d3-logo

D3 brand assets.
23
star
49

d3-cam16

A d3 implementation of the CIECAM16 color appearance model.
JavaScript
22
star
50

d3-hcg

The HCG (Hue, Chroma, Grayness) color space derived from the Munsell color system.
JavaScript
20
star
51

d3-scripts

Common scripts for D3 modules.
JavaScript
15
star
52

d3-hull

DEPRECATED; see d3-polygon’s hull function.
JavaScript
14
star
53

blur-benchmark

temporary benchmark for d3.blur implementations
JavaScript
2
star