aabbworld

package module
v1.21.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

aabbworld

Go Version GoDoc License

aabbworld is a Go library for 2D worlds made of axis-aligned boxes (AABBs). It began as a set of operations on the boxes themselves and grew upward from there: a plane with its own edge rules (stop, wrap or open at each edge) and the transformations that move boxes on it, a spatial index over the boxes placed in it, a collision engine that separates the ones that overlap, and a line-of-sight scan. Space is the whole of it; geom and plane are its vocabulary.

Features  •  Installation  •  Example  •  Edges  •  Architecture  •  Benchmarks  •  Documentation

Design Goals

aabbworld is the geometry and the per-tick questions of a simulation, with no opinion about how the simulation stores its entities. It is built around a few principles:

  • The world is a slice. A Space is told its items as []Item — whose box, where it lies, what may be done with it — or as runs over the caller's own columns (RebuildRuns), read and pushed where they lie, and answers questions about them. It fits under any entity system, or none.
  • No hidden costs. Rebuild records the slice and defers indexing to the first query that needs it; several rebuilds in a tick cost one indexing. Boxes are read as they are now, so a collision tick needs no second rebuild for queries to see its pushes. Boxes that stand for good are handed over apart (RebuildStill) and indexed once, so a tick costs what moves.
  • Zero-allocation hot paths. Rebuilding, pairing, solving, querying and scanning reuse their buffers; a steady tick allocates nothing.
  • Edge rules are the plane's business. Wrapping, clamping and leaving are applied by the Space to a box once, and every index and query understands the wrapped pieces that result.
  • Native Go, one small dependency (kjkrol/uid) for entity identifiers, no CGO.

📦 Installation

aabbworld requires Go 1.27 or newer.

go get github.com/kjkrol/aabbworld

Optionally, build with GOEXPERIMENT=simd: on amd64, arm64 or wasm, the collision tick then tests the boxes of a crowded cell a vector at a time, and queries and sight test theirs likewise, with the same results (see Performance); aabbworld.SIMD() reports whether it does.

✨ Key Features

Area What you get
Boxes geom.Vec, geom.AABB: intersection, containment, penetration, axis distance
Plane-aware boxes plane.AABB keeps its size and how far it runs past a wrapping seam; its wrapped pieces follow (VisitFragments, DeepestOverlapWith)
Edge rules Per axis: stop whole, wrap (WrapX, WrapY, Torus) or open (OpenX, OpenY, boxes may leave)
Transformations Place, Move, MoveTo, WrapAABB fold a box into the space under its edge rules and say when it has left
Spatial index Rebuild from a slice, Query by rectangle and Capability mask, seams included; RebuildStill holds what stands apart, indexed once and never paired with itself
Collisions CollideEngine: pairs every two CanCollide boxes within reach, asks your Handler to confirm each overlap, separates them over a few passes, reports who moved and who left; Config.Field pushes boxes out of the solid ground of a grid through its open sides only, and out of walls at any angle (WallField) square to them
Sight Scan fills a View with what an observer sees through a Cone: entities nearest first, depth samples, or the lit outline; Cone.Transparency lets a forest shorten sight where a wall cuts it; Cone.Eye, Elevation and Ground give sight heights, so a hawk looks over the wall and a hill hides the plain behind it, and Cone.Profile reads a faceted ground along each ray exactly, a few points a cell; View.Shadows lists the ground out of sight, holes in a view drawn to its full reach; Cone.Cover walks the walls and forests of a grid cell by cell along each ray instead of holding them as entities

Example

One tick of a small world: move, rebuild, collide, then ask who is where and who sees whom. This is ExampleSpace and runs as a test, so it stays in step with the API.

package main

import (
	"fmt"
	"math"
	"slices"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/collide"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

// printer is a collide.Handler that confirms every pair and says what the engine did.
type printer struct{}

func (printer) Touch(_, _ uid.UID64, pen geom.Vec) (geom.Vec, bool) { return pen, true }
func (printer) Contact(a, b uid.UID64, pen geom.Vec) {
	fmt.Printf("contact %d-%d, penetration %s\n", a, b, pen)
}
func (printer) Moved(id uid.UID64, box plane.AABB) { fmt.Printf("moved %d to %s\n", id, box) }

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 100, Height: 100, Edges: aabbworld.Torus, BucketSize: 16,
	})
	if err != nil {
		panic(err)
	}

	// The world as a slice: whose box, where it lies, what may be done with it.
	items := []aabbworld.Item{
		{ID: 1, Box: plane.NewAABB(geom.NewVec(10, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 2, Box: plane.NewAABB(geom.NewVec(24, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 3, Box: plane.NewAABB(geom.NewVec(60, 10), 10, 10), Caps: aabbworld.CanCollide | aabbworld.Static},
	}
	for i := range items {
		space.Place(&items[i].Box)
	}
	engine := space.CollideEngine(printer{}, collide.Config{Reach: 0.5, Iterations: 8})

	// Tick: box 2 drifts left into box 1, the space is told, the engine separates them.
	space.Move(&items[1].Box, geom.NewVec(-6, 0))
	space.Rebuild(items)
	engine.Tick()

	// Query sees the boxes where the engine left them.
	var inQuarter []uid.UID64
	space.Query(geom.NewAABBAt(geom.NewVec(0, 0), 50, 50), aabbworld.AnyCapability, func(id uid.UID64) {
		inQuarter = append(inQuarter, id)
	})
	slices.Sort(inQuarter)
	fmt.Println("in the top-left quarter:", inQuarter)

	// Sight: what box 1 sees looking right.
	var view aabbworld.View
	cone := aabbworld.Cone{Direction: geom.NewVec(1, 0), HalfAngle: math.Pi / 8, Radius: 60}
	if space.Scan(1, cone, &view) {
		view.Entities(func(id uid.UID64, dist float32) { fmt.Printf("1 sees %d at distance %.0f\n", id, dist) })
	}
}
contact 1-2, penetration (-2,0)
moved 1 to {(9,10) (19,20)}
moved 2 to {(19,10) (29,20)}
in the top-left quarter: [1 2]
1 sees 2 at distance 5

Tick lifecycle

  1. Move the boxes with Space.Move (or MoveTo); the edge rules are applied to each.
  2. Rebuild with the items as they now stand, or RebuildRuns with runs over the caller's columns. This is the one stamp a Space needs: it records the slice, or the runs, and indexes lazily. What stands for good — trees, houses — goes to RebuildStill instead, once, and is kept across every Rebuild: queries see it, the engine pairs it with the moving boxes alone and never pushes it.
  3. Tick the engine. Every two CanCollide boxes within Reach of each other are paired; each overlapping pair is put to Handler.Touch, which may confirm it, refine the penetration, or veto it; confirmed pairs are separated over up to Iterations passes and reported by Contact; every pushed box is reported once by Moved, or listed by Engine.Left — with the box it came to rest at — when the push took it out through an open edge.
  4. Ask. Query and Scan see the pushed boxes as they are now.

Items must stay put between rebuilds — their boxes may move, but the slice may not grow, shrink or reorder without a Rebuild; the records under runs likewise, and their capabilities may not change.

Edges

Edges says what a box does at each edge of the world, per axis. The zero value stops it whole. WrapX and WrapY make an axis periodic: a box leaving by one edge comes back through the opposite one. OpenX and OpenY let a box leave; Place and Move return false once it is wholly outside, and it drops out of the index. Torus wraps both axes. An axis cannot both wrap and be open.

Conceptually a torus glues the top edge of the plane to the bottom, then the left edge to the right; this seam-stitching turns the rectangle into the surface shown below.

Torus

A box straddling a seam is held as its main piece plus up to three wrapped pieces, and every index and query understands them. This program moves a 2×2 box at the origin of a 16×16 torus by (-1,-1), so it wraps past the right and bottom edges and splits into the pieces plotted below (it is ExampleSpace_Move):

Wrapped AABB fragments

space, _ := aabbworld.NewSpace(aabbworld.Config{Width: 16, Height: 16, Edges: aabbworld.Torus, BucketSize: 4})

items := []aabbworld.Item{{ID: uid.UID64(1), Box: space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))}}
box := &items[0].Box
space.Move(box, geom.NewVec(-1, -1))
space.Rebuild(items)

fmt.Printf("New position: %s\n", box)
box.VisitFragments(func(pos plane.FragPosition, piece geom.AABB) bool {
	fmt.Printf("- Fragment %d: %s\n", pos, piece)
	return true
})
New position: {(15,15) (16,16)}
- Fragment 1: {(0,15) (1,16)}
- Fragment 2: {(15,0) (16,1)}
- Fragment 3: {(0,0) (1,1)}

Architecture

The packages form a strict acyclic graph; each imports only the layers below it. Every package has a doc.go describing what it brings.

Package Responsibility
github.com/kjkrol/uid 64-bit generational entity identifiers; a Space never mints one, it only names what it was told
geom The vocabulary: Vec and AABB, with intersection, containment, penetration and axis distance; no notion of a world
plane A box as a Space holds it: AABB with a Size and an Overhang, its wrapped pieces (VisitFragments), the deepest Overlap of two boxes
internal/plane The surface behind a Space: Edges rules and what they do to a box — Translate, Expand, WrapAABB, Left
internal/spatial The index: Grid over a slice of items with lazily built cells for Query and a counting-sorted sweep for Pairs; Capability, Resolution
internal/raycast Sight: a cone scan over any queryable index — the angular sweep, shadows, and the View it fills
collide The public contract of a collision engine: Config, Handler, Engine
internal/collide The engine behind it: Pairs from the grid → Solver → Handler, and who Left through an open edge
aabbworld (public) The package you import: Space, Item, Capability, Edges, Config, View, Cone; wires the rest together
geom ──► plane ──► internal/plane ──► internal/spatial ──► internal/collide ──┐
  │        │                                                                  ├─► aabbworld
  │        └──► collide ──────────────────────────────────────────────────────┤
  └───────────► internal/raycast ─────────────────────────────────────────────┘

⏱️ Performance

Measured on an Intel i5-8265U with the float32 boxes of v1.17.0 (see BENCHMARKS.md); every path below reports 0 allocs/op.

Operation Scene Cost
Collision tick (pair, ask, separate) 8,388 boxes, 10×10 each, covering 20% of a 2048×2048 torus 1.69 ms
Collision tick 33,554 boxes, 5×5 each, covering 20% of the same torus 7.5 ms
Collision tick, crowded cells 12,000 boxes 8×8 and 20 of 100×100, 256-unit buckets 7.30 ms; 2.32 ms with GOEXPERIMENT=simd
Rebuild + pairs + 8 queries 8,388 boxes, 5×5 each, on a 1024×1024 torus 1.12 ms
Solve confirmed pairs 13,547 candidate pairs, 3,763 contacts 2.78 ms
Scan a 90° cone and list what it sees 1,000 entities in sight range 26.4 µs
Scan a 90° cone through see-through entities, list and outline 1,000 entities, 3 in 10 at τ = 0.5 32.8 µs
The same scan with heights over a 32-unit heightfield 1,000 entities, 3 in 10 at τ = 0.5, ground sampled every 32 102 µs (3.1× the scan without heights)
Fold a box across the far corner (WrapAABB) torus 13 ns

Deep dive: per-scene tables, what each benchmark measures, and what the numbers taught us (why the index keeps two layouts, why Rebuild is lazy) are in BENCHMARKS.md.

make bench

Projects using aabbworld

  • gram — a game engine over the GOKe ECS and Ebitengine (formerly gokebiten); its world, collision and vision plugins are built on Space.

📖 Documentation

Contributing

Commit prefixes and conventions are in Contributor Recommendations.

License

MIT

Documentation

Overview

Package aabbworld is a 2D world of axis-aligned boxes: the boxes themselves, a plane with its own edge rules, a spatial index over the boxes placed in it, and the questions a simulation asks of them each tick — who is near whom, who is pushing whom apart, who sees what.

It began as a library of operations on the boxes (packages geom and plane) and grew upward from there: a plane the boxes move on (stop, wrap or open at each edge), a grid that indexes them, a collision engine that separates the ones that overlap, and a line-of-sight scan. Space is the whole of it; geom and plane are its vocabulary. It knows nothing of any entity system: it is told the world as a slice and answers questions about it.

Space and Item

A Space is built once by NewSpace from a Config: the world's size, what happens at its edges, and the side of one grid cell. It is then told the world by Space.Rebuild, as a slice of Item — whose box it is (a uid.UID64), where it lies (a plane.AABB), and what may be done with it (a Capability).

The items are a snapshot the caller owns. A Space keeps the slice it was last handed and reads the boxes in it as they are now, so the caller may move them between Rebuilds; what it may not do is add, drop or reorder items without a Rebuild. Rebuild itself is cheap: it records the slice, and leaves indexing to the first query that needs it, so several Rebuilds in a tick cost one indexing.

A caller that keeps its entities in columns of its own hands them over without copying, by Space.RebuildRuns: a Run is the ids of a column and where in each of its records lie the box and the Capability (RunOf works the offsets out from a slice of rows). The Space reads the boxes where they lie and a collision engine pushes them there, so the column is the only copy; the records must not move between slots until the last question before the next Rebuild.

Boxes that stand for good — trees, houses, a wall as an entity — are handed over apart, by Space.RebuildStill, in runs and items as RebuildRuns takes them. The Space indexes them once and keeps them across every Rebuild, which then speaks of the boxes that move alone: every question sees both, and a collision engine pairs a still box with the moving ones, never with another still one, and never pushes it. A tick then costs what moves, not what stands. An entity is still or moving, never both, and a still box stays where it is until the next RebuildStill.

Numbers

Every coordinate, size, distance and angle a Space takes or gives is a float32, so a box is 32 bytes. Whole units are exact up to 2^24 (16,777,216); between them the step is about 0.001 at 10,000 and 0.008 at 100,000, well under a unit in any world a game draws. Sight works its rays out in float64 inside and answers in float32. The collision engine takes two boxes overlapping by no more than a few such steps at their edges for touching, never pushing them apart: a share of so little moves neither box.

Edges

Edges says what a box does at each edge of the world, per axis. The zero value stops it whole: a box is clamped so it never leaves. WrapX and WrapY make the axis periodic — a box leaving by one edge comes back through the opposite one, and while it straddles the seam it is held as a main box plus up to three wrapped pieces (see plane.AABB.VisitFragments). OpenX and OpenY let a box leave; once wholly outside it is reported gone by Space.Place and Space.Move and dropped from the index. Torus wraps on both axes. An axis cannot both wrap and be open.

Space.Place, Space.Move and Space.MoveTo apply those rules to a box; Space.WrapAABB folds any rectangle into the space the same way.

Capability

A Capability is a set of up to eight bits that says what may be done with an item. Every question names the bits it wants and is answered only with items sharing at least one of them; AnyCapability accepts everything, Plain is geometry and nothing more. CanCollide is what a collision engine pairs up; Static marks a side a contact never shifts; Sensor marks one that is detected but separates nothing.

Tick lifecycle

One tick of a simulation reads:

  1. Move the boxes: Space.Move on each, under the edge rules.
  2. Space.Rebuild with the items as they now stand, or Space.RebuildRuns with the runs; the boxes of Space.RebuildStill stay as they were.
  3. collide.Engine.Tick on the engine built by Space.CollideEngine: every two CanCollide boxes within reach of each other are paired, but never two still ones, each overlapping pair is put to the handler's Touch, confirmed pairs are separated over a few passes and reported by Contact, and every box that was pushed is reported once by Moved — unless the push took it out through an open edge, in which case it is listed by collide.Engine.Left instead, with the box it came to rest at. With collide.Config.Field the engine also pushes every movable box out of the solid ground of a grid, in the same passes.
  4. Ask: Space.Query and Space.Scan see the pushed boxes as they are now; no further Rebuild is owed for that.

Queries and sight

Space.Query calls back for every indexed piece intersecting a rectangle, seams included — a box straddling a seam may be reported once per piece. Space.Scan fills a View with what one observer sees through a Cone: the entities in sight, nearest first (View.Entities), the reach of sight at evenly spaced angles (View.Depths), or the lit region as a fan of points (View.Outline). A View is a reusable buffer for one goroutine. Space.Read queries and scans from many goroutines at once while nothing writes the Space.

Sight has a budget of the cone's radius along every angle. An empty stretch costs its length; a stretch through an entity of transparency τ costs its length divided by τ; an entity at τ ≤ 0 blocks sight where it is met. A forest at τ = 0.5 is thus looked through at half the reach, a wall is not looked through at all. Cone.Transparency gives τ per entity and is nil by default, when everything blocks. Every entity sight reaches is seen, a forest looked into as much as a wall looked at.

Sight has heights once Cone.Elevation, Cone.Ground, Cone.Profile or Cone.Heights is set: the eye is Cone.Eye up, an entity spans its bottom to its top, the ground lies at Cone.Ground of a point and is sampled every Cone.GroundStep along a ray — or, for a ground of flat facets, Cone.Profile hands each ray the points where its slope changes, a few a cell in place of a sample every step, and what the ground hides is then exact; Cone.Heights is such a ground as data, a lattice of corner heights the scan walks itself, every point sunk by Cone.Bend times the distance squared. An entity is seen when the straight line from the eye to its top clears the ground and every nearer blocking entity's band, within the budget — a see-through entity charges only the stretch the line spends inside its band. The reach of an angle is the farthest lit ground, so a hawk looks over a wall the walker beside it is stopped by, and a hill hides the plain behind it from the lowland alone. View.Shadows lists the stretches of ground an observer cannot see within the radius, so a view with heights can be drawn to its full reach with holes where the ground is out of sight. Details are in internal/raycast.

Ground on a grid

Walls, forests and rock laid out on a grid need not be entities. Cone.Cover is a CoverField: for every ray the scan asks its owner for the stretches of the ray inside cells with cover — where the ray enters and leaves each cell, the band the cover spans, how see-through it is — and treats them as it treats entities, budget, walls and shadows alike; they are never listed as seen. The owner walks its cells exactly, so on a plane nothing behind a wall is read, and the cost of a scan follows the cells the rays cross, not how much cover the world holds or how it is laid out. collide.Config.Field is a collide.SolidField: for every movable box the engine asks for the solid boxes of the ground around it, with the sides of each that face open ground, and pushes the box out only through those — a box sliding along a wall of many cells never catches on a seam. One that is a collide.WallField hands walls at any angle besides — a railing along a slanted bridge — each a collide.FieldWall a box is pushed out of square to it, round a free end where that is shorter. A collide.FieldHandler hears of each contact with the ground once per entity and cell a tick.

SIMD

Built with GOEXPERIMENT=simd on amd64, arm64 or wasm, the wide code runs on the vectors of the simd package: 128 bits on Neon and wasm, 256 or 512 on amd64 as the CPU allows. The collision engine's pair sweep tests a crowded cell — eight entries or more — a vector of boxes at a time: one box against the next several, their edges loaded side by side, the cell's claim on each pair checked in the same pass. It finds the same pairs, in the same order, as the plain sweep, which every other build runs. Crowds in large buckets gain most, sparse cells nothing; see BENCHMARKS.md. Sight's cone, and Query without AVX2, test a cell's pieces a vector at a time from columns of the cells' edges, built with the cells once either has been asked; sight works out before each sweep where its rays enter and leave the boxes in sight, a vector of rays against a box at a time. It reports what the plain code reports, to the bit.

On an amd64 CPU with AVX2 the sweep, the cone and the rays run on kernels written for AVX2 instead, eight boxes or four rays at a time: there they are as fast as simd's or faster, at every width simd gives. Over a Cone.Heights field, with AVX2, sight walks the ground of four rays at a time, a ray to a lane, the corners of their cells read lane by lane. GODEBUG=simd=0 turns every kernel off; SIMD reports whether any runs.

Package dependencies

The packages form a strict acyclic graph. Each layer imports only layers below it:

Layer 0   geom              — the vocabulary: Vec, AABB
Layer 1   plane             — AABB with a Size and an Overhang, wrapped pieces, Overlap        (→ geom)
Layer 2   internal/plane    — Surface: the edge rules; Translate, Expand, WrapAABB, Left      (→ geom, plane)
Layer 3   internal/spatial  — Grid: the items, lazy cells for Query, a sweep for Pairs, a still
                              layer; Capability, Resolution                                   (→ geom, plane, internal/plane)
          internal/raycast  — View: a cone scan over any queryable index, shadows and depths  (→ geom)
          collide           — the public contract of an engine: Config, Handler, Engine       (→ geom, plane)
Layer 4   internal/collide  — Engine over a Grid: Pairs → Solver → Handler; Left               (→ geom, plane, internal/plane, internal/spatial)
Layer 5   aabbworld         — Space, Item, Capability, Edges, Config, View, Cone: the package
                              you import, wiring the rest together                           (→ all of the above)

Expressed as a directed graph (arrow = "is imported by"):

geom ──► plane ──► internal/plane ──► internal/spatial ──► internal/collide ──┐
  │        │                                                                  ├─► aabbworld
  │        └──► collide ──────────────────────────────────────────────────────┤
  └───────────► internal/raycast ─────────────────────────────────────────────┘

github.com/kjkrol/uid is an external module used throughout for 64-bit generational entity identifiers; a Space never mints one, it only names what it was told.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SIMD added in v1.18.0

func SIMD() bool

SIMD reports whether the collision engine's pair sweep tests a crowded cell a vector of boxes at a time, and queries and sight their boxes and rays several at a time: built with GOEXPERIMENT=simd on amd64, arm64 or wasm, and run where the simd package has hardware vectors (on amd64, AVX).

Types

type Capability

type Capability uint8

Capability is what may be done with an entity, as a set of up to eight bits — a question names the bits it wants, and only entities sharing one are answered with.

const (
	// Plain is an entity that is nothing but geometry; the zero value.
	Plain Capability = 0
	// CanCollide is an entity that takes part in collisions — what a CollideEngine pairs up.
	CanCollide Capability = 1 << 1
	// Static is an entity nothing shifts; a contact pushes only the other side.
	Static Capability = 1 << 2
	// Sensor is an entity only ever detected; a contact with it separates nothing.
	Sensor Capability = 1 << 3
	// AnyCapability accepts every entity.
	AnyCapability Capability = 0xFF
)

type Cone

type Cone struct {
	Direction geom.Vec
	HalfAngle float32 // below π
	Radius    float32
	// Transparency is τ per entity: 1 as empty, 0.5 costs twice its depth, ≤ 0 blocks; nil blocks all.
	Transparency func(id uid.UID64) float32
	// Eye is the height the observer looks from; it matters once Elevation or Ground is set.
	Eye float32
	// Elevation is the bottom and top of each entity; nil spans every entity over all heights.
	Elevation func(id uid.UID64) (bottom, top float32)
	// Ground is the height of the ground at a point, sampled every GroundStep along a ray (0: a
	// sixteenth of Radius); nil is flat ground at 0.
	Ground     func(p geom.Vec) float32
	GroundStep float32
	// Profile is the ground along each ray, exactly, in place of Ground sampled every GroundStep:
	// the points where its slope changes; Ground still stands a box on the ground. nil: none.
	Profile ProfileField
	// Cover is the ground cover of a world on a grid — walls, forests — walked cell by cell along
	// each ray instead of being entities in the Space; nil is none.
	Cover CoverField
	// Heights is the ground as a lattice of corner heights, read along each ray inside the scan in
	// place of Ground and Profile, which it stands in for; nil is none.
	Heights *HeightField
	// Bend is how far the ground sinks below its height with the square of the distance from the
	// eye (a world's curvature), applied to Heights alone; 0 is flat.
	Bend float32
}

Cone bounds a visibility query: a direction, a half-angle either side of it, how far it reaches, how see-through each entity is and, when sight has heights, where the eye is and how the world stands. The budget model behind Transparency and the sightlines behind Eye, Elevation and Ground are in the package doc.

type Config

type Config struct {
	// Width and Height of the world, in world units.
	Width, Height uint32
	// Edges is what happens to a box at the edges of the world; the zero value stops it whole.
	Edges Edges
	// BucketSize is the side of one grid cell in world units, rounded up to a power of two.
	BucketSize uint32
}

Config sizes a Space.

type CoverField added in v1.9.0

type CoverField = iraycast.CoverField

CoverField is what stands on the cells of a grid and holds sight back, as a ray meets it: Walk follows the ray from origin along the unit dir for length and calls visit, nearest first, for every stretch inside a cell with cover — where the ray enters and leaves the cell, the band the cover spans (bottom, top; ±Inf without heights) and how see-through it is (tau as Transparency: ≤ 0 blocks). visit returning false ends the walk. The owner of the grid walks it exactly (a DDA over its cells), so what lies behind a wall on a plane is never read.

type Edges

type Edges uint8

Edges is what happens to a box at the edges of the world, per axis; zero stops it whole.

const (
	// WrapX returns a box leaving by the left or right edge through the opposite one.
	WrapX Edges = 1 << iota
	// WrapY returns a box leaving by the top or bottom edge through the opposite one.
	WrapY
	// OpenX lets a box leave by the left or right edge; wholly outside, it is dropped from the index.
	OpenX
	// OpenY lets a box leave by the top or bottom edge; wholly outside, it is dropped from the index.
	OpenY
	// Torus wraps on both axes.
	Torus = WrapX | WrapY
)

func (Edges) WrapsX

func (e Edges) WrapsX() bool

WrapsX reports whether the left and right edges wrap.

func (Edges) WrapsY

func (e Edges) WrapsY() bool

WrapsY reports whether the top and bottom edges wrap.

type HeightField added in v1.19.0

type HeightField = iraycast.HeightField

HeightField is the ground as a lattice of corner heights over square cells: Cols by Rows corners, Cell apart, row by row from the world's origin (the corner (x, y) at Corners[y*Cols+x]). A cell is two flat triangles folded along the diagonal whose two corners differ less in height; off the lattice the ground is 0; on an axis that wraps the corner past the last is the first again.

type Item added in v1.5.0

type Item struct {
	ID   uid.UID64
	Box  plane.AABB
	Caps Capability
}

Item is one box a Rebuild hands the Space: whose it is, where it lies, what may be done with it.

type ProfileField added in v1.11.0

type ProfileField = iraycast.ProfileField

ProfileField is the ground along a ray, exactly: Along follows the ray from origin along the unit dir for length and calls visit, nearest first, with every point where the ground's slope changes — a ground of flat facets, the edges and folds of the cells the ray crosses — and with length itself: how far along (d, above 0) and the ground's height there; visit returning false ends the walk. Between those points the ground is straight, so what it hides is decided there alone: the owner of a faceted ground gives a ray a few points a cell, read off its corners, in place of a sample every GroundStep. A wrapping world's owner folds the ray onto the world itself.

type Run added in v1.14.0

type Run struct {
	IDs     []uid.UID64
	Base    unsafe.Pointer
	Stride  uintptr
	BoxOff  uintptr
	CapsOff uintptr
}

Run is a column of boxes in memory the caller owns: record i starts i·Stride bytes past Base, with its box at BoxOff and its Capability at CapsOff, and IDs[i] names it.

func RunOf added in v1.14.0

func RunOf[T any](
	ids []uid.UID64, rows []T, box func(*T) *plane.AABB, caps func(*T) *Capability,
) Run

RunOf is the run over rows, named by ids, with the box and the capability that box and caps point at in a row.

type Shadow added in v1.8.0

type Shadow struct {
	Sample   int
	From, To float32
}

Shadow is a stretch of ground along one of the angles a View reads, From to To away from the observer, that the observer cannot see; Sample is the angle's index, as in Depths.

type Space

type Space struct {
	Config
	// contains filtered or unexported fields
}

Space is a plane with edge rules and a grid over the items of its last Rebuild, read as they are now: a Tick that pushes them is seen by the next Query without another Rebuild.

Example

ExampleSpace is one tick of a small world: move, rebuild, collide, then ask who is where and who sees whom.

package main

import (
	"fmt"
	"math"
	"slices"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/collide"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

// printer is a collide.Handler that confirms every pair and says what the engine did.
type printer struct{}

func (printer) Touch(_, _ uid.UID64, pen geom.Vec) (geom.Vec, float32, bool) { return pen, 0.5, true }
func (printer) Contact(a, b uid.UID64, pen geom.Vec) {
	fmt.Printf("contact %d-%d, penetration %s\n", a, b, pen)
}
func (printer) Moved(id uid.UID64, box plane.AABB) { fmt.Printf("moved %d to %s\n", id, box) }

// ExampleSpace is one tick of a small world: move, rebuild, collide, then ask who is where and
// who sees whom.
func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 100, Height: 100, Edges: aabbworld.Torus, BucketSize: 16,
	})
	if err != nil {
		panic(err)
	}

	// The world as a slice: whose box, where it lies, what may be done with it.
	items := []aabbworld.Item{
		{ID: 1, Box: plane.NewAABB(geom.NewVec(10, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 2, Box: plane.NewAABB(geom.NewVec(24, 10), 10, 10), Caps: aabbworld.CanCollide},
		{ID: 3, Box: plane.NewAABB(geom.NewVec(60, 10), 10, 10), Caps: aabbworld.CanCollide | aabbworld.Static},
	}
	for i := range items {
		space.Place(&items[i].Box)
	}
	engine := space.CollideEngine(printer{}, collide.Config{Reach: 0.5, Iterations: 8})

	// Tick: box 2 drifts left into box 1, the space is told, the engine separates them.
	space.Move(&items[1].Box, geom.NewVec(-6, 0))
	space.Rebuild(items)
	engine.Tick()

	// Query sees the boxes where the engine left them.
	var inQuarter []uid.UID64
	space.Query(geom.NewAABBAt(geom.NewVec(0, 0), 50, 50), aabbworld.AnyCapability, func(id uid.UID64) {
		inQuarter = append(inQuarter, id)
	})
	slices.Sort(inQuarter)
	fmt.Println("in the top-left quarter:", inQuarter)

	// Sight: what box 1 sees looking right.
	var view aabbworld.View
	cone := aabbworld.Cone{Direction: geom.NewVec(1, 0), HalfAngle: math.Pi / 8, Radius: 60}
	if space.Scan(1, cone, &view) {
		view.Entities(func(id uid.UID64, dist float32) { fmt.Printf("1 sees %d at distance %.0f\n", id, dist) })
	}
}
Output:
contact 1-2, penetration (-2,0)
moved 1 to {(9,10) (19,20)}
moved 2 to {(19,10) (29,20)}
in the top-left quarter: [1 2]
1 sees 2 at distance 5

func NewSpace

func NewSpace(cfg Config) (*Space, error)

NewSpace builds a Space, fitting the world into the nearest power-of-two grid.

func (*Space) Bounds

func (s *Space) Bounds() (width, height uint32, edges Edges)

Bounds is the world's size and what happens at its edges.

func (*Space) CollideEngine added in v1.5.0

func (s *Space) CollideEngine(handler collide.Handler, cfg collide.Config) collide.Engine

CollideEngine builds an engine over the Space's CanCollide boxes, reporting to handler.

func (*Space) Move added in v1.5.0

func (s *Space) Move(box *plane.AABB, delta geom.Vec) bool

Move moves box by delta under the edge rules; false once it has left by an open edge.

Example
package main

import (
	"fmt"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 16, Height: 16, Edges: aabbworld.Torus, BucketSize: 4,
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	items := []aabbworld.Item{{ID: uid.UID64(1), Box: space.WrapAABB(geom.NewAABBAt(geom.NewVec(0, 0), 2, 2))}}
	box := &items[0].Box
	space.Move(box, geom.NewVec(-1, -1))
	space.Rebuild(items)

	fmt.Printf("New position: %s\n", box)
	box.VisitFragments(func(pos plane.FragPosition, piece geom.AABB) bool {
		fmt.Printf("- Fragment %d: %s\n", pos, piece)
		return true
	})
}
Output:
New position: {(15,15) (16,16)}
- Fragment 1: {(0,15) (1,16)}
- Fragment 2: {(15,0) (16,1)}
- Fragment 3: {(0,0) (1,1)}

func (*Space) MoveRun added in v1.15.0

func (s *Space) MoveRun(run Run, deltas []geom.Vec, left []uid.UID64) []uid.UID64

MoveRun is Move of the box of record i of run by deltas[i], for every i whose delta is not zero. It returns left with the ID of every box it moved that has left by an open edge appended.

func (*Space) MoveTo

func (s *Space) MoveTo(box *plane.AABB, to geom.Vec) bool

MoveTo puts box with its top-left at to, under the edge rules; false once it has left that way.

func (*Space) Place added in v1.5.0

func (s *Space) Place(box *plane.AABB) bool

Place puts a fresh box under the edge rules; false if it lies wholly past an open edge.

func (*Space) Query

func (s *Space) Query(box geom.AABB, want Capability, fn func(id uid.UID64)) int

Query calls fn for every indexed piece in box sharing want, seams included, and returns how many: on a wrapping axis a box ending exactly on the seam meets what begins on its other side; past an edge that does not wrap it meets what hangs out there and nothing else.

func (*Space) QueryCone added in v1.19.0

func (s *Space) QueryCone(
	origin, dir geom.Vec, halfAngle, radius float32, want Capability, fn func(id uid.UID64),
) int

QueryCone calls fn for every indexed piece that may reach into the cone — within radius of origin and, for a cone narrower than a half-turn, not wholly beyond either of its edges — sharing want, seams included, and returns how many; a piece straddling a seam may be reported more than once, one just outside may be reported, one inside is never missed.

func (*Space) Read added in v1.15.0

func (s *Space) Read() *SpaceRead

Read reads s.

func (*Space) Rebuild added in v1.5.0

func (s *Space) Rebuild(items []Item)

Rebuild hands the Space items, which must stay put until the next Rebuild. Indexing waits for the first Query or Scan that needs it, so several Rebuilds in a row cost one indexing.

func (*Space) RebuildRuns added in v1.14.0

func (s *Space) RebuildRuns(runs []Run, items []Item)

RebuildRuns is Rebuild over the boxes of runs and then of items, read where they lie: Query and Scan see them as they are, and a Tick pushes them in place; a box may move between Rebuilds, a Capability may not. Until the last Query, Scan or Tick before the next Rebuild, the memory under both must hold the same records in the same places; a caller that moves records, as an ECS does when entities migrate (in goke, once any table's ChunkSnapshot.TableVer changed), gathers its runs again and rebuilds. The boxes of RebuildStill are left as they are.

func (*Space) RebuildStill added in v1.21.0

func (s *Space) RebuildStill(runs []Run, items []Item)

RebuildStill hands the Space the boxes that stand until the next RebuildStill, over runs and items held as RebuildRuns holds its own but indexed once, however many Rebuilds follow. Every question sees them beside the boxes of Rebuild, and a Tick pairs them with those alone, never moving them; an entity is one or the other, never both.

func (*Space) Scan

func (s *Space) Scan(observer uid.UID64, cone Cone, v *View) bool

Scan fills v with what observer sees through cone and reports whether it could.

func (*Space) WrapAABB

func (s *Space) WrapAABB(box geom.AABB) plane.AABB

WrapAABB folds any rectangle into the space: wrapped pieces on a wrapping axis, else clipped.

type SpaceRead added in v1.15.0

type SpaceRead struct {
	// contains filtered or unexported fields
}

SpaceRead reads a Space: what lies where and what an observer sees, from as many goroutines at once as read it while nothing writes the Space; a Scan's View is one goroutine's.

func (*SpaceRead) Bounds added in v1.15.0

func (r *SpaceRead) Bounds() (width, height uint32, edges Edges)

Bounds is the Space's Bounds.

func (*SpaceRead) Query added in v1.15.0

func (r *SpaceRead) Query(box geom.AABB, want Capability, fn func(id uid.UID64)) int

Query is the Space's Query.

func (*SpaceRead) QueryCone added in v1.19.0

func (r *SpaceRead) QueryCone(
	origin, dir geom.Vec, halfAngle, radius float32, want Capability, fn func(id uid.UID64),
) int

QueryCone is the Space's QueryCone.

func (*SpaceRead) Ready added in v1.15.0

func (r *SpaceRead) Ready()

Ready indexes the Space as the first Query or Scan after a Rebuild would: called before readers fan out, none of them waits for another to index it.

func (*SpaceRead) Scan added in v1.15.0

func (r *SpaceRead) Scan(observer uid.UID64, cone Cone, v *View) bool

Scan is the Space's Scan.

func (*SpaceRead) WrapAABB added in v1.15.0

func (r *SpaceRead) WrapAABB(box geom.AABB) plane.AABB

WrapAABB is the Space's WrapAABB.

type View

type View struct {
	// contains filtered or unexported fields
}

View is one observer's line of sight: filled by Space.Scan, then read as many ways as needed. The zero value is ready; it must not be copied once scanned, and serves one goroutine.

Example
package main

import (
	"fmt"
	"math"

	"github.com/kjkrol/aabbworld"
	"github.com/kjkrol/aabbworld/geom"
	"github.com/kjkrol/aabbworld/plane"
	"github.com/kjkrol/uid"
)

func main() {
	space, err := aabbworld.NewSpace(aabbworld.Config{
		Width: 1000, Height: 1000,
		BucketSize: 256,
	})
	if err != nil {
		panic(err)
	}

	const guard = uid.UID64(1)
	space.Rebuild([]aabbworld.Item{
		{ID: guard, Box: plane.NewAABB(geom.NewVec(100, 100), 10, 10)},
		{ID: uid.UID64(2), Box: plane.NewAABB(geom.NewVec(300, 100), 10, 10)},
		{ID: uid.UID64(3), Box: plane.NewAABB(geom.NewVec(500, 100), 10, 10)},
	})

	cone := aabbworld.Cone{
		Direction: geom.NewVec(1.0, 0.0),
		HalfAngle: math.Pi / 6,
		Radius:    600,
	}

	var view aabbworld.View
	var fog []geom.Vec

	grew := 0
	for tick := 1; tick <= 3; tick++ {
		before := cap(fog)
		if !space.Scan(guard, cone, &view) {
			continue
		}

		view.Entities(func(id uid.UID64, dist float32) {
			if tick == 1 {
				fmt.Printf("sees %d at %.0f\n", id, dist)
			}
		})

		fog = view.Outline(0, fog[:0])
		if cap(fog) != before {
			grew++
		}
	}
	fmt.Printf("outline buffer grew %d time(s) over 3 ticks\n", grew)
}
Output:
sees 2 at 195
outline buffer grew 1 time(s) over 3 ticks

func (*View) Depths

func (v *View) Depths(k int, dst []float32) []float32

Depths appends to dst the reach at k ≥ 2 angles evenly spaced across the cone.

func (*View) Entities

func (v *View) Entities(fn func(id uid.UID64, dist float32)) int

Entities calls fn for every entity in view, nearest first, and returns how many.

func (*View) Outline

func (v *View) Outline(maxArcStep float32, dst []geom.Vec) []geom.Vec

Outline appends the lit region to dst as a fan from the observer; maxArcStep 0 picks a default.

func (*View) Shadows added in v1.8.0

func (v *View) Shadows(k int, dst []Shadow) []Shadow

Shadows appends to dst the stretches of ground the observer cannot see within the radius, at the same k ≥ 2 angles as Depths: with heights every run of hidden ground — behind a crest, in a wall's shadow, past a cliff — up to where ground is lit again; on a plane, the reach to the radius.

Directories

Path Synopsis
Package collide is the contract of a Space's collision engine: what it is told (Config), whom it reports to (Handler), and what a caller drives (Engine).
Package collide is the contract of a Space's collision engine: what it is told (Config), whom it reports to (Handler), and what a caller drives (Engine).
Package geom holds the 2D vocabulary of aabbworld: Vec, a point or a displacement, and AABB, an axis-aligned box.
Package geom holds the 2D vocabulary of aabbworld: Vec, a point or a displacement, and AABB, an axis-aligned box.
internal
collide
Package collide is the engine behind the public collide contract: it finds the overlapping items of one grid, separates them and reports as it goes.
Package collide is the engine behind the public collide contract: it finds the overlapping items of one grid, separates them and reports as it goes.
plane
Package plane is the surface behind a Space: the edge rules of a bounded plane or a torus, and what they do to the public plane's boxes — folding, moving, growing, and telling when one has left.
Package plane is the surface behind a Space: the edge rules of a bounded plane or a torus, and what they do to the public plane's boxes — folding, moving, growing, and telling when one has left.
raycast
Package raycast is the state and the algorithm behind the public View of package aabbworld: what one observer sees through a cone, worked out over any index that can be queried by rectangle.
Package raycast is the state and the algorithm behind the public View of package aabbworld: what one observer sees through a cone, worked out over any index that can be queried by rectangle.
simdx
Package simdx is what the wide code needs beside the portable simd package: whether vectors run in hardware and which kernels run on them, how far past its data a slice loaded a vector at a time must run, and a mask as a bitmask, one bit a lane, which simd has no method for.
Package simdx is what the wide code needs beside the portable simd package: whether vectors run in hardware and which kernels run on them, how far past its data a slice loaded a vector at a time must run, and a mask as a bitmask, one bit a lane, which simd has no method for.
spatial
Package spatial is the index behind a Space: a cell grid over a slice of items, answering range queries and finding every two items close enough to matter.
Package spatial is the index behind a Space: a cell grid over a slice of items, answering range queries and finding every two items close enough to matter.
Package plane is a box as a Space holds it: a geom.AABB that knows its own size and how far it runs past the far edges of a wrapping world, so that its wrapped pieces follow from it.
Package plane is a box as a Space holds it: a geom.AABB that knows its own size and how far it runs past the far edges of a wrapping world, so that its wrapped pieces follow from it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL