Compare commits

..
Author SHA1 Message Date
JovannMC e9622135c1 fix: avoid calculating velocity if accel is available 2026-11-25 22:41:23 +03:00
JovannMC 5e06df1458 Merge branch 'server-rewrite' into maya/onboarding-middleware 2026-11-25 20:04:48 +03:00
JovannMC 96309573b3 fix(onboarding): navigate properly on previous step 2026-11-25 19:12:16 +03:00
JovannMC 3d13bfc5df fix(onboarding): show solarxr (driver) trackers in middleware
slimetora can use solarxr to connect to slimevr now
2026-11-24 21:24:49 +03:00
JovannMC 3a570585a8 feat(solarxr): add linear acceleration
slimetora already calculates linear acceleration. adds to solarxr and takes precedence over velocity, if available
2026-11-24 17:35:13 +03:00
Sapphire 48255272d2 Put exit code and received signal in Sentry event tags instead of extra 2026-11-23 04:23:52 -05:00
Sapphire e4b0d0a58e Catch exceptions in implementation of ProcessHandle::allProcesses 2026-11-21 20:16:00 -05:00
Sapphire ae9efb1a92 Clean up conditions in TrackerBattery a bit 2026-11-21 17:39:48 -05:00
Sapphire 0368292bf1 Toggle to show battery runtime estimate instead of percentage 2026-11-21 17:37:05 -05:00
Sapphire d55c0ef494 Don't snap skeleton height when switching units
This ends up showing the 'are you sure you want to do this' popup
when switching units, which is annoying. Feel free to revert if this has
bad side effects.
2026-11-21 17:15:00 -05:00
JovannMC baa82a3683 feat(onboarding): unknown trackers in external software page 2026-11-21 23:50:41 +03:00
JovannMC ee58f3d5f4 feat(onboarding): external software ui
adds middleware connection page based off wifi slime page

fixed wifi/middleware title padding on mobile & use DOCS_TROUBLESHOOTING_URL properly
2026-11-20 23:03:29 +03:00
Butterscotch! 7bc6d99f09 AutoBone weighted average bone contribution 2026-11-20 01:35:27 -05:00
Erimel 7cf14188e6 make foot plant and toe snap less agressive 2026-11-19 16:15:57 -05:00
Erimel 292da8d91f upper waist as default 2026-11-19 16:14:11 -05:00
JovannMC a8e4006b34 feat(onboarding): tracker type external software btn 2026-11-19 23:49:18 +03:00
Erimel 594391a647 gui lint 2026-11-18 17:45:06 -05:00
Erimel e719fe38cf spotless 2026-11-18 17:37:23 -05:00
Erimel 9667fd93be Fix Stay Aligned first frame being way too strong 2026-11-18 17:36:19 -05:00
Erimel e2406cacac improve upper leg twist math 2026-11-18 17:25:44 -05:00
Erimel 48b36961f7 Increase max yaw reset smooth time to 1s 2026-11-18 16:31:06 -05:00
Erimel 128d5e58da Skeleton processor reset when yaw reset smoothing finishes 2026-11-18 16:20:11 -05:00
Erimel c71f06cf71 TapDetection -> TrackerAction 2026-11-18 16:04:05 -05:00
Aed 78deb81e21 Tap/Button Reset settings (#1963) 2026-11-18 13:32:52 -05:00
Erimel 768a623cd2 Move Setup Wizard at the bottom of the settings 2026-11-17 23:29:03 -05:00
Erimel 3ea39549ba fix tests 2026-11-17 20:59:47 -05:00
Erimel e2e0a3d87d tune prediction 2026-11-17 20:52:02 -05:00
Erimel 2068b208f8 lower default prediction 2026-11-17 20:19:28 -05:00
Erimel f44baef615 compensate for feet pose mounting going inwards 2026-11-17 20:19:20 -05:00
Erimel 40848cd8a3 bone offset in tracker module 2026-11-17 19:48:24 -05:00
Erimel c9e0479a51 Remove TrackerDataType 2026-11-17 14:49:45 -05:00
Erimel 4e5f0736d9 Constrain preferred rotations 2026-11-16 20:07:50 -05:00
Erimel 4e84ebdfc9 upper leg twist as post processing 2026-11-16 19:59:44 -05:00
Erimel 999c27c36f yawAlign 300ms todo 2026-11-16 19:58:14 -05:00
Erimel 64af814db0 Revert "Add TODO for GIT_COMMIT_HASH"
This reverts commit f2b86ec6fd.
2026-11-16 19:03:00 -05:00
Erimel 0479b162b4 Improve feet scaling in preview 2026-11-16 17:14:43 -05:00
Erimel f2b86ec6fd Add TODO for GIT_COMMIT_HASH 2026-11-16 15:43:42 -05:00
Erimel e4482971b0 Disable stay aligned for ADC_RESISTANCE 2026-11-16 15:43:18 -05:00
Erimel cf55f48e2f reorganize stayaligned ImuTypes 2026-11-16 15:34:11 -05:00
loucass003 caf8435636 Migrate old server configs to rewrite 2026-11-13 23:59:35 +01:00
loucass003 6b65058bb3 Fix multiple trackers on the same part display. add occluded to the assignment conflict stuff 2026-11-13 21:34:34 +01:00
loucass003 4fa3f83f95 Fix crowdin when built for prod 2026-11-13 19:36:26 +01:00
Erimel 4481aea2b3 80% knee interpolation default 2026-11-12 16:33:09 -05:00
Erimel 8c1478d3e4 Fix preffered rotation snapping 2026-11-12 16:07:14 -05:00
Erimel 9942e843ff Fix upper legs twist math 2026-11-12 15:12:01 -05:00
Erimel d0fa419131 improve hip tracker reliability 2026-11-12 15:07:14 -05:00
Erimel 834e5d340e Improve arm IK constraints 2026-11-12 14:04:48 -05:00
Erimel 1a65edb0d0 CI 2026-11-11 18:57:42 -05:00
Erimel b87b1f3e42 Improve arm IK and allow leg positional trackers 2026-11-11 18:47:55 -05:00
Erimel f1578ed3fe improved finger tracking 2026-11-11 16:36:07 -05:00
Erimel 178f40226b Recenter mocap mode 2026-11-11 14:06:58 -05:00
Erimel 7c5d3219c3 Improved constraints and reduced feet sinking 2026-11-10 19:41:48 -05:00
Erimel 1d8a441d01 IK preferred rotation WIP 2026-11-09 20:01:56 -05:00
Erimel c64fcb1f95 Fix floor level calculation 2026-11-09 17:04:30 -05:00
Butterscotch! 7e40b54c1b Fix IK offset constraint alignment 2026-11-07 01:42:22 -05:00
Erimel bcf4e9e027 Better arm FK 2026-11-06 17:11:07 -05:00
Butterscotch! 456e09c1ed Improve arm IK consistency 2026-11-05 22:53:34 -05:00
Sapphire ab82ce59e7 Fix bindings provider 2026-11-05 03:53:02 -05:00
109 changed files with 2385 additions and 955 deletions

No files matched your search

+5 -5
View File
@@ -32,7 +32,7 @@ static void OnYawReset(BridgeTransport& conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::YAW, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
@@ -43,7 +43,7 @@ static void OnFullReset(BridgeTransport& conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::FULL, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
@@ -54,7 +54,7 @@ static void OnMountingCalibration(BridgeTransport& conn) {
flatbuffers::FlatBufferBuilder fbb;
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, 0, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
@@ -67,7 +67,7 @@ static void OnFeetMountingCalibration(BridgeTransport& conn) {
auto bodyParts = fbb.CreateVector(
{ datatypes::BodyPart::LEFT_FOOT, datatypes::BodyPart::RIGHT_FOOT });
auto resetReq = rpc::CreateResetRequest(fbb, rpc::ResetType::MOUNTING, bodyParts, 0.f);
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::ResetRequest, resetReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
@@ -80,7 +80,7 @@ static void OnToggleTracking(BridgeTransport& conn) {
shouldPause = !shouldPause;
auto toggleReq = rpc::CreateSetPauseTrackingRequest(fbb, shouldPause);
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, 0, 0, rpc::RpcMessage::SetPauseTrackingRequest, toggleReq.Union());
auto msgHeader = rpc::CreateRpcMessageHeader(fbb, flatbuffers::nullopt, flatbuffers::nullopt, rpc::RpcMessage::SetPauseTrackingRequest, toggleReq.Union());
auto rpcMsgs = fbb.CreateVector({ msgHeader });
auto bundle = CreateMessageBundle(fbb, 0, rpcMsgs);
+18 -19
View File
@@ -326,7 +326,6 @@ tracker-infos-custom_name = Custom Name
tracker-infos-url = Tracker URL
tracker-infos-hardware_identifier = Hardware ID
tracker-infos-mac_address = MAC address
tracker-infos-data_type = Data type
tracker-infos-imu = IMU Sensor
tracker-infos-board_type = Main board
tracker-infos-network_version = Protocol Version
@@ -778,8 +777,8 @@ settings-general-fk_settings-self_localization-title = Mocap mode
settings-general-fk_settings-self_localization-description = Mocap Mode allows the skeleton to roughly track its own position without any positional tracker.
## Gesture control settings (tracker tapping)
settings-general-gesture_control-subtitle = Tap/button based resets
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker or pressing its button. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
settings-general-gesture_control-subtitle = Tracker actions
settings-general-gesture_control-description = Allows resets to be triggered by tapping a tracker repetitively or pressing its button.
# This is a unit: 3 taps, 2 taps, 1 tap
# $amount (Number) - Amount of taps (touches to the tracker's case)
settings-general-gesture_control-taps = { $amount ->
@@ -792,27 +791,19 @@ settings-general-gesture_control-trackers = { $amount ->
[one] 1 tracker
*[other] { $amount } trackers
}
settings-general-gesture_control-column-reset = Reset
settings-general-gesture_control-BUTTON = Button
settings-general-gesture_control-TAP = Tap
settings-general-gesture_control-BOTH = Both
settings-general-gesture_control-column-action = Action
settings-general-gesture_control-column-tracker = Tracker
settings-general-gesture_control-column-method = Method
settings-general-gesture_control-column-taps = Taps
settings-general-gesture_control-column-delay = Delay
settings-general-gesture_control-yawReset-name = Yaw reset
settings-general-gesture_control-fullReset-name = Full reset
settings-general-gesture_control-mountingReset-name = Mounting calibration
settings-general-gesture_control-yawResetEnabled = Enable tap to yaw reset
settings-general-gesture_control-yawResetDelay = Yaw reset delay
settings-general-gesture_control-yawResetTaps = Taps for yaw reset
settings-general-gesture_control-yawResetTracker = Yaw reset tracker
settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
settings-general-gesture_control-fullResetDelay = Full reset delay
settings-general-gesture_control-fullResetTaps = Taps for full reset
settings-general-gesture_control-fullResetTracker = Full reset tracker
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
settings-general-gesture_control-mountingResetTracker = Mounting reset tracker
# The number of trackers that can have higher acceleration before a tap is rejected
settings-general-gesture_control-numberTrackersOverThreshold = Trackers over threshold
settings-general-gesture_control-tapsTrackersOverThreshold = Taps trackers over threshold
settings-general-gesture_control-numberTrackersOverThreshold-description = Increase this value if tap detection is not working. Do not increase it above what is needed to make it work in order to prevent false positives.
## Appearance settings
@@ -1163,6 +1154,7 @@ settings-home-table_columns-desc = Choose which columns are shown in the tracker
settings-home-display_group = Display
settings-home-tracker_display = Tracker info
settings-home-tracker_display-desc = Choose which extra details are shown on trackers
settings-home-tracker_display-battery_runtime_estimate = Battery runtime estimate
settings-home-tracker_display-battery_voltage = Battery voltage
settings-home-tracker_display-numeric_signal = Numeric signal strength
@@ -1197,6 +1189,7 @@ onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 & V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly
onboarding-quiz-slimeset-answer-wifi = Wi-Fi-based Slime
onboarding-quiz-slimeset-answer-dongle = Dongle-based Slime
onboarding-quiz-slimeset-answer-middleware = External software
onboarding-quiz-usage-title = What are you using your trackers for?
onboarding-quiz-usage-description = If you plan on using SlimeVR for multiple purposes, you can change the affected settings later.
@@ -1271,17 +1264,24 @@ onboarding-home-start = Let's get set up!
## Tracker connection setup
onboarding-connect_tracker-title = Let's connect your trackers
onboarding-connect_tracker-description = Enter your Wi-Fi network below and submit once. Every tracker you connect via USB, now or later, will automatically use those credentials.
onboarding-connect_tracker-description-middleware =
Follow the instructions of the external software you are using to connect your trackers.
This page is for connecting non-SlimeVR trackers via external software, which interprets devices to act like SlimeVR trackers.
onboarding-connect_tracker-learn_more = Learn more
onboarding-connect_tracker-issue-serial = I'm having trouble connecting!
onboarding-connect_tracker-issue-middleware = I'm having trouble connecting!
onboarding-connect_tracker-usb = USB Tracker
onboarding-connect_tracker-tracker_mac_name = SlimeVR Tracker ({ $suffix })
onboarding-connect_tracker-tracker_port_name = USB Tracker ({ $port })
onboarding-connect_tracker-network_profile-ignore = I configured my firewall and know what I'm doing
onboarding-connect_tracker-waiting_first_title = Waiting for your first tracker
onboarding-connect_tracker-waiting_first_desc = Plug one in over USB to get started.
onboarding-connect_tracker-waiting_first_desc-middleware = Follow the instructions of the external software you are using to connect your trackers.
onboarding-connect_tracker-scan_results_title = Select network & enter password
onboarding-connect_tracker-scan_results_desc = Enter your Wi-Fi credentials on the left to connect your trackers.
onboarding-connect_tracker-all_caught_up = All caught up. Plug in more any time
onboarding-connect_tracker-all_caught_up-middleware = All caught up. Connect more from the external software any time.
onboarding-connect_tracker-shake_tip = Not sure which tracker is which? Shake a tracker to see it light up in the list.
onboarding-connect_tracker-close = Close
onboarding-connect_tracker-connection_status-serial_init = Connecting to serial device
@@ -1310,7 +1310,6 @@ onboarding-connect_tracker-connected_trackers = { $amount ->
} connected
onboarding-connect_tracker-setting_up = Setting up ({ $amount })
onboarding-connect_tracker-next = I connected all my trackers
## Tracker assignment setup
onboarding-assign_trackers-title = Assign trackers
onboarding-assign_trackers-description = Let's choose which tracker goes where. Click on a location where you want to place a tracker.
@@ -1878,7 +1877,7 @@ tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-open = Go to VRChat OSC Settings
tracking_checklist-ignore = Ignore
preview-mocap_mode_soon = Mocap Mode (Soon™)
preview-recenter_mocap = Recenter Mocap Mode
preview-disable_render = Disable rendering
preview-disabled_render = Rendering disabled
preview-render_mode = Change rendering mode
+8 -1
View File
@@ -192,7 +192,14 @@ function AppRoutes() {
<Route path="dongle" element={<DonglePage />} />
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
<Route path="add-trackers" element={<AddTrackersPage />} />
<Route path="connect-trackers" element={<ConnectTrackersPage />} />
<Route
path="connect-trackers"
element={<ConnectTrackersPage type="slimevr" />}
/>
<Route
path="connect-middleware"
element={<ConnectTrackersPage type="middleware" />}
/>
<Route path="trackers-assign" element={<TrackersAssignPage />} />
<Route path="mounting/choose" element={<MountingChoose />} />
<Route path="mounting/auto" element={<AutomaticMountingPage />} />
+18 -8
View File
@@ -13,6 +13,7 @@ import { Typography } from './commons/Typography';
import { useLocaleConfig } from '@/i18n/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import {
RecenterMocapModeRequestT,
RpcMessage,
SkeletonProportionsRequestT,
SkeletonProportionsResponseT,
@@ -21,11 +22,11 @@ import { Tooltip } from './commons/Tooltip';
import { Vector3 } from 'three';
import { RecordIcon } from './commons/icon/RecordIcon';
import { PauseIcon } from './commons/icon/PauseIcon';
import { HumanIcon } from './commons/icon/HumanIcon';
import { useConfig } from '@/hooks/config';
import { useBHV } from '@/hooks/bvh';
import { usePauseTracking } from '@/hooks/pause-tracking';
import { PlayIcon } from './commons/icon/PlayIcon';
import { RecenterIcon } from './commons/icon/RecenterIcon';
export function PreviewControls({ open }: { open: boolean }) {
const [userHeight, setUserHeight] = useState('');
@@ -117,6 +118,7 @@ export function PreviewControls({ open }: { open: boolean }) {
</Clickable>
</Tooltip>
)}
<Tooltip
content={
<Typography
@@ -137,18 +139,26 @@ export function PreviewControls({ open }: { open: boolean }) {
{paused && <PlayIcon width={25} />}
</Clickable>
</Tooltip>
<Tooltip
content={
<Typography
variant="section-title"
id="preview-mocap_mode_soon"
/>
<Typography variant="section-title" id="preview-recenter_mocap" />
}
preferedDirection="top"
>
<div className="flex justify-center items-center w-10 h-10 rounded-full cursor-not-allowed">
<HumanIcon width={20} />
</div>
<Clickable
className={classNames(
'flex justify-center items-center w-10 h-10 rounded-full hover:bg-background-60 cursor-pointer'
)}
onClick={() =>
sendRPCPacket(
RpcMessage.RecenterMocapModeRequest,
new RecenterMocapModeRequestT()
)
}
>
<RecenterIcon width={24} />
</Clickable>
</Tooltip>
</div>
</div>
@@ -74,14 +74,14 @@ export function PersonFrontIcon({
<circle
className="body-part-circle"
cx="82"
cy="140"
cy="155"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.UPPER_WAIST]}
/>
<circle
className="body-part-circle"
cx="82"
cy="155"
cy="169"
r={CIRCLE_RADIUS}
id={BodyPart[BodyPart.LOWER_WAIST]}
/>
@@ -0,0 +1,12 @@
export function LinkIcon({ size = 24 }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
height={size}
width={size}
>
<path d="M7.95,21q-2.05,0-3.5-1.45T3,16.05q0-1 0.38-1.9t1.08-1.6L7.8,9.23l1.4,1.4L5.85,13.98Q5.43,14.4 5.21,14.94T5,16.05q0,1.22 0.86,2.09T7.95,19q0.58,0 1.13-0.21t0.97-0.64l3.32-3.35l1.43,1.43l-3.35,3.32q-0.7,0.7-1.6,1.07T7.95,21Zm1.98-5.5L8.5,14.08L14.08,8.5L15.5,9.92L9.93,15.5Zm6.27-0.7l-1.4-1.42l3.35-3.33q0.42-0.42 0.63-0.95T18.98,8q0-1.25-0.85-2.13Q17.28,5 16.03,5q-0.58,0-1.11,0.21q-0.54,0.21-0.96,0.64L10.63,9.2L9.2,7.8l3.35-3.35q0.7-0.7 1.6-1.07T16.05,3q2.05,0 3.49,1.45t1.44,3.52q0,0.98-0.36,1.88t-1.06,1.6L16.2,14.8Z" />
</svg>
);
}
@@ -0,0 +1,7 @@
export function RecenterIcon({ width = 24 }: { width?: number }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width={width}>
<path d="M11,23V18.83L9.9,19.9L8.5,18.5L12,15l3.5,3.5l-1.4,1.4L13,18.83V23H11ZM5.5,15.5L4.1,14.1L5.18,13H1V11H5.18L4.1,9.9L5.5,8.5L9,12L5.5,15.5Zm13,0L15,12l3.5-3.5l1.4,1.4L18.83,11H23v2H18.83l1.08,1.1l-1.4,1.4Zm-6.5-2q-0.63,0-1.06-0.44T10.5,12t0.44-1.06T12,10.5t1.06,0.44T13.5,12t-0.44,1.06T12,13.5ZM12,9L8.5,5.5L9.9,4.1L11,5.18V1h2V5.18L14.1,4.1l1.4,1.4L12,9Z" />
</svg>
);
}
@@ -277,26 +277,8 @@ export function HeightSelectionInput({
};
const handleUnitChange = (newUnit: 'meter' | 'foot') => {
if (!headHeight || newUnit === unit) return;
if (newUnit === unit) return;
const fullHeight = headHeight / EYE_HEIGHT_TO_HEIGHT_RATIO;
let snappedHeight;
if (newUnit === 'foot') {
// Snap to nearest inch
const totalInches = Math.round(convert(fullHeight, 'meter').to('inch'));
snappedHeight = convert(totalInches, 'inch').to('meter');
} else {
// Snap to nearest centimeter
const totalCm = Math.round(convert(fullHeight, 'meter').to('cm'));
snappedHeight = convert(totalCm, 'cm').to('meter');
}
const newEyeHeight = round4Digit(
snappedHeight * EYE_HEIGHT_TO_HEIGHT_RATIO
);
setHeadHeight(newEyeHeight);
onUnitChange(newUnit);
};
@@ -3,9 +3,7 @@ import { A } from '@/components/commons/A';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import { LoaderIcon, SlimeState } from '@/components/commons/icon/LoaderIcon';
export const DOCS_TROUBLESHOOTING_URL =
'https://docs.slimevr.dev/common-issues.html';
import { DOCS_TROUBLESHOOTING_URL } from './TrackerList';
export function ErrorDetailModal({
isOpen,
@@ -3,6 +3,9 @@ import classNames from 'classnames';
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
import {
BoardType,
DeviceOrigin,
TrackerStatus,
TrackerProvisioningStatus,
TrackingChecklistPublicNetworksT,
TrackingChecklistStepId,
@@ -16,8 +19,16 @@ import {
} from '@/hooks/wifi-form';
import { useTrackingChecklist } from '@/hooks/tracking-checklist';
import { useBreakpoint } from '@/hooks/breakpoint';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import {
connectedIMUTrackersAtom,
connectedTrackersAtom,
unknownDevicesAtom,
} from '@/store/app-store';
import { A } from '@/components/commons/A';
import {
BUTTERFLY_BOARDS,
SLIME_BOARDS,
} from '@/components/commons/BodyPartIcon';
import { Button } from '@/components/commons/Button';
import { Dropdown } from '@/components/commons/Dropdown';
import { Input } from '@/components/commons/Input';
@@ -32,11 +43,18 @@ import {
} from '@/components/commons/icon/ArrowIcons';
import { MoreSetsConfirm } from '@/components/onboarding/pages/quiz/MoreSetsConfirm';
import {
DOCS_TROUBLESHOOTING_URL,
MIDDLEWARE_DOCS_URL,
mergeTrackerList,
NoSerialLogsModal,
normalizeMac,
TrackerList,
DOCS_TROUBLESHOOTING_URL,
TrackerType,
} from './TrackerList';
import {
PendingTrackerCard,
PendingTrackersDivider,
} from '@/components/tracker/PendingTrackers';
export function FloatingWifiForm({
summary,
@@ -326,6 +344,16 @@ function WifiFormFields({
);
}
function MiddlewareLinks() {
return (
<div className="flex flex-col gap-2">
<ArrowLink to={MIDDLEWARE_DOCS_URL} direction="right" variant="boxed-2">
<Typography id="onboarding-connect_tracker-issue-middleware" />
</ArrowLink>
</div>
);
}
function TroubleshootingLinks({
networkProfileBanner,
}: {
@@ -348,13 +376,153 @@ function TroubleshootingLinks({
);
}
export function ConnectTrackersPage() {
export function ConnectTrackersPage({ type }: { type: TrackerType }) {
return type === 'middleware' ? (
<MiddlewareConnectTrackersPage />
) : (
<SlimeVRConnectTrackersPage />
);
}
function isMiddlewareBoard(boardType?: BoardType | null) {
return (
boardType == null ||
(!SLIME_BOARDS.has(boardType) && !BUTTERFLY_BOARDS.has(boardType))
);
}
function MiddlewareConnectTrackersPage() {
const { applyProgress, state } = useOnboarding();
const { isMobile } = useBreakpoint('mobile');
const connectedTrackers = useAtomValue(connectedTrackersAtom);
const activeTrackers = useMemo(
() =>
connectedTrackers.filter(
({ tracker }) => tracker.status !== TrackerStatus.TIMED_OUT
),
[connectedTrackers]
);
const unknownDevices = useAtomValue(unknownDevicesAtom);
const rows = useMemo(
() =>
mergeTrackerList(
[],
activeTrackers.filter(
({ tracker, device }) =>
tracker.origin === DeviceOrigin.DRIVER ||
(tracker.origin === DeviceOrigin.UDP &&
isMiddlewareBoard(device?.hardwareInfo?.officialBoardType))
)
),
[activeTrackers]
);
const pendingDevices = useMemo(() => {
const liveHardwareIds = new Set(
activeTrackers
.map(({ device }) =>
normalizeMac(device?.hardwareInfo?.hardwareIdentifier)
)
.filter((hardwareId): hardwareId is string => !!hardwareId)
);
return unknownDevices.filter((device) => {
const hardwareId = normalizeMac(device.hardwareId);
return (
isMiddlewareBoard(device.boardType) &&
hardwareId &&
!liveHardwareIds.has(hardwareId)
);
});
}, [activeTrackers, unknownDevices]);
applyProgress(0.4);
return (
<div className="w-full h-full flex flex-col xs:flex-row overflow-hidden min-h-0">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 mobile:pt-0 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="flex flex-col gap-1">
<Typography
variant="mobile-title"
id="onboarding-connect_tracker-title"
/>
<Typography
variant="standard"
whitespace="whitespace-pre-wrap"
id="onboarding-connect_tracker-description-middleware"
/>
</div>
{!isMobile && (
<div className="flex flex-col gap-2">
<TipBox>
<Typography
variant="standard"
color="text-accent-background-10"
id="onboarding-connect_tracker-shake_tip"
/>
</TipBox>
<MiddlewareLinks />
</div>
)}
</div>
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between">
<TrackerList
rows={rows}
isMiddleware
hideEmptyState={pendingDevices.length > 0}
>
{pendingDevices.length > 0 && (
<div className="flex flex-col gap-3">
<PendingTrackersDivider devices={pendingDevices} />
<div className="grid sm:grid-cols-1 md:grid-cols-2 gap-4">
{pendingDevices.map((device) => (
<PendingTrackerCard
key={device.hardwareId as string}
device={device}
/>
))}
</div>
</div>
)}
{isMobile && (
<div className="pt-2 shrink-0">
<MiddlewareLinks />
</div>
)}
</TrackerList>
<div className="flex flex-row justify-between items-center shrink-0 py-4 border-t border-background-60">
<Button
variant="secondary"
state={{ alonePage: state.alonePage }}
to={
state.alonePage
? '/onboarding/add-trackers'
: '/onboarding/quiz/slime-set'
}
id="onboarding-wifi_creds-back-v2"
/>
{state.alonePage ? (
<Button
variant="primary"
to="/"
id="onboarding-connect_tracker-next"
/>
) : (
<MoreSetsConfirm />
)}
</div>
</div>
</div>
);
}
function SlimeVRConnectTrackersPage() {
const { l10n } = useLocalization();
const { visibleSteps, toggleSession } = useTrackingChecklist();
const { applyProgress, state } = useOnboarding();
const connectedIMUTrackers = useAtomValue(connectedIMUTrackersAtom);
const { isMobile } = useBreakpoint('mobile');
const credsForm = useWifiCredsForm();
const scan = useWifiScan();
const session = useWifiProvisioningSession(credsForm.control);
@@ -430,7 +598,9 @@ export function ConnectTrackersPage() {
id="tracking_checklist-NETWORK_PROFILE_PUBLIC-desc"
elems={{
PublicFixLink: (
<A href="https://docs.slimevr.dev/common-issues.html#network-profile-is-currently-set-to-public" />
<A
href={`${DOCS_TROUBLESHOOTING_URL}#network-profile-is-currently-set-to-public`}
/>
),
}}
vars={{
@@ -467,7 +637,7 @@ export function ConnectTrackersPage() {
return (
<>
<div className="w-full h-full flex flex-col xs:flex-row overflow-hidden min-h-0">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="w-full xs:w-[340px] sm:w-[380px] lg:w-[400px] xl:w-[440px] p-5 mobile:pt-0 flex flex-col gap-4 shrink-0 overflow-y-auto border-b xs:border-b-0 xs:border-r border-background-60 justify-between">
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-1">
<Typography
@@ -499,7 +669,7 @@ export function ConnectTrackersPage() {
)}
</div>
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between mobile:pb-14">
<div className="flex-1 flex flex-col gap-4 px-4 pt-4 min-h-0 overflow-hidden justify-between mobile:pb-[76px]">
<div className="flex flex-col gap-4 min-h-0 flex-1">
<TrackerList
rows={rows}
@@ -24,6 +24,9 @@ import { TrackerWifi } from '@/components/tracker/TrackerWifi';
export const DOCS_TROUBLESHOOTING_URL =
'https://docs.slimevr.dev/common-issues.html';
export const MIDDLEWARE_DOCS_URL = 'https://docs.slimevr.dev/tools/index.html';
export type TrackerType = 'slimevr' | 'middleware';
export const trackerStatusLabelMap: Record<TrackerProvisioningStatus, string> =
{
@@ -401,9 +404,11 @@ export function NoSerialLogsModal({
export function StatusBar({
connectedCount,
connectingCount,
isMiddleware,
}: {
connectedCount: number;
connectingCount: number;
isMiddleware?: boolean;
}) {
return (
<div className="hidden sm:flex rounded-lg bg-background-60 p-4 items-center gap-3 shrink-0">
@@ -430,7 +435,7 @@ export function StatusBar({
id={
connectingCount > 0
? 'onboarding-connect_tracker-setting_up'
: 'onboarding-connect_tracker-all_caught_up'
: `onboarding-connect_tracker-all_caught_up${isMiddleware ? '-middleware' : ''}`
}
vars={{ amount: connectingCount }}
/>
@@ -443,20 +448,23 @@ function EmptyTrackerListIllustration({
scanStatus,
hasNetworks = false,
onOpenNoSerialLogsModal,
isMiddleware = false,
}: {
scanStatus: WifiScanStatus;
hasNetworks?: boolean;
onOpenNoSerialLogsModal?: () => void;
isMiddleware?: boolean;
}) {
const isError =
scanStatus === WifiScanStatus.CONNECTION_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND ||
scanStatus === WifiScanStatus.UNSUPPORTED;
!isMiddleware &&
(scanStatus === WifiScanStatus.CONNECTION_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR ||
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND ||
scanStatus === WifiScanStatus.UNSUPPORTED);
const hasScanResults = scanStatus === WifiScanStatus.RESULTS || hasNetworks;
const titleId =
const slimevrTitleId =
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND
? 'onboarding-connect_tracker-connection_status-no_serial_device_found'
: scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR
@@ -468,8 +476,7 @@ function EmptyTrackerListIllustration({
: hasScanResults
? 'onboarding-connect_tracker-scan_results_title'
: 'onboarding-connect_tracker-waiting_first_title';
const descId =
const slimevrDescId =
scanStatus === WifiScanStatus.NO_SERIAL_DEVICE_FOUND
? 'onboarding-wifi_creds-scan_error_no_device'
: scanStatus === WifiScanStatus.NO_SERIAL_LOGS_ERROR
@@ -482,13 +489,17 @@ function EmptyTrackerListIllustration({
? 'onboarding-connect_tracker-scan_results_desc'
: 'onboarding-connect_tracker-waiting_first_desc';
const middlewareTitleId = 'onboarding-connect_tracker-waiting_first_title';
const middlewareDescId =
'onboarding-connect_tracker-waiting_first_desc-middleware';
return (
<EmptyState
className="flex-1 h-full min-h-[220px] !gap-3 my-auto"
slimeState={isError ? SlimeState.SAD : SlimeState.JUMPY}
titleColor={isError ? 'text-status-critical' : undefined}
titleId={titleId}
descriptionId={descId}
titleId={isMiddleware ? middlewareTitleId : slimevrTitleId}
descriptionId={isMiddleware ? middlewareDescId : slimevrDescId}
action={
isError && (
<button
@@ -558,8 +569,7 @@ export function mergeTrackerList(
for (const ct of connectedIMUTrackers) {
if (claimedConnected.has(ct)) continue;
const mac = normalizeMac(ct.device?.hardwareInfo?.hardwareIdentifier);
const key = mac || `connected-${ct.device?.id}`;
const key = `connected-${ct.tracker.trackerId}`;
rows.push({ kind: 'connected', key, tracker: ct });
}
@@ -568,16 +578,20 @@ export function mergeTrackerList(
export function TrackerList({
rows,
scanStatus,
networks,
scanStatus = WifiScanStatus.NONE,
networks = [],
onOpenNoSerialLogsModal,
children,
isMiddleware = false,
hideEmptyState = false,
}: {
rows: TrackerRow[];
scanStatus: WifiScanStatus;
networks: WifiNetworkT[];
onOpenNoSerialLogsModal: () => void;
children: ReactNode;
scanStatus?: WifiScanStatus;
networks?: WifiNetworkT[];
onOpenNoSerialLogsModal?: () => void;
children?: ReactNode;
isMiddleware?: boolean;
hideEmptyState?: boolean;
}) {
const { isMobile } = useBreakpoint('mobile');
const connectedCount = useMemo(
@@ -597,6 +611,7 @@ export function TrackerList({
<StatusBar
connectedCount={connectedCount}
connectingCount={connectingCount}
isMiddleware={isMiddleware}
/>
)}
@@ -623,13 +638,14 @@ export function TrackerList({
/>
)
)
) : (
) : !hideEmptyState ? (
<EmptyTrackerListIllustration
scanStatus={scanStatus}
hasNetworks={networks.length > 0}
onOpenNoSerialLogsModal={onOpenNoSerialLogsModal}
isMiddleware={isMiddleware}
/>
)}
) : null}
{children}
</div>
</div>
@@ -5,17 +5,21 @@ import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { useNavigate } from 'react-router-dom';
import { LinkIcon } from '@/components/commons/icon/LinkIcon';
import { useBreakpoint } from '@/hooks/breakpoint';
export function QuizButton({
name,
active,
icon,
onClick,
textVariant = 'section-title',
}: {
active?: boolean;
name: string;
icon: ReactNode;
onClick: () => void;
textVariant?: 'section-title' | 'standard';
}) {
return (
<Clickable
@@ -23,7 +27,7 @@ export function QuizButton({
pressed={active}
className={classNames(
'flex rounded-lg bg-background-60 hover:bg-background-50 cursor-pointer',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20 text-center',
{
'outline-accent-background-30': active,
'outline-transparent': !active,
@@ -31,12 +35,13 @@ export function QuizButton({
)}
>
{icon}
<Typography id={name} variant="section-title" />
<Typography id={name} variant={textVariant} bold />
</Clickable>
);
}
export function QuizSlimeSetQuestion() {
const { isMobile } = useBreakpoint('mobile');
const { applyProgress, setSlimeSet, slimeSet } = useOnboarding();
const nav = useNavigate();
@@ -49,6 +54,9 @@ export function QuizSlimeSetQuestion() {
case 'dongle-slime':
nav('/onboarding/dongle');
break;
case 'middleware':
nav('/onboarding/connect-middleware');
break;
case 'slime-v1':
case 'wifi-slime':
nav('/onboarding/connect-trackers');
@@ -103,7 +111,7 @@ export function QuizSlimeSetQuestion() {
variant="section-title"
id="onboarding-quiz-slimeset-thirdparty-sets"
/>
<div className="grid grid-cols-2 gap-4">
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,0.45fr)] mobile:grid-cols-3 gap-4">
<QuizButton
onClick={() => next('wifi-slime')}
icon={
@@ -129,6 +137,16 @@ export function QuizSlimeSetQuestion() {
}
name="onboarding-quiz-slimeset-answer-dongle"
/>
<QuizButton
onClick={() => next('middleware')}
textVariant={isMobile ? 'section-title' : 'standard'}
icon={
<div className="fill-background-20">
<LinkIcon size={isMobile ? 50 : 40} />
</div>
}
name="onboarding-quiz-slimeset-answer-middleware"
/>
</div>
</div>
</div>
@@ -174,7 +174,9 @@ export function AssignmentNavFooter({
? '/onboarding/connect-trackers'
: slimeSet && ['butterfly', 'dongle-slime'].includes(slimeSet)
? '/onboarding/dongle'
: '/onboarding/connect-trackers';
: slimeSet === 'middleware'
? '/onboarding/connect-middleware'
: '/onboarding/connect-trackers';
return (
<div className="flex flex-row justify-between items-center">
@@ -84,7 +84,6 @@ export function SettingsSidebar() {
<div className="flex flex-col gap-2">
<Typography variant="section-title" id="settings-sidebar-utils" />
<div className="flex flex-col gap-1">
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
<SettingsLink to="/settings/logs" id="settings-sidebar-logs" />
<SettingsLink
@@ -101,6 +100,7 @@ export function SettingsSidebar() {
to="/settings/advanced"
id="settings-sidebar-advanced"
/>
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
</div>
</div>
</div>
@@ -22,7 +22,7 @@ import {
} from '@/components/settings/SettingRow';
import { FullResetIcon } from '@/components/commons/icon/ResetIcon';
import { settingReset } from '@/components/settings/SettingReset';
import { TapDetectionSettings } from './components/TapDetectionSettings';
import { TrackerActionSettings } from './components/TrackerActionSettings';
import { defineSettingsPage } from '@/components/settings/settings-definitions';
type ResetsSettingsForm = {
@@ -101,8 +101,8 @@ export const resetsSettingsPage = defineSettingsPage({
},
tapThreshold: {
rows: {
numberTrackersOverThreshold: {
title: 'settings-general-gesture_control-numberTrackersOverThreshold',
tapsTrackersOverThreshold: {
title: 'settings-general-gesture_control-tapsTrackersOverThreshold',
description:
'settings-general-gesture_control-numberTrackersOverThreshold-description',
},
@@ -250,7 +250,7 @@ export function ResetsSettings() {
</SettingRow>
</SettingsGroup>
<TapDetectionSettings
<TrackerActionSettings
resets={groups.tapResets}
threshold={groups.tapThreshold}
/>
@@ -267,7 +267,7 @@ export function ResetsSettings() {
name="yawResetSmoothTime"
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.0}
max={0.5}
max={1.0}
step={0.05}
/>
}
@@ -1,4 +1,3 @@
import { useLocalization } from '@fluent/react';
import { useEffect } from 'react';
import { FieldPath, useForm } from 'react-hook-form';
import {
@@ -123,11 +123,14 @@ export function TrackersTableColumnsSettings({
}
const trackerDisplayToggleOrder: (keyof TrackerDisplayConfig)[] = [
'showBatteryRuntimeEstimate',
'showBatteryVoltage',
'showNumericSignal',
];
const trackerDisplayToggleLabel: Record<keyof TrackerDisplayConfig, string> = {
showBatteryRuntimeEstimate:
'settings-home-tracker_display-battery_runtime_estimate',
showBatteryVoltage: 'settings-home-tracker_display-battery_voltage',
showNumericSignal: 'settings-home-tracker_display-numeric_signal',
};
@@ -3,10 +3,12 @@ import { ReactNode, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import {
BodyPart,
ChangeTapDetectionSettingsRequestT,
ChangeTrackerActionSettingsRequestT,
RpcMessage,
TapDetectionSettingsRequestT,
TapDetectionSettingsResponseT,
TrackerActionMethod,
TrackerActionSettingsRequestT,
TrackerActionSettingsResponseT,
TrackerActionSettingsT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useSettingsDefaults } from '@/hooks/settings-defaults';
@@ -40,48 +42,64 @@ import {
SettingsGroupDef,
} from '@/components/settings/settings-definitions';
type TapDetectionForm = {
type TrackerActionForm = {
yawResetEnabled: boolean;
fullResetEnabled: boolean;
mountingResetEnabled: boolean;
yawResetDelay: number;
fullResetDelay: number;
mountingResetDelay: number;
yawResetBodyPart: string;
yawResetMethod: string;
yawResetTaps: number;
yawResetDelay: number;
fullResetEnabled: boolean;
fullResetBodyPart: string;
fullResetMethod: string;
fullResetTaps: number;
fullResetDelay: number;
mountingResetEnabled: boolean;
mountingResetBodyPart: string;
mountingResetMethod: string;
mountingResetTaps: number;
yawResetTracker: string;
fullResetTracker: string;
mountingResetTracker: string;
numberTrackersOverThreshold: number;
mountingResetDelay: number;
tapsTrackersOverThreshold: number;
};
// The server always sends every field, the fallbacks only satisfy the optional types
function toForm(settings: TapDetectionSettingsResponseT): TapDetectionForm {
function toForm(settings: TrackerActionSettingsResponseT): TrackerActionForm {
return {
yawResetEnabled: settings.yawResetEnabled ?? false,
fullResetEnabled: settings.fullResetEnabled ?? false,
mountingResetEnabled: settings.mountingResetEnabled ?? false,
yawResetDelay: settings.yawResetDelay ?? 0,
fullResetDelay: settings.fullResetDelay ?? 0,
mountingResetDelay: settings.mountingResetDelay ?? 0,
yawResetTaps: settings.yawResetTaps ?? 0,
fullResetTaps: settings.fullResetTaps ?? 0,
mountingResetTaps: settings.mountingResetTaps ?? 0,
yawResetTracker: String(settings.yawResetTracker ?? BodyPart.NONE),
fullResetTracker: String(settings.fullResetTracker ?? BodyPart.NONE),
mountingResetTracker: String(
settings.mountingResetTracker ?? BodyPart.NONE
yawResetEnabled: settings.yawResetAction?.enabled ?? false,
yawResetBodyPart: String(
settings.yawResetAction?.bodyPart ?? BodyPart.NONE
),
numberTrackersOverThreshold: settings.numberTrackersOverThreshold ?? 0,
yawResetMethod: String(
settings.yawResetAction?.method ?? TrackerActionMethod.TAP
),
yawResetTaps: settings.yawResetAction?.taps ?? 2,
yawResetDelay: settings.yawResetAction?.delay ?? 0,
fullResetEnabled: settings.fullResetAction?.enabled ?? false,
fullResetBodyPart: String(
settings.fullResetAction?.bodyPart ?? BodyPart.NONE
),
fullResetMethod: String(
settings.fullResetAction?.method ?? TrackerActionMethod.TAP
),
fullResetTaps: settings.fullResetAction?.taps ?? 2,
fullResetDelay: settings.fullResetAction?.delay ?? 0,
mountingResetEnabled: settings.mountingResetAction?.enabled ?? false,
mountingResetBodyPart: String(
settings.mountingResetAction?.bodyPart ?? BodyPart.NONE
),
mountingResetMethod: String(
settings.mountingResetAction?.method ?? TrackerActionMethod.TAP
),
mountingResetTaps: settings.mountingResetAction?.taps ?? 2,
mountingResetDelay: settings.mountingResetAction?.delay ?? 0,
tapsTrackersOverThreshold: settings.tapsTrackersOverThreshold ?? 0,
};
}
const tapDetectionSettingsAtom = atom<TapDetectionSettingsResponseT | null>(
const trackerActionSettingsAtom = atom<TrackerActionSettingsResponseT | null>(
null
);
const tapDetectionSettingsValueAtom = selectAtom(
tapDetectionSettingsAtom,
const trackerActionSettingsValueAtom = selectAtom(
trackerActionSettingsAtom,
(settings) => settings,
isEqual
);
@@ -111,19 +129,19 @@ function FocusableRow({
);
}
export function TapDetectionSettings({
export function TrackerActionSettings({
resets,
threshold,
}: {
resets: SettingsGroupDef<'yawReset' | 'fullReset' | 'mountingReset'>;
threshold: SettingsGroupDef<'numberTrackersOverThreshold'>;
threshold: SettingsGroupDef<'tapsTrackersOverThreshold'>;
}) {
const setSettings = useSetAtom(tapDetectionSettingsAtom);
const settings = useAtomValue(tapDetectionSettingsValueAtom);
const setSettings = useSetAtom(trackerActionSettingsAtom);
const settings = useAtomValue(trackerActionSettingsValueAtom);
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
const defaults = useSettingsDefaults().tapDetection;
const defaults = useSettingsDefaults().trackerAction;
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
@@ -140,31 +158,49 @@ export function TapDetectionSettings({
label: l10n.getString(`body_part-${BodyPart[value]}`),
}));
const TrackerActionMethods: { value: string; label: string }[] =
Object.values(TrackerActionMethod)
.filter((v): v is TrackerActionMethod => typeof v === 'number')
.map((value) => ({
value: String(value),
label: l10n.getString(
`settings-general-gesture_control-${TrackerActionMethod[value]}`
),
}));
const { control, watch, handleSubmit, reset, setValue } =
useForm<TapDetectionForm>({
useForm<TrackerActionForm>({
defaultValues: toForm(defaults),
mode: 'onChange',
reValidateMode: 'onChange',
});
const onSubmit = (values: TapDetectionForm) => {
const settingsReq = new ChangeTapDetectionSettingsRequestT();
settingsReq.fullResetDelay = values.fullResetDelay;
settingsReq.fullResetEnabled = values.fullResetEnabled;
settingsReq.fullResetTaps = values.fullResetTaps;
settingsReq.yawResetDelay = values.yawResetDelay;
settingsReq.yawResetEnabled = values.yawResetEnabled;
settingsReq.yawResetTaps = values.yawResetTaps;
settingsReq.yawResetTracker = Number(values.yawResetTracker);
settingsReq.mountingResetTracker = Number(values.mountingResetTracker);
settingsReq.fullResetTracker = Number(values.fullResetTracker);
settingsReq.mountingResetEnabled = values.mountingResetEnabled;
settingsReq.mountingResetDelay = values.mountingResetDelay;
settingsReq.mountingResetTaps = values.mountingResetTaps;
settingsReq.numberTrackersOverThreshold =
values.numberTrackersOverThreshold;
const onSubmit = (values: TrackerActionForm) => {
const settingsReq = new ChangeTrackerActionSettingsRequestT();
settingsReq.yawResetAction = new TrackerActionSettingsT(
values.yawResetEnabled,
values.yawResetDelay,
Number(values.yawResetBodyPart),
Number(values.yawResetMethod),
values.yawResetTaps
);
settingsReq.fullResetAction = new TrackerActionSettingsT(
values.fullResetEnabled,
values.fullResetDelay,
Number(values.fullResetBodyPart),
Number(values.fullResetMethod),
values.fullResetTaps
);
settingsReq.mountingResetAction = new TrackerActionSettingsT(
values.mountingResetEnabled,
values.mountingResetDelay,
Number(values.mountingResetBodyPart),
Number(values.mountingResetMethod),
values.mountingResetTaps
);
settingsReq.tapsTrackersOverThreshold = values.tapsTrackersOverThreshold;
sendRPCPacket(RpcMessage.ChangeTapDetectionSettingsRequest, settingsReq);
sendRPCPacket(RpcMessage.ChangeTrackerActionSettingsRequest, settingsReq);
};
useEffect(() => {
@@ -176,8 +212,8 @@ export function TapDetectionSettings({
useConnectedEffect(() => {
sendRPCPacket(
RpcMessage.TapDetectionSettingsRequest,
new TapDetectionSettingsRequestT()
RpcMessage.TrackerActionSettingsRequest,
new TrackerActionSettingsRequestT()
);
}, []);
@@ -187,27 +223,33 @@ export function TapDetectionSettings({
}, [settings]);
useRPCPacket(
RpcMessage.TapDetectionSettingsResponse,
(settings: TapDetectionSettingsResponseT) => {
RpcMessage.TrackerActionSettingsResponse,
(settings: TrackerActionSettingsResponseT) => {
setSettings(settings);
}
);
const resetThreshold = settingReset<
TapDetectionForm,
'numberTrackersOverThreshold'
TrackerActionForm,
'tapsTrackersOverThreshold'
>(
defaults.numberTrackersOverThreshold ?? undefined,
watch('numberTrackersOverThreshold'),
defaults.tapsTrackersOverThreshold ?? undefined,
watch('tapsTrackersOverThreshold'),
(next) => {
setValue('numberTrackersOverThreshold', next);
setValue('tapsTrackersOverThreshold', next);
handleSubmit(onSubmit)();
}
);
const defaultForm = toForm(defaults);
const resetKindFields = (id: (typeof resetKinds)[number]['id']) =>
[`${id}Enabled`, `${id}Tracker`, `${id}Taps`, `${id}Delay`] as const;
[
`${id}Enabled`,
`${id}BodyPart`,
`${id}Method`,
`${id}Taps`,
`${id}Delay`,
] as const;
const kindReset = (id: (typeof resetKinds)[number]['id']) => {
const fields = resetKindFields(id);
return {
@@ -224,16 +266,19 @@ export function TapDetectionSettings({
id: 'yawReset',
enabled: watch('yawResetEnabled'),
icon: <YawResetIcon width={20} />,
method: watch('yawResetMethod'),
},
{
id: 'fullReset',
enabled: watch('fullResetEnabled'),
icon: <FullResetIcon width={20} />,
method: watch('fullResetMethod'),
},
{
id: 'mountingReset',
enabled: watch('mountingResetEnabled'),
icon: <MountingResetIcon width={20} />,
method: watch('mountingResetMethod'),
},
] as const;
@@ -245,7 +290,7 @@ export function TapDetectionSettings({
);
const mobileCaption = (id: string) => (
<div className="md:hidden">
<div className="lg:hidden">
<Typography bold id={`settings-general-gesture_control-column-${id}`} />
</div>
);
@@ -259,27 +304,28 @@ export function TapDetectionSettings({
<Typography id="settings-general-gesture_control-description" />
</div>
<div className="rounded-2xl bg-background-80 overflow-hidden">
<table className="w-full text-left border-collapse block md:table">
<thead className="hidden md:table-header-group">
<table className="w-full text-left border-collapse block lg:table">
<thead className="hidden lg:table-header-group">
<tr className="border-b border-background-60 uppercase">
<th className="py-3 pl-4 pr-2 w-0" />
<th className="py-3 pr-4 w-64 whitespace-nowrap">
{column('reset')}
{column('action')}
</th>
<th className="py-3 px-4">{column('tracker')}</th>
<th className="py-3 px-4">{column('method')}</th>
<th className="py-3 px-4 w-56">{column('taps')}</th>
<th className="py-3 pl-4 pr-4 w-56">{column('delay')}</th>
</tr>
</thead>
<tbody className="divide-y divide-background-60 block md:table-row-group">
{resetKinds.map(({ id, enabled, icon }) => (
<tbody className="divide-y divide-background-60 block lg:table-row-group">
{resetKinds.map(({ id, enabled, icon, method }) => (
<FocusableRow
key={id}
setting={resets.rows[id]}
className="grid grid-cols-[1.75rem_minmax(0,1fr)_minmax(0,1fr)] md:table-row gap-x-2 gap-y-3 md:gap-0 items-center pl-1 pr-3 py-3 xs:pl-2 xs:pr-4 xs:py-4 md:p-0"
className="grid grid-cols-[1.75rem_minmax(0,1fr)_minmax(0,1fr)] lg:table-row gap-x-2 gap-y-3 lg:gap-0 items-center pl-1 pr-3 py-3 xs:pl-2 xs:pr-4 xs:py-4 lg:p-0"
>
<td className="contents md:table-cell md:py-3 md:pl-4 md:pr-2 align-middle">
<div className="contents md:flex md:items-center md:gap-2">
<td className="contents lg:table-cell lg:py-3 lg:pl-4 lg:pr-2 align-middle">
<div className="contents lg:flex lg:items-center lg:gap-2">
<div className="col-start-1 row-start-1 flex justify-center">
<SettingResetButton {...kindReset(id)} />
</div>
@@ -293,7 +339,7 @@ export function TapDetectionSettings({
</div>
</div>
</td>
<td className="col-start-2 col-span-2 row-start-1 min-w-0 pr-12 block md:table-cell md:py-3 md:pr-4 align-middle">
<td className="col-start-2 col-span-2 row-start-1 min-w-0 pr-12 block lg:table-cell lg:py-3 lg:pr-2 align-middle">
<label
htmlFor={`tap-${id}`}
className="flex items-center gap-2.5 cursor-pointer whitespace-nowrap"
@@ -308,7 +354,7 @@ export function TapDetectionSettings({
/>
</label>
</td>
<td className="col-start-2 col-span-2 row-start-2 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-2 smol:col-start-2 smol:col-span-1 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
@@ -321,23 +367,45 @@ export function TapDetectionSettings({
display="block"
control={control}
placeholder={''}
name={`${id}Tracker` as keyof TapDetectionForm}
name={`${id}BodyPart` as keyof TrackerActionForm}
items={bodyParts}
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-2 smol:col-span-1 min-w-0 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-2 smol:col-start-3 smol:col-span-1 smol:row-start-2 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
'flex flex-col gap-1.5',
!enabled && 'opacity-50'
)}
>
{mobileCaption('method')}
<Dropdown
display="block"
control={control}
placeholder={''}
name={`${id}Method` as keyof TrackerActionForm}
items={TrackerActionMethods}
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-2 smol:col-span-1 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={
!enabled || Number(method) == TrackerActionMethod.BUTTON
}
className={classNames(
'flex flex-col gap-1.5',
(!enabled ||
Number(method) == TrackerActionMethod.BUTTON) &&
'opacity-50'
)}
>
{mobileCaption('taps')}
<NumberSelector
control={control}
name={`${id}Taps` as keyof TapDetectionForm}
name={`${id}Taps` as keyof TrackerActionForm}
valueLabelFormat={(value) =>
l10n.getString(
'settings-general-gesture_control-taps',
@@ -350,7 +418,7 @@ export function TapDetectionSettings({
/>
</fieldset>
</td>
<td className="col-start-2 col-span-2 row-start-4 smol:col-start-3 smol:col-span-1 smol:row-start-3 min-w-0 block md:table-cell md:py-3 md:px-4 align-middle">
<td className="col-start-2 col-span-2 row-start-3 smol:col-start-3 smol:col-span-1 smol:row-start-3 min-w-0 block lg:table-cell lg:py-3 lg:px-2 align-middle">
<fieldset
disabled={!enabled}
className={classNames(
@@ -361,7 +429,7 @@ export function TapDetectionSettings({
{mobileCaption('delay')}
<NumberSelector
control={control}
name={`${id}Delay` as keyof TapDetectionForm}
name={`${id}Delay` as keyof TrackerActionForm}
valueLabelFormat={(value) => secondsFormat.format(value)}
min={0.2}
max={3.0}
@@ -377,13 +445,13 @@ export function TapDetectionSettings({
<SettingsGroup group={threshold}>
<SettingRow
setting={threshold.rows.numberTrackersOverThreshold}
setting={threshold.rows.tapsTrackersOverThreshold}
controlWidth="wide"
{...resetThreshold}
control={
<NumberSelector
control={control}
name="numberTrackersOverThreshold"
name="tapsTrackersOverThreshold"
valueLabelFormat={(value) =>
l10n.getString('settings-general-gesture_control-trackers', {
amount: Math.round(value),
@@ -33,14 +33,17 @@ export function TrackerBattery({
});
const charging = (voltage || 0) > 4.3;
const debug = config?.debug;
const showRuntime =
config?.trackerDisplay?.showBatteryRuntimeEstimate &&
runtime != null &&
runtime > 0;
const showVoltage = voltage && config?.trackerDisplay?.showBatteryVoltage;
const pct = value > 2 ? 0 : Math.min(Math.max(value, 0), 1);
return (
<Tooltip
disabled={charging || !runtime || debug}
disabled={charging || !showRuntime}
preferedDirection="left"
content={<Typography>{percentFormatter.format(pct)}</Typography>}
>
@@ -50,7 +53,7 @@ export function TrackerBattery({
</div>
{((!charging || showVoltage) && (
<div className="w-15">
{!charging && runtime != null && runtime > 0 && (
{!charging && showRuntime && (
<Typography color={textColor}>
{(runtime / BigInt(3600000000)).toString() +
'h ' +
@@ -61,7 +64,7 @@ export function TrackerBattery({
'min'}
</Typography>
)}
{!charging && (!runtime || debug) && (
{!charging && !showRuntime && (
<Typography color={textColor}>
{percentFormatter.format(pct)}
</Typography>
@@ -14,7 +14,6 @@ import {
MagnetometerStatus,
MountingMethod,
RpcMessage,
TrackerDataType,
} from 'solarxr-protocol';
import { useDebouncedEffect } from '@/hooks/timeout';
import { useTrackerFromId } from '@/hooks/tracker';
@@ -362,14 +361,6 @@ export function TrackerSettingsPage() {
<Typography id="tracker-infos-mac_address" />
<Typography>{macAddress || '--'}</Typography>
</div>
<div className="flex justify-between">
<Typography>
{l10n.getString('tracker-infos-data_type')}
</Typography>
<Typography>
{TrackerDataType[tracker?.tracker.info?.dataType ?? 0]}
</Typography>
</div>
<div className="flex justify-between">
<Typography>{l10n.getString('tracker-infos-imu')}</Typography>
<Typography>
@@ -48,6 +48,7 @@ import { NavLink, useNavigate } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
import { openUrl } from '@/hooks/crossplatform';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { DOCS_TROUBLESHOOTING_URL } from '@/components/onboarding/pages/connect-trackers/TrackerList';
function Step({
step: { status, id, optional, firstRequired },
@@ -345,7 +346,7 @@ const stepContentLookup: Record<
PublicFixLink: (
<A
className="text-background-20"
href="https://docs.slimevr.dev/common-issues.html#network-profile-is-currently-set-to-public"
href={`${DOCS_TROUBLESHOOTING_URL}#network-profile-is-currently-set-to-public`}
/>
),
}}
+2
View File
@@ -69,11 +69,13 @@ export const trackersTableColumnOrder = [
export type TrackersTableOptionalColumn = (typeof trackersTableColumnOrder)[number];
export interface TrackerDisplayConfig {
showBatteryRuntimeEstimate: boolean;
showBatteryVoltage: boolean;
showNumericSignal: boolean;
}
export const defaultTrackerDisplay: TrackerDisplayConfig = {
showBatteryRuntimeEstimate: true,
showBatteryVoltage: false,
showNumericSignal: false,
};
+1 -1
View File
@@ -59,7 +59,7 @@ export type OnboardingContext = ReturnType<typeof useProvideOnboarding>;
export function useProvideOnboarding() {
const { setConfig } = useConfig();
const [slimeSet, setSlimeSet] = useState<
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime'
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime' | 'middleware'
>();
const [usage, setUsage] = useState<'vr-gaming' | 'mocap' | 'vtubing'>();
const [vrcOsc, setVrcOSC] = useState<boolean>();
+8 -8
View File
@@ -5,8 +5,8 @@ import {
QuatT,
ResetTrackerAssignmentsT,
RpcMessage,
TapDetectionSetupModeRequestT,
TapDetectionSetupNotificationT,
TrackerActionSetupModeRequestT,
TrackerActionSetupNotificationT,
} from 'solarxr-protocol';
import { useChokerWarning } from './choker-warning';
import { useWebsocketAPI } from './websocket-api';
@@ -59,14 +59,14 @@ export function useTrackerAssignment(mode: AssignmentMode) {
useConnectedEffect(() => {
sendRPCPacket(
RpcMessage.TapDetectionSetupModeRequest,
new TapDetectionSetupModeRequestT(true)
RpcMessage.TrackerActionSetupModeRequest,
new TrackerActionSetupModeRequestT(true)
);
return () => {
sendRPCPacket(
RpcMessage.TapDetectionSetupModeRequest,
new TapDetectionSetupModeRequestT(false)
RpcMessage.TrackerActionSetupModeRequest,
new TrackerActionSetupModeRequestT(false)
);
};
}, []);
@@ -150,8 +150,8 @@ export function useTrackerAssignment(mode: AssignmentMode) {
};
useRPCPacket(
RpcMessage.TapDetectionSetupNotification,
(tapSetup: TapDetectionSetupNotificationT) => {
RpcMessage.TrackerActionSetupNotification,
(tapSetup: TrackerActionSetupNotificationT) => {
if (armedPart === BodyPart.NONE || !tapSetup.trackerId) return;
handleDropTracker(tapSetup.trackerId, armedPart);
playTapSetupSound(config?.feedbackSoundVolume);
+7 -7
View File
@@ -75,7 +75,7 @@ const ASSIGNABLE_PARTS = new Set(ALL_ASSIGNABLE_PARTS);
type SetupRegionName =
| 'legs'
| 'chest'
| 'upperChest'
| 'hip'
| 'feet'
| 'upperArms'
@@ -96,12 +96,12 @@ const SETUP_REGIONS: {
needs: SetupRegionName[];
}[] = [
{ id: 'legs', parts: [...LEGS_PARTS], needs: [] },
{ id: 'chest', parts: [BodyPart.UPPER_CHEST], needs: [] },
{ id: 'hip', parts: [BodyPart.HIP], needs: ['chest'] },
{ id: 'upperChest', parts: [BodyPart.UPPER_CHEST], needs: [] },
{ id: 'hip', parts: [BodyPart.HIP], needs: ['upperChest'] },
// one spine point at a time, each halving the largest remaining gap
{ id: 'lowerWaist', parts: [BodyPart.LOWER_WAIST], needs: ['hip'] },
{ id: 'lowerChest', parts: [BodyPart.LOWER_CHEST], needs: ['lowerWaist'] },
{ id: 'upperWaist', parts: [BodyPart.UPPER_WAIST], needs: ['lowerChest'] },
{ id: 'upperWaist', parts: [BodyPart.UPPER_WAIST], needs: ['hip'] },
{ id: 'lowerChest', parts: [BodyPart.LOWER_CHEST], needs: ['upperWaist'] },
{ id: 'lowerWaist', parts: [BodyPart.LOWER_WAIST], needs: ['lowerChest'] },
{
id: 'feet',
parts: [BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT],
@@ -110,7 +110,7 @@ const SETUP_REGIONS: {
{
id: 'upperArms',
parts: [BodyPart.LEFT_UPPER_ARM, BodyPart.RIGHT_UPPER_ARM],
needs: ['legs', 'chest'],
needs: ['legs', 'upperChest'],
},
{
id: 'lowerArms',
+3
View File
@@ -43,6 +43,7 @@ export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string>
'tracking_checklist-STANDABLE_INSTALLED',
[TrackingChecklistStepId.VRCHAT_OSC_TRACKING_DISABLED]:
'tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED',
[TrackingChecklistStepId.FIRMWARE_UPDATE]: 'tracking_checklist-FIRMWARE_UPDATE',
};
export const trackingchecklistIdtoSettingsDescription: Record<
@@ -77,6 +78,8 @@ export const trackingchecklistIdtoSettingsDescription: Record<
'tracking_checklist-STANDABLE_INSTALLED-settings_desc',
[TrackingChecklistStepId.VRCHAT_OSC_TRACKING_DISABLED]:
'tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-settings_desc',
[TrackingChecklistStepId.FIRMWARE_UPDATE]:
'tracking_checklist-FIRMWARE_UPDATE-settings_desc',
};
export type TrackingChecklistStepStatus =
+17 -31
View File
@@ -16,7 +16,6 @@ import {
ResetsSettingsResponseT,
SkeletonSettingsResponseT,
StayAlignedSettingsResponseT,
TapDetectionSettingsResponseT,
TimeoutSettingsResponseT,
TrackerDataT,
TrackerStatus,
@@ -24,6 +23,7 @@ import {
VMCOSCSettingsResponseT,
VRCOSCSettingsResponseT,
VRMSettingsResponseT,
TrackerActionSettingsResponseT,
} from 'solarxr-protocol';
import { selectAtom } from 'jotai/utils';
import { isEqual } from '@react-hookz/deep-equal';
@@ -48,7 +48,7 @@ export type SettingsDefaults = {
skeleton: SkeletonSettingsResponseT;
resets: ResetsSettingsResponseT;
stayAligned: StayAlignedSettingsResponseT;
tapDetection: TapDetectionSettingsResponseT;
trackerAction: TrackerActionSettingsResponseT;
timeout: TimeoutSettingsResponseT;
hid: HIDSettingsResponseT;
driver: DriverSettingsResponseT;
@@ -233,39 +233,25 @@ export function groupTrackersByDevice(
return order.map((key) => byDevice.get(key)!);
}
const PRESENT_STATUSES = new Set([
TrackerStatus.OK,
TrackerStatus.SLEEPING,
TrackerStatus.TIMED_OUT,
TrackerStatus.OCCLUDED,
]);
function isPresent(status: TrackerStatus) {
return PRESENT_STATUSES.has(status);
}
export function groupTrackerByBodyPart(
trackers: FlatDeviceTracker[]
): Partial<Record<BodyPart, FlatDeviceTracker>> {
const byPart: Partial<Record<BodyPart, FlatDeviceTracker>> = {};
trackers
.toSorted((a, b) => {
if (
a.tracker.info &&
b.tracker.info &&
a.tracker.info.bodyPart == b.tracker.info.bodyPart
) {
// Make sure the active tracker is further in the array, so that it takes precedence in the byPart record.
// This shouldn't happen if the body parts are equal, but handle it just in case.
if (a.tracker.status == b.tracker.status) return 0;
if (
a.tracker.status !== TrackerStatus.OK &&
a.tracker.status !== TrackerStatus.SLEEPING &&
a.tracker.status !== TrackerStatus.TIMED_OUT
) {
// put a before b
return -1;
} else {
// put b before a
return 1;
}
}
return a.tracker.trackerId - b.tracker.trackerId;
})
.forEach((td) => {
byPart[td.tracker.info?.bodyPart ?? BodyPart.NONE] = td;
});
trackers.forEach((td) => {
const part = td.tracker.info?.bodyPart ?? BodyPart.NONE;
if (!byPart[part] || isPresent(td.tracker.status)) byPart[part] = td;
});
return byPart;
}
+13 -8
View File
@@ -197,13 +197,13 @@ const fingerRight = (file: string) =>
// shows. The length ratio keeps the tip on the bone's tail despite the tuck.
const TOE_TUCK = 0.5;
const toeScale = (width: number, depth: number) =>
spanBone({ width, depth, length: 1 + TOE_TUCK, girthFrom: 'foot' });
const toeOffset = inBoneLengths({ length: TOE_TUCK, depth: 0.11 });
const toe = (file: string, scale = toeScale(1.3, 1.0)) =>
spanBone({ width, depth, length: 1 + TOE_TUCK, girthFrom: 'height' });
const toeOffset = inBoneLengths({ length: TOE_TUCK, depth: -0.02 });
const toe = (file: string, scale = toeScale(1, 1.0)) =>
part(model(file, { scale, offset: toeOffset }));
const toeRight = (file: string, scale = toeScale(1.3, 1.0)) =>
const toeRight = (file: string, scale = toeScale(1, 1.0)) =>
part(model(file, { scale: otherSide(scale), offset: toeOffset }));
const bigToeScale = toeScale(1.3, 1.15);
const bigToeScale = toeScale(1, 1.1);
const HEAD_SIZE_EXPONENT = 0.25;
const headSize = ({ bodyScale }: SkeletonProportions) =>
@@ -245,9 +245,14 @@ const lowerArmScale = spanBone({
const upperLegScale = spanBone({ girthFrom: 'hips', length: 1.0 });
const lowerLegScale = spanBone({ girthFrom: 'hips', length: 0.78 });
const footScale: ShapeScale = {
compute: ({ boneLength }) => {
const ratio = boneLength / RIG_FOOT_LENGTH;
return { width: 0.91 * ratio, length: 1.12 * ratio, depth: 1.195 };
compute: ({ boneLength, proportions }) => {
const heightRatio = proportions.bodyScale;
const footRatio = boneLength / RIG_FOOT_LENGTH;
return {
width: 0.91 * footRatio,
length: 1.12 * footRatio,
depth: 1.1 * heightRatio,
};
},
};
// Forward follows foot length; the drop from the ankle to the sole doesn't.
+35 -2
View File
@@ -1,5 +1,5 @@
import { BrowserWindow } from 'electron';
import { isAppUrl, openExternalUrl } from './urls';
import { BrowserWindow, session } from 'electron';
import { getAppUrl, isAppUrl, openExternalUrl } from './urls';
import { IPC_CHANNELS } from '@slimevr/gui-shared';
const SESSION_SET_URL = /^https:\/\/[\w-]+\.crowdin\.com\/backend\/jwt\/set\b/;
@@ -27,6 +27,39 @@ const HIDE_WAIT_JS = `document.querySelectorAll('.slimevr-crowdin-wait').forEach
let crowdinPopup: BrowserWindow | null = null;
const FAKE_ORIGIN = 'http://localhost';
const JIPT_API = /^https:\/\/[\w-]+\.crowdin\.com\/api\/v2\/jipt\//;
// The jipt API rejects any non-http(s) origin with "Invalid origin", and the
// prod build runs on app://. we make it sees http://localhost instead
export function rewriteCrowdinOrigin() {
const appUrl = new URL(getAppUrl());
const appOrigin = `${appUrl.protocol}//${appUrl.host}`;
if (appOrigin.startsWith('http')) return;
session.defaultSession.webRequest.onBeforeRequest(
{ urls: ['https://*.crowdin.com/*'] },
(details, callback) => {
const url = new URL(details.url);
if (details.resourceType === 'subFrame') {
callback(replaceParam(url, 'jipt', FAKE_ORIGIN, appOrigin));
return;
}
if (JIPT_API.test(details.url)) {
callback(replaceParam(url, 'origin', appOrigin, FAKE_ORIGIN));
return;
}
callback({});
}
);
}
function replaceParam(url: URL, param: string, from: string, to: string) {
if (url.searchParams.get(param) !== from) return {};
url.searchParams.set(param, to);
return { redirectURL: url.toString() };
}
export function openCrowdinPopup(parent: BrowserWindow, url: string) {
if (crowdinPopup) {
crowdinPopup.loadURL(url);
+3 -1
View File
@@ -37,7 +37,7 @@ import { discordPresence } from './presence';
import { options } from './cli';
import { mkdir, writeFile } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
import { openCrowdinPopup } from './crowdin';
import { openCrowdinPopup, rewriteCrowdinOrigin } from './crowdin';
import {
applyErrorReporting,
captureJavaNotFound,
@@ -603,6 +603,8 @@ app.whenReady().then(async () => {
return new Response(response.body, { status: response.status, headers });
});
rewriteCrowdinOrigin();
try {
await createFolders();
} catch (err) {
+12 -5
View File
@@ -178,7 +178,8 @@ export function captureServerExit(
const eventId = Sentry.captureMessage('server_exit_nonzero', {
...serverScope,
level: 'error',
extra: { code, signal, outputTail },
tags: { code, signal },
extra: { outputTail },
});
lastServerFailure = { eventId, code, signal, outputTail };
}
@@ -192,10 +193,16 @@ export function sendCrashReport(kind: CrashReportKind) {
event_id: failure?.eventId,
message: failure ? 'server_exit_nonzero' : `server_${kind}`,
level: 'error',
tags: serverScope.tags,
extra: failure
? { code: failure.code, signal: failure.signal, outputTail: failure.outputTail }
: { outputTail: serverOutputTail() },
tags: failure
? {
...serverScope.tags,
code: failure.code,
signal: failure.signal,
}
: serverScope.tags,
extra: {
outputTail: failure?.outputTail ?? serverOutputTail(),
},
});
});
return true;
@@ -47,7 +47,7 @@ import dev.slimevr.sentry.registerErrorReportSnapshots
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpServer
import dev.slimevr.util.appCoroutineExceptionHandler
@@ -191,7 +191,7 @@ class ForegroundService : Service() {
)
val stepMountingManager = StepMountingManager.create(ctx = phase1, scope = scope)
val resetsManager = ResetsManager.create(ctx = phase1, skeleton = skeleton, vrcOscManager = vrcOscManager, stepMountingManager = stepMountingManager, scope = scope)
val tapDetectionManager = TapDetectionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
val trackerActionManager = TrackerActionManager.create(ctx = phase1, resetsManager = resetsManager, scope = scope)
val keybindManager = KeybindManager.create(scope = scope)
val serverInfos = ServerInfos(::resolveAndroidLocalIpAddress)
@@ -221,7 +221,7 @@ class ForegroundService : Service() {
vmcManager = vmcManager,
vrcOscManager = vrcOscManager,
resetsManager = resetsManager,
tapDetectionManager = tapDetectionManager,
trackerActionManager = trackerActionManager,
stepMountingManager = stepMountingManager,
logSources = listOf(serverLogSource),
)
+1
View File
@@ -52,6 +52,7 @@ kotlin {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.10.0")
implementation("it.krzeminski:snakeyaml-engine-kmp:3.2.1")
}
}
val commonTest = getByName("commonTest") {
@@ -15,7 +15,7 @@ import dev.slimevr.serial.SerialServer
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpServer
import dev.slimevr.vmc.VMCManager
@@ -53,7 +53,7 @@ interface AppContextProvider : Phase1ContextProvider {
val vmcManager: VMCManager
val vrcOscManager: VRCOSCManager
val resetsManager: ResetsManager
val tapDetectionManager: TapDetectionManager
val trackerActionManager: TrackerActionManager
val stepMountingManager: StepMountingManager
val logSources: List<LogSourceProvider>
fun startObserving()
@@ -81,7 +81,7 @@ class AppContext(
override val vmcManager: VMCManager,
override val vrcOscManager: VRCOSCManager,
override val resetsManager: ResetsManager,
override val tapDetectionManager: TapDetectionManager,
override val trackerActionManager: TrackerActionManager,
override val stepMountingManager: StepMountingManager,
override val logSources: List<LogSourceProvider>,
) : AppContextProvider {
@@ -99,7 +99,7 @@ class AppContext(
vmcManager.startObserving(this)
vrcOscManager.startObserving(this)
resetsManager.startObserving()
tapDetectionManager.startObserving()
trackerActionManager.startObserving()
stepMountingManager.startObserving()
}
@@ -0,0 +1,29 @@
package dev.slimevr.autobone
class WeightedAverage {
var value: Float = 0f
private set
var weight: Float = 0f
private set
fun average() = if (weight > 0f) {
value / weight
} else {
0f
}
fun addValue(value: Float, weight: Float) {
this.value += value * weight
this.weight += weight
}
fun subtractValue(value: Float, weight: Float) {
this.value -= value * weight
this.weight -= weight
}
fun reset() {
value = 0f
weight = 0f
}
}
@@ -0,0 +1,106 @@
package dev.slimevr.autobone
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.bodyPartMap
import dev.slimevr.skeleton.mapValues
import dev.slimevr.util.Side
import dev.slimevr.util.side
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
val BODY_PARTS_TO_ADJUST = arrayOf(
BodyPart.NECK,
BodyPart.UPPER_CHEST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
BodyPart.LEFT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG,
BodyPart.RIGHT_LOWER_LEG,
)
// TODO This should probably be every bone excluding arms, feet, and toes?
val CONTRIBUTING_BODY_PARTS = BODY_PARTS_TO_ADJUST.plus(
arrayOf(
BodyPart.HEAD,
),
)
data class TrackerFrame(
val rotation: Quaternion,
val position: Vector3?,
)
typealias AutoBoneRecording = List<TrackerFrame>
// TODO Figure out actually doing the recording
typealias BoneContribution = WeightedAverage
typealias BoneContributions = BodyPartMap<BoneContribution>
fun process(recording: BodyPartMap<AutoBoneRecording>) {
// TODO Actually make skeletons
val skeletonA: ComputedSkeleton = bodyPartMap()
val skeletonB: ComputedSkeleton = bodyPartMap()
val contributions: BoneContributions = bodyPartMap()
val recordingLength = recording.minOf { it.value.size }
for (i in 0 until recordingLength) {
val trackers = recording.mapValues { _, frames -> frames[i] }
// TODO Apply trackers to skeletons A and B somehow
computeContributions(contributions, skeletonA, skeletonB)
// TODO Figure out how to choose adjustment scale
// TODO Test new config to see if it actually reduces error
}
}
fun boneContribution(contribution: BoneContribution, ankleAToB: Vector3, localBoneTailAToB: Vector3) {
val boneToSlideDirectionRatio = ankleAToB.unit().dot(localBoneTailAToB.unit())
// - if bone is too short, + if bone is too long
contribution.addValue(boneToSlideDirectionRatio, localBoneTailAToB.len())
}
fun computeContributions(contributions: BoneContributions, skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
val leftAnkleA = skeletonA[BodyPart.LEFT_LOWER_LEG]?.tailPosition ?: error("Missing left ankle position A")
val leftAnkleB = skeletonB[BodyPart.LEFT_LOWER_LEG]?.tailPosition ?: error("Missing left ankle position B")
val leftAnkleAToB = leftAnkleB - leftAnkleA
val rightAnkleA = skeletonA[BodyPart.RIGHT_LOWER_LEG]?.tailPosition ?: error("Missing right ankle position A")
val rightAnkleB = skeletonB[BodyPart.RIGHT_LOWER_LEG]?.tailPosition ?: error("Missing right ankle position B")
val rightAnkleAToB = rightAnkleB - rightAnkleA
// TODO Consider headset sliding; if HMD consistently aligns with sliding, then
// either height is wrong, or the headset has weird movement
CONTRIBUTING_BODY_PARTS.forEach { bodyPart ->
val boneA = skeletonA[bodyPart] ?: return@forEach
val boneB = skeletonB[bodyPart] ?: return@forEach
val contribution = contributions.getOrPut(bodyPart) { BoneContribution() }
val localBoneTailAToB = boneB.localTailPosition - boneA.localTailPosition
val side = bodyPart.side
// LEFT (or both)
if (side != Side.RIGHT) {
boneContribution(
contribution,
leftAnkleAToB,
localBoneTailAToB,
)
}
// RIGHT (or both)
if (side != Side.LEFT) {
boneContribution(
contribution,
rightAnkleAToB,
localBoneTailAToB,
)
}
}
}
@@ -1,68 +0,0 @@
package dev.slimevr.autobone
import dev.slimevr.skeleton.ComputedSkeleton
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
fun slideContributionWeight(ankleA: Vector3, ankleB: Vector3, localBoneTailA: Vector3, localBoneTailB: Vector3): Float {
val ankleAToB = ankleB - ankleA
val localBoneTailAToB = localBoneTailB - localBoneTailA
val boneToSlideDirectionRatio = ankleAToB.unit().dot(localBoneTailAToB.unit())
// if +, shorten bone, if -, lengthen bone
// sum all contribution weights, divide each bone's weight by the sum, then multiply
// by the slide magnitude in order to find the corresponding bone change
return localBoneTailAToB.len() * boneToSlideDirectionRatio
}
// TODO This is a placeholder
val PLACEHOLDER_BODY_PARTS_TO_ADJUST = arrayOf(
BodyPart.UPPER_CHEST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
// etc.
)
fun step(skeletonA: ComputedSkeleton, skeletonB: ComputedSkeleton) {
// TODO We need to consider both ankles, there are two... We can do contribution per
// ankle
// TODO This is a placeholder
val ankleA = Vector3.ZERO
// TODO This is a placeholder
val ankleB = Vector3.ZERO
// TODO Consider headset sliding; if HMD consistently aligns with sliding, then
// either height is wrong, or the headset has weird movement
val contributions = PLACEHOLDER_BODY_PARTS_TO_ADJUST.map { bodyPart ->
val boneA = skeletonA[bodyPart] ?: return@map 0f
val boneB = skeletonB[bodyPart] ?: return@map 0f
slideContributionWeight(
ankleA,
ankleB,
boneA.localTailPosition,
boneB.localTailPosition,
)
}.filter { it > 0f }
// TODO This is a placeholder
val slideMag = 1f
val contributionSum = contributions.sum()
val perBoneSlide = contributions.map {
(it * slideMag) / contributionSum
}
// TODO This is a placeholder
val config = 1f
val newConfigs = perBoneSlide.map {
config + it
}
// TODO Test new config to see if it actually reduces error? Or do we just
// accept the changes? The contribution scales for each frame and considers
// direction; we should be able to skip checking if it reduces error
}
@@ -2,18 +2,22 @@ package dev.slimevr.config
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.tracker.driverTrackerHardwareId
import dev.slimevr.tracker.hidTrackerHardwareId
import dev.slimevr.tracker.udpTrackerHardwareId
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.CoroutineScope
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.datatypes.BodyPart
private const val DEVICES_CONFIG_VERSION = 1
private const val DEVICES_CONFIG_VERSION = 2
const val DEVICES_CONFIG_PATH = "devices.json"
@Serializable
@@ -88,9 +92,32 @@ class DevicesConfig(
private fun migrateDevicesConfig(json: JsonObject): JsonObject {
val version = json["version"]?.jsonPrimitive?.intOrNull ?: 0
return when {
else -> json
if (version >= DEVICES_CONFIG_VERSION) return json
val migrated = (version + 1..DEVICES_CONFIG_VERSION).fold(json) { current, to -> migrateDevicesConfigTo(to, current) }
return JsonObject(migrated + ("version" to JsonPrimitive(DEVICES_CONFIG_VERSION)))
}
/** Brings a devices config up to version [to] from the one before. */
private fun migrateDevicesConfigTo(to: Int, json: JsonObject): JsonObject = when (to) {
1 -> json
2 -> migrateDevicesConfigV2(json)
else -> error("No devices config migration to version $to")
}
/** Version 1 keyed trackers by their bare hardware id, version 2 prefixes it with the tracker origin. */
private fun migrateDevicesConfigV2(json: JsonObject): JsonObject {
val udpTrackerId = Regex("((?:[0-9A-F]{2}:){5}[0-9A-F]{2}|\\d{1,3}(?:\\.\\d{1,3}){3}):(\\d{1,9})")
val hidTrackerId = Regex("[0-9A-F]{12}|[0-9A-F]{16}")
fun prefixed(id: String): String {
if (id.startsWith("vmc:") || id.startsWith("vrcosc:")) return id
udpTrackerId.matchEntire(id)?.let { return udpTrackerHardwareId(it.groupValues[1], it.groupValues[2].toInt()) }
if (hidTrackerId.matches(id)) return hidTrackerHardwareId(id)
return driverTrackerHardwareId(id)
}
val trackers = json["trackers"] as? JsonObject ?: return json
return JsonObject(json + ("trackers" to JsonObject(trackers.mapKeys { (id, _) -> prefixed(id) })))
}
private fun parseAndMigrateDevicesConfig(raw: String): DevicesConfigState {
@@ -0,0 +1,276 @@
package dev.slimevr.config
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.hidTrackerHardwareId
import dev.slimevr.tracker.udpTrackerHardwareId
import io.github.axisangles.ktmath.Quaternion
import it.krzeminski.snakeyaml.engine.kmp.api.Load
import it.krzeminski.snakeyaml.engine.kmp.api.LoadSettings
import kotlinx.coroutines.delay
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.StayAlignedRelaxedPose
/** Config file of the previous server, in the same folder as the current config. */
const val LEGACY_CONFIG_PATH = "vrconfig.yml"
private const val MIN_LEGACY_CONFIG_VERSION = 14
private val UDP_TRACKER_NAME = Regex("udp://((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})/(\\d{1,9})")
private val HID_TRACKER_NAME = Regex("([0-9A-Fa-f]{12})/0")
private val LEGACY_POSE_KEYS = listOf(
StayAlignedRelaxedPose.STANDING to "standingRelaxedPose",
StayAlignedRelaxedPose.SITTING to "sittingRelaxedPose",
StayAlignedRelaxedPose.FLAT to "flatRelaxedPose",
)
data class LegacyConfigMigration(
val settings: SettingsConfigState,
val user: UserConfigData,
val devices: DevicesConfigState,
)
suspend fun importLegacyConfig(storage: ConfigStorage) {
if (storage.exists(GLOBAL_CONFIG_PATH)) return
val raw = storage.read(LEGACY_CONFIG_PATH) ?: return
val migration = try {
migrateLegacyConfig(raw)
} catch (e: Exception) {
AppLogger.config.error(e, "Failed to read ${storage.displayPath(LEGACY_CONFIG_PATH)}")
return
}
if (migration == null) {
AppLogger.config.info("Skipped ${storage.displayPath(LEGACY_CONFIG_PATH)}, only version $MIN_LEGACY_CONFIG_VERSION and newer are imported")
return
}
val defaults = GlobalConfigState()
storage.write(
configPath(SETTINGS_PROFILE_DIR, profileFileName(defaults.selectedSettingsProfile)),
jsonConfig.encodeToString(migration.settings),
overwrite = false,
)
storage.write(
configPath(USER_PROFILE_DIR, profileFileName(defaults.selectedUserProfile)),
jsonConfig.encodeToString(migration.user),
overwrite = false,
)
storage.write(DEVICES_CONFIG_PATH, jsonConfig.encodeToString(migration.devices), overwrite = false)
AppLogger.config.info("Imported ${storage.displayPath(LEGACY_CONFIG_PATH)}")
}
fun migrateLegacyConfig(yaml: String): LegacyConfigMigration? {
// Configs saved before the GUI trimmed the VRM hold its whole glTF JSON, which can go past the 3 MB default
val loadSettings = LoadSettings.builder().setCodePointLimit(Int.MAX_VALUE).build()
val root = Load(loadSettings).loadOne(yaml) as? Map<*, *> ?: return null
val version = intOf(root["modelVersion"]) ?: return null
if (version < MIN_LEGACY_CONFIG_VERSION) return null
return LegacyConfigMigration(
settings = settingsOf(root),
user = userOf(root),
devices = devicesOf(root),
)
}
private fun settingsOf(root: Map<*, *>): SettingsConfigState {
val defaults = SettingsConfigState()
val server = section(root, "server")
val skeleton = section(root, "skeleton")
val toggles = section(skeleton, "toggles")
val values = section(skeleton, "values")
val resets = section(root, "resetsConfig")
val tap = section(root, "tapDetection")
val vmc = section(root, "vmc")
val hid = section(root, "hidConfig")
val stayAligned = section(root, "stayAlignedConfig")
val defaultToggles = defaults.skeletonConfig.toggles
val defaultRatios = defaults.skeletonConfig.ratios
val defaultResets = defaults.resetsConfig
val defaultTap = defaults.trackerActionConfig
val defaultVmc = defaults.vmcConfig
return defaults.copy(
trackersConfig = defaults.trackersConfig.copy(
globalMagEnabled = boolOf(server["useMagnetometerOnAllTrackers"]) ?: defaults.trackersConfig.globalMagEnabled,
),
hidConfig = defaults.hidConfig.copy(
trackersOverHid = boolOf(hid["trackersOverHID"]) ?: defaults.hidConfig.trackersOverHid,
),
skeletonConfig = defaults.skeletonConfig.copy(
toggles = defaultToggles.copy(
floorClip = boolOf(toggles["floorClip"]) ?: defaultToggles.floorClip,
skatingCorrection = boolOf(toggles["skatingCorrection"]) ?: defaultToggles.skatingCorrection,
toeSnap = boolOf(toggles["toeSnap"]) ?: defaultToggles.toeSnap,
footPlant = boolOf(toggles["footPlant"]) ?: defaultToggles.footPlant,
mocapMode = boolOf(toggles["selfLocalization"]) ?: defaultToggles.mocapMode,
enforceConstraints = boolOf(toggles["enforceConstraints"]) ?: defaultToggles.enforceConstraints,
),
ratios = defaultRatios.copy(
interpolateUpperLegsTwistWithLowerLegs = floatOf(values["kneeTrackerAnkleAveraging"])
?: defaultRatios.interpolateUpperLegsTwistWithLowerLegs,
),
),
resetsConfig = defaultResets.copy(
resetMountingFeet = boolOf(resets["resetMountingFeet"]) ?: defaultResets.resetMountingFeet,
armsMountingResetMode = armsMountingResetModeOf(resets["mode"]) ?: defaultResets.armsMountingResetMode,
yawResetSmoothTime = floatOf(resets["yawResetSmoothTime"]) ?: defaultResets.yawResetSmoothTime,
saveMountingReset = boolOf(resets["saveMountingReset"]) ?: defaultResets.saveMountingReset,
resetHmdAttitude = boolOf(resets["resetHmdPitch"]) ?: defaultResets.resetHmdAttitude,
),
trackerActionConfig = defaultTap.copy(
yawResetAction = defaultTap.yawResetAction.copy(
enabled = boolOf(tap["yawResetEnabled"]) ?: defaultTap.yawResetAction.enabled,
delay = floatOf(tap["yawResetDelay"]) ?: defaultTap.yawResetAction.delay,
bodyPart = stringOf(tap["yawResetTracker"])?.let(::bodyPartOf) ?: defaultTap.yawResetAction.bodyPart,
taps = intOf(tap["yawResetTaps"]) ?: defaultTap.yawResetAction.taps,
),
fullResetAction = defaultTap.fullResetAction.copy(
enabled = boolOf(tap["fullResetEnabled"]) ?: defaultTap.fullResetAction.enabled,
delay = floatOf(tap["fullResetDelay"]) ?: defaultTap.fullResetAction.delay,
bodyPart = stringOf(tap["fullResetTracker"])?.let(::bodyPartOf) ?: defaultTap.fullResetAction.bodyPart,
taps = intOf(tap["fullResetTaps"]) ?: defaultTap.fullResetAction.taps,
),
mountingResetAction = defaultTap.mountingResetAction.copy(
enabled = boolOf(tap["mountingResetEnabled"]) ?: defaultTap.mountingResetAction.enabled,
delay = floatOf(tap["mountingResetDelay"]) ?: defaultTap.mountingResetAction.delay,
bodyPart = stringOf(tap["mountingResetTracker"])?.let(::bodyPartOf) ?: defaultTap.mountingResetAction.bodyPart,
taps = intOf(tap["mountingResetTaps"]) ?: defaultTap.mountingResetAction.taps,
),
tapsTrackersOverThreshold = intOf(tap["numberTrackersOverThreshold"]) ?: defaultTap.tapsTrackersOverThreshold,
),
vmcConfig = defaultVmc.copy(
enabled = boolOf(vmc["enabled"]) ?: defaultVmc.enabled,
portIn = intOf(vmc["portIn"]) ?: defaultVmc.portIn,
portOut = intOf(vmc["portOut"]) ?: defaultVmc.portOut,
address = stringOf(vmc["address"]) ?: defaultVmc.address,
mirrorTracking = boolOf(vmc["mirrorTracking"]) ?: defaultVmc.mirrorTracking,
anchorAtHips = boolOf(vmc["anchorHip"]) ?: defaultVmc.anchorAtHips,
vrmJson = vrmJsonOf(vmc["vrmJson"]) ?: defaultVmc.vrmJson,
),
stayAlignedConfig = defaults.stayAlignedConfig.copy(
enabled = boolOf(stayAligned["enabled"]) ?: defaults.stayAlignedConfig.enabled,
),
)
}
private fun userOf(root: Map<*, *>): UserConfigData {
val skeleton = section(root, "skeleton")
val stayAligned = section(root, "stayAlignedConfig")
val poses = LEGACY_POSE_KEYS.mapNotNull { (pose, key) ->
val old = section(stayAligned, key)
if (boolOf(old["enabled"]) != true) return@mapNotNull null
pose to StayAlignedPoseConfig(
recorded = true,
enabled = true,
upperLegAngleInDeg = floatOf(old["upperLegAngleInDeg"]) ?: 0f,
lowerLegAngleInDeg = floatOf(old["lowerLegAngleInDeg"]) ?: 0f,
footAngleInDeg = floatOf(old["footAngleInDeg"]) ?: 0f,
)
}.toMap()
val user = UserConfigData(stayAlignedPoses = poses)
val height = (floatOf(skeleton["hmdHeight"]) ?: 0f) - (floatOf(skeleton["floorHeight"]) ?: 0f)
if (height < MIN_USER_HEIGHT) return user
// Proportions are not imported, they are the defaults for the imported height
return withDefaultProportions(user.copy(userHeight = height))
}
private fun devicesOf(root: Map<*, *>): DevicesConfigState {
val oldTrackers = section(root, "trackers")
val trackers = oldTrackers.entries.mapNotNull { (name, old) ->
val hardwareId = (name as? String)?.let(::hardwareIdOf) ?: return@mapNotNull null
val config = old as? Map<*, *> ?: return@mapNotNull null
hardwareId to TrackerConfig(
bodyPart = stringOf(config["designation"])?.let { bodyPartOf(it.removePrefix("body:").uppercase()) },
customName = stringOf(config["customName"])?.takeIf { it.isNotBlank() },
mountingOrientation = quaternionOf(config["mountingOrientation"]) ?: Quaternion.IDENTITY,
)
}.toMap()
val knownDevices = (root["knownDevices"] as? List<*>).orEmpty().mapNotNull { stringOf(it)?.uppercase() }.toSet()
return DevicesConfigState(allowedUdpDevices = knownDevices, trackers = trackers)
}
private fun hardwareIdOf(trackerName: String): String? {
UDP_TRACKER_NAME.matchEntire(trackerName)?.let { return udpTrackerHardwareId(it.groupValues[1].uppercase(), it.groupValues[2].toInt()) }
HID_TRACKER_NAME.matchEntire(trackerName)?.let { return hidTrackerHardwareId(it.groupValues[1].uppercase()) }
return null
}
private fun bodyPartOf(trackerPosition: String): BodyPart? = when (trackerPosition) {
"CHEST" -> BodyPart.UPPER_CHEST
"WAIST" -> BodyPart.LOWER_WAIST
else -> BodyPart.entries.firstOrNull { it != BodyPart.NONE && it.name == trackerPosition }
}
/** T-pose down does not exist anymore, both T-poses become the side T-pose. */
private fun armsMountingResetModeOf(value: Any?): ArmsMountingResetMode? = when (stringOf(value)) {
"BACK" -> ArmsMountingResetMode.BACK
"FORWARD" -> ArmsMountingResetMode.FORWARD
"TPOSE_UP", "TPOSE_DOWN" -> ArmsMountingResetMode.SIDE
else -> null
}
/** Strip older VRM that were too big */
private fun vrmJsonOf(value: Any?): String? {
val raw = stringOf(value)?.takeIf { it.isNotEmpty() } ?: return null
val gltf = try {
jsonConfig.parseToJsonElement(raw).jsonObject
} catch (_: IllegalArgumentException) {
return null
}
val extensions = gltf["extensions"] as? JsonObject
return buildJsonObject {
if (extensions != null) {
put(
"extensions",
buildJsonObject {
extensions["VRM"]?.let { put("VRM", it) }
extensions["VRMC_vrm"]?.let { put("VRMC_vrm", it) }
},
)
}
gltf["extensionsUsed"]?.let { put("extensionsUsed", it) }
gltf["nodes"]?.let { put("nodes", it) }
}.toString()
}
private fun quaternionOf(value: Any?): Quaternion? {
val map = value as? Map<*, *> ?: return null
return Quaternion(
floatOf(map["w"]) ?: return null,
floatOf(map["x"]) ?: return null,
floatOf(map["y"]) ?: return null,
floatOf(map["z"]) ?: return null,
)
}
private fun section(map: Map<*, *>, key: String): Map<*, *> = map[key] as? Map<*, *> ?: emptyMap<Any?, Any?>()
private fun stringOf(value: Any?): String? = value as? String
private fun boolOf(value: Any?): Boolean? = when (value) {
is Boolean -> value
is String -> value.toBooleanStrictOrNull()
else -> null
}
private fun floatOf(value: Any?): Float? = when (value) {
is Number -> value.toFloat()
is String -> value.toFloatOrNull()
else -> null
}
private fun intOf(value: Any?): Int? = when (value) {
is Number -> value.toInt()
is String -> value.toIntOrNull()
else -> null
}
@@ -20,6 +20,7 @@ import solarxr_protocol.rpc.ProfileKind
import solarxr_protocol.rpc.ProfileOperationStatus
import java.util.UUID
const val GLOBAL_CONFIG_PATH = "global.json"
private const val GLOBAL_CONFIG_VERSION = 1
private const val CURRENT_CONSENT_VERSION = 2
@@ -67,7 +68,7 @@ class GlobalConfig(
companion object {
suspend fun create(scope: CoroutineScope, storage: ConfigStorage): GlobalConfig {
val initialState = loadFileWithBackup(storage, "global.json", GlobalConfigState()) {
val initialState = loadFileWithBackup(storage, GLOBAL_CONFIG_PATH, GlobalConfigState()) {
parseAndMigrateGlobalConfig(it)
}.let(::withSafeProfileNames)
val context = Context.create(
@@ -79,12 +80,12 @@ class GlobalConfig(
val globalConfig = GlobalConfig(context)
globalConfig.startObserving()
// Persists defaults filled on load (the generated userId), autosave skips the initial state
storage.write("global.json", jsonConfig.encodeToString(initialState))
storage.write(GLOBAL_CONFIG_PATH, jsonConfig.encodeToString(initialState))
launchAutosave(
scope = scope,
state = context.state,
storage = storage,
toPath = { "global.json" },
toPath = { GLOBAL_CONFIG_PATH },
serialize = { jsonConfig.encodeToString(it) },
)
return globalConfig
@@ -280,6 +281,7 @@ class AppConfig(
companion object {
suspend fun create(scope: CoroutineScope, storage: ConfigStorage): AppConfig {
importLegacyConfig(storage)
val globalConfig = GlobalConfig.create(scope, storage)
val userConfig = UserConfig.create(scope, storage, globalConfig.context.state.value.selectedUserProfile)
@@ -12,6 +12,7 @@ import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.KeybindId
import solarxr_protocol.rpc.RoutingOutput
@@ -47,24 +48,23 @@ data class DriverConfig(
val sendVelocity: Boolean = false,
)
// Used in TrackerActionConfig
@Serializable
data class TapDetectionConfig(
var yawResetDelay: Float = 0.2f,
var fullResetDelay: Float = 1.4f,
var mountingResetDelay: Float = 1.4f,
var yawResetEnabled: Boolean = true,
var fullResetEnabled: Boolean = true,
var mountingResetEnabled: Boolean = true,
data class TrackerActionSettings(
val enabled: Boolean = true,
val delay: Float,
@Serializable(with = BodyPartSerializer::class)
var yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
@Serializable(with = BodyPartSerializer::class)
var mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
@Serializable(with = BodyPartSerializer::class)
var fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
var yawResetTaps: Int = 2,
var fullResetTaps: Int = 3,
var mountingResetTaps: Int = 3,
var numberTrackersOverThreshold: Int = 1,
val bodyPart: BodyPart?,
val method: TrackerActionMethod = TrackerActionMethod.BOTH,
val taps: Int,
)
@Serializable
data class TrackerActionConfig(
val yawResetAction: TrackerActionSettings = TrackerActionSettings(delay = 0.2f, bodyPart = BodyPart.UPPER_CHEST, taps = 2),
val fullResetAction: TrackerActionSettings = TrackerActionSettings(delay = 1.4f, bodyPart = BodyPart.LEFT_UPPER_LEG, taps = 3),
val mountingResetAction: TrackerActionSettings = TrackerActionSettings(delay = 1.0f, bodyPart = BodyPart.RIGHT_UPPER_LEG, taps = 3),
val tapsTrackersOverThreshold: Int = 1,
)
@Serializable
@@ -170,7 +170,7 @@ data class SettingsConfigState(
val hidConfig: HidConfig = HidConfig(),
val boneRoutingConfig: BoneRoutingConfig = BoneRoutingConfig(),
val driverConfig: DriverConfig = DriverConfig(),
val tapDetectionConfig: TapDetectionConfig = TapDetectionConfig(),
val trackerActionConfig: TrackerActionConfig = TrackerActionConfig(),
val resetsConfig: ResetsConfig = ResetsConfig(),
val keybinds: List<KeybindConfig> = defaultKeybinds(),
val skeletonConfig: SkeletonConfig = SkeletonConfig(),
@@ -16,6 +16,9 @@ import solarxr_protocol.rpc.StayAlignedRelaxedPose
private const val USER_CONFIG_VERSION = 1
private const val DEFAULT_USER_HEIGHT = 1.6f
/** Lowest eye height accepted as the user height. */
const val MIN_USER_HEIGHT = 0.9f
/** A relaxed pose of the user, used by Stay Aligned to correct moving trackers. */
@Serializable
data class StayAlignedPoseConfig(
@@ -83,8 +83,8 @@ class HeightCalibrationManager(
combine(
controllers.map { controller ->
controller.context.state.map { s ->
val position = s.position ?: error("hands (or Controller) will always have a position in this case")
TrackerSnapshot(position = position, rotation = s.rawRotation)
val rawPosition = s.rawPosition ?: error("hands (or Controller) will always have a rawPosition in this case")
TrackerSnapshot(position = rawPosition, rotation = s.rawRotation)
}
},
) { snapshots -> snapshots.minByOrNull { it.position.y } ?: error("snapshots is empty; controllers check above should have prevented this") }
@@ -7,6 +7,7 @@ import dev.slimevr.hid.HIDDataLegacy
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverBehaviour
import dev.slimevr.hid.HIDRotationButtonLegacy
import solarxr_protocol.datatypes.TrackerActionMethod
class HIDButtonLegacyBehaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
private val lastButton = mutableMapOf<Int, Int>()
@@ -24,7 +25,11 @@ class HIDButtonLegacyBehaviour(private val appContext: AppContextProvider) : HID
if (!fired) return
val tracker = receiver.getTracker(hidId) ?: return
appContext.tapDetectionManager.actionTriggered(tracker.context.state.value.id, "HIDButtonLegacy")
appContext.trackerActionManager.actionTriggered(
tracker.context.state.value.id,
"HIDButtonLegacy",
TrackerActionMethod.BUTTON,
)
}
companion object {
@@ -7,6 +7,7 @@ import dev.slimevr.hid.HIDReceiverActions
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.hidTrackerHardwareId
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
@@ -53,10 +54,11 @@ internal suspend fun registerHidDevice(
/** Creates or finds the [Tracker] for an already-registered HID device and links it to [hidId]. */
internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int, imuType: ImuType? = null): Tracker? {
val deviceState = receiver.appContext.server.getDevice(deviceId)?.context?.state?.value ?: return null
val hardwareId = hidTrackerHardwareId(deviceState.address)
val tracker = receiver.getTracker(hidId)
?: receiver.appContext.server.context.state.value.trackers.values
.find { it.context.state.value.hardwareId == deviceState.address && it.context.state.value.origin == DeviceOrigin.HID }
.find { it.context.state.value.hardwareId == hardwareId && it.context.state.value.origin == DeviceOrigin.HID }
?: run {
val trackerId = receiver.appContext.server.nextHandle()
val newTracker = Tracker.create(
@@ -64,7 +66,7 @@ internal fun ensureHidTracker(receiver: HIDReceiver, hidId: Int, deviceId: Int,
id = trackerId,
deviceId = deviceState.id,
imuType = imuType,
hardwareId = deviceState.address,
hardwareId = hardwareId,
origin = DeviceOrigin.HID,
appContext = receiver.appContext,
)
@@ -4,12 +4,17 @@ import dev.slimevr.AppContextProvider
import dev.slimevr.hid.HIDButton
import dev.slimevr.hid.HIDReceiver
import dev.slimevr.hid.HIDReceiverBehaviour
import solarxr_protocol.datatypes.TrackerActionMethod
class HIDButtonV3Behaviour(private val appContext: AppContextProvider) : HIDReceiverBehaviour {
override fun observe(receiver: HIDReceiver) {
receiver.packetEvents.on<HIDButton> { packet ->
val tracker = receiver.getTracker(packet.hidId) ?: return@on
appContext.tapDetectionManager.actionTriggered(tracker.context.state.value.id, "HIDButtonV3")
appContext.trackerActionManager.actionTriggered(
tracker.context.state.value.id,
"HIDButtonV3",
TrackerActionMethod.BUTTON,
)
}.launchIn(receiver.context.scope)
}
}
@@ -46,6 +46,9 @@ import kotlin.collections.listOf
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
// Feet go slightly inwards on pose mounting
private const val FEET_POSE_DEG_INWARDS = 15
data class ResetsState(
val canDoYawReset: Boolean,
val canDoMountingReset: Boolean,
@@ -233,6 +236,11 @@ class ResetsManager(
}
private fun getYawOffset(bodyPart: BodyPart?, armsResetMode: ArmsMountingResetMode) = when (bodyPart) {
// Feet go back but a little inwards
BodyPart.LEFT_FOOT -> FastMath.PI - FEET_POSE_DEG_INWARDS * FastMath.DEG_TO_RAD
BodyPart.RIGHT_FOOT -> FastMath.PI + FEET_POSE_DEG_INWARDS * FastMath.DEG_TO_RAD
// Going forward
in ResetBodyParts.UPPER_LEGS -> 0f
@@ -90,7 +90,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.LOWER_CHEST,
Vector3.ZERO,
Quaternion.fromRotationVector(Vector3(cos(elapsed), sin(elapsed), 0f)),
Vector3.ZERO,
null,
@@ -99,7 +98,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.LEFT_LOWER_LEG,
Vector3.ZERO,
Quaternion.fromRotationVector(Vector3(cos(elapsed + 1000), sin(elapsed + 1000), 0f)),
Vector3.ZERO,
null,
@@ -114,7 +112,6 @@ class YouSpinMeRightRoundBehaviour(val inputHz: Int = 100, val speed: Float = 1f
receiver.context.dispatch(
SkeletonActions.SetBonePose(
BodyPart.HEAD,
Vector3.ZERO,
Quaternion.IDENTITY,
Vector3.ZERO,
Vector3(circleX, state.skeletonHeight + jumpHeight, circleZ),
@@ -299,7 +296,7 @@ class ComputedSkeletonBehaviour(
// If head changed position, set the new position in state (for Localizer).
if (bodyPart == BodyPart.HEAD && !boneInput.isPositionActive && boneInput.position != previous?.position) {
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, Vector3.ZERO, null, null, boneInput.position, false))
receiver.context.dispatch(SkeletonActions.SetBonePose(BodyPart.HEAD, null, null, boneInput.position, false))
}
}
// Inputs changed; re-run FK
@@ -2,169 +2,201 @@ package dev.slimevr.skeleton
import com.jme3.math.FastMath
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
// For fingers and toes
// TODO: should constrain splay separately from swing.
private val DIGIT_CONSTRAINT = TwistSwingConstraint(
10f * FastMath.DEG_TO_RAD,
115f * FastMath.DEG_TO_RAD,
private val METACARPAL_THUMB_CONSTRAINT = LooseHingeConstraint(
-80f * FastMath.DEG_TO_RAD,
100f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
Vector3.NEG_X,
)
private val THUMB_CONSTRAINT = LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
100f * FastMath.DEG_TO_RAD,
3f * FastMath.DEG_TO_RAD,
Vector3.NEG_X,
)
private val LEFT_PROXIMAL_FINGER_CONSTRAINT = LooseHingeConstraint(
-65f * FastMath.DEG_TO_RAD,
110f * FastMath.DEG_TO_RAD,
30f * FastMath.DEG_TO_RAD,
Vector3.POS_Z,
)
private val LEFT_FINGER_CONSTRAINT = LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
110f * FastMath.DEG_TO_RAD,
3f,
Vector3.POS_Z,
)
private val RIGHT_PROXIMAL_FINGER_CONSTRAINT = LEFT_PROXIMAL_FINGER_CONSTRAINT.copy(hingeAxis = Vector3.NEG_Z)
private val RIGHT_FINGER_CONSTRAINT = LEFT_FINGER_CONSTRAINT.copy(hingeAxis = Vector3.NEG_Z)
private val TOE_CONSTRAINT = LooseHingeConstraint(
-70f * FastMath.DEG_TO_RAD,
90f * FastMath.DEG_TO_RAD,
30f * FastMath.DEG_TO_RAD,
Vector3.NEG_X,
)
// TODO Actually figure out good values for these constraints, maybe a source would be
// good?
val BODY_PART_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
mapOf(
// Left arm
BodyPart.LEFT_SHOULDER to TwistSwingConstraint(
105f * FastMath.DEG_TO_RAD,
45f * FastMath.DEG_TO_RAD,
70f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_UPPER_ARM to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
BodyPart.LEFT_UPPER_ARM to FreeHingeConstraint(
-40f * FastMath.DEG_TO_RAD,
125f * FastMath.DEG_TO_RAD,
Vector3.POS_Y,
),
BodyPart.LEFT_LOWER_ARM to LooseHingeConstraint(
-180f * FastMath.DEG_TO_RAD,
-160f * FastMath.DEG_TO_RAD,
0f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
Vector3.NEG_Z,
),
BodyPart.LEFT_HAND to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
70f * FastMath.DEG_TO_RAD,
95f * FastMath.DEG_TO_RAD,
),
// Right arm
BodyPart.RIGHT_SHOULDER to TwistSwingConstraint(
105f * FastMath.DEG_TO_RAD,
45f * FastMath.DEG_TO_RAD,
70f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_UPPER_ARM to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
BodyPart.RIGHT_UPPER_ARM to FreeHingeConstraint(
-40f * FastMath.DEG_TO_RAD,
125f * FastMath.DEG_TO_RAD,
Vector3.NEG_Y,
),
BodyPart.RIGHT_LOWER_ARM to LooseHingeConstraint(
-180f * FastMath.DEG_TO_RAD,
-160f * FastMath.DEG_TO_RAD,
0f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
Vector3.POS_Z,
),
BodyPart.RIGHT_HAND to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
70f * FastMath.DEG_TO_RAD,
95f * FastMath.DEG_TO_RAD,
),
// Spine
BodyPart.UPPER_CHEST to TwistSwingConstraint(
95f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
105f * FastMath.DEG_TO_RAD,
),
BodyPart.LOWER_CHEST to TwistSwingConstraint(
30f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
110f * FastMath.DEG_TO_RAD,
),
BodyPart.UPPER_WAIST to TwistSwingConstraint(
40f * FastMath.DEG_TO_RAD,
110f * FastMath.DEG_TO_RAD,
35f * FastMath.DEG_TO_RAD,
60f * FastMath.DEG_TO_RAD,
),
BodyPart.LOWER_WAIST to TwistSwingConstraint(
40f * FastMath.DEG_TO_RAD,
110f * FastMath.DEG_TO_RAD,
35f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
),
BodyPart.HIP to TwistSwingConstraint(
65f * FastMath.DEG_TO_RAD,
120f * FastMath.DEG_TO_RAD,
50f * FastMath.DEG_TO_RAD,
80f * FastMath.DEG_TO_RAD,
),
// Left leg
BodyPart.LEFT_UPPER_LEG to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
170f * FastMath.DEG_TO_RAD,
BodyPart.LEFT_UPPER_LEG to LooseHingeConstraint(
-50f * FastMath.DEG_TO_RAD,
165f * FastMath.DEG_TO_RAD,
90f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_LOWER_LEG to LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
-165f * FastMath.DEG_TO_RAD,
6f * FastMath.DEG_TO_RAD,
65f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_FOOT to LooseHingeConstraint(
-45f * FastMath.DEG_TO_RAD,
20f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
),
// TODO enforcing constraint looks bad
// BodyPart.LEFT_FOOT to LooseHingeConstraint(
// -60f * FastMath.DEG_TO_RAD,
// 90f * FastMath.DEG_TO_RAD,
// 80f * FastMath.DEG_TO_RAD,
// ),
// Right leg
BodyPart.RIGHT_UPPER_LEG to TwistSwingConstraint(
120f * FastMath.DEG_TO_RAD,
170f * FastMath.DEG_TO_RAD,
BodyPart.RIGHT_UPPER_LEG to LooseHingeConstraint(
-50f * FastMath.DEG_TO_RAD,
165f * FastMath.DEG_TO_RAD,
90f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_LOWER_LEG to LooseHingeConstraint(
-5f * FastMath.DEG_TO_RAD,
180f * FastMath.DEG_TO_RAD,
40f * FastMath.DEG_TO_RAD,
-165f * FastMath.DEG_TO_RAD,
6f * FastMath.DEG_TO_RAD,
65f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_FOOT to LooseHingeConstraint(
-45f * FastMath.DEG_TO_RAD,
20f * FastMath.DEG_TO_RAD,
55f * FastMath.DEG_TO_RAD,
),
// BodyPart.RIGHT_FOOT to LooseHingeConstraint(
// -60f * FastMath.DEG_TO_RAD,
// 90f * FastMath.DEG_TO_RAD,
// 80f * FastMath.DEG_TO_RAD,
// ),
// Left fingers
BodyPart.LEFT_THUMB_METACARPAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_THUMB_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_THUMB_DISTAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_INDEX_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_INDEX_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.LEFT_INDEX_DISTAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_MIDDLE_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_MIDDLE_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.LEFT_MIDDLE_DISTAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_RING_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_RING_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.LEFT_RING_DISTAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_LITTLE_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_LITTLE_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.LEFT_LITTLE_DISTAL to DIGIT_CONSTRAINT,
BodyPart.LEFT_THUMB_METACARPAL to METACARPAL_THUMB_CONSTRAINT,
BodyPart.LEFT_THUMB_PROXIMAL to THUMB_CONSTRAINT,
BodyPart.LEFT_THUMB_DISTAL to THUMB_CONSTRAINT,
BodyPart.LEFT_INDEX_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.LEFT_INDEX_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_INDEX_DISTAL to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_MIDDLE_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.LEFT_MIDDLE_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_MIDDLE_DISTAL to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_RING_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.LEFT_RING_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_RING_DISTAL to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_LITTLE_PROXIMAL to LEFT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.LEFT_LITTLE_INTERMEDIATE to LEFT_FINGER_CONSTRAINT,
BodyPart.LEFT_LITTLE_DISTAL to LEFT_FINGER_CONSTRAINT,
// Right fingers
BodyPart.RIGHT_THUMB_METACARPAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_THUMB_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_THUMB_DISTAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_INDEX_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_INDEX_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_INDEX_DISTAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_DISTAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_RING_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_RING_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_RING_DISTAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_LITTLE_PROXIMAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_LITTLE_INTERMEDIATE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_LITTLE_DISTAL to DIGIT_CONSTRAINT,
BodyPart.RIGHT_THUMB_METACARPAL to METACARPAL_THUMB_CONSTRAINT,
BodyPart.RIGHT_THUMB_PROXIMAL to THUMB_CONSTRAINT,
BodyPart.RIGHT_THUMB_DISTAL to THUMB_CONSTRAINT,
BodyPart.RIGHT_INDEX_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.RIGHT_INDEX_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_INDEX_DISTAL to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_DISTAL to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_RING_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.RIGHT_RING_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_RING_DISTAL to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_LITTLE_PROXIMAL to RIGHT_PROXIMAL_FINGER_CONSTRAINT,
BodyPart.RIGHT_LITTLE_INTERMEDIATE to RIGHT_FINGER_CONSTRAINT,
BodyPart.RIGHT_LITTLE_DISTAL to RIGHT_FINGER_CONSTRAINT,
// Left toes
BodyPart.LEFT_BIG_TOE to DIGIT_CONSTRAINT,
BodyPart.LEFT_INDEX_TOE to DIGIT_CONSTRAINT,
BodyPart.LEFT_MIDDLE_TOE to DIGIT_CONSTRAINT,
BodyPart.LEFT_RING_TOE to DIGIT_CONSTRAINT,
BodyPart.LEFT_LITTLE_TOE to DIGIT_CONSTRAINT,
// Right toes
BodyPart.RIGHT_BIG_TOE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_INDEX_TOE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_TOE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_RING_TOE to DIGIT_CONSTRAINT,
BodyPart.RIGHT_LITTLE_TOE to DIGIT_CONSTRAINT,
// Toes
BodyPart.LEFT_BIG_TOE to TOE_CONSTRAINT,
BodyPart.LEFT_INDEX_TOE to TOE_CONSTRAINT,
BodyPart.LEFT_MIDDLE_TOE to TOE_CONSTRAINT,
BodyPart.LEFT_RING_TOE to TOE_CONSTRAINT,
BodyPart.LEFT_LITTLE_TOE to TOE_CONSTRAINT,
BodyPart.RIGHT_BIG_TOE to TOE_CONSTRAINT,
BodyPart.RIGHT_INDEX_TOE to TOE_CONSTRAINT,
BodyPart.RIGHT_MIDDLE_TOE to TOE_CONSTRAINT,
BodyPart.RIGHT_RING_TOE to TOE_CONSTRAINT,
BodyPart.RIGHT_LITTLE_TOE to TOE_CONSTRAINT,
),
)
fun constrainSkeleton(
bones: InputSkeleton,
constraints: BodyPartMap<Constraint>,
onlyActive: Boolean,
): InputSkeleton {
// Apply constraints top-down
for ((parentBodyPart, bodyPart) in iterateBodyPartHierarchy()) {
val bone = bones[bodyPart] ?: continue
if (onlyActive && !bone.isRotationActive) continue
val constraint = constraints[bodyPart] ?: continue
val parentRotation = bones[parentBodyPart]?.rotation ?: Quaternion.IDENTITY
bones[bodyPart] = bone.copy(
@@ -177,40 +209,84 @@ fun constrainSkeleton(
return bones
}
/**
* Used for the initial rotation before doing IK to promote movement and preferred axis.
*/
val BODY_PART_PREFERRED_ROTATION = BodyPartMap(
mapOf(
BodyPart.LEFT_UPPER_ARM to Quaternion.fromRotationVector(-45f * FastMath.DEG_TO_RAD, 90f * FastMath.DEG_TO_RAD, -100f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_UPPER_ARM to Quaternion.fromRotationVector(-45f * FastMath.DEG_TO_RAD, -90f * FastMath.DEG_TO_RAD, 100f * FastMath.DEG_TO_RAD),
BodyPart.LEFT_LOWER_ARM to Quaternion.fromRotationVector(0f, 70f * FastMath.DEG_TO_RAD, 0f),
BodyPart.RIGHT_LOWER_ARM to Quaternion.fromRotationVector(0f, -70f * FastMath.DEG_TO_RAD, 0f),
BodyPart.LEFT_UPPER_LEG to Quaternion.rotationAroundXAxis(35f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_UPPER_LEG to Quaternion.rotationAroundXAxis(35f * FastMath.DEG_TO_RAD),
BodyPart.LEFT_LOWER_LEG to Quaternion.rotationAroundXAxis(-20f * FastMath.DEG_TO_RAD),
BodyPart.RIGHT_LOWER_LEG to Quaternion.rotationAroundXAxis(-20f * FastMath.DEG_TO_RAD),
// BodyPart.UPPER_CHEST to Quaternion.rotationAroundXAxis(-10f * FastMath.DEG_TO_RAD),
// BodyPart.LOWER_CHEST to Quaternion.rotationAroundXAxis(-5f * FastMath.DEG_TO_RAD),
// BodyPart.UPPER_WAIST to Quaternion.rotationAroundXAxis(7.5f * FastMath.DEG_TO_RAD),
// BodyPart.LOWER_WAIST to Quaternion.rotationAroundXAxis(7.5f * FastMath.DEG_TO_RAD),
),
)
// Constraints to apply to a local offset to best fit a bone's natural movement
// Basically the max angle change per IK iteration within local axes
// TODO May need to decay constraint over iterations
val BODY_PART_OFFSET_CONSTRAINT_MAP: BodyPartMap<Constraint> = BodyPartMap(
mapOf(
// TODO Figure out arms
// BodyPart.LEFT_UPPER_ARM to AxisConstraint(),
// BodyPart.RIGHT_UPPER_ARM to AxisConstraint(),
BodyPart.LEFT_UPPER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.LEFT_LOWER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.UPPER_CHEST to LooseAxisConstraint(
10f * FastMath.DEG_TO_RAD,
BodyPart.RIGHT_UPPER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
BodyPart.LOWER_CHEST to LooseAxisConstraint(
10f * FastMath.DEG_TO_RAD,
),
BodyPart.UPPER_WAIST to LooseAxisConstraint(
10f * FastMath.DEG_TO_RAD,
),
BodyPart.LOWER_WAIST to LooseAxisConstraint(
10f * FastMath.DEG_TO_RAD,
BodyPart.RIGHT_LOWER_ARM to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
Vector3.POS_X,
),
// BodyPart.UPPER_CHEST to TwistSwingConstraint(
// 8f * FastMath.DEG_TO_RAD,
// 4f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.LOWER_CHEST to TwistSwingConstraint(
// 4f * FastMath.DEG_TO_RAD,
// 2f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.UPPER_WAIST to TwistSwingConstraint(
// 6f * FastMath.DEG_TO_RAD,
// 4f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
// BodyPart.LOWER_WAIST to TwistSwingConstraint(
// 3f * FastMath.DEG_TO_RAD,
// 2f * FastMath.DEG_TO_RAD,
// Vector3.POS_X,
// ),
BodyPart.LEFT_UPPER_LEG to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
),
BodyPart.LEFT_LOWER_LEG to LooseAxisConstraint(
0.1f * FastMath.DEG_TO_RAD,
0.2f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_UPPER_LEG to LooseAxisConstraint(
5f * FastMath.DEG_TO_RAD,
),
BodyPart.RIGHT_LOWER_LEG to LooseAxisConstraint(
0.1f * FastMath.DEG_TO_RAD,
0.2f * FastMath.DEG_TO_RAD,
),
),
)
@@ -17,12 +17,11 @@ val BODY_PART_IK_CHAIN_MAP: BodyPartMap<IKChain> = BodyPartMap(
BodyPart.RIGHT_UPPER_ARM,
BodyPart.RIGHT_LOWER_ARM,
),
BodyPart.HIP to listOf(
BodyPart.LOWER_WAIST to listOf(
BodyPart.UPPER_CHEST,
BodyPart.LOWER_CHEST,
BodyPart.UPPER_WAIST,
BodyPart.LOWER_WAIST,
BodyPart.HIP,
),
BodyPart.LEFT_LOWER_LEG to listOf(
BodyPart.LEFT_UPPER_LEG,
@@ -32,15 +31,5 @@ val BODY_PART_IK_CHAIN_MAP: BodyPartMap<IKChain> = BodyPartMap(
BodyPart.RIGHT_UPPER_LEG,
BodyPart.RIGHT_LOWER_LEG,
),
BodyPart.LEFT_FOOT to listOf(
BodyPart.LEFT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG,
BodyPart.LEFT_FOOT,
),
BodyPart.RIGHT_FOOT to listOf(
BodyPart.RIGHT_UPPER_LEG,
BodyPart.RIGHT_LOWER_LEG,
BodyPart.RIGHT_FOOT,
),
),
)
@@ -99,7 +99,7 @@ inline fun BodyPart.findFirstParent(predicate: (BodyPart) -> Boolean): BodyPart?
}
val headPartSet = setOf(BodyPart.HEAD)
fun highestBodyParts(bodyParts: Set<BodyPart>): Set<BodyPart> {
fun highestBodyParts(bodyParts: Collection<BodyPart>): Set<BodyPart> {
if (BodyPart.HEAD in bodyParts) return headPartSet
// Construct boolean array once
@@ -0,0 +1,52 @@
package dev.slimevr.skeleton.computedprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonComputedProcessor
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
/**
* Rotates the first Quaternion to match its twist to the rotation of
* the second Quaternion
*
* @param from the first Quaternion
* @param to the second Quaternion
* @return the rotated Quaternion
*/
private fun alignTwist(from: Quaternion, to: Quaternion): Quaternion {
val local = to.localAbout(from)
val twist = local.eulerHeading()
return twist.globalAbout(from)
}
/**
* Handles rotating the upper legs' twist to match the lower legs' twist to make VRChat's knee IK work better.
*
* This is a computed processor running after IK because we want to use the real upper leg's twist for IK and constraints.
*/
class UpperLegsTwistComputedProcessor(val settings: Settings) : SkeletonComputedProcessor {
/**
* First value is the BodyPart to be aligned.
* Second value is the source BodyPart.
*/
private val bodyPartToSources = arrayOf(
BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG,
)
override fun process(mutableComputedSkeleton: ComputedSkeleton, inputSkeleton: InputSkeleton) {
val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs
if (ratio == 0f) return
// Upper legs are written, lower legs are read, so the two never overlap
for ((part, source) in bodyPartToSources) {
val bone = mutableComputedSkeleton[part] ?: continue
val sourceRotation = mutableComputedSkeleton[source]?.rotation ?: continue
val alignedRotation = alignTwist(bone.rotation, sourceRotation)
mutableComputedSkeleton[part] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio))
}
}
}
@@ -1,9 +1,11 @@
package dev.slimevr.skeleton
import com.jme3.math.FastMath
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.withSign
@@ -41,15 +43,30 @@ data class TwistSwingConstraint(
* Swing range in radians.
*/
val swing: Float,
val twistAxis: Vector3 = Vector3.POS_Y,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, Vector3.NEG_Y)
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, twistAxis)
swingQ = constrainAngle(swingQ, swing)
twistQ = constrainAngle(twistQ, twist)
return swingQ * twistQ
}
}
data class TwistConstraint(
/**
* Twist range in radians.
*/
val twist: Float = 0f,
val twistAxis: Vector3 = Vector3.POS_Y,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
var (swingQ, twistQ) = decomposeToSwingTwist(localRotation, twistAxis)
twistQ = constrainAngle(twistQ, twist)
return swingQ * twistQ
}
}
data class HingeConstraint(
/**
* Minimum rotation in radians.
@@ -59,7 +76,7 @@ data class HingeConstraint(
* Maximum rotation in radians.
*/
val max: Float,
val hingeAxis: Vector3 = Vector3.NEG_X,
val hingeAxis: Vector3 = Vector3.POS_X,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
val (_, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
@@ -80,7 +97,7 @@ data class LooseHingeConstraint(
* Maximum non-hinge axis rotation in radians.
*/
val allowedDeviation: Float,
val hingeAxis: Vector3 = Vector3.NEG_X,
val hingeAxis: Vector3 = Vector3.POS_X,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
val (nonHingeRot, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
@@ -89,8 +106,25 @@ data class LooseHingeConstraint(
}
}
data class FreeHingeConstraint(
/**
* Minimum rotation in radians.
*/
val min: Float = 0f,
/**
* Maximum rotation in radians.
*/
val max: Float,
val hingeAxis: Vector3 = Vector3.POS_X,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
val (nonHingeRot, hingeAxisRot) = decomposeToSwingTwist(localRotation, hingeAxis)
return nonHingeRot * constrainOnAxis(hingeAxisRot, min, max, hingeAxis)
}
}
data class AxisConstraint(
val axis: Vector3 = Vector3.NEG_X,
val axis: Vector3 = Vector3.POS_X,
) : Constraint {
override fun apply(
localRotation: Quaternion,
@@ -102,7 +136,7 @@ data class LooseAxisConstraint(
* Maximum non-axis rotation in radians.
*/
val allowedDeviation: Float,
val axis: Vector3 = Vector3.NEG_X,
val axis: Vector3 = Vector3.POS_X,
) : Constraint {
override fun apply(localRotation: Quaternion): Quaternion {
val (nonAxisRot, axisRot) = decomposeToSwingTwist(localRotation, axis)
@@ -143,36 +177,27 @@ fun constrainAngle(rotation: Quaternion, angle: Float): Quaternion {
}
}
// Wraps an angle to -pi to pi
private fun wrapAngle(angle: Float) = angle - FastMath.TWO_PI * floor((angle + FastMath.PI) / FastMath.TWO_PI)
fun constrainOnAxis(
rotation: Quaternion,
minAngle: Float,
maxAngle: Float,
axis: Vector3,
): Quaternion {
val magnitudeMin = sin(minAngle * 0.5f)
val magnitudeMax = sin(maxAngle * 0.5f)
val magnitudeSqrMin = (magnitudeMin * magnitudeMin).withSign(minAngle)
val magnitudeSqrMax = (magnitudeMax * magnitudeMax).withSign(maxAngle)
val vector = rotation.xyz
val rotMagnitudeSqr = vector.lenSq().withSign(vector.dot(axis) * rotation.w)
return if (rotMagnitudeSqr !in magnitudeSqrMin..magnitudeSqrMax) {
val distToMin = min(
abs(rotMagnitudeSqr - magnitudeSqrMin),
abs(rotMagnitudeSqr + magnitudeSqrMin),
)
val distToMax = min(
abs(rotMagnitudeSqr - magnitudeSqrMax),
abs(rotMagnitudeSqr + magnitudeSqrMax),
)
val magnitude = if (distToMin < distToMax) magnitudeMin else magnitudeMax
val magnitudeSqr =
abs(if (distToMin < distToMax) magnitudeSqrMin else magnitudeSqrMax)
val angle = rotation.angleAboutR(axis)
return if (angle !in minAngle..maxAngle) {
val distToMin = abs(wrapAngle(angle - minAngle))
val distToMax = abs(wrapAngle(angle - maxAngle))
val magnitude = if (distToMin < distToMax) minAngle else maxAngle
// Could do Quaternion.fromRotationVector(axis * magnitude) but this is more optimized
// and constraints run several times per frame because of IK.
val halfMagnitude = magnitude * 0.5f
Quaternion(
sqrt(1f - magnitudeSqr),
vector.unit() * -magnitude,
cos(halfMagnitude),
axis * sin(halfMagnitude),
)
} else {
rotation
@@ -1,23 +1,36 @@
package dev.slimevr.skeleton.fkprocessors
import com.jme3.math.FastMath
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.Skeleton
import dev.slimevr.skeleton.SkeletonFkProcessor
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.math.abs
// The max height to plant feet by
const val ROTATION_CORRECTION_VERTICAL = 0.1f
private const val ROTATION_CORRECTION_VERTICAL = 0.1f
private const val ANKLE_DOWN_MIN = 0.35f
private const val ANKLE_DOWN_MAX = 0.63f
fun computeFootPlantRatio(
ankleHeight: Float,
floorLevel: Float,
ankleLocalPosition: Vector3,
): Float {
val ankleHeightAboveFloor = ankleHeight - floorLevel
val ratioOfRangeFromFloor = (ankleHeightAboveFloor / ROTATION_CORRECTION_VERTICAL).coerceIn(0f, 1f)
// Ratio of range *to* floor
return 1f - ratioOfRangeFromFloor
val rangeToFloorRatio = 1f - ratioOfRangeFromFloor
// Lessen the ratio as the ankle doesn't point down
val ankleDownDirection = abs(ankleLocalPosition.unit().y.coerceAtMost(0f))
val ankleDownRatio = FastMath.remapClamped(ankleDownDirection, ANKLE_DOWN_MIN, ANKLE_DOWN_MAX, 0f, 1f)
return rangeToFloorRatio * ankleDownRatio
}
fun correctFootAttitude(
@@ -27,21 +40,26 @@ fun correctFootAttitude(
): Quaternion = rotation.interpQ(rotation.eulerHeading(), correctionRatio)
class FootPlantFkProcessor(val skeleton: Skeleton) : SkeletonFkProcessor {
val bodyParts: Array<BodyPart> = arrayOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT)
val bodyParts = arrayOf(
BodyPart.LEFT_LOWER_LEG to BodyPart.LEFT_FOOT,
BodyPart.RIGHT_LOWER_LEG to BodyPart.RIGHT_FOOT,
)
override fun process(mutableInputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) {
if (!skeleton.effectiveFootPlant) return
for (bodyPart in bodyParts) {
val input = mutableInputSkeleton[bodyPart] ?: continue
for ((anklePart, footPart) in bodyParts) {
val input = mutableInputSkeleton[footPart] ?: continue
if (input.isRotationActive) continue
val output = fk[bodyPart] ?: continue
mutableInputSkeleton[bodyPart] = input.copy(
val foot = fk[footPart] ?: continue
val ankle = fk[anklePart] ?: continue
mutableInputSkeleton[footPart] = input.copy(
rotation = correctFootAttitude(
input.rotation,
computeFootPlantRatio(
output.headPosition.y,
foot.headPosition.y,
floorLevel,
ankle.localTailPosition,
),
),
)
@@ -10,10 +10,10 @@ import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.math.abs
const val TOE_SNAP_RANGE_MULTIPLIER = 2f
const val MAX_TOE_SNAP_RATIO = 0.8f
const val ANKLE_DOWN_MIN = 0.65f
const val ANKLE_DOWN_MAX = 0.85f
private const val TOE_SNAP_RANGE_MULTIPLIER = 1.64f
private const val MAX_TOE_SNAP_RATIO = 0.8f
private const val ANKLE_DOWN_MIN = 0.75f
private const val ANKLE_DOWN_MAX = 0.94f
fun computeToeSnapRatio(
ankleHeight: Float,
@@ -65,6 +65,7 @@ class ToeSnapFkProcessor(val skeleton: Skeleton) : SkeletonFkProcessor {
if (input.isRotationActive) continue
val length = input.offset.len()
if (length <= 0f) continue
val ankle = fk[anklePart] ?: continue
val foot = fk[footPart] ?: continue
mutableInputSkeleton[footPart] = input.copy(
@@ -5,6 +5,7 @@ import dev.slimevr.util.subListOfLast
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
import kotlin.math.log
fun requireBone(bones: ComputedSkeleton, bodyPart: BodyPart) = requireNotNull(bones[bodyPart]) {
"The computed skeleton is missing \"${bodyPart}\" from the IK chain."
@@ -19,6 +20,11 @@ fun chainDistanceFromTarget(
return (target - chainTail).len()
}
fun chainOffsetsLength(
bones: ComputedSkeleton,
chain: IKChain,
): Double = chain.sumOf { requireBone(bones, it).offset.len().toDouble() }
fun parentRot(
bones: ComputedSkeleton,
bodyPart: BodyPart,
@@ -26,26 +32,55 @@ fun parentRot(
bones[parent]?.rotation
} ?: Quaternion.IDENTITY
const val PREFERRED_ROTATION_START_BIAS = 62.0
const val PREFERRED_ROTATION_START_BIAS_MULTIPLIER = (PREFERRED_ROTATION_START_BIAS * PREFERRED_ROTATION_START_BIAS) - PREFERRED_ROTATION_START_BIAS
fun adjustToPreferredRotations(
mutableBoneInputs: InputSkeleton,
mutableComputedSkeleton: ComputedSkeleton,
goals: List<IKChainGoal>,
constraints: BodyPartMap<Constraint>?,
) {
val changedBodyParts = mutableSetOf<BodyPart>()
for (goal in goals) {
val chainEndToTarget = chainDistanceFromTarget(mutableComputedSkeleton, goal.chain, goal.target).toDouble()
val maxChainLength = chainOffsetsLength(mutableComputedSkeleton, goal.chain)
val distanceRatio = (chainEndToTarget / maxChainLength).coerceAtMost(1.0)
val t = (log(PREFERRED_ROTATION_START_BIAS + (distanceRatio * PREFERRED_ROTATION_START_BIAS_MULTIPLIER), PREFERRED_ROTATION_START_BIAS) - 1).toFloat()
for (bodyPart in goal.chain) {
val preferredRotation = BODY_PART_PREFERRED_ROTATION[bodyPart] ?: continue
val bone = mutableBoneInputs[bodyPart] ?: continue
val offsetRotation = bone.rotation * preferredRotation.pow(t)
val newRotation = constraints?.get(bodyPart)?.apply(
parentRot(mutableComputedSkeleton, bodyPart),
offsetRotation,
) ?: offsetRotation
mutableBoneInputs[bodyPart] = bone.copy(rotation = newRotation)
changedBodyParts.add(bodyPart)
}
}
if (changedBodyParts.isNotEmpty()) buildBones(mutableComputedSkeleton, mutableBoneInputs, changedBodyParts)
}
// Bones are most likely opposite along the X axis
private val oppositeRotation = Quaternion.rotationAroundXAxis(FastMath.PI)
private val smallRotation = Quaternion.rotationAroundXAxis(1f * FastMath.DEG_TO_RAD)
fun fromChainToTarget(
bodyPart: BodyPart,
bones: ComputedSkeleton,
chain: IKChain,
target: Vector3,
): Quaternion? {
val boneHead = requireBone(bones, bodyPart).headPosition
val bone = requireBone(bones, bodyPart)
val chainTail = requireBone(bones, chain.last()).tailPosition
val localChainTail = chainTail - boneHead
val localChainTail = chainTail - bone.headPosition
val localChainTailLenSq = localChainTail.lenSq()
if (FastMath.isApproxZero(localChainTailLenSq)) {
// Chain tail is at the origin
return null
}
val localTarget = target - boneHead
val localTarget = target - bone.headPosition
val localTargetLenSq = localTarget.lenSq()
if (FastMath.isApproxZero(localTargetLenSq)) {
// Target is at the origin
@@ -53,20 +88,11 @@ fun fromChainToTarget(
}
val offset = Quaternion.fromTo(localChainTail.unit(), localTarget.unit())
return if (localTargetLenSq < localChainTailLenSq &&
FastMath.isApproxZero(offset.angleQ())
) {
// TODO Should be based off a preferred axis/direction, currently seems to
// "snap" a little when hitting this fallback
// If the target is closer than the tail and the bone is parallel to the target,
// apply an arbitrary small rotation to promote movement
alignOffset(parentRot(bones, bodyPart).inv(), smallRotation)
} else if (FastMath.isApproxEqual(offset.lenSq(), 1f)) {
return if (FastMath.isApproxEqual(offset.lenSq(), 1f)) {
offset
} else {
// When the vectors are exactly opposite, arbitrarily choose an axis
alignOffset(parentRot(bones, bodyPart).inv(), oppositeRotation)
alignOffset(bone.rotation.inv(), oppositeRotation)
}
}
@@ -134,10 +160,10 @@ fun ccdIkIteration(
// Constrain the local offset
val localConstrainedOffset = offsetConstraint?.let {
val parentRot = parentRot(mutableComputedSkeleton, bodyPart)
val rotation = mutableComputedSkeleton[bodyPart]?.rotation ?: return@let null
alignOffset(
parentRot.inv(),
it.apply(alignOffset(parentRot, offset)),
rotation.inv(),
it.apply(alignOffset(rotation, offset)),
)
} ?: offset
@@ -155,7 +181,8 @@ fun ccdIkIteration(
rotateChain(mutableBoneInputs, chain, constrainedOffset)
// Only build bones for inputs that were changed
buildBones(mutableComputedSkeleton, mutableBoneInputs, chain.toSet())
// If performance is bad, we can combine buildBones calls for non-overlapping IK chains
buildBones(mutableComputedSkeleton, mutableBoneInputs, chain)
}
typealias IKChain = List<BodyPart>
@@ -179,8 +206,13 @@ fun ccdIk(
// No goal leaves every bone as the FK pass built it, so nothing below needs to run
if (goals.isEmpty()) return true
// Set each bone we're gonna do IK on to its preferred rotation
adjustToPreferredRotations(mutableBoneInputs, mutableComputedSkeleton, goals, constraints)
// IK iterations
var allGoalsMet = true
for (i in 0 until maxIterations) {
var allGoalsMet = true
allGoalsMet = true
for ((chain, target) in goals) {
// Only iterate chains not meeting the threshold
if (chainDistanceFromTarget(mutableComputedSkeleton, chain, target) <= threshold) continue
@@ -203,7 +235,5 @@ fun ccdIk(
if (allGoalsMet) break
}
return goals.all { (chain, target) ->
chainDistanceFromTarget(mutableComputedSkeleton, chain, target) <= threshold
}
return allGoalsMet
}
@@ -0,0 +1,109 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
data class ArmSource(
val bodyPart: BodyPart,
val needsActive: Boolean = true,
// null means it uses all remaining.
val ratio: Float? = null,
// For body-part-prerequisites.kt
val reliable: Boolean = false,
)
val ARM_TO_SOURCE = arrayOf(
BodyPart.LEFT_SHOULDER to arrayOf(
ArmSource(BodyPart.LEFT_UPPER_ARM, true, 0.04f),
ArmSource(BodyPart.UPPER_CHEST, false, null, true),
),
BodyPart.RIGHT_SHOULDER to arrayOf(
ArmSource(BodyPart.RIGHT_UPPER_ARM, true, 0.04f),
ArmSource(BodyPart.UPPER_CHEST, false, null, true),
),
BodyPart.LEFT_UPPER_ARM to arrayOf(
ArmSource(BodyPart.LEFT_LOWER_ARM, true),
ArmSource(BodyPart.LEFT_HAND, true),
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.4f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
BodyPart.RIGHT_UPPER_ARM to arrayOf(
ArmSource(BodyPart.RIGHT_LOWER_ARM, true),
ArmSource(BodyPart.RIGHT_HAND, true),
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.4f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
BodyPart.LEFT_LOWER_ARM to arrayOf(
ArmSource(BodyPart.LEFT_HAND, true),
ArmSource(BodyPart.LEFT_UPPER_ARM, true),
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.2f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
BodyPart.RIGHT_LOWER_ARM to arrayOf(
ArmSource(BodyPart.RIGHT_HAND, true),
ArmSource(BodyPart.RIGHT_UPPER_ARM, true),
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.2f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
BodyPart.LEFT_HAND to arrayOf(
ArmSource(BodyPart.LEFT_LOWER_ARM),
ArmSource(BodyPart.LEFT_UPPER_ARM),
ArmSource(BodyPart.LEFT_SHOULDER, true, 0.25f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
BodyPart.RIGHT_HAND to arrayOf(
ArmSource(BodyPart.RIGHT_LOWER_ARM),
ArmSource(BodyPart.RIGHT_UPPER_ARM),
ArmSource(BodyPart.RIGHT_SHOULDER, true, 0.25f),
ArmSource(BodyPart.UPPER_CHEST, false),
),
)
/**
* Handles imputing missing arm bones from other arm bones and the upper chest.
*
* It's useful to set a good starting rotation for arms before IK.
*
* This processor must run after the spine processor.
*/
class ArmsInputProcessor : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val boneInputs = BodyPartMap(mutableInputSkeleton)
for ((bodyPart, sources) in ARM_TO_SOURCE) {
val bone = boneInputs[bodyPart] ?: continue
if (bone.isRotationActive && bone.isAccelerationActive) continue
var ratioSum = 0f
var rotation: Quaternion? = null
var acceleration: Vector3? = null
for ((index, source) in sources.withIndex()) {
val sourceBone = boneInputs[source.bodyPart] ?: continue
if (source.needsActive && !sourceBone.isRotationActive) continue
val isLastSource = index == sources.count() - 1
val remainingRatio = 1f - ratioSum
val ratio = (if (!isLastSource) source.ratio?.coerceAtMost(remainingRatio) else null) ?: remainingRatio
if (!bone.isRotationActive) {
rotation = (rotation ?: Quaternion.ZERO) + (sourceBone.rotation * ratio)
}
if (!bone.isAccelerationActive) {
acceleration = (acceleration ?: Vector3.ZERO) + (sourceBone.acceleration * ratio)
}
ratioSum += ratio
if (ratioSum >= 1f) break
}
if ((rotation == null || rotation == bone.rotation) && (acceleration == null || acceleration == bone.acceleration)) continue
mutableInputSkeleton[bodyPart] = bone.copy(rotation = rotation?.unit() ?: bone.rotation, acceleration = acceleration ?: bone.acceleration)
}
}
}
@@ -16,6 +16,6 @@ class ConstraintInputProcessor(
val skeletonConfig = settings.context.state.value.data.skeletonConfig
if (!skeletonConfig.toggles.enforceConstraints) return
constrainSkeleton(mutableInputSkeleton, constraints)
constrainSkeleton(mutableInputSkeleton, constraints, true)
}
}
@@ -5,27 +5,12 @@ import dev.slimevr.skeleton.SkeletonInputProcessor
import solarxr_protocol.datatypes.BodyPart
/**
* Linked BodyPart to the BodyPart it takes its rotation from.
*
* Order matters: an untracked arm cascades down from the upper chest in one pass.
* Linked BodyPart to the BodyPart it takes its rotation from. Order matters.
*/
val BONE_DIRECT_LINK_SOURCES = arrayOf(
BodyPart.HEAD to BodyPart.NECK,
BodyPart.LEFT_FOOT to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_FOOT to BodyPart.RIGHT_LOWER_LEG,
BodyPart.LEFT_SHOULDER to BodyPart.UPPER_CHEST,
BodyPart.RIGHT_SHOULDER to BodyPart.UPPER_CHEST,
BodyPart.LEFT_UPPER_ARM to BodyPart.LEFT_SHOULDER,
BodyPart.RIGHT_UPPER_ARM to BodyPart.RIGHT_SHOULDER,
BodyPart.LEFT_LOWER_ARM to BodyPart.LEFT_UPPER_ARM,
BodyPart.RIGHT_LOWER_ARM to BodyPart.RIGHT_UPPER_ARM,
BodyPart.LEFT_HAND to BodyPart.LEFT_LOWER_ARM,
BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM,
)
/**
@@ -37,8 +22,9 @@ class DirectLinkInputProcessor : SkeletonInputProcessor {
val bone = mutableInputSkeleton[bodyPart] ?: continue
if (bone.isRotationActive && bone.isAccelerationActive) continue
val rotation = if (!bone.isRotationActive) mutableInputSkeleton[source]?.rotation ?: bone.rotation else bone.rotation
val acceleration = if (!bone.isAccelerationActive) mutableInputSkeleton[source]?.acceleration ?: bone.acceleration else bone.acceleration
val source = mutableInputSkeleton[source]
val rotation = if (!bone.isRotationActive) source?.rotation ?: bone.rotation else bone.rotation
val acceleration = if (!bone.isAccelerationActive) source?.acceleration ?: bone.acceleration else bone.acceleration
if (rotation == bone.rotation && acceleration == bone.acceleration) continue
@@ -35,8 +35,8 @@ private val UPSAMPLING_TIME_CARRYOVER_LIMIT = 900.milliseconds
private const val SMOOTHING_MS_MAX = 50.0
// Prediction
private const val PREDICTION_MS_MAX = 32.0
private const val PREVIOUS_PREDICTION_DECAY = 0.25f
private const val PREDICTION_MS_MAX = 30.0
private const val PREVIOUS_PREDICTION_CARRYOVER = 0.2f
// Used to minimize latency even more for arm tracking where it is more noticeable
private val PART_MULTIPLIER = BodyPartMap(
@@ -100,7 +100,7 @@ private fun computePredictedRotation(
if (previousRotation == null) return targetRotation
// Use some of the previous prediction
val previousPredictionDelta = previousPredictedRotation?.localAbout(previousRotation)?.pow(PREVIOUS_PREDICTION_DECAY)
val previousPredictionDelta = previousPredictedRotation?.localAbout(previousRotation)?.pow(PREVIOUS_PREDICTION_CARRYOVER)
?: Quaternion.IDENTITY
val currentDelta = if (poseTimeDelta > Duration.ZERO) {
@@ -6,35 +6,52 @@ import dev.slimevr.skeleton.SkeletonInputProcessor
import dev.slimevr.util.Side
import dev.slimevr.util.side
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import solarxr_protocol.datatypes.BodyPart
private const val INTERMEDIATE_FROM_PROXIMAL = 2.12f
private const val DISTAL_FROM_PROXIMAL = 3.03f
private const val INTERMEDIATE_FROM_PROXIMAL_CURL = 2.12f
private const val DISTAL_FROM_PROXIMAL_CURL = 3.03f
private val PROXIMAL_REST_ROTATION = Quaternion.rotationAroundZAxis(0.15f)
private val PROXIMAL_THUMB_REST_ROTATION = Quaternion.rotationAroundXAxis(-0.15f)
private val THUMB_PARTS = arrayOf(
BodyPart.LEFT_THUMB_METACARPAL,
BodyPart.LEFT_THUMB_PROXIMAL,
BodyPart.LEFT_THUMB_DISTAL,
BodyPart.RIGHT_THUMB_METACARPAL,
BodyPart.RIGHT_THUMB_PROXIMAL,
BodyPart.RIGHT_THUMB_DISTAL,
)
private const val INTERMEDIATE_FROM_PROXIMAL = 1.04f
private const val DISTAL_FROM_PROXIMAL = 1.10f
private fun getRestRotation(hand: BoneInput, finger: BoneInput, multiplier: Float): Quaternion {
val isThumb = finger.bodyPart in THUMB_PARTS
val restRotation = if (isThumb) {
PROXIMAL_THUMB_REST_ROTATION
private const val REST_ANGLE = 0.15f
private fun getRestRotation(handRotation: Quaternion, axis: Vector3, multiplier: Float): Quaternion {
val restRotation = Quaternion.fromRotationVector(axis * REST_ANGLE)
return handRotation * restRotation.pow(multiplier)
}
/**
* Interpolate the forward, back and side rotation with different ratios: one ratio for forward and one ratio for back and side.
*/
private fun interpolateForwardBackSide(hand: Quaternion, finger: Quaternion, forwardRatio: Float, backSideRatio: Float, axis: Vector3): Quaternion {
// Work with the local rotation to avoid axes being ambiguous
val local = finger.localAbout(hand)
// If forward is going back, actually use the backSideRatio.
val actualForwardRatio = if (local.angleAboutR(axis) < 0f) {
backSideRatio
} else {
val side = hand.bodyPart.side
if (side == Side.RIGHT) {
PROXIMAL_REST_ROTATION.inv()
} else {
PROXIMAL_REST_ROTATION
}
forwardRatio
}
return hand.rotation * restRotation.pow(multiplier)
// Early return for optimization
if (actualForwardRatio == backSideRatio) return hand.interpQ(finger, backSideRatio)
// Decompose the local rotation into its twist (forward) and its swing (side) along the axis
val forward = local.project(axis).unit()
val side = local / forward
// Scale each axis of the local rotation with our ratios
val scaledForward = forward.pow(actualForwardRatio)
val scaledSide = side.pow(backSideRatio)
// Recompose the local rotation. We removed forward from local rotation to get side, so we must add forward to side back.
val scaledLocal = scaledSide * scaledForward
// Return scaled local rotation applied to From rotation
return scaledLocal.globalAbout(hand)
}
/**
@@ -46,59 +63,102 @@ class FingersInputProcessor : SkeletonInputProcessor {
val proximal: BodyPart,
val intermediate: BodyPart,
val distal: BodyPart,
val axis: Vector3,
val isThumb: Boolean = false,
)
private val fingers = arrayOf(
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_THUMB_METACARPAL, BodyPart.LEFT_THUMB_PROXIMAL, BodyPart.LEFT_THUMB_DISTAL, Vector3.NEG_X, true),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_INDEX_PROXIMAL, BodyPart.LEFT_INDEX_INTERMEDIATE, BodyPart.LEFT_INDEX_DISTAL, Vector3.POS_Z),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_MIDDLE_PROXIMAL, BodyPart.LEFT_MIDDLE_INTERMEDIATE, BodyPart.LEFT_MIDDLE_DISTAL, Vector3.POS_Z),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_RING_PROXIMAL, BodyPart.LEFT_RING_INTERMEDIATE, BodyPart.LEFT_RING_DISTAL, Vector3.POS_Z),
Finger(BodyPart.LEFT_HAND, BodyPart.LEFT_LITTLE_PROXIMAL, BodyPart.LEFT_LITTLE_INTERMEDIATE, BodyPart.LEFT_LITTLE_DISTAL, Vector3.POS_Z),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_THUMB_METACARPAL, BodyPart.RIGHT_THUMB_PROXIMAL, BodyPart.RIGHT_THUMB_DISTAL, Vector3.NEG_X, true),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_INDEX_PROXIMAL, BodyPart.RIGHT_INDEX_INTERMEDIATE, BodyPart.RIGHT_INDEX_DISTAL, Vector3.NEG_Z),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_MIDDLE_PROXIMAL, BodyPart.RIGHT_MIDDLE_INTERMEDIATE, BodyPart.RIGHT_MIDDLE_DISTAL, Vector3.NEG_Z),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_RING_PROXIMAL, BodyPart.RIGHT_RING_INTERMEDIATE, BodyPart.RIGHT_RING_DISTAL, Vector3.NEG_Z),
Finger(BodyPart.RIGHT_HAND, BodyPart.RIGHT_LITTLE_PROXIMAL, BodyPart.RIGHT_LITTLE_INTERMEDIATE, BodyPart.RIGHT_LITTLE_DISTAL, Vector3.NEG_Z),
)
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for (finger in fingers) {
val hand = mutableInputSkeleton[finger.hand] ?: continue
val handRotation = mutableInputSkeleton[finger.hand]?.rotation ?: continue
val proximal = mutableInputSkeleton[finger.proximal] ?: continue
val intermediate = mutableInputSkeleton[finger.intermediate] ?: continue
val distal = mutableInputSkeleton[finger.distal] ?: continue
// Proximal
if (!proximal.isRotationActive) {
// Missing proximal bone. Impute it from intermediate > distal > hand
val newRotation = if (intermediate.isRotationActive) {
hand.rotation.interpQ(intermediate.rotation, 1f / INTERMEDIATE_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
intermediate.rotation,
1f / INTERMEDIATE_FROM_PROXIMAL_CURL,
1f / INTERMEDIATE_FROM_PROXIMAL,
finger.axis,
)
} else if (distal.isRotationActive) {
hand.rotation.interpQ(distal.rotation, 1f / DISTAL_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
distal.rotation,
1f / DISTAL_FROM_PROXIMAL_CURL,
1f / DISTAL_FROM_PROXIMAL,
finger.axis,
)
} else {
getRestRotation(hand, proximal, 1f)
getRestRotation(handRotation, finger.axis, 1f)
}
mutableInputSkeleton[finger.proximal] = proximal.copy(rotation = newRotation)
}
// Intermediate
if (!intermediate.isRotationActive) {
// Missing intermediate bone. Impute it from distal > proximal > hand
val newRotation = if (distal.isRotationActive) {
hand.rotation.interpQ(distal.rotation, INTERMEDIATE_FROM_PROXIMAL / DISTAL_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
distal.rotation,
INTERMEDIATE_FROM_PROXIMAL_CURL / DISTAL_FROM_PROXIMAL_CURL,
INTERMEDIATE_FROM_PROXIMAL / DISTAL_FROM_PROXIMAL,
finger.axis,
)
} else if (proximal.isRotationActive) {
hand.rotation.interpQ(proximal.rotation, INTERMEDIATE_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
proximal.rotation,
INTERMEDIATE_FROM_PROXIMAL_CURL,
INTERMEDIATE_FROM_PROXIMAL,
finger.axis,
)
} else {
getRestRotation(hand, proximal, INTERMEDIATE_FROM_PROXIMAL)
getRestRotation(handRotation, finger.axis, INTERMEDIATE_FROM_PROXIMAL_CURL)
}
mutableInputSkeleton[finger.intermediate] = intermediate.copy(rotation = newRotation)
}
// Distal
if (!distal.isRotationActive) {
// Missing distal bone. Impute it from intermediate > proximal > hand
val newRotation = if (intermediate.isRotationActive) {
hand.rotation.interpQ(intermediate.rotation, DISTAL_FROM_PROXIMAL / INTERMEDIATE_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
intermediate.rotation,
DISTAL_FROM_PROXIMAL_CURL / INTERMEDIATE_FROM_PROXIMAL_CURL,
DISTAL_FROM_PROXIMAL / INTERMEDIATE_FROM_PROXIMAL,
finger.axis,
)
} else if (proximal.isRotationActive) {
hand.rotation.interpQ(proximal.rotation, DISTAL_FROM_PROXIMAL)
interpolateForwardBackSide(
handRotation,
proximal.rotation,
DISTAL_FROM_PROXIMAL_CURL,
DISTAL_FROM_PROXIMAL,
finger.axis,
)
} else {
getRestRotation(hand, proximal, DISTAL_FROM_PROXIMAL)
getRestRotation(handRotation, finger.axis, DISTAL_FROM_PROXIMAL_CURL)
}
mutableInputSkeleton[finger.distal] = distal.copy(rotation = newRotation)
}
@@ -8,8 +8,8 @@ import solarxr_protocol.datatypes.BodyPart
// Neck bends less when looking up
private const val UP_RATIO = 0.74f
// Neck bends slightly more when looking down.
private const val DOWN_RATIO = 1.14f
// Neck bends more when looking down.
private const val DOWN_RATIO = 1.25f
/**
* Guesses where the neck is supposed to be when the user has a head tracker but no neck tracker.
@@ -43,9 +43,9 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_CHEST to Reliability(-11.5f, -20f), // Itself
// To
SpineSource.LOWER_CHEST to Reliability(-6f, -15f, 0f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 4f, 0.4f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 4f, 0.44f),
SpineSource.LOWER_WAIST to Reliability(2f, 5f, 0.4f),
SpineSource.HIP to Reliability(4f, 6.25f, 0.35f),
SpineSource.HIP to Reliability(4f, 6.25f, 0.4f),
SpineSource.UPPER_LEGS to Reliability(4f, 5f),
),
SpineSource.LOWER_CHEST to arrayOf(
@@ -53,9 +53,9 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_CHEST to Reliability(-18f, 40f),
SpineSource.LOWER_CHEST to Reliability(30f), // Itself
// To
SpineSource.UPPER_WAIST to Reliability(1.5f, 10f, 0.4f),
SpineSource.UPPER_WAIST to Reliability(1.5f, 10f, 0.44f),
SpineSource.LOWER_WAIST to Reliability(2f, 8f, 0.4f),
SpineSource.HIP to Reliability(4f, 7.25f, 0.35f),
SpineSource.HIP to Reliability(4f, 7.25f, 0.4f),
SpineSource.UPPER_LEGS to Reliability(4f, 6f),
),
SpineSource.UPPER_WAIST to arrayOf(
@@ -65,7 +65,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_WAIST to Reliability(40f), // Itself
// To
SpineSource.LOWER_WAIST to Reliability(16f, 18f, 0.85f),
SpineSource.HIP to Reliability(4.5f, 13.5f, 0.87f),
SpineSource.HIP to Reliability(4.5f, 13.5f, 0.88f),
SpineSource.UPPER_LEGS to Reliability(0.25f, 12f),
),
SpineSource.LOWER_WAIST to arrayOf(
@@ -75,7 +75,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.UPPER_WAIST to Reliability(25f),
SpineSource.LOWER_WAIST to Reliability(38f), // Itself
// To
SpineSource.HIP to Reliability(5.25f, 13f, 0.87f),
SpineSource.HIP to Reliability(5.25f, 13f, 0.88f),
SpineSource.UPPER_LEGS to Reliability(1.75f, 11f),
),
SpineSource.HIP to arrayOf(
@@ -84,7 +84,7 @@ private val SPINE_SOURCE_RELIABILITY = arrayOf(
SpineSource.LOWER_CHEST to Reliability(9.75f, 9.25f),
SpineSource.UPPER_WAIST to Reliability(13f, 20f),
SpineSource.LOWER_WAIST to Reliability(14f, 30f),
SpineSource.HIP to Reliability(38f, 60f, 0.92f), // Itself
SpineSource.HIP to Reliability(38f, 60f), // Itself
// To
SpineSource.UPPER_LEGS to Reliability(7f, 17f),
),
@@ -239,22 +239,22 @@ private fun interpolateRatio(fromUpperToLower: Float, curvature: Float, fromReli
private fun interpolateForwardSide(fromRotation: Quaternion, toRotation: Quaternion, forwardRatio: Float, sideRatio: Float?): Quaternion {
if (sideRatio == null) return fromRotation.interpQ(toRotation, forwardRatio)
// Work with the rotation delta to avoid axes being ambiguous
val delta = fromRotation.inv() * toRotation
// Work with the local rotation to avoid axes being ambiguous
val local = toRotation.localAbout(fromRotation)
// Decompose the delta into its twist (forward) and swing (remaining/sides) along the x-axis
val forward = delta.project(Vector3.POS_X).unit()
val side = delta / forward
// Decompose the local rotation into its twist (forward) and swing (remaining/sides) along the x-axis
val forward = local.project(Vector3.POS_X).unit()
val side = local / forward
// Scale each axis of the delta with our ratios
// Scale each axis of the local rotation with our ratios
val scaledForward = forward.pow(forwardRatio)
val scaledSide = side.pow(sideRatio)
// Recompose the delta. We removed formward from delta to get side, so we must add forward to side back.
val scaledDelta = scaledSide * scaledForward
// Recompose the local rotation. We removed forward from local rotation to get side, so we must add forward to side back.
val scaledLocal = scaledSide * scaledForward
// Return scaled delta applied to From rotation
return fromRotation * scaledDelta
// Return scaled local rotation applied to From rotation
return scaledLocal.globalAbout(fromRotation)
}
/**
@@ -1,17 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
/**
* Handles tracker offset. For example, an HMD's rotation will be about 10cm in front of the head bone.
*/
class BoneOffsetInputProcessor : SkeletonInputProcessor {
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
for ((bodyPart, bone) in mutableInputSkeleton) {
if (bone.boneOffset.isZero()) continue
val localOffset = bone.rotation.sandwich(bone.boneOffset)
mutableInputSkeleton[bodyPart] = bone.copy(position = bone.position?.plus(localOffset))
}
}
}
@@ -1,51 +0,0 @@
package dev.slimevr.skeleton.inputprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.InputSkeleton
import dev.slimevr.skeleton.SkeletonInputProcessor
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
/**
* Rotates the first Quaternion to match its roll to the rotation of
* the second Quaternion
*
* @param from the first Quaternion
* @param to the second Quaternion
* @return the rotated Quaternion
*/
private fun alignRoll(from: Quaternion, to: Quaternion): Quaternion {
val r = to.inv() * from
val c = Quaternion(r.w, 0f, -r.y, 0f)
return (to * r * c).unit()
}
/**
* Handles rotating the upper legs' roll to match the lower legs' roll.
*/
class UpperLegsRollAlignInputProcessor(val settings: Settings) : SkeletonInputProcessor {
/**
* First value is the BodyPart to be aligned.
*
* Second value is a source BodyPart
*/
private val bodyPartToSources = arrayOf(
BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_LOWER_LEG,
)
override fun process(mutableInputSkeleton: InputSkeleton, skeletonHeight: Float) {
val ratio = settings.context.state.value.data.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs
if (ratio == 0f) return
// Upper legs are written, lower legs are read, so the two never overlap
for (bodyPartToSource in bodyPartToSources) {
val bone = mutableInputSkeleton[bodyPartToSource.first] ?: continue
if (!bone.isRotationActive) continue
val sourceRotation = mutableInputSkeleton[bodyPartToSource.second]?.rotation ?: continue
val alignedRotation = alignRoll(bone.rotation, sourceRotation)
mutableInputSkeleton[bodyPartToSource.first] = bone.copy(rotation = bone.rotation.interpR(alignedRotation, ratio))
}
}
}
@@ -4,11 +4,12 @@ import dev.slimevr.Phase1ContextProvider
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.skeleton.computedprocessors.UpperLegsTwistComputedProcessor
import dev.slimevr.skeleton.computedprocessors.VelocityComputedProcessor
import dev.slimevr.skeleton.fkprocessors.FootPlantFkProcessor
import dev.slimevr.skeleton.fkprocessors.LocalizerFkProcessor
import dev.slimevr.skeleton.fkprocessors.ToeSnapFkProcessor
import dev.slimevr.skeleton.inputprocessors.BoneOffsetInputProcessor
import dev.slimevr.skeleton.inputprocessors.ArmsInputProcessor
import dev.slimevr.skeleton.inputprocessors.ConstraintInputProcessor
import dev.slimevr.skeleton.inputprocessors.DirectLinkInputProcessor
import dev.slimevr.skeleton.inputprocessors.FallbackInputProcessor
@@ -18,7 +19,6 @@ import dev.slimevr.skeleton.inputprocessors.HeadPositionFallbackInputProcessor
import dev.slimevr.skeleton.inputprocessors.NeckInputProcessor
import dev.slimevr.skeleton.inputprocessors.SpineInputProcessor
import dev.slimevr.skeleton.inputprocessors.ToesInputProcessor
import dev.slimevr.skeleton.inputprocessors.UpperLegsRollAlignInputProcessor
import dev.slimevr.skeleton.targetprocessors.FloorClipTargetProcessor
import dev.slimevr.skeleton.targetprocessors.PositionalTargetProcessor
import dev.slimevr.skeleton.targetprocessors.SkatingCorrectionTargetProcessor
@@ -47,7 +47,6 @@ data class BoneInput(
val bodyPart: BodyPart,
val headOffset: Vector3,
val offset: Vector3,
val boneOffset: Vector3,
val poseTime: ComparableTimeMark?,
val rotation: Quaternion,
val acceleration: Vector3,
@@ -63,7 +62,6 @@ data class BoneState(
val bodyPart: BodyPart,
val headOffset: Vector3,
val offset: Vector3,
val boneOffset: Vector3,
val rotation: Quaternion,
val acceleration: Vector3,
val headPosition: Vector3,
@@ -113,7 +111,6 @@ val DEFAULT_BONE_INPUT = BoneInput(
bodyPart = BodyPart.NONE,
headOffset = Vector3.ZERO,
offset = Vector3.ZERO,
boneOffset = Vector3.ZERO,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
@@ -154,7 +151,6 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO
bodyPart = bone.bodyPart,
headOffset = bone.headOffset,
offset = bone.offset,
boneOffset = bone.boneOffset,
rotation = bone.rotation,
acceleration = bone.acceleration,
headPosition = headPosition,
@@ -167,7 +163,7 @@ fun buildBone(bone: BoneInput, parentBone: BoneState?, velocity: Velocity = ZERO
/**
* Runs FK from boneInputs, mutating the passed bones.
*/
fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton, changedParts: Set<BodyPart> = headPartSet) {
fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton, changedParts: Collection<BodyPart> = headPartSet) {
for (bodyPart in highestBodyParts(changedParts)) {
for ((parentPart, childPart) in iterateBodyPartHierarchy(bodyPart, false)) {
val rawBone = boneInputs[childPart] ?: continue
@@ -180,7 +176,6 @@ fun buildBones(mutableBones: BodyPartMap<BoneState>, boneInputs: InputSkeleton,
sealed interface SkeletonActions {
data class SetBonePose(
val bodyPart: BodyPart,
val boneOffset: Vector3?,
val rotation: Quaternion?,
val acceleration: Vector3?,
val position: Vector3?,
@@ -191,6 +186,7 @@ sealed interface SkeletonActions {
data class PauseTracking(val pause: Boolean) : SkeletonActions
data class SetPausedBoneInputs(val pausedBoneInputs: InputSkeleton) : SkeletonActions
data object ResetHeadPosition : SkeletonActions
data object RecenterHeadPosition : SkeletonActions
data object ResetFloorLevel : SkeletonActions
data class RequestProcessorReset(val resetType: ResetType) : SkeletonActions
data class ProcessorResetsApplied(val count: Int) : SkeletonActions
@@ -273,13 +269,12 @@ class Skeleton(
// Run before FK on the inputs
inputProcessors = listOf(
FilteringInputProcessor(settings),
BoneOffsetInputProcessor(),
HeadPositionFallbackInputProcessor(),
FallbackInputProcessor(),
SpineInputProcessor(settings),
NeckInputProcessor(),
UpperLegsRollAlignInputProcessor(settings),
DirectLinkInputProcessor(),
ArmsInputProcessor(),
FingersInputProcessor(),
ToesInputProcessor(),
ConstraintInputProcessor(settings),
@@ -302,6 +297,7 @@ class Skeleton(
),
// Run on the result of IK and persist.
ikComputedProcessors = listOf(
UpperLegsTwistComputedProcessor(settings),
VelocityComputedProcessor(),
),
),
@@ -11,7 +11,6 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = action.boneOffset ?: bone.boneOffset,
poseTime = timeSource.markNow(),
rotation = action.rotation ?: bone.rotation,
acceleration = action.acceleration ?: bone.acceleration,
@@ -29,7 +28,6 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(
boneInputs = state.boneInputs.mutateCopy {
it[action.bodyPart] = bone.copy(
boneOffset = Vector3.ZERO,
poseTime = null,
rotation = Quaternion.IDENTITY,
acceleration = Vector3.ZERO,
@@ -70,6 +68,16 @@ fun reduce(state: SkeletonState, action: SkeletonActions): SkeletonState = when
state.copy(boneInputs = state.boneInputs.mutateCopy { it[BodyPart.HEAD] = headBone.copy(position = null) })
}
is SkeletonActions.RecenterHeadPosition -> {
val headBone = state.boneInputs[BodyPart.HEAD] ?: return state
if (headBone.isPositionActive) return state
state.copy(
boneInputs = state.boneInputs.mutateCopy { bones ->
bones[BodyPart.HEAD] = headBone.copy(position = headBone.position?.let { Vector3(0f, it.y, 0f) })
},
)
}
is SkeletonActions.ResetFloorLevel -> {
val skeletonHeight = state.skeletonHeight
val headHeight = state.boneInputs[BodyPart.HEAD]?.position?.y ?: skeletonHeight
@@ -16,7 +16,6 @@ class FloorClipTargetProcessor(
BodyPart.RIGHT_LOWER_LEG,
),
) : SkeletonTargetProcessor {
// TODO don't just correct ankles, also correct some of the hip (20% in old code). Probably to be done on IK directly.
override fun process(mutableIkTargets: IKTargets, inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) {
if (!skeleton.effectiveFloorClip) return
@@ -1,6 +1,7 @@
package dev.slimevr.skeleton.targetprocessors
import dev.slimevr.config.Settings
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.ComputedSkeleton
import dev.slimevr.skeleton.IKTargets
import dev.slimevr.skeleton.InputSkeleton
@@ -12,6 +13,24 @@ import kotlin.collections.set
val POSITIONAL_IK_TARGETS = arrayOf(
BodyPart.LEFT_HAND to BodyPart.LEFT_LOWER_ARM,
BodyPart.RIGHT_HAND to BodyPart.RIGHT_LOWER_ARM,
// BodyPart.HIP to BodyPart.LOWER_WAIST,
BodyPart.LEFT_UPPER_LEG to BodyPart.LEFT_UPPER_LEG,
BodyPart.RIGHT_UPPER_LEG to BodyPart.RIGHT_UPPER_LEG,
BodyPart.LEFT_LOWER_LEG to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_LOWER_LEG to BodyPart.RIGHT_LOWER_LEG,
BodyPart.LEFT_FOOT to BodyPart.LEFT_LOWER_LEG,
BodyPart.RIGHT_FOOT to BodyPart.RIGHT_LOWER_LEG,
)
val requiredInactive = BodyPartMap(
mapOf(
BodyPart.LEFT_HAND to arrayOf(BodyPart.LEFT_SHOULDER, BodyPart.LEFT_UPPER_ARM, BodyPart.LEFT_LOWER_ARM),
BodyPart.RIGHT_HAND to arrayOf(BodyPart.RIGHT_SHOULDER, BodyPart.RIGHT_UPPER_ARM, BodyPart.RIGHT_LOWER_ARM),
),
)
// Target IK to positional trackers
@@ -19,20 +38,13 @@ class PositionalTargetProcessor(
val settings: Settings,
val bodyParts: Array<Pair<BodyPart, BodyPart>> = POSITIONAL_IK_TARGETS,
) : SkeletonTargetProcessor {
val requiredInactive = arrayOf(
BodyPart.LEFT_LOWER_ARM,
BodyPart.LEFT_UPPER_ARM,
BodyPart.RIGHT_LOWER_ARM,
BodyPart.RIGHT_UPPER_ARM,
)
override fun process(mutableIkTargets: IKTargets, inputSkeleton: InputSkeleton, fk: ComputedSkeleton, floorLevel: Float) {
if (!settings.context.state.value.data.skeletonConfig.toggles.useTrackerPositions) return
// TODO Use active rotations as IK constraints instead and fill in the blanks
// Disable if you have arm trackers
if (requiredInactive.any { inputSkeleton[it]?.isRotationActive == true }) return
for ((bodyPart, target) in bodyParts) {
// TODO Use active rotations as IK constraints instead and fill in the blanks
// Disable if you have arm trackers
if (requiredInactive[bodyPart]?.any { inputSkeleton[it]?.isRotationActive == true } == true) continue
mutableIkTargets[target] = inputSkeleton[bodyPart]?.position ?: continue
}
}
@@ -47,7 +47,7 @@ const val UNLOCK_WARMUP_MAX = 0.050f
// The distance correction scales with the linear velocity and distance from locked position
const val DISTANCE_MIN = 0.01f
const val DISTANCE_MAX = 0.1f
const val DISTANCE_CORRECTION_MIN = 0f
const val DISTANCE_CORRECTION_MIN = 0.05f
const val DISTANCE_CORRECTION_MAX = 1f
// The correction speed accelerates with time
@@ -310,10 +310,8 @@ class SkatingCorrectionTargetProcessor(val settings: Settings, val skeleton: Ske
}
override fun reset(resetType: ResetType) {
if (resetType == ResetType.FULL) {
lastProcessTime = timeSource.markNow()
lockState.clear()
releaseSmoothing.clear()
}
lastProcessTime = timeSource.markNow()
lockState.clear()
releaseSmoothing.clear()
}
}
@@ -54,7 +54,7 @@ private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMas
trackerId = tracker.id.toUShort(),
status = if (trackerMask.status) tracker.status else TrackerStatus.NONE,
rotation = if (trackerMask.rotation) tracker.rawRotation.toQuat() else null,
position = if (trackerMask.position && tracker.position != null) tracker.position.toVec3f() else null,
position = if (trackerMask.position && tracker.rawPosition != null) tracker.rawPosition.toVec3f() else null,
info = if (trackerMask.info) {
TrackerInfo(
isImu = tracker.imuType != null,
@@ -67,7 +67,6 @@ private fun createTracker(device: DeviceState, tracker: TrackerState, trackerMas
customName = tracker.customName,
lastMountingMethod = tracker.lastMountingMethod,
magnetometer = tracker.magStatus,
dataType = tracker.trackerDataType,
boneOffset = (tracker.boneOffsets[tracker.bodyPart] ?: Vector3.ZERO).toVec3f(),
)
} else {
@@ -11,6 +11,7 @@ import dev.slimevr.solarxr.toQuaternion
import dev.slimevr.solarxr.toVector3
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.driverTrackerHardwareId
import dev.slimevr.util.inFloatingSeconds
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Quaternion
@@ -100,9 +101,10 @@ class DriverIncomingTrackersBehaviour(
return@onDriverMessage
}
val hardwareId = req.hardwareIdentifier
val trackerHardwareId = driverTrackerHardwareId(hardwareId)
val existing = server.context.state.value.trackers.values
.find { it.context.state.value.hardwareId == hardwareId }
.find { it.context.state.value.hardwareId == trackerHardwareId }
if (existing != null) {
val trackerState = existing.context.state.value
// Tracker is in use by another driver right now
@@ -149,7 +151,7 @@ class DriverIncomingTrackersBehaviour(
intendedBodyPart = req.bodyPart,
intendedBoneOffset = offset?.boneOffset,
deviceId = deviceId,
hardwareId = hardwareId,
hardwareId = trackerHardwareId,
origin = DeviceOrigin.DRIVER,
driverName = driverName,
appContext = appContext,
@@ -189,8 +191,8 @@ class DriverIncomingTrackersBehaviour(
val trackerId = event.trackerId.toInt()
if (trackerId == 0) return@on
// Map velocity to accel
val acceleration = event.linearVelocity?.let { velocity ->
// use linear acceleration if available, otherwise use calculated acceleration from velocity
val acceleration = event.linearAcceleration?.toVector3() ?: event.linearVelocity?.let { velocity ->
val now = timeSource.markNow()
val velocity = velocity.toVector3()
val lastVelocity = lastVelocities[trackerId]
@@ -36,9 +36,9 @@ import dev.slimevr.solarxr.rpc.SettingsResetBehaviour
import dev.slimevr.solarxr.rpc.SkeletonProportionsBehaviour
import dev.slimevr.solarxr.rpc.SkeletonSettingsBehaviour
import dev.slimevr.solarxr.rpc.StayAlignedBehaviour
import dev.slimevr.solarxr.rpc.TapDetectionBehaviour
import dev.slimevr.solarxr.rpc.TelemetryBehaviour
import dev.slimevr.solarxr.rpc.TimeoutSettingsBehaviour
import dev.slimevr.solarxr.rpc.TrackerActionBehaviour
import dev.slimevr.solarxr.rpc.TrackerImuTelemetryBehaviour
import dev.slimevr.solarxr.rpc.TrackingChecklistBehaviour
import dev.slimevr.solarxr.rpc.UpdateTrackerBehaviour
@@ -190,7 +190,7 @@ class SolarXRBridge(
)
}
add(ResetsBehaviour(appContext.config.settings))
add(TapDetectionBehaviour(appContext.config.settings, appContext.tapDetectionManager))
add(TrackerActionBehaviour(appContext.config.settings, appContext.trackerActionManager))
add(VrcOscBehaviour(appContext.config.settings, appContext.vrcOscManager))
add(VmcBehaviour(appContext.config.settings, appContext.vmcManager))
add(HeightCalibrationBehaviour(appContext.heightCalibrationManager))
@@ -4,6 +4,7 @@ import dev.slimevr.AppContextProvider
import dev.slimevr.VRServer
import dev.slimevr.skeleton.BODY_PART_IK_CHAIN_MAP
import dev.slimevr.skeleton.BodyPartMap
import dev.slimevr.skeleton.inputprocessors.ARM_TO_SOURCE
import dev.slimevr.skeleton.inputprocessors.BONE_DIRECT_LINK_SOURCES
import dev.slimevr.skeleton.inputprocessors.SPINE_IMPUTED_PARTS
import dev.slimevr.skeleton.iterateBodyPartHierarchy
@@ -27,6 +28,11 @@ import solarxr_protocol.rpc.BodyPartPrerequisitesResponse
import solarxr_protocol.rpc.BodyPartRequirement
private val DIRECT_LINK_SOURCE_OF: BodyPartMap<BodyPart> = BodyPartMap(BONE_DIRECT_LINK_SOURCES.toMap())
private val ARM_SOURCE_OF: BodyPartMap<List<BodyPart>> = BodyPartMap(
ARM_TO_SOURCE.associate { armSource ->
armSource.first to armSource.second.mapNotNull { if (it.reliable) it.bodyPart else null }
},
)
// Finger and toe bones. Their processors impute each one from its siblings, so one is never a
// prerequisite for another: only the hand or foot they hang off is.
@@ -53,8 +59,8 @@ private fun trackingPointsFlow(server: VRServer): Flow<List<TrackingPoint>> = al
* List the bones that are solved by IK
*
* TODO: Ahead of the solver. [dev.slimevr.skeleton.targetprocessors.PositionalTargetProcessor] still
* drops the IK once any arm bone has a tracker, so a controller plus an upper arm leaves the
* forearm copying the upper arm.
* drops the IK once any arm bone has a tracker, so a controller plus an upper arm leaves the
* forearm copying the upper arm.
*/
internal fun ikSolvedParts(trackers: List<TrackingPoint>, useTrackerPositions: Boolean): Set<BodyPart> {
if (!useTrackerPositions) return emptySet()
@@ -96,8 +102,9 @@ private fun limbPrerequisites(bodyPart: BodyPart): List<List<BodyPart>> {
var ancestor = parentOf(bodyPart)
while (ancestor != null && ancestor !in SPINE_IMPUTED_PARTS && ancestor != BodyPart.NECK) {
val source = DIRECT_LINK_SOURCE_OF[ancestor]
val followsWithoutTracker = (source != null && source in SPINE_IMPUTED_PARTS) || ancestor in DIGIT_PARTS
val directLink = DIRECT_LINK_SOURCE_OF[ancestor]
val armSources = ARM_SOURCE_OF[ancestor]
val followsWithoutTracker = directLink in SPINE_IMPUTED_PARTS || armSources?.any { it in SPINE_IMPUTED_PARTS } == true || ancestor in DIGIT_PARTS
if (!followsWithoutTracker) required.add(listOf(ancestor))
ancestor = parentOf(ancestor)
}
@@ -21,7 +21,7 @@ private fun buildSettingsDefaultsResponse(): SettingsDefaultsResponse {
skeleton = buildSkeletonSettingsResponse(settings.skeletonConfig),
resets = buildResetsSettingsResponse(settings.resetsConfig),
stayAligned = buildStayAlignedSettingsResponse(settings.stayAlignedConfig, user),
tapDetection = buildTapDetectionSettingsResponse(settings.tapDetectionConfig),
trackerAction = buildTrackerActionSettingsResponse(settings.trackerActionConfig),
timeout = buildTimeoutSettingsResponse(settings.trackersConfig),
hid = buildHidSettingsResponse(settings.hidConfig),
driver = buildDriverSettingsResponse(settings.driverConfig),
@@ -1,5 +1,6 @@
package dev.slimevr.solarxr.rpc
import dev.slimevr.config.MIN_USER_HEIGHT
import dev.slimevr.config.UserConfig
import dev.slimevr.config.UserConfigActions
import dev.slimevr.config.withDefaultProportions
@@ -29,8 +30,6 @@ import solarxr_protocol.rpc.SkeletonProportionsRequest
import solarxr_protocol.rpc.SkeletonProportionsResetAllRequest
import solarxr_protocol.rpc.SkeletonProportionsResponse
private const val MIN_HEIGHT = 0.9f
class SkeletonProportionsBehaviour(
private val userConfig: UserConfig,
private val skeleton: Skeleton,
@@ -70,7 +69,7 @@ class SkeletonProportionsBehaviour(
val headHeight = req.headHeight ?: return@on
val floorHeight = req.floorHeight ?: 0f
val height = headHeight - floorHeight
if (height >= MIN_HEIGHT) {
if (height >= MIN_USER_HEIGHT) {
userConfig.context.dispatch(
UserConfigActions.Update { withUserHeight(this, height) },
)
@@ -80,7 +79,7 @@ class SkeletonProportionsBehaviour(
receiver.rpcDispatcher.on<SkeletonProportionsResetAllRequest> {
val height = userConfig.context.state.value.data.userHeight
if (height >= MIN_HEIGHT) {
if (height >= MIN_USER_HEIGHT) {
userConfig.context.dispatch(UserConfigActions.Update { withDefaultProportions(this) })
}
}.launchIn(receiver.context.scope)
@@ -14,9 +14,12 @@ import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ChangeSkeletonSettingsRequest
import solarxr_protocol.rpc.LegTweaksTmpChange
import solarxr_protocol.rpc.LegTweaksTmpClear
import solarxr_protocol.rpc.RecenterMocapModeRequest
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.SetPauseTrackingRequest
import solarxr_protocol.rpc.SkeletonRatios
import solarxr_protocol.rpc.SkeletonSettingsRequest
@@ -142,5 +145,12 @@ class SkeletonSettingsBehaviour(
},
)
}.launchIn(receiver.context.scope)
// Reset Mocap Mode head
receiver.rpcDispatcher.on<RecenterMocapModeRequest> { _ ->
receiver.appContext.skeleton.context.dispatchAll(
listOf(SkeletonActions.RecenterHeadPosition, SkeletonActions.RequestProcessorReset(ResetType.FULL)),
)
}.launchIn(receiver.context.scope)
}
}
@@ -2,74 +2,95 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.config.TapDetectionConfig
import dev.slimevr.config.TrackerActionConfig
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.tapdetection.TapDetectionActions
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.trackeraction.TrackerActionActions
import dev.slimevr.trackeraction.TrackerActionManager
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.ChangeTapDetectionSettingsRequest
import solarxr_protocol.rpc.TapDetectionSettingsRequest
import solarxr_protocol.rpc.TapDetectionSettingsResponse
import solarxr_protocol.rpc.TapDetectionSetupModeRequest
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ChangeTrackerActionSettingsRequest
import solarxr_protocol.rpc.TrackerActionSettings
import solarxr_protocol.rpc.TrackerActionSettingsRequest
import solarxr_protocol.rpc.TrackerActionSettingsResponse
import solarxr_protocol.rpc.TrackerActionSetupModeRequest
internal fun buildTapDetectionSettingsResponse(config: TapDetectionConfig) = TapDetectionSettingsResponse(
yawResetDelay = config.yawResetDelay,
fullResetDelay = config.fullResetDelay,
mountingResetDelay = config.mountingResetDelay,
yawResetEnabled = config.yawResetEnabled,
fullResetEnabled = config.fullResetEnabled,
mountingResetEnabled = config.mountingResetEnabled,
yawResetTaps = config.yawResetTaps.toUByte(),
fullResetTaps = config.fullResetTaps.toUByte(),
mountingResetTaps = config.mountingResetTaps.toUByte(),
yawResetTracker = config.yawResetBodyPart,
fullResetTracker = config.fullResetBodyPart,
mountingResetTracker = config.mountingResetBodyPart,
numberTrackersOverThreshold = config.numberTrackersOverThreshold.toUByte(),
internal fun buildTrackerActionSettingsResponse(config: TrackerActionConfig) = TrackerActionSettingsResponse(
yawResetAction = TrackerActionSettings(
enabled = config.yawResetAction.enabled,
delay = config.yawResetAction.delay,
bodyPart = config.yawResetAction.bodyPart ?: BodyPart.NONE,
method = config.yawResetAction.method,
taps = config.yawResetAction.taps.toUByte(),
),
fullResetAction = TrackerActionSettings(
enabled = config.fullResetAction.enabled,
delay = config.fullResetAction.delay,
bodyPart = config.fullResetAction.bodyPart ?: BodyPart.NONE,
method = config.fullResetAction.method,
taps = config.fullResetAction.taps.toUByte(),
),
mountingResetAction = TrackerActionSettings(
enabled = config.mountingResetAction.enabled,
delay = config.mountingResetAction.delay,
bodyPart = config.mountingResetAction.bodyPart ?: BodyPart.NONE,
method = config.mountingResetAction.method,
taps = config.mountingResetAction.taps.toUByte(),
),
tapsTrackersOverThreshold = config.tapsTrackersOverThreshold.toUByte(),
)
class TapDetectionBehaviour(
class TrackerActionBehaviour(
private val settings: Settings,
private val tapDetectionManager: TapDetectionManager,
private val trackerActionManager: TrackerActionManager,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
// Send config
receiver.onRpc<TapDetectionSettingsRequest> { _, txId ->
receiver.sendRpc(buildTapDetectionSettingsResponse(settings.context.state.value.data.tapDetectionConfig), txId)
receiver.onRpc<TrackerActionSettingsRequest> { _, txId ->
receiver.sendRpc(buildTrackerActionSettingsResponse(settings.context.state.value.data.trackerActionConfig), txId)
}.launchIn(receiver.context.scope)
// Push config changes, including profile switches
settings.context.state
.map { buildTapDetectionSettingsResponse(it.data.tapDetectionConfig) }
.map { buildTrackerActionSettingsResponse(it.data.trackerActionConfig) }
.distinctUntilChanged()
.drop(1)
.onEach(receiver::sendRpc)
.launchIn(receiver.context.scope)
// Receive config
receiver.rpcDispatcher.on<ChangeTapDetectionSettingsRequest> { req ->
receiver.rpcDispatcher.on<ChangeTrackerActionSettingsRequest> { req ->
settings.context.dispatch(
SettingsActions.Update {
copy(
tapDetectionConfig = TapDetectionConfig(
yawResetDelay = req.yawResetDelay ?: 0f,
fullResetDelay = req.fullResetDelay ?: 0f,
mountingResetDelay = req.mountingResetDelay ?: 0f,
yawResetEnabled = req.yawResetEnabled == true,
fullResetEnabled = req.fullResetEnabled == true,
mountingResetEnabled = req.mountingResetEnabled == true,
yawResetTaps = req.yawResetTaps?.toInt() ?: 2,
fullResetTaps = req.fullResetTaps?.toInt() ?: 2,
mountingResetTaps = req.mountingResetTaps?.toInt() ?: 2,
yawResetBodyPart = req.yawResetTracker,
fullResetBodyPart = req.fullResetTracker,
mountingResetBodyPart = req.mountingResetTracker,
numberTrackersOverThreshold = req.numberTrackersOverThreshold?.toInt() ?: 1,
trackerActionConfig = TrackerActionConfig(
yawResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.yawResetAction?.enabled == true,
delay = req.yawResetAction?.delay ?: 0f,
bodyPart = req.yawResetAction?.bodyPart,
method = req.yawResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.yawResetAction?.taps?.toInt() ?: 2,
),
fullResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.fullResetAction?.enabled == true,
delay = req.fullResetAction?.delay ?: 0f,
bodyPart = req.fullResetAction?.bodyPart,
method = req.fullResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.fullResetAction?.taps?.toInt() ?: 2,
),
mountingResetAction = dev.slimevr.config.TrackerActionSettings(
enabled = req.mountingResetAction?.enabled == true,
delay = req.mountingResetAction?.delay ?: 0f,
bodyPart = req.mountingResetAction?.bodyPart,
method = req.mountingResetAction?.method ?: TrackerActionMethod.TAP,
taps = req.mountingResetAction?.taps?.toInt() ?: 2,
),
tapsTrackersOverThreshold = req.tapsTrackersOverThreshold.toInt(),
),
)
},
@@ -77,8 +98,8 @@ class TapDetectionBehaviour(
}.launchIn(receiver.context.scope)
// Setup Mode (tap/button press to assign)
receiver.rpcDispatcher.on<TapDetectionSetupModeRequest> { req ->
tapDetectionManager.context.dispatch(TapDetectionActions.SetSetupMode(req.setupMode == true))
receiver.rpcDispatcher.on<TrackerActionSetupModeRequest> { req ->
trackerActionManager.context.dispatch(TrackerActionActions.SetSetupMode(req.setupMode))
}.launchIn(receiver.context.scope)
}
}
@@ -8,7 +8,7 @@ import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import dev.slimevr.solarxr.toVector3
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import io.github.axisangles.ktmath.Quaternion
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetTrackerAssignments
@@ -31,7 +31,7 @@ class UpdateTrackerBehaviour(
val state = it.context.state.value
it != tracker &&
state.bodyPart == bodyPart &&
state.status.isActive()
isPresent(state.status)
}.forEach {
it.context.dispatch(
TrackerActions.Update { copy(bodyPart = null) },
@@ -1,76 +0,0 @@
package dev.slimevr.tapdetection
import dev.slimevr.Phase1ContextProvider
import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resets.ResetsManager
import dev.slimevr.tracker.Tracker
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TapDetectionSetupNotification
import kotlin.collections.listOf
data class TapDetectionState(
val setupMode: Boolean = false,
val yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
val fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
val mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
)
sealed interface TapDetectionActions {
data class SetSetupMode(val setupMode: Boolean) : TapDetectionActions
data class UpdateBodyParts(val yawResetBodyPart: BodyPart?, val fullResetBodyPart: BodyPart?, val mountingResetBodyPart: BodyPart?) : TapDetectionActions
}
typealias TapDetectionContext = Context<TapDetectionState, TapDetectionActions>
typealias TapDetectionBehaviour = Behaviour<TapDetectionManager>
class TapDetectionManager(val context: TapDetectionContext, val server: VRServer, val resetsManager: ResetsManager, val settings: Settings) {
fun startObserving() = context.observeAll(this)
suspend fun actionTriggered(trackerId: Int, sourceName: String = "TapDetection") {
val tracker = server.getTracker(trackerId) ?: return
val state = context.state.value
// If it's in setup mode, tap/button press to assign
if (state.setupMode) {
server.sendSolarxrRpc(
TapDetectionSetupNotification(
trackerId.toUShort(),
),
)
return
}
val bodyPart = tracker.context.state.value.bodyPart ?: return
val tapDetectionConfig = settings.context.state.value.data.tapDetectionConfig
val (resetType, actionDelay) = when (bodyPart) {
state.yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> ResetType.YAW to tapDetectionConfig.yawResetDelay
state.fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> ResetType.FULL to tapDetectionConfig.fullResetDelay
state.mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> ResetType.MOUNTING to tapDetectionConfig.mountingResetDelay
else -> return
}
resetsManager.scheduleReset(
sourceName,
resetType,
actionDelay,
)
}
companion object {
fun create(ctx: Phase1ContextProvider, resetsManager: ResetsManager, scope: CoroutineScope): TapDetectionManager {
val context = Context.create(
initialState = TapDetectionState(),
scope = scope,
reducer = ::reduce,
behaviours = listOf(TapDetectionBasicBehaviour()),
name = "TapDetectionManager",
)
return TapDetectionManager(context, ctx.server, resetsManager, ctx.config.settings)
}
}
}
@@ -1,6 +0,0 @@
package dev.slimevr.tapdetection
fun reduce(state: TapDetectionState, action: TapDetectionActions): TapDetectionState = when (action) {
is TapDetectionActions.SetSetupMode -> state.copy(setupMode = action.setupMode)
is TapDetectionActions.UpdateBodyParts -> state.copy(yawResetBodyPart = action.yawResetBodyPart, fullResetBodyPart = action.fullResetBodyPart, mountingResetBodyPart = action.mountingResetBodyPart)
}
@@ -3,7 +3,7 @@ package dev.slimevr.tracker.behaviours
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
@@ -15,13 +15,13 @@ class TrackerAssignmentConflictBehaviour : TrackerBehaviour {
override fun observe(receiver: Tracker) {
val server = receiver.appContext.server
receiver.context.state
.distinctUntilChanged { old, new -> old.status.isActive() == new.status.isActive() }
.distinctUntilChanged { old, new -> isPresent(old.status) == isPresent(new.status) }
.onEach { state ->
val bodyPart = state.bodyPart ?: return@onEach
val bodyPartTaken = server.context.state.value.trackers.values.any { other ->
val otherState = other.context.state.value
otherState.id != state.id && otherState.bodyPart == bodyPart && otherState.status.isActive()
otherState.id != state.id && otherState.bodyPart == bodyPart && isPresent(otherState.status)
}
if (bodyPartTaken) {
receiver.context.dispatch(TrackerActions.Update { copy(bodyPart = null) })
@@ -17,7 +17,7 @@ import kotlin.time.Duration.Companion.seconds
/**
* Detects whether a tracker is at rest or rotating.
* Used for Stay Aligned and TapDetection.
* Used for Stay Aligned.
*/
class TrackerMotionDetectionBehaviour : TrackerBehaviour {
@@ -79,8 +79,6 @@ class TrackerMotionDetectionBehaviour : TrackerBehaviour {
*/
private fun isRotating(lastRotation: RawRotation, rotation: RawRotation) = Angle.absBetween(lastRotation, rotation) > MAX_ROTATION
// TODO : these values may need fine-tuning for TapDetection
// or maybe need multiple motion detector with an abstract class
companion object {
val MAX_ROTATION = Angle.ofDeg(2f)
val ENTER_REST_TIME = 1.seconds
@@ -3,14 +3,13 @@ package dev.slimevr.tracker.behaviours
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
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.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
/**
* Marks the calibration stale when the tracker starts being used on a body part: when it connects
@@ -24,7 +23,7 @@ class TrackerStaleCalibrationBehaviour : TrackerBehaviour {
override fun observe(receiver: Tracker) {
var previous: Placement? = null
receiver.context.state
.map { Placement(it.status.isActive() || it.status == TrackerStatus.OCCLUDED, it.bodyPart) }
.map { Placement(isPresent(it.status), it.bodyPart) }
.distinctUntilChanged()
.onEach { placement ->
val last = previous
@@ -63,8 +63,6 @@ class TrackerStayAlignedBehaviour(
*/
@OptIn(ExperimentalCoroutinesApi::class)
private fun observeRun(receiver: Tracker) {
var lastRotationTime = timeSource.markNow()
val serverFlow = receiver.appContext.server.context.state
val enabledFlow = settings.context.state.map { it.data.stayAlignedConfig.enabled }.distinctUntilChanged()
@@ -76,6 +74,7 @@ class TrackerStayAlignedBehaviour(
// Ignore every other emission for performance (50FPS instead of 100FPS when at 100TPS)
var index = 0
var lastRotationTime = timeSource.markNow()
receiver.context.state
.distinctUntilChangedBy { it.rawRotation }
.filter { index++ % 2 == 0 }
@@ -5,6 +5,7 @@ import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -13,7 +14,6 @@ import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerStatus
class TrackerToSkeletonBehaviour : TrackerBehaviour {
var lastBodyPartSent: BodyPart? = null
@@ -26,7 +26,7 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
// Tell the skeleton the tracker has stopped sending data to the last bone it was sending data to.
lastBodyPartSent?.let {
val trackerState = receiver.context.state.value
if ((!trackerState.status.isActive() && trackerState.status != TrackerStatus.OCCLUDED) || trackerState.bodyPart != lastBodyPartSent) {
if (!isPresent(trackerState.status) || trackerState.bodyPart != lastBodyPartSent) {
receiver.appContext.skeleton.context.dispatch(
SkeletonActions.DisableBone(it),
)
@@ -46,7 +46,6 @@ class TrackerToSkeletonBehaviour : TrackerBehaviour {
val pendingResets = trackerState.pendingSkeletonResets
val bonePoseActions = SkeletonActions.SetBonePose(
bodyPart,
trackerState.boneOffsets[bodyPart],
trackerState.rotation,
trackerState.acceleration,
trackerState.position,
@@ -0,0 +1,7 @@
package dev.slimevr.tracker
fun udpTrackerHardwareId(deviceHardwareId: String, sensorId: Int): String = "udp:$deviceHardwareId:$sensorId"
fun hidTrackerHardwareId(address: String): String = "hid:$address"
fun driverTrackerHardwareId(hardwareIdentifier: String): String = "driver:$hardwareIdentifier"
@@ -27,11 +27,10 @@ import solarxr_protocol.datatypes.MagnetometerStatus
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
import solarxr_protocol.datatypes.hardware_info.TrackerDataType
import solarxr_protocol.rpc.ResetType
import kotlin.time.Duration
// A tracker is initialized as ROTATING to prevent TapDetection and Stay Aligned from running immediately.
// A tracker is initialized as ROTATING to prevent Stay Aligned from running immediately.
enum class Motion {
ROTATING,
RESTING,
@@ -66,7 +65,6 @@ data class TrackerState(
val intendedBodyPart: BodyPart?,
val boneOffsets: Map<BodyPart, Vector3>,
val customName: String?,
val trackerDataType: TrackerDataType, // TODO flex sensors
val lastMountingMethod: MountingMethod,
val mountingOrientation: HeadingAlignment,
val lastReference: Quaternion?,
@@ -77,6 +75,7 @@ data class TrackerState(
val rawAcceleration: RawAcceleration?,
val acceleration: CalibratedAcceleration?,
val rawMagnetometer: Vector3,
val rawPosition: Vector3?,
val position: Vector3?,
val imuTemp: Float?,
val accumulatedTicks: UShort,
@@ -209,7 +208,6 @@ class Tracker(
intendedBodyPart = null,
boneOffsets = emptyMap(),
customName = null,
trackerDataType = TrackerDataType.ROTATION,
lastMountingMethod = MountingMethod.MANUAL,
mountingOrientation = Quaternion.IDENTITY,
lastReference = Quaternion.IDENTITY,
@@ -220,6 +218,7 @@ class Tracker(
rawAcceleration = null,
acceleration = null,
rawMagnetometer = Vector3.ZERO,
rawPosition = null,
position = null,
imuTemp = null,
accumulatedTicks = 0u,
@@ -38,7 +38,7 @@ fun reduce(
// Other inputs
val rawAcceleration: RawAcceleration? = action.acceleration ?: state.rawAcceleration
val rawMagnetometer = action.magnetometer ?: state.rawMagnetometer
val position = action.position ?: state.position
val rawPosition = action.position ?: state.rawPosition
// Rotation calibration: going from raw rotation to rotation since reset
val rotation: CalibratedRotation =
@@ -67,12 +67,25 @@ fun reduce(
state.acceleration
}
val position =
if (action.position != null) {
val boneOffset = state.boneOffsets[state.bodyPart]
if (boneOffset != null) {
action.position + rotation.sandwich(boneOffset)
} else {
action.position
}
} else {
state.position
}
state.copy(
rawRotation = rawRotation,
rotation = rotation,
rawAcceleration = rawAcceleration,
acceleration = acceleration,
rawMagnetometer = rawMagnetometer,
rawPosition = rawPosition,
position = position,
accumulatedTicks = accumulatedTicks,
rotationDirty = false,
@@ -252,6 +265,7 @@ fun reduce(
state.copy(
sessionCalibration = state.sessionCalibration.copy(headingCorrection = action.heading),
yawResetSmoothing = if (action.done) null else state.yawResetSmoothing,
pendingSkeletonResets = if (action.done) state.pendingSkeletonResets + ResetType.YAW else state.pendingSkeletonResets,
rotationDirty = true,
)
}
@@ -32,22 +32,24 @@ object StayAlignedDefaults {
val IMU_TO_YAW_CORRECTION = buildMap {
// Mag is enabled on MPU9250 but server doesn't know about it
set(ImuType.MPU9250, YAW_CORRECTION_IMU_DISABLED)
set(ImuType.MPU6050, YAW_CORRECTION_IMU_BAD)
set(ImuType.MPU6500, YAW_CORRECTION_IMU_BAD)
set(ImuType.BNO055, YAW_CORRECTION_IMU_BAD)
set(ImuType.BMI160, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM20948, YAW_CORRECTION_IMU_BAD)
set(ImuType.LSM6DS3TRC, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM42688, YAW_CORRECTION_IMU_OK)
set(ImuType.BMI270, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DSO, YAW_CORRECTION_IMU_OK)
set(ImuType.BNO080, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BNO085, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BNO055, YAW_CORRECTION_IMU_BAD)
set(ImuType.MPU6050, YAW_CORRECTION_IMU_BAD)
set(ImuType.BNO086, YAW_CORRECTION_IMU_GOOD)
set(ImuType.BMI160, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM20948, YAW_CORRECTION_IMU_BAD)
set(ImuType.ICM42688, YAW_CORRECTION_IMU_OK)
set(ImuType.BMI270, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DS3TRC, YAW_CORRECTION_IMU_BAD)
set(ImuType.LSM6DSV, YAW_CORRECTION_IMU_GOOD)
set(ImuType.LSM6DSO, YAW_CORRECTION_IMU_OK)
set(ImuType.LSM6DSR, YAW_CORRECTION_IMU_GOOD)
set(ImuType.ICM45686, YAW_CORRECTION_IMU_GOOD)
set(ImuType.ICM45605, YAW_CORRECTION_IMU_GOOD)
// ADC_RESISTANCE is a flex sensor so it has no yaw drift
set(ImuType.ADC_RESISTANCE, YAW_CORRECTION_IMU_DISABLED)
set(ImuType.ICM55686, YAW_CORRECTION_IMU_GOOD)
}
@@ -1,6 +1,6 @@
package dev.slimevr.tapdetection
package dev.slimevr.trackeraction
import dev.slimevr.config.TapDetectionConfig
import dev.slimevr.config.TrackerActionConfig
import dev.slimevr.tracker.TrackerState
import dev.slimevr.util.timeSource
import io.github.axisangles.ktmath.Vector3
@@ -13,16 +13,14 @@ import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TapDetectionSetupNotification
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeMark
class TapDetectionBasicBehaviour : TapDetectionBehaviour {
class TapDetectionBehaviour : TrackerActionBehaviour {
data class TrackerTapDetectionState(
var trackerId: Int,
var performsReset: Boolean = false,
@@ -34,8 +32,8 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
// Loads TapDetection config and initializes a tracker's state
private fun createTrackerTapDetectionState(
tapDetectionConfig: TapDetectionConfig,
tapDetectionState: TapDetectionState,
tapDetectionConfig: TrackerActionConfig,
tapDetectionState: TrackerActionState,
trackerState: TrackerState,
): TrackerTapDetectionState {
// This holds a tracker's config and state for tap detection
@@ -44,19 +42,19 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
// setupMode uses defaults
if (!tapDetectionState.setupMode) {
when (trackerState.bodyPart) {
tapDetectionState.yawResetBodyPart if tapDetectionConfig.yawResetEnabled -> {
tapDetectionState.yawResetBodyPart if tapDetectionConfig.yawResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.yawResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.yawResetAction.taps
}
tapDetectionState.fullResetBodyPart if tapDetectionConfig.fullResetEnabled -> {
tapDetectionState.fullResetBodyPart if tapDetectionConfig.fullResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.fullResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.fullResetAction.taps
}
tapDetectionState.mountingResetBodyPart if tapDetectionConfig.mountingResetEnabled -> {
tapDetectionState.mountingResetBodyPart if tapDetectionConfig.mountingResetAction.enabled -> {
trackerTapDetectionState.performsReset = true
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.mountingResetTaps
trackerTapDetectionState.tapsNeeded = tapDetectionConfig.mountingResetAction.taps
}
else -> {}
@@ -82,9 +80,9 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
)
@OptIn(ExperimentalCoroutinesApi::class)
override fun observe(receiver: TapDetectionManager) {
override fun observe(receiver: TrackerActionManager) {
val tapConfigFlow = receiver.settings.context.state
.map { it.data.tapDetectionConfig }
.map { it.data.trackerActionConfig }
.distinctUntilChanged()
val setupModeFlow = receiver.context.state
.map { it.setupMode }
@@ -110,19 +108,19 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
combine(tapConfigFlow, setupModeFlow, okTrackersFlow, ::Triple).onEach { (tapDetectionConfig, setupMode, trackers) ->
if (setupMode) {
receiver.context.dispatch(TapDetectionActions.UpdateBodyParts(null, null, null))
receiver.context.dispatch(TrackerActionActions.UpdateBodyParts(null, null, null))
return@onEach
}
val trackersBodyParts = trackers.map { it.context.state.value.bodyPart }.toSet()
val yawResetBodyPart = arrayOf(tapDetectionConfig.yawResetBodyPart, BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.HIP, BodyPart.LOWER_WAIST, BodyPart.UPPER_WAIST)
val yawResetBodyPart = arrayOf(tapDetectionConfig.yawResetAction.bodyPart, BodyPart.UPPER_CHEST, BodyPart.LOWER_CHEST, BodyPart.HIP, BodyPart.UPPER_WAIST, BodyPart.LOWER_WAIST)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.UPPER_CHEST
val fullResetBodyPart = arrayOf(tapDetectionConfig.fullResetBodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG)
val fullResetBodyPart = arrayOf(tapDetectionConfig.fullResetAction.bodyPart, BodyPart.LEFT_UPPER_LEG, BodyPart.LEFT_LOWER_LEG)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.LEFT_UPPER_LEG
val mountingResetBodyPart = arrayOf(tapDetectionConfig.mountingResetBodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG)
val mountingResetBodyPart = arrayOf(tapDetectionConfig.mountingResetAction.bodyPart, BodyPart.RIGHT_UPPER_LEG, BodyPart.RIGHT_LOWER_LEG)
.firstOrNull { it in trackersBodyParts } ?: BodyPart.RIGHT_UPPER_LEG
receiver.context.dispatch(TapDetectionActions.UpdateBodyParts(yawResetBodyPart, fullResetBodyPart, mountingResetBodyPart))
receiver.context.dispatch(TrackerActionActions.UpdateBodyParts(yawResetBodyPart, fullResetBodyPart, mountingResetBodyPart))
}.launchIn(receiver.context.scope)
// Outer flow is refreshed whenever TapDetection config, setupMode, or a tracker's bodyPart or status changes
@@ -134,7 +132,7 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
)
.flatMapLatest { (tapDetectionConfig, tapDetectionState, trackers) ->
// To keep track of which trackers are moving
val numberTrackersOverThreshold = tapDetectionConfig.numberTrackersOverThreshold
val tapsTrackersOverThreshold = tapDetectionConfig.tapsTrackersOverThreshold
val bodyPartsToCheck = falsePositiveBodyParts + tapDetectionState.yawResetBodyPart + tapDetectionState.fullResetBodyPart + tapDetectionState.mountingResetBodyPart
val trackersOverThreshold = mutableSetOf<Int>()
@@ -169,14 +167,14 @@ class TapDetectionBasicBehaviour : TapDetectionBehaviour {
val othersOverThreshold = trackersOverThreshold.count() - if (isOverThreshold) 1 else 0
val tapTriggered = runTapDetection(
timeSource.markNow(),
othersOverThreshold >= numberTrackersOverThreshold,
othersOverThreshold >= tapsTrackersOverThreshold,
trackerTapDetectionState,
rawAcceleration,
thresholdMultiplier,
)
if (tapTriggered) {
receiver.actionTriggered(trackerTapDetectionState.trackerId)
receiver.actionTriggered(trackerTapDetectionState.trackerId, "TapDetection", TrackerActionMethod.TAP)
}
}
}
@@ -0,0 +1,83 @@
package dev.slimevr.trackeraction
import dev.slimevr.Phase1ContextProvider
import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.context.Behaviour
import dev.slimevr.context.Context
import dev.slimevr.resets.ResetsManager
import kotlinx.coroutines.CoroutineScope
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerActionMethod
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.TrackerActionSetupNotification
import kotlin.collections.listOf
data class TrackerActionState(
val setupMode: Boolean = false,
val yawResetBodyPart: BodyPart? = BodyPart.UPPER_CHEST,
val fullResetBodyPart: BodyPart? = BodyPart.LEFT_UPPER_LEG,
val mountingResetBodyPart: BodyPart? = BodyPart.RIGHT_UPPER_LEG,
)
sealed interface TrackerActionActions {
data class SetSetupMode(val setupMode: Boolean) : TrackerActionActions
data class UpdateBodyParts(val yawResetBodyPart: BodyPart?, val fullResetBodyPart: BodyPart?, val mountingResetBodyPart: BodyPart?) : TrackerActionActions
}
typealias TrackerActionContext = Context<TrackerActionState, TrackerActionActions>
typealias TrackerActionBehaviour = Behaviour<TrackerActionManager>
class TrackerActionManager(val context: TrackerActionContext, val server: VRServer, val resetsManager: ResetsManager, val settings: Settings) {
fun startObserving() = context.observeAll(this)
suspend fun actionTriggered(trackerId: Int, sourceName: String, sourceMethod: TrackerActionMethod) {
val tracker = server.getTracker(trackerId) ?: return
val state = context.state.value
// If it's in setup mode, tap/button press to assign
if (state.setupMode) {
server.sendSolarxrRpc(
TrackerActionSetupNotification(
trackerId.toUShort(),
),
)
return
}
val bodyPart = tracker.context.state.value.bodyPart ?: return
val trackerActionConfig = settings.context.state.value.data.trackerActionConfig
val (resetType, actionDelay) = when (bodyPart) {
state.yawResetBodyPart if trackerActionConfig.yawResetAction.enabled -> ResetType.YAW to trackerActionConfig.yawResetAction.delay
state.fullResetBodyPart if trackerActionConfig.fullResetAction.enabled -> ResetType.FULL to trackerActionConfig.fullResetAction.delay
state.mountingResetBodyPart if trackerActionConfig.mountingResetAction.enabled -> ResetType.MOUNTING to trackerActionConfig.mountingResetAction.delay
else -> return
}
val method = when (resetType) {
ResetType.YAW -> trackerActionConfig.yawResetAction.method
ResetType.FULL -> trackerActionConfig.fullResetAction.method
ResetType.MOUNTING -> trackerActionConfig.mountingResetAction.method
}
if (method == sourceMethod || method == TrackerActionMethod.BOTH) {
resetsManager.scheduleReset(
"TrackerAction ($sourceName)",
resetType,
actionDelay,
)
}
}
companion object {
fun create(ctx: Phase1ContextProvider, resetsManager: ResetsManager, scope: CoroutineScope): TrackerActionManager {
val context = Context.create(
initialState = TrackerActionState(),
scope = scope,
reducer = ::reduce,
behaviours = listOf(TapDetectionBehaviour()),
name = "TrackerActionManager",
)
return TrackerActionManager(context, ctx.server, resetsManager, ctx.config.settings)
}
}
}
@@ -0,0 +1,6 @@
package dev.slimevr.trackeraction
fun reduce(state: TrackerActionState, action: TrackerActionActions): TrackerActionState = when (action) {
is TrackerActionActions.SetSetupMode -> state.copy(setupMode = action.setupMode)
is TrackerActionActions.UpdateBodyParts -> state.copy(yawResetBodyPart = action.yawResetBodyPart, fullResetBodyPart = action.fullResetBodyPart, mountingResetBodyPart = action.mountingResetBodyPart)
}
@@ -7,6 +7,7 @@ import dev.slimevr.device.DeviceActions
import dev.slimevr.logging.AppLogger
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
import dev.slimevr.tracker.udpTrackerHardwareId
import dev.slimevr.util.udpHardwareId
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
@@ -43,7 +44,7 @@ fun getCorrectedAcceleration(acceleration: Vector3, protocolVersion: Int) = if (
internal fun assignTracker(receiver: UDPConnection, device: Device, info: SensorInfo): Tracker {
val deviceState = device.context.state.value
val deviceHardwareId = deviceState.hardwareId ?: udpHardwareId(deviceState.macAddress, deviceState.address)
val hardwareId = "$deviceHardwareId:${info.sensorId}"
val hardwareId = udpTrackerHardwareId(deviceHardwareId, info.sensorId)
val existingTracker = receiver.appContext.server.context.state.value.trackers.values
.find { t -> t.context.state.value.deviceId == deviceState.id && t.context.state.value.hardwareId == hardwareId }
@@ -6,10 +6,9 @@ import dev.slimevr.config.DevicesConfigActions
import dev.slimevr.device.Device
import dev.slimevr.logging.AppLogger
import dev.slimevr.skeleton.SkeletonActions
import dev.slimevr.util.isActive
import dev.slimevr.util.isPresent
import kotlinx.coroutines.cancel
import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.TrackerStatus
private fun findUdpDevices(appContext: AppContextProvider, predicate: (String) -> Boolean): List<Device> = appContext.server.context.state.value.devices.values.filter { device ->
val state = device.context.state.value
@@ -35,7 +34,7 @@ fun removeUdpDevice(appContext: AppContextProvider, device: Device) {
// The tracker's own skeleton behaviour dies with its scope, so release its bone here
trackerStates
.filter { it.status.isActive() || it.status == TrackerStatus.OCCLUDED }
.filter { isPresent(it.status) }
.mapNotNull { it.bodyPart }
.forEach { bodyPart ->
appContext.skeleton.context.dispatch(SkeletonActions.DisableBone(bodyPart))
@@ -3,3 +3,6 @@ package dev.slimevr.util
import solarxr_protocol.datatypes.TrackerStatus
fun TrackerStatus.isActive() = this == TrackerStatus.OK || this == TrackerStatus.SLEEPING || this == TrackerStatus.TIMED_OUT
/** Active, or occluded and expected back. A present tracker keeps its bone and its body part. */
fun isPresent(status: TrackerStatus) = status.isActive() || status == TrackerStatus.OCCLUDED
@@ -123,6 +123,8 @@ class VRCOSCManager(
context.observeAll(this)
}
// TODO limit to once every 300ms to prevent lerping on VRChat's side
// https://docs.vrchat.com/docs/osc-trackers#receiving-head-data
fun yawAlign(referenceRotation: Quaternion) {
context.scope.launch {
events.emit(VRCOSCEvent.YawAlign(referenceRotation))
@@ -39,7 +39,6 @@ import dev.slimevr.skeleton.buildBones
import dev.slimevr.solarxr.rpc.ServerInfos
import dev.slimevr.stepmounting.StepMountingManager
import dev.slimevr.stepmounting.StepMountingState
import dev.slimevr.tapdetection.TapDetectionManager
import dev.slimevr.tracker.Motion
import dev.slimevr.tracker.SessionCalibration
import dev.slimevr.tracker.StayAlignedData
@@ -48,6 +47,7 @@ import dev.slimevr.tracker.TrackerBehaviour
import dev.slimevr.tracker.behaviours.TrackerRotationRefreshBehaviour
import dev.slimevr.tracker.behaviours.TrackerStaleCalibrationBehaviour
import dev.slimevr.tracker.behaviours.TrackerTpsBehaviour
import dev.slimevr.trackeraction.TrackerActionManager
import dev.slimevr.trackingchecklist.TrackingChecklist
import dev.slimevr.udp.UdpPeer
import dev.slimevr.udp.UdpServer
@@ -315,7 +315,7 @@ abstract class TestAppContext : AppContextProvider {
override val vmcManager: VMCManager get() = error("not used in test")
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 trackerActionManager: TrackerActionManager get() = error("not used in test")
override val boneRouting: BoneRoutingManager get() = error("not used in test")
override val stepMountingManager: StepMountingManager get() = error("not used in test")
override val logSources: List<LogSourceProvider> = emptyList()
@@ -0,0 +1,45 @@
package dev.slimevr.config
import kotlinx.coroutines.test.runTest
import solarxr_protocol.datatypes.BodyPart
import kotlin.test.Test
import kotlin.test.assertEquals
class DevicesConfigMigrationTest {
@Test
fun `version 1 tracker ids get the prefix of their origin`() = runTest {
val storage = MemoryStorage()
storage.files[DEVICES_CONFIG_PATH] = """
{
"version": 1,
"allowedUdpDevices": ["AA:BB:CC:DD:EE:01"],
"trackers": {
"AA:BB:CC:DD:EE:01:0": { "bodyPart": "HIP" },
"192.168.1.20:1": { "bodyPart": "LEFT_FOOT" },
"A1B2C3D4E5F6": { "bodyPart": "RIGHT_FOOT" },
"0000A1B2C3D4E5F6": { "bodyPart": "LEFT_HAND" },
"LHR-1A2B3C4D": { "bodyPart": "LOWER_CHEST" },
"vmc:tracker:abc": { "bodyPart": "HEAD" },
"vrcosc:vrsystem:head": { "bodyPart": "NECK" }
}
}
""".trimIndent()
val devices = AppConfig.create(backgroundScope, storage).devices.context.state.value
assertEquals(
mapOf(
"udp:AA:BB:CC:DD:EE:01:0" to BodyPart.HIP,
"udp:192.168.1.20:1" to BodyPart.LEFT_FOOT,
"hid:A1B2C3D4E5F6" to BodyPart.RIGHT_FOOT,
"hid:0000A1B2C3D4E5F6" to BodyPart.LEFT_HAND,
"driver:LHR-1A2B3C4D" to BodyPart.LOWER_CHEST,
"vmc:tracker:abc" to BodyPart.HEAD,
"vrcosc:vrsystem:head" to BodyPart.NECK,
),
devices.trackers.mapValues { it.value.bodyPart },
)
assertEquals(setOf("AA:BB:CC:DD:EE:01"), devices.allowedUdpDevices)
assertEquals(2, devices.version)
}
}
@@ -0,0 +1,304 @@
package dev.slimevr.config
import dev.slimevr.skeleton.computeAllDefaultProportionsByBone
import io.github.axisangles.ktmath.Quaternion
import kotlinx.coroutines.test.runTest
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.rpc.ArmsMountingResetMode
import solarxr_protocol.rpc.StayAlignedRelaxedPose
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
private val LEGACY_CONFIG = """
---
server:
trackerPort: 6969
useMagnetometerOnAllTrackers: true
filters:
type: "prediction"
amount: 1.0
vmc:
enabled: true
portIn: 39541
portOut: 39538
address: "192.168.1.20"
anchorHip: false
vrmJson: "{\"nodes\":[]}"
mirrorTracking: true
skeleton:
toggles:
floorClip: false
selfLocalization: true
toeSnap: true
enforceConstraints: false
extendedSpine: false
values:
kneeTrackerAnkleAveraging: 0.6
kneeAnkleAveraging: 0.2
offsets:
chestLength: 0.42
hmdHeight: 1.72
floorHeight: 0.02
legTweaks:
correctionStrength: 0.8
tapDetection:
yawResetDelay: 0.4
fullResetDelay: 2.0
mountingResetDelay: 1.0
yawResetEnabled: false
fullResetEnabled: true
mountingResetEnabled: true
yawResetTracker: "CHEST"
mountingResetTracker: "WAIST"
fullResetTracker: "LEFT_UPPER_LEG"
setupMode: false
yawResetTaps: 4
fullResetTaps: 3
mountingResetTaps: 5
numberTrackersOverThreshold: 2
resetsConfig:
resetMountingFeet: true
mode: "TPOSE_DOWN"
yawResetSmoothTime: 0.5
saveMountingReset: true
resetHmdPitch: true
lastMountingMethod: "AUTOMATIC"
stayAlignedConfig:
enabled: true
standingRelaxedPose:
enabled: true
upperLegAngleInDeg: 4.5
lowerLegAngleInDeg: -2.0
footAngleInDeg: 10.0
sittingRelaxedPose:
enabled: false
upperLegAngleInDeg: 0.0
lowerLegAngleInDeg: 0.0
footAngleInDeg: 0.0
flatRelaxedPose:
enabled: false
upperLegAngleInDeg: 0.0
lowerLegAngleInDeg: 0.0
footAngleInDeg: 0.0
setupComplete: true
hidConfig:
trackersOverHID: true
trackers:
udp://AA:BB:CC:DD:EE:01/0:
customName: "Chest"
designation: "body:chest"
hide: false
adjustment: null
mountingOrientation:
x: 0.0
"y": 1.0
z: -0.0
w: -4.371139E-8
mountingResetOrientation:
x: 0.0
"y": 0.3
z: 0.0
w: 0.95
allowDriftCompensation: true
shouldHaveMagEnabled: null
udp://AA:BB:CC:DD:EE:01/1:
customName: null
designation: "body:waist"
hide: false
adjustment: null
mountingOrientation: null
mountingResetOrientation: null
allowDriftCompensation: true
shouldHaveMagEnabled: null
udp://AA:BB:CC:DD:EE:02/0:
designation: "body:upper_chest"
"123456ABCDEF/0":
designation: "body:left_foot"
ABCDEF123456/0:
customName: null
designation: null
mountingOrientation: null
HMD:
designation: "body:head"
PICO_CONTROLLER_LEFT:
designation: "body:left_hand"
knownDevices:
- "AA:BB:CC:DD:EE:01"
- "aa:bb:cc:dd:ee:02"
velocityConfig:
sendDerivedVelocity: true
vrcOSC:
enabled: true
overlay:
mirrored: false
visible: false
modelVersion: "15"
""".trimIndent()
class LegacyConfigTest {
private val migration = assertNotNull(migrateLegacyConfig(LEGACY_CONFIG))
@Test
fun `listed settings are imported`() {
val settings = migration.settings
assertTrue(settings.trackersConfig.globalMagEnabled)
assertTrue(settings.hidConfig.trackersOverHid)
assertTrue(settings.stayAlignedConfig.enabled)
val toggles = settings.skeletonConfig.toggles
assertFalse(toggles.floorClip)
assertTrue(toggles.mocapMode)
assertTrue(toggles.toeSnap)
assertFalse(toggles.enforceConstraints)
assertEquals(SkeletonTogglesConfig().skatingCorrection, toggles.skatingCorrection)
assertEquals(SkeletonTogglesConfig().footPlant, toggles.footPlant)
assertEquals(0.6f, settings.skeletonConfig.ratios.interpolateUpperLegsTwistWithLowerLegs)
val resets = settings.resetsConfig
assertTrue(resets.resetMountingFeet)
assertEquals(ArmsMountingResetMode.SIDE, resets.armsMountingResetMode)
assertEquals(0.5f, resets.yawResetSmoothTime)
assertTrue(resets.saveMountingReset)
assertTrue(resets.resetHmdAttitude)
val tap = settings.trackerActionConfig
assertEquals(0.4f, tap.yawResetAction.delay)
assertEquals(2.0f, tap.fullResetAction.delay)
assertEquals(1.0f, tap.mountingResetAction.delay)
assertFalse(tap.yawResetAction.enabled)
assertEquals(BodyPart.UPPER_CHEST, tap.yawResetAction.bodyPart)
assertEquals(BodyPart.LOWER_WAIST, tap.mountingResetAction.bodyPart)
assertEquals(BodyPart.LEFT_UPPER_LEG, tap.fullResetAction.bodyPart)
assertEquals(4, tap.yawResetAction.taps)
assertEquals(5, tap.mountingResetAction.taps)
assertEquals(2, tap.tapsTrackersOverThreshold)
val vmc = settings.vmcConfig
assertTrue(vmc.enabled)
assertEquals(39541, vmc.portIn)
assertEquals(39538, vmc.portOut)
assertEquals("192.168.1.20", vmc.address)
assertFalse(vmc.anchorAtHips)
assertTrue(vmc.mirrorTracking)
assertEquals("{\"nodes\":[]}", vmc.vrmJson)
}
@Test
fun `unlisted settings keep the defaults`() {
val defaults = SettingsConfigState()
val settings = migration.settings
assertEquals(defaults.skeletonConfig.ratios.copy(interpolateUpperLegsTwistWithLowerLegs = 0.6f), settings.skeletonConfig.ratios)
assertEquals(defaults.driverConfig, settings.driverConfig)
assertEquals(defaults.vrcOscConfig, settings.vrcOscConfig)
assertEquals(defaults.boneRoutingConfig, settings.boneRoutingConfig)
assertEquals(defaults.trackersConfig.timeoutDelay, settings.trackersConfig.timeoutDelay)
assertEquals(defaults.resetsConfig.mountingMethod, settings.resetsConfig.mountingMethod)
}
@Test
fun `an uncalibrated height keeps the default user`() {
val yaml = LEGACY_CONFIG.replace("hmdHeight: 1.72", "hmdHeight: -1.0").replace("floorHeight: 0.02", "floorHeight: 0.0")
val user = assertNotNull(migrateLegacyConfig(yaml)).user
assertEquals(UserConfigData().userHeight, user.userHeight)
assertEquals(UserConfigData().proportions, user.proportions)
}
@Test
fun `a null vrm is not imported`() {
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: null")
assertNull(assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
}
@Test
fun `user height is the old hmd height above the floor`() {
// hmdHeight 1.72 minus floorHeight 0.02 in the fixture
assertEquals(1.70f, migration.user.userHeight, 0.0001f)
}
@Test
fun `proportions are the defaults for the imported height`() {
val proportions = migration.user.proportions
assertEquals(computeAllDefaultProportionsByBone(1.70f), proportions)
assertNotEquals(UserConfigData().proportions, proportions)
}
@Test
fun `recorded stay aligned poses are imported`() {
val poses = migration.user.stayAlignedPoses
assertEquals(setOf(StayAlignedRelaxedPose.STANDING), poses.keys)
assertEquals(StayAlignedPoseConfig(recorded = true, enabled = true, upperLegAngleInDeg = 4.5f, lowerLegAngleInDeg = -2.0f, footAngleInDeg = 10.0f), poses[StayAlignedRelaxedPose.STANDING])
}
@Test
fun `udp and hid trackers map to their hardware ids`() {
val trackers = migration.devices.trackers
assertEquals(setOf("udp:AA:BB:CC:DD:EE:01:0", "udp:AA:BB:CC:DD:EE:01:1", "udp:AA:BB:CC:DD:EE:02:0", "hid:123456ABCDEF", "hid:ABCDEF123456"), trackers.keys)
val chest = trackers.getValue("udp:AA:BB:CC:DD:EE:01:0")
assertEquals(BodyPart.UPPER_CHEST, chest.bodyPart)
assertEquals("Chest", chest.customName)
assertEquals(Quaternion(-4.371139E-8f, 0f, 1f, 0f), chest.mountingOrientation)
assertNull(chest.mountingResetOrientation)
assertNull(chest.magEnabled)
assertEquals(BodyPart.LOWER_WAIST, trackers.getValue("udp:AA:BB:CC:DD:EE:01:1").bodyPart)
assertEquals(Quaternion.IDENTITY, trackers.getValue("udp:AA:BB:CC:DD:EE:01:1").mountingOrientation)
assertEquals(BodyPart.UPPER_CHEST, trackers.getValue("udp:AA:BB:CC:DD:EE:02:0").bodyPart)
assertEquals(BodyPart.LEFT_FOOT, trackers.getValue("hid:123456ABCDEF").bodyPart)
assertEquals(TrackerConfig(), trackers.getValue("hid:ABCDEF123456"))
assertEquals(setOf("AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"), migration.devices.allowedUdpDevices)
}
@Test
fun `a whole glTF JSON is trimmed to what the GUI sends`() {
val gltf = """{"asset":{"version":"2.0"},"materials":[{"name":"skin"}],"extensionsUsed":["VRMC_vrm"],"extensions":{"VRMC_vrm":{"specVersion":"1.0","humanoid":{"humanBones":{"hips":{"node":0}}}},"KHR_materials_unlit":{}},"nodes":[{"translation":[0.0,1.0,0.0]}]}"""
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: '$gltf'")
val vrmJson = assertNotNull(assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
assertEquals(
"""{"extensions":{"VRMC_vrm":{"specVersion":"1.0","humanoid":{"humanBones":{"hips":{"node":0}}}}},"extensionsUsed":["VRMC_vrm"],"nodes":[{"translation":[0.0,1.0,0.0]}]}""",
vrmJson,
)
}
@Test
fun `a config larger than 3 MB is still read`() {
val padding = "x".repeat(4 * 1024 * 1024)
val yaml = LEGACY_CONFIG.replace("vrmJson: \"{\\\"nodes\\\":[]}\"", "vrmJson: '{\"nodes\":[],\"padding\":\"$padding\"}'")
assertEquals("{\"nodes\":[]}", assertNotNull(migrateLegacyConfig(yaml)).settings.vmcConfig.vrmJson)
}
@Test
fun `configs older than version 14 are skipped`() {
assertNull(migrateLegacyConfig(LEGACY_CONFIG.replace("modelVersion: \"15\"", "modelVersion: \"13\"")))
assertNull(migrateLegacyConfig(LEGACY_CONFIG.replace("\nmodelVersion: \"15\"", "")))
}
@Test
fun `first start loads the imported config`() = runTest {
val storage = MemoryStorage()
storage.files[LEGACY_CONFIG_PATH] = LEGACY_CONFIG
val config = AppConfig.create(backgroundScope, storage)
assertEquals(migration.settings, config.settings.context.state.value.data)
assertEquals(migration.user, config.userConfig.context.state.value.data)
assertEquals(migration.devices, config.devices.context.state.value)
assertEquals(LEGACY_CONFIG, storage.files[LEGACY_CONFIG_PATH])
}
@Test
fun `an existing config is never overwritten by the import`() = runTest {
val storage = MemoryStorage()
AppConfig.create(backgroundScope, storage)
storage.files[LEGACY_CONFIG_PATH] = LEGACY_CONFIG
val config = AppConfig.create(backgroundScope, storage)
assertEquals(SettingsConfigState(), config.settings.context.state.value.data)
assertEquals(DevicesConfigState(), config.devices.context.state.value)
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more