gohan/world_test.go

133 lines
2.9 KiB
Go

package gohan
import (
"math"
"testing"
"github.com/hajimehoshi/ebiten/v2"
)
type movementSystem struct {
Position *positionComponent
Velocity *velocityComponent
}
func (s *movementSystem) Update(entity Entity) error {
s.Position.X, s.Position.Y = s.Position.X+s.Velocity.X, s.Position.Y+s.Velocity.Y
return nil
}
func (s *movementSystem) Draw(entity Entity, screen *ebiten.Image) error {
return nil
}
func TestWorld(t *testing.T) {
const iterations = 1024
_, e, positionComponentID, velocityComponentID := newTestWorld()
entities := make([]Entity, iterations)
position := e.getComponent(positionComponentID).(*positionComponent)
velocity := e.getComponent(velocityComponentID).(*velocityComponent)
expectedX, expectedY := position.X+(velocity.X*iterations), position.Y+(velocity.Y*iterations)
for i := 0; i < iterations; i++ {
entities[i] = NewEntity()
if i > 0 {
if !entities[i-1].Remove() {
t.Errorf("failed to remove entity %d", entities[i-1])
}
}
err := Update()
if err != nil {
t.Fatal(err)
}
}
// Fetch component again to ensure consistency.
position = e.getComponent(positionComponentID).(*positionComponent)
if round(position.X) != round(expectedX) || round(position.Y) != round(expectedY) {
t.Errorf("failed to update system: expected position (%f,%f), got (%f,%f)", expectedX, expectedY, position.X, position.Y)
}
}
func BenchmarkUpdateWorldInactive(b *testing.B) {
newTestWorld()
b.StopTimer()
b.ResetTimer()
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
err := Update()
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkUpdateWorldActive(b *testing.B) {
newTestWorld()
entities := make([]Entity, b.N)
b.StopTimer()
b.ResetTimer()
b.ReportAllocs()
b.StartTimer()
for i := 0; i < b.N; i++ {
entities[i] = NewEntity()
if i > 0 {
if !entities[i-1].Remove() {
b.Errorf("failed to remove entity %d", entities[i-1])
}
}
err := Update()
if err != nil {
b.Fatal(err)
}
}
}
func newTestWorld() (w *world, e Entity, positionComponentID componentID, velocityComponentID componentID) {
Reset()
e = NewEntity()
position := &positionComponent{
componentID: positionComponentID,
X: 108,
Y: 0,
}
e.AddComponent(position)
positionComponentID = componentID(1)
velocity := &velocityComponent{
componentID: velocityComponentID,
X: -0.1,
Y: 0.2,
}
e.AddComponent(velocity)
velocityComponentID = componentID(2)
movement := &movementSystem{}
AddSystem(movement)
return w, e, positionComponentID, velocityComponentID
}
// Round values to eliminate floating point precision errors. This is only
// necessary during testing because we validate the final values.
func round(f float64) float64 {
return math.Round(f*10) / 10
}
// Note: Because drawing a System is functionally the same as updating a System,
// as only an extra argument is passed, there are no drawing tests or benchmarks.