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 which id sits where, and leaves indexing to the first query that needs it, so several Rebuilds in a tick cost one indexing.
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:
- Move the boxes: Space.Move on each, under the edge rules.
- Space.Rebuild with the items as they now stand.
- collide.Engine.Tick on the engine built by Space.CollideEngine: every two CanCollide boxes within reach of each other are paired, 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.
- 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.
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 or Cone.Profile 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. 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.
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;
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 ΒΆ
- type Capability
- type Cone
- type Config
- type CoverField
- type Edges
- type Item
- type ProfileField
- type Shadow
- type Space
- func (s *Space) Bounds() (width, height uint32, edges Edges)
- func (s *Space) CollideEngine(handler collide.Handler, cfg collide.Config) collide.Engine
- func (s *Space) Move(box *plane.AABB, delta geom.Vec) bool
- func (s *Space) MoveTo(box *plane.AABB, to geom.Vec) bool
- func (s *Space) Place(box *plane.AABB) bool
- func (s *Space) Query(box geom.AABB, want Capability, fn func(id uid.UID64)) int
- func (s *Space) Rebuild(items []Item)
- func (s *Space) Scan(observer uid.UID64, cone Cone, v *View) bool
- func (s *Space) WrapAABB(box geom.AABB) plane.AABB
- type View
Examples ΒΆ
Constants ΒΆ
This section is empty.
Variables ΒΆ
This section is empty.
Functions ΒΆ
This section is empty.
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 float64 // below Ο
Radius float64
// Transparency is Ο per entity: 1 as empty, 0.5 costs twice its depth, β€ 0 blocks; nil blocks all.
Transparency func(id uid.UID64) float64
// Eye is the height the observer looks from; it matters once Elevation or Ground is set.
Eye float64
// Elevation is the bottom and top of each entity; nil spans every entity over all heights.
Elevation func(id uid.UID64) (bottom, top float64)
// 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) float64
GroundStep float64
// 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
}
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 )
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 Shadow ΒΆ added in v1.8.0
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, 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) }
// 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 float64) { 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 (*Space) CollideEngine ΒΆ added in v1.5.0
CollideEngine builds an engine over the Space's CanCollide boxes, reporting to handler.
func (*Space) Move ΒΆ added in v1.5.0
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) MoveTo ΒΆ
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
Place puts a fresh box under the edge rules; false if it lies wholly past an open edge.
func (*Space) Query ΒΆ
Query calls fn for every indexed piece in box sharing want, seams included, and returns how many.
func (*Space) Rebuild ΒΆ added in v1.5.0
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.
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 float64) {
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 ΒΆ
Depths appends to dst the reach at k β₯ 2 angles evenly spaced across the cone.
func (*View) Entities ΒΆ
Entities calls fn for every entity in view, nearest first, and returns how many.
func (*View) Outline ΒΆ
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
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. |
|
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. |
