Skip to content

Commit

Permalink
add pos/area utils and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
BuckarooBanzay committed Aug 26, 2024
1 parent 63455e6 commit ada15f4
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
35 changes: 35 additions & 0 deletions area.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package types

type Area struct {
Pos1 *Pos
Pos2 *Pos
}

func NewArea(p1, p2 *Pos) *Area {
p1, p2 = SortPos(p1, p2)
return &Area{Pos1: p1, Pos2: p2}
}

// the inclusive size
func (a *Area) Size() *Pos {
return a.Pos2.Subtract(a.Pos1).Add(NewPos(1, 1, 1))
}

func (a *Area) Volume() int {
s := a.Size()
return s.X() * s.Y() * s.Z()
}

func (a *Area) Corners() []*Pos {
return []*Pos{
{a.Pos1.X(), a.Pos1.Y(), a.Pos1.Z()},
{a.Pos2.X(), a.Pos1.Y(), a.Pos1.Z()},
{a.Pos1.X(), a.Pos2.Y(), a.Pos1.Z()},
{a.Pos1.X(), a.Pos1.Y(), a.Pos2.Z()},

{a.Pos2.X(), a.Pos2.Y(), a.Pos2.Z()},
{a.Pos1.X(), a.Pos2.Y(), a.Pos2.Z()},
{a.Pos2.X(), a.Pos1.Y(), a.Pos2.Z()},
{a.Pos2.X(), a.Pos2.Y(), a.Pos1.Z()},
}
}
26 changes: 26 additions & 0 deletions area_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package types_test

import (
"testing"

"github.com/minetest-go/types"
"github.com/stretchr/testify/assert"
)

func TestArea(t *testing.T) {
p1 := types.NewPos(1, 2, 3)
p2 := types.NewPos(10, 20, 30)

a := types.NewArea(p1, p2)
s := a.Size()
assert.Equal(t, types.NewPos(10, 19, 28), s)

v := a.Volume()
assert.Equal(t, 5320, v)

visited := map[string]bool{}
for _, p := range a.Corners() {
assert.False(t, visited[p.String()])
visited[p.String()] = true
}
}
6 changes: 6 additions & 0 deletions pos.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (

type Pos [3]int

// zero position
var PosZero = Pos{0, 0, 0}

// size of a mapblock
var MapBlockSize = Pos{16, 16, 16}

func NewPos(x, y, z int) *Pos {
return &Pos{x, y, z}
}
Expand Down
9 changes: 9 additions & 0 deletions pos_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,12 @@ func TestSortPos(t *testing.T) {
assert.Equal(t, 2, p2[1])
assert.Equal(t, 3, p2[2])
}

func TestPosIsWithin(t *testing.T) {
p1 := &types.Pos{1, 2, 3}
p2 := &types.Pos{10, 20, 30}

assert.True(t, types.NewPos(1, 2, 3).IsWithin(p1, p2))
assert.True(t, types.NewPos(10, 2, 3).IsWithin(p1, p2))
assert.False(t, types.NewPos(0, 2, 3).IsWithin(p1, p2))
}

0 comments on commit ada15f4

Please sign in to comment.