Skip to content

Gamepad Support #18445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

ShadowMarker789
Copy link
Contributor

Pull Request is still in progress and this should be considered a draft.

Things I want clarification on

  1. Button Names

    • I don't know what to call these button names. They have been tentatively named Button0 through Button15 but this is probably not what we want to ship. Each controller vendor seems to have different names for them. As a suggestion, would there be any objections to using the GameMaker Names ? The W3C specification specifically avoids giving names to the buttons.
      image
  2. What should the Capture API look like? We want to provide a robust way to enable background processing of Controller updates and events even when the UIThread dispatcher is being held up.

Gamepads

I am restricting this to specifically Controllers and Gamepads. They don't have to conform exactly to the Standard Gamepad gamepad but I am narrowing the scope of this to make it saner to implement - supporting literally every device under the sun on all of the platforms would be too grand of an undertaking for me.

To-do list

  • Windows Implementation
    • Works with XInput devices so far, need to work on RawInput for PS and other controller styles. (I do not own any controllers to test with)
  • Linux Implementation via libudev (No work done yet)
  • MacOS and iOS implementation
    • If the apple documentation is to believed it is the same API for both platforms.
  • Android Implementation
  • Web implementation
  • XY Navigation Support
    • A way to "Handle" these events to override navigation behaviours
    • A way to disable navigation behaviours from the gamepad
  • Bindings (As in, which button does what)
    • Use internally a variant of the SDL Gamepad Database for sane default mapping
    • An API to adjust the mapping for each device independently
  • Documentation
  • Control Catalogue Sample
    • I also want to add a small game there, multi-player, either split-screen or single-shared-screen to show off the API capabilities.
  • Sign off on Avalonia Team
    • API Surface
    • How UI Elements should interact with Gamepad events (Should these events be routed?)
    • Sign off on approach

Tentative Requirements

(Partially elicited through conversations with various Avalonia team members)

  • The system must provide a robust way of processing known events in the sequential manner without losing any information
    • Stick trajectory must be preserved
    • Button presses must not be "Skipped" if the Dispatcher thread is sleeping or otherwise occupied.
  • The system must provide automatic sane default mapping of common controllers such as the Playstation and Switch controllers
  • The system must provide an API to change the aforementioned mapping
  • The system must provide a way to cancel event-processing if the event was handled by the UI
  • The system must provide a way to pre-process controller events before they reach the UI
  • The system must provide a robust way of getting real-time background-thread readings from the controller even if the UI Thread Dispatcher is currently blocked or otherwise occupied
  • The system must provide both human-readable and machine-identifying names and IDs of gamepads
  • The system must provide the Timestamp of when events were triggered

What does the pull request do?

This pull request adds Gamepad support for AvaloniaUI.

What is the current behavior?

There is no gamepad support.

What is the updated/expected behavior with this PR?

  • Adding a new tab to the Control Catalogue to demonstrate and test the APIs.
  • Adds a new API for receiving and reacting to gamepad events.

How was the solution implemented (if it's not obvious)?

Creating an Interface IGamepadManager and abstract class GamepadManager to manage gamepads.

The entry-point to getting Gamepad events is GamepadManager.Instance which is nullable and returns null if the current platform does not support gamepads (e.g.: Headless)

An implementation of this per-platform, since each major platform has its own quirks and particularities for Gamepads.

Using only managed C# code interface with the system level APIs at a low-level.

For Windows, one must dual-wield RawInput HID and XInput for full support. This appears to be the best way to have broad-scale support ranging from Windows 7 to Windows 11 without losing support for any particular kind of device. WGI (Windows.Gaming.Input) doesn't function when the window is out-of-focus, and would put requirements on the version of windows if we wanted to integrate with it. GameInput is not yet production ready in my opinion, it's still part of the GDK and not subsumed into the Windows SDK and it looks like the license for GameInput.h isn't friendly to OSS which is problematic, and GameInput has bugs in it and doesn't work with bluetooth controllers. DirectInput is feasible but more complex to use for C# compared with RawInput, so RawInput it is.

For Linux libudev will be used

For Android, there's probably a similar low-level API, needs research and impl.

For Apple MacOS and iOS [iOS 7.0+ iPadOS 7.0+ Mac Catalyst 13.1+ macOS 10.9+ tvOS 9.0+ visionOS 1.0+], https://developer.apple.com/documentation/gamecontroller?language=objc

For Web, there's the w3c gamepad API https://w3c.github.io/gamepad

Checklist

Breaking changes

None

Obsoletions / Deprecations

None

Fixed issues

Satisfies #6945

@ShadowMarker789 ShadowMarker789 marked this pull request as draft March 15, 2025 04:33
@avaloniaui-bot
Copy link

You can test this PR using the following package version. 11.3.999-cibuild0055559-alpha. (feed url: https://nuget-feed-all.avaloniaui.net/v3/index.json) [PRBUILDID]

@cla-avalonia
Copy link
Collaborator

cla-avalonia commented Mar 15, 2025

@ShadowMarker789,

Please read the following Contributor License Agreement (CLA). If you agree with the CLA, please reply with the following:

@cla-avalonia agree
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the AvaloniaUI OÜ ( “AvaloniaUI OÜ” ) for Your contributions to
AvaloniaUI OÜ open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to AvaloniaUI OÜ under this Agreement.

“Project” means any of the projects owned or managed by AvaloniaUI OÜ and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant AvaloniaUI OÜ, and those who receive the Submission directly
or indirectly from AvaloniaUI OÜ, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant AvaloniaUI OÜ, and those who receive the Submission directly or
indirectly from AvaloniaUI OÜ, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to AvaloniaUI OÜ. You agree to notify AvaloniaUI OÜ in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the Republic of Estonia, and
the parties consent to exclusive jurisdiction and venue in the courts sitting in Talinn,
Estonia. The parties waive all defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by AvaloniaUI OÜ.

AvaloniaUI OÜ dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

@thevortexcloud
Copy link
Contributor

I don't know what to call these button names.

Depending on how much you feel like over engineering/abstracting things, you could possibly not name them at all. Steam Input for example gets games to register actions rather than specific buttons. Then it works out how to trigger those actions based on specific controllers/buttons. That way no game has to worry about specific buttons, and Valve can also deal with each controller type individually if they need to (even if it's some very unique controller with non traditional buttons/layouts).

https://partner.steamgames.com/doc/features/steam_controller/concepts

Obviously you would still need a way to define the mapping somewhere.

@ShadowMarker789
Copy link
Contributor Author

I don't know what to call these button names.

Depending on how much you feel like over engineering/abstracting things, you could possibly not name them at all. Steam Input for example gets games to register actions rather than specific buttons. Then it works out how to trigger those actions based on specific controllers/buttons. That way no game has to worry about specific buttons, and Valve can also deal with each controller type individually if they need to (even if it's some very unique controller with non traditional buttons/layouts).

https://partner.steamgames.com/doc/features/steam_controller/concepts

Obviously you would still need a way to define the mapping somewhere.

I'm not convinced it would make sense for Avalonia itself as a library to provide a set of actions as actions are in the domain of the application/game itself. It wouldn't be up for us to decide the set of actions, that would be something the application developer would or could build atop of what we provide.

As fun as it is to overengineer, I think if we want to deliver this, perhaps a dash of simplicity to taste would be what's called for instead.

@thevortexcloud
Copy link
Contributor

I'm not convinced it would make sense for Avalonia itself as a library to provide a set of actions as actions are in the domain of the application/game itself

Valve does this. The game defines the action name (and therefore what it does) via a config file (which also specifies the expected type of input, such as digital or analogue). Games can also provide a default binding for common controllers. Users can also override the bindings transparently to the game (since the game only cares about the actions). I will admit though, Valve's approach is also fairly complex since it also allows for context aware bindings (EG different controls for when in a game menu compared to the actual game). But that's probably not needed here.

I personally would want to move away from specific key events anyway in most cases. I know it's a legacy approach from WPF, but it does not change the fact that it makes developers make (often bad) assumptions about input devices. EG not everybody uses QWERTY keyboards, nor do they use controllers that have analogue triggers. What might be a sensible binding for one person will be awful for someone else. I have seen some game engines in recent years actually refuse to directly expose raw input events for that exact reason.

@TomEdwardsEnscape
Copy link
Contributor

TomEdwardsEnscape commented Mar 15, 2025

Nice work so far. Some thought about the intended uses of gamepad input is required before further steps are taken.

Discussions in the feature request suggest that this feature is constrained to providing input for an event-driven GUI, not a real-time simulation/game. But in this PR you have a goal of creating "a small game". I'd advise against this, as piping real-time input through a windowing event loop will never work properly. Avalonia's rendering and input processing models will fight against you. If you want real-time, run a frame loop, poll for input within it, and draw directly on the GPU.

There are more substantial issues beyond this. A huge challenge is that with a mouse we know what the user wants to interact with because they are pointing at it. But a gamepad steers instead of points, and there are many different ways to interpret steering.

  1. In this comment we hear how @Sewer56 has implemented physical navigation, where the pixel bounds of each control decide where focus moves when the user presses up/down/left/right.
  2. Another paradigm is logical navigation, where NavigationDirection values are passed to code which understands the layout of the UI. This allows a control to capture navigation within its bounds or direct it away as it sees fit.
  3. Yet another paradigm is emulation of a pointer. This is popular in game menus these days, and here is one example from Ubisoft. Pointer emulation requires real-time processing of gamepad input. But it gets more complicated than that: what you can't easily see from the video I just linked to is that the pointer is "sticky" and moves slower while over an interactive element. So the real-time gamepad input processor has knowledge of the UI layout, while also defining part of that layout (the pointer position) in a bi-directional dependency.

Add to this the existing discussions about how gamepad layouts are different, and about how different cultures interpret input of the exact same gamepad differently (Japan's A/B & O/X switch). The conclusion I draw is that it's reasonable to expose a stream of button presses on the gamepad, but nowhere near enough. There is still a tonne of design and implementation work before those events can be turned into UI interactions.

Do we want to put that on the plate of the Avalonia consumer? I don't think so. I would like to see gamepad input support in Avalonia extend all the way to actually navigating through a live UI. My recommendation is designing public APIs which expose all the necessary information to implement at least the three paradigms above, and then implementing them as a drop-in component for a TopLevel. The job of each implementation is to entirely encapsulate gamepad input and turn it into semantic Avalonia events raised on specific objects in the visual/logical tree.

@thevortexcloud
Copy link
Contributor

thevortexcloud commented Mar 15, 2025

Yet another paradigm is emulation of a pointer.

I will also add to this: There are several ways to emulate a mouse pointer with different input sources and you can't really assume a single way is the "best way". EG Steam Controllers have touch pads on them which can be mapped directly to mouse movement. Xbox controllers however have joysticks, and NES controllers have neither. Each of those would need completely differently logic. Although I am not sure if direct pointer emulation should be the goal here (at that point you may as well just write a platform specific userspace mouse driver and not touch Avalonia's code at all).

@thevortexcloud
Copy link
Contributor

thevortexcloud commented Mar 16, 2025

Another thing: SDL 3 uses these names for buttons:

https://wiki.libsdl.org/SDL3/SDL_GamepadButton

All buttons can also be rebound by the user via a config file (specified via an environment variable), or a developer by code.

https://wiki.libsdl.org/SDL3/SDL_AddGamepadMapping
https://wiki.libsdl.org/SDL3/SDL_AddGamepadMappingsFromFile
https://wiki.libsdl.org/SDL3/SDL_HINT_GAMECONTROLLERCONFIG
https://wiki.libsdl.org/SDL3/SDL_HINT_GAMECONTROLLERCONFIG_FILE

Which is also probably a somewhat reasonable compromise if the "action" approach is too complicated. This also has the advantage of allowing new controllers to be supported without having to update the app. But I am still not a fan of it assuming a finite set of buttons exist.

@ShadowMarker789
Copy link
Contributor Author

But in this PR you have a goal of creating "a small game". I'd advise against this, as piping real-time input through a windowing event loop will never work properly. Avalonia's rendering and input processing models will fight against you. If you want real-time, run a frame loop, poll for input within it, and draw directly on the GPU.

I did mean a sample in the control catalogue to "show off" the feature. I'd have to actually create a GameObject and "play around with it" to determine if the rendering and input processing you mention would fight against me so.

@@ -1782,6 +1783,80 @@ public enum LayeredWindowFlags

[DllImport("user32.dll")]
public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, LayeredWindowFlags dwFlags);
[DllImport("user32", ExactSpelling = true)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use CsWin32 for new interop methods and NativeMethods.txt?
We slowly migrate out from hand-written pinvokes.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use CsWin32 for new interop methods and NativeMethods.txt? We slowly migrate out from hand-written pinvokes.

I should be able to, but that won't handle when XInput v 1.4 isn't available for a fallback to XInput v 9.1.0

That's still the recommended way to handle XInput if you're not shipping your own native binaries or statically linking your specific version of XInput.

For XInput specifically, these hand-written invocations might need to remain, but the actual structs themselves were copied from source-generated output of another open-source project (TerraFX.Interop.Windows)

I ran my approach for LoadLibrary xinput1_4.dll, if that fails fallback to xinput9_1_0.dll - the layout and size of the structs are the same across all versions and this approach will succeed in all versions of windows dating back to Windows XP without code modifications.

/// <summary>
/// The static entry-point to interacting with Gamepads. This is null if the current platform does not have a Gamepad implementation.
/// </summary>
public static GamepadManager? Instance { get; protected set; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally should be a TopLevel bound API instead of global statics.

Copy link
Member

@maxkatz6 maxkatz6 Mar 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which is actually similar to window.Gamepad essentially on browser

});
}

public IObservable<GamepadEventArgs> GamepadStream => _gamepadStream;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, is it supposed to be routed event API or observable API?
We will need to discuss this API on the API review later. But I am just asking early questions.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, is it supposed to be routed event API or observable API? We will need to discuss this API on the API review later. But I am just asking early questions.

Yeah, I am being pulled in both directions - the Observable API is great for streaming these events, but if we want them to route on the UI layer, they would need to be routable events.

I am considering splitting these two up, with an IObservable that doesn't get routed, and if not "handled" at this level, producing routed-events from these - in line with what TomEdwards was saying above - turning these "raw" gamepad events into Semantic Avalonia events that can work with a UI.

}

public IObservable<GamepadEventArgs> GamepadStream => _gamepadStream;
public IReadOnlyList<GamepadState> GetSnapshot() => [.. _currentState];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GetSnapshot doesn't seem to add any value here, as it only reads last already recorded state. Without requesting current value from the system directly (so, similarly to how we don't have unreliable global mouse state in Avalonia).

Value == state.Value;
}

public readonly override int GetHashCode()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make it a record struct?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great suggestion! Taken and implemented.

// this struct is a glorified fixed-buffer and these "unused fields" will be used.
public struct GamepadButtons
{
private ButtonState _0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, we can use actual fixed-buffer structs on netstandard.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe, but we don't have MemoryMarshal.CreateSpan(T, Int32) in .Net Standard 2.0

So I would still need to venture off the happy-path for spans to keep NS2.0 compatibility. :(

@maxkatz6 maxkatz6 added feature os-windows needs-api-review The PR adds new public APIs that should be reviewed. labels Mar 16, 2025
@avaloniaui-bot
Copy link

You can test this PR using the following package version. 11.3.999-cibuild0055579-alpha. (feed url: https://nuget-feed-all.avaloniaui.net/v3/index.json) [PRBUILDID]

@ShadowMarker789
Copy link
Contributor Author

In an initial quick test for input latency, I used the following setup

OBS Recording my microphone near the controller, and Window Capture (via Windows 10 Composition Capture).

Splitting the recorded file into audio and video frames, doing some analysis.

I can look at the audio stream for when my controller clicked, and I can look at the video frames to see when the entity actually moved and was rendered.

The click was observed at 0.465 seconds into the footage, but the movement was seen on a frame at 0.467 seconds... there's probably a delay from the USB microphone, so it's coming in at maybe a frame or so of latency.

It reacts really quickly, and I don't have any good ways of measuring input latency when you're using a separate render-thread. Forcing it into a single thread and using DXGI, it feels really responsive, more responsive than some of the games I've played.

@emmauss
Copy link
Contributor

emmauss commented Mar 20, 2025

On Android, gamepad input is treated the same way as key events from keyboard. They are handled on DispatchKeyEvents for buttons and DispatchGenericMotionEvent for axes. It would be easier to extend our existing key events to cover gamepad input.

@emmauss
Copy link
Contributor

emmauss commented Mar 20, 2025

Also, please fixup and author your commits using your github user. The CLA bot doesn't work well with email users.

@emmauss
Copy link
Contributor

emmauss commented Mar 20, 2025

Your git modules are broken.

@Trevo525
Copy link

Trevo525 commented Mar 20, 2025

It reacts really quickly, and I don't have any good ways of measuring input latency when you're using a separate render-thread. Forcing it into a single thread and using DXGI, it feels really responsive, more responsive than some of the games I've played.

The amount of latency between the control and windows is irrelevant. At least, it's out of control of Avalonia. Could you use a script to press the button and use that to time how long it takes for it to register in your app?

https://www.autohotkey.com/docs/v2/KeyList.htm#Controller

Squashing many things
@ShadowMarker789
Copy link
Contributor Author

Also, please fixup and author your commits using your github user. The CLA bot doesn't work well with email users.

I've attempted to squash the commits under my github profile. Does it look better now?

@emmauss
Copy link
Contributor

emmauss commented Mar 29, 2025

Also, please fixup and author your commits using your github user. The CLA bot doesn't work well with email users.

I've attempted to squash the commits under my github profile. Does it look better now?

Yes. It good now. You only need to accept the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature needs-api-review The PR adds new public APIs that should be reviewed. os-windows
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants