Changed directory structure to contain less symlinks so dependencies will get recalculated correctly by make

This commit is contained in:
pelya
2010-10-12 19:04:21 +03:00
parent a5ff12846e
commit 2e1a4992d3
1349 changed files with 33 additions and 48 deletions

View File

@@ -0,0 +1,603 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* This is the joystick API for Simple DirectMedia Layer */
#include "SDL_events.h"
#include "SDL_sysjoystick.h"
#include "SDL_joystick_c.h"
#if !SDL_EVENTS_DISABLED
#include "../events/SDL_events_c.h"
#endif
/* This is used for Quake III Arena */
#if SDL_EVENTS_DISABLED
#define SDL_Lock_EventThread()
#define SDL_Unlock_EventThread()
#endif
Uint8 SDL_numjoysticks = 0;
SDL_Joystick **SDL_joysticks = NULL;
static SDL_Joystick *default_joystick = NULL;
int
SDL_JoystickInit(void)
{
int arraylen;
int status;
SDL_numjoysticks = 0;
status = SDL_SYS_JoystickInit();
if (status >= 0) {
arraylen = (status + 1) * sizeof(*SDL_joysticks);
SDL_joysticks = (SDL_Joystick **) SDL_malloc(arraylen);
if (SDL_joysticks == NULL) {
SDL_numjoysticks = 0;
} else {
SDL_memset(SDL_joysticks, 0, arraylen);
SDL_numjoysticks = status;
}
status = 0;
}
default_joystick = NULL;
return (status);
}
/*
* Count the number of joysticks attached to the system
*/
int
SDL_NumJoysticks(void)
{
return SDL_numjoysticks;
}
/*
* Get the implementation dependent name of a joystick
*/
const char *
SDL_JoystickName(int device_index)
{
if ((device_index < 0) || (device_index >= SDL_numjoysticks)) {
SDL_SetError("There are %d joysticks available", SDL_numjoysticks);
return (NULL);
}
return (SDL_SYS_JoystickName(device_index));
}
/*
* Open a joystick for use - the index passed as an argument refers to
* the N'th joystick on the system. This index is the value which will
* identify this joystick in future joystick events.
*
* This function returns a joystick identifier, or NULL if an error occurred.
*/
SDL_Joystick *
SDL_JoystickOpen(int device_index)
{
int i;
SDL_Joystick *joystick;
if ((device_index < 0) || (device_index >= SDL_numjoysticks)) {
SDL_SetError("There are %d joysticks available", SDL_numjoysticks);
return (NULL);
}
/* If the joystick is already open, return it */
for (i = 0; SDL_joysticks[i]; ++i) {
if (device_index == SDL_joysticks[i]->index) {
joystick = SDL_joysticks[i];
++joystick->ref_count;
return (joystick);
}
}
/* Create and initialize the joystick */
joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick));
if (joystick == NULL) {
SDL_OutOfMemory();
return NULL;
}
SDL_memset(joystick, 0, (sizeof *joystick));
joystick->index = device_index;
if (SDL_SYS_JoystickOpen(joystick) < 0) {
SDL_free(joystick);
return NULL;
}
if (joystick->naxes > 0) {
joystick->axes = (Sint16 *) SDL_malloc
(joystick->naxes * sizeof(Sint16));
}
if (joystick->nhats > 0) {
joystick->hats = (Uint8 *) SDL_malloc
(joystick->nhats * sizeof(Uint8));
}
if (joystick->nballs > 0) {
joystick->balls = (struct balldelta *) SDL_malloc
(joystick->nballs * sizeof(*joystick->balls));
}
if (joystick->nbuttons > 0) {
joystick->buttons = (Uint8 *) SDL_malloc
(joystick->nbuttons * sizeof(Uint8));
}
if (((joystick->naxes > 0) && !joystick->axes)
|| ((joystick->nhats > 0) && !joystick->hats)
|| ((joystick->nballs > 0) && !joystick->balls)
|| ((joystick->nbuttons > 0) && !joystick->buttons)) {
SDL_OutOfMemory();
SDL_JoystickClose(joystick);
return NULL;
}
if (joystick->axes) {
SDL_memset(joystick->axes, 0, joystick->naxes * sizeof(Sint16));
}
if (joystick->hats) {
SDL_memset(joystick->hats, 0, joystick->nhats * sizeof(Uint8));
}
if (joystick->balls) {
SDL_memset(joystick->balls, 0,
joystick->nballs * sizeof(*joystick->balls));
}
if (joystick->buttons) {
SDL_memset(joystick->buttons, 0, joystick->nbuttons * sizeof(Uint8));
}
/* Add joystick to list */
++joystick->ref_count;
SDL_Lock_EventThread();
for (i = 0; SDL_joysticks[i]; ++i)
/* Skip to next joystick */ ;
SDL_joysticks[i] = joystick;
SDL_Unlock_EventThread();
return (joystick);
}
/*
* Returns 1 if the joystick has been opened, or 0 if it has not.
*/
int
SDL_JoystickOpened(int device_index)
{
int i, opened;
opened = 0;
for (i = 0; SDL_joysticks[i]; ++i) {
if (SDL_joysticks[i]->index == (Uint8) device_index) {
opened = 1;
break;
}
}
return (opened);
}
/*
* Checks to make sure the joystick is valid.
*/
int
SDL_PrivateJoystickValid(SDL_Joystick ** joystick)
{
int valid;
if (*joystick == NULL) {
*joystick = default_joystick;
}
if (*joystick == NULL) {
SDL_SetError("Joystick hasn't been opened yet");
valid = 0;
} else {
valid = 1;
}
return valid;
}
/*
* Get the device index of an opened joystick.
*/
int
SDL_JoystickIndex(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
return (joystick->index);
}
/*
* Get the number of multi-dimensional axis controls on a joystick
*/
int
SDL_JoystickNumAxes(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
return (joystick->naxes);
}
/*
* Get the number of hats on a joystick
*/
int
SDL_JoystickNumHats(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
return (joystick->nhats);
}
/*
* Get the number of trackballs on a joystick
*/
int
SDL_JoystickNumBalls(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
return (joystick->nballs);
}
/*
* Get the number of buttons on a joystick
*/
int
SDL_JoystickNumButtons(SDL_Joystick * joystick)
{
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
return (joystick->nbuttons);
}
/*
* Get the current state of an axis control on a joystick
*/
Sint16
SDL_JoystickGetAxis(SDL_Joystick * joystick, int axis)
{
Sint16 state;
if (!SDL_PrivateJoystickValid(&joystick)) {
return (0);
}
if (axis < joystick->naxes) {
state = joystick->axes[axis];
} else {
SDL_SetError("Joystick only has %d axes", joystick->naxes);
state = 0;
}
return (state);
}
/*
* Get the current state of a hat on a joystick
*/
Uint8
SDL_JoystickGetHat(SDL_Joystick * joystick, int hat)
{
Uint8 state;
if (!SDL_PrivateJoystickValid(&joystick)) {
return (0);
}
if (hat < joystick->nhats) {
state = joystick->hats[hat];
} else {
SDL_SetError("Joystick only has %d hats", joystick->nhats);
state = 0;
}
return (state);
}
/*
* Get the ball axis change since the last poll
*/
int
SDL_JoystickGetBall(SDL_Joystick * joystick, int ball, int *dx, int *dy)
{
int retval;
if (!SDL_PrivateJoystickValid(&joystick)) {
return (-1);
}
retval = 0;
if (ball < joystick->nballs) {
if (dx) {
*dx = joystick->balls[ball].dx;
}
if (dy) {
*dy = joystick->balls[ball].dy;
}
joystick->balls[ball].dx = 0;
joystick->balls[ball].dy = 0;
} else {
SDL_SetError("Joystick only has %d balls", joystick->nballs);
retval = -1;
}
return (retval);
}
/*
* Get the current state of a button on a joystick
*/
Uint8
SDL_JoystickGetButton(SDL_Joystick * joystick, int button)
{
Uint8 state;
if (!SDL_PrivateJoystickValid(&joystick)) {
return (0);
}
if (button < joystick->nbuttons) {
state = joystick->buttons[button];
} else {
SDL_SetError("Joystick only has %d buttons", joystick->nbuttons);
state = 0;
}
return (state);
}
/*
* Close a joystick previously opened with SDL_JoystickOpen()
*/
void
SDL_JoystickClose(SDL_Joystick * joystick)
{
int i;
if (!SDL_PrivateJoystickValid(&joystick)) {
return;
}
/* First decrement ref count */
if (--joystick->ref_count > 0) {
return;
}
/* Lock the event queue - prevent joystick polling */
SDL_Lock_EventThread();
if (joystick == default_joystick) {
default_joystick = NULL;
}
SDL_SYS_JoystickClose(joystick);
/* Remove joystick from list */
for (i = 0; SDL_joysticks[i]; ++i) {
if (joystick == SDL_joysticks[i]) {
SDL_memmove(&SDL_joysticks[i], &SDL_joysticks[i + 1],
(SDL_numjoysticks - i) * sizeof(joystick));
break;
}
}
/* Let the event thread keep running */
SDL_Unlock_EventThread();
/* Free the data associated with this joystick */
if (joystick->axes) {
SDL_free(joystick->axes);
}
if (joystick->hats) {
SDL_free(joystick->hats);
}
if (joystick->balls) {
SDL_free(joystick->balls);
}
if (joystick->buttons) {
SDL_free(joystick->buttons);
}
SDL_free(joystick);
}
void
SDL_JoystickQuit(void)
{
/* Stop the event polling */
SDL_Lock_EventThread();
SDL_numjoysticks = 0;
SDL_Unlock_EventThread();
/* Quit the joystick setup */
SDL_SYS_JoystickQuit();
if (SDL_joysticks) {
SDL_free(SDL_joysticks);
SDL_joysticks = NULL;
}
}
/* These are global for SDL_sysjoystick.c and SDL_events.c */
int
SDL_PrivateJoystickAxis(SDL_Joystick * joystick, Uint8 axis, Sint16 value)
{
int posted;
/* Update internal joystick state */
joystick->axes[axis] = value;
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
if (SDL_GetEventState(SDL_JOYAXISMOTION) == SDL_ENABLE) {
SDL_Event event;
event.type = SDL_JOYAXISMOTION;
event.jaxis.which = joystick->index;
event.jaxis.axis = axis;
event.jaxis.value = value;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
posted = 1;
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
return (posted);
}
int
SDL_PrivateJoystickHat(SDL_Joystick * joystick, Uint8 hat, Uint8 value)
{
int posted;
/* Update internal joystick state */
joystick->hats[hat] = value;
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
if (SDL_GetEventState(SDL_JOYHATMOTION) == SDL_ENABLE) {
SDL_Event event;
event.jhat.type = SDL_JOYHATMOTION;
event.jhat.which = joystick->index;
event.jhat.hat = hat;
event.jhat.value = value;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
posted = 1;
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
return (posted);
}
int
SDL_PrivateJoystickBall(SDL_Joystick * joystick, Uint8 ball,
Sint16 xrel, Sint16 yrel)
{
int posted;
/* Update internal mouse state */
joystick->balls[ball].dx += xrel;
joystick->balls[ball].dy += yrel;
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
if (SDL_GetEventState(SDL_JOYBALLMOTION) == SDL_ENABLE) {
SDL_Event event;
event.jball.type = SDL_JOYBALLMOTION;
event.jball.which = joystick->index;
event.jball.ball = ball;
event.jball.xrel = xrel;
event.jball.yrel = yrel;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
posted = 1;
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
return (posted);
}
int
SDL_PrivateJoystickButton(SDL_Joystick * joystick, Uint8 button, Uint8 state)
{
int posted;
#if !SDL_EVENTS_DISABLED
SDL_Event event;
switch (state) {
case SDL_PRESSED:
event.type = SDL_JOYBUTTONDOWN;
break;
case SDL_RELEASED:
event.type = SDL_JOYBUTTONUP;
break;
default:
/* Invalid state -- bail */
return (0);
}
#endif /* !SDL_EVENTS_DISABLED */
/* Update internal joystick state */
joystick->buttons[button] = state;
/* Post the event, if desired */
posted = 0;
#if !SDL_EVENTS_DISABLED
if (SDL_GetEventState(event.type) == SDL_ENABLE) {
event.jbutton.which = joystick->index;
event.jbutton.button = button;
event.jbutton.state = state;
if ((SDL_EventOK == NULL)
|| (*SDL_EventOK) (SDL_EventOKParam, &event)) {
posted = 1;
SDL_PushEvent(&event);
}
}
#endif /* !SDL_EVENTS_DISABLED */
return (posted);
}
void
SDL_JoystickUpdate(void)
{
int i;
for (i = 0; SDL_joysticks[i]; ++i) {
SDL_SYS_JoystickUpdate(SDL_joysticks[i]);
}
}
int
SDL_JoystickEventState(int state)
{
#if SDL_EVENTS_DISABLED
return SDL_IGNORE;
#else
const Uint32 event_list[] = {
SDL_JOYAXISMOTION, SDL_JOYBALLMOTION, SDL_JOYHATMOTION,
SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP,
};
unsigned int i;
switch (state) {
case SDL_QUERY:
state = SDL_IGNORE;
for (i = 0; i < SDL_arraysize(event_list); ++i) {
state = SDL_EventState(event_list[i], SDL_QUERY);
if (state == SDL_ENABLE) {
break;
}
}
break;
default:
for (i = 0; i < SDL_arraysize(event_list); ++i) {
SDL_EventState(event_list[i], state);
}
break;
}
return (state);
#endif /* SDL_EVENTS_DISABLED */
}
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,47 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* Useful functions and variables from SDL_joystick.c */
#include "SDL_joystick.h"
/* The number of available joysticks on the system */
extern Uint8 SDL_numjoysticks;
/* Initialization and shutdown functions */
extern int SDL_JoystickInit(void);
extern void SDL_JoystickQuit(void);
/* Internal event queueing functions */
extern int SDL_PrivateJoystickAxis(SDL_Joystick * joystick,
Uint8 axis, Sint16 value);
extern int SDL_PrivateJoystickBall(SDL_Joystick * joystick,
Uint8 ball, Sint16 xrel, Sint16 yrel);
extern int SDL_PrivateJoystickHat(SDL_Joystick * joystick,
Uint8 hat, Uint8 value);
extern int SDL_PrivateJoystickButton(SDL_Joystick * joystick,
Uint8 button, Uint8 state);
/* Internal sanity checking functions */
extern int SDL_PrivateJoystickValid(SDL_Joystick ** joystick);
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,85 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is SDL_free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* This is the system specific header for the SDL joystick API */
#include "SDL_joystick.h"
/* The SDL joystick structure */
struct _SDL_Joystick
{
Uint8 index; /* Device index */
const char *name; /* Joystick name - system dependent */
int naxes; /* Number of axis controls on the joystick */
Sint16 *axes; /* Current axis states */
int nhats; /* Number of hats on the joystick */
Uint8 *hats; /* Current hat states */
int nballs; /* Number of trackballs on the joystick */
struct balldelta
{
int dx;
int dy;
} *balls; /* Current ball motion deltas */
int nbuttons; /* Number of buttons on the joystick */
Uint8 *buttons; /* Current button states */
struct joystick_hwdata *hwdata; /* Driver dependent information */
int ref_count; /* Reference count for multiple opens */
};
/* Function to scan the system for joysticks.
* Joystick 0 should be the system default joystick.
* This function should return the number of available joysticks, or -1
* on an unrecoverable fatal error.
*/
extern int SDL_SYS_JoystickInit(void);
/* Function to get the device-dependent name of a joystick */
extern const char *SDL_SYS_JoystickName(int index);
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
extern int SDL_SYS_JoystickOpen(SDL_Joystick * joystick);
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
extern void SDL_SYS_JoystickUpdate(SDL_Joystick * joystick);
/* Function to close a joystick after use */
extern void SDL_SYS_JoystickClose(SDL_Joystick * joystick);
/* Function to perform any system-specific joystick related cleanup */
extern void SDL_SYS_JoystickQuit(void);
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,240 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_BEOS
/* This is the system specific header for the SDL joystick API */
#include <be/support/String.h>
#include <be/device/Joystick.h>
extern "C"
{
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
/* The maximum number of joysticks we'll detect */
#define MAX_JOYSTICKS 16
/* A list of available joysticks */
static char *SDL_joyport[MAX_JOYSTICKS];
static char *SDL_joyname[MAX_JOYSTICKS];
/* The private structure used to keep track of a joystick */
struct joystick_hwdata
{
BJoystick *stick;
uint8 *new_hats;
int16 *new_axes;
};
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int SDL_SYS_JoystickInit(void)
{
BJoystick joystick;
int numjoysticks;
int i;
int32 nports;
char name[B_OS_NAME_LENGTH];
/* Search for attached joysticks */
nports = joystick.CountDevices();
numjoysticks = 0;
SDL_memset(SDL_joyport, 0, (sizeof SDL_joyport));
SDL_memset(SDL_joyname, 0, (sizeof SDL_joyname));
for (i = 0; (SDL_numjoysticks < MAX_JOYSTICKS) && (i < nports); ++i)
{
if (joystick.GetDeviceName(i, name) == B_OK) {
if (joystick.Open(name) != B_ERROR) {
BString stick_name;
joystick.GetControllerName(&stick_name);
SDL_joyport[numjoysticks] = strdup(name);
SDL_joyname[numjoysticks] = strdup(stick_name.String());
numjoysticks++;
joystick.Close();
}
}
}
return (numjoysticks);
}
/* Function to get the device-dependent name of a joystick */
const char *SDL_SYS_JoystickName(int index)
{
return SDL_joyname[index];
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
BJoystick *stick;
/* Create the joystick data structure */
joystick->hwdata = (struct joystick_hwdata *)
SDL_malloc(sizeof(*joystick->hwdata));
if (joystick->hwdata == NULL) {
SDL_OutOfMemory();
return (-1);
}
SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
stick = new BJoystick;
joystick->hwdata->stick = stick;
/* Open the requested joystick for use */
if (stick->Open(SDL_joyport[joystick->index]) == B_ERROR) {
SDL_SetError("Unable to open joystick");
SDL_SYS_JoystickClose(joystick);
return (-1);
}
/* Set the joystick to calibrated mode */
stick->EnableCalibration();
/* Get the number of buttons, hats, and axes on the joystick */
joystick->nbuttons = stick->CountButtons();
joystick->naxes = stick->CountAxes();
joystick->nhats = stick->CountHats();
joystick->hwdata->new_axes = (int16 *)
SDL_malloc(joystick->naxes * sizeof(int16));
joystick->hwdata->new_hats = (uint8 *)
SDL_malloc(joystick->nhats * sizeof(uint8));
if (!joystick->hwdata->new_hats || !joystick->hwdata->new_axes) {
SDL_OutOfMemory();
SDL_SYS_JoystickClose(joystick);
return (-1);
}
/* We're done! */
return (0);
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
static const Uint8 hat_map[9] = {
SDL_HAT_CENTERED,
SDL_HAT_UP,
SDL_HAT_RIGHTUP,
SDL_HAT_RIGHT,
SDL_HAT_RIGHTDOWN,
SDL_HAT_DOWN,
SDL_HAT_LEFTDOWN,
SDL_HAT_LEFT,
SDL_HAT_LEFTUP
};
const int JITTER = (32768 / 10); /* 10% jitter threshold (ok?) */
BJoystick *stick;
int i, change;
int16 *axes;
uint8 *hats;
uint32 buttons;
/* Set up data pointers */
stick = joystick->hwdata->stick;
axes = joystick->hwdata->new_axes;
hats = joystick->hwdata->new_hats;
/* Get the new joystick state */
stick->Update();
stick->GetAxisValues(axes);
stick->GetHatValues(hats);
buttons = stick->ButtonValues();
/* Generate axis motion events */
for (i = 0; i < joystick->naxes; ++i) {
change = ((int32) axes[i] - joystick->axes[i]);
if ((change > JITTER) || (change < -JITTER)) {
SDL_PrivateJoystickAxis(joystick, i, axes[i]);
}
}
/* Generate hat change events */
for (i = 0; i < joystick->nhats; ++i) {
if (hats[i] != joystick->hats[i]) {
SDL_PrivateJoystickHat(joystick, i, hat_map[hats[i]]);
}
}
/* Generate button events */
for (i = 0; i < joystick->nbuttons; ++i) {
if ((buttons & 0x01) != joystick->buttons[i]) {
SDL_PrivateJoystickButton(joystick, i, (buttons & 0x01));
}
buttons >>= 1;
}
}
/* Function to close a joystick after use */
void SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
if (joystick->hwdata) {
joystick->hwdata->stick->Close();
delete joystick->hwdata->stick;
if (joystick->hwdata->new_hats) {
SDL_free(joystick->hwdata->new_hats);
}
if (joystick->hwdata->new_axes) {
SDL_free(joystick->hwdata->new_axes);
}
SDL_free(joystick->hwdata);
joystick->hwdata = NULL;
}
}
/* Function to perform any system-specific joystick related cleanup */
void SDL_SYS_JoystickQuit(void)
{
int i;
for (i = 0; SDL_joyport[i]; ++i) {
SDL_free(SDL_joyport[i]);
}
SDL_joyport[0] = NULL;
for (i = 0; SDL_joyname[i]; ++i) {
SDL_free(SDL_joyname[i]);
}
SDL_joyname[0] = NULL;
}
}; // extern "C"
#endif /* SDL_JOYSTICK_BEOS */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,613 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_USBHID
/*
* Joystick driver for the uhid(4) interface found in OpenBSD,
* NetBSD and FreeBSD.
*
* Maintainer: <vedge at csoft.org>
*/
#include <sys/param.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#ifndef __FreeBSD_kernel_version
#define __FreeBSD_kernel_version __FreeBSD_version
#endif
#if defined(HAVE_USB_H)
#include <usb.h>
#endif
#ifdef __DragonFly__
#include <bus/usb/usb.h>
#include <bus/usb/usbhid.h>
#else
#include <dev/usb/usb.h>
#include <dev/usb/usbhid.h>
#endif
#if defined(HAVE_USBHID_H)
#include <usbhid.h>
#elif defined(HAVE_LIBUSB_H)
#include <libusb.h>
#elif defined(HAVE_LIBUSBHID_H)
#include <libusbhid.h>
#endif
#ifdef defined(__FREEBSD__) || defined(__FreeBSD_kernel__)
#ifndef __DragonFly__
#include <osreldate.h>
#endif
#include <sys/joystick.h>
#endif
#if SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H
#include <machine/joystick.h>
#endif
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#define MAX_UHID_JOYS 4
#define MAX_JOY_JOYS 2
#define MAX_JOYS (MAX_UHID_JOYS + MAX_JOY_JOYS)
#if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063) && false
struct usb_ctl_report {
int ucr_report;
u_char ucr_data[1024]; /* filled data size will vary */
};
#endif
struct report
{
struct usb_ctl_report *buf; /* Buffer */
size_t size; /* Buffer size */
int rid; /* Report ID */
enum
{
SREPORT_UNINIT,
SREPORT_CLEAN,
SREPORT_DIRTY
} status;
};
static struct
{
int uhid_report;
hid_kind_t kind;
const char *name;
} const repinfo[] = {
{UHID_INPUT_REPORT, hid_input, "input"},
{UHID_OUTPUT_REPORT, hid_output, "output"},
{UHID_FEATURE_REPORT, hid_feature, "feature"}
};
enum
{
REPORT_INPUT = 0,
REPORT_OUTPUT = 1,
REPORT_FEATURE = 2
};
enum
{
JOYAXE_X,
JOYAXE_Y,
JOYAXE_Z,
JOYAXE_SLIDER,
JOYAXE_WHEEL,
JOYAXE_RX,
JOYAXE_RY,
JOYAXE_RZ,
JOYAXE_count
};
struct joystick_hwdata
{
int fd;
char *path;
enum
{
BSDJOY_UHID, /* uhid(4) */
BSDJOY_JOY /* joy(4) */
} type;
struct report_desc *repdesc;
struct report inreport;
int axis_map[JOYAXE_count]; /* map present JOYAXE_* to 0,1,.. */
};
static char *joynames[MAX_JOYS];
static char *joydevnames[MAX_JOYS];
static int report_alloc(struct report *, struct report_desc *, int);
static void report_free(struct report *);
#if defined(USBHID_UCR_DATA) || (defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063)) || defined(__FreeBSD_kernel__)
#define REP_BUF_DATA(rep) ((rep)->buf->ucr_data)
#else
#define REP_BUF_DATA(rep) ((rep)->buf->data)
#endif
int
SDL_SYS_JoystickInit(void)
{
char s[16];
int i, fd;
SDL_numjoysticks = 0;
SDL_memset(joynames, 0, sizeof(joynames));
SDL_memset(joydevnames, 0, sizeof(joydevnames));
for (i = 0; i < MAX_UHID_JOYS; i++) {
SDL_Joystick nj;
SDL_snprintf(s, SDL_arraysize(s), "/dev/uhid%d", i);
nj.index = SDL_numjoysticks;
joynames[nj.index] = strdup(s);
if (SDL_SYS_JoystickOpen(&nj) == 0) {
SDL_SYS_JoystickClose(&nj);
SDL_numjoysticks++;
} else {
SDL_free(joynames[nj.index]);
joynames[nj.index] = NULL;
}
}
for (i = 0; i < MAX_JOY_JOYS; i++) {
SDL_snprintf(s, SDL_arraysize(s), "/dev/joy%d", i);
fd = open(s, O_RDONLY);
if (fd != -1) {
joynames[SDL_numjoysticks++] = strdup(s);
close(fd);
}
}
/* Read the default USB HID usage table. */
hid_init(NULL);
return (SDL_numjoysticks);
}
const char *
SDL_SYS_JoystickName(int index)
{
if (joydevnames[index] != NULL) {
return (joydevnames[index]);
}
return (joynames[index]);
}
static int
usage_to_joyaxe(unsigned usage)
{
int joyaxe;
switch (usage) {
case HUG_X:
joyaxe = JOYAXE_X;
break;
case HUG_Y:
joyaxe = JOYAXE_Y;
break;
case HUG_Z:
joyaxe = JOYAXE_Z;
break;
case HUG_SLIDER:
joyaxe = JOYAXE_SLIDER;
break;
case HUG_WHEEL:
joyaxe = JOYAXE_WHEEL;
break;
case HUG_RX:
joyaxe = JOYAXE_RX;
break;
case HUG_RY:
joyaxe = JOYAXE_RY;
break;
case HUG_RZ:
joyaxe = JOYAXE_RZ;
break;
default:
joyaxe = -1;
}
return joyaxe;
}
static unsigned
hatval_to_sdl(Sint32 hatval)
{
static const unsigned hat_dir_map[8] = {
SDL_HAT_UP, SDL_HAT_RIGHTUP, SDL_HAT_RIGHT, SDL_HAT_RIGHTDOWN,
SDL_HAT_DOWN, SDL_HAT_LEFTDOWN, SDL_HAT_LEFT, SDL_HAT_LEFTUP
};
unsigned result;
if ((hatval & 7) == hatval)
result = hat_dir_map[hatval];
else
result = SDL_HAT_CENTERED;
return result;
}
int
SDL_SYS_JoystickOpen(SDL_Joystick * joy)
{
char *path = joynames[joy->index];
struct joystick_hwdata *hw;
struct hid_item hitem;
struct hid_data *hdata;
struct report *rep;
int fd;
int i;
fd = open(path, O_RDONLY);
if (fd == -1) {
SDL_SetError("%s: %s", path, strerror(errno));
return (-1);
}
hw = (struct joystick_hwdata *)
SDL_malloc(sizeof(struct joystick_hwdata));
if (hw == NULL) {
SDL_OutOfMemory();
close(fd);
return (-1);
}
joy->hwdata = hw;
hw->fd = fd;
hw->path = strdup(path);
if (!SDL_strncmp(path, "/dev/joy", 8)) {
hw->type = BSDJOY_JOY;
joy->naxes = 2;
joy->nbuttons = 2;
joy->nhats = 0;
joy->nballs = 0;
joydevnames[joy->index] = strdup("Gameport joystick");
goto usbend;
} else {
hw->type = BSDJOY_UHID;
}
{
int ax;
for (ax = 0; ax < JOYAXE_count; ax++)
hw->axis_map[ax] = -1;
}
hw->repdesc = hid_get_report_desc(fd);
if (hw->repdesc == NULL) {
SDL_SetError("%s: USB_GET_REPORT_DESC: %s", hw->path,
strerror(errno));
goto usberr;
}
rep = &hw->inreport;
#if defined(__FREEBSD__) && (__FreeBSD_kernel_version > 800063) || defined(__FreeBSD_kernel__)
rep->rid = hid_get_report_id(fd);
if (rep->rid < 0) {
#else
if (ioctl(fd, USB_GET_REPORT_ID, &rep->rid) < 0) {
#endif
rep->rid = -1; /* XXX */
}
if (report_alloc(rep, hw->repdesc, REPORT_INPUT) < 0) {
goto usberr;
}
if (rep->size <= 0) {
SDL_SetError("%s: Input report descriptor has invalid length",
hw->path);
goto usberr;
}
#if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__)
hdata = hid_start_parse(hw->repdesc, 1 << hid_input, rep->rid);
#else
hdata = hid_start_parse(hw->repdesc, 1 << hid_input);
#endif
if (hdata == NULL) {
SDL_SetError("%s: Cannot start HID parser", hw->path);
goto usberr;
}
joy->naxes = 0;
joy->nbuttons = 0;
joy->nhats = 0;
joy->nballs = 0;
for (i = 0; i < JOYAXE_count; i++)
hw->axis_map[i] = -1;
while (hid_get_item(hdata, &hitem) > 0) {
char *sp;
const char *s;
switch (hitem.kind) {
case hid_collection:
switch (HID_PAGE(hitem.usage)) {
case HUP_GENERIC_DESKTOP:
switch (HID_USAGE(hitem.usage)) {
case HUG_JOYSTICK:
case HUG_GAME_PAD:
s = hid_usage_in_page(hitem.usage);
sp = SDL_malloc(SDL_strlen(s) + 5);
SDL_snprintf(sp, SDL_strlen(s) + 5, "%s (%d)",
s, joy->index);
joydevnames[joy->index] = sp;
}
}
break;
case hid_input:
switch (HID_PAGE(hitem.usage)) {
case HUP_GENERIC_DESKTOP:
{
unsigned usage = HID_USAGE(hitem.usage);
int joyaxe = usage_to_joyaxe(usage);
if (joyaxe >= 0) {
hw->axis_map[joyaxe] = 1;
} else if (usage == HUG_HAT_SWITCH) {
joy->nhats++;
}
break;
}
case HUP_BUTTON:
joy->nbuttons++;
break;
default:
break;
}
break;
default:
break;
}
}
hid_end_parse(hdata);
for (i = 0; i < JOYAXE_count; i++)
if (hw->axis_map[i] > 0)
hw->axis_map[i] = joy->naxes++;
usbend:
/* The poll blocks the event thread. */
fcntl(fd, F_SETFL, O_NONBLOCK);
return (0);
usberr:
close(hw->fd);
SDL_free(hw->path);
SDL_free(hw);
return (-1);
}
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joy)
{
struct hid_item hitem;
struct hid_data *hdata;
struct report *rep;
int nbutton, naxe = -1;
Sint32 v;
#if defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H || defined(__FreeBSD_kernel__)
struct joystick gameport;
static int x, y, xmin = 0xffff, ymin = 0xffff, xmax = 0, ymax = 0;
if (joy->hwdata->type == BSDJOY_JOY) {
if (read(joy->hwdata->fd, &gameport, sizeof gameport) !=
sizeof gameport)
return;
if (abs(x - gameport.x) > 8) {
x = gameport.x;
if (x < xmin) {
xmin = x;
}
if (x > xmax) {
xmax = x;
}
if (xmin == xmax) {
xmin--;
xmax++;
}
v = (Sint32) x;
v -= (xmax + xmin + 1) / 2;
v *= 32768 / ((xmax - xmin + 1) / 2);
SDL_PrivateJoystickAxis(joy, 0, v);
}
if (abs(y - gameport.y) > 8) {
y = gameport.y;
if (y < ymin) {
ymin = y;
}
if (y > ymax) {
ymax = y;
}
if (ymin == ymax) {
ymin--;
ymax++;
}
v = (Sint32) y;
v -= (ymax + ymin + 1) / 2;
v *= 32768 / ((ymax - ymin + 1) / 2);
SDL_PrivateJoystickAxis(joy, 1, v);
}
if (gameport.b1 != joy->buttons[0]) {
SDL_PrivateJoystickButton(joy, 0, gameport.b1);
}
if (gameport.b2 != joy->buttons[1]) {
SDL_PrivateJoystickButton(joy, 1, gameport.b2);
}
return;
}
#endif /* defined(__FREEBSD__) || SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H */
rep = &joy->hwdata->inreport;
if (read(joy->hwdata->fd, REP_BUF_DATA(rep), rep->size) != rep->size) {
return;
}
#if defined(USBHID_NEW) || (defined(__FREEBSD__) && __FreeBSD_kernel_version >= 500111) || defined(__FreeBSD_kernel__)
hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input, rep->rid);
#else
hdata = hid_start_parse(joy->hwdata->repdesc, 1 << hid_input);
#endif
if (hdata == NULL) {
fprintf(stderr, "%s: Cannot start HID parser\n", joy->hwdata->path);
return;
}
for (nbutton = 0; hid_get_item(hdata, &hitem) > 0;) {
switch (hitem.kind) {
case hid_input:
switch (HID_PAGE(hitem.usage)) {
case HUP_GENERIC_DESKTOP:
{
unsigned usage = HID_USAGE(hitem.usage);
int joyaxe = usage_to_joyaxe(usage);
if (joyaxe >= 0) {
naxe = joy->hwdata->axis_map[joyaxe];
/* scaleaxe */
v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem);
v -= (hitem.logical_maximum +
hitem.logical_minimum + 1) / 2;
v *= 32768 /
((hitem.logical_maximum -
hitem.logical_minimum + 1) / 2);
if (v != joy->axes[naxe]) {
SDL_PrivateJoystickAxis(joy, naxe, v);
}
} else if (usage == HUG_HAT_SWITCH) {
v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem);
SDL_PrivateJoystickHat(joy, 0,
hatval_to_sdl(v) -
hitem.logical_minimum);
}
break;
}
case HUP_BUTTON:
v = (Sint32) hid_get_data(REP_BUF_DATA(rep), &hitem);
if (joy->buttons[nbutton] != v) {
SDL_PrivateJoystickButton(joy, nbutton, v);
}
nbutton++;
break;
default:
continue;
}
break;
default:
break;
}
}
hid_end_parse(hdata);
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joy)
{
if (SDL_strncmp(joy->hwdata->path, "/dev/joy", 8)) {
report_free(&joy->hwdata->inreport);
hid_dispose_report_desc(joy->hwdata->repdesc);
}
close(joy->hwdata->fd);
SDL_free(joy->hwdata->path);
SDL_free(joy->hwdata);
return;
}
void
SDL_SYS_JoystickQuit(void)
{
int i;
for (i = 0; i < MAX_JOYS; i++) {
if (joynames[i] != NULL)
SDL_free(joynames[i]);
if (joydevnames[i] != NULL)
SDL_free(joydevnames[i]);
}
return;
}
static int
report_alloc(struct report *r, struct report_desc *rd, int repind)
{
int len;
#ifdef __DragonFly__
len = hid_report_size(rd, r->rid, repinfo[repind].kind);
#elif __FREEBSD__
# if (__FreeBSD_kernel_version >= 460000) || defined(__FreeBSD_kernel__)
# if (__FreeBSD_kernel_version <= 500111)
len = hid_report_size(rd, r->rid, repinfo[repind].kind);
# else
len = hid_report_size(rd, repinfo[repind].kind, r->rid);
# endif
# else
len = hid_report_size(rd, repinfo[repind].kind, &r->rid);
# endif
#else
# ifdef USBHID_NEW
len = hid_report_size(rd, repinfo[repind].kind, r->rid);
# else
len = hid_report_size(rd, repinfo[repind].kind, &r->rid);
# endif
#endif
if (len < 0) {
SDL_SetError("Negative HID report size");
return (-1);
}
r->size = len;
if (r->size > 0) {
r->buf = SDL_malloc(sizeof(*r->buf) - sizeof(REP_BUF_DATA(r)) +
r->size);
if (r->buf == NULL) {
SDL_OutOfMemory();
return (-1);
}
} else {
r->buf = NULL;
}
r->status = SREPORT_CLEAN;
return (0);
}
static void
report_free(struct report *r)
{
if (r->buf != NULL) {
SDL_free(r->buf);
}
r->status = SREPORT_UNINIT;
}
#endif /* SDL_JOYSTICK_USBHID */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,874 @@
/* *INDENT-OFF* */
/*
*
* @APPLE_LICENSE_HEADER_START@
*
* Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#ifndef _IOKIT_HID_IOHIDLIB_H_
#define _IOKIT_HID_IOHIDLIB_H_
#include <sys/cdefs.h>
__BEGIN_DECLS
#include <CoreFoundation/CoreFoundation.h>
#if COREFOUNDATION_CFPLUGINCOM_SEPARATE
#include <CoreFoundation/CFPlugInCOM.h>
#endif
#include <IOKit/IOTypes.h>
#include <IOKit/IOReturn.h>
#include <IOKit/hid/IOHIDKeys.h>
struct IOHIDEventStruct
{
IOHIDElementType type;
IOHIDElementCookie elementCookie;
SInt32 value;
AbsoluteTime timestamp;
UInt32 longValueSize;
void * longValue;
};
typedef struct IOHIDEventStruct IOHIDEventStruct;
/* FA12FA38-6F1A-11D4-BA0C-0005028F18D5 */
#define kIOHIDDeviceUserClientTypeID CFUUIDGetConstantUUIDWithBytes(NULL, \
0xFA, 0x12, 0xFA, 0x38, 0x6F, 0x1A, 0x11, 0xD4, \
0xBA, 0x0C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5)
/* 13AA9C44-6F1B-11D4-907C-0005028F18D5 */
#define kIOHIDDeviceFactoryID CFUUIDGetConstantUUIDWithBytes(NULL, \
0x13, 0xAA, 0x9C, 0x44, 0x6F, 0x1B, 0x11, 0xD4, \
0x90, 0x7C, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5)
/* 78BD420C-6F14-11D4-9474-0005028F18D5 */
/*! @defined kIOHIDDeviceInterfaceID
@discussion Interface ID for the IOHIDDeviceInterface. Corresponds to an
available HID device. */
#define kIOHIDDeviceInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \
0x78, 0xBD, 0x42, 0x0C, 0x6F, 0x14, 0x11, 0xD4, \
0x94, 0x74, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5)
/* 7D0B510E-16D5-11D7-9E9B-000393992E38 */
/*! @defined kIOHIDDeviceInterfaceID121
@discussion Interface ID for the IOHIDDeviceInterface121. Corresponds to
an available HID device that includes methods from
IOHIDDeviceInterface. This interface is available on
IOHIDLib 1.2.1 and Mac OS X 10.2.3 or later.*/
#define kIOHIDDeviceInterfaceID121 CFUUIDGetConstantUUIDWithBytes(NULL, \
0x7d, 0xb, 0x51, 0xe, 0x16, 0xd5, 0x11, 0xd7, \
0x9e, 0x9b, 0x0, 0x3, 0x93, 0x99, 0x2e, 0x38)
/* B70ABF31-16D5-11D7-AB35-000393992E38 */
/*! @defined kIOHIDDeviceInterfaceID122
@discussion Interface ID for the IOHIDDeviceInterface122. Corresponds to
an available HID device that includes methods from
IOHIDDeviceInterface and IOHIDDeviceInterface121. This
interface is available on IOHIDLib 1.2.2 and Mac OS X 10.3
or later.*/
#define kIOHIDDeviceInterfaceID122 CFUUIDGetConstantUUIDWithBytes(NULL, \
0xb7, 0xa, 0xbf, 0x31, 0x16, 0xd5, 0x11, 0xd7, \
0xab, 0x35, 0x0, 0x3, 0x93, 0x99, 0x2e, 0x38)
/* 8138629E-6F14-11D4-970E-0005028F18D5 */
/*! @defined kIOHIDQueueInterfaceID
@discussion Interface ID for the kIOHIDQueueInterfaceID. Corresponds to a
queue for a specific HID device. */
#define kIOHIDQueueInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL, \
0x81, 0x38, 0x62, 0x9E, 0x6F, 0x14, 0x11, 0xD4, \
0x97, 0x0E, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5)
/* 80CDCC00-755D-11D4-8E0F-0005028F18D5 */
/*! @defined kIOHIDOutputTransactionInterfaceID
@discussion Interface ID for the kIOHIDOutputTransactionInterfaceID.
Corresponds to an output transaction for one or more report IDs
on a specific device. */
#define kIOHIDOutputTransactionInterfaceID CFUUIDGetConstantUUIDWithBytes(NULL,\
0x80, 0xCD, 0xCC, 0x00, 0x75, 0x5D, 0x11, 0xD4, \
0x80, 0xEF, 0x00, 0x05, 0x02, 0x8F, 0x18, 0xD5)
/*! @typedef IOHIDCallbackFunction
@discussion Type and arguments of callout C function that is used when a
completion routine is called, see
IOHIDLib.h:setRemovalCallback().
@param target void * pointer to your data, often a pointer to an object.
@param result Completion result of desired operation.
@param refcon void * pointer to more data.
@param sender Interface instance sending the completion routine.
*/
typedef void (*IOHIDCallbackFunction)
(void * target, IOReturn result, void * refcon, void * sender);
/*! @typedef IOHIDElementCallbackFunction
@discussion Type and arguments of callout C function that is used when a
completion routine is called, see IOHIDLib.h:setElementValue().
@param target void * pointer to your data, often a pointer to an object.
@param result Completion result of desired operation.
@param refcon void * pointer to more data.
@param sender Interface instance sending the completion routine.
@param elementCookie Element within interface instance sending completion.
*/
typedef void (*IOHIDElementCallbackFunction)
(void * target,
IOReturn result,
void * refcon,
void * sender,
IOHIDElementCookie elementCookie);
/*! @typedef IOHIDReportCallbackFunction
@discussion Type and arguments of callout C function that is used when a
completion routine is called, see IOHIDLib.h:setReport().
@param target void * pointer to your data, often a pointer to an object.
@param result Completion result of desired operation.
@param refcon void * pointer to more data.
@param sender Interface instance sending the completion routine.
@param bufferSize Size of the buffer received upon completion.
*/
typedef void (*IOHIDReportCallbackFunction)
(void * target,
IOReturn result,
void * refcon,
void * sender,
UInt32 bufferSize);
/* Forward declarations of the queue and output transaction interfaces */
struct IOHIDQueueInterface;
struct IOHIDOutputTransactionInterface;
typedef struct IOHIDQueueInterface IOHIDQueueInterface;
typedef struct IOHIDOutputTransactionInterface IOHIDOutputTransactionInterface;
//
// IOHIDDeviceInterface Functions available in version 1.0 (10.0) and higher of Mac OS X
//
#define IOHIDDEVICEINTERFACE_FUNCS_100 \
IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \
CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \
IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \
mach_port_t (*getAsyncPort)(void * self); \
IOReturn (*open)(void * self, UInt32 flags); \
IOReturn (*close)(void * self); \
IOReturn (*setRemovalCallback)(void * self, IOHIDCallbackFunction removalCallback, \
void * removalTarget, void * removalRefcon); \
IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * valueEvent); \
IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * valueEvent, UInt32 timeoutMS, \
IOHIDElementCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon); \
IOReturn (*queryElementValue)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * valueEvent, UInt32 timeoutMS, \
IOHIDElementCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon); \
IOReturn (*startAllQueues)(void * self); \
IOReturn (*stopAllQueues)(void * self); \
IOHIDQueueInterface ** (*allocQueue) (void *self); \
IOHIDOutputTransactionInterface ** (*allocOutputTransaction) (void *self)
//
// IOHIDDeviceInterface Functions available in version 1.2.1 (10.2.3) and higher of Mac OS X
//
#define IOHIDDEVICEINTERFACE_FUNCS_121 \
IOReturn (*setReport)(void * self, IOHIDReportType reportType, UInt32 reportID, \
void * reportBuffer, UInt32 reportBufferSize, \
UInt32 timeoutMS, IOHIDReportCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon); \
IOReturn (*getReport)(void * self, IOHIDReportType reportType, \
UInt32 reportID, void * reportBuffer, \
UInt32 * reportBufferSize, UInt32 timeoutMS, \
IOHIDReportCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon)
//
// IOHIDDeviceInterface Functions available in version 1.2.2 (10.3) and higher of Mac OS X
//
#define IOHIDDEVICEINTERFACE_FUNCS_122 \
IOReturn (*copyMatchingElements)(void * self, CFDictionaryRef matchingDict, \
CFArrayRef * elements); \
IOReturn (*setInterruptReportHandlerCallback)(void * self, void * reportBuffer, \
UInt32 reportBufferSize, \
IOHIDReportCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon)
typedef struct IOHIDDeviceInterface
{
IUNKNOWN_C_GUTS;
IOHIDDEVICEINTERFACE_FUNCS_100;
IOHIDDEVICEINTERFACE_FUNCS_121;
} IOHIDDeviceInterface;
typedef struct IOHIDDeviceInterface121
{
IUNKNOWN_C_GUTS;
IOHIDDEVICEINTERFACE_FUNCS_100;
IOHIDDEVICEINTERFACE_FUNCS_121;
} IOHIDDeviceInterface121;
typedef struct IOHIDDeviceInterface122
{
IUNKNOWN_C_GUTS;
IOHIDDEVICEINTERFACE_FUNCS_100;
IOHIDDEVICEINTERFACE_FUNCS_121;
IOHIDDEVICEINTERFACE_FUNCS_122;
} IOHIDDeviceInterface122;
//
// IOHIDQueueInterface Functions available in version 1.0 (10.0) and higher of Mac OS X
//
#define IOHIDQUEUEINTERFACE_FUNCS_100 \
IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \
CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \
IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \
mach_port_t (*getAsyncPort)(void * self); \
IOReturn (*create)(void * self, UInt32 flags, UInt32 depth); \
IOReturn (*dispose)(void * self); \
IOReturn (*addElement)(void * self, IOHIDElementCookie elementCookie, UInt32 flags);\
IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie); \
Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie); \
IOReturn (*start)(void * self); \
IOReturn (*stop)(void * self); \
IOReturn (*getNextEvent)(void * self, IOHIDEventStruct * event, \
AbsoluteTime maxTime, UInt32 timeoutMS); \
IOReturn (*setEventCallout)(void * self, IOHIDCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon); \
IOReturn (*getEventCallout)(void * self, IOHIDCallbackFunction * outCallback, \
void ** outCallbackTarget, void ** outCallbackRefcon)
struct IOHIDQueueInterface
{
IUNKNOWN_C_GUTS;
IOHIDQUEUEINTERFACE_FUNCS_100;
};
//
// IOHIDOutputTransactionInterface Functions available in version 1.2 (10.2) and higher of Mac OS X
//
#define IOHIDOUTPUTTRANSACTIONINTERFACE_FUNCS_120 \
IOReturn (*createAsyncEventSource)(void * self, CFRunLoopSourceRef * source); \
CFRunLoopSourceRef (*getAsyncEventSource)(void * self); \
IOReturn (*createAsyncPort)(void * self, mach_port_t * port); \
mach_port_t (*getAsyncPort)(void * self); \
IOReturn (*create)(void * self); \
IOReturn (*dispose)(void * self); \
IOReturn (*addElement)(void * self, IOHIDElementCookie elementCookie); \
IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie); \
Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie); \
IOReturn (*setElementDefault)(void *self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * valueEvent); \
IOReturn (*getElementDefault)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * outValueEvent); \
IOReturn (*setElementValue)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * valueEvent); \
IOReturn (*getElementValue)(void * self, IOHIDElementCookie elementCookie, \
IOHIDEventStruct * outValueEvent); \
IOReturn (*commit)(void * self, UInt32 timeoutMS, IOHIDCallbackFunction callback, \
void * callbackTarget, void * callbackRefcon); \
IOReturn (*clear)(void * self)
struct IOHIDOutputTransactionInterface
{
IUNKNOWN_C_GUTS;
IOHIDOUTPUTTRANSACTIONINTERFACE_FUNCS_120;
};
//
// BEGIN READABLE STRUCTURE DEFINITIONS
//
// This portion of uncompiled code provides a more reader friendly representation of
// the CFPlugin methods defined above.
#if 0
/*! @class IOHIDDeviceInterface
@discussion CFPlugin object subclass which provides the primary interface to
HID devices.
*/
typedef struct IOHIDDeviceInterface
{
IUNKNOWN_C_GUTS;
/*! @function createAsyncEventSource
@abstract Creates async eventsource.
@discussion This method will create an async mach port, if one
has not already been created.
@param source Reference to CFRunLoopSourceRef that is created.
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncEventSource)(void * self,
CFRunLoopSourceRef * source);
/*! @function getAsyncEventSource
@abstract Gets the created async event source.
@result Returns a CFRunLoopSourceRef.
*/
CFRunLoopSourceRef (*getAsyncEventSource)(void * self);
/*! @function createAsyncPort
@abstract Creates an async port.
@discussion The port must be created before any callbacks can be used.
@param port Reference to mach port that is created.
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncPort)(void * self, mach_port_t * port);
/*! @function getAsyncPort
@abstract Gets the current async port.
@result Returns a mach_port_t.
*/
mach_port_t (*getAsyncPort)(void * self);
/*! @function open
@abstract Opens the device.
@param flags Flags to be passed down to the user client.
@result Returns an IOReturn code.
*/
IOReturn (*open)(void * self, UInt32 flags);
/*! @function close
@abstract Closes the device.
@result Returns an IOReturn code.
*/
IOReturn (*close)(void * self);
/*! @function setRemovalCallback
@abstract Sets callback to be used when device is removed.
@param removalCallback Called when the device is removed.
@param removeTarget Passed to the callback.
@param removalRefcon Passed to the callback.
@result Returns an IOReturn code.
*/
IOReturn (*setRemovalCallback)(void * self,
IOHIDCallbackFunction removalCallback,
void * removalTarget,
void * removalRefcon);
/*! @function getElementValue
@abstract Obtains the most recent value of an element.
@discussion This call is most useful for interrupt driven elements,
such as input type elements. Since feature type element values
need to be polled from the device, it is recommended to use the
queryElementValue method to obtain the current value. The
timestamp field in the event details the last time the element
value was altered.
@param elementCookie The element of interest.
@param valueEvent The event that will be filled. If a long value is
present, it is up to the caller to deallocate it.
@result Returns an IOReturn code.
*/
IOReturn (*getElementValue)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * valueEvent);
/*! @function setElementValue
@abstract Sets an element value on the device.
@discussion This call is most useful for feature type elements. It is
recommended to use IOOutputTransaction for output type elements.
@param elementCookie The element of interest.
@param valueEvent The event that will be filled. If a long value is
present, it will be copied.
@param timeoutMS UNSUPPORTED.
@param callback UNSUPPORTED.
@param callbackTarget UNSUPPORTED.
@param callbackRefcon UNSUPPORTED.
@result Returns an IOReturn code.
*/
IOReturn (*setElementValue)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * valueEvent,
UInt32 timeoutMS,
IOHIDElementCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
/*! @function queryElementValue
@abstract Obtains the current value of an element.
@discussion This call is most useful for feature type elements. This
method will poll the device for the current element value.
@param elementCookie The element of interest.
@param valueEvent The event that will be filled. If a long value is
present, it is up to the caller to deallocate it.
@param timeoutMS UNSUPPORTED.
@param callback UNSUPPORTED.
@param callbackTarget UNSUPPORTED.
@param callbackRefcon UNSUPPORTED.
@result Returns an IOReturn code.
*/
IOReturn (*queryElementValue)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * valueEvent,
UInt32 timeoutMS,
IOHIDElementCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
/*! @function startAllQueues
@abstract Starts data delivery on all queues for this device.
@result Returns an IOReturn code.
*/
IOReturn (*startAllQueues)(void * self);
/*! @function stopAllQueues
@abstract Stops data delivery on all queues for this device.
@result Returns an IOReturn code.
*/
IOReturn (*stopAllQueues)(void * self);
/*! @function allocQueue
@abstract Wrapper to return instances of the IOHIDQueueInterface.
@result Returns the created IOHIDQueueInterface.
*/
IOHIDQueueInterface ** (*allocQueue) (void *self);
/*! @function allocOutputTransaction
@abstract Wrapper to return instances of the IOHIDOutputTransactionInterface.
@result Returns the created IOHIDOutputTransactionInterface.
*/
IOHIDOutputTransactionInterface ** (*allocOutputTransaction) (void *self);
} IOHIDDeviceInterface;
/*! @class IOHIDDeviceInterface121
@discussion CFPlugin object subclass which provides the primary interface to
HID devices. This class is a subclass of IOHIDDeviceInterface.
*/
typedef struct IOHIDDeviceInterface121
{
IUNKNOWN_C_GUTS;
IOHIDDEVICEINTERFACE_FUNCS_100;
/*! @function setReport
@abstract Sends a report to the device.
@param reportType The report type.
@param reportID The report id.
@param reportBuffer Pointer to a preallocated buffer.
@param reportBufferSize Size of the reportBuffer in bytes.
@param timeoutMS
@param callback If null, this method will behave synchronously.
@param callbackTarget The callback target passed to the callback.
@param callbackRefcon The callback refcon passed to the callback.
@result Returns an IOReturn code.
*/
IOReturn (*setReport) (void * self,
IOHIDReportType reportType,
UInt32 reportID,
void * reportBuffer,
UInt32 reportBufferSize,
UInt32 timeoutMS,
IOHIDReportCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
/*! @function getReport
@abstract Obtains a report from the device.
@param reportType The report type.
@param reportID The report ID.
@param reportBuffer Pointer to a preallocated buffer.
@param reportBufferSize Size of the reportBuffer in bytes.
When finished, will contain the actual size of the report.
@param timeoutMS
@param callback If null, this method will behave synchronously.
@param callbackTarget The callback target passed to the callback.
@param callbackRefcon The callback refcon passed to the callback.
@result Returns an IOReturn code.
*/
IOReturn (*getReport) (void * self,
IOHIDReportType reportType,
UInt32 reportID,
void * reportBuffer,
UInt32 * reportBufferSize,
UInt32 timeoutMS,
IOHIDReportCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
}IOHIDDeviceInterface121;
/*! @class IOHIDDeviceInterface122
@discussion CFPlugin object subclass which provides the primary interface to
HID devices. This class is a subclass of IOHIDDeviceInterface121.
*/
typedef struct IOHIDDeviceInterface122
{
IUNKNOWN_C_GUTS;
IOHIDDEVICEINTERFACE_FUNCS_100;
IOHIDDEVICEINTERFACE_FUNCS_121;
/*! @function copyMatchingElements
@abstract Obtains specific elements defined by the device.
@discussion Using keys defined in IOHIDKeys.h for elements, create a
matching dictonary containing items that you wish to search for.
A null array indicates that no elements matching that criteria
were found. Each item in the array is a reference to the same
dictionary item that represents each element in the I/O Registry.
It is up to the caller to release the returned array of elements.
@param matchingDict Dictionary containg key/value pairs to match on. Pass
a null value to match on all elements.
@param elements Pointer to a CFArrayRef that will be returned by this
method. It is up to the caller to release it when finished.
@result Returns an IOReturn code.
*/
IOReturn (*copyMatchingElements)(void * self,
CFDictionaryRef matchingDict,
CFArrayRef * elements);
/*! @function setInterruptReportHandlerCallback
@abstract Sets the report handler callout to be called when the data
is received from the Interrupt-In pipe.
@discussion In order for this to work correctly, you must call
createAsyncPort and createAsyncEventSource.
@param reportBuffer Pointer to a preallocated buffer.
@param reportBufferSize Size of the reportBuffer in bytes.
@param callback If non-NULL, is a callback to be called when data
is received from the device.
@param callbackTarget The callback target passed to the callback
@param callbackRefcon The callback refcon passed to the callback.
@result Returns an IOReturn code.
*/
IOReturn (*setInterruptReportHandlerCallback)(
void * self,
void * reportBuffer,
UInt32 reportBufferSize,
IOHIDReportCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
}IOHIDDeviceInterface122;
/*! @class IOHIDQueueInterface
@discussion CFPlugin object subclass which provides an interface for input
queues from HID devices. Created by an IOHIDDeviceInterface
object.
*/
typedef struct IOHIDQueueInterface
{
IUNKNOWN_C_GUTS;
/*! @function createAsyncEventSource
@abstract Creates an async event source.
@discussion This will be used with setEventCallout.
@param source The newly created event source.
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncEventSource)(void * self,
CFRunLoopSourceRef * source);
/*! @function getAsyncEventSource
@abstract Obtains the current event source.
@result Returns a CFRunLoopSourceRef.
*/
CFRunLoopSourceRef (*getAsyncEventSource)(void * self);
/*! @function createAsyncPort
@abstract Creates an async port.
@discussion This will be used with createAsyncEventSource.
@param port The newly created async port.
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncPort)(void * self, mach_port_t * port);
/*! @function getAsyncPort
@abstract Obtains the current async port.
@result Returns a mach_port_t.
*/
mach_port_t (*getAsyncPort)(void * self);
/*! @function create
@abstract Creates the current queue.
@param flags
@param depth The maximum number of elements in the queue
before the oldest elements in the queue begin to be lost.
@result Returns an IOReturn code.
*/
IOReturn (*create)(void * self,
UInt32 flags,
UInt32 depth);
/*! @function create
@abstract Disposes of the current queue.
@result Returns an IOReturn code.
*/
IOReturn (*dispose)(void * self);
/*! @function addElement
@abstract Adds an element to the queue.
@discussion If the element has already been added to queue,
an error will be returned.
@param elementCookie The element of interest.
@param flags
@result Returns an IOReturn code.
*/
IOReturn (*addElement)(void * self,
IOHIDElementCookie elementCookie,
UInt32 flags);
/*! @function removeElement
@abstract Removes an element from the queue.
@discussion If the element has not been added to queue,
an error will be returned.
@param elementCookie The element of interest.
@result Returns an IOReturn code.
*/
IOReturn (*removeElement)(void * self, IOHIDElementCookie elementCookie);
/*! @function hasElement
@abstract Checks whether an element has been added to
the queue.
@discussion Will return true if present, otherwise will return false.
@param elementCookie The element of interest.
@result Returns a Boolean value.
*/
Boolean (*hasElement)(void * self, IOHIDElementCookie elementCookie);
/*! @function start
@abstract Starts event delivery to the queue.
@result Returns an IOReturn code.
*/
IOReturn (*start)(void * self);
/*! @function stop
@abstract Stops event delivery to the queue.
@result Returns an IOReturn code.
*/
IOReturn (*stop)(void * self);
/*! @function getNextEvent
@abstract Reads next event from the queue.
@param event The event that will be filled. If a long value is
present, it is up to the caller to deallocate it.
@param maxtime UNSUPPORTED. If non-zero, limits read events to
those that occured on or before maxTime.
@param timoutMS UNSUPPORTED. The timeout in milliseconds, a zero
timeout will cause this call to be non-blocking (returning
queue empty) if there is a NULL callback, and blocking forever
until the queue is non-empty if there is a valid callback.
@result Returns an IOReturn code.
*/
IOReturn (*getNextEvent)(void * self,
IOHIDEventStruct * event,
AbsoluteTime maxTime,
UInt32 timeoutMS);
/*! @function setEventCallout
@abstract Sets the event callout to be called when the queue
transitions to non-empty.
@discussion In order for this to work correctly, you must call
createAsyncPort and createAsyncEventSource.
@param callback if non-NULL is a callback to be called when data
is inserted to the queue
@param callbackTarget The callback target passed to the callback
@param callbackRefcon The callback refcon passed to the callback.
@result Returns an IOReturn code.
*/
IOReturn (*setEventCallout)(void * self,
IOHIDCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
/*! @function getEventCallout
@abstract Gets the event callout.
@discussion This callback will be called the queue transitions
to non-empty.
@param callback if non-NULL is a callback to be called when data
is inserted to the queue
@param callbackTarget The callback target passed to the callback
@param callbackRefcon The callback refcon passed to the callback
@result Returns an IOReturn code.
*/
IOReturn (*getEventCallout)(void * self,
IOHIDCallbackFunction * outCallback,
void ** outCallbackTarget,
void ** outCallbackRefcon);
} IOHIDQueueInterface;
/*! @class IOHIDOutputTransactionInterface
@discussion CFPlugin object subclass which privides interface for output
transactions to HID devices. Created by a IOHIDDeviceInterface
object. */
typedef struct IOHIDOutputTransactionInterface
{
IUNKNOWN_C_GUTS;
/*! @function createAsyncEventSource
@abstract Creates an async event source.
@discussion This will be used with setEventCallout.
@param source The newly created event source
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncEventSource)(void * self,
CFRunLoopSourceRef * source);
/*! @function getAsyncEventSource
@abstract Obtains the current event source.
@result Returns a CFRunLoopSourceRef.
*/
CFRunLoopSourceRef (*getAsyncEventSource)(void * self);
/*! @function createAsyncPort
@abstract Creates an async port.
@discussion This will be used with createAsyncEventSource.
@param port The newly created async port.
@result Returns an IOReturn code.
*/
IOReturn (*createAsyncPort)(void * self, mach_port_t * port);
/*! @function getAsyncPort
@abstract Obtains the current async port.
@result Returns a mach_port_t.
*/
mach_port_t (*getAsyncPort)(void * self);
/*! @function create
@abstract Creates the current transaction.
@discussion This method will free any memory that has been
allocated for this transaction.
@result Returns an IOReturn code.
*/
IOReturn (*create)(void * self);
/*! @function dispose
@abstract Disposes of the current transaction.
@discussion The transaction will have to be recreated, in order
to perform any operations on the transaction.
@result Returns an IOReturn code.
*/
IOReturn (*dispose)(void * self);
/*! @function addElement
@abstract Adds an element to the transaction.
@discussion If the element has already been added to transaction,
an error will be returned.
@param elementCookie The element of interest.
@result Returns an IOReturn code.
*/
IOReturn (*addElement) (void * self, IOHIDElementCookie elementCookie);
/*! @function removeElement
@abstract Removes an element from the transaction.
@discussion If the element has not been added to transaction,
an error will be returned.
@param elementCookie The element of interest.
@result Returns an IOReturn code.
*/
IOReturn (*removeElement) (void * self, IOHIDElementCookie elementCookie);
/*! @function hasElement
@abstract Checks whether an element has been added to
the transaction.
@discussion Will return true if present, otherwise will return false.
@param elementCookie The element of interest.
@result Returns a Boolean value.
*/
Boolean (*hasElement) (void * self, IOHIDElementCookie elementCookie);
/*! @function setElementDefault
@abstract Sets the default value of an element in a
transaction.
@discussion An error will be returned if the element has not been
added to the transaction.
@param elementCookie The element of interest.
@param valueEvent The event that will be filled. If a long value is
present, it will be copied.
@result Returns an IOReturn code.
*/
IOReturn (*setElementDefault)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * valueEvent);
/*! @function getElementDefault
@abstract Obtains the default value of an element in a
transaction.
@discussion An error will be returned if the element has not been
added to the transaction.
@param elementCookie The element of interest.
@param outValueEvent The event that will be filled. If a long value is
present, it is up to the caller to deallocate it.
@result Returns an IOReturn code.
*/
IOReturn (*getElementDefault)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * outValueEvent);
/*! @function setElementValue
@abstract Sets the value of an element in a transaction.
@discussion An error will be returned if the element has not been
added to the transaction.
@param elementCookie The element of interest.
@param valueEvent The event that will be filled. If a long value is
present, it will be copied.
@result Returns an IOReturn code.
*/
IOReturn (*setElementValue)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * valueEvent);
/*! @function getElementValue
@abstract Obtains the value of an element in a transaction.
@discussion An error will be returned if the element has not been
added to the transaction.
@param elementCookie The element of interest.
@param outValueEvent The event that will be filled. If a long value is
present, it is up to the caller to deallocate it.
@result Returns an IOReturn code.
*/
IOReturn (*getElementValue)(void * self,
IOHIDElementCookie elementCookie,
IOHIDEventStruct * outValueEvent);
/*! @function commit
@abstract Commits the transaction.
@discussion Transaction element values, if set, will be sent to the
device. Otherwise, the default element value will be used. If
neither are set, that element will be omitted from the commit.
After a transaction is committed, transaction element values
will be cleared. Default values will be preserved.
@param timeoutMS UNSUPPORTED
@param callback UNSUPPORTED
@param callbackTarget UNSUPPORTED
@param callbackRefcon UNSUPPORTED
@result Returns an IOReturn code.
*/
IOReturn (*commit)(void * self,
UInt32 timeoutMS,
IOHIDCallbackFunction callback,
void * callbackTarget,
void * callbackRefcon);
/*! @function clear
@abstract Clears the transaction.
@discussion Transaction element values will cleared. Default
values will be preserved.
@result Returns an IOReturn code.
*/
IOReturn (*clear)(void * self);
} IOHIDOutputTransactionInterface;
#endif
__END_DECLS
#endif /* !_IOKIT_HID_IOHIDLIB_H_ */

View File

@@ -0,0 +1,851 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_IOKIT
/* SDL joystick driver for Darwin / Mac OS X, based on the IOKit HID API */
/* Written 2001 by Max Horn */
#include <unistd.h>
#include <ctype.h>
#include <sysexits.h>
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/IOCFPlugIn.h>
#ifdef MACOS_10_0_4
#include <IOKit/hidsystem/IOHIDUsageTables.h>
#else
/* The header was moved here in Mac OS X 10.1 */
#include <Kernel/IOKit/hidsystem/IOHIDUsageTables.h>
#endif
#if MAC_OS_X_VERSION_MIN_REQUIRED == 1030
#include "10.3.9-FIX/IOHIDLib.h"
#else
#include <IOKit/hid/IOHIDLib.h>
#endif
#include <IOKit/hid/IOHIDKeys.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Carbon/Carbon.h> /* for NewPtrClear, DisposePtr */
/* For force feedback testing. */
#include <ForceFeedback/ForceFeedback.h>
#include <ForceFeedback/ForceFeedbackConstants.h>
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#include "SDL_sysjoystick_c.h"
/* Linked list of all available devices */
static recDevice *gpDeviceList = NULL;
static void
HIDReportErrorNum(char *strError, long numError)
{
SDL_SetError(strError);
}
static void HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
recDevice * pDevice);
/* returns current value for element, polling element
* will return 0 on error conditions which should be accounted for by application
*/
static SInt32
HIDGetElementValue(recDevice * pDevice, recElement * pElement)
{
IOReturn result = kIOReturnSuccess;
IOHIDEventStruct hidEvent;
hidEvent.value = 0;
if (NULL != pDevice && NULL != pElement && NULL != pDevice->interface) {
result =
(*(pDevice->interface))->getElementValue(pDevice->interface,
pElement->cookie,
&hidEvent);
if (kIOReturnSuccess == result) {
/* record min and max for auto calibration */
if (hidEvent.value < pElement->minReport)
pElement->minReport = hidEvent.value;
if (hidEvent.value > pElement->maxReport)
pElement->maxReport = hidEvent.value;
}
}
/* auto user scale */
return hidEvent.value;
}
static SInt32
HIDScaledCalibratedValue(recDevice * pDevice, recElement * pElement,
long min, long max)
{
float deviceScale = max - min;
float readScale = pElement->maxReport - pElement->minReport;
SInt32 value = HIDGetElementValue(pDevice, pElement);
if (readScale == 0)
return value; /* no scaling at all */
else
return ((value - pElement->minReport) * deviceScale / readScale) +
min;
}
static void
HIDRemovalCallback(void *target, IOReturn result, void *refcon, void *sender)
{
recDevice *device = (recDevice *) refcon;
device->removed = 1;
device->uncentered = 1;
}
/* Create and open an interface to device, required prior to extracting values or building queues.
* Note: appliction now owns the device and must close and release it prior to exiting
*/
static IOReturn
HIDCreateOpenDeviceInterface(io_object_t hidDevice, recDevice * pDevice)
{
IOReturn result = kIOReturnSuccess;
HRESULT plugInResult = S_OK;
SInt32 score = 0;
IOCFPlugInInterface **ppPlugInInterface = NULL;
if (NULL == pDevice->interface) {
result =
IOCreatePlugInInterfaceForService(hidDevice,
kIOHIDDeviceUserClientTypeID,
kIOCFPlugInInterfaceID,
&ppPlugInInterface, &score);
if (kIOReturnSuccess == result) {
/* Call a method of the intermediate plug-in to create the device interface */
plugInResult =
(*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
CFUUIDGetUUIDBytes
(kIOHIDDeviceInterfaceID),
(void *)
&(pDevice->interface));
if (S_OK != plugInResult)
HIDReportErrorNum
("CouldnÕt query HID class device interface from plugInInterface",
plugInResult);
(*ppPlugInInterface)->Release(ppPlugInInterface);
} else
HIDReportErrorNum
("Failed to create **plugInInterface via IOCreatePlugInInterfaceForService.",
result);
}
if (NULL != pDevice->interface) {
result = (*(pDevice->interface))->open(pDevice->interface, 0);
if (kIOReturnSuccess != result)
HIDReportErrorNum
("Failed to open pDevice->interface via open.", result);
else
(*(pDevice->interface))->setRemovalCallback(pDevice->interface,
HIDRemovalCallback,
pDevice, pDevice);
}
return result;
}
/* Closes and releases interface to device, should be done prior to exting application
* Note: will have no affect if device or interface do not exist
* application will "own" the device if interface is not closed
* (device may have to be plug and re-plugged in different location to get it working again without a restart)
*/
static IOReturn
HIDCloseReleaseInterface(recDevice * pDevice)
{
IOReturn result = kIOReturnSuccess;
if ((NULL != pDevice) && (NULL != pDevice->interface)) {
/* close the interface */
result = (*(pDevice->interface))->close(pDevice->interface);
if (kIOReturnNotOpen == result) {
/* do nothing as device was not opened, thus can't be closed */
} else if (kIOReturnSuccess != result)
HIDReportErrorNum("Failed to close IOHIDDeviceInterface.",
result);
/* release the interface */
result = (*(pDevice->interface))->Release(pDevice->interface);
if (kIOReturnSuccess != result)
HIDReportErrorNum("Failed to release IOHIDDeviceInterface.",
result);
pDevice->interface = NULL;
}
return result;
}
/* extracts actual specific element information from each element CF dictionary entry */
static void
HIDGetElementInfo(CFTypeRef refElement, recElement * pElement)
{
long number;
CFTypeRef refType;
refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementCookieKey));
if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
pElement->cookie = (IOHIDElementCookie) number;
refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMinKey));
if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
pElement->minReport = pElement->min = number;
pElement->maxReport = pElement->min;
refType = CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementMaxKey));
if (refType && CFNumberGetValue(refType, kCFNumberLongType, &number))
pElement->maxReport = pElement->max = number;
/*
TODO: maybe should handle the following stuff somehow?
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMinKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMin = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementScaledMaxKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->scaledMax = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementSizeKey));
if (refType && CFNumberGetValue (refType, kCFNumberLongType, &number))
pElement->size = number;
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsRelativeKey));
if (refType)
pElement->relative = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsWrappingKey));
if (refType)
pElement->wrapping = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementIsNonLinearKey));
if (refType)
pElement->nonLinear = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasPreferedStateKey));
if (refType)
pElement->preferredState = CFBooleanGetValue (refType);
refType = CFDictionaryGetValue (refElement, CFSTR(kIOHIDElementHasNullStateKey));
if (refType)
pElement->nullState = CFBooleanGetValue (refType);
*/
}
/* examines CF dictionary vlaue in device element hierarchy to determine if it is element of interest or a collection of more elements
* if element of interest allocate storage, add to list and retrieve element specific info
* if collection then pass on to deconstruction collection into additional individual elements
*/
static void
HIDAddElement(CFTypeRef refElement, recDevice * pDevice)
{
recElement *element = NULL;
recElement **headElement = NULL;
long elementType, usagePage, usage;
CFTypeRef refElementType =
CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementTypeKey));
CFTypeRef refUsagePage =
CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsagePageKey));
CFTypeRef refUsage =
CFDictionaryGetValue(refElement, CFSTR(kIOHIDElementUsageKey));
if ((refElementType)
&&
(CFNumberGetValue(refElementType, kCFNumberLongType, &elementType))) {
/* look at types of interest */
if ((elementType == kIOHIDElementTypeInput_Misc)
|| (elementType == kIOHIDElementTypeInput_Button)
|| (elementType == kIOHIDElementTypeInput_Axis)) {
if (refUsagePage
&& CFNumberGetValue(refUsagePage, kCFNumberLongType,
&usagePage) && refUsage
&& CFNumberGetValue(refUsage, kCFNumberLongType, &usage)) {
switch (usagePage) { /* only interested in kHIDPage_GenericDesktop and kHIDPage_Button */
case kHIDPage_GenericDesktop:
{
switch (usage) { /* look at usage to determine function */
case kHIDUsage_GD_X:
case kHIDUsage_GD_Y:
case kHIDUsage_GD_Z:
case kHIDUsage_GD_Rx:
case kHIDUsage_GD_Ry:
case kHIDUsage_GD_Rz:
case kHIDUsage_GD_Slider:
case kHIDUsage_GD_Dial:
case kHIDUsage_GD_Wheel:
element = (recElement *)
NewPtrClear(sizeof(recElement));
if (element) {
pDevice->axes++;
headElement = &(pDevice->firstAxis);
}
break;
case kHIDUsage_GD_Hatswitch:
element = (recElement *)
NewPtrClear(sizeof(recElement));
if (element) {
pDevice->hats++;
headElement = &(pDevice->firstHat);
}
break;
}
}
break;
case kHIDPage_Button:
element = (recElement *)
NewPtrClear(sizeof(recElement));
if (element) {
pDevice->buttons++;
headElement = &(pDevice->firstButton);
}
break;
default:
break;
}
}
} else if (kIOHIDElementTypeCollection == elementType)
HIDGetCollectionElements((CFMutableDictionaryRef) refElement,
pDevice);
}
if (element && headElement) { /* add to list */
recElement *elementPrevious = NULL;
recElement *elementCurrent = *headElement;
while (elementCurrent && usage >= elementCurrent->usage) {
elementPrevious = elementCurrent;
elementCurrent = elementCurrent->pNext;
}
if (elementPrevious) {
elementPrevious->pNext = element;
} else {
*headElement = element;
}
element->usagePage = usagePage;
element->usage = usage;
element->pNext = elementCurrent;
HIDGetElementInfo(refElement, element);
pDevice->elements++;
}
}
/* collects information from each array member in device element list (each array memeber = element) */
static void
HIDGetElementsCFArrayHandler(const void *value, void *parameter)
{
if (CFGetTypeID(value) == CFDictionaryGetTypeID())
HIDAddElement((CFTypeRef) value, (recDevice *) parameter);
}
/* handles retrieval of element information from arrays of elements in device IO registry information */
static void
HIDGetElements(CFTypeRef refElementCurrent, recDevice * pDevice)
{
CFTypeID type = CFGetTypeID(refElementCurrent);
if (type == CFArrayGetTypeID()) { /* if element is an array */
CFRange range = { 0, CFArrayGetCount(refElementCurrent) };
/* CountElementsCFArrayHandler called for each array member */
CFArrayApplyFunction(refElementCurrent, range,
HIDGetElementsCFArrayHandler, pDevice);
}
}
/* handles extracting element information from element collection CF types
* used from top level element decoding and hierarchy deconstruction to flatten device element list
*/
static void
HIDGetCollectionElements(CFMutableDictionaryRef deviceProperties,
recDevice * pDevice)
{
CFTypeRef refElementTop =
CFDictionaryGetValue(deviceProperties, CFSTR(kIOHIDElementKey));
if (refElementTop)
HIDGetElements(refElementTop, pDevice);
}
/* use top level element usage page and usage to discern device usage page and usage setting appropriate vlaues in device record */
static void
HIDTopLevelElementHandler(const void *value, void *parameter)
{
CFTypeRef refCF = 0;
if (CFGetTypeID(value) != CFDictionaryGetTypeID())
return;
refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsagePageKey));
if (!CFNumberGetValue
(refCF, kCFNumberLongType, &((recDevice *) parameter)->usagePage))
SDL_SetError("CFNumberGetValue error retrieving pDevice->usagePage.");
refCF = CFDictionaryGetValue(value, CFSTR(kIOHIDElementUsageKey));
if (!CFNumberGetValue
(refCF, kCFNumberLongType, &((recDevice *) parameter)->usage))
SDL_SetError("CFNumberGetValue error retrieving pDevice->usage.");
}
/* extracts device info from CF dictionary records in IO registry */
static void
HIDGetDeviceInfo(io_object_t hidDevice, CFMutableDictionaryRef hidProperties,
recDevice * pDevice)
{
CFMutableDictionaryRef usbProperties = 0;
io_registry_entry_t parent1, parent2;
/* Mac OS X currently is not mirroring all USB properties to HID page so need to look at USB device page also
* get dictionary for usb properties: step up two levels and get CF dictionary for USB properties
*/
if ((KERN_SUCCESS ==
IORegistryEntryGetParentEntry(hidDevice, kIOServicePlane, &parent1))
&& (KERN_SUCCESS ==
IORegistryEntryGetParentEntry(parent1, kIOServicePlane, &parent2))
&& (KERN_SUCCESS ==
IORegistryEntryCreateCFProperties(parent2, &usbProperties,
kCFAllocatorDefault,
kNilOptions))) {
if (usbProperties) {
CFTypeRef refCF = 0;
/* get device info
* try hid dictionary first, if fail then go to usb dictionary
*/
/* get product name */
refCF =
CFDictionaryGetValue(hidProperties, CFSTR(kIOHIDProductKey));
if (!refCF)
refCF =
CFDictionaryGetValue(usbProperties,
CFSTR("USB Product Name"));
if (refCF) {
if (!CFStringGetCString
(refCF, pDevice->product, 256,
CFStringGetSystemEncoding()))
SDL_SetError
("CFStringGetCString error retrieving pDevice->product.");
}
/* get usage page and usage */
refCF =
CFDictionaryGetValue(hidProperties,
CFSTR(kIOHIDPrimaryUsagePageKey));
if (refCF) {
if (!CFNumberGetValue
(refCF, kCFNumberLongType, &pDevice->usagePage))
SDL_SetError
("CFNumberGetValue error retrieving pDevice->usagePage.");
refCF =
CFDictionaryGetValue(hidProperties,
CFSTR(kIOHIDPrimaryUsageKey));
if (refCF)
if (!CFNumberGetValue
(refCF, kCFNumberLongType, &pDevice->usage))
SDL_SetError
("CFNumberGetValue error retrieving pDevice->usage.");
}
if (NULL == refCF) { /* get top level element HID usage page or usage */
/* use top level element instead */
CFTypeRef refCFTopElement = 0;
refCFTopElement =
CFDictionaryGetValue(hidProperties,
CFSTR(kIOHIDElementKey));
{
/* refCFTopElement points to an array of element dictionaries */
CFRange range = { 0, CFArrayGetCount(refCFTopElement) };
CFArrayApplyFunction(refCFTopElement, range,
HIDTopLevelElementHandler, pDevice);
}
}
CFRelease(usbProperties);
} else
SDL_SetError
("IORegistryEntryCreateCFProperties failed to create usbProperties.");
if (kIOReturnSuccess != IOObjectRelease(parent2))
SDL_SetError("IOObjectRelease error with parent2.");
if (kIOReturnSuccess != IOObjectRelease(parent1))
SDL_SetError("IOObjectRelease error with parent1.");
}
}
static recDevice *
HIDBuildDevice(io_object_t hidDevice)
{
recDevice *pDevice = (recDevice *) NewPtrClear(sizeof(recDevice));
if (pDevice) {
/* get dictionary for HID properties */
CFMutableDictionaryRef hidProperties = 0;
kern_return_t result =
IORegistryEntryCreateCFProperties(hidDevice, &hidProperties,
kCFAllocatorDefault,
kNilOptions);
if ((result == KERN_SUCCESS) && hidProperties) {
/* create device interface */
result = HIDCreateOpenDeviceInterface(hidDevice, pDevice);
if (kIOReturnSuccess == result) {
HIDGetDeviceInfo(hidDevice, hidProperties, pDevice); /* hidDevice used to find parents in registry tree */
HIDGetCollectionElements(hidProperties, pDevice);
} else {
DisposePtr((Ptr) pDevice);
pDevice = NULL;
}
CFRelease(hidProperties);
} else {
DisposePtr((Ptr) pDevice);
pDevice = NULL;
}
}
return pDevice;
}
/* disposes of the element list associated with a device and the memory associated with the list
*/
static void
HIDDisposeElementList(recElement ** elementList)
{
recElement *pElement = *elementList;
while (pElement) {
recElement *pElementNext = pElement->pNext;
DisposePtr((Ptr) pElement);
pElement = pElementNext;
}
*elementList = NULL;
}
/* disposes of a single device, closing and releaseing interface, freeing memory fro device and elements, setting device pointer to NULL
* all your device no longer belong to us... (i.e., you do not 'own' the device anymore)
*/
static recDevice *
HIDDisposeDevice(recDevice ** ppDevice)
{
kern_return_t result = KERN_SUCCESS;
recDevice *pDeviceNext = NULL;
if (*ppDevice) {
/* save next device prior to disposing of this device */
pDeviceNext = (*ppDevice)->pNext;
/* free posible io_service_t */
if ((*ppDevice)->ffservice) {
IOObjectRelease((*ppDevice)->ffservice);
(*ppDevice)->ffservice = 0;
}
/* free element lists */
HIDDisposeElementList(&(*ppDevice)->firstAxis);
HIDDisposeElementList(&(*ppDevice)->firstButton);
HIDDisposeElementList(&(*ppDevice)->firstHat);
result = HIDCloseReleaseInterface(*ppDevice); /* function sanity checks interface value (now application does not own device) */
if (kIOReturnSuccess != result)
HIDReportErrorNum
("HIDCloseReleaseInterface failed when trying to dipose device.",
result);
DisposePtr((Ptr) * ppDevice);
*ppDevice = NULL;
}
return pDeviceNext;
}
/* Function to scan the system for joysticks.
* Joystick 0 should be the system default joystick.
* This function should return the number of available joysticks, or -1
* on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
IOReturn result = kIOReturnSuccess;
mach_port_t masterPort = 0;
io_iterator_t hidObjectIterator = 0;
CFMutableDictionaryRef hidMatchDictionary = NULL;
recDevice *device, *lastDevice;
io_object_t ioHIDDeviceObject = 0;
SDL_numjoysticks = 0;
if (gpDeviceList) {
SDL_SetError("Joystick: Device list already inited.");
return -1;
}
result = IOMasterPort(bootstrap_port, &masterPort);
if (kIOReturnSuccess != result) {
SDL_SetError("Joystick: IOMasterPort error with bootstrap_port.");
return -1;
}
/* Set up a matching dictionary to search I/O Registry by class name for all HID class devices. */
hidMatchDictionary = IOServiceMatching(kIOHIDDeviceKey);
if (hidMatchDictionary) {
/* Add key for device type (joystick, in this case) to refine the matching dictionary. */
/* NOTE: we now perform this filtering later
UInt32 usagePage = kHIDPage_GenericDesktop;
UInt32 usage = kHIDUsage_GD_Joystick;
CFNumberRef refUsage = NULL, refUsagePage = NULL;
refUsage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usage);
CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsageKey), refUsage);
refUsagePage = CFNumberCreate (kCFAllocatorDefault, kCFNumberIntType, &usagePage);
CFDictionarySetValue (hidMatchDictionary, CFSTR (kIOHIDPrimaryUsagePageKey), refUsagePage);
*/
} else {
SDL_SetError
("Joystick: Failed to get HID CFMutableDictionaryRef via IOServiceMatching.");
return -1;
}
/*/ Now search I/O Registry for matching devices. */
result =
IOServiceGetMatchingServices(masterPort, hidMatchDictionary,
&hidObjectIterator);
/* Check for errors */
if (kIOReturnSuccess != result) {
SDL_SetError("Joystick: Couldn't create a HID object iterator.");
return -1;
}
if (!hidObjectIterator) { /* there are no joysticks */
gpDeviceList = NULL;
SDL_numjoysticks = 0;
return 0;
}
/* IOServiceGetMatchingServices consumes a reference to the dictionary, so we don't need to release the dictionary ref. */
/* build flat linked list of devices from device iterator */
gpDeviceList = lastDevice = NULL;
while ((ioHIDDeviceObject = IOIteratorNext(hidObjectIterator))) {
/* build a device record */
device = HIDBuildDevice(ioHIDDeviceObject);
if (!device)
continue;
/* Filter device list to non-keyboard/mouse stuff */
if ((device->usagePage != kHIDPage_GenericDesktop) ||
((device->usage != kHIDUsage_GD_Joystick &&
device->usage != kHIDUsage_GD_GamePad &&
device->usage != kHIDUsage_GD_MultiAxisController))) {
/* release memory for the device */
HIDDisposeDevice(&device);
DisposePtr((Ptr) device);
continue;
}
/* We have to do some storage of the io_service_t for
* SDL_HapticOpenFromJoystick */
if (FFIsForceFeedback(ioHIDDeviceObject) == FF_OK) {
device->ffservice = ioHIDDeviceObject;
} else {
device->ffservice = 0;
}
/* Add device to the end of the list */
if (lastDevice)
lastDevice->pNext = device;
else
gpDeviceList = device;
lastDevice = device;
}
result = IOObjectRelease(hidObjectIterator); /* release the iterator */
/* Count the total number of devices we found */
device = gpDeviceList;
while (device) {
SDL_numjoysticks++;
device = device->pNext;
}
return SDL_numjoysticks;
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
recDevice *device = gpDeviceList;
for (; index > 0; index--)
device = device->pNext;
return device->product;
}
/* Function to open a joystick for use.
* The joystick to open is specified by the index field of the joystick.
* This should fill the nbuttons and naxes fields of the joystick structure.
* It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
recDevice *device = gpDeviceList;
int index;
for (index = joystick->index; index > 0; index--)
device = device->pNext;
joystick->hwdata = device;
joystick->name = device->product;
joystick->naxes = device->axes;
joystick->nhats = device->hats;
joystick->nballs = 0;
joystick->nbuttons = device->buttons;
return 0;
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
recDevice *device = joystick->hwdata;
recElement *element;
SInt32 value, range;
int i;
if (device->removed) { /* device was unplugged; ignore it. */
if (device->uncentered) {
device->uncentered = 0;
/* Tell the app that everything is centered/unpressed... */
for (i = 0; i < device->axes; i++)
SDL_PrivateJoystickAxis(joystick, i, 0);
for (i = 0; i < device->buttons; i++)
SDL_PrivateJoystickButton(joystick, i, 0);
for (i = 0; i < device->hats; i++)
SDL_PrivateJoystickHat(joystick, i, SDL_HAT_CENTERED);
}
return;
}
element = device->firstAxis;
i = 0;
while (element) {
value = HIDScaledCalibratedValue(device, element, -32768, 32767);
if (value != joystick->axes[i])
SDL_PrivateJoystickAxis(joystick, i, value);
element = element->pNext;
++i;
}
element = device->firstButton;
i = 0;
while (element) {
value = HIDGetElementValue(device, element);
if (value > 1) /* handle pressure-sensitive buttons */
value = 1;
if (value != joystick->buttons[i])
SDL_PrivateJoystickButton(joystick, i, value);
element = element->pNext;
++i;
}
element = device->firstHat;
i = 0;
while (element) {
Uint8 pos = 0;
range = (element->max - element->min + 1);
value = HIDGetElementValue(device, element) - element->min;
if (range == 4) /* 4 position hatswitch - scale up value */
value *= 2;
else if (range != 8) /* Neither a 4 nor 8 positions - fall back to default position (centered) */
value = -1;
switch (value) {
case 0:
pos = SDL_HAT_UP;
break;
case 1:
pos = SDL_HAT_RIGHTUP;
break;
case 2:
pos = SDL_HAT_RIGHT;
break;
case 3:
pos = SDL_HAT_RIGHTDOWN;
break;
case 4:
pos = SDL_HAT_DOWN;
break;
case 5:
pos = SDL_HAT_LEFTDOWN;
break;
case 6:
pos = SDL_HAT_LEFT;
break;
case 7:
pos = SDL_HAT_LEFTUP;
break;
default:
/* Every other value is mapped to center. We do that because some
* joysticks use 8 and some 15 for this value, and apparently
* there are even more variants out there - so we try to be generous.
*/
pos = SDL_HAT_CENTERED;
break;
}
if (pos != joystick->hats[i])
SDL_PrivateJoystickHat(joystick, i, pos);
element = element->pNext;
++i;
}
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
/* Should we do anything here? */
return;
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
while (NULL != gpDeviceList)
gpDeviceList = HIDDisposeDevice(&gpDeviceList);
}
#endif /* SDL_JOYSTICK_IOKIT */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,88 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifndef SDL_JOYSTICK_IOKIT_H
#if MAC_OS_X_VERSION_MIN_REQUIRED == 1030
#include "10.3.9-FIX/IOHIDLib.h"
#else
#include <IOKit/hid/IOHIDLib.h>
#endif
#include <IOKit/hid/IOHIDKeys.h>
struct recElement
{
IOHIDElementCookie cookie; /* unique value which identifies element, will NOT change */
long usagePage, usage; /* HID usage */
long min; /* reported min value possible */
long max; /* reported max value possible */
#if 0
/* TODO: maybe should handle the following stuff somehow? */
long scaledMin; /* reported scaled min value possible */
long scaledMax; /* reported scaled max value possible */
long size; /* size in bits of data return from element */
Boolean relative; /* are reports relative to last report (deltas) */
Boolean wrapping; /* does element wrap around (one value higher than max is min) */
Boolean nonLinear; /* are the values reported non-linear relative to element movement */
Boolean preferredState; /* does element have a preferred state (such as a button) */
Boolean nullState; /* does element have null state */
#endif /* 0 */
/* runtime variables used for auto-calibration */
long minReport; /* min returned value */
long maxReport; /* max returned value */
struct recElement *pNext; /* next element in list */
};
typedef struct recElement recElement;
struct joystick_hwdata
{
io_service_t ffservice; /* Interface for force feedback, 0 = no ff */
IOHIDDeviceInterface **interface; /* interface to device, NULL = no interface */
char product[256]; /* name of product */
long usage; /* usage page from IOUSBHID Parser.h which defines general usage */
long usagePage; /* usage within above page from IOUSBHID Parser.h which defines specific usage */
long axes; /* number of axis (calculated, not reported by device) */
long buttons; /* number of buttons (calculated, not reported by device) */
long hats; /* number of hat switches (calculated, not reported by device) */
long elements; /* number of total elements (shouldbe total of above) (calculated, not reported by device) */
recElement *firstAxis;
recElement *firstButton;
recElement *firstHat;
int removed;
int uncentered;
struct joystick_hwdata *pNext; /* next device */
};
typedef struct joystick_hwdata recDevice;
#endif /* SDL_JOYSTICK_IOKIT_H */

View File

@@ -0,0 +1,91 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#if defined(SDL_JOYSTICK_DUMMY) || defined(SDL_JOYSTICK_DISABLED)
/* This is the system specific header for the SDL joystick API */
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
SDL_numjoysticks = 0;
return (0);
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
SDL_SetError("Logic error: No joysticks available");
return (NULL);
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
SDL_SetError("Logic error: No joysticks available");
return (-1);
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
return;
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
return;
}
#endif /* SDL_JOYSTICK_DUMMY || SDL_JOYSTICK_DISABLED */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,45 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#import <UIKit/UIKit.h>
#import <SDL_types.h>
/* *INDENT-OFF* */
@interface SDLUIAccelerationDelegate: NSObject <UIAccelerometerDelegate> {
UIAccelerationValue x, y, z;
BOOL isRunning;
BOOL hasNewData;
}
+(SDLUIAccelerationDelegate *)sharedDelegate;
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration;
-(void)getLastOrientation:(Sint16 *)data;
-(void)startup;
-(void)shutdown;
-(BOOL)isRunning;
-(BOOL)hasNewData;
-(void)setHasNewData:(BOOL)value;
@end
/* *INDENT-ON* */

View File

@@ -0,0 +1,142 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#import "SDLUIAccelerationDelegate.h"
/* needed for SDL_IPHONE_MAX_GFORCE macro */
#import "../../../include/SDL_config_iphoneos.h"
static SDLUIAccelerationDelegate *sharedDelegate=nil;
@implementation SDLUIAccelerationDelegate
/*
Returns a shared instance of the SDLUIAccelerationDelegate, creating the shared delegate if it doesn't exist yet.
*/
+(SDLUIAccelerationDelegate *)sharedDelegate {
if (sharedDelegate == nil) {
sharedDelegate = [[SDLUIAccelerationDelegate alloc] init];
}
return sharedDelegate;
}
/*
UIAccelerometerDelegate delegate method. Invoked by the UIAccelerometer instance when it has new data for us.
We just take the data and mark that we have new data available so that the joystick system will pump it to the
events system when SDL_SYS_JoystickUpdate is called.
*/
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
hasNewData = YES;
}
/*
getLastOrientation -- put last obtained accelerometer data into Sint16 array
Called from the joystick system when it needs the accelerometer data.
Function grabs the last data sent to the accelerometer and converts it
from floating point to Sint16, which is what the joystick system expects.
To do the conversion, the data is first clamped onto the interval
[-SDL_IPHONE_MAX_G_FORCE, SDL_IPHONE_MAX_G_FORCE], then the data is multiplied
by MAX_SINT16 so that it is mapped to the full range of an Sint16.
You can customize the clamped range of this function by modifying the
SDL_IPHONE_MAX_GFORCE macro in SDL_config_iphoneos.h.
Once converted to Sint16, the accelerometer data no longer has coherent units.
You can convert the data back to units of g-force by multiplying it
in your application's code by SDL_IPHONE_MAX_GFORCE / 0x7FFF.
*/
-(void)getLastOrientation:(Sint16 *)data {
#define MAX_SINT16 0x7FFF
/* clamp the data */
if (x > SDL_IPHONE_MAX_GFORCE) x = SDL_IPHONE_MAX_GFORCE;
else if (x < -SDL_IPHONE_MAX_GFORCE) x = -SDL_IPHONE_MAX_GFORCE;
if (y > SDL_IPHONE_MAX_GFORCE) y = SDL_IPHONE_MAX_GFORCE;
else if (y < -SDL_IPHONE_MAX_GFORCE) y = -SDL_IPHONE_MAX_GFORCE;
if (z > SDL_IPHONE_MAX_GFORCE) z = SDL_IPHONE_MAX_GFORCE;
else if (z < -SDL_IPHONE_MAX_GFORCE) z = -SDL_IPHONE_MAX_GFORCE;
/* pass in data mapped to range of SInt16 */
data[0] = (x / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[1] = (y / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
data[2] = (z / SDL_IPHONE_MAX_GFORCE) * MAX_SINT16;
}
/*
Initialize SDLUIAccelerationDelegate. Since we don't have any data yet,
just set our last received data to zero, and indicate we don't have any;
*/
-(id)init {
self = [super init];
x = y = z = 0.0;
hasNewData = NO;
return self;
}
-(void)dealloc {
sharedDelegate = nil;
[self shutdown];
[super dealloc];
}
/*
Lets our delegate start receiving accelerometer updates.
*/
-(void)startup {
[UIAccelerometer sharedAccelerometer].delegate = self;
isRunning = YES;
}
/*
Stops our delegate from receiving accelerometer updates.
*/
-(void)shutdown {
if ([UIAccelerometer sharedAccelerometer].delegate == self) {
[UIAccelerometer sharedAccelerometer].delegate = nil;
}
isRunning = NO;
}
/*
Our we currently receiving accelerometer updates?
*/
-(BOOL)isRunning {
return isRunning;
}
/*
Do we have any data that hasn't been pumped into SDL's event system?
*/
-(BOOL)hasNewData {
return hasNewData;
}
/*
When the joystick system grabs the new data, it sets this to NO.
*/
-(void)setHasNewData:(BOOL)value {
hasNewData = value;
}
@end

View File

@@ -0,0 +1,125 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* This is the system specific header for the SDL joystick API */
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#import "SDLUIAccelerationDelegate.h"
const char *accelerometerName = "iPhone accelerometer";
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
SDL_numjoysticks = 1;
return (1);
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
switch(index) {
case 0:
return accelerometerName;
default:
SDL_SetError("No joystick available with that index");
return NULL;
}
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
if (joystick->index == 0) {
joystick->naxes = 3;
joystick->nhats = 0;
joystick->nballs = 0;
joystick->nbuttons = 0;
joystick->name = accelerometerName;
[[SDLUIAccelerationDelegate sharedDelegate] startup];
return 0;
}
else {
SDL_SetError("No joystick available with that index");
return (-1);
}
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
Sint16 orientation[3];
if ([[SDLUIAccelerationDelegate sharedDelegate] hasNewData]) {
[[SDLUIAccelerationDelegate sharedDelegate] getLastOrientation: orientation];
[[SDLUIAccelerationDelegate sharedDelegate] setHasNewData: NO];
SDL_PrivateJoystickAxis(joystick, 0, orientation[0]);
SDL_PrivateJoystickAxis(joystick, 1, orientation[1]);
SDL_PrivateJoystickAxis(joystick, 2, orientation[2]);
}
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
if (joystick->index == 0 && [[SDLUIAccelerationDelegate sharedDelegate] isRunning]) {
[[SDLUIAccelerationDelegate sharedDelegate] shutdown];
}
SDL_SetError("No joystick open with that index");
return;
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
return;
}
/* vi: set ts=4 sw=4 expandtab: */

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,55 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#if SDL_INPUT_LINUXEV
#include <linux/input.h>
#endif
/* The private structure used to keep track of a joystick */
struct joystick_hwdata
{
int fd;
char *fname; /* Used in haptic subsystem */
/* The current linux joystick driver maps hats to two axes */
struct hwdata_hat
{
int axis[2];
} *hats;
/* The current linux joystick driver maps balls to two axes */
struct hwdata_ball
{
int axis[2];
} *balls;
/* Support for the Linux 2.4 unified input interface */
#if SDL_INPUT_LINUXEV
SDL_bool is_hid;
Uint8 key_map[KEY_MAX - BTN_MISC];
Uint8 abs_map[ABS_MAX];
struct axis_correct
{
int used;
int coef[3];
} abs_correct[ABS_MAX];
#endif
};

View File

@@ -0,0 +1,172 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_NDS
/* This is the system specific header for the SDL joystick API */
#include <nds.h>
#include <stdio.h> /* For the definition of NULL */
#include "SDL_error.h"
#include "SDL_events.h"
#include "SDL_joystick.h"
#include "SDL_sysjoystick.h"
#include "SDL_joystick_c.h"
#include "../../video/nds/SDL_ndsevents_c.h"
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
SDL_numjoysticks = 1;
return (1);
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
if (!index)
return "NDS builtin joypad";
SDL_SetError("No joystick available with that index");
return (NULL);
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
joystick->nbuttons = 8;
joystick->nhats = 0;
joystick->nballs = 0;
joystick->naxes = 2;
return 0;
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
u32 keysd, keysu;
int magnitude = 16384;
/*scanKeys(); - this is done in PumpEvents, because touch uses it too */
keysd = keysDown();
keysu = keysUp();
if ((keysd & KEY_UP)) {
SDL_PrivateJoystickAxis(joystick, 1, -magnitude);
}
if ((keysd & KEY_DOWN)) {
SDL_PrivateJoystickAxis(joystick, 1, magnitude);
}
if ((keysd & KEY_LEFT)) {
SDL_PrivateJoystickAxis(joystick, 0, -magnitude);
}
if ((keysd & KEY_RIGHT)) {
SDL_PrivateJoystickAxis(joystick, 0, magnitude);
}
if ((keysu & (KEY_UP | KEY_DOWN))) {
SDL_PrivateJoystickAxis(joystick, 1, 0);
}
if ((keysu & (KEY_LEFT | KEY_RIGHT))) {
SDL_PrivateJoystickAxis(joystick, 0, 0);
}
if ((keysd & KEY_A)) {
SDL_PrivateJoystickButton(joystick, 0, SDL_PRESSED);
}
if ((keysd & KEY_B)) {
SDL_PrivateJoystickButton(joystick, 1, SDL_PRESSED);
}
if ((keysd & KEY_X)) {
SDL_PrivateJoystickButton(joystick, 2, SDL_PRESSED);
}
if ((keysd & KEY_Y)) {
SDL_PrivateJoystickButton(joystick, 3, SDL_PRESSED);
}
if ((keysd & KEY_L)) {
SDL_PrivateJoystickButton(joystick, 4, SDL_PRESSED);
}
if ((keysd & KEY_R)) {
SDL_PrivateJoystickButton(joystick, 5, SDL_PRESSED);
}
if ((keysd & KEY_SELECT)) {
SDL_PrivateJoystickButton(joystick, 6, SDL_PRESSED);
}
if ((keysd & KEY_START)) {
SDL_PrivateJoystickButton(joystick, 7, SDL_PRESSED);
}
if ((keysu & KEY_A)) {
SDL_PrivateJoystickButton(joystick, 0, SDL_RELEASED);
}
if ((keysu & KEY_B)) {
SDL_PrivateJoystickButton(joystick, 1, SDL_RELEASED);
}
if ((keysu & KEY_X)) {
SDL_PrivateJoystickButton(joystick, 2, SDL_RELEASED);
}
if ((keysu & KEY_Y)) {
SDL_PrivateJoystickButton(joystick, 3, SDL_RELEASED);
}
if ((keysu & KEY_L)) {
SDL_PrivateJoystickButton(joystick, 4, SDL_RELEASED);
}
if ((keysu & KEY_R)) {
SDL_PrivateJoystickButton(joystick, 5, SDL_RELEASED);
}
if ((keysu & KEY_SELECT)) {
SDL_PrivateJoystickButton(joystick, 6, SDL_RELEASED);
}
if ((keysu & KEY_START)) {
SDL_PrivateJoystickButton(joystick, 7, SDL_RELEASED);
}
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
}
#endif /* SDL_JOYSTICK_NDS */

View File

@@ -0,0 +1,180 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_RISCOS
/*
RISC OS - Joystick support by Alan Buckley (alan_baa@hotmail.com) - 10 April 2003
Note: Currently assumes joystick is present if joystick module is loaded
and that there is one joystick with four buttons.
*/
/* This is the system specific header for the SDL joystick API */
#include "SDL_events.h"
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#include "kernel.h"
#define JOYSTICK_READ 0x43F40
struct joystick_hwdata
{
int joystate;
};
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return number of joysticks, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
_kernel_swi_regs regs;
/* Try to read joystick 0 */
regs.r[0] = 0;
if (_kernel_swi(JOYSTICK_READ, &regs, &regs) == NULL) {
/* Switch works so assume we've got a joystick */
return 1;
}
/* Switch fails so it looks like there's no joystick here */
return (0);
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
if (index == 0) {
return "RISC OS Joystick 0";
}
SDL_SetError("No joystick available with that index");
return (NULL);
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
_kernel_swi_regs regs;
if (!(joystick->hwdata = SDL_malloc(sizeof(struct joystick_hwdata))))
return -1;
regs.r[0] = joystick->index;
/* Don't know how to get exact count of buttons so assume max of 4 for now */
joystick->nbuttons = 4;
joystick->nhats = 0;
joystick->nballs = 0;
joystick->naxes = 2;
joystick->hwdata->joystate = 0;
return 0;
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
_kernel_swi_regs regs;
regs.r[0] = joystick->index;
if (_kernel_swi(JOYSTICK_READ, &regs, &regs) == NULL) {
int newstate = regs.r[0];
int oldstate = joystick->hwdata->joystate;
if (newstate != oldstate) {
if ((newstate & 0xFF) != (oldstate & 0xFF)) {
int y = regs.r[0] & 0xFF;
/* Convert to signed values */
if (y >= 128)
y -= 256;
SDL_PrivateJoystickAxis(joystick, 1, -y * 256); /* Up and down opposite to result in SDL */
}
if ((newstate & 0xFF00) != (oldstate & 0xFF00)) {
int x = (regs.r[0] & 0xFF00) >> 8;
if (x >= 128)
x -= 256;
SDL_PrivateJoystickAxis(joystick, 0, x * 256);
}
if ((newstate & 0xFF0000) != (oldstate & 0xFF0000)) {
int buttons = (regs.r[0] & 0xFF0000) >> 16;
int oldbuttons = (oldstate & 0xFF0000) >> 16;
int i;
for (i = 0; i < joystick->nbuttons; i++) {
if ((buttons & (1 << i)) != (oldbuttons & (1 << i))) {
if (buttons & (1 << i))
SDL_PrivateJoystickButton(joystick, i,
SDL_PRESSED);
else
SDL_PrivateJoystickButton(joystick, i,
SDL_RELEASED);
}
}
}
joystick->hwdata->joystate = newstate;
}
}
return;
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
if (joystick->hwdata)
SDL_free(joystick->hwdata);
return;
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
SDL_numjoysticks = 0;
return;
}
#endif /* SDL_JOYSTICK_RISCOS */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,802 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_DINPUT
/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de
* A. Formiga's WINMM driver.
*
* Hats and sliders are completely untested; the app I'm writing this for mostly
* doesn't use them and I don't own any joysticks with them.
*
* We don't bother to use event notification here. It doesn't seem to work
* with polled devices, and it's fine to call IDirectInputDevice2_GetDeviceData and
* let it return 0 events. */
#include "SDL_error.h"
#include "SDL_events.h"
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#define INITGUID /* Only set here, if set twice will cause mingw32 to break. */
#include "SDL_dxjoystick_c.h"
#ifndef DIDFT_OPTIONAL
#define DIDFT_OPTIONAL 0x80000000
#endif
#define INPUT_QSIZE 32 /* Buffer up to 32 input messages */
#define MAX_JOYSTICKS 8
#define AXIS_MIN -32768 /* minimum value for axis coordinate */
#define AXIS_MAX 32767 /* maximum value for axis coordinate */
#define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/100) /* 1% motion */
/* external variables referenced. */
extern HWND SDL_HelperWindow;
/* local variables */
static LPDIRECTINPUT dinput = NULL;
extern HRESULT(WINAPI * DInputCreate) (HINSTANCE hinst, DWORD dwVersion,
LPDIRECTINPUT * ppDI,
LPUNKNOWN punkOuter);
static DIDEVICEINSTANCE SYS_Joystick[MAX_JOYSTICKS]; /* array to hold joystick ID values */
static int SYS_NumJoysticks;
static HINSTANCE DInputDLL = NULL;
/* local prototypes */
static void SetDIerror(const char *function, HRESULT code);
static BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE *
pdidInstance, VOID * pContext);
static BOOL CALLBACK EnumDevObjectsCallback(LPCDIDEVICEOBJECTINSTANCE dev,
LPVOID pvRef);
static Uint8 TranslatePOV(DWORD value);
static int SDL_PrivateJoystickAxis_Int(SDL_Joystick * joystick, Uint8 axis,
Sint16 value);
static int SDL_PrivateJoystickHat_Int(SDL_Joystick * joystick, Uint8 hat,
Uint8 value);
static int SDL_PrivateJoystickButton_Int(SDL_Joystick * joystick,
Uint8 button, Uint8 state);
/* Taken from Wine - Thanks! */
DIOBJECTDATAFORMAT dfDIJoystick2[] = {
{ &GUID_XAxis,DIJOFS_X,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_YAxis,DIJOFS_Y,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_ZAxis,DIJOFS_Z,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RxAxis,DIJOFS_RX,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RyAxis,DIJOFS_RY,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RzAxis,DIJOFS_RZ,DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,DIJOFS_SLIDER(0),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,DIJOFS_SLIDER(1),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_POV,DIJOFS_POV(0),DIDFT_OPTIONAL|DIDFT_POV|DIDFT_ANYINSTANCE,0},
{ &GUID_POV,DIJOFS_POV(1),DIDFT_OPTIONAL|DIDFT_POV|DIDFT_ANYINSTANCE,0},
{ &GUID_POV,DIJOFS_POV(2),DIDFT_OPTIONAL|DIDFT_POV|DIDFT_ANYINSTANCE,0},
{ &GUID_POV,DIJOFS_POV(3),DIDFT_OPTIONAL|DIDFT_POV|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(0),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(1),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(2),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(3),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(4),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(5),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(6),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(7),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(8),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(9),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(10),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(11),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(12),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(13),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(14),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(15),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(16),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(17),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(18),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(19),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(20),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(21),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(22),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(23),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(24),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(25),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(26),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(27),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(28),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(29),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(30),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(31),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(32),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(33),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(34),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(35),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(36),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(37),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(38),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(39),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(40),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(41),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(42),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(43),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(44),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(45),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(46),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(47),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(48),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(49),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(50),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(51),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(52),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(53),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(54),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(55),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(56),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(57),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(58),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(59),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(60),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(61),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(62),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(63),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(64),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(65),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(66),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(67),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(68),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(69),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(70),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(71),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(72),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(73),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(74),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(75),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(76),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(77),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(78),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(79),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(80),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(81),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(82),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(83),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(84),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(85),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(86),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(87),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(88),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(89),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(90),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(91),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(92),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(93),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(94),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(95),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(96),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(97),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(98),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(99),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(100),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(101),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(102),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(103),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(104),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(105),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(106),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(107),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(108),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(109),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(110),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(111),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(112),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(113),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(114),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(115),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(116),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(117),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(118),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(119),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(120),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(121),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(122),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(123),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(124),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(125),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(126),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ NULL,DIJOFS_BUTTON(127),DIDFT_OPTIONAL|DIDFT_BUTTON|DIDFT_ANYINSTANCE,0},
{ &GUID_XAxis,FIELD_OFFSET(DIJOYSTATE2,lVX),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_YAxis,FIELD_OFFSET(DIJOYSTATE2,lVY),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_ZAxis,FIELD_OFFSET(DIJOYSTATE2,lVZ),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RxAxis,FIELD_OFFSET(DIJOYSTATE2,lVRx),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RyAxis,FIELD_OFFSET(DIJOYSTATE2,lVRy),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RzAxis,FIELD_OFFSET(DIJOYSTATE2,lVRz),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglVSlider[0]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglVSlider[1]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_XAxis,FIELD_OFFSET(DIJOYSTATE2,lAX),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_YAxis,FIELD_OFFSET(DIJOYSTATE2,lAY),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_ZAxis,FIELD_OFFSET(DIJOYSTATE2,lAZ),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RxAxis,FIELD_OFFSET(DIJOYSTATE2,lARx),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RyAxis,FIELD_OFFSET(DIJOYSTATE2,lARy),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RzAxis,FIELD_OFFSET(DIJOYSTATE2,lARz),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglASlider[0]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglASlider[1]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_XAxis,FIELD_OFFSET(DIJOYSTATE2,lFX),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_YAxis,FIELD_OFFSET(DIJOYSTATE2,lFY),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_ZAxis,FIELD_OFFSET(DIJOYSTATE2,lFZ),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RxAxis,FIELD_OFFSET(DIJOYSTATE2,lFRx),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RyAxis,FIELD_OFFSET(DIJOYSTATE2,lFRy),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_RzAxis,FIELD_OFFSET(DIJOYSTATE2,lFRz),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglFSlider[0]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
{ &GUID_Slider,FIELD_OFFSET(DIJOYSTATE2,rglFSlider[1]),DIDFT_OPTIONAL|DIDFT_AXIS|DIDFT_ANYINSTANCE,0},
};
const DIDATAFORMAT c_dfDIJoystick2 = {
sizeof(DIDATAFORMAT),
sizeof(DIOBJECTDATAFORMAT),
DIDF_ABSAXIS,
sizeof(DIJOYSTATE2),
SDL_arraysize(dfDIJoystick2),
dfDIJoystick2
};
/* Convert a DirectInput return code to a text message */
static void
SetDIerror(const char *function, HRESULT code)
{
/*
SDL_SetError("%s() [%s]: %s", function,
DXGetErrorString9A(code), DXGetErrorDescription9A(code));
*/
SDL_SetError("%s() DirectX error %d", function, code);
}
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
HRESULT result;
HINSTANCE instance;
SYS_NumJoysticks = 0;
result = CoInitialize(NULL);
if (FAILED(result)) {
SetDIerror("CoInitialize", result);
return (-1);
}
result = CoCreateInstance(&CLSID_DirectInput, NULL, CLSCTX_INPROC_SERVER,
&IID_IDirectInput, (LPVOID)&dinput);
if (FAILED(result)) {
SetDIerror("CoCreateInstance", result);
return (-1);
}
/* Because we used CoCreateInstance, we need to Initialize it, first. */
instance = GetModuleHandle(NULL);
if (instance == NULL) {
SDL_SetError("GetModuleHandle() failed with error code %d.",
GetLastError());
return (-1);
}
result = IDirectInput_Initialize(dinput, instance, DIRECTINPUT_VERSION);
if (FAILED(result)) {
SetDIerror("IDirectInput::Initialize", result);
return (-1);
}
/* Look for joysticks, wheels, head trackers, gamepads, etc.. */
result = IDirectInput_EnumDevices(dinput,
DIDEVTYPE_JOYSTICK,
EnumJoysticksCallback,
NULL, DIEDFL_ATTACHEDONLY);
return SYS_NumJoysticks;
}
static BOOL CALLBACK
EnumJoysticksCallback(const DIDEVICEINSTANCE * pdidInstance, VOID * pContext)
{
SDL_memcpy(&SYS_Joystick[SYS_NumJoysticks], pdidInstance,
sizeof(DIDEVICEINSTANCE));
SYS_NumJoysticks++;
if (SYS_NumJoysticks >= MAX_JOYSTICKS)
return DIENUM_STOP;
return DIENUM_CONTINUE;
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
/***-> test for invalid index ? */
return (SYS_Joystick[index].tszProductName);
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
HRESULT result;
LPDIRECTINPUTDEVICE device;
DIPROPDWORD dipdw;
SDL_memset(&dipdw, 0, sizeof(DIPROPDWORD));
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
/* allocate memory for system specific hardware data */
joystick->hwdata =
(struct joystick_hwdata *) SDL_malloc(sizeof(struct joystick_hwdata));
if (joystick->hwdata == NULL) {
SDL_OutOfMemory();
return (-1);
}
SDL_memset(joystick->hwdata, 0, sizeof(struct joystick_hwdata));
joystick->hwdata->buffered = 1;
joystick->hwdata->Capabilities.dwSize = sizeof(DIDEVCAPS);
result =
IDirectInput_CreateDevice(dinput,
&SYS_Joystick[joystick->index].
guidInstance, &device, NULL);
if (FAILED(result)) {
SetDIerror("IDirectInput::CreateDevice", result);
return (-1);
}
/* Now get the IDirectInputDevice2 interface, instead. */
result = IDirectInputDevice_QueryInterface(device,
&IID_IDirectInputDevice2,
(LPVOID *) & joystick->
hwdata->InputDevice);
/* We are done with this object. Use the stored one from now on. */
IDirectInputDevice_Release(device);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice::QueryInterface", result);
return (-1);
}
/* Aquire shared access. Exclusive access is required for forces,
* though. */
result =
IDirectInputDevice2_SetCooperativeLevel(joystick->hwdata->
InputDevice, SDL_HelperWindow,
DISCL_EXCLUSIVE |
DISCL_BACKGROUND);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::SetCooperativeLevel", result);
return (-1);
}
/* Use the extended data structure: DIJOYSTATE2. */
result =
IDirectInputDevice2_SetDataFormat(joystick->hwdata->InputDevice,
&c_dfDIJoystick2);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::SetDataFormat", result);
return (-1);
}
/* Get device capabilities */
result =
IDirectInputDevice2_GetCapabilities(joystick->hwdata->InputDevice,
&joystick->hwdata->Capabilities);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::GetCapabilities", result);
return (-1);
}
/* Force capable? */
if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) {
result = IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::Acquire", result);
return (-1);
}
/* reset all accuators. */
result =
IDirectInputDevice2_SendForceFeedbackCommand(joystick->hwdata->
InputDevice,
DISFFC_RESET);
/* Not necessarily supported, ignore if not supported.
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::SendForceFeedbackCommand",
result);
return (-1);
}
*/
result = IDirectInputDevice2_Unacquire(joystick->hwdata->InputDevice);
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::Unacquire", result);
return (-1);
}
/* Turn on auto-centering for a ForceFeedback device (until told
* otherwise). */
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = DIPROPAUTOCENTER_ON;
result =
IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice,
DIPROP_AUTOCENTER, &dipdw.diph);
/* Not necessarily supported, ignore if not supported.
if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::SetProperty", result);
return (-1);
}
*/
}
/* What buttons and axes does it have? */
IDirectInputDevice2_EnumObjects(joystick->hwdata->InputDevice,
EnumDevObjectsCallback, joystick,
DIDFT_BUTTON | DIDFT_AXIS | DIDFT_POV);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = INPUT_QSIZE;
/* Set the buffer size */
result =
IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice,
DIPROP_BUFFERSIZE, &dipdw.diph);
if (result == DI_POLLEDDEVICE) {
/* This device doesn't support buffering, so we're forced
* to use less reliable polling. */
joystick->hwdata->buffered = 0;
} else if (FAILED(result)) {
SetDIerror("IDirectInputDevice2::SetProperty", result);
return (-1);
}
return (0);
}
static BOOL CALLBACK
EnumDevObjectsCallback(LPCDIDEVICEOBJECTINSTANCE dev, LPVOID pvRef)
{
SDL_Joystick *joystick = (SDL_Joystick *) pvRef;
HRESULT result;
input_t *in = &joystick->hwdata->Inputs[joystick->hwdata->NumInputs];
in->ofs = dev->dwOfs;
if (dev->dwType & DIDFT_BUTTON) {
in->type = BUTTON;
in->num = joystick->nbuttons;
joystick->nbuttons++;
} else if (dev->dwType & DIDFT_POV) {
in->type = HAT;
in->num = joystick->nhats;
joystick->nhats++;
} else if (dev->dwType & DIDFT_AXIS) {
DIPROPRANGE diprg;
DIPROPDWORD dilong;
in->type = AXIS;
in->num = joystick->naxes;
diprg.diph.dwSize = sizeof(diprg);
diprg.diph.dwHeaderSize = sizeof(diprg.diph);
diprg.diph.dwObj = dev->dwOfs;
diprg.diph.dwHow = DIPH_BYOFFSET;
diprg.lMin = AXIS_MIN;
diprg.lMax = AXIS_MAX;
result =
IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice,
DIPROP_RANGE, &diprg.diph);
if (FAILED(result)) {
return DIENUM_CONTINUE; /* don't use this axis */
}
/* Set dead zone to 0. */
dilong.diph.dwSize = sizeof(dilong);
dilong.diph.dwHeaderSize = sizeof(dilong.diph);
dilong.diph.dwObj = dev->dwOfs;
dilong.diph.dwHow = DIPH_BYOFFSET;
dilong.dwData = 0;
result =
IDirectInputDevice2_SetProperty(joystick->hwdata->InputDevice,
DIPROP_DEADZONE, &dilong.diph);
if (FAILED(result)) {
return DIENUM_CONTINUE; /* don't use this axis */
}
joystick->naxes++;
} else {
/* not supported at this time */
return DIENUM_CONTINUE;
}
joystick->hwdata->NumInputs++;
if (joystick->hwdata->NumInputs == MAX_INPUTS) {
return DIENUM_STOP; /* too many */
}
return DIENUM_CONTINUE;
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate_Polled(SDL_Joystick * joystick)
{
DIJOYSTATE2 state;
HRESULT result;
int i;
result =
IDirectInputDevice2_GetDeviceState(joystick->hwdata->InputDevice,
sizeof(DIJOYSTATE2), &state);
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice);
result =
IDirectInputDevice2_GetDeviceState(joystick->hwdata->InputDevice,
sizeof(DIJOYSTATE2), &state);
}
/* Set each known axis, button and POV. */
for (i = 0; i < joystick->hwdata->NumInputs; ++i) {
const input_t *in = &joystick->hwdata->Inputs[i];
switch (in->type) {
case AXIS:
switch (in->ofs) {
case DIJOFS_X:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lX);
break;
case DIJOFS_Y:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lY);
break;
case DIJOFS_Z:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lZ);
break;
case DIJOFS_RX:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lRx);
break;
case DIJOFS_RY:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lRy);
break;
case DIJOFS_RZ:
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.lRz);
break;
case DIJOFS_SLIDER(0):
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.rglSlider[0]);
break;
case DIJOFS_SLIDER(1):
SDL_PrivateJoystickAxis_Int(joystick, in->num,
(Sint16) state.rglSlider[1]);
break;
}
break;
case BUTTON:
SDL_PrivateJoystickButton_Int(joystick, in->num,
(Uint8) (state.
rgbButtons[in->ofs -
DIJOFS_BUTTON0]
? SDL_PRESSED :
SDL_RELEASED));
break;
case HAT:
{
Uint8 pos = TranslatePOV(state.rgdwPOV[in->ofs -
DIJOFS_POV(0)]);
SDL_PrivateJoystickHat_Int(joystick, in->num, pos);
break;
}
}
}
}
void
SDL_SYS_JoystickUpdate_Buffered(SDL_Joystick * joystick)
{
int i;
HRESULT result;
DWORD numevents;
DIDEVICEOBJECTDATA evtbuf[INPUT_QSIZE];
numevents = INPUT_QSIZE;
result =
IDirectInputDevice2_GetDeviceData(joystick->hwdata->InputDevice,
sizeof(DIDEVICEOBJECTDATA), evtbuf,
&numevents, 0);
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice);
result =
IDirectInputDevice2_GetDeviceData(joystick->hwdata->InputDevice,
sizeof(DIDEVICEOBJECTDATA),
evtbuf, &numevents, 0);
}
/* Handle the events or punt */
if (FAILED(result))
return;
for (i = 0; i < (int) numevents; ++i) {
int j;
for (j = 0; j < joystick->hwdata->NumInputs; ++j) {
const input_t *in = &joystick->hwdata->Inputs[j];
if (evtbuf[i].dwOfs != in->ofs)
continue;
switch (in->type) {
case AXIS:
SDL_PrivateJoystickAxis(joystick, in->num,
(Sint16) evtbuf[i].dwData);
break;
case BUTTON:
SDL_PrivateJoystickButton(joystick, in->num,
(Uint8) (evtbuf[i].
dwData ? SDL_PRESSED :
SDL_RELEASED));
break;
case HAT:
{
Uint8 pos = TranslatePOV(evtbuf[i].dwData);
SDL_PrivateJoystickHat(joystick, in->num, pos);
}
}
}
}
}
static Uint8
TranslatePOV(DWORD value)
{
const int HAT_VALS[] = {
SDL_HAT_UP,
SDL_HAT_UP | SDL_HAT_RIGHT,
SDL_HAT_RIGHT,
SDL_HAT_DOWN | SDL_HAT_RIGHT,
SDL_HAT_DOWN,
SDL_HAT_DOWN | SDL_HAT_LEFT,
SDL_HAT_LEFT,
SDL_HAT_UP | SDL_HAT_LEFT
};
if (LOWORD(value) == 0xFFFF)
return SDL_HAT_CENTERED;
/* Round the value up: */
value += 4500 / 2;
value %= 36000;
value /= 4500;
if (value >= 8)
return SDL_HAT_CENTERED; /* shouldn't happen */
return HAT_VALS[value];
}
/* SDL_PrivateJoystick* doesn't discard duplicate events, so we need to
* do it. */
static int
SDL_PrivateJoystickAxis_Int(SDL_Joystick * joystick, Uint8 axis, Sint16 value)
{
if (joystick->axes[axis] != value)
return SDL_PrivateJoystickAxis(joystick, axis, value);
return 0;
}
static int
SDL_PrivateJoystickHat_Int(SDL_Joystick * joystick, Uint8 hat, Uint8 value)
{
if (joystick->hats[hat] != value)
return SDL_PrivateJoystickHat(joystick, hat, value);
return 0;
}
static int
SDL_PrivateJoystickButton_Int(SDL_Joystick * joystick, Uint8 button,
Uint8 state)
{
if (joystick->buttons[button] != state)
return SDL_PrivateJoystickButton(joystick, button, state);
return 0;
}
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
HRESULT result;
result = IDirectInputDevice2_Poll(joystick->hwdata->InputDevice);
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
IDirectInputDevice2_Acquire(joystick->hwdata->InputDevice);
IDirectInputDevice2_Poll(joystick->hwdata->InputDevice);
}
if (joystick->hwdata->buffered)
SDL_SYS_JoystickUpdate_Buffered(joystick);
else
SDL_SYS_JoystickUpdate_Polled(joystick);
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
IDirectInputDevice2_Unacquire(joystick->hwdata->InputDevice);
IDirectInputDevice2_Release(joystick->hwdata->InputDevice);
if (joystick->hwdata != NULL) {
/* free system specific hardware data */
SDL_free(joystick->hwdata);
}
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
IDirectInput_Release(dinput);
dinput = NULL;
}
#endif /* SDL_JOYSTICK_DINPUT */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,73 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifndef SDL_JOYSTICK_DINPUT_H
/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de
* A. Formiga's WINMM driver.
*
* Hats and sliders are completely untested; the app I'm writing this for mostly
* doesn't use them and I don't own any joysticks with them.
*
* We don't bother to use event notification here. It doesn't seem to work
* with polled devices, and it's fine to call IDirectInputDevice2_GetDeviceData and
* let it return 0 events. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define DIRECTINPUT_VERSION 0x0700 /* Need version 7 for force feedback. */
#include <dinput.h>
#define MAX_INPUTS 256 /* each joystick can have up to 256 inputs */
/* local types */
typedef enum Type
{ BUTTON, AXIS, HAT } Type;
typedef struct input_t
{
/* DirectInput offset for this input type: */
DWORD ofs;
/* Button, axis or hat: */
Type type;
/* SDL input offset: */
Uint8 num;
} input_t;
/* The private structure used to keep track of a joystick */
struct joystick_hwdata
{
LPDIRECTINPUTDEVICE2 InputDevice;
DIDEVCAPS Capabilities;
int buffered;
input_t Inputs[MAX_INPUTS];
int NumInputs;
};
#endif /* SDL_JOYSTICK_DINPUT_H */

View File

@@ -0,0 +1,428 @@
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2010 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#ifdef SDL_JOYSTICK_WINMM
/* Win32 MultiMedia Joystick driver, contributed by Andrei de A. Formiga */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
#include <regstr.h>
#include "SDL_events.h"
#include "SDL_joystick.h"
#include "../SDL_sysjoystick.h"
#include "../SDL_joystick_c.h"
#define MAX_JOYSTICKS 16
#define MAX_AXES 6 /* each joystick can have up to 6 axes */
#define MAX_BUTTONS 32 /* and 32 buttons */
#define AXIS_MIN -32768 /* minimum value for axis coordinate */
#define AXIS_MAX 32767 /* maximum value for axis coordinate */
/* limit axis to 256 possible positions to filter out noise */
#define JOY_AXIS_THRESHOLD (((AXIS_MAX)-(AXIS_MIN))/256)
#define JOY_BUTTON_FLAG(n) (1<<n)
/* array to hold joystick ID values */
static UINT SYS_JoystickID[MAX_JOYSTICKS];
static JOYCAPS SYS_Joystick[MAX_JOYSTICKS];
static char *SYS_JoystickName[MAX_JOYSTICKS];
/* The private structure used to keep track of a joystick */
struct joystick_hwdata
{
/* joystick ID */
UINT id;
/* values used to translate device-specific coordinates into
SDL-standard ranges */
struct _transaxis
{
int offset;
float scale;
} transaxis[6];
};
/* Convert a win32 Multimedia API return code to a text message */
static void SetMMerror(char *function, int code);
static char *
GetJoystickName(int index, const char *szRegKey)
{
/* added 7/24/2004 by Eckhard Stolberg */
/*
see if there is a joystick for the current
index (1-16) listed in the registry
*/
char *name = NULL;
HKEY hTopKey;
HKEY hKey;
DWORD regsize;
LONG regresult;
char regkey[256];
char regvalue[256];
char regname[256];
SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR);
hTopKey = HKEY_LOCAL_MACHINE;
regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
if (regresult != ERROR_SUCCESS) {
hTopKey = HKEY_CURRENT_USER;
regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
}
if (regresult != ERROR_SUCCESS) {
return NULL;
}
/* find the registry key name for the joystick's properties */
regsize = sizeof(regname);
SDL_snprintf(regvalue, SDL_arraysize(regvalue), "Joystick%d%s", index + 1,
REGSTR_VAL_JOYOEMNAME);
regresult =
RegQueryValueExA(hKey, regvalue, 0, 0, (LPBYTE) regname, &regsize);
RegCloseKey(hKey);
if (regresult != ERROR_SUCCESS) {
return NULL;
}
/* open that registry key */
SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s", REGSTR_PATH_JOYOEM,
regname);
regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
if (regresult != ERROR_SUCCESS) {
return NULL;
}
/* find the size for the OEM name text */
regsize = sizeof(regvalue);
regresult =
RegQueryValueExA(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, NULL, &regsize);
if (regresult == ERROR_SUCCESS) {
/* allocate enough memory for the OEM name text ... */
name = (char *) SDL_malloc(regsize);
if (name) {
/* ... and read it from the registry */
regresult = RegQueryValueExA(hKey,
REGSTR_VAL_JOYOEMNAME, 0, 0,
(LPBYTE) name, &regsize);
}
}
RegCloseKey(hKey);
return (name);
}
/* Function to scan the system for joysticks.
* This function should set SDL_numjoysticks to the number of available
* joysticks. Joystick 0 should be the system default joystick.
* It should return 0, or -1 on an unrecoverable fatal error.
*/
int
SDL_SYS_JoystickInit(void)
{
int i;
int maxdevs;
int numdevs;
JOYINFOEX joyinfo;
JOYCAPS joycaps;
MMRESULT result;
/* Reset the joystick ID & name mapping tables */
for (i = 0; i < MAX_JOYSTICKS; ++i) {
SYS_JoystickID[i] = 0;
SYS_JoystickName[i] = NULL;
}
/* Loop over all potential joystick devices */
numdevs = 0;
maxdevs = joyGetNumDevs();
for (i = JOYSTICKID1; i < maxdevs && numdevs < MAX_JOYSTICKS; ++i) {
joyinfo.dwSize = sizeof(joyinfo);
joyinfo.dwFlags = JOY_RETURNALL;
result = joyGetPosEx(i, &joyinfo);
if (result == JOYERR_NOERROR) {
result = joyGetDevCaps(i, &joycaps, sizeof(joycaps));
if (result == JOYERR_NOERROR) {
SYS_JoystickID[numdevs] = i;
SYS_Joystick[numdevs] = joycaps;
SYS_JoystickName[numdevs] =
GetJoystickName(i, joycaps.szRegKey);
numdevs++;
}
}
}
return (numdevs);
}
/* Function to get the device-dependent name of a joystick */
const char *
SDL_SYS_JoystickName(int index)
{
if (SYS_JoystickName[index] != NULL) {
return (SYS_JoystickName[index]);
} else {
return (SYS_Joystick[index].szPname);
}
}
/* Function to open a joystick for use.
The joystick to open is specified by the index field of the joystick.
This should fill the nbuttons and naxes fields of the joystick structure.
It returns 0, or -1 if there is an error.
*/
int
SDL_SYS_JoystickOpen(SDL_Joystick * joystick)
{
int index, i;
int caps_flags[MAX_AXES - 2] =
{ JOYCAPS_HASZ, JOYCAPS_HASR, JOYCAPS_HASU, JOYCAPS_HASV };
int axis_min[MAX_AXES], axis_max[MAX_AXES];
/* shortcut */
index = joystick->index;
axis_min[0] = SYS_Joystick[index].wXmin;
axis_max[0] = SYS_Joystick[index].wXmax;
axis_min[1] = SYS_Joystick[index].wYmin;
axis_max[1] = SYS_Joystick[index].wYmax;
axis_min[2] = SYS_Joystick[index].wZmin;
axis_max[2] = SYS_Joystick[index].wZmax;
axis_min[3] = SYS_Joystick[index].wRmin;
axis_max[3] = SYS_Joystick[index].wRmax;
axis_min[4] = SYS_Joystick[index].wUmin;
axis_max[4] = SYS_Joystick[index].wUmax;
axis_min[5] = SYS_Joystick[index].wVmin;
axis_max[5] = SYS_Joystick[index].wVmax;
/* allocate memory for system specific hardware data */
joystick->hwdata =
(struct joystick_hwdata *) SDL_malloc(sizeof(*joystick->hwdata));
if (joystick->hwdata == NULL) {
SDL_OutOfMemory();
return (-1);
}
SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
/* set hardware data */
joystick->hwdata->id = SYS_JoystickID[index];
for (i = 0; i < MAX_AXES; ++i) {
if ((i < 2) || (SYS_Joystick[index].wCaps & caps_flags[i - 2])) {
joystick->hwdata->transaxis[i].offset = AXIS_MIN - axis_min[i];
joystick->hwdata->transaxis[i].scale =
(float) (AXIS_MAX - AXIS_MIN) / (axis_max[i] - axis_min[i]);
} else {
joystick->hwdata->transaxis[i].offset = 0;
joystick->hwdata->transaxis[i].scale = 1.0; /* Just in case */
}
}
/* fill nbuttons, naxes, and nhats fields */
joystick->nbuttons = SYS_Joystick[index].wNumButtons;
joystick->naxes = SYS_Joystick[index].wNumAxes;
if (SYS_Joystick[index].wCaps & JOYCAPS_HASPOV) {
joystick->nhats = 1;
} else {
joystick->nhats = 0;
}
return (0);
}
static Uint8
TranslatePOV(DWORD value)
{
Uint8 pos;
pos = SDL_HAT_CENTERED;
if (value != JOY_POVCENTERED) {
if ((value > JOY_POVLEFT) || (value < JOY_POVRIGHT)) {
pos |= SDL_HAT_UP;
}
if ((value > JOY_POVFORWARD) && (value < JOY_POVBACKWARD)) {
pos |= SDL_HAT_RIGHT;
}
if ((value > JOY_POVRIGHT) && (value < JOY_POVLEFT)) {
pos |= SDL_HAT_DOWN;
}
if (value > JOY_POVBACKWARD) {
pos |= SDL_HAT_LEFT;
}
}
return (pos);
}
/* Function to update the state of a joystick - called as a device poll.
* This function shouldn't update the joystick structure directly,
* but instead should call SDL_PrivateJoystick*() to deliver events
* and update joystick device state.
*/
void
SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
{
MMRESULT result;
int i;
DWORD flags[MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ,
JOY_RETURNR, JOY_RETURNU, JOY_RETURNV
};
DWORD pos[MAX_AXES];
struct _transaxis *transaxis;
int value, change;
JOYINFOEX joyinfo;
joyinfo.dwSize = sizeof(joyinfo);
joyinfo.dwFlags = JOY_RETURNALL | JOY_RETURNPOVCTS;
if (!joystick->hats) {
joyinfo.dwFlags &= ~(JOY_RETURNPOV | JOY_RETURNPOVCTS);
}
result = joyGetPosEx(joystick->hwdata->id, &joyinfo);
if (result != JOYERR_NOERROR) {
SetMMerror("joyGetPosEx", result);
return;
}
/* joystick motion events */
pos[0] = joyinfo.dwXpos;
pos[1] = joyinfo.dwYpos;
pos[2] = joyinfo.dwZpos;
pos[3] = joyinfo.dwRpos;
pos[4] = joyinfo.dwUpos;
pos[5] = joyinfo.dwVpos;
transaxis = joystick->hwdata->transaxis;
for (i = 0; i < joystick->naxes; i++) {
if (joyinfo.dwFlags & flags[i]) {
value =
(int) (((float) pos[i] +
transaxis[i].offset) * transaxis[i].scale);
change = (value - joystick->axes[i]);
if ((change < -JOY_AXIS_THRESHOLD)
|| (change > JOY_AXIS_THRESHOLD)) {
SDL_PrivateJoystickAxis(joystick, (Uint8) i, (Sint16) value);
}
}
}
/* joystick button events */
if (joyinfo.dwFlags & JOY_RETURNBUTTONS) {
for (i = 0; i < joystick->nbuttons; ++i) {
if (joyinfo.dwButtons & JOY_BUTTON_FLAG(i)) {
if (!joystick->buttons[i]) {
SDL_PrivateJoystickButton(joystick, (Uint8) i,
SDL_PRESSED);
}
} else {
if (joystick->buttons[i]) {
SDL_PrivateJoystickButton(joystick, (Uint8) i,
SDL_RELEASED);
}
}
}
}
/* joystick hat events */
if (joyinfo.dwFlags & JOY_RETURNPOV) {
Uint8 pos;
pos = TranslatePOV(joyinfo.dwPOV);
if (pos != joystick->hats[0]) {
SDL_PrivateJoystickHat(joystick, 0, pos);
}
}
}
/* Function to close a joystick after use */
void
SDL_SYS_JoystickClose(SDL_Joystick * joystick)
{
if (joystick->hwdata != NULL) {
/* free system specific hardware data */
SDL_free(joystick->hwdata);
joystick->hwdata = NULL;
}
}
/* Function to perform any system-specific joystick related cleanup */
void
SDL_SYS_JoystickQuit(void)
{
int i;
for (i = 0; i < MAX_JOYSTICKS; i++) {
if (SYS_JoystickName[i] != NULL) {
SDL_free(SYS_JoystickName[i]);
SYS_JoystickName[i] = NULL;
}
}
}
/* implementation functions */
void
SetMMerror(char *function, int code)
{
static char *error;
static char errbuf[1024];
errbuf[0] = 0;
switch (code) {
case MMSYSERR_NODRIVER:
error = "Joystick driver not present";
break;
case MMSYSERR_INVALPARAM:
case JOYERR_PARMS:
error = "Invalid parameter(s)";
break;
case MMSYSERR_BADDEVICEID:
error = "Bad device ID";
break;
case JOYERR_UNPLUGGED:
error = "Joystick not attached";
break;
case JOYERR_NOCANDO:
error = "Can't capture joystick input";
break;
default:
SDL_snprintf(errbuf, SDL_arraysize(errbuf),
"%s: Unknown Multimedia system error: 0x%x",
function, code);
break;
}
if (!errbuf[0]) {
SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function,
error);
}
SDL_SetError("%s", errbuf);
}
#endif /* SDL_JOYSTICK_WINMM */
/* vi: set ts=4 sw=4 expandtab: */