2024-02-10 19:45:06 +01:00
|
|
|
package systems
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
. "openquell/components"
|
|
|
|
|
|
|
|
|
|
"github.com/hajimehoshi/ebiten/v2"
|
|
|
|
|
"github.com/mlange-42/arche/ecs"
|
|
|
|
|
"github.com/mlange-42/arche/generic"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type GridSystem struct {
|
2024-02-23 18:47:15 +01:00
|
|
|
World *ecs.World
|
|
|
|
|
Selector *generic.Filter3[Renderable, Position, Solid]
|
|
|
|
|
UseCache bool
|
|
|
|
|
Cache *ebiten.Image
|
|
|
|
|
Count int // register tile count, invalidates cache
|
|
|
|
|
Background *ebiten.Image
|
|
|
|
|
Width, Height, Tilesize int
|
2024-02-10 19:45:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewGridSystem(world *ecs.World, width, height,
|
2024-02-23 18:47:15 +01:00
|
|
|
tilesize int, background *ebiten.Image) System {
|
2024-02-10 19:45:06 +01:00
|
|
|
|
|
|
|
|
cache := ebiten.NewImage(width, height)
|
|
|
|
|
|
|
|
|
|
system := &GridSystem{
|
|
|
|
|
Selector: generic.NewFilter3[Renderable, Position, Solid](),
|
|
|
|
|
UseCache: false,
|
|
|
|
|
Cache: cache,
|
|
|
|
|
Width: width,
|
|
|
|
|
Height: height,
|
|
|
|
|
Tilesize: tilesize,
|
|
|
|
|
Background: background,
|
|
|
|
|
World: world,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return system
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-01 10:55:14 +01:00
|
|
|
func (system *GridSystem) Update() error {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2024-02-10 19:45:06 +01:00
|
|
|
|
|
|
|
|
func (system *GridSystem) Draw(screen *ebiten.Image) {
|
|
|
|
|
op := &ebiten.DrawImageOptions{}
|
2024-02-22 14:33:01 +01:00
|
|
|
query := system.Selector.Query(system.World)
|
2024-03-01 10:55:14 +01:00
|
|
|
|
2024-02-22 14:33:01 +01:00
|
|
|
if !system.UseCache || query.Count() != system.Count {
|
2024-02-10 19:45:06 +01:00
|
|
|
// map not cached or cacheable, write it to the cache
|
2024-03-01 10:55:14 +01:00
|
|
|
system.Cache.DrawImage(system.Background, op)
|
2024-02-10 19:45:06 +01:00
|
|
|
|
2024-02-22 14:33:01 +01:00
|
|
|
system.Count = query.Count()
|
2024-03-01 10:55:14 +01:00
|
|
|
counter := 0
|
2024-02-10 19:45:06 +01:00
|
|
|
for query.Next() {
|
|
|
|
|
sprite, pos, _ := query.Get()
|
2024-03-01 10:55:14 +01:00
|
|
|
counter++
|
|
|
|
|
op.GeoM.Reset()
|
|
|
|
|
op.GeoM.Translate(float64(pos.X), float64(pos.Y))
|
|
|
|
|
system.Cache.DrawImage(sprite.Image, op)
|
2024-02-10 19:45:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
op.GeoM.Reset()
|
|
|
|
|
screen.DrawImage(system.Cache, op)
|
|
|
|
|
|
|
|
|
|
system.UseCache = true
|
2024-03-01 10:55:14 +01:00
|
|
|
|
2024-02-10 19:45:06 +01:00
|
|
|
} else {
|
|
|
|
|
// use the cached map
|
|
|
|
|
op.GeoM.Reset()
|
|
|
|
|
screen.DrawImage(system.Cache, op)
|
2024-02-22 14:33:01 +01:00
|
|
|
query.Close()
|
2024-02-10 19:45:06 +01:00
|
|
|
}
|
|
|
|
|
}
|