Skip to content

Commit 3eb1d76

Browse files
committed
Add game rumble for iPhone and Apple game controllers
Preserve per-player motor state and SDK vibration handles, apply batches atomically, and route Core Haptics output through existing controller assignments. Add independent launcher controls and lifecycle tests. Supersedes #86. Physical feel and controller compatibility still require device testing.
1 parent ea3ed86 commit 3eb1d76

16 files changed

Lines changed: 548 additions & 19 deletions

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,8 @@ With an Apple developer account you can instead build and install from Xcode: `-
9292
**Touch controls.** Tap **2D** / **3D** at the top to switch layouts; the app remembers your choice. Wonder, Engage, Dread, 13 Sentinels, Link's Awakening, Ace Attorney Investigations Collection, Unicorn Overlord, Rhythm Heaven Groove, Octopath Traveler 0, Pokémon Legends: Z-A, Cuphead, Absolum, Brain Memory Training Academy, The Great Ace Attorney Chronicles, STEINS;GATE RE:BOOT, Big Brain Academy: Brain vs. Brain, Patrick's Parabox, Celeste and Raging Loop start in 2D, the other games in 3D (STEINS;GATE RE:BOOT's quick save is R3, in the 3D layout). In 3D, the right stick (the camera in most games) is not drawn: swipe on the right third of the screen, starting anywhere off the buttons. In Super Mario Galaxy and Super Mario Galaxy 2, other touches outside the controls move the pointer; in Captain Toad: Treasure Tracker they touch the game's screen (touch blocks, stun enemies), and in Big Brain Academy: Brain vs. Brain too (its menus and activities).
9393
A connected game controller hides the touch controls and keeps every button.
9494

95+
**Rumble.** Game vibration uses the iPhone's haptic engine or a compatible connected controller. Controllers with separate left/right haptic outputs keep those effects separate. The launcher's **Game rumble** and **Rumble strength** settings control it independently of **Touch feedback**. Phone rumble approximates the Switch's effects; physical feel and controller compatibility still need device testing.
96+
9597
**Shaking.** Shake the iPhone to shake the controller, in games that read its motion: Super Mario Odyssey's motion moves (such as the cap throw on a shake) need it, and Odyssey only takes them in its default docked mode. A light bump does not count; a sharp flick of the phone does.
9698

9799
- **Game language** is English by default. Pick another when packing with `--language` (`-l`), by code or by name: `-l ja`, `-l zh-Hans`, `-l French` (`LANGUAGE` in Spyder). It must be one the game has; the script prints the game's languages and stops on one it lacks. To change it without rebuilding, pick another on the settings screen.

‎dm/games/settings.tsv‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,5 @@ DM_LANG choice languages build:DM_LANG languages>1 Game language
1313
DM_SHOW_FPS toggle - build:DM_SHOW_FPS always Frame-rate counter
1414
DM_METAL_HUD toggle - 0 always Performance HUD
1515
DM_TOUCH_HAPTICS toggle - 1 always Touch feedback Haptic clicks when pressing touch controls.
16+
DM_RUMBLE toggle - 1 always Game rumble Vibration from the game on your phone or connected controller.
17+
DM_RUMBLE_GAIN range 0:3:0.1 1.0 always Rumble strength Adjusts game rumble alongside the game's own vibration setting.

‎dm/host/Makefile‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ endif
1616
GAME_H = gen/$(GAME)/game_profile.h
1717
CFLAGS=-O1 -g -Wall -Wno-unused-function
1818
# Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts)
19-
SRC=main.c loader.c hle.c crash.c probe.c thread.c memstat.m $(sort $(wildcard hle_*.c)) front_mac.m entry.S
19+
SRC=main.c loader.c hle.c crash.c probe.c thread.c memstat.m haptics_apple.m $(sort $(wildcard hle_*.c)) front_mac.m entry.S
2020
# NVN null device + nn::vi + the Vulkan layer (dm/gfx/)
2121
# 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
2222
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))
@@ -50,8 +50,8 @@ endif
5050
endif
5151
.PHONY: FORCE
5252
FORCE:
53-
dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h dm_input.h pad_slots.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB)
54-
clang $(CFLAGS) -I../gfx/nvn/include -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework QuartzCore -framework Metal -framework GameController -framework AudioToolbox -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers
53+
dmhost: $(SRC) $(GFX) ../third_party/stb_vorbis/stb_vorbis.c dm.h hle.h dm_input.h pad_slots.h hle_haptics.h haptics_apple.h front.h $(GFX_H) $(GAME_H) $(GAME_STAMP) $(VPX_LIB)
54+
clang $(CFLAGS) -I../gfx/nvn/include -I../third_party/vulkan-headers/include -I$(dir $(GAME_H)) -I$(VPX) -I../third_party/stb_vorbis -fobjc-arc -o $@ $(SRC) $(GFX) $(VPX_LIB) -framework Cocoa -framework QuartzCore -framework Metal -framework GameController -framework CoreHaptics -framework AudioToolbox -framework VideoToolbox -framework CoreMedia -framework CoreVideo -framework ImageIO -framework UniformTypeIdentifiers
5555
clean: # the host and everything make generates for it (gen/: the profile headers, the game stamp and the libvpx build; dmhost_* and *.dSYM beside them, as in .gitignore)
5656
rm -rf gen dmhost dmhost_* *.dSYM
5757
.PHONY: clean

‎dm/host/front_mac.m‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include "front.h"
1515
#include "hle.h"
1616
#include "pad_slots.h"
17+
#include "haptics_apple.h"
1718
#include <signal.h>
1819
#include <math.h>
1920

@@ -114,6 +115,7 @@ static void on_key(NSEvent *e, int down) {
114115
static int32_t pad_axis(float v) { return (int32_t)(fmaxf(-1.f, fminf(1.f, v)) * DM_STICK_MAX); }
115116
static void pad_read(GCExtendedGamepad *g) {
116117
int p = g_merge ? 0 : pad_slot_of(&g_slots, (__bridge const void *)g.controller); if (p < 0) return;
118+
dm_haptics_apple_controller(p, g.controller);
117119
uint64_t m = 0;
118120
#define K(btn, bit) if (btn.isPressed) m |= bit
119121
K(g.buttonB, DM_BTN_A); K(g.buttonA, DM_BTN_B); K(g.buttonY, DM_BTN_X); K(g.buttonX, DM_BTN_Y); // by position: right A, bottom B, top X, left Y
@@ -133,13 +135,14 @@ static void pads_changed(GCController *gone) {
133135
any = 1; c.extendedGamepad.valueChangedHandler = ^(GCExtendedGamepad *g, GCControllerElement *el) { (void)el; pad_read(g); };
134136
pad_read(c.extendedGamepad);
135137
}
136-
if (!any) dm_pad_set(0, 0, 0, 0, 0);
138+
if (!any) { dm_pad_set(0, 0, 0, 0, 0); dm_haptics_apple_controller(0, nil); }
137139
return;
138140
}
139141
NSArray<GCController *> *now = GCController.controllers; char nb[16];
140142
for (int p = 0; p < DM_PLAYERS; p++) if (g_held[p] && (g_held[p] == gone || ![now containsObject:g_held[p]])) {
141143
npad_name(p, nb, sizeof nb); LOG("controller '%s' disconnected: player %d (npad %s) is free", pad_name(g_held[p]), p + 1, nb);
142144
g_held[p].extendedGamepad.valueChangedHandler = nil;
145+
dm_haptics_apple_controller(p, nil);
143146
pad_slot_free(&g_slots, (__bridge const void *)g_held[p]); g_held[p] = nil;
144147
dm_pad_set_player(p, 0, 0, 0, 0, 0); // nothing stays pressed
145148
}
@@ -240,6 +243,7 @@ void front_run(void (*guest)(void)) {
240243
GCController *c = n.object; int conn = n.name == GCControllerDidConnectNotification;
241244
if (!c.extendedGamepad || g_merge) LOG("controller %s: %s%s", conn ? "connected" : "disconnected", pad_name(c), c.extendedGamepad ? "" : " (no extended gamepad profile: not used)");
242245
pads_changed(conn ? nil : c); }];
246+
dm_haptics_apple_init();
243247
pads_start();
244248
[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown | NSEventMaskKeyUp handler:^NSEvent *(NSEvent *e) {
245249
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

‎dm/host/haptics_apple.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Shared Core Haptics output for the Mac and iOS front ends. Configure routes before guest boot.
2+
#pragma once
3+
#import <GameController/GameController.h>
4+
#include "hle_haptics.h"
5+
void dm_haptics_apple_init(void);
6+
void dm_haptics_apple_controller(int player, GCController *controller);
7+
void dm_haptics_apple_shutdown(void);

‎dm/host/haptics_apple.m‎

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
// Core Haptics adapts the game's bands; it cannot reproduce the Switch's exact waveforms.
2+
// All engines and players belong to one serial queue. Guest threads enqueue ordered snapshots only.
3+
#import "haptics_apple.h"
4+
#import <CoreHaptics/CoreHaptics.h>
5+
#import <TargetConditionals.h>
6+
#if TARGET_OS_IPHONE
7+
#import <UIKit/UIKit.h>
8+
#import <AVFAudio/AVFAudio.h>
9+
#else
10+
#import <AppKit/AppKit.h>
11+
#endif
12+
#include <math.h>
13+
#include <pthread.h>
14+
15+
@interface DmRumbleChannel : NSObject
16+
@property(nonatomic) CHHapticEngine *engine;
17+
@property(nonatomic) id<CHHapticAdvancedPatternPlayer> pattern;
18+
@property(nonatomic) int player;
19+
@property(nonatomic) uint64_t generation;
20+
@property(nonatomic) uint64_t silenceGeneration;
21+
- (void)apply:(dm_haptic_level)level;
22+
- (void)stop;
23+
@end
24+
25+
static dispatch_queue_t queue;
26+
static NSMutableArray<DmRumbleChannel *> *channels[DM_PLAYERS];
27+
static GCController *controllers[DM_PLAYERS];
28+
#if TARGET_OS_IPHONE
29+
static BOOL phoneSupported;
30+
#endif
31+
static float gain = 1;
32+
static pthread_mutex_t routeLock = PTHREAD_MUTEX_INITIALIZER;
33+
static unsigned errors;
34+
static void report(NSError *e) {
35+
if (++errors <= 8 || errors % 64 == 0) fprintf(stderr, "[RED] haptics: %s\n", e.localizedDescription.UTF8String ?: "engine unavailable");
36+
}
37+
38+
@implementation DmRumbleChannel
39+
- (void)stop {
40+
self.generation++; self.silenceGeneration++;
41+
self.engine.stoppedHandler = ^(CHHapticEngineStoppedReason reason) { (void)reason; }; self.engine.resetHandler = ^{};
42+
[self.pattern stopAtTime:CHHapticTimeImmediate error:nil]; self.pattern = nil;
43+
[self.engine stopWithCompletionHandler:nil];
44+
}
45+
- (void)apply:(dm_haptic_level)level {
46+
uint64_t silence = ++self.silenceGeneration;
47+
NSError *error = nil;
48+
if (!self.pattern) {
49+
if (level.intensity == 0) return;
50+
if (![self.engine startAndReturnError:&error]) { report(error); dm_haptics_clear(self.player); return; }
51+
__weak DmRumbleChannel *weak = self;
52+
uint64_t generation = ++self.generation;
53+
void (^reset)(void) = ^{
54+
dispatch_async(queue, ^{
55+
DmRumbleChannel *c = weak; if (!c || c.generation != generation) return;
56+
c.pattern = nil;
57+
dm_haptics_clear(c.player); // queued effects from before an interruption cannot restart
58+
});
59+
};
60+
self.engine.stoppedHandler = ^(CHHapticEngineStoppedReason reason) { (void)reason; reset(); };
61+
self.engine.resetHandler = reset;
62+
CHHapticEvent *event = [[CHHapticEvent alloc] initWithEventType:CHHapticEventTypeHapticContinuous parameters:@[
63+
[[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticIntensity value:1],
64+
[[CHHapticEventParameter alloc] initWithParameterID:CHHapticEventParameterIDHapticSharpness value:0.5]
65+
] relativeTime:0 duration:30];
66+
CHHapticPattern *pattern = [[CHHapticPattern alloc] initWithEvents:@[event] parameters:@[] error:&error];
67+
self.pattern = pattern ? [self.engine createAdvancedPlayerWithPattern:pattern error:&error] : nil;
68+
if (!self.pattern) { report(error); dm_haptics_clear(self.player); return; }
69+
self.pattern.loopEnabled = YES;
70+
self.pattern.isMuted = YES;
71+
if (![self.pattern startAtTime:CHHapticTimeImmediate error:&error]) { report(error); self.pattern = nil; dm_haptics_clear(self.player); return; }
72+
}
73+
// Controls live outside the loop: the loop boundary never replays an initial intensity.
74+
NSArray *parameters = @[
75+
[[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticIntensityControl value:level.intensity relativeTime:0],
76+
[[CHHapticDynamicParameter alloc] initWithParameterID:CHHapticDynamicParameterIDHapticSharpnessControl value:level.sharpness - 0.5f relativeTime:0]
77+
];
78+
if (![self.pattern sendParameters:parameters atTime:CHHapticTimeImmediate error:&error]) {
79+
report(error); [self stop]; dm_haptics_clear(self.player); return;
80+
}
81+
self.pattern.isMuted = NO;
82+
if (level.intensity == 0) {
83+
// Reuse a warm player for nearby pulses, then release idle hardware. This never times out an active effect.
84+
__weak DmRumbleChannel *weak = self;
85+
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), queue, ^{
86+
DmRumbleChannel *c = weak; if (c && c.silenceGeneration == silence) [c stop];
87+
});
88+
}
89+
}
90+
@end
91+
92+
static void apply(dm_haptic_state s) {
93+
dispatch_async(queue, ^{ @autoreleasepool {
94+
if (s.epoch != dm_haptics_epoch(s.player)) return;
95+
NSArray<DmRumbleChannel *> *out = channels[s.player];
96+
for (NSUInteger i = 0; i < out.count; i++) {
97+
dm_haptic_level level = out.count == 2 ? dm_haptics_level(&s.motor[i], 1, gain) : dm_haptics_level(s.motor, 2, gain);
98+
[out[i] apply:level];
99+
}
100+
} });
101+
}
102+
static void add_engine(int p, CHHapticEngine *engine) {
103+
if (!engine) return;
104+
engine.playsHapticsOnly = YES; engine.autoShutdownEnabled = NO;
105+
DmRumbleChannel *c = [DmRumbleChannel new]; c.engine = engine; c.player = p;
106+
[channels[p] addObject:c];
107+
}
108+
static void configure(int p, GCController *controller) {
109+
for (DmRumbleChannel *c in channels[p]) [c stop];
110+
channels[p] = [NSMutableArray new];
111+
if (controller) {
112+
GCDeviceHaptics *h = controller.haptics;
113+
NSSet *localities = h.supportedLocalities;
114+
if ([localities containsObject:GCHapticsLocalityLeftHandle] && [localities containsObject:GCHapticsLocalityRightHandle]) {
115+
CHHapticEngine *left = [h createEngineWithLocality:GCHapticsLocalityLeftHandle];
116+
CHHapticEngine *right = [h createEngineWithLocality:GCHapticsLocalityRightHandle];
117+
if (left && right) { add_engine(p, left); add_engine(p, right); }
118+
}
119+
if (!channels[p].count) add_engine(p, [h createEngineWithLocality:GCHapticsLocalityDefault]);
120+
}
121+
#if TARGET_OS_IPHONE
122+
else if (!p && phoneSupported) {
123+
NSError *error = nil;
124+
CHHapticEngine *engine = [[CHHapticEngine alloc] initWithAudioSession:AVAudioSession.sharedInstance error:&error];
125+
if (!engine) report(error);
126+
add_engine(p, engine);
127+
}
128+
#endif
129+
dm_haptics_route(p, channels[p].count != 0);
130+
}
131+
void dm_haptics_apple_controller(int p, GCController *controller) {
132+
if (!queue || p < 0 || p >= DM_PLAYERS) return;
133+
pthread_mutex_lock(&routeLock);
134+
if (controllers[p] != controller) {
135+
controllers[p] = controller;
136+
dm_haptics_route(p, 0); // invalidate queued work before changing hardware
137+
dispatch_sync(queue, ^{ configure(p, controller); });
138+
}
139+
pthread_mutex_unlock(&routeLock);
140+
}
141+
static void suspend(unsigned reason, BOOL on) {
142+
dm_haptics_suspend(reason, on);
143+
void (^stop)(void) = ^{
144+
for (int p = 0; p < DM_PLAYERS; p++) for (DmRumbleChannel *c in channels[p]) [c stop];
145+
};
146+
if (on) { if (dispatch_get_specific(&queue)) stop(); else dispatch_sync(queue, stop); }
147+
}
148+
void dm_haptics_apple_shutdown(void) {
149+
if (queue) suspend(DM_HAPTICS_INACTIVE, YES);
150+
}
151+
void dm_haptics_apple_init(void) {
152+
static dispatch_once_t once;
153+
dispatch_once(&once, ^{
154+
queue = dispatch_queue_create("dm.rumble", DISPATCH_QUEUE_SERIAL);
155+
dispatch_queue_set_specific(queue, &queue, &queue, NULL);
156+
const char *e = getenv("DM_RUMBLE_GAIN");
157+
if (e) { float v = strtof(e, NULL); if (isfinite(v)) gain = fmaxf(0, fminf(3, v)); }
158+
e = getenv("DM_RUMBLE");
159+
dm_haptics_init(apply, !e || atoi(e) != 0);
160+
#if TARGET_OS_IPHONE
161+
phoneSupported = CHHapticEngine.capabilitiesForHardware.supportsHaptics;
162+
#endif
163+
dispatch_sync(queue, ^{ configure(0, nil); });
164+
NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;
165+
#if TARGET_OS_IPHONE
166+
[nc addObserverForName:UIApplicationWillResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; suspend(DM_HAPTICS_INACTIVE, YES); }];
167+
[nc addObserverForName:UIApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; suspend(DM_HAPTICS_INACTIVE, NO); }];
168+
[nc addObserverForName:UIApplicationWillTerminateNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; dm_haptics_apple_shutdown(); }];
169+
[nc addObserverForName:AVAudioSessionInterruptionNotification object:nil queue:nil usingBlock:^(NSNotification *n) {
170+
suspend(DM_HAPTICS_INTERRUPTED, [n.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue] == AVAudioSessionInterruptionTypeBegan);
171+
}];
172+
[nc addObserverForName:AVAudioSessionRouteChangeNotification object:nil queue:nil usingBlock:^(NSNotification *n) {
173+
(void)n; dm_haptics_clear(0);
174+
}];
175+
#else
176+
[nc addObserverForName:NSApplicationWillResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; suspend(DM_HAPTICS_INACTIVE, YES); }];
177+
[nc addObserverForName:NSApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; suspend(DM_HAPTICS_INACTIVE, NO); }];
178+
[nc addObserverForName:NSApplicationWillTerminateNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; dm_haptics_apple_shutdown(); }];
179+
#endif
180+
atexit(dm_haptics_apple_shutdown);
181+
});
182+
}

0 commit comments

Comments
 (0)