Reimplement cursor as a query operation

This commit is contained in:
2020-04-10 20:54:58 +01:00
parent bb3ddc4896
commit f3fea83173
5 changed files with 58 additions and 37 deletions

View File

@@ -3,7 +3,6 @@ package ui
import (
"flag"
"fmt"
"image"
"log"
"os"
"runtime/debug"
@@ -19,6 +18,11 @@ type Game interface {
Draw(*ebiten.Image) error
}
type CustomCursor interface {
// The cursor draw operation
Cursor() (*ebiten.Image, *ebiten.DrawImageOptions, error)
}
var (
screenScale = flag.Float64("screen-scale", 1.0, "Scale the window by this factor")
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
@@ -32,8 +36,6 @@ type Window struct {
KeyUpHandlers map[ebiten.Key]func()
MouseWheelHandler func(float64, float64)
cursor *ebiten.Image
// Allow the "game" to be switched out at any time
game Game
@@ -74,15 +76,26 @@ func (w *Window) Layout(_, _ int) (int, int) {
return w.xRes, w.yRes
}
func (w *Window) SetCursor(cursor *ebiten.Image) {
w.cursor = cursor
func (w *Window) drawCursor(screen *ebiten.Image) error {
cIface, ok := w.game.(CustomCursor)
if !ok {
return nil
}
cursor, op, err := cIface.Cursor()
if err != nil {
return err
}
// Hide the system cursor if we have a custom one
if cursor == nil {
ebiten.SetCursorMode(ebiten.CursorModeVisible)
} else {
ebiten.SetCursorMode(ebiten.CursorModeHidden)
return nil
}
ebiten.SetCursorMode(ebiten.CursorModeHidden)
return screen.DrawImage(cursor, op)
}
func (w *Window) Update(screen *ebiten.Image) (outErr error) {
@@ -125,23 +138,14 @@ func (w *Window) Update(screen *ebiten.Image) (outErr error) {
return err
}
if w.cursor != nil {
// TODO: account for scaling, including the hotspot.
pos := image.Pt(ebiten.CursorPosition())
op := ebiten.DrawImageOptions{}
op.GeoM.Translate(float64(pos.X), float64(pos.Y))
if err := screen.DrawImage(w.cursor, &op); err != nil {
return err
}
}
if w.debug {
// Draw FPS, etc, to the screen
msg := fmt.Sprintf("tps=%0.2f fps=%0.2f", ebiten.CurrentTPS(), ebiten.CurrentFPS())
ebitenutil.DebugPrint(screen, msg)
}
return nil
// Draw the cursor last
return w.drawCursor(screen)
}
// TODO: a stop or other cancellation mechanism