feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# game
What games need beyond what apps do, for [MyGo](https://github.com/egoist/mygo),
opt-in: MyGo is an app framework.
- `game.View` runs a game's loop in a native UI element, in fixed steps
with the player's input, `game.Camera` looks at its world, and
`game.IntegerFit` shows a canvas of pixel art pixel-perfect at any size.
- `gamepad` reads game controllers in one standard layout, on macOS
(GameController.framework), Windows (XInput), Linux (evdev) and in
browsers (the Gamepad API).
```go
import "github.com/egoist/mygo/plugins/game/gamepad"
for _, pad := range gamepad.Pads() {
s := pad.State()
x, y := s.LeftStick()
move(x, y)
}
```
See [the documentation](../../docs/plugins/game.md).
+335
View File
@@ -0,0 +1,335 @@
// Package game has what games need beyond what apps do, opt-in, out of
// MyGo's core ui: a game loop that updates a world in fixed steps with
// the player's input and draws it every frame (View), and a camera that
// looks at a 2D world (Camera), shown pixel-perfect at any size through
// a ui.Canvas (IntegerFit). Its package gamepad reads controllers.
//
// type farm struct{ x, y float32 }
//
// func (f *farm) Update(in *game.Input) {
// if in.Down(ui.KeyD) {
// f.x += 2
// }
// }
//
// func (f *farm) Draw(p *ui.Painter, r ui.Rect, alpha float64) {
// game.Camera{X: f.x, Y: f.y, Zoom: 3}.Draw(p, r, func() { drawWorld(p) })
// }
//
// ui.View(func(c *ui.Context) { game.View(c, f).Fill() })
package game
import (
"math"
"time"
"github.com/egoist/mygo/ui"
)
// A Game is a game View runs: it updates the game's world in fixed
// steps, whatever the display's rate, and draws it every frame, as
// Ebitengine's Update and Draw.
type Game interface {
// Update advances the game one step, of 1/Rate seconds unless
// the game has a Rate method, with the input since the step before.
Update(in *Input)
// Draw draws the game into r. alpha, from 0 to 1, is how far the
// frame's time is into the next step: a game may draw what moves
// that far between its last two places, for motion smoother than its
// steps.
Draw(p *ui.Painter, r ui.Rect, alpha float64)
}
// Rate is how many steps a second a View runs a game, unless the
// game has a method Rate() int giving its own.
const Rate = 60
// maxCatchUp is the most time steps catch up on, after a pause such as a
// window out of sight: MonoGame's MaxElapsedTime.
const maxCatchUp = 250 * time.Millisecond
// Input is what a game's player did, as a step sees it: the keys and
// pointer buttons held, and those pressed and released since the step
// before, even if pressed and released between two steps. Keys are by
// position, as PhysicalKey: KeyW is the key in W's place whatever the
// layout, as games want for WASD.
type Input struct {
down, pressed, released map[ui.Key]bool
x, y float32
inside bool
buttons, bPressed, bReleased [3]bool
wheelX, wheelY float32
w, h float32
focused bool
}
func newInput() *Input {
return &Input{down: map[ui.Key]bool{}, pressed: map[ui.Key]bool{}, released: map[ui.Key]bool{}}
}
// Down reports whether k is held.
func (in *Input) Down(k ui.Key) bool { return in.down[k] }
// Pressed reports whether k was pressed since the step before.
func (in *Input) Pressed(k ui.Key) bool { return in.pressed[k] }
// Released reports whether k was released since the step before.
func (in *Input) Released(k ui.Key) bool { return in.released[k] }
// Pointer returns where the pointer is in the view, from its top-left
// corner, and whether it is over the view.
func (in *Input) Pointer() (x, y float32, over bool) { return in.x, in.y, in.inside }
// PointerDown reports whether pointer button b (0 the primary, 1 the
// secondary, 2 the middle) is held.
func (in *Input) PointerDown(b int) bool { return b >= 0 && b < 3 && in.buttons[b] }
// PointerPressed reports whether button b was pressed since the step
// before.
func (in *Input) PointerPressed(b int) bool { return b >= 0 && b < 3 && in.bPressed[b] }
// PointerReleased reports whether button b was released since the step
// before.
func (in *Input) PointerReleased(b int) bool { return b >= 0 && b < 3 && in.bReleased[b] }
// Wheel returns how far the wheel or touchpad scrolled since the step
// before, in DIPs, down and right positive.
func (in *Input) Wheel() (dx, dy float32) { return in.wheelX, in.wheelY }
// Size returns the view's size.
func (in *Input) Size() (w, h float32) { return in.w, in.h }
// Focused reports whether the view has the keyboard, which it loses with
// its window or to another element: a game pauses without it, as the
// player is elsewhere.
func (in *Input) Focused() bool { return in.focused }
// step forgets what happened before this step.
func (in *Input) step() {
clear(in.pressed)
clear(in.released)
in.bPressed, in.bReleased = [3]bool{}, [3]bool{}
in.wheelX, in.wheelY = 0, 0
}
// releaseAll lets go of everything held, as when the window loses the
// keyboard, whose releases never come.
func (in *Input) releaseAll() {
for k := range in.down {
in.released[k] = true
}
clear(in.down)
for b, held := range in.buttons {
if held {
in.bReleased[b] = true
}
}
in.buttons = [3]bool{}
}
// loop is what a View keeps from frame to frame.
type loop struct {
game Game
in *Input
last time.Time
lag time.Duration
wantFocus bool
}
func (l *loop) rate() int {
if r, ok := l.game.(interface{ Rate() int }); ok && r.Rate() > 0 {
return r.Rate()
}
return Rate
}
func (l *loop) input(ev ui.InputEvent) bool {
in := l.in
switch ev.Kind {
case ui.InputKeyDown, ui.InputKeyUp:
if ev.Mods&(ui.Super|ui.Ctrl|ui.Alt) != 0 && ev.Kind == ui.InputKeyDown {
return false // the menus' shortcuts
}
k := ev.PhysicalKey
if k == ui.KeyUnknown {
k = ev.Key
}
if k == ui.KeyUnknown {
return false // a modifier on its own, or a key of no name
}
if ev.Kind == ui.InputKeyDown {
if !ev.Repeat && !in.down[k] {
in.pressed[k] = true
}
in.down[k] = true
} else if in.down[k] {
in.released[k] = true
delete(in.down, k)
}
return true
case ui.InputPointerDown, ui.InputPointerUp:
in.x, in.y = ev.X, ev.Y
if ev.Button >= 0 && ev.Button < 3 {
down := ev.Kind == ui.InputPointerDown
if down && !in.buttons[ev.Button] {
in.bPressed[ev.Button] = true
} else if !down && in.buttons[ev.Button] {
in.bReleased[ev.Button] = true
}
in.buttons[ev.Button] = down
}
if ev.Kind == ui.InputPointerDown {
l.wantFocus = true
}
return true
case ui.InputPointerMove:
in.x, in.y = ev.X, ev.Y
in.inside = ev.X >= 0 && ev.Y >= 0 && ev.X < in.w && ev.Y < in.h
return true
case ui.InputScroll:
in.wheelX += ev.DX
in.wheelY += ev.DY
return true
}
return false
}
func (l *loop) draw(p *ui.Painter, r ui.Rect) {
p.AnimationFrame()
l.in.w, l.in.h = r.W, r.H
step := time.Second / time.Duration(l.rate())
now := frameTime(p)
if !l.last.IsZero() {
// Painting twice a frame, at its one time, runs no step twice.
l.lag += min(max(now.Sub(l.last), 0), maxCatchUp)
}
l.last = now
for l.lag >= step {
l.game.Update(l.in)
l.in.step()
l.lag -= step
}
l.game.Draw(p, r, float64(l.lag)/float64(step))
}
type loopKey struct{}
// frameTime returns the time of the frame p paints; tests replace it.
var frameTime = func(p *ui.Painter) time.Time { return p.Now() }
// View creates an element that runs g: Update in fixed steps of the game's
// rate, with the keys, pointer and wheel the element takes as Input, and
// Draw every frame, as long as it shows. It takes the keyboard focus as it
// appears and when clicked, and lets go of what was held when the window
// loses the keyboard. Size it as any element, as with Fill:
//
// game.View(c, g).Fill()
func View(c *ui.Context, g Game) ui.Element {
e := ui.Box(c).Focusable().AutoFocus()
l := *ui.Local(e, loopKey{}, func() *loop { return &loop{in: newInput()} })
l.game = g
if l.wantFocus {
l.wantFocus = false
e.Focus()
}
l.in.focused = e.Focused()
if !l.in.focused {
l.in.releaseAll()
}
return e.HandleInput(l.input).Draw(l.draw)
}
// IntegerFit returns where a canvas of w×h pixels shows in r as large as
// it can with a whole number of the screen's pixels for each of its own,
// at least one, centered (letterboxed): pixel-perfect scaling, for p's
// screen, as Godot's viewport stretch and Stardew Valley draw pixel art.
// k is that number. A game draws its world into a ui.Canvas of a logical
// size, as 480×270, and shows it there:
//
// dst, _ := game.IntegerFit(p, 480, 270, r)
// p.Image(world.Bitmap(), dst, ui.FillBox)
//
// The pointer at x, y of the view is at ((x+r.X-dst.X)*480/dst.W,
// (y+r.Y-dst.Y)*270/dst.H) of the canvas.
func IntegerFit(p *ui.Painter, w, h int, r ui.Rect) (dst ui.Rect, k int) {
if w <= 0 || h <= 0 {
return ui.Rect{}, 0
}
s := p.Scale()
k = max(int(min(r.W*s/float32(w), r.H*s/float32(h))), 1)
dw, dh := float32(w*k)/s, float32(h*k)/s
// On whole pixels of the screen, as the snapped image is.
x := float32(int((r.X+(r.W-dw)/2)*s+0.5)) / s
y := float32(int((r.Y+(r.H-dh)/2)*s+0.5)) / s
return ui.Rect{X: x, Y: y, W: dw, H: dh}, k
}
// A Camera looks at a 2D world: the world's point X, Y shows at the middle
// of the view, Zoom times as large (0 is 1), turned Rotation degrees, as
// raylib's Camera2D. World units are DIPs at a zoom of 1.
type Camera struct {
X, Y float32
Zoom float32
Rotation float32
}
func (cam Camera) zoom() float32 {
if cam.Zoom == 0 {
return 1
}
return cam.Zoom
}
// Transform returns the transform from the world to the window, for the
// view r, with the origin (0, 0): Painter.Transform(cam.Transform(r), 0, 0,
// draw). Draw is that, snapped and clipped.
func (cam Camera) Transform(r ui.Rect) ui.Transform {
z := cam.zoom()
t := ui.Translation(-cam.X, -cam.Y)
if cam.Rotation != 0 {
t = t.Then(ui.Rotation(-cam.Rotation))
}
return t.Then(ui.Scaling(z, z)).Then(ui.Translation(r.X+r.W/2, r.Y+r.H/2))
}
// Draw draws what fn draws in world coordinates through the camera into r,
// clipped to it. Unturned, the world moves by whole pixels of the screen,
// so that the edges of tiles drawn at whole world units stay on them,
// while parts of bitmaps, which ui.Painter.ImageRegion places where they
// are under a transform, glide.
func (cam Camera) Draw(p *ui.Painter, r ui.Rect, fn func()) {
t := cam.Transform(r)
if cam.Rotation == 0 {
z := cam.zoom()
s := p.Scale()
snap := func(v float32) float32 { return float32(math.Round(float64(v*s))) / s }
t = ui.Scaling(z, z).Then(ui.Translation(snap(r.X+r.W/2-cam.X*z), snap(r.Y+r.H/2-cam.Y*z)))
}
p.Clip(r, 0, func() { p.Transform(t, 0, 0, fn) })
}
// ToWorld returns the world's point at x, y of the view r, from its
// top-left corner, as Input.Pointer gives it.
func (cam Camera) ToWorld(r ui.Rect, x, y float32) (wx, wy float32) {
z := cam.zoom()
dx, dy := (x-r.W/2)/z, (y-r.H/2)/z
if cam.Rotation != 0 {
a := float64(cam.Rotation) * math.Pi / 180
sin, cos := float32(math.Sin(a)), float32(math.Cos(a))
dx, dy = dx*cos-dy*sin, dx*sin+dy*cos
}
return cam.X + dx, cam.Y + dy
}
// Visible returns the part of the world the camera shows in the view r:
// the bounds of it when turned. A game draws only the tiles in it.
func (cam Camera) Visible(r ui.Rect) ui.Rect {
xs, ys := [4]float32{}, [4]float32{}
for i, c := range [4][2]float32{{0, 0}, {r.W, 0}, {0, r.H}, {r.W, r.H}} {
xs[i], ys[i] = cam.ToWorld(r, c[0], c[1])
}
x0, x1 := min(xs[0], xs[1], xs[2], xs[3]), max(xs[0], xs[1], xs[2], xs[3])
y0, y1 := min(ys[0], ys[1], ys[2], ys[3]), max(ys[0], ys[1], ys[2], ys[3])
return ui.Rect{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}
}
+268
View File
@@ -0,0 +1,268 @@
package game
import (
"image/color"
"math"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
// stepper records the steps a View runs.
type stepper struct {
steps int
wDown, wPressed []bool
spacePressed int
wReleased int
clicks int
focused bool
alpha float64
draws int
}
func (s *stepper) Update(in *Input) {
s.steps++
s.wDown = append(s.wDown, in.Down(ui.KeyW))
s.wPressed = append(s.wPressed, in.Pressed(ui.KeyW))
if in.Pressed(ui.KeySpace) {
s.spacePressed++
}
if in.Released(ui.KeyW) {
s.wReleased++
}
if in.PointerPressed(0) {
s.clicks++
}
s.focused = in.Focused()
}
func (s *stepper) Draw(p *ui.Painter, r ui.Rect, alpha float64) {
s.alpha, s.draws = alpha, s.draws+1
}
// gameTester tests a game in a view whose frames are at the test's
// clock, now.
func gameTester(t *testing.T, g Game, now *time.Time) *ui.Tester {
before := frameTime
frameTime = func(*ui.Painter) time.Time { return *now }
t.Cleanup(func() { frameTime = before })
tt := ui.NewTester(func(c *ui.Context) { View(c, g).Size(200, 100) }, 200, 100)
tt.Frame()
return tt
}
func TestView(t *testing.T) {
g := &stepper{}
now := time.Unix(1000, 0)
tt := gameTester(t, g, &now)
if g.steps != 0 || g.draws == 0 {
t.Fatalf("first frame: %d steps, %d draws", g.steps, g.draws)
}
// 100 ms are 6 steps, and a third of the next.
now = now.Add(105 * time.Millisecond)
tt.Frame()
if g.steps != 6 || !g.focused {
t.Errorf("%d steps in 105 ms, focused %v", g.steps, g.focused)
}
if math.Abs(g.alpha-0.3) > 0.01 {
t.Errorf("alpha %v", g.alpha)
}
// Painting again at the same time runs no step.
tt.Frame()
if g.steps != 6 {
t.Errorf("%d steps after painting twice", g.steps)
}
// W held: down in every step, pressed in the first only.
g.wDown, g.wPressed = nil, nil
tt.KeyDown(ui.KeyW)
now = now.Add(50 * time.Millisecond)
tt.Frame()
if len(g.wDown) != 3 || !g.wDown[0] || !g.wDown[2] || !g.wPressed[0] || g.wPressed[1] {
t.Errorf("W held: down %v, pressed %v", g.wDown, g.wPressed)
}
// Space tapped between two steps: pressed in the next.
tt.Key(0, ui.KeySpace)
now = now.Add(20 * time.Millisecond)
tt.Frame()
if g.spacePressed != 1 {
t.Errorf("Space pressed in %d steps", g.spacePressed)
}
// The window losing the keyboard lets go of W.
tt.SetFocused(false)
now = now.Add(20 * time.Millisecond)
tt.Frame()
if g.focused {
t.Error("focused without the keyboard")
}
if g.wReleased != 1 || g.wDown[len(g.wDown)-1] {
t.Errorf("W after losing the keyboard: released %d, down %v", g.wReleased, g.wDown[len(g.wDown)-1])
}
tt.SetFocused(true)
// A click.
tt.ClickAt(10, 10)
now = now.Add(20 * time.Millisecond)
tt.Frame()
if g.clicks != 1 {
t.Errorf("%d clicks", g.clicks)
}
// After a long pause, a quarter of a second of steps, not all.
before := g.steps
now = now.Add(10 * time.Second)
tt.Frame()
if n := g.steps - before; n != 15 {
t.Errorf("%d steps after 10 s", n)
}
}
// fastGame runs at its own rate.
type fastGame struct{ stepper }
func (fastGame) Rate() int { return 120 }
func TestRate(t *testing.T) {
g := &fastGame{}
now := time.Unix(1000, 0)
tt := gameTester(t, g, &now)
now = now.Add(100 * time.Millisecond)
tt.Frame()
if g.steps != 12 {
t.Errorf("%d steps in 100 ms at 120 a second", g.steps)
}
}
// TestAnyFrameRate checks that the steps keep the game's rate, and alpha
// its place between them, whatever the frames' rate: under the steps', at
// a display's, and far over it, as frames uncapped (MYGO_UNCAPPED) come.
// A second of frames runs 60 steps, and alpha, from 0 to 1, grows from
// frame to frame between two steps.
func TestAnyFrameRate(t *testing.T) {
for _, every := range []time.Duration{20 * time.Millisecond, 6250 * time.Microsecond, time.Millisecond, 100 * time.Microsecond} {
g := &stepper{}
now := time.Unix(1000, 0)
tt := gameTester(t, g, &now)
steps, alpha := g.steps, g.alpha
for range time.Second / every {
now = now.Add(every)
tt.Frame()
if g.alpha < 0 || g.alpha >= 1 {
t.Fatalf("frames every %v: alpha %v", every, g.alpha)
}
if g.steps == steps && g.alpha <= alpha {
t.Fatalf("frames every %v: alpha went from %v to %v within a step", every, alpha, g.alpha)
}
steps, alpha = g.steps, g.alpha
}
if g.steps != Rate {
t.Errorf("frames every %v: %d steps in a second, want %d", every, g.steps, Rate)
}
}
}
var red = ui.RGB(255, 0, 0)
// paint renders what draw paints into a 400×300 view.
func paint(scale float32, draw func(p *ui.Painter, r ui.Rect)) *ui.Tester {
tt := ui.NewTester(func(c *ui.Context) { ui.Box(c).Size(400, 300).Draw(draw) }, 400, 300)
tt.SetScale(scale)
tt.Frame()
return tt
}
func isRed(c color.RGBA) bool { return c.R > 250 && c.G < 5 && c.B < 5 }
func TestCamera(t *testing.T) {
r := ui.Rect{X: 50, Y: 20, W: 400, H: 300}
cam := Camera{X: 100, Y: 80, Zoom: 2}
// The camera's point shows at the middle.
if x, y := cam.ToWorld(r, 200, 150); x != 100 || y != 80 {
t.Errorf("middle = %v, %v", x, y)
}
if x, y := cam.ToWorld(r, 0, 0); x != 0 || y != 5 {
t.Errorf("corner = %v, %v", x, y)
}
if v := cam.Visible(r); v != (ui.Rect{X: 0, Y: 5, W: 200, H: 150}) {
t.Errorf("visible = %v", v)
}
// Transform maps the world back to where ToWorld found it: the world's
// point at the view's top-left corner paints there.
img := paint(1, func(p *ui.Painter, r ui.Rect) {
wx, wy := cam.ToWorld(r, 0, 0)
p.Transform(cam.Transform(r), 0, 0, func() {
p.Fill(ui.Rect{X: wx, Y: wy, W: 2, H: 2}, red, 0)
})
}).Image()
if !isRed(img.RGBAAt(1, 1)) || isRed(img.RGBAAt(6, 6)) {
t.Errorf("world corner: %v at 1, 1, %v at 6, 6", img.RGBAAt(1, 1), img.RGBAAt(6, 6))
}
turned := Camera{Rotation: 90}
img = paint(1, func(p *ui.Painter, r ui.Rect) {
wx, wy := turned.ToWorld(r, 300, 150)
p.Transform(turned.Transform(r), 0, 0, func() {
p.Fill(ui.Rect{X: wx - 2, Y: wy - 2, W: 4, H: 4}, red, 0)
})
}).Image()
if !isRed(img.RGBAAt(300, 150)) || isRed(img.RGBAAt(310, 150)) {
t.Errorf("turned: %v at 300, 150, %v at 310, 150", img.RGBAAt(300, 150), img.RGBAAt(310, 150))
}
}
func TestIntegerFit(t *testing.T) {
var dst, small ui.Rect
var k, smallK int
paint(2, func(p *ui.Painter, r ui.Rect) {
// 1000×600 DIPs at 2×: 2000×1200 pixels, for 480×270: 4 times (1920×1080).
dst, k = IntegerFit(p, 480, 270, ui.Rect{X: 10, Y: 20, W: 1000, H: 600})
// Smaller than the canvas: one pixel each, overflowing.
small, smallK = IntegerFit(p, 480, 270, ui.Rect{W: 100, H: 100})
})
if k != 4 || dst != (ui.Rect{X: 30, Y: 50, W: 960, H: 540}) {
t.Errorf("fit %v, k %d", dst, k)
}
if smallK != 1 || small.W != 240 {
t.Errorf("fit %v, k %d in a small view", small, smallK)
}
}
// Through an unturned camera, the world moves by whole pixels: a tile at
// whole world units has no edge pixel partly covered.
func TestCameraSnaps(t *testing.T) {
img := paint(2, func(p *ui.Painter, r ui.Rect) {
Camera{X: 10.3, Y: 7.77, Zoom: 3}.Draw(p, r, func() {
p.Fill(ui.Rect{X: 0, Y: 0, W: 16, H: 16}, red, 0)
})
}).Image()
bg := img.RGBAAt(799, 599)
reds := 0
for y := range img.Bounds().Dy() {
for x := range img.Bounds().Dx() {
c := img.RGBAAt(x, y)
if isRed(c) {
reds++
} else if c != bg {
t.Fatalf("pixel %d, %d partly covered: %v", x, y, c)
}
}
}
if reds != 96*96 {
t.Errorf("%d red pixels", reds)
}
}
// A modifier on its own is no key of a game's, and is left to the window, as
// Alt to the menu bar.
func TestModifierKeyAlone(t *testing.T) {
l := &loop{in: newInput()}
for _, ev := range []ui.InputEvent{
{Kind: ui.InputKeyDown, Code: ui.CodeShiftLeft, Mods: ui.Shift},
{Kind: ui.InputKeyUp, Code: ui.CodeShiftLeft},
{Kind: ui.InputKeyUp, Code: ui.CodeAltLeft},
} {
if l.input(ev) {
t.Errorf("took %+v", ev)
}
}
if l.in.Down(ui.KeyUnknown) || l.in.Pressed(ui.KeyUnknown) || l.in.Released(ui.KeyUnknown) {
t.Error("a key of no name is held")
}
}
+234
View File
@@ -0,0 +1,234 @@
// Package gamepad reads game controllers: their buttons, triggers and
// sticks in the standard layout of an Xbox controller, which the W3C's
// Gamepad API and SDL's game controller database name, whatever pad it is:
//
// for _, pad := range gamepad.Pads() {
// s := pad.State()
// x, y := s.LeftStick()
// if s.Pressed(gamepad.South) {
// jump()
// }
// }
//
// A game reads the pads' states once a frame, or once a step of its world,
// and keeps the last to tell a button just pressed from one held
// (State.JustPressed).
//
// The pads come from GameController.framework on macOS (Xbox, PlayStation,
// Switch Pro and MFi controllers), XInput on Windows (Xbox controllers and
// those that act as one, as Steam Input makes of others), evdev on Linux
// (/dev/input, readable by the user at the seat), and the Gamepad API in
// browsers. On macOS, input reaches the app in front only, as games
// expect. Every function and method is safe to call from any goroutine.
package gamepad
import (
"math"
"sync"
"time"
)
// Button is a button of the standard layout, named by place: South is A
// on an Xbox controller, Cross on a PlayStation one, B on a Nintendo one.
type Button uint8
// The buttons, in the order of the W3C's standard gamepad.
const (
South Button = iota
East
West
North
LeftShoulder
RightShoulder
LeftTrigger // analog: Value is from 0 to 1
RightTrigger
Back // View, Select, Share, Minus
Start
LeftStickButton
RightStickButton
Up
Down
Left
Right
Guide // the Xbox, PlayStation or Home button, where the system leaves it
ButtonCount
)
// Axis is an axis of the sticks, from -1 to 1: right and down are
// positive, as on the screen.
type Axis uint8
// The axes.
const (
LeftX Axis = iota
LeftY
RightX
RightY
AxisCount
)
// State is what a pad's controls read at one time.
type State struct {
// Buttons are from 0 to 1: 0 or 1 but for the triggers.
Buttons [ButtonCount]float32
// Axes are from -1 to 1, as the pad reports them, without a dead
// zone.
Axes [AxisCount]float32
}
// Deadzone is how far from the middle a stick must move to count, as a
// fraction of its reach: sticks rest a little off their middle.
const Deadzone = 0.15
// pressThreshold is how far an analog trigger must go to be pressed.
const pressThreshold = 0.25
// Value returns how far b is pressed, from 0 to 1.
func (s State) Value(b Button) float32 {
if b >= ButtonCount {
return 0
}
return s.Buttons[b]
}
// Pressed reports whether b is pressed: a trigger a quarter of the way.
func (s State) Pressed(b Button) bool { return s.Value(b) >= pressThreshold }
// JustPressed reports whether b is pressed in s and was not in last, the
// state read before.
func (s State) JustPressed(last State, b Button) bool { return s.Pressed(b) && !last.Pressed(b) }
// JustReleased reports whether b was pressed in last and is not in s.
func (s State) JustReleased(last State, b Button) bool { return !s.Pressed(b) && last.Pressed(b) }
// Axis returns the raw value of a, from -1 to 1.
func (s State) Axis(a Axis) float32 {
if a >= AxisCount {
return 0
}
return s.Axes[a]
}
// LeftStick returns where the left stick is, each coordinate from -1 to 1,
// right and down positive, with a radial dead zone: 0 near the middle,
// then from 0 at Deadzone to 1 at the rim, the same in every direction.
func (s State) LeftStick() (x, y float32) { return stick(s.Axes[LeftX], s.Axes[LeftY]) }
// RightStick returns where the right stick is, as LeftStick.
func (s State) RightStick() (x, y float32) { return stick(s.Axes[RightX], s.Axes[RightY]) }
func stick(x, y float32) (float32, float32) {
m := float32(math.Hypot(float64(x), float64(y)))
if m < Deadzone {
return 0, 0
}
k := min((m-Deadzone)/(1-Deadzone), 1) / m
return x * k, y * k
}
// A Pad is a game controller, from when it connects until it disconnects;
// connected again, it is a Pad anew.
type Pad struct {
dev device
name string
connected bool
}
// Name returns the pad's name, as its maker gives it.
func (p *Pad) Name() string { return p.name }
// Connected reports whether the pad is still connected.
func (p *Pad) Connected() bool {
mu.Lock()
defer mu.Unlock()
return p.connected
}
// State reads the pad's controls now; a pad no longer connected reads
// nothing pressed.
func (p *Pad) State() State {
mu.Lock()
defer mu.Unlock()
if !p.connected {
return State{}
}
var s State
if !p.dev.read(&s) {
p.disconnect()
return State{}
}
return s
}
func (p *Pad) disconnect() {
p.connected = false
p.dev.close()
for i, q := range pads {
if q == p {
pads = append(pads[:i], pads[i+1:]...)
break
}
}
}
// A device is a pad as a platform knows it.
type device interface {
// key identifies the device while it is connected.
key() string
name() string
// read reads the device's controls, and reports false once it is
// gone.
read(s *State) bool
close()
}
var (
mu sync.Mutex
pads []*Pad
scanned time.Time
scanEach = time.Second // how often to look for pads anew
)
// Pads returns the pads connected, in the order they connected. It looks
// for pads connected since at most once a second.
func Pads() []*Pad {
mu.Lock()
defer mu.Unlock()
if now := time.Now(); scanned.IsZero() || now.Sub(scanned) >= scanEach {
scanned = now
known := map[string]device{}
for _, p := range pads {
known[p.dev.key()] = p.dev
}
update(scanDevices(known))
}
return append([]*Pad(nil), pads...)
}
// scanDevices finds the devices connected, the known ones among them as
// they are; tests replace it.
var scanDevices = scan
// update takes the devices a scan found: the pads of devices gone
// disconnect, and new devices connect as pads.
func update(found []device) {
present := map[string]bool{}
for _, d := range found {
present[d.key()] = true
}
for _, p := range append([]*Pad(nil), pads...) {
if !present[p.dev.key()] {
p.disconnect()
}
}
have := map[string]bool{}
for _, p := range pads {
have[p.dev.key()] = true
}
for _, d := range found {
if !have[d.key()] {
have[d.key()] = true
pads = append(pads, &Pad{dev: d, name: d.name(), connected: true})
}
}
}
+195
View File
@@ -0,0 +1,195 @@
//go:build !ios
package gamepad
import (
"runtime"
"strconv"
"sync"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
)
// macOS reads pads through GameController.framework: GCController's
// controllers with an extended gamepad profile, which Xbox, PlayStation,
// Switch Pro and MFi controllers have. The framework finds controllers
// on the main run loop, which a running MyGo app turns.
var (
gcOnce sync.Once
gcOK bool
poolPush, poolPop uintptr
sendFloat func(id objc.ID, sel objc.SEL) float32
selControllers, selCount, selObjectAt, selExtended, selVendor, selUTF8,
selValue, selXAxis, selYAxis, selRetain, selRelease, selResponds objc.SEL
buttonSels [ButtonCount]objc.SEL
selDpad, selLeftStick, selRightStick, selUp, selDown, selLeft, selRight objc.SEL
)
func loadGC() bool {
gcOnce.Do(func() {
if _, err := purego.Dlopen("/System/Library/Frameworks/GameController.framework/GameController", purego.RTLD_LAZY|purego.RTLD_GLOBAL); err != nil {
return
}
libobjc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
return
}
if poolPush, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPush"); err != nil {
return
}
if poolPop, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPop"); err != nil {
return
}
msgSend, err := purego.Dlsym(libobjc, "objc_msgSend")
if err != nil {
return
}
purego.RegisterFunc(&sendFloat, msgSend)
sel := objc.RegisterName
selControllers, selCount, selObjectAt = sel("controllers"), sel("count"), sel("objectAtIndex:")
selExtended, selVendor, selUTF8 = sel("extendedGamepad"), sel("vendorName"), sel("UTF8String")
selValue, selXAxis, selYAxis = sel("value"), sel("xAxis"), sel("yAxis")
selRetain, selRelease, selResponds = sel("retain"), sel("release"), sel("respondsToSelector:")
selDpad, selLeftStick, selRightStick = sel("dpad"), sel("leftThumbstick"), sel("rightThumbstick")
selUp, selDown, selLeft, selRight = sel("up"), sel("down"), sel("left"), sel("right")
for b, name := range map[Button]string{
South: "buttonA", East: "buttonB", West: "buttonX", North: "buttonY",
LeftShoulder: "leftShoulder", RightShoulder: "rightShoulder",
LeftTrigger: "leftTrigger", RightTrigger: "rightTrigger",
Back: "buttonOptions", Start: "buttonMenu", Guide: "buttonHome",
LeftStickButton: "leftThumbstickButton", RightStickButton: "rightThumbstickButton",
} {
buttonSels[b] = sel(name)
}
gcOK = objc.GetClass("GCController") != 0
})
return gcOK
}
// withPool runs fn in an autorelease pool, for the objects the framework
// returns autoreleased. A pool belongs to its thread: the goroutine stays
// on one until the pool is popped.
func withPool(fn func()) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
p, _, _ := purego.SyscallN(poolPush)
defer purego.SyscallN(poolPop, p)
fn()
}
type gcPad struct {
ctl objc.ID // retained
title string
}
func controllers() []objc.ID {
list := objc.ID(objc.GetClass("GCController")).Send(selControllers)
if list == 0 {
return nil
}
n := int(objc.Send[uint](list, selCount))
ids := make([]objc.ID, n)
for i := range n {
ids[i] = list.Send(selObjectAt, uint(i))
}
return ids
}
func scan(known map[string]device) []device {
if !loadGC() {
return nil
}
var found []device
withPool(func() {
for _, c := range controllers() {
if c.Send(selExtended) == 0 {
continue // a remote or a micro gamepad
}
k := strconv.FormatUint(uint64(c), 16)
if d, ok := known[k]; ok {
found = append(found, d)
continue
}
d := &gcPad{ctl: c.Send(selRetain)}
if v := c.Send(selVendor); v != 0 {
d.title = goString(objc.Send[uintptr](v, selUTF8))
}
found = append(found, d)
}
})
return found
}
func goString(p uintptr) string {
if p == 0 {
return ""
}
b := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&p))), 256)
for i, c := range b {
if c == 0 {
return string(b[:i])
}
}
return string(b)
}
func (d *gcPad) key() string { return strconv.FormatUint(uint64(d.ctl), 16) }
func (d *gcPad) name() string { return d.title }
func (d *gcPad) close() { d.ctl.Send(selRelease) }
// gcPresent reports whether a controller is still among the controllers;
// tests replace it.
var gcPresent = func(ctl objc.ID) bool {
for _, c := range controllers() {
if c == ctl {
return true
}
}
return false
}
func value(input objc.ID) float32 {
if input == 0 {
return 0
}
return sendFloat(input, selValue)
}
func (d *gcPad) read(s *State) bool {
ok := false
withPool(func() {
if ok = gcPresent(d.ctl); !ok {
return
}
gp := d.ctl.Send(selExtended)
if gp == 0 {
ok = false
return
}
for b, sel := range buttonSels {
// Older systems have no Home or Options button.
if sel != 0 && objc.Send[bool](gp, selResponds, sel) {
s.Buttons[b] = value(gp.Send(sel))
}
}
if pad := gp.Send(selDpad); pad != 0 {
s.Buttons[Up] = value(pad.Send(selUp))
s.Buttons[Down] = value(pad.Send(selDown))
s.Buttons[Left] = value(pad.Send(selLeft))
s.Buttons[Right] = value(pad.Send(selRight))
}
// GameController's y axes go up.
if st := gp.Send(selLeftStick); st != 0 {
s.Axes[LeftX], s.Axes[LeftY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
}
if st := gp.Send(selRightStick); st != 0 {
s.Axes[RightX], s.Axes[RightY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
}
})
return ok
}
@@ -0,0 +1,53 @@
//go:build !ios
package gamepad
import (
"math"
"testing"
"github.com/ebitengine/purego/objc"
)
// A controller GameController makes for tests, of the extended gamepad
// profile, reads in this package's layout: its y axes turned to go down.
func TestGameController(t *testing.T) {
if !loadGC() {
t.Skip("no GameController.framework")
}
saved := gcPresent
gcPresent = func(objc.ID) bool { return true }
defer func() { gcPresent = saved }()
var d *gcPad
withPool(func() {
c := objc.ID(objc.GetClass("GCController")).Send(objc.RegisterName("controllerWithExtendedGamepad"))
if c == 0 {
return
}
d = &gcPad{ctl: c.Send(selRetain)}
gp := c.Send(selExtended)
setValue := objc.RegisterName("setValue:")
gp.Send(buttonSels[South]).Send(setValue, float32(1))
gp.Send(buttonSels[RightTrigger]).Send(setValue, float32(0.6))
setAxes := objc.RegisterName("setValueForXAxis:yAxis:")
gp.Send(selLeftStick).Send(setAxes, float32(0.5), float32(0.25))
gp.Send(selDpad).Send(setAxes, float32(0), float32(1))
})
if d == nil {
t.Skip("no controllerWithExtendedGamepad")
}
defer d.close()
var s State
if !d.read(&s) {
t.Fatal("read failed")
}
if !s.Pressed(South) || s.Pressed(East) || !s.Pressed(Up) || s.Pressed(Down) {
t.Errorf("buttons %v", s.Buttons)
}
if math.Abs(float64(s.Value(RightTrigger))-0.6) > 1e-3 {
t.Errorf("right trigger %v", s.Value(RightTrigger))
}
if math.Abs(float64(s.Axes[LeftX])-0.5) > 1e-3 || math.Abs(float64(s.Axes[LeftY])+0.25) > 1e-3 {
t.Errorf("left stick %v, %v: y should go down", s.Axes[LeftX], s.Axes[LeftY])
}
}
+73
View File
@@ -0,0 +1,73 @@
package gamepad
import (
"strconv"
"syscall/js"
)
// Browsers report pads through navigator.getGamepads(), each at an index
// for as long as it is connected. Those with the "standard" mapping have
// their buttons and axes in this package's order; others keep the order
// the browser gives, which fits the first buttons and axes of most.
type jsPad struct {
index int
id string
}
func pollPads() js.Value {
nav := js.Global().Get("navigator")
if !nav.Truthy() || !nav.Get("getGamepads").Truthy() {
return js.Undefined()
}
return nav.Call("getGamepads")
}
func scan(known map[string]device) []device {
list := pollPads()
if !list.Truthy() {
return nil
}
var found []device
for i := range list.Length() {
g := list.Index(i)
if !g.Truthy() || !g.Get("connected").Bool() {
continue
}
d := &jsPad{index: i, id: g.Get("id").String()}
if k, ok := known[d.key()]; ok {
found = append(found, k)
continue
}
found = append(found, d)
}
return found
}
func (d *jsPad) key() string { return strconv.Itoa(d.index) + "\x00" + d.id }
func (d *jsPad) name() string { return d.id }
func (d *jsPad) close() {}
func (d *jsPad) read(s *State) bool {
list := pollPads()
if !list.Truthy() || d.index >= list.Length() {
return false
}
g := list.Index(d.index)
if !g.Truthy() || !g.Get("connected").Bool() || g.Get("id").String() != d.id {
return false
}
buttons := g.Get("buttons")
for i := range min(buttons.Length(), int(ButtonCount)) {
b := buttons.Index(i)
s.Buttons[i] = float32(b.Get("value").Float())
if s.Buttons[i] == 0 && b.Get("pressed").Bool() {
s.Buttons[i] = 1 // a browser that reports only pressed
}
}
axes := g.Get("axes")
for i := range min(axes.Length(), int(AxisCount)) {
s.Axes[i] = float32(axes.Index(i).Float())
}
return true
}
+255
View File
@@ -0,0 +1,255 @@
//go:build linux && !android && (amd64 || arm64) && !android
package gamepad
import (
"encoding/binary"
"os"
"path/filepath"
"strings"
"syscall"
"unsafe"
)
// Linux reads pads from evdev, /dev/input/event*, which systemd-logind
// lets the user at the seat read. The kernel's drivers report gamepads in
// one layout (Documentation/input/gamepad.rst): BTN_SOUTH and the rest by
// place, sticks on ABS_X/Y and ABS_RX/RY, triggers on ABS_Z/RZ, the
// d-pad on a hat or buttons. Xbox controllers (xpad, and Steam's virtual
// pad) are the exception that predates it: they report X as BTN_X, the
// code of BTN_NORTH, and Y as BTN_Y, that of BTN_WEST.
// Event types and codes.
const (
evKey = 0x01
evAbs = 0x03
btnSouth = 0x130
btnEast = 0x131
btnNorth = 0x133 // also BTN_X
btnWest = 0x134 // also BTN_Y
btnTL = 0x136
btnTR = 0x137
btnTL2 = 0x138
btnTR2 = 0x139
btnSelect = 0x13a
btnStart = 0x13b
btnMode = 0x13c
btnThumbL = 0x13d
btnThumbR = 0x13e
btnUp = 0x220
btnDown = 0x221
btnLeft = 0x222
btnRight = 0x223
absX = 0x00
absY = 0x01
absZ = 0x02
absRX = 0x03
absRY = 0x04
absRZ = 0x05
absHat0X = 0x10
absHat0Y = 0x11
absMax = 0x3f
keyMax = 0x2ff
)
// ioctl requests of evdev: _IOC(dir, 'E', nr, size).
func ioc(dir, nr, size uintptr) uintptr { return dir<<30 | size<<16 | 'E'<<8 | nr }
const iocRead = 2
func eviocgname(n uintptr) uintptr { return ioc(iocRead, 0x06, n) }
func eviocgbit(ev, n uintptr) uintptr { return ioc(iocRead, 0x20+ev, n) }
func eviocgabs(abs uintptr) uintptr { return ioc(iocRead, 0x40+abs, unsafe.Sizeof(absInfo{})) }
func eviocgkey(n uintptr) uintptr { return ioc(iocRead, 0x18, n) }
func eviocgid() uintptr { return ioc(iocRead, 0x02, unsafe.Sizeof(inputID{})) }
func ioctl(fd int, req uintptr, p unsafe.Pointer) bool {
_, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(p))
return e == 0
}
type absInfo struct{ value, minimum, maximum, fuzz, flat, resolution int32 }
type inputID struct{ bustype, vendor, product, version uint16 }
type evdevPad struct {
path string
fd int
title string
xbox bool // BTN_X and BTN_Y are X and Y, west and north
// rightOnZ: a pad of no ABS_RX has its right stick on ABS_Z/RZ, and
// triggers only as buttons.
rightOnZ bool
abs [absMax + 1]absInfo
hasAbs [absMax + 1]bool
keys [keyMax + 1]bool
axes [absMax + 1]int32
buf []byte
}
func scan(known map[string]device) []device {
paths, _ := filepath.Glob("/dev/input/event*")
var found []device
for _, p := range paths {
if k, ok := known[p]; ok {
found = append(found, k)
continue
}
if d := openEvdev(p); d != nil {
found = append(found, d)
}
}
return found
}
func bit(b []byte, i int) bool { return i/8 < len(b) && b[i/8]&(1<<(i%8)) != 0 }
// openEvdev opens the device at path if it is a gamepad.
func openEvdev(path string) *evdevPad {
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
if err != nil {
return nil
}
keys := make([]byte, keyMax/8+1)
if !ioctl(fd, eviocgbit(evKey, uintptr(len(keys))), unsafe.Pointer(&keys[0])) || !bit(keys, btnSouth) {
syscall.Close(fd)
return nil
}
d := &evdevPad{path: path, fd: fd, buf: make([]byte, 24*64)}
name := make([]byte, 256)
if ioctl(fd, eviocgname(uintptr(len(name))), unsafe.Pointer(&name[0])) {
d.title = strings.TrimRight(string(name), "\x00")
}
var id inputID
ioctl(fd, eviocgid(), unsafe.Pointer(&id))
d.xbox = id.vendor == 0x045e || id.vendor == 0x28de || driver(path) == "xpad"
abs := make([]byte, absMax/8+1)
ioctl(fd, eviocgbit(evAbs, uintptr(len(abs))), unsafe.Pointer(&abs[0]))
for a := range absMax + 1 {
if bit(abs, a) && ioctl(fd, eviocgabs(uintptr(a)), unsafe.Pointer(&d.abs[a])) {
d.hasAbs[a] = true
d.axes[a] = d.abs[a].value
}
}
d.rightOnZ = !d.hasAbs[absRX] && d.hasAbs[absZ]
state := make([]byte, keyMax/8+1)
if ioctl(fd, eviocgkey(uintptr(len(state))), unsafe.Pointer(&state[0])) {
for k := range keyMax + 1 {
d.keys[k] = bit(state, k)
}
}
return d
}
// driver returns the name of the kernel driver of an evdev device.
func driver(path string) string {
link, err := os.Readlink("/sys/class/input/" + filepath.Base(path) + "/device/device/driver")
if err != nil {
return ""
}
return filepath.Base(link)
}
func (d *evdevPad) key() string { return d.path }
func (d *evdevPad) name() string { return d.title }
func (d *evdevPad) close() { syscall.Close(d.fd) }
// drain reads the events waiting, and reports false once the device is
// gone.
func (d *evdevPad) drain() bool {
for {
n, err := syscall.Read(d.fd, d.buf)
if err == syscall.EAGAIN || err == syscall.EINTR {
return true
}
if err != nil || n == 0 {
return false // ENODEV: unplugged
}
for i := 0; i+24 <= n; i += 24 {
e := d.buf[i:]
typ := binary.LittleEndian.Uint16(e[16:])
code := binary.LittleEndian.Uint16(e[18:])
value := int32(binary.LittleEndian.Uint32(e[20:]))
switch {
case typ == evKey && int(code) <= keyMax:
d.keys[code] = value != 0
case typ == evAbs && int(code) <= absMax:
d.axes[code] = value
}
}
if n < len(d.buf) {
return true
}
}
}
// norm maps axis a to -1..1, or 0..1 when half.
func (d *evdevPad) norm(a int, half bool) float32 {
if !d.hasAbs[a] {
return 0
}
lo, hi := float32(d.abs[a].minimum), float32(d.abs[a].maximum)
if hi <= lo {
return 0
}
t := (float32(d.axes[a]) - lo) / (hi - lo)
if half {
return min(max(t, 0), 1)
}
return min(max(t*2-1, -1), 1)
}
func (d *evdevPad) read(s *State) bool {
if !d.drain() {
return false
}
press := func(b Button, code int) {
if d.keys[code] {
s.Buttons[b] = 1
}
}
press(South, btnSouth)
press(East, btnEast)
if d.xbox {
press(West, btnNorth)
press(North, btnWest)
} else {
press(North, btnNorth)
press(West, btnWest)
}
press(LeftShoulder, btnTL)
press(RightShoulder, btnTR)
press(Back, btnSelect)
press(Start, btnStart)
press(Guide, btnMode)
press(LeftStickButton, btnThumbL)
press(RightStickButton, btnThumbR)
press(Up, btnUp)
press(Down, btnDown)
press(Left, btnLeft)
press(Right, btnRight)
if d.hasAbs[absHat0X] {
if v := d.axes[absHat0X]; v < 0 {
s.Buttons[Left] = 1
} else if v > 0 {
s.Buttons[Right] = 1
}
if v := d.axes[absHat0Y]; v < 0 {
s.Buttons[Up] = 1
} else if v > 0 {
s.Buttons[Down] = 1
}
}
s.Axes[LeftX], s.Axes[LeftY] = d.norm(absX, false), d.norm(absY, false)
if d.rightOnZ {
s.Axes[RightX], s.Axes[RightY] = d.norm(absZ, false), d.norm(absRZ, false)
} else {
s.Axes[RightX], s.Axes[RightY] = d.norm(absRX, false), d.norm(absRY, false)
s.Buttons[LeftTrigger] = d.norm(absZ, true)
s.Buttons[RightTrigger] = d.norm(absRZ, true)
}
press(LeftTrigger, btnTL2)
press(RightTrigger, btnTR2)
return true
}
@@ -0,0 +1,139 @@
//go:build linux && !android && (amd64 || arm64) && !android
package gamepad
import (
"encoding/binary"
"os"
"syscall"
"testing"
"time"
"unsafe"
"github.com/egoist/mygo/internal/wait"
)
// uinput makes virtual input devices.
const (
uiDevCreate = 1<<0 | 'U'<<8 | 1 // _IO('U', 1)
uiDevDestroy = 'U'<<8 | 2
uiSetEvBit = 1<<30 | 4<<16 | 'U'<<8 | 100
uiSetKeyBit = 1<<30 | 4<<16 | 'U'<<8 | 101
uiSetAbsBit = 1<<30 | 4<<16 | 'U'<<8 | 103
)
type uinputSetup struct {
id inputID
name [80]byte
ff uint32
}
type uinputAbsSetup struct {
code uint16
_ uint16
info absInfo
}
func uiDevSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputSetup{})<<16 | 'U'<<8 | 3 }
func uiAbsSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputAbsSetup{})<<16 | 'U'<<8 | 4 }
// A virtual pad, made with uinput, reads as the kernel's drivers report
// pads: its buttons by place, sticks, triggers and hat. It needs
// /dev/uinput and /dev/input, as in the Linux test container
// (MYGO_UINPUT=1).
func TestEvdev(t *testing.T) {
if os.Getenv("MYGO_UINPUT") == "" {
t.Skip("MYGO_UINPUT not set")
}
// A DualSense reports its left button, Square, as BTN_WEST; an Xbox
// controller its left one, X, as BTN_X, BTN_NORTH's code.
t.Run("PlayStation", func(t *testing.T) { testEvdev(t, 0x054c, btnWest) })
t.Run("Xbox", func(t *testing.T) { testEvdev(t, 0x045e, btnNorth) })
}
func testEvdev(t *testing.T, vendor uint16, west uint16) {
fd, err := syscall.Open("/dev/uinput", syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
if err != nil {
t.Skip(err)
}
defer syscall.Close(fd)
set := func(req uintptr, v int) {
if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(v)); e != 0 {
t.Fatalf("ioctl %#x %d: %v", req, v, e)
}
}
set(uiSetEvBit, evKey)
set(uiSetEvBit, evAbs)
for _, k := range []int{btnSouth, btnEast, btnNorth, btnWest, btnTL, btnTR, btnSelect, btnStart, btnMode, btnThumbL, btnThumbR} {
set(uiSetKeyBit, k)
}
axes := map[uint16]absInfo{
absX: {minimum: -32768, maximum: 32767}, absY: {minimum: -32768, maximum: 32767},
absRX: {minimum: -32768, maximum: 32767}, absRY: {minimum: -32768, maximum: 32767},
absZ: {maximum: 255}, absRZ: {maximum: 255},
absHat0X: {minimum: -1, maximum: 1}, absHat0Y: {minimum: -1, maximum: 1},
}
for code, info := range axes {
set(uiSetAbsBit, int(code))
s := uinputAbsSetup{code: code, info: info}
if !ioctl(fd, uiAbsSetup(), unsafe.Pointer(&s)) {
t.Fatal("UI_ABS_SETUP")
}
}
setup := uinputSetup{id: inputID{bustype: 3, vendor: vendor, product: 0x0ce6}}
copy(setup.name[:], "Virtual Pad")
if !ioctl(fd, uiDevSetup(), unsafe.Pointer(&setup)) {
t.Fatal("UI_DEV_SETUP")
}
set(uiDevCreate, 0)
// Destroyed by the test, unless it fails first.
defer syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uiDevDestroy, 0)
var pad *Pad
wait.Until(t, "the virtual pad", func() bool {
scanned = time.Time{}
for _, p := range Pads() {
if p.Name() == "Virtual Pad" {
pad = p
}
}
return pad != nil
})
emit := func(typ, code uint16, value int32) {
var e [24]byte
binary.LittleEndian.PutUint16(e[16:], typ)
binary.LittleEndian.PutUint16(e[18:], code)
binary.LittleEndian.PutUint32(e[20:], uint32(value))
if _, err := syscall.Write(fd, e[:]); err != nil {
t.Fatal(err)
}
}
emit(evKey, btnSouth, 1)
emit(evKey, west, 1)
emit(evAbs, absX, 32767)
emit(evAbs, absRY, -32768)
emit(evAbs, absRZ, 255)
emit(evAbs, absHat0Y, -1)
emit(0, 0, 0) // SYN_REPORT
// State drains what the kernel passed on so far: wait until it has.
wait.Until(t, "the report read", func() bool { return pad.State().Axes[LeftX] >= 0.99 })
s := pad.State()
for _, b := range []Button{South, West, RightTrigger, Up} {
if !s.Pressed(b) {
t.Errorf("button %d not pressed: %v", b, s.Buttons)
}
}
for _, b := range []Button{East, North, LeftTrigger, Down} {
if s.Pressed(b) {
t.Errorf("button %d pressed: %v", b, s.Buttons)
}
}
if s.Axes[LeftX] < 0.99 || s.Axes[RightY] > -0.99 || s.Axes[LeftY] < -0.01 || s.Axes[LeftY] > 0.01 {
t.Errorf("axes %v", s.Axes)
}
emit(evKey, btnSouth, 0)
emit(0, 0, 0)
wait.Until(t, "South released", func() bool { return !pad.State().Pressed(South) })
set(uiDevDestroy, 0)
wait.Until(t, "the pad disconnected once destroyed", func() bool { pad.State(); return !pad.Connected() })
}
@@ -0,0 +1,5 @@
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js
package gamepad
func scan(known map[string]device) []device { return nil }
+96
View File
@@ -0,0 +1,96 @@
package gamepad
import (
"math"
"testing"
)
// fakeDevice is a pad whose state a test sets.
type fakeDevice struct {
id string
state State
gone bool
closed bool
}
func (d *fakeDevice) key() string { return d.id }
func (d *fakeDevice) name() string { return "Fake " + d.id }
func (d *fakeDevice) close() { d.closed = true }
func (d *fakeDevice) read(s *State) bool {
*s = d.state
return !d.gone
}
// withDevices has scans find devs, which a test changes.
func withDevices(t *testing.T, devs *[]device) {
t.Helper()
saved, savedEach := scanDevices, scanEach
scanDevices = func(known map[string]device) []device { return *devs }
scanEach = 0
mu.Lock()
pads, scanned = nil, scanned.AddDate(-1, 0, 0)
mu.Unlock()
t.Cleanup(func() {
scanDevices, scanEach = saved, savedEach
mu.Lock()
pads = nil
mu.Unlock()
})
}
func TestPadsConnectAndDisconnect(t *testing.T) {
a, b := &fakeDevice{id: "a"}, &fakeDevice{id: "b"}
devs := []device{a}
withDevices(t, &devs)
ps := Pads()
if len(ps) != 1 || ps[0].Name() != "Fake a" || !ps[0].Connected() {
t.Fatalf("pads %v", ps)
}
first := ps[0]
devs = []device{b, a}
ps = Pads()
if len(ps) != 2 || ps[0] != first || ps[1].Name() != "Fake b" {
t.Fatalf("pads in connecting order: %v", ps)
}
// Unplugged between scans: reading finds it gone.
a.gone = true
a.state.Buttons[South] = 1
if first.State().Pressed(South) || first.Connected() || !a.closed {
t.Error("a pad gone still reads, or is not closed")
}
// Gone from a scan.
devs = nil
if ps = Pads(); len(ps) != 0 {
t.Errorf("pads after unplugging: %v", ps)
}
}
func TestState(t *testing.T) {
var last, s State
s.Buttons[South] = 1
s.Buttons[LeftTrigger] = 0.2
s.Buttons[RightTrigger] = 0.3
if !s.Pressed(South) || s.Pressed(LeftTrigger) || !s.Pressed(RightTrigger) {
t.Error("Pressed")
}
if !s.JustPressed(last, South) || s.JustPressed(s, South) || !last.JustReleased(s, South) {
t.Error("JustPressed, JustReleased")
}
// Within the dead zone, nothing; at the rim, all the way, in every
// direction alike.
s.Axes[LeftX], s.Axes[LeftY] = 0.1, 0.05
if x, y := s.LeftStick(); x != 0 || y != 0 {
t.Errorf("rest = %v, %v", x, y)
}
s.Axes[LeftX], s.Axes[LeftY] = 0.7071, 0.7071
if x, y := s.LeftStick(); math.Abs(math.Hypot(float64(x), float64(y))-1) > 1e-3 {
t.Errorf("diagonal rim = %v, %v", x, y)
}
s.Axes[RightX] = -(Deadzone + (1-Deadzone)/2)
if x, _ := s.RightStick(); math.Abs(float64(x)+0.5) > 1e-4 {
t.Errorf("half way past the dead zone = %v", x)
}
if s.Value(ButtonCount) != 0 || s.Axis(AxisCount) != 0 {
t.Error("out of range")
}
}
+143
View File
@@ -0,0 +1,143 @@
//go:build windows && (amd64 || arm64)
package gamepad
import (
"strconv"
"sync"
"syscall"
"unsafe"
)
// Windows reads pads through XInput, which has four slots, for Xbox
// controllers and those that act as one. XInputGetStateEx, exported by
// ordinal 100, reads the Guide button too.
type xinputGamepad struct {
buttons uint16
leftTrigger uint8
rightTrigger uint8
thumbLX int16
thumbLY int16
thumbRX int16
thumbRY int16
}
type xinputState struct {
packet uint32
gamepad xinputGamepad
}
const (
errorSuccess = 0
xinputSlots = 4
xinputDpadUp = 0x0001
xinputDpadDown = 0x0002
xinputDpadLeft = 0x0004
xinputDpadRight = 0x0008
xinputStart = 0x0010
xinputBack = 0x0020
xinputLeftThumb = 0x0040
xinputRightThumb = 0x0080
xinputLeftShoulder = 0x0100
xinputRightShoulder = 0x0200
xinputGuide = 0x0400
xinputA = 0x1000
xinputB = 0x2000
xinputX = 0x4000
xinputY = 0x8000
)
var (
xinputOnce sync.Once
xinputGetState uintptr
)
func loadXInput() {
xinputOnce.Do(func() {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
getProc := kernel32.NewProc("GetProcAddress")
for _, name := range []string{"xinput1_4.dll", "xinput1_3.dll", "xinput9_1_0.dll"} {
lib, err := syscall.LoadLibrary(name)
if err != nil {
continue
}
// XInputGetStateEx, by ordinal, where there is one.
if p, _, _ := getProc.Call(uintptr(lib), 100); p != 0 {
xinputGetState = p
return
}
if p, err := syscall.GetProcAddress(lib, "XInputGetState"); err == nil {
xinputGetState = p
return
}
}
})
}
func getState(slot int, s *xinputState) bool {
r, _, _ := syscall.SyscallN(xinputGetState, uintptr(slot), uintptr(unsafe.Pointer(s)))
return r == errorSuccess
}
type xinputPad struct{ slot int }
func scan(known map[string]device) []device {
loadXInput()
if xinputGetState == 0 {
return nil
}
var found []device
for slot := range xinputSlots {
d := &xinputPad{slot}
if k, ok := known[d.key()]; ok {
// Read as it is used; a slot that empties disconnects there.
found = append(found, k)
continue
}
// Asking an empty slot is slow, which is why scans are rare.
var st xinputState
if getState(slot, &st) {
found = append(found, d)
}
}
return found
}
func (d *xinputPad) key() string { return "xinput" + strconv.Itoa(d.slot) }
func (d *xinputPad) name() string { return "Xbox Controller " + strconv.Itoa(d.slot+1) }
func (d *xinputPad) close() {}
func (d *xinputPad) read(s *State) bool {
var st xinputState
if !getState(d.slot, &st) {
return false
}
g := st.gamepad
bits := [...]struct {
b Button
mask uint16
}{
{South, xinputA}, {East, xinputB}, {West, xinputX}, {North, xinputY},
{LeftShoulder, xinputLeftShoulder}, {RightShoulder, xinputRightShoulder},
{Back, xinputBack}, {Start, xinputStart},
{LeftStickButton, xinputLeftThumb}, {RightStickButton, xinputRightThumb},
{Up, xinputDpadUp}, {Down, xinputDpadDown}, {Left, xinputDpadLeft}, {Right, xinputDpadRight},
{Guide, xinputGuide},
}
for _, b := range bits {
if g.buttons&b.mask != 0 {
s.Buttons[b.b] = 1
}
}
s.Buttons[LeftTrigger] = float32(g.leftTrigger) / 255
s.Buttons[RightTrigger] = float32(g.rightTrigger) / 255
// XInput's y axes go up.
s.Axes[LeftX] = thumb(g.thumbLX)
s.Axes[LeftY] = -thumb(g.thumbLY)
s.Axes[RightX] = thumb(g.thumbRX)
s.Axes[RightY] = -thumb(g.thumbRY)
return true
}
func thumb(v int16) float32 { return max(float32(v)/32767, -1) }