Jump to content


JoyShockLibrary 3.0

¿Quieres enterarte al momento de las nuevas descargas? Síguenos en Twitter, Mastodon o Threads!

El DualShock 4 de Sony PlayStation, el DualSense, los Joy-Cons de Nintendo Switch (usados por parejas) y el mando Pro de Nintendo Switch tienen mucho en común. Tienen muchas de las características que se esperan de los mandos de juego modernos. También tienen una entrada increíblemente versátil e infrautilizada que su mayor rival (el mando de la Xbox One de Microsoft) no tiene: el giroscopio.

El objetivo con JoyShockLibrary es permitir a los desarrolladores de juegos soportar DS4, DS, Joy-Cons, y Pro Controllers de forma nativa en los juegos de PC. He compilado la biblioteca para Windows, pero utiliza herramientas agnósticas, y espero que otros desarrolladores puedan hacerla funcionar en otras plataformas (como Linux o Mac) sin demasiados problemas.

Reference

JoyShockLibrary.h has everything you need to use the library, but here's a breakdown of everything in there.

Structs

struct JOY_SHOCK_STATE - This struct contains the state for all the sticks, buttons, and triggers on the controller. If you're just using JoyShockLibrary to be able to use JoyCons, Pro Controllers, and DualShock 4s similarly to how you'd use other devices, this has everything you need to know.

  • int buttons contains the states of all the controller's buttons with the following masks:
    • 0x00001 - d-pad up
    • 0x00002 - d-pad down
    • 0x00004 - d-pad left
    • 0x00008 - d-pad right
    • 0x00010 - + on Nintendo devices, Options on DS4
    • 0x00020 - - on Nintendo devices, Share on DS4
    • 0x00040 - left-stick click on Nintendo devices, L3 on DS4
    • 0x00080 - right-stick click on Nintendo devices, R3 on DS4
    • 0x00100 - L on Nintendo devices, L1 on DS4
    • 0x00200 - R on Nintendo devices, R1 on DS4
    • 0x00400 - ZL on Nintendo devices, L2 on DS4
    • 0x00800 - ZR on Nintendo devices, R2 on DS4
    • 0x01000 - the South face-button: B on Nintendo devices, ⨉ on DS4
    • 0x02000 - the East face-button: A on Nintendo devices, ○ on DS4
    • 0x04000 - the West face-button: Y on Nintendo devices, □ on DS4
    • 0x08000 - the North face-button: X on Nintendo devices, △ on DS4
    • 0x10000 - Home on Nintendo devices, PS on DS4
    • 0x20000 - Capture on Nintendo devices, touchpad click on DS4
    • 0x40000 - SL on Nintendo JoyCons
    • 0x80000 - SR on Nintendo JoyCons
  • float lTrigger - how far has the left trigger been pressed? This will be 1 or 0 on Nintendo devices, which don't have analog triggers
  • float rTrigger - how far has the right trigger been pressed? This will be 1 or 0 on Nintendo devices, which don't have analog triggers
  • float stickLX, stickLY - left-stick X axis and Y axis, respectively, from -1 to 1
  • float stickRX, stickRX - right-stick X axis and Y axis, respectively, from -1 to 1

struct IMU_STATE - Each supported device contains an IMU which has a 3-axis accelerometer and a 3-axis gyroscope. IMU_STATE is where you find that info.

  • float accelX, accelY, accelZ - accelerometer X axis, Y axis, and Z axis, respectively, in g (g-force).
  • float gyroX, gyroY, gyroZ - gyroscope angular velocity X, Y, and Z, respectively, in dps (degrees per second), when correctly calibrated.

Functions

All these functions should be thread-safe, and none of them should cause any harm if given the wrong handle. If they do, please report this to me as an isuse.

int JslConnectDevices() - Register any connected devices. Returns the number of devices connected, which is helpful for getting the handles for those devices with the next function.

int JslGetConnectedDeviceHandles(int* deviceHandleArray, int size) - Fills the array deviceHandleArray of size size with the handles for all connected devices, up to the length of the array. Use the length returned by JslConnectDevices to make sure you've got all connected devices' handles.

void JslDisconnectAndDisposeAll() - Disconnect devices, no longer polling them for input.

JOY_SHOCK_STATE JslGetSimpleState(int deviceId) - Get the latest button + trigger + stick state for the controller with the given id.

IMU_STATE JslGetIMUState(int deviceId) - Get the latest accelerometer + gyroscope state for the controller with the given id.

int JslGetButtons(int deviceId) - Get the latest button state for the controller with the given id. If you want more than just the buttons, it's more efficient to use JslGetSimpleState.

float JslGetLeftX/JslGetLeftY/JslGetRightX/JslGetRightY(int deviceId) - Get the latest stick state for the controller with the given id. If you want more than just a single stick axis, it's more efficient to use JslGetSimpleState.

float JslGetLeftTrigger/JslGetRightTrigger(int deviceId) - Get the latest trigger state for the controller with the given id. If you want more than just a single trigger, it's more efficient to use JslGetSimpleState.

float JslGetGyroX/JslGetGyroY/JslGetGyroZ(int deviceId) - Get the latest angular velocity for a given gyroscope axis. If you want more than just a single gyroscope axis velocity, it's more efficient to use JslGetIMUState.

float JslGetAccelX/JslGetAccelY/JslGetAccelZ(int deviceId) - Get the latest acceleration for a given axis. If you want more than just a accelerometer axis, it's more efficient to use JslGetIMUState.

float JslGetStickStep(int deviceId) - Different devices use different size data types and different ranges on those data types when reporting stick axes. For some calculations, it may be important to know the limits of the current device and work around them in different ways. This gives the smallest step size between two values for the given device's analog sticks.

float JslGetTriggerStep(int deviceId) - Some devices have analog triggers, some don't. For some calculations, it may be important to know the limits of the current device and work around them in different ways. This gives the smallest step size between two values for the given device's triggers, or 1.0 if they're actually just binary inputs.

float JslGetTriggerStep(int deviceId) - Some devices have analog triggers, some don't. For some calculations, it may be important to know the limits of the current device and work around them in different ways. This gives the smallest step size between two values for the given device's triggers, or 1.0 if they're actually just binary inputs.

float JslGetPollRate(int deviceId) - Different devices report back new information at different rates. For the given device, this gives how many times one would usually expect the device to report back per second.

void JslResetContinuousCalibration(int deviceId) - JoyShockLibrary has helpful functions for calibrating the gyroscope by averaging out its input over time. This deletes all calibration data that's been accumulated, if any, this session.

void JslStartContinuousCalibration(int deviceId) - Start collecting gyro data, recording the ongoing average and using that to offset gyro output.

void JslPauseContinuousCalibration(int deviceId) - Stop collecting gyro data, but don't delete it.

void JslGetCalibrationOffset(int deviceId, float& xOffset, float& yOffset, float& zOffset) - Get the calibrated offset value for the given device's gyro. You don't have to use it; all gyro output for this device is already being offset by this vector before leaving JoyShockLibrary.

void JslSetCalibrationOffset(int deviceId, float xOffset, float yOffset, float zOffset) - Manually set the calibrated offset value for the given device's gyro.

void JslSetCallback(void(*callback)(int, JOY_SHOCK_STATE, JOY_SHOCK_STATE, IMU_STATE, IMU_STATE, float)) - Set a callback function by which JoyShockLibrary can report the current state for each device. This callback will be given the deviceId for the reporting device, its current button + trigger + stick state, its previous button + trigger + stick state, its current accelerometer + gyro state, its previous accelerometer + gyro state, and the amount of time since the last report for this device (in seconds).

int JslGetControllerType(int deviceId) - What type of controller is this device?

  • Left JoyCon
  • Right JoyCon
  • Switch Pro Controller
  • DualShock 4

int JslGetControllerSplitType(int deviceId) - Is this a half-controller or full? If half, what kind?

  • Left half
  • Right half
  • Full controller

int JslGetControllerColour(int deviceId) - Get the colour of the controller. Only Nintendo devices support this. Others will report white.

void JslSetLightColour(int deviceId, int colour) - Set the light colour on the given controller. Only DualShock 4s support this. Players will often prefer to be able to disable the light, so make sure to give them that option, but when setting players up in a local multiplayer game, setting the light colour is a useful way to uniquely identify different controllers.

void JslSetPlayerNumber(int deviceId, int number) - Set the lights that indicate player number. This only works on Nintendo devices.

void JslSetRumble(int deviceId, int smallRumble, int bigRumble) - DualShock 4s have two types of rumble, and they can be set at the same time with different intensities. These can be set from 0 to 255. Nintendo devices support rumble as well, but totally differently. They call it "HD rumble", and it's a great feature, but JoyShockLibrary doesn't yet support it.

Known and Perceived Issues

Bluetooth connectivity

JoyShockLibrary doesn't yet support setting rumble and light colour for the DualShock 4 via Bluetooth.

JoyCons and Pro Controllers can only be connected by Bluetooth. Some Bluetooth adapters can't keep up with these devices, resulting in laggy input. This is especially common when more than one device is connected (such as when using a pair of JoyCons). There is nothing JoyShockMapper or JoyShockLibrary can do about this.

Gyro poll rate on Nintendo devices

The Nintendo devices report every 15ms, but their IMUs actually report every 5ms. Every 15ms report includes the last 3 gyro and accelerometer reports. When creating the latest IMU state for Nintendo devices, JoyShockLibrary averages out those 3 gyro and accelerometer reports, so that it can best include all that information in a sensible format. For things like controlling a cursor on a plane, this should be of little to no consequence, since the result is the same as adding all 3 reports separately over shorter time intervals. But for representing real 3D rotations of the controller, this causes the Nintendo devices to be slightly less accurate than they could be, because we're combining 3 rotations in a simplistic way.

In a future version I hope to either combine the 3 rotations in a way that works better in 3D, or to add a way for a single controller event to report several IMU events at the same time.

Credits

I'm Jibb Smart, and I made JoyShockLibrary.

JoyShockLibrary uses substantial portions of mfosse's JoyCon-Driver, a vJoy feeder for most communication with Nintendo devices, building on it with info from dekuNukem's Nintendo Switch Reverse Engineering page in order to (for example) unpack all gyro and accelerometer samples from each report.

JoyShockLibrary's DualShock 4 support would likely not be possible without the info available on PSDevWiki and Eleccelerator Wiki. chrippa's ds4drv was also a handy reference for getting rumble and lights working right away.

This software also relies on and links signal11's HIDAPI to connect to USB and Bluetooth devices. Since HIDAPI is linked statically, .objs are included. Since .objs may need to be compiled with the same compiler version as the dll itself, HIDAPI itself is included in a .zip.


Que novedades incluye la versión 3.0

Released

La versión 3 mejora la seguridad de los hilos y el comportamiento de JslConnectDevices para que pueda ser llamado sin restablecer las conexiones actuales. También mejora la calibración automática y añade funciones para ayudar a obtener una entrada de giroscopio útil y de alta resolución. También incluye un montón de nuevas características de calidad de vida.

Busque estas nuevas funciones en el README:

  • JslSetGyroSpace (opciones de giroscopio que se adaptan a la orientación preferida del controlador del jugador)
  • JslGetAndFlushAccumulatedGyro (obtiene el movimiento completo del giroscopio incluso cuando se sondea a baja velocidad)
  • JslSetConnectCallback
  • JslSetDisconnectCallback
  • JslGetTimeSinceLastUpdate
  • JslGetControllerInfoAndSettings
  • JslGetAutoCalibrationStatus

No te pierdas nada, síguenos en Twitter, Mastodon o Threads!
Preguntas, aportes y peticiones en el foro.

  • Contenido similar

    • Por Dekuwa
      Microsoft Activation Scripts (MAS) es una colección de scripts para activar productos de Microsoft utilizando HWID / KMS38 / KMS con especial foco en el uso de código abierto, menos detecciones de anti-virus y mayor facilidad de uso.

      Principales características de Microsoft Activation Scripts (MAS):
      Activación de HWID Activación de KMS38 Activación de KMS en línea Carpetas $OEM$ para la preactivación Solución de problemas de activación Insertar la clave HWID de Windows 10-11 Cambiar Windows 10-11-Server Edition Comprobar el estado de activación de Windows-Office Disponible en versión Todo en Uno y Archivos Separados Totalmente de código abierto Menos detección de antivirus Los archivos son transparentes script por lotes o archivo oficial de Microsoft Tres tipos de activación diferentes:
      Licencia digital para Windows 10 (permanente) KMS38 para Windows 10 y Windows Server (hasta el año 2038) Online KMS para Windows, Windows Server y Office (para 180 días. Se necesita crear una tarea para la auto-activación de por vida). Cómo utilizar:
      Descargue el archivo desde aquí mismo de forma completamente gratuita. Extraiga este archivo con un gestor de archivos de terceros, como 7zip En la carpeta extraída, busque la carpeta llamada All-In-One-Version Ejecute el archivo llamado MAS_AIO.cmd Verá las opciones de activación, siga las instrucciones en pantalla. Eso es todo. Aplicación creada por massgravel.
    • Por Dekuwa
      Playnite es un gestor y lanzador de bibliotecas de videojuegos de código abierto compatible con bibliotecas de terceros como Steam, Epic, GOG, EA App, Battle.net y otras. Incluye compatibilidad con emulación de juegos, lo que proporciona una interfaz unificada para tus juegos.


      Principales características de Playnite:
      Importa bibliotecas populares ¡Enlaza juegos de Steam, Epic, Origin, GOG, Battle.net, Ubisoft Connect y otros servicios, incluidos juegos que no están instalados! Compatibilidad con emulación Playnite admite una amplia variedad de emuladores de consola. Temas La apariencia de Playnite se puede personalizar por completo, desde cambios de color simples hasta rediseños completos del diseño. Extensiones La funcionalidad de Playnite se puede ampliar con complementos y extensiones de script. Modo de pantalla completa El modo de pantalla completa con compatibilidad total con el controlador está disponible. Contador de tiempo de juego Playnite registra tu tiempo en el juego (cualquier juego, incluidos los emulados). Rápido La interfaz de usuario de Playnite es rápida y consume pocos recursos, incluso con bibliotecas grandes. Portátil Playnite puede ejecutarse desde un almacenamiento portátil sin necesidad de instalar dependencias del sistema. Completamente gratuito Ninguna de las funciones de Playnite está bloqueada detrás de un muro de pago y el código fuente completo está disponible bajo la licencia MIT. Seguro y privado Playnite no almacena ninguna información de usuario en servidores remotos. Toda la información sobre tu biblioteca se almacena localmente en tu PC. Al vincular una cuenta, solo guardamos la misma cantidad de información que cuando inicias sesión en la biblioteca o tienda relacionada a través del navegador web. Integración con igdb.com Playnite puede descargar automáticamente metadatos para todos tus juegos, incluidos los personalizados (carátulas, descripciones y otra información). Playnite ha sido creado por Josefnemec.
    • Por Dekuwa
      Citron un emulador de Nintendo Switch diseñado para brindar una experiencia optimizada para jugar tus juegos favoritos y explorar otros nuevos. Citron es un emulador de alto rendimiento y fácil de usar, diseñado tanto para entusiastas como para desarrolladores.
      Descargo de responsabilidad: Citron está destinado estrictamente para uso legal de homebrew y no está afiliado ni respaldado por Nintendo. El uso de Citron para copias pirateadas o no autorizadas de juegos está estrictamente prohibido. Respeta a los desarrolladores de juegos y apóyalos comprando copias legítimas de sus juegos.

      Características principales
      Alto rendimiento: optimizado para la velocidad y una jugabilidad fluida. Fácil de usar: interfaz limpia e intuitiva. Multiplataforma: disponible en múltiples plataformas. Compatibilidad con homebrew: totalmente compatible con juegos y aplicaciones homebrew legales. Desarrollo continuo: ¡mantente atento a las actualizaciones frecuentes a medida que Citron evoluciona! Citron ha sido creado por Zephyron.
    • Por Dekuwa
      Borked3DS es un emulador de Nintendo 3DS para Windows, macOS, Linux y Android basado en Citra, incorporando elementos de Lime3DS y Mandarine, además de proporcionar su propio material.

      Nuevas características de Borked3DS
      Paridad de características en términos de configuración y funciones entre las versiones de escritorio y Android: prácticamente todas las opciones de la versión de escritorio que son aplicables a la versión de Android están aquí, excepto una (Offset Time, para que conste). El que estas características funcionen o no en tu dispositivo puede depender de la GPU de tu dispositivo o de la situación de compatibilidad de controladores (o puede que algunas hayan tenido errores desde el principio; en cuyo caso, se agradecen las PR con correcciones). Para algunas características, puedes obtener mejores resultados con hardware que admita Vulkan 1.3+ y/o OpenGL 4.6+. Compatibilidad con portal IR de Skylanders integrado en la versión de escritorio: si tienes ese hardware, debería funcionar de forma nativa en Borked3DS en la mayoría de los juegos de 3DS que admiten el hardware (la interfaz de administración se puede encontrar en el menú Herramientas y puedes encontrar más detalles en general del desarrollador original aquí). La capacidad de personalizar la optimización de sombreadores SPIR-V en Vulkan para escritorio y Android: anteriormente, las cosas estaban codificadas para optimizar solo el tamaño y solo a través de Glslang sin opción para deshabilitarlo o cambiarlo. Este proyecto canaliza esos sombreadores directamente a través de spirv-opt y además le permite elegir optimizar el tamaño, el rendimiento o deshabilitarlo por completo y volver al método heredado. También puede elegir activar la validación y/o legalización de SPIR-V, lo que puede ayudar con la depuración y prueba de sombreadores personalizados. Mejores opciones de registro en Android: ahora puede elegir la verbosidad por nivel de registro, y la función de filtrado de expresiones regulares que se encuentra en la bifurcación de PabloMK7 también está aquí. De forma predeterminada, el registro de Android estaba codificado en el nivel :Info, lo que significaba que faltaban algunos mensajes a los que podría haber tenido derecho o que pueden ayudar a otros desarrolladores a resolver problemas. Mejores descripciones y sugerencias para todas las opciones en todos los frontends: si no sabes qué hace una configuración, probablemente haya algún texto de ayuda para ella en este proyecto. Una interfaz de escritorio más compacta y optimizada: útil para personas como yo que todavía tienen que trabajar con pantallas de menor resolución en sus computadoras portátiles. Mi mayor problema con las versiones anteriores era que se desperdiciaba mucho espacio en la interfaz de configuración porque las cosas se representaban verticalmente. Por eso, ahora las cosas también se representan horizontalmente, lo que es un uso más eficiente del espacio de la pantalla. Más opciones en términos de versiones para implementar: hay AppImages de Linux basadas en Ubuntu 20.04, 22.04 y 24.04 (en lugar de solo 22.04), y versiones compiladas con GCC y Clang para Windows y Linux. Puedes elegir la que funcione mejor para ti en cualquier hardware o software que tengas. Las dependencias de terceros son más recientes que las de otras bifurcaciones y, dado que se crean a partir de la fuente de Git, a veces son de vanguardia. Por lo tanto, piense en compatibilidad con controladores de entrada de vanguardia a través de SDL tan pronto como estén disponibles, compatibilidad con las diversas actualizaciones de la API de Vulkan entre los lanzamientos de las principales versiones del SDK de Vulkan o binarios creados con los compiladores más recientes disponibles para cualquier plataforma compatible.
    • Por Dekuwa
      ShaderGlass es un overlay para ejecutar shadders de la GPU sobre el escritorio de Windows.

      Principales características de ShaderGlass
      Aplica efectos de sombreado sobre cualquier ventana del escritorio Incluye la cobertura de la biblioteca de sombreadores RetroArch: Simulación de monitores CRT Escalado de imágenes Simulación de TV / VHS Suavizado, eliminación de ruido, desenfoque, nitidez y muchos más Funciona con la mayoría de los emuladores, plataformas retro y editores de pixel art incluyendo: DOSBox, FS-UAE, Altirra, ScummVM, AGS, VICE, Aseprite etc. Excelente compañero para el dibujo de pixel art que muestra una vista previa sombreada y/o con relación de aspecto corregida Incluso puedes usarlo encima de YouTube, Twitch o juegos modernos Guardar y cargar perfiles Múltiples modos de funcionamiento, incluyendo pantalla completa sin bordes
×
×
  • Crear nuevo...