ichigo/engine/sheet.go

62 lines
1.5 KiB
Go
Raw Normal View History

2021-08-26 13:54:22 +10:00
package engine
import (
"image"
2021-09-08 20:08:57 +10:00
"drjosh.dev/gurgle/geom"
2021-08-26 13:54:22 +10:00
"github.com/hajimehoshi/ebiten/v2"
)
2021-08-27 11:49:11 +10:00
var _ interface {
Prepper
Scanner
} = &Sheet{}
2021-08-26 13:54:22 +10:00
// Sheet handles images that consist of a grid of equally sized regions
// (cells) and can produce subimages for the cell at an index. This is useful
2021-09-02 11:53:04 +10:00
// for various applications such as sprite animation and tile maps. Additionally
// each sheet carries a collection of animations that use the sheet.
2021-08-26 13:54:22 +10:00
type Sheet struct {
2021-09-02 11:53:04 +10:00
AnimDefs map[string]*AnimDef
2021-08-26 13:54:22 +10:00
CellSize image.Point
Src ImageRef
w int // width as measured in number of cells
}
2021-09-02 11:53:04 +10:00
// NewAnim returns a new Anim for the given key, or nil if not found in
// AnimDefs.
func (s *Sheet) NewAnim(key string) *Anim {
return s.AnimDefs[key].NewAnim()
}
2021-09-08 12:24:34 +10:00
// NewAnims returns a new Anim for every AnimDef in the AnimDefs map.
func (s *Sheet) NewAnims() map[string]*Anim {
m := make(map[string]*Anim, len(s.AnimDefs))
for k, d := range s.AnimDefs {
m[k] = d.NewAnim()
}
return m
}
2021-09-02 11:53:04 +10:00
// Prepare computes the width of the image (in cells).
2021-08-27 14:52:24 +10:00
func (s *Sheet) Prepare(*Game) error {
2021-08-26 13:54:22 +10:00
s.w, _ = s.Src.Image().Size()
s.w /= s.CellSize.X
2021-08-27 14:52:24 +10:00
return nil
2021-08-26 13:54:22 +10:00
}
2021-09-22 15:55:38 +10:00
// Scan visits &s.Src.
2021-09-22 15:48:02 +10:00
func (s *Sheet) Scan(visit func(interface{}) error) error {
return visit(&s.Src)
}
2021-08-26 13:54:22 +10:00
2021-09-02 11:53:04 +10:00
// SubImage returns an *ebiten.Image corresponding to the given cell index.
2021-08-26 13:54:22 +10:00
func (s *Sheet) SubImage(i int) *ebiten.Image {
2021-09-08 20:08:57 +10:00
p := geom.CMul(image.Pt(i%s.w, i/s.w), s.CellSize)
2021-08-26 13:54:22 +10:00
r := image.Rectangle{p, p.Add(s.CellSize)}
return s.Src.Image().SubImage(r).(*ebiten.Image)
}
2021-09-23 14:17:18 +10:00
func (s *Sheet) String() string { return "Sheet" }