Two-dimensional recursive spatial subdivision: Flutter implementation of d3-quadtree

Overview

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 Skypak:

<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 array 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 array 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 array 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.

You might also like...

changelog.dart provides a library and a command-line application to manage in the correct way the git metadata to build the changelog between two release

changelog.dart provides a library and a command-line application to manage in the correct way the git metadata to build the changelog between two release

changelog.dart 🎯 changelog.dart: a collection of tools to manages in a fashion way a repository as maintainer. 🎯 Project Homepage Table of Content I

Dec 18, 2022

A program for booking restaurants that allows two types of the user (admin & customer).

  A program for booking restaurants that allows two types of the user (admin & customer).

restaurant Programmed by Flutter A program for booking restaurants that allows two types of the user (admin & customer). The admin can upload products

May 22, 2022

Two Screens of a sample real estate app.

Two Screens of a sample real estate app.

Flutter UI Practice Two Sample Screens for a real estate app UI These UI Screens are from RetroPortal Studio The Images are from unsplash How To Test

Dec 15, 2022

Flutter firebase auth - Simple implementation of Firebase Authentication using Flutter

FlutterFire Authentication Sample A simple implementation of Firebase Authentica

Apr 2, 2022

Flutter slidable custom - A Flutter implementation of slidable list item with directional slide actions that can be dismissed

Flutter slidable custom - A Flutter implementation of slidable list item with directional slide actions that can be dismissed

Slidable is a Flutter Favorite package! flutter_slidable A Flutter implementatio

Feb 7, 2022

[Flutter SDK V.2] - Youtube Video is a Flutter application built to demonstrate the use of Modern development tools with best practices implementation like Clean Architecture, Modularization, Dependency Injection, BLoC, etc.

[Flutter SDK V.2] - Youtube Video is a Flutter application built to demonstrate the use of Modern development tools with best practices implementation like Clean Architecture, Modularization, Dependency Injection, BLoC, etc.

[Flutter SDK V.2] - Youtube Video is a Flutter application built to demonstrate the use of Modern development tools with best practices implementation like Clean Architecture, Modularization, Dependency Injection, BLoC, etc.

Jan 2, 2023

DropdownButton, ToggleButton & CheckboxListTile implementation in Flutter as a Mobile App Development exercise.

DropdownButton, ToggleButton & CheckboxListTile implementation in Flutter as a Mobile App Development exercise.

Sort & Filter UI A new Flutter project. Getting Started This project is a starting point for a Flutter application. ⏮ Preview A few resources to get y

Sep 29, 2021

Interview questions and answers for preparation, built in pure flutter also have CI implementation for learning.

Interview questions and answers for preparation, built in pure flutter also have CI implementation for learning.

toughest An app for interview preparation. Unique animations. More than 100 questions and answer. Good UI. Featured in many websites. For Vietnam user

Dec 27, 2022

Backdrop implementation in flutter.

Backdrop implementation in flutter.

backdrop Backdrop implementation in flutter. This widget is in active development. Any contribution, idea, criticism or feedback is welcomed. NOTE: If

Dec 16, 2022
Comments
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • .github/workflows/dart.yml (github-actions)
    • pubspec.yaml (pub)

    Configuration

    🔡 Renovate has detected a custom config for this PR. Feel free to ask for help if you have any doubts and would like it reviewed.

    Important: Now that this branch is edited, Renovate can't rebase it from the base branch any more. If you make changes to the base branch that could impact this onboarding PR, please merge them manually.

    What to Expect

    With your current configuration, Renovate will create 3 Pull Requests:

    chore(deps): update dart-lang/setup-dart digest to 196f545
    • Schedule: ["at any time"]
    • Branch name: renovate/dart-lang-setup-dart-digest
    • Merge into: master
    • Upgrade dart-lang/setup-dart to 196f54580e9eee2797c57e85e289339f85e6779d
    chore(deps): update actions/checkout action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-checkout-3.x
    • Merge into: master
    • Upgrade actions/checkout to v3
    chore(deps): update dependency very_good_analysis to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/very_good_analysis-3.x
    • Merge into: master
    • Upgrade very_good_analysis to ^3.0.0

    🚸 Branch creation will be limited to maximum 2 per hour, so it doesn't swamp any CI resources or spam the project. See docs for prhourlylimit for details.


    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
Simple UI design implementation of two pages.

dating_app_clone A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started

null 4 Sep 22, 2021
Get It - Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your App. Maintainer: @escamoteur

❤️ Sponsor get_it This is a simple Service Locator for Dart and Flutter projects with some additional goodies highly inspired by Splat. It can be used

Flutter Community 1k Jan 1, 2023
Flutter package for drag-and-drop reordering of two-level lists

drag_and_drop_lists Two-level drag and drop reorderable lists. Features Reorder elements between multiple lists Reorder lists Drag and drop new elemen

Philip Brink 168 Dec 18, 2022
Create flutter project with all needed configuration in two minutes (theme, localization, connect to firebase, FCM, local notifications, safe API call, error handling, animation..etc)

Flutter GetX Template Flutter Getx template to make starting project fast and easy . Introduction We all face the same problem when we want to start a

Emad Beltaje 150 Jan 7, 2023
A Flutter widget that simply balances the lines of two-line text

Flutter Balanced Text ⚖️ A Flutter widget that simply balances the lines of two-line text, especially useful on long titles or short descriptions. Doe

Raşit Ayaz 3 Nov 10, 2022
Hero Effect for common words of two Text (Flutter)

Hero Effect for common words of text widget (something like magic move in keynote) Features Usage Usage is easily and likes Hero,but obviously the chi

null 7 Oct 12, 2022
This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two pages application with user bid in input and count down view.

Nilam This is an auction application just like eBay. Using firebase as the backend for signup & sign-in functionality. In addition to that, it's a two

Md. Siam 5 Nov 9, 2022
Material color picker, you can customize colors. Selection in two step, first main color and after shades.

Flutter Material Color Picker Material Color picker is a Flutter widget, that can be customizable. By default, it's Material Colors, but you can defin

Jean-Charles Moussé 70 Nov 25, 2022
Note provider - Note App using Provider state management, Sqflite and Localization for two language Arabic and English.

note_provider Sqflite with provider statemanagement Getting Started This project is a starting point for a Flutter application. A few resources to get

Mohanned Anwar 0 Jan 1, 2022
This is a university marketplace, where students buy and sell products and services online or offline. Mainly to connect the two parties together.

marktorder A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Ibukunoluwa Naphtali 1 Jan 10, 2022