move AssetFS into Game

This commit is contained in:
Josh Deprez 2021-08-22 20:27:08 +10:00
parent 66e0fcd1fa
commit 1d33ac227a
4 changed files with 10 additions and 11 deletions

View file

@ -4,16 +4,12 @@ import (
"compress/gzip"
"encoding/gob"
"image"
"io/fs"
"log"
"github.com/hajimehoshi/ebiten/v2"
)
var (
// Assets (usually embed.FS)
AssetFS fs.FS
// AnimDefs are easier to write as Go expressions -
// so just set this.
AnimDefs map[string]*AnimDef
@ -22,6 +18,7 @@ var (
// Ensure ref types satisfy interfaces.
_ Loader = &ImageRef{}
_ Loader = &SceneRef{}
_ Scener = &SceneRef{}
)
@ -71,14 +68,14 @@ func (r *ImageRef) Image() *ebiten.Image {
// Load loads the image. Load is required before Image returns.
// Loading the same path multiple times uses a cache to return
// the same image.
func (r *ImageRef) Load() error {
func (r *ImageRef) Load(g *Game) error {
// Fast path load from cache
r.image = imageCache[r.Path]
if r.image != nil {
return nil
}
// Slow path
f, err := AssetFS.Open(r.Path)
f, err := g.AssetFS.Open(r.Path)
if err != nil {
return err
}
@ -108,8 +105,8 @@ type SceneRef struct {
}
// Load loads the scene from the file.
func (r *SceneRef) Load() error {
f, err := AssetFS.Open(r.Path)
func (r *SceneRef) Load(g *Game) error {
f, err := g.AssetFS.Open(r.Path)
if err != nil {
return err
}

View file

@ -2,6 +2,7 @@ package engine
import (
"encoding/gob"
"io/fs"
"github.com/hajimehoshi/ebiten/v2"
)
@ -14,6 +15,7 @@ func init() {
// One component must be the designated root component - usually a
// scene of some kind.
type Game struct {
AssetFS fs.FS
ScreenWidth int
ScreenHeight int
Root DrawUpdater // typically a *Scene or SceneRef though
@ -94,7 +96,7 @@ func (g *Game) Load() error {
if !ok {
return nil
}
return l.Load()
return l.Load(g)
})
}

View file

@ -39,7 +39,7 @@ type Identifier interface {
// Loader components get the chance to load themselves. This happens
// before preparation.
type Loader interface {
Load() error
Load(game *Game) error
}
// ParallaxScaler components have a scaling factor. This is used for

View file

@ -20,7 +20,6 @@ func main() {
ebiten.SetWindowSize(640, 480)
ebiten.SetWindowTitle("TODO")
engine.AssetFS = assets
// engine.AnimDefs set in game/anims.go
denseTiles := [][]engine.Tile{
@ -103,6 +102,7 @@ func main() {
}
game := &engine.Game{
AssetFS: assets,
ScreenHeight: 240,
ScreenWidth: 320,
Root: &engine.Scene{