ebiten/ui/glfw/canvas.go

97 lines
2.0 KiB
Go
Raw Normal View History

2014-12-05 18:26:02 +01:00
package glfw
import (
glfw "github.com/go-gl/glfw3"
"github.com/hajimehoshi/ebiten/graphics"
"github.com/hajimehoshi/ebiten/graphics/opengl"
"github.com/hajimehoshi/ebiten/ui"
"image"
"runtime"
)
type Canvas struct {
2014-12-06 19:27:55 +01:00
window *glfw.Window
context *opengl.Context
keyboard *Keyboard
funcs chan func()
funcsDone chan struct{}
2014-12-05 18:26:02 +01:00
}
func NewCanvas(width, height, scale int, title string) *Canvas {
window, err := glfw.CreateWindow(width*scale, height*scale, title, nil, nil)
if err != nil {
panic(err)
}
canvas := &Canvas{
2014-12-06 19:27:55 +01:00
window: window,
keyboard: NewKeyboard(),
funcs: make(chan func()),
funcsDone: make(chan struct{}),
2014-12-05 18:26:02 +01:00
}
2014-12-06 19:27:55 +01:00
ui.SetKeyboard(canvas.keyboard)
graphics.SetTextureFactory(canvas)
2014-12-05 18:26:02 +01:00
// For retina displays, recalculate the scale with the framebuffer size.
2014-12-05 19:10:17 +01:00
windowWidth, _ := window.GetFramebufferSize()
2014-12-05 18:26:02 +01:00
realScale := windowWidth / width
canvas.run()
canvas.use(func() {
canvas.context = opengl.NewContext(width, height, realScale)
})
return canvas
}
2014-12-06 20:14:35 +01:00
func (c *Canvas) Draw(d ui.Drawer) (err error) {
2014-12-05 18:26:02 +01:00
c.use(func() {
2014-12-06 20:14:35 +01:00
err = c.context.Update(d)
2014-12-05 18:26:02 +01:00
c.window.SwapBuffers()
})
2014-12-06 20:14:35 +01:00
return
2014-12-05 18:26:02 +01:00
}
func (c *Canvas) IsClosed() bool {
return c.window.ShouldClose()
}
2014-12-06 21:21:20 +01:00
func (c *Canvas) CreateTexture(img image.Image, filter graphics.Filter) (graphics.TextureID, error) {
var id graphics.TextureID
2014-12-05 18:26:02 +01:00
var err error
c.use(func() {
id, err = opengl.CreateTexture(img, filter)
})
return id, err
}
2014-12-06 21:21:20 +01:00
func (c *Canvas) CreateRenderTarget(width, height int, filter graphics.Filter) (graphics.RenderTargetID, error) {
var id graphics.RenderTargetID
2014-12-05 18:26:02 +01:00
var err error
c.use(func() {
id, err = opengl.CreateRenderTarget(width, height, filter)
})
return id, err
}
func (c *Canvas) run() {
go func() {
runtime.LockOSThread()
c.window.MakeContextCurrent()
glfw.SwapInterval(1)
for {
f := <-c.funcs
f()
c.funcsDone <- struct{}{}
}
}()
}
func (c *Canvas) use(f func()) {
c.funcs <- f
<-c.funcsDone
}
2014-12-05 19:10:17 +01:00
func (c *Canvas) update() {
2014-12-06 19:27:55 +01:00
c.keyboard.update(c.window)
2014-12-05 19:10:17 +01:00
}