tins2020/textures.go

97 lines
2.0 KiB
Go

package tins2020
import (
"errors"
"fmt"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
"opslag.de/schobers/fs/vfs"
)
type Texture struct {
texture *sdl.Texture
rect *sdl.Rect
}
func NewTextureFromSurface(renderer *sdl.Renderer, surface *sdl.Surface) (*Texture, error) {
texture, err := renderer.CreateTextureFromSurface(surface)
if err != nil {
return nil, err
}
return &Texture{texture: texture, rect: &sdl.Rect{X: 0, Y: 0, W: surface.W, H: surface.H}}, nil
}
func (t *Texture) Rect() *sdl.Rect { return t.rect }
func (t *Texture) Copy(renderer *sdl.Renderer, target *sdl.Rect) {
renderer.Copy(t.texture, t.rect, target)
}
// func (t *Texture) CopyF(renderer *sdl.Renderer, target *sdl.FRect) {
// renderer.CopyF(t.texture, t.rect, target) // Depends on SDL >=2.0.10
// }
func (t *Texture) Destroy() { t.texture.Destroy() }
type Textures struct {
dir vfs.CopyDir
renderer *sdl.Renderer
textures map[string]*Texture
}
func (t *Textures) Init(renderer *sdl.Renderer, dir vfs.CopyDir) {
t.dir = dir
t.renderer = renderer
t.textures = map[string]*Texture{}
}
func (t *Textures) Load(name, path string, other ...string) error {
err := t.load(name, path)
if err != nil {
return err
}
if len(other) == 0 {
return nil
}
if len(other)%2 != 0 {
return errors.New("expected name/path pairs")
}
for i := 0; i < len(other); i += 2 {
err = t.load(other[i], other[i+1])
if err != nil {
return fmt.Errorf("error loading '%s'; error: %v", other[i], err)
}
}
return nil
}
func (t *Textures) load(name, path string) error {
texturePath, err := t.dir.Retrieve(path)
if err != nil {
return err
}
surface, err := img.Load(texturePath)
if err != nil {
return err
}
defer surface.Free()
texture, err := NewTextureFromSurface(t.renderer, surface)
if err != nil {
return err
}
t.textures[name] = texture
return nil
}
func (t *Textures) Texture(name string) *Texture { return t.textures[name] }
func (t *Textures) Destroy() {
if t.textures == nil {
return
}
for _, t := range t.textures {
t.Destroy()
}
}