src/haptic/darwin/SDL_syshaptic.c
author Edgar Simo <bobbens@gmail.com>
Wed, 30 Jul 2008 10:28:37 +0000
branchgsoc2008_force_feedback
changeset 2550 b5b8a7f4a965
parent 2547 3cfe0ae232c0
child 2552 ee048e7bc909
permissions -rw-r--r--
Reset device and enable actuators when initializing.
     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 
   374 
   375    /* Reset and then enable actuators. */
   376    ret = FFDeviceSendForceFeedbackCommand( haptic->hwdata->device,
   377                                            FFSFFC_RESET );
   378    if (ret != FF_OK) {
   379       SDL_SetError("Haptic: Unable to reset device: %s.", FFStrError(ret));
   380       goto open_err;
   381    }
   382    ret = FFDeviceSendForceFeedbackCommand( haptic->hwdata->device,
   383                                            FFSFFC_SETACTUATORSON  );
   384    if (ret != FF_OK) {
   385       SDL_SetError("Haptic: Unable to enable actuators: %s.", FFStrError(ret));
   386       goto open_err;
   387    }
   388 
   389 
   390    /* Allocate effects memory. */
   391    haptic->effects = (struct haptic_effect *)
   392          SDL_malloc(sizeof(struct haptic_effect) * haptic->neffects);
   393    if (haptic->effects == NULL) {
   394       SDL_OutOfMemory();
   395       goto open_err;
   396    }
   397    /* Clear the memory */
   398    SDL_memset(haptic->effects, 0,
   399          sizeof(struct haptic_effect) * haptic->neffects);
   400    
   401    return 0;
   402    
   403    /* Error handling */
   404 open_err:
   405    FFReleaseDevice(haptic->hwdata->device);
   406 creat_err:
   407    if (haptic->hwdata != NULL) {
   408       free(haptic->hwdata);
   409       haptic->hwdata = NULL;                                              
   410    }
   411    return -1;
   412 
   413 }
   414 
   415 
   416 /*
   417  * Opens a haptic device for usage.
   418  */
   419 int
   420 SDL_SYS_HapticOpen(SDL_Haptic * haptic)
   421 {
   422    return SDL_SYS_HapticOpenFromService(haptic,
   423                 SDL_hapticlist[haptic->index].dev);
   424 }
   425 
   426 
   427 /*
   428  * Opens a haptic device from first mouse it finds for usage.
   429  */
   430 int
   431 SDL_SYS_HapticMouse(void)
   432 {
   433    return -1;
   434 }
   435 
   436 
   437 /*
   438  * Checks to see if a joystick has haptic features.
   439  */
   440 int
   441 SDL_SYS_JoystickIsHaptic(SDL_Joystick * joystick)
   442 {
   443    return SDL_FALSE;
   444 }
   445 
   446 
   447 /*
   448  * Checks to see if the haptic device and joystick and in reality the same.
   449  */
   450 int
   451 SDL_SYS_JoystickSameHaptic(SDL_Haptic * haptic, SDL_Joystick * joystick)
   452 {
   453    return 0;
   454 }
   455 
   456 
   457 /*
   458  * Opens a SDL_Haptic from a SDL_Joystick.
   459  */
   460 int
   461 SDL_SYS_HapticOpenFromJoystick(SDL_Haptic * haptic, SDL_Joystick * joystick)
   462 {
   463    return -1;
   464 }
   465 
   466 
   467 /*
   468  * Closes the haptic device.
   469  */
   470 void
   471 SDL_SYS_HapticClose(SDL_Haptic * haptic)
   472 {
   473    int i;
   474 
   475    if (haptic->hwdata) {
   476 
   477       /* Free the effects. */
   478       for (i=0; i<haptic->neffects; i++) {        
   479          if (haptic->effects[i].hweffect != NULL) {
   480             SDL_SYS_HapticFreeFFEFFECT(&haptic->effects[i].hweffect->effect,
   481                                        haptic->effects[i].effect.type);
   482             SDL_free(haptic->effects[i].hweffect);
   483          } 
   484       }    
   485       SDL_free(haptic->effects);
   486       haptic->neffects = 0;
   487 
   488       /* Clean up */
   489       FFReleaseDevice(haptic->hwdata->device);
   490 
   491       /* Free */
   492       SDL_free(haptic->hwdata);
   493       haptic->hwdata = NULL;
   494    }
   495 }
   496 
   497 
   498 /* 
   499  * Clean up after system specific haptic stuff
   500  */
   501 void
   502 SDL_SYS_HapticQuit(void)
   503 {
   504    int i;
   505 
   506    for (i=0; i < SDL_numhaptics; i++) {
   507       /* Opened and not closed haptics are leaked, this is on purpose.
   508        * Close your haptic devices after usage. */
   509 
   510       /* Free the io_service_t */
   511       IOObjectRelease(SDL_hapticlist[i].dev);
   512    }
   513 }
   514 
   515 
   516 /*
   517  * Sets the direction.
   518  */
   519 static int
   520 SDL_SYS_SetDirection( FFEFFECT * effect, SDL_HapticDirection *dir, int naxes )
   521 {
   522    LONG *rglDir;
   523 
   524    /* Handle no axes a part. */
   525    if (naxes == 0) {
   526       effect->rglDirection = NULL;
   527       return 0;
   528    }
   529 
   530    /* Has axes. */
   531    rglDir = SDL_malloc( sizeof(LONG) * naxes );
   532    if (rglDir == NULL) {
   533       SDL_OutOfMemory();
   534       return -1;
   535    }
   536    SDL_memset( rglDir, 0, sizeof(LONG) * naxes );
   537    effect->rglDirection = rglDir;
   538 
   539    switch (dir->type) {
   540       case SDL_HAPTIC_POLAR:
   541          effect->dwFlags |= FFEFF_POLAR;
   542          rglDir[0] = dir->dir[0];
   543          return 0;
   544       case SDL_HAPTIC_CARTESIAN:
   545          effect->dwFlags |= FFEFF_CARTESIAN;
   546          rglDir[0] = dir->dir[0];
   547          rglDir[1] = dir->dir[1];
   548          rglDir[2] = dir->dir[2];
   549          return 0;
   550       case SDL_HAPTIC_SPHERICAL:
   551          effect->dwFlags |= FFEFF_SPHERICAL;
   552          rglDir[0] = dir->dir[0];
   553          rglDir[1] = dir->dir[1];
   554          rglDir[2] = dir->dir[2];
   555          return 0;
   556 
   557       default:
   558          SDL_SetError("Haptic: Unknown direction type.");
   559          return -1;
   560    }
   561 }
   562 
   563 #define CONVERT(x)   (((x)*10000) / 0xFFFF )
   564 /*
   565  * Creates the FFEFFECT from a SDL_HapticEffect.
   566  */
   567 static int
   568 SDL_SYS_ToFFEFFECT( SDL_Haptic * haptic, FFEFFECT * dest, SDL_HapticEffect * src )
   569 {
   570    int i;
   571    FFCONSTANTFORCE *constant;
   572    FFPERIODIC *periodic;
   573    FFCONDITION *condition; /* Actually an array of conditions - one per axis. */
   574    FFRAMPFORCE *ramp;
   575    FFCUSTOMFORCE *custom;
   576    FFENVELOPE *envelope;
   577    SDL_HapticConstant *hap_constant;
   578    SDL_HapticPeriodic *hap_periodic;
   579    SDL_HapticCondition *hap_condition;
   580    SDL_HapticRamp *hap_ramp;
   581    SDL_HapticCustom *hap_custom;
   582    DWORD *axes;
   583 
   584    /* Set global stuff. */
   585    SDL_memset(dest, 0, sizeof(FFEFFECT));
   586    dest->dwSize = sizeof(FFEFFECT); /* Set the structure size. */
   587    dest->dwSamplePeriod = 0; /* Not used by us. */
   588    dest->dwGain = 10000; /* Gain is set globally, not locally. */
   589 
   590    /* Envelope. */
   591    envelope = SDL_malloc( sizeof(FFENVELOPE) );
   592    if (envelope == NULL) {
   593       SDL_OutOfMemory();
   594       return -1;
   595    }
   596    SDL_memset(envelope, 0, sizeof(FFENVELOPE));
   597    dest->lpEnvelope = envelope;
   598    envelope->dwSize = sizeof(FFENVELOPE); /* Always should be this. */
   599 
   600    /* Axes. */
   601    dest->cAxes = haptic->naxes;
   602    if (dest->cAxes > 0) {
   603       axes = SDL_malloc(sizeof(DWORD) * dest->cAxes);
   604       if (axes == NULL) {
   605          SDL_OutOfMemory();
   606          return -1;
   607       }
   608       axes[0] = FFJOFS_X; /* Always at least one axis. */
   609       if (dest->cAxes > 1) {
   610          axes[1] = FFJOFS_Y;
   611       }
   612       if (dest->cAxes > 2) {
   613          axes[2] = FFJOFS_Z;
   614       }
   615       dest->rgdwAxes = axes;
   616    }
   617 
   618 
   619    /* The big type handling switch, even bigger then linux's version. */
   620    switch (src->type) {
   621       case SDL_HAPTIC_CONSTANT:
   622          hap_constant = &src->constant;
   623          constant = SDL_malloc( sizeof(FFCONSTANTFORCE) );
   624          if (constant == NULL) {
   625             SDL_OutOfMemory();
   626             return -1;
   627          }
   628          SDL_memset(constant, 0, sizeof(FFCONSTANTFORCE));
   629 
   630          /* Specifics */
   631          constant->lMagnitude = CONVERT(hap_constant->level);
   632          dest->cbTypeSpecificParams = sizeof(FFCONSTANTFORCE); 
   633          dest->lpvTypeSpecificParams = constant;
   634 
   635          /* Generics */
   636          dest->dwDuration = hap_constant->length * 1000; /* In microseconds. */
   637          dest->dwTriggerButton = FFJOFS_BUTTON(hap_constant->button);
   638          dest->dwTriggerRepeatInterval = hap_constant->interval;
   639          dest->dwStartDelay = hap_constant->delay * 1000; /* In microseconds. */
   640 
   641          /* Direction. */
   642          if (SDL_SYS_SetDirection(dest, &hap_constant->direction, dest->cAxes) < 0) {
   643             return -1;
   644          }
   645          
   646          /* Envelope */
   647          envelope->dwAttackLevel = CONVERT(hap_constant->attack_level);
   648          envelope->dwAttackTime = hap_constant->attack_length * 1000;
   649          envelope->dwFadeLevel = CONVERT(hap_constant->fade_level);
   650          envelope->dwFadeTime = hap_constant->fade_length * 1000;
   651 
   652          break;
   653 
   654       case SDL_HAPTIC_SINE:
   655       case SDL_HAPTIC_SQUARE:
   656       case SDL_HAPTIC_TRIANGLE:
   657       case SDL_HAPTIC_SAWTOOTHUP:
   658       case SDL_HAPTIC_SAWTOOTHDOWN:
   659          hap_periodic = &src->periodic;
   660          periodic = SDL_malloc(sizeof(FFPERIODIC));
   661          if (periodic == NULL) {
   662             SDL_OutOfMemory();
   663             return -1;
   664          }
   665          SDL_memset(periodic, 0, sizeof(FFPERIODIC));
   666 
   667          /* Specifics */
   668          periodic->dwMagnitude = CONVERT(hap_periodic->magnitude);
   669          periodic->lOffset = CONVERT(hap_periodic->offset);
   670          periodic->dwPhase = hap_periodic->phase;
   671          periodic->dwPeriod = hap_periodic->period * 1000;
   672          dest->cbTypeSpecificParams = sizeof(FFPERIODIC);
   673          dest->lpvTypeSpecificParams = periodic;
   674 
   675          /* Generics */
   676          dest->dwDuration = hap_periodic->length * 1000; /* In microseconds. */
   677          dest->dwTriggerButton = FFJOFS_BUTTON(hap_periodic->button);
   678          dest->dwTriggerRepeatInterval = hap_periodic->interval;
   679          dest->dwStartDelay = hap_periodic->delay * 1000; /* In microseconds. */
   680          
   681          /* Direction. */
   682          if (SDL_SYS_SetDirection(dest, &hap_periodic->direction, dest->cAxes) < 0) {
   683             return -1;
   684          }
   685          
   686          /* Envelope */
   687          envelope->dwAttackLevel = CONVERT(hap_periodic->attack_level);
   688          envelope->dwAttackTime = hap_periodic->attack_length * 1000;
   689          envelope->dwFadeLevel = CONVERT(hap_periodic->fade_level);
   690          envelope->dwFadeTime = hap_periodic->fade_length * 1000;
   691 
   692          break;
   693 
   694       case SDL_HAPTIC_SPRING:
   695       case SDL_HAPTIC_DAMPER:
   696       case SDL_HAPTIC_INERTIA:
   697       case SDL_HAPTIC_FRICTION:
   698          hap_condition = &src->condition;
   699          condition = SDL_malloc(sizeof(FFCONDITION) * dest->cAxes);
   700          if (condition == NULL) {
   701             SDL_OutOfMemory();
   702             return -1;
   703          }
   704          SDL_memset(condition, 0, sizeof(FFCONDITION));
   705 
   706          /* Specifics */
   707          for (i=0; i<dest->cAxes; i++) {
   708             condition[i].lOffset = CONVERT(hap_condition->center[i]);
   709             condition[i].lPositiveCoefficient = CONVERT(hap_condition->right_coeff[i]);
   710             condition[i].lNegativeCoefficient = CONVERT(hap_condition->left_coeff[i]);
   711             condition[i].dwPositiveSaturation = CONVERT(hap_condition->right_sat[i]);
   712             condition[i].dwNegativeSaturation = CONVERT(hap_condition->left_sat[i]);
   713             condition[i].lDeadBand = CONVERT(hap_condition->deadband[i]);
   714          }
   715          dest->cbTypeSpecificParams = sizeof(FFCONDITION) * dest->cAxes;
   716          dest->lpvTypeSpecificParams = condition;
   717 
   718          /* Generics */
   719          dest->dwDuration = hap_condition->length * 1000; /* In microseconds. */
   720          dest->dwTriggerButton = FFJOFS_BUTTON(hap_condition->button);
   721          dest->dwTriggerRepeatInterval = hap_condition->interval;
   722          dest->dwStartDelay = hap_condition->delay * 1000; /* In microseconds. */
   723 
   724          /* Direction. */
   725          if (SDL_SYS_SetDirection(dest, &hap_condition->direction, dest->cAxes) < 0) {
   726             return -1;                
   727          }                            
   728                                       
   729          /* Envelope */
   730 /* TODO Check is envelope actually used.
   731          envelope->dwAttackLevel = CONVERT(hap_condition->attack_level);
   732          envelope->dwAttackTime = hap_condition->attack_length * 1000;
   733          envelope->dwFadeLevel = CONVERT(hap_condition->fade_level);
   734          envelope->dwFadeTime = hap_condition->fade_length * 1000;
   735 */
   736 
   737          break;
   738 
   739       case SDL_HAPTIC_RAMP:
   740          hap_ramp = &src->ramp;
   741          ramp = SDL_malloc(sizeof(FFRAMPFORCE));
   742          if (ramp == NULL) {
   743             SDL_OutOfMemory();
   744             return -1;
   745          }
   746          SDL_memset(ramp, 0, sizeof(FFRAMPFORCE));
   747 
   748          /* Specifics */
   749          ramp->lStart = CONVERT(hap_ramp->start);
   750          ramp->lEnd = CONVERT(hap_ramp->end);
   751          dest->cbTypeSpecificParams = sizeof(FFRAMPFORCE);
   752          dest->lpvTypeSpecificParams = ramp;
   753 
   754          /* Generics */
   755          dest->dwDuration = hap_ramp->length * 1000; /* In microseconds. */
   756          dest->dwTriggerButton = FFJOFS_BUTTON(hap_ramp->button);
   757          dest->dwTriggerRepeatInterval = hap_ramp->interval;
   758          dest->dwStartDelay = hap_ramp->delay * 1000; /* In microseconds. */
   759 
   760          /* Direction. */
   761          if (SDL_SYS_SetDirection(dest, &hap_ramp->direction, dest->cAxes) < 0) {
   762             return -1;
   763          }
   764 
   765          /* Envelope */
   766          envelope->dwAttackLevel = CONVERT(hap_ramp->attack_level);
   767          envelope->dwAttackTime = hap_ramp->attack_length * 1000;
   768          envelope->dwFadeLevel = CONVERT(hap_ramp->fade_level);
   769          envelope->dwFadeTime = hap_ramp->fade_length * 1000;
   770 
   771          break;
   772 
   773       case SDL_HAPTIC_CUSTOM:
   774          hap_custom = &src->custom;
   775          custom = SDL_malloc(sizeof(FFCUSTOMFORCE));
   776          if (custom == NULL) {
   777             SDL_OutOfMemory();
   778             return -1;
   779          }
   780          SDL_memset(custom, 0, sizeof(FFCUSTOMFORCE));
   781 
   782          /* Specifics */
   783          custom->cChannels = hap_custom->channels;
   784          custom->dwSamplePeriod = hap_custom->period * 1000;
   785          custom->cSamples = hap_custom->samples;
   786          custom->rglForceData = SDL_malloc(sizeof(LONG)*custom->cSamples*custom->cChannels);
   787          for (i=0; i<hap_custom->samples*hap_custom->channels; i++) { /* Copy data. */
   788             custom->rglForceData[i] = CONVERT(hap_custom->data[i]);
   789          }
   790          dest->cbTypeSpecificParams = sizeof(FFCUSTOMFORCE);
   791          dest->lpvTypeSpecificParams = custom;
   792 
   793          /* Generics */
   794          dest->dwDuration = hap_custom->length * 1000; /* In microseconds. */
   795          dest->dwTriggerButton = FFJOFS_BUTTON(hap_custom->button);
   796          dest->dwTriggerRepeatInterval = hap_custom->interval;
   797          dest->dwStartDelay = hap_custom->delay * 1000; /* In microseconds. */
   798 
   799          /* Direction. */
   800          if (SDL_SYS_SetDirection(dest, &hap_custom->direction, dest->cAxes) < 0) {
   801             return -1;
   802          }
   803          
   804          /* Envelope */
   805          envelope->dwAttackLevel = CONVERT(hap_custom->attack_level);
   806          envelope->dwAttackTime = hap_custom->attack_length * 1000;
   807          envelope->dwFadeLevel = CONVERT(hap_custom->fade_level);
   808          envelope->dwFadeTime = hap_custom->fade_length * 1000;
   809 
   810          break;
   811 
   812 
   813       default:
   814          SDL_SetError("Haptic: Unknown effect type.");
   815          return -1;
   816    }
   817 
   818    return 0;
   819 }
   820 
   821 
   822 /*
   823  * Frees an FFEFFECT allocated by SDL_SYS_ToFFEFFECT.
   824  */
   825 static void
   826 SDL_SYS_HapticFreeFFEFFECT( FFEFFECT * effect, int type )
   827 {
   828    FFCUSTOMFORCE *custom;
   829 
   830    if (effect->lpEnvelope != NULL) {
   831       SDL_free(effect->lpEnvelope);
   832       effect->lpEnvelope = NULL;
   833    }
   834    if (effect->rgdwAxes != NULL) {
   835       SDL_free(effect->rgdwAxes);
   836       effect->rgdwAxes = NULL;
   837    }
   838    if (effect->lpvTypeSpecificParams != NULL) {
   839       if (type == SDL_HAPTIC_CUSTOM) { /* Must free the custom data. */
   840          custom = (FFCUSTOMFORCE*) effect->lpvTypeSpecificParams;
   841          SDL_free(custom->rglForceData);
   842          custom->rglForceData = NULL;
   843       }
   844       SDL_free(effect->lpvTypeSpecificParams);
   845       effect->lpvTypeSpecificParams = NULL;
   846    }
   847    if (effect->rglDirection != NULL) {
   848       SDL_free(effect->rglDirection);
   849       effect->rglDirection = NULL;
   850    }
   851 }
   852 
   853 
   854 /*
   855  * Gets the effect type from the generic SDL haptic effect wrapper.
   856  */
   857 CFUUIDRef
   858 SDL_SYS_HapticEffectType(struct haptic_effect * effect)
   859 {
   860    switch (effect->effect.type) {
   861       case SDL_HAPTIC_CONSTANT:
   862          return kFFEffectType_ConstantForce_ID;
   863 
   864       case SDL_HAPTIC_RAMP:
   865          return kFFEffectType_RampForce_ID;
   866 
   867       case SDL_HAPTIC_SQUARE:
   868          return kFFEffectType_Square_ID;
   869 
   870       case SDL_HAPTIC_SINE:
   871          return kFFEffectType_Sine_ID;
   872 
   873       case SDL_HAPTIC_TRIANGLE:
   874          return kFFEffectType_Triangle_ID;
   875 
   876       case SDL_HAPTIC_SAWTOOTHUP:
   877          return kFFEffectType_SawtoothUp_ID;
   878 
   879       case SDL_HAPTIC_SAWTOOTHDOWN:
   880          return kFFEffectType_SawtoothDown_ID;
   881 
   882       case SDL_HAPTIC_SPRING:
   883          return kFFEffectType_Spring_ID;
   884 
   885       case SDL_HAPTIC_DAMPER:
   886          return kFFEffectType_Damper_ID;
   887 
   888       case SDL_HAPTIC_INERTIA:
   889          return kFFEffectType_Inertia_ID;
   890 
   891       case SDL_HAPTIC_FRICTION:
   892          return kFFEffectType_Friction_ID;
   893 
   894       case SDL_HAPTIC_CUSTOM:
   895          return kFFEffectType_CustomForce_ID;
   896 
   897       default:
   898          SDL_SetError("Haptic: Unknown effect type.");
   899          return NULL;
   900    }
   901 }
   902 
   903 
   904 /*
   905  * Creates a new haptic effect.
   906  */
   907 int
   908 SDL_SYS_HapticNewEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   909       SDL_HapticEffect * base)
   910 {
   911    HRESULT ret;
   912    CFUUIDRef type;
   913 
   914    /* Alloc the effect. */
   915    effect->hweffect = (struct haptic_hweffect *)
   916          SDL_malloc(sizeof(struct haptic_hweffect));
   917    if (effect->hweffect == NULL) {
   918       SDL_OutOfMemory();
   919       goto err_hweffect;
   920    }
   921 
   922    /* Get the type. */
   923    type = SDL_SYS_HapticEffectType(effect);
   924    if (type == NULL) {
   925       goto err_hweffect;
   926    }
   927 
   928    /* Get the effect. */
   929    if (SDL_SYS_ToFFEFFECT(haptic, &effect->hweffect->effect, base) < 0) {
   930       goto err_effectdone;
   931    }
   932 
   933    /* Create the actual effect. */
   934    ret = FFDeviceCreateEffect(haptic->hwdata->device, type,
   935          &effect->hweffect->effect, &effect->hweffect->ref);
   936    if (ret != FF_OK) {
   937       SDL_SetError("Haptic: Unable to create effect: %s.", FFStrError(ret));
   938       goto err_effectdone;
   939    }
   940 
   941    return 0;
   942 
   943 err_effectdone:
   944    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, base->type);
   945 err_hweffect:
   946    if (effect->hweffect != NULL) {
   947       SDL_free(effect->hweffect);
   948       effect->hweffect = NULL;
   949    }
   950    return -1;
   951 }
   952 
   953 
   954 /*
   955  * Updates an effect.
   956  */
   957 int
   958 SDL_SYS_HapticUpdateEffect(SDL_Haptic * haptic,
   959       struct haptic_effect * effect, SDL_HapticEffect * data)
   960 {
   961    HRESULT ret;
   962    FFEffectParameterFlag flags;
   963    FFEFFECT temp;
   964 
   965    /* Get the effect. */
   966    SDL_memset(&temp, 0, sizeof(FFEFFECT));
   967    if (SDL_SYS_ToFFEFFECT(haptic, &temp, data) < 0) {
   968       goto err_update;
   969    }
   970 
   971    /* Set the flags.  Might be worthwhile to diff temp with loaded effect and
   972     *  only change those parameters. */
   973    flags = FFEP_ALLPARAMS;
   974 
   975    /* Create the actual effect. */
   976    ret = FFEffectSetParameters(effect->hweffect->ref, &temp, flags);
   977    if (ret != FF_OK) {
   978       SDL_SetError("Haptic: Unable to update effect: %s.", FFStrError(ret));
   979       goto err_update;
   980    }
   981 
   982    /* Copy it over. */
   983    SDL_SYS_HapticFreeFFEFFECT(&effect->hweffect->effect, data->type);
   984    SDL_memcpy(&effect->hweffect->effect, &temp, sizeof(FFEFFECT));
   985 
   986    return 0;
   987 
   988 err_update:
   989    SDL_SYS_HapticFreeFFEFFECT(&temp, data->type);
   990    return -1;
   991 }
   992 
   993 
   994 /*
   995  * Runs an effect.
   996  */
   997 int
   998 SDL_SYS_HapticRunEffect(SDL_Haptic * haptic, struct haptic_effect * effect,
   999                         Uint32 iterations)
  1000 {
  1001    HRESULT ret;
  1002    Uint32 iter;
  1003 
  1004    /* Check if it's infinite. */
  1005    if (iterations == SDL_HAPTIC_INFINITY) {
  1006       iter = FF_INFINITE;
  1007    }
  1008    else
  1009       iter = iterations;
  1010 
  1011    /* Run the effect. */
  1012    ret = FFEffectStart(effect->hweffect->ref, iter, 0);
  1013    if (ret != FF_OK) {
  1014       SDL_SetError("Haptic: Unable to run the effect: %s.", FFStrError(ret));
  1015       return -1;
  1016    }
  1017 
  1018    return 0;
  1019 }
  1020 
  1021 
  1022 /*
  1023  * Stops an effect.
  1024  */
  1025 int
  1026 SDL_SYS_HapticStopEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1027 {
  1028    HRESULT ret;
  1029 
  1030    ret = FFEffectStop(effect->hweffect->ref);
  1031    if (ret != FF_OK) {
  1032       SDL_SetError("Haptic: Unable to stop the effect: %s.", FFStrError(ret));
  1033       return -1;
  1034    }
  1035 
  1036    return 0;
  1037 }
  1038 
  1039 
  1040 /*
  1041  * Frees the effect.
  1042  */
  1043 void
  1044 SDL_SYS_HapticDestroyEffect(SDL_Haptic * haptic, struct haptic_effect * effect)
  1045 {
  1046    HRESULT ret;
  1047 
  1048    ret = FFDeviceReleaseEffect(haptic->hwdata->device, effect->hweffect->ref);
  1049    if (ret != FF_OK) {
  1050       SDL_SetError("Haptic: Error removing the effect from the device: %s.",
  1051                    FFStrError(ret));
  1052    }
  1053    SDL_free(effect->hweffect->effect.lpvTypeSpecificParams);
  1054    effect->hweffect->effect.lpvTypeSpecificParams = NULL;
  1055    SDL_free(effect->hweffect);
  1056    effect->hweffect = NULL;
  1057 }
  1058 
  1059 
  1060 /*
  1061  * Gets the status of a haptic effect.
  1062  */
  1063 int
  1064 SDL_SYS_HapticGetEffectStatus(SDL_Haptic * haptic, struct haptic_effect * effect)
  1065 {
  1066    HRESULT ret;
  1067    FFEffectStatusFlag status;
  1068 
  1069    ret = FFEffectGetEffectStatus(effect->hweffect->ref, &status);
  1070    if (ret != FF_OK) {
  1071       SDL_SetError("Haptic: Unable to get effect status: %s.", FFStrError(ret));
  1072       return -1;
  1073    }
  1074 
  1075    if (status == 0) return SDL_FALSE;
  1076    return SDL_TRUE; /* Assume it's playing or emulated. */
  1077 }
  1078 
  1079 
  1080 /*
  1081  * Sets the gain.
  1082  */
  1083 int
  1084 SDL_SYS_HapticSetGain(SDL_Haptic * haptic, int gain)
  1085 {
  1086    HRESULT ret;
  1087    Uint32 val;
  1088 
  1089    val = gain * 100; /* Mac OS X uses 0 to 10,000 */
  1090    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device, FFPROP_FFGAIN, &val);
  1091    if (ret != FF_OK) {
  1092       SDL_SetError("Haptic: Error setting gain: %s.", FFStrError(ret));
  1093       return -1;
  1094    }
  1095 
  1096    return 0;
  1097 }
  1098 
  1099 
  1100 /*
  1101  * Sets the autocentering.
  1102  */
  1103 int
  1104 SDL_SYS_HapticSetAutocenter(SDL_Haptic * haptic, int autocenter)
  1105 {
  1106    HRESULT ret;
  1107    Uint32 val;
  1108 
  1109    /* Mac OS X only has 0 (off) and 1 (on) */
  1110    if (autocenter == 0) val = 0;
  1111    else val = 1;
  1112 
  1113    ret = FFDeviceSetForceFeedbackProperty(haptic->hwdata->device,
  1114                FFPROP_AUTOCENTER, &val);
  1115    if (ret != FF_OK) {
  1116       SDL_SetError("Haptic: Error setting autocenter: %s.", FFStrError(ret));
  1117       return -1;
  1118    }
  1119   
  1120    return 0;
  1121 
  1122 }
  1123 
  1124 
  1125 #endif /* SDL_HAPTIC_IOKIT */