doodle/pkg/sprites/sprites.go
Noah Petherbridge 215ed5c847 Stabilize Load Screen by Deferring SDL2 Calls
* The loading screen for Edit and Play modes is stable and the risk of
  game crash is removed. The root cause was the setupAsync() functions
  running on a background goroutine, and running SDL2 draw functions
  while NOT on the main thread, which causes problems.
* The fix is all SDL2 Texture draws become lazy loaded: when the main
  thread is presenting, any Wallpaper or ui.Image that has no texture
  yet gets one created at that time from the cached image.Image.
* All internal game logic then uses image.Image types, to cache bitmaps
  of Level Chunks, Wallpaper images, Sprite icons, etc. and the game is
  free to prepare these asynchronously; only the main thread ever
  Presents and the SDL2 textures initialize on first appearance.
* Several functions had arguments cleaned up: Canvas.LoadLevel() does
  not need the render.Engine as (e.g. wallpaper) textures don't render
  at that stage.
2021-07-19 17:14:00 -07:00

69 lines
1.4 KiB
Go

package sprites
import (
"bytes"
"errors"
"image/png"
"io/ioutil"
"os"
"runtime"
"git.kirsle.net/apps/doodle/assets"
"git.kirsle.net/apps/doodle/pkg/log"
"git.kirsle.net/apps/doodle/pkg/wasm"
"git.kirsle.net/go/render"
"git.kirsle.net/go/ui"
)
// LoadImage loads a sprite as a ui.Image object. It checks Doodle's embedded
// bindata, then the filesystem before erroring out.
//
// NOTE: only .png images supported as of now. TODO
func LoadImage(e render.Engine, filename string) (*ui.Image, error) {
// Try the bindata first.
if data, err := assets.Asset(filename); err == nil {
log.Debug("sprites.LoadImage: %s from bindata", filename)
img, err := png.Decode(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
return ui.ImageFromImage(img)
}
// WASM: try the file over HTTP ajax request.
if runtime.GOOS == "js" {
data, err := wasm.HTTPGet(filename)
if err != nil {
return nil, err
}
img, err := png.Decode(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
return ui.ImageFromImage(img)
}
// Then try the file system.
if _, err := os.Stat(filename); !os.IsNotExist(err) {
log.Debug("sprites.LoadImage: %s from filesystem", filename)
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
img, err := png.Decode(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
return ui.ImageFromImage(img)
}
return nil, errors.New("no such sprite found")
}