Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: thehobbit85 <[email protected]>
Date: Wed, 4 Nov 2026 20:40:56 -0800
Subject: [PATCH] Support Steam Controller and shared Mac control mappings
Adapt seedds/nxnative PR #221 by thehobbit85 ([email protected]) at source commit 5e2b1c7276e0745825f17d7875ec0e56b6913f7b to the NX2Apple pinned engine and existing input mapping carrier. Preserve fork window, screen, aspect and cursor behavior while integrating controller ownership, motion, haptics and shared preferences.
Retain the pin refresh's split Joy-Con input, per-half motion and haptic localities in the shared controller registry. Preserve the newer pointer, embedded-section and iOS game-framework behavior.
Advertise DMControllerMappings=1 in Mac app metadata so launchers can gate the shared mapping contract independently of DMSettings.
Front-ends: Gate shared DM_KEYMAP, DM_PAD_MAP and controller.<model> preferences on the DMControllerMappings capability marker. See docs/frontends.md for the exact storage contract.
Upstream-Status: forwarded seedds/nxnative#221
Reason: Provide Steam Controller support and shared Mac controller mappings on the pinned engine while the upstream pull request is pending
Issue: seedds/nxnative#221
---
dm/games/0100F2C0115B6000/README.md | 6 +
dm/host/Makefile | 4 +-
dm/host/controllers_mac.h | 20 +
dm/host/controllers_mac.m | 975 ++++++++++++++++++++++++
dm/host/dm_input.h | 6 +-
dm/host/front_mac.m | 310 +-------
dm/host/haptics_apple.h | 10 +
dm/host/haptics_apple.m | 48 +-
dm/host/hle_haptics.h | 2 +-
dm/host/hle_hid.c | 175 +++--
dm/host/home_quit.h | 4 +-
dm/host/input_map.h | 46 +-
dm/host/input_preferences_mac.h | 47 ++
dm/host/pad_hid_mac.h | 38 +-
dm/host/pad_joycon_mac.h | 2 +-
dm/host/pad_map.h | 17 +
dm/host/pad_motion.h | 36 +
dm/host/steam_input.h | 97 +++
dm/host/tests/Makefile | 11 +
dm/host/tests/t_controllers_mac.m | 1065 +++++++++++++++++++++++++++
dm/host/tests/t_haptics_apple.m | 49 +-
dm/host/tests/t_hid.c | 247 ++++++-
dm/host/tests/t_input_map.c | 35 +
dm/host/tests/t_pad_map.c | 104 +++
dm/host/tests/t_pad_motion.c | 19 +
dm/mac/launcher.c | 28 +-
dm/mac/pack_app.py | 4 +-
dm/tools/impact_map.tsv | 10 +
dm/tools/tests/test_nsp_mac_app.py | 109 ++-
docs/development.md | 4 +
docs/env_switches.tsv | 7 +-
docs/frontends.md | 32 +
docs/mac-controllers.md | 253 +++++++
docs/reference/services.md | 37 +-
34 files changed, 3483 insertions(+), 374 deletions(-)
create mode 100644 dm/host/controllers_mac.h
create mode 100644 dm/host/controllers_mac.m
create mode 100644 dm/host/input_preferences_mac.h
create mode 100644 dm/host/pad_map.h
create mode 100644 dm/host/pad_motion.h
create mode 100644 dm/host/steam_input.h
create mode 100644 dm/host/tests/t_controllers_mac.m
create mode 100644 dm/host/tests/t_pad_map.c
create mode 100644 dm/host/tests/t_pad_motion.c
create mode 100644 docs/mac-controllers.md
diff --git a/dm/games/0100F2C0115B6000/README.md b/dm/games/0100F2C0115B6000/README.md
index 10876cc..dd12253 100644
--- a/dm/games/0100F2C0115B6000/README.md
+++ b/dm/games/0100F2C0115B6000/README.md
@@ -64,6 +64,8 @@ Game-specific findings. The general host changes they led to are listed under [F
## Services
+- **Resolved: Steam Controller stick drift suppressing gyro aiming.** In update 1.4.3, small nonzero stick values at rest take priority over bow gyro input. The adapter's default 10% radial deadzone reports a centred stick as zero. The game also resets its aim reference at an exactly identity orientation; Recenter keeps that truthful pose rather than fabricating a rotation. Current physical-device retesting remains open, including trackpads, rear buttons, mapping persistence, Bluetooth and Puck. The gyro scale has not been calibrated against a known rotation.
+- **Resolved in the host; gameplay retest pending:** six-axis handles now use SDK style indices and device bytes. The earlier handle-format mismatch was independent of the gyro-aiming failure; changing the style alone did not restore aiming.
- SDK 20 calls it needed (each aborted in `sm::Initialize` or read a null applet proxy, one per boot): `oe::GetPreviousProgramIndex`, the hardware Opus decoder's C interface, cache storage, `fs::IsSaveDataExisting` for another title (it asks for Breath of the Wild's save: none), `MountSaveDataReadOnly`, `time::ClockSnapshot::CreateWithStandardSystemClock` ([Applet resource user ID, launch parameters and VR mode](../../../docs/reference/services.md#applet-resource-user-id-launch-parameters-and-vr-mode), [Hardware Opus decoders](../../../docs/reference/audio.md#hardware-opus-decoders-built-on-the-sdks-software-decoders), [Cache storage and other titles' save data](../../../docs/reference/services.md#cache-storage-and-other-titles-save-data), [Steady clock, clock snapshots and user clocks](../../../docs/reference/services.md#steady-clock-clock-snapshots-and-user-clocks)).
- **Resolved: clock snapshot types** ([PR #385](https://github.com/seedds/nxnative/pull/385), static SDK check). SDK build `574284b40c06cf1821a44857939083bee5716820` passes type 1 for standard snapshots (`sdk+0x441890`) and 2 for adjustable snapshots (`sdk+0x441924`); both entries first read the time-service session through `sdk+0xb6b280`. The host now sets the standard type and takes over the adjustable entry as described in [Steady clock, clock snapshots and user clocks](../../../docs/reference/services.md#steady-clock-clock-snapshots-and-user-clocks). This verifies the ABI; gameplay was not rerun for this check.
- `main` imports `nn::ro` (it loads NRO modules at run time).
@@ -113,6 +115,10 @@ General host changes first needed here; each applies to every game:
- **RomFS folder transfer and startup deletion failures:** [RomFS images](../../../docs/reference/packing.md#romfs-folder-transfers-fail-or-leave-stale-game-files).
+- **Six-axis SDK handle encoding:** [Handle style, device and sensor count](../../../docs/reference/services.md#six-axis-handle-encoding).
+
+- **Steam Controller stick drift suppressing gyro aiming:** [Radial stick deadzone](../../../docs/reference/services.md#steam-controller-stick-drift-suppresses-gyro-aiming).
+
- **Resolved in the host (#531): `DM_NVN_GPUPROF` abort when an upload flush lands in a profiled draw pass:** [GPU profiles stamp only the encoder they began](../../../docs/reference/rendering.md#gpu-profiles-stamp-only-the-encoder-they-began). Covered by `t_gpuprof`; not rerun in the game.
- **Resolved in the host (#342): recurring startup crash during archive compaction**, with a workaround for Metal's serializer defect: [Pipeline archive compaction crashes in Metal's serializer](../../../docs/reference/shaders.md#a-compaction-flush-that-crashes-then-crashes-every-start). Confirmed with local manifest replays; no new gameplay or iOS validation.
diff --git a/dm/host/Makefile b/dm/host/Makefile
index cac0b94..b97e46f 100644
--- a/dm/host/Makefile
+++ b/dm/host/Makefile
@@ -20,7 +20,7 @@ GAME_H = gen/$(GAME)/game_profile.h
include ../mac/min_os.mk
CFLAGS=-O1 -g -Wall -Wno-unused-function -mmacosx-version-min=$(MACOS_MIN)
# Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts)
-SRC=main.c loader.c hle.c crash.c probe.c thread.c save_sync.c memstat.m haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m web_apple.m entry.S
+SRC=main.c loader.c hle.c crash.c probe.c thread.c save_sync.c memstat.m haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m controllers_mac.m web_apple.m entry.S
# NVN null device + nn::vi + the Vulkan layer (dm/gfx/)
# Sources under dm/gfx, dm/gfx/nvn, dm/gfx/tex, dm/gfx/vk and dm/gfx/gl are included by wildcard (tests/ and metal/ do not go into the host): adding a file does not touch this line
GFX=$(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/nvn/*.m ../gfx/nvn/*.S ../gfx/tex/*.c ../gfx/tex/*.m ../gfx/vk/*.m ../gfx/gl/*.m))
@@ -79,7 +79,7 @@ endif
endif
.PHONY: FORCE
FORCE:
-dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h romfs_image.h save_sync.h dm_input.h pad_slots.h hle_haptics.h haptics_apple.h motion_fusion.h motion_apple.h motion_pro.h motion_pro_mac.h pad_apple.h pad_hid.h pad_hid_mac.h pad_joycon.h pad_joycon_mac.h home_quit.h home_quit_mac.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB) $(DAV1D_LIB) $(MSL_H)
+dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h romfs_image.h save_sync.h dm_input.h input_map.h input_preferences_mac.h pad_slots.h pad_map.h pad_motion.h steam_input.h controllers_mac.h hle_haptics.h haptics_apple.h motion_fusion.h motion_apple.h motion_pro.h motion_pro_mac.h pad_apple.h pad_hid.h pad_hid_mac.h pad_joycon.h pad_joycon_mac.h home_quit.h home_quit_mac.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB) $(DAV1D_LIB) $(MSL_H)
clang $(CFLAGS) -I../gfx/nvn/include -I$(dir $(MSL_H)) -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I$(DAV1D)/include -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) $(DAV1D_LIB) -framework Cocoa -framework WebKit -framework UserNotifications -framework QuartzCore -framework Metal -framework MetalFX -framework GameController -framework CoreHaptics -framework IOKit -framework AudioToolbox -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers
clean: # the host and everything make generates for it (gen/: the profile headers, the game stamp and the libvpx and dav1d builds; dmhost_* and *.dSYM beside them, as in .gitignore)
rm -rf gen dmhost dmhost_* *.dSYM
diff --git a/dm/host/controllers_mac.h b/dm/host/controllers_mac.h
new file mode 100644
index 0000000..494a201
--- /dev/null
+++ b/dm/host/controllers_mac.h
@@ -0,0 +1,20 @@
+#pragma once
+#import <Cocoa/Cocoa.h>
+// Main-thread controller routing and a model-specific mapping panel.
+void front_controllers_start(void);
+NSMenu *front_controllers_menu(void);
+
+#include "front.h"
+void front_controllers_mouse(const dm_touch *touch);
+void front_controllers_focus(int active);
+void front_controllers_modal(int active);
+void front_controllers_window(int active);
+
+// Main-thread input for the Home quit prompt. Read physical buttons before remapping.
+@class GCController;
+GCController *front_controllers_quit_buttons(int *home, int *a, int *b);
+void front_controllers_quit_prompt(int active);
+void front_home_poll(void);
+
+// Called on the main thread when mapped input reaches the game.
+void front_game_input(void);
diff --git a/dm/host/controllers_mac.m b/dm/host/controllers_mac.m
new file mode 100644
index 0000000..1ca3f30
--- /dev/null
+++ b/dm/host/controllers_mac.m
@@ -0,0 +1,975 @@
+// Mac controller input: keep the existing eight-player slot policy, with
+// shared button choices and per-model extras for GameController and Triton HID.
+#import "controllers_mac.h"
+#import <GameController/GameController.h>
+#import <IOKit/hid/IOHIDManager.h>
+#import "haptics_apple.h"
+#include "dm.h"
+#include "motion_apple.h"
+#include "motion_pro_mac.h"
+#include "pad_slots.h"
+#include "pad_apple.h"
+#include "pad_map.h"
+#include "input_preferences_mac.h"
+#include "steam_input.h"
+#include "pad_motion.h"
+#include "pad_hid_mac.h"
+#include "pad_joycon_mac.h"
+#include <math.h>
+
+enum { PAD_OFF, PAD_DPAD, PAD_LEFT_STICK, PAD_RIGHT_STICK, PAD_TOUCH };
+
+@interface DMController : NSObject {
+@public
+ int slot, map[DM_PAD_BUTTONS];
+ steam_state input;
+ uint32_t quit_buttons; // raw Triton buttons, including changes while guest input is suspended
+ IOHIDDeviceRef device; // Triton only: proprietary output and feature reports
+ joycon_pad *joycon; // borrowed until joycon_detach, with an independent player slot
+ hid_pad *generic; // borrowed until hidpad_detach; never a Triton output route
+ unsigned char report[512];
+ BOOL feature_warning, rumble_warning, gyro_enabled, connected;
+ uint64_t registry_id;
+ int pad_mode[2], touch_id[2];
+ pad_motion_state motion;
+ NSTimeInterval motion_at, gc_not_before;
+}
+@property NSString *name;
+@property NSString *model;
+@property GCController *controller;
+@end
+@implementation DMController
+- (instancetype)init { if ((self = [super init])) { slot = -1; touch_id[0]=touch_id[1]=-1; gyro_enabled=YES; pad_physical_default(map, 0); } return self; }
+- (void)dealloc { if (device) CFRelease(device); }
+@end
+
+static NSMutableArray<DMController *> *g_devices;
+static NSMutableDictionary *g_maps; // session-only model choices when saving is disabled
+static NSString *g_controls_domain;
+static NSDictionary *g_legacy_maps; // read-only import of the old controllers.plist
+static pad_map g_button_map;
+static BOOL g_map_fixed, g_maps_loaded, g_maps_saved;
+static pad_slots g_slots;
+static int g_merge, g_focus=1, g_app_focus=1, g_window_focus=1, g_modal, g_quit_prompt;
+static __weak DMController *g_motion_source;
+static __weak DMController *g_merge_haptics_source;
+static NSTimeInterval controller_now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC,&t); return t.tv_sec+t.tv_nsec/1e9; }
+static dm_touch g_mouse; static int g_mouse_down;
+static BOOL g_touches_published;
+static void steam_keepalive(DMController *d);
+static void controllers_changed(GCController *gone);
+static BOOL steam_discover(void);
+static void steam_native_admission(void);
+static void controller_panel_refresh(void);
+static void controller_read_gc(DMController *d, id<GCDevicePhysicalInputState> state);
+static void controller_reset_motion(DMController *d);
+static void controller_attach_motion(DMController *d);
+static void joycon_haptics_sync(GCController *gone);
+
+static NSString *controller_map_key(DMController *d) { return [@"controller." stringByAppendingString:d.model]; }
+static void controller_load_map(DMController *d) {
+ pad_physical_default(d->map, 0);
+ for(int i=0;i<IM_BUTTONS;i++) d->map[i]=g_button_map.to[i]; // NOLINT(bugprone-signed-char-misuse): -1 is the unbound mapping, not a character.
+ d->pad_mode[0]=[d.model isEqual:@"Valve Triton"] ? PAD_DPAD : PAD_OFF;
+ d->pad_mode[1]=[d.model isEqual:@"Valve Triton"] ? PAD_TOUCH : PAD_OFF;
+ d->gyro_enabled=YES;
+ id a=input_preferences_enabled() ? input_preference(g_controls_domain,controller_map_key(d)) : g_maps[d.model];
+ if(![a isKindOfClass:NSDictionary.class]) return;
+ id pads=a[@"pads"], gyro=a[@"gyro"], extra=a[@"buttons"];
+ if([pads isKindOfClass:NSArray.class] && [pads count]==2)
+ for(int i=0;i<2;i++) if([pads[i] isKindOfClass:NSNumber.class] && [pads[i] doubleValue]==[pads[i] intValue] && [pads[i] intValue]>=PAD_OFF && [pads[i] intValue]<=PAD_TOUCH) d->pad_mode[i]=[pads[i] intValue];
+ if([gyro isKindOfClass:NSNumber.class] && ([gyro doubleValue]==0 || [gyro doubleValue]==1)) d->gyro_enabled=[gyro boolValue];
+ // Only extra physical sources live here. Standard buttons have one shared
+ // map for the game, never a hidden per-model override of DM_PAD_MAP.
+ if([extra isKindOfClass:NSDictionary.class]) for(int i=IM_BUTTONS;i<DM_PAD_BUTTONS;i++) {
+ id v=extra[@(i).stringValue]; if(![v isKindOfClass:NSNumber.class]) continue;
+ int n=[v intValue]; if([v doubleValue]==n && (n==-1 || (n>=0 && n<16) || n==63)) d->map[i]=n;
+ }
+}
+static void controller_reload_maps(void) {
+ BOOL saved=input_preferences_enabled();
+ if(g_maps_loaded && !saved && !g_maps_saved) return; // keep this session's edits
+ if(g_maps_saved!=saved) [g_maps removeAllObjects];
+ g_maps_loaded=YES; g_maps_saved=saved;
+ if(g_controls_domain) CFPreferencesAppSynchronize((__bridge CFStringRef)g_controls_domain);
+ g_map_fixed=input_map_fixed("DM_PAD_MAP");
+ pad_map_default(&g_button_map);
+ NSString *spec=input_preference_map(g_controls_domain,"DM_PAD_MAP",1);
+ if(spec) pad_map_parse(&g_button_map,spec.UTF8String);
+ for(DMController *d in g_devices) {
+ BOOL gyro=d->gyro_enabled;
+ controller_load_map(d);
+ if(gyro!=d->gyro_enabled) { controller_reset_motion(d); controller_attach_motion(d); steam_keepalive(d); }
+ }
+}
+static BOOL controller_save_buttons(void) {
+ NSMutableArray *entries=[NSMutableArray array];
+ for(int i=0;i<IM_BUTTONS;i++) if(g_button_map.to[i]!=i) {
+ int to=g_button_map.to[i]; // NOLINT(bugprone-signed-char-misuse): preserve the -1 unbound mapping.
+ NSString *name=to==63 ? @"Shake" : to<0 ? @"none" : @(im_names[to]);
+ [entries addObject:[NSString stringWithFormat:@"%s=%@",im_names[i],name]];
+ }
+ BOOL ok=input_preference_write(g_controls_domain,@"launcher.DM_PAD_MAP",entries.count ? [entries componentsJoinedByString:@","] : nil);
+ for(DMController *d in g_devices) for(int i=0;i<IM_BUTTONS;i++) d->map[i]=g_button_map.to[i]; // NOLINT(bugprone-signed-char-misuse): -1 is the unbound mapping, not a character.
+ return ok;
+}
+static BOOL controller_set_button(int source, int target) {
+ if(g_map_fixed || source<0 || source>=IM_BUTTONS || !(target==-1 || (target>=0 && target<IM_BUTTONS) || target==63)) return NO;
+ g_button_map.to[source]=(int8_t)target;
+ return controller_save_buttons();
+}
+static BOOL controller_save_map(DMController *d) {
+ NSMutableDictionary *extra=[NSMutableDictionary dictionary], *value=[NSMutableDictionary dictionary];
+ for(int i=IM_BUTTONS;i<DM_PAD_BUTTONS;i++) if(d->map[i]!=-1) extra[@(i).stringValue]=@(d->map[i]);
+ if(extra.count) value[@"buttons"]=extra;
+ BOOL triton=[d.model isEqual:@"Valve Triton"];
+ if(d->pad_mode[0]!=(triton ? PAD_DPAD : PAD_OFF) || d->pad_mode[1]!=(triton ? PAD_TOUCH : PAD_OFF)) value[@"pads"]=@[@(d->pad_mode[0]),@(d->pad_mode[1])];
+ if(!d->gyro_enabled) value[@"gyro"]=@NO;
+ g_maps[d.model]=value;
+ BOOL ok=input_preference_write(g_controls_domain,controller_map_key(d),value.count ? value : nil);
+ // Apply even when synchronization failed: the panel reports session-only use.
+ for(DMController *other in g_devices) if(other!=d && [other.model isEqual:d.model]) {
+ for(int i=IM_BUTTONS;i<DM_PAD_BUTTONS;i++) other->map[i]=d->map[i];
+ memcpy(other->pad_mode,d->pad_mode,sizeof d->pad_mode); other->gyro_enabled=d->gyro_enabled;
+ }
+ return ok;
+}
+// An old per-model standard map may conflict with another model or a launcher
+// choice. Import only on the player's explicit action, keeping the file intact.
+static BOOL controller_import_map(DMController *d) {
+ if(g_map_fixed) return NO;
+ id value=g_legacy_maps[d.model], buttons=value;
+ if([value isKindOfClass:NSDictionary.class]) buttons=value[@"buttons"];
+ if(![buttons isKindOfClass:NSArray.class] || [buttons count]!=DM_PAD_BUTTONS) return NO;
+ for(int i=0;i<DM_PAD_BUTTONS;i++) {
+ id v=buttons[i]; if(![v isKindOfClass:NSNumber.class]) continue;
+ int n=[v intValue]; if([v doubleValue]!=n || !(n==-1 || (n>=0 && n<16) || n==63)) continue;
+ if(i<IM_BUTTONS) g_button_map.to[i]=(int8_t)n; else d->map[i]=n;
+ }
+ if([value isKindOfClass:NSDictionary.class]) {
+ id pads=value[@"pads"],gyro=value[@"gyro"];
+ if([pads isKindOfClass:NSArray.class] && [pads count]==2) for(int i=0;i<2;i++) {
+ id v=pads[i]; if([v isKindOfClass:NSNumber.class] && [v doubleValue]==[v intValue] && [v intValue]>=PAD_OFF && [v intValue]<=PAD_TOUCH) d->pad_mode[i]=[v intValue];
+ }
+ if([gyro isKindOfClass:NSNumber.class] && ([gyro doubleValue]==0 || [gyro doubleValue]==1)) d->gyro_enabled=[gyro boolValue];
+ }
+ BOOL buttons_ok=controller_save_buttons(); return controller_save_map(d) && buttons_ok;
+}
+static int32_t stronger(int32_t a, int32_t b) { return abs(a) >= abs(b) ? a : b; }
+// IOHID output runs on the haptics queue; removal synchronously stops that route
+// before closing the device. Kept as a seam for packet/lifetime regression tests.
+static IOReturn (*steam_write)(IOHIDDeviceRef,IOHIDReportType,CFIndex,const uint8_t *,CFIndex)=IOHIDDeviceSetReport;
+static void controller_route_haptics(DMController *d, int player) {
+ if (d && d->device) dm_haptics_apple_output(player,d,^(dm_haptic_state state,float gain) {
+ uint8_t bytes[10];
+ float left=dm_haptics_apple_controller_intensity(dm_haptics_level(&state.motor[0],1,gain).intensity);
+ float right=dm_haptics_apple_controller_intensity(dm_haptics_level(&state.motor[1],1,gain).intensity);
+ steam_rumble_report(bytes,(uint16_t)(left*65535),(uint16_t)(right*65535));
+ IOReturn r=steam_write(d->device,kIOHIDReportTypeOutput,0x80,bytes,sizeof bytes);
+ if(r!=kIOReturnSuccess && !d->rumble_warning) {
+ fprintf(stderr,"[RED] Steam Controller rumble failed (0x%x)\n",r); d->rumble_warning=YES;
+ }
+ });
+ else if(d && d->joycon) {
+ GCController *pair=nil;
+ for(GCController *c in GCController.controllers) if(joycon_is_gc_controller(c) && c.haptics) { pair=c; break; }
+ if(g_merge) dm_haptics_apple_controller(player,pair);
+ else dm_haptics_apple_controller_locality(player,pair,d->joycon->st.pid==JOYCON_PID_L ? GCHapticsLocalityLeftHandle : GCHapticsLocalityRightHandle);
+ } else dm_haptics_apple_controller(player,d.controller);
+}
+static BOOL controller_has_haptics(DMController *d) {
+ if(d->device || d.controller.haptics.supportedLocalities.count) return YES;
+ if(d->joycon) for(GCController *c in GCController.controllers)
+ if(joycon_is_gc_controller(c) && c.haptics.supportedLocalities.count) return YES;
+ return NO;
+}
+static void controller_merge_haptics(void) {
+ DMController *current=g_merge_haptics_source;
+ // A newly connected pad must not steal an ongoing merged-player effect.
+ if(current && current->slot>=0 && controller_has_haptics(current)) return;
+ DMController *route=nil;
+ for (DMController *pad in g_devices) if (pad->slot>=0) {
+ if (!route && (pad.controller || pad->joycon)) route=pad;
+ if (controller_has_haptics(pad)) { route=pad; break; }
+ }
+ if(route!=current) { g_merge_haptics_source=route; controller_route_haptics(route,0); }
+}
+static void controller_touches(void) {
+ dm_touch touches[16]; int n=0; unsigned used=1;
+ // Reserve every held ID before allocating a newly pressed pad's finger.
+ for(DMController *d in g_devices) for(int i=0;i<2;i++) {
+ if(!g_focus || d->slot<0 || d->pad_mode[i]!=PAD_TOUCH || !d->input.pad[i].down) d->touch_id[i]=-1;
+ if(d->touch_id[i]>=0) used|=1u<<d->touch_id[i];
+ }
+ if(g_focus && g_mouse_down) touches[n++]=g_mouse;
+ for(DMController *d in g_devices) for(int i=0;i<2;i++) {
+ if(!g_focus || d->slot<0 || d->pad_mode[i]!=PAD_TOUCH || !d->input.pad[i].down) continue;
+ if(d->touch_id[i]<0) for(int j=1;j<16;j++) if(!(used & (1u<<j))) { d->touch_id[i]=j; used|=1u<<j; break; }
+ if(d->touch_id[i]<0) continue;
+ steam_pad pad=d->input.pad[i];
+ touches[n++]=(dm_touch){(uint32_t)d->touch_id[i], fminf(.999f,(pad.x+32767)/65534.0f), fminf(.999f,(32767-pad.y)/65534.0f)};
+ }
+ // DM_CTL can hold a scripted touch too. Release only a finger this front
+ // end published, rather than clearing scripted input on every pad event.
+ if(n || g_touches_published) dm_touch_set(touches,n);
+ g_touches_published=n>0;
+}
+void front_controllers_mouse(const dm_touch *touch) {
+ g_mouse_down=g_focus && touch!=NULL; if(touch) { g_mouse=*touch; g_mouse.id=0; } controller_touches();
+}
+static steam_state controller_effective(DMController *d) {
+ if(!g_focus) return (steam_state){0};
+ steam_state s=d->input;
+ for(int i=0;i<2;i++) if(s.pad[i].down) {
+ int32_t x=s.pad[i].x,y=s.pad[i].y;
+ if(d->pad_mode[i]==PAD_DPAD) {
+ if(x < -8192) s.buttons|=DM_BTN_LEFT; if(x > 8192) s.buttons|=DM_BTN_RIGHT;
+ if(y < -8192) s.buttons|=DM_BTN_DOWN; if(y > 8192) s.buttons|=DM_BTN_UP;
+ } else if(d->pad_mode[i]==PAD_LEFT_STICK || d->pad_mode[i]==PAD_RIGHT_STICK) {
+ if(abs(x)<4096 && abs(y)<4096) x=y=0;
+ if(d->pad_mode[i]==PAD_LEFT_STICK) { s.lx=stronger(s.lx,x); s.ly=stronger(s.ly,y); }
+ else { s.rx=stronger(s.rx,x); s.ry=stronger(s.ry,y); }
+ }
+ }
+ return s;
+}
+// All adapters publish through this boundary, including shared remapping and
+// merged input. Preserve the upstream pointer threshold after normalization.
+static void controller_publish_player(int player, uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
+ const int32_t dead=DM_STICK_MAX*15/100;
+ if(buttons || abs(lx)>dead || abs(ly)>dead || abs(rx)>dead || abs(ry)>dead) front_game_input();
+ dm_pad_set_player(player,buttons,lx,ly,rx,ry);
+}
+static void controller_publish(DMController *d) {
+ if (g_merge) {
+ uint64_t buttons = 0; int32_t lx=0, ly=0, rx=0, ry=0;
+ for (DMController *pad in g_devices) if (pad->slot >= 0) {
+ steam_state s=controller_effective(pad);
+ buttons |= pad_map_buttons(s.buttons, pad->map);
+ lx=stronger(lx,s.lx); ly=stronger(ly,s.ly); rx=stronger(rx,s.rx); ry=stronger(ry,s.ry);
+ }
+ controller_publish_player(0, buttons, lx, ly, rx, ry);
+ } else if (d->slot >= 0) {
+ steam_state s=controller_effective(d);
+ controller_publish_player(d->slot, pad_map_buttons(s.buttons, d->map), s.lx,s.ly,s.rx,s.ry);
+ }
+ controller_touches();
+}
+// Keep upstream's native and passive Pro motion attached to the same admitted slots as buttons.
+static void controller_pro_changed(void) {
+ int count = 0, player = -1;
+ for (DMController *d in g_devices) if (d.controller && [d.controller.productCategory isEqualToString:@"Switch Pro Controller"]) {
+ count++; player = d->slot < 0 ? -1 : g_merge ? 0 : d->slot;
+ }
+ dm_motion_pro_players(count, player);
+}
+static void controller_attach_motion(DMController *d) {
+ if (d.controller && d->slot >= 0 && g_focus && d->gyro_enabled) dm_motion_attach(d.controller, g_merge ? 0 : d->slot);
+}
+static DMController *controller_motion_source(void) {
+ for(DMController *d in g_devices) if(d->slot>=0 && d->gyro_enabled && d->motion.have_tick && controller_now()-d->motion_at<.25) return d;
+ return nil;
+}
+static void controller_publish_motion(DMController *d) {
+ if(!g_focus || d->slot<0 || !d->gyro_enabled || !d->motion.have_tick) return;
+ if(g_merge) {
+ if(controller_motion_source()!=d) return;
+ if(g_motion_source!=d) { dm_pad_motion(0,NULL); g_motion_source=d; }
+ }
+ dm_pad_motion(g_merge ? 0 : d->slot,&d->motion.value);
+}
+static void controller_reset_motion(DMController *d) {
+ BOOL source=!g_merge || g_motion_source==d;
+ if(g_motion_source==d) g_motion_source=nil;
+ pad_motion_reset(&d->motion);
+ if(d->joycon) {
+ d->joycon->motion=(pro_motion){0};
+ if(d->slot>=0) dm_motion_clear_hid(g_merge ? 0 : d->slot);
+ }
+ if (d.controller && d->slot >= 0) dm_motion_detach(d.controller, g_merge ? 0 : d->slot);
+ else if(d->slot>=0 && source) dm_pad_motion(g_merge ? 0 : d->slot,NULL);
+}
+// The prompt reads the controllers while guest input is suspended. Window/app
+// focus and the software keyboard still apply to both.
+static int controller_listening(void) { return g_app_focus && g_window_focus && !g_modal; }
+GCController *front_controllers_quit_buttons(int *home, int *a, int *b) {
+ GCController *holder=nil;
+ *home=*a=*b=0;
+ if(!controller_listening()) return nil;
+ for(DMController *d in g_devices) if(d->slot>=0) {
+ GCExtendedGamepad *g=d.controller.extendedGamepad;
+ if(g) {
+ if(g.buttonHome.isPressed) { *home=1; if(!holder) holder=d.controller; }
+ *a|=g.buttonA.isPressed; *b|=g.buttonB.isPressed;
+ } else if(d->joycon) {
+ *home|=d->joycon->st.home;
+ *a|=!!(d->joycon->st.buttons & DM_BTN_A); *b|=!!(d->joycon->st.buttons & DM_BTN_B);
+ } else if(d->device) {
+ // Triton's Guide and physical A (bottom) / B (right), before DM_PAD_MAP.
+ *home|=!!(d->quit_buttons & (1u<<22));
+ *a|=!!(d->quit_buttons & DM_BTN_B); *b|=!!(d->quit_buttons & DM_BTN_A);
+ }
+ }
+ return holder;
+}
+static void controller_update_focus(void) {
+ int was_focused=g_focus, listening=controller_listening();
+ g_focus=listening && !g_quit_prompt;
+ dm_haptics_apple_focus(g_focus);
+ dm_motion_pro_active(g_focus);
+ if(!g_focus) {
+ g_mouse_down=0;
+ for(DMController *d in g_devices) {
+ controller_reset_motion(d);
+ if(!listening) d->input=(steam_state){0};
+ controller_publish(d);
+ }
+ controller_touches();
+ } else if(!was_focused) {
+ // Native buttons held through a focus change need no new physical
+ // event. Only restore already admitted controllers, never cached peers.
+ for(DMController *d in g_devices) if(d->slot>=0) {
+ if(d.controller) { controller_attach_motion(d); controller_read_gc(d,[d.controller.input capture]); }
+ else if(d->generic) hidpad_read(d->generic);
+ else if(d->joycon) joycon_read(d->joycon);
+ else if(d->device) controller_publish(d);
+ }
+ front_home_poll();
+ }
+}
+void front_controllers_quit_prompt(int active) {
+ if(g_quit_prompt==active) return;
+ g_quit_prompt=active; controller_update_focus();
+}
+void front_controllers_focus(int active) { g_app_focus=active; controller_update_focus(); }
+void front_controllers_window(int active) { g_window_focus=active; controller_update_focus(); }
+void front_controllers_modal(int active) { g_modal=active; controller_update_focus(); }
+static void controller_connect(DMController *d) {
+ if (d->slot >= 0) return;
+ d->slot = pad_slot_take(&g_slots, (__bridge const void *)d, d.name.UTF8String);
+ if (d->slot < 0) { fprintf(stderr, "controller '%s': all %d players are taken\n", d.name.UTF8String, DM_PLAYERS); return; }
+ controller_attach_motion(d);
+ controller_pro_changed();
+ if (g_merge) controller_merge_haptics(); else controller_route_haptics(d, d->slot);
+ dm_pad_players(g_merge ? 1 : pad_slot_mask(&g_slots));
+ fprintf(stderr, "controller '%s': player %d\n", d.name.UTF8String, g_merge ? 1 : d->slot + 1);
+ controller_panel_refresh();
+}
+static void controller_disconnect(DMController *d) {
+ if (d->slot < 0) return;
+ controller_reset_motion(d);
+ int slot = d->slot;
+ pad_slot_free(&g_slots, (__bridge const void *)d); d->slot = -1;
+ controller_pro_changed();
+ d->input = (steam_state){0}; d->quit_buttons=0;
+ if (g_merge) controller_merge_haptics(); else dm_haptics_apple_controller(slot, nil);
+ if (g_merge) controller_publish(d); else dm_pad_set_player(slot, 0, 0, 0, 0, 0);
+ dm_pad_players(g_merge ? (pad_slot_mask(&g_slots) ? 1 : 0) : pad_slot_mask(&g_slots));
+ controller_touches();
+ controller_panel_refresh();
+ if(controller_listening()) front_home_poll();
+}
+// Generic HID uses the same registry, slot table and shared button map as GC
+// and Triton. Its decoder keeps physical state through focus changes.
+static DMController *controller_for_hid(hid_pad *hid) {
+ for(DMController *d in g_devices) if(d->generic==hid) return d;
+ return nil;
+}
+static void hidpad_read(hid_pad *hid) {
+ DMController *d=controller_for_hid(hid); if(!d) return;
+ int32_t s[4]; pad_hid_sticks(&hid->st,s);
+ d->input=(steam_state){.buttons=(uint32_t)pad_hid_buttons(&hid->st),.lx=s[0],.ly=s[1],.rx=s[2],.ry=s[3]};
+ controller_connect(d); controller_publish(d);
+}
+static void hidpad_attach(hid_pad *hid) {
+ DMController *d=[DMController new]; d->generic=hid;
+ d.name=@(hid->name); d.model=[@"HID / " stringByAppendingString:d.name];
+ controller_load_map(d); [g_devices addObject:d]; hidpad_read(hid);
+}
+static void hidpad_detach(hid_pad *hid) {
+ DMController *d=controller_for_hid(hid); if(!d) return;
+ controller_disconnect(d); d->generic=NULL; [g_devices removeObject:d];
+ controller_panel_refresh();
+}
+static int32_t controller_axis(float v) { return (int32_t)(fmaxf(-1, fminf(1, v)) * DM_STICK_MAX); }
+// Main's split Joy-Con decoder keeps each half sideways, with the shared
+// registry owning its slot, mappings and focus gate alongside Steam and GC.
+static DMController *controller_for_joycon(joycon_pad *pad) {
+ for(DMController *d in g_devices) if(d->joycon==pad) return d;
+ return nil;
+}
+static void joycon_read(joycon_pad *pad) {
+ DMController *d=controller_for_joycon(pad); if(!d) return;
+ d->input=(steam_state){.buttons=(uint32_t)pad->st.buttons,.lx=controller_axis(pad->st.sx),.ly=controller_axis(pad->st.sy)};
+ controller_publish(d);
+}
+static void joycon_read_motion(joycon_pad *pad, const uint8_t *rep, size_t len) {
+ DMController *d=controller_for_joycon(pad);
+ if(!d || !g_focus || d->slot<0 || !d->gyro_enabled) return;
+ const char *e=getenv("DM_MOTION"); if(e && !atoi(e)) return;
+ pro_motion_sample samples[3];
+ int n=joycon_motion_decode(&pad->motion,pad->st.pid,rep,len,now_ns(),samples);
+ for(int i=0;i<n;i++) dm_motion_set_hid(g_merge ? 0 : d->slot,samples[i].acc,samples[i].rot,samples[i].ns);
+}
+static void joycon_attach(joycon_pad *pad) {
+ DMController *d=[DMController new]; d->joycon=pad;
+ d.name=@(pad->name); d.model=[@"Nintendo / " stringByAppendingString:d.name];
+ controller_load_map(d); [g_devices addObject:d]; controller_connect(d); joycon_read(pad);
+}
+static void joycon_detach(joycon_pad *pad) {
+ DMController *d=controller_for_joycon(pad); if(!d) return;
+ controller_disconnect(d); d->joycon=NULL; [g_devices removeObject:d]; controller_panel_refresh();
+}
+static void joycon_home_changed(void) { if(controller_listening()) front_home_poll(); }
+static void joycon_haptics_sync(GCController *gone) {
+ if(!g_joycon_split) return;
+ GCController *pair=nil;
+ for(GCController *c in GCController.controllers) if(c!=gone && joycon_is_gc_controller(c) && c.haptics) { pair=c; break; }
+ if(g_merge) {
+ DMController *route=g_merge_haptics_source;
+ if(route && route->joycon) dm_haptics_apple_controller(0,pair);
+ return;
+ }
+ for(DMController *d in g_devices) if(d->joycon && d->slot>=0)
+ dm_haptics_apple_controller_locality(d->slot,pair,d->joycon->st.pid==JOYCON_PID_L ? GCHapticsLocalityLeftHandle : GCHapticsLocalityRightHandle);
+}
+static void controller_read_gc(DMController *d, id<GCDevicePhysicalInputState> state) {
+ // A native event's source HID is already published. Scan at admission,
+ // after that event exists, so notification/enumeration order cannot let a
+ // Triton profile take a native slot before its interface is claimed.
+ if(d->slot<0 && !steam_discover()) return;
+ // Seizing a HID stops new native events, but macOS can retain its profile
+ // and cached buttons. Never allocate a player from that cached snapshot.
+ if (state.lastEventTimestamp <= d->gc_not_before) return;
+ uint32_t b = 0;
+ #define K(name, n) if (state.buttons[name].pressedInput.pressed) b |= 1u << n
+ // Normalize Nintendo labels before the shared button map, as on iOS.
+ if (dm_pad_labelled(d.controller)) { K(GCInputButtonA,0); K(GCInputButtonB,1); K(GCInputButtonX,2); K(GCInputButtonY,3); }
+ else { K(GCInputButtonB,0); K(GCInputButtonA,1); K(GCInputButtonY,2); K(GCInputButtonX,3); }
+ K(GCInputLeftThumbstickButton,4); K(GCInputRightThumbstickButton,5);
+ K(GCInputLeftShoulder,6); K(GCInputRightShoulder,7); K(GCInputLeftTrigger,8); K(GCInputRightTrigger,9);
+ K(GCInputButtonMenu,10); K(GCInputButtonOptions,11);
+ id<GCDirectionPadElement> pad=state.dpads[GCInputDirectionPad];
+ if(pad.left.pressed) b|=DM_BTN_LEFT; if(pad.up.pressed) b|=DM_BTN_UP;
+ if(pad.right.pressed) b|=DM_BTN_RIGHT; if(pad.down.pressed) b|=DM_BTN_DOWN;
+ K(GCInputXboxPaddleOne,16); K(GCInputXboxPaddleTwo,17);
+ K(GCInputXboxPaddleThree,18); K(GCInputXboxPaddleFour,19);
+ K(GCInputBackLeftButton(0),16); K(GCInputBackRightButton(0),17);
+ K(GCInputBackLeftButton(1),18); K(GCInputBackRightButton(1),19);
+ K(GCInputLeftPaddle,16); K(GCInputRightPaddle,17);
+ K(GCInputDualShockTouchpadButton,21);
+ K(GCInputButtonHome,22); K(GCInputButtonShare,23);
+ #undef K
+ id<GCDirectionPadElement> left=state.dpads[GCInputLeftThumbstick], right=state.dpads[GCInputRightThumbstick];
+ d->input = (steam_state){.buttons=b, .lx=controller_axis(left.xAxis.value), .ly=controller_axis(left.yAxis.value),
+ .rx=controller_axis(right.xAxis.value), .ry=controller_axis(right.yAxis.value)};
+ if(d->slot<0) {
+ if(!b && abs(d->input.lx)<4096 && abs(d->input.ly)<4096 && abs(d->input.rx)<4096 && abs(d->input.ry)<4096) return;
+ controller_connect(d);
+ if(d->slot>=0) steam_native_admission();
+ }
+ if(!controller_listening()) d->input=(steam_state){0}; // joining in the mapping panel is allowed
+ else if(d->slot>=0) front_home_poll();
+ controller_publish(d);
+}
+static void controller_gate_gc(DMController *d) {
+ // Use GameController's own clock; its epoch is deliberately unspecified.
+ id<GCDevicePhysicalInputState> initial=[d.controller.input capture];
+ d->gc_not_before=initial.lastEventTimestamp+initial.lastEventLatency;
+}
+static DMController *controller_add_gc(GCController *c) {
+ DMController *d = [DMController new]; d.controller = c;
+ d.name = c.vendorName ?: @"Game Controller";
+ d.model = [NSString stringWithFormat:@"%@ / %@", d.name, c.productCategory ?: @"Extended Gamepad"];
+ controller_load_map(d); [g_devices addObject:d];
+ for (NSString *button in @[GCInputButtonHome, GCInputButtonShare])
+ c.physicalInputProfile.buttons[button].preferredSystemGestureState = GCSystemGestureStateDisabled;
+ c.input.queue = dispatch_get_main_queue();
+ controller_gate_gc(d);
+ __weak DMController *weak = d;
+ c.extendedGamepad.buttonHome.pressedChangedHandler = ^(GCControllerButtonInput *button, float value, BOOL down) {
+ (void)button; (void)value; (void)down;
+ DMController *pad=weak;
+ if(pad && controller_listening()) {
+ if(pad->slot<0) controller_read_gc(pad,[pad.controller.input capture]);
+ else front_home_poll();
+ }
+ };
+ c.input.elementValueDidChangeHandler = ^(id<GCDevicePhysicalInput> input, id<GCPhysicalInputElement> el) {
+ (void)el; DMController *pad=weak; if (pad) controller_read_gc(pad,[input capture]);
+ };
+ return d;
+}
+static void controllers_reconcile(NSArray<GCController *> *now) {
+ for (DMController *d in g_devices.copy) if (d.controller && (![now containsObject:d.controller] || (g_joycon_split && joycon_is_gc_controller(d.controller)))) {
+ d.controller.extendedGamepad.buttonHome.pressedChangedHandler = nil;
+ d.controller.input.elementValueDidChangeHandler = nil; controller_disconnect(d); [g_devices removeObject:d];
+ }
+ for(DMController *d in g_devices) if(d->device) {
+ if(d->connected) { BOOL opening=d->slot<0; controller_connect(d); if(opening) steam_keepalive(d); }
+ else controller_disconnect(d);
+ }
+ for (GCController *c in now) if (c.extendedGamepad && !(g_joycon_split && joycon_is_gc_controller(c))) {
+ BOOL found=NO; for (DMController *d in g_devices) if (d.controller == c) found=YES;
+ if (!found) controller_add_gc(c);
+ }
+ controller_pro_changed();
+ controller_panel_refresh();
+}
+static void controllers_changed(GCController *gone) {
+ // Native notifications can precede the manager's asynchronous HID callback.
+ // Claim new interfaces synchronously before arming ANY new native profile.
+ steam_discover();
+ NSMutableArray<GCController *> *now=[GCController.controllers mutableCopy]; if(gone) [now removeObject:gone];
+ controllers_reconcile(now);
+ joycon_haptics_sync(gone);
+ hidpad_retry();
+}
+
+// SDL's Triton protocol, using macOS IOHID directly: no external driver/library.
+// Prefer direct Triton input so its touchpads/IMU are available even when the
+// GameController profile exposes only standard buttons. Exclusive ownership
+// prevents duplicate native events without guessing identity from model names.
+static IOHIDManagerRef g_hid;
+// A native collection and the vendor-report collection can be siblings. Their
+// opens commit together; suppression handles never receive protocol callbacks.
+@interface DMSteamHID : NSObject {
+@public
+ IOHIDDeviceRef device;
+ uint64_t registry_id;
+ int product;
+ BOOL protocol, native, gamepad, opened;
+}
+@property NSString *group;
+@property DMController *raw;
+@end
+@implementation DMSteamHID
+- (void)dealloc { if(device) CFRelease(device); }
+@end
+static NSMutableDictionary<NSNumber *,DMSteamHID *> *g_steam_hids;
+static NSMutableSet<NSString *> *g_steam_fallback;
+static NSMutableSet<NSNumber *> *g_steam_attempted;
+static long hid_number(IOHIDDeviceRef device, CFStringRef key) {
+ CFTypeRef v = IOHIDDeviceGetProperty(device, key); long n = -1;
+ if (v && CFGetTypeID(v) == CFNumberGetTypeID()) CFNumberGetValue(v, kCFNumberLongType, &n);
+ return n;
+}
+static void steam_keepalive(DMController *d) {
+ if (!d->device || d->slot < 0) return;
+ // Temporary lizard-mode off, refreshed every three seconds. Firmware's
+ // watchdog restores desktop behavior after this process exits (as in SDL).
+ uint8_t feature[64] = {1, 0x87, 3, 9, 0, 0};
+ IOReturn r = steam_write(d->device, kIOHIDReportTypeFeature, 1, feature, sizeof feature);
+ uint8_t imu[64]; steam_imu_report(imu,d->gyro_enabled);
+ IOReturn motion=steam_write(d->device,kIOHIDReportTypeFeature,1,imu,sizeof imu);
+ if(r==kIOReturnSuccess) r=motion;
+ if (r != kIOReturnSuccess && !d->feature_warning) {
+ fprintf(stderr, "[RED] Steam Controller feature report failed (0x%x); quit Steam if it owns this device\n", r); d->feature_warning=YES;
+ }
+}
+static void steam_report(void *context, IOReturn result, void *sender, IOHIDReportType type, uint32_t reportID, uint8_t *bytes, CFIndex length) {
+ (void)sender; (void)type; (void)reportID;
+ DMController *d = (__bridge DMController *)context;
+ if (result != kIOReturnSuccess) { d->connected=NO; controller_disconnect(d); controllers_changed(nil); return; }
+ if (length < 0) return;
+ steam_state state; int event = steam_decode(bytes, (size_t)length, &state);
+ if (event == -1) { d->connected=NO; controller_disconnect(d); controllers_changed(nil); }
+ else if (event > 0) {
+ BOOL newConnection=!d->connected; d->connected=YES;
+ if(newConnection) controllers_changed(nil);
+ if(d->slot<0) return;
+ if (event == 1) {
+ uint32_t changed=d->quit_buttons ^ state.buttons;
+ d->quit_buttons=state.buttons;
+ if(controller_listening()) {
+ d->input = state;
+ if(changed & ((1u<<22)|DM_BTN_A|DM_BTN_B)) front_home_poll();
+ if(g_focus && d->gyro_enabled && pad_motion_update(&d->motion,state.tick,state.tick_us,state.acc,state.gyro)) { d->motion_at=controller_now(); controller_publish_motion(d); }
+ }
+ controller_publish(d);
+ }
+ }
+}
+static uint64_t steam_registry_id(IOHIDDeviceRef device) {
+ uint64_t id=0; IORegistryEntryGetRegistryEntryID(IOHIDDeviceGetService(device),&id); return id;
+}
+static NSString *steam_group(IOHIDDeviceRef device, int pid, long interface) {
+ // USB's registry topology distinguishes controllers without model names or
+ // serial guesses. Puck ports 2..5 are independent controllers on one USB
+ // device, so use their interface ancestor, not the receiver's identity.
+ BOOL puck=pid==0x1304 || pid==0x1305;
+ io_registry_entry_t entry=IOHIDDeviceGetService(device);
+ IOObjectRetain(entry);
+ for(int depth=0; entry && depth<64; depth++) {
+ if(IOObjectConformsTo(entry,puck ? "IOUSBHostInterface" : "IOUSBHostDevice")) {
+ uint64_t id=0; IORegistryEntryGetRegistryEntryID(entry,&id); IOObjectRelease(entry);
+ return id ? [NSString stringWithFormat:@"usb:%llu",(unsigned long long)id] : nil;
+ }
+ io_registry_entry_t parent=IO_OBJECT_NULL;
+ IORegistryEntryGetParentEntry(entry,kIOServicePlane,&parent);
+ IOObjectRelease(entry); entry=parent;
+ }
+ if(entry) IOObjectRelease(entry);
+ // Bluetooth has no USB ancestor. Only use the OS's explicit physical ID;
+ // a generic parent can be shared by unrelated devices or split collections.
+ CFTypeRef value=IOHIDDeviceGetProperty(device,CFSTR(kIOHIDPhysicalDeviceUniqueIDKey));
+ if(value && CFGetTypeID(value)==CFStringGetTypeID() && CFStringGetLength(value))
+ return [NSString stringWithFormat:@"hid:%d:%@:%ld",pid,(__bridge NSString *)value,puck ? interface : -1];
+ return nil;
+}
+static BOOL steam_protocol(IOHIDDeviceRef device, BOOL *complete) {
+ CFArrayRef elements=IOHIDDeviceCopyMatchingElements(device,NULL,kIOHIDOptionsTypeNone);
+ if(!elements) { *complete=NO; return NO; }
+ uint64_t bits[3]={0};
+ for(id value in (__bridge NSArray *)elements) {
+ IOHIDElementRef element=(__bridge IOHIDElementRef)value;
+ IOHIDElementType type=IOHIDElementGetType(element);
+ if(type<kIOHIDElementTypeInput_Misc || type>kIOHIDElementTypeInput_ScanCodes) continue;
+ uint32_t report=IOHIDElementGetReportID(element);
+ int i=report==0x42 ? 0 : report==0x45 ? 1 : report==0x47 ? 2 : -1;
+ if(i>=0) bits[i]+=(uint64_t)IOHIDElementGetReportSize(element)*(IOHIDElementIsArray(element) ? IOHIDElementGetReportCount(element) : 1);
+ }
+ CFRelease(elements);
+ // The decoder needs 46 bytes including the report ID. A standard gamepad
+ // collection is suppression-only unless it actually advertises that state.
+ return bits[0]>=45*8 || bits[1]>=45*8 || bits[2]>=45*8;
+}
+static DMSteamHID *steam_identify(IOHIDDeviceRef device, BOOL *complete) {
+ int vid=(int)hid_number(device,CFSTR(kIOHIDVendorIDKey)), pid=(int)hid_number(device,CFSTR(kIOHIDProductIDKey));
+ if(vid<0 || pid<0) { *complete=NO; return nil; }
+ if(vid!=0x28de || (pid!=0x1302 && pid!=0x1303 && pid!=0x1304 && pid!=0x1305)) return nil;
+ uint64_t id=steam_registry_id(device);
+ if(!id) { *complete=NO; return nil; }
+ if(g_steam_hids[@(id)]) return g_steam_hids[@(id)];
+ long interface=-1;
+ CFTypeRef property=IORegistryEntrySearchCFProperty(IOHIDDeviceGetService(device),kIOServicePlane,CFSTR("bInterfaceNumber"),kCFAllocatorDefault,kIORegistryIterateRecursively|kIORegistryIterateParents);
+ if(property) { if(CFGetTypeID(property)==CFNumberGetTypeID()) CFNumberGetValue(property,kCFNumberLongType,&interface); CFRelease(property); }
+ long page=hid_number(device,CFSTR(kIOHIDPrimaryUsagePageKey)), usage=hid_number(device,CFSTR(kIOHIDPrimaryUsageKey));
+ if(page<0 || usage<0) { *complete=NO; return nil; }
+ BOOL gamepad=page==kHIDPage_GenericDesktop && (usage==kHIDUsage_GD_GamePad || usage==kHIDUsage_GD_Joystick);
+ BOOL unknown_interface=interface<0 && (pid==0x1304 || pid==0x1305);
+ if(unknown_interface && !gamepad) { *complete=NO; return nil; }
+ BOOL native=[GCController supportsHIDDevice:device];
+ BOOL report=steam_protocol(device,complete);
+ if(unknown_interface && report) { *complete=NO; return nil; }
+ BOOL protocol=steam_device(vid,pid,(int)interface) && report;
+ // An unsupported standard gamepad collection may be a sibling of the
+ // Triton protocol too: include it in the same ownership transaction.
+ if(!protocol && !native && !gamepad) return nil;
+ DMSteamHID *hid=[DMSteamHID new]; hid->device=(IOHIDDeviceRef)CFRetain(device);
+ hid->registry_id=id; hid->product=pid; hid->protocol=protocol; hid->native=native; hid->gamepad=gamepad;
+ hid.group=unknown_interface ? nil : steam_group(device,pid,interface);
+ if(!hid.group) fprintf(stderr,"[RED] Steam Controller HID has no stable physical identity; retaining fallback input.\n");
+ return hid;
+}
+static void steam_close(DMSteamHID *hid) {
+ if(!hid->opened) return;
+ DMController *d=hid.raw;
+ if(d) {
+ IOHIDDeviceRegisterInputReportCallback(hid->device,d->report,sizeof d->report,NULL,NULL);
+ IOHIDDeviceUnscheduleFromRunLoop(hid->device,CFRunLoopGetMain(),kCFRunLoopCommonModes);
+ controller_disconnect(d); [g_devices removeObject:d]; hid.raw=nil;
+ }
+ IOHIDDeviceClose(hid->device,kIOHIDOptionsTypeNone); hid->opened=NO;
+}
+static NSDictionary<NSString *,NSMutableArray<DMSteamHID *> *> *steam_groups(void) {
+ NSMutableDictionary *groups=[NSMutableDictionary dictionary];
+ for(DMSteamHID *hid in g_steam_hids.allValues) if(hid.group) {
+ if(!groups[hid.group]) groups[hid.group]=[NSMutableArray array];
+ [groups[hid.group] addObject:hid];
+ }
+ return groups;
+}
+static void steam_claim(NSString *key, NSArray<DMSteamHID *> *group) {
+ if([g_steam_fallback containsObject:key]) return;
+ DMSteamHID *protocol=nil; int nprotocol=0;
+ for(DMSteamHID *hid in group) if(hid->protocol) { protocol=hid; ++nprotocol; }
+ // Wait for a raw sibling during enumeration. If a native event is admitted
+ // first, steam_native_admission freezes that group in native fallback.
+ if(!nprotocol) return;
+ // Unknown multiple protocol endpoints cannot safely select an output route.
+ BOOL failed=nprotocol!=1, claimed=NO;
+ for(DMSteamHID *hid in group) if(!failed && !hid->opened) {
+ [g_steam_attempted addObject:@(hid->registry_id)];
+ IOReturn r=IOHIDDeviceOpen(hid->device,kIOHIDOptionsTypeSeizeDevice);
+ if(r!=kIOReturnSuccess) {
+ fprintf(stderr,"[RED] cannot exclusively open Steam Controller (0x%x); native fallback retained. Quit Steam, check Input Monitoring permissions, then reconnect.\n",r);
+ failed=YES;
+ } else { hid->opened=YES; claimed=YES; }
+ }
+ if(failed) {
+ // Roll back only this controller's group, never another Puck port.
+ for(DMSteamHID *hid in group) steam_close(hid);
+ [g_steam_fallback addObject:key]; return;
+ }
+ if(!claimed) return;
+ // Established routes passed their own admission scan. Preserve their slot,
+ // held input and rumble; gate only queued input in unadmitted profiles.
+ for(DMController *pad in g_devices) if(pad.controller && pad->slot<0) controller_gate_gc(pad);
+ if(protocol.raw) return;
+ DMController *d=[DMController new]; d->device=(IOHIDDeviceRef)CFRetain(protocol->device); d->registry_id=protocol->registry_id;
+ d.name=@"Steam Controller (2026)"; d.model=@"Valve Triton";
+ controller_load_map(d); [g_devices addObject:d]; protocol.raw=d;
+ IOHIDDeviceRegisterInputReportCallback(d->device,d->report,sizeof d->report,steam_report,(__bridge void *)d);
+ IOHIDDeviceScheduleWithRunLoop(d->device,CFRunLoopGetMain(),kCFRunLoopCommonModes);
+}
+static void steam_native_admission(void) {
+ for(NSString *key in steam_groups()) {
+ BOOL raw=NO;
+ for(DMSteamHID *hid in g_steam_hids.allValues) if([hid.group isEqual:key] && hid.raw) raw=YES;
+ if(!raw) [g_steam_fallback addObject:key];
+ }
+}
+static BOOL steam_discover(void) {
+ if(!g_hid) return YES; // DM_STEAM_HID=0 leaves GameController in charge.
+ if(!g_steam_hids) g_steam_hids=[NSMutableDictionary dictionary];
+ if(!g_steam_fallback) g_steam_fallback=[NSMutableSet set];
+ CFMutableDictionaryRef match=IOServiceMatching("IOHIDDevice");
+ if(!match) return NO;
+ ((__bridge NSMutableDictionary *)match)[@kIOHIDVendorIDKey]=@0x28de;
+ io_iterator_t iterator=IO_OBJECT_NULL;
+ if(IOServiceGetMatchingServices(kIOMainPortDefault,match,&iterator)!=KERN_SUCCESS) return NO;
+ if(!iterator) return YES;
+ BOOL complete=YES;
+ NSMutableArray<DMSteamHID *> *found=[NSMutableArray array];
+ io_service_t service;
+ while((service=IOIteratorNext(iterator))) {
+ IOHIDDeviceRef device=IOHIDDeviceCreate(kCFAllocatorDefault,service);
+ if(device) { DMSteamHID *hid=steam_identify(device,&complete); if(hid) [found addObject:hid]; CFRelease(device); }
+ else complete=NO;
+ IOObjectRelease(service);
+ }
+ if(!IOIteratorIsValid(iterator)) complete=NO;
+ IOObjectRelease(iterator);
+ if(!complete) return NO; // no partial ownership transaction
+ for(DMSteamHID *hid in found) g_steam_hids[@(hid->registry_id)]=hid;
+ NSMutableSet *unknown=[NSMutableSet set];
+ for(DMSteamHID *hid in g_steam_hids.allValues) if(!hid.group && (hid->native || hid->gamepad)) [unknown addObject:@(hid->product)];
+ NSDictionary *groups=steam_groups();
+ BOOL native_safe=YES;
+ for(NSString *key in groups) {
+ NSArray<DMSteamHID *> *group=groups[key];
+ if([unknown containsObject:@(group.firstObject->product)]) {
+ BOOL opened=NO; for(DMSteamHID *hid in group) if(hid->opened) opened=YES;
+ // Missing identity may describe a sibling with asymmetric metadata.
+ // Never claim another compatible group behind native fallback. If
+ // it appeared after a raw claim, preserve active players and defer
+ // new native admission until the ambiguity is gone.
+ if(opened) native_safe=NO; else [g_steam_fallback addObject:key];
+ } else steam_claim(key,group);
+ }
+ return native_safe;
+}
+// Called before generic HID opens a device. A late generic callback must not
+// pre-open a Triton sibling non-exclusively or create a second player for it.
+static int hidpad_available(IOHIDDeviceRef device) {
+ if(g_joycon_split && joycon_is_pid(hid_number(device,CFSTR(kIOHIDVendorIDKey)),hid_number(device,CFSTR(kIOHIDProductIDKey)))) return 0;
+ if(!g_hid) return 1; // explicit direct-HID opt-out retains generic fallback
+ long vid=hid_number(device,CFSTR(kIOHIDVendorIDKey)), pid=hid_number(device,CFSTR(kIOHIDProductIDKey));
+ if(vid!=0x28de || (pid!=0x1302 && pid!=0x1303 && pid!=0x1304 && pid!=0x1305)) return 1;
+ if(!steam_discover()) return 0;
+ BOOL complete=YES; DMSteamHID *hid=steam_identify(device,&complete);
+ if(!complete || !hid || hid->protocol) return 0;
+ if(!hid.group) return 1; // discovery already excluded conflicting raw owners
+ for(DMSteamHID *peer in g_steam_hids.allValues) if([peer.group isEqual:hid.group] && peer->opened) return 0;
+ // As for a native GC event, admitting fallback freezes this physical group
+ // until unplug. A protocol collection arriving later cannot steal it.
+ [g_steam_fallback addObject:hid.group];
+ return 1;
+}
+static void steam_added(void *context, IOReturn result, void *sender, IOHIDDeviceRef device) {
+ (void)context; (void)sender; (void)device; if(result!=kIOReturnSuccess) return;
+ controllers_changed(nil);
+}
+static void steam_removed(void *context, IOReturn result, void *sender, IOHIDDeviceRef device) {
+ (void)context; (void)result; (void)sender;
+ uint64_t id=steam_registry_id(device);
+ DMSteamHID *removed=g_steam_hids[@(id)];
+ if(removed) {
+ NSString *key=removed.group;
+ steam_close(removed); [g_steam_hids removeObjectForKey:@(id)];
+ // Losing either half invalidates this raw route. Do not seize a late
+ // replacement behind native input; wait for the whole group to unplug.
+ if(key) {
+ BOOL remains=NO;
+ for(DMSteamHID *hid in g_steam_hids.allValues) if([hid.group isEqual:key]) { steam_close(hid); remains=YES; }
+ if(remains) [g_steam_fallback addObject:key]; else [g_steam_fallback removeObject:key];
+ }
+ }
+ [g_steam_attempted removeObject:@(id)];
+ controllers_changed(nil); controller_panel_refresh();
+}
+
+// Shared standard buttons; model-specific extra inputs. Physical labels avoid label ambiguity.
+static NSArray<NSString *> *source_names(void) {
+ return @[@"East (right face)", @"South (bottom face)", @"North (top face)", @"West (left face)",
+ @"Left stick press", @"Right stick press", @"Left shoulder", @"Right shoulder", @"Left trigger", @"Right trigger",
+ @"Menu / Start", @"View / Select", @"D-pad left", @"D-pad up", @"D-pad right", @"D-pad down",
+ @"L4 / Paddle 1", @"R4 / Paddle 2", @"L5 / Paddle 3", @"R5 / Paddle 4", @"Left pad click", @"Right pad click", @"Guide / Home", @"Quick Access / Share"];
+}
+@interface DMControllerPanel : NSObject
+@property NSPanel *panel;
+@property NSPopUpButton *devices;
+@property NSMutableArray<NSPopUpButton *> *buttons;
+@property NSArray<DMController *> *choices;
+@property NSMutableArray<NSPopUpButton *> *pads;
+@property NSButton *gyro;
+@property NSButton *recenter;
+@property NSButton *importLegacy;
+@property NSTextField *note;
+@property NSMutableArray<NSButton *> *presets;
+@property DMController *selected;
+- (void)refresh;
+@end
+static DMControllerPanel *g_panel;
+@implementation DMControllerPanel
+- (void)show:(id)sender {
+ (void)sender;
+ controller_reload_maps();
+ for(DMController *d in g_devices) controller_publish(d);
+ if (!self.panel) {
+ self.panel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0,0,520,770) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:NO];
+ self.panel.title = @"Controller Mapping"; self.panel.releasedWhenClosed = NO;
+ NSView *v = self.panel.contentView;
+ self.devices = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(20,720,480,30)];
+ self.devices.target=self; self.devices.action=@selector(selectDevice:); [v addSubview:self.devices];
+ self.note=[NSTextField wrappingLabelWithString:@""];
+ self.note.frame=NSMakeRect(20,657,480,57); [v addSubview:self.note];
+ self.importLegacy=[NSButton buttonWithTitle:@"Import previous mapping for this model" target:self action:@selector(importPrevious:)];
+ self.importLegacy.frame=NSMakeRect(20,620,480,30); [v addSubview:self.importLegacy];
+ self.pads=[NSMutableArray array];
+ for(int i=0;i<2;i++) {
+ NSTextField *label=[NSTextField labelWithString:i ? @"Right trackpad" : @"Left trackpad"];
+ label.frame=NSMakeRect(20,586-i*32,180,24); [v addSubview:label];
+ NSPopUpButton *mode=[[NSPopUpButton alloc] initWithFrame:NSMakeRect(255,582-i*32,235,28)];
+ [mode addItemsWithTitles:@[@"Off",@"D-pad",@"Left stick",@"Right stick",@"Switch touchscreen"]];
+ mode.tag=i; mode.target=self; mode.action=@selector(mapPad:); [v addSubview:mode]; [self.pads addObject:mode];
+ }
+ self.gyro=[NSButton checkboxWithTitle:@"Motion controls" target:self action:@selector(mapGyro:)];
+ self.gyro.frame=NSMakeRect(20,510,220,28); [v addSubview:self.gyro];
+ self.recenter=[NSButton buttonWithTitle:@"Recenter gyro" target:self action:@selector(recenterGyro:)];
+ self.recenter.frame=NSMakeRect(255,510,235,28); [v addSubview:self.recenter];
+ NSScrollView *scroll = [[NSScrollView alloc] initWithFrame:NSMakeRect(20,65,480,425)]; scroll.hasVerticalScroller=YES;
+ NSView *rows = [[NSView alloc] initWithFrame:NSMakeRect(0,0,455,DM_PAD_BUTTONS*32)];
+ self.buttons = [NSMutableArray array];
+ NSArray *targets = @[@"Unassigned", @"A", @"B", @"X", @"Y", @"Left stick press", @"Right stick press", @"L", @"R", @"ZL", @"ZR", @"+", @"-", @"D-pad left", @"D-pad up", @"D-pad right", @"D-pad down", @"Shake"];
+ for (int i=0; i<DM_PAD_BUTTONS; i++) {
+ CGFloat y=(DM_PAD_BUTTONS-i-1)*32;
+ NSTextField *label=[NSTextField labelWithString:source_names()[i]]; label.frame=NSMakeRect(0,y+4,230,24); [rows addSubview:label];
+ NSPopUpButton *button=[[NSPopUpButton alloc] initWithFrame:NSMakeRect(235,y,210,28)];
+ [button addItemsWithTitles:targets]; button.tag=i; button.target=self; button.action=@selector(mapButton:);
+ [rows addSubview:button]; [self.buttons addObject:button];
+ }
+ scroll.documentView=rows; [v addSubview:scroll];
+ [scroll.contentView scrollToPoint:NSMakePoint(0, rows.frame.size.height-scroll.contentSize.height)];
+ self.presets=[NSMutableArray array];
+ for (int i=0; i<2; i++) {
+ NSButton *preset=[NSButton buttonWithTitle:i ? @"Xbox Labels" : @"Nintendo Positions" target:self action:@selector(preset:)];
+ preset.frame=NSMakeRect(20+i*245,18,235,32); preset.tag=i; [v addSubview:preset]; [self.presets addObject:preset];
+ }
+ [self.panel center];
+ }
+ [self refresh]; [self.panel makeKeyAndOrderFront:nil];
+}
+- (void)refresh {
+ if (!self.panel) return;
+ NSMutableArray *choices=[NSMutableArray array]; for (DMController *d in g_devices) if (d->slot>=0) [choices addObject:d];
+ self.choices=choices;
+ if (![choices containsObject:self.selected]) self.selected=choices.firstObject;
+ [self.devices removeAllItems];
+ for (DMController *d in choices) [self.devices addItemWithTitle:[NSString stringWithFormat:@"Player %d: %@", g_merge ? 1 : d->slot+1, d.name]];
+ if (!choices.count) [self.devices addItemWithTitle:@"Connect a controller and press a button to configure it"];
+ else [self.devices selectItemAtIndex:[choices indexOfObject:self.selected]];
+ self.note.stringValue=g_map_fixed ? @"Standard buttons are fixed by the launch environment or env.txt for this run. Extra inputs remain configurable for this model." : input_preferences_enabled() ? @"Standard button choices apply to every controller for this game and are shared with launchers. Extra inputs, trackpads and motion are saved per model." : @"Saved choices are disabled. Changes apply only to this session. Standard buttons apply to every controller; extra inputs apply to this model.";
+ self.importLegacy.hidden=!g_legacy_maps[self.selected.model ?: @""];
+ self.importLegacy.enabled=self.selected && !g_map_fixed;
+ for(NSButton *preset in self.presets) preset.enabled=self.selected && !g_map_fixed;
+ BOOL triton=[self.selected.model isEqual:@"Valve Triton"];
+ for(int i=0;i<2;i++) { [self.pads[i] selectItemAtIndex:self.selected ? self.selected->pad_mode[i] : PAD_OFF]; self.pads[i].enabled=triton; }
+ self.gyro.enabled=triton; self.gyro.state=self.selected && self.selected->gyro_enabled ? NSControlStateValueOn : NSControlStateValueOff;
+ self.recenter.enabled=triton && self.selected->gyro_enabled;
+ for (int i=0; i<DM_PAD_BUTTONS; i++) {
+ int n=self.selected ? self.selected->map[i] : -1;
+ [self.buttons[i] selectItemAtIndex:n==63 ? 17 : n+1]; self.buttons[i].enabled=self.selected && (i>=IM_BUTTONS || !g_map_fixed);
+ }
+}
+- (void)selectDevice:(id)sender { (void)sender; NSInteger n=self.devices.indexOfSelectedItem; if(n>=0 && n<(NSInteger)self.choices.count) self.selected=self.choices[n]; [self refresh]; }
+- (void)apply:(BOOL)saved {
+ if (!saved) {
+ NSAlert *alert=[NSAlert new]; alert.messageText=@"Controller mapping could not be saved"; alert.informativeText=@"The mapping works for this session. Check the app log and available disk space."; [alert runModal];
+ }
+ for (DMController *d in g_devices) {
+ controller_publish(d);
+ }
+ [self refresh];
+}
+- (void)mapButton:(NSPopUpButton *)sender {
+ if (!self.selected || self.selected->slot<0) return;
+ NSInteger n=sender.indexOfSelectedItem; int target=n==17 ? 63 : (int)n-1;
+ if(sender.tag<IM_BUTTONS) [self apply:controller_set_button((int)sender.tag,target)];
+ else { self.selected->map[sender.tag]=target; [self apply:controller_save_map(self.selected)]; }
+}
+- (void)mapPad:(NSPopUpButton *)sender { if(self.selected) { self.selected->pad_mode[sender.tag]=(int)sender.indexOfSelectedItem; [self apply:controller_save_map(self.selected)]; } }
+- (void)mapGyro:(NSButton *)sender {
+ if(!self.selected) return;
+ self.selected->gyro_enabled=sender.state==NSControlStateValueOn;
+ BOOL ok=controller_save_map(self.selected);
+ for(DMController *d in g_devices) if([d.model isEqual:self.selected.model]) { controller_reset_motion(d); controller_attach_motion(d); steam_keepalive(d); }
+ [self apply:ok];
+}
+- (void)recenterGyro:(id)sender { (void)sender; if(self.selected) { controller_reset_motion(self.selected); controller_attach_motion(self.selected); } }
+- (void)preset:(NSButton *)sender {
+ if(!self.selected || g_map_fixed) return;
+ int map[DM_PAD_BUTTONS]; pad_physical_default(map,(int)sender.tag);
+ for(int i=0;i<IM_BUTTONS;i++) g_button_map.to[i]=(int8_t)map[i];
+ [self apply:controller_save_buttons()];
+}
+- (void)importPrevious:(id)sender {
+ (void)sender; if(!self.selected || g_map_fixed) return;
+ BOOL ok=controller_import_map(self.selected);
+ for(DMController *d in g_devices) if([d.model isEqual:self.selected.model]) { controller_reset_motion(d); controller_attach_motion(d); steam_keepalive(d); }
+ [self apply:ok];
+}
+@end
+static void controller_panel_refresh(void) { [g_panel refresh]; }
+NSMenu *front_controllers_menu(void) {
+ if (!g_panel) g_panel=[DMControllerPanel new];
+ NSMenu *menu=[[NSMenu alloc] initWithTitle:@"Controllers"];
+ NSMenuItem *item=[menu addItemWithTitle:@"Button Mapping…" action:@selector(show:) keyEquivalent:@""];
+ item.target=g_panel; return menu;
+}
+void front_controllers_start(void) {
+ g_devices=[NSMutableArray array]; g_maps=[NSMutableDictionary dictionary];
+ g_controls_domain=input_preferences_domain(); controller_reload_maps();
+ NSString *root=getenv("DM_ROOT") ? @(getenv("DM_ROOT")) : [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"org.nxnative.controllers"];
+ g_legacy_maps=[NSDictionary dictionaryWithContentsOfFile:[root stringByAppendingPathComponent:@"controllers.plist"]];
+ g_merge=getenv("DM_PAD_MERGE") && atoi(getenv("DM_PAD_MERGE"));
+ static const char keyboard=0;
+ const char *keyboard_player=getenv("DM_KBD_PLAYER");
+ if (!g_merge && keyboard_player && !strcmp(keyboard_player,"own")) pad_slot_take(&g_slots,&keyboard,"keyboard");
+ // Independent devices are essential: the manager must not pre-open an
+ // interface non-exclusively before steam_attach claims it exclusively.
+ const char *steam_hid=getenv("DM_STEAM_HID");
+ if (!(steam_hid && !strcmp(steam_hid,"0"))) {
+ g_steam_attempted=[NSMutableSet set];
+ g_hid=IOHIDManagerCreate(kCFAllocatorDefault,kIOHIDManagerOptionIndependentDevices);
+ NSMutableArray *matches=[NSMutableArray array];
+ for (NSNumber *pid in @[@0x1302,@0x1303,@0x1304,@0x1305]) [matches addObject:@{@kIOHIDVendorIDKey:@0x28de,@kIOHIDProductIDKey:pid}];
+ IOHIDManagerSetDeviceMatchingMultiple(g_hid,(__bridge CFArrayRef)matches);
+ IOHIDManagerRegisterDeviceMatchingCallback(g_hid,steam_added,NULL); IOHIDManagerRegisterDeviceRemovalCallback(g_hid,steam_removed,NULL);
+ IOHIDManagerScheduleWithRunLoop(g_hid,CFRunLoopGetMain(),kCFRunLoopCommonModes);
+ IOReturn r=IOHIDManagerOpen(g_hid,kIOHIDOptionsTypeNone);
+ if(r!=kIOReturnSuccess) fprintf(stderr,"[RED] Steam Controller HID access unavailable (0x%x); check macOS Input Monitoring permissions\n",r);
+ NSTimer *timer=[NSTimer timerWithTimeInterval:3 repeats:YES block:^(NSTimer *t) { (void)t; for (DMController *d in g_devices) steam_keepalive(d); }];
+ [NSRunLoop.mainRunLoop addTimer:timer forMode:NSRunLoopCommonModes];
+ }
+ for (NSNotificationName name in @[GCControllerDidConnectNotification,GCControllerDidDisconnectNotification])
+ [NSNotificationCenter.defaultCenter addObserverForName:name object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) { controllers_changed([n.name isEqual:GCControllerDidDisconnectNotification] ? n.object : nil); }];
+ joycon_start();
+ controllers_changed(nil);
+ hidpad_start();
+ dm_motion_pro_start(controller_pro_changed);
+ dm_motion_pro_active(g_focus);
+ for(NSNotificationName name in @[NSApplicationDidResignActiveNotification,NSApplicationDidBecomeActiveNotification])
+ [NSNotificationCenter.defaultCenter addObserverForName:name object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) { front_controllers_focus([n.name isEqual:NSApplicationDidBecomeActiveNotification]); }];
+}
diff --git a/dm/host/dm_input.h b/dm/host/dm_input.h
index fc987df..fa51e93 100644
--- a/dm/host/dm_input.h
+++ b/dm/host/dm_input.h
@@ -19,7 +19,7 @@ uint64_t dm_input_samples(void); // Cumulative number of times the game has sa
uint64_t dm_cheats_keys(void);
// Physical controller path (Mac / iOS GameController): stored separately from keyboard / touch and scripted input (DM_KEYS / DM_CTL); when the game reads player 1,
// buttons are ORed bitwise and each stick axis takes whichever source is deflected more. All 0 when no controller is connected.
-// dm_pad_set is player 1's controller (DM_BTN_SHAKE counts there only); dm_pad_set_player sets player n + 1's, which the game reads on its own npad (hle_hid.c) while
+// dm_pad_set is player 1's controller (DM_BTN_SHAKE follows each controller's player); dm_pad_set_player sets player n + 1's, which the game reads on its own npad (hle_hid.c) while
// dm_pad_players has its bit set; a player whose npad the game does not support (SetSupportedNpadIdType) feeds player 1 instead, so a one-player game sees every controller
#define DM_PLAYERS 8 // npads No1..No8; player 1 is the Handheld npad in handheld mode (DM_OPMODE=0)
void dm_pad_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry);
@@ -40,6 +40,10 @@ uint32_t dm_player_npad(int player); // the npad id the game reads player p + 1
// axis the most deflected one, plus the presses since the last peek (a tap between two peeks is reported once). Any thread
void dm_input_hold(int on);
void dm_input_peek(uint64_t *buttons, int32_t axes[4]);
+// Physical six-axis samples in Switch coordinates: G (gravity is -Z at rest),
+// revolutions/s, accumulated revolutions, and a column-major direction matrix.
+typedef struct { float acc[3], gyro[3], angle[3], dir[9]; } dm_motion;
+void dm_pad_motion(int player, const dm_motion *sample); // NULL clears history on disconnect/recenter
// Optional diagnostic DM_HID_RECEIPT_LOG=<writable JSONL path>: received samples of real GetNpadState returns.
// Fields read_start_ns/time_ns use the same host now_ns(); the front-end publish window must use the same helper, and a read interval that spans a publish must not be force-matched.
diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m
index cfb6dcb..041bf07 100644
--- a/dm/host/front_mac.m
+++ b/dm/host/front_mac.m
@@ -7,7 +7,7 @@
// safe mode, values, details and the import of cheat files (see the code below).
// Key map (Nintendo layout): WASD left stick, arrow keys D-pad (with Shift held: the right stick, for the camera), J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;
// DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).
-// Controllers: face buttons as on the iPhone, by position (right A, bottom B, top X, left Y) or on a Nintendo pad by its labels (pad_apple.h), shoulders L R, triggers ZL ZR, Menu + Options −, both sticks and their presses.
+// Controllers: Nintendo positions by default, or labels on Nintendo pads (pad_apple.h). Shared mappings and per-model extras live in controllers_mac.m.
// Each controller is a player of its own (local co-op): the first one connected is player 1, together with the keyboard, the next player 2, and so on up to 8 (pad_slots.h);
// DM_PAD_MERGE=1 merges every controller into player 1 instead, DM_KBD_PLAYER=own makes the keyboard player 1 on its own, with the controllers from player 2 on.
#import <Cocoa/Cocoa.h>
@@ -18,14 +18,9 @@
#include "dm_input.h"
#include "front.h"
#include "hle.h"
-#include "pad_slots.h"
-#include "input_map.h"
+#include "controllers_mac.h"
+#include "input_preferences_mac.h"
#include "haptics_apple.h"
-#include "motion_apple.h"
-#include "motion_pro_mac.h"
-#include "pad_apple.h"
-#include "pad_hid_mac.h"
-#include "pad_joycon_mac.h"
#include "home_quit.h"
#include "home_quit_mac.h"
#include <signal.h>
@@ -34,7 +29,7 @@
static CAMetalLayer *g_layer;
static uint64_t g_btn;
-static int8_t g_shift_fn[IM_KEYS]; // a D-pad key pressed with Shift held: the right-stick function it holds until released, plus 1 (0: none)
+static key_state g_key_state;
static int g_input_on = 1; // main thread: the game window is key, so its keyboard, mouse and controllers reach the game (input_release / input_resume)
void *front_metal_layer(void) { return (__bridge void *)g_layer; }
@@ -118,7 +113,7 @@ void front_screen_match(int fps) {
}
// The pointer hides on game input while it is over the picture of the active game window (issue #675): AppKit shows it again when the mouse moves, input_release when
// the window loses focus. The title bar, other windows and other apps keep theirs; the mouse is the touch screen (DmGameView), and moving it shows the pointer
-static void cursor_hide_for_input(void) {
+void front_game_input(void) {
if (!g_win.isKeyWindow || !NSApp.isActive) return;
NSView *v = g_win.contentView;
if (NSPointInRect([v convertPoint:g_win.mouseLocationOutsideOfEventStream fromView:nil], v.bounds)) [NSCursor setHiddenUntilMouseMoves:YES];
@@ -139,125 +134,13 @@ static int fn_shortcut(NSEvent *e) {
}
static void on_key(NSEvent *e, int down) {
if (!g_input_on) return;
- unsigned short c = e.keyCode;
- int f = key_map_fn(&g_keys, c); if (f < 0) return;
- // A D-pad key pressed with Shift held is the matching right-stick direction until it is released; without Shift, the D-pad. The keyboard had no right stick: a 3D game's camera
- // could be turned only with a controller (Donkey Kong Bananza)
- if (c < IM_KEYS) {
- if (down && f >= 12 && f <= 15 && (e.modifierFlags & NSEventModifierFlagShift)) g_shift_fn[c] = (int8_t)((f == 12 ? IM_RLEFT : f == 13 ? IM_RUP : f == 14 ? IM_RRIGHT : IM_RDOWN) + 1);
- if (g_shift_fn[c]) { int rf = g_shift_fn[c] - 1; g_held_fn = down ? (g_held_fn | 1u << rf) : (g_held_fn & ~(1u << rf)); if (!down) g_shift_fn[c] = 0; push(); return; }
- }
- g_held_fn = down ? (g_held_fn | 1u << f) : (g_held_fn & ~(1u << f));
+ int f = key_map_fn(&g_keys, e.keyCode); if (f < 0) return;
+ g_held_fn = key_state_event(&g_key_state, &g_keys, e.keyCode, down, (e.modifierFlags & NSEventModifierFlagShift) != 0);
g_btn = (g_held_fn & 0xffff) | (g_held_fn >> IM_SHAKE & 1 ? DM_BTN_SHAKE : 0);
- if (down) cursor_hide_for_input(); // a key the game takes
+ if (down) front_game_input();
push();
}
-// Physical controllers (GameController) go to dm_pad_set_player, mapped as the iPhone's (DmGamepad.m read_pad, same layout); player 1's is ORed with the keyboard, a stick takes
-// whichever is deflected more (hle_hid.c). DM_KEYS uses player 1's path, so player 1's controller touched during a script takes it over.
-// Players: every controller with an extended gamepad profile holds a slot (pad_slots.h: player 1 first, a reconnected controller gets its player back), and hle_hid.c reports
-// player n on its own npad while the slot is held (dm_pad_players). A one-player game that supports only No1 / Handheld still sees every controller as player 1 (hle_hid.c).
-// With DM_PAD_MERGE=1 every controller is player 1, as before (the last one moved wins; when the last one goes away its buttons and sticks are released)
-static pad_slots g_slots;
-static GCController *g_held[DM_PLAYERS]; // the controller of each slot, kept alive while it holds it (the slot table keys on its pointer)
-static int g_merge, g_kbd_own;
-static pad_map g_padmap; // DM_PAD_MAP (input_map.h): what each button sends, applied to every controller
-static int32_t pad_axis(float v) { return (int32_t)(fmaxf(-1.f, fminf(1.f, v)) * DM_STICK_MAX); }
-// A controller's state for player p, GameController or raw HID: a pressed button or a stick past 15% hides the pointer (cursor_hide_for_input), a resting stick's drift does not
-static void pad_set(int p, uint64_t m, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
- m = pad_map_apply(&g_padmap, m); // DM_PAD_MAP
- const int32_t dead = DM_STICK_MAX * 15 / 100;
- if (m || abs(lx) > dead || abs(ly) > dead || abs(rx) > dead || abs(ry) > dead) cursor_hide_for_input();
- dm_pad_set_player(p, m, lx, ly, rx, ry);
-}
-static void hq_poll(void);
-static home_quit g_hq; // the Home button's hold and quit prompt (home_quit.h): while the prompt is open the controllers' input goes to it, not to the game
-static void pad_read(GCExtendedGamepad *g) {
- if (!g_input_on) return;
- hq_poll(); if (hq_blocks_input(g_hq.phase)) return;
- int p = g_merge ? 0 : pad_slot_of(&g_slots, (__bridge const void *)g.controller); if (p < 0) return;
- dm_haptics_apple_controller(p, g.controller);
- uint64_t m = dm_pad_face(g); // by position, a Nintendo pad by its labels
- #define K(btn, bit) if (btn.isPressed) m |= bit
- K(g.leftShoulder, DM_BTN_L); K(g.rightShoulder, DM_BTN_R); K(g.leftTrigger, DM_BTN_ZL); K(g.rightTrigger, DM_BTN_ZR);
- K(g.buttonMenu, DM_BTN_PLUS); K(g.buttonOptions, DM_BTN_MINUS); K(g.leftThumbstickButton, DM_BTN_LS); K(g.rightThumbstickButton, DM_BTN_RS); // nil on pads without them: not pressed
- K(g.dpad.left, DM_BTN_LEFT); K(g.dpad.up, DM_BTN_UP); K(g.dpad.right, DM_BTN_RIGHT); K(g.dpad.down, DM_BTN_DOWN);
- #undef K
- pad_set(p, m, pad_axis(g.leftThumbstick.xAxis.value), pad_axis(g.leftThumbstick.yAxis.value), pad_axis(g.rightThumbstick.xAxis.value), pad_axis(g.rightThumbstick.yAxis.value));
-}
-// Home and Capture: without this macOS takes them as system gestures (Home opens the Games app). Capture has no function in the host, Home quits when it is held (hq_poll).
-// macOS 27 respects the claim when the Home button setting for apps lets the app decide (hq_log_setting names it in the log)
-static void pad_keep_system_buttons(GCController *c) {
- for (NSString *b in @[GCInputButtonHome, GCInputButtonShare]) c.physicalInputProfile.buttons[b].preferredSystemGestureState = GCSystemGestureStateDisabled;
- c.extendedGamepad.buttonHome.pressedChangedHandler = ^(GCControllerButtonInput *b, float v, BOOL down) { (void)b; (void)v; (void)down; if (g_input_on) hq_poll(); };
-}
-static const char *pad_name(GCController *c) { return c.vendorName.UTF8String ?: "?"; }
-static void npad_name(int p, char *out, size_t cap) { uint32_t id = dm_player_npad(p); if (id == 0x20) snprintf(out, cap, "handheld"); else snprintf(out, cap, "%u", id); }
-static void pro_players_changed(GCController *gone) {
- int count = 0, player = -1;
- for (GCController *c in GCController.controllers) if (c != gone && c.extendedGamepad && [c.productCategory isEqualToString:@"Switch Pro Controller"]) {
- count++; player = g_merge ? 0 : pad_slot_of(&g_slots, (__bridge const void *)c);
- }
- dm_motion_pro_players(count, player);
-}
-static void pro_devices_changed(void) { pro_players_changed(nil); }
-static int gc_pad_used(GCController *c) {
- return c && c.extendedGamepad && !(g_joycon_split && joycon_is_gc_controller(c));
-}
-static void joycon_haptics_sync(GCController *gone) {
- if (!g_joycon_split) return;
- GCController *jc = nil;
- for (GCController *c in GCController.controllers) if (c != gone && joycon_is_gc_controller(c) && c.haptics) { jc = c; break; }
- if (g_merge) { if (g_joycons && jc) dm_haptics_apple_controller(0, jc); return; }
- for (joycon_pad *d = g_joycons; d; d = d->next) {
- int p = pad_slot_of(&g_slots, d); if (p < 0) continue;
- GCHapticsLocality loc = d->st.pid == JOYCON_PID_L ? GCHapticsLocalityLeftHandle : GCHapticsLocalityRightHandle;
- dm_haptics_apple_controller_locality(p, jc, loc);
- }
-}
-// DM_PAD_MERGE: whether a controller still plays player 1 (gone: one just removed, not counted), a GameController one or a raw HID pad (pad_hid_mac.h, pad_joycon_mac.h)
-static int merge_pads_left(GCController *gone) {
- if (g_hidpads || g_joycons) return 1;
- for (GCController *c in GCController.controllers) if (gc_pad_used(c) && c != gone) return 1;
- return 0;
-}
-// Called at start and on every connect / disconnect (gone: the controller that was just removed, nil on a connect)
-static void pads_changed(GCController *gone) {
- if (g_merge) {
- int any = 0;
- for (GCController *c in GCController.controllers) if (gc_pad_used(c) && c != gone) {
- any = 1; pad_keep_system_buttons(c); c.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *g, GCControllerElement *el) { (void)el; pad_read(g); };
- dm_motion_attach(c, 0); // every controller is player 1: the last one moved drives its six-axis sensor
- pad_read(c.extendedGamepad);
- }
- if (gone) dm_motion_detach(gone, 0);
- if (!any) { if (!g_hidpads && !g_joycons) dm_pad_set(0, 0, 0, 0, 0); if (!g_joycons) dm_haptics_apple_controller(0, nil); } // a raw HID pad still plays player 1 (pad_hid_mac.h)
- joycon_haptics_sync(gone);
- pro_players_changed(gone);
- return;
- }
- NSArray<GCController *> *now = GCController.controllers; char nb[16];
- for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p] && (g_held[p] == gone || ![now containsObject:g_held[p]] || !gc_pad_used(g_held[p]))) {
- npad_name(p, nb, sizeof nb); LOG("controller '%s' disconnected: player %d (npad %s) is free", pad_name(g_held[p]), p + 1, nb);
- g_held[p].extendedGamepad.valueChangedHandler = nil;
- dm_motion_detach(g_held[p], p);
- dm_haptics_apple_controller(p, nil);
- pad_slot_free(&g_slots, (__bridge const void *)g_held[p]); g_held[p] = nil;
- dm_pad_set_player(p, 0, 0, 0, 0, 0); // nothing stays pressed
- }
- for (GCController *c in now) if (gc_pad_used(c) && c != gone && pad_slot_of(&g_slots, (__bridge const void *)c) < 0) {
- int p = pad_slot_take(&g_slots, (__bridge const void *)c, pad_name(c));
- if (p < 0) { LOG("controller '%s' connected: all %d players are taken, not used", pad_name(c), DM_PLAYERS); continue; }
- g_held[p] = c; pad_keep_system_buttons(c);
- c.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *g, GCControllerElement *el) { (void)el; pad_read(g); };
- dm_motion_attach(c, p);
- npad_name(p, nb, sizeof nb); LOG("controller '%s' connected: player %d (npad %s)%s", pad_name(c), p + 1, nb, c.motion.hasRotationRate ? ", with motion (gyro)" : "");
- pad_read(c.extendedGamepad);
- }
- dm_pad_players(pad_slot_mask(&g_slots));
- joycon_haptics_sync(gone);
- pro_players_changed(gone);
-}
// Display sleep: macOS counts keyboard and mouse input as user activity, not a controller's, so in controller-only play the display dims and locks; the latency
// activity in front_run keeps the system awake, not the display. While the game window is key the display stays awake (NSActivityIdleDisplaySleepDisabled);
// losing focus or being minimized lets it sleep again. An explicit lock or sleep is not held off, and no input is synthesized
@@ -267,111 +150,27 @@ static void display_awake(int on) {
g_display_activity = [NSProcessInfo.processInfo beginActivityWithOptions:NSActivityIdleDisplaySleepDisabled reason:@"NxNative active game window"];
else if (!on && g_display_activity) { [NSProcessInfo.processInfo endActivity:g_display_activity]; g_display_activity = nil; }
}
-// Focus: a window that is no longer key sees no key-up, mouse-up or controller release, so whatever is held when it loses focus (another app, the text box, minimized) would
-// stay pressed in the game. The front end releases only what it pressed itself: scripted buttons and sticks have their own path, and the touch is also DM_KEYS / DM_CTL's (hle_hid.c).
-// Out of focus a controller's changes are ignored, so back in focus each controller is read as it is now (a button still held, a stick still deflected)
-static int g_mouse_down; // the mouse holds the touch (DmGameView)
-// Nothing the controllers pressed stays pressed (focus lost, the Home quit prompt open)
-static void pads_release(void) {
- if (g_merge) { if (merge_pads_left(nil)) dm_pad_set(0, 0, 0, 0, 0); return; }
- for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p]) dm_pad_set_player(p, 0, 0, 0, 0, 0);
- for (hid_pad *d = g_hidpads; d; d = d->next) { int p = pad_slot_of(&g_slots, d); if (p >= 0) dm_pad_set_player(p, 0, 0, 0, 0, 0); }
- for (joycon_pad *d = g_joycons; d; d = d->next) { int p = pad_slot_of(&g_slots, d); if (p >= 0) dm_pad_set_player(p, 0, 0, 0, 0, 0); }
-}
-// Each controller read as it is now (focus back, the Home quit prompt closed)
-static void pads_reread(void) {
- if (g_merge) { for (GCController *c in GCController.controllers) if (gc_pad_used(c)) pad_read(c.extendedGamepad); }
- else for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p].extendedGamepad) pad_read(g_held[p].extendedGamepad);
- for (hid_pad *d = g_hidpads; d; d = d->next) hidpad_read(d);
- for (joycon_pad *d = g_joycons; d; d = d->next) joycon_read(d);
-}
+// Release only front-end input when the game window loses focus. Controller
+// and mouse ownership lives in controllers_mac.m, keyboard state stays here.
static void hq_close(void);
static void input_release(void) {
- hq_close(); // the prompt or the hold indicator, if one is up: the Games app the system opens for Home takes the focus too
[NSCursor setHiddenUntilMouseMoves:NO];
display_awake(0);
g_input_on = 0;
- dm_motion_pro_active(0);
- for (joycon_pad *d = g_joycons; d; d = d->next) {
- d->motion = (pro_motion){0};
- int p = g_merge ? 0 : pad_slot_of(&g_slots, d);
- if (p >= 0) dm_motion_clear_hid(p);
- }
- g_btn = 0; g_held_fn = 0; memset(g_shift_fn, 0, sizeof g_shift_fn); push();
- if (g_mouse_down) { g_mouse_down = 0; dm_touch_set(NULL, 0); }
- pads_release();
+ key_state_clear(&g_key_state); g_btn = 0; g_held_fn = 0; push();
+ front_controllers_window(0);
+ hq_close();
}
static void input_resume(void) {
display_awake(1);
g_input_on = 1;
- dm_motion_pro_active(1);
- pads_reread();
-}
-// Raw HID gamepads (pad_hid_mac.h): a player slot each, as a GameController controller, named by the device's product name
-static void hidpad_read(hid_pad *d) {
- if (!g_input_on || hq_blocks_input(g_hq.phase)) return;
- int p = g_merge ? 0 : pad_slot_of(&g_slots, d); if (p < 0) return;
- int32_t s[4]; pad_hid_sticks(&d->st, s);
- pad_set(p, pad_hid_buttons(&d->st), s[0], s[1], s[2], s[3]);
-}
-static void hidpad_attach(hid_pad *d) {
- int p = g_merge ? 0 : pad_slot_take(&g_slots, d, d->name); char nb[16];
- if (p < 0) { LOG("controller '%s' (HID) connected: all %d players are taken, not used", d->name, DM_PLAYERS); return; }
- npad_name(p, nb, sizeof nb); LOG("controller '%s' (HID) connected: player %d (npad %s)", d->name, p + 1, nb);
- if (!g_merge) dm_pad_players(pad_slot_mask(&g_slots)); // merged, every controller is player 1, as pads_changed has it
- hidpad_read(d);
-}
-static void hidpad_detach(hid_pad *d) { // d is already off g_hidpads
- if (g_merge) { // as pads_changed: released when the last controller goes away
- LOG("controller '%s' (HID) disconnected", d->name);
- if (!merge_pads_left(nil)) dm_pad_set(0, 0, 0, 0, 0);
- return;
- }
- int p = pad_slot_free(&g_slots, d); char nb[16]; if (p < 0) return;
- npad_name(p, nb, sizeof nb); LOG("controller '%s' (HID) disconnected: player %d (npad %s) is free", d->name, p + 1, nb);
- dm_pad_set_player(p, 0, 0, 0, 0, 0); // nothing stays pressed
- dm_pad_players(pad_slot_mask(&g_slots));
-}
-// Split Joy-Con sideways controllers (pad_joycon_mac.h, DM_JOYCON_SPLIT=1): each half takes a player slot of its own
-static void joycon_read(joycon_pad *d) {
- if (!g_input_on || hq_blocks_input(g_hq.phase)) return;
- int p = g_merge ? 0 : pad_slot_of(&g_slots, d); if (p < 0) return;
- pad_set(p, d->st.buttons, pad_axis(d->st.sx), pad_axis(d->st.sy), 0, 0);
-}
-static void joycon_read_motion(joycon_pad *d, const uint8_t *rep, size_t len) {
- if (!g_input_on || hq_blocks_input(g_hq.phase)) return;
- const char *e = getenv("DM_MOTION"); if (e && !atoi(e)) return;
- int p = g_merge ? 0 : pad_slot_of(&g_slots, d); if (p < 0) return;
- pro_motion_sample samples[3];
- int n = joycon_motion_decode(&d->motion, d->st.pid, rep, len, now_ns(), samples);
- for (int i = 0; i < n; i++) dm_motion_set_hid(p, samples[i].acc, samples[i].rot, samples[i].ns);
-}
-static void joycon_attach(joycon_pad *d) {
- int p = g_merge ? 0 : pad_slot_take(&g_slots, d, d->name); char nb[16];
- if (p < 0) { LOG("controller '%s' (split Joy-Con) connected: all %d players are taken, not used", d->name, DM_PLAYERS); return; }
- npad_name(p, nb, sizeof nb); LOG("controller '%s' (split Joy-Con) connected: player %d (npad %s), with motion (gyro) and rumble", d->name, p + 1, nb);
- if (!g_merge) dm_pad_players(pad_slot_mask(&g_slots));
- joycon_haptics_sync(nil);
- joycon_read(d);
-}
-static void joycon_detach(joycon_pad *d) {
- if (g_merge) {
- LOG("controller '%s' (split Joy-Con) disconnected", d->name);
- if (!g_joycons) { dm_motion_clear_hid(0); dm_haptics_apple_controller(0, nil); }
- if (!merge_pads_left(nil)) dm_pad_set(0, 0, 0, 0, 0);
- return;
- }
- int p = pad_slot_free(&g_slots, d); char nb[16]; if (p < 0) return;
- npad_name(p, nb, sizeof nb); LOG("controller '%s' (split Joy-Con) disconnected: player %d (npad %s) is free", d->name, p + 1, nb);
- dm_motion_clear_hid(p);
- dm_haptics_apple_controller(p, nil);
- dm_pad_set_player(p, 0, 0, 0, 0, 0);
- dm_pad_players(pad_slot_mask(&g_slots));
-}
-static void joycon_home_changed(void) { if (g_input_on) hq_poll(); }
+ front_controllers_window(1);
+}
+
// Quit with the Home button (home_quit.h, LNPANDY/NX2Apple#336): held for 2 s it opens the prompt (home_quit_mac.h) over the game's view, A quits through the same path as ⌘Q
// (NSApp terminate, so the save writer and the other exit handlers run as there), B or Home closes it. While the prompt is open the game is told it lost the focus, as the
// Switch's HOME menu does, and gets no controller input or touch; the keyboard and ⌘Q work as always. DM_HOME_QUIT=0 turns it off
+static home_quit g_hq;
static int g_hq_on;
static NSTimer *g_hq_timer; // while Home is held: the time runs on without a button change
static NSView *g_hq_hold, *g_hq_prompt; static CAShapeLayer *g_hq_ring;
@@ -400,20 +199,6 @@ static void hq_log_setting(void) {
}
#endif
}
-static void hq_buttons(int *home, int *a, int *b, GCController **holder) {
- *home = *a = *b = 0;
- for (GCController *c in GCController.controllers) {
- if (!gc_pad_used(c)) continue;
- GCExtendedGamepad *g = c.extendedGamepad; if (!g) continue;
- if (g.buttonHome.isPressed) { *home = 1; if (!*holder) *holder = c; }
- *a |= g.buttonA.isPressed; *b |= g.buttonB.isPressed;
- }
- for (joycon_pad *d = g_joycons; d; d = d->next) {
- if (d->st.home) *home = 1;
- if (d->st.buttons & DM_BTN_A) *a = 1;
- if (d->st.buttons & DM_BTN_B) *b = 1;
- }
-}
static void hq_fade(NSView *v, int in) {
if (!v) return;
if (in) v.alphaValue = 0;
@@ -427,11 +212,10 @@ static void hq_changed(hq_phase was, hq_phase now, GCController *holder) {
NSView *cv = g_win.contentView;
switch (now) {
case HQ_HOLDING:
- g_hq_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer *t) { (void)t; hq_poll(); }];
+ g_hq_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 60 repeats:YES block:^(NSTimer *t) { (void)t; front_home_poll(); }];
break;
case HQ_PROMPT: {
- pads_release(); // nothing the game held stays pressed while the prompt has the controllers
- if (g_mouse_down) { g_mouse_down = 0; dm_touch_set(NULL, 0); }
+ front_controllers_quit_prompt(1);
dm_focus_set(2);
GCExtendedGamepad *g = holder.extendedGamepad;
g_hq_prompt = hq_prompt_view(cv.bounds, @(g_hq_text[HQ_TEXT_TITLE]), @(g_hq_text[HQ_TEXT_NOTE]), @(g_hq_text[HQ_TEXT_QUIT]), @(g_hq_text[HQ_TEXT_CANCEL]),
@@ -445,7 +229,7 @@ static void hq_changed(hq_phase was, hq_phase now, GCController *holder) {
LOG("front end: quit prompt closed, the game goes on");
break;
case HQ_IDLE:
- if (was == HQ_SETTLE) pads_reread(); // the game reads the controllers again, as they are now
+ if (was == HQ_SETTLE) front_controllers_quit_prompt(0); // the game reads the controllers again, as they are now
break;
case HQ_QUIT:
LOG("front end: quit from the Home button prompt");
@@ -453,10 +237,10 @@ static void hq_changed(hq_phase was, hq_phase now, GCController *holder) {
break;
}
}
-static void hq_poll(void) {
- static int busy; if (!g_hq_on || !g_win || busy) return;
+void front_home_poll(void) {
+ static int busy; if (!g_hq_on || !g_win || !g_input_on || busy) return;
busy = 1;
- int home, a, b; GCController *holder = nil; hq_buttons(&home, &a, &b, &holder);
+ int home, a, b; GCController *holder = front_controllers_quit_buttons(&home, &a, &b);
double now = CACurrentMediaTime();
hq_phase was = g_hq.phase, ph = hq_step(&g_hq, now, home, a, b);
if (ph != was) hq_changed(was, ph, holder);
@@ -471,26 +255,8 @@ static void hq_close(void) {
if (g_hq.phase == HQ_IDLE || g_hq.phase == HQ_QUIT) return;
if (g_hq.phase == HQ_PROMPT) LOG("front end: quit prompt closed, the window lost the focus");
hq_cancel(&g_hq); hq_hide_hold(); hq_hide_prompt();
+ front_controllers_quit_prompt(0);
}
-static void pads_start(void) {
- key_map_default(&g_keys); pad_map_default(&g_padmap);
- const char *km = getenv("DM_KEYMAP"), *pm = getenv("DM_PAD_MAP");
- if (km && *km) { int bad = key_map_parse(&g_keys, km); LOG("front end: keyboard map from DM_KEYMAP (%s)%s", km, bad ? ", malformed entries left out" : ""); }
- if (pm && *pm) { int bad = pad_map_parse(&g_padmap, pm); LOG("front end: controller buttons from DM_PAD_MAP (%s)%s", pm, bad ? ", malformed entries left out" : ""); }
- const char *e = getenv("DM_PAD_MERGE"); g_merge = e && atoi(e);
- e = getenv("DM_KBD_PLAYER"); g_kbd_own = !g_merge && e && !strcmp(e, "own");
- static const char kbd = 0;
- if (g_kbd_own) pad_slot_take(&g_slots, &kbd, "keyboard"); // holds player 1 for good
- LOG("front end: %s", g_merge ? "every controller is player 1 (DM_PAD_MERGE)" : g_kbd_own ? "the keyboard is player 1, each controller a player of its own from player 2 on (DM_KBD_PLAYER=own)"
- : "each controller is a player of its own, the keyboard plays with player 1");
- hq_start();
- joycon_start();
- pads_changed(nil);
- hq_log_setting();
- dm_motion_pro_start(pro_devices_changed);
- hidpad_start();
-}
-
// Mouse as a single-point touchscreen (front.h dm_touch_set): left button down / drag = finger 0, release = lifted. The content view takes the clicks,
// not a window-wide event monitor, so clicks on the title bar, the window buttons and the resize edges still reach AppKit.
// The picture's width / height (front.h front_picture_shape; 16:9 until the first present), which the present fits into the view
@@ -507,9 +273,9 @@ - (void)mouseDragged:(NSEvent *)e {
double a = g_picture_aspect; if (w / h > a) w = h * a; else h = w / a; // the centered picture the present fits into the view (16:9, or a taller one under DM_SCREEN_ASPECT)
double x0 = (b.width - w) / 2, y0 = (b.height - h) / 2;
dm_touch t = {0, (float)fmin(fmax((p.x - x0) / w, 0), 0.999), (float)fmin(fmax(1 - (p.y - y0) / h, 0), 0.999)}; // The AppKit view origin is at bottom left, the touchscreen origin is at top left
- dm_touch_set(&t, 1); g_mouse_down = 1;
+ front_controllers_mouse(&t);
}
-- (void)mouseUp:(NSEvent *)e { (void)e; if (g_mouse_down) { g_mouse_down = 0; dm_touch_set(NULL, 0); } }
+- (void)mouseUp:(NSEvent *)e { (void)e; front_controllers_mouse(NULL); }
// The drawable follows the view in pixels: a layer assigned to a layer-backed view kept the drawable at the first window's 1280x720 in fullscreen too, so the game picture was
// scaled down to it and up again by the compositor
- (void)fitDrawable {
@@ -1458,6 +1224,7 @@ void front_run(void (*guest)(void)) {
dispatch_async(dispatch_get_main_queue(), ^{ [g_cheats_menu showPanel:nil]; });
[[bar addItemWithTitle:@"Window" action:nil keyEquivalent:@""] setSubmenu:wm];
[wm addItemWithTitle:@"Enter Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"].keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagCommand;
+ [[bar addItemWithTitle:@"Controllers" action:nil keyEquivalent:@""] setSubmenu:front_controllers_menu()];
NSApp.mainMenu = bar;
const char *fs = getenv("DM_FULLSCREEN"); // 1 (or any value but 0): start in fullscreen; 0, the settings window's Window, or unset: a window
if (fs && strcmp(fs, "0")) {
@@ -1503,15 +1270,16 @@ void front_run(void (*guest)(void)) {
if (hidden && !over && !armed) show();
else if (!hidden && over && CACurrentMediaTime() - last >= idle) { hidden = 1; [NSCursor hide]; } }];
}
- for (NSNotificationName nm in @[GCControllerDidConnectNotification, GCControllerDidDisconnectNotification])
- [NSNotificationCenter.defaultCenter addObserverForName:nm object:nil queue:NSOperationQueue.mainQueue usingBlock:^(NSNotification *n) {
- GCController *c = n.object; int conn = n.name == GCControllerDidConnectNotification;
- if (g_joycon_split && joycon_is_gc_controller(c)) return;
- if (!c.extendedGamepad || g_merge) LOG("controller %s: %s%s", conn ? "connected" : "disconnected", pad_name(c), c.extendedGamepad ? "" : " (no extended gamepad profile: not used)");
- pads_changed(conn ? nil : c);
- if (conn) hq_log_setting(); }];
dm_haptics_apple_init();
- pads_start();
+ key_map_default(&g_keys);
+ NSString *keys = input_preference_map(input_preferences_domain(), "DM_KEYMAP", 0);
+ if (keys) key_map_parse(&g_keys, keys.UTF8String);
+ hq_start();
+ front_controllers_start();
+ hq_log_setting();
+ [NSNotificationCenter.defaultCenter addObserverForName:GCControllerDidConnectNotification object:nil queue:NSOperationQueue.mainQueue
+ usingBlock:^(NSNotification *n) { (void)n; hq_log_setting(); }];
+ front_controllers_window(win.isKeyWindow && !win.miniaturized);
[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown | NSEventMaskKeyUp handler:^NSEvent *(NSEvent *e) {
if (e.window != win) return e; // Only swallow keys for the game window; other windows such as the software keyboard input box receive typing as usual
if (e.type == NSEventTypeKeyDown && (e.modifierFlags & NSEventModifierFlagCommand)) return e; // ⌘ shortcuts go to the menu; a key released while ⌘ is held still reaches the game, or it would stay pressed
@@ -1592,8 +1360,9 @@ int front_text_input(const char *title, const char *sub, const char *guide, cons
dispatch_sync(dispatch_get_main_queue(), ^{
// The box takes the keyboard and the mouse, so the game window never sees the key-up of the button or the touch-up of the click that opened it: nothing may stay pressed
// while it is up, or the game reads the stuck button / touch the moment the box closes (Stardew Valley's character creation re-opened the keyboard endlessly)
- g_btn = 0; g_held_fn = 0; memset(g_shift_fn, 0, sizeof g_shift_fn); push();
- dm_touch_set(NULL, 0);
+ key_state_clear(&g_key_state); g_btn = 0; g_held_fn = 0; push();
+ front_controllers_modal(1);
+ front_controllers_mouse(NULL);
int min_chars = g_swkbd_min_chars > 0 ? g_swkbd_min_chars : 0;
NSString *info = [NSString stringWithFormat:@"%s%s%s", sub ? sub : "", sub && *sub && guide && *guide ? "\n" : "", guide ? guide : ""];
for (;;) {
@@ -1611,6 +1380,7 @@ int front_text_input(const char *title, const char *sub, const char *guide, cons
// On hardware the applet would not have accepted the shorter text (OK stayed disabled); a game that rejects it re-opens the keyboard for ever, so the box comes back with the rule instead
info = [info stringByAppendingFormat:@"\nAt least %d characters are needed here.", min_chars];
}
+ front_controllers_modal(0);
});
if (!r) return 0;
(void)max_chars; // Truncation is done uniformly in hle_swkbd.c in UTF-16 units
diff --git a/dm/host/haptics_apple.h b/dm/host/haptics_apple.h
index d8ce98f..bd2ef35 100644
--- a/dm/host/haptics_apple.h
+++ b/dm/host/haptics_apple.h
@@ -5,4 +5,14 @@
void dm_haptics_apple_init(void);
void dm_haptics_apple_controller(int player, GCController *controller);
void dm_haptics_apple_controller_locality(int player, GCController *controller, GCHapticsLocality locality);
+// Apply the controller cutoff after converting the game's bands and applying gain.
+float dm_haptics_apple_controller_intensity(float intensity);
+// Native HID alternative. Runs on the adapter's serial queue, refreshed at 40 ms
+// while nonzero; receives zero on route changes/suspend/exit. Owner identifies
+// an unchanged route. Never calls hardware on a guest thread.
+typedef void (^dm_haptics_output)(dm_haptic_state state, float gain);
+void dm_haptics_apple_output(int player, id owner, dm_haptics_output output);
void dm_haptics_apple_shutdown(void);
+
+// Mac game-window/modal gate, independent of application activation.
+void dm_haptics_apple_focus(int active);
diff --git a/dm/host/haptics_apple.m b/dm/host/haptics_apple.m
index ca0414f..849af06 100644
--- a/dm/host/haptics_apple.m
+++ b/dm/host/haptics_apple.m
@@ -40,6 +40,9 @@ - (void)stop;
static NSMutableArray<DmRumbleChannel *> *channels[DM_PLAYERS];
static GCController *controllers[DM_PLAYERS];
static GCHapticsLocality controllerLocalities[DM_PLAYERS];
+static id outputOwners[DM_PLAYERS]; // protected by routeLock
+static dm_haptics_output nativeOutputs[DM_PLAYERS]; // serial queue only
+static uint64_t outputGeneration[DM_PLAYERS];
#if TARGET_OS_IPHONE
static BOOL phoneSupported;
#endif
@@ -71,7 +74,7 @@ static NSTimeInterval now(void) {
// low band at 0.1-0.4 all race long: 0.45 leaves crashes and drifts). The mapping stays linear by default: the opposite need, low levels that
// rotating motors do not render at all (Breath of the Wild's charged attack on an Xbox controller), is open (docs/reference/services.md)
static float rumble_min;
-static float controller_level(float x) {
+float dm_haptics_apple_controller_intensity(float x) {
x = isfinite(x) ? fmaxf(0, fminf(1, x)) : 0;
return x <= rumble_min ? 0 : (x - rumble_min) / (1 - rumble_min);
}
@@ -161,7 +164,7 @@ - (BOOL)startEngine {
return YES;
}
- (void)apply:(dm_haptic_level)level {
- if ([self.target hasPrefix:@"controller"]) level.intensity = controller_level(level.intensity);
+ if ([self.target hasPrefix:@"controller"]) level.intensity = dm_haptics_apple_controller_intensity(level.intensity);
uint64_t silence = ++self.silenceGeneration;
NSError *error = nil;
self.level = level;
@@ -254,8 +257,8 @@ static void ds4_apply(dm_haptic_state s) {
ds4_out *o = &ds4[s.player];
if (!o->dev) return;
const dm_vibration *l = &s.motor[0], *r = &s.motor[1];
- o->motor[0] = (uint8_t)lrintf(controller_level((0.85f * l->amplitude_low + 0.15f * r->amplitude_low) * gain) * 255);
- o->motor[1] = (uint8_t)lrintf(controller_level((0.15f * l->amplitude_high + 0.85f * r->amplitude_high) * gain) * 255);
+ o->motor[0] = (uint8_t)lrintf(dm_haptics_apple_controller_intensity((0.85f * l->amplitude_low + 0.15f * r->amplitude_low) * gain) * 255);
+ o->motor[1] = (uint8_t)lrintf(dm_haptics_apple_controller_intensity((0.15f * l->amplitude_high + 0.85f * r->amplitude_high) * gain) * 255);
if (o->motor[0] == o->sent[0] && o->motor[1] == o->sent[1]) return;
ds4_send(s.player);
}
@@ -308,9 +311,21 @@ static BOOL ds4_route(int p, GCController *controller) {
}
#endif
+static void native_stop(int p) {
+ outputGeneration[p]++;
+ if (nativeOutputs[p]) nativeOutputs[p]((dm_haptic_state){.player=p}, gain);
+}
+static void native_apply(dm_haptic_state s, uint64_t generation) {
+ int p=s.player;
+ if (!nativeOutputs[p] || generation != outputGeneration[p] || s.epoch != dm_haptics_epoch(p)) return;
+ nativeOutputs[p](s,gain);
+ if (s.motor[0].amplitude_low || s.motor[0].amplitude_high || s.motor[1].amplitude_low || s.motor[1].amplitude_high)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 40*NSEC_PER_MSEC),queue,^{ native_apply(s,generation); });
+}
static void apply(dm_haptic_state s) {
dispatch_async(queue, ^{ @autoreleasepool {
if (s.epoch != dm_haptics_epoch(s.player)) return;
+ if (nativeOutputs[s.player]) { native_apply(s,++outputGeneration[s.player]); return; }
NSArray<DmRumbleChannel *> *out = channels[s.player];
#if !TARGET_OS_IPHONE
if ([out.firstObject isKindOfClass:DmDs4Channel.class]) { ds4_apply(s); return; }
@@ -396,11 +411,29 @@ void dm_haptics_apple_controller_locality(int p, GCController *controller, GCHap
if (!queue || p < 0 || p >= DM_PLAYERS) return;
pthread_mutex_lock(&routeLock);
BOOL sameLoc = (controllerLocalities[p] == locality) || (locality && [controllerLocalities[p] isEqualToString:locality]);
- if (controllers[p] != controller || !sameLoc) {
+ if (controllers[p] != controller || !sameLoc || outputOwners[p]) {
controllers[p] = controller;
controllerLocalities[p] = locality;
+ outputOwners[p] = nil;
dm_haptics_route(p, 0); // invalidate queued work before changing hardware
- dispatch_sync(queue, ^{ configure(p, controller, locality); });
+ dispatch_sync(queue, ^{ native_stop(p); nativeOutputs[p]=nil; configure(p, controller, locality); });
+ }
+ pthread_mutex_unlock(&routeLock);
+}
+void dm_haptics_apple_output(int p, id owner, dm_haptics_output output) {
+ if (!queue || p < 0 || p >= DM_PLAYERS) return;
+ if (!owner || !output) { dm_haptics_apple_controller(p,nil); return; }
+ pthread_mutex_lock(&routeLock);
+ if (outputOwners[p] != owner) {
+ outputOwners[p]=owner; controllers[p]=nil; controllerLocalities[p]=nil; dm_haptics_route(p,0);
+ dispatch_sync(queue, ^{
+ native_stop(p);
+ for (DmRumbleChannel *c in channels[p]) [c stop];
+#if !TARGET_OS_IPHONE
+ ds4_release(p);
+#endif
+ channels[p]=[NSMutableArray new]; nativeOutputs[p]=[output copy]; dm_haptics_route(p,1);
+ });
}
pthread_mutex_unlock(&routeLock);
}
@@ -410,10 +443,11 @@ void dm_haptics_apple_controller(int p, GCController *controller) {
static void suspend(unsigned reason, BOOL on) {
dm_haptics_suspend(reason, on);
void (^stop)(void) = ^{
- for (int p = 0; p < DM_PLAYERS; p++) for (DmRumbleChannel *c in channels[p]) [c stop];
+ for (int p = 0; p < DM_PLAYERS; p++) { native_stop(p); for (DmRumbleChannel *c in channels[p]) [c stop]; }
};
if (on) { if (dispatch_get_specific(&queue)) stop(); else dispatch_sync(queue, stop); }
}
+void dm_haptics_apple_focus(int active) { if(queue) suspend(DM_HAPTICS_UNFOCUSED,!active); }
void dm_haptics_apple_shutdown(void) {
if (queue) suspend(DM_HAPTICS_INACTIVE, YES);
}
diff --git a/dm/host/hle_haptics.h b/dm/host/hle_haptics.h
index d808df0..3fb623b 100644
--- a/dm/host/hle_haptics.h
+++ b/dm/host/hle_haptics.h
@@ -6,7 +6,7 @@ typedef struct { float amplitude_low, frequency_low, amplitude_high, frequency_h
typedef struct { int player, motor; dm_vibration value; } dm_vibration_update;
typedef struct { int player; uint64_t epoch; dm_vibration motor[2]; } dm_haptic_state;
typedef struct { float intensity, sharpness; } dm_haptic_level;
-enum { DM_HAPTICS_INACTIVE = 1, DM_HAPTICS_INTERRUPTED = 2 };
+enum { DM_HAPTICS_INACTIVE = 1, DM_HAPTICS_INTERRUPTED = 2, DM_HAPTICS_UNFOCUSED = 4 };
// The sink copies/enqueues each snapshot in order; called under the state lock, it must not reenter.
// No hardware calls on the sending thread. A changed epoch invalidates all older queued snapshots.
diff --git a/dm/host/hle_hid.c b/dm/host/hle_hid.c
index 751b9da..5351ff9 100644
--- a/dm/host/hle_hid.c
+++ b/dm/host/hle_hid.c
@@ -2,7 +2,7 @@
// Generic, game-independent version: player 1 is always connected, as the handheld controller (Npad id 0x20) with DM_OPMODE=0 (handheld), otherwise as the 1P full-key controller (id 0);
// players 2..8 are full-key controllers on No2..No8 (ids 1..7) while the front end reports a controller for them (dm_pad_players; the Mac gives each physical controller a player
// of its own, front_mac.m). A player whose npad the game does not support (SetSupportedNpadIdType) is not reported: in a one-player game it feeds player 1, otherwise it is not used.
-// Six-axis sensor: one per connected controller (two for handheld), at rest lying flat, player 1's shaken side to side while the front end holds DM_BTN_SHAKE (see the six-axis section below).
+// Six-axis sensor: physical motion when supplied by the front end, otherwise at rest lying flat; DM_BTN_SHAKE provides the existing synthetic gesture (see below).
// Vibration follows the player assignments through hle_haptics.c. Mouse and keyboard: not connected; the controller applet reports the connected players with player 1 selected.
#include "hle.h"
#include "hle_haptics.h"
@@ -38,27 +38,29 @@ static _Atomic int64_t g_sampling = 1 << 16; // starts high so the history ent
static uint64_t pack(int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
return (uint64_t)(uint16_t)lx | (uint64_t)(uint16_t)ly << 16 | (uint64_t)(uint16_t)rx << 32 | (uint64_t)(uint16_t)ry << 48;
}
-// Shake (DM_BTN_SHAKE on any player 1 path): whole side-to-side cycles on the guest clock, so the controller always comes back to rest. A press starts a shake (or continues one still
-// finishing), holding keeps shaking, and a release lets the current cycle finish: a tap of one frame is still one whole shake
+// Shake (DM_BTN_SHAKE on any input path): whole side-to-side cycles on the guest clock, so the controller always comes back to rest. A press starts a shake (or continues one still
+// finishing), holding keeps shaking, and a release lets the current cycle finish: a tap of one frame is still one whole shake. Track each controller slot separately; slot 0
+// also includes keyboard / touch and scripted input. Sensor reads route these sources with the same player assignments as buttons and physical motion.
#define SHAKE_HZ 6.0
static const uint64_t SHAKE_CYCLE_NS = (uint64_t)(1e9 / SHAKE_HZ);
-static _Atomic uint64_t g_shake_t0, g_shake_end; // the current shake's start and end; end = UINT64_MAX while held
-static _Atomic int g_shake_on;
-static void shake_note(void) {
- int on = ((atomic_load(&g_btn) | atomic_load(&g_sc_btn) | atomic_load(&g_pad_btn[0])) & DM_BTN_SHAKE) != 0;
- if (atomic_exchange(&g_shake_on, on) == on) return;
+static _Atomic uint64_t g_shake_t0[DM_PLAYERS], g_shake_end[DM_PLAYERS]; // each shake's start and end; end = UINT64_MAX while held
+static _Atomic int g_shake_on[DM_PLAYERS];
+static void shake_note(int p) {
+ uint64_t buttons = atomic_load(&g_pad_btn[p]); if (!p) buttons |= atomic_load(&g_btn) | atomic_load(&g_sc_btn);
+ int on = (buttons & DM_BTN_SHAKE) != 0;
+ if (atomic_exchange(&g_shake_on[p], on) == on) return;
uint64_t t = guest_ns();
- if (on) { if (t >= atomic_load(&g_shake_end)) atomic_store(&g_shake_t0, t); atomic_store(&g_shake_end, UINT64_MAX); }
- else { uint64_t t0 = atomic_load(&g_shake_t0); atomic_store(&g_shake_end, t0 + ((t - t0) / SHAKE_CYCLE_NS + 1) * SHAKE_CYCLE_NS); }
+ if (on) { if (t >= atomic_load(&g_shake_end[p])) atomic_store(&g_shake_t0[p], t); atomic_store(&g_shake_end[p], UINT64_MAX); }
+ else { uint64_t t0 = atomic_load(&g_shake_t0[p]); atomic_store(&g_shake_end[p], t0 + ((t - t0) / SHAKE_CYCLE_NS + 1) * SHAKE_CYCLE_NS); }
}
void dm_input_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
uint64_t old = atomic_exchange(&g_btn, buttons); atomic_fetch_or(&g_latch, buttons & ~old); atomic_fetch_or(&g_peek_latch, buttons & ~old); atomic_store(&g_axes, pack(lx, ly, rx, ry));
- shake_note();
+ shake_note(0);
}
void dm_pad_set_player(int p, uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
if (p < 0 || p >= DM_PLAYERS) return;
uint64_t old = atomic_exchange(&g_pad_btn[p], buttons); atomic_fetch_or(&g_pad_latch[p], buttons & ~old); atomic_fetch_or(&g_peek_latch, buttons & ~old); atomic_store(&g_pad_axes[p], pack(lx, ly, rx, ry));
- if (!p) shake_note();
+ shake_note(p);
}
static int32_t pick(int32_t a, int32_t b);
static int32_t ax(uint64_t v, int i);
@@ -75,7 +77,7 @@ void dm_input_peek(uint64_t *buttons, int32_t axes[4]) {
void dm_pad_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { dm_pad_set_player(0, buttons, lx, ly, rx, ry); }
static void script_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
uint64_t old = atomic_exchange(&g_sc_btn, buttons); atomic_fetch_or(&g_sc_latch, buttons & ~old); atomic_fetch_or(&g_peek_latch, buttons & ~old); atomic_store(&g_sc_axes, pack(lx, ly, rx, ry));
- shake_note();
+ shake_note(0);
}
uint64_t dm_input_samples(void) { return (uint64_t)atomic_load(&g_sampling); }
// DM_KEYS scripted input (for tests): "seconds:key[+key][~hold seconds][*count/interval seconds],...", e.g. "8:A,12:A,15:Down~0.5,16:A+B,40:A*80/2" (A every 2 s from 40 s on, 80 times). Key names A B X Y LS RS L R ZL ZR (plus the sticks LLeft LUp LRight LDown and RLeft RUp RRight RDown) Plus Minus Left Up Right Down, left stick LLeft LUp LRight LDown,
@@ -317,7 +319,10 @@ void dm_pad_players(uint32_t mask) {
mask = (mask | 1u) & ((1u << DM_PLAYERS) - 1);
uint32_t old = atomic_exchange(&g_players, mask);
for (int p = 1; p < DM_PLAYERS; p++) if ((old ^ mask) >> p & 1) {
- if (!(mask >> p & 1)) dm_pad_set_player(p, 0, 0, 0, 0, 0); // a controller that went away leaves nothing pressed
+ if (!(mask >> p & 1)) {
+ dm_pad_set_player(p, 0, 0, 0, 0, 0); // a controller that went away leaves nothing pressed
+ atomic_store(&g_shake_end[p], 0); // discard its finishing cycle and history before the slot can be reused
+ }
if (atomic_load(&g_ids_supported) & id_bit((uint32_t)p)) style_changed((uint32_t)p);
}
note_merged();
@@ -555,18 +560,22 @@ HLE_FORCE("_ZN2nn3hid21ShowControllerSupportEPNS0_27ControllerSupportResultInfoE
typedef struct { int64_t delta_ns, sampling; float acc[3], gyro[3], angle[3], dir[9]; uint32_t attributes, _pad; } SixAxisState;
_Static_assert(sizeof(SixAxisState) == 0x60, "SixAxisState");
enum { SIX_PERIOD_NS = 5000000 };
+enum { MOTION_HISTORY = 64 };
#define SHAKE_G 3.0
#define SHAKE_REV 1.5
-static int shaking(uint64_t t) { return t >= atomic_load(&g_shake_t0) && t < atomic_load(&g_shake_end); }
// Live motion (dm_motion_set: a controller's gyro and accelerometer, front_mac.m / DmGamepad.m through motion_apple.h; dm_motion_set_switch: the iPhone's own, already in the
// Switch frame, DmGamepad.m): while a player's samples keep arriving (within
// MOTION_STALE_NS on the host clock) their six-axis sensor reports them (motion_fusion.h) instead of lying flat; a shake (DM_BTN_SHAKE) still adds its side-to-side acceleration.
// Every history entry is the newest sample, numbered by time. DM_MOTION=0 ignores live motion; DM_MOTION_AXES / DM_MOTION_ACC_SIGN map Apple's axes (motion_fusion.h);
// DM_MOTION_GAIN sets the tilt correction (default 0.5); DM_MOTION_LOG=1 logs player 1's mapped sample once a second, for checking the axes
enum { MOTION_STALE_NS = 300000000 };
-typedef struct { pthread_mutex_t mu; motion_state st; uint64_t last_ns, received_ns, logged; } live_motion;
+typedef struct {
+ pthread_mutex_t mu; motion_state st; uint64_t last_ns, received_ns, logged;
+ dm_motion history[MOTION_HISTORY]; uint64_t time[MOTION_HISTORY], count;
+} live_motion;
static live_motion g_motion[DM_PLAYERS] = {[0 ... DM_PLAYERS - 1] = {.mu = PTHREAD_MUTEX_INITIALIZER}};
static live_motion g_hid_motion[DM_PLAYERS] = {[0 ... DM_PLAYERS - 1] = {.mu = PTHREAD_MUTEX_INITIALIZER}};
+static live_motion g_direct_motion[DM_PLAYERS] = {[0 ... DM_PLAYERS - 1] = {.mu = PTHREAD_MUTEX_INITIALIZER}};
static live_motion g_phone_motion = {.mu = PTHREAD_MUTEX_INITIALIZER};
static pthread_once_t g_motion_once = PTHREAD_ONCE_INIT;
static motion_map g_motion_map; static float g_motion_gain = 0.5f; static int g_motion_off, g_motion_log, g_phone_mode;
@@ -596,7 +605,7 @@ static void motion_set(int p, const float acc[3], const float rot[3], int source
LOG("[hid] motion player 1 (%s): acc %+.2f %+.2f %+.2f G, gyro %+.3f %+.3f %+.3f rev/s (flat and still should read acc 0 0 -1)",
source == 1 ? "phone" : source == 2 ? "controller HID" : "controller", m->st.acc[0], m->st.acc[1], m->st.acc[2], m->st.gyro[0], m->st.gyro[1], m->st.gyro[2]);
}
- m->last_ns = t; m->received_ns = now;
+ m->last_ns = t; m->received_ns = now; m->count = 0;
pthread_mutex_unlock(&m->mu);
}
void dm_motion_set(int p, const float acc[3], const float rot[3]) { motion_set(p, acc, rot, 0, 0); }
@@ -608,45 +617,72 @@ void dm_motion_clear(int p) {
}
void dm_motion_clear_hid(int p) {
if (p < 0 || p >= DM_PLAYERS) return;
- pthread_mutex_lock(&g_hid_motion[p].mu); g_hid_motion[p].last_ns = 0; pthread_mutex_unlock(&g_hid_motion[p].mu);
+ pthread_mutex_lock(&g_hid_motion[p].mu); g_hid_motion[p].last_ns = 0; g_hid_motion[p].count = 0; pthread_mutex_unlock(&g_hid_motion[p].mu);
+}
+// Direct transports may supply their own device-clock integration. Store those samples in
+// the shared HID source so GameController, phone selection and disconnect use one policy.
+void dm_pad_motion(int p, const dm_motion *s) {
+ if (p < 0 || p >= DM_PLAYERS) return;
+ live_motion *m = &g_direct_motion[p];
+ if (!s) { pthread_mutex_lock(&m->mu); m->last_ns = m->count = 0; pthread_mutex_unlock(&m->mu); return; }
+ pthread_once(&g_motion_once, motion_env); if (g_motion_off) return;
+ uint64_t now = now_ns();
+ pthread_mutex_lock(&m->mu);
+ if (!m->last_ns || now - m->received_ns >= 250000000ull) m->count = 0;
+ unsigned i = m->count++ % MOTION_HISTORY;
+ m->history[i] = *s; m->time[i] = guest_ns();
+ m->last_ns = m->received_ns = now;
+ pthread_mutex_unlock(&m->mu);
}
-static uint64_t motion_copy(live_motion *m, motion_state *out) { // copies a source while it is fresh; returns its timestamp
- uint64_t t;
+static uint64_t motion_copy(live_motion *m, uint64_t time, dm_motion *out) {
pthread_mutex_lock(&m->mu);
- t = m->last_ns && now_ns() - m->received_ns <= MOTION_STALE_NS ? m->last_ns : 0;
- if (t) *out = m->st;
+ uint64_t stale = m->count ? 250000000ull : MOTION_STALE_NS;
+ uint64_t t = m->last_ns && now_ns() - m->received_ns < stale ? m->last_ns : 0;
+ if (t && m->count) {
+ // Before the first recorded sample there is no physical state to invent.
+ t = 0;
+ uint64_t n = m->count < MOTION_HISTORY ? m->count : MOTION_HISTORY;
+ for (uint64_t k = 0; k < n; k++) {
+ unsigned i = (m->count - 1 - k) % MOTION_HISTORY;
+ if (m->time[i] <= time) { *out = m->history[i]; t = m->last_ns; break; }
+ }
+ } else if (t) motion_fill(&m->st, out->acc, out->gyro, out->angle, out->dir);
pthread_mutex_unlock(&m->mu);
return t;
}
-static int motion_live(int p, motion_state *out) {
+enum { MOTION_NONE, MOTION_LIVE, MOTION_DIRECT };
+static int physical_motion(int p, uint64_t time, dm_motion *out) {
if (p < 0 || p >= DM_PLAYERS) return 0;
- pthread_once(&g_motion_once, motion_env);
- if (!p && g_phone_mode > 0) return motion_copy(&g_phone_motion, out) != 0;
- // Match the button path: in a one-player game, a controller in another slot also drives player 1.
- uint32_t src = p ? 1u << p : 1u | merged_players(); uint64_t newest = 0;
+ pthread_once(&g_motion_once, motion_env); if (g_motion_off) return 0;
+ if (!p && g_phone_mode > 0) return motion_copy(&g_phone_motion, time, out) != 0;
+ // Match the button path: a one-player game also accepts the other players' controllers.
+ uint32_t src = p ? 1u << p : 1u | merged_players(); uint64_t newest = 0; int selected = MOTION_NONE;
for (int i = 0; i < DM_PLAYERS; i++) if (src >> i & 1) {
- motion_state st; uint64_t t = motion_copy(&g_motion[i], &st);
- if (!t) t = motion_copy(&g_hid_motion[i], &st);
- if (t > newest) { newest = t; *out = st; }
+ dm_motion sample; uint64_t t = motion_copy(&g_motion[i], time, &sample); int kind = MOTION_LIVE;
+ if (!t) {
+ t = motion_copy(&g_hid_motion[i], time, &sample);
+ dm_motion direct; uint64_t d = motion_copy(&g_direct_motion[i], time, &direct);
+ if (d && d >= t) { t = d; sample = direct; kind = MOTION_DIRECT; }
+ }
+ if (t > newest) { newest = t; *out = sample; selected = kind; }
}
- if (newest) return 1;
- return !p && g_phone_mode < 0 && motion_copy(&g_phone_motion, out);
+ if (newest) return selected;
+ return !p && g_phone_mode < 0 && motion_copy(&g_phone_motion, time, out);
}
-static void six_sample_live(SixAxisState *s, int64_t samp, const motion_state *ms, int shakes) {
- memset(s, 0, sizeof *s);
- uint64_t t = (uint64_t)samp * SIX_PERIOD_NS;
- s->delta_ns = SIX_PERIOD_NS; s->sampling = samp; s->attributes = 1;
- motion_fill(ms, s->acc, s->gyro, s->angle, s->dir);
- if (shakes && shaking(t)) s->acc[0] += (float)(SHAKE_G * sin(2 * M_PI * SHAKE_HZ * (double)(t - atomic_load(&g_shake_t0)) / 1e9));
+static int shake_source(int p, uint64_t t) {
+ if (p < 0) return -1;
+ uint32_t candidates = 1u << p; if (!p) candidates |= merged_players();
+ for (int j = 0; j < DM_PLAYERS; j++) if ((candidates >> j & 1) && t >= atomic_load(&g_shake_t0[j]) && t < atomic_load(&g_shake_end[j])) return j;
+ return -1;
}
-static void six_sample(SixAxisState *s, int64_t samp, int shakes) {
+static void six_sample(SixAxisState *s, int64_t samp, int shake) {
memset(s, 0, sizeof *s);
uint64_t t = (uint64_t)samp * SIX_PERIOD_NS;
s->delta_ns = SIX_PERIOD_NS; s->sampling = samp; s->attributes = 1; // IsConnected
s->acc[2] = -1;
double yaw = 0;
- if (shakes && shaking(t)) {
- double ph = 2 * M_PI * SHAKE_HZ * (double)(t - atomic_load(&g_shake_t0)) / 1e9;
+ if (shake >= 0) {
+ double ph = 2 * M_PI * SHAKE_HZ * (double)(t - atomic_load(&g_shake_t0[shake])) / 1e9;
s->acc[0] = (float)(SHAKE_G * sin(ph));
s->gyro[2] = (float)(SHAKE_REV * sin(ph));
yaw = SHAKE_REV / (2 * M_PI * SHAKE_HZ) * (1 - cos(ph)); s->angle[2] = (float)yaw;
@@ -654,25 +690,52 @@ static void six_sample(SixAxisState *s, int64_t samp, int shakes) {
float c = (float)cos(2 * M_PI * yaw), sn = (float)sin(2 * M_PI * yaw);
s->dir[0] = c; s->dir[1] = sn; s->dir[3] = -sn; s->dir[4] = c; s->dir[8] = 1;
}
-// SixAxisSensorHandle: byte 0 the style's bit number, byte 1 the npad id, byte 2 the device (left / right Joy-Con of a pair). The styles made of two Joy-Cons (handheld, dual) have
-// two sensors, the others one. A handle reads as connected while its controller is connected in that style; otherwise its entries are zero (not connected) and the count 0.
-// Only player 1's controller shakes (DM_BTN_SHAKE comes from the keyboard, the iPhone and DM_KEYS, all player 1)
-static int six_connected(uint32_t h) { return (h & 0xff) < 32 && (style_of(h >> 8 & 0xff) >> (h & 0xff) & 1); }
+// SixAxisSensorHandle (libnx _hidGetSixAxisSensorHandles): byte 0 the SDK style index (FullKey 3 .. JoyRight 7), byte 1 the npad id, byte 2 the device, byte 3 reserved.
+// FullKey / Handheld expose one combined sensor (device 2); JoyDual exposes left / right (0 / 1), and single Joy-Cons only their side. A disconnected handle returns zero entries.
+// Mapped Shake follows its controller's player, including controllers merged into player 1 for one-player games.
+static int six_connected(uint32_t h) {
+ unsigned type = h & 0xff, id = h >> 8 & 0xff, device = h >> 16 & 0xff;
+ if (h >> 24 || type < 3 || type > 7 || style_of(id) != (1u << (type - 3))) return 0;
+ return type <= 4 ? device == 2 : type == 5 ? device <= 1 : device == (type == 7);
+}
static int six_states(SixAxisState *out, int n, uint32_t h) {
if (n <= 0) return 0;
if (!six_connected(h)) { memset(out, 0, sizeof *out * (size_t)n); return 0; }
int64_t samp = (int64_t)(guest_ns() / SIX_PERIOD_NS);
- int pl = player_of(h >> 8 & 0xff), shakes = pl == 0;
- motion_state ms;
- if (motion_live(pl, &ms)) { for (int i = 0; i < n; i++) six_sample_live(&out[i], samp - i, &ms, shakes); return n; }
- for (int i = 0; i < n; i++) six_sample(&out[i], samp - i, shakes);
+ int p=player_of(h >> 8 & 0xff);
+ for (int i = 0; i < n; i++) {
+ uint64_t time = (uint64_t)(samp - i) * SIX_PERIOD_NS;
+ int shake = shake_source(p, time);
+ six_sample(&out[i], samp - i, shake);
+ dm_motion m; int source = physical_motion(p,time,&m);
+ // Native/Pro/phone motion keeps upstream's additive Shake. Direct Steam
+ // history retains its complete synthetic cycle, then resumes the physical samples.
+ if (source && (shake < 0 || source == MOTION_LIVE)) {
+ float shake_acc = shake >= 0 ? out[i].acc[0] : 0;
+ memcpy(out[i].acc,m.acc,sizeof m.acc); memcpy(out[i].gyro,m.gyro,sizeof m.gyro);
+ memcpy(out[i].angle,m.angle,sizeof m.angle); memcpy(out[i].dir,m.dir,sizeof m.dir);
+ out[i].acc[0] += shake_acc;
+ }
+ }
return n;
}
-HLE_FORCE("_ZN2nn3hid23GetSixAxisSensorHandlesEPNS0_19SixAxisSensorHandleEiRKjNS_4util10BitFlagSetILi32ENS0_12NpadStyleTagEEE", "six-axis sensor handles: two for handheld / dual Joy-Cons, one otherwise",
+static unsigned six_rest(uint32_t h) {
+ if (!six_connected(h)) return 1;
+ int p=player_of(h >> 8 & 0xff); if (shake_source(p,guest_ns()) >= 0) return 0;
+ dm_motion m; int present=physical_motion(p,guest_ns(),&m);
+ if (!present) return 1;
+ float speed=0,acc=0; for(int i=0;i<3;i++) { speed+=m.gyro[i]*m.gyro[i]; acc+=m.acc[i]*m.acc[i]; }
+ return speed < 0.0001f && fabsf(acc-1) < 0.1f;
+}
+HLE_FORCE("_ZN2nn3hid23GetSixAxisSensorHandlesEPNS0_19SixAxisSensorHandleEiRKjNS_4util10BitFlagSetILi32ENS0_12NpadStyleTagEEE", "six-axis sensor handles: two for dual Joy-Cons, one otherwise",
int, h_hid_SixHandles, uint32_t *h, int n, const uint32_t *id, uint32_t style) {
- int k = style & (STYLE_HANDHELD | STYLE_JOYDUAL) ? 2 : 1; if (k > n) k = n;
- for (int i = 0; i < k; i++) h[i] = (uint32_t)(style ? __builtin_ctz(style) : 0) | (*id & 0xff) << 8 | (uint32_t)i << 16;
- return k > 0 ? k : 0;
+ style &= STYLE_FULLKEY | STYLE_HANDHELD | STYLE_JOYDUAL | STYLE_JOYLEFT | STYLE_JOYRIGHT;
+ if (n <= 0 || !style) return 0;
+ unsigned type = (unsigned)__builtin_ctz(style) + 3;
+ unsigned device = type <= 4 ? 2 : type == 7 ? 1 : 0;
+ int k = type == 5 ? 2 : 1; if (k > n) k = n;
+ for (int i = 0; i < k; i++) h[i] = type | (*id & 0xff) << 8 | (device + (unsigned)i) << 16;
+ return k;
}
HLE_FORCE("_ZN2nn3hid18StartSixAxisSensorERKNS0_19SixAxisSensorHandleE", "six-axis sensor; always sampling on the host", void, h_hid_SixStart, const uint32_t *h) { (void)h; }
// Merged mouse pointer (Nmouse, Switch 2 SDKs; Pokemon Pokopia, main+0x11251dc). The SDK opens the hid service itself in InitializeNmouse, which the host does not serve (abort 0xe15). No device
@@ -866,11 +929,7 @@ HLE_FORCE("_ZN2nn3hid16GetGestureStatesEPNS0_12GestureStateEi", "gesture states,
// Six-axis details: the current state, at rest unless shaking, fusion off
HLE_FORCE("_ZN2nn3hid17StopSixAxisSensorERKNS0_19SixAxisSensorHandleE", "six-axis sensor; always sampling on the host", void, h_hid_SixStop, const uint32_t *h) { (void)h; }
HLE_FORCE("_ZN2nn3hid21GetSixAxisSensorStateEPNS0_18SixAxisSensorStateERKNS0_19SixAxisSensorHandleE", "six-axis sensor current state", void, h_hid_SixState, SixAxisState *s, const uint32_t *h) { six_states(s, 1, *h); }
-HLE_FORCE("_ZN2nn3hid21IsSixAxisSensorAtRestERKNS0_19SixAxisSensorHandleE", "six-axis sensor at rest: yes unless player 1's is shaking or a live controller is turning", unsigned, h_hid_SixRest, const uint32_t *h) {
- int pl = player_of(*h >> 8 & 0xff); motion_state ms;
- if (motion_live(pl, &ms)) return fabsf(ms.gyro[0]) + fabsf(ms.gyro[1]) + fabsf(ms.gyro[2]) < 0.01f && !(pl == 0 && shaking(guest_ns()));
- return pl != 0 || !shaking(guest_ns());
-}
+HLE_FORCE("_ZN2nn3hid21IsSixAxisSensorAtRestERKNS0_19SixAxisSensorHandleE", "physical motion or the simulated shake determines rest", unsigned, h_hid_SixRest, const uint32_t *h) { return six_rest(*h); }
// The console's own six-axis sensor (SevenSixAxisSensor, the body's orientation in handheld mode; The Legend of Zelda: Breath of the Wild): takes a work buffer and is switched through the hid service. The host provides none: switching succeeds, 0 states
HLE_FORCE("_ZN2nn3hid28InitializeSevenSixAxisSensorEPvm", "console six-axis sensor initialization; not provided by the host", Result, h_hid_SevenInit, void *buf, size_t n) { (void)buf; (void)n; return RES_OK; }
HLE_FORCE("_ZN2nn3hid26FinalizeSevenSixAxisSensorEv", "console six-axis sensor", Result, h_hid_SevenFini, void) { return RES_OK; }
diff --git a/dm/host/home_quit.h b/dm/host/home_quit.h
index 64b6b9d..ddab115 100644
--- a/dm/host/home_quit.h
+++ b/dm/host/home_quit.h
@@ -1,9 +1,9 @@
// Quit with the Home button (Mac front end, front_mac.m; LNPANDY/NX2Apple#336). Holding Home (the logo button on Xbox and PlayStation pads) for HQ_HOLD_S seconds opens a
// "Quit?" prompt over the game: A quits (the same exit as ⌘Q), B or a new press of Home closes it. Letting go of Home before the time is up does nothing. A and B are
// GameController's buttonA and buttonB (by label: the bottom button on an Xbox or PlayStation pad, the one printed A on a Nintendo pad), not the Switch buttons the game
-// gets. Pure, so tests/t_home_quit.c checks it without a controller or a window.
+// gets. Direct Triton reports use Guide and the physical A and B labels. Pure, so tests/t_home_quit.c checks it without a controller or a window.
//
-// The hold works wherever the press reaches the host: pad_keep_system_buttons claims Home on every pad (preferredSystemGestureState = GCSystemGestureStateDisabled), and
+// The hold works wherever the press reaches the host: controller_add_gc claims Home on each native pad (preferredSystemGestureState = GCSystemGestureStateDisabled), and
// macOS 27 respects the claim when the Home button setting for apps lets the app decide (front_mac.m logs the setting). When the system takes Home anyway (it opens the
// Games app or the player's chosen app), the game window loses the focus and whatever was shown closes (hq_cancel). DM_HOME_QUIT=0 turns it off. A front end passes the
// texts in the player's language as DM_HOME_QUIT_TEXT (hq_text_line, docs/frontends.md), English otherwise.
diff --git a/dm/host/input_map.h b/dm/host/input_map.h
index 56fa499..64419ad 100644
--- a/dm/host/input_map.h
+++ b/dm/host/input_map.h
@@ -1,10 +1,11 @@
// The Mac front end's button assignments (front_mac.m; pure, so tests/t_input_map.c checks it without a keyboard or controller), named as DM_KEYS names them (hle_hid.c).
// DM_KEYMAP=<name>=<key code>,… puts a function on another key: <key code> is the macOS virtual key code (NSEvent.keyCode, decimal), or "none" to leave the function on no key.
-// The names are the 16 buttons, the four directions of each stick (LUp … RRight) and Shake; the left stick is on W A S D, the right stick on no key, unless DM_KEYMAP says so.
+// The names are the 16 buttons, the four directions of each stick (LUp … RRight) and Shake; the left stick is on W A S D, the right stick on Shift+arrow keys (unless those arrows are remapped), with additional keys assignable through DM_KEYMAP.
// One key holds one function: the last assignment of a key wins, and the function that held it before is left on no key, so "A=40,B=38" swaps A and B.
// DM_PAD_MAP=<name>=<name>,… changes what a controller's buttons send: the button that sends <first> by default (by position, as the iPhone maps it) sends <second> instead,
-// "none" sends nothing; buttons not named stay as they are, so "A=B,B=A" swaps them. Only the 16 buttons take part (the sticks stay sticks).
+// "none" sends nothing; buttons not named stay as they are, so "A=B,B=A" swaps them. Sources are the 16 buttons (the sticks stay sticks); Shake is also a target.
// A malformed entry is left out and named in the log; the rest of the list still applies.
+// input_map_valid() is the same parser without a map or a log line: the Mac launcher (dm/mac/launcher.c) checks a saved DM_KEYMAP / DM_PAD_MAP with it, so a saved value is used only when the host takes every entry of it.
#pragma once
#include <stdint.h>
#include <stdio.h>
@@ -40,14 +41,14 @@ static void key_map_default(key_map *m) {
static void pad_map_default(pad_map *m) { for (int b = 0; b < IM_BUTTONS; b++) m->to[b] = (int8_t)b; }
// Walks "<name>=<value>,…", calling one(name's function, value text, its length) for each entry; returns the number of malformed entries, each logged here
-static int im_parse(const char *spec, int max_fn, int (*one)(void *, int, const char *, size_t), void *ctx) {
+static int im_parse(const char *spec, int max_fn, int (*one)(void *, int, const char *, size_t), void *ctx, int log) {
int bad = 0;
for (const char *p = spec; p && *p; ) {
const char *end = strchr(p, ','); size_t n = end ? (size_t)(end - p) : strlen(p);
const char *eq = memchr(p, '=', n);
int f = eq ? im_name(p, (size_t)(eq - p)) : -1;
if (f < 0 || f >= max_fn || !one(ctx, f, eq + 1, n - (size_t)(eq + 1 - p))) {
- fprintf(stderr, "[dm] [RED] input map: '%.*s' is not <name>=<value>, left out\n", (int)n, p); // dm.h LOG's form (this header stays free of dm.h for the test)
+ if (log) fprintf(stderr, "[dm] [RED] input map: '%.*s' is not <name>=<value>, left out\n", (int)n, p); // dm.h LOG's form (this header stays free of dm.h for the test)
bad++;
}
p = end ? end + 1 : NULL;
@@ -67,12 +68,43 @@ static int im_key_one(void *ctx, int f, const char *v, size_t n) {
static int im_pad_one(void *ctx, int f, const char *v, size_t n) {
pad_map *m = ctx;
if (n == 4 && !strncasecmp(v, "none", 4)) { m->to[f] = -1; return 1; }
- int t = im_name(v, n); if (t < 0 || t >= IM_BUTTONS) return 0;
+ int t = im_name(v, n); if (t == IM_SHAKE) t = 63;
+ if (t < 0 || (t >= IM_BUTTONS && t != 63)) return 0;
m->to[f] = (int8_t)t; return 1;
}
-static int key_map_parse(key_map *m, const char *spec) { return im_parse(spec, IM_N, im_key_one, m); }
-static int pad_map_parse(pad_map *m, const char *spec) { return im_parse(spec, IM_BUTTONS, im_pad_one, m); }
+static int key_map_parse(key_map *m, const char *spec) { return im_parse(spec, IM_N, im_key_one, m, 1); }
+static int pad_map_parse(pad_map *m, const char *spec) { return im_parse(spec, IM_BUTTONS, im_pad_one, m, 1); }
+// 1 when spec is a DM_KEYMAP (pad = 0) or DM_PAD_MAP (pad = 1) value the host takes whole: not empty, every entry well-formed. Pure: nothing is logged, no map is kept
+static int input_map_valid(const char *spec, int pad) {
+ if (!spec || !*spec) return 0;
+ key_map k; pad_map m; key_map_default(&k); pad_map_default(&m);
+ return pad ? !im_parse(spec, IM_BUTTONS, im_pad_one, &m, 0) : !im_parse(spec, IM_N, im_key_one, &k, 0);
+}
static int key_map_fn(const key_map *m, unsigned code) { return code < IM_KEYS ? m->fn[code] : -1; }
+// Functions held by physical keys. Zero is released; a held entry is function + 1.
+typedef struct { uint8_t pressed[IM_KEYS]; } key_state;
+static void key_state_clear(key_state *s) { memset(s, 0, sizeof *s); }
+static uint32_t key_state_event(key_state *s, const key_map *m, unsigned code, int down, int shift) {
+ if (code < IM_KEYS) {
+ if (!down) s->pressed[code] = 0;
+ else if (!s->pressed[code]) {
+ int f = key_map_fn(m, code);
+ // Shift changes only the default D-pad arrows. Explicitly moved/disabled arrows keep their mapping.
+ // Capture once on key-down: repeats and key-up must not reinterpret a later modifier state.
+ if (shift) {
+ if (code == 123 && f == 12) f = IM_RLEFT;
+ else if (code == 126 && f == 13) f = IM_RUP;
+ else if (code == 124 && f == 14) f = IM_RRIGHT;
+ else if (code == 125 && f == 15) f = IM_RDOWN;
+ }
+ if (f >= 0) s->pressed[code] = (uint8_t)(f + 1);
+ }
+ }
+ uint32_t held = 0;
+ for (unsigned i = 0; i < IM_KEYS; i++) if (s->pressed[i]) held |= 1u << (s->pressed[i] - 1);
+ return held;
+}
+
// The buttons a controller sends for the buttons the default mapping read (DM_BTN_* bits); bits above the 16 buttons (DM_BTN_SHAKE) pass through
static uint64_t pad_map_apply(const pad_map *m, uint64_t btn) {
uint64_t out = btn & ~0xffffull;
diff --git a/dm/host/input_preferences_mac.h b/dm/host/input_preferences_mac.h
new file mode 100644
index 0000000..b3a2dee
--- /dev/null
+++ b/dm/host/input_preferences_mac.h
@@ -0,0 +1,47 @@
+// Shared controls use the app's preferences domain, as dm/mac/launcher.c does.
+// The host can also run outside a bundle; then its compiled game selects the domain.
+#pragma once
+#import <Foundation/Foundation.h>
+#include "game_profile.h"
+#include "input_map.h"
+static NSString *input_preferences_domain(void) {
+ return NSBundle.mainBundle.bundleIdentifier ?: [@"org.nxnative." DM_GAME_ID lowercaseString];
+}
+static BOOL input_preferences_enabled(void) {
+ const char *off=getenv("DM_SAVED_CHOICES"); return !off || strcmp(off,"0");
+}
+static id input_preference(NSString *domain, NSString *key) {
+ if(!domain || !input_preferences_enabled()) return nil;
+ return CFBridgingRelease(CFPreferencesCopyAppValue((__bridge CFStringRef)key,(__bridge CFStringRef)domain));
+}
+static BOOL input_preference_write(NSString *domain, NSString *key, id value) {
+ if(!input_preferences_enabled()) return YES; // this session only
+ if(!domain) return NO;
+ CFPreferencesSetAppValue((__bridge CFStringRef)key,(__bridge CFPropertyListRef)value,(__bridge CFStringRef)domain);
+ return CFPreferencesAppSynchronize((__bridge CFStringRef)domain);
+}
+static BOOL input_env_contains(const char *list, const char *key) {
+ if(!list) return NO;
+ size_t n=strlen(key);
+ for(const char *p=list; *p;) { while(*p==' ') p++; const char *e=strchr(p,' '); size_t len=e ? (size_t)(e-p) : strlen(p);
+ if(len==n && !strncmp(p,key,n)) return YES;
+ p+=len;
+ }
+ return NO;
+}
+static BOOL input_map_fixed(const char *env) {
+ if(!getenv(env)) return NO;
+ // A standalone host has no launcher provenance. In an app the launcher
+ // distinguishes saved values from temporary environment/env.txt overrides.
+ const char *launch=getenv("DM_ENV_LAUNCH_KEYS");
+ return !launch || input_env_contains(launch,env) || input_env_contains(getenv("DM_ENV_FILE_KEYS"),env);
+}
+static NSString *input_preference_map(NSString *domain, const char *env, int pad) {
+ if(input_map_fixed(env)) return @(getenv(env));
+ id value=input_preference(domain,[@"launcher." stringByAppendingString:@(env)]);
+ if(!value) return nil;
+ if(![value isKindOfClass:NSString.class] || [value lengthOfBytesUsingEncoding:NSUTF8StringEncoding]>1023 || !input_map_valid([value UTF8String],pad)) {
+ fprintf(stderr,"[RED] saved %s ignored: invalid input map\n",env); return nil;
+ }
+ return value;
+}
diff --git a/dm/host/pad_hid_mac.h b/dm/host/pad_hid_mac.h
index b3b3212..55b6cd8 100644
--- a/dm/host/pad_hid_mac.h
+++ b/dm/host/pad_hid_mac.h
@@ -1,5 +1,5 @@
-// Mac: raw HID gamepads that GameController does not list (pad_hid.h, GitHub issue #637), read on the main run loop alongside front_mac.m's GameController players.
-// Each device takes a player slot as a GameController controller does; front_mac.m defines the slot side (hidpad_attach / hidpad_detach / hidpad_read).
+// Mac: raw HID gamepads that GameController does not list (pad_hid.h, GitHub issue #637), read on the main run loop alongside GameController and Triton.
+// controllers_mac.m owns slots, mappings and transport admission (hidpad_attach / hidpad_detach / hidpad_read / hidpad_available).
// Skipped, so no controller is read twice: GameController's synthetic devices, and every device GameController says it will list itself (+[GCController supportsHIDDevice:]:
// Xbox, PlayStation, Switch and MFi pads of any vendor). DM_HID_PADS=0 turns this off.
#pragma once
@@ -14,6 +14,19 @@ typedef struct hid_pad { IOHIDDeviceRef hid; pad_hid st; char name[64]; struct h
static IOHIDManagerRef g_hidpad_manager;
static hid_pad *g_hidpads;
static int g_hidpad_log;
+// Matching callbacks are one-shot. Retain deferred matches until ownership
+// changes or removal so a transient registry scan cannot lose a controller.
+static CFMutableArrayRef g_hidpad_waiting;
+static void hidpad_wait(IOHIDDeviceRef hid) {
+ if(!g_hidpad_waiting) g_hidpad_waiting=CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);
+ if(g_hidpad_waiting && !CFArrayContainsValue(g_hidpad_waiting,CFRangeMake(0,CFArrayGetCount(g_hidpad_waiting)),hid)) CFArrayAppendValue(g_hidpad_waiting,hid);
+}
+static void hidpad_forget(IOHIDDeviceRef hid) {
+ if(!g_hidpad_waiting) return;
+ CFIndex i=CFArrayGetFirstIndexOfValue(g_hidpad_waiting,CFRangeMake(0,CFArrayGetCount(g_hidpad_waiting)),hid);
+ if(i!=kCFNotFound) CFArrayRemoveValueAtIndex(g_hidpad_waiting,i);
+}
+static int hidpad_available(IOHIDDeviceRef hid);
static void hidpad_attach(hid_pad *d);
static void hidpad_detach(hid_pad *d);
static void hidpad_read(hid_pad *d);
@@ -40,7 +53,9 @@ static void hidpad_found(void *ctx, IOReturn result, void *sender, IOHIDDeviceRe
(void)ctx; (void)sender;
if (result != kIOReturnSuccess || IOHIDDeviceGetProperty(hid, CFSTR(kIOHIDGCSyntheticDeviceKey)) == kCFBooleanTrue) return;
for (hid_pad *d = g_hidpads; d; d = d->next) if (d->hid == hid) return;
- if ([GCController supportsHIDDevice:hid]) return; // front_mac.m reads it through its GCController (once per device: the call is not cheap)
+ if ([GCController supportsHIDDevice:hid]) return; // the adapter reads it through its GCController (once per device: the call is not cheap)
+ if (!hidpad_available(hid)) { hidpad_wait(hid); return; }
+ hidpad_forget(hid);
NSNumber *vendor = (__bridge NSNumber *)IOHIDDeviceGetProperty(hid, CFSTR(kIOHIDVendorIDKey)), *product = (__bridge NSNumber *)IOHIDDeviceGetProperty(hid, CFSTR(kIOHIDProductIDKey));
int vid = vendor.intValue, pid = product.intValue;
hid_pad *d = calloc(1, sizeof *d); if (!d) { LOG("[RED] HID gamepad: cannot allocate device state"); return; }
@@ -49,34 +64,47 @@ static void hidpad_found(void *ctx, IOReturn result, void *sender, IOHIDDeviceRe
snprintf(d->name, sizeof d->name, "%s", name.UTF8String ?: "HID gamepad");
NSArray *els = CFBridgingRelease(IOHIDDeviceCopyMatchingElements(hid, NULL, kIOHIDOptionsTypeNone));
for (id o in els) { IOHIDElementRef e = (__bridge IOHIDElementRef)o; int a = pad_hid_axis_of(IOHIDElementGetUsagePage(e), IOHIDElementGetUsage(e)); if (a >= 0) d->st.has[a] = 1; }
+ IOReturn r = IOHIDDeviceOpen(hid, kIOHIDOptionsTypeNone);
+ if (r != kIOReturnSuccess) { LOG("[RED] HID gamepad '%s': cannot open device (0x%x)", d->name, r); free(d); return; }
d->hid = (IOHIDDeviceRef)CFRetain(hid); d->next = g_hidpads; g_hidpads = d;
IOHIDDeviceRegisterInputValueCallback(hid, hidpad_value, d);
+ IOHIDDeviceScheduleWithRunLoop(hid, CFRunLoopGetMain(), kCFRunLoopCommonModes);
hidpad_attach(d);
// HID has no standard button numbering: the default map is 8BitDo's, so another vendor's pad may have its buttons in other places
if (vid != PAD_HID_DEFAULT_VENDOR && !getenv("DM_HID_MAP"))
LOG("controller '%s' (HID, %04x:%04x): buttons use 8BitDo's numbering; if they are in the wrong places, DM_HID_LOG=1 logs each button's number for a DM_HID_MAP", d->name, vid, pid);
}
+static void hidpad_retry(void) {
+ if(!g_hidpad_waiting || !CFArrayGetCount(g_hidpad_waiting)) return;
+ CFArrayRef pending=CFArrayCreateCopy(kCFAllocatorDefault,g_hidpad_waiting); if(!pending) return;
+ for(CFIndex i=0;i<CFArrayGetCount(pending);i++) hidpad_found(NULL,kIOReturnSuccess,NULL,(IOHIDDeviceRef)CFArrayGetValueAtIndex(pending,i));
+ CFRelease(pending);
+}
static void hidpad_removed(void *ctx, IOReturn result, void *sender, IOHIDDeviceRef hid) {
(void)ctx; (void)result; (void)sender;
+ hidpad_forget(hid);
hid_pad **link = &g_hidpads;
while (*link && (*link)->hid != hid) link = &(*link)->next;
if (!*link) return;
hid_pad *d = *link; *link = d->next;
IOHIDDeviceRegisterInputValueCallback(hid, NULL, NULL);
+ IOHIDDeviceUnscheduleFromRunLoop(hid, CFRunLoopGetMain(), kCFRunLoopCommonModes);
hidpad_detach(d);
+ IOHIDDeviceClose(hid, kIOHIDOptionsTypeNone);
CFRelease(d->hid); free(d);
}
static void hidpad_start(void) {
const char *e = getenv("DM_HID_PADS"); if (e && !atoi(e)) return;
e = getenv("DM_HID_LOG"); g_hidpad_log = e && atoi(e);
- g_hidpad_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (!g_hidpad_manager) return;
+ // Do not auto-open matches: the shared adapter first resolves Triton/GC ownership.
+ g_hidpad_manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDManagerOptionIndependentDevices); if (!g_hidpad_manager) return;
IOHIDManagerSetDeviceMatchingMultiple(g_hidpad_manager, (__bridge CFArrayRef)@[
@{@kIOHIDDeviceUsagePageKey: @(kHIDPage_GenericDesktop), @kIOHIDDeviceUsageKey: @(kHIDUsage_GD_GamePad)},
@{@kIOHIDDeviceUsagePageKey: @(kHIDPage_GenericDesktop), @kIOHIDDeviceUsageKey: @(kHIDUsage_GD_Joystick)}]);
IOHIDManagerRegisterDeviceMatchingCallback(g_hidpad_manager, hidpad_found, NULL);
IOHIDManagerRegisterDeviceRemovalCallback(g_hidpad_manager, hidpad_removed, NULL);
IOHIDManagerScheduleWithRunLoop(g_hidpad_manager, CFRunLoopGetMain(), kCFRunLoopCommonModes);
- IOReturn r = IOHIDManagerOpen(g_hidpad_manager, kIOHIDOptionsTypeNone); // nonexclusive: GameController and other apps keep their devices
+ IOReturn r = IOHIDManagerOpen(g_hidpad_manager, kIOHIDOptionsTypeNone); // independent: only accepted devices are opened above
if (r != kIOReturnSuccess) {
LOG("[RED] HID gamepads: cannot open HID (0x%x); only GameController controllers are read", r);
IOHIDManagerUnscheduleFromRunLoop(g_hidpad_manager, CFRunLoopGetMain(), kCFRunLoopCommonModes);
diff --git a/dm/host/pad_joycon_mac.h b/dm/host/pad_joycon_mac.h
index a995be7..388c4b6 100644
--- a/dm/host/pad_joycon_mac.h
+++ b/dm/host/pad_joycon_mac.h
@@ -1,5 +1,5 @@
// Mac: split a Bluetooth Joy-Con pair into two sideways controllers (pad_joycon.h, LNPANDY/NX2Apple#740).
-// When DM_JOYCON_SPLIT=1 is set, front_mac.m skips GameController's combined Joy-Con entry and reads Joy-Con (L) (0x057e:0x2006)
+// When DM_JOYCON_SPLIT=1 is set, controllers_mac.m skips GameController's combined Joy-Con entry and reads Joy-Con (L) (0x057e:0x2006)
// and Joy-Con (R) (0x057e:0x2007) directly with IOHIDManager so each half gets its own player slot.
#pragma once
#import <IOKit/hid/IOHIDManager.h>
diff --git a/dm/host/pad_map.h b/dm/host/pad_map.h
new file mode 100644
index 0000000..2f482e5
--- /dev/null
+++ b/dm/host/pad_map.h
@@ -0,0 +1,17 @@
+// Physical button order: east, south, north, west, LS, RS, L, R, ZL, ZR,
+// +, -, left, up, right, down, L4, R4, L5, R5, pad clicks L/R, Guide, Quick Access.
+// First 16 match the Switch's position layout. Extra buttons start unassigned.
+#pragma once
+#include "dm_input.h"
+#define DM_PAD_BUTTONS 24
+static inline void pad_physical_default(int *map, int xbox) {
+ for (int i = 0; i < DM_PAD_BUTTONS; i++) map[i] = i < 16 ? i : -1;
+ if (xbox) { map[0] = 1; map[1] = 0; map[2] = 3; map[3] = 2; }
+}
+static inline uint64_t pad_map_buttons(uint32_t physical, const int *map) {
+ uint64_t result = 0;
+ for (int i = 0; i < DM_PAD_BUTTONS; i++) if ((physical >> i) & 1) {
+ int to = map[i]; if ((to >= 0 && to < 16) || to == 63) result |= 1ull << to;
+ }
+ return result;
+}
diff --git a/dm/host/pad_motion.h b/dm/host/pad_motion.h
new file mode 100644
index 0000000..27b19e2
--- /dev/null
+++ b/dm/host/pad_motion.h
@@ -0,0 +1,36 @@
+// Per-device gyro integration. Recenter establishes the identity orientation;
+// no time is integrated across lost packets, suspend or a clock-format change.
+#pragma once
+#include "dm_input.h"
+#include <math.h>
+#include <string.h>
+typedef struct { dm_motion value; float q[4]; uint32_t tick; unsigned tick_us; int have_tick; } pad_motion_state;
+static inline void pad_motion_reset(pad_motion_state *m) { memset(m, 0, sizeof *m); }
+static inline int pad_motion_update(pad_motion_state *m, uint32_t tick, unsigned tick_us, const float *acc, const float *gyro) {
+ for (int i=0;i<3;i++) if (!isfinite(acc[i]) || !isfinite(gyro[i])) return 0;
+ unsigned elapsed = tick - m->tick;
+ if (tick_us == 32) elapsed &= 0xffff;
+ if (m->have_tick && m->tick_us == tick_us && !elapsed) return 0;
+ float dt = m->have_tick && m->tick_us == tick_us ? elapsed * tick_us / 1e6f : 0;
+ if (!m->have_tick) m->q[0] = 1;
+ m->have_tick=1; m->tick=tick; m->tick_us=tick_us;
+ if (dt > 0.1f) dt = 0;
+ memcpy(m->value.acc,acc,sizeof m->value.acc); memcpy(m->value.gyro,gyro,sizeof m->value.gyro);
+ float speed=sqrtf(gyro[0]*gyro[0]+gyro[1]*gyro[1]+gyro[2]*gyro[2]);
+ if (speed > 0 && dt > 0) {
+ float half=speed*dt*(float)M_PI, k=sinf(half)/speed;
+ float w=cosf(half), x=gyro[0]*k, y=gyro[1]*k, z=gyro[2]*k;
+ float a=m->q[0], b=m->q[1], c=m->q[2], d=m->q[3];
+ m->q[0]=a*w-b*x-c*y-d*z; m->q[1]=a*x+b*w+c*z-d*y;
+ m->q[2]=a*y-b*z+c*w+d*x; m->q[3]=a*z+b*y-c*x+d*w;
+ float norm=sqrtf(m->q[0]*m->q[0]+m->q[1]*m->q[1]+m->q[2]*m->q[2]+m->q[3]*m->q[3]);
+ for(int i=0;i<4;i++) m->q[i]/=norm;
+ }
+ for(int i=0;i<3;i++) m->value.angle[i] += gyro[i]*dt;
+ float w=m->q[0],x=m->q[1],y=m->q[2],z=m->q[3];
+ float *d=m->value.dir;
+ d[0]=1-2*(y*y+z*z); d[1]=2*(x*y+w*z); d[2]=2*(x*z-w*y);
+ d[3]=2*(x*y-w*z); d[4]=1-2*(x*x+z*z); d[5]=2*(y*z+w*x);
+ d[6]=2*(x*z+w*y); d[7]=2*(y*z-w*x); d[8]=1-2*(x*x+y*y);
+ return 1;
+}
diff --git a/dm/host/steam_input.h b/dm/host/steam_input.h
new file mode 100644
index 0000000..a252573
--- /dev/null
+++ b/dm/host/steam_input.h
@@ -0,0 +1,97 @@
+/*
+ * Triton protocol adapted from SDL_hidapi_steam_triton.c and Valve's controller
+ * structs in SDL e4ed62ee3f7d7fda8bf8e0f09e42b14a7ac11984. This is an altered,
+ * standalone implementation, not the SDL driver. See docs/mac-controllers.md.
+ *
+ * Copyright (C) 1997-2026 Sam Lantinga <[email protected]>
+ * Copyright (C) Valve Corporation
+ * This software is provided 'as-is', without any express or implied warranty.
+ * In no event will the authors be held liable for any damages arising from the
+ * use of this software. Permission is granted to anyone to use this software
+ * for any purpose, including commercial applications, and to alter it and
+ * redistribute it freely, subject to the following restrictions:
+ * 1. The origin of this software must not be misrepresented; you must not claim
+ * that you wrote the original software. If you use this software in a product,
+ * an acknowledgment in the product documentation would be appreciated but is
+ * not required.
+ * 2. Altered source versions must be plainly marked as such, and must not be
+ * misrepresented as being the original software.
+ * 3. This notice may not be removed or altered from any source distribution.
+ */
+#pragma once
+#include <math.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+#include "pad_map.h"
+typedef struct { int down; int32_t x, y; float pressure; } steam_pad;
+typedef struct {
+ uint32_t buttons; int32_t lx, ly, rx, ry;
+ steam_pad pad[2];
+ float acc[3], gyro[3]; // Switch coordinates: acceleration in G, gyro in revolutions/s
+ uint32_t tick; unsigned tick_us;
+} steam_state;
+static inline int steam_device(int vid, int pid, int interface) {
+ return vid == 0x28de && (pid == 0x1302 || pid == 0x1303 ||
+ ((pid == 0x1304 || pid == 0x1305) && interface >= 2 && interface <= 5));
+}
+static inline unsigned steam_u16(const unsigned char *p) { return (unsigned)p[0] | ((unsigned)p[1] << 8); }
+static inline int steam_i16(const unsigned char *p) { unsigned n = steam_u16(p); return n >= 32768 ? (int)n - 65536 : (int)n; }
+static inline int32_t steam_axis(const unsigned char *p) {
+ int n = steam_u16(p); if (n >= 32768) n -= 65536; return n == -32768 ? -32767 : n;
+}
+// Raw HID sticks drift slightly at rest. Games can treat any nonzero stick as
+// intentional input and suppress gyro aiming (TotK). Keep the centre exactly
+// zero, rescale the remaining travel, and retain full per-axis diagonals.
+static inline float steam_deadzone_value(void) {
+ const char *e = getenv("DM_STEAM_DEADZONE"); if (!e) return 0.10f;
+ char *end; float v = strtof(e, &end);
+ return end != e && !*end && v >= 0 && v < 0.9f ? v : 0.10f;
+}
+static inline void steam_deadzone(int32_t *x, int32_t *y, float dz) {
+ float fx = *x / 32767.0f, fy = *y / 32767.0f, radius = hypotf(fx, fy);
+ if (radius <= dz) { *x = *y = 0; return; }
+ if (radius >= 1) return; // square-range diagonals are already beyond full radial travel; do not rotate them by clipping
+ float scale = (radius - dz) / ((1 - dz) * radius);
+ *x = (int32_t)lrintf(fmaxf(-1, fminf(1, fx * scale)) * 32767);
+ *y = (int32_t)lrintf(fmaxf(-1, fminf(1, fy * scale)) * 32767);
+}
+// Return 1 for a complete state, -1 disconnected, 2 connected, 0 ignored.
+// USB (0x42), BLE (0x45), and timestamped (0x47) share their first 18 bytes.
+// Require the full 46-byte state, including touch/IMU, to reject truncated input.
+static inline int steam_decode(const unsigned char *p, size_t n, steam_state *s) {
+ if (n < 2) return 0;
+ if (p[0] == 0x46 || p[0] == 0x79) return p[1] == 1 ? -1 : p[1] == 2 ? 2 : 0;
+ if (n < 46 || (p[0] != 0x42 && p[0] != 0x45 && p[0] != 0x47)) return 0;
+ uint32_t b = (uint32_t)p[2] | ((uint32_t)p[3] << 8) | ((uint32_t)p[4] << 16) | ((uint32_t)p[5] << 24);
+ // Wire bit for each physical input (triggers also use their analog values).
+ static const int wire[DM_PAD_BUTTONS] = {1, 0, 3, 2, 15, 5, 19, 9, 27, 23, 6, 14, 12, 13, 11, 10, 17, 7, 18, 8, 26, 22, 16, 4};
+ s->buttons = 0;
+ for (int i = 0; i < DM_PAD_BUTTONS; i++) if (b & (1u << wire[i])) s->buttons |= 1u << i;
+ if (steam_u16(p + 6) >= 16384) s->buttons |= DM_BTN_ZL;
+ if (steam_u16(p + 8) >= 16384) s->buttons |= DM_BTN_ZR;
+ s->lx = steam_axis(p + 10); s->ly = steam_axis(p + 12);
+ s->rx = steam_axis(p + 14); s->ry = steam_axis(p + 16);
+ float dz = steam_deadzone_value();
+ steam_deadzone(&s->lx, &s->ly, dz); steam_deadzone(&s->rx, &s->ry, dz);
+ int pad = p[0] == 0x47 ? 20 : 18; // timestamped reports insert a trackpad timestamp
+ for (int i = 0; i < 2; i++, pad += 6) {
+ s->pad[i] = (steam_pad){!!(b & (1u << (i ? 21 : 25))), steam_axis(p + pad), steam_axis(p + pad + 2), steam_u16(p + pad + 4) / 32768.0f};
+ }
+ s->tick_us = p[0] == 0x47 ? 32 : 1;
+ s->tick = p[0] == 0x47 ? steam_u16(p + 32) : steam_u16(p + 30) | (uint32_t)steam_u16(p + 32) << 16;
+ // SDL maps Triton (x,y,z) to (x,z,-y); Switch's (x,-z,y) basis undoes
+ // that permutation. Gravity uses the opposite sign to SDL specific force.
+ for (int i = 0; i < 3; i++) {
+ s->acc[i] = -steam_i16(p + 34 + 2*i) * (2.0f / 32768);
+ s->gyro[i] = steam_i16(p + 40 + 2*i) * (2000.0f / (32768 * 360.0f));
+ }
+ return 1;
+}
+static inline void steam_rumble_report(unsigned char out[10], uint16_t left, uint16_t right) {
+ memset(out, 0, 10); out[0] = 0x80;
+ out[4] = left; out[5] = left >> 8; out[7] = right; out[8] = right >> 8;
+}
+static inline void steam_imu_report(unsigned char out[64], int enabled) {
+ memset(out, 0, 64); out[0] = 1; out[1] = 0x87; out[2] = 3; out[3] = 48; out[4] = enabled ? 0x18 : 0;
+}
diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile
index a35ca5e..cac33f6 100644
--- a/dm/host/tests/Makefile
+++ b/dm/host/tests/Makefile
@@ -71,6 +71,9 @@ run: $(B)/t_net_eventfd $(B)/t_language $(B)/t_motion $(B)/t_heap_size $(B)/t_to
TMPDIR="$(abspath $(B))" $(B)/t_cheats $(QUIET)
$(B)/t_nro
$(B)/t_symbols
+ $(B)/t_pad_map
+ $(B)/t_pad_motion
+ $(B)/t_controllers_mac
run: $(B)/t_nro
run: $(B)/t_symbols
$(B)/t_symbols: t_symbols.c ../hle.c ../loader.c ../hle.h ../dm.h $(GAME_H) | $(B)
@@ -383,3 +386,11 @@ $(B)/t_profile_runtime: t_profile_runtime.c ../hle_profile.c ../hle_profile.h ..
.PHONY: profile-runtime
profile-runtime: $(B)/t_profile_runtime
TMPDIR="$(abspath $(B))" $(B)/t_profile_runtime
+
+run: $(B)/t_pad_map $(B)/t_pad_motion $(B)/t_controllers_mac
+$(B)/t_pad_motion: t_pad_motion.c ../pad_motion.h ../dm_input.h | $(B)
+ $(CLANG) -O1 -Wall -Werror -o $@ t_pad_motion.c
+$(B)/t_pad_map: t_pad_map.c ../pad_map.h ../steam_input.h ../dm_input.h | $(B)
+ $(CLANG) -O1 -Wall -Werror -o $@ t_pad_map.c
+$(B)/t_controllers_mac: t_controllers_mac.m ../home_quit.h ../pad_hid.h ../pad_hid_mac.h ../pad_apple.h ../input_map.h ../input_preferences_mac.h ../controllers_mac.m ../controllers_mac.h ../pad_joycon.h ../pad_joycon_mac.h ../pad_map.h ../pad_motion.h ../steam_input.h ../pad_slots.h ../front.h ../dm_input.h ../haptics_apple.h ../hle_haptics.h ../dm.h ../motion_apple.h ../motion_pro_mac.h ../motion_pro.h $(GAME_H) | $(B)
+ $(CLANG) $(GINC) -O1 -fobjc-arc -Wall -Werror -Wno-unused-function -o $@ t_controllers_mac.m -framework Cocoa -framework GameController -framework IOKit
diff --git a/dm/host/tests/t_controllers_mac.m b/dm/host/tests/t_controllers_mac.m
new file mode 100644
index 0000000..4423db2
--- /dev/null
+++ b/dm/host/tests/t_controllers_mac.m
@@ -0,0 +1,1065 @@
+// GameController snapshots exercise the same read/remap/publish path as hardware.
+#import <GameController/GameController.h>
+#import <IOKit/hid/IOHIDManager.h>
+#include <assert.h>
+// Mock only the OS HID boundary. The adapter's validation, registry discovery,
+// ownership, report decoding, slot allocation and cleanup all run unchanged.
+static NSMutableDictionary *hid_registry, *hid_opened, *hid_scheduled, *hid_callbacks;
+static NSMutableDictionary *hid_nodes;
+static NSArray *hid_scan; static NSUInteger hid_scan_index;
+static BOOL hid_scan_fails, hid_scan_invalid, hid_scan_empty;
+static NSArray<GCController *> *native_devices;
+static int hid_open_count, hid_close_count;
+static IOHIDDeviceRef hid_last_closed;
+static void check_hid_stopped(IOHIDDeviceRef device);
+static CFTypeRef test_hid_property(IOHIDDeviceRef device, CFStringRef key) {
+ return (__bridge CFTypeRef)((__bridge NSDictionary *)device)[(__bridge NSString *)key];
+}
+static CFArrayRef test_hid_elements(IOHIDDeviceRef device,CFDictionaryRef match,IOOptionBits options) {
+ (void)match; (void)options;
+ id elements=((__bridge NSDictionary *)device)[@"elements"];
+ return elements ? CFRetain((__bridge CFArrayRef)elements) : NULL;
+}
+static IOHIDElementType test_element_type(IOHIDElementRef e) { (void)e; return kIOHIDElementTypeInput_Misc; }
+static uint32_t test_element_report(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"report"] unsignedIntValue]; }
+static uint32_t test_element_size(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"bits"] unsignedIntValue]; }
+static uint32_t test_element_count(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"count"] unsignedIntValue]; }
+static Boolean test_element_array(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"array"] boolValue]; }
+static io_service_t test_hid_service(IOHIDDeviceRef device) {
+ return [((__bridge NSDictionary *)device)[@"registry"] unsignedIntValue];
+}
+static kern_return_t test_registry_id(io_registry_entry_t service,uint64_t *id) { *id=service; return KERN_SUCCESS; }
+// Keep the SDK ownership contracts when analysis does not inline these mocks.
+static CFTypeRef CF_RETURNS_RETAINED test_registry_property(io_registry_entry_t service,const io_name_t plane,CFStringRef key,CFAllocatorRef allocator,IOOptionBits options) {
+ (void)plane; (void)key; (void)allocator; (void)options;
+ id value=hid_registry[@(service)][@"interface"]; return value ? CFRetain((__bridge CFTypeRef)value) : NULL;
+}
+static IOReturn test_hid_open(IOHIDDeviceRef device,IOOptionBits options) {
+ NSDictionary *properties=(__bridge NSDictionary *)device;
+ assert(options==kIOHIDOptionsTypeSeizeDevice || (options==kIOHIDOptionsTypeNone && [properties[@"generic"] boolValue])); ++hid_open_count;
+ if([properties[@"fail"] boolValue]) return kIOReturnExclusiveAccess;
+ assert(!hid_opened[properties[@"registry"]]); hid_opened[properties[@"registry"]]=properties;
+ return kIOReturnSuccess;
+}
+static void test_hid_callback(IOHIDDeviceRef device,uint8_t *report,CFIndex size,IOHIDReportCallback callback,void *context) {
+ (void)report; (void)size;
+ NSNumber *id=((__bridge NSDictionary *)device)[@"registry"];
+ assert(hid_opened[id]);
+ if(callback) { assert(context); hid_callbacks[id]=@YES; }
+ else [hid_callbacks removeObjectForKey:id];
+}
+static void test_hid_value_callback(IOHIDDeviceRef device,IOHIDValueCallback callback,void *context) {
+ NSNumber *id=((__bridge NSDictionary *)device)[@"registry"]; assert(hid_opened[id]);
+ if(callback) { assert(context); hid_callbacks[id]=@YES; }
+ else [hid_callbacks removeObjectForKey:id];
+}
+static uint32_t test_element_page(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"page"] unsignedIntValue]; }
+static uint32_t test_element_usage(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"usage"] unsignedIntValue]; }
+static CFIndex test_element_min(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"min"] longValue]; }
+static CFIndex test_element_max(IOHIDElementRef e) { return [((__bridge NSDictionary *)e)[@"max"] longValue]; }
+static IOHIDElementRef test_value_element(IOHIDValueRef v) { return (__bridge IOHIDElementRef)((__bridge NSDictionary *)v)[@"element"]; }
+static CFIndex test_value_integer(IOHIDValueRef v) { return [((__bridge NSDictionary *)v)[@"value"] longValue]; }
+static void test_hid_schedule(IOHIDDeviceRef device,CFRunLoopRef loop,CFStringRef mode) {
+ assert(loop==CFRunLoopGetMain() && CFEqual(mode,kCFRunLoopCommonModes));
+ NSNumber *id=((__bridge NSDictionary *)device)[@"registry"]; assert(hid_opened[id] && hid_callbacks[id]); hid_scheduled[id]=@YES;
+}
+static void test_hid_unschedule(IOHIDDeviceRef device,CFRunLoopRef loop,CFStringRef mode) {
+ (void)loop; (void)mode;
+ NSNumber *id=((__bridge NSDictionary *)device)[@"registry"]; assert(hid_scheduled[id]); [hid_scheduled removeObjectForKey:id];
+}
+static IOReturn test_hid_close(IOHIDDeviceRef device,IOOptionBits options) {
+ assert(options==kIOHIDOptionsTypeNone);
+ NSNumber *id=((__bridge NSDictionary *)device)[@"registry"];
+ assert(hid_opened[id] && !hid_callbacks[id] && !hid_scheduled[id]); check_hid_stopped(device);
+ [hid_opened removeObjectForKey:id]; hid_last_closed=device; ++hid_close_count;
+ return kIOReturnSuccess;
+}
+static kern_return_t test_matching_services(mach_port_t port,CFDictionaryRef match CF_RELEASES_ARGUMENT,io_iterator_t *iterator) {
+ (void)port; assert([((__bridge NSDictionary *)match)[@kIOHIDVendorIDKey] intValue]==0x28de);
+ CFRelease(match); if(hid_scan_fails) return kIOReturnError;
+ hid_scan=hid_registry.allKeys; hid_scan_index=0; *iterator=hid_scan_empty ? 0 : 100; return KERN_SUCCESS;
+}
+static io_object_t test_iterator_next(io_iterator_t iterator) { assert(iterator==100); return hid_scan_index<hid_scan.count ? [hid_scan[hid_scan_index++] unsignedIntValue] : 0; }
+static boolean_t test_iterator_valid(io_iterator_t iterator) { assert(iterator==100); return !hid_scan_invalid; }
+static IOHIDDeviceRef test_hid_create(CFAllocatorRef allocator,io_service_t service) {
+ (void)allocator; if([hid_registry[@(service)][@"create_fail"] boolValue]) return NULL;
+ return (IOHIDDeviceRef)CFRetain((__bridge CFTypeRef)hid_registry[@(service)]);
+}
+static kern_return_t test_object_retain(io_object_t object) { (void)object; return KERN_SUCCESS; }
+static boolean_t test_object_conforms(io_object_t object,const io_name_t name) { return [hid_nodes[@(object)][@"class"] isEqual:@(name)]; }
+static kern_return_t test_registry_parent(io_registry_entry_t entry,const io_name_t plane,io_registry_entry_t *parent) {
+ (void)plane; *parent=[hid_nodes[@(entry)][@"parent"] unsignedIntValue]; return *parent ? KERN_SUCCESS : KERN_FAILURE;
+}
+static kern_return_t test_object_release(io_object_t object) { (void)object; return KERN_SUCCESS; }
+@interface GCController (HIDFixture)
++ (BOOL)testSupportsHIDDevice:(IOHIDDeviceRef)device;
++ (NSArray<GCController *> *)testControllers;
+@end
+@implementation GCController (HIDFixture)
++ (BOOL)testSupportsHIDDevice:(IOHIDDeviceRef)device { return [((__bridge NSDictionary *)device)[@"native"] boolValue]; }
++ (NSArray<GCController *> *)testControllers { return native_devices ?: @[]; }
+@end
+#define supportsHIDDevice testSupportsHIDDevice
+#define controllers testControllers
+#define IOHIDDeviceRegisterInputValueCallback test_hid_value_callback
+#define IOHIDElementGetUsagePage test_element_page
+#define IOHIDElementGetUsage test_element_usage
+#define IOHIDElementGetLogicalMin test_element_min
+#define IOHIDElementGetLogicalMax test_element_max
+#define IOHIDValueGetElement test_value_element
+#define IOHIDValueGetIntegerValue test_value_integer
+#define IOHIDDeviceCopyMatchingElements test_hid_elements
+#define IOHIDElementGetType test_element_type
+#define IOHIDElementGetReportID test_element_report
+#define IOHIDElementGetReportSize test_element_size
+#define IOHIDElementGetReportCount test_element_count
+#define IOHIDElementIsArray test_element_array
+#define IOHIDDeviceGetProperty test_hid_property
+#define IOHIDDeviceGetService test_hid_service
+#define IORegistryEntryGetRegistryEntryID test_registry_id
+#define IORegistryEntrySearchCFProperty test_registry_property
+#define IOHIDDeviceOpen test_hid_open
+#define IOHIDDeviceRegisterInputReportCallback test_hid_callback
+#define IOHIDDeviceScheduleWithRunLoop test_hid_schedule
+#define IOHIDDeviceUnscheduleFromRunLoop test_hid_unschedule
+#define IOHIDDeviceClose test_hid_close
+#define IOServiceGetMatchingServices test_matching_services
+#define IOIteratorNext test_iterator_next
+#define IOIteratorIsValid test_iterator_valid
+#define IOHIDDeviceCreate test_hid_create
+#define IOObjectRelease test_object_release
+#define IOObjectRetain test_object_retain
+#define IOObjectConformsTo test_object_conforms
+#define IORegistryEntryGetParentEntry test_registry_parent
+#import "../controllers_mac.m"
+#include "../home_quit.h"
+static void (^test_home_poll)(void);
+void front_home_poll(void) { if(test_home_poll) test_home_poll(); }
+
+static unsigned pointer_activity;
+void front_game_input(void) { ++pointer_activity; }
+static uint64_t received[DM_PLAYERS]; static int32_t axes[DM_PLAYERS][4]; static uint32_t players;
+static GCController *rumble[DM_PLAYERS];
+static GCHapticsLocality rumble_locality[DM_PLAYERS];
+static unsigned route_changes[DM_PLAYERS], pad_updates[DM_PLAYERS];
+static dm_haptics_output raw_output[DM_PLAYERS];
+static uint8_t written[64]; static CFIndex written_n, written_id; static IOHIDReportType written_type;
+static IOReturn fake_write(IOHIDDeviceRef d, IOHIDReportType type, CFIndex id, const uint8_t *b, CFIndex n) {
+ assert(d); written_type=type; written_n=n; written_id=id; memcpy(written,b,n); return kIOReturnSuccess;
+}
+static dm_touch touches[16]; static int ntouches;
+uint64_t now_ns(void) { return (uint64_t)(controller_now() * 1e9); }
+static int native_motion_player = -1, native_motion_cleared = -1, native_motion_samples;
+void dm_motion_set(int p, const float a[3], const float r[3]) { native_motion_player=p; native_motion_samples++; assert(a[2] == -1 && r[1] == 1); }
+void dm_motion_clear(int p) { native_motion_cleared=p; }
+static unsigned hid_motion_samples[DM_PLAYERS], hid_motion_clears[DM_PLAYERS];
+void dm_motion_set_hid(int p, const float a[3], const float r[3], uint64_t t) { (void)a; (void)r; assert(t); ++hid_motion_samples[p]; }
+void dm_motion_clear_hid(int p) { ++hid_motion_clears[p]; }
+static dm_motion motions[DM_PLAYERS]; static int motion_present[DM_PLAYERS];
+static int output_focused=1;
+void dm_haptics_apple_focus(int active) { output_focused=active; }
+void dm_touch_set(const dm_touch *t, int n) { ntouches=n; if(n) memcpy(touches,t,n*sizeof *t); }
+void dm_pad_motion(int p, const dm_motion *m) { motion_present[p]=m!=NULL; if(m) motions[p]=*m; }
+void dm_haptics_apple_output(int p, id owner, dm_haptics_output output) { (void)owner; ++route_changes[p]; raw_output[p]=[output copy]; rumble[p]=nil; }
+dm_haptic_level dm_haptics_level(const dm_vibration *v, int count, float gain) { (void)count; return (dm_haptic_level){v->amplitude_low*gain,0}; }
+static BOOL test_intensity_cutoff;
+static unsigned intensity_calls;
+static float intensity_inputs[2];
+float dm_haptics_apple_controller_intensity(float intensity) {
+ if (!test_intensity_cutoff) return intensity;
+ assert(intensity_calls < 2);
+ intensity_inputs[intensity_calls] = intensity;
+ return intensity_calls++ ? 0.5f : 0; // the real cutoff mapping is tested in t_haptics_apple
+}
+void dm_pad_set_player(int p, uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { ++pad_updates[p]; received[p] = b; axes[p][0]=lx; axes[p][1]=ly; axes[p][2]=rx; axes[p][3]=ry; }
+void dm_pad_players(uint32_t m) { players = m; }
+void dm_haptics_apple_controller_locality(int p, GCController *c, GCHapticsLocality locality) { dm_haptics_apple_controller(p,c); rumble_locality[p]=locality; }
+void dm_haptics_apple_controller(int p, GCController *c) { ++route_changes[p]; rumble[p] = c; raw_output[p]=nil; }
+// GameController's newer live-input API is read-only. Adapt real mutable GC
+// snapshots at the OS boundary and supply event times explicitly.
+@interface TestButton : NSObject
+@property GCControllerButtonInput *button;
+@end
+@implementation TestButton
+- (id)pressedInput { return self; }
+- (BOOL)isPressed { return self.button.isPressed; }
+@end
+@interface TestLiveInput : NSObject
+@property GCController *snapshot;
+@property NSTimeInterval lastEventTimestamp, lastEventLatency;
+@property dispatch_queue_t queue;
+@property(copy) void (^elementValueDidChangeHandler)(id<GCDevicePhysicalInput>, id<GCPhysicalInputElement>);
+@end
+@implementation TestLiveInput
+- (id)capture { return self; }
+- (id)buttons {
+ NSMutableDictionary *buttons=[NSMutableDictionary dictionary];
+ for(NSString *key in self.snapshot.physicalInputProfile.buttons) {
+ TestButton *b=[TestButton new]; b.button=self.snapshot.physicalInputProfile.buttons[key]; buttons[key]=b;
+ }
+ return buttons;
+}
+- (id)dpads { return self.snapshot.physicalInputProfile.dpads; }
+@end
+// A queued pre-seize event updates the live state between separate timestamp
+// and latency reads. Capturing first sees one coherent state at time 20.
+@interface RacingLiveInput : TestLiveInput @end
+@implementation RacingLiveInput
+- (NSTimeInterval)lastEventTimestamp { return 10; }
+- (NSTimeInterval)lastEventLatency { return 0; }
+- (id)capture {
+ TestLiveInput *frozen=[TestLiveInput new]; frozen.snapshot=self.snapshot;
+ frozen.lastEventTimestamp=20; frozen.lastEventLatency=0; return frozen;
+}
+@end
+@interface NamedSteamController : GCController
+@property TestLiveInput *testInput;
+@end
+@implementation NamedSteamController
+- (instancetype)init {
+ if((self=[super init])) {
+ self.testInput=[TestLiveInput new]; self.testInput.snapshot=[GCController controllerWithExtendedGamepad];
+ self.testInput.lastEventTimestamp=10; self.testInput.lastEventLatency=1;
+ }
+ return self;
+}
+- (NSString *)vendorName { return @"Steam Controller"; }
+- (NSString *)productCategory { return @"Extended Gamepad"; }
+- (GCExtendedGamepad *)extendedGamepad { return self.testInput.snapshot.extendedGamepad; }
+- (GCControllerLiveInput *)input { return (id)self.testInput; }
+@end
+static void gc_event_at(DMController *d, double time) {
+ TestLiveInput *input=((NamedSteamController *)d.controller).testInput;
+ input.lastEventTimestamp=time;
+ assert(input.elementValueDidChangeHandler);
+ input.elementValueDidChangeHandler((id)input,nil);
+}
+static void gc_event(DMController *d) { gc_event_at(d,d->gc_not_before+1); }
+@interface TestNativeMotion : NSObject
+@property BOOL hasRotationRate, hasGravityAndUserAcceleration, sensorsRequireManualActivation, sensorsActive;
+@property GCAcceleration acceleration, gravity, userAcceleration;
+@property GCRotationRate rotationRate;
+@property(copy) GCMotionValueChangedHandler valueChangedHandler;
+@end
+@implementation TestNativeMotion @end
+@interface MotionController : NamedSteamController
+@property TestNativeMotion *testMotion;
+@end
+@implementation MotionController
+- (GCMotion *)motion { return (id)self.testMotion; }
+- (NSString *)productCategory { return @"Switch Pro Controller"; }
+- (GCPhysicalInputProfile *)physicalInputProfile { return self.testInput.snapshot.physicalInputProfile; }
+@end
+// Dropping upstream's Nintendo label mapping must fail through the real adapter,
+// including a shared remap applied after the physical buttons are normalized.
+@interface JoyConHaptics : NSObject @end
+@implementation JoyConHaptics
+- (NSSet *)supportedLocalities { return [NSSet setWithObjects:GCHapticsLocalityLeftHandle,GCHapticsLocalityRightHandle,nil]; }
+@end
+@interface JoyConController : MotionController @end
+@implementation JoyConController
+- (NSString *)productCategory { return @"Nintendo Switch Joy-Con (L/R)"; }
+- (GCDeviceHaptics *)haptics { return (id)[JoyConHaptics new]; }
+@end
+static void test_split_joycon_routing(void) {
+ for(int merged=0;merged<2;merged++) {
+ g_merge=merged; g_slots=(pad_slots){0}; g_joycon_split=1;
+ JoyConController *pair=[JoyConController new]; native_devices=@[pair];
+ controllers_reconcile(@[pair]); assert(!g_devices.count);
+ joycon_pad left={0},right={0};
+ joycon_init(&left.st,JOYCON_PID_L); joycon_init(&right.st,JOYCON_PID_R);
+ snprintf(left.name,sizeof left.name,"Joy-Con (L)"); snprintf(right.name,sizeof right.name,"Joy-Con (R)");
+ joycon_attach(&left); joycon_attach(&right);
+ DMController *l=controller_for_joycon(&left), *r=controller_for_joycon(&right);
+ assert(l && r && l->slot==0 && r->slot==1 && players==(merged ? 1u : 3u));
+ assert(rumble[0]==pair);
+ if(!merged) assert(rumble[1]==pair && [rumble_locality[0] isEqual:GCHapticsLocalityLeftHandle] && [rumble_locality[1] isEqual:GCHapticsLocalityRightHandle]);
+ DMController *steam=[DMController new]; steam.name=@"Steam Controller"; steam.model=@"Valve Triton";
+ steam->device=(IOHIDDeviceRef)CFRetain(CFSTR("coexisting Steam")); steam->connected=YES; steam_write=fake_write;
+ controller_load_map(steam); [g_devices addObject:steam]; controller_connect(steam);
+ controllers_reconcile(@[pair]); assert(steam->slot==2 && g_devices.count==3 && players==(merged ? 1u : 7u));
+ assert(rumble[0]==pair && (merged || raw_output[2]));
+ controller_disconnect(steam); [g_devices removeObject:steam];
+ uint8_t report[49]={0x30}; report[1]=3; report[14]=16;
+ unsigned before=hid_motion_samples[merged ? 0 : r->slot];
+ joycon_read_motion(&right,report,sizeof report); assert(hid_motion_samples[merged ? 0 : r->slot]>before);
+ unsigned cleared=hid_motion_clears[0];
+ l->map[0]=3; left.st.buttons=DM_BTN_A; left.st.sx=.5f; joycon_read(&left);
+ right.st.buttons=DM_BTN_B; right.st.home=1; joycon_read(&right);
+ assert(received[0]==(DM_BTN_Y | (merged ? DM_BTN_B : 0)) && axes[0][0]>0);
+ if(!merged) assert(received[1]==DM_BTN_B);
+ int home,a,b; front_controllers_quit_buttons(&home,&a,&b); assert(home && a && b);
+ front_controllers_quit_prompt(1); assert(!received[0] && hid_motion_clears[0]>cleared);
+ front_controllers_quit_buttons(&home,&a,&b); assert(home && a && b);
+ front_controllers_quit_prompt(0); assert(received[0]&DM_BTN_Y);
+ front_controllers_window(0); assert(!received[0]);
+ front_controllers_window(1); assert(received[0]&DM_BTN_Y);
+ joycon_detach(&left); assert(!controller_for_joycon(&left));
+ assert(received[0]==(merged ? DM_BTN_B : 0));
+ joycon_detach(&right); assert(!g_devices.count && !players && !received[merged ? 0 : 1]);
+ g_joycon_split=0; controllers_reconcile(@[pair]); assert(g_devices.count==1);
+ [g_devices removeAllObjects]; native_devices=@[];
+ }
+ g_merge=0; g_slots=(pad_slots){0};
+ puts("Split Joy-Con shared slots, maps, focus, Home and combined-pair suppression: OK");
+}
+static void test_nintendo_labels(void) {
+ MotionController *c = [MotionController new];
+ DMController *d = controller_add_gc(c);
+ GCControllerButtonInput *buttons[] = {c.extendedGamepad.buttonA, c.extendedGamepad.buttonB, c.extendedGamepad.buttonX, c.extendedGamepad.buttonY};
+ uint64_t targets[] = {DM_BTN_A, DM_BTN_B, DM_BTN_X, DM_BTN_Y};
+ for (int i = 0; i < 4; i++) {
+ [buttons[i] setValue:1]; gc_event(d); assert(received[d->slot] == targets[i]);
+ [buttons[i] setValue:0]; gc_event(d); assert(!received[d->slot]);
+ }
+ d->map[0] = 3;
+ [c.extendedGamepad.buttonA setValue:1]; gc_event(d); assert(received[d->slot] == DM_BTN_Y);
+ controller_disconnect(d); [g_devices removeObject:d]; controller_pro_changed();
+ g_slots = (pad_slots){0};
+}
+static void test_native_motion_integration(void) {
+ for (int merged = 0; merged < 2; merged++) {
+ g_merge = merged; g_slots = (pad_slots){0};
+ static char keyboard; if (!merged) pad_slot_take(&g_slots, &keyboard, "keyboard");
+ MotionController *c = [MotionController new]; c.testMotion = [TestNativeMotion new];
+ TestNativeMotion *m = c.testMotion; m.hasRotationRate = YES; m.sensorsRequireManualActivation = YES;
+ m.acceleration = (GCAcceleration){0, 0, -1}; m.rotationRate = (GCRotationRate){0, 1, 0};
+ DMController *d = controller_add_gc(c);
+ [c.extendedGamepad.buttonB setValue:1]; gc_event(d);
+ int player = merged ? 0 : 1;
+ assert(d->slot == player && m.sensorsActive && m.valueChangedHandler);
+ assert(g_pro_controllers == 1 && g_pro_slot == player);
+ m.valueChangedHandler((id)m); assert(native_motion_player == player && native_motion_samples);
+ front_controllers_focus(0); assert(!m.sensorsActive && !m.valueChangedHandler && native_motion_cleared == player && !g_pro_active);
+ front_controllers_focus(1); assert(m.sensorsActive && m.valueChangedHandler && g_pro_active);
+ m.valueChangedHandler((id)m); assert(native_motion_player == player);
+ controller_disconnect(d); assert(!m.valueChangedHandler && !m.sensorsActive && g_pro_slot == -1);
+ [g_devices removeObject:d]; controller_pro_changed(); assert(g_pro_controllers == 0);
+ }
+ g_slots = (pad_slots){0}; g_merge = 0;
+}
+static void test_native_registration_race(void) {
+ NamedSteamController *native=[NamedSteamController new];
+ RacingLiveInput *input=[RacingLiveInput new]; input.snapshot=native.testInput.snapshot; native.testInput=input;
+ [native.extendedGamepad.buttonB setValue:1];
+ DMController *d=controller_add_gc(native);
+ input.elementValueDidChangeHandler((id)input,nil);
+ assert(d->slot<0 && !players); // cached button must not create a duplicate player
+ [g_devices removeObject:d];
+}
+static void test_raw_ownership(void) {
+ steam_write=fake_write;
+ DMController *raw=[DMController new], *empty=[DMController new];
+ raw->device=(IOHIDDeviceRef)CFRetain(CFSTR("raw")); empty->device=(IOHIDDeviceRef)CFRetain(CFSTR("empty"));
+ raw.name=empty.name=@"Steam Controller (2026)"; raw.model=empty.model=@"Valve Triton";
+ controller_load_map(raw); controller_load_map(empty);
+ GCController *native=[NamedSteamController new], *identical=[NamedSteamController new];
+ g_devices=[@[empty,raw] mutableCopy];
+ controllers_reconcile(@[native,identical]);
+ assert(raw->slot<0 && empty->slot<0 && !players); // idle Puck owns no player
+ raw->connected=YES; controllers_reconcile(@[native,identical]);
+ assert(raw->slot==0 && players==1 && raw_output[0]); // ambiguous names keep all raw features
+ empty->connected=YES; controllers_reconcile(@[native,identical]);
+ assert(empty->slot==1 && players==3 && raw_output[1]); // identical live devices remain independent
+ DMController *cached=g_devices[2], *unrelated=g_devices[3];
+ [native.extendedGamepad.buttonB setValue:1];
+ gc_event_at(cached,cached->gc_not_before); // event queued before the exclusive claim
+ assert(cached->slot<0 && players==3);
+ gc_event(unrelated); assert(unrelated->slot<0); // neutral events do not join
+ [identical.extendedGamepad.leftThumbstick.xAxis setValue:.01];
+ gc_event(unrelated); assert(unrelated->slot<0); // neither does idle stick noise
+ front_controllers_window(0); // joining from the mapping panel must work
+ [identical.extendedGamepad.buttonA setValue:1]; gc_event(unrelated);
+ assert(unrelated->slot==2 && players==7 && !received[2] && !output_focused);
+ front_controllers_window(1); gc_event(unrelated);
+ assert(unrelated->slot==2 && players==7 && received[2]==DM_BTN_B && rumble[2]==identical);
+ unsigned char packet[46]={0x42}; packet[30]=1; packet[39]=0x40; packet[45]=0x10;
+ for(DMController *d in @[raw,empty]) {
+ steam_report((__bridge void *)d,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,packet,46);
+ assert(motion_present[d->slot] && motions[d->slot].gyro[2]>0);
+ d->input.pad[0]=(steam_pad){1,25000,0,1}; d->input.pad[1]=(steam_pad){1,0,0,1}; controller_publish(d);
+ assert(received[d->slot]==DM_BTN_RIGHT);
+ raw_output[d->slot]((dm_haptic_state){.motor={{.amplitude_low=1}}},1);
+ assert(written_id==0x80 && steam_u16(written+4)==65535);
+ }
+ assert(ntouches==2 && touches[0].id!=touches[1].id);
+ raw->connected=NO; controllers_reconcile(@[native,identical]);
+ assert(raw->slot<0 && !raw_output[0] && !motion_present[0] && ntouches==1);
+ assert(empty->slot==1 && raw_output[1] && unrelated->slot==2 && rumble[2]==identical);
+ controllers_reconcile(@[native,identical]); assert(cached->slot<0); // cached profile cannot resurrect a slot
+ raw->connected=YES; controllers_reconcile(@[native,identical]); assert(raw->slot==0 && raw_output[0]);
+ for(DMController *d in g_devices) controller_disconnect(d);
+ g_devices=[NSMutableArray array]; g_slots=(pad_slots){0};
+}
+static void check_hid_stopped(IOHIDDeviceRef device) {
+ for(DMController *d in g_devices) if(d->device==device) {
+ assert(d->slot<0 && !d->motion.have_tick && d->touch_id[0]<0 && d->touch_id[1]<0);
+ }
+}
+static NSDictionary *hid_device(int id,int pid,int interface,int page,int usage,BOOL fail) {
+ NSDictionary *properties=@{@"registry":@(id), @kIOHIDVendorIDKey:@0x28de, @kIOHIDProductIDKey:@(pid),
+ @"interface":@(interface), @"elements":@[@{@"report":@(page==1 && (usage==2 || usage==6) ? 1 : 0x42), @"bits":@360}], @kIOHIDPrimaryUsagePageKey:@(page), @kIOHIDPrimaryUsageKey:@(usage), @"fail":@(fail), @kIOHIDPhysicalDeviceUniqueIDKey:[NSString stringWithFormat:@"fixture-%d",id]};
+ hid_registry[@(id)]=properties; return properties;
+}
+static void test_hid_ownership(void) {
+ hid_registry=[NSMutableDictionary dictionary]; hid_opened=[NSMutableDictionary dictionary];
+ hid_scheduled=[NSMutableDictionary dictionary]; hid_callbacks=[NSMutableDictionary dictionary];
+ g_steam_attempted=[NSMutableSet set]; steam_write=fake_write;
+ hid_device(1,0x1304,0,0xff00,1,NO); // Puck non-controller interface
+ hid_device(2,0x1302,0,1,2,NO); // composite mouse
+ hid_device(3,0x1303,0,1,6,NO); // composite keyboard
+ hid_device(4,0x1102,0,0xff00,1,NO); // original Steam Controller protocol
+ steam_discover(); assert(!hid_open_count); // opt-out: no HID manager
+ g_hid=(IOHIDManagerRef)CFSTR("test manager");
+ steam_discover(); assert(!hid_open_count && !g_devices.count);
+ NSDictionary *first=hid_device(5,0x1304,2,0xff00,1,NO);
+ NSDictionary *second=hid_device(6,0x1304,3,0xff00,1,NO);
+ hid_device(7,0x1302,0,0xff00,1,YES); // another owner denies exclusive access
+ steam_discover(); assert(hid_open_count==3 && g_devices.count==2 && !players);
+ DMController *raw=nil, *peer=nil;
+ for(DMController *d in g_devices) { if(d->registry_id==5) raw=d; if(d->registry_id==6) peer=d; }
+ assert(raw && peer && hid_scheduled.count==2);
+ // The manager's handle is a different object referring to the same service.
+ NSMutableDictionary *duplicate=[first mutableCopy];
+ assert((__bridge IOHIDDeviceRef)duplicate!=raw->device);
+ steam_added(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)duplicate);
+ assert(hid_open_count==3 && g_devices.count==2);
+ raw->connected=peer->connected=YES; controllers_changed(nil);
+ int player=raw->slot, peer_player=peer->slot;
+ assert(player>=0 && peer_player>=0 && player!=peer_player && players==3);
+ assert(raw_output[player] && raw_output[peer_player]);
+ raw->input.pad[1]=(steam_pad){1,0,0,1}; controller_publish(raw); assert(ntouches==1);
+ [hid_registry removeObjectForKey:@5]; // removal means registry scan no longer returns it
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)duplicate);
+ assert(hid_close_count==1 && hid_last_closed==(__bridge IOHIDDeviceRef)first);
+ assert(raw->slot<0 && !raw_output[player] && ntouches==0 && peer->slot==peer_player && raw_output[peer_player]);
+ assert(![g_steam_attempted containsObject:@5]);
+ // Failed claims do not suppress native controls or retry midway through play.
+ GCController *native=[NamedSteamController new]; controllers_reconcile(@[native]);
+ DMController *d=g_devices.lastObject; [native.extendedGamepad.buttonB setValue:1]; gc_event(d);
+ assert(d->slot>=0 && rumble[d->slot]==native);
+ steam_discover(); assert(hid_open_count==3);
+ controller_disconnect(d); [g_devices removeObject:d];
+ NSDictionary *failed=hid_registry[@7]; [hid_registry removeObjectForKey:@7];
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)failed);
+ assert(![g_steam_attempted containsObject:@7]);
+ hid_device(7,0x1302,0,0xff00,1,NO); steam_discover(); assert(hid_open_count==4);
+ // An unrelated hotplug must not interrupt already admitted native pads,
+ // including identical names and held buttons that produce no further event.
+ NamedSteamController *late=[NamedSteamController new], *unrelated=[NamedSteamController new];
+ DMController *late_pad=controller_add_gc(late), *native_peer=controller_add_gc(unrelated);
+ [late.extendedGamepad.buttonB setValue:1]; [unrelated.extendedGamepad.buttonA setValue:1];
+ gc_event_at(late_pad,12); gc_event_at(native_peer,12);
+ assert(late_pad->slot>=0 && native_peer->slot>=0);
+ int late_slot=late_pad->slot, native_slot=native_peer->slot;
+ unsigned old_routes=route_changes[native_slot], old_updates=pad_updates[native_slot];
+ late.testInput.lastEventLatency=unrelated.testInput.lastEventLatency=8; // claim time 20
+ NSDictionary *late_hid=hid_device(8,0x1303,0,0xff00,1,NO); steam_discover();
+ assert(late_pad->slot==late_slot && native_peer->slot==native_slot && peer->slot==peer_player);
+ assert(received[late_slot]==DM_BTN_A && received[native_slot]==DM_BTN_B && rumble[native_slot]==unrelated);
+ assert(route_changes[native_slot]==old_routes && pad_updates[native_slot]==old_updates);
+ controller_disconnect(late_pad); controller_disconnect(native_peer); [g_devices removeObject:late_pad]; [g_devices removeObject:native_peer];
+ [hid_registry removeObjectForKey:@8]; steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)late_hid);
+ for(NSDictionary *device in @[second,hid_registry[@7]]) {
+ [hid_registry removeObjectForKey:device[@"registry"]];
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)device);
+ }
+ assert(!players && !g_devices.count && !hid_opened.count && hid_close_count==4);
+ g_hid=NULL; g_slots=(pad_slots){0};
+}
+static void hid_fixture_start(void) {
+ hid_registry=[NSMutableDictionary dictionary]; hid_opened=[NSMutableDictionary dictionary];
+ hid_scheduled=[NSMutableDictionary dictionary]; hid_callbacks=[NSMutableDictionary dictionary];
+ g_steam_hids=nil; g_steam_fallback=nil; hid_nodes=[NSMutableDictionary dictionary];
+ g_steam_attempted=[NSMutableSet set]; g_hid=(IOHIDManagerRef)CFSTR("test manager"); steam_write=fake_write;
+}
+static void hid_fixture_finish(void) {
+ native_devices=nil;
+ for(NSDictionary *device in hid_registry.allValues.copy) {
+ [hid_registry removeObjectForKey:device[@"registry"]];
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)device);
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)device);
+ }
+ for(DMController *d in g_devices) controller_disconnect(d);
+ g_devices=[NSMutableArray array]; g_slots=(pad_slots){0}; g_hid=NULL;
+ assert(!g_hidpads && (!g_hidpad_waiting || !CFArrayGetCount(g_hidpad_waiting)));
+}
+static void test_native_event_admission(BOOL composite) {
+ hid_fixture_start();
+ NamedSteamController *other=[NamedSteamController new], *late=[NamedSteamController new];
+ native_devices=@[other,late];
+ DMController *held=controller_add_gc(other);
+ [other.extendedGamepad.buttonA setValue:1]; [other.extendedGamepad.leftThumbstick.xAxis setValue:.5]; gc_event(held);
+ assert(held->slot==0 && received[0]==DM_BTN_B && axes[0][0]==16383);
+ unsigned routes=route_changes[0], updates=pad_updates[0];
+ DMController *candidate=controller_add_gc(late); // native notification beats HID callback
+ [late.extendedGamepad.buttonB setValue:1]; late.testInput.lastEventLatency=8;
+ NSMutableDictionary *source=[hid_device(9,0x1304,2,1,composite ? 2 : 5,NO) mutableCopy];
+ source[@"native"]=@YES; hid_registry[@9]=source;
+ if(composite) {
+ // Two collections in the same Puck port share its interface ancestor.
+ hid_nodes[@9]=@{@"parent":@102}; hid_nodes[@102]=@{@"class":@"IOUSBHostInterface"};
+ steam_discover(); assert(!hid_opened.count); // native-only discovery remains undecided
+ gc_event_at(candidate,10); // stale cached input cannot commit native fallback
+ [late.extendedGamepad.buttonB setValue:0]; gc_event_at(candidate,12); // neither can neutral input
+ assert(candidate->slot<0 && !g_steam_fallback.count);
+ [late.extendedGamepad.buttonB setValue:1];
+ hid_device(10,0x1304,2,0xff00,1,NO); hid_nodes[@10]=@{@"parent":@102};
+ }
+ gc_event_at(candidate,12); // first physical event must discover and claim its source
+ assert(candidate->slot<0 && hid_opened[@9] && players==1);
+ assert(held->slot==0 && received[0]==DM_BTN_B && axes[0][0]==16383 && rumble[0]==other);
+ assert(route_changes[0]==routes && pad_updates[0]==updates);
+ DMController *raw=g_devices.lastObject;
+ if(composite) {
+ assert(hid_opened[@9] && hid_opened[@10]);
+ assert(!hid_callbacks[@9] && hid_callbacks[@10]); // suppression-only source has no decoder
+ }
+ unsigned char packet[46]={0x42}; packet[30]=1; packet[39]=0x40; packet[45]=0x10;
+ steam_report((__bridge void *)raw,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,packet,46);
+ assert(raw->slot==1 && motion_present[1] && raw_output[1] && candidate->slot<0 && players==3);
+ assert(held->slot==0 && received[0]==DM_BTN_B && route_changes[0]==routes && pad_updates[0]==updates);
+ gc_event_at(candidate,19); assert(candidate->slot<0); // queued pre-claim native input stays suppressed
+ for(NSDictionary *device in hid_registry.allValues.copy) {
+ [hid_registry removeObjectForKey:device[@"registry"]];
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)device);
+ assert(held->slot==0 && received[0]==DM_BTN_B && rumble[0]==other && route_changes[0]==routes && pad_updates[0]==updates);
+ }
+ hid_fixture_finish();
+}
+static void test_sibling_fallback(int failure) {
+ hid_fixture_start();
+ NamedSteamController *other=[NamedSteamController new], *native=[NamedSteamController new];
+ native_devices=@[other,native];
+ DMController *held=controller_add_gc(other); [other.extendedGamepad.buttonA setValue:1]; gc_event(held);
+ unsigned routes=route_changes[0], updates=pad_updates[0];
+ DMController *candidate=controller_add_gc(native); [native.extendedGamepad.buttonB setValue:1];
+ // Direct USB siblings can be different interfaces of one controller.
+ NSMutableDictionary *source=[hid_device(9,0x1302,0,1,5,failure==1) mutableCopy];
+ source[@"elements"]=@[@{@"report":@1,@"bits":@360}]; // standard gamepad, no Triton state
+ source[@"native"]=@YES; hid_registry[@9]=source;
+ hid_nodes[@9]=@{@"parent":@100}; hid_nodes[@100]=@{@"class":@"IOUSBHostDevice"};
+ if(failure==3) {
+ gc_event(candidate); // native admission freezes this unresolved group
+ assert(candidate->slot==1 && !hid_opened.count);
+ }
+ hid_device(10,0x1302,2,0xff00,1,failure==2); hid_nodes[@10]=@{@"parent":@100};
+ steam_discover();
+ if(failure) {
+ assert(!hid_opened.count && !hid_scheduled.count && !hid_callbacks.count);
+ gc_event(candidate); assert(candidate->slot==1 && players==3 && rumble[1]==native);
+ assert(!raw_output[1] && received[1]==DM_BTN_A);
+ // A rescan cannot seize the successful sibling behind native fallback.
+ int opens=hid_open_count; steam_discover(); assert(hid_open_count==opens);
+ } else {
+ assert(hid_opened.count==2 && hid_callbacks.count==1 && !hid_callbacks[@9]);
+ DMController *raw=g_steam_hids[@10].raw; assert(raw);
+ unsigned char packet[46]={0x42}; packet[30]=1;
+ steam_report((__bridge void *)raw,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,packet,46);
+ assert(raw->slot==1 && candidate->slot<0 && players==3);
+ }
+ assert(held->slot==0 && received[0]==DM_BTN_B && rumble[0]==other);
+ assert(route_changes[0]==routes && pad_updates[0]==updates);
+ hid_fixture_finish(); assert(!hid_opened.count);
+}
+static void test_puck_transaction_isolation(void) {
+ hid_fixture_start();
+ hid_nodes[@9]=@{@"parent":@102}; hid_nodes[@102]=@{@"class":@"IOUSBHostInterface",@"parent":@100};
+ hid_nodes[@10]=@{@"parent":@103}; hid_nodes[@103]=@{@"class":@"IOUSBHostInterface",@"parent":@100};
+ hid_nodes[@100]=@{@"class":@"IOUSBHostDevice"};
+ hid_device(9,0x1304,2,0xff00,1,NO); hid_device(10,0x1304,3,0xff00,1,NO); steam_discover();
+ DMController *peer=g_steam_hids[@9].raw, *raw=g_steam_hids[@10].raw;
+ peer->connected=raw->connected=YES; controllers_changed(nil);
+ int slot=peer->slot; assert(slot>=0 && slot<DM_PLAYERS);
+ peer->input.buttons=DM_BTN_B; controller_publish(peer);
+ unsigned routes=route_changes[slot], updates=pad_updates[slot];
+ // A late native collection fails on port 3; only port 3 rolls back.
+ NSMutableDictionary *source=[hid_device(11,0x1304,3,1,2,YES) mutableCopy];
+ source[@"native"]=@YES; hid_registry[@11]=source; hid_nodes[@11]=@{@"parent":@103}; steam_discover();
+ assert(raw->slot<0 && !hid_opened[@10] && hid_opened[@9]);
+ assert(peer->slot==slot && received[slot]==DM_BTN_B && raw_output[slot]);
+ assert(route_changes[slot]==routes && pad_updates[slot]==updates);
+ // Removing one sibling cannot clear the failure latch for the remaining one.
+ [hid_registry removeObjectForKey:@11]; steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)source);
+ int opens=hid_open_count; steam_discover(); assert(hid_open_count==opens);
+ hid_fixture_finish(); assert(!hid_opened.count);
+}
+static void test_unknown_hid_identity(BOOL raw_first) {
+ hid_fixture_start();
+ NSMutableDictionary *device=[hid_device(9,0x1303,0,0xff00,1,NO) mutableCopy];
+ device[@"native"]=@YES; device[@kIOHIDPhysicalDeviceUniqueIDKey]=@42; hid_registry[@9]=device;
+ if(raw_first) {
+ [hid_registry removeObjectForKey:@9];
+ hid_device(10,0x1303,0,0xff00,1,NO); steam_discover();
+ DMController *raw=g_steam_hids[@10].raw; assert(raw);
+ raw->connected=YES; controllers_changed(nil);
+ assert(raw->slot==0); raw->input.buttons=DM_BTN_A; controller_publish(raw);
+ hid_registry[@9]=device;
+ }
+ NamedSteamController *native=[NamedSteamController new]; native_devices=@[native];
+ DMController *d=controller_add_gc(native); [native.extendedGamepad.buttonA setValue:1]; gc_event(d);
+ if(raw_first) {
+ assert(d->slot<0 && hid_opened.count==1 && players==1 && received[0]==DM_BTN_A);
+ } else {
+ assert(d->slot==0 && received[0]==DM_BTN_B && !hid_opened.count);
+ // A sibling with asymmetric metadata must not create a raw duplicate.
+ hid_device(10,0x1303,0,0xff00,1,NO); steam_discover();
+ assert(!hid_opened.count && players==1 && received[0]==DM_BTN_B);
+ [hid_registry removeObjectForKey:@9]; steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)device);
+ steam_discover(); assert(!hid_opened.count); // latch lasts for the remaining sibling
+ }
+ hid_fixture_finish();
+}
+static void test_protocol_metadata(void) {
+ BOOL complete=YES;
+ NSDictionary *short_report=@{@"elements":@[@{@"report":@0x42,@"bits":@180,@"count":@2}]};
+ assert(!steam_protocol((__bridge IOHIDDeviceRef)short_report,&complete) && complete);
+ NSDictionary *array_report=@{@"elements":@[@{@"report":@0x45,@"bits":@8,@"count":@45,@"array":@YES}]};
+ assert(steam_protocol((__bridge IOHIDDeviceRef)array_report,&complete) && complete);
+ assert(!steam_protocol((__bridge IOHIDDeviceRef)@{},&complete) && !complete);
+}
+static void test_incomplete_discovery(void) {
+ hid_fixture_start();
+ NamedSteamController *c=[NamedSteamController new]; native_devices=@[c];
+ DMController *d=controller_add_gc(c); [c.extendedGamepad.buttonB setValue:1];
+ hid_scan_fails=YES; gc_event(d); assert(d->slot<0 && !players); hid_scan_fails=NO;
+ hid_scan_invalid=YES; gc_event(d); assert(d->slot<0 && !players); hid_scan_invalid=NO;
+ NSMutableDictionary *device=[hid_device(9,0x1302,0,0xff00,1,NO) mutableCopy]; hid_registry[@9]=device;
+ device[@"create_fail"]=@YES; gc_event(d); assert(d->slot<0 && !players); [device removeObjectForKey:@"create_fail"];
+ device[@"registry"]=@0; gc_event(d); assert(d->slot<0 && !players); device[@"registry"]=@9;
+ [device removeObjectForKey:@kIOHIDPrimaryUsagePageKey]; gc_event(d); assert(d->slot<0 && !players);
+ [hid_registry removeAllObjects]; hid_scan_empty=YES;
+ gc_event(d); assert(d->slot==0 && received[0]==DM_BTN_A); hid_scan_empty=NO;
+ hid_fixture_finish();
+ // The opt-out admits native input even if raw discovery would fail.
+ hid_scan_fails=YES; c=[NamedSteamController new]; d=controller_add_gc(c);
+ [c.extendedGamepad.buttonB setValue:1]; gc_event(d); assert(d->slot==0 && received[0]==DM_BTN_A);
+ controller_disconnect(d); [g_devices removeObject:d]; hid_scan_fails=NO; g_slots=(pad_slots){0};
+}
+@interface TestHaptics : NSObject @end
+@implementation TestHaptics
+- (NSArray *)supportedLocalities { return @[GCHapticsLocalityDefault]; }
+@end
+@interface HapticController : NamedSteamController @end
+@implementation HapticController
+- (GCDeviceHaptics *)haptics { return (id)[TestHaptics new]; }
+@end
+static void test_merged_hotplug(void) {
+ g_merge=1; steam_write=fake_write;
+ DMController *puck=[DMController new]; puck.name=@"Steam Controller (2026)"; puck.model=@"Valve Triton";
+ puck->device=(IOHIDDeviceRef)CFRetain(CFSTR("idle Puck")); [g_devices addObject:puck]; controller_load_map(puck);
+ GCController *c=[HapticController new]; DMController *held=controller_add_gc(c);
+ [c.extendedGamepad.buttonA setValue:1]; gc_event(held);
+ assert(rumble[0]==c && received[0]==DM_BTN_B);
+ unsigned routes=route_changes[0];
+ puck->connected=YES; controller_connect(puck); controller_publish(puck);
+ assert(held->slot==0 && received[0]==DM_BTN_B && rumble[0]==c && route_changes[0]==routes);
+ controller_disconnect(puck); assert(rumble[0]==c && received[0]==DM_BTN_B && route_changes[0]==routes);
+ controller_connect(puck); controller_disconnect(held); assert(raw_output[0]); // ownership changes only when current owner leaves
+ controller_disconnect(puck); assert(!raw_output[0] && !rumble[0]);
+ g_devices=[NSMutableArray array]; g_slots=(pad_slots){0}; g_merge=0;
+}
+// A launcher-authored map must reach both adapters, and a panel edit must be
+// visible to the launcher in the same domain. Each run owns a disposable domain.
+static void test_shared_controls(void) {
+ NSString *domain=[@"org.nxnative.test.controls." stringByAppendingString:NSUUID.UUID.UUIDString];
+ g_controls_domain=domain;
+ CFPreferencesSetAppValue(CFSTR("launcher.DM_PAD_MAP"),CFSTR("A=B,B=A"),(__bridge CFStringRef)domain);
+ assert(CFPreferencesAppSynchronize((__bridge CFStringRef)domain));
+ controller_reload_maps();
+ DMController *native=[DMController new]; native.model=@"Native"; controller_load_map(native);
+ DMController *steam=[DMController new]; steam.model=@"Valve Triton"; controller_load_map(steam);
+ assert(native->map[0]==1 && steam->map[1]==0);
+ [g_devices addObject:native]; [g_devices addObject:steam];
+ assert(controller_set_button(0,3));
+ assert(native->map[0]==3 && steam->map[0]==3);
+ id saved=CFBridgingRelease(CFPreferencesCopyAppValue(CFSTR("launcher.DM_PAD_MAP"),(__bridge CFStringRef)domain));
+ assert([saved isEqual:@"A=Y,B=A"]);
+ // Extra buttons are final Switch targets: the shared map is not applied twice.
+ steam->map[16]=0; steam->pad_mode[0]=PAD_RIGHT_STICK; steam->gyro_enabled=NO;
+ assert(controller_save_map(steam)); controller_load_map(steam);
+ assert(pad_map_buttons(1u<<16,steam->map)==DM_BTN_A && steam->pad_mode[0]==PAD_RIGHT_STICK && !steam->gyro_enabled);
+ // Standalone and launcher/file overrides are temporary and lock standard rows.
+ setenv("DM_PAD_MAP","A=X",1); unsetenv("DM_ENV_LAUNCH_KEYS"); controller_reload_maps();
+ assert(steam->map[0]==2 && g_map_fixed && !controller_set_button(0,1));
+ unsetenv("DM_PAD_MAP"); setenv("DM_ENV_LAUNCH_KEYS","",1); controller_reload_maps();
+ assert(steam->map[0]==3 && !g_map_fixed);
+ // Launcher-exported saved values are refreshed from the domain, not mistaken for overrides.
+ setenv("DM_PAD_MAP","A=B",1); controller_reload_maps(); assert(steam->map[0]==3);
+ setenv("DM_ENV_FILE_KEYS","DM_PAD_MAP",1); controller_reload_maps(); assert(steam->map[0]==1 && g_map_fixed);
+ unsetenv("DM_ENV_FILE_KEYS"); unsetenv("DM_PAD_MAP"); unsetenv("DM_ENV_LAUNCH_KEYS");
+ setenv("DM_SAVED_CHOICES","0",1); controller_reload_maps();
+ assert(steam->map[0]==0 && steam->map[16]==-1 && steam->gyro_enabled);
+ assert(controller_set_button(0,2)); steam->map[16]=1; assert(controller_save_map(steam));
+ controller_reload_maps(); assert(steam->map[0]==2 && steam->map[16]==1);
+ saved=CFBridgingRelease(CFPreferencesCopyAppValue(CFSTR("launcher.DM_PAD_MAP"),(__bridge CFStringRef)domain));
+ assert([saved isEqual:@"A=Y,B=A"]);
+ unsetenv("DM_SAVED_CHOICES"); controller_reload_maps(); assert(steam->map[0]==3 && steam->map[16]==0);
+ // A model dictionary cannot override standard buttons or reinterpret malformed fields.
+ NSDictionary *bad=@{@"buttons":@{@"0":@2,@"16":@1.5,@"17":@63,@"18":@64},@"pads":@[@1.5,@5],@"gyro":@"false"};
+ CFPreferencesSetAppValue(CFSTR("controller.Valve Triton"),(__bridge CFDictionaryRef)bad,(__bridge CFStringRef)domain);
+ controller_reload_maps();
+ assert(steam->map[0]==3 && steam->map[16]==-1 && steam->map[17]==63 && steam->map[18]==-1);
+ assert(steam->pad_mode[0]==PAD_DPAD && steam->pad_mode[1]==PAD_TOUCH && steam->gyro_enabled);
+ // Removing a choice restores defaults; a bad value cannot partially change a saved map.
+ CFPreferencesSetAppValue(CFSTR("launcher.DM_PAD_MAP"),CFSTR("A=X,Q=B"),(__bridge CFStringRef)domain);
+ controller_reload_maps(); assert(steam->map[0]==0);
+ assert(controller_set_button(0,63)); controller_reload_maps(); assert(steam->map[0]==63);
+ assert(controller_set_button(0,0));
+ assert(!CFPreferencesCopyAppValue(CFSTR("launcher.DM_PAD_MAP"),(__bridge CFStringRef)domain));
+ for(NSString *key in @[@"launcher.DM_PAD_MAP",@"controller.Valve Triton"]) CFPreferencesSetAppValue((__bridge CFStringRef)key,NULL,(__bridge CFStringRef)domain);
+ assert(CFPreferencesAppSynchronize((__bridge CFStringRef)domain));
+ g_devices=[NSMutableArray array];
+}
+// The OS boundary supplies real decoder values; routing, mappings, focus and
+// mixed transport ownership are the production code above, with no device I/O.
+static NSDictionary *generic_device(int id) {
+ return @{@"registry":@(id), @"generic":@YES, @kIOHIDVendorIDKey:@PAD_HID_DEFAULT_VENDOR,
+ @kIOHIDProductIDKey:@1, @kIOHIDProductKey:@"8BitDo fixture",
+ @"elements":@[@{@"page":@1,@"usage":@0x30},@{@"page":@1,@"usage":@0x31}]};
+}
+static void generic_value(hid_pad *pad,int page,int usage,int value,int min,int max) {
+ NSDictionary *v=@{@"element":@{@"page":@(page),@"usage":@(usage),@"min":@(min),@"max":@(max)},@"value":@(value)};
+ hidpad_value(pad,kIOReturnSuccess,NULL,(__bridge IOHIDValueRef)v);
+}
+// The real adapter callbacks and prompt state machine, without a window or a
+// wall-clock delay. Only admitted GC/Triton inputs can operate the prompt.
+static void test_home_quit_routing(void) {
+ hid_fixture_start();
+ DMController *raw=[DMController new]; raw.name=raw.model=@"Triton";
+ raw->device=(IOHIDDeviceRef)CFRetain(CFSTR("quit controller")); raw->connected=YES;
+ raw->map[22]=0; // short Guide presses deliver Switch A
+ raw->map[0]=raw->map[1]=3; // both physical face buttons deliver Switch Y
+ [g_devices addObject:raw]; controller_connect(raw);
+ const int raw_slot=raw->slot; assert(raw_slot==0);
+
+ NamedSteamController *native=[NamedSteamController new], *cached=[NamedSteamController new];
+ native_devices=@[native,cached];
+ controller_add_gc(cached); [cached.extendedGamepad.buttonA setValue:1]; // no fresh input to admit this profile
+ DMController *gc=controller_add_gc(native);
+ [native.extendedGamepad.buttonX setValue:1]; gc_event(gc);
+ const int gc_slot=gc->slot; assert(gc_slot==1);
+ NSDictionary *props=generic_device(907); IOHIDDeviceRef hid=(__bridge IOHIDDeviceRef)props;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,hid);
+ DMController *generic=controller_for_hid(g_hidpads); assert(generic);
+ const int generic_slot=generic->slot; assert(generic_slot==2);
+ generic_value(g_hidpads,9,2,1,0,1);
+
+ __block home_quit q={0}; __block double now=0;
+ test_home_poll=^{
+ int home,a,b; front_controllers_quit_buttons(&home,&a,&b);
+ front_controllers_quit_prompt(hq_blocks_input(hq_step(&q,now,home,a,b)));
+ };
+ void (^report)(unsigned char,unsigned char)=^(unsigned char faces,unsigned char guide) {
+ uint8_t bytes[46]={0x42,0,faces,0,guide};
+ steam_report((__bridge void *)raw,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,bytes,sizeof bytes);
+ };
+ GCControllerButtonInput *logo=native.extendedGamepad.buttonHome;
+ assert(logo && logo.pressedChangedHandler);
+ [logo setValue:1]; logo.pressedChangedHandler(logo,1,YES);
+ int home,a,b; assert(front_controllers_quit_buttons(&home,&a,&b)==native && home && !a && !b);
+ assert(q.phase==HQ_HOLDING); now+=HQ_HOLD_S; front_home_poll(); assert(q.phase==HQ_PROMPT);
+ [logo setValue:0]; logo.pressedChangedHandler(logo,0,NO);
+ [logo setValue:1]; logo.pressedChangedHandler(logo,1,YES); assert(q.phase==HQ_SETTLE);
+ [logo setValue:0]; logo.pressedChangedHandler(logo,0,NO); assert(q.phase==HQ_IDLE);
+
+ report(0,1);
+ assert(q.phase==HQ_HOLDING && received[raw_slot]==DM_BTN_A && received[generic_slot]==DM_BTN_A);
+ dm_touch finger={0,.5,.5}; front_controllers_mouse(&finger);
+ now+=HQ_HOLD_S; front_home_poll();
+ assert(q.phase==HQ_PROMPT && !output_focused && !received[raw_slot] && !received[gc_slot] && !received[generic_slot] && !ntouches);
+ report(0,0); assert(q.phase==HQ_PROMPT); // the cached native A cannot quit
+ report(2,0); assert(q.phase==HQ_SETTLE && !received[raw_slot]); // raw wire B cancels despite remapping
+ front_controllers_mouse(&finger); assert(!ntouches);
+ report(0,0); assert(q.phase==HQ_IDLE && output_focused && received[gc_slot] && received[generic_slot]==DM_BTN_A);
+ report(0,1); now+=HQ_HOLD_S; front_home_poll(); assert(q.phase==HQ_PROMPT);
+ front_controllers_window(0); hq_cancel(&q); front_controllers_quit_prompt(0);
+ front_controllers_window(1); assert(q.phase==HQ_IDLE); // raw Guide held across focus loss
+ report(0,0); report(0,1); now+=HQ_HOLD_S; front_home_poll();
+ report(0,0); [native.extendedGamepad.buttonB setValue:1]; gc_event(gc);
+ assert(q.phase==HQ_SETTLE && !received[gc_slot]); // native B cancels a raw Guide hold
+ [native.extendedGamepad.buttonB setValue:0]; gc_event(gc);
+ assert(q.phase==HQ_IDLE && received[gc_slot]);
+ report(0,1); now+=HQ_HOLD_S; front_home_poll(); report(1,1);
+ assert(q.phase==HQ_QUIT && !received[raw_slot]); // wire A quits, regardless of its guest mapping
+ test_home_poll=nil; front_controllers_quit_prompt(0);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,hid); hid_fixture_finish();
+ puts("Home quit: adapter ownership, physical labels, prompt/settle gating and focus recovery: OK");
+}
+static void test_generic_hid_routing(void) {
+ for(int merged=0;merged<2;merged++) {
+ hid_fixture_start(); g_merge=merged; g_slots=(pad_slots){0};
+ static char keyboard; if(!merged) pad_slot_take(&g_slots,&keyboard,"keyboard");
+ NamedSteamController *native=[NamedSteamController new]; native_devices=@[native];
+ DMController *gc=controller_add_gc(native); [native.extendedGamepad.buttonA setValue:1];
+ unsigned activity=pointer_activity; gc_event(gc); assert(pointer_activity>activity);
+ int gcslot=gc->slot; assert(gcslot==(merged ? 0 : 1));
+ NSDictionary *props=generic_device(901); IOHIDDeviceRef hid=(__bridge IOHIDDeviceRef)props;
+ setenv("DM_HID_MAP","A=3",1); hidpad_found(NULL,kIOReturnSuccess,NULL,hid); unsetenv("DM_HID_MAP");
+ hid_pad *pad=g_hidpads; assert(pad && pad->hid==hid);
+ DMController *d=controller_for_hid(pad); assert(d && !d->device && !d.controller);
+ assert(d->slot==(merged ? 1 : 2) && gc->slot==gcslot && players==(merged ? 1u : 7u));
+ assert(pad->st.has[PH_X] && pad->st.has[PH_Y]);
+ assert(rumble[gcslot]==native && !raw_output[d->slot]);
+ CFIndex old_written=written_n; steam_keepalive(d); assert(written_n==old_written);
+ d->map[0]=3; // raw usage3 -> A, then shared A -> Y
+ int player=merged ? 0 : d->slot;
+ activity=pointer_activity; generic_value(pad,9,3,1,0,1);
+ assert(received[player]==(DM_BTN_Y | (merged ? DM_BTN_B : 0)) && pointer_activity>activity);
+ generic_value(pad,1,0x30,100,0,100); assert(axes[player][0]==DM_STICK_MAX);
+ front_controllers_window(0); assert(!received[player] && !axes[player][0]);
+ activity=pointer_activity; generic_value(pad,9,3,0,0,1); generic_value(pad,9,3,1,0,1);
+ assert(!received[player] && pointer_activity==activity);
+ front_controllers_window(1); assert(received[player]==(DM_BTN_Y | (merged ? DM_BTN_B : 0)) && axes[player][0]==DM_STICK_MAX);
+ hidpad_found(NULL,kIOReturnSuccess,NULL,hid); assert(g_hidpads==pad && !pad->next);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,hid);
+ assert(!g_hidpads && !d->generic && ![g_devices containsObject:d] && !hid_opened[@901]);
+ assert(received[player]==(merged ? DM_BTN_B : 0) && rumble[gcslot]==native);
+ hidpad_found(NULL,kIOReturnSuccess,NULL,hid); assert(controller_for_hid(g_hidpads)->slot==(merged ? 1 : 2));
+ controller_disconnect(gc); [g_devices removeObject:gc]; native_devices=@[];
+ activity=pointer_activity; generic_value(g_hidpads,1,0x30,51,0,100); assert(pointer_activity==activity); // drift
+ generic_value(g_hidpads,1,0x30,100,0,100); assert(pointer_activity>activity);
+ generic_value(g_hidpads,1,0x30,50,0,100);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,hid); assert(!received[player] && !hid_opened.count);
+ hid_fixture_finish(); g_merge=0;
+ }
+ puts("Generic HID mixed slots, remapping, focus, merged release and pointer activity: OK");
+}
+static void test_generic_hid_ownership(void) {
+ hid_fixture_start();
+ // Reject native/synthetic devices before opening, and leave no state on failure.
+ for(NSString *key in @[@"native",@kIOHIDGCSyntheticDeviceKey,@"fail"]) {
+ NSMutableDictionary *props=[generic_device(902) mutableCopy]; props[key]=@YES;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)props);
+ assert(!g_hidpads && !hid_opened.count && !g_devices.count);
+ }
+ // Callback order cannot let a generic sibling pre-open the raw group.
+ NSMutableDictionary *sibling=[hid_device(903,0x1302,0,1,5,NO) mutableCopy];
+ sibling[@"elements"]=@[]; sibling[@kIOHIDPhysicalDeviceUniqueIDKey]=@"mixed";
+ hid_registry[@903]=sibling;
+ NSMutableDictionary *protocol=[hid_device(904,0x1302,1,0xff00,1,NO) mutableCopy];
+ protocol[@kIOHIDPhysicalDeviceUniqueIDKey]=@"mixed"; hid_registry[@904]=protocol;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)sibling);
+ assert(!g_hidpads && hid_opened.count==2 && g_devices.count==1);
+ DMController *raw=g_devices.firstObject; assert(raw->device && !raw->generic);
+ raw->connected=YES; controllers_reconcile(@[]);
+ raw->input.buttons=DM_BTN_A; unsigned activity=pointer_activity; controller_publish(raw); assert(pointer_activity>activity);
+ hid_fixture_finish();
+ // Failed raw ownership permits an unsupported standard collection to work
+ // generically, and that admitted fallback cannot be seized by later scans.
+ hid_fixture_start();
+ sibling=[hid_device(905,0x1302,0,1,5,NO) mutableCopy];
+ sibling[@"elements"]=@[]; sibling[@"generic"]=@YES; sibling[@kIOHIDPhysicalDeviceUniqueIDKey]=@"fallback";
+ hid_registry[@905]=sibling;
+ protocol=[hid_device(906,0x1302,1,0xff00,1,YES) mutableCopy];
+ protocol[@kIOHIDPhysicalDeviceUniqueIDKey]=@"fallback"; hid_registry[@906]=protocol;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)sibling);
+ assert(g_hidpads && g_devices.count==1 && !g_devices.firstObject->device);
+ assert([g_steam_fallback containsObject:@"hid:4866:fallback:-1"]);
+ unsigned opened=hid_open_count;
+ protocol[@"fail"]=@NO; // permission becomes available, but no mid-play takeover
+ steam_discover(); assert((unsigned)hid_open_count==opened && g_devices.count==1);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)sibling); hid_fixture_finish();
+ hid_fixture_start();
+ setenv("DM_HID_PADS","0",1); hidpad_start(); unsetenv("DM_HID_PADS");
+ assert(!g_hidpad_manager && g_hid); // generic opt-out does not disable Triton
+ g_hid=NULL; // DM_STEAM_HID=0: generic gamepads remain independently available
+ NSDictionary *plain=generic_device(907);
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)plain); assert(g_hidpads);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)plain); hid_fixture_finish();
+ puts("Generic HID GC/synthetic exclusions and Triton ownership coordination: OK");
+}
+static void test_generic_unknown_identity(void) {
+ for(int raw_first=0;raw_first<2;raw_first++) {
+ hid_fixture_start();
+ NSDictionary *raw=hid_device(908,0x1302,1,0xff00,1,NO);
+ if(raw_first) steam_discover(); else [hid_registry removeObjectForKey:@908];
+ NSMutableDictionary *unknown=[hid_device(909,0x1302,0,1,5,NO) mutableCopy];
+ unknown[@"elements"]=@[]; unknown[@"generic"]=@YES;
+ [unknown removeObjectForKey:@kIOHIDPhysicalDeviceUniqueIDKey]; hid_registry[@909]=unknown;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)unknown);
+ if(raw_first) {
+ assert(!g_hidpads && g_devices.count==1 && g_devices.firstObject->device);
+ [hid_registry removeObjectForKey:@908];
+ steam_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)raw);
+ assert(g_hidpads && g_devices.count==1 && !g_devices.firstObject->device);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)unknown);
+ } else {
+ assert(g_hidpads && g_devices.count==1 && !g_devices.firstObject->device);
+ hid_registry[@908]=raw; steam_discover();
+ assert(hid_opened.count==1 && !g_devices.firstObject->device);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)unknown);
+ }
+ hid_fixture_finish();
+ }
+ // Incomplete registry scans defer input without losing the matching event.
+ hid_fixture_start();
+ NSMutableDictionary *deferred=[hid_device(910,0x1302,0,1,5,NO) mutableCopy];
+ deferred[@"elements"]=@[]; deferred[@"generic"]=@YES; hid_registry[@910]=deferred;
+ hid_scan_fails=YES; hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)deferred);
+ assert(!g_hidpads); hid_scan_fails=NO; controllers_changed(nil); assert(g_hidpads);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)deferred); hid_fixture_finish();
+ // Puck interface metadata is optional for a standard nonprotocol gamepad;
+ // without it no physical port may be guessed for a raw ownership claim.
+ hid_fixture_start();
+ NSMutableDictionary *puck=[hid_device(911,0x1304,-1,1,5,NO) mutableCopy];
+ puck[@"elements"]=@[]; puck[@"generic"]=@YES; hid_registry[@911]=puck;
+ hidpad_found(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)puck);
+ assert(g_hidpads && g_devices.count==1 && !g_devices.firstObject->device);
+ hidpad_removed(NULL,kIOReturnSuccess,NULL,(__bridge IOHIDDeviceRef)puck); hid_fixture_finish();
+ puts("Generic HID missing identity and deferred admission recover without duplicate raw routes: OK");
+}
+int main(int argc, char **argv) {
+ @autoreleasepool {
+ g_devices = [NSMutableArray array]; g_maps = [NSMutableDictionary dictionary];
+ pad_map_default(&g_button_map);
+ // Upstream focus handling releases only input the front end owns;
+ // DM_CTL may be holding a scripted finger with no mouse/pad touch.
+ dm_touch scripted={0,.25,.75}; dm_touch_set(&scripted,1);
+ front_controllers_window(0); assert(ntouches==1 && touches[0].x==.25);
+ front_controllers_window(1); dm_touch_set(NULL,0);
+ test_split_joycon_routing();
+ test_nintendo_labels();
+ test_native_motion_integration();
+ test_native_registration_race();
+ test_protocol_metadata();
+ test_raw_ownership();
+ test_hid_ownership();
+ test_native_event_admission(NO);
+ test_native_event_admission(YES);
+ for(int failure=0;failure<4;failure++) test_sibling_fallback(failure);
+ test_puck_transaction_isolation();
+ test_unknown_hid_identity(NO);
+ test_unknown_hid_identity(YES);
+ test_incomplete_discovery();
+ test_merged_hotplug();
+ test_generic_hid_routing();
+ test_home_quit_routing();
+ test_generic_hid_ownership();
+ test_generic_unknown_identity();
+ test_shared_controls();
+ NSString *tmp = [NSTemporaryDirectory() stringByAppendingPathComponent:NSUUID.UUID.UUIDString];
+ [NSFileManager.defaultManager createDirectoryAtPath:tmp withIntermediateDirectories:YES attributes:nil error:nil];
+ g_controls_domain=[@"org.nxnative.test.controllers." stringByAppendingString:NSUUID.UUID.UUIDString];
+ controller_reload_maps();
+ GCController *c = [NamedSteamController new];
+ DMController *d = controller_add_gc(c);
+ [c.extendedGamepad.buttonB setValue:1]; [c.extendedGamepad.leftThumbstick.xAxis setValue:0.5]; gc_event(d);
+ assert(received[0] == DM_BTN_A && axes[0][0] == 16383 && players == 1);
+ assert(controller_set_button(0,3)); controller_publish(d); assert(received[0] == DM_BTN_Y);
+ controller_reload_maps();
+ pad_physical_default(d->map, 0); controller_load_map(d); assert(d->map[0] == 3);
+ [c.extendedGamepad.buttonB setValue:0]; gc_event(d); assert(!received[0]);
+ [c.extendedGamepad.buttonA setValue:1]; gc_event(d); assert(received[0] == DM_BTN_B);
+ front_controllers_window(0); assert(!received[0]);
+ front_controllers_window(1); assert(received[0]==DM_BTN_B); // restore held native state without another event
+ controller_disconnect(d); assert(!received[0] && !players);
+ controller_connect(d); gc_event(d); assert(d->slot == 0 && received[0] == DM_BTN_B);
+ // A raw Steam pad shares the same slots and mapping, including extras.
+ DMController *steam = [DMController new]; steam.name = @"Steam Controller (2026)"; steam.model = @"Valve Triton";
+ [g_devices addObject:steam]; controller_load_map(steam); controller_connect(steam);
+ steam->connected=YES; // already connected fixture; packets below exercise state updates
+ assert(steam->slot == 1 && players == 3);
+ assert(steam->pad_mode[0] == PAD_DPAD && steam->pad_mode[1] == PAD_TOUCH && steam->gyro_enabled);
+ steam->input.pad[0]=(steam_pad){1,25000,-25000,1};
+ steam->input.pad[1]=(steam_pad){1,-32767,32767,1};
+ controller_publish(steam);
+ assert(received[1] == (DM_BTN_RIGHT|DM_BTN_DOWN));
+ assert(ntouches==1 && touches[0].x==0 && touches[0].y==0);
+ unsigned finger=touches[0].id;
+ dm_touch mouse={0,.5,.5}; front_controllers_mouse(&mouse);
+ assert(ntouches==2 && touches[1].id==finger);
+ front_controllers_mouse(NULL); assert(ntouches==1 && touches[0].id==finger);
+ steam->pad_mode[0]=PAD_LEFT_STICK; controller_publish(steam);
+ assert(!received[1] && axes[1][0]==25000 && axes[1][1]==-25000);
+ assert(controller_save_map(steam)); steam->pad_mode[0]=PAD_OFF; controller_load_map(steam);
+ assert(steam->pad_mode[0]==PAD_LEFT_STICK);
+ unsigned char packet[46]={0x42}; packet[30]=1; packet[38]=0; packet[39]=0x40; packet[44]=0; packet[45]=0x10;
+ steam_report((__bridge void *)steam,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,packet,46);
+ assert(motion_present[1] && motions[1].acc[2]==-1 && motions[1].gyro[2]>0);
+ assert(ntouches==0); // finger-up packet releases a held pad
+ steam->input.pad[1]=(steam_pad){1,0,0,1}; controller_publish(steam); assert(ntouches==1);
+ front_controllers_focus(0); assert(!received[1] && ntouches==0 && !motion_present[1]);
+ front_controllers_focus(1); assert(ntouches==0); // needs fresh input after focus loss
+ front_controllers_window(0); assert(!output_focused);
+ front_controllers_focus(1); assert(!output_focused); // app can be active with another window key
+ steam_report((__bridge void *)steam,kIOReturnSuccess,NULL,kIOHIDReportTypeInput,0x42,packet,46);
+ assert(!motion_present[1] && !received[1]);
+ front_controllers_window(1); assert(output_focused);
+ gc_event(d);
+ steam->input=(steam_state){0};
+ steam->input.buttons = 1u << 16; steam->map[16] = 0; controller_publish(steam); assert(received[1] == DM_BTN_A);
+ controller_disconnect(steam); assert(received[1] == 0 && players == 1);
+ assert(!motion_present[1] && ntouches==0);
+ // Merge mode releases a removed pad without clearing a held peer.
+ g_merge = 1; controller_connect(steam); steam->input.buttons = 1u << 16; controller_publish(steam);
+ assert(rumble[0] == c);
+ assert(received[0] == (DM_BTN_A | DM_BTN_B));
+ controller_disconnect(steam); assert(received[0] == DM_BTN_B && rumble[0] == c);
+ GCController *second = [NamedSteamController new];
+ DMController *other = controller_add_gc(second);
+ [second.extendedGamepad.buttonB setValue:1]; gc_event(other);
+ [second.extendedGamepad.buttonB setValue:0]; gc_event(other);
+ controller_disconnect(d); assert(received[0] == 0 && rumble[0] == second);
+ controller_disconnect(other); assert(rumble[0] == nil);
+ if (argc == 3 && !strcmp(argv[1], "--ui-smoke")) {
+ [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory];
+ g_merge = 0; controller_connect(d); controller_connect(steam);
+ front_controllers_menu(); [g_panel show:nil];
+ assert(g_panel.choices.count == 2 && g_panel.buttons.count == DM_PAD_BUTTONS);
+ [g_panel.devices selectItemAtIndex:1]; [g_panel selectDevice:g_panel.devices];
+ assert(g_panel.selected == steam);
+ steam->motion.have_tick=1;
+ [g_panel.buttons[0] selectItemAtIndex:4]; [g_panel mapButton:g_panel.buttons[0]];
+ assert(steam->map[0]==3 && d->map[0]==3 && steam->motion.have_tick);
+ setenv("DM_PAD_MAP","A=B",1); controller_reload_maps(); [g_panel refresh];
+ assert(!g_panel.buttons[0].enabled && g_panel.buttons[16].enabled && !g_panel.presets[0].enabled);
+ unsetenv("DM_PAD_MAP"); controller_reload_maps(); [g_panel refresh];
+ assert(g_panel.buttons[0].enabled && steam->map[0]==3);
+ [g_panel.buttons[16] selectItemAtIndex:2]; [g_panel mapButton:g_panel.buttons[16]];
+ assert(steam->map[16] == 1);
+ [g_panel.pads[0] selectItemAtIndex:PAD_DPAD]; [g_panel mapPad:g_panel.pads[0]];
+ assert(steam->pad_mode[0]==PAD_DPAD);
+ g_panel.gyro.state=NSControlStateValueOff; [g_panel mapGyro:g_panel.gyro]; assert(!steam->gyro_enabled);
+ g_panel.gyro.state=NSControlStateValueOn; [g_panel mapGyro:g_panel.gyro]; assert(steam->gyro_enabled);
+ steam->motion.have_tick=1; [g_panel recenterGyro:nil]; assert(!steam->motion.have_tick);
+ [NSRunLoop.mainRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
+ NSView *view = g_panel.panel.contentView;
+ NSBitmapImageRep *bitmap = [view bitmapImageRepForCachingDisplayInRect:view.bounds];
+ [view cacheDisplayInRect:view.bounds toBitmapImageRep:bitmap];
+ assert([[bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}] writeToFile:@(argv[2]) atomically:YES]);
+ if (getenv("DM_UI_HOLD")) [NSRunLoop.mainRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:60]];
+ [g_panel.panel close];
+ puts("Controller mapping panel actions and rendering: OK");
+ }
+ // The direct route writes output report 0x80 and feature report 1; no
+ // hardware is touched. The actual haptics queue/lifecycle is tested separately.
+ g_merge=0; steam_write=fake_write; controller_disconnect(steam);
+ steam->device=(IOHIDDeviceRef)CFRetain(CFSTR("test device")); controller_connect(steam);
+ assert(raw_output[steam->slot]);
+ dm_haptic_state effect={.player=steam->slot,.motor={{.amplitude_low=.5f},{.amplitude_low=1}}};
+ raw_output[steam->slot](effect,1);
+ assert(written_n==10 && written_type==kIOHIDReportTypeOutput && written_id==0x80);
+ assert(steam_u16(written+4)==32767 && steam_u16(written+7)==65535);
+ test_intensity_cutoff=YES;
+ effect.motor[0].amplitude_low=.15f; effect.motor[1].amplitude_low=.3625f;
+ raw_output[steam->slot](effect,2);
+ assert(intensity_calls==2 && fabsf(intensity_inputs[0]-.3f)<1e-6f && fabsf(intensity_inputs[1]-.725f)<1e-6f);
+ assert(steam_u16(written+4)==0 && steam_u16(written+7)==32767);
+ test_intensity_cutoff=NO;
+ raw_output[steam->slot]((dm_haptic_state){0},1); assert(!steam_u16(written+4) && !steam_u16(written+7));
+ steam_keepalive(steam); assert(written_n==64 && written_type==kIOHIDReportTypeFeature && written_id==1 && written[3]==48 && written[4]==0x18);
+ steam->gyro_enabled=NO; steam_keepalive(steam); assert(written[4]==0);
+ controller_disconnect(steam);
+ // An old 24-number mapping can be imported without overwriting shared choices on load.
+ NSMutableArray *legacy=[NSMutableArray array]; for(int i=0;i<DM_PAD_BUTTONS;i++) [legacy addObject:@(i==0 ? 1 : -1)];
+ g_legacy_maps=@{steam.model:legacy};
+ controller_load_map(steam); assert(steam->map[0]==3); // never silently overrides shared choices
+ assert(controller_import_map(steam)); controller_reload_maps();
+ assert(steam->map[0]==1 && d->map[0]==1);
+ for(NSString *key in @[@"launcher.DM_PAD_MAP",@"controller.Valve Triton",controller_map_key(d)]) CFPreferencesSetAppValue((__bridge CFStringRef)key,NULL,(__bridge CFStringRef)g_controls_domain);
+ assert(CFPreferencesAppSynchronize((__bridge CFStringRef)g_controls_domain));
+ [NSFileManager.defaultManager removeItemAtPath:tmp error:nil];
+ puts("GameController routing, remapping, persistence and disconnect: OK");
+ }
+}
diff --git a/dm/host/tests/t_haptics_apple.m b/dm/host/tests/t_haptics_apple.m
index f7a5dfb..40fdeb7 100644
--- a/dm/host/tests/t_haptics_apple.m
+++ b/dm/host/tests/t_haptics_apple.m
@@ -99,7 +99,7 @@ @interface TestEngine : NSObject
@property(copy) void (^startingReset)(void);
@end
@implementation TestEngine
-- (NSTimeInterval)currentTime { return now(); } // an engine's clock runs like the host's
+- (NSTimeInterval)currentTime { return (double)testTime / NSEC_PER_SEC; } // the same clock as the driven dispatch deadlines
- (BOOL)startAndReturnError:(NSError **)e {
self.starts++; self.handlersAtStart = self.resetHandler && self.stoppedHandler;
self.startingReset = self.resetHandler;
@@ -266,6 +266,39 @@ int main(void) { @autoreleasepool {
dispatch_queue_set_specific(queue, &queue, &queue, NULL);
timers = [NSMutableArray new];
dm_haptics_init(apply, 1); drain();
+ __block int rawCalls=0; __block float rawLeft=0;
+ NSObject *owner=[NSObject new];
+ // Reusing a DualShock player's slot for a raw output must release its HID claim.
+ // Use the same fake handles as the HID registry tests: release also closes the device.
+ TestHid *oldRoute = [TestHid new], *otherRoute = [TestHid new];
+ TestHandle *oldHandle = [TestHandle new], *otherHandle = [TestHandle new];
+ oldHandle.hid = oldRoute; otherHandle.hid = otherRoute;
+ dispatch_sync(queue, ^{
+ ds4[2].dev = (IOHIDDeviceRef)CFBridgingRetain(oldHandle);
+ ds4[3].dev = (IOHIDDeviceRef)CFBridgingRetain(otherHandle);
+ });
+ dm_haptics_apple_output(2, owner, ^(dm_haptic_state s, float gain) { rawCalls++; rawLeft=s.motor[0].amplitude_low*gain; });
+ dispatch_sync(queue, ^{
+ assert(!ds4[2].dev && ds4[3].dev);
+ assert(oldRoute.closes == 1 && otherRoute.closes == 0);
+ ds4_release(3);
+ assert(otherRoute.closes == 1);
+ });
+ dm_vibration_update raw={2,0,{0.5f,160,0,320}};
+ dm_haptics_send(&raw,1); drain(); assert(rawLeft==0.5f && (dm_haptics_available() & 4));
+ int before=rawCalls;
+ advance(0.039); assert(rawCalls==before);
+ advance(0.001); assert(rawCalls==before+1 && rawLeft==0.5f); // firmware watchdog refreshed at 40 ms
+ advance(0.08); assert(rawCalls==before+3 && rawLeft==0.5f); // refresh continues without a new game send
+ suspend(DM_HAPTICS_INACTIVE,YES); drain(); assert(rawLeft==0);
+ before=rawCalls; advance(0.12); assert(rawCalls==before); // stale timers cannot revive rumble
+ suspend(DM_HAPTICS_INACTIVE,NO); dm_haptics_send(&raw,1); drain(); assert(rawLeft==0.5f);
+ dm_haptics_apple_focus(0); drain(); assert(rawLeft==0);
+ suspend(DM_HAPTICS_INACTIVE,YES); suspend(DM_HAPTICS_INACTIVE,NO);
+ dm_haptics_send(&raw,1); drain(); assert(rawLeft==0); // app activation cannot bypass window suspension
+ dm_haptics_apple_focus(1); dm_haptics_send(&raw,1); drain(); assert(rawLeft==0.5f);
+ dm_haptics_apple_controller(2,nil); drain(); assert(rawLeft==0 && !(dm_haptics_available() & 4));
+ before=rawCalls; advance(0.04); assert(rawCalls==before); // stale route cannot refresh after disconnect
TestEngine *left = [TestEngine new], *right = [TestEngine new];
dispatch_sync(queue, ^{
channels[0] = [NSMutableArray new];
@@ -383,9 +416,12 @@ int main(void) { @autoreleasepool {
dm_haptics_apple_controller(0, (id)unsupported); drain();
assert(!(dm_haptics_available() & 1) && unsupported.haptics.attempts == 0);
// DM_RUMBLE_MIN: controller levels below it are silent, the rest stretched over the full range; the phone keeps its levels
- assert(controller_level(0) == 0 && controller_level(0.3f) == 0.3f && controller_level(1) == 1 && controller_level(NAN) == 0);
+ assert(dm_haptics_apple_controller_intensity(0) == 0 && dm_haptics_apple_controller_intensity(0.3f) == 0.3f && dm_haptics_apple_controller_intensity(1) == 1 && dm_haptics_apple_controller_intensity(NAN) == 0);
rumble_min = 0.45f;
- assert(controller_level(0.4f) == 0 && controller_level(0.45f) == 0 && fabsf(controller_level(0.725f) - 0.5f) < 1e-6f && controller_level(1) == 1);
+ dm_vibration rawLevel = {.amplitude_low=0.3f, .frequency_low=160, .frequency_high=320};
+ assert(dm_haptics_apple_controller_intensity(dm_haptics_level(&rawLevel, 1, 1).intensity) == 0);
+ assert(fabsf(dm_haptics_apple_controller_intensity(dm_haptics_level(&rawLevel, 1, 2).intensity) - 3.0f/11.0f) < 1e-6f); // gain before cutoff
+ assert(dm_haptics_apple_controller_intensity(0.4f) == 0 && dm_haptics_apple_controller_intensity(0.45f) == 0 && fabsf(dm_haptics_apple_controller_intensity(0.725f) - 0.5f) < 1e-6f && dm_haptics_apple_controller_intensity(1) == 1);
TestController *cut = [TestController new]; cut.haptics = [TestHaptics new];
dm_haptics_apple_controller(0, (id)cut); drain();
send_pair(0.3, 0); drain();
@@ -453,6 +489,13 @@ int main(void) { @autoreleasepool {
assert(jc.haptics.attempts == 2);
assert([jc.haptics.requestedLocalities[0] isEqual:GCHapticsLocalityLeftHandle]);
assert([jc.haptics.requestedLocalities[1] isEqual:GCHapticsLocalityRightHandle]);
+ // Switching a split locality to native Steam output invalidates its old
+ // route, and switching back stops native output before restoring locality.
+ __block unsigned nativeStops=0;
+ dm_haptics_apple_output(0,@"split-to-Steam",^(dm_haptic_state state,float level) { (void)level; if(!state.motor[0].amplitude_low && !state.motor[1].amplitude_low) ++nativeStops; });
+ drain(); assert(outputOwners[0] && !controllers[0] && !controllerLocalities[0] && !channels[0].count);
+ dm_haptics_apple_controller_locality(0,(id)jc,GCHapticsLocalityLeftHandle); drain();
+ assert(nativeStops && !outputOwners[0] && !nativeOutputs[0] && channels[0].count==1 && [controllerLocalities[0] isEqual:GCHapticsLocalityLeftHandle]);
dm_haptics_apple_controller(0, nil); dm_haptics_apple_controller(1, nil); drain();
assert(ds4_crc((const uint8_t *)"123456789", 9) == 0xCBF43926u); // the report's CRC32 (IEEE, reflected)
dm_haptics_apple_shutdown();
diff --git a/dm/host/tests/t_hid.c b/dm/host/tests/t_hid.c
index 18bb4b4..a69a9c9 100644
--- a/dm/host/tests/t_hid.c
+++ b/dm/host/tests/t_hid.c
@@ -15,15 +15,16 @@ void dm_oe_execute(int index, const void *param, size_t n) { (void)index; (void)
void front_web_shot(const char *path) { (void)path; }
static int checks, fails, g_mode = 1, g_signals;
+static uint64_t test_time = 1000000000ull;
static void *g_signalled;
static time_t rumble_second = 1;
-static uint64_t motion_now = 1000000000ull;
+#define motion_now test_time
static void (*script_hold)(void);
static int hid_clock_gettime(clockid_t clock, struct timespec *ts) { (void)clock; *ts = (struct timespec){.tv_sec = rumble_second}; return 0; }
static int hid_usleep(useconds_t usec) { (void)usec; if (script_hold) script_hold(); return 0; }
#define CHECK(c, msg) do { checks++; if (!(c)) { fails++; fprintf(stderr, "FAIL: %s (line %d)\n", msg, __LINE__); } } while (0)
int dm_opmode(void) { return g_mode; }
-uint64_t guest_ns(void) { return 1000000000ull; }
+uint64_t guest_ns(void) { return test_time; }
uint64_t now_ns(void) { return motion_now; }
static uint64_t test_frame; // presented frames (t_rec moves it)
uint64_t dm_guest_frame(void) { return test_frame; }
@@ -112,7 +113,7 @@ static void t_npads(void) {
CHECK(h_hid_Strap() == RES_OK && h_hid_StrapArg(arg) == RES_OK, "both strap guide overloads answer as the player closing the guide");
CHECK(applet_opens == 7 && applet_depth == 0, "every answer opened and closed its applet");
arg[0] = 1;
- CHECK(six_connected(0x0100 | 0) && !six_connected(0x0200 | 0), "player 2 has a six-axis sensor, No3 none");
+ CHECK(six_connected(0x20103) && !six_connected(0x20203), "player 2 has a six-axis sensor, No3 none");
// A one-player game ({No1, Handheld}): player 2's controller plays as player 1, No2 reads as not connected
g_signals = 0; ids((const uint32_t[]){0, NPAD_HANDHELD}, 2);
@@ -250,7 +251,7 @@ static void t_script_hold(void) {
CHECK(buttons_of(0, STYLE_FULLKEY) == (DM_BTN_A | DM_BTN_B | DM_BTN_X), "script, controller and keyboard buttons are combined");
CHECK(buttons_of(0, STYLE_FULLKEY) == (DM_BTN_A | DM_BTN_B | DM_BTN_X), "a scripted hold survives controller updates after the press latch is consumed");
CHECK(lx_of(0) == -0x7000, "the scripted stick wins over controller drift");
- CHECK(atomic_load(&g_shake_on), "controller updates do not stop a scripted shake");
+ CHECK(atomic_load(&g_shake_on[0]), "controller updates do not stop a scripted shake");
}
static void t_script(void) {
g_mode = 1; dm_pad_players(1);
@@ -261,7 +262,7 @@ static void t_script(void) {
script_hold = t_script_hold; keys_main(NULL); script_hold = NULL;
CHECK(buttons_of(0, STYLE_FULLKEY) == (DM_BTN_B | DM_BTN_X), "script release preserves the controller and keyboard buttons");
CHECK(lx_of(0) == 120, "script release preserves the controller stick");
- CHECK(!atomic_load(&g_shake_on), "script release ends its shake hold");
+ CHECK(!atomic_load(&g_shake_on[0]), "script release ends its shake hold");
dm_input_set(0, 0, 0, 0, 0); dm_pad_set(0, 0, 0, 0, 0); buttons_of(0, STYLE_FULLKEY);
g_steps[0] = (key_step){.btn = DM_BTN_Y}; keys_main(NULL);
CHECK(buttons_of(0, STYLE_FULLKEY) == DM_BTN_Y, "a short scripted press is latched until the game reads");
@@ -274,6 +275,7 @@ static void t_script(void) {
script_set(0, 0, 0, 0, 0); buttons_of(NPAD_HANDHELD, STYLE_HANDHELD);
g_mode = 1; dm_pad_players(1);
g_nsteps = 0; g_steps = NULL;
+ test_time += 1000000000ull; // let the scripted Shake finish before the physical-motion tests
}
// DM_REC (GitHub issue #313): player 1's physical input written as DM_KEYS steps, read back by the DM_KEYS parser and played on the scripted path at the game's reads (keys_sync);
@@ -406,7 +408,7 @@ static void t_motion_threads(void) {
}
static void t_motion_live(void) {
g_mode = 1; dm_pad_players(1);
- atomic_store(&g_shake_t0, 0); atomic_store(&g_shake_end, 0); // no shake: the clocks here stand at 1 s, so the cycle t_script's shake finishes would never end
+ for (int p = 0; p < DM_PLAYERS; p++) { atomic_store(&g_shake_t0[p], 0); atomic_store(&g_shake_end[p], 0); } // no shake: the clocks here stand at 1 s, so the cycle t_script's shake finishes would never end
uint32_t h; uint32_t id = 0;
CHECK(h_hid_SixHandles(&h, 1, &id, STYLE_FULLKEY) == 1, "one six-axis handle for player 1");
@@ -460,7 +462,7 @@ static void t_motion_live(void) {
}
static void t_motion_hid(void) {
g_mode = 1; dm_pad_players(3); ids((uint32_t[]){0, 1, NPAD_HANDHELD}, 3); g_phone_mode = 0;
- uint32_t h = 0; SixAxisState st; // SixAxisSensorHandle uses the style bit index (FullKey = 0), unlike VibrationDeviceHandle's SDK style = 3.
+ uint32_t h = 0x20003; SixAxisState st; // FullKey SDK style 3, combined sensor device 2.
float flat[3] = {0, 0, -1}, tilted[3] = {.5f, 0, -.8660254f}, turn[3] = {0, 0, 2 * (float)M_PI};
motion_now += 1000000000;
dm_motion_clear(0);
@@ -491,16 +493,246 @@ static void t_motion_hid(void) {
dm_pad_players(1); g_phone_mode = -1;
}
+static void t_six_handles(void) {
+ // Independent SDK wire fixtures (libnx _hidGetSixAxisSensorHandles): style,
+ // npad, device, reserved. FullKey and Handheld use the combined device 2.
+ static const struct { uint32_t style, id; int count; uint32_t first, second; } cases[] = {
+ {STYLE_FULLKEY, 1, 1, 0x20103, 0},
+ {STYLE_HANDHELD, NPAD_HANDHELD, 1, 0x22004, 0},
+ {STYLE_JOYDUAL, 1, 2, 0x00105, 0x10105},
+ {STYLE_JOYLEFT, 1, 1, 0x00106, 0},
+ {STYLE_JOYRIGHT, 1, 1, 0x10107, 0},
+ {STYLE_FULLKEY | STYLE_JOYDUAL, 1, 1, 0x20103, 0},
+ };
+ uint32_t h[3];
+ for (unsigned i=0; i<sizeof cases/sizeof *cases; i++) {
+ h[0]=h[1]=h[2]=0xdeadbeef;
+ CHECK(h_hid_SixHandles(h,2,&cases[i].id,cases[i].style) == cases[i].count, "SDK six-axis sensor count for each style");
+ CHECK(h[0] == cases[i].first && (cases[i].count == 1 ? h[1] == 0xdeadbeef : h[1] == cases[i].second) && h[2] == 0xdeadbeef,
+ "SDK six-axis handle bytes and output bounds");
+ }
+ uint32_t id=0;
+ h[0]=h[1]=0xdeadbeef;
+ CHECK(h_hid_SixHandles(h,1,&id,STYLE_JOYDUAL) == 1 && h[0] == 5 && h[1] == 0xdeadbeef, "one-slot output truncates the JoyDual handle list");
+ h[0]=0xdeadbeef;
+ CHECK(!h_hid_SixHandles(h,0,&id,STYLE_FULLKEY) && !h_hid_SixHandles(h,-1,&id,STYLE_FULLKEY) && h[0] == 0xdeadbeef, "nonpositive capacity leaves handles untouched");
+ CHECK(!h_hid_SixHandles(h,2,&id,0) && !h_hid_SixHandles(h,2,&id,1u<<15) && h[0] == 0xdeadbeef, "unsupported styles return no six-axis handles");
+
+ g_mode=1; ids((uint32_t[]){0,1,NPAD_HANDHELD},3); dm_pad_players(3);
+ SixAxisState six[2]; uint32_t first=0x20003;
+ CHECK(h_hid_SixStates(six,2,&first) == 2 && six[0].attributes == 1 && six[1].attributes == 1, "FullKey SDK handle reads connected history");
+ dm_input_set(DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ uint32_t invalid[] = {0, 3, 0x20000, 0x30003, 0x1020003, 0x20004, 0x20803};
+ for (unsigned i=0; i<sizeof invalid/sizeof *invalid; i++) {
+ memset(six,0xff,sizeof six);
+ CHECK(!h_hid_SixStates(six,2,&invalid[i]) && !six[0].attributes && !six[1].attributes, "invalid or disconnected six-axis handles do not read live motion");
+ CHECK(h_hid_SixRest(&invalid[i]), "invalid six-axis handle cannot inherit a player's Shake");
+ }
+ dm_input_set(0,0,0,0,0); test_time += 200000000;
+ g_mode=0; uint32_t handheld=0x22004;
+ CHECK(h_hid_SixStates(six,2,&handheld) == 2 && six[0].attributes == 1, "Handheld combined sensor reads with its SDK handle");
+ CHECK(!h_hid_SixStates(six,2,&first), "FullKey handle disconnects after switching to handheld mode");
+ g_mode=1;
+}
+
+static void t_shake(void) {
+ SixAxisState six[6]; NpadState pad;
+ uint32_t first = 0x20003;
+ g_mode = 1; ids((uint32_t[]){0,1,2,3,4,5,6,7,NPAD_HANDHELD}, 9);
+ dm_input_set(0,0,0,0,0);
+ for (int p = 0; p < DM_PLAYERS; p++) { dm_pad_set_player(p,0,0,0,0,0); dm_pad_motion(p,NULL); }
+ dm_pad_players(0xff); test_time += 1000000000ull;
+ for (int p = 0; p < DM_PLAYERS; p++) fill(&pad,(uint32_t)p,STYLE_FULLKEY); // consume older tests' press latches
+
+ for (int p = 1; p < DM_PLAYERS; p++) {
+ uint32_t h = 0x20003 | (uint32_t)p << 8;
+ dm_pad_set_player(p,DM_BTN_A | DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ h_hid_SixState(six,&h);
+ CHECK(six[0].acc[0] > 0 && six[0].gyro[2] > 0 && !h_hid_SixRest(&h), "each secondary player receives its own mapped Shake");
+ h_hid_SixState(six,&first);
+ CHECK(six[0].acc[0] == 0 && h_hid_SixRest(&first), "secondary Shake does not leak into player 1 in multiplayer");
+ fill(&pad,(uint32_t)p,STYLE_FULLKEY);
+ CHECK(pad.buttons == DM_BTN_A, "Shake never reaches the game's Npad button bits");
+ dm_pad_set_player(p,0,0,0,0,0); test_time += 20000000;
+ h_hid_SixState(six,&h);
+ CHECK(six[0].acc[0] > 0 && !h_hid_SixRest(&h), "releasing secondary Shake lets the current cycle finish");
+ test_time += 200000000;
+ h_hid_SixState(six,&h);
+ CHECK(six[0].acc[0] == 0 && h_hid_SixRest(&h), "released secondary Shake returns to rest");
+ }
+
+ // DM_KBD_PLAYER=own puts the controller in slot 1. A one-player game
+ // merges it into player 1, including a tap released before any sensor read.
+ ids((uint32_t[]){0,NPAD_HANDHELD}, 2); dm_pad_players(7);
+ test_time = (test_time / SIX_PERIOD_NS + 1) * SIX_PERIOD_NS;
+ dm_pad_set_player(1,DM_BTN_SHAKE,0,0,0,0); test_time += 1000000;
+ dm_pad_set_player(1,0,0,0,0,0); test_time += 19000000;
+ CHECK(h_hid_SixStates(six,6,&first) == 6 && six[0].acc[0] > 0 && six[5].acc[0] == 0,
+ "one-player merged Shake preserves a short tap and its sensor history");
+ CHECK(!h_hid_SixRest(&first), "one-player merged Shake is not reported at rest");
+ test_time += 200000000;
+ CHECK(h_hid_SixRest(&first), "one-player merged tap finishes its cycle");
+
+ dm_pad_set_player(1,DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ ids((uint32_t[]){0,1}, 2);
+ uint32_t second = 0x20103;
+ h_hid_SixState(six,&second);
+ CHECK(six[0].acc[0] > 0 && h_hid_SixRest(&first), "held Shake follows the player's current Npad assignment");
+ dm_pad_set_player(2,DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ CHECK(h_hid_SixRest(&first), "unsupported multiplayer slots do not shake player 1");
+ ids((uint32_t[]){0}, 1);
+ dm_pad_set_player(1,0,0,0,0,0); test_time += 200000000;
+ h_hid_SixState(six,&first);
+ CHECK(six[0].acc[0] != 0 && !h_hid_SixRest(&first), "releasing one merged controller leaves another controller's Shake held");
+ dm_pad_set_player(2,0,0,0,0,0); test_time += 200000000;
+ CHECK(h_hid_SixRest(&first), "all merged Shake sources released returns to rest");
+
+ g_mode = 0; ids((uint32_t[]){NPAD_HANDHELD}, 1);
+ uint32_t handheld = 0x22004;
+ dm_pad_set_player(1,DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ h_hid_SixState(six,&handheld);
+ CHECK(six[0].acc[0] > 0 && !h_hid_SixRest(&handheld), "secondary Shake merges into the handheld sensor");
+ dm_pad_players(1);
+ h_hid_SixState(six,&handheld);
+ CHECK(six[0].acc[0] == 0 && h_hid_SixRest(&handheld), "disconnecting a merged Shake controller removes its motion");
+ dm_pad_players(3);
+ h_hid_SixStates(six,6,&handheld);
+ int cleared = 1; for (int i = 0; i < 6; i++) cleared &= six[i].acc[0] == 0;
+ CHECK(cleared && h_hid_SixRest(&handheld), "immediate slot reuse does not inherit the disconnected controller's Shake history");
+ test_time += 200000000;
+
+ g_mode = 1; ids((uint32_t[]){0,1}, 2);
+ dm_motion physical = {.acc={0,0,-1}, .gyro={0,0,0.25f}, .dir={1,0,0,0,1,0,0,0,1}};
+ dm_pad_motion(1,&physical);
+ dm_pad_set_player(1,DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ h_hid_SixState(six,&second);
+ CHECK(six[0].acc[0] > 0 && six[0].gyro[2] > 0.5f, "secondary Shake overrides physical motion for its whole cycle");
+ dm_pad_set_player(1,0,0,0,0,0); test_time += 200000000; dm_pad_motion(1,&physical);
+ h_hid_SixState(six,&second);
+ CHECK(six[0].acc[0] == 0 && six[0].gyro[2] == 0.25f, "physical motion resumes after secondary Shake finishes");
+ dm_pad_motion(1,NULL);
+
+ dm_input_set(DM_BTN_SHAKE,0,0,0,0); dm_pad_set(DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ dm_input_set(0,0,0,0,0); test_time += 200000000;
+ CHECK(!h_hid_SixRest(&first) && h_hid_SixRest(&second), "keyboard release preserves player 1's controller Shake without affecting player 2");
+ dm_pad_set(0,0,0,0,0); test_time += 200000000;
+ CHECK(h_hid_SixRest(&first), "keyboard and first-controller Shake still return to rest");
+
+ script_set(DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ h_hid_SixState(six,&first);
+ CHECK(six[0].acc[0] > 0 && !h_hid_SixRest(&first) && h_hid_SixRest(&second), "scripted Shake reaches only player 1's sensor");
+ dm_pad_set_player(1,DM_BTN_SHAKE,0,0,0,0); test_time += 20000000;
+ CHECK(!h_hid_SixRest(&first) && !h_hid_SixRest(&second), "scripted and secondary-controller Shake can run together");
+ script_set(0,0,0,0,0); test_time += 200000000;
+ CHECK(h_hid_SixRest(&first) && !h_hid_SixRest(&second), "script release preserves the secondary controller's Shake");
+ dm_pad_set_player(1,0,0,0,0,0); test_time += 200000000;
+ CHECK(h_hid_SixRest(&second), "secondary Shake returns to rest after the overlapping script finishes");
+}
+
+// An offline applet sees every input route while guest reads remain quiet. Its edge latch is independent of each npad's consumed press latch.
+static void t_applet_input(void) {
+ g_mode = 1; ids((uint32_t[]){0, 1, 2, NPAD_HANDHELD}, 4); dm_pad_players(7);
+ dm_input_set(0, 0, 0, 0, 0); script_set(0, 0, 0, 0, 0);
+ for (int p = 0; p < DM_PLAYERS; p++) dm_pad_set_player(p, 0, 0, 0, 0, 0);
+ uint64_t b; int32_t a[4]; dm_input_peek(&b, a);
+ dm_input_hold(1);
+ dm_input_set(DM_BTN_A, 100, 0, 0, 0);
+ script_set(DM_BTN_X, 300, -400, 0, 0);
+ dm_pad_set_player(1, DM_BTN_B, -200, 0, 0, 500);
+ CHECK(buttons_of(0, STYLE_FULLKEY) == 0 && buttons_of(1, STYLE_FULLKEY) == 0, "applet hold hides keyboard, script and the other player's buttons from the game");
+ CHECK(lx_of(0) == 0 && lx_of(1) == 0, "applet hold centres every guest npad's sticks");
+ dm_input_peek(&b, a);
+ CHECK(b == (DM_BTN_A | DM_BTN_X | DM_BTN_B), "applet sees every route after guest reads consumed their press latches");
+ CHECK(a[0] == 300 && a[1] == -400 && a[2] == 0 && a[3] == 500, "applet combines the most deflected axes across routes and players");
+ dm_input_set(0, 0, 0, 0, 0); script_set(0, 0, 0, 0, 0); dm_pad_set_player(1, 0, 0, 0, 0, 0);
+ dm_pad_set_player(2, DM_BTN_Y, 0, 0, 0, 0); dm_pad_set_player(2, 0, 0, 0, 0, 0);
+ CHECK(buttons_of(2, STYLE_FULLKEY) == 0, "a tapped third-player button stays hidden from guest reads during the applet");
+ dm_input_peek(&b, a); CHECK(b == DM_BTN_Y, "applet retains a third-player tap between polls");
+ dm_input_peek(&b, a); CHECK(b == 0, "applet consumes that short press once");
+ dm_input_hold(0);
+ CHECK(buttons_of(0, STYLE_FULLKEY) == 0 && buttons_of(1, STYLE_FULLKEY) == 0 && buttons_of(2, STYLE_FULLKEY) == 0, "closing the applet does not replay its taps to the game");
+ dm_pad_set(DM_BTN_A, 0, 0, 0, 0); dm_pad_set(0, 0, 0, 0, 0);
+ dm_input_peek(&b, a); CHECK(b == DM_BTN_A, "applet peek still sees a short controller press after the hold");
+ uint64_t first = buttons_of(0, STYLE_FULLKEY), second = buttons_of(0, STYLE_FULLKEY);
+ CHECK(first == DM_BTN_A && second == 0, "applet peek does not consume the game's independent short-press latch");
+ dm_pad_players(0);
+}
+
int main(void) {
CHECK(setenv("DM_RUMBLE_LOG", "1", 1) == 0, "enable rumble diagnostics");
t_slots();
t_npads();
t_script();
+ t_six_handles();
t_vibration();
t_rumble_log();
t_motion_threads();
t_motion_live();
t_motion_hid();
+ g_mode = 1; ids((uint32_t[]){0,1}, 2); dm_pad_players(3);
+ test_time = (test_time / SIX_PERIOD_NS + 1) * SIX_PERIOD_NS;
+ dm_motion motion = {.acc={0,0,-1}, .gyro={0.1f,0.2f,0.3f}, .dir={1,0,0,0,1,0,0,0,1}};
+ dm_pad_motion(1, &motion);
+ SixAxisState six[3]; uint32_t h = 0x20103;
+ CHECK(six_states(six, 3, h) == 3 && six[0].gyro[2] == 0.3f, "physical gyro reaches its player's six-axis state");
+ CHECK(!h_hid_SixRest(&h), "physical gyro is not reported at rest");
+ test_time += SIX_PERIOD_NS; motion.gyro[2] = 0.6f; dm_pad_motion(1, &motion);
+ six_states(six, 3, h);
+ CHECK(six[0].gyro[2] == 0.6f && six[1].gyro[2] == 0.3f, "six-axis history preserves distinct samples");
+ ids((uint32_t[]){0},1); six_states(six,1,0x20003);
+ CHECK(six[0].gyro[2] == 0.6f, "one-player title receives merged controller motion");
+ test_time += 1000000000ull; six_states(six,1,0x20003);
+ CHECK(six[0].gyro[2] == 0 && six[0].acc[2] == -1, "stale physical motion returns to rest");
+ test_time += 1000000; memset(motion.gyro,0,sizeof motion.gyro); dm_pad_motion(1,&motion);
+ six_states(six,3,0x20003);
+ CHECK(six[0].gyro[2]==0 && six[1].gyro[2]==0 && six[2].gyro[2]==0, "fresh motion never revives history from before a stale gap");
+ dm_pad_motion(1, NULL); six_states(six, 1, 0x20003); CHECK(six[0].gyro[2] == 0, "disconnect clears sensor history");
+ // The direct Steam history participates in the same source policy as GC, Pro and phone motion.
+ test_time = (test_time / SIX_PERIOD_NS + 1) * SIX_PERIOD_NS;
+ motion.acc[0] = .25f; dm_pad_motion(0, &motion);
+ dm_motion_set_switch(0, (float[]){0, -1, 0}, (float[]){0, 0, 0});
+ six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .25f, "auto phone does not replace direct controller history");
+ g_phone_mode = 1; six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[1] == -1, "forced phone overrides direct controller history");
+ g_phone_mode = -1;
+ dm_motion_set(0, (float[]){.5f, 0, -.8660254f}, (float[]){0, 0, 0});
+ six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .5f, "fresh GC motion has priority over direct HID history");
+ dm_motion_clear(0); six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .25f, "clearing GC reveals the preserved direct HID history");
+ dm_pad_motion(0, NULL); six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[1] == -1, "disconnecting direct HID allows auto phone fallback");
+ g_motion_off = 1; dm_pad_motion(0, &motion); six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[2] == -1, "DM_MOTION disables direct history and all fallback sources");
+ g_motion_off = 0; g_phone_motion.last_ns = 0;
+ dm_pad_motion(1, NULL); six_states(six,1,0x20003); CHECK(six[0].gyro[2] == 0, "disconnect clears sensor history");
+ // A newly arriving merged controller cannot erase the previous source's history.
+ test_time = (test_time / SIX_PERIOD_NS + 1) * SIX_PERIOD_NS;
+ dm_pad_motion(0, &motion);
+ test_time += SIX_PERIOD_NS + 2000000;
+ dm_motion later = motion; later.acc[0] = .75f; dm_pad_motion(1, &later);
+ six_states(six, 2, 0x20003);
+ CHECK(six[0].acc[0] == .25f && six[1].acc[0] == .25f, "new direct source with no matching history preserves the older source");
+ test_time += SIX_PERIOD_NS; six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .75f, "new direct source takes over once its sample reaches the sensor clock");
+ dm_pad_motion(0, NULL); dm_pad_motion(1, NULL);
+ // Steam's integrated history and passive Pro integration never clear or mix each other.
+ test_time = (test_time / SIX_PERIOD_NS + 1) * SIX_PERIOD_NS;
+ dm_motion_set_hid(0, (float[]){.5f, 0, -.8660254f}, (float[]){0, 0, 0}, test_time);
+ dm_pad_motion(0, &motion); dm_pad_motion(0, NULL); six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .5f, "direct disconnect leaves passive Pro motion intact");
+ dm_pad_motion(0, &motion); dm_motion_clear_hid(0); six_states(six, 1, 0x20003);
+ CHECK(six[0].acc[0] == .25f, "passive Pro removal leaves direct Steam history intact");
+ dm_pad_motion(0, NULL);
+ // Upstream native motion keeps its orientation during a synthetic Shake.
+ dm_motion_set(0, (float[]){.5f, 0, -.8660254f}, (float[]){0, 0, (float)M_PI});
+ dm_pad_set(DM_BTN_SHAKE, 0, 0, 0, 0); test_time += 20000000;
+ six_states(six, 1, 0x20003);
+ CHECK(fabsf(six[0].gyro[2] - .5f) < 1e-6f && fabsf(six[0].dir[2] + .5f) < .01f && six[0].acc[0] > .5f,
+ "native motion retains its gyro and orientation while Shake adds acceleration");
+ dm_pad_set(0, 0, 0, 0, 0); test_time += 200000000; dm_motion_clear(0);
+ t_shake();
t_rec();
{ // Nmouse with no device (SDK 21's forms): the pointer range is kept, the merged handle 0 takes settings, the standard mouse and the handle queries report nothing
int w = 0, h = 0; uint64_t std = 7; uint32_t npad = 9;
@@ -514,6 +746,7 @@ int main(void) {
CHECK(!h_hid_NmouseEnable(5, 1) && !h_hid_NmousePos(5, 0, 0), "an unknown handle does not");
CHECK(!h_hid_NmouseState(NULL, merged) && !h_hid_NmouseNpad(&npad, merged) && npad == 9, "no state and no controller behind the merged handle");
}
+ t_applet_input();
printf("hid players: %d checks, %d failed\n", checks, fails);
return fails != 0;
}
diff --git a/dm/host/tests/t_input_map.c b/dm/host/tests/t_input_map.c
index 96736ad..8ea0ab7 100644
--- a/dm/host/tests/t_input_map.c
+++ b/dm/host/tests/t_input_map.c
@@ -28,6 +28,29 @@ int main(void) {
CHECK(key_map_fn(&k, 7) == 2 && key_map_fn(&k, 6) == 8 && key_map_fn(&k, 38) == 0, "the good entry applies, the malformed ones change nothing");
CHECK(key_map_parse(&k, "") == 0 && key_map_parse(&k, NULL) == 0 && key_map_parse(&k, "L=12,") == 0, "empty lists and a trailing comma are fine");
+ // Capture the function on key-down: modifier changes, repeat events and other keys cannot steal its release.
+ key_map_default(&k); key_state state = {0};
+ CHECK(key_state_event(&state, &k, 126, 1, 1) == (1u << IM_RUP), "Shift+Up drives the right stick, not the D-pad");
+ CHECK(key_state_event(&state, &k, 126, 1, 0) == (1u << IM_RUP), "repeat after releasing Shift keeps the initial function");
+ CHECK(key_state_event(&state, &k, 126, 0, 0) == 0, "releasing the arrow without Shift releases the right stick");
+ CHECK(key_state_event(&state, &k, 123, 1, 0) == (1u << 12), "unshifted Left remains D-pad");
+ CHECK(key_state_event(&state, &k, 123, 1, 1) == (1u << 12), "pressing Shift during a held arrow does not switch functions");
+ CHECK(key_state_event(&state, &k, 123, 0, 1) == 0, "D-pad releases even when Shift was subsequently pressed");
+ CHECK(key_state_event(&state, &k, 124, 1, 1) == (1u << IM_RRIGHT), "Shift+Right drives right stick right");
+ CHECK(key_state_event(&state, &k, 125, 1, 1) == ((1u << IM_RRIGHT) | (1u << IM_RDOWN)), "Shift arrows combine diagonally");
+ key_state_clear(&state);
+ CHECK(key_state_event(&state, &k, 124, 0, 0) == 0, "focus/modal clear releases every captured function");
+ CHECK(key_map_parse(&k, "A=126,RUp=15") == 0, "custom arrow and explicit right-stick binding parse");
+ CHECK(key_state_event(&state, &k, 126, 1, 1) == 1, "a remapped arrow respects its custom function with Shift");
+ key_state_clear(&state); key_map_default(&k); key_map_parse(&k, "RUp=15");
+ CHECK(key_state_event(&state, &k, 126, 1, 1) == (1u << IM_RUP), "default shifted arrow remains available with another right-stick binding");
+ CHECK(key_state_event(&state, &k, 15, 1, 0) == (1u << IM_RUP), "two physical keys may hold the same function");
+ CHECK(key_state_event(&state, &k, 126, 0, 0) == (1u << IM_RUP), "releasing one key preserves the other held right-stick binding");
+ CHECK(key_state_event(&state, &k, 15, 0, 0) == 0, "last physical release clears the function");
+ CHECK(key_state_event(&state, &k, 200, 1, 1) == 0, "out-of-range key cannot change input");
+ key_map_parse(&k, "Up=none");
+ CHECK(key_state_event(&state, &k, 126, 1, 1) == 0, "an explicitly disabled arrow is not re-enabled by Shift");
+
pad_map m; pad_map_default(&m);
CHECK(pad_map_is_default(&m) && pad_map_apply(&m, DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE) == (DM_BTN_A | DM_BTN_ZR | DM_BTN_SHAKE), "default: every button sends itself, Shake passes");
CHECK(pad_map_parse(&m, "A=B,B=A") == 0 && !pad_map_is_default(&m), "a swap parses");
@@ -38,6 +61,18 @@ int main(void) {
pad_map_default(&m);
CHECK(pad_map_parse(&m, "A=LUp,LUp=A,Shake=B,Y=X") == 3 && m.to[3] == 2 && m.to[0] == 0, "sticks and Shake are no buttons here: left out; Y=X applies");
+ CHECK(input_map_valid("A=Shake", 1) && pad_map_parse(&m,"A=Shake")==0 && pad_map_apply(&m,DM_BTN_A)==DM_BTN_SHAKE, "Shake is an additive target, keeping per-player Shake mappings in the shared store");
+
+ // input_map_valid: what the launcher checks a saved DM_KEYMAP / DM_PAD_MAP with; the whole value must be one the host takes
+ CHECK(input_map_valid("A=40,B=38", 0) && input_map_valid("RUp=126,Up=none,Shake=49", 0) && input_map_valid("a=49,", 0), "keymap: a swap, the right stick, none, a trailing comma are valid");
+ CHECK(input_map_valid("A=B,B=A", 1) && input_map_valid("ZL=L,minus=none", 1), "pad map: a swap and none are valid");
+ CHECK(!input_map_valid("Q=1", 0) && !input_map_valid("A=40,Q=1", 0), "keymap: an unknown name is invalid, also next to a good entry");
+ CHECK(!input_map_valid("A=128", 0) && !input_map_valid("A=abc", 0) && !input_map_valid("A=-1", 0) && !input_map_valid("A=", 0) && !input_map_valid("A", 0), "keymap: a key code past 127, text, a sign or no value is invalid");
+ CHECK(!input_map_valid("A=LUp", 1) && !input_map_valid("Shake=B", 1) && !input_map_valid("A=Q", 1) && !input_map_valid("A=40", 1), "pad map: sticks, Shake, unknown names and key codes are invalid");
+ CHECK(!input_map_valid("A=B", 0) && !input_map_valid("A=40", 1) && !input_map_valid("A=40,B=38", 1), "a value of one map is not valid for the other");
+ CHECK(!input_map_valid("", 0) && !input_map_valid("", 1) && !input_map_valid(NULL, 0) && !input_map_valid(NULL, 1), "empty and missing values are invalid (nothing to apply)");
+ CHECK(!input_map_valid(",", 0), "a lone comma holds an entry with no name: invalid");
+
printf("input map: %d checks, %d failed\n", checks, fails);
return fails != 0;
}
diff --git a/dm/host/tests/t_pad_map.c b/dm/host/tests/t_pad_map.c
new file mode 100644
index 0000000..6035d6e
--- /dev/null
+++ b/dm/host/tests/t_pad_map.c
@@ -0,0 +1,104 @@
+#include <assert.h>
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+#include "../pad_map.h"
+#include "../steam_input.h"
+static steam_state decode_sticks(unsigned char report, int16_t lx, int16_t ly, int16_t rx, int16_t ry) {
+ unsigned char packet[46] = {0}; packet[0] = report;
+ int16_t axes[] = {lx, ly, rx, ry};
+ for (int i = 0; i < 4; i++) { uint16_t v = (uint16_t)axes[i]; packet[10+2*i] = v; packet[11+2*i] = v >> 8; }
+ packet[39] = 0x40; packet[41] = 0x40; // motion must survive centred sticks
+ int pad = report == 0x47 ? 20 : 18; packet[pad] = 3; packet[pad+2] = 4;
+ steam_state s; assert(steam_decode(packet, sizeof packet, &s) == 1);
+ assert(s.acc[2] == -1 && s.gyro[0] > 0 && s.pad[0].x == 3 && s.pad[0].y == 4);
+ return s;
+}
+static void t_deadzone(void) {
+ unsetenv("DM_STEAM_DEADZONE");
+ for (int i = 0; i < 3; i++) {
+ unsigned char report = (unsigned char[]){0x42,0x45,0x47}[i];
+ steam_state s = decode_sticks(report, 7, -9, -13, 11);
+ assert(s.lx == 0 && s.ly == 0 && s.rx == 0 && s.ry == 0); // rest must not suppress gyro aiming
+ s = decode_sticks(report, 2000, 2000, 3000, -3000);
+ assert(s.lx == 0 && s.ly == 0 && s.rx > 0 && s.ry == -s.rx); // radial, not per-axis
+ s = decode_sticks(report, 3276, 0, 3278, 0);
+ assert(s.lx == 0 && s.ly == 0 && s.rx == 1 && s.ry == 0); // continuous at the boundary
+ s = decode_sticks(report, 16384, 0, 12000, -16000);
+ assert(s.lx == 14564 && s.ly == 0 && s.rx == 11149 && s.ry == -14865);
+ s = decode_sticks(report, 32767, 0, -32768, 0);
+ assert(s.lx == 32767 && s.rx == -32767); // full travel is retained
+ s = decode_sticks(report, 32767, -32768, -32768, 32767);
+ assert(s.lx == 32767 && s.ly == -32767 && s.rx == -32767 && s.ry == 32767);
+ s = decode_sticks(report, 32767, 16384, -16384, -32768);
+ assert(s.lx == 32767 && s.ly == 16384 && s.rx == -16384 && s.ry == -32767); // preserve asymmetric outer diagonals
+ }
+ setenv("DM_STEAM_DEADZONE", "0.2", 1);
+ steam_state s = decode_sticks(0x42, 6000, 0, 16384, 0);
+ assert(s.lx == 0 && s.rx == 12288);
+ setenv("DM_STEAM_DEADZONE", "0.8", 1);
+ s = decode_sticks(0x42, 32767, 16384, -16384, -32768);
+ assert(s.lx == 32767 && s.ly == 16384 && s.rx == -16384 && s.ry == -32767);
+ setenv("DM_STEAM_DEADZONE", "0", 1);
+ s = decode_sticks(0x42, 7, -9, -13, 11);
+ assert(s.lx == 7 && s.ly == -9 && s.rx == -13 && s.ry == 11);
+ const char *invalid[] = {"", "garbage", "0junk", "nan", "inf", "-0.1", "0.9", "1"};
+ for (unsigned i = 0; i < sizeof invalid / sizeof *invalid; i++) {
+ setenv("DM_STEAM_DEADZONE", invalid[i], 1);
+ s = decode_sticks(0x42, 7, -9, 16384, 0);
+ assert(s.lx == 0 && s.ly == 0 && s.rx == 14564); // invalid settings retain the safe default
+ }
+ unsetenv("DM_STEAM_DEADZONE");
+}
+int main(void) {
+ t_deadzone();
+ int map[DM_PAD_BUTTONS]; pad_physical_default(map, 0);
+ assert(pad_map_buttons(1u << 0, map) == DM_BTN_A); // east -> Switch A
+ pad_physical_default(map, 1);
+ assert(pad_map_buttons(1u << 1, map) == DM_BTN_A); // south -> label A
+ map[16] = 63; assert(pad_map_buttons(1u << 16, map) == DM_BTN_SHAKE);
+ map[1] = -1; assert(pad_map_buttons(1u << 1, map) == 0);
+ map[1] = 100; assert(pad_map_buttons(1u << 1, map) == 0);
+ unsigned char packet[64] = {0x42, 1}; steam_state s = {0};
+ // South A, L4, right trackpad click. Signed axes and half-pulled triggers.
+ packet[2] = 1; packet[4] = 0x42;
+ packet[7] = 0x40; packet[9] = 0x40;
+ packet[10] = 0xff; packet[11] = 0x7f;
+ packet[12] = 0; packet[13] = 0x80;
+ for (int i = 0; i < 3; i++) {
+ packet[0] = (unsigned char[]){0x42, 0x45, 0x47}[i];
+ assert(steam_decode(packet, 46, &s) == 1);
+ assert(s.buttons == ((1u << 1) | (1u << 16) | (1u << 21) | DM_BTN_ZL | DM_BTN_ZR));
+ assert(s.lx == 32767 && s.ly == -32767 && s.rx == 0 && s.ry == 0);
+ for (int n = 0; n < 46; n++) assert(steam_decode(packet, n, &s) == 0);
+ }
+ packet[0] = 0x79; packet[1] = 1; assert(steam_decode(packet, 2, &s) == -1);
+ packet[0] = 0x46; assert(steam_decode(packet, 2, &s) == -1);
+ packet[1] = 2; assert(steam_decode(packet, 2, &s) == 2);
+ packet[0] = 0x43; assert(steam_decode(packet, 64, &s) == 0);
+ assert(steam_device(0x28de, 0x1302, -1)); assert(steam_device(0x28de, 0x1303, -1));
+ assert(steam_device(0x28de, 0x1304, 2)); assert(steam_device(0x28de, 0x1305, 5));
+ assert(!steam_device(0x28de, 0x1304, 1)); assert(!steam_device(0x28de, 0x1142, 2));
+ assert(!steam_device(0x1234, 0x1302, 2));
+ for (int version = 0; version < 3; version++) {
+ unsigned char imu[46] = {0}; imu[0] = (unsigned char[]){0x42,0x45,0x47}[version];
+ imu[5] = 0x02; imu[4] = 0x20; // both trackpads touched
+ int pad = version == 2 ? 20 : 18;
+ imu[pad+1] = 0x40; imu[pad+3] = 0xc0; imu[pad+5] = 0x40;
+ imu[pad+7] = 0x80; imu[pad+9] = 0x7f;
+ int tick = version == 2 ? 32 : 30; imu[tick] = 0xfe; imu[tick+1] = 0xff;
+ imu[39] = 0x40; imu[41] = 0x40; // +1G Z, +1000 degrees/second X
+ assert(steam_decode(imu, sizeof imu, &s) == 1);
+ assert(s.pad[0].down && s.pad[1].down && s.pad[0].x == 16384 && s.pad[0].y == -16384);
+ assert(s.pad[1].x == -32767 && fabsf(s.pad[0].pressure - 0.5f) < 1e-5f);
+ assert(s.acc[2] == -1 && fabsf(s.gyro[0] - 1000.0f/360) < 1e-5f);
+ assert(s.tick == 65534 && s.tick_us == (version == 2 ? 32 : 1));
+ }
+ unsigned char output[10], feature[64];
+ steam_rumble_report(output, 0x1234, 0xabcd);
+ assert(output[0] == 0x80 && output[4] == 0x34 && output[5] == 0x12 && output[7] == 0xcd && output[8] == 0xab);
+ assert(output[1] == 0 && output[2] == 0 && output[3] == 0 && output[6] == 0 && output[9] == 0);
+ steam_imu_report(feature, 1); assert(feature[0] == 1 && feature[1] == 0x87 && feature[3] == 48 && feature[4] == 0x18);
+ steam_imu_report(feature, 0); assert(feature[4] == 0);
+ puts("pad mapping and Steam Controller reports: OK");
+}
diff --git a/dm/host/tests/t_pad_motion.c b/dm/host/tests/t_pad_motion.c
new file mode 100644
index 0000000..f785cf0
--- /dev/null
+++ b/dm/host/tests/t_pad_motion.c
@@ -0,0 +1,19 @@
+#include "../pad_motion.h"
+#include <assert.h>
+#include <stdio.h>
+int main(void) {
+ pad_motion_state m = {0}; float acc[3]={0,0,-1}, gyro[3]={0,0,0.25f};
+ assert(pad_motion_update(&m, 65000, 32, acc, gyro));
+ assert(!pad_motion_update(&m, 65000, 32, acc, gyro));
+ assert(pad_motion_update(&m, 2464, 32, acc, gyro)); // 16-bit wrap, 96 ms
+ assert(fabsf(m.value.angle[2] - 0.024f) < 1e-5f);
+ assert(fabsf(m.value.dir[0] - cosf(0.024f*2*M_PI)) < 1e-5f);
+ assert(fabsf(m.value.dir[1] - sinf(0.024f*2*M_PI)) < 1e-5f);
+ float angle = m.value.angle[2]; pad_motion_update(&m, 50000, 32, acc, gyro); // gap: no invented motion
+ assert(m.value.angle[2] == angle);
+ pad_motion_reset(&m); assert(!m.have_tick);
+ pad_motion_update(&m, 0xfffffff0, 1, acc, gyro); pad_motion_update(&m, 984, 1, acc, gyro);
+ assert(fabsf(m.value.angle[2] - 0.00025f) < 1e-6f);
+ gyro[1] = NAN; assert(!pad_motion_update(&m, 1984, 1, acc, gyro));
+ puts("motion timestamp wrap, units, orientation and stale-gap handling: OK");
+}
diff --git a/dm/mac/launcher.c b/dm/mac/launcher.c
index a80f656..f36f73b 100644
--- a/dm/mac/launcher.c
+++ b/dm/mac/launcher.c
@@ -6,6 +6,8 @@
// (the previous run's kept as <title ID>.prev.log). Environment switches: one KEY=VALUE per line in <Application Support folder>/env.txt, then Resources/dm/env.txt (the first one wins; neither
// replaces a variable already set), as the iOS app reads Documents/env.txt and dm/env.txt. Then the player's saved choices: launcher.<VAR> strings in the app's preferences domain (its bundle ID), which a
// front end or a settings window writes, each checked against the bundle's settings (Info.plist DMSettings, from launcher.json) and used only for a variable still unset; DM_SAVED_CHOICES=0 ignores them.
+// DM_KEYMAP and DM_PAD_MAP are saved choices too (launcher.DM_KEYMAP, launcher.DM_PAD_MAP) but no launcher.json rows, so DMSettings cannot check them: the host's own parser does (dm/host/input_map.h,
+// input_map_valid), and a value it would not take whole is ignored. They are read whether or not the settings window ran, since the window does not offer them.
// So the order is: the launch environment, the player's env.txt, the bundle's, saved choices, the host's tested defaults (docs/frontends.md, Saved choices).
// Before the host starts, the settings window (dm/mac/Launcher.swift dm_mac_launcher, linked in by pack_app.py) runs in this process and puts the player's settings into the environment; it keeps
// what the launch environment and the env files set (DM_ENV_LAUNCH_KEYS, DM_ENV_FILE_KEYS). DM_LAUNCHER=0 or --no-launcher (open <app> --args --no-launcher) starts the game without the window,
@@ -27,6 +29,10 @@
#include <unistd.h>
#include "romfs_image.h"
#include "save_sync.h"
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-function" // the header is the host's: this file uses only input_map_valid
+#include "input_map.h"
+#pragma clang diagnostic pop
extern char **environ;
int dm_mac_launcher(void); // Launcher.swift: 1 = Play (the settings are in the environment), 0 = the player quit, 2 = no window (apply the saved choices here)
@@ -153,12 +159,24 @@ static int rule_env(CFTypeRef rule, char *env, size_t n) { // a rule's variabl
return e && CFGetTypeID(e) == CFStringGetTypeID() && CFStringGetCString(e, env, (CFIndex)n, kCFStringEncodingUTF8);
}
-static void saved_choices(void) { // after the env files, before the bundle's own defaults (DM_LANG): a variable already set keeps its value
+static void saved_control(CFStringRef domain, const char *env, int pad) { // DM_KEYMAP / DM_PAD_MAP: checked by the host's parser, not by DMSettings
+ CFStringRef key = CFStringCreateWithFormat(NULL, NULL, CFSTR("launcher.%s"), env);
+ CFPropertyListRef v = CFPreferencesCopyAppValue(key, domain); CFRelease(key);
+ if (!v) return;
+ char s[1024];
+ if (CFGetTypeID(v) != CFStringGetTypeID() || !CFStringGetCString(v, s, sizeof s, kCFStringEncodingUTF8)) fprintf(stderr, "launcher: saved choice for %s ignored: not a string of at most %zu bytes\n", env, sizeof s - 1);
+ else if (!input_map_valid(s, pad)) fprintf(stderr, "launcher: saved choice %s=%s ignored: the host does not take it\n", env, s);
+ else if (getenv(env)) fprintf(stderr, "launcher: saved choice %s=%s not used: %s=%s is set (environment or env.txt)\n", env, s, env, getenv(env));
+ else { setenv(env, s, 0); fprintf(stderr, "launcher: env %s=%s (saved choice)\n", env, s); }
+ CFRelease(v);
+}
+
+static void saved_choices(int window) { // after the env files, before the bundle's own defaults (DM_LANG): a variable already set keeps its value. window: the settings window ran and applied its own settings
CFArrayRef rules = setting_rules(); CFStringRef domain = CFBundleGetIdentifier(CFBundleGetMainBundle());
- if (!rules || !domain) return; // packed without launcher settings: nothing to choose
+ if (!domain) return;
const char *off = getenv("DM_SAVED_CHOICES");
if (off && !strcmp(off, "0")) { fprintf(stderr, "launcher: saved choices ignored (DM_SAVED_CHOICES=0)\n"); return; }
- for (CFIndex i = 0; i < CFArrayGetCount(rules); i++) {
+ for (CFIndex i = 0; rules && !window && i < CFArrayGetCount(rules); i++) { // packed without launcher settings: nothing of these to choose
CFTypeRef rule = CFArrayGetValueAtIndex(rules, i); char env[128], s[256];
if (!rule_env(rule, env, sizeof env)) continue;
CFStringRef key = CFStringCreateWithFormat(NULL, NULL, CFSTR("launcher.%s"), env);
@@ -170,6 +188,7 @@ static void saved_choices(void) { // after the env files, before the bundle's
else { setenv(env, s, 0); fprintf(stderr, "launcher: env %s=%s (saved choice)\n", env, s); }
CFRelease(v);
}
+ saved_control(domain, "DM_KEYMAP", 0); saved_control(domain, "DM_PAD_MAP", 1);
}
// Cloud saves: the folder chosen in the settings window (Launcher.swift CloudSavesSection, cloudSaves.folder in the app's preferences) becomes DM_SAVE_SYNC
@@ -283,6 +302,7 @@ int main(int argc, char **argv) {
fprintf(stderr, "launcher: %s (%s), host %s\n", name, id, host);
CFArrayRef rules = setting_rules(); // the settings the launch environment already set: the window shows them, fixed
for (CFIndex i = 0; rules && i < CFArrayGetCount(rules); i++) { char env[128]; if (rule_env(CFArrayGetValueAtIndex(rules, i), env, sizeof env) && getenv(env)) add_key(&g_launch_keys, env); }
+ for (const char **key=(const char *[]){"DM_KEYMAP","DM_PAD_MAP",NULL}; *key; key++) if(getenv(*key)) add_key(&g_launch_keys,*key);
snprintf(p, sizeof p, "%s/env.txt", sup); env_file(p);
snprintf(p, sizeof p, "%s/env.txt", dm); env_file(p);
setenv("DM_ENV_FILE_KEYS", g_file_keys ? g_file_keys : "", 1); setenv("DM_ENV_LAUNCH_KEYS", g_launch_keys ? g_launch_keys : "", 1);
@@ -292,7 +312,7 @@ int main(int argc, char **argv) {
if (!window) fprintf(stderr, "launcher: no settings window (DM_LAUNCHER=0 or --no-launcher)\n");
int shown = window ? dm_mac_launcher() : 2;
if (!shown) return 0; // Quit: no game
- if (shown == 2) saved_choices();
+ saved_choices(shown == 1); // the window applied its settings; the controls are not among them
cloud_saves_folder();
setenv("DM_ROOT", sup, 0); setenv("DM_ROMFS", romfs, 0); setenv("DM_SAVE", save, 0); setenv("DM_TEMP", temp, 0);
snprintf(p, sizeof p, "%s/msl", res); setenv("DM_MSL_DIR", p, 0);
diff --git a/dm/mac/pack_app.py b/dm/mac/pack_app.py
index d25c446..b506f17 100755
--- a/dm/mac/pack_app.py
+++ b/dm/mac/pack_app.py
@@ -130,7 +130,7 @@ def info_plist(a, minos, icon):
'CFBundleVersion': a.version or '1.0', 'CFBundleShortVersionString': a.version or '1.0', 'CFBundlePackageType': 'APPL', 'CFBundleExecutable': EXE,
'CFBundleInfoDictionaryVersion': '6.0', 'LSMinimumSystemVersion': minos, 'LSArchitecturePriority': ['arm64'], 'NSHighResolutionCapable': True,
'LSApplicationCategoryType': a.category or 'public.app-category.games', 'LSSupportsGameMode': False, 'DMTitleID': a.title_id.upper(), 'DMRomfsMarker': a.marker or '', 'DMLanguage': a.lang or 'en-US',
- 'DMForkPatches': fork_patches()}
+ 'DMForkPatches': fork_patches(), 'DMControllerMappings': 1}
if icon: p['CFBundleIconFile'] = 'AppIcon'
if a.settings:
listed = json.loads(Path(a.settings).read_text(encoding='utf-8'))['settings']
@@ -293,7 +293,7 @@ def pack(a):
if not codesign: raise SystemExit('codesign is not available')
codesign = Path(codesign).resolve()
minos = min_os(a.host)
- sources = [Path(__file__).resolve(), HERE / 'launcher.c', HERE.parent / 'host/romfs_image.h', HERE.parent / 'host/save_sync.c', HERE.parent / 'host/save_sync.h', HERE.parent / 'tools/romfs.py'] + swift_sources()
+ sources = [Path(__file__).resolve(), HERE / 'launcher.c', HERE.parent / 'host/romfs_image.h', HERE.parent / 'host/input_map.h', HERE.parent / 'host/dm_input.h', HERE.parent / 'host/save_sync.c', HERE.parent / 'host/save_sync.h', HERE.parent / 'tools/romfs.py'] + swift_sources()
inputs = {'options': vars(a), 'files': [(str(p), p.stat().st_mode, digest(p), os.readlink(p) if p.is_symlink() else None) for p in files + sources],
'trees': [(p, inventory(Path(p))) for p in (a.romfs, a.aoc, a.html, *(str(x[1]) for x in programs), *(str(x[3]) for x in programs)) if p and Path(p).exists()],
'tools': [[str(c), c.stat().st_mode, c.stat().st_size, c.stat().st_mtime_ns, c.stat().st_ctime_ns, run([c, '--version']).strip()] for c in (clang, swiftc)] + [
diff --git a/dm/tools/impact_map.tsv b/dm/tools/impact_map.tsv
index c3d5771..d918515 100644
--- a/dm/tools/impact_map.tsv
+++ b/dm/tools/impact_map.tsv
@@ -139,6 +139,16 @@ dm/host/pad_apple.h hle:*hid* controller face buttons from GameController
dm/host/motion_fusion.h hle:*SixAxisSensor* six-axis motion mapping and orientation
dm/host/motion_pro.h hle:*SixAxisSensor* passive Switch Pro Controller IMU decoder
dm/host/motion_pro_mac.h hle:*SixAxisSensor* Mac Pro Controller raw motion transport and routing
+dm/host/input_map.h present:* the Mac front end's key and controller button map
+dm/host/input_preferences_mac.h present:* shared per-game control choices and launch overrides
+dm/host/controllers_mac.h present:* Mac controller lifecycle and mapping panel
+dm/host/pad_map.h hle:*hid* physical controller button mapping
+dm/host/pad_hid_mac.h hle:*hid* generic Mac HID ownership, lifecycle and input
+dm/host/pad_motion.h hle:*SixAxisSensor* Steam Controller motion history
+dm/host/steam_input.h hle:*hid* Steam Controller report decoding and trackpads
+dm/host/haptics_apple.h hle:*Vibration* Apple and direct controller rumble routes
+dm/host/haptics_apple.m hle:*Vibration* Apple and direct controller rumble output
+dm/host/hle_haptics.h hle:*Vibration* the shared rumble interface
dm/host/front.h present:* the front end
dm/ios/* *:* the iOS app
dm/third_party/ryujinx/src/Ryujinx.Graphics.Shader/Translation/Transforms/GeometryToCompute.cs shader:stage:gs geometry compute input and output lowering
diff --git a/dm/tools/tests/test_nsp_mac_app.py b/dm/tools/tests/test_nsp_mac_app.py
index 47ada51..7304908 100644
--- a/dm/tools/tests/test_nsp_mac_app.py
+++ b/dm/tools/tests/test_nsp_mac_app.py
@@ -118,7 +118,7 @@ class PackReuse(unittest.TestCase):
'font/nintendo_ext.ttf': b'font', 'aoc/1/data': b'dlc', 'pso/gpu.mtl4a': b'archive',
'pso/prebuilt.tsv': b'prebuilt', 'pso/rest_pairs.tsv': b'rest', 'pso/archive.tsv': b'index',
'env.txt': b'DM_TEST=1', 'split.tsv': b'split', 'icon.jpg': b'jpeg', 'source/launcher.c': b'launcher',
- 'host/romfs_image.h': b'validator', 'host/save_sync.c': b'sync', 'host/save_sync.h': b'sync api', 'tools/romfs.py': b'reader',
+ 'host/romfs_image.h': b'validator', 'host/input_map.h': b'maps', 'host/dm_input.h': b'buttons', 'host/save_sync.c': b'sync', 'host/save_sync.h': b'sync api', 'tools/romfs.py': b'reader',
'source/Launcher.swift': b'window', 'ios/Sources/LauncherSettings.swift': b'model', 'ios/Sources/LauncherRow.swift': b'rows',
}
for n in pack_app.TABLES: files['profile/' + n] = n.encode()
@@ -176,6 +176,13 @@ class PackReuse(unittest.TestCase):
self.assertTrue(any('--sign' in c for c in self.commands))
self.assertTrue(self.key.is_file())
+ def test_controller_mapping_capability_without_settings(self):
+ self.args.settings = None
+ info = pack_app.info_plist(self.args, '26.6', False)
+ self.assertNotIn('DMSettings', info)
+ self.assertIs(type(info['DMControllerMappings']), int)
+ self.assertEqual(info['DMControllerMappings'], 1)
+
def test_retargeted_input_symlink_repacks(self):
msl = self.tmp / 'msl'
for name in ('left.metallib', 'right.metallib'): (msl / name).write_bytes(b'same library')
@@ -199,6 +206,7 @@ class PackReuse(unittest.TestCase):
'patched/main.obs.tsv', 'patched/nro.tsv', 'msl/k.metallib', 'msl/k.json', 'msl/inputs.tsv', 'font/nintendo_ext.ttf',
'pso/gpu.mtl4a', 'pso/prebuilt.tsv', 'pso/rest_pairs.tsv', 'pso/archive.tsv', 'env.txt', 'icon.jpg', 'source/launcher.c',
'source/Launcher.swift', 'ios/Sources/LauncherSettings.swift', 'ios/Sources/LauncherRow.swift', # the settings window's sources
+ 'host/input_map.h', 'host/dm_input.h', # the launcher's headers
'host/save_sync.c', 'host/save_sync.h'] # the cloud-save code the launcher links (its send after the host exits)
names += ['profile/' + n for n in pack_app.TABLES]
for name in names:
@@ -500,6 +508,7 @@ class App(unittest.TestCase):
self.assertEqual((p['CFBundleExecutable'], p['CFBundleName'], p['CFBundleIdentifier'], p['CFBundleShortVersionString']), ('nxnative', 'Game: Test', 'org.nxnative.01008cf01baac000', '1.0.1'))
self.assertEqual((p['DMTitleID'], p['DMLanguage'], p['DMRomfsMarker'], p['CFBundleIconFile']), (TID, 'fr', 'region_common/audio/edward.bfsar', 'AppIcon'))
self.assertIs(p['LSSupportsGameMode'], False) # macOS's Game Mode holds the GPU at its lowest clock (frame-rate.md)
+ self.assertEqual(p['DMControllerMappings'], 1)
self.assertEqual(p['DMSettings'], []) # launcher.json's settings, as the saved choices they accept: none here
self.assertRegex(p['DMCommit'], r'^[0-9a-f]{12}(\+dirty)?$') # the packing checkout (scripts/bug_report.py, the host's start line)
self.assertEqual(p['DMChain'], '0123456789ab') # the chain of the libraries packed (msl/b-<chain>)
@@ -573,6 +582,104 @@ class App(unittest.TestCase):
subprocess.run(['defaults', 'delete', domain], capture_output=True)
Path(os.path.expanduser(f'~/Library/Preferences/{domain}.plist')).unlink(missing_ok=True)
+ def test_saved_controls(self):
+ """launcher.DM_KEYMAP and launcher.DM_PAD_MAP: saved choices that are no launcher.json rows, checked by the host's own parser (input_map.h) instead of DMSettings;
+ same order as the other saved choices (the environment and the env files win) and the same DM_SAVED_CHOICES=0"""
+ domain = f'org.nxnative.test.{uuid.uuid4().hex}' # never a real game's domain
+ a = types.SimpleNamespace(**vars(self.args)); a.out = str(self.tmp / 'Controls.app'); a.icon = None; a.bundle_id = domain
+ with mock.patch.object(pack_app, 'sign', lambda *x: None), mock.patch('sys.stdout'): pack_app.pack(a) # launcher.json has no settings: only the controls are saved choices here
+ app = Path(a.out); log = self.tmp / f'home/Library/Logs/nxnative/{TID}.log'
+
+ def run(**env):
+ p = self.launch(app=app, **env); out = p.communicate(timeout=30)[0].decode()
+ self.assertEqual(p.returncode, 7, out)
+ return self.host_run(), log.read_text()
+
+ def save(key, *value): subprocess.run(['defaults', 'write', domain, f'launcher.{key}', *value], check=True)
+ sup_env = self.tmp / f'home/Library/Application Support/nxnative/{TID}/env.txt'
+ try:
+ r, text = run()
+ self.assertEqual((r.get('DM_KEYMAP'), r.get('DM_PAD_MAP')), (None, None)) # nothing saved: the host's own defaults
+ save('DM_KEYMAP', '-string', 'A=40,B=38,RUp=126'); save('DM_PAD_MAP', '-string', 'A=B,B=A')
+ r, text = run()
+ self.assertEqual((r['DM_KEYMAP'], r['DM_PAD_MAP']), ('A=40,B=38,RUp=126', 'A=B,B=A')) # a valid saved keymap and pad map are applied
+ self.assertIn('launcher: env DM_KEYMAP=A=40,B=38,RUp=126 (saved choice)', text)
+ r, text = run(DM_KEYMAP='X=7') # a front end's launch override wins for that start
+ self.assertEqual((r['DM_KEYMAP'], r['DM_PAD_MAP']), ('X=7', 'A=B,B=A'))
+ self.assertIn('saved choice DM_KEYMAP=A=40,B=38,RUp=126 not used: DM_KEYMAP=X=7 is set', text)
+ sup_env.parent.mkdir(parents=True, exist_ok=True); sup_env.write_text('DM_PAD_MAP=Y=X\n') # the player's env.txt wins too
+ try:
+ r, text = run()
+ self.assertEqual((r['DM_KEYMAP'], r['DM_PAD_MAP']), ('A=40,B=38,RUp=126', 'Y=X'))
+ self.assertIn('saved choice DM_PAD_MAP=A=B,B=A not used', text)
+ finally: sup_env.unlink()
+ r, text = run(DM_SAVED_CHOICES='0') # the tested defaults; the saved values stay saved
+ self.assertEqual((r.get('DM_KEYMAP'), r.get('DM_PAD_MAP')), (None, None))
+ self.assertIn('saved choices ignored (DM_SAVED_CHOICES=0)', text)
+ self.assertEqual(subprocess.run(['defaults', 'read', domain, 'launcher.DM_KEYMAP'], capture_output=True, text=True).stdout.strip(), 'A=40,B=38,RUp=126')
+ for bad in ('Q=1', 'A=40,Q=1', 'A=128', 'A=abc', 'A=LUp'): # a value the host would not take whole: ignored, logged, the rest still apply
+ with self.subTest(bad=bad):
+ save('DM_KEYMAP', '-string', bad)
+ r, text = run()
+ self.assertNotIn('DM_KEYMAP', r)
+ self.assertEqual(r['DM_PAD_MAP'], 'A=B,B=A')
+ self.assertIn(f'saved choice DM_KEYMAP={bad} ignored: the host does not take it', text)
+ save('DM_PAD_MAP', '-string', 'A=40') # a key code is no button; a keymap value is no pad map
+ r, text = run(); self.assertNotIn('DM_PAD_MAP', r); self.assertIn('saved choice DM_PAD_MAP=A=40 ignored', text)
+ save('DM_PAD_MAP', '-string', '') # empty: nothing to apply
+ r, text = run(); self.assertNotIn('DM_PAD_MAP', r); self.assertIn('saved choice DM_PAD_MAP= ignored', text)
+ save('DM_PAD_MAP', '-float', '1.5') # not a string
+ r, text = run(); self.assertNotIn('DM_PAD_MAP', r); self.assertIn('saved choice for DM_PAD_MAP ignored: not a string', text)
+ finally:
+ subprocess.run(['defaults', 'delete', domain], capture_output=True)
+ Path(os.path.expanduser(f'~/Library/Preferences/{domain}.plist')).unlink(missing_ok=True)
+
+ def test_host_controls_share_bundle_domain(self):
+ """The host child and launcher use the custom bundle domain, including override provenance."""
+ domain = f'org.nxnative.test.{uuid.uuid4().hex}'
+ source = self.tmp / 'controls_probe.m'; host = self.tmp / 'controls_probe'
+ fake_id = 'TEST-' + uuid.uuid4().hex.upper()
+ fallback = 'org.nxnative.' + fake_id.lower()
+ (self.tmp / 'game_profile.h').write_text('#define DM_GAME_ID "' + fake_id + '"\n')
+ source.write_text(r'''#include "input_preferences_mac.h"
+int main(void) { @autoreleasepool {
+ NSString *domain=input_preferences_domain();
+ NSString *value=input_preference_map(domain,"DM_PAD_MAP",1);
+ NSString *out=[NSString stringWithFormat:@"domain=%@\nvalue=%@\nfixed=%d\n",domain,value ?: @"none",input_map_fixed("DM_PAD_MAP")];
+ [out writeToFile:[@(getenv("HOME")) stringByAppendingPathComponent:@"host_run.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
+ if(!input_map_fixed("DM_PAD_MAP") && !input_preference_write(domain,@"launcher.DM_PAD_MAP",@"A=Y")) return 9;
+ return 7;
+} }
+''')
+ subprocess.run(['xcrun', 'clang', '-arch', 'arm64', '-fobjc-arc', '-I', str(self.tmp), '-I', str(REPO / 'dm/host'),
+ '-framework', 'Foundation', '-o', str(host), str(source)], check=True, capture_output=True)
+ a = types.SimpleNamespace(**vars(self.args)); a.out = str(self.tmp / 'ControlsProbe.app'); a.icon = None; a.bundle_id = domain; a.host = str(host)
+ with mock.patch.object(pack_app, 'sign', lambda *x: None), mock.patch('sys.stdout'): pack_app.pack(a)
+
+ def run(**env):
+ p = self.launch(app=Path(a.out), **env); out = p.communicate(timeout=30)[0].decode()
+ self.assertEqual(p.returncode, 7, out)
+ return self.host_run()
+
+ def saved():
+ return subprocess.run(['defaults', 'read', domain, 'launcher.DM_PAD_MAP'], check=True, capture_output=True, text=True).stdout.strip()
+
+ try:
+ standalone = subprocess.run([str(host)], env={'HOME': str(self.tmp / 'home')}, capture_output=True)
+ self.assertEqual(standalone.returncode, 7, standalone.stderr)
+ self.assertEqual(self.host_run()['domain'], fallback)
+ subprocess.run(['defaults', 'write', domain, 'launcher.DM_PAD_MAP', '-string', 'A=B'], check=True)
+ self.assertEqual(run(), {'domain': domain, 'value': 'A=B', 'fixed': '0'})
+ self.assertEqual(saved(), 'A=Y') # host's panel-facing write is visible to the next launcher
+ self.assertEqual(run(DM_PAD_MAP='A=X'), {'domain': domain, 'value': 'A=X', 'fixed': '1'})
+ self.assertEqual(saved(), 'A=Y') # a launch override never leaks into saved choices
+ self.assertEqual(run(DM_SAVED_CHOICES='0'), {'domain': domain, 'value': 'none', 'fixed': '0'})
+ self.assertEqual(saved(), 'A=Y')
+ finally:
+ for cleanup in (domain, fallback, 'org.nxnative.' + fake_id):
+ subprocess.run(['defaults', 'delete', cleanup], capture_output=True)
+ Path(os.path.expanduser(f'~/Library/Preferences/{cleanup}.plist')).unlink(missing_ok=True)
+
def test_signed(self): # ad-hoc, both the host and the bundle, never the hardened runtime (it refuses the executable memory the host makes for the game's code)
for target in (self.app, self.app / 'Contents/MacOS/dmhost'):
subprocess.run(['codesign', '--verify', '--strict', target], check=True, capture_output=True)
diff --git a/docs/development.md b/docs/development.md
index 4d70499..07010f3 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -601,6 +601,10 @@ Why the host is a child process: macOS privacy checks (TCC) cover files on remov
Signing: `pack_app.py` signs the inner host first, then the bundle (`codesign --force --sign <identity>`). It signs ad-hoc by default; `--mac-sign "<identity>"` (`MAC_SIGN` in Spyder) names a Developer ID or another identity. It never uses the hardened runtime: `--options runtime` refuses the executable memory the host maps for the game's code. Notarization needs the hardened runtime, so the app is not notarized. Gatekeeper blocks it on a Mac it was downloaded to until it is allowed in System Settings › Privacy & Security. `dm/tools/tests/test_nsp_mac_app.py` tests the packer and the launcher with a stand-in host, without game files.
+For the Steam Controller's direct HID input, see [Input Monitoring and rebuilt apps](mac-controllers.md#input-monitoring-and-rebuilt-apps), including renewing permission after an ad-hoc rebuild.
+
+Mac controller routing, including the split Joy-Con adapters in the shared controller registry, model-specific extras, shared mapping preferences and their hardware validation limits are described in [Mac controllers](mac-controllers.md). Packaged apps advertise this contract with `DMControllerMappings=1` in `Info.plist` so front ends can gate mapping controls.
+
## Build and run on a device with Xcode
With an Apple developer account, Xcode can sign and install the app itself:
diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
index 08e9eec..3f37f7b 100644
--- a/docs/env_switches.tsv
+++ b/docs/env_switches.tsv
@@ -93,7 +93,7 @@ DM_JIT_SERVE path Folder of a `nn::jit` image (`jit.img`, `jit.tsv`, `jit.out`):
DM_JOYCON_SPLIT switch `1` splits a Bluetooth Nintendo Switch Joy-Con pair on macOS (`0x057e:0x2006` and `0x057e:0x2007`) into two sideways controllers over `IOHIDManager` (`pad_joycon_mac.h`, requires Input Monitoring permission) with per-half 6-axis motion and `LeftHandle` / `RightHandle` Core Haptics rumble
DM_KBD switch `=<text>`: the system keyboard returns that text as OK without showing an input box; unset with no window, it returns cancel
DM_KBD_PLAYER switch `own` makes the Mac keyboard player 1 on its own, with controllers from player 2 on (by default the first controller shares player 1 with the keyboard)
-DM_KEYMAP player Mac keyboard: `<name>=<key code>,…` puts a button (`A` … `Down`), a stick direction (`LUp` … `RRight`) or `Shake` on another key (macOS virtual key code, or `none`); one key holds one function (`input_map.h`)
+DM_KEYMAP player Mac keyboard: `<name>=<key code>,…` puts a button (`A` … `Down`), a stick direction (`LUp` … `RRight`) or `Shake` on another key (macOS virtual key code, or `none`); one key holds one function (`input_map.h`); a Mac app also keeps it as the saved choice `launcher.DM_KEYMAP`, used when the host takes the whole value
DM_KEYS switch Scripted input: `<seconds or f<frame>>:<key>[+key][~hold or ~f<frames>][*count/interval],…` presses buttons, sticks, touches and `Shake` at those times; `=@<file>` reads the steps from the file
DM_LANG player Game language as a language code (default `en-US`; the iOS app sets the one the IPA was packed with)
DM_LAUNCHER switch `0` skips the iOS settings screen or the Mac settings window and starts the game at once, with the saved choices (on the Mac also `--no-launcher`)
@@ -238,7 +238,7 @@ DM_OODLE_JOB path `=<job file>`: the host runs the game's own Oodle decoder on e
DM_OODLE_MODULES path The rewritten modules the Mac host's Oodle tool mode loads when `shader_split.py` decodes Trinity packs; set by the NSP script
DM_OODLE_SERVE switch `=1`: the host answers decode requests on stdin / stdout with the game's own Oodle (or LZ5) decoder from the guest main thread before the SDK starts, until stdin ends
DM_OPMODE player The operation mode the game sees: `0` handheld, `1` console (default: the profile's `op_mode`, console unless set); read once at startup
-DM_PAD_MAP player Mac controllers: `<name>=<name>,…` makes the button that sends the first by default send the second (or `none`), e.g. `A=B,B=A` swaps them (`input_map.h`)
+DM_PAD_MAP player Mac controllers: `<name>=<name>,…` makes the button that sends the first by default send the second (or `none` / `Shake`), e.g. `A=B,B=A` swaps them (`input_map.h`); a Mac app also keeps it as the saved choice `launcher.DM_PAD_MAP`, used when the host takes the whole value
DM_PAD_MERGE switch `=1` merges every controller into player 1, as before, instead of giving each controller a player of its own (Mac and iOS)
DM_PATCH_FRONT switch `=<bytes>`: the size of the patch area right before the module base for a long text (`BIG_TEXT`); set only by the rewriter's own rerun with the size it needs
DM_PHONE_MOTION switch On iOS, whether the phone's own device motion drives player 1's six-axis sensor: `auto` (default) while no controller supplies fresh motion, `1` phone only, `0` never; each source keeps its own orientation
@@ -337,6 +337,8 @@ DM_SLOWFRAME diagnostic `=1` writes the per-frame timing breakdown to the log on
DM_SPIN switch `0` makes the rewriter's spin gate return at once, so guest poll loops spin with no sleep; the gate stays (on by default)
DM_SPIN_LIST diagnostic `=1` makes `patch_nso.py` print every guest poll loop it found and sends through a spin gate
DM_SPIN_POLL switch `=<µs>`: how long a spin-gate wait polls before it sleeps with the yield back-off (default 2000; `0` yields on every pass)
+DM_STEAM_DEADZONE switch `=0..0.9` (exclusive upper bound) sets the radial deadzone for both raw Steam Controller sticks; default 0.10, `0` disables it; invalid values use the default
+DM_STEAM_HID switch `=0` disables the Mac direct Steam Controller HID adapter and leaves input to Apple GameController; enabled otherwise
DM_SVC diagnostic `=1` logs memory SVCs (`SetHeapSize`, `MapMemory`, `Map`/`UnmapPhysicalMemory`) with their addresses and sizes
DM_SYMCHECK diagnostic `=1` checks every hashed module symbol lookup against a linear search and logs a red line for each mismatch
DM_TBUF_ALIGN diagnostic `=<bytes>` uses that value as the linear-texture alignment when it is larger than the device's `minimumLinearTextureAlignmentForPixelFormat`, for buffer textures and for linear textures on a pool's buffer: a Mac can then reproduce a phone's larger alignment (a 64-byte one fails the buffers and linear textures a device with 64 bytes cannot view), to check `tbuf_as_2d`'s aligned-row copy and the upload of unaligned linear textures (`linear_fit`)
@@ -373,6 +375,7 @@ DM_TOUCH_STICK player iOS left touch-stick position: corner (default), higher or
DM_UDC_SELFTEST diagnostic `=1` runs a start-up check of DontCare load and store on private depth-stencil and RGBA8 textures (clear, Load + DontCare, read back) and logs one result line
DM_UE_SHADERS path Folder of the Unreal shader code archives decoded by `uepak.py`, for `shader_split.py` (default `ue_shaders` beside the RomFS); needed when the RomFS has Unreal paks
DM_UE_TEXTURE_POOL switch Megabytes Unreal's texture streaming pool (`r.Streaming.PoolSize`) is raised to, overriding the profile's `ue_texture_pool`; `0` keeps the game's own pool. On iOS only this switch turns it on (`Documents/env.txt`)
+DM_UI_HOLD test When set, keeps the controller mapping test window open for 60 seconds after its UI screenshot for manual inspection
DM_UPSCALER player `metalfx` draws the game's own upscaler shaders (agl's NDSR network, found by the shader map) with MetalFX's spatial scaler; `game` (the default) runs them
DM_VK_CAPTURE path `=<dir>` (Mac) writes every SPIR-V module the game creates to `<dir>/<key>.spv`; the NSP script's Vulkan shader capture stage sets it
DM_VK_LOG diagnostic `=1` logs Vulkan object creation in the Vulkan-on-Metal layer
diff --git a/docs/frontends.md b/docs/frontends.md
index c6e325c..0361af2 100644
--- a/docs/frontends.md
+++ b/docs/frontends.md
@@ -67,6 +67,7 @@ Each app keeps the player's choices in its own preferences domain, its bundle ID
- **Only choices that differ from the tested default are kept.** A setting the player left at its default follows the defaults of a later build. Remove a key when the player picks the default again. For "Reset to tested defaults", remove the keys of the settings the player can change; the app's own screen does that when Play applies the defaults, and keeps the saved choice of a setting fixed for this start.
- **Checked when read.** The launcher uses a saved value only when this build still offers it: one of a `choice`'s options, a `toggle`'s `on` or `off`, or a number from a `range`'s `min` to `max`. It checks against the app's own list, which the packer copies into `Info.plist` as `DMSettings`. Any other value, a value that is not a string, or a key no setting has is ignored; it stays saved until the settings screen's Play replaces it with the player's choice. So a rebuild that stops offering a value falls back to its tested default.
+- **Controls are saved choices too, with another check.** `launcher.DM_KEYMAP` (keys) and `launcher.DM_PAD_MAP` (controller buttons) are strings in the same domain, in the form the environment variables take (`defaults write org.nxnative.<title ID> launcher.DM_PAD_MAP -string "A=B,B=A"`; the forms are in [env_switches.tsv](env_switches.tsv)). They are no `launcher.json` rows, so `DMSettings` cannot check them: the launcher checks them with the host's own parser (`input_map_valid` in `dm/host/input_map.h`, which the host and the launcher share). A value the host would not take whole (an unknown name, a key code past 127, a button where a key code belongs, an empty string, or a value that is not a string) is ignored and logged, though the host alone would apply the good entries of it. They follow the order below and `DM_SAVED_CHOICES=0`, and the launcher reads them whether or not its settings window ran: the window does not offer them.
- **The order**, the first that sets a variable wins:
1. the launch environment (a front end's launch overrides, a terminal);
2. the player's `env.txt` (`~/Library/Application Support/nxnative/<title ID>/env.txt`; on the iPhone, `Documents/env.txt`);
@@ -78,6 +79,37 @@ Each app keeps the player's choices in its own preferences domain, its bundle ID
- **`DM_SCREEN=<number>`** opens the Mac game's window on the screen with that `NSScreenNumber` (`CGDirectDisplayID`), centred, before any `DM_FULLSCREEN` request, so a front end can keep the game on its own display. An unknown number is ignored and logged. NX2Apple sets it to the screen of its own window.
- **A sandboxed front end** cannot write another app's preferences domain; this store is for front ends outside the App Sandbox, as NX2Apple is.
+### Controller-specific choices
+
+Mac apps whose `Info.plist` contains the integer **`DMControllerMappings=1`** implement this shared mapping contract. Front ends must check this capability before showing or saving these mappings. `DMSettings` alone does not advertise controller mapping support.
+
+The Mac [controller panel](mac-controllers.md#controllers-and-mapping) reads
+and writes `launcher.DM_PAD_MAP` for the standard 16 buttons, shared by every
+controller for this game. Its Nintendo Positions preset removes the key,
+Xbox Labels writes `A=B,B=A,X=Y,Y=X`. `Shake` is also accepted as a target
+(`A=Shake`), in addition to the buttons and `none` from PR #386. Sources remain
+the 16 standard buttons. The keyboard map is independent.
+
+Extra inputs use `controller.<model>` dictionaries in the **same app domain**
+(for example `controller.Valve Triton`). No model dictionary may override the
+standard button map. Its optional fields are:
+
+| Field | Value | Default |
+|---|---|---|
+| `buttons` | Dictionary of physical source strings `16` through `23` to integer Switch targets `0` through `15`, `63` for Shake, or `-1` for Unassigned | All unassigned |
+| `pads` | Two integers, left then right: 0 Off, 1 D-pad, 2 Left stick, 3 Right stick, 4 Switch touchscreen | Triton `[1,4]`, other models `[0,0]` |
+| `gyro` | Boolean | true |
+
+Source order is L4/Paddle 1, R4/Paddle 2, L5/Paddle 3, R5/Paddle 4, left pad
+click, right pad click, Guide/Home, Quick Access/Share. These extra targets
+are final Switch functions, not inputs to `DM_PAD_MAP` again. A pad used as a
+D-pad supplies the ordinary D-pad sources and follows the standard map.
+Only fields differing from defaults are written, an empty model dictionary
+is removed. Malformed fields are ignored. `DM_SAVED_CHOICES=0` ignores these
+dictionaries too and never writes them. The panel reloads preferences when
+opened, external edits take effect then or at the next game start. Older
+`controllers.plist` files are read only by the panel's explicit import action.
+
### The cloud saves folder
The folder a Mac app's save is synced through ([Cloud saves](settings.md#cloud-saves)) is not a row of the settings list, since a folder is none of its kinds. It has a key of its own in the same store: `cloudSaves.folder`, a string with the folder's absolute path (`defaults write org.nxnative.<title ID> cloudSaves.folder "$HOME/Library/Mobile Documents/com~apple~CloudDocs/My Saves"`). Remove the key, or write an empty string, to turn cloud saves off. The app's settings window shows and changes the same key, so the player sees the folder a front end chose.
diff --git a/docs/mac-controllers.md b/docs/mac-controllers.md
new file mode 100644
index 0000000..e633df5
--- /dev/null
+++ b/docs/mac-controllers.md
@@ -0,0 +1,253 @@
+# Mac controllers
+
+## Controllers and mapping
+
+Connect a supported controller and press a button, then open
+**Controllers → Button Mapping…**.
+Select the controller and assign each physical button to a Switch button,
+Shake, or Unassigned. **Nintendo Positions** is the default (right face button
+is A), **Xbox Labels** makes the bottom face button A. Changes take effect
+immediately. The first 16 button choices apply to **every controller for this
+game**, using the same saved map as an external launcher. Rear buttons, pad
+clicks, Guide/Share, trackpad modes and motion choices are saved per model in
+the same app preferences domain. Extra buttons are usable only when the
+controller/driver exposes them. A rear button mapped to A sends Switch A,
+it is not remapped a second time by the standard button map.
+
+Hold physical Home (Guide on Triton) for two seconds to open the Mac quit prompt.
+Physical A confirms, B or a new Home press cancels, regardless of the game's
+button map. The game resumes controller input once those buttons are released.
+For the macOS Home setting and `DM_HOME_QUIT=0`, see [On the Mac](playing.md#on-the-mac).
+
+The panel shows when standard buttons are fixed by a launch override or
+`env.txt`, remove that override and restart to edit them. With
+`DM_SAVED_CHOICES=0`, the panel starts with defaults and edits last only for
+that session. Opening the panel reads the latest saved choices again.
+
+Older builds saved mappings in `controllers.plist` under `DM_ROOT`, or
+`~/Library/Application Support/org.nxnative.controllers/` without `DM_ROOT`.
+If one exists, **Import previous mapping for this model** imports the selected
+model's buttons, trackpads and motion choices. Its standard buttons become
+the game's shared map for all controllers. Import is explicit because two
+old model maps can disagree, or a launcher may already have saved choices.
+The old file is kept unchanged, new edits use the shared preferences.
+
+Shake drives that controller's six-axis sensor and follows its player assignment.
+In one-player games it merges into player 1 with the controller's other input,
+including when `DM_KBD_PLAYER=own` reserves the first slot for the keyboard.
+A brief press completes one shake cycle, holding repeats it.
+
+The existing eight-player allocation is retained: controllers take separate
+slots. Press a button or move a stick to join with a GameController device,
+reconnecting controllers reclaim a free slot of their model, and a
+disconnect releases all held input. The keyboard shares player 1 by default.
+`DM_KBD_PLAYER=own` reserves player 1 for the keyboard, `DM_PAD_MERGE=1` combines
+controllers into player 1. Two identical models may exchange slots on reconnect.
+
+## Split Joy-Con
+
+With `DM_JOYCON_SPLIT=1` at launch, each Bluetooth Joy-Con half uses its own
+sideways player slot, stick, six-axis motion and Home input. The combined
+GameController pair supplies left and right handle rumble without taking an
+additional input slot. Both halves share the standard button mapping with
+Steam Controller and other pads. Leaving this option off keeps the combined
+GameController pair. If the split HID manager cannot open, the host retains
+the combined pair.
+
+## Generic HID gamepads
+
+A gamepad macOS pairs but GameController does not support (such as an 8BitDo
+in D-input mode) uses the generic HID reader. It shares the same player slots,
+button map and mapping panel with GameController and Triton, it does not use
+Triton's rumble or motion protocol. `DM_HID_MAP` maps device button usages to
+standard buttons first, then `DM_PAD_MAP` applies the game's shared choices.
+`DM_HID_LOG=1` logs button usages, `DM_HID_PADS=0` disables only this fallback.
+Buttons and sticks held through a focus change resume when the game regains
+focus. GameController-supported and synthetic devices are excluded.
+
+For shared ownership, incomplete device metadata and recovery after deferred
+admission, see [controller hotplug and fallback](reference/services.md#steam-controller-hotplug-interrupts-other-players).
+Physical device and hotplug retesting remain open.
+
+## Steam Controller (2026)
+
+The Mac host includes a direct IOKit HID adapter for Valve's 2026 **Triton**
+controller. It takes exclusive ownership of validated Triton HID interfaces for
+trackpads, motion and rumble, before registering native input. Matching native
+profile names is unnecessary: identical controllers and separate Puck
+interfaces keep their raw features. Empty Puck interfaces and cached native
+profiles never claim a player slot. Other controllers use Apple's GameController
+or the generic HID fallback described above.
+
+The Triton adapter supports:
+
+- USB-C, Bluetooth, and paired Puck controller interfaces (Valve USB IDs
+ `28de:1302`, `1303`, `1304`, `1305`).
+- Both sticks and stick clicks, face buttons, D-pad, shoulders, triggers,
+ Menu/View, Guide/Quick Access, four rear buttons and both trackpad clicks.
+- Both raw sticks use a 10% radial deadzone so resting drift does not suppress
+ gyro aiming. Remaining travel is rescaled to full range. Set
+ `DM_STEAM_DEADZONE` to a fraction from 0 to below 0.9 to adjust it (0 disables
+ it), invalid values use 0.10. Trackpad coordinates are unaffected.
+- Rear buttons and trackpad clicks can be assigned in the same mapping panel.
+ Their default is Unassigned.
+- Left trackpad defaults to **D-pad**, right trackpad to **Switch touchscreen**.
+ In the mapping panel either can select Off, D-pad, Left stick, Right stick or
+ Switch touchscreen. Touching the pad presses a finger at its absolute screen
+ position, moving drags, lifting releases. Mouse and pad fingers can coexist.
+ A game must read the Switch touchscreen for this mode to have an effect,
+ some games do so only in handheld mode (`DM_OPMODE=0`).
+- Gyro and accelerometer feed the game's six-axis input. **Motion controls**
+ enables it, **Recenter gyro** resets the integrated orientation. Orientation
+ uses raw gyro integration without drift correction, so recenter when needed.
+ Missing samples expire after 250 ms, focus loss and disconnect clear motion.
+- Left/right rumble is adapted from the game's vibration amplitudes, with a
+ 40 ms refresh for the firmware watchdog. It stops when the game window loses focus (including the mapping panel or
+ minimization), on disconnect and normal exit. `DM_RUMBLE=0` disables it, `DM_RUMBLE_GAIN` adjusts strength
+ (default 1, range 0–3). This approximates vibration, it does not reproduce
+ Switch HD Rumble waveforms or add separate trackpad texture effects.
+ `DM_RUMBLE_MIN` (default 0, range 0–0.9) silences controller intensities at or
+ below the threshold and rescales the remaining range, after applying gain.
+
+The adapter runs without Steam and temporarily disables desktop mouse/keyboard
+emulation while connected to the game, the controller's watchdog restores it
+after exit. The app owns those controller interfaces until it closes, other
+apps cannot receive their input during that time. To use Steam's input route
+instead, set `DM_STEAM_HID=0` before starting the game. If exclusive access fails,
+native controls remain available, but raw rumble, gyro and trackpads cannot be
+guaranteed. Quit Steam, then follow [Input Monitoring and rebuilt apps](#input-monitoring-and-rebuilt-apps)
+to check the permission and reconnect. Errors appear in the app log.
+
+Connecting a Steam Controller preserves other controllers' player slots, held
+buttons/sticks and rumble. Native admission scans for raw interfaces before a
+player joins, so delayed notifications cannot create duplicate players. In merge
+mode the current rumble owner keeps its route until it disconnects.
+
+Composite native and raw interfaces are opened together. A failed open releases
+only that controller's group and keeps it on native fallback until the whole
+group disconnects. Puck ports remain independent. If native input joins before
+its raw sibling is available, that connection also stays native until reconnect.
+
+The adapter uses USB device/interface ancestry or macOS's physical-device ID,
+never profile names. If macOS omits that identity, it keeps native fallback and
+blocks conflicting new raw claims. If an unidentified native interface appears
+while a compatible raw route is already open, it defers new native admissions
+until that ambiguity clears, preserving existing players. Restart with
+`DM_STEAM_HID=0` to use only native input on such a driver. The log identifies
+missing identity and exclusive-open failures.
+
+For pairing, firmware updates and Puck setup, follow
+[Valve's 2026 controller guide](https://help.steampowered.com/en/faqs/view/33E8-5EDF-24E6-4CFB).
+The original 2015 Steam Controller is a different protocol and is not handled
+by this adapter.
+
+Physical-device validation is incomplete. Trackpads, rear buttons, mapping
+persistence, Bluetooth and Puck operation still need hardware testing on this
+revision. The gyro scale has not been calibrated against a known rotation.
+
+Native GameController motion and passive Switch Pro Controller motion use the
+upstream motion system and follow the same player slots as mapped buttons.
+Steam Controller history participates in that system's source selection:
+usable native motion takes precedence, and iPhone builds retain their phone
+motion selection. `DM_MOTION=0` disables all physical motion, including Steam
+Controller motion. Focus loss and disconnect clear the affected source.
+Native, Pro Controller and phone motion keep their live orientation during
+mapped Shake, adding the shake acceleration. Direct Steam motion retains its
+whole synthetic Shake cycle, then resumes its recorded physical samples.
+
+## Shared launcher controls
+
+The [controls coordination comment on PR #221](https://github.com/seedds/nxnative/pull/221#issuecomment-6441650311)
+separates controller hardware support from the shared mapping model proposed in
+[issue #388](https://github.com/seedds/nxnative/issues/388). The Triton report
+reader supplies physical buttons, sticks, trackpads and motion, the mapping
+layer turns those inputs into Switch controls. A launcher UI does not need to
+implement or change the hardware protocol.
+
+The launcher and host share the [saved-choices store](frontends.md#saved-choices)
+and `input_map.h` parser from [PR #386](https://github.com/seedds/nxnative/pull/386).
+`launcher.DM_KEYMAP` changes keyboard functions, `launcher.DM_PAD_MAP` changes
+standard controller buttons. The controller panel writes the latter key,
+removing it when Nintendo Positions restores the default. It does not change
+the keyboard map. `Shake` is an additional controller target so existing
+per-player Shake bindings remain expressible (`A=Shake`), stick directions
+are keyboard functions, not controller button sources or targets.
+
+The domain is the app's `CFBundleIdentifier`, including a custom bundle ID,
+a standalone host uses `org.nxnative.<compiled title ID>` with the ID in
+lowercase, matching the packer's default bundle ID. Launch environment
+and `env.txt` values take precedence and remain temporary. Saved values must
+pass the shared parser as a whole. `DM_SAVED_CHOICES=0` ignores saved controls
+and prevents writes, `DM_LAUNCHER=0` skips the launch window but still applies
+them. See [controller-specific choices](frontends.md#controller-specific-choices)
+for the extra-input data in that same domain. Transport discovery, report
+decoding, rumble and six-axis sampling remain independent of these choices.
+
+Recenter keeps a truthful identity orientation. A game that treats an exactly
+identity orientation as an unset aim reference may need controller movement
+after recentering. The radial deadzone prevents resting stick drift from
+overriding gyro aiming.
+
+## Input Monitoring and rebuilt apps
+
+macOS can require **System Settings → Privacy & Security → Input Monitoring**
+permission for the Steam Controller's direct HID interfaces. Bluetooth pairing
+does not grant this permission. Native buttons may still work when direct HID
+access is denied, while rumble, gyro or trackpads are unavailable. Apple explains
+the permission in [Control access to input monitoring on Mac](https://support.apple.com/guide/mac-help/control-access-to-input-monitoring-on-mac-mchl4cedafb6/mac).
+
+1. Quit the game completely and quit Steam, so another process is not holding
+ the controller.
+2. Open **System Settings → Privacy & Security → Input Monitoring** and enable
+ the game app you actually launch. If it is missing, use **+** to select that
+ `.app` from its current location. For a standalone `dmhost` launched from a
+ terminal, check the terminal application that launched it, such as Terminal
+ or iTerm, instead, macOS can attribute the access to that application.
+3. Accept **Quit & Reopen** if offered, or fully quit and relaunch the affected
+ app yourself. Reconnect the controller and bring the game window into focus.
+ Press a button, then open **Controllers → Button Mapping…** to confirm that
+ the controller is listed and check its assignments. Close the panel and test
+ input and rumble in the game, input and rumble are deliberately suspended
+ while the mapping panel has focus.
+
+If the controller worked before rebuilding or replacing the app, an enabled
+entry may still refer to the previous build. The Mac packer signs ad-hoc by
+default, and that signature identifies a particular version of the code,
+permission may need to be granted again after a rebuild. Keeping the same app
+name or bundle ID alone does not guarantee that macOS recognizes the new code
+as the previously authorized app. See Apple's
+[code identity explanation](https://developer.apple.com/documentation/technotes/tn3127-inside-code-signing-requirements#Designated-requirement).
+
+With the rebuilt app closed, turn its Input Monitoring switch off and on, then
+relaunch. If access is still denied, select its old entry and remove it with
+**−**, use **+** to add the rebuilt `.app` from the exact path you now launch,
+and enable it again. This matters when keeping old and new builds for comparison:
+check the selected app's location rather than relying on identical display names.
+
+If the entry remains stale, reset only this app's Input Monitoring decision from
+Terminal. Replace the example path with the rebuilt app's absolute path:
+
+```sh
+app="/absolute/path/to/My Game.app"
+bundle_id=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist") &&
+ test -n "$bundle_id" &&
+ /usr/bin/tccutil reset ListenEvent "$bundle_id"
+```
+
+The reset removes the decision, it does not grant permission. Reopen the app,
+enable it in Input Monitoring, then quit and reopen once more if requested.
+The command is scoped to the bundle ID read from that app, copies with the same
+ID share that scope. It does not clear other permissions or other apps' entries.
+For a Terminal-launched host, reset/re-enable the terminal application's entry
+instead. Apple documents `ListenEvent` and the per-app reset in
+[Resetting access to protected resources](https://developer.apple.com/documentation/xcode/resetting-access-to-protected-resources-in-macos).
+
+If the controller still does not appear, check the [Mac app log](development.md#a-mac-app)
+at `~/Library/Logs/nxnative/<title ID>.log` (or the terminal output for a standalone
+host). `Steam Controller HID access unavailable` and
+`cannot exclusively open Steam Controller` point to HID access or another app
+holding the device, neither message alone proves a permission problem. Also
+check that `DM_STEAM_HID=0` is not disabling the direct adapter. If Bluetooth
+input fails in Steam and other games too, troubleshoot the Mac's connection
+first. For repeated development builds, the packer's existing `--mac-sign`
+option can use a stable signing identity, see [Mac app signing](development.md#a-mac-app).
diff --git a/docs/reference/services.md b/docs/reference/services.md
index 8a97476..813b5b0 100644
--- a/docs/reference/services.md
+++ b/docs/reference/services.md
@@ -277,6 +277,27 @@ Most service calls can be found before they crash, before the first boot or the
- **Fix:** look up the player once and derive the style from that same result before constructing the player mask.
- **Found on:** clang static analysis ([issue #424](https://github.com/seedds/nxnative/issues/424)); no gameplay failure reported.
+### Steam Controller hotplug interrupts other players
+
+- **Symptom:** connecting a Steam Controller clears another controller's held input or rumble and makes it press a button to rejoin; a composite controller can appear as two players or lose native fallback after a partial exclusive open.
+- **Cause:** resetting every native profile covered the native/HID notification race, but discarded unrelated players. Independent opens of native, generic gamepad and vendor siblings could leave half of one controller seized. A generic reader with a separate slot table or an auto-opening HID manager could also allocate a duplicate player or prevent the exclusive claim. Dropping a deferred matching callback lost that generic controller until reconnect.
+- **Fix:** `controllers_mac.m` completes synchronous HID discovery before admitting a fresh, non-neutral native event. It gates only unadmitted snapshots and preserves established slots and the merged rumble owner. USB device ancestry, per-port Puck interface ancestry, or the OS physical-device ID groups sibling claims; report metadata selects the Triton endpoint. Opens commit together, suppression handles have no decoder, and failure releases only that group. Generic HID uses the same registry, slot allocation, shared mapping and focus gate, with a separate transport that never receives Triton output reports. Both managers use independent devices and open only after admission. Standard nonprotocol collections without physical identity or Puck interface metadata retain generic fallback when no conflicting raw route exists; ambiguous new raw claims wait instead of guessing a port. Deferred generic matches are retained and reconsidered when discovery changes, then released on unplug. See [Mac controller behavior and fallback](../mac-controllers.md#steam-controller-2026).
+- **Found on:** synthetic native/HID race, ownership-failure and mixed-controller regressions in `dm/host/tests/t_controllers_mac.m`; physical controller/game validation remains pending.
+
+### Steam Controller bypasses the rumble cutoff
+
+- **Symptom:** `DM_RUMBLE_MIN` silences quiet effects on native controllers but has no effect on the Steam Controller's direct HID output.
+- **Cause:** the direct adapter converted the game's vibration bands and gain into motor reports without applying the cutoff used by the Core Haptics and DualShock 4 routes.
+- **Fix:** all three routes share `dm_haptics_apple_controller_intensity`. The Steam adapter applies it independently to each motor after band conversion and gain, before encoding the output report. Guest vibration values are unchanged. Replacing a DualShock route with a direct output also releases that player's old HID claim, preserving other players' claims.
+- **Found on:** synthetic regressions in `dm/host/tests/t_controllers_mac.m` and `t_haptics_apple.m`, covering packet mapping, gain before cutoff, threshold/rescaling and route replacement. No new hardware or game validation.
+
+### Steam Controller stick drift suppresses gyro aiming
+
+- **Symptom:** six-axis values reach the game but gyro aiming does nothing, or stops after using a stick.
+- **Cause:** the raw Triton reports contain small nonzero stick values at rest. Passing them through as intentional input prevents a game that prioritizes stick input from using motion aiming.
+- **Fix (resolved in the decoder):** apply a radial deadzone to both sticks in `steam_input.h`, default 10%, rescaling the remaining travel to full range. `DM_STEAM_DEADZONE` accepts 0 to below 0.9; invalid values retain the default. Trackpads and motion remain unchanged. Decoder regressions cover all three report formats, centre drift, radial boundaries, travel, diagonals and settings.
+- **Found on:** [Tears of the Kingdom](../../dm/games/0100F2C0115B6000/README.md#services); the contributor's USB-C test confirmed gyro aiming with the proposed deadzone. No new local gameplay validation.
+
### History reads fill every requested entry
- **Symptom:** buttons and menus work, the sticks do nothing in play (Super Mario Odyssey: its first hint, "Look Around", waited forever); an `nn::diag` abort with Result 0x2aca in the first frames of `nnMain` (Hollow Knight: Silksong, Unity 6000.0.50f1: `bt: sdk+0x514580 main+0x1296c64 …`).
@@ -296,7 +317,7 @@ Most service calls can be found before they crash, before the first boot or the
- **Symptom:** motion moves never happen; shaking does nothing (Super Mario Odyssey: cap throws by shaking).
- **Cause:** the host handed out six-axis handles but reported no sensor.
-- **Fix:** it now reports one per connected controller: two for handheld or dual Joy-Cons, one otherwise, with the style, npad id and device in the handle. At rest the sensor lies flat: acceleration (0, 0, −1) G, no rotation, identity direction. Samples are 5 ms apart on the guest clock and numbered by time, so a history read returns the samples at those times. `DM_BTN_SHAKE` (`dm_input.h`: the iPhone shaken, Space on the Mac, `DM_KEYS` `Shake`) plays a side-to-side shake in whole cycles.
+- **Fix:** it reports one combined sensor per FullKey or Handheld controller, two for dual Joy-Cons and one for a single Joy-Con, with the SDK style index, npad id and device in the handle ([handle encoding](#six-axis-handle-encoding)). At rest the sensor lies flat: acceleration (0, 0, −1) G, no rotation, identity direction. Samples are 5 ms apart on the guest clock and numbered by time, so a history read returns the samples at those times. `DM_BTN_SHAKE` (`dm_input.h`: the iPhone shaken, Space on the Mac, `DM_KEYS` `Shake`) plays a side-to-side shake in whole cycles.
- **Found on:** [Super Mario Odyssey](../../dm/games/0100000000010000/README.md): it reads all 16 history entries per sensor and ignores the count, like its npad history ([History reads fill every requested entry](#history-reads-fill-every-requested-entry)).
- **Note:** find a game's swing detector by probing the accelerometer value it reads (`DM_PROBE=main:626248@x8+10` in Odyssey 1.4.1).
@@ -336,6 +357,20 @@ Most service calls can be found before they crash, before the first boot or the
- **Open:** passive reading cannot obtain factory calibration without issuing SPI commands alongside the OS driver. Nominal scales are 4096 counts/G and 70 mdps/count ([protocol research](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/imu_sensor_notes.md)); no automatic bias learning removes slow intentional turns. Sample order follows that research and [Linux hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c); SDL reverses it. Confirm order, sensitivity, drift and reconnects on hardware before calling the reworked reader device-tested. `t_motion_pro`, `t_motion_pro_mac` and `t_hid` cover decoding, timestamps, ownership, removal, ambiguity and source fallback with synthetic inputs.
- **Found on:** [Super Mario Galaxy](../../dm/games/010099C022B96000/README.md), docked pointer on a Pro Controller.
+### Six-axis handle encoding
+
+- **Symptom:** six-axis handles use byte 0 = 0 for a FullKey controller, which the SDK reserves for no style; Handheld exposes two sensors instead of its combined sensor.
+- **Cause:** `GetSixAxisSensorHandles` encoded the style bit number rather than the SDK style index, and treated Handheld like a Joy-Con pair. The reader accepted the same private format, hiding the mismatch.
+- **Fix (resolved):** use SDK style indices 3 through 7, with device 2 for FullKey / Handheld, 0 and 1 for JoyDual, and the corresponding side for single Joy-Cons, following [libnx's handle construction](https://github.com/switchbrew/libnx/blob/master/nx/source/services/hid.c). Readers validate the style, device, player and reserved byte consistently; invalid handles return no connected samples and report at rest. Tests use independent wire-format fixtures and cover docked / handheld histories, bounds and invalid handles.
+- **Found on:** the [Tears of the Kingdom PR #221 hardware investigation](../../dm/games/0100F2C0115B6000/README.md#services). This mismatch predates the Steam Controller adapter; correcting the style alone did not fix that game's aiming, which required the [stick deadzone](#steam-controller-stick-drift-suppresses-gyro-aiming). No new local gameplay validation.
+
+### Mapped Shake on secondary controllers
+
+- **Symptom:** a button mapped to Shake does nothing on a secondary controller, including the first physical controller with `DM_KBD_PLAYER=own`, even though its normal buttons work in a one-player game.
+- **Cause:** the synthetic shake tracked only the keyboard and controller slot 0, and six-axis reads enabled it only for player 1.
+- **Fix:** track whole shake cycles per controller slot and select a source using the same player assignments as buttons and physical motion. One-player games merge secondary sources into player 1; multiplayer keeps each player's shake separate. Short taps, release completion, physical-motion fallback and the at-rest query follow that source. Removing a slot discards its pending shake so reconnecting cannot inherit it.
+- **Found on:** controller-mapping review and synthetic regressions in `dm/host/tests/t_hid.c`, covering all secondary slots, keyboard reservation, docked/handheld merging, disconnect and physical-motion coexistence.
+
### SDK 20 six-axis sensor and amiibo (`nfp`) calls
- **Symptom:** SDK 20 calls that reach a service; `nfp`'s `AttachActivateEvent` / `AttachDeactivateEvent` crashed in the SDK at `sdk+0x3f2a78`.