Save after deleting a config. Reset target to no-op when deleting its config, rather...
[enjoyable.git] / JSActionAnalog.m
index e7d6eba..9c98f21 100644 (file)
@@ -5,49 +5,49 @@
 //  Created by Sam McCall on 5/05/09.
 //
 
-// TODO: Dead zone should be configurable per-device.
 #define DEAD_ZONE 0.3
 
 #import "JSActionAnalog.h"
 
-@implementation JSActionAnalog
+static float normalize(long p, long min, long max) {
+    return 2 * (p - min) / (float)(max - min) - 1;
+}
 
-@synthesize offset, scale;
+@implementation JSActionAnalog {
+    float magnitude;
+    long rawMin;
+    long rawMax;
+}
 
-- (id)initWithIndex:(int)newIndex offset:(float)offset_ scale:(float)scale_ {
+- (id)initWithIndex:(int)index rawMin:(long)rawMin_ rawMax:(long)rawMax_ {
     if ((self = [super init])) {
-        self.subActions = @[[[SubAction alloc] initWithIndex:0 name:@"Low" base:self],
-                            [[SubAction alloc] initWithIndex:1 name:@"High" base:self]];
-        self.index = newIndex;
-        self.offset = offset_;
-        self.scale = scale_;
-        self.name = [[NSString alloc] initWithFormat: @"Axis %d", self.index + 1];
+        self.name = [[NSString alloc] initWithFormat: @"Axis %d", index];
+        self.children = @[[[JSAction alloc] initWithName:@"Low" base:self],
+                          [[JSAction alloc] initWithName:@"High" base:self]];
+        rawMax = rawMax_;
+        rawMin = rawMin_;
     }
     return self;
 }
 
 - (id)findSubActionForValue:(IOHIDValueRef)value {
-    int raw = IOHIDValueGetIntegerValue(value);
-    float parsed = [self getRealValue:raw];
-    
-    if (parsed < -DEAD_ZONE)
-        return self.subActions[0];
-    else if (parsed > DEAD_ZONE)
-        return self.subActions[1];
+    float mag = normalize(IOHIDValueGetIntegerValue(value), rawMin, rawMax);
+    if (mag < -DEAD_ZONE)
+        return self.children[0];
+    else if (mag > DEAD_ZONE)
+        return self.children[1];
     else
         return nil;
 }
 
 - (void)notifyEvent:(IOHIDValueRef)value {
-    int raw = IOHIDValueGetIntegerValue(value);
-    float parsed = [self getRealValue:raw];
-    [self.subActions[0] setActive:parsed < -DEAD_ZONE];
-    [self.subActions[1] setActive:parsed > DEAD_ZONE];
+    magnitude = normalize(IOHIDValueGetIntegerValue(value), rawMin, rawMax);
+    [self.children[0] setActive:magnitude < -DEAD_ZONE];
+    [self.children[1] setActive:magnitude > DEAD_ZONE];
 }
 
-- (float)getRealValue:(int)value {
-    return offset + scale * value;
+- (float)magnitude {
+    return magnitude;
 }
 
-
 @end