src/haptic/darwin/SDL_syshaptic.c
author Edgar Simo <bobbens@gmail.com>
Tue, 22 Jul 2008 11:42:01 +0000
branchgsoc2008_force_feedback
changeset 2547 3cfe0ae232c0
parent 2546 daf40497dcd4
child 2550 b5b8a7f4a965
permissions -rw-r--r--
Accidently left in hidDevice.
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 2008 Edgar Simo
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Lesser General Public
     7     License as published by the Free Software Foundation; either
     8     version 2.1 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Lesser General Public License for more details.
    14 
    15     You should have received a copy of the GNU Lesser General Public
    16     License along with this library; if not, write to the Free Software
    17     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    18 
    19     Sam Lantinga
    20     slouken@libsdl.org
    21 */
    22 #include "SDL_config.h"
    23 
    24 #ifdef SDL_HAPTIC_IOKIT
    25 
    26 #include "SDL_haptic.h"
    27 #include "../SDL_syshaptic.h"
    28 #include "SDL_joystick.h"
    29 #include "../../joystick/SDL_sysjoystick.h" /* For the real SDL_Joystick */
    30 /*#include "../../joystick/dawrin/SDL_sysjoystick_c.h"*/ /* For joystick hwdata */ 
    31 
    32 #include <IOKit/IOKitLib.h>
    33 #include <IOKit/hid/IOHIDKeys.h>
    34 #include <ForceFeedback/ForceFeedback.h>
    35 #include <ForceFeedback/ForceFeedbackConstants.h>
    36 
    37 
    38 #define MAX_HAPTICS  32
    39 
    40 
    41 /*
    42  * List of available haptic devices.
    43  */
    44 static struct
    45 {
    46    char name[256];
    47    io_service_t dev;
    48    SDL_Haptic *haptic;
    49 } SDL_hapticlist[MAX_HAPTICS];
    50 
    51 
    52 /*
    53  * Haptic system hardware data.
    54  */
    55 struct haptic_hwdata
    56 {
    57    FFDeviceObjectReference device; /* Hardware device. */
    58 };
    59 
    60 
    61 /*
    62  * Haptic system effect data.
    63  */
    64 struct haptic_hweffect
    65 {
    66    FFEffectObjectReference ref; /* Reference. */
    67    struct FFEFFECT effect; /* Hardware effect. */
    68 };
    69 
    70 /*
    71  * Prototypes.
    72  */
    73 static void SDL_SYS_HapticFreeFFEFFECT(FFEFFECT * effect, int type);
    74 static int HIDGetDeviceProduct(io_service_t dev, char * name);
    75 
    76 
    77 /* 
    78  * Like strerror but for force feedback errors.
    79  */
    80 static const char *
    81 FFStrError(HRESULT err)
    82 {
    83    switch (err) {
    84       case FFERR_DEVICEFULL:
    85          return "device full";
    86       /*case FFERR_DEVICENOTREG:
    87          return "device not registered";*/
    88       case FFERR_DEVICEPAUSED:
    89          return "device paused";
    90       case FFERR_DEVICERELEASED:
    91          return "device released";
    92       case FFERR_EFFECTPLAYING:
    93          return "effect playing";
    94       case FFERR_EFFECTTYPEMISMATCH:
    95          return "effect type mismatch";
    96       case FFERR_EFFECTTYPENOTSUPPORTED:
    97          return "effect type not supported";
    98       case FFERR_GENERIC:
    99          return "undetermined error";
   100       case FFERR_HASEFFECTS:
   101          return "device has effects";
   102       case FFERR_INCOMPLETEEFFECT:
   103          return "incomplete effect";
   104       case FFERR_INTERNAL:
   105          return "internal fault";
   106       case FFERR_INVALIDDOWNLOADID:
   107          return "invalid download id";
   108       case FFERR_INVALIDPARAM:
   109          return "invalid parameter";
   110       case FFERR_MOREDATA:
   111          return "more data";
   112       case FFERR_NOINTERFACE:
   113          return "interface not supported";
   114       case FFERR_NOTDOWNLOADED:
   115          return "effect is not downloaded";
   116       case FFERR_NOTINITIALIZED:
   117          return "object has not been initialized";
   118       case FFERR_OUTOFMEMORY:
   119          return "out of memory";
   120       case FFERR_UNPLUGGED:
   121          return "device is unplugged";
   122       case FFERR_UNSUPPORTED:
   123          return "function call unsupported";
   124       case FFERR_UNSUPPORTEDAXIS:
   125          return "axis unsupported";
   126 
   127       default:
   128          return "unknown error";
   129    }
   130 }
   131 
   132 
   133 /*
   134  * Initializes the haptic subsystem.
   135  */
   136 int
   137 SDL_SYS_HapticInit(void)
   138 {
   139    int numhaptics;
   140    IOReturn result;
   141    io_iterator_t iter;
   142    CFDictionaryRef match;
   143    io_service_t device;
   144 
   145    /* Clear all the memory. */
   146    SDL_memset(SDL_hapticlist, 0, sizeof(SDL_hapticlist));
   147 
   148    /* Get HID devices. */
   149    match = IOServiceMatching(kIOHIDDeviceKey);
   150    if (match == NULL) {
   151       SDL_SetError("Haptic: Failed to get IOServiceMatching.");
   152       return -1;
   153    }
   154 
   155    /* Now search I/O Registry for matching devices. */
   156    result = IOServiceGetMatchingServices(kIOMasterPortDefault, match, &iter);
   157    if (result != kIOReturnSuccess) {
   158       SDL_SetError("Haptic: Couldn't create a HID object iterator.");
   159       return -1;
   160    }
   161    /* IOServiceGetMatchingServices consumes dictionary. */
   162 
   163    numhaptics = 0;
   164    while ((device = IOIteratorNext(iter)) != IO_OBJECT_NULL) {
   165 
   166       /* Check for force feedback. */
   167       if (FFIsForceFeedback(device) == FF_OK) {
   168          HIDGetDeviceProduct(device, SDL_hapticlist[numhaptics].name);
   169          SDL_hapticlist[numhaptics].dev = device;
   170          SDL_hapticlist[numhaptics].haptic = NULL;
   171          numhaptics++;
   172       }
   173       else { /* Free the unused device. */
   174          IOObjectRelease(device);
   175       }
   176 
   177       /* Reached haptic limit. */
   178       if (numhaptics >= MAX_HAPTICS)
   179          break;
   180    }
   181    IOObjectRelease(iter);
   182 
   183    return numhaptics;
   184 }
   185 
   186 
   187 /*
   188  * Return the name of a haptic device, does not need to be opened.
   189  */
   190 const char *
   191 SDL_SYS_HapticName(int index)
   192 {
   193    return SDL_hapticlist[index].name;
   194 }
   195 
   196 /*
   197  * Gets the device's product name.
   198  */
   199 static int
   200 HIDGetDeviceProduct(io_service_t dev, char *name)
   201 {
   202    CFMutableDictionaryRef hidProperties, usbProperties;
   203    io_registry_entry_t parent1, parent2;
   204    kern_return_t ret;
   205 
   206    hidProperties = usbProperties = 0;
   207 
   208    ret = IORegistryEntryCreateCFProperties(dev, &hidProperties,
   209                                            kCFAllocatorDefault,
   210                                            kNilOptions);
   211    if ((ret != KERN_SUCCESS) || !hidProperties) {
   212       SDL_SetError("Haptic: Unable to create CFProperties.");
   213       return -1;
   214    }
   215 
   216    /* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
   217     * get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
   218     */
   219    if ((KERN_SUCCESS ==
   220             IORegistryEntryGetParentEntry(dev, kIOServicePlane, &parent1))
   221          && (KERN_SUCCESS ==
   222             IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
   223          && (KERN_SUCCESS ==
   224             IORegistryEntryCreateCFProperties(parent2, &usbProperties,
   225                                               kCFAllocatorDefault,
   226                                               kNilOptions))) {
   227       if (usbProperties) {
   228          CFTypeRef refCF = 0;
   229          /* get device info
   230           * try hid dictionary first, if fail then go to usb dictionary
   231           */
   232 
   233 
   234          /* Get product name */
   235          refCF = CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
   236          if (!refCF)
   237             refCF =
   238                CFDictionaryGetValue(usbProperties, CFSTR("USB Product Name"));
   239          if (refCF) {
   240             if (!CFStringGetCString(refCF, name, 256,
   241                                     CFStringGetSystemEncoding())) {
   242                SDL_SetError("CFStringGetCString error retrieving pDevice->product.");
   243                return -1;
   244             }
   245          }
   246 
   247          CFRelease(usbProperties);
   248       }
   249       else {
   250          SDL_SetError("IORegistryEntryCreateCFProperties failed to create usbProperties.");
   251          return -1;
   252       }
   253 
   254       /* Release stuff. */
   255       if (kIOReturnSuccess != IOObjectRelease(parent2)) {
   256          SDL_SetError("IOObjectRelease error with parent2.");
   257       }
   258       if (kIOReturnSuccess != IOObjectRelease(parent1))  {
   259          SDL_SetError("IOObjectRelease error with parent1.");
   260       }
   261    }
   262    else {
   263       SDL_SetError("Haptic: Error getting registry entries.");
   264       return -1;
   265    }
   266 
   267    return 0;
   268 }
   269 
   270 
   271 #define FF_TEST(ff, s) \
   272 if (features.supportedEffects & ff) supported |= s
   273 /*
   274  * Gets supported features.
   275  */
   276 static unsigned int
   277 GetSupportedFeatures(FFDeviceObjectReference device,
   278                      int *neffects, int *nplaying, int *naxes)
   279 {
   280    HRESULT ret;
   281    FFCAPABILITIES features;
   282    unsigned int supported;
   283    Uint32 val;
   284 
   285    ret = FFDeviceGetForceFeedbackCapabilities(device, &features);
   286    if (ret != FF_OK) {
   287       SDL_SetError("Haptic: Unable to get device's supported features.");
   288       return 0;
   289    }
   290 
   291    supported = 0;
   292 
   293    /* Get maximum effects. */
   294    *neffects = features.storageCapacity;
   295    *nplaying = features.playbackCapacity;
   296 
   297    /* Test for effects. */
   298    FF_TEST(FFCAP_ET_CONSTANTFORCE, SDL_HAPTIC_CONSTANT);
   299    FF_TEST(FFCAP_ET_RAMPFORCE,     SDL_HAPTIC_RAMP);
   300    FF_TEST(FFCAP_ET_SQUARE,        SDL_HAPTIC_SQUARE);
   301    FF_TEST(FFCAP_ET_SINE,          SDL_HAPTIC_SINE);
   302    FF_TEST(FFCAP_ET_TRIANGLE,      SDL_HAPTIC_TRIANGLE);
   303    FF_TEST(FFCAP_ET_SAWTOOTHUP,    SDL_HAPTIC_SAWTOOTHUP);
   304    FF_TEST(FFCAP_ET_SAWTOOTHDOWN,  SDL_HAPTIC_SAWTOOTHDOWN);
   305    FF_TEST(FFCAP_ET_SPRING,        SDL_HAPTIC_SPRING);
   306    FF_TEST(FFCAP_ET_DAMPER,        SDL_HAPTIC_DAMPER);
   307    FF_TEST(FFCAP_ET_INERTIA,       SDL_HAPTIC_INERTIA);
   308    FF_TEST(FFCAP_ET_FRICTION,      SDL_HAPTIC_FRICTION);
   309    FF_TEST(FFCAP_ET_CUSTOMFORCE,   SDL_HAPTIC_CUSTOM);
   310 
   311    /* Check if supports gain. */
   312    ret = FFDeviceGetForceFeedbackProperty(device, FFPROP_FFGAIN,
   313                                           &val, sizeof(val));
   314    if (ret == FF_OK) supported |= SDL_HAPTIC_GAIN;
   315    else if (ret != FFERR_UNSUPPORTED) {
   316       SDL_SetError("Haptic: Unable to get if device supports gain: %s.",
   317                    FFStrError(ret));
   318       return 0;
   319    }
   320 
   321    /* Checks if supports autocenter. */
   322    ret = FFDeviceGetForceFeedbackProperty(device, FFPROP_AUTOCENTER,
   323                                           &val, sizeof(val));
   324    if (ret == FF_OK) supported |= SDL_HAPTIC_AUTOCENTER;
   325    else if (ret != FFERR_UNSUPPORTED) {
   326       SDL_SetError("Haptic: Unable to get if device supports autocenter: %s.",
   327                    FFStrError(ret));
   328       return 0;
   329    }
   330 
   331    /* Check for axes, we have an artificial limit on axes */
   332    *naxes = ((features.numFfAxes) > 3) ?
   333          3 : features.numFfAxes;
   334 
   335    /* Always supported features. */
   336    supported |= SDL_HAPTIC_STATUS;
   337    return supported;
   338 }
   339 
   340 
   341 /*
   342  * Opens the haptic device from the file descriptor.
   343  */
   344 static int
   345 SDL_SYS_HapticOpenFromService(SDL_Haptic * haptic, io_service_t service)
   346 {
   347    HRESULT ret;
   348 
   349    /* Allocate the hwdata */
   350    haptic->hwdata = (struct haptic_hwdata *)
   351          SDL_malloc(sizeof(*haptic->hwdata));
   352    if (haptic->hwdata == NULL) {
   353       SDL_OutOfMemory();
   354       goto creat_err;
   355    }
   356    SDL_memset(haptic->hwdata, 0, sizeof(*haptic->hwdata));
   357   
   358    /* Open the device */
   359    ret = FFCreateDevice( service, &haptic->hwdata->device);
   360    if (ret != FF_OK) {
   361       SDL_SetError("Haptic: Unable to create device from service: %s.",
   362                    FFStrError(ret));
   363       goto creat_err;
   364    }
   365 
   366    /* Get supported features. */
   367    haptic->supported = GetSupportedFeatures(haptic->hwdata->device,
   368                                             &haptic->neffects, &haptic->nplaying,
   369                                             &haptic->naxes);
   370    if (haptic->supported == 0) { /* Error since device supports nothing. */
   371       goto open_err;
   372    }
   373    haptic->effects = (struct haptic_effect *)
   374          SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects);
   375    if (haptic->effects == NULL) {
   376       SDL_OutOfMemory();
   377       goto open_err;
   378    }
   379    /* Clear the memory */
   380    SDL_memset(haptic->effects, 0,
   381          sizeof(struct haptic_effect) * haptic->neffects);
   382    
   383    return 0;
   384    
   385    /* Error handling */
   386 open_err:
   387    FFReleaseDevice(haptic->hwdata->device);
   388 creat_err:
   389    if (haptic->hwdata != NULL) {
   390       free(haptic->hwdata);
   391       haptic->hwdata = NULL;                                              
   392    }
   393    return -1;
   394 
   395 }
   396 
   397 
   398 /*
   399  * Opens a haptic device for usage.
   400  */
   401 int
   402 SDL_SYS_HapticOpen(SDL_Haptic * haptic)
   403 {
   404    return SDL_SYS_HapticOpenFromService(haptic,
   405                 SDL_hapticlist[haptic->index].dev);
   406 }
   407 
   408 
   409 /*
   410  * Opens a haptic device from first mouse it finds for usage.
   411  */
   412 int
   413 SDL_SYS_HapticMouse(void)
   414 {
   415    return -1;
   416 }
   417 
   418 
   419 /*
   420  * Checks to see if a joystick has haptic features.
   421  */
   422 int
   423 SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
   424 {
   425    return SDL_FALSE;
   426 }
   427 
   428 
   429 /*
   430  * Checks to see if the haptic device and joystick and in reality the same.
   431  */
   432 int
   433 SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
   434 {
   435    return 0;
   436 }
   437 
   438 
   439 /*
   440  * Opens a SDL_Haptic from a SDL_Joystick.
   441  */
   442 int
   443 SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
   444 {
   445    return -1;
   446 }
   447 
   448 
   449 /*
   450  * Closes the haptic device.
   451  */
   452 void
   453 SDL_SYS_HapticClose(SDL_Haptic * haptic)
   454 {
   455    int i;
   456 
   457    if (haptic->hwdata) {
   458 
   459       /* Free the effects. */
   460       for (i=0; i<haptic->neffects; i++) {        
   461          if (haptic->effects[i].hweffect != NULL) {
   462             SDL_SYS_HapticFreeFFEFFECT(&haptic->effects[i].hweffect->effect,
   463                                        haptic->effects[i].effect.type);
   464             SDL_free(haptic->effects[i].hweffect);
   465          } 
   466       }    
   467       SDL_free(haptic->effects);
   468       haptic->neffects = 0;
   469 
   470       /* Clean up */
   471       FFReleaseDevice(haptic->hwdata->device);
   472 
   473       /* Free */
   474       SDL_free(haptic->hwdata);
   475       haptic->hwdata = NULL;
   476    }
   477 }
   478 
   479 
   480 /* 
   481  * Clean up after system specific haptic stuff
   482  */
   483 void
   484 SDL_SYS_HapticQuit(void)
   485 {
   486    int i;
   487 
   488    for (i=0; i < SDL_numhaptics; i++) {
   489       /* Opened and not closed haptics are leaked, this is on purpose.
   490        * Close your haptic devices after usage. */
   491 
   492       /* Free the io_service_t */
   493       IOObjectRelease(SDL_hapticlist[i].dev);
   494    }
   495 }
   496 
   497 
   498 /*
   499  * Sets the direction.
   500  */
   501 static int
   502 SDL_SYS_SetDirection( FFEFFECT * effect, SDL_HapticDirection *dir, int naxes )
   503 {
   504    LONG *rglDir;
   505 
   506    /* Handle no axes a part. */
   507    if (naxes == 0) {
   508       effect->rglDirection = NULL;
   509       return 0;
   510    }
   511 
   512    /* Has axes. */
   513    rglDir = SDL_malloc( sizeof(LONG) * naxes );
   514    if (rglDir == NULL) {
   515       SDL_OutOfMemory();
   516       return -1;
   517    }
   518    SDL_memset( rglDir, 0, sizeof(LONG) * naxes );
   519    effect->rglDirection = rglDir;
   520 
   521    switch (dir->type) {
   522       case SDL_HAPTIC_POLAR:
   523          effect->dwFlags |= FFEFF_POLAR;
   524          rglDir[0] = dir->dir[0];
   525          return 0;
   526       case SDL_HAPTIC_CARTESIAN:
   527          effect->dwFlags |= FFEFF_CARTESIAN;
   528          rglDir[0] = dir->dir[0];
   529          rglDir[1] = dir->dir[1];
   530          rglDir[2] = dir->dir[2];
   531          return 0;
   532       case SDL_HAPTIC_SPHERICAL:
   533          effect->dwFlags |= FFEFF_SPHERICAL;
   534          rglDir[0] = dir->dir[0];
   535          rglDir[1] = dir->dir[1];
   536          rglDir[2] = dir->dir[2];
   537          return 0;
   538 
   539       default:
   540          SDL_SetError("Haptic: Unknown direction type.");
   541          return -1;
   542    }
   543 }
   544 
   545 #define CONVERT(x)   (((x)*10000) / 0xFFFF )
   546 /*
   547  * Creates the FFEFFECT from a SDL_HapticEffect.
   548  */
   549 static int
   550 SDL_SYS_ToFFEFFECT( SDL_Haptic * haptic, FFEFFECT * dest, SDL_HapticEffect * src )
   551 {
   552    int i;
   553    FFCONSTANTFORCE *constant;
   554    FFPERIODIC *periodic;
   555    FFCONDITION *condition; /* Actually an array of conditions - one per axis. */
   556    FFRAMPFORCE *ramp;
   557    FFCUSTOMFORCE *custom;
   558    FFENVELOPE *envelope;
   559    SDL_HapticConstant *hap_constant;
   560    SDL_HapticPeriodic *hap_periodic;
   561    SDL_HapticCondition *hap_condition;
   562    SDL_HapticRamp *hap_ramp;
   563    SDL_HapticCustom *hap_custom;
   564    DWORD *axes;
   565 
   566    /* Set global stuff. */
   567    SDL_memset(dest, 0, sizeof(FFEFFECT));
   568    dest->dwSize = sizeof(FFEFFECT); /* Set the structure size. */
   569    dest->dwSamplePeriod = 0; /* Not used by us. */
   570    dest->dwGain = 10000; /* Gain is set globally, not locally. */
   571 
   572    /* Envelope. */
   573    envelope = SDL_malloc( sizeof(FFENVELOPE) );
   574    if (envelope == NULL) {
   575       SDL_OutOfMemory();
   576       return -1;
   577    }
   578    SDL_memset(envelope, 0, sizeof(FFENVELOPE));
   579    dest->lpEnvelope = envelope;
   580    envelope->dwSize = sizeof(FFENVELOPE); /* Always should be this. */
   581 
   582    /* Axes. */
   583    dest->cAxes = haptic->naxes;
   584    if (dest->cAxes > 0) {
   585       axes = SDL_malloc(sizeof(DWORD) * dest->cAxes);
   586       if (axes == NULL) {
   587          SDL_OutOfMemory();
   588          return -1;
   589       }
   590       axes[0] = FFJOFS_X; /* Always at least one axis. */
   591       if (dest->cAxes > 1) {
   592          axes[1] = FFJOFS_Y;
   593       }
   594       if (dest->cAxes > 2) {
   595          axes[2] = FFJOFS_Z;
   596       }
   597       dest->rgdwAxes = axes;
   598    }
   599 
   600 
   601    /* The big type handling switch, even bigger then linux's version. */
   602    switch (src->type) {
   603       case SDL_HAPTIC_CONSTANT:
   604          hap_constant = &src->constant;
   605          constant = SDL_malloc( sizeof(FFCONSTANTFORCE) );
   606          if (constant == NULL) {
   607             SDL_OutOfMemory();
   608             return -1;
   609          }
   610          SDL_memset(constant, 0, sizeof(FFCONSTANTFORCE));
   611 
   612          /* Specifics */
   613          constant->lMagnitude = CONVERT(hap_constant->level);
   614          dest->cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); 
   615          dest->lpvTypeSpecificParams = constant;
   616 
   617          /* Generics */
   618          dest->dwDuration = hap_constant->length * 1000; /* In microseconds. */
   619          dest->dwTriggerButton = FFJOFS_BUTTON(hap_constant->button);
   620          dest->dwTriggerRepeatInterval = hap_constant->interval;
   621          dest->dwStartDelay = hap_constant->delay * 1000; /* In microseconds. */
   622 
   623          /* Direction. */
   624          if (SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes) < 0) {
   625             return -1;
   626          }
   627          
   628          /* Envelope */
   629          envelope->dwAttackLevel = CONVERT(hap_constant->attack_level);
   630          envelope->dwAttackTime = hap_constant->attack_length * 1000;
   631          envelope->dwFadeLevel = CONVERT(hap_constant->fade_level);
   632          envelope->dwFadeTime = hap_constant->fade_length * 1000;
   633 
   634          break;
   635 
   636       case SDL_HAPTIC_SINE:
   637       case SDL_HAPTIC_SQUARE:
   638       case SDL_HAPTIC_TRIANGLE:
   639       case SDL_HAPTIC_SAWTOOTHUP:
   640       case SDL_HAPTIC_SAWTOOTHDOWN:
   641          hap_periodic = &src->periodic;
   642          periodic = SDL_malloc(sizeof(FFPERIODIC));
   643          if (periodic == NULL) {
   644             SDL_OutOfMemory();
   645             return -1;
   646          }
   647          SDL_memset(periodic, 0, sizeof(FFPERIODIC));
   648 
   649          /* Specifics */
   650          periodic->dwMagnitude = CONVERT(hap_periodic->magnitude);
   651          periodic->lOffset = CONVERT(hap_periodic->offset);
   652          periodic->dwPhase = hap_periodic->phase;
   653          periodic->dwPeriod = hap_periodic->period * 1000;
   654          dest->cbTypeSpecificParams = sizeof(FFPERIODIC);
   655          dest->lpvTypeSpecificParams = periodic;
   656 
   657          /* Generics */
   658          dest->dwDuration = hap_periodic->length * 1000; /* In microseconds. */
   659          dest->dwTriggerButton = FFJOFS_BUTTON(hap_periodic->button);
   660          dest->dwTriggerRepeatInterval = hap_periodic->interval;
   661          dest->dwStartDelay = hap_periodic->delay * 1000; /* In microseconds. */
   662          
   663          /* Direction. */
   664          if (SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes) < 0) {
   665             return -1;
   666          }
   667          
   668          /* Envelope */
   669          envelope->dwAttackLevel = CONVERT(hap_periodic->attack_level);
   670          envelope->dwAttackTime = hap_periodic->attack_length * 1000;
   671          envelope->dwFadeLevel = CONVERT(hap_periodic->fade_level);
   672          envelope->dwFadeTime = hap_periodic->fade_length * 1000;
   673 
   674          break;
   675 
   676       case SDL_HAPTIC_SPRING:
   677       case SDL_HAPTIC_DAMPER:
   678       case SDL_HAPTIC_INERTIA:
   679       case SDL_HAPTIC_FRICTION:
   680          hap_condition = &src->condition;
   681          condition = SDL_malloc(sizeof(FFCONDITION) * dest->cAxes);
   682          if (condition == NULL) {
   683             SDL_OutOfMemory();
   684             return -1;
   685          }
   686          SDL_memset(condition, 0, sizeof(FFCONDITION));
   687 
   688          /* Specifics */
   689          for (i=0; i<dest->cAxes; i++) {
   690             condition[i].lOffset = CONVERT(hap_condition->center[i]);
   691             condition[i].lPositiveCoefficient = CONVERT(hap_condition->right_coeff[i]);
   692             condition[i].lNegativeCoefficient = CONVERT(hap_condition->left_coeff[i]);
   693             condition[i].dwPositiveSaturation = CONVERT(hap_condition->right_sat[i]);
   694             condition[i].dwNegativeSaturation = CONVERT(hap_condition->left_sat[i]);
   695             condition[i].lDeadBand = CONVERT(hap_condition->deadband[i]);
   696          }
   697          dest->cbTypeSpecificParams = sizeof(FFCONDITION) * dest->cAxes;
   698          dest->lpvTypeSpecificParams = condition;
   699 
   700          /* Generics */
   701          dest->dwDuration = hap_condition->length * 1000; /* In microseconds. */
   702          dest->dwTriggerButton = FFJOFS_BUTTON(hap_condition->button);
   703          dest->dwTriggerRepeatInterval = hap_condition->interval;
   704          dest->dwStartDelay = hap_condition->delay * 1000; /* In microseconds. */
   705 
   706          /* Direction. */
   707          if (SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes) < 0) {
   708             return -1;                
   709          }                            
   710                                       
   711          /* Envelope */
   712 /* TODO Check is envelope actually used.
   713          envelope->dwAttackLevel = CONVERT(hap_condition->attack_level);
   714          envelope->dwAttackTime = hap_condition->attack_length * 1000;
   715          envelope->dwFadeLevel = CONVERT(hap_condition->fade_level);
   716          envelope->dwFadeTime = hap_condition->fade_length * 1000;
   717 */
   718 
   719          break;
   720 
   721       case SDL_HAPTIC_RAMP:
   722          hap_ramp = &src->ramp;
   723          ramp = SDL_malloc(sizeof(FFRAMPFORCE));
   724          if (ramp == NULL) {
   725             SDL_OutOfMemory();
   726             return -1;
   727          }
   728          SDL_memset(ramp, 0, sizeof(FFRAMPFORCE));
   729 
   730          /* Specifics */
   731          ramp->lStart = CONVERT(hap_ramp->start);
   732          ramp->lEnd = CONVERT(hap_ramp->end);
   733          dest->cbTypeSpecificParams = sizeof(FFRAMPFORCE);
   734          dest->lpvTypeSpecificParams = ramp;
   735 
   736          /* Generics */
   737          dest->dwDuration = hap_ramp->length * 1000; /* In microseconds. */
   738          dest->dwTriggerButton = FFJOFS_BUTTON(hap_ramp->button);
   739          dest->dwTriggerRepeatInterval = hap_ramp->interval;
   740          dest->dwStartDelay = hap_ramp->delay * 1000; /* In microseconds. */
   741 
   742          /* Direction. */
   743          if (SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes) < 0) {
   744             return -1;
   745          }
   746 
   747          /* Envelope */
   748          envelope->dwAttackLevel = CONVERT(hap_ramp->attack_level);
   749          envelope->dwAttackTime = hap_ramp->attack_length * 1000;
   750          envelope->dwFadeLevel = CONVERT(hap_ramp->fade_level);
   751          envelope->dwFadeTime = hap_ramp->fade_length * 1000;
   752 
   753          break;
   754 
   755       case SDL_HAPTIC_CUSTOM:
   756          hap_custom = &src->custom;
   757          custom = SDL_malloc(sizeof(FFCUSTOMFORCE));
   758          if (custom == NULL) {
   759             SDL_OutOfMemory();
   760             return -1;
   761          }
   762          SDL_memset(custom, 0, sizeof(FFCUSTOMFORCE));
   763 
   764          /* Specifics */
   765          custom->cChannels = hap_custom->channels;
   766          custom->dwSamplePeriod = hap_custom->period * 1000;
   767          custom->cSamples = hap_custom->samples;
   768          custom->rglForceData = SDL_malloc(sizeof(LONG)*custom->cSamples*custom->cChannels);
   769          for (i=0; i<hap_custom->samples*hap_custom->channels; i++) { /* Copy data. */
   770             custom->rglForceData[i] = CONVERT(hap_custom->data[i]);
   771          }
   772          dest->cbTypeSpecificParams = sizeof(FFCUSTOMFORCE);
   773          dest->lpvTypeSpecificParams = custom;
   774 
   775          /* Generics */
   776          dest->dwDuration = hap_custom->length * 1000; /* In microseconds. */
   777          dest->dwTriggerButton = FFJOFS_BUTTON(hap_custom->button);
   778          dest->dwTriggerRepeatInterval = hap_custom->interval;
   779          dest->dwStartDelay = hap_custom->delay * 1000; /* In microseconds. */
   780 
   781          /* Direction. */
   782          if (SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes) < 0) {
   783             return -1;
   784          }
   785          
   786          /* Envelope */
   787          envelope->dwAttackLevel = CONVERT(hap_custom->attack_level);
   788          envelope->dwAttackTime = hap_custom->attack_length * 1000;
   789          envelope->dwFadeLevel = CONVERT(hap_custom->fade_level);
   790          envelope->dwFadeTime = hap_custom->fade_length * 1000;
   791 
   792          break;
   793 
   794 
   795       default:
   796          SDL_SetError("Haptic: Unknown effect type.");
   797          return -1;
   798    }
   799 
   800    return 0;
   801 }
   802 
   803 
   804 /*
   805  * Frees an FFEFFECT allocated by SDL_SYS_ToFFEFFECT.
   806  */
   807 static void
   808 SDL_SYS_HapticFreeFFEFFECT( FFEFFECT * effect, int type )
   809 {
   810    FFCUSTOMFORCE *custom;
   811 
   812    if (effect->lpEnvelope != NULL) {
   813       SDL_free(effect->lpEnvelope);
   814       effect->lpEnvelope = NULL;
   815    }
   816    if (effect->rgdwAxes != NULL) {
   817       SDL_free(effect->rgdwAxes);
   818       effect->rgdwAxes = NULL;
   819    }
   820    if (effect->lpvTypeSpecificParams != NULL) {
   821       if (type == SDL_HAPTIC_CUSTOM) { /* Must free the custom data. */
   822          custom = (FFCUSTOMFORCE*) effect->lpvTypeSpecificParams;
   823          SDL_free(custom->rglForceData);
   824          custom->rglForceData = NULL;
   825       }
   826       SDL_free(effect->lpvTypeSpecificParams);
   827       effect->lpvTypeSpecificParams = NULL;
   828    }
   829    if (effect->rglDirection != NULL) {
   830       SDL_free(effect->rglDirection);
   831       effect->rglDirection = NULL;
   832    }
   833 }
   834 
   835 
   836 /*
   837  * Gets the effect type from the generic SDL haptic effect wrapper.
   838  */
   839 CFUUIDRef
   840 SDL_SYS_HapticEffectType(struct haptic_effect * effect)
   841 {
   842    switch (effect->effect.type) {
   843       case SDL_HAPTIC_CONSTANT:
   844          return kFFEffectType_ConstantForce_ID;
   845 
   846       case SDL_HAPTIC_RAMP:
   847          return kFFEffectType_RampForce_ID;
   848 
   849       case SDL_HAPTIC_SQUARE:
   850          return kFFEffectType_Square_ID;
   851 
   852       case SDL_HAPTIC_SINE:
   853          return kFFEffectType_Sine_ID;
   854 
   855       case SDL_HAPTIC_TRIANGLE:
   856          return kFFEffectType_Triangle_ID;
   857 
   858       case SDL_HAPTIC_SAWTOOTHUP:
   859          return kFFEffectType_SawtoothUp_ID;
   860 
   861       case SDL_HAPTIC_SAWTOOTHDOWN:
   862          return kFFEffectType_SawtoothDown_ID;
   863 
   864       case SDL_HAPTIC_SPRING:
   865          return kFFEffectType_Spring_ID;
   866 
   867       case SDL_HAPTIC_DAMPER:
   868          return kFFEffectType_Damper_ID;
   869 
   870       case SDL_HAPTIC_INERTIA:
   871          return kFFEffectType_Inertia_ID;
   872 
   873       case SDL_HAPTIC_FRICTION:
   874          return kFFEffectType_Friction_ID;
   875 
   876       case SDL_HAPTIC_CUSTOM:
   877          return kFFEffectType_CustomForce_ID;
   878 
   879       default:
   880          SDL_SetError("Haptic: Unknown effect type.");
   881          return NULL;
   882    }
   883 }
   884 
   885 
   886 /*
   887  * Creates a new haptic effect.
   888  */
   889 int
   890 SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   891       SDL_HapticEffect * base)
   892 {
   893    HRESULT ret;
   894    CFUUIDRef type;
   895 
   896    /* Alloc the effect. */
   897    effect->hweffect = (struct haptic_hweffect *)
   898          SDL_malloc(sizeof(struct haptic_hweffect));
   899    if (effect->hweffect == NULL) {
   900       SDL_OutOfMemory();
   901       goto err_hweffect;
   902    }
   903 
   904    /* Get the type. */
   905    type = SDL_SYS_HapticEffectType(effect);
   906    if (type == NULL) {
   907       goto err_hweffect;
   908    }
   909 
   910    /* Get the effect. */
   911    if (SDL_SYS_ToFFEFFECT(haptic, &effect->hweffect->effect, base) < 0) {
   912       goto err_effectdone;
   913    }
   914 
   915    /* Create the actual effect. */
   916    ret = FFDeviceCreateEffect(haptic->hwdata->device, type,
   917          &effect->hweffect->effect, &effect->hweffect->ref);
   918    if (ret != FF_OK) {
   919       SDL_SetError("Haptic: Unable to create effect: %s.", FFStrError(ret));
   920       goto err_effectdone;
   921    }
   922 
   923    return 0;
   924 
   925 err_effectdone:
   926    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, base->type);
   927 err_hweffect:
   928    if (effect->hweffect != NULL) {
   929       SDL_free(effect->hweffect);
   930       effect->hweffect = NULL;
   931    }
   932    return -1;
   933 }
   934 
   935 
   936 /*
   937  * Updates an effect.
   938  */
   939 int
   940 SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
   941       struct haptic_effect * effect, SDL_HapticEffect * data)
   942 {
   943    HRESULT ret;
   944    FFEffectParameterFlag flags;
   945    FFEFFECT temp;
   946 
   947    /* Get the effect. */
   948    SDL_memset(&temp, 0, sizeof(FFEFFECT));
   949    if (SDL_SYS_ToFFEFFECT(haptic, &temp, data) < 0) {
   950       goto err_update;
   951    }
   952 
   953    /* Set the flags.  Might be worthwhile to diff temp with loaded effect and
   954     *  only change those parameters. */
   955    flags = FFEP_ALLPARAMS;
   956 
   957    /* Create the actual effect. */
   958    ret = FFEffectSetParameters(effect->hweffect->ref, &temp, flags);
   959    if (ret != FF_OK) {
   960       SDL_SetError("Haptic: Unable to update effect: %s.", FFStrError(ret));
   961       goto err_update;
   962    }
   963 
   964    /* Copy it over. */
   965    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, data->type);
   966    SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(FFEFFECT));
   967 
   968    return 0;
   969 
   970 err_update:
   971    SDL_SYS_HapticFreeFFEFFECT(&temp, data->type);
   972    return -1;
   973 }
   974 
   975 
   976 /*
   977  * Runs an effect.
   978  */
   979 int
   980 SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   981                         Uint32 iterations)
   982 {
   983    HRESULT ret;
   984    Uint32 iter;
   985 
   986    /* Check if it's infinite. */
   987    if (iterations == SDL_HAPTIC_INFINITY) {
   988       iter = FF_INFINITE;
   989    }
   990    else
   991       iter = iterations;
   992 
   993    /* Run the effect. */
   994    ret = FFEffectStart(effect->hweffect->ref, iter, 0);
   995    if (ret != FF_OK) {
   996       SDL_SetError("Haptic: Unable to run the effect: %s.", FFStrError(ret));
   997       return -1;
   998    }
   999 
  1000    return 0;
  1001 }
  1002 
  1003 
  1004 /*
  1005  * Stops an effect.
  1006  */
  1007 int
  1008 SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1009 {
  1010    HRESULT ret;
  1011 
  1012    ret = FFEffectStop(effect->hweffect->ref);
  1013    if (ret != FF_OK) {
  1014       SDL_SetError("Haptic: Unable to stop the effect: %s.", FFStrError(ret));
  1015       return -1;
  1016    }
  1017 
  1018    return 0;
  1019 }
  1020 
  1021 
  1022 /*
  1023  * Frees the effect.
  1024  */
  1025 void
  1026 SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1027 {
  1028    HRESULT ret;
  1029 
  1030    ret = FFDeviceReleaseEffect(haptic->hwdata->device, effect->hweffect->ref);
  1031    if (ret != FF_OK) {
  1032       SDL_SetError("Haptic: Error removing the effect from the device: %s.",
  1033                    FFStrError(ret));
  1034    }
  1035    SDL_free(effect->hweffect->effect.lpvTypeSpecificParams);
  1036    effect->hweffect->effect.lpvTypeSpecificParams = NULL;
  1037    SDL_free(effect->hweffect);
  1038    effect->hweffect = NULL;
  1039 }
  1040 
  1041 
  1042 /*
  1043  * Gets the status of a haptic effect.
  1044  */
  1045 int
  1046 SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect * effect)
  1047 {
  1048    HRESULT ret;
  1049    FFEffectStatusFlag status;
  1050 
  1051    ret = FFEffectGetEffectStatus(effect->hweffect->ref, &status);
  1052    if (ret != FF_OK) {
  1053       SDL_SetError("Haptic: Unable to get effect status: %s.", FFStrError(ret));
  1054       return -1;
  1055    }
  1056 
  1057    if (status == 0) return SDL_FALSE;
  1058    return SDL_TRUE; /* Assume it's playing or emulated. */
  1059 }
  1060 
  1061 
  1062 /*
  1063  * Sets the gain.
  1064  */
  1065 int
  1066 SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
  1067 {
  1068    HRESULT ret;
  1069    Uint32 val;
  1070 
  1071    val = gain * 100; /* Mac OS X uses 0 to 10,000 */
  1072    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, FFPROP_FFGAIN, &val);
  1073    if (ret != FF_OK) {
  1074       SDL_SetError("Haptic: Error setting gain: %s.", FFStrError(ret));
  1075       return -1;
  1076    }
  1077 
  1078    return 0;
  1079 }
  1080 
  1081 
  1082 /*
  1083  * Sets the autocentering.
  1084  */
  1085 int
  1086 SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
  1087 {
  1088    HRESULT ret;
  1089    Uint32 val;
  1090 
  1091    /* Mac OS X only has 0 (off) and 1 (on) */
  1092    if (autocenter == 0) val = 0;
  1093    else val = 1;
  1094 
  1095    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device,
  1096                FFPROP_AUTOCENTER, &val);
  1097    if (ret != FF_OK) {
  1098       SDL_SetError("Haptic: Error setting autocenter: %s.", FFStrError(ret));
  1099       return -1;
  1100    }
  1101   
  1102    return 0;
  1103 
  1104 }
  1105 
  1106 
  1107 #endif /* SDL_HAPTIC_IOKIT */