|
| 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