RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

Spatial structures

KD-trees, ball trees and BVHs, 2-D and 3-D convex hulls, Delaunay and Voronoi, k-nearest neighbours, point clouds and Morton codes.

import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
13 classes82 functions and methods83 of 153 documented65 runnable examplesWhat scipy.spatial does

Overview

Nearest-neighbour trees, a GPU-ready BVH, a cell list, hulls, Delaunay/Voronoi and point-cloud operations. Depends only on riptide_math (robust predicates, the 3 \times 3 eigen solver).

Data layout. Points are interleaved Float64Lists (x0 y0 z0 x1 y1 z1 …, dim values per point), never copied: trees keep an index permutation. That maps one-to-one onto a C-contiguous (n, dim) NDArray from part A when it lands.

What's in it

FileContentsCost
kd_tree.rayKdTree: any dimension, nanoflann-style sliding-midpoint splits, leaf buckets, k-nearest (knn, knnBatch, allocation-free knnInto), radius, countWithinbuild O(n \log n); query O(\log n + k) expected in low dimension
ball_tree.rayBallTree: median splits, centroid + radius nodes; kNN and radiussame; better for clustered data
neighbors.rayKnnResult, RadiusResult, KnnHeap, bruteForceKnn, bruteForceRadius (references)O(n \cdot m \cdot d)
aabb_bvh.rayAabbBvh: binned SAH on 3 axes, flattened 32-byte nodes with miss links (layout below), stackless queryAabb and raycast, overlapPairs (broadphase), refit, sahCost, depthbuild O(n \log n); refit O(n)
cell_list.rayCellList: uniform grid by counting sort (SoA cellStart/sorted/cellOf), 27-cell neighbour visits, pairsWithin — for SPH and particle-in-cellO(n + cells)
hull.rayconvexHull2d (monotone chain, robust), polygonArea, ConvexHull3d.quickHull (volume, area, vertices)O(n \log n)
delaunay.rayDelaunay2d (Delaunator sweep-hull, robust predicates; half-edges, hull, neighbours, circumcentres), Voronoi2d (cells clipped to a box)O(n \log n); O(n) cells
delaunay3.rayDelaunay3d (Bowyer–Watson, Morton insertion order, exact in-sphere/orientation), orient3, inSphereO(n \log n) expected
point_cloud.rayPointCloud: centroid, bounds, voxel downsample, normals (PCA of k neighbours), statistical outlier removal, rigidTransform (Horn quaternion), point-to-point icp, transform; symmetricEigen (small Jacobi)
morton.rayMorton: 3-D 63-bit and 2-D 62-bit encode/decode, 30-bit morton3d30 for GPUsO(1)

riptide_math keeps its simple O(n^{2}) convexHull3 (used by its EPA) and delaunay2 (Bowyer–Watson) as small references; this package has the fast versions. The triangle Bvh in riptide_math stays the ray-tracing BVH for meshes; AabbBvh is the general one (boxes, points, broadphase, GPU upload).

BVH node layout (GPU)

32 bytes per node, 8 little-endian 32-bit words, nodes in depth-first pre-order (node i at byte 32 \cdot i):

wordtypemeaning
0–2f32min.x, min.y, min.z (rounded towards -\infty)
3i32miss: next node after this subtree in pre-order (nodeCount = done)
4–6f32max.x, max.y, max.z (rounded towards +\infty)
7i32prim: -1 interior; leaf (first << 4) \| (count − 1), count 1–16 entries of primOrder from first

Interior node i: left child i + 1, right child miss of node i + 1. Upload nodes (bytes) and primOrder (u32) as two storage buffers; the stackless loop is in the AabbBvh doc comment. In GLSL std430: struct Node { vec3 lo; int miss; vec3 hi; int prim; }; (a vec3 followed by a 4-byte scalar packs into 16 bytes).

Functions and constants

Functions

f32Downfunction
double f32Down(double v)

v rounded to the nearest float32 not above it.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final x = 0.1;
  print('f32Down(0.1) = ${f32Down(x)} ≤ 0.1: ${f32Down(x) <= x}');
  print('f32Up(0.1)   = ${f32Up(x)} ≥ 0.1: ${f32Up(x) >= x}');
}
Output
f32Down(0.1) = 0.09999999403953552 ≤ 0.1: true
f32Up(0.1)   = 0.10000000149011612 ≥ 0.1: true
f32Upfunction
double f32Up(double v)

v rounded to the nearest float32 not below it.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Conservative float32 bounds keep boxes in a float32 BVH from shrinking.
  for (final v in [1.0, 1 / 3, -2.7]) {
    print('$v in [${f32Down(v)}, ${f32Up(v)}]');
  }
}
Output
1.0 in [1.0, 1.0]
0.3333333333333333 in [0.3333333134651184, 0.3333333432674408]
-2.7 in [-2.700000047683716, -2.6999998092651367]
circumcenterfunction
(double, double) circumcenter(double ax, double ay, double bx, double by, double cx, double cy)

Circumcentre of triangle (a, b, c).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final (x, y) = circumcenter(0, 0, 4, 0, 0, 3);
  final r = math.sqrt(x * x + y * y);
  print('circumcenter ($x, $y), radius $r');
}
Output
circumcenter (2.0, 1.5), radius 2.5
orient3function
int orient3(Float64List p, int a, int b, int c, int d)

Sign of \det(a - d, b - d, c - d).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final p = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1, 1, 1, 0]);
  print('d above the plane abc: ${orient3(p, 0, 1, 2, 3)}');
  print('d below: ${orient3(p, 0, 1, 2, 4)}');
  print('d on it (exactly): ${orient3(p, 0, 1, 2, 5)}');
}
Output
d above the plane abc: -1
d below: 1
d on it (exactly): 0
inSpherefunction
int inSphere(Float64List p, int a, int b, int c, int d, int e)
0 when e is strictly inside the sphere through positively oriented a, b, c, d; 0 on it; < 0 outside.
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Unit-sphere points a..d and two test points.
  final p = Float64List.fromList([1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0.5, 0, 0, 2]);
  print('(0, 0, 0.5): ${inSphere(p, 0, 1, 2, 3, 4)}');
  print('(0, 0, 2):   ${inSphere(p, 0, 1, 2, 3, 5)}');
}
Output
(0, 0, 0.5): 1
(0, 0, 2):   -1
convexHull2dfunction
Int32List convexHull2d(Float64List xy)

Convex hull of 2-D points (interleaved x y) by Andrew's monotone chain (1979), O(n \log n), with Shewchuk's robust orientation test from riptide_math, so near-collinear input never produces a reflex vertex. Returns the indices of the hull vertices counter-clockwise, starting at the lowest-x (then lowest-y) point; collinear points on edges and duplicates are left out. Fewer than 3 distinct non-collinear points give the distinct extremes.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final h = convexHull2d(xy);
  print('${h.length} hull corners: $h');
}
Output
9 hull corners: [23, 15, 4, 17, 20, 28, 14, 5, 3]
polygonAreafunction
double polygonArea(Float64List xy, List<int> poly)

Area enclosed by a polygon given as indices into interleaved xy (positive when counter-clockwise).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final xy = Float64List.fromList([0, 0, 4, 0, 4, 3, 1, 3, 1, 1, 0, 1]);
  final poly = [0, 1, 2, 3, 4, 5];
  print('area ${polygonArea(xy, poly)}');
  print('clockwise gives ${polygonArea(xy, poly.reversed.toList())}');
}
Output
area 10.0
clockwise gives -10.0
KnnResult bruteForceKnn(Float64List points, Float64List queries, int dim, int k)

Exact k nearest neighbours by brute force, O(n \cdot m \cdot d): the reference the trees are tested against. points and queries are interleaved (x0 y0 z0 x1 y1 z1 …, dim values per point).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = bruteForceKnn(xy, Float64List.fromList([50, 50]), 2, 4);
  print('4 nearest to (50, 50): ${r.indices}, quadrances ${r.dist2}');
}
Output
4 nearest to (50, 50): [1, 9, 24, 10], quadrances [5.0, 100.0, 144.0, 389.0]
RadiusResult bruteForceRadius(Float64List points, List<double> query, int dim, double radius)

Points within radius of query by brute force (the reference for the trees' radius search), nearest first.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = bruteForceRadius(xy, [50, 50], 2, 25);
  print('${r.length} points within 25: ${r.indices}');
}
Output
7 points within 25: [1, 9, 24, 10, 18, 12, 13]
sortedRadiusfunction
RadiusResult sortedRadius(List<(double, int)> hits)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = sortedRadius([(9.0, 2), (1.0, 7), (4.0, 3)]);
  print('indices ${r.indices}, quadrances ${r.dist2}');
}
Output
indices [7, 3, 2], quadrances [1.0, 4.0, 9.0]
(Float64List, Float64List) symmetricEigen(Float64List a, int n, {int maxSweeps = 50})

Eigen-decomposition of a small symmetric n \times n matrix a (row-major) by cyclic Jacobi rotations. Returns the eigenvalues (unsorted) and the eigenvectors as the columns of a row-major n \times n matrix. For the 4 \times 4 of Horn's method and other tiny problems; part A's dense eigensolvers are the general tool.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([2, 1, 0, 1, 2, 1, 0, 1, 2]);
  final (w, v) = symmetricEigen(a, 3);
  print('eigenvalues ${w.map((x) => x.toStringAsFixed(6)).toList()}');
  print('(2 − √2, 2, 2 + √2) = ${[2 - math.sqrt2, 2.0, 2 + math.sqrt2].map((x) => x.toStringAsFixed(6)).toList()}');
}
Output
eigenvalues [0.585786, 3.414214, 2.000000]
(2 − √2, 2, 2 + √2) = [0.585786, 2.000000, 3.414214]

Classes

class

AabbBvh

final class AabbBvh

A bounding volume hierarchy over axis-aligned boxes (or points) in 3-D, built top-down with the binned surface area heuristic (Wald 2007) on all three axes, and stored flattened for the GPU: one 32-byte node per entry in depth-first (pre-)order with a miss link, so a compute shader walks it without a stack.

Node layout (32 bytes, 8 little-endian 32-bit words; node i starts at byte 32 \cdot i)
wordtypemeaning
0–2f32min.x, min.y, min.z (rounded towards -\infty from the double-precision build)
3i32miss: the node to visit when this one is missed or finished — the next node after this subtree in pre-order; nodeCount means done
4–6f32max.x, max.y, max.z (rounded towards +\infty)
7i32prim: -1 for an interior node; for a leaf `(first << 4)(count − 1): count (1–16) primitives at primOrder[first …]`

An interior node's left child is always i + 1 and its right child is miss of node i + 1. Stackless traversal, the same in Raya (queryAabb, raycast) and GLSL:

int i = 0;
while (i < nodeCount) {
  Node n = nodes[i];
  if (!overlaps(n)) { i = n.miss; continue; }
  if (n.prim < 0) { i = i + 1; continue; }          // interior: descend into the left child
  int first = n.prim >> 4, count = (n.prim & 15) + 1;
  for (int k = 0; k < count; k++) visit(primOrder[first + k]);
  i = n.miss;
}

refit updates the boxes after primitives move without rebuilding (children always follow parents in the array, so one reverse pass suffices); quality degrades as the scene drifts, so rebuild when sahCost has grown a lot.

Constructors

factory AabbBvh.build(Float64List mins, Float64List maxs, {int maxLeaf = 4, int bins = 16})

Builds over count boxes given as interleaved mins and maxs (3 doubles per box). maxLeaf is 1–16.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  print('${bvh.nodeCount} nodes for ${bvh.primCount} boxes, depth ${bvh.depth}, SAH cost ${bvh.sahCost.toStringAsFixed(3)}');
}
Output
23 nodes for 12 boxes, depth 4, SAH cost 4.859
factory AabbBvh.points(Float64List xyz, {int maxLeaf = 4})

Builds over points (zero-size boxes), interleaved xyz.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final bvh = AabbBvh.points(xyz, maxLeaf: 8);
  print('${bvh.primCount} points in ${bvh.nodeCount} nodes');
  var hits = 0;
  bvh.queryAabb([0, 0, 0], [5, 5, 5], (p) => hits++);
  print('$hits points in the corner box [0, 5]³');
}
Output
200 points in 399 nodes
23 points in the corner box [0, 5]³

Properties

nodesfield
final Uint8List nodes

The flattened nodes (32 bytes each), ready to copy into a GPU storage buffer.

final Uint32List primOrder

Leaf primitive ranges index this permutation of the input boxes.

final int nodeCount
final int primCount
f32field
final Float32List f32

Views of nodes as floats (bounds) and ints (miss, prim).

i32field
final Int32List i32
sahCostgetter
double get sahCost

The SAH cost of the tree (traversal 1, intersection 1), relative to the root's area: lower is better.

depthgetter
int get depth

Depth of the deepest leaf (root = 0).

Methods

missmethod
int miss(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
primmethod
int prim(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
isLeafmethod
bool isLeaf(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
leafFirstmethod
int leafFirst(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
leafCountmethod
int leafCount(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
rightmethod
int right(int node)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // Walk the flattened tree: a node is followed by its left child; miss() jumps past its subtree.
  for (var node = 0; node < math.min(bvh.nodeCount, 7); node++) {
    if (bvh.isLeaf(node)) {
      print('node $node: leaf, prim code ${bvh.prim(node)} -> boxes ${[for (var s = 0; s < bvh.leafCount(node); s++) bvh.primOrder[bvh.leafFirst(node) + s]]}, miss -> ${bvh.miss(node)}');
    } else {
      print('node $node: inner, right child ${bvh.right(node)}, miss -> ${bvh.miss(node)}');
    }
  }
}
Output
node 0: inner, right child 12, miss -> 23
node 1: inner, right child 7, miss -> 12
node 2: inner, right child 4, miss -> 7
node 3: leaf, prim code 0 -> boxes [0], miss -> 4
node 4: inner, right child 6, miss -> 7
node 5: leaf, prim code 16 -> boxes [1], miss -> 6
node 6: leaf, prim code 32 -> boxes [2], miss -> 7
queryAabbmethod
void queryAabb(List<double> lo, List<double> hi, void Function(int prim) visit)

Calls visit with every primitive whose node box overlaps lo..hi (3 values each). Candidates only: the caller tests the primitive itself. Stackless, exactly as a shader would walk it.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  final found = <int>[];
  bvh.queryAabb([4, 0, 0], [9, 0.8, 1], found.add);
  print('boxes overlapping the query: ${found..sort()}');
}
Output
boxes overlapping the query: [3, 4, 6]
raycastmethod
({int prim, double t})? raycast(double ox, double oy, double oz, double dx, double dy, double dz, double? Function(int prim) hit, {double tMax = double.infinity})

Closest hit along the ray o + t \cdot d for t in [0, tMax]: hit tests one primitive and returns its hit distance (or null). Returns the nearest (prim, t) or null. Stackless; boxes beyond the current best are skipped.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  // A ray along +x at y = 1.2; hit() returns the entry distance into a primitive box.
  double? hit(int i) => mins[3 * i + 1] <= 1.2 && 1.2 <= maxs[3 * i + 1] ? math.max(0, mins[3 * i] - (-1)) : null;
  final h = bvh.raycast(-1, 1.2, 0.5, 1, 0, 0, hit);
  print('first hit: box ${h?.prim} at t = ${h?.t}');
}
Output
first hit: box 1 at t = 2.5
List<(int, int)> overlapPairs(Float64List mins, Float64List maxs)

Every pair (i, j), i < j, of input boxes in mins/maxs that overlap: the broadphase. O(n \log n + k).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  final pairs = bvh.overlapPairs(mins, maxs);
  print('${pairs.length} overlapping pairs: ${pairs.take(6).toList()}');
}
Output
11 overlapping pairs: [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
refitmethod
void refit(Float64List mins, Float64List maxs)

Recomputes every node box from moved primitives (same topology), O(n).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // 12 boxes in a row (min corners and max corners, xyz).
  const n = 12;
  final mins = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5, (i % 3) * 0.5, 0]]);
  final maxs = Float64List.fromList([for (var i = 0; i < n; i++) ...[i * 1.5 + 1.8, (i % 3) * 0.5 + 1, 1]]);
  final bvh = AabbBvh.build(mins, maxs, maxLeaf: 2);
  for (var i = 0; i < 3 * n; i++) {
    mins[i] += 10;
    maxs[i] += 10;
  }
  bvh.refit(mins, maxs); // same topology, new bounds
  final found = <int>[];
  bvh.queryAabb([10, 10, 10], [11, 11, 11], found.add);
  print('after moving everything by 10: $found');
}
Output
after moving everything by 10: [0]
final class BallTree

A ball tree (Omohundro 1989; the layout of scikit-learn's BallTree, BSD-3-Clause): every node is a hypersphere (centroid, radius) around its points, split at the median of the dimension of largest spread. Pruning uses \max(0, |q - c| - r), which stays useful in higher dimensions and for clustered data where k-d cells get long and thin. Points are interleaved (dim per point) and not copied.

Constructors

BallTreefactory
factory BallTree(Float64List points, int dim, {int leafSize = 16})
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final t = BallTree(xy, 2, leafSize: 4);
  print('${t.length} points, ${t.nodeCount} nodes');
}
Output
30 points, 15 nodes

Properties

pointsfield
final Float64List points
dimfield
final int dim
orderfield
final Int32List order
centersfield
final Float64List centers

Per node: centroid (dim values) and radius.

radiifield
final Float64List radii

Per node: centroid (dim values) and radius.

childfield
final Int32List child

Per node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.

startfield
final Int32List start

Per node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.

endfield
final Int32List end

Per node: left child (right is +1) or -1 for a leaf; leaf ranges [start, end) of order.

lengthgetter
int get length
nodeCountgetter
int get nodeCount

Methods

knnmethod
KnnResult knn(List<double> query, int k)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = BallTree(xy, 2).knn([20, 80], 5);
  print('5 nearest to (20, 80): ${r.indices}');
}
Output
5 nearest to (20, 80): [7, 0, 16, 3, 5]
knnBatchmethod
KnnResult knnBatch(Float64List queries, int k)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = BallTree(xy, 2).knnBatch(Float64List.fromList([0, 0, 100, 100]), 2);
  print('${r.queries} queries; nearest to (0, 0): ${r.indices.sublist(0, 2)}, to (100, 100): ${r.indices.sublist(2, 4)}');
}
Output
2 queries; nearest to (0, 0): [15, 29], to (100, 100): [28, 20]
knnIntomethod
void knnInto(List<double> query, KnnHeap heap)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final t = BallTree(xy, 2), heap = KnnHeap(3);
  t.knnInto([50, 50], heap);
  print('heap holds ${heap.count}, worst quadrance ${heap.worst}');
}
Output
heap holds 3, worst quadrance 144.0
radiusmethod
RadiusResult radius(List<double> query, double radius)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = BallTree(xy, 2).radius([50, 50], 20);
  print('${r.length} points within 20');
}
Output
4 points within 20
final class CellList

A uniform-grid cell list over 3-D points, built by counting sort (two passes, no per-cell lists): the neighbour structure for SPH, particle-in-cell deposition and short-range forces, where the search radius equals the cell size and points move every step (rebuild is O(n + cells), cheaper than any tree).

Layout (all SoA typed data, so a compute shader can read the same arrays):

  • Cells are numbered cell = (iz · ny + iy) · nx + ix with ix = floor((x − originX) / cellSize), clamped to the grid;
  • cellStart has cells + 1 entries: the points of cell c are sorted[cellStart[c].. cellStart[c + 1]);
  • sorted is the point indices ordered by cell, cellOf the cell of every input point.

Constructors

factory CellList.build(Float64List xyz, double cellSize, {List<double>? boxMin, List<double>? boxMax})

Bins interleaved xyz points into cells of cellSize covering their bounds (or the given box).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final c = CellList.build(xyz, 2.5);
  print('${c.cellCount} cells (${c.nx} × ${c.ny} × ${c.nz})');
}
Output
64 cells (4 × 4 × 4)

Properties

originXfield
final double originX
originYfield
final double originY
originZfield
final double originZ
final double cellSize
nxfield
final int nx
nyfield
final int ny
nzfield
final int nz
final Int32List cellStart
sortedfield
final Int32List sorted
cellOffield
final Int32List cellOf
cellCountgetter
int get cellCount

Methods

void forEachNear(double x, double y, double z, void Function(int point) visit)

Calls visit with every point in the 27 cells around (x, y, z): candidates within cellSize of it (and some farther ones; the caller checks the distance).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final c = CellList.build(xyz, 2);
  var count = 0;
  c.forEachNear(5, 5, 5, (i) => count++);
  print('$count candidates in the 27 cells around (5, 5, 5)');
}
Output
47 candidates in the 27 cells around (5, 5, 5)
List<(int, int)> pairsWithin(Float64List xyz, double radius)

Every pair (i, j), i < j, of points closer than radius ≤ cellSize in interleaved xyz.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(4);
  const n = 60;
  final xyz = Float64List.fromList([for (var i = 0; i < n; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0]]);
  final pairs = CellList.build(xyz, 1.5).pairsWithin(xyz, 1.5);
  print('${pairs.length} pairs closer than 1.5');
}
Output
93 pairs closer than 1.5
final class Delaunay2d

2-D Delaunay triangulation by the sweep-hull method of Delaunator: sort points by distance from the circumcentre of a seed triangle, add them one by one outside a convex hull kept as a linked list with an angular hash, fan to the visible hull edges and restore the Delaunay condition by edge flips. O(n \log n) in practice. Unlike Delaunator, both predicates are the robust ones from riptide_math (orientation and in-circle), so cocircular input (grids) never flips forever and never makes a reflex hull.

Output in Delaunator's half-edge form: triangle t has vertices triangles[3t.. 3t+2] (counter-clockwise, y up); half-edge e goes from triangles[e] to triangles[next(e)], and halfedges[e] is the opposite half-edge in the neighbouring triangle, or -1 on the hull.

Constructors

Delaunay2dfactory
factory Delaunay2d(Float64List points)

Triangulates interleaved x y points. Exact duplicates are skipped (they appear in no triangle). All points collinear: no triangles, and hull lists them in order along the line.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final d = Delaunay2d(xy);
  print('${d.triangleCount} triangles, hull ${d.hull.length}: 2n − 2 − h = ${2 * n - 2 - d.hull.length}');
}
Output
49 triangles, hull 9: 2n − 2 − h = 49

Static

nextHalfedgestaticmethod
static int nextHalfedge(int e)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Half-edges come in threes per triangle: 0 → 1 → 2 → 0.
  print([for (var e = 0; e < 6; e++) Delaunay2d.nextHalfedge(e)]);
}
Output
[1, 2, 0, 4, 5, 3]
prevHalfedgestaticmethod
static int prevHalfedge(int e)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print([for (var e = 0; e < 6; e++) Delaunay2d.prevHalfedge(e)]);
}
Output
[2, 0, 1, 5, 3, 4]

Properties

pointsfield
final Float64List points
final Int32List triangles
final Int32List halfedges
hullfield
final Int32List hull

Hull vertices counter-clockwise.

int get triangleCount

Methods

neighborsmethod
List<List<int>> neighbors()

Delaunay neighbours of every point (sorted), from the half-edges.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final d = Delaunay2d(xy);
  final nb = d.neighbors();
  print('point 0 has neighbours ${nb[0]}');
  print('average degree ${(nb.fold<int>(0, (s, l) => s + l.length) / n).toStringAsFixed(2)}');
}
Output
point 0 has neighbours [3, 7, 16, 23]
average degree 5.20
Float64List circumcenters()

The circumcentre of every triangle (interleaved), the vertices of the Voronoi diagram.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final d = Delaunay2d(xy);
  final c = d.circumcenters();
  print('${c.length ~/ 2} circumcentres; first (${c[0].toStringAsFixed(2)}, ${c[1].toStringAsFixed(2)})');
  final t0 = d.triangles[0];
  final r = math.sqrt(math.pow(c[0] - xy[2 * t0], 2) + math.pow(c[1] - xy[2 * t0 + 1], 2));
}
Output
49 circumcentres; first (55.33, 50.11)
voronoimethod
Voronoi2d voronoi(double x0, double y0, double x1, double y1)

The Voronoi diagram, every cell clipped to the box [x_{0}, x_{1}] \times [y_{0}, y_{1}].

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
  var total = 0.0;
  for (var i = 0; i < n; i++) {
    total += v.cellArea(i);
  }
  print('cell areas sum to ${total.toStringAsFixed(6)} (the box is 10000)');
}
Output
cell areas sum to 10000.000000 (the box is 10000)
final class Voronoi2d

A Voronoi diagram as the dual of a Delaunay2d: cell i is the box cut by the bisector half-planes of point i and each of its Delaunay neighbours (exactly the cell, since Voronoi neighbours are Delaunay neighbours), so hull sites get closed cells too. O(degree) per cell, O(n) in all.

Properties

final Delaunay2d delaunay
x0field
final double x0
y0field
final double y0
x1field
final double x1
y1field
final double y1

Methods

cellmethod
Float64List cell(int i)

The vertices of cell i, counter-clockwise, interleaved; empty for a skipped duplicate point outside the box.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final xy = Float64List.fromList([25, 25, 75, 25, 50, 75]);
  final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
  final c = v.cell(2);
  print('cell of the top point: ${[for (var k = 0; k < c.length ~/ 2; k++) '(${c[2 * k].toStringAsFixed(1)}, ${c[2 * k + 1].toStringAsFixed(1)})']}');
}
Output
cell of the top point: [(100.0, 68.8), (100.0, 100.0), (0.0, 100.0), (0.0, 68.8), (50.0, 43.8)]
cellAreamethod
double cellArea(int i)

Area of cell i.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final xy = Float64List.fromList([25, 25, 75, 25, 50, 75]);
  final v = Delaunay2d(xy).voronoi(0, 0, 100, 100);
  print([for (var i = 0; i < 3; i++) v.cellArea(i).toStringAsFixed(2)]);
}
Output
[2812.50, 2812.50, 4375.00]
final class Delaunay3d

3-D Delaunay tetrahedralisation by Bowyer–Watson insertion (Bowyer 1981, Watson 1981): points are inserted in Morton order inside a large enclosing tetrahedron; each one is located by a visibility walk, the tetrahedra whose circumsphere strictly contains it are removed, and the cavity is re-filled with a fan from the point. Both predicates (orientation, in-sphere) use a floating-point filter with Shewchuk's error bounds and an exact BigInt fallback, so cospherical input (grids) is handled without inconsistency. O(n \log n) expected for uniform input.

Tetrahedra are positively oriented: \det(a - d, b - d, c - d) > 0. Exact duplicates are skipped. With fewer than 4 non-coplanar points there are no tetrahedra.

Constructors

Delaunay3dfactory
factory Delaunay3d(Float64List xyz)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 40;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final d = Delaunay3d(xyz);
  final hull = ConvexHull3d.quickHull(xyz);
  print('${d.tetrahedronCount} tetrahedra, volume ${d.volume.toStringAsFixed(6)}');
  print('hull volume ${hull.volume.toStringAsFixed(6)} (the same)');
}
Output
164 tetrahedra, volume 484.109405
hull volume 484.109405 (the same)

Properties

pointsfield
final Float64List points

Interleaved xyz input.

final Int32List tetrahedra

4 vertex indices per tetrahedron.

final Int32List neighbors

4 per tetrahedron: the neighbour across the face opposite vertex k, or -1 on the hull.

int get tetrahedronCount
volumegetter
double get volume

Total volume (equals the convex hull's).

final class ConvexHull3d

A 3-D convex hull: triangles (3 vertex indices each, counter-clockwise seen from outside) over the input points.

Constructors

factory ConvexHull3d.quickHull(Float64List xyz)

QuickHull (Barber, Dobkin and Huhdanpaa 1996; the algorithm qhull implements, written here from the paper): start from an extreme tetrahedron, give each outside point to a face it sees, then repeatedly take a face's farthest point, find the faces visible from it by walking neighbours, and replace them with a fan from the horizon. Points within the tolerance \varepsilon = 3 \cdot 2^{-52}·(max|x| + max|y| + max|z|) of a face count as inside, so coplanar points never become vertices (qhull's default for vertices). O(n \log n) expected.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // A cube's 8 corners plus an inside point.
  final xyz = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5]);
  final h = ConvexHull3d.quickHull(xyz);
  print('${h.faceCount} triangles, vertices ${h.vertices}');
  print('volume ${h.volume}, area ${h.area}');
}
Output
12 triangles, vertices [0, 1, 2, 3, 4, 5, 6, 7]
volume 1.0, area 6.0

Properties

pointsfield
final Float64List points

The input points (interleaved xyz).

final Int32List triangles

Flat triangle list, 3 indices per face, wound counter-clockwise from outside. Empty when the input is degenerate (fewer than 4 points, or all coplanar within tolerance).

faceCountgetter
int get faceCount
verticesgetter
Int32List get vertices

The distinct hull vertices, ascending.

volumegetter
double get volume
areagetter
double get area
class

KdTree

final class KdTree

A k-d tree over points in any dimension (Float64), after nanoflann (Blanco and Rai, BSD-2-Clause): sliding-midpoint splits on the dimension of largest spread, leaf buckets of up to leafSize points, nodes as flat typed arrays, each split keeping both the largest coordinate on the low side and the smallest on the high side (nanoflann's divlow/divhigh) so the far child is pruned with the true gap, and searches that update the query-to-cell distance incrementally (Arya and Mount) instead of recomputing it.

Points are interleaved (x0 y0 … x1 y1 …, dim values per point) and are not copied: the tree keeps a permutation order into them. Build is O(n \log n); a k-nearest query is O(\log n + k) expected in low dimensions.

Constructors

KdTreefactory
factory KdTree(Float64List points, int dim, {int leafSize = 10})
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final t = KdTree(xy, 2, leafSize: 4);
  print('${t.length} points, ${t.nodeCount} nodes; root box ${t.rootMin} … ${t.rootMax}');
}
Output
30 points, 17 nodes; root box [8.0, 1.0] … [97.0, 100.0]

Properties

pointsfield
final Float64List points

The indexed points (interleaved, dim per point).

dimfield
final int dim
orderfield
final Int32List order

Leaf buckets are contiguous ranges of this permutation of point indices.

childfield
final Int32List child

Per node: left child index (the right child is child + 1), or -1 for a leaf.

final Int32List splitDim
final Float64List splitLow

Per interior node: the largest coordinate on the low side and the smallest on the high side.

final Float64List splitHigh

Per interior node: the largest coordinate on the low side and the smallest on the high side.

startfield
final Int32List start

Per leaf: the range [start, end) of order.

endfield
final Int32List end

Per leaf: the range [start, end) of order.

rootMinfield
final Float64List rootMin

Bounding box of all points.

rootMaxfield
final Float64List rootMax

Bounding box of all points.

lengthgetter
int get length
nodeCountgetter
int get nodeCount

Methods

knnmethod
KnnResult knn(List<double> query, int k)

The k nearest points to query (length dim).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = KdTree(xy, 2).knn([70, 30], 3);
  for (var j = 0; j < 3; j++) {
    print('neighbour ${j + 1}: point ${r.indices[j]}, quadrance ${r.dist2[j]}');
  }
}
Output
neighbour 1: point 13, quadrance 40.0
neighbour 2: point 18, quadrance 85.0
neighbour 3: point 25, quadrance 164.0
knnBatchmethod
KnnResult knnBatch(Float64List queries, int k)

k nearest neighbours of every query in queries (interleaved), k per query.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final q = Float64List.fromList([10, 10, 90, 90, 50, 50]);
  final r = KdTree(xy, 2).knnBatch(q, 1);
  print('nearest point to each query: ${r.indices}');
}
Output
nearest point to each query: [15, 28, 1]
knnIntomethod
void knnInto(List<double> query, KnnHeap heap)

Fills heap (call KnnHeap.reset first) with the nearest points to query; allocates nothing.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final t = KdTree(xy, 2), heap = KnnHeap(4);
  for (final q in [[0.0, 0.0], [100.0, 0.0]]) {
    heap.reset();
    t.knnInto(q, heap);
    print('$q: worst of 4 nearest at quadrance ${heap.worst}');
  }
}
Output
[0.0, 0.0]: worst of 4 nearest at quadrance 2689.0
[100.0, 0.0]: worst of 4 nearest at quadrance 1844.0
radiusmethod
RadiusResult radius(List<double> query, double radius, {bool sorted = true})

Every point within radius of query, nearest first when sorted.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final r = KdTree(xy, 2).radius([50, 50], 22);
  print('${r.length} within 22, nearest first: ${r.indices}');
}
Output
6 within 22, nearest first: [1, 9, 24, 10, 18, 12]
int countWithin(List<double> query, double radius)

The number of points within radius of query (no result list).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(7);
  const n = 30;
  final xy = Float64List.fromList([for (var i = 0; i < 2 * n; i++) (rng.nextDouble() * 100).roundToDouble()]);
  final t = KdTree(xy, 2);
  final counts = [for (var r = 0; r <= 60; r += 5) [r, t.countWithin([50, 50], r.toDouble())]];
  print('within 30: ${t.countWithin([50, 50], 30)}');
}
Output
within 30: 8
class

Morton

abstract final class Morton

Morton (Z-order) codes: interleave the bits of integer cell coordinates so points close in space get close codes. Used to sort points for cache-friendly traversal, LBVH builds and GPU-friendly spatial hashing. 64-bit codes need native Raya ints (not the web's 53-bit numbers); morton3d30 fits a GPU uint.

Static

encode3staticmethod
static int encode3(int x, int y, int z)

3-D code from 21-bit coordinates (0 \cdots 2^{21} - 1 each), 63 bits.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print('encode3(1, 2, 3) = ${Morton.encode3(1, 2, 3)}');
  print('binary ${Morton.encode3(1, 2, 3).toRadixString(2)}');
}
Output
encode3(1, 2, 3) = 53
binary 110101
decode3staticmethod
static (int, int, int) decode3(int code)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Morton.decode3(Morton.encode3(5, 9, 2)));
}
Output
(5, 9, 2)
encode2staticmethod
static int encode2(int x, int y)

2-D code from 31-bit coordinates, 62 bits.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The Z-order curve through an 8 × 8 grid.
  final order = List<List<int>>.filled(64, const [0, 0]);
  for (var x = 0; x < 8; x++) {
    for (var y = 0; y < 8; y++) {
      order[Morton.encode2(x, y)] = [x, y];
    }
  }
  print('encode2(3, 5) = ${Morton.encode2(3, 5)}');
}
Output
encode2(3, 5) = 39
decode2staticmethod
static (int, int) decode2(int code)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print([for (var c = 0; c < 8; c++) Morton.decode2(c)]);
}
Output
[(0, 0), (1, 0), (0, 1), (1, 1), (2, 0), (3, 0), (2, 1), (3, 1)]
morton3d30staticmethod
static int morton3d30(double x, double y, double z)

30-bit 3-D code (10 bits per axis) of a point already normalised to [0, 1]^{3}: the LBVH / GPU form.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Morton.morton3d30(0, 0, 0));
  print(Morton.morton3d30(0.5, 0.5, 0.5));
  print(Morton.morton3d30(1, 1, 1));
}
Output
0
939524096
1073741823
final class KnnResult

The k nearest neighbours of one or more queries: indices and squared Euclidean distances dist2, k per query, nearest first. When the data set has fewer than k points the missing slots are -1 and +\infty.

Constructors

KnnResultconstructor
KnnResult(this.k, this.indices, this.dist2)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = KnnResult(2, Int32List.fromList([4, 1, 0, 3]), Float64List.fromList([1, 2, 0.5, 9]));
  print('${r.queries} queries of k = ${r.k}');
}
Output
2 queries of k = 2

Properties

kfield
final int k
indicesfield
final Int32List indices
dist2field
final Float64List dist2
queriesgetter
int get queries

Number of queries.

final class RadiusResult

Points within a radius of one query: indices and squared distances dist2, nearest first when sorted.

Constructors

RadiusResultconstructor
RadiusResult(this.indices, this.dist2)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = RadiusResult(Int32List.fromList([3, 7]), Float64List.fromList([0.25, 4]));
  print('${r.length} hits: ${r.indices}');
}
Output
2 hits: [3, 7]

Properties

indicesfield
final Int32List indices
dist2field
final Float64List dist2
lengthgetter
int get length
class

KnnHeap

final class KnnHeap

A fixed-capacity list of the best k candidates, kept sorted by insertion (k is small in practice; nanoflann's KNNResultSet does the same). Reused across queries so a batch search allocates nothing per query.

Constructors

KnnHeapconstructor
KnnHeap(this.k)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final h = KnnHeap(3);
  for (final (i, d) in [(0, 9.0), (1, 4.0), (2, 1.0), (3, 16.0), (4, 2.0)]) {
    h.add(i, d);
  }
  print('kept ${h.count}, worst ${h.worst}');
}
Output
kept 3, worst 4.0

Properties

kfield
final int k
idxfield
final Int32List idx
d2field
final Float64List d2
countfield
int count
worstgetter
double get worst

The current pruning bound: the k-th best distance, or \infty while fewer than k are held.

Methods

resetmethod
void reset()
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final h = KnnHeap(2)..add(0, 1)..add(1, 2);
  h.reset();
  print('after reset: count ${h.count}, worst ${h.worst}');
}
Output
after reset: count 0, worst Infinity
addmethod
void add(int index, double dist2)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final h = KnnHeap(2);
  h.add(5, 3);
  h.add(6, 1);
  h.add(7, 2); // replaces the worst (3)
  print('worst now ${h.worst}');
}
Output
worst now 2.0
abstract final class PointCloud

Point-cloud operations on interleaved xyz Float64List clouds (the layouts Open3D and PCL describe; the algorithms are the textbook ones, written here).

Static

centroidstaticmethod
static Float64List centroid(Float64List xyz)
Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  print('centroid ${PointCloud.centroid(xyz).map((v) => v.toStringAsFixed(3)).toList()}');
}
Output
centroid [5.039, 4.537, 5.094]
boundsstaticmethod
static (Float64List, Float64List) bounds(Float64List xyz)

(min xyz, max xyz).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final (lo, hi) = PointCloud.bounds(xyz);
  print('min ${lo.map((v) => v.toStringAsFixed(2)).toList()}, max ${hi.map((v) => v.toStringAsFixed(2)).toList()}');
}
Output
min [0.07, 0.02, 0.00], max [9.97, 9.88, 9.95]
voxelDownsamplestaticmethod
static Float64List voxelDownsample(Float64List xyz, double voxel)

Voxel-grid downsampling: one point per occupied voxel of size voxel, the mean of the points in it. Output order follows the first point of each voxel.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(3);
  const n = 200;
  final xyz = Float64List.fromList([for (var i = 0; i < 3 * n; i++) rng.nextDouble() * 10]);
  final d = PointCloud.voxelDownsample(xyz, 4);
  print('${n} points -> ${d.length ~/ 3} voxel centroids');
}
Output
200 points -> 27 voxel centroids
estimateNormalsstaticmethod
static Float64List estimateNormals(Float64List xyz, {int k = 10, List<double>? viewpoint, KdTree? tree})

Unit normals by PCA of each point's k nearest neighbours: the eigenvector of the smallest eigenvalue of the neighbourhood covariance. Normals point towards viewpoint when given (otherwise their sign is arbitrary).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Points on the plane z = 0.5x: every normal is ±(−0.5, 0, 1)/|…|.
  final rng = math.Random(2);
  final xyz = Float64List.fromList([for (var i = 0; i < 100; i++) ...(() { final x = rng.nextDouble(), y = rng.nextDouble(); return [x, y, 0.5 * x]; })()]);
  final nrm = PointCloud.estimateNormals(xyz, viewpoint: [0, 0, 10]);
  print('normal at point 0: ${nrm.sublist(0, 3).map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
normal at point 0: [-0.4472, -0.0000, 0.8944]
static Int32List removeStatisticalOutliers(Float64List xyz, {int k = 8, double stdRatio = 2})

Statistical outlier removal (PCL's StatisticalOutlierRemoval): the mean distance d_{i} from each point to its k nearest others; points with d_{i} > \mu + stdRatio·\sigma are outliers. Returns the inlier indices.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(5);
  final pts = <double>[for (var i = 0; i < 60; i++) ...[rng.nextDouble(), rng.nextDouble(), 0]];
  pts.addAll([5, 5, 0, -4, 3, 0]);
  final xyz = Float64List.fromList(pts);
  final keep = PointCloud.removeStatisticalOutliers(xyz);
  print('kept ${keep.length} of ${xyz.length ~/ 3}');
}
Output
kept 60 of 62
rigidTransformstaticmethod
static ({Float64List rotation, Float64List translation}) rigidTransform(Float64List a, Float64List b, {Float64List? weights})

Least-squares rigid transform taking points a onto corresponding points b (same count, interleaved): b \approx R \cdot a + t. Horn's closed-form quaternion method (1987): the rotation is the eigenvector of the largest eigenvalue of a symmetric 4 \times 4 matrix built from the cross-covariance, so it is always a proper rotation (no SVD reflection fix-up). weights optional. Returns R row-major (9) and t (3).

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 1]);
  // b = R a + t with R a quarter turn about z, t = (3, 1, 0).
  final b = Float64List.fromList([3, 1, 0, 3, 2, 0, 1, 1, 0, 2, 2, 1]);
  final f = PointCloud.rigidTransform(a, b);
  print('R = ${f.rotation.map((v) => v.toStringAsFixed(6)).toList()}');
  print('t = ${f.translation.map((v) => v.toStringAsFixed(6)).toList()}');
}
Output
R = [0.000000, -1.000000, -0.000000, 1.000000, 0.000000, -0.000000, 0.000000, -0.000000, 1.000000]
t = [3.000000, 1.000000, -0.000000]
icpstaticmethod
static ({Float64List rotation, Float64List translation, double rmse, int iterations}) icp(Float64List source, Float64List target, {int maxIterations = 50, double tolerance = 1e-10, double maxDistance = double.infinity})

Point-to-point ICP (Besl and McKay 1992): repeatedly match every source point to its nearest target point (k-d tree) and solve the rigid transform (rigidTransform) until the RMS error stops improving by more than tolerance. Returns the accumulated transform taking source onto target, the final RMS distance and the iteration count. Pairs farther than maxDistance are ignored.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final rng = math.Random(9);
  final target = Float64List.fromList([for (var i = 0; i < 80; i++) ...(() { final u = rng.nextDouble() * 2 * math.pi; return [math.cos(u) * 2, math.sin(u), 0.0]; })()]);
  final source = Float64List.fromList(target);
  final c = math.cos(0.3), s = math.sin(0.3);
  PointCloud.transform(Float64List.fromList([c, -s, 0, s, c, 0, 0, 0, 1]), Float64List.fromList([0.4, -0.2, 0]), source);
  final r = PointCloud.icp(source, target);
  print('ICP: rmse ${r.rmse.toStringAsExponential(2)} after ${r.iterations} iterations');
  final aligned = Float64List.fromList(source);
  PointCloud.transform(r.rotation, r.translation, aligned);
}
Output from the Raya VM
ICP: rmse 4.91e-16 after 13 iterations
transformstaticmethod
static void transform(Float64List r, Float64List t, Float64List xyz)

Applies x \to R \cdot x + t in place to interleaved xyz.

Example
import 'package:riptide_numerics_spatial/riptide_numerics_spatial.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 1, 1]);
  // b = R a + t with R a quarter turn about z, t = (3, 1, 0).
  final b = Float64List.fromList([3, 1, 0, 3, 2, 0, 1, 1, 0, 2, 2, 1]);
  final f = PointCloud.rigidTransform(a, b);
  final moved = Float64List.fromList(a);
  PointCloud.transform(f.rotation, f.translation, moved);
  print('moved ≈ b: ${[for (var i = 0; i < 12; i++) (moved[i] - b[i]).abs() < 1e-9].every((v) => v)}');
}
Output
moved ≈ b: true