Skip to content
gravittonPublic

Repository files navigation

Gravitton hexagon

Latest Stable Version Build Status Coverage Status Go Dev Reference Go Version Software License

Hexagonal grid math: coordinates, ranges, lines and field of view


A map of walls, rough ground, a scout and a goal in hexes: the scout's field of view of radius 6, its line to the goal, hidden behind a wall, and its field of view in a sector of two sixth-turns toward the goal
Every picture in this README is drawn from what the package returns for the call beside it.

Features

  • Axial coordinates – two integers per hex, the third cube coordinate derived.
  • Immutable – every method returns a new value, and a Hex is a map key that compares with ==.
  • Traversal – neighbors, range, ring, spiral, circles, sectors and lines, each with an allocation-free Seq form.
  • Chunks – hexagonal chunks of any radius: the chunk, center, wrap and slice index of a hex, exact in integers.
  • Visibility – exact, symmetric line of sight and field of view, with a single-sweep field over a whole range.
  • Cube space – rotation by sixths of a turn, around any hex, and reflection across the q-, r- and s-axis.
  • Directions – six of them, by increasing angle, with flat-top and pointy-top compass aliases.
  • Seven coordinate systems – axial, offset and doubled, converting losslessly both ways.
  • Reproducible – fractional hexes round the same on amd64 and arm64.
  • Extras – geometry interop, JSON, name parsing and hextest assertions.

The rules behind them are in the package documentation.

Installation

go get github.com/gravitton/hexagon
import hex "github.com/gravitton/hexagon"

Usage

Coordinates

A hex is two integers, q and r. The third cube coordinate, s, is derived, so that q + r + s is always zero and no value can hold an inconsistent triple.

A hexagon of hexes labelled with their axial coordinates, their three cube coordinates, and their distance from the center

a := hex.Pt(2, -1) // axial (q, r)

a.S()      // -1, the derived cube coordinate
a.QRS()    // 2, -1, -1
a.Length() // 2, steps from the origin

a.String()             // "(2,-1)"
hex.ParseHex("(2,-1)") // the string back to the hex

Arithmetic

Hexes add, subtract and scale like vectors, each coordinate on its own.

Two hexes a and b with their sum, their difference, and a multiplied by two and by minus one

a, b := hex.Pt(2, -1), hex.Pt(-1, 2)

a.Add(b)        // Hex{1, 1}
a.Subtract(b)   // Hex{3, -3}
a.Multiply(2)   // Hex{4, -2}
a.DistanceTo(b) // 3, the length of the difference
a.Lerp(b, 0.5)  // Hex{1, 0}, the hex halfway along

Directions

Six directions, named for the cube axis they move along and ordered by increasing angle: clockwise as drawn on a screen with Y pointing down. Each has a compass alias in both layouts.

The six directions around a hex in the pointy-top and the flat-top layout, with their compass aliases

dir := hex.QPlus
dir.Opposite()         // QMinus
dir.Turn(1)            // SMinus, one step of increasing angle
dir.TurnsTo(hex.RPlus) // 2, the fewest steps there
dir.Hex()              // Hex{1, -1}, the step as a hex; Offset gives it as a geom.Vector[int]
dir.Angle()            // 5π/3

hex.Directions()                // all six, by increasing angle, as a fresh array
hex.DirectionOffsets()          // the Offset of each, in the same order
hex.DirectionFromAngle(math.Pi) // SPlus, the nearest of the six
hex.ParseDirection("QPlus")     // the name back to the constant, "None" to DirectionNone

The angles in both panels are the ones Angle returns, and they follow the pointy-top layout. In a flat-top layout every direction lies 30° further along, so take π/6 off a flat-top angle before DirectionFromAngle.

Neighbors

The neighbors come back as arrays indexed by direction, so they allocate nothing. DirectionTo splits the plane into the six wedges the directions point into.

The six neighbors and six diagonal neighbors of a hex, numbered by direction, and every hex around it coloured by the direction toward it

h := hex.Pt(0, 0)

h.Neighbors()                // the six adjacent hexes, indexed by Direction
h.Neighbor(hex.QPlus)        // Hex{1, -1}
h.DiagonalNeighbors()        // the six hexes two steps away, each between two neighbors
h.DirectionTo(hex.Pt(4, -1)) // SMinus, the direction nearest to another hex

A hex exactly between two directions, as a diagonal neighbor is, takes the earlier of the two by increasing angle.

Range, ring, spiral and line

A filled range of radius 2, the ring of radius 2 numbered in order, the spiral of radius 2 numbered from the center outward, and a line between two hexes

h.Range(2)  // all 19 hexes within radius 2
h.Ring(2)   // the 12 hexes at exactly radius 2, in order around
h.Spiral(2) // the same hexes as Range, ordered center-outward

a, b := hex.Pt(-3, 1), hex.Pt(3, -2)
a.LineTo(b) // the 7 hexes from a to b in a straight line

Ring(1) is exactly Neighbors(). A negative radius gives nil, a zero radius the center alone.

Each of them has a Seq form that walks the hexes without a buffer:

for near := range h.SpiralSeq(5) { // nearest first, stops at the break
	if occupied[near] {
		break
	}
}

To reuse a buffer, collect the Seq form with the standard library's slices.AppendSeq: it works with every one of them and allocates nothing once the buffer has room.

buffer := make([]hex.Hex, 0, hex.RangeLen(2)) // 19 hexes within radius 2; RingLen sizes a ring
buffer = slices.AppendSeq(buffer[:0], h.RangeSeq(2))

Circles

The circles of radius the square root of three, four and four and a half around a hex, each drawn over the hexes whose centers it holds: the range of one with the six diagonal neighbors, the hexagonal range of four, and that range with twelve hexes of the next ring

h.Circle(math.Sqrt(3)) // the 13 hexes whose centers lie within √3 of h: Range(1) and the diagonal neighbors; also CircleSeq
h.Circle(4)            // the 61 hexes of Range(4)
h.Circle(4.5)          // 73 hexes, Range(4) and the 12 hexes of ring 5 nearest to h

Circle is the round area beside the hexagonal Range: the hexes whose centers lie within a Euclidean radius, with neighbors one apart and the border included. A whole radius under seven gives exactly Range, since every ring beyond it has its nearest hexes farther than the radius, so a round blast or aura takes a radius between whole numbers, where the circle bulges past the hexagon's sides.

Chunks

A map tiled with hexagonal chunks of radius 2 in three colours: the chunk holding a hex outlined, the hex as far from the origin as from the center of its chunk, and every hex numbered by its index within its chunk

h := hex.Pt(3, 0)
chunk := h.Chunk(2)  // (1,0), the chunk of radius 2 holding h, a hex of the coarser grid
chunk.ChunkCenter(2) // (5,-2), the center of that chunk; Chunk of it is the chunk again
h.ChunkLocal(2)      // (-2,2), h from the center of its chunk, where a map of radius 2 wraps it
h.ChunkIndex(2)      // 5, its slot in a slice of hex.RangeLen(2), the same in every chunk

The ranges of one radius tile the plane, so every hex lies in exactly one chunk, and the chunks form a hex grid of their own: Neighbors of a chunk are the chunks around it, and chunk.ChunkCenter(2).Range(2) lists its hexes. A map that wraps around is the chunk of its own radius repeated over the plane: ChunkLocal wraps a position back onto it, and a slice of RangeLen indexed by ChunkIndex holds its tiles, so any hex, on the map or off its edge, reads its tile without a wrap. HexFromChunkIndex is the hex of a slot.

Sectors

The sector of radius 4 and one turn toward one direction, numbered ring by ring, widening evenly on both sides, with one hex on its border outlined, the wider sector of two turns, and two neighboring sectors sharing the hexes on their border

h.Sector(4, hex.QPlus, 1) // the 12 hexes of the cone a sixth-turn wide toward that direction, without h; also SectorSeq
h.Sector(4, hex.QPlus, 2) // the 24 hexes of the cone two sixth-turns wide
hex.SectorLen(4, 1)       // 12, sizes a buffer as RangeLen does

h.SectorContains(4, hex.QPlus, 1, hex.Pt(2, -3)) // true, the outlined hex on the border, without walking the cone

A sector is the cone in front of a unit: the hexes within a number of sixth-turns about the direction, half either side, both borders included, so it is the same on both sides. A width of one turn is 30° either side, with rings 1, 3, 3, 5, 5 hexes wide, as a straight edge falls on a hex grid, and two neighboring sectors of one turn share the hexes on their border. Zero turns is the ray along the direction, and six the whole range around the hex.

SectorContains answers for one hex in constant time and without allocating, where looking it up in Sector builds the whole cone: whether an enemy is in a unit's facing arc, or a hex in reach of a cone attack. Together with HasLineOfSight it asks whether a unit sees one target in its arc:

h.SectorContains(5, facing, 2, enemy) && h.HasLineOfSight(enemy, blocked)

For every hex the unit sees in its arc, FieldOfViewSector below sweeps the cone once.

Line of sight

Sight runs along the exact segment between two hex centers, in integers. A blocker the segment cuts through blocks it, however small the corner; one it only touches at a corner does not; and where the segment runs along the edge between two hexes, it takes both of them to block.

Three cases of a line of sight: through a blocking hex is hidden, along an edge beside one blocking hex is seen, along an edge between two blocking hexes is hidden

a, b := hex.Pt(0, 0), hex.Pt(2, 2)

among := func(walls ...hex.Hex) func(hex.Hex) bool {
	return func(h hex.Hex) bool {
		return slices.Contains(walls, h)
	}
}

a.HasLineOfSight(b, among(hex.Pt(1, 1)))               // false, through it
a.HasLineOfSight(b, among(hex.Pt(1, 0)))               // true, one beside the edge
a.HasLineOfSight(b, among(hex.Pt(1, 0), hex.Pt(0, 1))) // false, both beside the edge

The rule reads the same from either end, so two hexes always see each other or neither does, and neither end ever blocks. It differs from LineTo, which picks one hex per step: a hex off the line can block the sight, and a hex of the line the segment only touches does not.

Three maps with one wall each, the hexes of the line to the target outlined and the segment between the centers drawn: a wall the line steps past hides the target from the segment only, and of two walls beside an edge the segment runs along, the one the line walks into hides the target from the walk only

a := hex.Pt(0, 0) // among as above

a.LineTo(hex.Pt(3, 1))                           // (0,0) (1,0) (1,1) (2,1) (3,1), never visiting (2,0)
a.HasLineOfSight(hex.Pt(3, 1), among(hex.Pt(2, 0))) // false, the segment clips the wall

a.LineTo(hex.Pt(2, 2))                           // (0,0) (0,1) (1,1) (1,2) (2,2), to one side of the edge
a.HasLineOfSight(hex.Pt(2, 2), among(hex.Pt(1, 0))) // true, as walking the line says
a.HasLineOfSight(hex.Pt(2, 2), among(hex.Pt(0, 1))) // true, where walking the line says false

Field of view

The field of view of a hex among walls: lines to seven candidates, seen or hidden, every hex within radius 5, seen or hidden, and the hexes of the cone two turns wide, seen or hidden

a.HasLineOfSight(c, blocked) // whether a sees one candidate c
a.FieldOfView(5, blocked)   // the 48 hexes visible within radius 5; also FieldOfViewSeq

a.FieldOfViewSector(5, hex.SMinus, 2, blocked) // the 18 visible of the 35 hexes of Sector(5, hex.SMinus, 2); also FieldOfViewSectorSeq

blocked is a func(hex.Hex) bool, and HasLineOfSight asks it only about the hexes that can block the segment, so it costs the distance however many hexes block. slices.Contains on a short list of walls is enough on a small board; on a larger one use a lookup in a map[hex.Hex]bool or a grid, since a long list is scanned for every hex asked about.

FieldOfView is the field over a whole range: what a unit sees, or a blast reaches. It gives the hexes of Spiral(radius) that HasLineOfSight sees, but sweeps the rings outward once and asks blocked about each hex at most once, where a line to every hex walks the near ones again and again. At a radius of 40 it is about fifteen times faster; filter by HasLineOfSight for a handful of candidates.

FieldOfViewSector is the field of a cone, what a unit facing one way sees. It sweeps only the part of the rings the cone covers and asks blocked only about the hexes that can hide one of the sector, so a cone of one turn costs about a third of the whole field.

Rotation and reflection

A hex turned around the origin in six steps, the same hex turned around another hex, and the hex reflected across the q-, r- and s-axis

a, b := hex.Pt(3, -1), hex.Pt(1, 0)

a.Turn(1)          // Hex{1, 2}, 60° around the origin
a.TurnAround(b, 1) // Hex{2, 1}, 60° around b; negative steps turn the other way
a.ReflectQ()       // Hex{3, -2}, q kept, r and s swapped
a.ReflectR()       // Hex{-2, -1}, r kept, q and s swapped
a.ReflectS()       // Hex{-1, 3}, s kept, q and r swapped

Coordinate systems

Axial coordinates are the ones to compute with; the offset and doubled systems are the ones a rectangular map is stored in. Every system converts both ways without loss.

The same patch of pointy-top hexes indexed in the Axial, OffsetOddR, OffsetEvenR and DoubleWidth coordinate systems

The same patch of flat-top hexes indexed in the Axial, OffsetOddQ, OffsetEvenQ and DoubleHeight coordinate systems

a := hex.Pt(2, -1)
hex.OffsetOddR.To(a)                // geom.Point[int]{1, -1}
hex.OffsetOddR.From(geom.Pt(1, -1)) // back to Hex{2, -1}

hex.CoordinateSystems()            // all seven, as a fresh array
hex.ParseCoordinateSystem("Axial") // the name back to the constant

In an offset system the step to a neighbor depends on the parity of the row or column. Ask the system for it:

hex.OffsetOddR.Offsets(index)                     // all 6, indexed by Direction
hex.OffsetOddR.Offset(index, hex.PointyTopEast)   // just one
hex.OffsetOddR.Neighbor(index, hex.PointyTopEast) // the index that offset steps to
hex.OffsetOddR.Neighbors(index)                   // all 6 indices beside it, indexed by Direction

Direction.Offset() is the axial case of the same thing, equal to hex.Axial.Offset(index, direction).

Fractional hexes

FractionalHex is the float companion, for interpolation and for landing a position from pixel space on the grid; the pixel layout itself is grid.HexLayout. Round gives the hex a point lies in, keeping q + r + s = 0:

Points across a patch of hexes, each coloured by the hex it rounds to, and one fractional hex with the center of the hex it rounds to

f := hex.FracPt(1.4, -1.8)
f.Round()                                     // Hex{1, -2}
f.Length()                                    // 1.8, without rounding to a hex
hex.FracPt(0, 0).Lerp(hex.FracPt(3, -1), 0.5) // FractionalHex{1.5, -0.5}

hex.Pt(2, -1).Float()                  // the other way, exactly
hex.ParseFractionalHex("(1.40,-1.80)") // the form String prints, two decimals

f.Turn(1)                          // a sub-hex position turns and reflects like a Hex
f.TurnAround(hex.FracPt(1, 0), -1) // also ReflectQ, ReflectR and ReflectS

It also has Add, Subtract, Multiply, DistanceTo, Equal and IsZero, with the tolerance of geom.Epsilon on the float comparisons, and IsFinite, the test for a position Round can take: it panics on a NaN or an infinity.

Interop

The shapes and vectors this package builds on are in gravitton/geometry.

a.Point()         // geom.Point[int]{2, -1}
a.Vector()        // geom.Vector[int]{2, -1}, a hex as a step
a.Float().Point() // geom.Point[float64]{2, -1}; Vector gives it as a geom.Vector[float64]

json.Marshal(hex.Pt(2, -1))  // {"q":2,"r":-1}
json.Marshal(hex.QPlus)      // "QPlus"
json.Marshal(hex.OffsetOddR) // "OffsetOddR"

Testing

The hextest package has one assertion per type, exact for a Hex and within a relative tolerance for a FractionalHex, so the helpers stay out of the main package:

import "github.com/gravitton/hexagon/hextest"

hextest.AssertHex(t, got, hex.Pt(2, -1))
hextest.AssertFractionalHex(t, got, hex.FracPt(1.5, -0.5), "after lerp: ")

Full reference: pkg.go.dev.

Out of scope

This package is the coordinate math alone: a hex knows its neighbors, its distances and its shape on the grid, and nothing about where it is drawn or what it holds. What it leaves out is in gravitton/grid, built on it:

A layout needs no grid, and a grid speaks the offset coordinate of its system, which this package converts:

import "github.com/gravitton/grid"

layout := grid.NewHexPointyTopLayout(grid.HexPointyTopCellScale(34), hex.Axial)
layout.Center(hex.Pt(2, -1).Point())                 // (51,-29.44), where the hex is drawn
hex.Axial.From(layout.IndexAt(geom.Pt(60.0, -40.0))) // Hex{2, -1}, the hex under a point

g := grid.NewHexPointyTop[Tile](geom.Sz(20, 15), grid.HexPointyTopCellScale(34))
g.Path(hex.OffsetOddR.To(a), hex.OffsetOddR.To(b), passable, cost) // the cells of the cheapest path

Resources

Credits

License

The MIT License (MIT). Please see License File for more information.

Releases

Contributors

Languages