Documentation
¶
Overview ¶
+game:group:name=collision
Package collision finds overlapping colliders: an entity with a gfx.Transform and a Collider (a shape, the layers it is on and the layers it reacts to) is tested against the others every tick. The System keeps the World's Space: it sends Enter and Exit events through the ECS event queue, keeps the current [Contact]s and answers point, rect and ray queries, also against tile grids (TileGrid).
Detection only: nothing is moved. The broad phase (Broadphase, a uniform Grid by default), the narrow phase (Space.RegisterPair) and the pair filter (Config.Filter) can each be replaced or extended.
The rule for who reacts: a collider detects another when its Mask has a layer the other is on, and each detecting side gets its own event, with itself as Self. See doc/guide/engine/collision.md.
Package game never imports collision: add NewSystem to the stage that should run it.
Index ¶
- Constants
- Variables
- func ColliderColor(l Layers) gfx.Color
- func NameLayers(names map[Layers]string)
- type BoundsFunc
- type Broadphase
- type Collider
- type Config
- type Contact
- type Enter
- type Exit
- type Grid
- type Layers
- type NarrowFunc
- type OneWay
- type Pair
- type Proxy
- type RayHit
- type Shape
- type ShapeKind
- type Space
- func (s *Space) AddTiles(grid TileGrid, opts TileOptions)
- func (s *Space) AllContacts() []Contact
- func (s *Space) Contacts(e ecs.Entity) []Contact
- func (s *Space) QueryPoint(p gfx.Vec2, mask Layers) iter.Seq[ecs.Entity]
- func (s *Space) QueryRect(r gfx.Rect, mask Layers) iter.Seq[ecs.Entity]
- func (s *Space) QueryShapes(r gfx.Rect, mask Layers) iter.Seq[*Shape]
- func (s *Space) Raycast(from, to gfx.Vec2, mask Layers) (RayHit, bool)
- func (s *Space) RegisterPair(a, b ShapeKind, fn NarrowFunc)
- func (s *Space) RegisterShape(kind ShapeKind, bounds BoundsFunc)
- func (s *Space) RemoveTiles(grid TileGrid) bool
- func (s *Space) Shapes() iter.Seq[*Shape]
- func (s *Space) StaticsChanged()
- func (s *Space) TileGrids() iter.Seq2[TileGrid, TileOptions]
- func (s *Space) Tiles(grid TileGrid) (TileOptions, bool)
- type Stay
- type System
- type TileGrid
- type TileOptions
Constants ¶
const DefaultCellSize = 64
DefaultCellSize is the cell size of a Grid when none is given, in world units. A good cell is about twice the size of a typical collider.
const MaxGridProxies = maxProxy + 1
MaxGridProxies is the number of proxies a Grid can hold.
Variables ¶
var (
CID_Collider = ecs.RegisterComp[Collider]()
)
Functions ¶
func ColliderColor ¶
ColliderColor returns the debug outline color of a collider on layers l: the color of its lowest layer, from a palette of eight that repeats.
func NameLayers ¶
NameLayers gives single layers names that Layers.String and the debug overlay print instead of numbers. Later calls add to or replace earlier names. It changes no behavior; call it at startup.
Panics with "collision: NameLayers: <l> is not a single layer" if a key holds no layer or more than one.
Types ¶
type BoundsFunc ¶
BoundsFunc returns the world bounds of a custom-kind collider. t.Scale is already (1, 1) when the Transform's is zero.
type Broadphase ¶
type Broadphase interface {
// Reset drops every proxy.
Reset()
// Insert adds a proxy with the given world bounds, layer set and mask.
Insert(id Proxy, bounds gfx.Rect, layer, mask Layers)
// Pairs appends every pair of proxies whose bounds overlap (share an
// area) and in which at least one side detects the other (its mask holds
// a layer of the other), each pair once, in any order, and returns the
// extended slice. A pair that no side detects may be left out, which
// keeps a crowd of bullets that ignore each other free.
Pairs(out []Pair) []Pair
// Query appends every proxy whose bounds intersect q, whatever its layers, each once, and
// returns the extended slice. An axis on which q has zero size matches
// when q lies in [Min, Max) of the proxy's bounds, so a point query
// works as gfx.Rect.Contains.
Query(q gfx.Rect, out []Proxy) []Proxy
}
Broadphase finds candidate pairs cheaply; the narrow phase tests them. The Space uses two: one for dynamic colliders, refilled every tick, and one for static colliders, refilled when one of them changes. Grid is the default; a sweep-and-prune or a tree can take its place through Config.
The methods append to a slice the caller owns instead of taking a callback, so a Space calls them through the interface without allocating.
type Collider ¶
type Collider struct {
// Shape is ShapeRect, ShapeCircle, ShapeAnimBody or a custom kind.
Shape ShapeKind
// Offset is added to Transform.Pos: the top-left corner of a rect, the
// center of a circle.
Offset gfx.Vec2
// Size is the width and height of a rect, the radius (in X) of a
// circle.
Size gfx.Vec2
// Layer is the bitmask of layers this collider is on. Zero means
// DefaultLayer (layer 0).
Layer Layers
// Mask is the bitmask of layers this collider reacts to: it detects the
// colliders on them. Zero reacts to nothing (a coin, a wall).
Mask Layers
// Static marks a collider that does not move on its own. Static pairs
// are never tested; a static collider that is moved anyway is picked up
// on the next tick.
Static bool
// Sensor reports contacts but never pushes (for physics; detection
// treats every collider the same).
Sensor bool
// OneWay blocks only from one side (for physics): 0 every side, 1 up,
// 2 down, 3 left, 4 right.
OneWay OneWay
}
Collider gives an entity with a gfx.Transform a collision shape. The shape is axis-aligned: Transform.Scale scales Offset and Size (a negative scale mirrors), Transform.Rot is ignored.
+game:component
func (*Collider) DetectedBy ¶
DetectedBy reports whether other reacts to c.
func (*Collider) Detects ¶
Detects reports whether c reacts to other: c's Mask has a layer other is on. This is the one rule events, contacts and physics follow.
func (*Collider) LayerOrDefault ¶
LayerOrDefault returns c.Layer, or DefaultLayer when it is zero.
type Config ¶
type Config struct {
// CellSize is the cell size of the default grid broad phases, in world
// units; zero is DefaultCellSize. Raycast also queries the broad phases
// in pieces of this length.
CellSize float32
// Broadphase replaces the grid of the dynamic colliders, refilled every
// run; StaticBroadphase the grid of the static ones, refilled when one
// of them changes. Nil uses a Grid of CellSize.
Broadphase, StaticBroadphase Broadphase
// Filter, when set, decides per detecting side whether self reacts to
// other, after the mask test passed: a bullet ignores its shooter. It is
// not called for tile grids.
Filter func(self, other ecs.Entity) bool
// Stay, when set, also sends a Stay event every run for each pair that
// is still in contact. Off by default: a pair that stays in contact (a
// hero on a floor, a crowd) then costs an event per tick; read
// Space.Contacts instead where that is enough.
Stay bool
}
Config configures the System of a World.
type Contact ¶
type Contact struct {
// Self is the detecting entity, Other the detected one; Other is the
// zero Entity when the contact is with a tile grid.
Self, Other ecs.Entity
// Normal is the unit vector that points from Self out of Other: the
// direction to push Self.
Normal gfx.Vec2
// Depth is the penetration along Normal, >= 0.
Depth float32
// Tiles is the tile grid, for a contact with one; Cell is then the
// solid cell.
Tiles TileGrid
Cell image.Point
// contains filtered or unexported fields
}
Contact is one overlap seen from the side that detects it: Self's Mask has a layer Other is on. When both detect each other there are two contacts, one per side, with opposite normals.
type Enter ¶
type Enter struct{ Contact }
Enter is sent when Self starts detecting Other: once per detecting side and pair, and once per (collider, tile grid) however many cells touch. The Contact is the first one of the pair this tick.
type Exit ¶
type Exit struct {
Self, Other ecs.Entity
// Tiles is the tile grid of a tile pair, else nil.
Tiles TileGrid
}
Exit is sent when Self stops detecting Other: they no longer overlap, the mask or filter no longer accepts the pair, the tile grid was removed, or either entity was deleted or lost its Collider (then the entity in the event is stale; check World.IsAlive).
type Grid ¶
type Grid struct {
// contains filtered or unexported fields
}
Grid is the default Broadphase: a uniform grid of square cells. Each proxy is entered in every cell its bounds touch. The entries are a sorted slice instead of a hash map, so a rebuild reuses its memory, does not allocate once warm, and reads the entries in order.
Cell coordinates are clamped to ±2^19 cells (±33 million world units with 64-unit cells): far-away colliders share the edge cells, which costs speed, not correctness. A grid holds at most 2^24 proxies.
func NewGrid ¶
NewGrid returns an empty grid with square cells of the given size in world units; zero or less uses DefaultCellSize.
func (*Grid) Insert ¶
Insert implements Broadphase. Bounds with NaN coordinates are dropped.
Panics with "collision: Grid proxy <id> out of range" for a negative id or one of MaxGridProxies or more.
type Layers ¶
type Layers uint32
Layers is a bitmask of collision layers 0..31. Name single layers once with Layer and combine them with LayersOf and the methods, so game code never spells out bit operations:
var (
Player = collision.Layer(1)
Wall = collision.Layer(4)
)
hero := collision.Collider{Layer: Player, Mask: collision.LayersOf(Wall)}
const ( // NoLayers is the empty set. NoLayers Layers = 0 // DefaultLayer is layer 0, where a collider with a zero Layer is. DefaultLayer Layers = 1 // AllLayers has every layer. AllLayers Layers = ^Layers(0) )
Common layer sets.
func Layer ¶
Layer returns the set holding only layer n.
Panics with "collision: layer <n> out of range 0..31" for other n.
type NarrowFunc ¶
NarrowFunc tests two shapes for overlap. normal is the unit vector that points from self out of other (the direction to push self), depth the penetration along it (>= 0). Shapes that only touch do not overlap.
type OneWay ¶
type OneWay uint8
OneWay makes a collider or a tile grid block only from one side. Package collision stores it and reports it; package physics applies it.
+game:enum
const ( // OneWayNone blocks from every side. OneWayNone OneWay = iota // OneWayUp blocks only bodies coming from above, moving down onto it: a // platform you can jump through from below. OneWayUp // OneWayDown blocks only bodies coming from below. OneWayDown // OneWayLeft blocks only bodies coming from the left. OneWayLeft // OneWayRight blocks only bodies coming from the right. OneWayRight )
One-way directions. The direction names the blocking face.
type Pair ¶
type Pair struct{ A, B Proxy }
Pair is a candidate pair of proxies from Broadphase.Pairs.
type Proxy ¶
type Proxy int32
Proxy identifies a shape in a Broadphase: the index the Space gave it for this tick.
type RayHit ¶
type RayHit struct {
// Entity is the collider hit; the zero Entity for a tile.
Entity ecs.Entity
// Tiles and Cell are the grid and cell hit, for a tile.
Tiles TileGrid
Cell image.Point
// Point is where the ray enters the shape, Normal the unit normal of the
// face it enters through. A ray that starts inside a shape hits it at
// its start with a zero Normal.
Point, Normal gfx.Vec2
// Fraction is the distance to Point as a fraction of the ray, in [0, 1].
Fraction float32
}
RayHit is where a ray first hits a collider or a solid tile.
type Shape ¶
type Shape struct {
// Entity owns the collider; the zero Entity for a tile cell.
Entity ecs.Entity
// Kind is the collider's kind, with ShapeAnimBody turned into
// ShapeRect.
Kind ShapeKind
// Bounds is the axis-aligned box around the shape, in world units.
Bounds gfx.Rect
// Center is the circle's center, or the middle of Bounds for other
// kinds.
Center gfx.Vec2
// Radius is the circle's radius in world units, zero for other kinds.
Radius float32
// Layer is the collider's layer set, with the zero-Layer default
// applied; Mask is its mask.
Layer, Mask Layers
// Pos and Scale are the entity's Transform.Pos and Transform.Scale (zero
// Scale is (1, 1)), for custom kinds that need them.
Pos, Scale gfx.Vec2
// Collider is a copy of the entity's collider.
Collider Collider
}
Shape is a collider placed in the world, as the broad and narrow phases see it. The Space builds one per collider each tick; custom narrow-phase functions (NarrowFunc) receive two of them.
type ShapeKind ¶
type ShapeKind uint8
ShapeKind selects the shape of a Collider. Values from ShapeCustom on are the game's own: register them with Space.RegisterShape and Space.RegisterPair. The set is open, so it is a plain number in GOD.
const ( // ShapeRect is a rectangle of Size whose top-left corner is // Transform.Pos + Offset. ShapeRect ShapeKind = iota // ShapeCircle is a circle of radius Size.X around Transform.Pos + // Offset. ShapeCircle // ShapeAnimBody is a rectangle like ShapeRect whose Offset and Size the // anim.AnimationSystem writes from the body of the entity's animation // definition (the union of its body rects). The collider is skipped // while Size is zero (no clip loaded yet). ShapeAnimBody // ShapeCustom is the first kind a game may define. ShapeCustom ShapeKind = 128 )
Shape kinds.
type Space ¶
type Space struct {
// contains filtered or unexported fields
}
Space holds the collision state of a World: the colliders placed in the last System run, their contacts, the tile grids and the custom shapes. It is a World resource; get it with SpaceOf. Queries and Space.Contacts read the state of the last run, so a collider spawned or moved this tick counts from the next run on.
func SpaceOf ¶
SpaceOf returns w's Space, creating it on first use with the default grid broad phase. Game systems, physics and the debug overlay share it.
func (*Space) AddTiles ¶
func (s *Space) AddTiles(grid TileGrid, opts TileOptions)
AddTiles adds grid to the space: colliders whose Mask has the grid's layer get a contact per overlapped solid cell and one Enter and Exit per grid. Grids never detect anything. The grid is read each tick, so cells changed in place (a broken wall) count from the next run on.
Panics with "collision: tile grid already added" if grid is in the space, and "collision: nil tile grid" if it is nil.
func (*Space) AllContacts ¶
AllContacts returns every contact of the last run, sorted by Self, Other and cell. Same ownership as Space.Contacts.
func (*Space) Contacts ¶
Contacts returns the contacts in which e is Self in the last run, sorted by Other and then by tile cell. The slice belongs to the Space: it is valid until the next run and must not be changed.
func (*Space) QueryPoint ¶
QueryPoint yields the colliders of the last run that contain p (as gfx.Rect.Contains for boxes, the open disc for circles) and are on a layer of mask. A custom shape counts by its bounds. Tile grids are not searched: use the grid's own lookups. Yields no entity twice; does not allocate when ranged over directly.
func (*Space) QueryRect ¶
QueryRect yields the colliders of the last run that overlap r (share an area with it; touching is not enough) and are on a layer of mask. Same rules as Space.QueryPoint.
func (*Space) QueryShapes ¶
QueryShapes yields the placed colliders of the last run whose bounds overlap r and that are on a layer of mask, dynamic ones first: the shapes a mover tests itself against (see package physics). The shapes belong to the Space and are valid until the next run. Tile grids are not searched (Space.TileGrids). Does not allocate when ranged over directly.
func (*Space) Raycast ¶
Raycast returns the nearest hit of the segment from -> to with the colliders of the last run on a layer of mask and the cells of the tile grids on such a layer. A ray that only grazes a shape (runs along an edge or touches a corner) does not hit it. A custom shape is hit by its bounds. It does not allocate once warm.
func (*Space) RegisterPair ¶
func (s *Space) RegisterPair(a, b ShapeKind, fn NarrowFunc)
RegisterPair sets the narrow phase for shapes of kinds a and b; the reverse pair (b, a) is derived from it by flipping the normal. One of the kinds must be custom; ShapeRect stands for ShapeAnimBody too (tile cells are ShapeRect). A pair that meets without a narrow phase panics with "collision: no narrow phase for shapes <a> and <b>".
Panics with "collision: shapes <a> and <b> are built in" if neither kind is custom and "collision: nil narrow phase" for a nil fn.
func (*Space) RegisterShape ¶
func (s *Space) RegisterShape(kind ShapeKind, bounds BoundsFunc)
RegisterShape makes a custom kind (ShapeCustom or above) usable: bounds returns the world box of a collider of that kind. Register the narrow phase of each pair of kinds that can meet with Space.RegisterPair. Queries and rays test custom shapes by their bounds.
Panics with "collision: shape kind <k> is built in" for a kind below ShapeCustom and "collision: nil bounds" for a nil bounds.
func (*Space) RemoveTiles ¶
RemoveTiles removes grid from the space; its pairs end with an Exit on the next run. It reports false if grid was not in the space.
func (*Space) Shapes ¶
Shapes yields the colliders placed in the last run, dynamic ones first: what the debug overlay draws. The shapes belong to the Space and are valid until the next run.
func (*Space) StaticsChanged ¶
func (s *Space) StaticsChanged()
StaticsChanged tells the Space that a static collider was moved or changed in place (its Transform or Collider written through a pointer, SetComp of a present component, a tween, Lua): the next run re-reads every static. Adding or removing a static collider, or deleting its entity, is noticed without it. Cheap; call it once after a batch of writes. The level editor calls it after every edit.
type Stay ¶
type Stay struct{ Contact }
Stay is sent every run in which Self still detects Other, after the run that sent their Enter: once per detecting side and pair, and once per (collider, tile grid). Only with Config.Stay set; otherwise read Space.Contacts. The Contact is the pair's first one this tick.
type System ¶
type System struct {
// contains filtered or unexported fields
}
System runs collision detection on its World's Space every tick: it places the colliders, finds the contacts and sends Enter and Exit events (and Stay events with Config.Stay). Add it where the moves of the tick are done, usually at the end of the simulate stage; readers of the events and of Space.Contacts run after it in the same tick or before it in the next.
func NewSystem ¶
NewSystem configures w's Space with cfg and returns the system that updates it. With game.Engine, add it to a stage with game.Wrap.
Panics with "collision: Space already has a system" when called twice for one World.
func (*System) Detect ¶
func (sys *System) Detect()
Detect places the colliders and finds the contacts, without sending events: queries and Space.Contacts see the new state right after it. Package physics calls it once per substep and System.Publish once per tick, so events stay once per tick.
func (*System) Publish ¶
func (sys *System) Publish()
Publish sends the Enter, Exit (and Stay) events for the contacts of the last Detect, compared with the contacts of the Detect before the previous Publish. Detecting several times between two Publish calls reports only the state of the last Detect.
func (*System) Run ¶
Run implements system.Runner: System.Detect, then System.Publish.
type TileGrid ¶
type TileGrid interface {
// Solid reports whether cell (cx, cy) blocks.
Solid(cx, cy int) bool
// CellRect returns the world rectangle of cell (cx, cy).
CellRect(cx, cy int) gfx.Rect
// CellOf returns the cell that contains pos.
CellOf(pos gfx.Vec2) (cx, cy int)
}
TileGrid is a grid of solid cells, such as a *tilemap.CollisionGrid. Cell (0, 0) starts at world (0, 0) and every cell has the size of CellRect(0, 0). A solid cell counts as a full box, also when the tile's shape covers only part of it.
type TileOptions ¶
type TileOptions struct {
// Layer is the layer set of every cell; zero is DefaultLayer.
Layer Layers
// OneWay makes every cell block from one side only (for physics).
OneWay OneWay
}
TileOptions place a tile grid in a Space.