ebiten/ui/cocoa/texture_factory.go

124 lines
2.5 KiB
Go
Raw Normal View History

2013-12-06 18:20:48 +01:00
package cocoa
2013-12-30 19:17:39 +01:00
// @class NSOpenGLContext;
//
// NSOpenGLContext* CreateGLContext(NSOpenGLContext* sharedGLContext);
// void UseGLContext(NSOpenGLContext* glContext);
2013-12-07 17:35:24 +01:00
// void UnuseGLContext(void);
2013-12-06 18:20:48 +01:00
//
import "C"
import (
"github.com/hajimehoshi/go-ebiten/graphics"
"github.com/hajimehoshi/go-ebiten/graphics/opengl"
"image"
2013-12-08 14:13:48 +01:00
"runtime"
2013-12-06 18:20:48 +01:00
)
type textureFactory struct {
inited chan struct{}
graphicsDevice *opengl.Device
events chan interface{}
funcs chan func()
funcsDone chan struct{}
gameWindows chan *GameWindow
2013-12-06 18:20:48 +01:00
}
func newTextureFactory() *textureFactory {
return &textureFactory{
inited: make(chan struct{}),
funcs: make(chan func()),
funcsDone: make(chan struct{}),
gameWindows: make(chan *GameWindow),
2013-12-06 18:20:48 +01:00
}
}
func (t *textureFactory) run() {
var sharedContext *C.NSOpenGLContext
2013-12-06 18:20:48 +01:00
go func() {
2013-12-08 14:13:48 +01:00
runtime.LockOSThread()
t.graphicsDevice = opengl.NewDevice()
sharedContext = C.CreateGLContext(nil)
close(t.inited)
t.loop(sharedContext)
}()
<-t.inited
go func() {
for w := range t.gameWindows {
w.run(t.graphicsDevice, sharedContext)
}
}()
2013-12-06 18:20:48 +01:00
}
func (t *textureFactory) loop(sharedContext *C.NSOpenGLContext) {
2013-12-06 18:20:48 +01:00
for {
select {
case f := <-t.funcs:
C.UseGLContext(sharedContext)
2013-12-06 18:20:48 +01:00
f()
2013-12-07 17:35:24 +01:00
C.UnuseGLContext()
2013-12-06 18:20:48 +01:00
t.funcsDone <- struct{}{}
}
}
}
2013-12-13 22:10:24 +01:00
func (t *textureFactory) useGLContext(f func()) {
2013-12-06 18:20:48 +01:00
t.funcs <- f
<-t.funcsDone
}
func (t *textureFactory) createGameWindow(width, height, scale int, title string) *GameWindow {
w := newGameWindow(width, height, scale, title)
go func() {
t.gameWindows <- w
}()
return w
}
func (t *textureFactory) Events() <-chan interface{} {
if t.events != nil {
return t.events
}
t.events = make(chan interface{})
return t.events
}
func (t *textureFactory) CreateTexture(tag interface{}, img image.Image, filter graphics.Filter) {
go func() {
<-t.inited
var id graphics.TextureId
var err error
t.useGLContext(func() {
id, err = t.graphicsDevice.CreateTexture(img, filter)
})
if t.events == nil {
return
}
e := graphics.TextureCreatedEvent{
Tag: tag,
Id: id,
Error: err,
}
t.events <- e
}()
}
func (t *textureFactory) CreateRenderTarget(tag interface{}, width, height int) {
go func() {
<-t.inited
var id graphics.RenderTargetId
var err error
t.useGLContext(func() {
id, err = t.graphicsDevice.CreateRenderTarget(width, height)
})
if t.events == nil {
return
}
e := graphics.RenderTargetCreatedEvent{
Tag: tag,
Id: id,
Error: err,
}
t.events <- e
}()
2013-12-06 18:20:48 +01:00
}