ebiten/graphics/device.go

85 lines
2.2 KiB
Go
Raw Normal View History

2013-06-15 10:07:14 +02:00
package graphics
// #cgo LDFLAGS: -framework OpenGL
//
// #include <OpenGL/gl.h>
// #include <stdlib.h>
import "C"
2013-06-18 17:48:41 +02:00
import (
"image"
)
2013-06-15 10:07:14 +02:00
2013-06-17 16:10:55 +02:00
type Device struct {
2013-06-15 10:07:14 +02:00
screenWidth int
screenHeight int
screenScale int
graphicsContext *GraphicsContext
offscreenTexture *Texture
drawFunc func(*GraphicsContext, *Texture)
2013-06-18 17:48:41 +02:00
funcs []func()
2013-06-15 10:07:14 +02:00
}
2013-06-17 16:10:55 +02:00
func NewDevice(screenWidth, screenHeight, screenScale int,
drawFunc func(*GraphicsContext, *Texture)) *Device {
device := &Device{
2013-06-15 10:07:14 +02:00
screenWidth: screenWidth,
screenHeight: screenHeight,
screenScale: screenScale,
graphicsContext: newGraphicsContext(screenWidth, screenHeight, screenScale),
drawFunc: drawFunc,
2013-06-18 17:48:41 +02:00
funcs: []func(){},
2013-06-15 10:07:14 +02:00
}
2013-06-18 17:48:41 +02:00
device.offscreenTexture = device.NewTexture(screenWidth, screenHeight)
2013-06-17 16:10:55 +02:00
return device
2013-06-15 10:07:14 +02:00
}
2013-06-17 16:10:55 +02:00
func (device *Device) Update() {
2013-06-18 17:48:41 +02:00
for _, f := range device.funcs {
f()
}
device.funcs = []func(){}
2013-06-17 16:10:55 +02:00
g := device.graphicsContext
2013-06-15 10:07:14 +02:00
C.glEnable(C.GL_TEXTURE_2D)
C.glTexParameteri(C.GL_TEXTURE_2D, C.GL_TEXTURE_MIN_FILTER, C.GL_NEAREST)
C.glTexParameteri(C.GL_TEXTURE_2D, C.GL_TEXTURE_MAG_FILTER, C.GL_NEAREST)
2013-06-17 16:10:55 +02:00
g.SetOffscreen(device.offscreenTexture)
2013-06-15 10:07:14 +02:00
g.Clear()
2013-06-17 16:10:55 +02:00
device.drawFunc(g, device.offscreenTexture)
2013-06-15 10:07:14 +02:00
g.flush()
2013-06-17 16:10:55 +02:00
2013-06-15 10:07:14 +02:00
C.glTexParameteri(C.GL_TEXTURE_2D, C.GL_TEXTURE_MIN_FILTER, C.GL_LINEAR)
C.glTexParameteri(C.GL_TEXTURE_2D, C.GL_TEXTURE_MAG_FILTER, C.GL_LINEAR)
g.resetOffscreen()
g.Clear()
geometryMatrix := IdentityGeometryMatrix()
geometryMatrix.SetA(AffineMatrixElement(g.screenScale))
geometryMatrix.SetD(AffineMatrixElement(g.screenScale))
2013-06-17 16:10:55 +02:00
g.DrawTexture(device.offscreenTexture,
0, 0, device.screenWidth, device.screenHeight,
2013-06-15 10:07:14 +02:00
geometryMatrix, IdentityColorMatrix())
g.flush()
}
2013-06-18 17:48:41 +02:00
func (device *Device) NewTexture(width, height int) *Texture {
return createTexture(device, width, height, nil)
}
func (device *Device) NewTextureFromImage(img image.Image) *Texture {
var pix []uint8
switch img.(type) {
case *image.RGBA:
pix = img.(*image.RGBA).Pix
case *image.NRGBA:
pix = img.(*image.NRGBA).Pix
default:
panic("image should be RGBA or NRGBA")
}
size := img.Bounds().Size()
return createTexture(device, size.X, size.Y, pix)
}
func (device *Device) executeWhenDrawing(f func()) {
device.funcs = append(device.funcs, f)
}