Files
XMen/Assets/Scripts/SubDevice/CustomHIDDevice.cs
2025-07-10 14:49:53 +08:00

89 lines
2.4 KiB
C#

using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;
#if UNITY_EDITOR
using UnityEditor;
#endif
// 设备状态结构体
[StructLayout(LayoutKind.Explicit, Size = 2)]
public struct CustomHIDDeviceState : IInputStateTypeInfo
{
public FourCC format => new FourCC('H', 'I', 'D');
[FieldOffset(0)]
public byte reportId; // 报告ID
[FieldOffset(1)] // 按钮状态紧随报告ID之后
[InputControl(name = "button", layout = "Button", bit = 0)]
public byte buttons;
}
#if UNITY_EDITOR
// [InitializeOnLoad] // 确保在编辑器加载时运行
#endif
[InputControlLayout(stateType = typeof(CustomHIDDeviceState))]
public class CustomHIDDevice : InputDevice
{
// 在这里可以添加更多自定义功能和属性
public ButtonControl button { get; private set; }
protected override void FinishSetup()
{
// 初始化按钮控件
button = GetChildControl<ButtonControl>("button");
base.FinishSetup();
}
// // 注册设备和布局
// static CustomHIDDevice()
// {
// InputSystem.RegisterLayout<CustomHIDDevice>(
// matches: new InputDeviceMatcher()
// .WithInterface("HID")
// .WithCapability("vendorId", 0x16C0)
// .WithCapability("productId", 0x05DF)
// );
// }
// In the Player, to trigger the calling of the static constructor,
// create an empty method annotated with RuntimeInitializeOnLoadMethod.
// [RuntimeInitializeOnLoadMethod]
// static void Init() { }
public struct CustomHIDOutputReportCommand : IInputDeviceCommandInfo
{
public static FourCC Type { get { return new FourCC('C', 'H', 'O', 'R'); } }
public FourCC typeStatic => Type;
public InputDeviceCommand baseCommand;
// Output report data
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] reportData;
public static CustomHIDOutputReportCommand Create(byte[] data)
{
var command = new CustomHIDOutputReportCommand
{
baseCommand = new InputDeviceCommand(Type, Marshal.SizeOf<CustomHIDOutputReportCommand>()),
reportData = data
};
return command;
}
}
}