A tiny, fast 3D spatial partition for .NET using dynamic AABB tree (Also known as BVH) that you can trust to handle thousands of objects.
Define your game object with a way to get a tight bounding box enclosing it. The library doesn't care about any other details.
using System;
using System.Numerics;
using Playmaker.Spatial;
public sealed class Asteroid : ISpatialObject
{
public int Id { get; }
public AABB Bounds { get; set; }
public Asteroid(int id, Vector3 center)
{
Id = id;
Bounds = AABB.FromCenterAndSize(center, new Vector3(1, 1, 1));
}
}
var space = new SpatialPartition<Asteroid>();
var a = new Asteroid(1, new Vector3( 0, 0, 0));
var b = new Asteroid(2, new Vector3(10, 0, 0));
space.Insert(a);
space.Insert(b);
// AABB query
var nearOrigin = space.Query(AABB.FromCenterAndSize(Vector3.Zero, new Vector3(5, 5, 5))); // Or new AABB(min, max)
// First-hit raycast
var hitSomething = space.Raycast(new Ray(new Vector3(-5, 0, 0), Vector3.UnitX), out var hit);
if (hitSomething)
{
// hit.Object is your Asteroid, hit.Distance is distance along the ray
}
// "Penetrating" raycast means keep going through volumes and collect every hit along the ray,
// sorted by entry distance. Like Unity's Physics.RaycastAll.
var allHits = space.RaycastPenetrating(new Ray(new Vector3(-5, 0, 0), Vector3.UnitX));
// Each hit has Object, Distance, and even EntryPoint/ExitPoint for effects like bullet holes.
// Move an object: you must call Update when the objects bounds change.
a.Bounds = AABB.FromCenterAndSize(new Vector3(2, 0, 0), new Vector3(1, 1, 1));
space.Update(a);
// snapshot the whole tree for debugging; you could hook this up to a UI or something.
var tree = space.GetTreeInfo();
if (tree is not null)
{
Console.WriteLine(tree);
}
// Remove when gone
space.Remove(b);This class is not thread-safe. It’s fast enough to live on your main thread, but if you want to update/query from multiple threads, you're responsible to guard access.
There’s a small test project (Playmaker.Spatial.Tests) that exercises the real-world bits you’ll care about.
Run them from the repo root:
dotnet testThis project is licensed under Mozilla Public License 2.0. See LICENSE
This project stands on the shoulders of giants. The core idea is heavily inspired by the dynamic AABB tree in Box2D. I also learned significantly from Emmet O’Toole’s excellent Unity port, go read it:
https://github.com/EmmetOT/BoundingVolumeHierarchy/
Thank you for the groundwork and clarity. Any mistakes here are mine.