diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index 58be90a81..231b6259b 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -457,7 +457,9 @@ mounting_selection_menu-close = Close ## Sidebar settings settings-sidebar-title = Settings settings-sidebar-general = General -settings-sidebar-output = Output +settings-sidebar-outputs = Outputs +settings-sidebar-routing = Bone Routing +settings-sidebar-driver = SteamVR / Monado settings-sidebar-resets = Resets settings-sidebar-stay_aligned = Stay Aligned settings-sidebar-tracking = Tracking @@ -476,36 +478,60 @@ settings-sidebar-firmware-tool = DIY Firmware Tool settings-sidebar-vrc_warnings = VRChat Config Warnings settings-sidebar-advanced = Advanced -## Output settings -# Some keys have steamvr in them as we switched to output but want to keep existing translations -settings-general-output = Output Settings -settings-general-output_trackers = Output trackers -# Not all translation keys support multiline, only the ones that specify it will actually -# split it in lines (that also means you can split in lines however you want in those). -# The first spaces (not tabs) for indentation will be ignored, just to make the file look nice when writing. -# This one is one of this cases that cares about multilines -settings-general-output_trackers-description = - Enable or disable specific trackers to output. - Useful for games or apps that only support certain trackers. -settings-general-steamvr-trackers-waist = Waist -settings-general-steamvr-trackers-chest = Chest -settings-general-steamvr-trackers-left_foot = Left foot -settings-general-steamvr-trackers-right_foot = Right foot -settings-general-steamvr-trackers-left_knee = Left knee -settings-general-steamvr-trackers-right_knee = Right knee -settings-general-steamvr-trackers-left_elbow = Left elbow -settings-general-steamvr-trackers-right_elbow = Right elbow -settings-general-steamvr-trackers-left_hand = Left hand -settings-general-steamvr-trackers-right_hand = Right hand -settings-general-steamvr-trackers-tracker_toggling = Automatic tracker assignment -settings-general-output-trackers-tracker_toggling-description = Automatically handles toggling output trackers on or off depending on your current tracker assignments. -settings-general-steamvr-trackers-tracker_toggling-label = Automatic tracker assignment -settings-general-steamvr-trackers-hands-warning = Warning: Enabling the SteamVR hand trackers will disable inputs from real controllers. - This should only be enabled if you are using SlimeVR for hand tracking. +## Bone routing settings +settings-routing = Bone Routing +settings-routing-description = + Choose what each output receives. + SteamVR/Monado, VRChat OSC and VMC can each get a different set of body parts. +settings-routing-mode = Routing mode +settings-routing-automatic-label = Automatic routing +settings-routing-mode-description = + While Automatic is on, SlimeVR picks the best output for every bone so nothing is sent twice: SteamVR/Monado is preferred, VRChat OSC covers the bones it cannot take, and VMC always gets the full skeleton. + Turn it off to decide where every bone goes yourself, including sending one bone to several outputs at once. +settings-routing-bone = Bone +settings-routing-cell-required = This output needs this bone to work, so it is always sent. +settings-routing-cell-unavailable = This output is not available on this platform. +settings-routing-cell-duplicate = This bone reaches the same app through another output too, so it arrives twice. +settings-routing-duplicate-warning = { $bones } go to { $outputs } at the same time. Both might end up in the same app or game, which would see two trackers for each. +settings-routing-outputs = Outputs +settings-routing-bones = Bones +settings-routing-bones-description = A tick means the bone is sent to that output. A dash means the output does not support that bone. Turn off Automatic to pick them yourself. +settings-routing-output-driver = SteamVR / Monado +settings-routing-output-vrc_osc = VRChat OSC +settings-routing-output-vmc = VMC +settings-routing-output-bone-count = { $routed } of { $accepts } bones routed +settings-routing-output-badge-sending = Sending +settings-routing-output-sending-description = Connected and receiving the bones below. +settings-routing-output-badge-stopped = Not running +settings-routing-output-stopped-description = No SteamVR or Monado driver is connected, so nothing routed to it is sent. +settings-routing-output-badge-idle = Idle +settings-routing-output-idle-description = Turned on, but it has not found anything to send to yet, so those bones are not going out. +settings-routing-output-idle-automatic-description = Turned on, but it has not found anything to send to yet, so its bones go to another output until it does. +settings-routing-output-badge-off = Off +settings-routing-output-off-description = Turned off in its own settings, so nothing routed to it is sent. +settings-routing-output-badge-empty = Nothing routed +settings-routing-output-empty-description = No bone is routed to it, so it has nothing to send. +settings-routing-output-badge-unavailable = Unavailable +settings-routing-output-unavailable-description = This output does not exist on this platform. +settings-routing-group-spine = Spine & torso +settings-routing-group-legs = Legs +settings-routing-group-arms = Arms +settings-routing-group-left_fingers = Left hand fingers +settings-routing-group-right_fingers = Right hand fingers +settings-routing-hands-warning = Warning: Routing your hands to SteamVR/Monado replaces the input from your real controllers. + Only do this if you want SlimeVR trackers to track your hands. - Are you sure you want to do this? -settings-general-steamvr-trackers-hands-warning-cancel = Cancel -settings-general-steamvr-trackers-hands-warning-done = Yes + Route hands there anyway? +settings-routing-hands-warning-cancel = Cancel +settings-routing-hands-warning-done = Route hands + +## SteamVR / Monado output settings + +settings-driver = SteamVR / Monado +settings-driver-description = Settings for the SlimeVR driver, used by SteamVR and Monado alike. +settings-driver-bones = Bones sent +settings-driver-bones-description = Which bones this output receives is configured in Bone Routing. +settings-driver-bones-link = Open Bone Routing ## Tracker mechanics settings-general-trackers_settings = Trackers Settings diff --git a/gui/app/src/App.tsx b/gui/app/src/App.tsx index 0cb842cfe..50db7209e 100644 --- a/gui/app/src/App.tsx +++ b/gui/app/src/App.tsx @@ -26,6 +26,8 @@ import { DonglePage } from './components/onboarding/pages/Dongle'; import { ConfigContextProvider } from './components/providers/ConfigContext'; import { SerialDetectionModal } from './components/SerialDetectionModal'; import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings'; +import { BoneRoutingSettings } from './components/settings/pages/BoneRoutingSettings'; +import { DriverSettings } from './components/settings/pages/DriverSettings'; import { TopBar } from './components/TopBar'; import { TrackerSettingsPage } from './components/tracker/TrackerSettings'; import { VMCSettings } from './components/settings/pages/VMCSettings'; @@ -139,6 +141,8 @@ function Layout() { } /> } /> } /> + } /> + } /> } /> } /> } /> diff --git a/gui/app/src/components/settings/SettingsLayout.tsx b/gui/app/src/components/settings/SettingsLayout.tsx index 0d3ea7f89..97f745f27 100644 --- a/gui/app/src/components/settings/SettingsLayout.tsx +++ b/gui/app/src/components/settings/SettingsLayout.tsx @@ -20,7 +20,7 @@ export function SettingSelectorMobile() { [ { label: l10n.getString('settings-sidebar-general'), - value: { url: '/settings/trackers', scrollTo: 'output' }, + value: { url: '/settings/trackers', scrollTo: 'stayAligned' }, }, { label: l10n.getString('settings-sidebar-interface'), @@ -30,6 +30,14 @@ export function SettingSelectorMobile() { label: l10n.getString('settings-sidebar-keybinds'), value: { url: '/settings/keybinds' }, }, + { + label: l10n.getString('settings-sidebar-routing'), + value: { url: '/settings/routing', scrollTo: 'routing' }, + }, + { + label: l10n.getString('settings-sidebar-driver'), + value: { url: '/settings/driver', scrollTo: 'driver' }, + }, { label: l10n.getString('settings-sidebar-osc_trackers'), value: { url: '/settings/osc/vrchat', scrollTo: 'vrchat' }, diff --git a/gui/app/src/components/settings/SettingsPageLayout.tsx b/gui/app/src/components/settings/SettingsPageLayout.tsx index 93b91a188..6c3c539c2 100644 --- a/gui/app/src/components/settings/SettingsPageLayout.tsx +++ b/gui/app/src/components/settings/SettingsPageLayout.tsx @@ -57,7 +57,7 @@ export function SettingsPagePaneLayout({ {icon} -
{children}
+
{children}
); } diff --git a/gui/app/src/components/settings/SettingsSidebar.tsx b/gui/app/src/components/settings/SettingsSidebar.tsx index 990eeebc6..f9f8ae920 100644 --- a/gui/app/src/components/settings/SettingsSidebar.tsx +++ b/gui/app/src/components/settings/SettingsSidebar.tsx @@ -48,11 +48,6 @@ export function SettingsSidebar() {
-
+
+ +
+ + + + +
+
@@ -115,21 +135,6 @@ export function SettingsSidebar() { />
-
- OSC -
- - -
-
diff --git a/gui/app/src/components/settings/pages/BoneRoutingSettings.tsx b/gui/app/src/components/settings/pages/BoneRoutingSettings.tsx new file mode 100644 index 000000000..0104b651e --- /dev/null +++ b/gui/app/src/components/settings/pages/BoneRoutingSettings.tsx @@ -0,0 +1,677 @@ +import { useLocalization } from '@fluent/react'; +import classNames from 'classnames'; +import { ReactNode, useEffect, useMemo, useState } from 'react'; +import { + BodyPart, + BoneRouteT, + BoneRoutingSettingsRequestT, + BoneRoutingSettingsResponseT, + ChangeBoneRoutingSettingsRequestT, + RoutingOutput, + RoutingOutputState, + RoutingOutputStatusT, + RpcMessage, +} from 'solarxr-protocol'; +import { useWebsocketAPI } from '@/hooks/websocket-api'; +import { useLocaleConfig } from '@/i18n/config'; +import { + CHECKBOX_CLASSES, + CheckboxInternal, +} from '@/components/commons/Checkbox'; +import { Typography } from '@/components/commons/Typography'; +import { + SettingsPageLayout, + SettingsPagePaneLayout, +} from '@/components/settings/SettingsPageLayout'; +import { + ArrowDownIcon, + ArrowUpIcon, +} from '@/components/commons/icon/ArrowIcons'; +import { CheckIcon } from '@/components/commons/icon/CheckIcon'; +import { ChestIcon } from '@/components/commons/icon/ChestIcon'; +import { FingersIcon } from '@/components/commons/icon/FingersIcon'; +import { FootIcon } from '@/components/commons/icon/FootIcon'; +import { RouterIcon } from '@/components/commons/icon/RouterIcon'; +import { UpperArmIcon } from '@/components/commons/icon/UpperArmIcon'; +import { Tooltip } from '@/components/commons/Tooltip'; +import { WarningBox } from '@/components/commons/TipBox'; +import { HandsWarningModal } from './components/HandsWarningModal'; + +const OUTPUT_LABEL_ID: Record = { + [RoutingOutput.DRIVER]: 'settings-routing-output-driver', + [RoutingOutput.VRC_OSC]: 'settings-routing-output-vrc_osc', + [RoutingOutput.VMC]: 'settings-routing-output-vmc', +}; + +const BONE_GROUPS: { + id: string; + icon: ReactNode; + bones: BodyPart[]; + defaultOpen: boolean; +}[] = [ + { + id: 'spine', + icon: , + defaultOpen: true, + bones: [ + BodyPart.HEAD, + BodyPart.NECK, + BodyPart.UPPER_CHEST, + BodyPart.CHEST, + BodyPart.WAIST, + BodyPart.HIP, + ], + }, + { + id: 'legs', + icon: , + defaultOpen: true, + bones: [ + BodyPart.LEFT_UPPER_LEG, + BodyPart.LEFT_LOWER_LEG, + BodyPart.LEFT_FOOT, + BodyPart.RIGHT_UPPER_LEG, + BodyPart.RIGHT_LOWER_LEG, + BodyPart.RIGHT_FOOT, + ], + }, + { + id: 'arms', + icon: , + defaultOpen: true, + bones: [ + BodyPart.LEFT_SHOULDER, + BodyPart.LEFT_UPPER_ARM, + BodyPart.LEFT_LOWER_ARM, + BodyPart.LEFT_HAND, + BodyPart.RIGHT_SHOULDER, + BodyPart.RIGHT_UPPER_ARM, + BodyPart.RIGHT_LOWER_ARM, + BodyPart.RIGHT_HAND, + ], + }, + { + id: 'left_fingers', + icon: ( + + + + ), + defaultOpen: false, + bones: [ + BodyPart.LEFT_THUMB_METACARPAL, + BodyPart.LEFT_THUMB_PROXIMAL, + BodyPart.LEFT_THUMB_DISTAL, + BodyPart.LEFT_INDEX_PROXIMAL, + BodyPart.LEFT_INDEX_INTERMEDIATE, + BodyPart.LEFT_INDEX_DISTAL, + BodyPart.LEFT_MIDDLE_PROXIMAL, + BodyPart.LEFT_MIDDLE_INTERMEDIATE, + BodyPart.LEFT_MIDDLE_DISTAL, + BodyPart.LEFT_RING_PROXIMAL, + BodyPart.LEFT_RING_INTERMEDIATE, + BodyPart.LEFT_RING_DISTAL, + BodyPart.LEFT_LITTLE_PROXIMAL, + BodyPart.LEFT_LITTLE_INTERMEDIATE, + BodyPart.LEFT_LITTLE_DISTAL, + ], + }, + { + id: 'right_fingers', + icon: , + defaultOpen: false, + bones: [ + BodyPart.RIGHT_THUMB_METACARPAL, + BodyPart.RIGHT_THUMB_PROXIMAL, + BodyPart.RIGHT_THUMB_DISTAL, + BodyPart.RIGHT_INDEX_PROXIMAL, + BodyPart.RIGHT_INDEX_INTERMEDIATE, + BodyPart.RIGHT_INDEX_DISTAL, + BodyPart.RIGHT_MIDDLE_PROXIMAL, + BodyPart.RIGHT_MIDDLE_INTERMEDIATE, + BodyPart.RIGHT_MIDDLE_DISTAL, + BodyPart.RIGHT_RING_PROXIMAL, + BodyPart.RIGHT_RING_INTERMEDIATE, + BodyPart.RIGHT_RING_DISTAL, + BodyPart.RIGHT_LITTLE_PROXIMAL, + BodyPart.RIGHT_LITTLE_INTERMEDIATE, + BodyPart.RIGHT_LITTLE_DISTAL, + ], + }, +]; + +const HAND_BONES = new Set([BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND]); + +const ROW_CLASSES = 'flex items-center pl-4 pr-3 mobile:pl-3 mobile:pr-2'; + +const BONE_CELL_CLASSES = 'flex-1 min-w-44 mobile:min-w-0 mobile:flex-[1.6]'; + +const OUTPUT_CELL_CLASSES = + 'w-32 shrink-0 mobile:w-auto mobile:flex-1 mobile:shrink flex justify-center'; + +type RouteMap = Map>; + +function toRouteMap(routes: BoneRouteT[]): RouteMap { + return new Map( + routes.map((route) => [route.bone, new Set(route.outputs ?? [])]) + ); +} + +function toBoneRoutes(routes: RouteMap): BoneRouteT[] { + return Array.from(routes.entries()) + .filter(([, outputs]) => outputs.size > 0) + .map(([bone, outputs]) => { + const route = new BoneRouteT(); + route.bone = bone; + route.outputs = Array.from(outputs); + return route; + }); +} + +type OutputSummary = + | 'sending' + | 'idle' + | 'empty' + | 'stopped' + | 'off' + | 'unavailable'; + +const BADGE_CLASSES: Record = { + sending: 'bg-status-success', + idle: 'bg-status-special', + empty: 'bg-status-warning', + stopped: 'bg-background-50', + off: 'bg-background-50', + unavailable: 'bg-background-50', +}; + +function StatusBadge({ summary }: { summary: OutputSummary }) { + return ( + +
+ + + ); +} + +function OutputStatusRow({ + status, + routed, + automatic, +}: { + status: RoutingOutputStatusT; + routed: number; + automatic: boolean; +}) { + const accepts = status.accepts?.length ?? 0; + const summary = useMemo(() => { + switch (status.state ?? RoutingOutputState.UNSUPPORTED) { + case RoutingOutputState.UNSUPPORTED: + return 'unavailable'; + case RoutingOutputState.INACTIVE: + return status.output === RoutingOutput.DRIVER ? 'stopped' : 'off'; + case RoutingOutputState.ENABLED: + return 'idle'; + default: + return routed === 0 ? 'empty' : 'sending'; + } + }, [status, routed]); + + return ( +
+
+
+ +
+ +
+ +
+ + {(summary === 'sending' || + summary === 'idle' || + summary === 'empty') && ( + + )} +
+
+ ); +} + +function RouteCell({ + bone, + output, + automatic, + accepted, + required, + unavailable, + routed, + duplicate, + onToggle, +}: { + bone: BodyPart; + output: RoutingOutput; + automatic: boolean; + accepted: boolean; + required: boolean; + unavailable: boolean; + routed: boolean; + duplicate: boolean; + onToggle: (bone: BodyPart, output: RoutingOutput) => void; +}) { + const cell = (content: ReactNode, className?: string) => ( +
+ {content} +
+ ); + + if (!accepted) { + return cell(
); + } + + if (automatic) { + return routed + ? cell(, 'fill-accent-background-20') + : cell(
); + } + + const lockedId = required + ? 'settings-routing-cell-required' + : unavailable + ? 'settings-routing-cell-unavailable' + : null; + const tooltipId = + lockedId ?? (duplicate ? 'settings-routing-cell-duplicate' : null); + + const checkbox = ( + onToggle(bone, output)} + /> + ); + + return cell( + tooltipId ? ( + }> + {checkbox} + + ) : ( + checkbox + ) + ); +} + +export function BoneRoutingSettings() { + const { l10n } = useLocalization(); + const { currentLocales } = useLocaleConfig(); + const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); + const [settings, setSettings] = useState(new BoneRoutingSettingsResponseT()); + + const [automatic, setAutomatic] = useState(true); + const [routes, setRoutes] = useState(new Map()); + const [openGroups, setOpenGroups] = useState>( + () => new Set(BONE_GROUPS.filter((g) => g.defaultOpen).map((g) => g.id)) + ); + const [handsWarning, setHandsWarning] = useState< + [BodyPart, RoutingOutput] | null + >(null); + const [handsWarningAccepted, setHandsWarningAccepted] = useState(false); + + const outputs = useMemo(() => settings.outputs ?? [], [settings]); + + const accepts = useMemo( + () => + new Map( + outputs.map((status) => [status.output, new Set(status.accepts ?? [])]) + ), + [outputs] + ); + + const requires = useMemo( + () => + new Map( + outputs.map((status) => [status.output, new Set(status.requires ?? [])]) + ), + [outputs] + ); + + const conflicts = useMemo( + () => + new Map( + outputs.map((status) => [ + status.output, + new Set(status.conflicts ?? []), + ]) + ), + [outputs] + ); + + const routedCounts = useMemo(() => { + const counts = new Map( + outputs.map((status) => [status.output, 0]) + ); + for (const boneOutputs of routes.values()) { + for (const output of boneOutputs) { + counts.set(output, (counts.get(output) ?? 0) + 1); + } + } + return counts; + }, [outputs, routes]); + + const duplicated = useMemo(() => { + const result = new Map>(); + for (const [bone, boneOutputs] of routes) { + for (const output of boneOutputs) { + const clashes = conflicts.get(output); + if (!clashes) continue; + for (const other of boneOutputs) { + if (other === output || !clashes.has(other)) continue; + const clashed = result.get(bone) ?? new Set(); + clashed.add(output).add(other); + result.set(bone, clashed); + } + } + } + return result; + }, [routes, conflicts]); + + const duplicatedNames = useMemo(() => { + const list = new Intl.ListFormat(currentLocales, { type: 'conjunction' }); + const outputs = new Set( + Array.from(duplicated.values()).flatMap((clashed) => Array.from(clashed)) + ); + return { + bones: list.format( + Array.from(duplicated.keys()).map((bone) => + l10n.getString(`body_part-${BodyPart[bone]}`) + ) + ), + outputs: list.format( + Array.from(outputs).map((output) => + l10n.getString(OUTPUT_LABEL_ID[output]) + ) + ), + }; + }, [duplicated, l10n, currentLocales]); + + useEffect(() => { + sendRPCPacket( + RpcMessage.BoneRoutingSettingsRequest, + new BoneRoutingSettingsRequestT() + ); + }, []); + + useEffect(() => { + setAutomatic(settings.automatic ?? true); + setRoutes(toRouteMap(settings.routes ?? [])); + + const handsAlreadyOnDriver = (settings.routes ?? []).some( + (route) => + HAND_BONES.has(route.bone) && + (route.outputs ?? []).includes(RoutingOutput.DRIVER) + ); + if (handsAlreadyOnDriver) setHandsWarningAccepted(true); + }, [settings]); + + useRPCPacket( + RpcMessage.BoneRoutingSettingsResponse, + (res: BoneRoutingSettingsResponseT) => setSettings(res) + ); + + const submit = (nextAutomatic: boolean, nextRoutes: RouteMap) => { + const req = new ChangeBoneRoutingSettingsRequestT(); + req.automatic = nextAutomatic; + req.routes = toBoneRoutes(nextRoutes); + sendRPCPacket(RpcMessage.ChangeBoneRoutingSettingsRequest, req); + }; + + const applyToggle = (bone: BodyPart, output: RoutingOutput) => { + const next = new Map(routes); + const boneOutputs = new Set(next.get(bone) ?? []); + if (boneOutputs.has(output)) boneOutputs.delete(output); + else boneOutputs.add(output); + next.set(bone, boneOutputs); + setRoutes(next); + submit(automatic, next); + }; + + const toggle = (bone: BodyPart, output: RoutingOutput) => { + const enabling = !routes.get(bone)?.has(output); + const takesOverControllers = + enabling && output === RoutingOutput.DRIVER && HAND_BONES.has(bone); + + if (takesOverControllers && !handsWarningAccepted) { + setHandsWarning([bone, output]); + return; + } + applyToggle(bone, output); + }; + + const setMode = (nextAutomatic: boolean) => { + setAutomatic(nextAutomatic); + submit(nextAutomatic, routes); + }; + + const toggleGroup = (id: string) => { + const next = new Set(openGroups); + if (next.has(id)) next.delete(id); + else next.add(id); + setOpenGroups(next); + }; + + return ( + <> + setHandsWarning(null)} + accept={() => { + setHandsWarningAccepted(true); + if (handsWarning) applyToggle(handsWarning[0], handsWarning[1]); + setHandsWarning(null); + }} + /> + + } id="routing"> + <> + +
+ +
+ + +
+ + setMode(!automatic)} + label={l10n.getString('settings-routing-automatic-label')} + /> +
+ + +
+ {outputs.map((status) => ( + + ))} +
+ + +
+ +
+ {duplicated.size > 0 && ( +
+ + {l10n.getString('settings-routing-duplicate-warning', { + bones: duplicatedNames.bones, + outputs: duplicatedNames.outputs, + })} + +
+ )} + +
+
+
+
+
+ +
+ {outputs.map((status) => ( +
+ +
+ ))} +
+ + {BONE_GROUPS.map((group) => { + const open = openGroups.has(group.id); + return ( +
+ + + {open && ( +
+ {group.bones.map((bone) => ( +
+
+ +
+ + {outputs.map((status) => ( + + ))} +
+ ))} +
+ )} +
+ ); + })} +
+
+
+ +
+
+ + ); +} diff --git a/gui/app/src/components/settings/pages/DriverSettings.tsx b/gui/app/src/components/settings/pages/DriverSettings.tsx new file mode 100644 index 000000000..ae0ccbca7 --- /dev/null +++ b/gui/app/src/components/settings/pages/DriverSettings.tsx @@ -0,0 +1,119 @@ +import { useLocalization } from '@fluent/react'; +import { useEffect, useState } from 'react'; +import { DefaultValues, useForm } from 'react-hook-form'; +import { Button } from '@/components/commons/Button'; +import { + ChangeDriverSettingsRequestT, + DriverSettingsRequestT, + DriverSettingsResponseT, + RpcMessage, +} from 'solarxr-protocol'; +import { useWebsocketAPI } from '@/hooks/websocket-api'; +import { CheckBox } from '@/components/commons/Checkbox'; +import { Typography } from '@/components/commons/Typography'; +import { + SettingsPageLayout, + SettingsPagePaneLayout, +} from '@/components/settings/SettingsPageLayout'; +import { SteamIcon } from '@/components/commons/icon/SteamIcon'; + +type DriverForm = { + sendDerivedVelocity: boolean; +}; + +const defaultValues: DriverForm = { + sendDerivedVelocity: false, +}; + +export function DriverSettings() { + const [settings, setSettings] = useState(new DriverSettingsResponseT()); + const { l10n } = useLocalization(); + const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); + + const { control, watch, handleSubmit, getValues, reset } = + useForm({ + defaultValues, + mode: 'onChange', + reValidateMode: 'onChange', + }); + + const onSubmit = (values: DriverForm) => { + const settingsReq = new ChangeDriverSettingsRequestT(); + settingsReq.sendDerivedVelocity = values.sendDerivedVelocity; + sendRPCPacket(RpcMessage.ChangeDriverSettingsRequest, settingsReq); + }; + + useEffect(() => { + const subscription = watch((_, { type }) => { + if (type === 'change') handleSubmit(onSubmit)(); + }); + return () => subscription.unsubscribe(); + }, []); + + useEffect(() => { + sendRPCPacket( + RpcMessage.DriverSettingsRequest, + new DriverSettingsRequestT() + ); + }, []); + + useEffect(() => { + const formData: DefaultValues = { + sendDerivedVelocity: settings.sendDerivedVelocity, + }; + reset({ ...getValues(), ...formData }); + }, [settings]); + + useRPCPacket( + RpcMessage.DriverSettingsResponse, + (res: DriverSettingsResponseT) => setSettings(res) + ); + + return ( + + } id="driver"> + <> + +
+ +
+ + +
+ +
+
+
+ + +
+ +
+ + +
+
+ ); +} diff --git a/gui/app/src/components/settings/pages/GeneralSettings.tsx b/gui/app/src/components/settings/pages/GeneralSettings.tsx index fab287fe4..5022a9087 100644 --- a/gui/app/src/components/settings/pages/GeneralSettings.tsx +++ b/gui/app/src/components/settings/pages/GeneralSettings.tsx @@ -2,7 +2,6 @@ import { SettingsPageLayout, SettingsPagePaneLayout, } from '@/components/settings/SettingsPageLayout'; -import { OutputTrackersSettings } from './components/OutputSettings'; import { StayAlignedSettings } from './components/StayAlignedSettings'; import { ResetsSettings } from './components/ResetsSettings'; import { HIDSettings } from './components/HIDSettings'; @@ -59,7 +58,6 @@ export function GeneralSettings() { return (
- diff --git a/gui/app/src/components/settings/pages/components/HandsWarningModal.tsx b/gui/app/src/components/settings/pages/components/HandsWarningModal.tsx index d9ab9c7b5..a41ff5e39 100644 --- a/gui/app/src/components/settings/pages/components/HandsWarningModal.tsx +++ b/gui/app/src/components/settings/pages/components/HandsWarningModal.tsx @@ -1,6 +1,6 @@ import { Button } from '@/components/commons/Button'; import { WarningBox } from '@/components/commons/TipBox'; -import { Localized, useLocalization } from '@fluent/react'; +import { Localized } from '@fluent/react'; import { BaseModal } from '@/components/commons/BaseModal'; import ReactModal from 'react-modal'; @@ -23,8 +23,6 @@ export function HandsWarningModal({ */ accept: () => void; } & ReactModal.Props) { - const { l10n } = useLocalization(); - return (
- }} - > + }}> - Warning: Please don't use hands if you have controllers! + Warning: Routing hands to SteamVR/Monado replaces your + controllers!
- - +
diff --git a/gui/app/src/components/settings/pages/components/OutputSettings.tsx b/gui/app/src/components/settings/pages/components/OutputSettings.tsx deleted file mode 100644 index 6412c8889..000000000 --- a/gui/app/src/components/settings/pages/components/OutputSettings.tsx +++ /dev/null @@ -1,387 +0,0 @@ -import { useLocalization } from '@fluent/react'; -import { useEffect, useRef, useState } from 'react'; -import { DefaultValues, useForm } from 'react-hook-form'; -import { - BodyPart, - ChangeOutputTrackersSettingsRequestT, - OutputTrackersSettingsRequestT, - OutputTrackersSettingsResponseT, - RpcMessage, -} from 'solarxr-protocol'; -import { useWebsocketAPI } from '@/hooks/websocket-api'; -import { CheckBox } from '@/components/commons/Checkbox'; -import { Typography } from '@/components/commons/Typography'; -import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout'; -import { atom, useAtomValue, useSetAtom } from 'jotai'; -import { isEqual } from '@react-hookz/deep-equal'; -import { selectAtom } from 'jotai/utils'; -import { HandsWarningModal } from './HandsWarningModal'; -import { OutputIcon } from '@/components/commons/icon/OutputIcon'; - -type OutputTrackersForm = { - automaticTrackerToggle: boolean; - trackers: { - waist: boolean; - chest: boolean; - leftFoot: boolean; - rightFoot: boolean; - leftKnee: boolean; - rightKnee: boolean; - leftElbow: boolean; - rightElbow: boolean; - leftHand: boolean; - rightHand: boolean; - }; - sendDerivedVelocity: boolean; -}; - -const defaultValues: OutputTrackersForm = { - automaticTrackerToggle: true, - trackers: { - waist: false, - chest: false, - leftFoot: false, - rightFoot: false, - leftElbow: false, - rightElbow: false, - leftHand: false, - rightHand: false, - leftKnee: false, - rightKnee: false, - }, - sendDerivedVelocity: false, -}; - -// The tracker is at the tail of the bone. -// Example, the waist tracker is at the tail of the hip bone so we use the hip BodyPart -function togglesToBodyParts( - trackers: OutputTrackersForm['trackers'] -): BodyPart[] { - const toggleToBodyPart: [boolean, BodyPart][] = [ - [trackers.waist, BodyPart.HIP], - [trackers.chest, BodyPart.UPPER_CHEST], - [trackers.leftFoot, BodyPart.LEFT_FOOT], - [trackers.rightFoot, BodyPart.RIGHT_FOOT], - [trackers.leftKnee, BodyPart.LEFT_UPPER_LEG], - [trackers.rightKnee, BodyPart.RIGHT_UPPER_LEG], - [trackers.leftElbow, BodyPart.LEFT_UPPER_ARM], - [trackers.rightElbow, BodyPart.RIGHT_UPPER_ARM], - [trackers.leftHand, BodyPart.LEFT_HAND], - [trackers.rightHand, BodyPart.RIGHT_HAND], - ]; - - return toggleToBodyPart - .filter(([enabled]) => enabled) - .map(([, part]) => part); -} - -function bodyPartsToTrackers( - bodyParts: BodyPart[] -): OutputTrackersForm['trackers'] { - const set = new Set(bodyParts); - return { - waist: set.has(BodyPart.HIP), - chest: set.has(BodyPart.UPPER_CHEST), - leftFoot: set.has(BodyPart.LEFT_FOOT), - rightFoot: set.has(BodyPart.RIGHT_FOOT), - leftKnee: set.has(BodyPart.LEFT_UPPER_LEG), - rightKnee: set.has(BodyPart.RIGHT_UPPER_LEG), - leftElbow: set.has(BodyPart.LEFT_UPPER_ARM), - rightElbow: set.has(BodyPart.RIGHT_UPPER_ARM), - leftHand: set.has(BodyPart.LEFT_HAND), - rightHand: set.has(BodyPart.RIGHT_HAND), - }; -} - -const outputTrackersSettingsAtom = atom(new OutputTrackersSettingsResponseT()); -const outputTrackersSettingsValueAtom = selectAtom( - outputTrackersSettingsAtom, - (settings) => settings, - isEqual -); - -export function OutputTrackersSettings() { - const setSettings = useSetAtom(outputTrackersSettingsAtom); - const settings = useAtomValue(outputTrackersSettingsValueAtom); - const { l10n } = useLocalization(); - const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); - - const blockHandsWarning = useRef(false); - - // If not null, warning will be shown, and showHandsWarning will - // hold which hands should be toggled ([leftHand, rightHand]) - const [showHandsWarning, setShowHandsWarning] = useState< - [boolean, boolean] | null - >(null); - - const { control, watch, handleSubmit, getValues, setValue, reset } = - useForm({ - defaultValues, - mode: 'onChange', - reValidateMode: 'onChange', - }); - - const { automaticTrackerToggle } = watch(); - - const onSubmit = (values: OutputTrackersForm) => { - const settingsReq = new ChangeOutputTrackersSettingsRequestT(); - - let leftHand = values.trackers.leftHand; - let rightHand = values.trackers.rightHand; - - const hadHandTracker = - settings.trackers?.includes(BodyPart.LEFT_HAND) || - settings.trackers?.includes(BodyPart.RIGHT_HAND); - - if ( - !blockHandsWarning.current && - !showHandsWarning && - !hadHandTracker && - (leftHand || rightHand) - ) { - setShowHandsWarning([leftHand, rightHand]); - leftHand = false; - rightHand = false; - } else if (blockHandsWarning.current && !leftHand && !rightHand) { - blockHandsWarning.current = false; - } - - settingsReq.trackers = togglesToBodyParts({ - ...values.trackers, - leftHand, - rightHand, - }); - settingsReq.automaticTrackerToggle = values.automaticTrackerToggle; - settingsReq.sendDerivedVelocity = values.sendDerivedVelocity; - - sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, settingsReq); - }; - - useEffect(() => { - const subscription = watch((_, { type }) => { - if (type === 'change') handleSubmit(onSubmit)(); - }); - return () => subscription.unsubscribe(); - }, []); - - useEffect(() => { - sendRPCPacket( - RpcMessage.OutputTrackersSettingsRequest, - new OutputTrackersSettingsRequestT() - ); - }, []); - - useEffect(() => { - let formData: DefaultValues = {}; - - if (settings.trackers) { - formData = { - trackers: bodyPartsToTrackers(settings.trackers), - automaticTrackerToggle: settings.automaticTrackerToggle, - sendDerivedVelocity: settings.sendDerivedVelocity, - }; - if ( - !blockHandsWarning.current && - (settings.trackers.includes(BodyPart.LEFT_HAND) || - settings.trackers.includes(BodyPart.RIGHT_HAND)) - ) { - blockHandsWarning.current = true; - } - } - - reset({ ...getValues(), ...formData }); - }, [settings]); - - useRPCPacket( - RpcMessage.OutputTrackersSettingsResponse, - (settings: OutputTrackersSettingsResponseT) => { - setSettings(settings); - } - ); - - return ( - <> - { - setValue('trackers.leftHand', false); - setValue('trackers.rightHand', false); - setShowHandsWarning(null); - }} - accept={() => { - const [leftHand, rightHand] = showHandsWarning!; - blockHandsWarning.current = true; - setValue('trackers.leftHand', leftHand); - setValue('trackers.rightHand', rightHand); - setShowHandsWarning(null); - }} - /> - } id="output"> - <> - - {l10n.getString('settings-general-output')} - -
- - - {l10n.getString( - 'settings-general-steamvr-trackers-tracker_toggling' - )} - -
- {l10n - .getString( - 'settings-general-output-trackers-tracker_toggling-description' - ) - .split('\n') - .map((line, i) => ( - {line} - ))} -
- - -
- - {l10n.getString('settings-general-output_trackers')} - -
- {l10n - .getString('settings-general-output_trackers-description') - .split('\n') - .map((line, i) => ( - {line} - ))} -
- -
- - - - - - - - - - -
- -
- - {l10n.getString('settings-general-fk_settings-velocity_settings')} - -
- - {l10n.getString( - 'settings-general-fk_settings-velocity_settings-description' - )} - -
-
- -
- - - - ); -} diff --git a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx index d3084d123..45101f748 100644 --- a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx +++ b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx @@ -13,9 +13,11 @@ import { TrackingChecklistSteamVRDisconnectedT, TrackingChecklistStepId, BodyPart, - ChangeOutputTrackersSettingsRequestT, - OutputTrackersSettingsResponseT, - OutputTrackersSettingsRequestT, + RoutingOutput, + BoneRoutingSettingsRequestT, + BoneRoutingSettingsResponseT, + BoneRouteT, + ChangeBoneRoutingSettingsRequestT, } from 'solarxr-protocol'; import { ReactNode, useEffect, useMemo, useState } from 'react'; import { CheckIcon } from '@/components/commons/icon/CheckIcon'; @@ -175,42 +177,43 @@ function SteamVRDisconnected({ function SteamVRHandsEnabled() { const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); - const [steamVrTrackers, setSteamVrTrackers] = useState | null>(null); + const [routing, setRouting] = useState( + null + ); useEffect(() => { sendRPCPacket( - RpcMessage.OutputTrackersSettingsRequest, - new OutputTrackersSettingsRequestT() + RpcMessage.BoneRoutingSettingsRequest, + new BoneRoutingSettingsRequestT() ); }, []); useRPCPacket( - RpcMessage.OutputTrackersSettingsResponse, - (settings: OutputTrackersSettingsResponseT) => { - if (settings.trackers) { - setSteamVrTrackers(settings); - } - } + RpcMessage.BoneRoutingSettingsResponse, + (settings: BoneRoutingSettingsResponseT) => setRouting(settings) ); const disableHandTrackers = () => { - const req = new ChangeOutputTrackersSettingsRequestT(); + if (!routing) return; - const newTrackers = steamVrTrackers?.trackers.filter( - (tracker) => - tracker != BodyPart.LEFT_HAND && tracker != BodyPart.RIGHT_HAND - ); - if (newTrackers !== undefined) { - req.trackers = newTrackers; - } - req.automaticTrackerToggle = - steamVrTrackers?.automaticTrackerToggle === true; - req.sendDerivedVelocity = steamVrTrackers?.sendDerivedVelocity === true; + const req = new ChangeBoneRoutingSettingsRequestT(); + req.automatic = routing.automatic; + req.routes = (routing.routes ?? []) + .map((route) => { + const next = new BoneRouteT(); + next.bone = route.bone; + next.outputs = + route.bone === BodyPart.LEFT_HAND || + route.bone === BodyPart.RIGHT_HAND + ? (route.outputs ?? []).filter( + (output) => output !== RoutingOutput.DRIVER + ) + : (route.outputs ?? []); + return next; + }) + .filter((route) => route.outputs.length > 0); - sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, req); + sendRPCPacket(RpcMessage.ChangeBoneRoutingSettingsRequest, req); }; return ( diff --git a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt index e84786ac9..42c1e7f1f 100644 --- a/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt +++ b/server/android/src/main/java/dev/slimevr/android/ForegroundService.kt @@ -30,9 +30,9 @@ import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager import dev.slimevr.keybind.KeybindManager import dev.slimevr.networkprofile.NetworkProfileManager -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.Skeleton import dev.slimevr.stayaligned.StayAlignedManager import dev.slimevr.tapdetection.TapDetectionManager @@ -157,14 +157,13 @@ class ForegroundService : Service() { val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope) val trackingChecklist = TrackingChecklist.create(scope = scope) val udpServer = UdpServer.create(scope = scope, addressResolver = ::resolveAndroidUdpAddress) - val outputTrackerToggle = OutputTrackerToggleManager.create(ctx = phase1, scope = scope) + val boneRouting = BoneRoutingManager.create(scope = scope) val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = scope) - val vmcManager = VMCManager.create(ctx = phase1, skeleton = skeleton, scope = scope) + val vmcManager = VMCManager.create(scope = scope) val vrcOscManager = VRCOSCManager.create( ctx = phase1, scope = scope, oscQueryAddress = resolveAndroidOscQueryAddress(), - outputTrackerToggle = outputTrackerToggle, ) val resetsManager = ResetsManager.create(ctx = phase1, scope = scope) val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope) @@ -179,6 +178,7 @@ class ForegroundService : Service() { skipCheckUdev = true, keybindSupport = KeybindSupport.UNSUPPORTED, udevRulesInstalled = false, + supportsDriver = false, ), keybindManager = keybindManager, skeleton = skeleton, @@ -189,7 +189,7 @@ class ForegroundService : Service() { heightCalibrationManager = heightCalibrationManager, trackingChecklist = trackingChecklist, udpServer = udpServer, - outputTrackerToggle = outputTrackerToggle, + boneRouting = boneRouting, bvhManager = bvhManager, vmcManager = vmcManager, vrcOscManager = vrcOscManager, diff --git a/server/core/src/main/java/dev/slimevr/app-context.kt b/server/core/src/main/java/dev/slimevr/app-context.kt index 0fc85999f..8de1b29e3 100644 --- a/server/core/src/main/java/dev/slimevr/app-context.kt +++ b/server/core/src/main/java/dev/slimevr/app-context.kt @@ -6,9 +6,9 @@ import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager import dev.slimevr.keybind.KeybindManager import dev.slimevr.networkprofile.NetworkProfileManager -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.serial.SerialServer import dev.slimevr.skeleton.Skeleton import dev.slimevr.stayaligned.StayAlignedManager @@ -42,7 +42,7 @@ interface AppContextProvider : Phase1ContextProvider { val heightCalibrationManager: HeightCalibrationManager val trackingChecklist: TrackingChecklist val udpServer: UdpServer - val outputTrackerToggle: OutputTrackerToggleManager + val boneRouting: BoneRoutingManager val bvhManager: BVHManager val vmcManager: VMCManager val vrcOscManager: VRCOSCManager @@ -67,7 +67,7 @@ class AppContext( override val heightCalibrationManager: HeightCalibrationManager, override val trackingChecklist: TrackingChecklist, override val udpServer: UdpServer, - override val outputTrackerToggle: OutputTrackerToggleManager, + override val boneRouting: BoneRoutingManager, override val bvhManager: BVHManager, override val vmcManager: VMCManager, override val vrcOscManager: VRCOSCManager, @@ -85,8 +85,8 @@ class AppContext( networkProfileManager?.startObserving() trackingChecklist.startObserving(this) udpServer.startReceiving(this, server.context.scope) - outputTrackerToggle.startObserving() - vmcManager.startObserving() + boneRouting.startObserving(this) + vmcManager.startObserving(this) vrcOscManager.startObserving(this) resetsManager.startObserving() tapDetectionManager.startObserving() diff --git a/server/core/src/main/java/dev/slimevr/config/settings.kt b/server/core/src/main/java/dev/slimevr/config/settings.kt index 20c60766f..1f3b82814 100644 --- a/server/core/src/main/java/dev/slimevr/config/settings.kt +++ b/server/core/src/main/java/dev/slimevr/config/settings.kt @@ -16,6 +16,7 @@ import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.rpc.ArmsResetMode import solarxr_protocol.rpc.FilteringType import solarxr_protocol.rpc.KeybindId +import solarxr_protocol.rpc.RoutingOutput private const val SETTINGS_CONFIG_VERSION = 2 @@ -43,13 +44,17 @@ data class HidConfig( ) @Serializable -data class OutputTrackersConfig( - val automaticTrackerToggle: Boolean = true, +data class BoneRoutingConfig( + /** Generate the routes from the connected trackers and the output priority. */ + val automatic: Boolean = true, /** - * Do not read from directly, instead use + * Explicit routes, ignored while [automatic]. Do not read directly, use BoneRoutingManager. */ - @Serializable(with = BodyPartListSerializer::class) - val trackers: List = listOf(), + val manualRoutes: Map>? = null, +) + +@Serializable +data class DriverConfig( val sendDerivedVelocity: Boolean = false, // TODO do we actually need that or can we disable OpenVR's prediction ) @@ -210,7 +215,8 @@ data class SettingsConfigState( val trackers: Map = emptyMap(), val trackersConfig: TrackersConfig = TrackersConfig(), val hidConfig: HidConfig = HidConfig(), - val outputTrackersConfig: OutputTrackersConfig = OutputTrackersConfig(), + val boneRoutingConfig: BoneRoutingConfig = BoneRoutingConfig(), + val driverConfig: DriverConfig = DriverConfig(), val tapDetectionConfig: TapDetectionConfig = TapDetectionConfig(), val resetsConfig: ResetsConfig = ResetsConfig(), val keybinds: List = defaultKeybinds(), diff --git a/server/core/src/main/java/dev/slimevr/driver/behaviours.kt b/server/core/src/main/java/dev/slimevr/driver/behaviours.kt index d1b184f31..e784aaaa0 100644 --- a/server/core/src/main/java/dev/slimevr/driver/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/driver/behaviours.kt @@ -16,9 +16,11 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.TrackerStatus +import solarxr_protocol.rpc.RoutingOutput class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour { - // Keys should match with protocol.kt:bodyPartToRole + // Fallback chain per bone, used to attribute battery and status to the nearest + // physical tracker. Bones without an entry just report no battery. val bodyPartToNearest: BodyPartMap> = BodyPartMap( mapOf( BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.CHEST), @@ -45,7 +47,9 @@ class DriverOutgoingTrackersBehaviour : DriverBridgeBehaviour { combine( receiver.appContext.skeleton.computed, - receiver.appContext.outputTrackerToggle.context.state.map { it.trackers }, + receiver.appContext.boneRouting.context.state + .map { state -> state.routes.filterValues { RoutingOutput.DRIVER in it }.keys } + .distinctUntilChanged(), ::Pair, ) .distinctUntilChanged() diff --git a/server/core/src/main/java/dev/slimevr/driver/roles.kt b/server/core/src/main/java/dev/slimevr/driver/roles.kt new file mode 100644 index 000000000..1a3d0a06e --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/driver/roles.kt @@ -0,0 +1,63 @@ +package dev.slimevr.driver + +import solarxr_protocol.datatypes.BodyPart + +/** + * Tracker roles the driver understands, SteamVR or Monado alike. + * The values are the wire numbers used by the driver IPC protobuf. + */ +enum class TrackerRole( + val value: UByte, +) { + NONE(0.toUByte()), + WAIST(1.toUByte()), + LEFT_FOOT(2.toUByte()), + RIGHT_FOOT(3.toUByte()), + CHEST(4.toUByte()), + LEFT_KNEE(5.toUByte()), + RIGHT_KNEE(6.toUByte()), + LEFT_ELBOW(7.toUByte()), + RIGHT_ELBOW(8.toUByte()), + LEFT_SHOULDER(9.toUByte()), + RIGHT_SHOULDER(10.toUByte()), + LEFT_HAND(11.toUByte()), + RIGHT_HAND(12.toUByte()), + LEFT_CONTROLLER(13.toUByte()), + RIGHT_CONTROLLER(14.toUByte()), + HEAD(15.toUByte()), + NECK(16.toUByte()), + CAMERA(17.toUByte()), + KEYBOARD(18.toUByte()), + HMD(19.toUByte()), + BEACON(20.toUByte()), + GENERIC_CONTROLLER(21.toUByte()), + ; + + companion object { + fun fromValue(value: UByte): TrackerRole? = entries.firstOrNull { it.value == value } + } +} + +val bodyPartToRole: Map = mapOf( + BodyPart.HEAD to TrackerRole.HMD, + BodyPart.UPPER_CHEST to TrackerRole.CHEST, + BodyPart.LEFT_UPPER_ARM to TrackerRole.LEFT_ELBOW, + BodyPart.RIGHT_UPPER_ARM to TrackerRole.RIGHT_ELBOW, + BodyPart.HIP to TrackerRole.WAIST, + BodyPart.LEFT_UPPER_LEG to TrackerRole.LEFT_KNEE, + BodyPart.RIGHT_UPPER_LEG to TrackerRole.RIGHT_KNEE, + BodyPart.LEFT_FOOT to TrackerRole.LEFT_FOOT, + BodyPart.RIGHT_FOOT to TrackerRole.RIGHT_FOOT, + BodyPart.LEFT_SHOULDER to TrackerRole.LEFT_SHOULDER, + BodyPart.RIGHT_SHOULDER to TrackerRole.RIGHT_SHOULDER, + BodyPart.LEFT_HAND to TrackerRole.LEFT_HAND, + BodyPart.RIGHT_HAND to TrackerRole.RIGHT_HAND, +) + +val roleToBodyPart = bodyPartToRole.entries.associate { (k, v) -> v to k } + +/** + * Bones the driver output can accept. Used by the routing module. + * HEAD is the HMD coming in, we never send it. + */ +val DRIVER_SUPPORTED_BONES: Set = bodyPartToRole.keys - BodyPart.HEAD diff --git a/server/core/src/main/java/dev/slimevr/feature-flags.kt b/server/core/src/main/java/dev/slimevr/feature-flags.kt index 526c63c61..bbb68f9ff 100644 --- a/server/core/src/main/java/dev/slimevr/feature-flags.kt +++ b/server/core/src/main/java/dev/slimevr/feature-flags.kt @@ -7,4 +7,5 @@ data class FeatureFlags( var skipCheckUdev: Boolean = false, var udevRulesInstalled: Boolean? = null, var keybindSupport: KeybindSupport = KeybindSupport.UNSUPPORTED, + var supportsDriver: Boolean = true, ) diff --git a/server/core/src/main/java/dev/slimevr/outputtrackertoggle/behaviours.kt b/server/core/src/main/java/dev/slimevr/outputtrackertoggle/behaviours.kt deleted file mode 100644 index 904bd7565..000000000 --- a/server/core/src/main/java/dev/slimevr/outputtrackertoggle/behaviours.kt +++ /dev/null @@ -1,90 +0,0 @@ -package dev.slimevr.outputtrackertoggle - -import dev.slimevr.config.OutputTrackersConfig -import dev.slimevr.device.DeviceOrigin -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.emptyFlow -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.datatypes.TrackerStatus -import kotlin.collections.filter -import kotlin.collections.map - -class OutputTrackerToggleBasicBehaviour : OutputTrackerToggleBehaviour { - private val automaticToggleToTracker = mapOf( - BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.CHEST), - BodyPart.LEFT_UPPER_ARM to setOf(BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM), - BodyPart.RIGHT_UPPER_ARM to setOf(BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM), - BodyPart.HIP to setOf(BodyPart.HIP, BodyPart.WAIST, BodyPart.CHEST, BodyPart.UPPER_CHEST), - BodyPart.LEFT_UPPER_LEG to setOf(BodyPart.LEFT_UPPER_LEG), - BodyPart.RIGHT_UPPER_LEG to setOf(BodyPart.RIGHT_UPPER_LEG), - BodyPart.LEFT_FOOT to setOf(BodyPart.LEFT_FOOT, BodyPart.LEFT_LOWER_LEG, BodyPart.LEFT_UPPER_LEG), - BodyPart.RIGHT_FOOT to setOf(BodyPart.RIGHT_FOOT, BodyPart.RIGHT_LOWER_LEG, BodyPart.RIGHT_UPPER_LEG), - ) - - fun determineAutomaticOutputTrackers( - config: OutputTrackersConfig, - fineBodyParts: Set, - ): List { - val automaticTrackers = automaticToggleToTracker - .filterValues { it.any { bp -> bp in fineBodyParts } } - .keys - // Hands aren't toggled automatically - val handTrackers = config.trackers.filter { - it == BodyPart.LEFT_HAND || it == BodyPart.RIGHT_HAND - } - return (automaticTrackers + handTrackers).toList() - } - - @OptIn(ExperimentalCoroutinesApi::class) - override fun observe(receiver: OutputTrackerToggleManager) { - receiver.settings.context.state - .map { it.data.outputTrackersConfig } - .distinctUntilChanged() - .onEach { config -> - if (!config.automaticTrackerToggle) { - // Manual - receiver.context.dispatch(OutputTrackerToggleActions.SetOutputTrackers(config.trackers)) - } - } - .flatMapLatest { config -> - if (!config.automaticTrackerToggle) return@flatMapLatest emptyFlow() - - receiver.server.context.state - .map { it.trackers.values } - .flatMapLatest { trackers -> - // Tracker state emits on every rotation packet, but only bodyPart/status matter here. - // Dedup per tracker first, or combine gets resumed once per packet per tracker. - combine( - trackers.map { tracker -> - tracker.context.state.distinctUntilChanged { a, b -> a.bodyPart == b.bodyPart && a.status == b.status } - }, - ) { states -> - states.filter { (it.status == TrackerStatus.OK || it.status == TrackerStatus.SLEEPING) && it.origin != DeviceOrigin.DRIVER && it.origin != DeviceOrigin.VRC } - .map { it.bodyPart } - .toSet() - }.distinctUntilChanged() - } - .map { fineBodyParts -> config to fineBodyParts } - } - .onEach { (config, fineBodyParts) -> - // Get the output trackers based on body parts - val outputTrackers = determineAutomaticOutputTrackers(config, fineBodyParts) - - // Update state - receiver.context.dispatch(OutputTrackerToggleActions.SetOutputTrackers(outputTrackers)) - } - .launchIn(receiver.context.scope) - } - - override fun reduce(state: OutputTrackerToggleState, action: OutputTrackerToggleActions) = when (action) { - is OutputTrackerToggleActions.SetOutputTrackers -> { - state.copy(trackers = action.trackers) - } - } -} diff --git a/server/core/src/main/java/dev/slimevr/outputtrackertoggle/module.kt b/server/core/src/main/java/dev/slimevr/outputtrackertoggle/module.kt deleted file mode 100644 index 384cdc1e1..000000000 --- a/server/core/src/main/java/dev/slimevr/outputtrackertoggle/module.kt +++ /dev/null @@ -1,44 +0,0 @@ -package dev.slimevr.outputtrackertoggle - -import dev.slimevr.Phase1ContextProvider -import dev.slimevr.VRServer -import dev.slimevr.config.Settings -import dev.slimevr.context.Behaviour -import dev.slimevr.context.Context -import kotlinx.coroutines.CoroutineScope -import solarxr_protocol.datatypes.BodyPart -import kotlin.collections.listOf - -data class OutputTrackerToggleState( - /** - * The output trackers should be on the tail of the present BodyParts - * Example: for the SteamVR waist tracker, since it uses the hip's rotation and tail position, - * we check for BodyPart.HIP. - */ - val trackers: List, -) - -sealed interface OutputTrackerToggleActions { - data class SetOutputTrackers(val trackers: List) : OutputTrackerToggleActions -} - -typealias OutputTrackerToggleContext = Context -typealias OutputTrackerToggleBehaviour = Behaviour - -class OutputTrackerToggleManager(val context: OutputTrackerToggleContext, val server: VRServer, val settings: Settings) { - fun startObserving() = context.observeAll(this) - - companion object { - fun create(ctx: Phase1ContextProvider, scope: CoroutineScope): OutputTrackerToggleManager { - val context = Context.create( - initialState = OutputTrackerToggleState( - trackers = listOf(), - ), - scope = scope, - behaviours = listOf(OutputTrackerToggleBasicBehaviour()), - name = "OutputTrackerToggleManager", - ) - return OutputTrackerToggleManager(context, ctx.server, ctx.config.settings) - } - } -} diff --git a/server/core/src/main/java/dev/slimevr/routing/behaviours.kt b/server/core/src/main/java/dev/slimevr/routing/behaviours.kt new file mode 100644 index 000000000..87c921bb1 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/routing/behaviours.kt @@ -0,0 +1,66 @@ +package dev.slimevr.routing + +import dev.slimevr.AppContextProvider +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach + +class BoneRoutingBaseBehaviour : BoneRoutingBehaviour { + override fun reduce(state: BoneRoutingState, action: BoneRoutingActions) = when (action) { + is BoneRoutingActions.SetRoutes -> state.copy(routes = action.routes) + } +} + +class BoneRoutingBasicBehaviour(private val appContext: AppContextProvider) : BoneRoutingBehaviour { + @OptIn(ExperimentalCoroutinesApi::class) + override fun observe(receiver: BoneRoutingManager) { + val server = appContext.server + val settings = appContext.config.settings + + combine( + settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(), + outputStatesFlow(appContext), + ::Pair, + ) + .onEach { (config, outputStates) -> + if (!config.automatic) { + receiver.context.dispatch( + BoneRoutingActions.SetRoutes( + effectiveRoutes(config.manualRoutes.orEmpty(), outputStates), + ), + ) + } + } + .flatMapLatest { (config, outputStates) -> + if (!config.automatic) return@flatMapLatest emptyFlow() + + server.context.state + .map { it.trackers.values } + .flatMapLatest { trackers -> + // Tracker state emits on every rotation packet, but only bodyPart/status matter here. + // Dedup per tracker first, or combine gets resumed once per packet per tracker. + combine( + trackers.map { tracker -> + tracker.context.state.distinctUntilChanged { a, b -> a.bodyPart == b.bodyPart && a.status == b.status } + }, + ) { states -> trackedBodyParts(states.asList()) } + .distinctUntilChanged() + } + .map { fineBodyParts -> Triple(config, outputStates, fineBodyParts) } + } + .onEach { (config, outputStates, fineBodyParts) -> + val candidates = determineCandidateBones(config, fineBodyParts) + receiver.context.dispatch( + BoneRoutingActions.SetRoutes( + effectiveRoutes(computeAutomaticRoutes(candidates, outputStates), outputStates), + ), + ) + } + .launchIn(receiver.context.scope) + } +} diff --git a/server/core/src/main/java/dev/slimevr/routing/module.kt b/server/core/src/main/java/dev/slimevr/routing/module.kt new file mode 100644 index 000000000..194dd0ba0 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/routing/module.kt @@ -0,0 +1,44 @@ +package dev.slimevr.routing + +import dev.slimevr.AppContextProvider +import dev.slimevr.context.Behaviour +import dev.slimevr.context.Context +import kotlinx.coroutines.CoroutineScope + +data class BoneRoutingState( + /** + * Which outputs each bone is sent to. A bone that is absent, or maps to an empty + * set, is not sent anywhere. + * + * Automatic mode builds this from the connected trackers and the output priority. + * Manual mode resolves it from BoneRoutingConfig.manualRoutes, dropping outputs + * that are off or cannot take the bone. + */ + val routes: Routes, +) + +sealed interface BoneRoutingActions { + data class SetRoutes(val routes: Routes) : BoneRoutingActions +} + +typealias BoneRoutingContext = Context +typealias BoneRoutingBehaviour = Behaviour + +class BoneRoutingManager(val context: BoneRoutingContext) { + fun startObserving(appContext: AppContextProvider) { + context.behaviours.addAll(listOf(BoneRoutingBasicBehaviour(appContext))) + context.observeAll(this) + } + + companion object { + fun create(scope: CoroutineScope): BoneRoutingManager { + val context = Context.create( + initialState = BoneRoutingState(routes = emptyMap()), + scope = scope, + behaviours = listOf(BoneRoutingBaseBehaviour()), + name = "BoneRoutingManager", + ) + return BoneRoutingManager(context) + } + } +} diff --git a/server/core/src/main/java/dev/slimevr/routing/routing.kt b/server/core/src/main/java/dev/slimevr/routing/routing.kt new file mode 100644 index 000000000..535d28702 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/routing/routing.kt @@ -0,0 +1,191 @@ +package dev.slimevr.routing + +import dev.slimevr.AppContextProvider +import dev.slimevr.config.BoneRoutingConfig +import dev.slimevr.device.DeviceOrigin +import dev.slimevr.driver.DRIVER_SUPPORTED_BONES +import dev.slimevr.tracker.TrackerState +import dev.slimevr.vmc.VMC_SUPPORTED_BONES +import dev.slimevr.vrcosc.VRC_OSC_SUPPORTED_BONES +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.datatypes.TrackerStatus +import solarxr_protocol.rpc.RoutingOutput +import solarxr_protocol.rpc.RoutingOutputState +import solarxr_protocol.rpc.VRCOSCOutputState + +typealias Routes = Map> +typealias OutputStates = Map + +/** Every output treated as on, for what the user asked for rather than what is sent. */ +private val ALL_ACTIVE: OutputStates = RoutingOutput.entries.associateWith { RoutingOutputState.ACTIVE } + +private val PRIORITY_CHAIN = listOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC) + +fun acceptedBones(output: RoutingOutput): Set = when (output) { + RoutingOutput.DRIVER -> DRIVER_SUPPORTED_BONES + RoutingOutput.VRC_OSC -> VRC_OSC_SUPPORTED_BONES + RoutingOutput.VMC -> VMC_SUPPORTED_BONES +} + +fun conflictingOutputs(output: RoutingOutput): Set = when (output) { + in PRIORITY_CHAIN -> PRIORITY_CHAIN.toSet() - output + else -> emptySet() +} + +/** Bones an output needs to work at all, so the user cannot turn them off. */ +fun requiredBones(output: RoutingOutput): Set = when (output) { + RoutingOutput.DRIVER, RoutingOutput.VRC_OSC -> emptySet() + RoutingOutput.VMC -> VMC_SUPPORTED_BONES +} + +fun isActive(states: OutputStates, output: RoutingOutput): Boolean = states[output] == RoutingOutputState.ACTIVE + +fun platformSupports(appContext: AppContextProvider, output: RoutingOutput): Boolean = when (output) { + RoutingOutput.DRIVER -> appContext.featureFlags.supportsDriver + RoutingOutput.VRC_OSC, RoutingOutput.VMC -> true +} + +/** Emits the output states as the driver connects and the output configs change. */ +fun outputStatesFlow(appContext: AppContextProvider): Flow { + val settings = appContext.config.settings + + return combine( + appContext.server.context.state.map { it.drivers.isNotEmpty() }.distinctUntilChanged(), + settings.context.state.map { it.data.vrcOscConfig.enabled }.distinctUntilChanged(), + settings.context.state.map { it.data.vmcConfig.enabled }.distinctUntilChanged(), + appContext.vrcOscManager.context.state + .map { it.status.outputState == VRCOSCOutputState.READY } + .distinctUntilChanged(), + ) { driverConnected, vrcOscEnabled, vmcEnabled, vrcOscHasTarget -> + RoutingOutput.entries.associateWith { output -> + if (!platformSupports(appContext, output)) { + RoutingOutputState.UNSUPPORTED + } else { + when (output) { + RoutingOutput.DRIVER -> if (driverConnected) RoutingOutputState.ACTIVE else RoutingOutputState.INACTIVE + RoutingOutput.VRC_OSC -> when { + !vrcOscEnabled -> RoutingOutputState.INACTIVE + vrcOscHasTarget -> RoutingOutputState.ACTIVE + else -> RoutingOutputState.ENABLED + } + // Writes to a fixed address whether or not anything is there, so being + // on is the same as transmitting. + // FIXME: Maybe we should assume that we need to receive data from VMC for it to be considered working? + RoutingOutput.VMC -> if (vmcEnabled) RoutingOutputState.ACTIVE else RoutingOutputState.INACTIVE + } + } + } + } +} + +/** What the user asked for, including outputs that are switched off. */ +fun intendedRoutesFlow(appContext: AppContextProvider): Flow = combine( + appContext.config.settings.context.state.map { it.data.boneRoutingConfig }.distinctUntilChanged(), + appContext.boneRouting.context.state.map { it.routes }, +) { config, sent -> + effectiveRoutes(if (config.automatic) sent else config.manualRoutes.orEmpty(), ALL_ACTIVE) +}.distinctUntilChanged() + +/** + * What actually gets sent: the requested routes plus whatever each output requires, + * minus anything an output cannot accept or cannot currently send. + */ +fun effectiveRoutes(routes: Routes, outputStates: OutputStates): Routes { + val result = mutableMapOf>() + for ((bone, outputs) in routes) { + val kept = outputs.filterTo(mutableSetOf()) { + isActive(outputStates, it) && bone in acceptedBones(it) + } + if (kept.isNotEmpty()) result[bone] = kept + } + for (output in RoutingOutput.entries) { + if (!isActive(outputStates, output)) continue + for (bone in requiredBones(output)) { + result[bone] = result[bone].orEmpty() + output + } + } + return result +} + +/** + * The table a first switch to manual starts from: what automatic would route if every + * output this platform has were switched on. An output that is merely off still gets its + * bones, so switching it on later actually sends something. + * + * TODO: maybe this is bad, or annoying logic. we could default to just empty routes when switching to manual + */ +fun seedManualRoutes(appContext: AppContextProvider): Routes { + val config = appContext.config.settings.context.state.value.data.boneRoutingConfig + val trackers = appContext.server.context.state.value.trackers.values.map { it.context.state.value } + val allEnabled = RoutingOutput.entries.associateWith { + if (platformSupports(appContext, it)) RoutingOutputState.ACTIVE else RoutingOutputState.UNSUPPORTED + } + + return computeAutomaticRoutes(determineCandidateBones(config, trackedBodyParts(trackers)), allEnabled) +} + +fun applyRoutingChange( + config: BoneRoutingConfig, + automatic: Boolean, + routes: Routes, + seed: Routes, +): BoneRoutingConfig { + fun sanitized(source: Routes): Routes = source + .mapValues { (bone, outputs) -> + outputs.filterTo(mutableSetOf()) { bone in acceptedBones(it) && bone !in requiredBones(it) } + } + .filterValues { it.isNotEmpty() } + + return config.copy( + automatic = automatic, + manualRoutes = when { + automatic -> config.manualRoutes + config.automatic -> config.manualRoutes ?: sanitized(seed) + else -> sanitized(routes) + }, + ) +} + +private val candidateToFineBodyParts = mapOf( + BodyPart.UPPER_CHEST to setOf(BodyPart.UPPER_CHEST, BodyPart.CHEST), + BodyPart.LEFT_UPPER_ARM to setOf(BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM), + BodyPart.RIGHT_UPPER_ARM to setOf(BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM), + BodyPart.HIP to setOf(BodyPart.HIP, BodyPart.WAIST, BodyPart.CHEST, BodyPart.UPPER_CHEST), + BodyPart.LEFT_UPPER_LEG to setOf(BodyPart.LEFT_UPPER_LEG), + BodyPart.RIGHT_UPPER_LEG to setOf(BodyPart.RIGHT_UPPER_LEG), + BodyPart.LEFT_FOOT to setOf(BodyPart.LEFT_FOOT, BodyPart.LEFT_LOWER_LEG, BodyPart.LEFT_UPPER_LEG), + BodyPart.RIGHT_FOOT to setOf(BodyPart.RIGHT_FOOT, BodyPart.RIGHT_LOWER_LEG, BodyPart.RIGHT_UPPER_LEG), +) + +/** Tracker body parts that count as present. Loopback trackers never enable an output. */ +fun trackedBodyParts(trackers: Collection): Set = trackers + .filter { + (it.status == TrackerStatus.OK || it.status == TrackerStatus.SLEEPING) && + it.origin != DeviceOrigin.DRIVER && + it.origin != DeviceOrigin.VRC + } + .map { it.bodyPart } + .toSet() + +fun determineCandidateBones(config: BoneRoutingConfig, fineBodyParts: Set): Set { + val candidates = candidateToFineBodyParts + .filterValues { it.any { bp -> bp in fineBodyParts } } + .keys + // Hands aren't toggled automatically + val handBones = config.manualRoutes.orEmpty().keys.filter { + it == BodyPart.LEFT_HAND || it == BodyPart.RIGHT_HAND + } + return candidates + handBones +} + +/** Hands each bone to the best output that is on and can take it, so nothing is sent twice. */ +fun computeAutomaticRoutes(candidateBones: Set, outputStates: OutputStates): Routes { + val chain = PRIORITY_CHAIN.filter { isActive(outputStates, it) } + return candidateBones + .mapNotNull { bone -> chain.firstOrNull { bone in acceptedBones(it) }?.let { bone to setOf(it) } } + .toMap() +} diff --git a/server/core/src/main/java/dev/slimevr/solarxr/bone-routing.kt b/server/core/src/main/java/dev/slimevr/solarxr/bone-routing.kt new file mode 100644 index 000000000..c3243bc5f --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/solarxr/bone-routing.kt @@ -0,0 +1,98 @@ +package dev.slimevr.solarxr + +import dev.slimevr.AppContextProvider +import dev.slimevr.config.SettingsActions +import dev.slimevr.routing.OutputStates +import dev.slimevr.routing.Routes +import dev.slimevr.routing.applyRoutingChange +import dev.slimevr.routing.intendedRoutesFlow +import dev.slimevr.routing.acceptedBones +import dev.slimevr.routing.conflictingOutputs +import dev.slimevr.routing.requiredBones +import dev.slimevr.routing.outputStatesFlow +import dev.slimevr.routing.seedManualRoutes +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import solarxr_protocol.rpc.BoneRoute +import solarxr_protocol.rpc.BoneRoutingSettingsRequest +import solarxr_protocol.rpc.BoneRoutingSettingsResponse +import solarxr_protocol.rpc.ChangeBoneRoutingSettingsRequest +import solarxr_protocol.rpc.RoutingOutput +import solarxr_protocol.rpc.RoutingOutputStatus + +// Every bone any output can take gets a row, so the GUI can draw the whole table +// from the response alone. +private val ROUTABLE_BONES = RoutingOutput.entries.flatMapTo(mutableSetOf()) { acceptedBones(it) } + +private fun buildResponse( + automatic: Boolean, + routes: Routes, + outputStates: OutputStates, +) = BoneRoutingSettingsResponse( + automatic = automatic, + routes = ROUTABLE_BONES.map { bone -> + BoneRoute(bone = bone, outputs = routes[bone].orEmpty().toList()) + }, + outputs = RoutingOutput.entries.map { output -> + RoutingOutputStatus( + output = output, + accepts = acceptedBones(output).toList(), + requires = requiredBones(output).toList(), + conflicts = conflictingOutputs(output).toList(), + state = outputStates[output], + ) + }, +) + +class BoneRoutingBehaviour( + private val appContext: AppContextProvider, +) : SolarXRBridgeBehaviour { + private val settings = appContext.config.settings + + override fun observe(receiver: SolarXRBridge) { + val responses = combine( + settings.context.state.map { it.data.boneRoutingConfig.automatic }.distinctUntilChanged(), + intendedRoutesFlow(appContext), + outputStatesFlow(appContext), + ::buildResponse, + ).distinctUntilChanged() + + receiver.rpcDispatcher.on { + receiver.sendRpc(responses.first()) + }.launchIn(receiver.context.scope) + + responses + .drop(1) + .onEach(receiver::sendRpc) + .launchIn(receiver.context.scope) + + receiver.rpcDispatcher.on { req -> + val requested = req.routes.orEmpty() + .mapNotNull { route -> + val bone = route.bone ?: return@mapNotNull null + val outputs = route.outputs.orEmpty().toSet().ifEmpty { return@mapNotNull null } + bone to outputs + } + .toMap() + val seed = seedManualRoutes(appContext) + + settings.context.dispatch( + SettingsActions.Update { + copy( + boneRoutingConfig = applyRoutingChange( + config = boneRoutingConfig, + automatic = req.automatic == true, + routes = requested, + seed = seed, + ), + ) + }, + ) + }.launchIn(receiver.context.scope) + } +} diff --git a/server/core/src/main/java/dev/slimevr/solarxr/driver-settings.kt b/server/core/src/main/java/dev/slimevr/solarxr/driver-settings.kt new file mode 100644 index 000000000..32ed96764 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/solarxr/driver-settings.kt @@ -0,0 +1,38 @@ +package dev.slimevr.solarxr + +import dev.slimevr.config.Settings +import dev.slimevr.config.SettingsActions +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import solarxr_protocol.rpc.ChangeDriverSettingsRequest +import solarxr_protocol.rpc.DriverSettingsRequest +import solarxr_protocol.rpc.DriverSettingsResponse + +class DriverSettingsBehaviour( + private val settings: Settings, +) : SolarXRBridgeBehaviour { + override fun observe(receiver: SolarXRBridge) { + receiver.rpcDispatcher.on { + val config = settings.context.state.value.data.driverConfig + receiver.sendRpc(DriverSettingsResponse(sendDerivedVelocity = config.sendDerivedVelocity)) + }.launchIn(receiver.context.scope) + + settings.context.state + .drop(1) + .map { DriverSettingsResponse(sendDerivedVelocity = it.data.driverConfig.sendDerivedVelocity) } + .distinctUntilChanged() + .onEach(receiver::sendRpc) + .launchIn(receiver.context.scope) + + receiver.rpcDispatcher.on { req -> + settings.context.dispatch( + SettingsActions.Update { + copy(driverConfig = driverConfig.copy(sendDerivedVelocity = req.sendDerivedVelocity == true)) + }, + ) + }.launchIn(receiver.context.scope) + } +} diff --git a/server/core/src/main/java/dev/slimevr/solarxr/module.kt b/server/core/src/main/java/dev/slimevr/solarxr/module.kt index c6bad5859..37837dfd7 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/module.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/module.kt @@ -77,7 +77,8 @@ class SolarXRBridge( add(VmcBehaviour(appContext.config.settings)) add(HeightCalibrationBehaviour(appContext.heightCalibrationManager)) add(ProvisioningBehaviour(appContext.server, appContext.provisioningManager)) - add(OutputTrackersBehaviour(appContext.config.settings, appContext.outputTrackerToggle)) + add(BoneRoutingBehaviour(appContext)) + add(DriverSettingsBehaviour(appContext.config.settings)) add(SkeletonSettingsBehaviour(appContext.config.settings)) add(SkeletonProportionsBehaviour(appContext.config.userConfig, appContext.skeleton)) add(TrackingChecklistBehaviour(appContext.trackingChecklist, appContext.config.settings)) diff --git a/server/core/src/main/java/dev/slimevr/solarxr/output-trackers.kt b/server/core/src/main/java/dev/slimevr/solarxr/output-trackers.kt deleted file mode 100644 index a5c5ce9fa..000000000 --- a/server/core/src/main/java/dev/slimevr/solarxr/output-trackers.kt +++ /dev/null @@ -1,56 +0,0 @@ -package dev.slimevr.solarxr - -import dev.slimevr.config.OutputTrackersConfig -import dev.slimevr.config.Settings -import dev.slimevr.config.SettingsActions -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach -import solarxr_protocol.datatypes.BodyPart -import solarxr_protocol.rpc.ChangeOutputTrackersSettingsRequest -import solarxr_protocol.rpc.OutputTrackersSettingsRequest -import solarxr_protocol.rpc.OutputTrackersSettingsResponse - -class OutputTrackersBehaviour( - private val settings: Settings, - private val outputTrackerToggleManager: OutputTrackerToggleManager, -) : SolarXRBridgeBehaviour { - companion object { - private fun getSettingsResponse(config: OutputTrackersConfig, autoTrackers: List) = OutputTrackersSettingsResponse( - automaticTrackerToggle = config.automaticTrackerToggle, - trackers = if (config.automaticTrackerToggle) autoTrackers else config.trackers, - sendDerivedVelocity = config.sendDerivedVelocity, - ) - } - - override fun observe(receiver: SolarXRBridge) { - // Send config - receiver.rpcDispatcher.on { - receiver.sendRpc(getSettingsResponse(settings.context.state.value.data.outputTrackersConfig, outputTrackerToggleManager.context.state.value.trackers)) - }.launchIn(receiver.context.scope) - - combine(settings.context.state.map { it.data.outputTrackersConfig }, outputTrackerToggleManager.context.state.map { it.trackers }, ::Pair) - .map { (config, trackers) -> getSettingsResponse(config, trackers) } - .distinctUntilChanged() - .onEach(receiver::sendRpc) - .launchIn(receiver.context.scope) - - // Receive config - receiver.rpcDispatcher.on { req -> - settings.context.dispatch( - SettingsActions.Update { - copy( - outputTrackersConfig = OutputTrackersConfig( - automaticTrackerToggle = req.automaticTrackerToggle == true, - trackers = req.trackers ?: listOf(), - sendDerivedVelocity = req.sendDerivedVelocity == true, - ), - ) - }, - ) - }.launchIn(receiver.context.scope) - } -} diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt index a39ebddb7..bec57d7d0 100644 --- a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt @@ -11,6 +11,8 @@ import dev.slimevr.device.DeviceState import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.resets.ResetBodyParts import dev.slimevr.resets.ResetsManager +import dev.slimevr.routing.BoneRoutingManager +import dev.slimevr.routing.Routes import dev.slimevr.skeleton.Skeleton import dev.slimevr.tracker.TrackerState import dev.slimevr.vrchat.VRCConfigManager @@ -32,6 +34,7 @@ import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.TrackerStatus +import solarxr_protocol.rpc.RoutingOutput import solarxr_protocol.rpc.TrackingChecklistNeedCalibration import solarxr_protocol.rpc.TrackingChecklistPublicNetworks import solarxr_protocol.rpc.TrackingChecklistStep @@ -143,6 +146,52 @@ class TrackerErrorCheckBehaviour(private val server: VRServer) : TrackingCheckli } } +class SteamVRHandsCheckBehaviour( + private val server: VRServer, + private val settings: Settings, + private val boneRouting: BoneRoutingManager, +) : TrackingChecklistBehaviourType { + private val HAND_BONES = setOf(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + + private fun computeStep( + trackers: List, + routes: Routes, + driverConnected: Boolean, + automatic: Boolean, + ): TrackingChecklistStep { + // The skeleton computes a hand bone from the arm chain, so routing one sends a hand + // tracker to SteamVR whether or not the user wears anything on that hand. + val handsSentToDriver = HAND_BONES.any { hand -> routes[hand]?.contains(RoutingOutput.DRIVER) == true } + val handTrackers = trackers.filter { tracker -> tracker.bodyPart in HAND_BONES } + // Controllers reach us back through the driver, anything else on a hand is a + // tracker the user actually wears. + val hasControllers = handTrackers.any { tracker -> tracker.origin == DeviceOrigin.DRIVER } + val hasHandTrackers = handTrackers.any { tracker -> + tracker.origin != DeviceOrigin.DRIVER && tracker.origin != DeviceOrigin.VRC + } + + return TrackingChecklistStep( + valid = !handsSentToDriver || (!hasControllers && hasHandTrackers), + enabled = driverConnected && !automatic, + ignorable = true, + visibility = TrackingChecklistStepVisibility.WHEN_INVALID, + ) + } + + override fun observe(receiver: TrackingChecklist) { + combine( + trackerStatesFlow(server), + boneRouting.context.state.map { state -> state.routes }, + server.context.state.map { state -> state.drivers.isNotEmpty() }.distinctUntilChanged(), + settings.context.state.map { state -> state.data.boneRoutingConfig.automatic }.distinctUntilChanged(), + ::computeStep, + ) + .distinctUntilChanged() + .onEach { step -> receiver.context.dispatch(TrackingChecklistActions.UpdateStep(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED, step)) } + .launchIn(receiver.context.scope) + } +} + class VRChatSettingsCheckBehaviour( private val server: VRServer, private val skeleton: Skeleton, diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt index dc2827701..7fb96dd15 100644 --- a/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt +++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt @@ -35,6 +35,7 @@ class TrackingChecklist( add(FullResetCheckBehaviour(appContext.server, appContext.resetsManager)) add(MountingCalibrationCheckBehaviour(appContext.server, appContext.resetsManager, appContext.config.settings)) add(TrackerErrorCheckBehaviour(appContext.server)) + add(SteamVRHandsCheckBehaviour(appContext.server, appContext.config.settings, appContext.boneRouting)) add(FeetMountingCalibrationCheckBehaviour(appContext.server, appContext.resetsManager, appContext.config.settings)) // TODO: STAY_ALIGNED_CONFIGURED diff --git a/server/core/src/main/java/dev/slimevr/vmc/behaviours.kt b/server/core/src/main/java/dev/slimevr/vmc/behaviours.kt index 113bc6d77..0031cfe74 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/behaviours.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/behaviours.kt @@ -10,22 +10,26 @@ import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage import dev.slimevr.osc.OscReceiver import dev.slimevr.osc.OscSender +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.Skeleton import dev.slimevr.util.timeSource import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.RoutingOutput import kotlin.time.Duration.Companion.seconds class VMCOutputBehaviour( private val skeleton: Skeleton, private val settings: Settings, + private val boneRouting: BoneRoutingManager, ) : VMCBehaviourType { private val logSpamWaitDuration = 1.seconds private val initTime = System.currentTimeMillis() @@ -68,15 +72,19 @@ class VMCOutputBehaviour( } }.launchIn(receiver.context.scope) - skeleton.computed - .onEach { computedSkeleton -> + val routedBonesFlow = boneRouting.context.state + .map { state -> state.routes.filterValues { RoutingOutput.VMC in it }.keys } + .distinctUntilChanged() + + combine(skeleton.computed, routedBonesFlow, ::Pair) + .onEach { (computedSkeleton, routedBones) -> val s = sender ?: return@onEach val config = settings.context.state.value.data.vmcConfig val currentTime = System.currentTimeMillis() val vrm = vrmGeometry receiver.context.scope.launch { try { - s.send(buildBundle(computedSkeleton, config, currentTime, vrm)) + s.send(buildBundle(computedSkeleton, config, currentTime, vrm, routedBones)) } catch (e: Exception) { if (nextLogTime.hasPassedNow()) { AppLogger.vmc.error("Failed to send VMC frame", e) @@ -87,7 +95,7 @@ class VMCOutputBehaviour( }.launchIn(receiver.context.scope) } - private fun buildBundle(bones: Map, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?): OscBundle = OscBundle(1L, buildMessages(bones, config, currentTime, vrm).map { msg -> OscContent.Message(msg) }.toList()) + private fun buildBundle(bones: Map, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?, routedBones: Set): OscBundle = OscBundle(1L, buildMessages(bones, config, currentTime, vrm, routedBones).map { msg -> OscContent.Message(msg) }.toList()) private fun transformMessage(address: String, name: String, pos: Vector3, rot: Quaternion): OscMessage = OscMessage( address, @@ -103,7 +111,7 @@ class VMCOutputBehaviour( ), ) - private fun buildMessages(bones: Map, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?): Sequence = sequence { + private fun buildMessages(bones: Map, config: VMCConfig, currentTime: Long, vrm: VrmGeometry?, routedBones: Set): Sequence = sequence { val time = (currentTime - initTime) / 1000f yield(OscMessage("/VMC/Ext/T", listOf(OscArg.Float(time)))) yield(OscMessage("/VMC/Ext/OK", listOf(OscArg.Int(1)))) @@ -112,8 +120,9 @@ class VMCOutputBehaviour( yield(transformMessage("/VMC/Ext/Root/Pos", "root", Vector3.NULL, Quaternion.IDENTITY)) // TODO UpperChest + shoulders affecting arms local rot - // TODO Don't send fingers if we don't have any tracker for them for ((targetBodyPart, unityName) in BODY_PART_TO_UNITY_BONE) { + if (targetBodyPart !in routedBones) continue + val targetParentBodyPart = VMC_BONE_PARENTS[targetBodyPart] val trackingBodyPart = if (config.mirrorTracking) vmcMirrorSource(targetBodyPart) else targetBodyPart val trackingBone = bones[trackingBodyPart] ?: continue diff --git a/server/core/src/main/java/dev/slimevr/vmc/mapping.kt b/server/core/src/main/java/dev/slimevr/vmc/mapping.kt index 3118747a6..8e57a4bcc 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/mapping.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/mapping.kt @@ -60,6 +60,9 @@ val BODY_PART_TO_UNITY_BONE: Map = mapOf( BodyPart.RIGHT_LITTLE_DISTAL to "RightLittleDistal", ) +// Bones VMC can accept. Used by the routing module. +val VMC_SUPPORTED_BONES: Set = BODY_PART_TO_UNITY_BONE.keys + // HIP-rooted hierarchy. VMC/Unity expects this; our skeleton is HEAD-rooted. val VMC_HIERARCHY_MAP: Map> = mapOf( BodyPart.HIP to arrayOf(BodyPart.WAIST, BodyPart.LEFT_UPPER_LEG, BodyPart.RIGHT_UPPER_LEG), diff --git a/server/core/src/main/java/dev/slimevr/vmc/module.kt b/server/core/src/main/java/dev/slimevr/vmc/module.kt index a9f2fcaf4..fdaba3436 100644 --- a/server/core/src/main/java/dev/slimevr/vmc/module.kt +++ b/server/core/src/main/java/dev/slimevr/vmc/module.kt @@ -1,9 +1,8 @@ package dev.slimevr.vmc -import dev.slimevr.Phase1ContextProvider +import dev.slimevr.AppContextProvider import dev.slimevr.context.Behaviour import dev.slimevr.context.Context -import dev.slimevr.skeleton.Skeleton import kotlinx.coroutines.CoroutineScope object VMCState @@ -14,18 +13,23 @@ typealias VMCContext = Context typealias VMCBehaviourType = Behaviour class VMCManager(val context: VMCContext) { - fun startObserving() = context.observeAll(this) + fun startObserving(appContext: AppContextProvider) { + val settings = appContext.config.settings + val behaviours = listOf( + VMCOutputBehaviour(appContext.skeleton, settings, appContext.boneRouting), + VMCInputBehaviour(settings), + ) + + context.behaviours.addAll(behaviours) + context.observeAll(this) + } companion object { - fun create(ctx: Phase1ContextProvider, skeleton: Skeleton, scope: CoroutineScope): VMCManager { - val settings = ctx.config.settings + fun create(scope: CoroutineScope): VMCManager { val context = Context.create( initialState = VMCState, scope = scope, - behaviours = listOf( - VMCOutputBehaviour(skeleton, settings), - VMCInputBehaviour(settings), - ), + behaviours = emptyList(), name = "VMC", ) return VMCManager(context) diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/module.kt b/server/core/src/main/java/dev/slimevr/vrcosc/module.kt index def09bc6c..100af6365 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/module.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/module.kt @@ -6,7 +6,6 @@ import dev.slimevr.Phase1ContextProvider import dev.slimevr.config.Settings import dev.slimevr.context.Behaviour import dev.slimevr.context.Context -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import io.github.axisangles.ktmath.Quaternion import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @@ -96,13 +95,12 @@ class VRCOSCManager( val context: VRCOSCContext, val oscQueryAddress: String, val settings: Settings, - val outputTrackerToggle: OutputTrackerToggleManager, ) { val events: EventDispatcher = EventDispatcher("VRCOSC", context.scope, capacity = 32) fun startObserving(appContext: AppContextProvider) { val behaviours = listOf( - VRCOSCOutputBehaviour(appContext.skeleton), + VRCOSCOutputBehaviour(appContext.skeleton, appContext.boneRouting), VRCOSCInputBehaviour(appContext), VRCOSCOscQueryBehaviour(localIp = oscQueryAddress), ) @@ -122,7 +120,6 @@ class VRCOSCManager( ctx: Phase1ContextProvider, scope: CoroutineScope, oscQueryAddress: String, - outputTrackerToggle: OutputTrackerToggleManager, ): VRCOSCManager { val settings = ctx.config.settings val context = Context.create( @@ -133,7 +130,7 @@ class VRCOSCManager( scope = scope, name = "VRCOSC", ) - return VRCOSCManager(context, oscQueryAddress, settings, outputTrackerToggle) + return VRCOSCManager(context, oscQueryAddress, settings) } } } diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt b/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt index 1faa458ca..0e45ccadd 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/output-encoder.kt @@ -4,7 +4,6 @@ import dev.slimevr.osc.OscArg import dev.slimevr.osc.OscBundle import dev.slimevr.osc.OscContent import dev.slimevr.osc.OscMessage -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import dev.slimevr.skeleton.BoneState import io.github.axisangles.ktmath.EulerOrder import io.github.axisangles.ktmath.Quaternion @@ -23,13 +22,16 @@ private val trackerIdsByBodyPart = mapOf( BodyPart.RIGHT_UPPER_ARM to 8, ) +/** Bones VRChat OSC can accept. Used by the routing module. */ +val VRC_OSC_SUPPORTED_BONES: Set = trackerIdsByBodyPart.keys + internal fun buildOutgoingBundle( bones: Map, - outputTrackerToggle: OutputTrackerToggleManager, + routedBones: Set, ): OscBundle? { val messages = buildList { for ((bodyPart, trackerId) in trackerIdsByBodyPart) { - if (bodyPart !in outputTrackerToggle.context.state.value.trackers) continue + if (bodyPart !in routedBones) continue val bone = bones[bodyPart] ?: continue add( diff --git a/server/core/src/main/java/dev/slimevr/vrcosc/output.kt b/server/core/src/main/java/dev/slimevr/vrcosc/output.kt index 29894903b..bdbd7e172 100644 --- a/server/core/src/main/java/dev/slimevr/vrcosc/output.kt +++ b/server/core/src/main/java/dev/slimevr/vrcosc/output.kt @@ -3,6 +3,7 @@ package dev.slimevr.vrcosc import dev.slimevr.config.VRCOSCConfig import dev.slimevr.logging.AppLogger import dev.slimevr.osc.OscSender +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.BoneState import dev.slimevr.skeleton.Skeleton import io.github.axisangles.ktmath.Quaternion @@ -12,6 +13,7 @@ import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.RoutingOutput import solarxr_protocol.rpc.VRCOSCOutputState import solarxr_protocol.rpc.VRCOSCTargetSource @@ -19,6 +21,7 @@ private const val FRAME_RETRY_DELAY_MS = 5_000L class VRCOSCOutputBehaviour( private val skeleton: Skeleton, + private val boneRouting: BoneRoutingManager, ) : VRCOSCBehaviour { private class OutputRuntime { var sender: OscSender? = null @@ -71,8 +74,12 @@ class VRCOSCOutputBehaviour( } private fun observeFrames(receiver: VRCOSCManager, runtime: OutputRuntime) { - skeleton.computed - .onEach { computedSkeleton -> sendFrame(receiver, runtime, computedSkeleton) } + val routedBones = boneRouting.context.state + .map { state -> state.routes.filterValues { RoutingOutput.VRC_OSC in it }.keys } + .distinctUntilChanged() + + combine(skeleton.computed, routedBones, ::Pair) + .onEach { (computedSkeleton, bones) -> sendFrame(receiver, runtime, computedSkeleton, bones) } .launchIn(receiver.context.scope) } @@ -139,6 +146,7 @@ class VRCOSCOutputBehaviour( receiver: VRCOSCManager, runtime: OutputRuntime, bones: Map, + routedBones: Set, ) { val sender = runtime.sender ?: return val state = receiver.context.state.value @@ -148,7 +156,7 @@ class VRCOSCOutputBehaviour( val now = System.currentTimeMillis() if (runtime.frameSendFailureActive && now < runtime.nextFrameRetryAt) return - val bundle = buildOutgoingBundle(bones, receiver.outputTrackerToggle) ?: return + val bundle = buildOutgoingBundle(bones, routedBones) ?: return try { sender.send(bundle) diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt index f1118fea8..5706a3c68 100644 --- a/server/core/src/test/java/dev/slimevr/TestServer.kt +++ b/server/core/src/test/java/dev/slimevr/TestServer.kt @@ -3,6 +3,7 @@ package dev.slimevr import dev.slimevr.bvh.BVHManager import dev.slimevr.config.AppConfig import dev.slimevr.config.ConfigStorage +import dev.slimevr.config.DefaultSettingsBehaviour import dev.slimevr.config.DefaultUserBehaviour import dev.slimevr.config.Settings import dev.slimevr.config.SettingsActions @@ -14,6 +15,9 @@ import dev.slimevr.config.UserConfigData import dev.slimevr.config.UserConfigState import dev.slimevr.context.Context import dev.slimevr.device.DeviceOrigin +import dev.slimevr.driver.DriverBridge +import dev.slimevr.driver.DriverBridgeActions +import dev.slimevr.driver.DriverBridgeState import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationActions import dev.slimevr.heightcalibration.HeightCalibrationManager @@ -22,12 +26,12 @@ import dev.slimevr.keybind.KeybindManager import dev.slimevr.math.angle.Angle import dev.slimevr.math.angle.AngleErrors import dev.slimevr.networkprofile.NetworkProfileManager -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsBasicBehaviour import dev.slimevr.resets.ResetsManager import dev.slimevr.resets.ResetsMountingTimeoutBehaviour import dev.slimevr.resets.ResetsState +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.serial.FlashingHandler import dev.slimevr.serial.SerialPortHandle import dev.slimevr.serial.SerialServer @@ -184,12 +188,22 @@ fun buildTestSettings(scope: CoroutineScope): Settings { val context = Context.create( initialState = initialState, scope = scope, - behaviours = emptyList(), + behaviours = listOf(DefaultSettingsBehaviour()), name = "Settings[test]", ) return Settings(context, scope, NoopConfigStorage, "settings") } +fun buildTestDriverBridge(server: VRServer, appContext: AppContextProvider, id: Int): DriverBridge { + val context = Context.create( + initialState = DriverBridgeState(protocolVersion = 0, trackers = emptyMap()), + scope = server.context.scope, + behaviours = emptyList(), + name = "TestDriver[$id]", + ) + return DriverBridge(id = id, context = context, appContext = appContext) +} + fun buildTestHeightCalibration(server: VRServer, userConfig: UserConfig, scope: CoroutineScope): HeightCalibrationManager { val initialState = HeightCalibrationState(status = UserHeightCalibrationStatus.NONE, currentHeight = 1.6f, canDoUserHeightCalibration = true) val context = Context.create( @@ -243,7 +257,7 @@ abstract class TestAppContext : AppContextProvider { override val vrcOscManager: VRCOSCManager get() = error("not used in test") override val resetsManager: ResetsManager get() = error("not used in test") override val tapDetectionManager: TapDetectionManager get() = error("not used in test") - override val outputTrackerToggle: OutputTrackerToggleManager get() = error("not used in test") + override val boneRouting: BoneRoutingManager get() = error("not used in test") override val stayAlignedManager: StayAlignedManager get() = error("not used in test") override fun startObserving() {} override suspend fun dispose() = Unit diff --git a/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt new file mode 100644 index 000000000..150a26a24 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/routing/AutomaticRoutesTest.kt @@ -0,0 +1,186 @@ +package dev.slimevr.routing + +import dev.slimevr.driver.DRIVER_SUPPORTED_BONES +import dev.slimevr.vmc.VMC_SUPPORTED_BONES +import dev.slimevr.vrcosc.VRC_OSC_SUPPORTED_BONES +import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.RoutingOutput +import solarxr_protocol.rpc.RoutingOutputState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Builds an OutputStates with only the named outputs ACTIVE. */ +private fun active(vararg outputs: RoutingOutput): OutputStates = + RoutingOutput.entries.associateWith { + if (it in outputs) RoutingOutputState.ACTIVE else RoutingOutputState.INACTIVE + } + +private val NONE_ACTIVE = active() + +/** + * Bones a typical full body setup produces. Deliberately includes lower legs, which + * no output can take, so the tests also cover candidates being dropped. + */ +private val COMMON_CANDIDATES = setOf( + BodyPart.HIP, + BodyPart.UPPER_CHEST, + BodyPart.UPPER_CHEST, + BodyPart.LEFT_UPPER_LEG, + BodyPart.RIGHT_UPPER_LEG, + BodyPart.LEFT_LOWER_LEG, + BodyPart.RIGHT_LOWER_LEG, +) + +private fun routedTo( + routes: Map>, + output: RoutingOutput, +): Set = routes.filterValues { output in it }.keys + +class AutomaticRoutesTest { + @Test + fun `the driver alone takes every bone it supports`() { + val routes = computeAutomaticRoutes(COMMON_CANDIDATES, active(RoutingOutput.DRIVER)) + + assertEquals(COMMON_CANDIDATES intersect DRIVER_SUPPORTED_BONES, routedTo(routes, RoutingOutput.DRIVER)) + assertEquals(emptySet(), routedTo(routes, RoutingOutput.VRC_OSC)) + assertEquals(emptySet(), routedTo(routes, RoutingOutput.VMC)) + } + + @Test + fun `OSC becomes primary when no driver is connected`() { + val routes = computeAutomaticRoutes(COMMON_CANDIDATES, active(RoutingOutput.VRC_OSC)) + + assertEquals(COMMON_CANDIDATES intersect VRC_OSC_SUPPORTED_BONES, routedTo(routes, RoutingOutput.VRC_OSC)) + assertEquals(emptySet(), routedTo(routes, RoutingOutput.DRIVER)) + } + + @Test + fun `OSC only gets bones the driver cannot take`() { + val routes = computeAutomaticRoutes( + COMMON_CANDIDATES, + active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC), + ) + + // The dedup contract: a bone never goes to both, so no duplicate trackers. + assertTrue(routes.values.none { RoutingOutput.DRIVER in it && RoutingOutput.VRC_OSC in it }) + // OSC is left with only what it supports and the driver did not already take. + assertEquals( + (COMMON_CANDIDATES intersect VRC_OSC_SUPPORTED_BONES) - DRIVER_SUPPORTED_BONES, + routedTo(routes, RoutingOutput.VRC_OSC), + ) + } + + @Test + fun `a bone neither can take goes nowhere`() { + // NECK is VMC only. + val routes = computeAutomaticRoutes( + setOf(BodyPart.NECK), + active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC), + ) + + assertEquals(emptySet(), routedTo(routes, RoutingOutput.DRIVER)) + assertEquals(emptySet(), routedTo(routes, RoutingOutput.VRC_OSC)) + } + + @Test + fun `VMC takes every supported bone regardless of candidates`() { + val states = active(RoutingOutput.VMC) + + val routes = effectiveRoutes(computeAutomaticRoutes(emptySet(), states), states) + + assertEquals(VMC_SUPPORTED_BONES, routedTo(routes, RoutingOutput.VMC)) + } + + @Test + fun `VMC does not disturb the priority chain`() { + val withoutVmcStates = active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC) + val withVmcStates = active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC) + + val withoutVmc = effectiveRoutes( + computeAutomaticRoutes(COMMON_CANDIDATES, withoutVmcStates), + withoutVmcStates, + ) + val withVmc = effectiveRoutes( + computeAutomaticRoutes(COMMON_CANDIDATES, withVmcStates), + withVmcStates, + ) + + assertEquals(routedTo(withoutVmc, RoutingOutput.DRIVER), routedTo(withVmc, RoutingOutput.DRIVER)) + assertEquals(routedTo(withoutVmc, RoutingOutput.VRC_OSC), routedTo(withVmc, RoutingOutput.VRC_OSC)) + assertEquals(VMC_SUPPORTED_BONES, routedTo(withVmc, RoutingOutput.VMC)) + } + + @Test + fun `nothing is routed when every output is off`() { + assertEquals(emptyMap(), computeAutomaticRoutes(COMMON_CANDIDATES, NONE_ACTIVE)) + } + + @Test + fun `an unsupported output is never routed to`() { + // Android: the driver IPC does not exist, so OSC has to take over. + val states = mapOf( + RoutingOutput.DRIVER to RoutingOutputState.UNSUPPORTED, + RoutingOutput.VRC_OSC to RoutingOutputState.ACTIVE, + RoutingOutput.VMC to RoutingOutputState.INACTIVE, + ) + + val routes = computeAutomaticRoutes(COMMON_CANDIDATES, states) + + assertEquals(emptySet(), routedTo(routes, RoutingOutput.DRIVER)) + assertEquals(COMMON_CANDIDATES intersect VRC_OSC_SUPPORTED_BONES, routedTo(routes, RoutingOutput.VRC_OSC)) + } + + @Test + fun `outputs on the priority chain conflict with each other`() { + // Both reach VRChat, so a bone on both arrives there twice. + assertEquals(setOf(RoutingOutput.VRC_OSC), conflictingOutputs(RoutingOutput.DRIVER)) + assertEquals(setOf(RoutingOutput.DRIVER), conflictingOutputs(RoutingOutput.VRC_OSC)) + } + + @Test + fun `VMC conflicts with nothing`() { + // A separate app entirely, so sharing a bone with it duplicates nothing. + assertEquals(emptySet(), conflictingOutputs(RoutingOutput.VMC)) + } + + @Test + fun `automatic never produces a conflicting route`() { + val routes = computeAutomaticRoutes(COMMON_CANDIDATES, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC)) + + for ((_, outputs) in routes) { + for (output in outputs) { + assertTrue(outputs.none { it != output && it in conflictingOutputs(output) }) + } + } + } + + @Test + fun `an enabled output that is not transmitting does not hold on to bones`() { + // The driver is on but nothing is connected, OSC is on but has found no target. + // Neither transmits, so neither should be handed anything. + val states = mapOf( + RoutingOutput.DRIVER to RoutingOutputState.ENABLED, + RoutingOutput.VRC_OSC to RoutingOutputState.ENABLED, + RoutingOutput.VMC to RoutingOutputState.INACTIVE, + ) + + assertEquals(emptyMap(), computeAutomaticRoutes(COMMON_CANDIDATES, states)) + } + + @Test + fun `an enabled output lets the next one in the chain take the bones`() { + // The driver would win the chain, but it is not transmitting, so OSC takes over + // rather than the bones being reserved for something with nobody listening. + val states = mapOf( + RoutingOutput.DRIVER to RoutingOutputState.ENABLED, + RoutingOutput.VRC_OSC to RoutingOutputState.ACTIVE, + RoutingOutput.VMC to RoutingOutputState.INACTIVE, + ) + + val routes = computeAutomaticRoutes(COMMON_CANDIDATES, states) + + assertEquals(emptySet(), routedTo(routes, RoutingOutput.DRIVER)) + assertEquals(COMMON_CANDIDATES intersect VRC_OSC_SUPPORTED_BONES, routedTo(routes, RoutingOutput.VRC_OSC)) + } +} diff --git a/server/core/src/test/java/dev/slimevr/outputtrackertoggle/OutputTrackerToggleTest.kt b/server/core/src/test/java/dev/slimevr/routing/CandidateBonesTest.kt similarity index 83% rename from server/core/src/test/java/dev/slimevr/outputtrackertoggle/OutputTrackerToggleTest.kt rename to server/core/src/test/java/dev/slimevr/routing/CandidateBonesTest.kt index d4f1417cf..19a84c346 100644 --- a/server/core/src/test/java/dev/slimevr/outputtrackertoggle/OutputTrackerToggleTest.kt +++ b/server/core/src/test/java/dev/slimevr/routing/CandidateBonesTest.kt @@ -1,13 +1,14 @@ -package dev.slimevr.outputtrackertoggle +package dev.slimevr.routing -import dev.slimevr.config.OutputTrackersConfig +import dev.slimevr.config.BoneRoutingConfig import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.RoutingOutput import kotlin.test.Test import kotlin.test.assertEquals -class OutputTrackerToggleTest { +class CandidateBonesTest { @Test - fun `Output trackers are automatically determined based off body parts`() { + fun `Candidate bones are automatically determined based off body parts`() { data class TestCase( val name: String, val fineBodyParts: Set, @@ -141,10 +142,12 @@ class OutputTrackerToggleTest { ), ) - val behaviour = OutputTrackerToggleBasicBehaviour() + testCases.forEach { case -> - val result = behaviour.determineAutomaticOutputTrackers( - config = OutputTrackersConfig(trackers = case.configuredTrackers), + val result = determineCandidateBones( + config = BoneRoutingConfig( + manualRoutes = case.configuredTrackers.associateWith { setOf(RoutingOutput.DRIVER) }, + ), fineBodyParts = case.fineBodyParts, ) @@ -155,4 +158,16 @@ class OutputTrackerToggleTest { ) } } + + @Test + fun `hands stay routable manually while never auto enabling`() { + val candidates = determineCandidateBones( + config = BoneRoutingConfig( + manualRoutes = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER)), + ), + fineBodyParts = emptySet(), + ) + + assertEquals(setOf(BodyPart.LEFT_HAND), candidates) + } } diff --git a/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt b/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt new file mode 100644 index 000000000..ffdc87686 --- /dev/null +++ b/server/core/src/test/java/dev/slimevr/routing/ManualRoutesTest.kt @@ -0,0 +1,242 @@ +package dev.slimevr.routing + +import dev.slimevr.config.BoneRoutingConfig +import solarxr_protocol.datatypes.BodyPart +import solarxr_protocol.rpc.RoutingOutput +import solarxr_protocol.rpc.RoutingOutputState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +private fun active(vararg outputs: RoutingOutput): OutputStates = + RoutingOutput.entries.associateWith { + if (it in outputs) RoutingOutputState.ACTIVE else RoutingOutputState.INACTIVE + } + +private val NONE_ACTIVE = active() +private val ALL_ON = active(*RoutingOutput.entries.toTypedArray()) + +private fun routesOf(vararg pairs: Pair>): Routes = mapOf(*pairs) + +private val AUTO_ROUTES = routesOf( + BodyPart.HIP to setOf(RoutingOutput.DRIVER), + BodyPart.LEFT_FOOT to setOf(RoutingOutput.DRIVER), +) + +private val HAND_TABLE = mapOf(BodyPart.LEFT_HAND to setOf(RoutingOutput.DRIVER)) + +class ManualRoutesTest { + @Test + fun `a bone can be routed to every output at once`() { + val routes = routesOf( + BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), + ) + + val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC)) + + assertEquals( + setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC), + sanitized[BodyPart.HIP], + ) + } + + @Test + fun `an unavailable output is dropped even when explicitly routed`() { + val routes = routesOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC)) + + val sanitized = effectiveRoutes(routes, active(RoutingOutput.VRC_OSC)) + + assertEquals(setOf(RoutingOutput.VRC_OSC), sanitized[BodyPart.HIP]) + } + + @Test + fun `an output that cannot take the bone is dropped`() { + // OSC has no slot for the neck, VMC does. + val routes = routesOf(BodyPart.NECK to setOf(RoutingOutput.VRC_OSC, RoutingOutput.VMC)) + + val sanitized = effectiveRoutes(routes, active(RoutingOutput.DRIVER, RoutingOutput.VRC_OSC, RoutingOutput.VMC)) + + assertEquals(setOf(RoutingOutput.VMC), sanitized[BodyPart.NECK]) + } + + @Test + fun `a bone left with no output is not kept`() { + val routes = routesOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) + + assertEquals(emptyMap(), effectiveRoutes(routes, NONE_ACTIVE)) + } +} + +class RoutingChangeTest { + @Test + fun `a fresh config is automatic with no manual table`() { + val config = BoneRoutingConfig() + + assertEquals(true, config.automatic) + assertNull(config.manualRoutes) + } + + @Test + fun `switching to manual the first time seeds from the automatic routes`() { + val config = BoneRoutingConfig(automatic = true, manualRoutes = null) + + val next = applyRoutingChange(config, automatic = false, routes = emptyMap(), seed = AUTO_ROUTES) + + assertEquals(false, next.automatic) + assertEquals(AUTO_ROUTES, next.manualRoutes.orEmpty()) + } + + @Test + fun `switching to manual again keeps the table the user built`() { + val config = BoneRoutingConfig(automatic = true, manualRoutes = HAND_TABLE) + + // The page was showing the automatic routes, so the request carries those. + val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES, seed = AUTO_ROUTES) + + assertEquals(HAND_TABLE, next.manualRoutes) + } + + @Test + fun `switching to manual again keeps an empty table the user cleared`() { + val config = BoneRoutingConfig(automatic = true, manualRoutes = emptyMap()) + + val next = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES, seed = AUTO_ROUTES) + + assertEquals(emptyMap(), next.manualRoutes) + } + + @Test + fun `editing while manual stores the new table`() { + val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE) + val edited = mapOf(BodyPart.HIP to setOf(RoutingOutput.VRC_OSC)) + + val next = applyRoutingChange(config, automatic = false, routes = edited, seed = AUTO_ROUTES) + + assertEquals(edited, next.manualRoutes) + } + + @Test + fun `switching back to automatic keeps the manual table`() { + val config = BoneRoutingConfig(automatic = false, manualRoutes = HAND_TABLE) + + val next = applyRoutingChange(config, automatic = true, routes = emptyMap(), seed = AUTO_ROUTES) + + assertEquals(true, next.automatic) + assertEquals(HAND_TABLE, next.manualRoutes) + } + + @Test + fun `staying automatic never creates a manual table`() { + val config = BoneRoutingConfig(automatic = true, manualRoutes = null) + + val next = applyRoutingChange(config, automatic = true, routes = AUTO_ROUTES, seed = AUTO_ROUTES) + + assertNull(next.manualRoutes) + } + + @Test + fun `a full round trip through automatic does not lose the manual table`() { + var config = BoneRoutingConfig(automatic = true, manualRoutes = null) + + config = applyRoutingChange(config, automatic = false, routes = emptyMap(), seed = AUTO_ROUTES) + config = applyRoutingChange(config, automatic = false, routes = HAND_TABLE, seed = AUTO_ROUTES) + config = applyRoutingChange(config, automatic = true, routes = HAND_TABLE, seed = AUTO_ROUTES) + config = applyRoutingChange(config, automatic = false, routes = AUTO_ROUTES, seed = AUTO_ROUTES) + + assertEquals(HAND_TABLE, config.manualRoutes) + } + + @Test + fun `the seed carries outputs that are merely off`() { + // What seedManualRoutes builds: automatic run with every output treated as on. + val allOn = RoutingOutput.entries.associateWith { RoutingOutputState.ACTIVE } + val seed = computeAutomaticRoutes(setOf(BodyPart.HIP), allOn) + + val config = applyRoutingChange( + BoneRoutingConfig(automatic = true, manualRoutes = null), + automatic = false, + routes = emptyMap(), + seed = seed, + ) + + // The driver was not connected at the time, but the bone is in the table so + // starting SteamVR later actually sends something. + assertEquals(setOf(RoutingOutput.DRIVER), config.manualRoutes.orEmpty()[BodyPart.HIP]) + } +} + +class ForcedRoutesTest { + @Test + fun `required bones are never stored, the server owns them`() { + val config = applyRoutingChange( + BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()), + automatic = false, + routes = mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER, RoutingOutput.VMC)), + seed = AUTO_ROUTES, + ) + + assertEquals(mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), config.manualRoutes) + } + + @Test + fun `a bone the user cannot edit is dropped entirely from storage`() { + // The neck is VMC only, and VMC is forced, so there is nothing to store. + val config = applyRoutingChange( + BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()), + automatic = false, + routes = mapOf(BodyPart.NECK to setOf(RoutingOutput.VMC)), + seed = AUTO_ROUTES, + ) + + assertEquals(emptyMap(), config.manualRoutes) + } + + @Test + fun `required bones come back when the routes are resolved`() { + val config = BoneRoutingConfig( + automatic = false, + manualRoutes = mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), + ) + + val resolved = effectiveRoutes( + config.manualRoutes.orEmpty(), + active(RoutingOutput.DRIVER, RoutingOutput.VMC), + ) + + assertEquals(setOf(RoutingOutput.DRIVER, RoutingOutput.VMC), resolved[BodyPart.HIP]) + assertEquals(setOf(RoutingOutput.VMC), resolved[BodyPart.NECK]) + } + + @Test + fun `an inactive output does not force anything`() { + val config = BoneRoutingConfig(automatic = false, manualRoutes = emptyMap()) + + val resolved = effectiveRoutes(config.manualRoutes.orEmpty(), active(RoutingOutput.DRIVER)) + + assertEquals(emptyMap(), resolved) + } + + @Test + fun `the page shows required bones ticked whatever is stored`() { + val shown = effectiveRoutes(emptyMap(), ALL_ON) + + assertEquals(setOf(RoutingOutput.VMC), shown[BodyPart.NECK]) + } + + @Test + fun `automatic gets required bones through the same step as manual`() { + val states = active(RoutingOutput.DRIVER, RoutingOutput.VMC) + + val automatic = effectiveRoutes(computeAutomaticRoutes(setOf(BodyPart.HIP), states), states) + val manual = effectiveRoutes(mapOf(BodyPart.HIP to setOf(RoutingOutput.DRIVER)), states) + + assertEquals(automatic[BodyPart.NECK], manual[BodyPart.NECK]) + assertEquals(automatic[BodyPart.HIP], manual[BodyPart.HIP]) + } + + @Test + fun `everything VMC accepts it also requires`() { + assertEquals(acceptedBones(RoutingOutput.VMC), requiredBones(RoutingOutput.VMC)) + assertEquals(emptySet(), requiredBones(RoutingOutput.DRIVER)) + } +} diff --git a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt index 162be4333..54f75b0e5 100644 --- a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt +++ b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt @@ -3,11 +3,13 @@ package dev.slimevr.trackingchecklist import dev.slimevr.TestAppContext import dev.slimevr.VRServer import dev.slimevr.VRServerActions +import dev.slimevr.buildTestDriverBridge import dev.slimevr.buildTestResetsManager import dev.slimevr.buildTestSettings import dev.slimevr.buildTestTracker import dev.slimevr.buildTestVrServer import dev.slimevr.config.Settings +import dev.slimevr.config.SettingsActions import dev.slimevr.device.DeviceOrigin import dev.slimevr.networkprofile.NetworkInfo import dev.slimevr.networkprofile.NetworkProfileActions @@ -15,6 +17,8 @@ import dev.slimevr.networkprofile.NetworkProfileManager import dev.slimevr.resets.ResetBodyParts import dev.slimevr.resets.ResetsActions import dev.slimevr.resets.ResetsManager +import dev.slimevr.routing.BoneRoutingActions +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.tracker.Tracker import dev.slimevr.tracker.TrackerActions import io.github.axisangles.ktmath.Vector3 @@ -26,6 +30,7 @@ import solarxr_protocol.datatypes.BodyPart import solarxr_protocol.datatypes.TrackerStatus import solarxr_protocol.datatypes.hardware_info.ImuType import solarxr_protocol.rpc.ResetType +import solarxr_protocol.rpc.RoutingOutput import solarxr_protocol.rpc.TrackingChecklistStep import solarxr_protocol.rpc.TrackingChecklistStepId import solarxr_protocol.rpc.TrackingChecklistTrackerReset @@ -45,6 +50,7 @@ class TrackingChecklistTest { override val resetsManager = this@Harness.resetsManager } private val checklist = TrackingChecklist.create(scope.backgroundScope) + private val boneRouting: BoneRoutingManager = BoneRoutingManager.create(scope.backgroundScope) private var nextId = 1 init { @@ -57,11 +63,28 @@ class TrackingChecklistTest { MountingCalibrationCheckBehaviour(server, resetsManager, settings), FeetMountingCalibrationCheckBehaviour(server, resetsManager, settings), NetworkProfileCheckBehaviour(networkProfileManager), + SteamVRHandsCheckBehaviour(server, settings, boneRouting), ), ) checklist.context.observeAll(checklist) } + fun connectDriver() { + val bridge = buildTestDriverBridge(server, appContext, id = nextId++) + server.context.dispatch(VRServerActions.DriverConnected(bridge)) + } + + fun routeToDriver(vararg bones: BodyPart) { + val routes = bones.associateWith { setOf(RoutingOutput.DRIVER) } + boneRouting.context.dispatch(BoneRoutingActions.SetRoutes(routes)) + } + + fun setAutomatic(automatic: Boolean) { + settings.context.dispatch( + SettingsActions.Update { copy(boneRoutingConfig = boneRoutingConfig.copy(automatic = automatic)) }, + ) + } + fun addTracker( bodyPart: BodyPart?, status: TrackerStatus = TrackerStatus.OK, @@ -269,4 +292,78 @@ class TrackingChecklistTest { assertEquals(false, h.step(TrackingChecklistStepId.NETWORK_PROFILE_PUBLIC).enabled) } + @Test + fun `STEAMVR_HANDS_ENABLED is disabled without a driver`() = runTest { + val h = Harness(this) + h.setAutomatic(false) + h.routeToDriver(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + runCurrent() + + assertEquals(false, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).enabled) + } + + @Test + fun `STEAMVR_HANDS_ENABLED flags hands sent to the driver while a controller is held`() = runTest { + val h = Harness(this) + h.setAutomatic(false) + h.connectDriver() + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP) + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.DRIVER) + h.routeToDriver(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + runCurrent() + + assertEquals(true, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).enabled) + assertEquals(false, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).valid) + } + + @Test + fun `STEAMVR_HANDS_ENABLED flags hands sent to the driver with no hand tracker worn`() = runTest { + val h = Harness(this) + h.setAutomatic(false) + h.connectDriver() + h.routeToDriver(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + runCurrent() + + // The hand bone is computed from the arm chain, so this is sent regardless. Turning + // it on by accident is the usual way to end up here. + assertEquals(false, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).valid) + } + + @Test + fun `STEAMVR_HANDS_ENABLED accepts hand trackers when no controller is held`() = runTest { + val h = Harness(this) + h.setAutomatic(false) + h.connectDriver() + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP) + h.routeToDriver(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + runCurrent() + + assertEquals(true, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).valid) + } + + @Test + fun `STEAMVR_HANDS_ENABLED ignores hands that are not routed to the driver`() = runTest { + val h = Harness(this) + h.setAutomatic(false) + h.connectDriver() + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP) + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.DRIVER) + runCurrent() + + assertEquals(true, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).valid) + } + + @Test + fun `STEAMVR_HANDS_ENABLED is disabled in automatic mode`() = runTest { + val h = Harness(this) + h.setAutomatic(true) + h.connectDriver() + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.UDP) + h.addTracker(BodyPart.LEFT_HAND, origin = DeviceOrigin.DRIVER) + h.routeToDriver(BodyPart.LEFT_HAND, BodyPart.RIGHT_HAND) + runCurrent() + + // Automatic owns the routes, so there is nothing the user could undo. + assertEquals(false, h.step(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED).enabled) + } } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt index 742a5e914..6425a77fa 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/Main.kt @@ -31,10 +31,10 @@ import dev.slimevr.firmware.FirmwareManager import dev.slimevr.heightcalibration.HeightCalibrationManager import dev.slimevr.keybind.KeybindManager import dev.slimevr.networkprofile.NetworkProfileManager -import dev.slimevr.outputtrackertoggle.OutputTrackerToggleManager import dev.slimevr.provisioning.ProvisioningManager import dev.slimevr.resets.ResetsManager import dev.slimevr.resolveConfigDirectory +import dev.slimevr.routing.BoneRoutingManager import dev.slimevr.skeleton.Skeleton import dev.slimevr.stayaligned.StayAlignedManager import dev.slimevr.tapdetection.TapDetectionManager @@ -118,14 +118,13 @@ fun main(args: Array) = runBlocking(appCoroutineExceptionHandler + } }) val udpServer = UdpServer.create(scope = this, addressResolver = ::resolveDesktopUdpAddress) - val outputTrackerToggle = OutputTrackerToggleManager.create(ctx = phase1, scope = this) + val boneRouting = BoneRoutingManager.create(scope = this) val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = this) - val vmcManager = VMCManager.create(ctx = phase1, skeleton = skeleton, scope = this) + val vmcManager = VMCManager.create(scope = this) val vrcOscManager = VRCOSCManager.create( ctx = phase1, scope = this, oscQueryAddress = resolveDesktopOscQueryAddress(), - outputTrackerToggle = outputTrackerToggle, ) val resetsManager = ResetsManager.create(ctx = phase1, scope = this) val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = this) @@ -146,7 +145,7 @@ fun main(args: Array) = runBlocking(appCoroutineExceptionHandler + heightCalibrationManager = heightCalibrationManager, trackingChecklist = trackingChecklist, udpServer = udpServer, - outputTrackerToggle = outputTrackerToggle, + boneRouting = boneRouting, bvhManager = bvhManager, vmcManager = vmcManager, vrcOscManager = vrcOscManager, diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt index 4bd23d7ee..69debedcd 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/ipc.kt @@ -15,16 +15,22 @@ const val FEEDER_PIPE = "\\\\.\\pipe\\SlimeVRInput" const val SOLARXR_PIPE = "\\\\.\\pipe\\SlimeVRRpc" suspend fun createIpcServers(appContext: AppContextProvider) = coroutineScope { + val driver = appContext.featureFlags.supportsDriver + when (CURRENT_PLATFORM) { Platform.LINUX, Platform.OSX -> { - launch { createUnixDriverSocket(appContext) } - launch { createUnixFeederSocket(appContext) } + if (driver) { + launch { createUnixDriverSocket(appContext) } + launch { createUnixFeederSocket(appContext) } + } launch { createUnixSolarXRSocket(appContext) } } Platform.WINDOWS -> { - launch { createWindowsDriverPipe(appContext) } - launch { createWindowsFeederPipe(appContext) } + if (driver) { + launch { createWindowsDriverPipe(appContext) } + launch { createWindowsFeederPipe(appContext) } + } launch { createWindowsSolarXRPipe(appContext) } } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt index 3840fef25..1cc99afdd 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/ipc/protocol.kt @@ -13,6 +13,9 @@ import dev.slimevr.desktop.platform.Version import dev.slimevr.driver.DriverBridge import dev.slimevr.driver.DriverBridgeInbound import dev.slimevr.driver.DriverBridgeOutbound +import dev.slimevr.driver.TrackerRole +import dev.slimevr.driver.bodyPartToRole +import dev.slimevr.driver.roleToBodyPart import dev.slimevr.logging.AppLogger import io.github.axisangles.ktmath.Quaternion import io.github.axisangles.ktmath.Vector3 @@ -20,70 +23,16 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import okio.Buffer -import solarxr_protocol.datatypes.BodyPart import java.io.File import java.nio.file.Path import kotlin.io.path.Path import kotlin.io.path.exists -/** - * SteamVR tracker roles to protobuf enum - */ -enum class TrackerRole( - val value: UByte, -) { - NONE(0.toUByte()), - WAIST(1.toUByte()), - LEFT_FOOT(2.toUByte()), - RIGHT_FOOT(3.toUByte()), - CHEST(4.toUByte()), - LEFT_KNEE(5.toUByte()), - RIGHT_KNEE(6.toUByte()), - LEFT_ELBOW(7.toUByte()), - RIGHT_ELBOW(8.toUByte()), - LEFT_SHOULDER(9.toUByte()), - RIGHT_SHOULDER(10.toUByte()), - LEFT_HAND(11.toUByte()), - RIGHT_HAND(12.toUByte()), - LEFT_CONTROLLER(13.toUByte()), - RIGHT_CONTROLLER(14.toUByte()), - HEAD(15.toUByte()), - NECK(16.toUByte()), - CAMERA(17.toUByte()), - KEYBOARD(18.toUByte()), - HMD(19.toUByte()), - BEACON(20.toUByte()), - GENERIC_CONTROLLER(21.toUByte()), - ; - - companion object { - fun fromValue(value: UByte): TrackerRole? = entries.firstOrNull { it.value == value } - } -} - -val bodyPartToRole = mapOf( - BodyPart.HEAD to TrackerRole.HMD, - BodyPart.UPPER_CHEST to TrackerRole.CHEST, - BodyPart.LEFT_UPPER_ARM to TrackerRole.LEFT_ELBOW, - BodyPart.RIGHT_UPPER_ARM to TrackerRole.RIGHT_ELBOW, - BodyPart.HIP to TrackerRole.WAIST, - BodyPart.LEFT_UPPER_LEG to TrackerRole.LEFT_KNEE, - BodyPart.RIGHT_UPPER_LEG to TrackerRole.RIGHT_KNEE, - BodyPart.LEFT_FOOT to TrackerRole.LEFT_FOOT, - BodyPart.RIGHT_FOOT to TrackerRole.RIGHT_FOOT, - BodyPart.LEFT_SHOULDER to TrackerRole.LEFT_SHOULDER, - BodyPart.RIGHT_SHOULDER to TrackerRole.RIGHT_SHOULDER, - BodyPart.LEFT_HAND to TrackerRole.LEFT_HAND, - BodyPart.RIGHT_HAND to TrackerRole.RIGHT_HAND, -) -val roleToBodyPart = bodyPartToRole.entries.associate { (k, v) -> v to k } - val solarxrToProtoStatus = mapOf( solarxr_protocol.datatypes.TrackerStatus.OK to TrackerStatus.Status.OK, solarxr_protocol.datatypes.TrackerStatus.SLEEPING to TrackerStatus.Status.OK,