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