GitHub快速開始

API 參考取自原始碼中的 Go 文件註解,以英文撰寫。

package rts

import "github.com/nsgo-dev/game/pkg/rts"

概覽

Package rts provides the unit-control layer of a real-time strategy game: whole-grid and HPA* sector-limited flow fields that steer many units toward a goal over an ai.Grid, a Crowd that moves those units with push-apart separation or ORCA local avoidance and wall sliding, formations defined in versioned YAML, box and click selection, and numbered control groups.

Everything is deterministic and steps on game.Loop's fixed steps with no background goroutines: the same orders on the same grid move the same units to the same places on every run on the same CPU architecture. Positions are float32, and Go may fuse a multiply and an add into one instruction on arm64 but not on x64, so the same orders can end a few ulps apart on different architectures; a lockstep multiplayer game across architectures should exchange state from an authoritative host rather than rely on each peer stepping its own Crowd.

索引

常數

const DefaultDoubleTapSteps = 18

DefaultDoubleTapSteps is the double-tap window, 18 steps or 0.3 seconds at 60 steps per second.

const DefaultFieldCacheSize = 16

DefaultFieldCacheSize is the number of flow fields a FieldCache keeps when NewFieldCache is given a capacity of 0 or less.

const FormationsVersion = 1

FormationsVersion is the formation file schema version this package reads and writes.

const GroupCount = 10

GroupCount is the number of control groups, one per digit key 0 to 9.

變數

var Unreachable = float32(math.Inf(1))

Unreachable is the integration cost of a cell no goal can be reached from, and of every cell outside the grid.

函式

func Assign(dst []int, positions []math2d.Vec2, slots []Slot, facing math2d.Vec2) []int

Assign matches units at positions to slots so that front units take front slots and units on the left take left slots, which keeps their paths from crossing. It returns, for each unit, the index of its slot, appended to dst[:0]; slots must have at least len(positions) entries, laid out by Layout (row-major, front row first), and facing is the formation's facing.

The match runs in O(n log n): units are ranked by how far ahead they stand along facing and dealt out to the rows front to back, then within a row ranked across and paired with the row's slots left to right. Ties fall back to the units' order in positions, so the result is deterministic.

func DrawFlowField(d *core.Drawing, f *FlowField, col core.Color, lineWidth float32)

DrawFlowField strokes one short line per reachable cell of f, from the cell's center along its direction, in col and lineWidth world units, under whatever camera transform d already has. Goal cells get a small cross. It is meant for debug overlays and draws the whole field as a single path.

func DrawSelectionBox(d *core.Drawing, r math2d.Rect, fill, stroke core.Color, lineWidth float32)

DrawSelectionBox fills r with fill and outlines it in stroke at lineWidth, under d's current transform; pass the rectangle from BoxSelector.Box while a drag is in progress.

func Place(dst []math2d.Vec2, slots []Slot, center, facing math2d.Vec2) []math2d.Vec2

Place returns the world positions of slots for a formation centered on center and facing along facing, appending them to dst[:0]. A zero or non-finite facing faces up the screen (negative Y).

型別

type AvoidanceMode uint8

AvoidanceMode selects how units in a Crowd avoid colliding with each other.

const (
	// AvoidancePush pushes overlapping units apart (the default).
	AvoidancePush AvoidanceMode = iota
	// AvoidanceORCA computes collision-free velocities ahead of contact using ai.ORCASolver.
	AvoidanceORCA
)

The avoidance modes.

func (m AvoidanceMode) String() string

String returns the mode's name.

type BoxSelector struct {
	// Picker finds the units; usually the game's Crowd.
	Picker Picker
	// Selection is the selection the selector changes.
	Selection *Selection
	// Filter, when set, keeps only the units it reports true for, such as the player's own.
	Filter func(UnitID) bool
	// DragThreshold is how far in world units the pointer moves before a press becomes a box drag; 0 or less uses 4.
	DragThreshold float32
	// ClickSlop is how far in world units from a unit's body a click still picks it; negative values count as 0.
	ClickSlop float32
	// View is the world area on screen, where a double click looks for units of the same kind; an empty View looks in the whole world.
	View math2d.Rect
	// contains filtered or unexported fields
}

BoxSelector turns pointer presses, drags and releases in world space into selections: a press and release without moving far picks the unit under the pointer, a drag picks every unit its rectangle touches, and a double click picks every unit in View of the same kind as the one clicked.

Convert pointer positions from view to world coordinates (through the game's camera) before passing them in. A BoxSelector is not safe for concurrent use.

func (b *BoxSelector) Box() (math2d.Rect, bool)

Box returns the drag rectangle in world space while a box drag is in progress, for drawing.

func (b *BoxSelector) Cancel()

Cancel abandons a pick in progress without changing the selection, as when the pointer leaves the view or Escape is pressed.

func (b *BoxSelector) Drag(p math2d.Vec2)

Drag moves the pointer of a pick in progress to world position p.

func (b *BoxSelector) Dragging() bool

Dragging reports whether a box drag is in progress.

func (b *BoxSelector) Press(p math2d.Vec2, mods core.Modifiers, clicks int)

Press starts a pick at world position p with the modifier keys held and the platform's click count (2 for a double click), as core.PressEvent reports them.

func (b *BoxSelector) Release(p math2d.Vec2) []UnitID

Release ends the pick at world position p, changes the selection, and returns the units picked (after Filter), in the selector's own slice that the next Release reuses. A click on empty ground in Replace mode clears the selection.

type ControlGroups struct {
	// DoubleTapSteps is how many steps apart two recalls of the same group count as a double tap; 0 or less uses DefaultDoubleTapSteps.
	DoubleTapSteps uint64
	// contains filtered or unexported fields
}

ControlGroups holds the ten numbered groups a player binds units to and recalls them by.

Double-tap detection counts game steps rather than wall-clock time, so it replays exactly: pass the same step counter (Crowd.Steps, or the game's own) to every HandleKey or Recall. The zero value holds ten empty groups and uses DefaultDoubleTapSteps. ControlGroups is not safe for concurrent use.

func (g *ControlGroups) Append(n int, ids []UnitID)

Append adds the units of ids that group n does not hold yet to its end.

func (g *ControlGroups) Assign(n int, ids []UnitID)

Assign binds group n to ids, replacing what it held. Repeats are dropped.

func (g *ControlGroups) Forget(id UnitID)

Forget removes id from every group, as when the unit dies.

func (g *ControlGroups) Group(n int) []UnitID

Group returns the units bound to group n in the order they were added, or nil for a group outside 0 to 9. The slice is the groups' own.

func (g *ControlGroups) HandleKey(ev core.KeyEvent, sel *Selection, step uint64) GroupEvent

HandleKey applies the usual strategy-game bindings for a digit key at game step step: Control or Command with a digit assigns the selection to that group, Shift with a digit adds the selection to it and selects the whole group, and a digit alone recalls it (twice quickly to focus). Keys other than unmodified or so-modified digits, and auto-repeats, report NoGroupAction and change nothing.

func (g *ControlGroups) Recall(n int, sel *Selection, step uint64) GroupAction

Recall replaces sel with group n at game step step and reports GroupFocused when the same group was recalled within DoubleTapSteps before, GroupRecalled otherwise. Recalling an empty group leaves sel unchanged and reports NoGroupAction.

func (g *ControlGroups) Retain(keep func(UnitID) bool)

Retain keeps in every group only the units keep reports true for.

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

Crowd moves many units over an ai.Grid. Units follow shared flow fields to their targets, keep apart from each other, and slide along blocked cells and the grid's edge.

Step advances every unit by one fixed step in O(n + b) time for n units, where b is the number of neighbor buckets, each as wide as the largest unit's reach or a cell, covering the units' bounding box: neighbors are found through that bucket grid, rebuilt each step without allocating once its buffers have grown, and each unit reads its flow field in constant time. Forces are computed from the positions at the start of the step for every unit before any unit moves, so the result does not depend on the order units move in within a step. It does depend on the order units were added in, which sets their IDs and the order their pushes are summed, so a replay must add the same units in the same order. A Crowd is not safe for concurrent use.

func NewCrowd(grid ai.Grid, opts CrowdOptions) *Crowd

NewCrowd returns an empty crowd moving units over grid.

func (c *Crowd) Add(spec UnitSpec) UnitID

Add places a new idle unit and returns its ID.

func (c *Crowd) Centroid(ids []UnitID) (math2d.Vec2, bool)

Centroid returns the mean position of the units in ids that exist, and false when none does.

func (c *Crowd) Fields() *FieldCache

Fields returns the crowd's flow field cache. After changing the grid, call the Crowd's Rebuild rather than the cache's, so fields the cache has since dropped but units still follow are rebuilt too.

func (c *Crowd) Grid() ai.Grid

Grid returns the grid the crowd moves over.

func (c *Crowd) KindOf(id UnitID) (int, bool)

KindOf returns the Kind of the unit with id.

func (c *Crowd) Len() int

Len returns the number of units.

func (c *Crowd) Move(ids []UnitID, o MoveOrder) int

Move orders the units in ids that exist to take up o's formation around o.Target and returns how many were ordered.

The slots are placed around the target facing o.Facing, and any slot that falls on a blocked cell, or on a cell the group cannot reach, moves to the nearest free cell that can be reached. Units are matched to slots with Assign, and the whole group shares one flow field whose goals are the slots' cells, built once (or found in the crowd's FieldCache) however many units there are. Each unit follows that field until it can see its own slot within the crowd's DirectRange, then walks straight to it; a unit that reaches the formation's area with a wall between it and its slot follows its own ai.AStar path there for the rest of the order, planning it afresh whenever the crowd pushes it off it.

When the units cannot reach o.Target, as when it lies on an island, the formation centers on the nearest cell they can reach instead. When o.Target is outside the grid, or the units stand nowhere they could walk from, Move orders nobody and returns 0.

func (c *Crowd) Options() CrowdOptions

Options returns the crowd's options with defaults filled in.

func (c *Crowd) Rebuild()

Rebuild integrates every flow field the crowd's units follow, and every field in its cache, again over the grid, in place, so the units see a change to the grid (a wall built, a bridge destroyed) on their next step. Call it after changing the grid's walkable cells or costs.

Units whose own paths around walls were planned on the old grid plan them again. Units whose field no longer has a walkable goal, because every cell their order sent them to is now blocked, stop where they stand, as after Stop.

func (c *Crowd) Remove(id UnitID) bool

Remove deletes the unit with id and reports whether it existed. The last unit takes the removed one's place in Units.

func (c *Crowd) Step(dt time.Duration)

Step advances every unit by dt.

func (c *Crowd) Steps() uint64

Steps returns how many times Step has advanced the crowd.

func (c *Crowd) Stop(ids ...UnitID)

Stop drops the orders of the units in ids, leaving them idle where they stand.

func (c *Crowd) Unit(id UnitID) (Unit, bool)

Unit returns the unit with id.

func (c *Crowd) UnitAt(p math2d.Vec2, slop float32) (UnitID, bool)

UnitAt returns the unit whose body is nearest to p among those within slop world units of it, and false when there is none. Equal distances go to the unit earlier in Units.

func (c *Crowd) Units() []Unit

Units returns every unit, in a stable order that changes only when units are added or removed. The slice is the crowd's own: read it, do not change it, and do not keep it across Add or Remove.

func (c *Crowd) UnitsIn(r math2d.Rect, out []UnitID) []UnitID

UnitsIn appends to out[:0] the IDs of the units whose bodies overlap r, in Units order.

type CrowdOptions struct {
	// Origin is the world position of the top-left corner of grid cell (0, 0); a non-finite coordinate counts as 0.
	Origin math2d.Vec2
	// CellSize is the width and height of a grid cell in world units; 0 or less, or a non-finite value, uses 1.
	CellSize float32
	// FieldCacheSize is the number of flow fields kept for reuse; 0 or less uses DefaultFieldCacheSize.
	FieldCacheSize int
	// Separation scales the push between overlapping units under AvoidancePush; 0 or less, or a non-finite value, uses 1.
	Separation float32
	// Gap is extra room units keep between their bodies, in world units; negative and non-finite values count as 0.
	Gap float32
	// ArriveRadius is how close a unit gets to its target to count as arrived; 0 or less, or a non-finite value, uses the unit's radius.
	ArriveRadius float32
	// DirectRange is the distance within which a unit that can see its target walks straight to it instead of following its flow field; 0 or less, or a non-finite value, uses 6 cells.
	DirectRange float32
	// Responsiveness is how quickly a unit's velocity turns to its desired velocity, per second; 0 or less, or a non-finite value, uses 8.
	Responsiveness float32
	// Avoidance selects how units keep clear of each other: AvoidancePush (default) pushes overlapping units apart, while AvoidanceORCA uses ai.ORCASolver to steer around neighbors before contact.
	Avoidance AvoidanceMode
	// ORCA tunes the ai.ORCASolver used when Avoidance is AvoidanceORCA. Zero or non-finite fields use ai.ORCASolver defaults.
	ORCA ai.ORCAConfig
}

CrowdOptions tunes a Crowd. The zero value works for units about half a cell wide.

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

FieldCache builds flow fields over one grid and keeps the most recently used ones, so units ordered to the same goals share a single field instead of each building their own.

Fields are keyed by their goal set, compared as a sorted set of distinct cells, so the same goals given in another order or with repeats find the same field. When the cache is full the least recently used field is dropped; a unit still holding it keeps following it, Crowd.Rebuild still rebuilds it after a grid change, and the cache builds a fresh one the next time those goals are asked for. A FieldCache is not safe for concurrent use.

func NewFieldCache(grid ai.Grid, origin math2d.Vec2, cellSize float32, capacity int) *FieldCache

NewFieldCache returns a cache of up to capacity 8-way flow fields over grid, whose cells are cellSize world units wide starting at origin.

func (fc *FieldCache) Builds() uint64

Builds returns how many fields the cache has built or rebuilt since it was made, which tells a test or a profiler whether units are sharing fields.

func (fc *FieldCache) CellSize() float32

CellSize returns the width and height of a cell in world units.

func (fc *FieldCache) Clear()

Clear drops every cached field.

func (fc *FieldCache) Field(goals ...ai.Cell) (*FlowField, bool)

Field returns the flow field toward goals, building it on first use, or nil and false when no goal is an in-bounds walkable cell.

func (fc *FieldCache) Grid() ai.Grid

Grid returns the grid the cache builds fields over.

func (fc *FieldCache) Len() int

Len returns the number of fields the cache holds.

func (fc *FieldCache) Origin() math2d.Vec2

Origin returns the world position of the top-left corner of cell (0, 0).

func (fc *FieldCache) Rebuild()

Rebuild integrates every cached field again over the grid, in place, so units following them see a change to the grid (a wall built, a bridge destroyed) on their next step. A field none of whose goals is walkable any more is dropped from the cache, so the next Field call for those goals reports false. Call it after changing the grid's walkable cells or costs; a Crowd's own Rebuild calls it and also rebuilds the fields its units still follow after the cache dropped them.

type FlowField struct {
	// Origin is the world position of the top-left corner of cell (0, 0).
	Origin math2d.Vec2
	// CellSize is the width and height of a cell in world units; 0 or less, or a non-finite value, is treated as 1.
	CellSize float32
	// Diagonal allows 8-way movement, with diagonal steps costing sqrt(2) and never cutting the corner of a blocked cell; false restricts movement to the 4 cardinal directions. NewFlowField enables it.
	Diagonal bool
	// contains filtered or unexported fields
}

FlowField holds, for every cell of an ai.Grid, the cost of the cheapest path to the nearest of its goal cells (the integration field) and the direction a unit standing in that cell moves to follow that path (the direction field).

One field serves every unit heading for the same goals: building it costs one Dijkstra search over the grid, and each unit then reads its direction in constant time with Sample. Cells map to world space through Origin and CellSize: cell (col, row) covers [Origin.X+col*CellSize, Origin.X+(col+1)*CellSize) horizontally and the same along Y.

A FlowField is not safe for concurrent use while it is being built.

func NewFlowField(origin math2d.Vec2, cellSize float32) *FlowField

NewFlowField returns an empty field with 8-way movement whose cells are cellSize world units wide, the top-left one starting at origin.

func (f *FlowField) Build(g ai.Grid, goals ...ai.Cell) bool

Build integrates g toward goals, replacing whatever the field held, and reports whether at least one goal is an in-bounds walkable cell. Goals that are out of bounds or blocked are ignored.

Stepping into a cell costs the step's length (1, or sqrt(2) diagonally) times the cell's cost, which comes from g's MoveCost when g is an ai.CostGrid (values of 0 or less, and non-finite ones, count as 1, as ai.AStar treats them) and is 1 otherwise, so a cell's integration cost equals the cost ai.AStar finds from it to the nearest goal. Build reuses the field's buffers, so rebuilding a field of the same size allocates nothing.

func (f *FlowField) CellAt(p math2d.Vec2) (ai.Cell, bool)

CellAt returns the cell holding world position p and whether it is inside the grid.

func (f *FlowField) CellCenter(c ai.Cell) math2d.Vec2

CellCenter returns the world position of the center of cell c.

func (f *FlowField) Cost(col, row int) float32

Cost returns the integration cost from (col, row) to the nearest goal, 0 on a goal and Unreachable for a cell outside the grid or with no path.

func (f *FlowField) Direction(col, row int) math2d.Vec2

Direction returns the unit vector a unit in (col, row) moves along, or the zero vector on a goal, on an unreachable cell and outside the grid.

func (f *FlowField) Goals() []ai.Cell

Goals returns the in-bounds walkable goal cells of the last Build, in the order given, without duplicates. The slice is the field's own and changes on the next Build.

func (f *FlowField) Reachable(col, row int) bool

Reachable reports whether a goal can be reached from (col, row).

func (f *FlowField) Sample(p math2d.Vec2) (dir math2d.Vec2, ok bool)

Sample returns the direction a unit at world position p moves along, blended bilinearly from the four cells around p so that units turn smoothly instead of in 45-degree steps. Only reachable cells take part in the blend, so a unit beside a wall is not pulled into it. ok is false when p is outside the grid or no reachable cell is near it; on a goal cell the direction is the zero vector and ok is true.

func (f *FlowField) Size() (cols, rows int)

Size returns the field's width in columns and height in rows, those of the grid it was last built on.

type Formation struct {
	// Name identifies the formation in its set.
	Name string `yaml:"name"`
	// Shape is the layout of the slots.
	Shape Shape `yaml:"shape"`
	// Spacing is the distance between neighboring slot centers in world units; it should be at least twice the largest unit radius so units in their slots do not push each other.
	Spacing float32 `yaml:"spacing"`
	// Width is the number of slots per row for the line, column and box shapes; 0 picks the shape's default. The wedge ignores it.
	Width int `yaml:"width,omitempty"`
}

Formation is a named layout that units ordered together take up around their target.

func (f Formation) Layout(dst []Slot, n int) []Slot

Layout returns the n slots of f around the formation's center, appending them to dst[:0]. Rows are filled front to back and centered across, so the slots' bounding box is centered on the origin. A formation with a non-positive or non-finite Spacing, or an unknown Shape, lays out a box with spacing 1.

func (f Formation) Validate() error

Validate reports whether f has a known shape, a positive finite spacing and a non-negative width.

type Formations struct {
	// Version is the schema version; it must be FormationsVersion.
	Version int `yaml:"version"`
	// Formations are the formations in the order the game lists them; names are unique.
	Formations []Formation `yaml:"formations"`
}

Formations is a formation file: the named formations a game offers its players, kept in YAML so a designer can edit them and review the diff.

version: 1
formations:
  - name: line
    shape: line
    spacing: 1.5
  - name: block
    shape: box
    spacing: 1.2
    width: 8
func ParseFormations(data []byte) (*Formations, error)

ParseFormations decodes and validates a formation file. Unknown fields, a second YAML document and any value Validate refuses are errors.

func (fs *Formations) Encode() ([]byte, error)

Encode validates fs and writes it as YAML with two-space indentation and fields in a fixed order, so encoding a parsed file gives back the same bytes for files written in that form.

func (fs *Formations) Get(name string) (Formation, bool)

Get returns the formation named name.

func (fs *Formations) Validate() error

Validate reports the first problem with fs: a version other than FormationsVersion, a formation with an empty or repeated name, an unknown shape, a spacing that is not a positive finite number, or a negative width.

type GroupAction uint8

GroupAction is what a digit key did to the control groups.

const (
	// NoGroupAction means the key was not a control group key.
	NoGroupAction GroupAction = iota
	// GroupAssigned means the group was set to the selection (Control or Command with a digit).
	GroupAssigned
	// GroupAdded means the selection was added to the group and the whole group selected (Shift with a digit).
	GroupAdded
	// GroupRecalled means the selection was replaced by the group (a digit alone).
	GroupRecalled
	// GroupFocused means the group was recalled twice in quick succession; the game should center its camera on the group.
	GroupFocused
)

The control group actions.

func (a GroupAction) String() string

String returns the action's name.

type GroupEvent struct {
	Action GroupAction
	// Group is the digit of the group acted on.
	Group int
}

GroupEvent reports what HandleKey did.

type MoveOrder struct {
	// Target is the world position the formation is centered on.
	Target math2d.Vec2
	// Formation lays out the units around Target. A zero Formation packs them into a box whose spacing fits the largest unit with the crowd's Gap.
	Formation Formation
	// Facing is the direction the formation faces; the zero vector faces from the group's centroid toward Target.
	Facing math2d.Vec2
	// KeepPace caps every unit at the slowest unit's speed, so the group moves and arrives together.
	KeepPace bool
}

MoveOrder sends a group of units to a target in formation.

type MoveState uint8

MoveState is where a unit is in carrying out its move order.

const (
	// Idle units have no order and only keep clear of their neighbors.
	Idle MoveState = iota
	// Moving units are on their way to their target.
	Moving
	// Arrived units reached their target and hold it.
	Arrived
)

The move states.

func (s MoveState) String() string

String returns the state's name.

type Picker interface {
	// UnitsIn appends to out[:0] the units whose bodies overlap r, in a stable order.
	UnitsIn(r math2d.Rect, out []UnitID) []UnitID
	// UnitAt returns the unit nearest p within slop world units.
	UnitAt(p math2d.Vec2, slop float32) (UnitID, bool)
	// KindOf returns the unit's game-defined kind.
	KindOf(id UnitID) (int, bool)
}

Picker finds units in world space; Crowd implements it.

type SectorFlowField struct {
	// Origin is the world position of the top-left corner of cell (0, 0).
	Origin math2d.Vec2
	// CellSize is the width and height of a cell in world units; 0 or less, or a non-finite value, is treated as 1.
	CellSize float32
	// Diagonal allows 8-way movement, with diagonal steps costing sqrt(2) and never cutting the corner of a blocked cell;
	// false restricts movement to the 4 cardinal directions. NewSectorFlowField enables it.
	Diagonal bool
	// contains filtered or unexported fields
}

SectorFlowField is a flow field integrated only across an active subset of square sectors (clusters), such as the cluster corridor produced by ai.HPA.FindClusters.

On large maps, integrating only the corridor of traversed clusters avoids scanning the entire grid while providing the same constant-time Cost, Reachable, Direction, and smooth bilinear Sample queries as FlowField. Cells outside active sectors report Unreachable.

A SectorFlowField reuses its internal buffers across Build calls and is not safe for concurrent use while building.

func NewSectorFlowField(origin math2d.Vec2, cellSize float32) *SectorFlowField

NewSectorFlowField returns an empty 8-way sector-limited flow field whose cells are cellSize world units wide, starting at origin.

func (f *SectorFlowField) ActiveSectors() int

ActiveSectors returns the number of sectors currently integrated in the field.

func (f *SectorFlowField) BuildAlongHPA(hpa *ai.HPA, start, goal ai.Cell, padding int) bool

BuildAlongHPA queries hpa for the cluster corridor from start to goal, optionally expands it by padding rings of neighboring clusters (0 keeps the exact HPA* corridor), and integrates the flow field toward goal over those active sectors only.

Because every step along the HPA* path stays inside the returned cluster corridor, start is guaranteed to be reachable from goal whenever hpa finds a path (provided f.Diagonal is compatible with hpa's movement rules).

func (f *SectorFlowField) BuildSectors(g ai.Grid, sectorSize int, sectors []ai.ClusterID, goals ...ai.Cell) bool

BuildSectors integrates g toward goals restricting the search to cells inside the given sectorSize-by-sectorSize sectors.

Duplicate and out-of-bounds sectors are ignored. Goals that are out of bounds, blocked, or outside active sectors are ignored. It reports whether at least one valid goal was seeded inside an active sector.

func (f *SectorFlowField) CellAt(p math2d.Vec2) (ai.Cell, bool)

CellAt returns the cell holding world position p and whether it is inside the grid.

func (f *SectorFlowField) CellCenter(c ai.Cell) math2d.Vec2

CellCenter returns the world position of the center of cell c.

func (f *SectorFlowField) Cost(col, row int) float32

Cost returns the integration cost from (col, row) to the nearest goal, 0 on a goal, and Unreachable for blocked cells, cells outside active sectors, or cells outside the grid.

func (f *SectorFlowField) Direction(col, row int) math2d.Vec2

Direction returns the unit vector a unit in (col, row) moves along, or the zero vector on a goal, unreachable cell, inactive sector, or outside the grid.

func (f *SectorFlowField) Goals() []ai.Cell

Goals returns the in-bounds walkable goal cells inside active sectors from the last build.

func (f *SectorFlowField) Reachable(col, row int) bool

Reachable reports whether a goal can be reached from (col, row) within the active sectors.

func (f *SectorFlowField) Sample(p math2d.Vec2) (dir math2d.Vec2, ok bool)

Sample returns the bilinearly blended movement direction at world position p, ignoring walls and inactive sectors just like FlowField.Sample.

func (f *SectorFlowField) SectorActive(col, row int) bool

SectorActive reports whether cell (col, row) belongs to an active sector.

func (f *SectorFlowField) Size() (cols, rows int)

Size returns the full grid width and height in cells that the field was built over.

type SelectMode uint8

SelectMode is how a pick changes the selection.

const (
	// Replace selects only the picked units.
	Replace SelectMode = iota
	// Extend adds the picked units to the selection.
	Extend
	// Invert toggles the picked units, as Selection.Toggle does.
	Invert
)

The select modes.

func ModeFor(m core.Modifiers) SelectMode

ModeFor returns the mode the held modifier keys ask for: Shift extends the selection, Control (or Command on macOS) toggles units in and out, and no modifier replaces it.

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

Selection is the set of units a player has selected, in the order they were selected.

The zero value is an empty selection ready to use. A Selection is not safe for concurrent use.

func (s *Selection) Add(ids ...UnitID)

Add selects each of ids that is not selected yet, after the units already selected.

func (s *Selection) Apply(mode SelectMode, picked []UnitID)

Apply changes s by picked according to mode.

func (s *Selection) Clear()

Clear deselects every unit.

func (s *Selection) Contains(id UnitID) bool

Contains reports whether id is selected.

func (s *Selection) IDs() []UnitID

IDs returns the selected units in selection order. The slice is the selection's own: read it, and copy it before changing the selection if you need to keep it.

func (s *Selection) Len() int

Len returns the number of selected units.

func (s *Selection) Remove(ids ...UnitID)

Remove deselects each of ids, keeping the others in order.

func (s *Selection) Retain(keep func(UnitID) bool)

Retain keeps only the selected units keep reports true for, such as those still alive.

func (s *Selection) Set(ids []UnitID)

Set replaces the selection with ids, dropping repeats.

func (s *Selection) Toggle(ids ...UnitID)

Toggle deselects the units of ids that are selected and selects the others. When every unit of ids is already selected they are all deselected; otherwise the unselected ones are added, as a Ctrl-drag over a mixed group does in most strategy games.

type Shape string

Shape is the layout of a formation's slots.

const (
	// ShapeLine puts the units side by side in rows of Width slots, one row when Width is 0.
	ShapeLine Shape = "line"
	// ShapeColumn puts the units one behind another in rows of Width slots, one slot wide when Width is 0.
	ShapeColumn Shape = "column"
	// ShapeBox fills a square, or rows of Width slots when Width is set.
	ShapeBox Shape = "box"
	// ShapeWedge puts one unit at the point and each row behind it one slot wider, as a V of filled rows.
	ShapeWedge Shape = "wedge"
)

The formation shapes. Rows run across the facing direction and row 0 is the front.

type Slot struct {
	// Offset is the slot's position relative to the formation's center, with X across the facing direction (positive to the right of it) and Y along it (positive ahead).
	Offset math2d.Vec2
	// Row is the slot's row, 0 at the front.
	Row int
}

Slot is one place in a formation.

type Unit struct {
	ID       UnitID
	Pos      math2d.Vec2
	Vel      math2d.Vec2
	Radius   float32
	MaxSpeed float32
	MaxAccel float32
	Kind     int
	// State is the unit's progress on its order.
	State MoveState
	// Target is the position the unit's order sends it to; for an idle unit, its position when it went idle.
	Target math2d.Vec2
	// contains filtered or unexported fields
}

Unit is a unit's state as the crowd last stepped it. Read units through Crowd.Units or Crowd.Unit; change them only through the Crowd's methods.

type UnitID uint32

UnitID identifies a unit in a Crowd. IDs start at 1 and are never reused, so 0 is never a valid ID.

type UnitSpec struct {
	// Pos is the unit's starting position in world units.
	Pos math2d.Vec2
	// Radius is the unit's body radius; 0 or less uses a quarter of the crowd's cell size.
	Radius float32
	// MaxSpeed is the unit's top speed in world units per second; 0 or less uses 4 cells per second.
	MaxSpeed float32
	// MaxAccel caps how fast the unit changes velocity, in world units per second squared; 0 or less uses four times MaxSpeed.
	MaxAccel float32
	// Kind is a game-defined unit type, used to select every unit of the same type with a double click.
	Kind int
}

UnitSpec describes a unit to add to a Crowd.