Skip to content

Add caller-driven GameController input with a native macOS backend - #137

Open
coolzi wants to merge 6 commits into
Try:masterfrom
coolzi:codex/macos-gamepad
Open

coolzi wants to merge 6 commits into
Try:masterfrom
coolzi:codex/macos-gamepad

Conversation

@coolzi

@coolzi coolzi commented Oct 25, 2026 •

Copy link
Copy Markdown

Add per-connection controller input following the API discussion in #138.

API

  • Application::controllers() enumerates copyable GameController handles. Copies and repeated enumeration share one native connection, current state and event queue. Handles compare by their shared implementation; reconnecting creates a different identity. There is no synthetic numeric device ID or redundant device field in per-controller events.
  • GameController delegates to its shared Impl. Detail::MacosController implements the native connection, reusing the portable queue/state. ControllerApi lives in system/controller, separately from SystemApi; no public handle-construction helper is exposed.
  • pull(callback) removes one event under a short queue lock, then invokes application code on the caller's thread outside that lock. It drains until the live queue is empty, including events added during a callback. An indefinitely active producer can keep the call running. The application serializes pulls across copies and must not reenter the same connection's pull. Cancellation replaces pending input immediately; a throwing callback leaves untouched events queued.
  • axis(Stick) and state() read synchronized current values without consuming events; device() exposes metadata and supported controls. Button::None = 0 identifies non-button events and is excluded from capability/state masks. Empty/moved-from handles safely return empty values. Disconnected handles retain their identity and terminal event.

Focus loss/recovery, overflow and disconnect produce per-connection cancellation events. Focus recovery refreshes the native sample before publishing its reset. Gameplay bindings, dead zones and neutral rearming remain application policy.

macOS integration

Enumeration runs on the main thread after AppKit launch, without requiring a Tempest window. The registry removes observers/handlers and releases native resources on the main thread; stale handles and final handle release on a worker remain safe. GameController.framework is weak-linked, with native availability checked before discovery. Other platforms currently return no controllers; this adds no Windows runtime dependency.

The macOS implProcessEvents path now dispatches ordinary Tempest timers, including inside nested Dialog::exec() loops. Timer iteration handles reentry, callback-time registry mutation and exceptions, and stops after application exit. The duplicate outer timer dispatch and Application::onEventLoop() workaround are removed. The local OpenGothic consumer uses a Timer for deferred menu delivery. The guarded finishLaunching completes AppKit startup when Tempest creates NSApplication and drives its own event loop.

Validation

  • The existing TempestTests project builds and passes 210/210 tests on macOS arm64, including 20 controller regressions. Its complete CTest run passes 8/8: the normal suite plus seven native Timer scenarios registered in the same test project.
  • Focused controller checks pass 20 portable + 3 synthetic native tests normally and in separate ASan/UBSan and TSan builds. Coverage includes callback-time cancellation, exception remainder, live draining, the None sentinel, copied/moved-from handles, native button mapping, callback lifetime, reconnect, focus ordering and worker-thread final release.
  • The seven Timer scenarios pass normally and with ASan/UBSan instrumentation on the changed production sources and fixture. They exercise native polling, mutation, nested dialogs, reentry, exceptions and both timer/native exit paths. Unrelated engine dependencies in that focused sanitizer harness are uninstrumented.
  • Regression controls fail on the previous implementation: callback-added events remain queued under the old drain budget; timers do not run from processEvents; relocating dispatch alone reproduces the shared timer-cursor defect. The corresponding fixed checks pass.
  • The local OpenGothic migration builds the game, editor, probe and all registered test executables; complete CTest passes 17/17, including the real AppKit/GCD nested-menu fixture. Its portable input suite passes 121/121, including preserved v1 binding serialization and stale-source rejection. Parent application changes are outside this PR.
  • Mach-O inspection confirms LC_LOAD_WEAK_DYLIB for GameController in the built library and companion executable.

No new physical-controller session, older-macOS run, real non-macOS build or full-engine sanitizer result is claimed. USB and sustained physical 60/120 FPS remain outside the companion acceptance scope. See docs/game-controller.md for the contract and test commands.

@Try

Try commented Oct 26, 2026

Copy link
Copy Markdown
Owner

Hi, @coolzi and thanks for PR!

While it looks cool as proof of concept; in order to progress with new feature, you need to create issue first with basic explanation of native api available on various OS. Note: you don't have to fill out every os yourself - I might be able to fill some gaps. What is needed is general overview of what api engine has to abstract.

Then we can consider, what api representation will fit best.
You can look here for general reference: #36

@coolzi coolzi changed the title Add native macOS GameController input and event-loop boundary Add caller-driven GameController input with a native macOS backend Oct 28, 2026

@Try Try left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Hi, @coolzi !

This PR looks much nice than a first one, I only found time to look a part of it. Haven't look at deep 'meat' part with connection handling yet.

Comment thread Engine/system/controllerstate.cpp Resolved
void disconnect();
void setActive(bool active);
// Button callbacks also carry the analog value for trigger buttons.
void button(Button button, bool pressed, float value);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

is those functions meant to be private?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

These are now protected in GameController::Impl (77803a5). They are needed by the derived Detail::MacosController to feed native button/axis updates and connection/focus changes into the shared state and queue. The public GameController handle exposes only device(), state(), axis() and pull(); applications cannot inject native events. The queue helper push() and the stored state remain private.

Comment thread Engine/CMakeLists.txt Resolved
Comment thread Tests/controllers/CMakeLists.txt Outdated
@@ -0,0 +1,43 @@
cmake_minimum_required(VERSION 3.16)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

I really see no value in such test-cases - there is very little they can do on test-machine with no devices

Comment thread Engine/system/gamecontroller.h Outdated
State state() const;
Vec2 axis(Stick stick) const;

// Synchronous callbacks on the caller's thread, with no internal lock held.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

In Tempest I prefer to keep code easy to use, with no need of long comments. What you have in doc is enough.

Comment thread Engine/system/api/controllerapi.h Outdated

#include "../gamecontroller.h"

namespace Tempest::Detail {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

no need to put it into ::Detail - basically same as SystemApi;
also let put into a dedicated directory: system/controller/controllerapi.h

Comment thread Engine/system/api/controllerapi.h Outdated
class ControllerApi final {
public:
static std::vector<GameController> controllers();
static GameController controller(std::shared_ptr<ControllerState> state);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

why this function is public?
given, that we ended up with a single usable public function - maybe transfer it to Tempest::Application::controllers ?

Comment thread Engine/system/api/macoscontrollerapi.mm Outdated
std::vector<std::shared_ptr<ControllerState>> MacOSControllerApi::controllers() const {
requireMainThread();
std::vector<std::shared_ptr<ControllerState>> result;
result.reserve(impl->devices.size());

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

It would make sense here, to have separation:
GameController - user-land one, only rerouted api calls into ::Impl.
Detail::MacosController - implements event pull and tracks mac-os specific state

Comment thread Engine/system/application.h Outdated

// UI-thread boundary between native event-processing steps. May re-enter
// through a modal loop; subscribers must unbind before being destroyed.
static Signal<void()>& onEventLoop();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

what is that for?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

This is used by the OpenGothic consumer to deliver deferred menu commands that may enter Dialog::exec(). Input is drained first; the UI command runs after that drain returns, so a nested dialog does not recursively enter the same controller's pull().

Dialog::exec() repeatedly calls Application::processEvents(). On macOS this processes native events but does not run Tempest's Timer dispatcher, which is called by the outer implExec() loop. The hook provides a delivery point both in that outer loop and inside nested dialogs, allowing input and cancellation to reach the active modal level. The controller backend itself does not subscribe to it.

I tried replacing the hook with a Timer in the local native regression fixture. With a Timer, the local native regression entered the parent dialog but never dispatched the queued command to open its child; the watchdog fired and seven assertions failed. The retained hook passes the nested-modal regression. Fixing Timer dispatch would be a separate event-loop change.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

On macOS this processes native events but does not run Tempest's Timer dispatcher, which is called by the outer implExec() loop.

Thats a bug. implProcessEvents meant to run timers

Comment thread Engine/system/api/macosapi.mm Resolved
if(id == 0)
throw std::overflow_error("GameController connection ID exhausted");
} while(!next.compare_exchange_weak(id, id + 1));
return id;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

is it just overcomplicated and slow way to do atomic_add ?!


GameController::Impl::Impl(std::string name, uint32_t buttons, uint32_t axes,
const State& initial, bool active)
: info{connectionId(), std::move(name), buttons & buttonMask, axes & axisMask}, active(active) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

what is a reason to have connectionId, provided that it's not part of native api?

size_t count;
{
std::lock_guard<std::mutex> guard(sync);
count = events.size();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

this is wrong - you poking size of data is one critical section and iterating in another.
overall not even needed, provided that intent is to drain all events and loop body already stops, of array of events is empty

}

namespace {
uint32_t supportedButtons(GCController* controller) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

need to have it static; dummy namespace is not needed

using DeviceId = uint64_t;

enum class Button : uint8_t {
South, East, West, North,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

need to add None = 0, for events that are not related to buttons

Comment thread Engine/system/gamecontroller.h Outdated
enum class ResetReason : uint8_t { None, FocusLost, Disconnected, Overflow, FocusGained };

Type type = Type::Reset;
DeviceId device = 0;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

why do you need deviceId here?
shouldn't be needed, since pull to tied to on specific device

Comment thread Engine/system/application.h Outdated

// UI-thread boundary between native event-processing steps. May re-enter
// through a modal loop; subscribers must unbind before being destroyed.
static Signal<void()>& onEventLoop();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

On macOS this processes native events but does not run Tempest's Timer dispatcher, which is called by the outer implExec() loop.

Thats a bug. implProcessEvents meant to run timers

@coolzi

coolzi commented Nov 9, 2026

Copy link
Copy Markdown
Author

Hi @Try, could you approve the CI run for this PR and review the latest commit, 933a0ce, when you have a chance? Thanks!

Construct controller fixtures through a shared friend helper so the tests and the library use the same private constructor symbol.
@coolzi

coolzi commented Nov 13, 2026

Copy link
Copy Markdown
Author

Thanks for rerunning CI, @Try! The MSVC linking issue is fixed in 6986dd6. Could you approve the new CI run and review that commit when you have a chance?

@Try

Try commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@coolzi if you still working on PR, why don't you run CI on your local fork?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants