From c76208abd1c8df21a7cba1f85a86f68d2fa9df74 Mon Sep 17 00:00:00 2001 From: rcelyte Date: Mon, 17 Jun 2024 04:32:36 +0000 Subject: [PATCH 1/1] d/solarxr: Add SolarXR WebSockets driver --- CMakeLists.txt | 3 + src/external/CMakeLists.txt | 5 + src/external/solarxr/CMakeLists.txt | 41 + src/external/solarxr/solarxr_protocol.fbs | 788 +++++++++++++++++ src/xrt/drivers/CMakeLists.txt | 9 + src/xrt/drivers/solarxr/solarxr_device.c | 822 ++++++++++++++++++ src/xrt/drivers/solarxr/solarxr_device.h | 34 + src/xrt/drivers/solarxr/websocket.c | 378 ++++++++ src/xrt/drivers/solarxr/websocket.h | 35 + src/xrt/targets/common/CMakeLists.txt | 4 + .../common/target_builder_lighthouse.c | 13 + .../targets/common/target_builder_qwerty.c | 13 + .../targets/common/target_builder_steamvr.c | 13 + 13 files changed, 2158 insertions(+) create mode 100644 src/external/solarxr/CMakeLists.txt create mode 100644 src/external/solarxr/solarxr_protocol.fbs create mode 100644 src/xrt/drivers/solarxr/solarxr_device.c create mode 100644 src/xrt/drivers/solarxr/solarxr_device.h create mode 100644 src/xrt/drivers/solarxr/websocket.c create mode 100644 src/xrt/drivers/solarxr/websocket.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 74d0bd7f9..22b5f7c7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -333,6 +333,7 @@ option_with_deps(XRT_BUILD_DRIVER_VIVE "Enable driver for HTC Vive, Vive Pro, Va option_with_deps(XRT_BUILD_DRIVER_WMR "Enable Windows Mixed Reality driver" DEPENDS "NOT WIN32") option_with_deps(XRT_BUILD_DRIVER_XREAL_AIR "Enable Xreal Air HMD driver" DEPENDS XRT_HAVE_HIDAPI) option_with_deps(XRT_BUILD_DRIVER_SIMULAVR "Enable simula driver" DEPENDS XRT_HAVE_REALSENSE) +option_with_deps(XRT_BUILD_DRIVER_SOLARXR "Enable SolarXR driver" DEPENDS XRT_HAVE_LINUX) option(XRT_BUILD_DRIVER_SIMULATED "Enable simulated driver" ON) option(XRT_BUILD_SAMPLES "Enable compiling sample code implementations that will not be linked into any final targets" ON) @@ -429,6 +430,7 @@ list( "TWRAP" "XREAL_AIR" "STEAMVR_LIGHTHOUSE" + "SOLARXR" ) # Package name needs to be known by the native code itself. @@ -653,6 +655,7 @@ message(STATUS "# DRIVER_VIVE: ${XRT_BUILD_DRIVER_VIVE}") message(STATUS "# DRIVER_WMR: ${XRT_BUILD_DRIVER_WMR}") message(STATUS "# DRIVER_XREAL_AIR: ${XRT_BUILD_DRIVER_XREAL_AIR}") message(STATUS "# DRIVER_STEAMVR_LIGHTHOUSE: ${XRT_BUILD_DRIVER_STEAMVR_LIGHTHOUSE}") +message(STATUS "# DRIVER_SOLARXR: ${XRT_BUILD_DRIVER_SOLARXR}") message(STATUS "#####----- Config -----#####") # cmake-format: on diff --git a/src/external/CMakeLists.txt b/src/external/CMakeLists.txt index baf5bbeb4..bf3297c62 100644 --- a/src/external/CMakeLists.txt +++ b/src/external/CMakeLists.txt @@ -188,6 +188,11 @@ target_include_directories( xrt-external-vdf SYSTEM INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/valve-file-vdf ) +# SolarXR codegen +if(XRT_BUILD_DRIVER_SOLARXR) + add_subdirectory(solarxr) +endif() + # nvpro pyramid if(XRT_HAVE_VULKAN) diff --git a/src/external/solarxr/CMakeLists.txt b/src/external/solarxr/CMakeLists.txt new file mode 100644 index 000000000..1c0cf016c --- /dev/null +++ b/src/external/solarxr/CMakeLists.txt @@ -0,0 +1,41 @@ +# Copyright 2024, rcelyte +# SPDX-License-Identifier: BSL-1.0 + +include(FetchContent) + +set(FLATCC_TEST + OFF + CACHE INTERNAL "" + ) +set(FLATCC_DEBUG_CLANG_SANITIZE + OFF + CACHE INTERNAL "" + ) +set(FLATCC_REFLECTION + OFF + CACHE INTERNAL "" + ) +set(FLATCC_ALLOW_WERROR + OFF + CACHE INTERNAL "" + ) +set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) +FetchContent_Declare( + FlatCC + DOWNLOAD_EXTRACT_TIMESTAMP true + URL_HASH SHA256=2533c2f1061498499f15acc7e0937dcf35bc68e685d237325124ae0d6c600c2b + URL https://github.com/dvidelabs/flatcc/archive/refs/tags/v0.6.1.tar.gz + ) +FetchContent_MakeAvailable(FlatCC) + +add_custom_command( + OUTPUT solarxr_protocol.h + COMMAND + flatcc_cli -a --outfile=solarxr_protocol.h + ${CMAKE_CURRENT_SOURCE_DIR}/solarxr_protocol.fbs + ) + +add_library(solarxr_protocol STATIC solarxr_protocol.h) +set_target_properties(solarxr_protocol PROPERTIES LINKER_LANGUAGE C) +target_include_directories(solarxr_protocol SYSTEM INTERFACE ${CMAKE_CURRENT_BINARY_DIR} ${FlatCC_SOURCE_DIR}/include) +target_link_libraries(solarxr_protocol INTERFACE flatccrt) diff --git a/src/external/solarxr/solarxr_protocol.fbs b/src/external/solarxr/solarxr_protocol.fbs new file mode 100644 index 000000000..a3074fb72 --- /dev/null +++ b/src/external/solarxr/solarxr_protocol.fbs @@ -0,0 +1,788 @@ +// Copyright 2022, Ryan Butler +// SPDX-License-Identifier: MIT OR Apache-2.0 + +// derived from https://github.com/SlimeVR/SolarXR-Protocol/tree/f74a0fd4e4c6968f9b8e56ac56ad30242dca2867/schema +// combined and adapted to work with FlatCC + +namespace solarxr_protocol.datatypes; +struct HzF32 { + f: float32; +} +struct TransactionId { + id: uint32; +} +struct DeviceId { + id: uint8; +} +table TrackerId { + device_id: solarxr_protocol.datatypes.DeviceId; + tracker_num: uint8; +} +table LogData { + message: string; + data: [uint8]; +} +enum FirmwareErrorCode: uint8 { + Other = 0, + Disconnected, + Occluded, + ImuError, +} +enum FilteringType: uint8 { + NONE = 0, + SMOOTHING = 1, + PREDICTION = 2 +} +enum TrackerRole: uint8 { + NONE = 0, + WAIST = 1, + LEFT_FOOT = 2, + RIGHT_FOOT = 3, + CHEST = 4, + LEFT_KNEE = 5, + RIGHT_KNEE = 6, + LEFT_ELBOW = 7, + RIGHT_ELBOW = 8, + LEFT_SHOULDER = 9, + RIGHT_SHOULDER = 10, + LEFT_HAND = 11, + RIGHT_HAND = 12, + LEFT_CONTROLLER = 13, + RIGHT_CONTROLLER = 14, + HEAD = 15, + NECK = 16, + CAMERA = 17, + KEYBOARD = 18, + HMD = 19, + BEACON = 20, + GENERIC_CONTROLLER = 21, +} +enum BodyPart: uint8 { + NONE = 0, + HEAD = 1, + NECK = 2, + CHEST = 3, + WAIST = 4, + HIP = 5, + LEFT_UPPER_LEG = 6, + RIGHT_UPPER_LEG = 7, + LEFT_LOWER_LEG = 8, + RIGHT_LOWER_LEG = 9, + LEFT_FOOT = 10, + RIGHT_FOOT = 11, + LEFT_LOWER_ARM = 14, + RIGHT_LOWER_ARM = 15, + LEFT_UPPER_ARM = 16, + RIGHT_UPPER_ARM = 17, + LEFT_HAND = 18, + RIGHT_HAND = 19, + LEFT_SHOULDER = 20, + RIGHT_SHOULDER = 21, + UPPER_CHEST = 22, + LEFT_HIP = 23, + RIGHT_HIP = 24, +} +enum TrackerStatus: uint8 { + NONE = 0, + DISCONNECTED = 1, + OK = 2, + BUSY = 3, + ERROR = 4, + OCCLUDED = 5, + TIMED_OUT = 6, +} +struct Temperature { + temp: float32; +} +struct Ipv4Address { + addr: uint32; +} +table Bytes { + b: [uint8]; +} +table StringTable { + s: string; +} + +namespace solarxr_protocol.datatypes.hardware_info; +enum McuType: uint16 { + Other = 0, + ESP8266, + ESP32, + OWOTRACK_ANDROID, + WRANGLER, + OWOTRACK_IOS, + ESP32_C3, + MOCOPI, + DEV_RESERVED = 250, +} +enum ImuType: uint16 { + Other = 0, + MPU9250, + MPU6500, + BNO080, + BNO085, + BNO055, + MPU6050, + BNO086, + BMI160, + ICM20948, + ICM42688, +} +struct HardwareAddress { + addr: uint64; +} +table HardwareInfo { + mcu_id: McuType; + display_name: string; + model: string; + manufacturer: string; + hardware_revision: string; + firmware_version: string; + hardware_address: HardwareAddress; + ip_address: solarxr_protocol.datatypes.Ipv4Address; + board_type: string; + hardware_identifier: string; + network_protocol_version: uint16 = null; +} +table HardwareStatus { + error_status: solarxr_protocol.datatypes.FirmwareErrorCode = null; + tps: uint8 = null (deprecated); + ping: uint16 = null; + rssi: int16 = null; + mcu_temp: float32 = null; + battery_voltage: float32 = null; + battery_pct_estimate: uint8 = null; + log_data: solarxr_protocol.datatypes.LogData; +} +table FirmwareStatusMask { + error_status: bool; + tps: bool; + ping: bool; + rssi: bool; + mcu_temp: bool; + battery_voltage: bool; + battery_pct_estimate: bool; +} + + + +namespace solarxr_protocol.datatypes.math; +struct Quat { + x: float32; + y: float32; + z: float32; + w: float32; +} +struct Vec3f { + x: float32; + y: float32; + z: float32; +} +namespace solarxr_protocol.data_feed.tracker; +table TrackerData { + tracker_id: solarxr_protocol.datatypes.TrackerId; + info: TrackerInfo; + status: solarxr_protocol.datatypes.TrackerStatus; + rotation: solarxr_protocol.datatypes.math.Quat; + position: solarxr_protocol.datatypes.math.Vec3f; + raw_angular_velocity: solarxr_protocol.datatypes.math.Vec3f; + raw_acceleration: solarxr_protocol.datatypes.math.Vec3f; + temp: solarxr_protocol.datatypes.Temperature; + linear_acceleration: solarxr_protocol.datatypes.math.Vec3f; + rotation_reference_adjusted: solarxr_protocol.datatypes.math.Quat; + rotation_identity_adjusted: solarxr_protocol.datatypes.math.Quat; + tps: uint16 = null; +} +table TrackerDataMask { + info: bool; + status: bool; + rotation: bool; + position: bool; + raw_angular_velocity: bool; + raw_acceleration: bool; + temp: bool; + linear_acceleration: bool; + rotation_reference_adjusted: bool; + rotation_identity_adjusted: bool; + tps: bool; +} +table TrackerInfo { + imu_type: solarxr_protocol.datatypes.hardware_info.ImuType; + body_part: solarxr_protocol.datatypes.BodyPart; + poll_rate: solarxr_protocol.datatypes.HzF32; + mounting_orientation: solarxr_protocol.datatypes.math.Quat; + editable: bool; + is_computed: bool; + is_imu: bool; + display_name: string; + custom_name: string; + allow_drift_compensation: bool; + mounting_reset_orientation: solarxr_protocol.datatypes.math.Quat; + is_hmd: bool; +} +namespace solarxr_protocol.data_feed.device_data; +table DeviceDataMask { + tracker_data: solarxr_protocol.data_feed.tracker.TrackerDataMask; + device_data: bool; +} +table DeviceData { + id: solarxr_protocol.datatypes.DeviceId; + custom_name: string; + hardware_info: solarxr_protocol.datatypes.hardware_info.HardwareInfo; + hardware_status: solarxr_protocol.datatypes.hardware_info.HardwareStatus; + trackers: [solarxr_protocol.data_feed.tracker.TrackerData]; +} +namespace solarxr_protocol.data_feed; +table Bone { + body_part: solarxr_protocol.datatypes.BodyPart; + rotation_g: solarxr_protocol.datatypes.math.Quat; + bone_length: float32; + head_position_g: solarxr_protocol.datatypes.math.Vec3f; +} + +namespace solarxr_protocol.data_feed; +union DataFeedMessage { + PollDataFeed, + StartDataFeed, + DataFeedUpdate, + DataFeedConfig, +} +table DataFeedMessageHeader { + message: DataFeedMessage; +} +table PollDataFeed { + config: DataFeedConfig; +} +table StartDataFeed { + data_feeds: [DataFeedConfig]; +} +table DataFeedUpdate { + devices: [solarxr_protocol.data_feed.device_data.DeviceData]; + synthetic_trackers: [solarxr_protocol.data_feed.tracker.TrackerData]; + bones: [solarxr_protocol.data_feed.Bone]; +} +table DataFeedConfig { + minimum_time_since_last: uint16 = 0; + data_mask: solarxr_protocol.data_feed.device_data.DeviceDataMask; + synthetic_trackers_mask: solarxr_protocol.data_feed.tracker.TrackerDataMask; + bone_mask: bool; +} + +namespace solarxr_protocol.rpc.settings; +table ModelToggles{ + extended_spine: bool = null; + extended_pelvis: bool = null; + extended_knee: bool = null; + force_arms_from_hmd: bool = null; + floor_clip: bool = null; + skating_correction: bool = null; + vive_emulation: bool = null; + toe_snap: bool = null; + foot_plant: bool = null; + self_localization: bool = null; +} +table ModelRatios{ + impute_waist_from_chest_hip: float32 = null; + impute_waist_from_chest_legs: float32 = null; + impute_hip_from_chest_legs: float32 = null; + impute_hip_from_waist_legs: float32 = null; + interp_hip_legs: float32 = null; + interp_knee_tracker_ankle: float32 = null; + interp_knee_ankle: float32 = null; +} +table LegTweaksSettings{ + correction_strength: float32 = null; +} +table ModelSettings { + toggles: ModelToggles; + ratios: ModelRatios; + leg_tweaks: LegTweaksSettings; +} + +namespace solarxr_protocol.rpc; +union RpcMessage { + HeartbeatRequest, + HeartbeatResponse, + ResetRequest, + ResetResponse, + AssignTrackerRequest, + SettingsRequest, + SettingsResponse, + ChangeSettingsRequest, + ClearDriftCompensationRequest, + RecordBVHRequest, + RecordBVHStatus, + SkeletonConfigRequest, + ChangeSkeletonConfigRequest, + SkeletonResetAllRequest, + SkeletonConfigResponse, + OpenSerialRequest, + CloseSerialRequest, + SetWifiRequest, + SerialUpdateResponse, + AutoBoneProcessRequest, + AutoBoneProcessStatusResponse, + AutoBoneEpochResponse, + OverlayDisplayModeRequest, + OverlayDisplayModeChangeRequest, + OverlayDisplayModeResponse, + SerialTrackerRebootRequest, + SerialTrackerGetInfoRequest, + SerialTrackerFactoryResetRequest, + SerialDevicesRequest, + SerialDevicesResponse, + NewSerialDeviceResponse, + StartWifiProvisioningRequest, + StopWifiProvisioningRequest, + WifiProvisioningStatusResponse, + ServerInfosRequest, + ServerInfosResponse, + LegTweaksTmpChange, + LegTweaksTmpClear, + TapDetectionSetupNotification, + SetPauseTrackingRequest, + StatusSystemRequest, + StatusSystemResponse, + StatusSystemUpdate, + StatusSystemFixed, + ClearMountingResetRequest, + HeightRequest, + HeightResponse, + AutoBoneApplyRequest, + AutoBoneStopRecordingRequest, + AutoBoneCancelRecordingRequest, + SaveFileNotification, + TrackingPauseStateRequest, + TrackingPauseStateResponse, + SerialTrackerGetWifiScanRequest, + UnknownDeviceHandshakeNotification, + AddUnknownDeviceRequest, + ForgetDeviceRequest, +} +table RpcMessageHeader { + tx_id: solarxr_protocol.datatypes.TransactionId; + message: RpcMessage; +} +table HeartbeatRequest {} +table HeartbeatResponse {} +enum ResetType: uint8 { + Yaw, + Full, + Mounting, +} +enum ResetStatus: uint8 { + STARTED, + FINISHED, +} +table ResetRequest { + reset_type: ResetType; +} +table ResetResponse { + reset_type: ResetType; + status: ResetStatus; +} +table AssignTrackerRequest { + tracker_id: solarxr_protocol.datatypes.TrackerId; + body_position: solarxr_protocol.datatypes.BodyPart; + mounting_orientation: solarxr_protocol.datatypes.math.Quat; + display_name: string; + allow_drift_compensation: bool; +} +table ClearDriftCompensationRequest {} +table SettingsRequest {} +table SettingsResponse { + steam_vr_trackers: SteamVRTrackersSetting; + filtering: FilteringSettings; + drift_compensation: DriftCompensationSettings; + osc_router: OSCRouterSettings; + vrc_osc: VRCOSCSettings; + vmc_osc: VMCOSCSettings; + model_settings: solarxr_protocol.rpc.settings.ModelSettings; + tap_detection_settings: TapDetectionSettings; + auto_bone_settings: AutoBoneSettings; + resets_settings: ResetsSettings; +} +table ChangeSettingsRequest { + steam_vr_trackers: SteamVRTrackersSetting; + filtering: FilteringSettings; + drift_compensation: DriftCompensationSettings; + osc_router: OSCRouterSettings; + vrc_osc: VRCOSCSettings; + vmc_osc: VMCOSCSettings; + model_settings: solarxr_protocol.rpc.settings.ModelSettings; + tap_detection_settings: TapDetectionSettings; + auto_bone_settings: AutoBoneSettings; + resets_settings: ResetsSettings; +} +table SteamVRTrackersSetting { + waist: bool; + chest: bool; + feet: bool (deprecated); + knees: bool (deprecated); + elbows: bool (deprecated); + hands: bool (deprecated); + automaticTrackerToggle: bool; + left_foot: bool; + right_foot: bool; + left_knee: bool; + right_knee: bool; + left_elbow: bool; + right_elbow: bool; + left_hand: bool; + right_hand: bool; +} +table FilteringSettings { + type: solarxr_protocol.datatypes.FilteringType; + amount: float32; +} +table DriftCompensationSettings { + enabled: bool; + amount: float32; + max_resets: uint16; +} +table OSCRouterSettings { + osc_settings: OSCSettings; +} +table VRCOSCSettings { + osc_settings: OSCSettings; + trackers: OSCTrackersSetting; +} +table VMCOSCSettings { + osc_settings: OSCSettings; + vrm_json: string; + anchor_hip: bool; + mirror_tracking: bool; +} +table OSCSettings { + enabled: bool; + port_in: uint16; + port_out: uint16; + address: string; +} +table OSCTrackersSetting { + head: bool; + chest: bool; + waist: bool; + knees: bool; + feet: bool; + elbows: bool; + hands: bool; +} +table TapDetectionSettings { + full_reset_delay: float = null; + full_reset_enabled: bool = null; + full_reset_taps: uint8 = null; + yaw_reset_delay: float = null; + yaw_reset_enabled: bool = null; + yaw_reset_taps: uint8 = null; + mounting_reset_delay: float = null; + mounting_reset_enabled: bool = null; + mounting_reset_taps: uint8 = null; + setup_mode: bool = null; + number_trackers_over_threshold: uint8 = null; +} +enum ArmsMountingResetMode: uint8 { + BACK, + FORWARD, + TPOSE_UP, + TPOSE_DOWN +} +table ResetsSettings { + reset_mounting_feet: bool; + arms_mounting_reset_mode: ArmsMountingResetMode; + yaw_reset_smooth_time: float32; + save_mounting_reset: bool; + reset_hmd_pitch: bool; +} +table TapDetectionSetupNotification { + tracker_id: solarxr_protocol.datatypes.TrackerId; +} +table RecordBVHRequest { + stop: bool; +} +table RecordBVHStatus { + recording: bool; +} +enum SkeletonBone: uint8 { + NONE = 0, + HEAD = 1, + NECK = 2, + CHEST = 3, + CHEST_OFFSET = 4, + WAIST = 5, + HIP = 6, + HIP_OFFSET = 7, + HIPS_WIDTH = 8, + UPPER_LEG = 9, + LOWER_LEG = 10, + FOOT_LENGTH = 11, + FOOT_SHIFT = 12, + SKELETON_OFFSET = 13, + SHOULDERS_DISTANCE = 14, + SHOULDERS_WIDTH = 15, + UPPER_ARM = 16, + LOWER_ARM = 17, + HAND_Y = 18, + HAND_Z = 19, + ELBOW_OFFSET = 20, + UPPER_CHEST = 21, +} +table SkeletonPart { + bone: SkeletonBone; + value: float; +} +table SkeletonConfigRequest {} +table SkeletonConfigResponse { + skeleton_parts: [SkeletonPart]; +} +table SkeletonResetAllRequest {} +table ChangeSkeletonConfigRequest { + bone: SkeletonBone; + value: float; +} +table SerialDevice { + port: string; + name: string; +} +table OpenSerialRequest { + auto: bool; + port: string; +} +table CloseSerialRequest {} +table SetWifiRequest { + ssid: string; + password: string; +} +table SerialUpdateResponse { + log: string; + closed: bool; +} +table SerialTrackerRebootRequest {} +table SerialTrackerGetInfoRequest {} +table SerialTrackerFactoryResetRequest {} +table SerialDevicesRequest {} +table SerialDevicesResponse { + devices: [SerialDevice]; +} +table NewSerialDeviceResponse { + device: SerialDevice; +} +table StartWifiProvisioningRequest { + ssid: string; + password: string; + port: string; +} +table StopWifiProvisioningRequest {} +enum WifiProvisioningStatus: uint8 { + NONE = 0, + SERIAL_INIT = 1, + PROVISIONING = 2, + CONNECTING = 3, + CONNECTION_ERROR = 4, + LOOKING_FOR_SERVER = 5, + COULD_NOT_FIND_SERVER = 6, + DONE = 7, +} +table WifiProvisioningStatusResponse { + status: WifiProvisioningStatus; +} +enum AutoBoneProcessType: uint8 { + NONE = 0, + RECORD = 1, + SAVE = 2, + PROCESS = 3, + APPLY = 4, +} +table AutoBoneProcessRequest { + process_type: AutoBoneProcessType; +} +table AutoBoneProcessStatusResponse { + process_type: AutoBoneProcessType; + message: string (deprecated); + current: uint32; + total: uint32; + completed: bool; + success: bool; + eta: float32; +} +table AutoBoneEpochResponse { + current_epoch: uint32; + total_epochs: uint32; + epoch_error: float32; + adjusted_skeleton_parts: [SkeletonPart]; +} +table AutoBoneSettings { + cursor_increment: int32 = null; + min_data_distance: int32 = null; + max_data_distance: int32 = null; + num_epochs: int32 = null; + print_every_num_epochs: int32 = null; + initial_adjust_rate: float32 = null; + adjust_rate_decay: float32 = null; + slide_error_factor: float32 = null; + offset_slide_error_factor: float32 = null; + foot_height_offset_error_factor: float32 = null; + body_proportion_error_factor: float32 = null; + height_error_factor: float32 = null; + position_error_factor: float32 = null; + position_offset_error_factor: float32 = null; + calc_init_error: bool = null; + target_hmd_height: float32 = null; + target_full_height: float32 = null; + randomize_frame_order: bool = null; + scale_each_step: bool = null; + sample_count: int32 = null; + sample_rate_ms: int64 = null; + save_recordings: bool = null; + use_skeleton_height: bool = null; + rand_seed: int64 = null; +} +table HeightRequest {} +table HeightResponse { + hmd_height: float32; + estimated_full_height: float32; +} +table AutoBoneApplyRequest {} +table AutoBoneStopRecordingRequest {} +table AutoBoneCancelRecordingRequest {} +table OverlayDisplayModeRequest {} +table OverlayDisplayModeChangeRequest { + is_visible: bool = null; + is_mirrored: bool = null; +} +table OverlayDisplayModeResponse { + is_visible: bool; + is_mirrored: bool; +} +table ServerInfosRequest {} +table ServerInfosResponse { + localIp: string; +} +table LegTweaksTmpChange { + floor_clip: bool = null; + skating_correction: bool = null; + toe_snap: bool = null; + foot_plant: bool = null; +} +table LegTweaksTmpClear { + floor_clip: bool = false; + skating_correction: bool = false; + toe_snap: bool = false; + foot_plant: bool = false; +} +union StatusData { + StatusTrackerReset, + StatusTrackerError, + StatusSteamVRDisconnected, + StatusUnassignedHMD, +} +table StatusTrackerReset { + tracker_id: solarxr_protocol.datatypes.TrackerId; +} +table StatusTrackerError { + tracker_id: solarxr_protocol.datatypes.TrackerId; +} +table StatusSteamVRDisconnected { + bridge_settings_name: string; +} +table StatusUnassignedHMD { + tracker_id: solarxr_protocol.datatypes.TrackerId; +} +table StatusSystemRequest {} +table StatusSystemResponse { + current_statuses: [StatusMessage]; +} +table StatusSystemUpdate { + new_status: StatusMessage; +} +table StatusSystemFixed { + fixed_status_id: uint32; +} +table StatusMessage { + id: uint32; + prioritized: bool = false; + data: StatusData; +} +table SetPauseTrackingRequest { + pauseTracking: bool; +} +table ClearMountingResetRequest {} +enum ComputerDirectory: uint8 { + Documents, +} +table SaveFileNotification { + data: [uint8]; + mime_type: string; + file_extension: string; + expected_dir: ComputerDirectory = null; + expected_filename: string; +} +table TrackingPauseStateRequest {} +table TrackingPauseStateResponse { + trackingPaused: bool; +} +table SerialTrackerGetWifiScanRequest {} +table UnknownDeviceHandshakeNotification { + mac_address: string; +} +table AddUnknownDeviceRequest { + mac_address: string; +} +table ForgetDeviceRequest { + mac_address: string; +} + +namespace solarxr_protocol.pub_sub; +table TopicId { + organization: string; + app_name: string; + topic: string; +} +table TopicHandle { + id: uint16; +} +union Topic { + TopicHandle, + TopicId, +} +table TopicMapping { + id: TopicId; + handle: TopicHandle; +} +table TopicHandleRequest { + id: TopicId; +} +table SubscriptionRequest { + topic: Topic; +} +namespace solarxr_protocol.pub_sub; +union PubSubUnion { + Message, + SubscriptionRequest, + TopicHandleRequest, + TopicMapping, +} +table PubSubHeader { + u: PubSubUnion; +} +union Payload { + solarxr_protocol.datatypes.StringTable, + solarxr_protocol.datatypes.Bytes, + KeyValues, +} +table Message { + topic: Topic; + payload: Payload; +} +table KeyValues { + keys: [string]; + values: [string]; +} + +namespace solarxr_protocol; +table MessageBundle { + data_feed_msgs: [solarxr_protocol.data_feed.DataFeedMessageHeader]; + rpc_msgs: [solarxr_protocol.rpc.RpcMessageHeader]; + pub_sub_msgs: [solarxr_protocol.pub_sub.PubSubHeader]; +} diff --git a/src/xrt/drivers/CMakeLists.txt b/src/xrt/drivers/CMakeLists.txt index 0d422f16e..900b6a309 100644 --- a/src/xrt/drivers/CMakeLists.txt +++ b/src/xrt/drivers/CMakeLists.txt @@ -494,6 +494,15 @@ if(XRT_BUILD_DRIVER_STEAMVR_LIGHTHOUSE) list(APPEND ENABLED_HEADSET_DRIVERS steamvr_lh) endif() +if(XRT_BUILD_DRIVER_SOLARXR) + add_library( + drv_solarxr STATIC solarxr/solarxr_device.c solarxr/solarxr_device.h + solarxr/websocket.c solarxr/websocket.h + ) + target_link_libraries(drv_solarxr PRIVATE xrt-interfaces aux_util solarxr_protocol) + list(APPEND ENABLED_DRIVERS solarxr) +endif() + if(XRT_BUILD_SAMPLES) # We build the sample driver to make sure it stays valid, # but it never gets linked into a final target. diff --git a/src/xrt/drivers/solarxr/solarxr_device.c b/src/xrt/drivers/solarxr/solarxr_device.c new file mode 100644 index 000000000..c3ea827e9 --- /dev/null +++ b/src/xrt/drivers/solarxr/solarxr_device.c @@ -0,0 +1,823 @@ +// Copyright 2024, rcelyte +// SPDX-License-Identifier: BSL-1.0 + +#define solarxr_protocol_rpc_SaveFileNotification_file_extension \ + solarxr_protocol_rpc_SaveFileNotification_file_extension +#include "solarxr_device.h" +#include "websocket.h" +#include "solarxr_protocol.h" + +#include "math/m_relation_history.h" +#include "math/m_vec3.h" +#include "os/os_threading.h" +#include "os/os_time.h" +#include "util/u_debug.h" +#include "util/u_device.h" + +#include "xrt/xrt_config_build.h" // TODO: drop `#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META` guards once !2206 is merged + +#include +#include + +#define BodyPart_COUNT 25 // must be kept in sync with schema +#define MAX_GENERIC_TRACKERS 32 +static const uint16_t updateIntervalMs = 10; +typedef uint32_t solarxr_trackerid_t; + +DEBUG_GET_ONCE_LOG_OPTION(solarxr_log, "SOLARXR_LOG", U_LOGGING_WARN) +DEBUG_GET_ONCE_BOOL_OPTION(solarxr_raw_trackers, "SOLARXR_RAW_TRACKERS", false) + +struct solarxr_generic_tracker +{ + struct xrt_device base; + struct os_mutex *mutex; + struct m_relation_history *history; + struct solarxr_generic_tracker **weakRef; +}; + +struct solarxr_device +{ + struct xrt_device base; + struct xrt_device *hmd; + struct os_thread thread; + struct WebSocket socket; + struct os_mutex mutex; + int64_t timestamp; + uint32_t generation; + struct solarxr_device_bone + { + struct xrt_pose pose; + float length; + } bones[BodyPart_COUNT]; + solarxr_trackerid_t trackerIds[MAX_GENERIC_TRACKERS]; + struct solarxr_generic_tracker *trackers[MAX_GENERIC_TRACKERS]; +}; + +static inline struct solarxr_device * +solarxr_device(struct xrt_device *const xdev) +{ + return (struct solarxr_device *)xdev; +} + +static inline struct solarxr_generic_tracker * +solarxr_generic_tracker(struct xrt_device *const xdev) +{ + return (struct solarxr_generic_tracker *)xdev; +} + +static void +solarxr_device_get_tracked_pose(struct xrt_device *const xdev, + const enum xrt_input_name name, + const int64_t at_timestamp_ns, + struct xrt_space_relation *const out_relation) +{ + struct xrt_device *const hmd = solarxr_device(xdev)->hmd; + if (hmd != NULL) { + xrt_device_get_tracked_pose(hmd, name, at_timestamp_ns, out_relation); + } +} + +static void +solarxr_device_update_inputs(struct xrt_device *const xdev) +{ + struct solarxr_device *const device = solarxr_device(xdev); + os_mutex_lock(&device->mutex); + for (uint32_t i = 0; i < device->base.input_count; ++i) { + device->base.inputs[i].timestamp = device->timestamp; + } + for (uint32_t i = 0; i < ARRAY_SIZE(device->trackers); ++i) { + if (device->trackers[i] != NULL) { + device->trackers[i]->base.inputs[0].timestamp = device->timestamp; + } + } + os_mutex_unlock(&device->mutex); + + struct xrt_space_relation head = {0}; + solarxr_device_get_tracked_pose(xdev, XRT_INPUT_GENERIC_HEAD_POSE, os_monotonic_get_ns(), &head); + if (head.relation_flags == 0) { + return; + } + char feedback[0x200]; + // clang-format off + unsigned feedback_len = (unsigned)snprintf(feedback, sizeof(feedback), "%s%f%s%f%s%f%s%f%s%f%s%f%s%f%s", "{" + "\"type\":\"pos\"," + "\"tracker_id\":0," + "\"x\":", (double)head.pose.position.x, "," + "\"y\":", (double)head.pose.position.y - .2f, "," // SlimeVR add 0.2 to the WebSocket HMD's Y position for some reason + "\"z\":", (double)head.pose.position.z, "," + "\"qw\":", (double)head.pose.orientation.w, "," + "\"qx\":", (double)head.pose.orientation.x, "," + "\"qy\":", (double)head.pose.orientation.y, "," + "\"qz\":", (double)head.pose.orientation.z, + "}"); + // clang-format on + assert(feedback_len < sizeof(feedback)); + WebSocket_sendWithOpcode(&device->socket, (uint8_t *)feedback, feedback_len, 0x1); +} + +static inline struct xrt_body_skeleton_joint_fb +offset_joint(const struct xrt_body_skeleton_joint_fb parent, const int32_t name, const struct xrt_vec3 offset) +{ + return (struct xrt_body_skeleton_joint_fb){ + .pose = + { + .orientation = parent.pose.orientation, + .position = m_vec3_add(parent.pose.position, offset), + }, + .joint = name, + .parent_joint = parent.joint, + }; +} + +static xrt_result_t +solarxr_device_get_body_skeleton(struct xrt_device *const xdev, + const enum xrt_input_name body_tracking_type, + struct xrt_body_skeleton *const out_value) +{ + struct xrt_body_skeleton_joint_fb *joints; + uint32_t joint_count; + int32_t none; + switch (body_tracking_type) { + case XRT_INPUT_FB_BODY_TRACKING: { + joints = out_value->body_skeleton_fb.joints; + joint_count = ARRAY_SIZE(out_value->body_skeleton_fb.joints); + none = XRT_BODY_JOINT_NONE_FB; + break; + } +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + case XRT_INPUT_META_FULL_BODY_TRACKING: { + joints = out_value->full_body_skeleton_meta.joints; + joint_count = ARRAY_SIZE(out_value->full_body_skeleton_meta.joints); + none = XRT_FULL_BODY_JOINT_NONE_META; + break; + } +#endif + default: return XRT_ERROR_NOT_IMPLEMENTED; + } + + struct solarxr_device *const device = solarxr_device(xdev); + for (uint32_t i = 0; i < joint_count; ++i) { + joints[i] = (struct xrt_body_skeleton_joint_fb){XRT_POSE_IDENTITY, none, none}; + } + + // The spec doesn't define a particular layout for these joints beyond simply "a T-pose", so... + // clang-format off + joints[0] = (struct xrt_body_skeleton_joint_fb){XRT_POSE_IDENTITY, XRT_BODY_JOINT_HEAD_FB, XRT_BODY_JOINT_ROOT_FB}; + joints[1] = offset_joint(joints[0], XRT_BODY_JOINT_NECK_FB, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_NECK].length, 0.f}); + joints[2] = offset_joint(joints[1], XRT_BODY_JOINT_CHEST_FB, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_UPPER_CHEST].length, 0.f}); + joints[3] = offset_joint(joints[2], XRT_BODY_JOINT_SPINE_UPPER_FB, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_CHEST].length, 0.f}); + joints[4] = offset_joint(joints[3], XRT_BODY_JOINT_SPINE_LOWER_FB, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_WAIST].length, 0.f}); + joints[5] = offset_joint(joints[4], XRT_BODY_JOINT_HIPS_FB, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_HIP].length, 0.f}); + joints[6] = offset_joint(joints[1], XRT_BODY_JOINT_LEFT_SHOULDER_FB, (struct xrt_vec3){-device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_SHOULDER].length, 0.f, 0.f}); + joints[7] = offset_joint(joints[1], XRT_BODY_JOINT_RIGHT_SHOULDER_FB, (struct xrt_vec3){device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_SHOULDER].length, 0.f, 0.f}); + joints[8] = offset_joint(joints[6], XRT_BODY_JOINT_LEFT_ARM_UPPER_FB, (struct xrt_vec3){-device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_UPPER_ARM].length, 0.f, 0.f}); + joints[9] = offset_joint(joints[7], XRT_BODY_JOINT_RIGHT_ARM_UPPER_FB, (struct xrt_vec3){device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_UPPER_ARM].length, 0.f, 0.f}); + joints[10] = offset_joint(joints[8], XRT_BODY_JOINT_LEFT_ARM_LOWER_FB, (struct xrt_vec3){-device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_LOWER_ARM].length, 0.f, 0.f}); + joints[11] = offset_joint(joints[9], XRT_BODY_JOINT_RIGHT_ARM_LOWER_FB, (struct xrt_vec3){device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_LOWER_ARM].length, 0.f, 0.f}); + joints[12] = offset_joint(joints[10], XRT_BODY_JOINT_LEFT_HAND_WRIST_FB, (struct xrt_vec3){-device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_HAND].length, 0.f, 0.f}); + joints[13] = offset_joint(joints[11], XRT_BODY_JOINT_RIGHT_HAND_WRIST_FB, (struct xrt_vec3){device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_HAND].length, 0.f, 0.f}); +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + if (body_tracking_type != XRT_INPUT_META_FULL_BODY_TRACKING) { + return XRT_SUCCESS; + } + joints[14] = offset_joint(joints[5], XRT_FULL_BODY_JOINT_LEFT_UPPER_LEG_META, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_UPPER_LEG].length, 0.f}); + joints[15] = offset_joint(joints[5], XRT_FULL_BODY_JOINT_RIGHT_UPPER_LEG_META, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_UPPER_LEG].length, 0.f}); + joints[16] = offset_joint(joints[14], XRT_FULL_BODY_JOINT_LEFT_LOWER_LEG_META, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_LOWER_LEG].length, 0.f}); + joints[17] = offset_joint(joints[15], XRT_FULL_BODY_JOINT_RIGHT_LOWER_LEG_META, (struct xrt_vec3){0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_LOWER_LEG].length, 0.f}); + joints[18] = offset_joint(joints[16], XRT_FULL_BODY_JOINT_LEFT_FOOT_TRANSVERSE_META, (struct xrt_vec3){0.f, 0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_LEFT_FOOT].length}); + joints[19] = offset_joint(joints[17], XRT_FULL_BODY_JOINT_RIGHT_FOOT_TRANSVERSE_META, (struct xrt_vec3){0.f, 0.f, -device->bones[solarxr_protocol_datatypes_BodyPart_RIGHT_FOOT].length}); +#endif + // clang-format on + return XRT_SUCCESS; +} + +static xrt_result_t +solarxr_device_get_body_joints(struct xrt_device *const xdev, + const enum xrt_input_name body_tracking_type, + const int64_t desired_timestamp_ns, + struct xrt_body_joint_set *const out_value) +{ + static const uint32_t jointMap[BodyPart_COUNT] = { + [solarxr_protocol_datatypes_BodyPart_HEAD] = XRT_BODY_JOINT_HEAD_FB, + [solarxr_protocol_datatypes_BodyPart_NECK] = XRT_BODY_JOINT_NECK_FB, + [solarxr_protocol_datatypes_BodyPart_CHEST] = XRT_BODY_JOINT_SPINE_UPPER_FB, + [solarxr_protocol_datatypes_BodyPart_WAIST] = XRT_BODY_JOINT_SPINE_LOWER_FB, + [solarxr_protocol_datatypes_BodyPart_HIP] = XRT_BODY_JOINT_HIPS_FB, +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + [solarxr_protocol_datatypes_BodyPart_LEFT_UPPER_LEG] = XRT_FULL_BODY_JOINT_LEFT_UPPER_LEG_META, + [solarxr_protocol_datatypes_BodyPart_RIGHT_UPPER_LEG] = XRT_FULL_BODY_JOINT_RIGHT_UPPER_LEG_META, + [solarxr_protocol_datatypes_BodyPart_LEFT_LOWER_LEG] = XRT_FULL_BODY_JOINT_LEFT_LOWER_LEG_META, + [solarxr_protocol_datatypes_BodyPart_RIGHT_LOWER_LEG] = XRT_FULL_BODY_JOINT_RIGHT_LOWER_LEG_META, + [solarxr_protocol_datatypes_BodyPart_LEFT_FOOT] = XRT_FULL_BODY_JOINT_LEFT_FOOT_TRANSVERSE_META, + [solarxr_protocol_datatypes_BodyPart_RIGHT_FOOT] = XRT_FULL_BODY_JOINT_RIGHT_FOOT_TRANSVERSE_META, +#endif + [solarxr_protocol_datatypes_BodyPart_LEFT_LOWER_ARM] = XRT_BODY_JOINT_LEFT_ARM_LOWER_FB, + [solarxr_protocol_datatypes_BodyPart_RIGHT_LOWER_ARM] = XRT_BODY_JOINT_RIGHT_ARM_LOWER_FB, + [solarxr_protocol_datatypes_BodyPart_LEFT_UPPER_ARM] = XRT_BODY_JOINT_LEFT_ARM_UPPER_FB, + [solarxr_protocol_datatypes_BodyPart_RIGHT_UPPER_ARM] = XRT_BODY_JOINT_RIGHT_ARM_UPPER_FB, + [solarxr_protocol_datatypes_BodyPart_LEFT_HAND] = XRT_BODY_JOINT_LEFT_HAND_WRIST_FB, + [solarxr_protocol_datatypes_BodyPart_RIGHT_HAND] = XRT_BODY_JOINT_RIGHT_HAND_WRIST_FB, + [solarxr_protocol_datatypes_BodyPart_LEFT_SHOULDER] = XRT_BODY_JOINT_LEFT_SHOULDER_FB, + [solarxr_protocol_datatypes_BodyPart_RIGHT_SHOULDER] = XRT_BODY_JOINT_RIGHT_SHOULDER_FB, + [solarxr_protocol_datatypes_BodyPart_UPPER_CHEST] = XRT_BODY_JOINT_CHEST_FB, + // LEFT_HIP + // RIGHT_HIP + }; + struct xrt_body_joint_location_fb *joints; + uint32_t joint_count; + switch (body_tracking_type) { + case XRT_INPUT_FB_BODY_TRACKING: { + joints = out_value->body_joint_set_fb.joint_locations; + joint_count = ARRAY_SIZE(out_value->body_joint_set_fb.joint_locations); + break; + } +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + case XRT_INPUT_META_FULL_BODY_TRACKING: { + joints = out_value->full_body_joint_set_meta.joint_locations; + joint_count = ARRAY_SIZE(out_value->full_body_joint_set_meta.joint_locations); + break; + } +#endif + default: return XRT_ERROR_NOT_IMPLEMENTED; + } + + struct solarxr_device *const device = solarxr_device(xdev); + os_mutex_lock(&device->mutex); + out_value->base_body_joint_set_meta.sample_time_ns = device->timestamp; + out_value->base_body_joint_set_meta.confidence = 1.f; // N/A + out_value->base_body_joint_set_meta.skeleton_changed_count = device->generation; + out_value->base_body_joint_set_meta.is_active = true; + for (uint32_t i = 0; i < joint_count; ++i) { + joints[i].relation = (struct xrt_space_relation)XRT_SPACE_RELATION_ZERO; + } + for (solarxr_protocol_datatypes_BodyPart_enum_t part = 0; part < ARRAY_SIZE(device->bones); ++part) { + const struct xrt_pose pose = device->bones[part].pose; + const uint32_t index = jointMap[part]; + if (index == 0 || index >= joint_count || + memcmp(&pose.orientation, &(struct xrt_quat){0}, sizeof(struct xrt_quat)) == 0) { + continue; + } + joints[index].relation = (struct xrt_space_relation){ + .relation_flags = XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | + XRT_SPACE_RELATION_POSITION_TRACKED_BIT, + .pose = pose, + }; + } + out_value->body_pose = (struct xrt_space_relation){ + .relation_flags = XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT | XRT_SPACE_RELATION_POSITION_TRACKED_BIT, + .pose = XRT_POSE_IDENTITY, + }; + os_mutex_unlock(&device->mutex); + return XRT_SUCCESS; +} + +static void * +solarxr_network_thread(void *const ptr) +{ + struct solarxr_device *const device = (struct solarxr_device *)ptr; + while (WebSocket_wait(&device->socket)) { + for (size_t buffer_len; (buffer_len = WebSocket_receive(&device->socket)) != 0;) { + if (solarxr_protocol_MessageBundle_verify_as_root(device->socket.buffer, buffer_len)) { + U_LOG_IFL_E(device->socket.log_level, + "solarxr_protocol_MessageBundle_verify_as_root() failed"); + continue; + } + const solarxr_protocol_MessageBundle_table_t bundle = + solarxr_protocol_MessageBundle_as_root(device->socket.buffer); + if (!solarxr_protocol_MessageBundle_data_feed_msgs_is_present(bundle)) { + continue; + } + const solarxr_protocol_data_feed_DataFeedMessageHeader_vec_t feeds = + solarxr_protocol_MessageBundle_data_feed_msgs_get(bundle); + const size_t feeds_len = solarxr_protocol_data_feed_DataFeedMessageHeader_vec_len(feeds); + solarxr_protocol_data_feed_device_data_DeviceData_vec_t devices = NULL; + solarxr_protocol_data_feed_tracker_TrackerData_vec_t trackers = NULL; + solarxr_protocol_data_feed_Bone_vec_t bones = NULL; + for (size_t i = 0; i < feeds_len; ++i) { + const solarxr_protocol_data_feed_DataFeedMessageHeader_table_t header = + solarxr_protocol_data_feed_DataFeedMessageHeader_vec_at(feeds, i); + if (solarxr_protocol_data_feed_DataFeedMessageHeader_message_type_get(header) != + solarxr_protocol_data_feed_DataFeedMessage_DataFeedUpdate) { + continue; + } + solarxr_protocol_data_feed_DataFeedUpdate_table_t update = + solarxr_protocol_data_feed_DataFeedMessageHeader_message_get(header); + if (solarxr_protocol_data_feed_DataFeedUpdate_bones_is_present(update)) { + bones = solarxr_protocol_data_feed_DataFeedUpdate_bones_get(update); + } + if (debug_get_bool_option_solarxr_raw_trackers()) { + if (solarxr_protocol_data_feed_DataFeedUpdate_devices_is_present(update)) { + devices = solarxr_protocol_data_feed_DataFeedUpdate_devices_get(update); + } + } else if (solarxr_protocol_data_feed_DataFeedUpdate_synthetic_trackers_is_present( + update)) { + trackers = + solarxr_protocol_data_feed_DataFeedUpdate_synthetic_trackers_get(update); + } + } + os_mutex_lock(&device->mutex); + uint32_t i = 0, devices_len = 0; + if (trackers != NULL) { + goto synthetic; + } + if (devices == NULL) { + os_mutex_unlock(&device->mutex); + break; + } + for (devices_len = (uint32_t)solarxr_protocol_data_feed_device_data_DeviceData_vec_len(devices); + i < devices_len; ++i) { + const solarxr_protocol_data_feed_device_data_DeviceData_table_t deviceData = + solarxr_protocol_data_feed_device_data_DeviceData_vec_at(devices, i); + if (!solarxr_protocol_data_feed_device_data_DeviceData_trackers_is_present( + deviceData)) { + continue; + } + trackers = solarxr_protocol_data_feed_device_data_DeviceData_trackers_get(deviceData); + synthetic: + for (uint32_t j = 0, + trackers_len = + solarxr_protocol_data_feed_tracker_TrackerData_vec_len(trackers); + j < trackers_len; ++j) { + const solarxr_protocol_data_feed_tracker_TrackerData_table_t trackerData = + solarxr_protocol_data_feed_tracker_TrackerData_vec_at(trackers, j); + const solarxr_protocol_datatypes_TrackerId_table_t idTable = + solarxr_protocol_data_feed_tracker_TrackerData_tracker_id_get(trackerData); + const solarxr_trackerid_t id = + solarxr_protocol_datatypes_TrackerId_tracker_num_get(idTable) | + (solarxr_protocol_datatypes_TrackerId_device_id_is_present(idTable) + ? (uint32_t)solarxr_protocol_datatypes_DeviceId_id_get( + solarxr_protocol_datatypes_TrackerId_device_id_get(idTable)) + << 8 + : 0xffffff00u); + static_assert(sizeof(wchar_t) == sizeof(id), + "Invalid datatype for `wmemchr()`"); + const solarxr_trackerid_t *const match = (const solarxr_trackerid_t *)wmemchr( + (const wchar_t *)device->trackerIds, (wchar_t)id, + ARRAY_SIZE(device->trackerIds)); + if (match == NULL) { + continue; + } + struct solarxr_generic_tracker *const tracker = + device->trackers[match - device->trackerIds]; + if (tracker == NULL) { + continue; + } + struct xrt_space_relation relation = {.pose.orientation.w = 1}; + if (solarxr_protocol_data_feed_tracker_TrackerData_rotation_is_present( + trackerData)) { + const solarxr_protocol_datatypes_math_Quat_struct_t rotation = + solarxr_protocol_data_feed_tracker_TrackerData_rotation_get( + trackerData); + relation.relation_flags |= XRT_SPACE_RELATION_ORIENTATION_VALID_BIT | + XRT_SPACE_RELATION_ORIENTATION_TRACKED_BIT; + relation.pose.orientation = (struct xrt_quat){ + .x = solarxr_protocol_datatypes_math_Quat_x_get(rotation), + .y = solarxr_protocol_datatypes_math_Quat_y_get(rotation), + .z = solarxr_protocol_datatypes_math_Quat_z_get(rotation), + .w = solarxr_protocol_datatypes_math_Quat_w_get(rotation), + }; + } + if (solarxr_protocol_data_feed_tracker_TrackerData_position_is_present( + trackerData)) { + const solarxr_protocol_datatypes_math_Vec3f_struct_t position = + solarxr_protocol_data_feed_tracker_TrackerData_position_get( + trackerData); + relation.relation_flags |= XRT_SPACE_RELATION_POSITION_VALID_BIT | + XRT_SPACE_RELATION_POSITION_TRACKED_BIT; + relation.pose.position = (struct xrt_vec3){ + .x = solarxr_protocol_datatypes_math_Vec3f_x_get(position), + .y = solarxr_protocol_datatypes_math_Vec3f_y_get(position), + .z = solarxr_protocol_datatypes_math_Vec3f_z_get(position), + }; + } + if (solarxr_protocol_data_feed_tracker_TrackerData_raw_angular_velocity_is_present( + trackerData)) { + const solarxr_protocol_datatypes_math_Vec3f_struct_t angular = + solarxr_protocol_data_feed_tracker_TrackerData_raw_angular_velocity_get( + trackerData); + relation.relation_flags |= + XRT_SPACE_RELATION_ANGULAR_VELOCITY_VALID_BIT; + relation.angular_velocity = (struct xrt_vec3){ + .x = solarxr_protocol_datatypes_math_Vec3f_x_get(angular), + .y = solarxr_protocol_datatypes_math_Vec3f_y_get(angular), + .z = solarxr_protocol_datatypes_math_Vec3f_z_get(angular), + }; + } + if (solarxr_protocol_data_feed_tracker_TrackerData_linear_acceleration_is_present( + trackerData)) { + const solarxr_protocol_datatypes_math_Vec3f_struct_t linear = + solarxr_protocol_data_feed_tracker_TrackerData_linear_acceleration_get( + trackerData); + relation.relation_flags |= XRT_SPACE_RELATION_LINEAR_VELOCITY_VALID_BIT; + relation.linear_velocity = (struct xrt_vec3){ + .x = solarxr_protocol_datatypes_math_Vec3f_x_get(linear), + .y = solarxr_protocol_datatypes_math_Vec3f_y_get(linear), + .z = solarxr_protocol_datatypes_math_Vec3f_z_get(linear), + }; + } + if (relation.relation_flags != 0) { + m_relation_history_push(tracker->history, &relation, + device->socket.timestamp); + } + } + } + if (bones != NULL) { + const size_t bones_len = solarxr_protocol_data_feed_Bone_vec_len(bones); + device->timestamp = device->socket.timestamp; + struct solarxr_device_bone newBones[ARRAY_SIZE(device->bones)] = {0}; + for (size_t i = 0; i < bones_len; ++i) { + const solarxr_protocol_data_feed_Bone_table_t bone = + solarxr_protocol_data_feed_Bone_vec_at(bones, i); + const solarxr_protocol_datatypes_BodyPart_enum_t part = + solarxr_protocol_data_feed_Bone_body_part_get(bone); + if (part >= ARRAY_SIZE(device->bones)) { + static bool _once = false; + if (!_once) { + _once = true; + U_LOG_IFL_W(device->socket.log_level, + "Unexpected SolarXR BodyPart %hhu", part); + } + continue; + } + const solarxr_protocol_datatypes_math_Quat_struct_t rotation = + solarxr_protocol_data_feed_Bone_rotation_g_get(bone); + const solarxr_protocol_datatypes_math_Vec3f_struct_t position = + solarxr_protocol_data_feed_Bone_head_position_g_get(bone); + newBones[part].pose = (struct xrt_pose){ + .orientation = + { + .x = solarxr_protocol_datatypes_math_Quat_x_get(rotation), + .y = solarxr_protocol_datatypes_math_Quat_y_get(rotation), + .z = solarxr_protocol_datatypes_math_Quat_z_get(rotation), + .w = solarxr_protocol_datatypes_math_Quat_w_get(rotation), + }, + .position = + { + .x = solarxr_protocol_datatypes_math_Vec3f_x_get(position), + .y = solarxr_protocol_datatypes_math_Vec3f_y_get(position), + .z = solarxr_protocol_datatypes_math_Vec3f_z_get(position), + }, + }; + newBones[part].length = solarxr_protocol_data_feed_Bone_bone_length_get(bone); + } + for (uint32_t i = 0; i < ARRAY_SIZE(device->bones); ++i) { + if (memcmp(&newBones[i].length, &device->bones[i].length, + sizeof(newBones[i].length)) == 0) { + continue; + } + ++device->generation; + break; + } + memcpy(device->bones, newBones, sizeof(device->bones)); + } + os_mutex_unlock(&device->mutex); + } + } + return NULL; +} + +static void +solarxr_device_destroy(struct xrt_device *xdev) +{ + struct solarxr_device *const device = solarxr_device(xdev); + WebSocket_destroy(&device->socket); + if (!pthread_equal(device->thread.thread, pthread_self())) { + os_thread_join(&device->thread); + } + for (uint32_t i = 0; i < ARRAY_SIZE(device->trackers); ++i) { + if (device->trackers[i] == NULL) { + continue; + } + device->trackers[i]->mutex = NULL; + device->trackers[i]->weakRef = NULL; + } + os_mutex_destroy(&device->mutex); + u_device_free(&device->base); +} + +static void +solarxr_generic_tracker_get_tracked_pose(struct xrt_device *const xdev, + const enum xrt_input_name name, + const int64_t at_timestamp_ns, + struct xrt_space_relation *const out_relation) +{ + struct solarxr_generic_tracker *const device = solarxr_generic_tracker(xdev); + if (device->mutex != NULL) { + os_mutex_lock(device->mutex); + } + m_relation_history_get(device->history, at_timestamp_ns, out_relation); + if (device->mutex != NULL) { + os_mutex_unlock(device->mutex); + } +} + +static void +solarxr_generic_tracker_destroy(struct xrt_device *const xdev) +{ + struct solarxr_generic_tracker *const device = solarxr_generic_tracker(xdev); + if (device->weakRef != NULL) { + os_mutex_lock(device->mutex); + *device->weakRef = NULL; + os_mutex_unlock(device->mutex); + } + m_relation_history_destroy(&device->history); + u_device_free(&device->base); +} + +uint32_t +solarxr_device_create_xdevs(struct xrt_device *const hmd, struct xrt_device **const out_xdevs, uint32_t out_xdevs_cap) +{ + if (out_xdevs_cap == 0) { + return 0; + } +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + struct solarxr_device *const device = U_DEVICE_ALLOCATE(struct solarxr_device, U_DEVICE_ALLOC_NO_FLAGS, 2, 0); +#else + struct solarxr_device *const device = U_DEVICE_ALLOCATE(struct solarxr_device, U_DEVICE_ALLOC_NO_FLAGS, 1, 0); +#endif + if (out_xdevs_cap - 1 > ARRAY_SIZE(device->trackers)) { + out_xdevs_cap = 1 + ARRAY_SIZE(device->trackers); + } + device->base.name = XRT_DEVICE_FB_BODY_TRACKING; + device->base.device_type = XRT_DEVICE_TYPE_BODY_TRACKER; + strncpy(device->base.str, "SolarXR WebSockets Connection", sizeof(device->base.str) - 1); + strncpy(device->base.serial, "ws://localhost:21110", sizeof(device->base.serial) - 1); + device->base.tracking_origin = hmd->tracking_origin; + device->base.body_tracking_supported = true; + device->base.update_inputs = solarxr_device_update_inputs; + device->base.get_tracked_pose = solarxr_device_get_tracked_pose; + device->base.get_body_skeleton = solarxr_device_get_body_skeleton; + device->base.get_body_joints = solarxr_device_get_body_joints; + device->base.destroy = solarxr_device_destroy; + device->base.inputs[0].name = XRT_INPUT_FB_BODY_TRACKING; +#ifdef XRT_FEATURE_OPENXR_BODY_TRACKING_FULL_BODY_META + device->base.inputs[1].name = XRT_INPUT_META_FULL_BODY_TRACKING; +#endif + device->hmd = hmd; + device->thread.thread = pthread_self(); + os_mutex_init(&device->mutex); + memset(device->trackerIds, 0xff, sizeof(device->trackerIds)); + if (!WebSocket_init(&device->socket, debug_get_log_option_solarxr_log())) { + solarxr_device_destroy(&device->base); + return 0; + } + if (!WebSocket_handshake(&device->socket)) { + solarxr_device_destroy(&device->base); + return 0; + } + flatcc_builder_t builder; + int result = flatcc_builder_init(&builder); + if (out_xdevs_cap >= 2) { + result = result || flatbuffers_buffer_start(&builder, solarxr_protocol_MessageBundle_file_identifier); + result = result || solarxr_protocol_MessageBundle_start(&builder); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_start(&builder); + result = result || solarxr_protocol_data_feed_PollDataFeed_start(&builder); + result = result || solarxr_protocol_data_feed_DataFeedConfig_start(&builder); + result = result || solarxr_protocol_data_feed_tracker_TrackerDataMask_start(&builder); + result = result || solarxr_protocol_data_feed_tracker_TrackerDataMask_info_add(&builder, true); + const solarxr_protocol_data_feed_tracker_TrackerDataMask_ref_t trackerDataMask = + solarxr_protocol_data_feed_tracker_TrackerDataMask_end(&builder); + if (debug_get_bool_option_solarxr_raw_trackers()) { + result = result || solarxr_protocol_data_feed_device_data_DeviceDataMask_start(&builder); + result = result || solarxr_protocol_data_feed_device_data_DeviceDataMask_tracker_data_add( + &builder, trackerDataMask); + result = result || + solarxr_protocol_data_feed_DataFeedConfig_data_mask_add( + &builder, solarxr_protocol_data_feed_device_data_DeviceDataMask_end(&builder)); + } else { + result = result || solarxr_protocol_data_feed_DataFeedConfig_synthetic_trackers_mask_add( + &builder, trackerDataMask); + } + result = result || solarxr_protocol_data_feed_PollDataFeed_config_add( + &builder, solarxr_protocol_data_feed_DataFeedConfig_end(&builder)); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_message_add_value( + &builder, solarxr_protocol_data_feed_DataFeedMessage_as_PollDataFeed( + solarxr_protocol_data_feed_PollDataFeed_end(&builder))); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_message_add_type( + &builder, solarxr_protocol_data_feed_DataFeedMessage_PollDataFeed); + result = result || solarxr_protocol_MessageBundle_data_feed_msgs_add( + &builder, solarxr_protocol_data_feed_DataFeedMessageHeader_vec_create( + &builder, + (solarxr_protocol_data_feed_DataFeedMessageHeader_ref_t[1]){ + solarxr_protocol_data_feed_DataFeedMessageHeader_end(&builder), + }, + 1)); + result = result || !flatbuffers_buffer_end(&builder, solarxr_protocol_MessageBundle_end(&builder)); + assert(result == 0); + size_t packet_len = 0; + uint8_t *const packet = flatcc_builder_get_direct_buffer(&builder, &packet_len); + result = WebSocket_send(&device->socket, packet, packet_len); + if (!result) { + U_LOG_IFL_E(device->socket.log_level, "WebSocket_send() failed"); + solarxr_device_destroy(&device->base); + return 0; + } + result = flatcc_builder_reset(&builder); + size_t buffer_len = 0; + do { + if (!WebSocket_wait(&device->socket)) { + U_LOG_IFL_E(device->socket.log_level, "WebSocket_receive() failed"); + solarxr_device_destroy(&device->base); + return 0; + } + buffer_len = WebSocket_receive(&device->socket); + } while (buffer_len == 0); + if (solarxr_protocol_MessageBundle_verify_as_root(device->socket.buffer, buffer_len)) { + U_LOG_IFL_E(device->socket.log_level, "solarxr_protocol_MessageBundle_verify_as_root() failed"); + solarxr_device_destroy(&device->base); + return 0; + } + const solarxr_protocol_MessageBundle_table_t bundle = + solarxr_protocol_MessageBundle_as_root(device->socket.buffer); + if (!solarxr_protocol_MessageBundle_data_feed_msgs_is_present(bundle)) { + U_LOG_IFL_E(device->socket.log_level, "Missing data feed"); + solarxr_device_destroy(&device->base); + return 0; + } + const solarxr_protocol_data_feed_DataFeedMessageHeader_vec_t feeds = + solarxr_protocol_MessageBundle_data_feed_msgs_get(bundle); + if (solarxr_protocol_data_feed_DataFeedMessageHeader_vec_len(feeds) != 1) { + U_LOG_IFL_E(device->socket.log_level, "Unexpected data feed count"); + solarxr_device_destroy(&device->base); + return 0; + } + const solarxr_protocol_data_feed_DataFeedMessageHeader_table_t header = + solarxr_protocol_data_feed_DataFeedMessageHeader_vec_at(feeds, 0); + if (solarxr_protocol_data_feed_DataFeedMessageHeader_message_type_get(header) != + solarxr_protocol_data_feed_DataFeedMessage_DataFeedUpdate) { + U_LOG_IFL_E(device->socket.log_level, "Unexpected data feed message type"); + solarxr_device_destroy(&device->base); + return 0; + } + solarxr_protocol_data_feed_DataFeedUpdate_table_t update = + solarxr_protocol_data_feed_DataFeedMessageHeader_message_get(header); + uint32_t trackerDescs_len = 0; + solarxr_protocol_data_feed_tracker_TrackerData_table_t trackerDescs[ARRAY_SIZE(device->trackers)]; + if (debug_get_bool_option_solarxr_raw_trackers()) { + if (solarxr_protocol_data_feed_DataFeedUpdate_devices_is_present(update)) { + const solarxr_protocol_data_feed_device_data_DeviceData_vec_t devices = + solarxr_protocol_data_feed_DataFeedUpdate_devices_get(update); + const uint32_t devices_len = + (uint32_t)solarxr_protocol_data_feed_device_data_DeviceData_vec_len(devices); + for (uint32_t i = 0; i < devices_len; ++i) { + const solarxr_protocol_data_feed_device_data_DeviceData_table_t deviceData = + solarxr_protocol_data_feed_device_data_DeviceData_vec_at(devices, i); + if (!solarxr_protocol_data_feed_device_data_DeviceData_trackers_is_present( + deviceData)) { + continue; + } + const solarxr_protocol_data_feed_tracker_TrackerData_vec_t trackers = + solarxr_protocol_data_feed_device_data_DeviceData_trackers_get(deviceData); + for (uint32_t i = 0, trackers_len = + solarxr_protocol_data_feed_tracker_TrackerData_vec_len( + trackers); + i < trackers_len && trackerDescs_len < ARRAY_SIZE(trackerDescs); ++i) { + trackerDescs[trackerDescs_len++] = + solarxr_protocol_data_feed_tracker_TrackerData_vec_at(trackers, i); + } + } + } + } else if (solarxr_protocol_data_feed_DataFeedUpdate_synthetic_trackers_is_present(update)) { + const solarxr_protocol_data_feed_tracker_TrackerData_vec_t trackers = + solarxr_protocol_data_feed_DataFeedUpdate_synthetic_trackers_get(update); + for (uint32_t i = 0, + trackers_len = solarxr_protocol_data_feed_tracker_TrackerData_vec_len(trackers); + i < trackers_len && trackerDescs_len < ARRAY_SIZE(trackerDescs); ++i) { + trackerDescs[trackerDescs_len++] = + solarxr_protocol_data_feed_tracker_TrackerData_vec_at(trackers, i); + } + } + if (trackerDescs_len > out_xdevs_cap - 1) { + trackerDescs_len = out_xdevs_cap - 1; + } + for (uint32_t i = 0; i < trackerDescs_len; ++i) { + const solarxr_protocol_datatypes_TrackerId_table_t idTable = + solarxr_protocol_data_feed_tracker_TrackerData_tracker_id_get(trackerDescs[i]); + const solarxr_trackerid_t id = + solarxr_protocol_datatypes_TrackerId_tracker_num_get(idTable) | + (solarxr_protocol_datatypes_TrackerId_device_id_is_present(idTable) + ? (uint32_t)solarxr_protocol_datatypes_DeviceId_id_get( + solarxr_protocol_datatypes_TrackerId_device_id_get(idTable)) + << 8 + : 0xffffff00u); + + struct solarxr_generic_tracker *const tracker = + U_DEVICE_ALLOCATE(struct solarxr_generic_tracker, U_DEVICE_ALLOC_NO_FLAGS, 1, 0); + tracker->base.name = XRT_DEVICE_VIVE_TRACKER; // TODO: use different name here? + tracker->base.device_type = XRT_DEVICE_TYPE_GENERIC_TRACKER; + snprintf(tracker->base.str, sizeof(tracker->base.str), "SolarXR Tracker %04x", id); + snprintf(tracker->base.serial, sizeof(tracker->base.serial), "%04x", id); + tracker->base.tracking_origin = hmd->tracking_origin; + tracker->base.orientation_tracking_supported = true; + tracker->base.position_tracking_supported = true; + tracker->base.update_inputs = u_device_noop_update_inputs; + tracker->base.get_tracked_pose = solarxr_generic_tracker_get_tracked_pose; + tracker->base.destroy = solarxr_generic_tracker_destroy; + tracker->base.inputs[0].name = XRT_INPUT_GENERIC_TRACKER_POSE; + tracker->mutex = &device->mutex; + m_relation_history_create(&tracker->history); + tracker->weakRef = &device->trackers[i]; + device->trackers[i] = tracker; + device->trackerIds[i] = id; + + if (!solarxr_protocol_data_feed_tracker_TrackerData_info_is_present(trackerDescs[i])) { + continue; + } + const solarxr_protocol_data_feed_tracker_TrackerInfo_table_t info = + solarxr_protocol_data_feed_tracker_TrackerData_info_get(trackerDescs[i]); + if (!solarxr_protocol_data_feed_tracker_TrackerInfo_display_name_is_present(info)) { + continue; + } + snprintf(tracker->base.str, sizeof(tracker->base.str), "SolarXR Tracker \"%s\"", + solarxr_protocol_data_feed_tracker_TrackerInfo_display_name_get(info)); + } + } + // Once IPC is implemented, this should be switched out for synchronous polling in xrt_device_update_inputs + result = result || flatbuffers_buffer_start(&builder, solarxr_protocol_MessageBundle_file_identifier); + result = result || solarxr_protocol_MessageBundle_start(&builder); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_start(&builder); + result = result || solarxr_protocol_data_feed_StartDataFeed_start(&builder); + result = result || solarxr_protocol_data_feed_DataFeedConfig_start(&builder); + result = + result || solarxr_protocol_data_feed_DataFeedConfig_minimum_time_since_last_add(&builder, updateIntervalMs); + if (out_xdevs_cap >= 2) { + result = result || solarxr_protocol_data_feed_tracker_TrackerDataMask_start(&builder); + result = result || solarxr_protocol_data_feed_tracker_TrackerDataMask_rotation_add(&builder, true); + result = result || solarxr_protocol_data_feed_tracker_TrackerDataMask_position_add(&builder, true); + result = result || + solarxr_protocol_data_feed_tracker_TrackerDataMask_raw_angular_velocity_add(&builder, true); + result = result || + solarxr_protocol_data_feed_tracker_TrackerDataMask_linear_acceleration_add(&builder, true); + const solarxr_protocol_data_feed_tracker_TrackerDataMask_ref_t trackerDataMask = + solarxr_protocol_data_feed_tracker_TrackerDataMask_end(&builder); + if (debug_get_bool_option_solarxr_raw_trackers()) { + result = result || solarxr_protocol_data_feed_device_data_DeviceDataMask_start(&builder); + result = result || solarxr_protocol_data_feed_device_data_DeviceDataMask_tracker_data_add( + &builder, trackerDataMask); + result = result || + solarxr_protocol_data_feed_DataFeedConfig_data_mask_add( + &builder, solarxr_protocol_data_feed_device_data_DeviceDataMask_end(&builder)); + } else { + result = result || solarxr_protocol_data_feed_DataFeedConfig_synthetic_trackers_mask_add( + &builder, trackerDataMask); + } + } + result = result || solarxr_protocol_data_feed_DataFeedConfig_bone_mask_add(&builder, true); + result = result || solarxr_protocol_data_feed_StartDataFeed_data_feeds_add( + &builder, solarxr_protocol_data_feed_DataFeedConfig_vec_create( + &builder, + (solarxr_protocol_data_feed_DataFeedConfig_ref_t[1]){ + solarxr_protocol_data_feed_DataFeedConfig_end(&builder), + }, + 1)); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_message_add_value( + &builder, solarxr_protocol_data_feed_DataFeedMessage_as_StartDataFeed( + solarxr_protocol_data_feed_StartDataFeed_end(&builder))); + result = result || solarxr_protocol_data_feed_DataFeedMessageHeader_message_add_type( + &builder, solarxr_protocol_data_feed_DataFeedMessage_StartDataFeed); + result = result || solarxr_protocol_MessageBundle_data_feed_msgs_add( + &builder, solarxr_protocol_data_feed_DataFeedMessageHeader_vec_create( + &builder, + (solarxr_protocol_data_feed_DataFeedMessageHeader_ref_t[1]){ + solarxr_protocol_data_feed_DataFeedMessageHeader_end(&builder), + }, + 1)); + result = result || !flatbuffers_buffer_end(&builder, solarxr_protocol_MessageBundle_end(&builder)); + assert(result == 0); + size_t packet_len = 0; + uint8_t *const packet = flatcc_builder_get_direct_buffer(&builder, &packet_len); + result = WebSocket_send(&device->socket, packet, packet_len); + flatcc_builder_clear(&builder); + if (!result) { + U_LOG_IFL_E(device->socket.log_level, "WebSocket_send() failed"); + for (uint32_t i = 0; i < ARRAY_SIZE(device->trackers); ++i) { + if (device->trackers[i] != NULL) { + solarxr_generic_tracker_destroy(&device->trackers[i]->base); + } + } + solarxr_device_destroy(&device->base); + return 0; + } + if (os_thread_start(&device->thread, solarxr_network_thread, device) != 0) { + U_LOG_IFL_E(device->socket.log_level, "pthread_create() failed"); + for (uint32_t i = 0; i < ARRAY_SIZE(device->trackers); ++i) { + if (device->trackers[i] != NULL) { + solarxr_generic_tracker_destroy(&device->trackers[i]->base); + } + } + solarxr_device_destroy(&device->base); + return 0; + } + uint32_t trackerCount = 0; + out_xdevs[trackerCount++] = &device->base; + for (uint32_t i = 0; i < ARRAY_SIZE(device->trackers); ++i) { + if (device->trackers[i] == NULL) { + continue; + } + assert(trackerCount < out_xdevs_cap); + out_xdevs[trackerCount++] = &device->trackers[i]->base; + } + return trackerCount; +} diff --git a/src/xrt/drivers/solarxr/solarxr_device.h b/src/xrt/drivers/solarxr/solarxr_device.h new file mode 100644 index 000000000..eb15d4edc --- /dev/null +++ b/src/xrt/drivers/solarxr/solarxr_device.h @@ -0,0 +1,34 @@ +// Copyright 2024, rcelyte +// SPDX-License-Identifier: BSL-1.0 +/*! + * @file + * @brief SolarXR protocol bridge device + * @ingroup drv_solarxr + */ + +#pragma once + +#include +#include +struct xrt_tracking_origin; +struct xrt_device; + +#ifdef __cplusplus +extern "C" { +#endif + +uint32_t +solarxr_device_create_xdevs(struct xrt_device *hmd, struct xrt_device **out_xdevs, uint32_t out_xdevs_cap); + +static inline struct xrt_device * +solarxr_device_create(struct xrt_device *const hmd) +{ + struct xrt_device *out = NULL; + const uint32_t result = solarxr_device_create_xdevs(hmd, &out, 1); + return result ? out : NULL; +} + + +#ifdef __cplusplus +} +#endif diff --git a/src/xrt/drivers/solarxr/websocket.c b/src/xrt/drivers/solarxr/websocket.c new file mode 100644 index 000000000..9505e18ea --- /dev/null +++ b/src/xrt/drivers/solarxr/websocket.c @@ -0,0 +1,378 @@ +// Copyright 2024, rcelyte +// SPDX-License-Identifier: BSL-1.0 + +#include "websocket.h" +#include "os/os_time.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool +ValidateDigest(const char base64[28], const uint8_t key[16]) +{ + const uint8_t map[0x80] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, + }; + assert(base64[27] == '='); + const char *base64_it = base64; + uint8_t digest[21], *digest_it = digest; + while (base64_it < &base64[28]) { + uint32_t word = 0; + for (const char *end = &base64_it[4]; base64_it < end; ++base64_it) { + word = word << 6 | map[*base64_it & 0x7f]; + } + for (const uint8_t *end = &digest_it[2]; digest_it <= end; ++digest_it) { + *digest_it = (uint8_t)(word >> (end - digest_it) * 8); + } + } + uint8_t source[16 + 36]; + memcpy(source, key, 16); + memcpy(&source[16], "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", 36); + uint32_t W[80], H[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0}; + const uint64_t bitlen = ((uint64_t)sizeof(source)) * 8; + const uint32_t loopcount = (sizeof(source) + 8) / 64 + 1, tailLen = 64 * loopcount - sizeof(source); + uint8_t tail[128] = {0x80}; + tail[tailLen - 8] = (uint8_t)(bitlen >> 56); + tail[tailLen - 7] = (uint8_t)(bitlen >> 48); + tail[tailLen - 6] = (uint8_t)(bitlen >> 40); + tail[tailLen - 5] = (uint8_t)(bitlen >> 32); + tail[tailLen - 4] = (uint8_t)(bitlen >> 24); + tail[tailLen - 3] = (uint8_t)(bitlen >> 16); + tail[tailLen - 2] = (uint8_t)(bitlen >> 8); + tail[tailLen - 1] = (uint8_t)(bitlen >> 0); + for (uint32_t lidx = 0, didx = 0; lidx < loopcount; lidx++) { + memset(W, 0, 80 * sizeof(uint32_t)); + for (uint32_t widx = 0; widx < 16; widx++) { + int32_t wcount = 24; + while (didx < sizeof(source) && wcount >= 0) { + W[widx] += (((uint32_t)source[didx]) << wcount); + didx++; + wcount -= 8; + } + while (wcount >= 0) { + W[widx] += (((uint32_t)tail[didx - sizeof(source)]) << wcount); + didx++; + wcount -= 8; + } + } + for (uint32_t widx = 16; widx < 32; widx++) { + const uint32_t value = W[widx - 3] ^ W[widx - 8] ^ W[widx - 14] ^ W[widx - 16]; + W[widx] = value << 1 | value >> 31; + } + for (uint32_t widx = 32; widx < 80; widx++) { + const uint32_t value = W[widx - 6] ^ W[widx - 16] ^ W[widx - 28] ^ W[widx - 32]; + W[widx] = value << 2 | value >> 30; + } + uint32_t a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = 0, k = 0; + for (uint32_t stage = 0, idx = 0; stage < 4; ++stage) { + for (uint32_t end = idx + 20; idx < end; ++idx) { + // clang-format off + switch (stage) { + case 0: f = (b & c) | ((~b) & d); k = 0x5a827999; break; + case 1: f = b ^ c ^ d; k = 0x6ed9eba1; break; + case 2: f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; break; + case 3: f = b ^ c ^ d; k = 0xca62c1d6; break; + } + // clang-format on + const uint32_t temp = (a << 5 | a >> 27) + f + e + k + W[idx]; + e = d; + d = c; + c = b << 30 | b >> 2; + b = a; + a = temp; + } + } + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + } + for (uint32_t i = 0; i < 20; ++i) { + if (digest[i] != (uint8_t)(H[i / 4] >> (24 - (i % 4) * 8))) { + return false; + } + } + return true; +} + +struct PacketHeader +{ + uint8_t opcode : 4, rsv3 : 1, rsv2 : 1, rsv1 : 1, fin : 1, len : 7, mask : 1, optional[12]; +}; + +bool +WebSocket_init(struct WebSocket *const state, const enum u_logging_level log_level) +{ + state->sockfd = socket(AF_INET, SOCK_STREAM, 0); + state->log_level = log_level; + state->timestamp = (int64_t)os_monotonic_get_ns(); + state->opcode = 0; + state->finished = true; + state->end = state->head = state->buffer; + memset(state->mask, 0, sizeof(state->mask)); + if (state->sockfd == -1) { + U_LOG_IFL_E(log_level, "socket() failed"); + return false; + } + return true; +} + +void +WebSocket_destroy(struct WebSocket *const state) +{ + const int sockfd = atomic_exchange(&state->sockfd, -1); + if (sockfd == -1) { + return; + } + shutdown(sockfd, SHUT_RDWR); // unblock `WebSocket_wait()` + while (atomic_load(&state->sockfd_pin) != 0) + sched_yield(); + close(sockfd); +} + +bool +WebSocket_handshake(const struct WebSocket *const state) +{ + const struct sockaddr_in localhost = {AF_INET, htons(21110), {htonl(INADDR_LOOPBACK)}, {0}}; + if (connect(state->sockfd, (const struct sockaddr *)&localhost, sizeof(struct sockaddr_in)) != 0) { + U_LOG_IFL_E(state->log_level, "connect() failed: %s", strerror(errno)); + return false; + } + uint8_t buffer[0x2000]; + uint32_t buffer_len = 0; + uint8_t key[16]; + { + __uint128_t keyValue = (__uint128_t)(unsigned)rand() | (__uint128_t)(unsigned)rand() << 32u | + (__uint128_t)(unsigned)rand() << 64u | (__uint128_t)(unsigned)rand() << 96u; + for (uint32_t i = 0; i < sizeof(key); ++i) { + key[i] = (keyValue % 96) + 32; + keyValue /= 96; + } + buffer_len = snprintf((char *)buffer, sizeof(buffer), "%s%.*s%s", + "GET / HTTP/1.1\r\n" + "Host: localhost:8080\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-Websocket-Key: ", + (int)sizeof(key), (const char *)key, + "\r\n" + "Sec-Websocket-Version: 13\r\n" + "\r\n"); + assert(buffer_len == 145); + if (send(state->sockfd, buffer, buffer_len, MSG_NOSIGNAL) != buffer_len) { + U_LOG_IFL_E(state->log_level, "send() failed"); + return false; + } + } + for (buffer_len = 0; buffer_len < 4 || memcmp(&buffer[buffer_len - 4], "\r\n\r\n", 4) != 0;) { + const ssize_t fragmentLength = + recv(state->sockfd, &buffer[buffer_len], sizeof(buffer) - 1 - buffer_len, 0); + if (fragmentLength <= 0) { + U_LOG_IFL_E(state->log_level, "recv() failed: %s", strerror(errno)); + return false; + } + buffer_len += fragmentLength; + } + if (buffer_len < 40 || memcmp(buffer, "HTTP/1.1 101", 12) != 0) { + U_LOG_IFL_E(state->log_level, "Bad HTTP response"); + return false; + } + buffer[buffer_len] = 0; + char *acceptBase64 = strstr((char *)buffer, "\r\nSec-WebSocket-Accept: "); + if (acceptBase64 == NULL) { + U_LOG_IFL_E(state->log_level, "Missing HTTP 'Sec-WebSocket-Accept' header"); + return false; + } + acceptBase64 += 24; + if (strstr(acceptBase64, "\r\n") != &acceptBase64[28] || !ValidateDigest(acceptBase64, key)) { + U_LOG_IFL_E(state->log_level, "Bad WebSocket accept nonce"); + return false; + } + return true; +} + +bool +WebSocket_wait(struct WebSocket *const state) +{ + atomic_fetch_add(&state->sockfd_pin, 1); + struct pollfd sockfd = {atomic_load(&state->sockfd), POLLIN, 0}; + bool result = false; + if (sockfd.fd != -1) { + result = poll(&sockfd, 1, -1) != -1 || errno == EINTR; + } + atomic_fetch_sub(&state->sockfd_pin, 1); + return result; +} + +bool +WebSocket_sendWithOpcode(struct WebSocket *const state, uint8_t packet[], const size_t packet_len, const uint8_t opcode) +{ + atomic_fetch_add(&state->sockfd_pin, 1); + const int sockfd = atomic_load(&state->sockfd); + if (sockfd == -1) { + atomic_fetch_sub(&state->sockfd_pin, 1); + return false; + } + struct PacketHeader header = { + .opcode = opcode, + .fin = true, + .mask = true, + }; + uint8_t payloadLength_len; + if (packet_len < 126) { + header.len = (uint8_t)packet_len; + payloadLength_len = 0; + } else if (packet_len < 0x10000) { + header.len = 126; + payloadLength_len = sizeof(uint16_t); + header.optional[0] = (uint8_t)(packet_len >> 8); + header.optional[1] = (uint8_t)packet_len; + } else { + header.len = 127; + payloadLength_len = sizeof(uint64_t); + header.optional[0] = (uint8_t)(packet_len >> 56); + header.optional[1] = (uint8_t)(packet_len >> 48); + header.optional[2] = (uint8_t)(packet_len >> 40); + header.optional[3] = (uint8_t)(packet_len >> 32); + header.optional[4] = (uint8_t)(packet_len >> 24); + header.optional[5] = (uint8_t)(packet_len >> 16); + header.optional[6] = (uint8_t)(packet_len >> 8); + header.optional[7] = (uint8_t)packet_len; + } + uint8_t *mask = &header.optional[payloadLength_len]; + memcpy(mask, (uint32_t[1]){rand()}, sizeof(uint32_t)); + for (size_t i = 0; i < packet_len; ++i) { + packet[i] ^= mask[i % sizeof(uint32_t)]; + } + const ssize_t result = sendmsg(sockfd, + &(const struct msghdr){ + .msg_iov = + (struct iovec[2]){ + {&header, 2 + payloadLength_len + sizeof(uint32_t)}, + {packet, packet_len}, + }, + .msg_iovlen = 2, + }, + MSG_NOSIGNAL); + atomic_fetch_sub(&state->sockfd_pin, 1); + return ((size_t)result == 2 + payloadLength_len + sizeof(uint32_t) + packet_len); +} + +size_t +WebSocket_receive(struct WebSocket *const state) +{ + atomic_fetch_add(&state->sockfd_pin, 1); + const int sockfd = atomic_load(&state->sockfd); + if (sockfd == -1) { + atomic_fetch_sub(&state->sockfd_pin, 1); + return 0; + } + while (true) { + if (state->head == state->end) { + struct PacketHeader header = {0}; + ssize_t length = recv(sockfd, &header, sizeof(header), MSG_PEEK | MSG_DONTWAIT); + const uint32_t payloadLength_len = + sizeof(uint16_t) * (header.len == 126) + sizeof(uint64_t) * (header.len == 127); + const uint32_t header_len = 2 + payloadLength_len + sizeof(uint32_t) * header.mask; + if (length < 0 && errno != EAGAIN) { + U_LOG_IFL_E(state->log_level, "recv() failed: %s", strerror(errno)); + break; + } + if (length < header_len) { + atomic_fetch_sub(&state->sockfd_pin, 1); + return 0; + } + length = recv(sockfd, &header, header_len, MSG_DONTWAIT); + if (length != header_len) { + U_LOG_IFL_E(state->log_level, "recv() failed: %s", + (length < 0) ? strerror(errno) : "bad length"); + break; + } + const uint64_t fragmentLength = + (header.len < 126) ? (uint64_t)header.len + : (header.len == 126) + ? (uint64_t)header.optional[0] << 8 | (uint64_t)header.optional[1] + : (uint64_t)header.optional[0] << 56 | (uint64_t)header.optional[1] << 48 | + (uint64_t)header.optional[2] << 40 | (uint64_t)header.optional[3] << 32 | + (uint64_t)header.optional[4] << 24 | (uint64_t)header.optional[5] << 16 | + (uint64_t)header.optional[6] << 8 | (uint64_t)header.optional[7]; + if (fragmentLength > (uint64_t)(size_t)(&state->buffer[sizeof(state->buffer)] - state->end)) { + U_LOG_IFL_E(state->log_level, "Packet too large"); + break; + } + if (state->finished) { + state->timestamp = (int64_t)os_monotonic_get_ns(); + state->opcode = header.opcode; + state->end = state->head = state->buffer; + } + if (!header.mask) { + memset(state->mask, 0, sizeof(state->mask)); + } else { + for (size_t i = 0, shift = (size_t)(state->head - state->buffer); i < 4; ++i) { + state->mask[(shift + i) % sizeof(state->mask)] = + header.optional[payloadLength_len + i]; + } + } + state->finished = header.fin; + state->end += fragmentLength; + } else { + const ssize_t length = + recv(sockfd, state->head, (size_t)(state->end - state->head), MSG_DONTWAIT); + if (length < 0 && errno != EAGAIN) { + U_LOG_IFL_E(state->log_level, "recv() failed: %s", strerror(errno)); + break; + } + if (length <= 0) { + atomic_fetch_sub(&state->sockfd_pin, 1); + return 0; + } + if (memcmp(state->mask, (const uint8_t[sizeof(state->mask)]){0}, sizeof(state->mask)) != 0) { + for (size_t i = 0, shift = (size_t)(state->head - state->buffer); i < (size_t)length; + ++i) { + state->head[i] ^= state->mask[(shift + i) % sizeof(state->mask)]; + } + } + state->head += (size_t)length; + } + if (state->head == state->end && state->finished) { + switch (state->opcode) { + case 0x1: + U_LOG_IFL_D(state->log_level, "TEXT - %.*s", + (unsigned)(size_t)(state->head - state->buffer), state->buffer); + break; + case 0x2: { + atomic_fetch_sub(&state->sockfd_pin, 1); + return (size_t)(state->head - state->buffer); + } + case 0x8: goto fail; + case 0x9: + if (!WebSocket_sendWithOpcode(state, state->buffer, + (size_t)(state->head - state->buffer), 0xa)) { + U_LOG_IFL_E(state->log_level, "WebSocket_sendWithOpcode(pong) failed"); + goto fail; + } + case 0xa: break; + default: { + U_LOG_IFL_E(state->log_level, "Unrecognized opcode: 0x%x", state->opcode); + goto fail; + } + } + } + } +fail: + atomic_fetch_sub(&state->sockfd_pin, 1); + WebSocket_destroy(state); + return 0; +} diff --git a/src/xrt/drivers/solarxr/websocket.h b/src/xrt/drivers/solarxr/websocket.h new file mode 100644 index 000000000..4cde54cac --- /dev/null +++ b/src/xrt/drivers/solarxr/websocket.h @@ -0,0 +1,35 @@ +// Copyright 2024, rcelyte +// SPDX-License-Identifier: BSL-1.0 + +#pragma once +#include "util/u_logging.h" + +struct WebSocket +{ + _Atomic(int) sockfd; + _Atomic(uint32_t) sockfd_pin; + enum u_logging_level log_level; + int64_t timestamp; + uint8_t opcode; + bool finished; + uint8_t *head, *end, mask[4], buffer[0x8000]; +}; + +bool +WebSocket_init(struct WebSocket *state, enum u_logging_level log_level); +void +WebSocket_destroy(struct WebSocket *state); // threadsafe +bool +WebSocket_handshake(const struct WebSocket *state); +bool +WebSocket_wait(struct WebSocket *state); +bool +WebSocket_sendWithOpcode(struct WebSocket *state, uint8_t packet[], size_t packet_len, uint8_t opcode); // threadsafe +size_t +WebSocket_receive(struct WebSocket *state); + +static inline bool +WebSocket_send(struct WebSocket *const state, uint8_t packet[], const size_t packet_len) +{ + return WebSocket_sendWithOpcode(state, packet, packet_len, 0x2); +} diff --git a/src/xrt/targets/common/CMakeLists.txt b/src/xrt/targets/common/CMakeLists.txt index e2b9ba79d..1fbf5f436 100644 --- a/src/xrt/targets/common/CMakeLists.txt +++ b/src/xrt/targets/common/CMakeLists.txt @@ -201,6 +201,10 @@ if(XRT_BUILD_DRIVER_SIMULAVR) target_link_libraries(target_lists PRIVATE drv_svr) endif() +if(XRT_BUILD_DRIVER_SOLARXR) + target_link_libraries(target_lists PRIVATE drv_solarxr) +endif() + #### # Instance # diff --git a/src/xrt/targets/common/target_builder_lighthouse.c b/src/xrt/targets/common/target_builder_lighthouse.c index f58782ff6..65c873a76 100644 --- a/src/xrt/targets/common/target_builder_lighthouse.c +++ b/src/xrt/targets/common/target_builder_lighthouse.c @@ -58,6 +58,10 @@ #include "opengloves/opengloves_interface.h" #endif +#ifdef XRT_BUILD_DRIVER_SOLARXR +#include "solarxr/solarxr_device.h" +#endif + #if defined(XRT_BUILD_DRIVER_SURVIVE) #define DEFAULT_DRIVER "survive" #else @@ -736,6 +740,15 @@ end_valve_index: try_add_opengloves(left, right, &left_ht, &right_ht); } +#ifdef XRT_BUILD_DRIVER_SOLARXR + const uint32_t count = solarxr_device_create_xdevs(head, &xsysd->xdevs[xsysd->xdev_count], + ARRAY_SIZE(xsysd->xdevs) - xsysd->xdev_count); + if (count != 0) { + xsysd->static_roles.body = xsysd->xdevs[xsysd->xdev_count]; + } + xsysd->xdev_count += count; +#endif + // Assign to role(s). ubrh->head = head; ubrh->left = left; diff --git a/src/xrt/targets/common/target_builder_qwerty.c b/src/xrt/targets/common/target_builder_qwerty.c index 2c66ad303..26d96aa14 100644 --- a/src/xrt/targets/common/target_builder_qwerty.c +++ b/src/xrt/targets/common/target_builder_qwerty.c @@ -18,6 +18,10 @@ #include "qwerty/qwerty_interface.h" +#ifdef XRT_BUILD_DRIVER_SOLARXR +#include "solarxr/solarxr_device.h" +#endif + #include @@ -100,6 +104,15 @@ qwerty_open_system_impl(struct xrt_builder *xb, ubrh->left = left; ubrh->right = right; +#ifdef XRT_BUILD_DRIVER_SOLARXR + const uint32_t count = solarxr_device_create_xdevs(head, &xsysd->xdevs[xsysd->xdev_count], + ARRAY_SIZE(xsysd->xdevs) - xsysd->xdev_count); + if (count != 0) { + xsysd->static_roles.body = xsysd->xdevs[xsysd->xdev_count]; + } + xsysd->xdev_count += count; +#endif + return XRT_SUCCESS; } diff --git a/src/xrt/targets/common/target_builder_steamvr.c b/src/xrt/targets/common/target_builder_steamvr.c index 814656519..f0b7de8a0 100644 --- a/src/xrt/targets/common/target_builder_steamvr.c +++ b/src/xrt/targets/common/target_builder_steamvr.c @@ -34,6 +34,10 @@ #include "xrt/xrt_space.h" #include "util/u_space_overseer.h" +#ifdef XRT_BUILD_DRIVER_SOLARXR +#include "solarxr/solarxr_device.h" +#endif + #ifndef XRT_BUILD_DRIVER_STEAMVR_LIGHTHOUSE #error "This builder requires the SteamVR Lighthouse driver" #endif @@ -153,6 +157,15 @@ steamvr_open_system(struct xrt_builder *xb, svrb->right_ht = u_system_devices_get_ht_device_right(xsysd); xsysd->static_roles.hand_tracking.right = svrb->right_ht; +#ifdef XRT_BUILD_DRIVER_SOLARXR + const uint32_t count = solarxr_device_create_xdevs(xsysd->static_roles.head, &xsysd->xdevs[xsysd->xdev_count], + ARRAY_SIZE(xsysd->xdevs) - xsysd->xdev_count); + if (count != 0) { + xsysd->static_roles.body = xsysd->xdevs[xsysd->xdev_count]; + } + xsysd->xdev_count += count; +#endif + /* * Space overseer. */ -- 2.44.2