ebiten/example/blocks/textures.go

122 lines
2.3 KiB
Go
Raw Normal View History

2014-12-06 17:09:59 +01:00
package blocks
2014-05-03 08:25:41 +02:00
import (
2014-12-05 14:16:58 +01:00
"github.com/hajimehoshi/ebiten/graphics"
2014-05-03 08:25:41 +02:00
"image"
"os"
"sync"
)
type namePath struct {
name string
path string
}
type nameSize struct {
name string
2014-12-06 17:09:59 +01:00
size Size
2014-05-03 08:25:41 +02:00
}
type Textures struct {
textureFactory graphics.TextureFactory
texturePaths chan namePath
renderTargetSizes chan nameSize
textures map[string]graphics.TextureId
renderTargets map[string]graphics.RenderTargetId
sync.RWMutex
}
func NewTextures(textureFactory graphics.TextureFactory) *Textures {
textures := &Textures{
textureFactory: textureFactory,
texturePaths: make(chan namePath),
renderTargetSizes: make(chan nameSize),
textures: map[string]graphics.TextureId{},
renderTargets: map[string]graphics.RenderTargetId{},
}
2014-05-03 17:40:53 +02:00
go func() {
for {
textures.loopMain()
}
}()
2014-05-03 08:25:41 +02:00
return textures
}
func loadImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return nil, err
}
return img, nil
}
2014-05-03 17:40:53 +02:00
func (t *Textures) loopMain() {
select {
case p := <-t.texturePaths:
name := p.name
path := p.path
go func() {
img, err := loadImage(path)
if err != nil {
panic(err)
}
2014-12-05 18:26:02 +01:00
id, err := t.textureFactory.CreateTexture(img, graphics.FilterNearest)
2014-05-03 17:40:53 +02:00
if err != nil {
panic(err)
}
t.Lock()
defer t.Unlock()
t.textures[name] = id
}()
case s := <-t.renderTargetSizes:
name := s.name
size := s.size
go func() {
2014-12-05 18:26:02 +01:00
id, err := t.textureFactory.CreateRenderTarget(size.Width, size.Height, graphics.FilterNearest)
2014-05-03 17:40:53 +02:00
if err != nil {
panic(err)
}
t.Lock()
defer t.Unlock()
t.renderTargets[name] = id
}()
2014-05-03 08:25:41 +02:00
}
}
func (t *Textures) RequestTexture(name string, path string) {
t.texturePaths <- namePath{name, path}
}
2014-12-06 17:09:59 +01:00
func (t *Textures) RequestRenderTarget(name string, size Size) {
2014-05-03 08:25:41 +02:00
t.renderTargetSizes <- nameSize{name, size}
}
func (t *Textures) Has(name string) bool {
t.RLock()
defer t.RUnlock()
_, ok := t.textures[name]
if ok {
return true
}
_, ok = t.renderTargets[name]
return ok
}
func (t *Textures) GetTexture(name string) graphics.TextureId {
t.RLock()
defer t.RUnlock()
return t.textures[name]
}
func (t *Textures) GetRenderTarget(name string) graphics.RenderTargetId {
t.RLock()
defer t.RUnlock()
return t.renderTargets[name]
}