diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl
index f14e564f0..5765662f0 100644
--- a/gui/app/public/i18n/en/translation.ftl
+++ b/gui/app/public/i18n/en/translation.ftl
@@ -626,28 +626,85 @@ settings-general-tracker_mechanics-trackers_over_usb-description =
settings-general-tracker_mechanics-timeout_delay = Timeout delay
settings-general-tracker_mechanics-timeout_delay-description = How long until a tracker is marked as '{ tracker-status-disconnected }' when the connection is lost.
-settings-stay_aligned-description = Stay Aligned reduces drift by gradually adjusting your trackers to match your relaxed poses.
-settings-stay_aligned-setup_group = Setup
-settings-stay_aligned-setup-label = Setup Stay Aligned
-settings-stay_aligned-setup-label-description = Record how your legs look when relaxed, so Stay Aligned has a reference to align to.
-settings-stay_aligned-setup-open = Open setup
-settings-stay_aligned-setup-description = You must complete "{ settings-stay_aligned-setup-label }" to enable Stay Aligned.
+settings-stay_aligned-description = Stay Aligned reduces yaw drift while you play. Trackers that stay still are held where they are, with no setup. To also correct trackers while you move, turn it on and record the poses you play in.
settings-stay_aligned-enabled-label = Enable Stay Aligned
-settings-stay_aligned-enabled-label-description = Turn Stay Aligned on or off. Each relaxed pose below can also be turned on or off.
-settings-stay_aligned-relaxed_poses-label = Relaxed Poses
-settings-stay_aligned-relaxed_poses-description = Stay Aligned uses your relaxed poses to keep the trackers aligned. Use "{ settings-stay_aligned-setup-label }" to update these poses.
-settings-stay_aligned-relaxed_poses-pose-description = Turn this on to let Stay Aligned use this pose. Use Save pose to record it.
-settings-stay_aligned-relaxed_poses-standing = Adjust trackers while standing
-settings-stay_aligned-relaxed_poses-sitting = Adjust trackers while sitting in a chair
-settings-stay_aligned-relaxed_poses-flat = Adjust trackers while sitting on the floor, or lying on your back
-settings-stay_aligned-relaxed_poses-save_pose = Save pose
-settings-stay_aligned-relaxed_poses-reset_pose = Reset pose
-settings-stay_aligned-relaxed_poses-close = Close
+settings-stay_aligned-enabled-label-description = Turn Stay Aligned on or off for all your trackers.
+settings-stay_aligned-status_group = Status
+settings-stay_aligned-status-correction = Correction
+settings-stay_aligned-status-position = Current detected position
+settings-stay_aligned-position-unknown = Not recognised
+settings-stay_aligned-position-standing = Standing
+settings-stay_aligned-position-sitting = Sitting
+settings-stay_aligned-position-flat = On the floor
+settings-stay_aligned-position-kneeling = Kneeling
+settings-stay_aligned-trackers-missing = No tracker for: { $parts }.
+settings-stay_aligned-status-badge-disabled = Off
+settings-stay_aligned-status-badge-correcting = Correcting
+settings-stay_aligned-status-badge-not_correcting = Not correcting
+settings-stay_aligned-status-text-disabled = Turn it on above to hold and correct your trackers.
+settings-stay_aligned-status-text-correcting = Moving trackers are corrected using the pose you are in.
+settings-stay_aligned-status-text-pose_unusable = Moving trackers are not corrected in this position.
+settings-stay_aligned-status-pose-name = { $pose }.
+settings-stay_aligned-status-badge-pose-ready = Ready
+settings-stay_aligned-status-badge-pose-not_recorded = Not recorded
+settings-stay_aligned-status-badge-pose-disabled = Turned off
+settings-stay_aligned-status-badge-pose-unknown = Unrecognised
+settings-stay_aligned-status-pose-ready = Moving trackers can be corrected with this pose.
+settings-stay_aligned-status-pose-not_recorded = Record this pose so moving trackers can be corrected in it.
+settings-stay_aligned-status-pose-disabled = This pose is turned off, so moving trackers are not corrected in it.
+settings-stay_aligned-status-pose-unknown = Your position does not match any pose, so moving trackers are not corrected.
+settings-stay_aligned-status-largest_correction = Largest correction
+settings-stay_aligned-status-largest_correction-part = { $part }, since your last reset.
+settings-stay_aligned-status-largest_correction-none = No tracker was turned since your last reset.
+settings-stay_aligned-status-largest_correction-off = Nothing is corrected while Stay Aligned is off.
+settings-stay_aligned-poses_group = Relaxed poses
+settings-stay_aligned-poses_group-description = Stay Aligned needs to know how your legs sit when you are relaxed, for each position you play in. Record the ones you use. Only your legs and torso count, arms and hands can be anywhere.
+settings-stay_aligned-pose-standing = Standing
+settings-stay_aligned-pose-standing-description = Stand relaxed with your legs in your natural stance.
+settings-stay_aligned-pose-sitting = Sitting in a chair
+settings-stay_aligned-pose-sitting-description = Sit relaxed in a chair, feet on the floor.
+settings-stay_aligned-pose-flat = Sitting on the floor or lying on your back
+settings-stay_aligned-pose-flat-description = Sit on the floor with your legs in front of you, relaxed.
+settings-stay_aligned-badge-recorded = Recorded
+settings-stay_aligned-badge-not_recorded = Not recorded
+settings-stay_aligned-badge-default = Default
+settings-stay_aligned-record = Record
+settings-stay_aligned-record_again = Record again
+settings-stay_aligned-toggle-record_first = Record this pose first
settings-stay_aligned-debug-label = Debugging
settings-stay_aligned-debug-description = Please include your settings when reporting problems about Stay Aligned.
settings-stay_aligned-debug-copy-label = Copy settings to clipboard
settings-stay_aligned-debug-copy-short = Copy
+## Stay Aligned pose recorder
+settings-stay_aligned-recorder-close = Cancel
+settings-stay_aligned-recorder-step-trackers = Trackers
+settings-stay_aligned-recorder-step-full_reset = Full reset
+settings-stay_aligned-recorder-step-mounting = Mounting calibration
+settings-stay_aligned-recorder-step-feet_mounting = Feet calibration
+settings-stay_aligned-recorder-step-record = Record pose
+settings-stay_aligned-recorder-trackers-intro = Stay Aligned needs a chest, waist or hip tracker plus both thighs and both ankles.
+settings-stay_aligned-recorder-trackers-assign = Assign trackers
+settings-stay_aligned-recorder-full_reset-intro = Poses are measured from calibrated trackers, so your trackers need a full reset first.
+settings-stay_aligned-recorder-mounting-intro = Your leg directions are measured from how the trackers are mounted, so they need calibrating first.
+settings-stay_aligned-recorder-feet_mounting-intro = Your foot angles are measured from how the feet trackers are mounted, and your feet have a calibration of their own.
+settings-stay_aligned-recorder-arms = Arms and hands can be anywhere.
+settings-stay_aligned-recorder-record-step-0 = 1. Press "Start", then get into the pose.
+settings-stay_aligned-recorder-record-step-1 = 2. Hold still. The pose is saved as soon as all your trackers are still.
+settings-stay_aligned-recorder-start = Start
+settings-stay_aligned-recorder-start_over = Start over
+settings-stay_aligned-recorder-try_again = Try again
+settings-stay_aligned-recorder-redo_preparation = Redo preparation
+settings-stay_aligned-recorder-live-hold = Hold the pose and keep your trackers still.
+settings-stay_aligned-recorder-live-wrong_pose = Wrong pose.
+settings-stay_aligned-recorder-live-detected = Detected: { $position }.
+settings-stay_aligned-recorder-live-not_still = Some trackers did not stay still.
+settings-stay_aligned-recorder-live-missing = Some trackers are missing.
+settings-stay_aligned-recorder-live-not_calibrated = Your trackers need a reset first.
+settings-stay_aligned-recorder-part-upper_body = Upper body
+settings-stay_aligned-recorder-state-still = Still
+settings-stay_aligned-recorder-state-moving = Moving
+
## Keybinds Page
settings-keybinds-description = Change keybinds for various shortcuts
keybind_config-keybind_name = Keybind
@@ -1520,35 +1577,6 @@ onboarding-user_height-manual-tip = While adjusting your height, try different p
onboarding-user_height-reset-warning = Warning: This will reset your proportions to be based on your height.
Are you sure you want to do this?
-## Stay Aligned setup
-onboarding-stay_aligned-title = Stay Aligned
-onboarding-stay_aligned-description = Configure Stay Aligned to keep your trackers aligned.
-onboarding-stay_aligned-put_trackers_on-title = Put on your trackers
-onboarding-stay_aligned-put_trackers_on-description = To save your resting poses, we'll use the trackers you just assigned. Put on all your trackers, you can see which are which in the figure to the right.
-onboarding-stay_aligned-put_trackers_on-trackers_warning = You have fewer than 5 trackers currently connected and assigned! This is the minimum amount of trackers required for Stay Aligned to function properly.
-onboarding-stay_aligned-put_trackers_on-next = I have all my trackers on
-onboarding-stay_aligned-verify_mounting-title = Mounting Calibration
-onboarding-stay_aligned-verify_mounting-change_method = Change method
-onboarding-stay_aligned-preparation-title = Preparation
-onboarding-stay_aligned-preparation-tip = Make sure to stand upright. Keep looking forward with your arms down at your sides.
-onboarding-stay_aligned-relaxed_poses-standing-title = Relaxed Standing Pose
-onboarding-stay_aligned-relaxed_poses-standing-step-0 = 1. Stand in a comfortable position. Relax!
-onboarding-stay_aligned-relaxed_poses-standing-step-1-v2 = 2. Press the "Save pose" button.
-onboarding-stay_aligned-relaxed_poses-sitting-title = Relaxed Sitting in Chair Pose
-onboarding-stay_aligned-relaxed_poses-sitting-step-0 = 1. Sit in a comfortable position. Relax!
-onboarding-stay_aligned-relaxed_poses-sitting-step-1-v2 = 2. Press the "Save pose" button.
-onboarding-stay_aligned-relaxed_poses-flat-title = Relaxed Sitting on Floor Pose
-onboarding-stay_aligned-relaxed_poses-flat-step-0 = 1. Sit on the floor with your legs in front. Relax!
-onboarding-stay_aligned-relaxed_poses-flat-step-1-v2 = 2. Press the "Save pose" button.
-onboarding-stay_aligned-relaxed_poses-skip_step = Skip
-onboarding-stay_aligned-done-title = Stay Aligned enabled!
-onboarding-stay_aligned-done-description = Your Stay Aligned setup is complete!
-onboarding-stay_aligned-done-description-2 = Setup is complete! You may restart the process if you want to recalibrate the poses.
-onboarding-stay_aligned-previous_step = Previous
-onboarding-stay_aligned-next_step = Next
-onboarding-stay_aligned-restart = Restart
-onboarding-stay_aligned-done = Done
-
## Home
home-settings = Home Page Settings
home-settings-close = Close
@@ -1843,7 +1871,7 @@ tracking_checklist-NETWORK_PROFILE_PUBLIC-settings_desc = Shown when a network a
tracking_checklist-STAY_ALIGNED_CONFIGURED = Configure Stay Aligned
tracking_checklist-STAY_ALIGNED_CONFIGURED-desc = Record the Stay Aligned poses to reduce drift
tracking_checklist-STAY_ALIGNED_CONFIGURED-settings_desc = Shown when Stay Aligned is not enabled.
-tracking_checklist-STAY_ALIGNED_CONFIGURED-open = Open Stay Aligned Wizard
+tracking_checklist-STAY_ALIGNED_CONFIGURED-open = Open Stay Aligned settings
tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED = Enable VRChat OSC tracking data
tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-desc = VRChat is connected, but isn't sending back your head and hand tracking data. Turn on the OSC tracking-data toggle in VRChat's settings. See how to enable it.
tracking_checklist-VRCHAT_OSC_TRACKING_DISABLED-settings_desc = Shown when VRChat is connected but does not send back your head and hand tracking data.
diff --git a/gui/app/src/App.tsx b/gui/app/src/App.tsx
index 2515d94c1..ff8908671 100644
--- a/gui/app/src/App.tsx
+++ b/gui/app/src/App.tsx
@@ -51,7 +51,6 @@ import { CrashScreen } from './components/CrashScreen';
import { ScaledProportionsPage } from './components/onboarding/pages/body-proportions/ScaledProportions';
import { FirmwareUpdate } from './components/firmware-update/FirmwareUpdate';
import { ConnectionLost } from './components/onboarding/pages/ConnectionLost';
-import { StayAlignedSetup } from './components/onboarding/pages/stay-aligned/StayAlignedSetup';
import { TrackingChecklistProvider } from './components/tracking-checklist/TrackingChecklistProvider';
import { ChecklistPage } from './components/tracking-checklist/TrackingChecklist';
import { QuizSlimeSetQuestion } from './components/onboarding/pages/quiz/SlimeSetQuestion';
@@ -211,7 +210,6 @@ function AppRoutes() {
path="body-proportions/scaled"
element={ }
/>
- } />
} />
diff --git a/gui/app/src/components/commons/BaseModal.tsx b/gui/app/src/components/commons/BaseModal.tsx
index 51ed9faba..0239af9fc 100644
--- a/gui/app/src/components/commons/BaseModal.tsx
+++ b/gui/app/src/components/commons/BaseModal.tsx
@@ -50,7 +50,8 @@ export function BaseModal({
classNames(
'fixed top-0 right-0 left-0 bottom-0 flex flex-col justify-center',
'items-center w-full h-full bg-background-90 bg-opacity-60',
- important ? 'z-50' : 'z-40'
+ // Above the app chrome (top bar, settings page picker, floating buttons) at z-50
+ important ? 'z-[70]' : 'z-[60]'
)
}
className={
diff --git a/gui/app/src/components/commons/icon/SimevrIcon.tsx b/gui/app/src/components/commons/icon/SimevrIcon.tsx
index 2e5ae8a09..fe2644665 100644
--- a/gui/app/src/components/commons/icon/SimevrIcon.tsx
+++ b/gui/app/src/components/commons/icon/SimevrIcon.tsx
@@ -73,11 +73,7 @@ export function SlimeVRIcon({ drag }: { drag?: boolean }) {
stroke="#CD5000"
/>
-
+
diff --git a/gui/app/src/components/commons/icon/SlimeVRIcon.tsx b/gui/app/src/components/commons/icon/SlimeVRIcon.tsx
index 67bc2e7e3..90a5c4eee 100644
--- a/gui/app/src/components/commons/icon/SlimeVRIcon.tsx
+++ b/gui/app/src/components/commons/icon/SlimeVRIcon.tsx
@@ -59,11 +59,7 @@ export function SlimeVRIcon({ width = 28 }: { width?: number }) {
stroke="#FFFFFF"
/>
-
+
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/StayAlignedSetup.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/StayAlignedSetup.tsx
deleted file mode 100644
index 3abaf5e0e..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/StayAlignedSetup.tsx
+++ /dev/null
@@ -1,239 +0,0 @@
-import { Typography } from '@/components/commons/Typography';
-import { DoneStep } from './stay-aligned-steps/Done';
-import { useLocalization } from '@fluent/react';
-import {
- FlatRelaxedPoseStep,
- SittingRelaxedPoseStep,
- StandingRelaxedPoseStep,
-} from './stay-aligned-steps/RelaxedPoseSteps';
-import {
- ChangeStayAlignedEnabledRequestT,
- MountingMethod,
- RpcMessage,
-} from 'solarxr-protocol';
-import { useResetsSettings } from '@/hooks/resets-settings';
-import { RPCPacketType, useWebsocketAPI } from '@/hooks/websocket-api';
-import { useEffect, useRef } from 'react';
-import VerticalStepper from '@/components/commons/VerticalStepper';
-import { useBreakpoint } from '@/hooks/breakpoint';
-import {
- SkeletonPreviewView,
- SkeletonVisualizerWidget,
-} from '@/components/widgets/SkeletonVisualizerWidget';
-import { Vector3 } from 'three';
-import { Easing } from '@tweenjs/tween.js';
-import { VerifyMountingStep } from './stay-aligned-steps/VerifyMounting';
-import { PutTrackersOnStep } from './stay-aligned-steps/PutTrackersOnStep';
-import { PreparationStep } from './stay-aligned-steps/PreparationStep';
-
-export function enableStayAligned(
- enable: boolean,
- sendRPCPacket: (type: RpcMessage, data: RPCPacketType) => void
-) {
- const req = new ChangeStayAlignedEnabledRequestT();
- req.enabled = enable;
- sendRPCPacket(RpcMessage.ChangeStayAlignedEnabledRequest, req);
-}
-
-export function StayAlignedSetup() {
- const { l10n } = useLocalization();
- const { isMobile } = useBreakpoint('mobile');
- const { sendRPCPacket, useConnectedEffect } = useWebsocketAPI();
- const { resetsSettings } = useResetsSettings();
-
- const viewsRef = useRef<{
- cam1?: SkeletonPreviewView;
- cam2?: SkeletonPreviewView;
- }>({});
-
- useConnectedEffect(() => {
- // Disable Stay Aligned as soon as we enter the setup flow so that we don't
- // adjust the trackers while trying to set up the feature
- enableStayAligned(false, sendRPCPacket);
- }, []);
-
- const updateCamSizes = () => {
- const views = viewsRef.current;
- if (!views.cam1 || !views.cam2) return;
- if (!views.cam2.hidden) {
- if (isMobile) {
- views.cam1.height = 1;
- views.cam2.height = 1;
- views.cam2.width = 0.5;
- views.cam1.width = 0.5;
- views.cam1.bottom = 0;
- views.cam2.bottom = 0;
- views.cam2.left = 0.5;
- } else {
- views.cam1.height = 0.5;
- views.cam2.height = 0.5;
- views.cam2.width = 1;
- views.cam1.width = 1;
- views.cam1.bottom = 0;
- views.cam2.bottom = 0.5;
- views.cam2.left = 0;
- }
- } else {
- views.cam1.height = 1;
- views.cam2.height = 1;
- views.cam2.width = 1;
- views.cam1.width = 1;
- views.cam1.bottom = 0;
- views.cam2.bottom = 0;
- views.cam2.left = 0;
- }
- };
-
- const onStepChange = (index: number, id?: string) => {
- if (id === 'start') {
- enableStayAligned(false, sendRPCPacket);
- }
-
- const views = viewsRef.current;
- if (!views.cam1 || !views.cam2) return;
- switch (id) {
- case 'standing': {
- views.cam2.hidden = true;
- views.cam1.tween
- .stop()
- .to(new Vector3(0, 1, -6), 500)
- .easing(Easing.Quadratic.InOut)
- .startFromCurrentValues();
- break;
- }
- case 'flat':
- case 'sitting': {
- views.cam2.hidden = false;
- views.cam1.tween
- .stop()
- .to(new Vector3(-5, 1, -0), 500)
- .easing(Easing.Quadratic.InOut)
- .startFromCurrentValues();
-
- views.cam2.tween
- .stop()
- .to(new Vector3(0, 4, -0.2), 500)
- .easing(Easing.Quadratic.InOut)
- .startFromCurrentValues();
- break;
- }
- default: {
- views.cam2.hidden = true;
- views.cam1.tween
- .stop()
- .to(new Vector3(3, 2.5, -3), 1000)
- .easing(Easing.Quadratic.InOut)
- .startFromCurrentValues();
- break;
- }
- }
-
- updateCamSizes();
- };
-
- useEffect(() => {
- updateCamSizes();
- }, [isMobile]);
-
- return (
-
-
-
-
- {l10n.getString('onboarding-stay_aligned-title')}
-
-
- {l10n.getString('onboarding-stay_aligned-description')}
-
-
-
-
-
-
-
- {
- viewsRef.current.cam1 = context.addView({
- left: 0,
- bottom: 0,
- width: 1,
- height: 1,
- position: new Vector3(3, 2.5, -3),
- onHeightChange(v, newHeight) {
- v.controls.target.set(0, newHeight / 2, 0);
- const scale = Math.max(1, newHeight) / 1.5;
- v.camera.zoom = 1 / scale;
- },
- });
-
- viewsRef.current.cam2 = context.addView({
- left: 0,
- bottom: 0.5,
- width: 1,
- height: 0.5,
- hidden: true,
- position: new Vector3(3, 2.5, -3),
- onHeightChange(v, newHeight) {
- v.controls.target.set(0, newHeight / 2, 0);
- const scale = Math.max(1, newHeight) / 1.5;
- v.camera.zoom = 1 / scale;
- },
- });
- }}
- />
-
-
- );
-}
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/Done.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/Done.tsx
deleted file mode 100644
index 90892ff2e..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/Done.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-import { Button } from '@/components/commons/Button';
-import { Typography } from '@/components/commons/Typography';
-import { VerticalStepComponentProps } from '@/components/commons/VerticalStepper';
-import { Localized } from '@fluent/react';
-
-export function DoneStep({ goTo }: VerticalStepComponentProps) {
- return (
-
-
-
-
-
-
-
-
-
-
-
- goTo('start')} />
-
-
-
-
-
-
- );
-}
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PreparationStep.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PreparationStep.tsx
deleted file mode 100644
index 338711801..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PreparationStep.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { Button } from '@/components/commons/Button';
-import { FullResetExamples } from '@/components/commons/FullResetExamples';
-import { TipBox } from '@/components/commons/TipBox';
-import { Typography } from '@/components/commons/Typography';
-import { VerticalStepComponentProps } from '@/components/commons/VerticalStepper';
-import { ResetButton } from '@/components/home/ResetButton';
-import { Localized } from '@fluent/react';
-import { ResetAvailability, ResetType } from 'solarxr-protocol';
-import { useAtomValue } from 'jotai';
-import { serverGuardsAtom } from '@/store/app-store';
-
-export function PreparationStep({
- nextStep,
- prevStep,
- isActive,
-}: VerticalStepComponentProps) {
- const serverGuards = useAtomValue(serverGuardsAtom);
- return (
-
- {serverGuards?.mountingReset === ResetAvailability.NEEDS_FULL_RESET && (
- <>
-
-
-
-
-
-
- TIP
-
-
-
-
- {
- if (isActive) {
- nextStep();
- }
- }}
- />
-
- >
- )}
- {serverGuards &&
- serverGuards.mountingReset !== ResetAvailability.NEEDS_FULL_RESET && (
-
- )}
-
- );
-}
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PutTrackersOnStep.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PutTrackersOnStep.tsx
deleted file mode 100644
index 5ab361139..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/PutTrackersOnStep.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { BodyDisplay } from '@/components/commons/BodyDisplay';
-import { Button } from '@/components/commons/Button';
-import { TipBox, WarningBox } from '@/components/commons/TipBox';
-import { Typography } from '@/components/commons/Typography';
-import { VerticalStepComponentProps } from '@/components/commons/VerticalStepper';
-import { assignedTrackersAtom } from '@/store/app-store';
-import { Localized } from '@fluent/react';
-import { useAtomValue } from 'jotai';
-
-export function PutTrackersOnStep({ nextStep }: VerticalStepComponentProps) {
- const assignedTrackers = useAtomValue(assignedTrackersAtom);
-
- // Keep the button while in dev
- const canContinue = assignedTrackers.length >= 5 || import.meta.env.DEV;
-
- return (
-
-
-
-
-
-
-
-
-
-
- Tip
-
-
- {assignedTrackers.length < 5 && (
-
-
- Warning
-
-
- )}
-
-
-
-
-
- );
-}
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/RelaxedPoseSteps.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/RelaxedPoseSteps.tsx
deleted file mode 100644
index b8c33b982..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/RelaxedPoseSteps.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { Button } from '@/components/commons/Button';
-import { Typography } from '@/components/commons/Typography';
-import {
- DetectRelaxedPoseButton,
- ResetRelaxedPoseButton,
-} from '@/components/stay-aligned/RelaxedPose';
-import { useLocalization } from '@fluent/react';
-import { StayAlignedRelaxedPose } from 'solarxr-protocol';
-import { enableStayAligned } from '@/components/onboarding/pages/stay-aligned/StayAlignedSetup';
-import { useWebsocketAPI } from '@/hooks/websocket-api';
-import { VerticalStepComponentProps } from '@/components/commons/VerticalStepper';
-import { ReactNode } from 'react';
-
-function PosePage({
- nextStep,
- prevStep,
- descriptionKeys,
- children,
- relaxedPose,
- lastStep = false,
-}: VerticalStepComponentProps & {
- descriptionKeys: string[];
- children: ReactNode;
- relaxedPose: StayAlignedRelaxedPose;
- lastStep?: boolean;
-}) {
- const { l10n } = useLocalization();
- const { sendRPCPacket } = useWebsocketAPI();
- return (
-
-
- {descriptionKeys.map((descriptionKey, i) => (
- {l10n.getString(descriptionKey)}
- ))}
-
-
- {children}
-
-
-
- {l10n.getString('onboarding-stay_aligned-previous_step')}
-
-
- {
- if (lastStep) {
- enableStayAligned(true, sendRPCPacket);
- }
- nextStep();
- }}
- pose={relaxedPose}
- >
- {l10n.getString('onboarding-stay_aligned-relaxed_poses-skip_step')}
-
- {
- if (lastStep) {
- enableStayAligned(true, sendRPCPacket);
- }
- nextStep();
- }}
- pose={relaxedPose}
- />
-
-
-
- );
-}
-
-export const StandingRelaxedPoseStep = (
- verticalStepProps: VerticalStepComponentProps
-) => (
-
-
-
-);
-
-export const SittingRelaxedPoseStep = (
- verticalStepProps: VerticalStepComponentProps
-) => (
-
-
-
-);
-
-export const FlatRelaxedPoseStep = (
- verticalStepProps: VerticalStepComponentProps
-) => (
-
-
-
-);
diff --git a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/VerifyMounting.tsx b/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/VerifyMounting.tsx
deleted file mode 100644
index ea1e80cfb..000000000
--- a/gui/app/src/components/onboarding/pages/stay-aligned/stay-aligned-steps/VerifyMounting.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-import { ReactNode, useState } from 'react';
-import { Button } from '@/components/commons/Button';
-import { Typography } from '@/components/commons/Typography';
-import {
- PoseMountingInstructions,
- PoseMountingVideo,
-} from '@/components/mounting/PoseMountingVideo';
-import { MountingMethod, ResetType } from 'solarxr-protocol';
-import { ResetButton } from '@/components/home/ResetButton';
-import { VerticalStepComponentProps } from '@/components/commons/VerticalStepper';
-import { useCancelMountingOnLeave } from '@/components/onboarding/pages/mounting/MountingFlow';
-import { MountingMethodModal } from '@/components/mounting/MountingMethodModal';
-import { MountingMethodRadio } from '@/components/mounting/MountingMethodRadio';
-import { StepMedia } from '@/components/mounting/StepMountingStatus';
-import { useResetsSettings } from '@/hooks/resets-settings';
-
-function MountingLayout({
- instructions,
- media,
- actions,
-}: {
- instructions: ReactNode;
- media: ReactNode;
- actions: ReactNode;
-}) {
- return (
-
-
-
-
- {instructions}
-
-
- {media}
-
-
-
{actions}
-
-
- );
-}
-
-function ChangeMethodButton() {
- const [isOpen, setOpen] = useState(false);
-
- return (
- <>
- setOpen(true)}
- id="onboarding-stay_aligned-verify_mounting-change_method"
- />
- setOpen(false)} />
- >
- );
-}
-
-function ResetMounting({
- nextStep,
- prevStep,
- isActive,
- instructions,
- media,
-}: VerticalStepComponentProps & {
- instructions: ReactNode;
- media: ReactNode;
-}) {
- useCancelMountingOnLeave();
-
- return (
-
-
-
-
- {
- if (isActive) nextStep();
- }}
- />
-
- >
- }
- />
- );
-}
-
-function PickMethodStep({ prevStep }: VerticalStepComponentProps) {
- return (
-
- );
-}
-
-export function VerifyMountingStep(props: VerticalStepComponentProps) {
- const { resetsSettings } = useResetsSettings();
-
- switch (resetsSettings?.mountingMethod) {
- case MountingMethod.STEP:
- return (
-
-
-
-
- }
- media={
-
-
-
- }
- />
- );
- case MountingMethod.POSE:
- return (
- }
- media={ }
- />
- );
- default:
- return ;
- }
-}
diff --git a/gui/app/src/components/settings/pages/StayAlignedSettings.tsx b/gui/app/src/components/settings/pages/StayAlignedSettings.tsx
index 852d08dd8..acfd36934 100644
--- a/gui/app/src/components/settings/pages/StayAlignedSettings.tsx
+++ b/gui/app/src/components/settings/pages/StayAlignedSettings.tsx
@@ -1,84 +1,44 @@
-import { Localized, useLocalization } from '@fluent/react';
-import { useEffect, useState } from 'react';
-import { useForm } from 'react-hook-form';
+import { useLocalization } from '@fluent/react';
+import { useState } from 'react';
+import { FieldValues } from 'react-hook-form';
import {
- ChangeStayAlignedSettingsRequestT,
- RpcMessage,
- StayAlignedSettingsRequestT,
+ StayAlignedPoseState,
+ StayAlignedRelaxedPose,
StayAlignedSettingsResponseT,
} from 'solarxr-protocol';
+import { useAtomValue } from 'jotai';
import { Button } from '@/components/commons/Button';
-import { CheckBox } from '@/components/commons/Checkbox';
+import { CheckboxInternal } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
+import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIcon';
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPagePaneLayout';
import {
SettingRow,
SettingsAdvanced,
SettingsGroup,
} from '@/components/settings/SettingRow';
-import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIcon';
-import { useAtomValue, atom, useSetAtom } from 'jotai';
-import { selectAtom } from 'jotai/utils';
-import { isEqual } from '@react-hookz/deep-equal';
+import { settingReset } from '@/components/settings/SettingReset';
+import { defineSettingsPage } from '@/components/settings/settings-definitions';
+import { PoseRecorderModal } from '@/components/stay-aligned/PoseRecorderModal';
+import { PoseRow } from '@/components/stay-aligned/PoseRow';
+import { StayAlignedStatusRow } from '@/components/stay-aligned/StayAlignedStatusRow';
+import {
+ POSE_KEY,
+ POSE_ORDER,
+ RecordablePose,
+ useStayAlignedSettings,
+ useStayAlignedStatus,
+} from '@/hooks/stay-aligned';
+import { useSettingsDefaults } from '@/hooks/settings-defaults';
+import { useLocaleConfig } from '@/i18n/config';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import { bodypartToString } from '@/utils/formatting';
-import { useLocaleConfig } from '@/i18n/config';
-import { useWebsocketAPI } from '@/hooks/websocket-api';
-import { useSettingsDefaults } from '@/hooks/settings-defaults';
-import { settingReset } from '@/components/settings/SettingReset';
-import {
- FlatRelaxedPoseModal,
- SittingRelaxedPoseModal,
- StandingRelaxedPoseModal,
-} from './components/StayAlignedPoseModal';
-import { defineSettingsPage } from '@/components/settings/settings-definitions';
-export type StayAlignedSettingsForm = {
- setupComplete: boolean;
- enabled: boolean;
- standingEnabled: boolean;
- standingUpperLegAngle: number;
- standingLowerLegAngle: number;
- standingFootAngle: number;
- sittingEnabled: boolean;
- sittingUpperLegAngle: number;
- sittingLowerLegAngle: number;
- sittingFootAngle: number;
- flatEnabled: boolean;
- flatUpperLegAngle: number;
- flatLowerLegAngle: number;
- flatFootAngle: number;
-};
-
-function toForm(
- settings: StayAlignedSettingsResponseT
-): StayAlignedSettingsForm {
- return {
- setupComplete: settings.setupComplete,
- enabled: settings.enabled,
- standingEnabled: settings.standingEnabled,
- standingUpperLegAngle: settings.standingUpperLegAngle,
- standingLowerLegAngle: settings.standingLowerLegAngle,
- standingFootAngle: settings.standingFootAngle,
- sittingEnabled: settings.sittingEnabled,
- sittingUpperLegAngle: settings.sittingUpperLegAngle,
- sittingLowerLegAngle: settings.sittingLowerLegAngle,
- sittingFootAngle: settings.sittingFootAngle,
- flatEnabled: settings.flatEnabled,
- flatUpperLegAngle: settings.flatUpperLegAngle,
- flatLowerLegAngle: settings.flatLowerLegAngle,
- flatFootAngle: settings.flatFootAngle,
- };
-}
-
-const stayAlignedSettingsAtom = atom(null);
-const stayAlignedSettingsValueAtom = selectAtom(
- stayAlignedSettingsAtom,
- (settings) => settings,
- isEqual
-);
-
-function CopySettingsButton({ values }: { values: StayAlignedSettingsForm }) {
+function CopySettingsButton({
+ settings,
+}: {
+ settings: StayAlignedSettingsResponseT;
+}) {
const { l10n } = useLocalization();
const { currentLocales } = useLocaleConfig();
const numberFormat = new Intl.NumberFormat(currentLocales, {
@@ -89,21 +49,28 @@ function CopySettingsButton({ values }: { values: StayAlignedSettingsForm }) {
const trackers = useAtomValue(connectedIMUTrackersAtom);
const copySettings = () => {
- const config = values;
+ const poses = settings.poses
+ .map((pose) => {
+ const source = pose.recorded
+ ? 'recorded'
+ : pose.hasDefault
+ ? 'default'
+ : 'not recorded';
+ const angles = `upper_leg=${numberFormat.format(pose.upperLegAngle)}, lower_leg=${numberFormat.format(pose.lowerLegAngle)}, foot=${numberFormat.format(pose.footAngle)}`;
+ return `${StayAlignedRelaxedPose[pose.pose]}: ${pose.enabled ? 'enabled' : 'not enabled'}, ${source} (${angles})`;
+ })
+ .join('\n');
const debug = `
Stay Aligned debug info:
GENERAL
=======
-Enabled: ${config.enabled}
-Setup complete: ${config.setupComplete}
+Enabled: ${settings.enabled}
RELAXED POSES
=============
-Standing: ${config.standingEnabled ? `Enabled (upper_leg=${numberFormat.format(config.standingUpperLegAngle)}, lower_leg=${numberFormat.format(config.standingLowerLegAngle)}, foot=${numberFormat.format(config.standingFootAngle)})` : 'Not enabled'}
-Sitting: ${config.sittingEnabled ? `Enabled (upper_leg=${numberFormat.format(config.sittingUpperLegAngle)}, lower_leg=${numberFormat.format(config.sittingLowerLegAngle)}, foot=${numberFormat.format(config.sittingFootAngle)})` : 'Not enabled'}
-Flat: ${config.flatEnabled ? `Enabled (upper_leg=${numberFormat.format(config.flatUpperLegAngle)}, lower_leg=${numberFormat.format(config.flatLowerLegAngle)}, foot=${numberFormat.format(config.flatFootAngle)})` : 'Not enabled'}
+${poses}
TRACKERS
========
@@ -136,34 +103,33 @@ export const stayAlignedSettingsPage = defineSettingsPage({
path: 'stay-aligned',
title: 'settings-sidebar-stay_aligned',
groups: {
- setup: {
- title: 'settings-stay_aligned-setup_group',
+ general: {
rows: {
- setup: {
- title: 'settings-stay_aligned-setup-label',
- description: 'settings-stay_aligned-setup-label-description',
- },
enabled: {
title: 'settings-stay_aligned-enabled-label',
description: 'settings-stay_aligned-enabled-label-description',
},
},
},
- relaxedPoses: {
- title: 'settings-stay_aligned-relaxed_poses-label',
- description: 'settings-stay_aligned-relaxed_poses-description',
+ status: {
+ title: 'settings-stay_aligned-status_group',
+ rows: {},
+ },
+ poses: {
+ title: 'settings-stay_aligned-poses_group',
+ description: 'settings-stay_aligned-poses_group-description',
rows: {
standing: {
- title: 'settings-stay_aligned-relaxed_poses-standing',
- description: 'settings-stay_aligned-relaxed_poses-pose-description',
+ title: 'settings-stay_aligned-pose-standing',
+ description: 'settings-stay_aligned-pose-standing-description',
},
sitting: {
- title: 'settings-stay_aligned-relaxed_poses-sitting',
- description: 'settings-stay_aligned-relaxed_poses-pose-description',
+ title: 'settings-stay_aligned-pose-sitting',
+ description: 'settings-stay_aligned-pose-sitting-description',
},
flat: {
- title: 'settings-stay_aligned-relaxed_poses-flat',
- description: 'settings-stay_aligned-relaxed_poses-pose-description',
+ title: 'settings-stay_aligned-pose-flat',
+ description: 'settings-stay_aligned-pose-flat-description',
},
},
},
@@ -182,115 +148,17 @@ export const stayAlignedSettingsPage = defineSettingsPage({
const { groups } = stayAlignedSettingsPage;
export function StayAlignedSettings() {
- const setSettings = useSetAtom(stayAlignedSettingsAtom);
- const settings = useAtomValue(stayAlignedSettingsValueAtom);
- const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
+ const { settings, setEnabled, setPoseEnabled, resetPose } =
+ useStayAlignedSettings();
+ const status = useStayAlignedStatus();
const defaults = useSettingsDefaults().stayAligned;
-
- const { control, watch, handleSubmit, reset, setValue } =
- useForm({
- defaultValues: toForm(defaults),
- mode: 'onChange',
- reValidateMode: 'onChange',
- });
-
- const values = watch();
-
- const onSubmit = (values: StayAlignedSettingsForm) => {
- const settingsReq = new ChangeStayAlignedSettingsRequestT();
- settingsReq.enabled = values.enabled;
- settingsReq.standingEnabled = values.standingEnabled;
- settingsReq.sittingEnabled = values.sittingEnabled;
- settingsReq.flatEnabled = values.flatEnabled;
-
- sendRPCPacket(RpcMessage.ChangeStayAlignedSettingsRequest, settingsReq);
- };
-
- const resetTo = (
- name: 'enabled' | 'standingEnabled' | 'sittingEnabled' | 'flatEnabled'
- ) =>
- settingReset(
- defaults[name],
- watch(name),
- (next) => {
- setValue(name, next);
- handleSubmit(onSubmit)();
- }
- );
-
- useEffect(() => {
- const subscription = watch((_, { type }) => {
- if (type === 'change') handleSubmit(onSubmit)();
- });
- return () => subscription.unsubscribe();
- }, []);
-
- useConnectedEffect(() => {
- sendRPCPacket(
- RpcMessage.StayAlignedSettingsRequest,
- new StayAlignedSettingsRequestT()
- );
- }, []);
-
- useEffect(() => {
- if (!settings) return;
- reset(toForm(settings));
- }, [settings]);
-
- useRPCPacket(
- RpcMessage.StayAlignedSettingsResponse,
- (settings: StayAlignedSettingsResponseT) => {
- setSettings(settings);
- }
+ const [recordingPose, setRecordingPose] = useState(
+ null
);
- const config = values;
- const hasStandingPose =
- config.standingEnabled ||
- config.standingUpperLegAngle !== 0.0 ||
- config.standingLowerLegAngle !== 0.0 ||
- config.standingFootAngle !== 0.0;
- const hasSittingPose =
- config.sittingEnabled ||
- config.sittingUpperLegAngle !== 0.0 ||
- config.sittingLowerLegAngle !== 0.0 ||
- config.sittingFootAngle !== 0.0;
- const hasFlatPose =
- config.flatEnabled ||
- config.flatUpperLegAngle !== 0.0 ||
- config.flatLowerLegAngle !== 0.0 ||
- config.flatFootAngle !== 0.0;
-
- const openStanding = useState(false);
- const openSitting = useState(false);
- const openFlat = useState(false);
-
- const poses = [
- {
- id: 'standing',
- setting: groups.relaxedPoses.rows.standing,
- name: 'standingEnabled' as const,
- hasPose: hasStandingPose,
- open: openStanding,
- modal: ,
- },
- {
- id: 'sitting',
- setting: groups.relaxedPoses.rows.sitting,
- name: 'sittingEnabled' as const,
- hasPose: hasSittingPose,
- open: openSitting,
- modal: ,
- },
- {
- id: 'flat',
- setting: groups.relaxedPoses.rows.flat,
- name: 'flatEnabled' as const,
- hasPose: hasFlatPose,
- open: openFlat,
- modal: ,
- },
- ];
+ // The defaults fill the page until the real settings arrive, the controls wait with a loading state
+ const loaded = settings !== null;
+ const shown = settings ?? defaults;
return (
-
-
+
- }
- />
- (
+ defaults.enabled,
+ shown.enabled,
+ setEnabled
+ )}
control={
- setEnabled(event.currentTarget.checked)}
/>
}
/>
-
- {poses.map(({ id, setting, name, hasPose, open, modal }) => (
-
- {modal}
-
- open[1](true)}
- />
-
-
-
- }
- />
- ))}
+
+
+
+
+
+
+
+ {POSE_ORDER.map((poseId) => {
+ const pose = shown.poses.find(
+ (candidate) => candidate.pose === poseId
+ );
+ if (!pose) return null;
+ return (
+ setRecordingPose(poseId)}
+ onToggle={(enabled) => setPoseEnabled(poseId, enabled)}
+ onReset={() => resetPose(poseId)}
+ />
+ );
+ })}
}
+ control={ }
/>
+
+ setRecordingPose(null)}
+ />
);
}
diff --git a/gui/app/src/components/settings/pages/components/StayAlignedPoseModal.tsx b/gui/app/src/components/settings/pages/components/StayAlignedPoseModal.tsx
deleted file mode 100644
index a2ddbab7c..000000000
--- a/gui/app/src/components/settings/pages/components/StayAlignedPoseModal.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import { BaseModal } from '@/components/commons/BaseModal';
-import { Button } from '@/components/commons/Button';
-import { Typography } from '@/components/commons/Typography';
-import {
- DetectRelaxedPoseButton,
- ResetRelaxedPoseButton,
-} from '@/components/stay-aligned/RelaxedPose';
-import { useLocalization } from '@fluent/react';
-import { Dispatch, ReactNode, SetStateAction } from 'react';
-import { StayAlignedRelaxedPose } from 'solarxr-protocol';
-
-function StayAlignedPoseModal({
- open,
- title,
- descriptionKeys,
- children,
- relaxedPose,
-}: {
- open: [boolean, Dispatch>];
- title: string;
- descriptionKeys: string[];
- children: ReactNode;
- relaxedPose: StayAlignedRelaxedPose;
- lastStep?: boolean;
-}) {
- const { l10n } = useLocalization();
-
- return (
- {
- open[1](false);
- }}
- >
-
-
- {l10n.getString(title)}
-
-
- {descriptionKeys.map((descriptionKey, i) => (
- {l10n.getString(descriptionKey)}
- ))}
-
-
- {children}
-
-
-
open[1](false)}>
- {l10n.getString('settings-stay_aligned-relaxed_poses-close')}
-
-
- {
- open[1](false);
- }}
- pose={relaxedPose}
- >
- {l10n.getString('settings-stay_aligned-relaxed_poses-reset_pose')}
-
- {
- open[1](false);
- }}
- pose={relaxedPose}
- />
-
-
-
-
- );
-}
-
-export const StandingRelaxedPoseModal = ({
- open,
-}: {
- open: [boolean, Dispatch>];
-}) => (
-
-
-
-);
-
-export const SittingRelaxedPoseModal = ({
- open,
-}: {
- open: [boolean, Dispatch>];
-}) => (
-
-
-
-);
-
-export const FlatRelaxedPoseModal = ({
- open,
-}: {
- open: [boolean, Dispatch>];
-}) => (
-
-
-
-);
diff --git a/gui/app/src/components/settings/search-destinations.ts b/gui/app/src/components/settings/search-destinations.ts
index 606a58b86..4f5c38504 100644
--- a/gui/app/src/components/settings/search-destinations.ts
+++ b/gui/app/src/components/settings/search-destinations.ts
@@ -43,11 +43,5 @@ export const searchDestinations: SearchDestination[] = [
title: 'navbar-connect_trackers',
state: { alonePage: true },
},
- {
- section: 'page',
- path: '/onboarding/stay-aligned',
- title: 'onboarding-stay_aligned-title',
- state: { alonePage: true },
- },
{ section: 'page', path: '/onboarding/home', title: 'navbar-onboarding' },
];
diff --git a/gui/app/src/components/stay-aligned/PoseRecorderModal.tsx b/gui/app/src/components/stay-aligned/PoseRecorderModal.tsx
new file mode 100644
index 000000000..76dddd9cd
--- /dev/null
+++ b/gui/app/src/components/stay-aligned/PoseRecorderModal.tsx
@@ -0,0 +1,551 @@
+import classNames from 'classnames';
+import { Localized, useLocalization } from '@fluent/react';
+import { ReactNode, useEffect, useMemo } from 'react';
+import { useAtomValue } from 'jotai';
+import {
+ MountingMethod,
+ ResetLifecycle,
+ ResetType,
+ StayAlignedPart,
+ StayAlignedPoseCountdownT,
+ StayAlignedPoseRecordingDetail,
+ StayAlignedPoseRecordingLifecycle,
+ StayAlignedPoseRecordingStatusResponseT,
+ StayAlignedStatusResponseT,
+} from 'solarxr-protocol';
+import { BaseModal } from '@/components/commons/BaseModal';
+import { Button } from '@/components/commons/Button';
+import { FullResetExamples } from '@/components/commons/FullResetExamples';
+import { IconButton } from '@/components/commons/IconButton';
+import { Timeline, TimelineItem } from '@/components/commons/Timeline';
+import { Typography } from '@/components/commons/Typography';
+import { CloseIcon } from '@/components/commons/icon/CloseIcon';
+import { ResetButton } from '@/components/home/ResetButton';
+import {
+ PoseMountingInstructions,
+ PoseMountingVideo,
+} from '@/components/mounting/PoseMountingVideo';
+import { StepMedia } from '@/components/mounting/StepMountingStatus';
+import { useCancelReset } from '@/hooks/reset';
+import { useLocaleConfig } from '@/i18n/config';
+import {
+ PART_LABEL,
+ POSE_DESCRIPTION,
+ POSE_IMAGE,
+ POSE_TITLE,
+ RecordablePose,
+ RecorderStep,
+ useRecorderSteps,
+ useStayAlignedRecording,
+} from '@/hooks/stay-aligned';
+import { resetStatusAtom } from '@/store/app-store';
+import { RecordingLive } from './RecordingLive';
+
+const MODAL_CLASSES = classNames(
+ 'focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent outline-none',
+ 'relative flex flex-col gap-4 bg-background-70 border border-background-60 p-6 rounded-lg m-2',
+ 'text-background-10 text-standard w-[min(920px,100%)]',
+ 'mobile:w-full mobile:p-4 mobile:h-[min(40rem,calc(100dvh-1rem))]'
+);
+
+const STEP_TITLE: Record = {
+ trackers: 'settings-stay_aligned-recorder-step-trackers',
+ 'full-reset': 'settings-stay_aligned-recorder-step-full_reset',
+ mounting: 'settings-stay_aligned-recorder-step-mounting',
+ 'feet-mounting': 'settings-stay_aligned-recorder-step-feet_mounting',
+ record: 'settings-stay_aligned-recorder-step-record',
+};
+
+interface RecorderFrame {
+ pose: RecordablePose;
+ timeline: RecorderStep[];
+ current: RecorderStep;
+ onClose: () => void;
+}
+
+function RecorderTimeline({
+ timeline,
+ current,
+ body,
+}: {
+ timeline: RecorderStep[];
+ current: RecorderStep;
+ body: ReactNode;
+}) {
+ if (timeline.length === 1) return <>{body}>;
+
+ const currentIndex = timeline.indexOf(current);
+ const stateOf = (index: number) => {
+ if (index < currentIndex) return 'done';
+ if (index === currentIndex) return 'current';
+ return 'todo';
+ };
+
+ return (
+
+ {timeline.map((step, index) => (
+ }
+ >
+ {step === current && (
+ {body}
+ )}
+
+ ))}
+
+ );
+}
+
+function RecorderLayout({
+ frame,
+ body,
+ media,
+ actions,
+}: {
+ frame: RecorderFrame;
+ body: ReactNode;
+ media: ReactNode;
+ actions: ReactNode;
+}) {
+ return (
+ <>
+
+
+
+
+
+
+ >
+ );
+}
+
+function TrackersStep({
+ frame,
+ missingParts,
+}: {
+ frame: RecorderFrame;
+ missingParts: StayAlignedPart[];
+}) {
+ const { l10n } = useLocalization();
+ const { currentLocales } = useLocaleConfig();
+ const partList = useMemo(
+ () => new Intl.ListFormat(currentLocales, { type: 'conjunction' }),
+ [currentLocales]
+ );
+
+ return (
+
+
+ l10n.getString(PART_LABEL[part]))
+ ),
+ }}
+ />
+ >
+ }
+ media={
+
+ }
+ actions={
+
+ }
+ />
+ );
+}
+
+function FullResetStep({
+ frame,
+ onDone,
+}: {
+ frame: RecorderFrame;
+ onDone: () => void;
+}) {
+ return (
+
+
+
+
+
+
+
+ >
+ }
+ media={
+
+ }
+ actions={ }
+ />
+ );
+}
+
+function MountingStep({
+ frame,
+ mountingMethod,
+ onDone,
+}: {
+ frame: RecorderFrame;
+ mountingMethod: MountingMethod | undefined;
+ onDone: () => void;
+}) {
+ const stepMounting = mountingMethod === MountingMethod.STEP;
+
+ return (
+
+
+ {stepMounting ? (
+
+
+
+
+ ) : (
+
+ )}
+ >
+ }
+ media={
+ stepMounting ? (
+
+ ) : (
+
+ )
+ }
+ actions={
+
+ }
+ />
+ );
+}
+
+function FeetMountingStep({
+ frame,
+ onDone,
+}: {
+ frame: RecorderFrame;
+ onDone: () => void;
+}) {
+ return (
+
+
+
+
+
+
+ >
+ }
+ media={
+
+
+
+
+ }
+ actions={
+
+ }
+ />
+ );
+}
+
+type RecordPhase = 'idle' | 'countdown' | 'waiting' | 'failed';
+
+function recordPhase(
+ recording: StayAlignedPoseRecordingStatusResponseT | null
+): RecordPhase {
+ switch (recording?.lifecycle) {
+ case StayAlignedPoseRecordingLifecycle.RUNNING:
+ return recording.detailType ===
+ StayAlignedPoseRecordingDetail.StayAlignedPoseCountdown
+ ? 'countdown'
+ : 'waiting';
+ case StayAlignedPoseRecordingLifecycle.FAILED:
+ return 'failed';
+ default:
+ return 'idle';
+ }
+}
+
+function RecordActions({
+ phase,
+ recording,
+ onStart,
+ onRedoPreparation,
+}: {
+ phase: RecordPhase;
+ recording: StayAlignedPoseRecordingStatusResponseT | null;
+ onStart: () => void;
+ onRedoPreparation: () => void;
+}) {
+ if (phase === 'countdown' && recording) {
+ // The countdown replaces the label, like the reset buttons
+ const { progress, duration } =
+ recording.detail as StayAlignedPoseCountdownT;
+ return (
+
+
+
+
+
+ {duration - progress}
+
+
+ );
+ }
+ if (phase === 'waiting') {
+ return (
+
+ );
+ }
+ if (phase === 'failed') {
+ return (
+ <>
+
+
+ >
+ );
+ }
+ return (
+
+ );
+}
+
+function RecordStep({
+ frame,
+ phase,
+ recording,
+ onStart,
+ onRedoPreparation,
+}: {
+ frame: RecorderFrame;
+ phase: RecordPhase;
+ recording: StayAlignedPoseRecordingStatusResponseT | null;
+ onStart: () => void;
+ onRedoPreparation: () => void;
+}) {
+ const live = (phase === 'waiting' || phase === 'failed') && recording;
+
+ return (
+
+
+ {' '}
+
+
+
+ {live ? (
+
+ ) : (
+
+
+
+
+ )}
+
+ >
+ }
+ media={
+
+ }
+ actions={
+
+ }
+ />
+ );
+}
+
+function PoseRecorder({
+ pose,
+ status,
+ onClose,
+}: {
+ pose: RecordablePose;
+ status: StayAlignedStatusResponseT | null;
+ onClose: () => void;
+}) {
+ const { recording, start, cancel, clear } = useStayAlignedRecording();
+ const resetStatus = useAtomValue(resetStatusAtom);
+ const cancelReset = useCancelReset();
+
+ const phase = recordPhase(recording);
+ const recordingRuns = phase === 'countdown' || phase === 'waiting';
+ const steps = useRecorderSteps(recordingRuns, status);
+
+ // A saved pose has nothing left to show
+ useEffect(() => {
+ if (recording?.lifecycle === StayAlignedPoseRecordingLifecycle.DONE)
+ onClose();
+ }, [recording]);
+
+ const frame: RecorderFrame = {
+ pose,
+ timeline: steps.timeline,
+ current: steps.current,
+ onClose: () => {
+ if (recordingRuns) cancel();
+ if (resetStatus?.lifecycle === ResetLifecycle.RUNNING) cancelReset();
+ onClose();
+ },
+ };
+
+ switch (steps.current) {
+ case 'trackers':
+ return ;
+ case 'full-reset':
+ return (
+ steps.done('full-reset')} />
+ );
+ case 'mounting':
+ return (
+ steps.done('mounting')}
+ />
+ );
+ case 'feet-mounting':
+ return (
+ steps.done('feet-mounting')}
+ />
+ );
+ case 'record':
+ return (
+ start(pose)}
+ onRedoPreparation={() => {
+ clear();
+ steps.redo();
+ }}
+ />
+ );
+ }
+}
+
+export function PoseRecorderModal({
+ pose,
+ status,
+ onClose,
+}: {
+ pose: RecordablePose | null;
+ status: StayAlignedStatusResponseT | null;
+ onClose: () => void;
+}) {
+ return (
+
+ {pose !== null && (
+
+ )}
+
+ );
+}
diff --git a/gui/app/src/components/stay-aligned/PoseRow.tsx b/gui/app/src/components/stay-aligned/PoseRow.tsx
new file mode 100644
index 000000000..f3e01a49a
--- /dev/null
+++ b/gui/app/src/components/stay-aligned/PoseRow.tsx
@@ -0,0 +1,126 @@
+import classNames from 'classnames';
+import { StayAlignedPoseT } from 'solarxr-protocol';
+import { Button } from '@/components/commons/Button';
+import { CheckboxInternal } from '@/components/commons/Checkbox';
+import { StatusBadge, StatusVariant } from '@/components/commons/StatusBadge';
+import { Tooltip } from '@/components/commons/Tooltip';
+import { Typography } from '@/components/commons/Typography';
+import { SettingResetButton } from '@/components/settings/SettingReset';
+import { useFocusSetting } from '@/components/settings/SettingRow';
+import { SettingDef } from '@/components/settings/settings-definitions';
+import {
+ POSE_DESCRIPTION,
+ POSE_IMAGE,
+ POSE_KEY,
+ POSE_TITLE,
+ RecordablePose,
+} from '@/hooks/stay-aligned';
+
+function sourceBadge(pose: StayAlignedPoseT): {
+ id: string;
+ variant: StatusVariant;
+} {
+ if (pose.recorded) {
+ return { id: 'settings-stay_aligned-badge-recorded', variant: 'success' };
+ }
+ if (pose.hasDefault) {
+ return { id: 'settings-stay_aligned-badge-default', variant: 'special' };
+ }
+ return { id: 'settings-stay_aligned-badge-not_recorded', variant: 'neutral' };
+}
+
+export function PoseRow({
+ setting,
+ poseId,
+ pose,
+ onRecord,
+ onToggle,
+ onReset,
+ loading,
+ suggested,
+ reset,
+}: {
+ setting: SettingDef;
+ poseId: RecordablePose;
+ pose: StayAlignedPoseT;
+ loading: boolean;
+ suggested: boolean;
+ reset: boolean;
+ onRecord: () => void;
+ onToggle: (enabled: boolean) => void;
+ onReset: () => void;
+}) {
+ const { ref, highlighted } = useFocusSetting(
+ setting.key
+ );
+ const key = POSE_KEY[poseId];
+ const badge = sourceBadge(pose);
+ const toggleBlocked = !pose.recorded && !pose.hasDefault;
+ const recordId = pose.recorded
+ ? 'settings-stay_aligned-record_again'
+ : 'settings-stay_aligned-record';
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ }
+ preferedDirection="top"
+ disabled={!toggleBlocked}
+ >
+ onToggle(event.currentTarget.checked)}
+ />
+
+
+
+
+
+
+ );
+}
diff --git a/gui/app/src/components/stay-aligned/RecordingLive.tsx b/gui/app/src/components/stay-aligned/RecordingLive.tsx
new file mode 100644
index 000000000..0937efccd
--- /dev/null
+++ b/gui/app/src/components/stay-aligned/RecordingLive.tsx
@@ -0,0 +1,198 @@
+import classNames from 'classnames';
+import { useLocalization } from '@fluent/react';
+import {
+ StayAlignedPart,
+ StayAlignedPoseRecordingDetail,
+ StayAlignedPoseRecordingFailure,
+ StayAlignedPoseRecordingLifecycle,
+ StayAlignedPoseRecordingStatusResponseT,
+ StayAlignedPoseWaitingT,
+ StayAlignedRecordingTrackerState,
+ StayAlignedRelaxedPose,
+} from 'solarxr-protocol';
+import { ProgressBar } from '@/components/commons/ProgressBar';
+import { Typography } from '@/components/commons/Typography';
+import { CrossIcon } from '@/components/commons/icon/CrossIcon';
+import { WarningIcon } from '@/components/commons/icon/WarningIcon';
+import { PART_LABEL, PART_ORDER, POSITION_LABEL } from '@/hooks/stay-aligned';
+
+const STATE_DOT: Record = {
+ [StayAlignedRecordingTrackerState.STILL]: 'bg-status-success',
+ [StayAlignedRecordingTrackerState.MOVING]: 'bg-status-warning',
+};
+
+const STATE_LABEL: Record = {
+ [StayAlignedRecordingTrackerState.STILL]:
+ 'settings-stay_aligned-recorder-state-still',
+ [StayAlignedRecordingTrackerState.MOVING]:
+ 'settings-stay_aligned-recorder-state-moving',
+};
+
+const BADGE_CLASSES =
+ 'flex h-8 w-8 shrink-0 items-center justify-center rounded-full fill-background-10 text-standard-bold tabular-nums';
+
+function RecordingBadge({
+ failed,
+ wrongPose,
+ secondsLeft,
+}: {
+ failed: boolean;
+ wrongPose: boolean;
+ secondsLeft: number;
+}) {
+ if (failed) {
+ return (
+
+
+
+ );
+ }
+ if (wrongPose) {
+ return (
+
+
+
+ );
+ }
+ return (
+
+ {secondsLeft}
+
+ );
+}
+
+function RecordingStatus({
+ recording,
+ failed,
+ wrongPose,
+ detectedPose,
+}: {
+ recording: StayAlignedPoseRecordingStatusResponseT;
+ failed: boolean;
+ wrongPose: boolean;
+ detectedPose: StayAlignedRelaxedPose;
+}) {
+ const { l10n } = useLocalization();
+
+ if (wrongPose) {
+ return (
+
+ {' '}
+
+
+ );
+ }
+ if (!failed) {
+ return ;
+ }
+ if (recording.failure === StayAlignedPoseRecordingFailure.MISSING_TRACKERS) {
+ return ;
+ }
+ if (recording.failure === StayAlignedPoseRecordingFailure.NOT_CALIBRATED) {
+ return (
+
+ );
+ }
+ return ;
+}
+
+export function RecordingLive({
+ recording,
+}: {
+ recording: StayAlignedPoseRecordingStatusResponseT;
+}) {
+ const failed =
+ recording.lifecycle === StayAlignedPoseRecordingLifecycle.FAILED;
+
+ const waiting =
+ recording.detailType ===
+ StayAlignedPoseRecordingDetail.StayAlignedPoseWaiting
+ ? (recording.detail as StayAlignedPoseWaitingT)
+ : null;
+
+ const trackers = waiting?.trackers ?? [];
+
+ const wrongPose = failed
+ ? recording.failure === StayAlignedPoseRecordingFailure.WRONG_POSE ||
+ recording.failure === StayAlignedPoseRecordingFailure.POSITION_UNKNOWN
+ : waiting?.detectedPose !== recording.pose;
+
+ const secondsLeft = waiting ? waiting.duration - waiting.progress : 0;
+ const timeLeft = waiting ? secondsLeft / waiting.duration : 0;
+
+ return (
+
+
+
+
+ {PART_ORDER.map((part) => {
+ const state = trackers.find(
+ (tracker) => tracker.part === part
+ )?.state;
+ if (state === undefined) return null;
+ const moving = state === StayAlignedRecordingTrackerState.MOVING;
+ return (
+
+
+
+
+
+
+
+
+
+ );
+ })}
+
+
+ );
+}
diff --git a/gui/app/src/components/stay-aligned/RelaxedPose.tsx b/gui/app/src/components/stay-aligned/RelaxedPose.tsx
deleted file mode 100644
index b4b127ee4..000000000
--- a/gui/app/src/components/stay-aligned/RelaxedPose.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { useLocalization } from '@fluent/react';
-import {
- DetectStayAlignedRelaxedPoseRequestT,
- RpcMessage,
- StayAlignedRelaxedPose,
-} from 'solarxr-protocol';
-import { useWebsocketAPI } from '@/hooks/websocket-api';
-import { MouseEventHandler } from 'react';
-import { Button, ButtonProps } from '@/components/commons/Button';
-
-/**
- * Tells the server to set a relaxed pose to the current pose's angles.
- */
-export function DetectRelaxedPoseButton({
- pose,
- onClick,
-}: {
- pose: StayAlignedRelaxedPose;
- onClick?: MouseEventHandler;
-}) {
- const { sendRPCPacket } = useWebsocketAPI();
- const { l10n } = useLocalization();
-
- return (
- {
- const req = new DetectStayAlignedRelaxedPoseRequestT();
- req.pose = pose;
- sendRPCPacket(RpcMessage.DetectStayAlignedRelaxedPoseRequest, req);
- if (onClick) {
- onClick(e);
- }
- }}
- >
- {l10n.getString('settings-stay_aligned-relaxed_poses-save_pose')}
-
- );
-}
-
-/**
- * Tells the server to reset the angles in a relaxed pose.
- */
-export function ResetRelaxedPoseButton({
- pose,
- variant = 'primary',
- onClick,
- children,
-}: {
- variant: ButtonProps['variant'];
- pose: StayAlignedRelaxedPose;
- onClick?: MouseEventHandler;
-} & React.PropsWithChildren) {
- const { sendRPCPacket } = useWebsocketAPI();
- const { l10n } = useLocalization();
-
- return (
- {
- const req = new DetectStayAlignedRelaxedPoseRequestT();
- req.pose = pose;
- sendRPCPacket(RpcMessage.ResetStayAlignedRelaxedPoseRequest, req);
- if (onClick) {
- onClick(e);
- }
- }}
- >
- {children ||
- l10n.getString('settings-stay_aligned-relaxed_poses-reset_pose')}
-
- );
-}
diff --git a/gui/app/src/components/stay-aligned/StayAlignedStatusRow.tsx b/gui/app/src/components/stay-aligned/StayAlignedStatusRow.tsx
new file mode 100644
index 000000000..85829454d
--- /dev/null
+++ b/gui/app/src/components/stay-aligned/StayAlignedStatusRow.tsx
@@ -0,0 +1,220 @@
+import { useLocalization } from '@fluent/react';
+import { useMemo } from 'react';
+import {
+ BodyPart,
+ StayAlignedPoseState,
+ StayAlignedStatusResponseT,
+} from 'solarxr-protocol';
+import {
+ StatusBadge,
+ StatusRow,
+ StatusVariant,
+} from '@/components/commons/StatusBadge';
+import { Typography } from '@/components/commons/Typography';
+import { useLocaleConfig } from '@/i18n/config';
+import { PART_LABEL, POSITION_LABEL } from '@/hooks/stay-aligned';
+
+interface StatusLine {
+ variant: StatusVariant;
+ badge: string;
+ text: string;
+}
+
+const POSE_STATUS: Record = {
+ [StayAlignedPoseState.ENABLED]: {
+ variant: 'success',
+ badge: 'settings-stay_aligned-status-badge-pose-ready',
+ text: 'settings-stay_aligned-status-pose-ready',
+ },
+ [StayAlignedPoseState.NOT_RECORDED]: {
+ variant: 'warning',
+ badge: 'settings-stay_aligned-status-badge-pose-not_recorded',
+ text: 'settings-stay_aligned-status-pose-not_recorded',
+ },
+ [StayAlignedPoseState.DISABLED]: {
+ variant: 'neutral',
+ badge: 'settings-stay_aligned-status-badge-pose-disabled',
+ text: 'settings-stay_aligned-status-pose-disabled',
+ },
+};
+
+const POSE_UNKNOWN: StatusLine = {
+ variant: 'warning',
+ badge: 'settings-stay_aligned-status-badge-pose-unknown',
+ text: 'settings-stay_aligned-status-pose-unknown',
+};
+
+function correction(status: StayAlignedStatusResponseT): StatusLine {
+ if (!status.enabled) {
+ return {
+ variant: 'neutral',
+ badge: 'settings-stay_aligned-status-badge-disabled',
+ text: 'settings-stay_aligned-status-text-disabled',
+ };
+ }
+ if (status.missingParts.length > 0) {
+ return {
+ variant: 'warning',
+ badge: 'settings-stay_aligned-status-badge-not_correcting',
+ text: 'settings-stay_aligned-trackers-missing',
+ };
+ }
+ if (status.detectedPose?.state !== StayAlignedPoseState.ENABLED) {
+ return {
+ variant: 'neutral',
+ badge: 'settings-stay_aligned-status-badge-not_correcting',
+ text: 'settings-stay_aligned-status-text-pose_unusable',
+ };
+ }
+ return {
+ variant: 'success',
+ badge: 'settings-stay_aligned-status-badge-correcting',
+ text: 'settings-stay_aligned-status-text-correcting',
+ };
+}
+
+function position(status: StayAlignedStatusResponseT): StatusLine {
+ const line = status.detectedPose
+ ? POSE_STATUS[status.detectedPose.state]
+ : POSE_UNKNOWN;
+ // Nothing is corrected while Stay Aligned is off, so no pose is good or bad
+ if (!status.enabled) return { ...line, variant: 'neutral' };
+ return line;
+}
+
+function PositionText({
+ status,
+ text,
+}: {
+ status: StayAlignedStatusResponseT;
+ text: string;
+}) {
+ const { l10n } = useLocalization();
+ if (!status.detectedPose) return ;
+ return (
+
+ {' '}
+
+
+ );
+}
+
+function CorrectionValue({ status }: { status: StayAlignedStatusResponseT }) {
+ const { currentLocales } = useLocaleConfig();
+ const degreeFormat = useMemo(
+ () =>
+ new Intl.NumberFormat(currentLocales, {
+ style: 'unit',
+ unit: 'degree',
+ unitDisplay: 'narrow',
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ }),
+ [currentLocales]
+ );
+
+ return (
+
+
+ {degreeFormat.format(status.largestCorrection?.degrees ?? 0)}
+
+
+ );
+}
+
+function CorrectionText({ status }: { status: StayAlignedStatusResponseT }) {
+ const { l10n } = useLocalization();
+ if (!status.enabled) {
+ return (
+
+ );
+ }
+ if (!status.largestCorrection) {
+ return (
+
+ );
+ }
+ return (
+
+ );
+}
+
+export function StayAlignedStatusRow({
+ status,
+}: {
+ status: StayAlignedStatusResponseT | null;
+}) {
+ const { l10n } = useLocalization();
+ const { currentLocales } = useLocaleConfig();
+ const partList = useMemo(
+ () => new Intl.ListFormat(currentLocales, { type: 'conjunction' }),
+ [currentLocales]
+ );
+ const shown = status && correction(status);
+ const pose = status && position(status);
+
+ return (
+
+
+ }
+ badge={
+ shown &&
+ }
+ >
+ {status && shown && (
+
+ l10n.getString(PART_LABEL[part])
+ )
+ ),
+ }}
+ />
+ )}
+
+
+ }
+ badge={pose && }
+ >
+ {status && pose && }
+
+
+ }
+ badge={status && }
+ >
+ {status && }
+
+
+ );
+}
diff --git a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx
index a45f1a012..7d8bcebdf 100644
--- a/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx
+++ b/gui/app/src/components/tracking-checklist/TrackingChecklist.tsx
@@ -454,8 +454,7 @@ const stepContentLookup: Record<
{step.ignorable && (
= {
+ [StayAlignedRelaxedPose.STANDING]: 'standing',
+ [StayAlignedRelaxedPose.SITTING]: 'sitting',
+ [StayAlignedRelaxedPose.FLAT]: 'flat',
+};
+
+export const POSE_TITLE: Record = {
+ [StayAlignedRelaxedPose.STANDING]: 'settings-stay_aligned-pose-standing',
+ [StayAlignedRelaxedPose.SITTING]: 'settings-stay_aligned-pose-sitting',
+ [StayAlignedRelaxedPose.FLAT]: 'settings-stay_aligned-pose-flat',
+};
+
+export const POSE_DESCRIPTION: Record = {
+ [StayAlignedRelaxedPose.STANDING]: 'settings-stay_aligned-pose-standing-description',
+ [StayAlignedRelaxedPose.SITTING]: 'settings-stay_aligned-pose-sitting-description',
+ [StayAlignedRelaxedPose.FLAT]: 'settings-stay_aligned-pose-flat-description',
+};
+
+export const POSE_IMAGE: Record = {
+ [StayAlignedRelaxedPose.STANDING]: '/images/stay-aligned/StayAlignedStanding.webp',
+ [StayAlignedRelaxedPose.SITTING]: '/images/stay-aligned/StayAlignedSitting.webp',
+ [StayAlignedRelaxedPose.FLAT]: '/images/stay-aligned/StayAlignedFloor.webp',
+};
+
+export const POSITION_LABEL: Record = {
+ [StayAlignedRelaxedPose.UNKNOWN]: 'settings-stay_aligned-position-unknown',
+ [StayAlignedRelaxedPose.STANDING]: 'settings-stay_aligned-position-standing',
+ [StayAlignedRelaxedPose.SITTING]: 'settings-stay_aligned-position-sitting',
+ [StayAlignedRelaxedPose.FLAT]: 'settings-stay_aligned-position-flat',
+ [StayAlignedRelaxedPose.KNEELING]: 'settings-stay_aligned-position-kneeling',
+};
+
+export const PART_LABEL: Record = {
+ [StayAlignedPart.UPPER_BODY]: 'settings-stay_aligned-recorder-part-upper_body',
+ [StayAlignedPart.LEFT_UPPER_LEG]: 'body_part-LEFT_UPPER_LEG',
+ [StayAlignedPart.RIGHT_UPPER_LEG]: 'body_part-RIGHT_UPPER_LEG',
+ [StayAlignedPart.LEFT_LOWER_LEG]: 'body_part-LEFT_LOWER_LEG',
+ [StayAlignedPart.RIGHT_LOWER_LEG]: 'body_part-RIGHT_LOWER_LEG',
+ [StayAlignedPart.LEFT_FOOT]: 'body_part-LEFT_FOOT',
+ [StayAlignedPart.RIGHT_FOOT]: 'body_part-RIGHT_FOOT',
+};
+
+export const PART_ORDER = [
+ StayAlignedPart.UPPER_BODY,
+ StayAlignedPart.LEFT_UPPER_LEG,
+ StayAlignedPart.RIGHT_UPPER_LEG,
+ StayAlignedPart.LEFT_LOWER_LEG,
+ StayAlignedPart.RIGHT_LOWER_LEG,
+ StayAlignedPart.LEFT_FOOT,
+ StayAlignedPart.RIGHT_FOOT,
+];
+
+const PREP_ORDER: PrepStep[] = ['trackers', 'full-reset', 'mounting', 'feet-mounting'];
+
+export function useStayAlignedSettings() {
+ const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
+ const [settings, setSettings] = useState(null);
+
+ useRPCPacket(
+ RpcMessage.StayAlignedSettingsResponse,
+ (response: StayAlignedSettingsResponseT) => setSettings(response)
+ );
+
+ useConnectedEffect(() => {
+ sendRPCPacket(
+ RpcMessage.StayAlignedSettingsRequest,
+ new StayAlignedSettingsRequestT()
+ );
+ }, []);
+
+ const change = (override: {
+ enabled?: boolean;
+ pose?: { pose: StayAlignedRelaxedPose; enabled: boolean };
+ }) => {
+ if (!settings) return;
+
+ const request = new ChangeStayAlignedSettingsRequestT();
+ request.enabled = override.enabled ?? settings.enabled;
+ request.poseToggles = settings.poses.map((pose) => {
+ const toggle = new StayAlignedPoseToggleT();
+ toggle.pose = pose.pose;
+ toggle.enabled =
+ override.pose?.pose === pose.pose ? override.pose.enabled : pose.enabled;
+ return toggle;
+ });
+ sendRPCPacket(RpcMessage.ChangeStayAlignedSettingsRequest, request);
+ };
+
+ const resetPose = (pose: StayAlignedRelaxedPose) => {
+ const request = new ResetStayAlignedRelaxedPoseRequestT();
+ request.pose = pose;
+ sendRPCPacket(RpcMessage.ResetStayAlignedRelaxedPoseRequest, request);
+ };
+
+ return {
+ settings,
+ setEnabled: (enabled: boolean) => change({ enabled }),
+ setPoseEnabled: (pose: StayAlignedRelaxedPose, enabled: boolean) =>
+ change({ pose: { pose, enabled } }),
+ resetPose,
+ };
+}
+
+export function useStayAlignedStatus() {
+ const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
+ const [status, setStatus] = useState(null);
+
+ useRPCPacket(
+ RpcMessage.StayAlignedStatusResponse,
+ (response: StayAlignedStatusResponseT) => setStatus(response)
+ );
+
+ useConnectedEffect(() => {
+ sendRPCPacket(
+ RpcMessage.StartStayAlignedStatusRequest,
+ new StartStayAlignedStatusRequestT()
+ );
+ return () => {
+ sendRPCPacket(
+ RpcMessage.StopStayAlignedStatusRequest,
+ new StopStayAlignedStatusRequestT()
+ );
+ };
+ }, []);
+
+ return status;
+}
+
+function playRecordingSounds(
+ volume: number,
+ {
+ lifecycle,
+ detailType,
+ detail,
+ }: Omit
+) {
+ const sounds = resetSounds[ResetType.MOUNTING];
+
+ if (lifecycle === StayAlignedPoseRecordingLifecycle.DONE) {
+ restartAndPlay(sounds.end, volume);
+ restartAndPlay(sounds.mew, volume);
+ return;
+ }
+
+ if (
+ lifecycle !== StayAlignedPoseRecordingLifecycle.RUNNING ||
+ detailType !== StayAlignedPoseRecordingDetail.StayAlignedPoseCountdown
+ ) {
+ return;
+ }
+
+ const { progress } = detail as StayAlignedPoseCountdownT;
+ if (progress === 0) {
+ restartAndPlay(sounds.initial, volume);
+ }
+ playCountdownTick(sounds.tick, progress, volume);
+}
+
+export function useStayAlignedRecording() {
+ const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
+ const { config } = useConfig();
+ const [recording, setRecording] =
+ useState(null);
+
+ useRPCPacket(
+ RpcMessage.StayAlignedPoseRecordingStatusResponse,
+ (response: StayAlignedPoseRecordingStatusResponseT) => {
+ setRecording(response);
+ if (!config?.feedbackSound) return;
+ playRecordingSounds(config.feedbackSoundVolume ?? 1, response);
+ }
+ );
+
+ const start = (pose: StayAlignedRelaxedPose) => {
+ setRecording(null);
+ const request = new StartStayAlignedPoseRecordingRequestT();
+ request.pose = pose;
+ sendRPCPacket(RpcMessage.StartStayAlignedPoseRecordingRequest, request);
+ };
+
+ const cancel = () => {
+ sendRPCPacket(
+ RpcMessage.CancelStayAlignedPoseRecordingRequest,
+ new CancelStayAlignedPoseRecordingRequestT()
+ );
+ };
+
+ return { recording, start, cancel, clear: () => setRecording(null) };
+}
+
+export function useRecorderSteps(
+ recording: boolean,
+ status: StayAlignedStatusResponseT | null
+) {
+ const { steps: checklistSteps } = useTrackingChecklist();
+ const { resetsSettings } = useResetsSettings();
+ const [redone, setRedone] = useState([]);
+ const [seen, setSeen] = useState([]);
+
+ const needsCalibration = (id: TrackingChecklistStepId) => {
+ const step = checklistSteps.find((checklistStep) => checklistStep.id === id);
+ return !!step && step.enabled && !step.valid;
+ };
+ const feetSeparate = !!checklistSteps.find(
+ (checklistStep) =>
+ checklistStep.id === TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION
+ )?.enabled;
+
+ const mountingRuns =
+ resetsSettings?.mountingMethod === MountingMethod.STEP ||
+ resetsSettings?.mountingMethod === MountingMethod.POSE;
+
+ const mountingNeeded =
+ mountingRuns &&
+ (needsCalibration(TrackingChecklistStepId.MOUNTING_CALIBRATION) ||
+ redone.includes('mounting'));
+ const feetMountingNeeded =
+ feetSeparate &&
+ (needsCalibration(TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION) ||
+ redone.includes('feet-mounting'));
+ const fullResetNeeded =
+ needsCalibration(TrackingChecklistStepId.FULL_RESET) ||
+ redone.includes('full-reset');
+
+ const isNeeded = (step: PrepStep) => {
+ if (step === 'trackers') return (status?.missingParts.length ?? 0) > 0;
+ if (step === 'full-reset') return fullResetNeeded;
+ if (step === 'mounting') return mountingNeeded;
+ return feetMountingNeeded;
+ };
+ const needed = PREP_ORDER.filter(isNeeded);
+ const neededKey = needed.join();
+
+ useEffect(() => {
+ setSeen((previous) =>
+ needed.every((step) => previous.includes(step))
+ ? previous
+ : [...previous, ...needed.filter((step) => !previous.includes(step))]
+ );
+ }, [neededKey]);
+
+ // Once a recording runs it is not interrupted by what is asked
+ const current: RecorderStep = recording ? 'record' : (needed[0] ?? 'record');
+ const timeline: RecorderStep[] = [
+ ...PREP_ORDER.filter((step) => seen.includes(step) || needed.includes(step)),
+ 'record',
+ ];
+
+ return {
+ timeline,
+ current,
+ mountingMethod: resetsSettings?.mountingMethod,
+ missingParts: status?.missingParts ?? [],
+ redo: () => setRedone(['full-reset', 'mounting', 'feet-mounting']),
+ done: (step: PrepStep) =>
+ setRedone((previous) => previous.filter((s) => s !== step)),
+ };
+}
diff --git a/gui/app/src/hooks/tracker-assignment.ts b/gui/app/src/hooks/tracker-assignment.ts
index 0de5665c4..a7336677f 100644
--- a/gui/app/src/hooks/tracker-assignment.ts
+++ b/gui/app/src/hooks/tracker-assignment.ts
@@ -45,7 +45,7 @@ export function useTrackerAssignment(mode: AssignmentMode) {
const { sendRPCPacket, useRPCPacket, useConnectedEffect } = useWebsocketAPI();
const sendAssign = useAssignTracker();
const shell = providePicker();
- const { trackerByPart, flatTrackers } = shell;
+ const { trackerByPart } = shell;
const [pending, setPending] = useState(null);
const [panelOpen, setPanelOpen] = useState(false);
diff --git a/gui/app/src/sounds/sounds.ts b/gui/app/src/sounds/sounds.ts
index 5e18eac90..7b3f8b276 100644
--- a/gui/app/src/sounds/sounds.ts
+++ b/gui/app/src/sounds/sounds.ts
@@ -20,7 +20,7 @@ const mew = createAudio('/sounds/mew.ogg');
export const scaledProportionsClick = createAudio(
'/sounds/full-reset/full-click-1.ogg'
);
-const resetSounds: Record<
+export const resetSounds: Record<
ResetType,
{
initial: HTMLAudioElement | null;
@@ -116,6 +116,21 @@ export function restartAndPlay(audio: HTMLAudioElement | null, volume: number) {
}
}
+export function playCountdownTick(
+ ticks: HTMLAudioElement[] | null,
+ second: number,
+ volume: number
+) {
+ if (!ticks || second < 1) return;
+
+ const cycleLength = ticks.length * 2 - 2;
+ const positionInCycle = second % cycleLength;
+ const tickIndex =
+ positionInCycle < ticks.length ? positionInCycle : cycleLength - positionInCycle;
+
+ restartAndPlay(ticks[tickIndex], volume);
+}
+
export function handleResetSounds(
volume: number,
{ lifecycle, resetType, detailType, detail }: Omit
@@ -133,24 +148,7 @@ export function handleResetSounds(
restartAndPlay(sounds.initial, volume);
}
- if (sounds.tick) {
- const arrayLength = sounds.tick.length;
-
- const cycleLength = arrayLength * 2 - 2;
- const positionInCycle = Math.floor(progress / 1000) % cycleLength;
-
- let tickIndex;
-
- if (positionInCycle < arrayLength) {
- tickIndex = positionInCycle;
- } else {
- tickIndex = cycleLength - positionInCycle;
- }
-
- if (progress >= 1000 && sounds.tick[tickIndex]) {
- restartAndPlay(sounds.tick[tickIndex], volume);
- }
- }
+ playCountdownTick(sounds.tick, Math.floor(progress / 1000), volume);
}
if (lifecycle === ResetLifecycle.DONE) {
diff --git a/server/core/src/main/java/dev/slimevr/config/settings.kt b/server/core/src/main/java/dev/slimevr/config/settings.kt
index f010202e3..bac23bed7 100644
--- a/server/core/src/main/java/dev/slimevr/config/settings.kt
+++ b/server/core/src/main/java/dev/slimevr/config/settings.kt
@@ -162,31 +162,10 @@ data class VMCConfig(
val vrmJson: String? = null,
)
-// Used in StayAlignedConfig
-@Serializable
-data class StayAlignedRelaxedPoseConfig(
- /** Whether Stay Aligned should adjust the tracker yaws when the player is in this pose. */
- var enabled: Boolean = false,
- /** Angle between the upper leg yaw and the centre yaw. */
- var upperLegAngleInDeg: Float = 0.0f,
- /** Angle between the lower leg yaw and the centre yaw. */
- var lowerLegAngleInDeg: Float = 0.0f,
- /** Angle between the foot and the centre yaw. */
- var footAngleInDeg: Float = 0.0f,
-)
-
@Serializable
data class StayAlignedConfig(
- /** Global enable toggle for all poses */
- var enabled: Boolean = false,
- /** Standing relaxed pose */
- val standingRelaxedPose: StayAlignedRelaxedPoseConfig = StayAlignedRelaxedPoseConfig(),
- /** Sitting relaxed pose */
- val sittingRelaxedPose: StayAlignedRelaxedPoseConfig = StayAlignedRelaxedPoseConfig(),
- /** Flat relaxed pose */
- val flatRelaxedPose: StayAlignedRelaxedPoseConfig = StayAlignedRelaxedPoseConfig(),
- /** Whether setup has been completed */
- var setupComplete: Boolean = false,
+ /** Whether Stay Aligned runs. The relaxed poses it uses are in the user config. */
+ val enabled: Boolean = false,
)
@Serializable
diff --git a/server/core/src/main/java/dev/slimevr/config/user.kt b/server/core/src/main/java/dev/slimevr/config/user.kt
index bc6fcd464..160197d93 100644
--- a/server/core/src/main/java/dev/slimevr/config/user.kt
+++ b/server/core/src/main/java/dev/slimevr/config/user.kt
@@ -11,14 +11,32 @@ import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
private const val USER_CONFIG_VERSION = 1
private const val DEFAULT_USER_HEIGHT = 1.6f
+/** A relaxed pose of the user, used by Stay Aligned to correct moving trackers. */
+@Serializable
+data class StayAlignedPoseConfig(
+ /** The user recorded this pose. */
+ val recorded: Boolean = false,
+ /** Whether Stay Aligned corrects moving trackers with this pose. */
+ val enabled: Boolean = false,
+ /** Angle between the upper leg yaw and the centre yaw. */
+ val upperLegAngleInDeg: Float = 0.0f,
+ /** Angle between the lower leg yaw and the centre yaw. */
+ val lowerLegAngleInDeg: Float = 0.0f,
+ /** Angle between the foot yaw and the centre yaw. */
+ val footAngleInDeg: Float = 0.0f,
+)
+
@Serializable
data class UserConfigData(
val userHeight: Float = DEFAULT_USER_HEIGHT,
val proportions: Map = computeAllDefaultProportionsByBone(DEFAULT_USER_HEIGHT),
+ /** Only the poses that differ from their default are stored. */
+ val stayAlignedPoses: Map = emptyMap(),
val version: Int = USER_CONFIG_VERSION,
)
diff --git a/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt b/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt
index 492703a88..c5cf2240a 100644
--- a/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt
+++ b/server/core/src/main/java/dev/slimevr/firmware/behaviours/ota-callback.kt
@@ -9,8 +9,8 @@ import dev.slimevr.logging.AppLogger
import dev.slimevr.util.stripIpAddressPort
import io.ktor.network.selector.SelectorManager
import io.ktor.network.sockets.InetSocketAddress
-import io.ktor.network.sockets.toJavaAddress
import io.ktor.network.sockets.aSocket
+import io.ktor.network.sockets.toJavaAddress
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
diff --git a/server/core/src/main/java/dev/slimevr/logging/logger.kt b/server/core/src/main/java/dev/slimevr/logging/logger.kt
index c557eac09..5a1c92423 100644
--- a/server/core/src/main/java/dev/slimevr/logging/logger.kt
+++ b/server/core/src/main/java/dev/slimevr/logging/logger.kt
@@ -42,6 +42,7 @@ object AppLogger {
val coroutines = noCoLogger("Coroutines")
val console = noCoLogger("Console")
+
// For the UDP receive thread, which blocks on the socket and handles each datagram inline. A
// suspend logger would need a coroutine there, and resuming one per packet costs more than the
// packet's own work. Same name as udp logger, so its lines read as the rest of the UDP logs
diff --git a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt
index 69027de59..c26fe178e 100644
--- a/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt
+++ b/server/core/src/main/java/dev/slimevr/skeleton/behaviours.kt
@@ -199,8 +199,7 @@ class ComputedSkeletonBehaviour(
*/
private val idleIntervalDuration = 100.milliseconds
- private fun hasActiveInput(boneInputs: InputSkeleton): Boolean =
- boneInputs.values.any { it.isRotationActive || it.isAccelerationActive || it.isPositionActive }
+ private fun hasActiveInput(boneInputs: InputSkeleton): Boolean = boneInputs.values.any { it.isRotationActive || it.isAccelerationActive || it.isPositionActive }
/** Shortest gap between two tick starts before the later one is pushed to the next slot */
private val minimumGap = intervalDuration * 0.75
diff --git a/server/core/src/main/java/dev/slimevr/solarxr/module.kt b/server/core/src/main/java/dev/slimevr/solarxr/module.kt
index 18be607f1..b157a6f69 100644
--- a/server/core/src/main/java/dev/slimevr/solarxr/module.kt
+++ b/server/core/src/main/java/dev/slimevr/solarxr/module.kt
@@ -222,7 +222,7 @@ class SolarXRBridge(
add(ServerInfosBehaviour(appContext.serverInfos))
add(KeybindsBehaviour(appContext.config.settings, appContext.keybindManager))
add(SessionCalibrationBehaviour(appContext.resetsManager))
- add(StayAlignedBehaviour(appContext.config.settings, appContext.server))
+ add(StayAlignedBehaviour(appContext.config.settings, appContext.config.userConfig, appContext.server, appContext.trackingChecklist))
}
fun create(
diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/settings-defaults.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/settings-defaults.kt
index 151a9d381..c0f728a34 100644
--- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/settings-defaults.kt
+++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/settings-defaults.kt
@@ -2,6 +2,7 @@ package dev.slimevr.solarxr.rpc
import dev.slimevr.config.GlobalConfigState
import dev.slimevr.config.SettingsConfigState
+import dev.slimevr.config.UserConfigData
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
import solarxr_protocol.rpc.BoneRoutingSettingsResponse
@@ -14,11 +15,12 @@ import solarxr_protocol.rpc.SettingsDefaultsResponse
// answers every domain at once.
private fun buildSettingsDefaultsResponse(): SettingsDefaultsResponse {
val settings = SettingsConfigState()
+ val user = UserConfigData()
val global = GlobalConfigState()
return SettingsDefaultsResponse(
skeleton = buildSkeletonSettingsResponse(settings.skeletonConfig),
resets = buildResetsSettingsResponse(settings.resetsConfig),
- stayAligned = buildStayAlignedSettingsResponse(settings.stayAlignedConfig),
+ stayAligned = buildStayAlignedSettingsResponse(settings.stayAlignedConfig, user),
tapDetection = buildTapDetectionSettingsResponse(settings.tapDetectionConfig),
timeout = buildTimeoutSettingsResponse(settings.trackersConfig),
hid = buildHidSettingsResponse(settings.hidConfig),
diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/stay-aligned.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/stay-aligned.kt
index 698b1124a..488ae38e4 100644
--- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/stay-aligned.kt
+++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/stay-aligned.kt
@@ -4,131 +4,292 @@ import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.config.SettingsActions
import dev.slimevr.config.StayAlignedConfig
-import dev.slimevr.config.StayAlignedRelaxedPoseConfig
+import dev.slimevr.config.UserConfig
+import dev.slimevr.config.UserConfigActions
+import dev.slimevr.config.UserConfigData
import dev.slimevr.logging.AppLogger
import dev.slimevr.solarxr.SolarXRBridge
import dev.slimevr.solarxr.SolarXRBridgeBehaviour
-import dev.slimevr.tracker.stayaligned.poses.RelaxedPose
+import dev.slimevr.tracker.TrackerState
+import dev.slimevr.tracker.stayaligned.PoseRecordingCheck
+import dev.slimevr.tracker.stayaligned.StayAlignedDefaults
+import dev.slimevr.tracker.stayaligned.checkPoseRecording
+import dev.slimevr.tracker.stayaligned.missingRequiredParts
+import dev.slimevr.tracker.stayaligned.poses.PlayerPose
+import dev.slimevr.tracker.stayaligned.poses.STAY_ALIGNED_POSES
+import dev.slimevr.tracker.stayaligned.poses.hasStayAlignedPoseDefault
+import dev.slimevr.tracker.stayaligned.poses.stayAlignedPoseConfig
+import dev.slimevr.tracker.stayaligned.recordedPoseConfig
+import dev.slimevr.trackingchecklist.TrackingChecklist
+import dev.slimevr.util.allContextStates
+import dev.slimevr.util.isActive
+import kotlinx.coroutines.FlowPreview
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
-import solarxr_protocol.rpc.ChangeStayAlignedEnabledRequest
+import kotlinx.coroutines.flow.sample
+import kotlinx.coroutines.launch
+import solarxr_protocol.rpc.CancelStayAlignedPoseRecordingRequest
import solarxr_protocol.rpc.ChangeStayAlignedSettingsRequest
-import solarxr_protocol.rpc.DetectStayAlignedRelaxedPoseRequest
import solarxr_protocol.rpc.ResetStayAlignedRelaxedPoseRequest
+import solarxr_protocol.rpc.StartStayAlignedPoseRecordingRequest
+import solarxr_protocol.rpc.StartStayAlignedStatusRequest
+import solarxr_protocol.rpc.StayAlignedDetectedPoseState
+import solarxr_protocol.rpc.StayAlignedPose
+import solarxr_protocol.rpc.StayAlignedPoseCountdown
+import solarxr_protocol.rpc.StayAlignedPoseRecordingDetail
+import solarxr_protocol.rpc.StayAlignedPoseRecordingFailure
+import solarxr_protocol.rpc.StayAlignedPoseRecordingLifecycle
+import solarxr_protocol.rpc.StayAlignedPoseRecordingStatusResponse
+import solarxr_protocol.rpc.StayAlignedPoseState
+import solarxr_protocol.rpc.StayAlignedPoseWaiting
+import solarxr_protocol.rpc.StayAlignedRecordingTracker
import solarxr_protocol.rpc.StayAlignedRelaxedPose
import solarxr_protocol.rpc.StayAlignedSettingsRequest
import solarxr_protocol.rpc.StayAlignedSettingsResponse
+import solarxr_protocol.rpc.StayAlignedStatusResponse
+import solarxr_protocol.rpc.StayAlignedTrackerCorrection
+import solarxr_protocol.rpc.StopStayAlignedStatusRequest
+import solarxr_protocol.rpc.TrackingChecklistStepId
+import kotlin.math.abs
+import kotlin.math.round
+import kotlin.time.Duration.Companion.milliseconds
+import kotlin.time.Duration.Companion.seconds
-internal fun buildStayAlignedSettingsResponse(config: StayAlignedConfig) = StayAlignedSettingsResponse(
+internal fun buildStayAlignedSettingsResponse(config: StayAlignedConfig, userConfig: UserConfigData) = StayAlignedSettingsResponse(
enabled = config.enabled,
- standingEnabled = config.standingRelaxedPose.enabled,
- standingUpperLegAngle = config.standingRelaxedPose.upperLegAngleInDeg,
- standingLowerLegAngle = config.standingRelaxedPose.lowerLegAngleInDeg,
- standingFootAngle = config.standingRelaxedPose.footAngleInDeg,
- sittingEnabled = config.sittingRelaxedPose.enabled,
- sittingUpperLegAngle = config.sittingRelaxedPose.upperLegAngleInDeg,
- sittingLowerLegAngle = config.sittingRelaxedPose.lowerLegAngleInDeg,
- sittingFootAngle = config.sittingRelaxedPose.footAngleInDeg,
- flatEnabled = config.flatRelaxedPose.enabled,
- flatUpperLegAngle = config.flatRelaxedPose.upperLegAngleInDeg,
- flatLowerLegAngle = config.flatRelaxedPose.lowerLegAngleInDeg,
- flatFootAngle = config.flatRelaxedPose.footAngleInDeg,
- setupComplete = config.setupComplete,
+ poses = STAY_ALIGNED_POSES.map { pose ->
+ val poseConfig = stayAlignedPoseConfig(userConfig, pose)
+ StayAlignedPose(
+ pose = pose,
+ recorded = poseConfig.recorded,
+ hasDefault = hasStayAlignedPoseDefault(pose),
+ enabled = poseConfig.enabled,
+ upperLegAngle = poseConfig.upperLegAngleInDeg,
+ lowerLegAngle = poseConfig.lowerLegAngleInDeg,
+ footAngle = poseConfig.footAngleInDeg,
+ )
+ },
)
+internal fun buildStayAlignedStatusResponse(enabled: Boolean, trackerStates: List, userConfig: UserConfigData) = StayAlignedStatusResponse(
+ enabled = enabled,
+ detectedPose = detectedPose(PlayerPose.of(trackerStates).relaxedPose, userConfig),
+ missingParts = missingRequiredParts(trackerStates),
+ largestCorrection = if (enabled) largestCorrection(trackerStates) else null,
+)
+
+private fun largestCorrection(trackerStates: List): StayAlignedTrackerCorrection? {
+ val corrections = trackerStates.mapNotNull { state ->
+ // A tracker that is not connected keeps its correction but nothing uses it
+ val bodyPart = state.bodyPart?.takeIf { state.status.isActive() } ?: return@mapNotNull null
+ StayAlignedTrackerCorrection(bodyPart = bodyPart, degrees = round(abs(state.stayAlignedData.yawCorrection.toDeg()) * 10f) / 10f)
+ }
+ return corrections.maxByOrNull { it.degrees }?.takeIf { it.degrees > 0f }
+}
+
+private fun detectedPose(pose: StayAlignedRelaxedPose, userConfig: UserConfigData): StayAlignedDetectedPoseState? {
+ if (pose == StayAlignedRelaxedPose.UNKNOWN) return null
+ val config = stayAlignedPoseConfig(userConfig, pose)
+ val state = when {
+ config.enabled -> StayAlignedPoseState.ENABLED
+ !config.recorded && !hasStayAlignedPoseDefault(pose) -> StayAlignedPoseState.NOT_RECORDED
+ else -> StayAlignedPoseState.DISABLED
+ }
+ return StayAlignedDetectedPoseState(pose = pose, state = state)
+}
+
class StayAlignedBehaviour(
private val settings: Settings,
+ private val userConfig: UserConfig,
private val server: VRServer,
+ private val trackingChecklist: TrackingChecklist,
) : SolarXRBridgeBehaviour {
override fun observe(receiver: SolarXRBridge) {
- // Send config
+ observeSettings(receiver)
+ observeStatus(receiver)
+ observeRecording(receiver)
+ }
+
+ private suspend fun sendConfig(receiver: SolarXRBridge) {
+ receiver.sendRpc(buildStayAlignedSettingsResponse(settings.context.state.value.data.stayAlignedConfig, userConfig.context.state.value.data))
+ }
+
+ private fun observeSettings(receiver: SolarXRBridge) {
receiver.rpcDispatcher.on {
- sendConfig(receiver, settings)
+ sendConfig(receiver)
}.launchIn(receiver.context.scope)
// Push config changes, including profile switches
- settings.context.state
- .map { buildStayAlignedSettingsResponse(it.data.stayAlignedConfig) }
+ combine(
+ settings.context.state.map { it.data.stayAlignedConfig }.distinctUntilChanged(),
+ userConfig.context.state.map { it.data }.distinctUntilChanged(),
+ ::buildStayAlignedSettingsResponse,
+ )
.distinctUntilChanged()
.drop(1)
.onEach(receiver::sendRpc)
.launchIn(receiver.context.scope)
- // Receive config
receiver.rpcDispatcher.on { req ->
- settings.context.dispatch(
- SettingsActions.Update {
- copy(
- stayAlignedConfig = StayAlignedConfig(
- setupComplete = if (req.enabled) true else stayAlignedConfig.setupComplete,
- enabled = req.enabled,
- standingRelaxedPose = stayAlignedConfig.standingRelaxedPose.copy(
- enabled = req.standingEnabled,
- ),
- sittingRelaxedPose = stayAlignedConfig.sittingRelaxedPose.copy(
- enabled = req.sittingEnabled,
- ),
- flatRelaxedPose = stayAlignedConfig.flatRelaxedPose.copy(
- enabled = req.flatEnabled,
- ),
- ),
- )
+ settings.context.dispatch(SettingsActions.Update { copy(stayAlignedConfig = StayAlignedConfig(enabled = req.enabled)) })
+ userConfig.context.dispatch(
+ UserConfigActions.Update {
+ // Only the poses that change are stored, so the others keep following their default.
+ // A pose can only be turned on once it is recorded, or when it has a default
+ val toggled = req.poseToggles.orEmpty()
+ .filter { stayAlignedPoseConfig(this, it.pose).enabled != it.enabled }
+ .filter { !it.enabled || stayAlignedPoseConfig(this, it.pose).recorded || hasStayAlignedPoseDefault(it.pose) }
+ .associate { it.pose to stayAlignedPoseConfig(this, it.pose).copy(enabled = it.enabled) }
+ copy(stayAlignedPoses = stayAlignedPoses + toggled)
},
)
- sendConfig(receiver, settings)
+ sendConfig(receiver)
}.launchIn(receiver.context.scope)
- // Receive enabled
- receiver.rpcDispatcher.on { req ->
- settings.context.dispatch(
- SettingsActions.Update {
- copy(
- stayAlignedConfig = stayAlignedConfig.copy(
- setupComplete = if (req.enabled) true else stayAlignedConfig.setupComplete,
- enabled = req.enabled,
- ),
- )
- },
- )
- }.launchIn(receiver.context.scope)
-
- // Detect pose
- receiver.rpcDispatcher.on { req ->
- val pose = req.pose
- val trackerStates = server.context.state.value.trackers.values.map { it.context.state.value }
- val relaxedPose = RelaxedPose.fromTrackers(trackerStates)
- updatePoseInConfig(pose, StayAlignedRelaxedPoseConfig(true, relaxedPose.upperLeg.toDeg(), relaxedPose.lowerLeg.toDeg(), relaxedPose.foot.toDeg()))
- AppLogger.stayAligned.info("Set relaxed pose $pose with $relaxedPose")
- sendConfig(receiver, settings)
- }.launchIn(receiver.context.scope)
-
- // Reset pose
receiver.rpcDispatcher.on { req ->
- val pose = req.pose
- updatePoseInConfig(pose, StayAlignedRelaxedPoseConfig(false, 0f, 0f, 0f))
- AppLogger.stayAligned.info("Reset relaxed pose $pose")
- sendConfig(receiver, settings)
+ if (req.pose == StayAlignedRelaxedPose.UNKNOWN) return@on
+ userConfig.context.dispatch(UserConfigActions.Update { copy(stayAlignedPoses = stayAlignedPoses - req.pose) })
+ AppLogger.stayAligned.info("Reset relaxed pose ${req.pose}")
+ sendConfig(receiver)
}.launchIn(receiver.context.scope)
}
- private suspend fun sendConfig(receiver: SolarXRBridge, settings: Settings) {
- receiver.sendRpc(buildStayAlignedSettingsResponse(settings.context.state.value.data.stayAlignedConfig))
+ @OptIn(FlowPreview::class)
+ private fun observeStatus(receiver: SolarXRBridge) {
+ var statusJob: Job? = null
+
+ receiver.rpcDispatcher.on {
+ statusJob?.cancel()
+ statusJob = combine(
+ settings.context.state.map { it.data.stayAlignedConfig.enabled }.distinctUntilChanged(),
+ userConfig.context.state.map { it.data }.distinctUntilChanged(),
+ allContextStates(server.context.state, { state -> state.trackers.values }) { tracker ->
+ tracker.context.state.sample(STATUS_SAMPLE_INTERVAL)
+ },
+ ) { enabled, userConfigData, trackers -> buildStayAlignedStatusResponse(enabled, trackers, userConfigData) }
+ .distinctUntilChanged()
+ .onEach(receiver::sendRpc)
+ .launchIn(receiver.context.scope)
+ }.launchIn(receiver.context.scope)
+
+ receiver.rpcDispatcher.on {
+ statusJob?.cancel()
+ statusJob = null
+ }.launchIn(receiver.context.scope)
}
- private fun updatePoseInConfig(pose: StayAlignedRelaxedPose, poseConfig: StayAlignedRelaxedPoseConfig) {
- settings.context.dispatch(
- SettingsActions.Update {
- copy(
- stayAlignedConfig = when (pose) {
- StayAlignedRelaxedPose.STANDING -> stayAlignedConfig.copy(standingRelaxedPose = poseConfig)
- StayAlignedRelaxedPose.SITTING -> stayAlignedConfig.copy(sittingRelaxedPose = poseConfig)
- StayAlignedRelaxedPose.FLAT -> stayAlignedConfig.copy(flatRelaxedPose = poseConfig)
- },
- )
- },
+ private fun currentTrackerStates(): List = server.context.state.value.trackers.values.map { it.context.state.value }
+
+ private fun observeRecording(receiver: SolarXRBridge) {
+ var recordingJob: Job? = null
+ var recordingPose: StayAlignedRelaxedPose? = null
+
+ receiver.rpcDispatcher.on { req ->
+ if (req.pose == StayAlignedRelaxedPose.UNKNOWN) return@on
+ recordingJob?.cancel()
+ recordingPose = req.pose
+ recordingJob = receiver.context.scope.launch { recordPose(receiver, req.pose) }
+ }.launchIn(receiver.context.scope)
+
+ receiver.rpcDispatcher.on {
+ val job = recordingJob ?: return@on
+ val pose = recordingPose ?: return@on
+ if (!job.isActive) return@on
+ job.cancel()
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.CANCELED, null))
+ }.launchIn(receiver.context.scope)
+ }
+
+ /**
+ * Gives the user time to get into the pose, then waits until every tracker that is read is still and
+ * the position matches the pose, and saves the pose. Gives up when that does not happen in time.
+ */
+ private suspend fun recordPose(receiver: SolarXRBridge, pose: StayAlignedRelaxedPose) {
+ val countdown = StayAlignedDefaults.POSE_RECORDING_COUNTDOWN_SECONDS
+ val timeout = StayAlignedDefaults.POSE_RECORDING_TIMEOUT_SECONDS
+
+ if (missingRequiredParts(currentTrackerStates()).isNotEmpty()) {
+ AppLogger.stayAligned.info("Not recording relaxed pose $pose: trackers are missing")
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.FAILED, null, StayAlignedPoseRecordingFailure.MISSING_TRACKERS))
+ return
+ }
+
+ // A pose measured on trackers that are not reset or mounted would be saved wrong
+ val steps = trackingChecklist.context.state.value.steps
+ if (CALIBRATION_STEPS.any { id -> steps[id]?.let { it.enabled && !it.valid } == true }) {
+ AppLogger.stayAligned.info("Not recording relaxed pose $pose: trackers are not calibrated")
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.FAILED, null, StayAlignedPoseRecordingFailure.NOT_CALIBRATED))
+ return
+ }
+
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.RUNNING, StayAlignedPoseCountdown(0, countdown)))
+ repeat(countdown) { index ->
+ delay(1.seconds)
+ if (index != countdown - 1) {
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.RUNNING, StayAlignedPoseCountdown(index + 1, countdown)))
+ }
+ }
+
+ // The GUI shows the checks and the seconds waited, so both are sent whenever one changes
+ val checks = allContextStates(server.context.state, { state -> state.trackers.values }) { tracker -> tracker.context.state }
+ .map { trackers -> checkPoseRecording(trackers, pose) }
+ .distinctUntilChanged()
+ val waited = flow {
+ repeat(timeout + 1) { second ->
+ emit(second)
+ delay(1.seconds)
+ }
+ }
+ val (check, seconds) = combine(checks, waited, ::Pair)
+ .onEach { (check, seconds) -> receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.RUNNING, waitingDetail(seconds, timeout, check))) }
+ .first { (check, seconds) -> check.failure == StayAlignedPoseRecordingFailure.NONE || seconds == timeout }
+
+ if (check.failure != StayAlignedPoseRecordingFailure.NONE) {
+ AppLogger.stayAligned.info("Relaxed pose $pose not recorded: ${check.failure}")
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.FAILED, waitingDetail(seconds, timeout, check), check.failure))
+ return
+ }
+
+ // The trackers may have changed since the check that passed, so what is saved is measured now
+ val trackers = currentTrackerStates()
+ if (missingRequiredParts(trackers).isNotEmpty()) {
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.FAILED, waitingDetail(seconds, timeout, check), StayAlignedPoseRecordingFailure.MISSING_TRACKERS))
+ return
+ }
+ val recorded = recordedPoseConfig(trackers)
+ userConfig.context.dispatch(UserConfigActions.Update { copy(stayAlignedPoses = stayAlignedPoses + (pose to recorded)) })
+ AppLogger.stayAligned.info("Recorded relaxed pose $pose: upperLeg=${recorded.upperLegAngleInDeg} lowerLeg=${recorded.lowerLegAngleInDeg} foot=${recorded.footAngleInDeg}")
+ receiver.sendRpc(recordingStatus(pose, StayAlignedPoseRecordingLifecycle.DONE, waitingDetail(seconds, timeout, check)))
+ }
+
+ private fun waitingDetail(progressSeconds: Int, durationSeconds: Int, check: PoseRecordingCheck) = StayAlignedPoseWaiting(
+ progress = progressSeconds,
+ duration = durationSeconds,
+ detectedPose = check.detectedPose,
+ trackers = check.parts.map { (part, state) -> StayAlignedRecordingTracker(part = part, state = state) },
+ )
+
+ private fun recordingStatus(
+ pose: StayAlignedRelaxedPose,
+ lifecycle: StayAlignedPoseRecordingLifecycle,
+ detail: StayAlignedPoseRecordingDetail?,
+ failure: StayAlignedPoseRecordingFailure = StayAlignedPoseRecordingFailure.NONE,
+ ) = StayAlignedPoseRecordingStatusResponse(pose = pose, lifecycle = lifecycle, detail = detail, failure = failure)
+
+ private companion object {
+ val STATUS_SAMPLE_INTERVAL = 250.milliseconds
+ val CALIBRATION_STEPS = listOf(
+ TrackingChecklistStepId.FULL_RESET,
+ TrackingChecklistStepId.MOUNTING_CALIBRATION,
+ TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION,
)
}
}
diff --git a/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt b/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt
index 3a664b51f..cad472ee7 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/behaviours/stay-aligned.kt
@@ -1,6 +1,7 @@
package dev.slimevr.tracker.behaviours
import dev.slimevr.config.Settings
+import dev.slimevr.config.UserConfig
import dev.slimevr.math.angle.Angle
import dev.slimevr.tracker.Tracker
import dev.slimevr.tracker.TrackerActions
@@ -24,6 +25,7 @@ import solarxr_protocol.datatypes.MagnetometerStatus
class TrackerStayAlignedBehaviour(
private val settings: Settings,
+ private val userConfig: UserConfig,
) : TrackerBehaviour {
override fun observe(receiver: Tracker) {
@@ -65,12 +67,12 @@ class TrackerStayAlignedBehaviour(
val serverFlow = receiver.appContext.server.context.state
- val stayAlignedConfigFlow = settings.context.state.map { it.data.stayAlignedConfig }.distinctUntilChanged()
+ val enabledFlow = settings.context.state.map { it.data.stayAlignedConfig.enabled }.distinctUntilChanged()
val imuTypeFlow = receiver.context.state.map { it.imuType }.distinctUntilChanged()
val magStatusFlow = receiver.context.state.map { it.magStatus }.distinctUntilChanged()
- combine(stayAlignedConfigFlow, imuTypeFlow, magStatusFlow, ::Triple)
- .flatMapLatest { (stayAlignedConfig, imuType, magStatus) ->
- if (magStatus == MagnetometerStatus.ENABLED || imuType == null || !stayAlignedConfig.enabled) return@flatMapLatest emptyFlow()
+ combine(enabledFlow, imuTypeFlow, magStatusFlow, ::Triple)
+ .flatMapLatest { (enabled, imuType, magStatus) ->
+ if (magStatus == MagnetometerStatus.ENABLED || imuType == null || !enabled) return@flatMapLatest emptyFlow()
// Ignore every other emission for performance (50FPS instead of 100FPS when at 100TPS)
var index = 0
@@ -90,7 +92,7 @@ class TrackerStayAlignedBehaviour(
state,
serverFlow.value.trackers.values.map { it.context.state.value },
applyYawCorrection,
- stayAlignedConfig,
+ userConfig.context.state.value.data,
)
if (yawCorrectionResult != null) {
receiver.context.dispatch(TrackerActions.SetYawCorrection(yawCorrectionResult))
diff --git a/server/core/src/main/java/dev/slimevr/tracker/module.kt b/server/core/src/main/java/dev/slimevr/tracker/module.kt
index 3b7ba8b2c..c48373966 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/module.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/module.kt
@@ -185,7 +185,7 @@ class Tracker(
TrackerConfigBehaviour(devices, hardwareId),
TrackerMotionDetectionBehaviour(),
TrackerToSkeletonBehaviour(),
- TrackerStayAlignedBehaviour(settings),
+ TrackerStayAlignedBehaviour(settings, appContext.config.userConfig),
)
val context = Context.create(
initialState = trackerState,
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/defaults.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/defaults.kt
index 10a7b3c16..f13603762 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/defaults.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/defaults.kt
@@ -1,7 +1,6 @@
package dev.slimevr.tracker.stayaligned
import dev.slimevr.math.angle.Angle
-import dev.slimevr.tracker.stayaligned.poses.RelaxedPose
import solarxr_protocol.datatypes.hardware_info.ImuType
/**
@@ -9,14 +8,9 @@ import solarxr_protocol.datatypes.hardware_info.ImuType
* algorithm from a single place.
*/
object StayAlignedDefaults {
- // Relaxed pose for kneeling. This isn't that common, so we don't want to ask
- // players to provide this relaxed pose during setup.
- val RELAXED_POSE_KNEELING =
- RelaxedPose(
- upperLeg = Angle.ofDeg(0.0f),
- lowerLeg = Angle.ofDeg(0.0f),
- foot = Angle.ofDeg(0.0f),
- )
+ // Recording a relaxed pose: time to get into the pose, then the time every tracker has to settle
+ const val POSE_RECORDING_COUNTDOWN_SECONDS = 3
+ const val POSE_RECORDING_TIMEOUT_SECONDS = 10
// Weights to calculate the average yaw of the skeleton
const val CENTRE_ERROR_HEAD_WEIGHT = 0.5f
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/pose-recording.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/pose-recording.kt
new file mode 100644
index 000000000..d60fa81dd
--- /dev/null
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/pose-recording.kt
@@ -0,0 +1,53 @@
+package dev.slimevr.tracker.stayaligned
+
+import dev.slimevr.config.StayAlignedPoseConfig
+import dev.slimevr.tracker.Motion
+import dev.slimevr.tracker.TrackerState
+import dev.slimevr.tracker.stayaligned.poses.PlayerPose
+import dev.slimevr.tracker.stayaligned.poses.RelaxedPose
+import solarxr_protocol.rpc.StayAlignedPart
+import solarxr_protocol.rpc.StayAlignedPoseRecordingFailure
+import solarxr_protocol.rpc.StayAlignedRecordingTrackerState
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
+
+data class PoseRecordingCheck(
+ val parts: Map,
+ val detectedPose: StayAlignedRelaxedPose,
+ val failure: StayAlignedPoseRecordingFailure,
+)
+
+/** Whether each part that has a tracker is still or moving. */
+private fun partStates(trackerStates: List): Map = StayAlignedPart.entries.mapNotNull { part ->
+ val trackers = trackersOf(trackerStates, part)
+ when {
+ trackers.isEmpty() -> null
+ trackers.all { it.motion == Motion.RESTING } -> part to StayAlignedRecordingTrackerState.STILL
+ else -> part to StayAlignedRecordingTrackerState.MOVING
+ }
+}.toMap()
+
+/** Missing trackers come first, then trackers that move, then the pose. */
+fun checkPoseRecording(trackerStates: List, requested: StayAlignedRelaxedPose): PoseRecordingCheck {
+ val parts = partStates(trackerStates)
+ val detectedPose = PlayerPose.of(trackerStates).relaxedPose
+ val failure = when {
+ missingRequiredParts(trackerStates).isNotEmpty() -> StayAlignedPoseRecordingFailure.MISSING_TRACKERS
+ StayAlignedRecordingTrackerState.MOVING in parts.values -> StayAlignedPoseRecordingFailure.NOT_STILL
+ detectedPose == StayAlignedRelaxedPose.UNKNOWN -> StayAlignedPoseRecordingFailure.POSITION_UNKNOWN
+ detectedPose != requested -> StayAlignedPoseRecordingFailure.WRONG_POSE
+ else -> StayAlignedPoseRecordingFailure.NONE
+ }
+ return PoseRecordingCheck(parts, detectedPose, failure)
+}
+
+/** The pose the user is in right now, measured from the rotations the trackers had when they started resting. */
+fun recordedPoseConfig(trackerStates: List): StayAlignedPoseConfig {
+ val relaxedPose = RelaxedPose.fromTrackers(trackerStates)
+ return StayAlignedPoseConfig(
+ recorded = true,
+ enabled = true,
+ upperLegAngleInDeg = relaxedPose.upperLeg.toDeg(),
+ lowerLegAngleInDeg = relaxedPose.lowerLeg.toDeg(),
+ footAngleInDeg = relaxedPose.foot.toDeg(),
+ )
+}
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt
index d39ad5d2b..6bcd9871d 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/player-pose.kt
@@ -4,17 +4,19 @@ import dev.slimevr.tracker.TrackerState
import dev.slimevr.tracker.getAllActiveFor
import dev.slimevr.tracker.getFirstActiveFor
import dev.slimevr.tracker.stayaligned.StayAlignedBodyParts
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
/**
- * The pose of the player.
+ * The pose of the player, with the relaxed pose the user records for it. Sitting on the ground and
+ * lying on the back share one.
*/
-enum class PlayerPose {
- UNKNOWN,
- STANDING,
- SITTING_IN_CHAIR,
- SITTING_ON_GROUND,
- LYING_ON_BACK,
- KNEELING,
+enum class PlayerPose(val relaxedPose: StayAlignedRelaxedPose) {
+ UNKNOWN(StayAlignedRelaxedPose.UNKNOWN),
+ STANDING(StayAlignedRelaxedPose.STANDING),
+ SITTING_IN_CHAIR(StayAlignedRelaxedPose.SITTING),
+ SITTING_ON_GROUND(StayAlignedRelaxedPose.FLAT),
+ LYING_ON_BACK(StayAlignedRelaxedPose.FLAT),
+ KNEELING(StayAlignedRelaxedPose.KNEELING),
;
companion object {
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/pose-config.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/pose-config.kt
new file mode 100644
index 000000000..c9e1aaf21
--- /dev/null
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/pose-config.kt
@@ -0,0 +1,16 @@
+package dev.slimevr.tracker.stayaligned.poses
+
+import dev.slimevr.config.StayAlignedPoseConfig
+import dev.slimevr.config.UserConfigData
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
+
+/** The poses the user can record and turn on, which is all of them but UNKNOWN. */
+val STAY_ALIGNED_POSES: List = StayAlignedRelaxedPose.entries - StayAlignedRelaxedPose.UNKNOWN
+
+private val DEFAULT_STAY_ALIGNED_POSES = mapOf(
+ StayAlignedRelaxedPose.KNEELING to StayAlignedPoseConfig(enabled = true),
+)
+
+fun hasStayAlignedPoseDefault(pose: StayAlignedRelaxedPose): Boolean = pose in DEFAULT_STAY_ALIGNED_POSES
+
+fun stayAlignedPoseConfig(data: UserConfigData, pose: StayAlignedRelaxedPose): StayAlignedPoseConfig = data.stayAlignedPoses[pose] ?: DEFAULT_STAY_ALIGNED_POSES[pose] ?: StayAlignedPoseConfig()
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt
index 13de96e10..7efd850ef 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/poses/relaxed-pose.kt
@@ -1,11 +1,10 @@
package dev.slimevr.tracker.stayaligned.poses
-import dev.slimevr.config.StayAlignedConfig
+import dev.slimevr.config.UserConfigData
import dev.slimevr.math.angle.Angle
import dev.slimevr.tracker.TrackerState
import dev.slimevr.tracker.getFirstActiveFor
import dev.slimevr.tracker.stayaligned.StayAlignedBodyParts
-import dev.slimevr.tracker.stayaligned.StayAlignedDefaults
import dev.slimevr.tracker.stayaligned.YawUtils.trackerYaw
class RelaxedPose(
@@ -25,62 +24,24 @@ class RelaxedPose(
*/
fun forPose(
playerPose: PlayerPose,
- config: StayAlignedConfig,
- ) = when (playerPose) {
- PlayerPose.STANDING -> {
- val poseConfig = config.standingRelaxedPose
- if (poseConfig.enabled) {
- RelaxedPose(
- Angle.ofDeg(poseConfig.upperLegAngleInDeg),
- Angle.ofDeg(poseConfig.lowerLegAngleInDeg),
- Angle.ofDeg(poseConfig.footAngleInDeg),
- )
- } else {
- null
- }
- }
-
- PlayerPose.SITTING_IN_CHAIR -> {
- val poseConfig = config.sittingRelaxedPose
- if (poseConfig.enabled) {
- RelaxedPose(
- Angle.ofDeg(poseConfig.upperLegAngleInDeg),
- Angle.ofDeg(poseConfig.lowerLegAngleInDeg),
- Angle.ofDeg(poseConfig.footAngleInDeg),
- )
- } else {
- null
- }
- }
-
- PlayerPose.SITTING_ON_GROUND,
- PlayerPose.LYING_ON_BACK,
- -> {
- val poseConfig = config.flatRelaxedPose
- if (poseConfig.enabled) {
- RelaxedPose(
- Angle.ofDeg(poseConfig.upperLegAngleInDeg),
- Angle.ofDeg(poseConfig.lowerLegAngleInDeg),
- Angle.ofDeg(poseConfig.footAngleInDeg),
- )
- } else {
- null
- }
- }
-
- PlayerPose.KNEELING ->
- StayAlignedDefaults.RELAXED_POSE_KNEELING
-
- else ->
- null
+ userConfig: UserConfigData,
+ ): RelaxedPose? {
+ val poseConfig = stayAlignedPoseConfig(userConfig, playerPose.relaxedPose)
+ if (!poseConfig.enabled) return null
+ return RelaxedPose(
+ Angle.ofDeg(poseConfig.upperLegAngleInDeg),
+ Angle.ofDeg(poseConfig.lowerLegAngleInDeg),
+ Angle.ofDeg(poseConfig.footAngleInDeg),
+ )
}
/**
* Gets the relaxed angles from the trackers.
*/
fun fromTrackers(trackerStates: List): RelaxedPose {
+ val restingRotation = { state: TrackerState -> state.stayAlignedData.lockedRotation ?: state.rotation }
val halfAngleBetween = { left: TrackerState, right: TrackerState ->
- (trackerYaw(left.rotation) - trackerYaw(right.rotation)) * 0.5f
+ (trackerYaw(restingRotation(left)) - trackerYaw(restingRotation(right))) * 0.5f
}
val upperLegAngle: Angle = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg)?.let { left ->
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/requirements.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/requirements.kt
new file mode 100644
index 000000000..4cebf5646
--- /dev/null
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/requirements.kt
@@ -0,0 +1,53 @@
+package dev.slimevr.tracker.stayaligned
+
+import dev.slimevr.tracker.TrackerState
+import dev.slimevr.tracker.getAllActiveFor
+import dev.slimevr.tracker.getFirstActiveFor
+import solarxr_protocol.rpc.StayAlignedPart
+
+/**
+ * The trackers Stay Aligned needs to correct the yaw of moving trackers: at least one upper body
+ * tracker plus both upper legs and both lower legs. Feet are optional and not part of this.
+ */
+class RequiredTrackers(
+ val upperBody: List,
+ val leftUpperLeg: TrackerState,
+ val rightUpperLeg: TrackerState,
+ val leftLowerLeg: TrackerState,
+ val rightLowerLeg: TrackerState,
+)
+
+/** The required trackers, or null when some are missing. */
+fun requiredTrackers(trackerStates: List): RequiredTrackers? {
+ val upperBody = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup)
+ if (upperBody.isEmpty()) return null
+ return RequiredTrackers(
+ upperBody = upperBody,
+ leftUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg) ?: return null,
+ rightUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg) ?: return null,
+ leftLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg) ?: return null,
+ rightLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg) ?: return null,
+ )
+}
+
+/** The active trackers of a part of the body. Empty when the user has none. */
+fun trackersOf(trackerStates: List, part: StayAlignedPart): List = when (part) {
+ StayAlignedPart.UPPER_BODY -> trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup)
+ StayAlignedPart.LEFT_UPPER_LEG -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg))
+ StayAlignedPart.RIGHT_UPPER_LEG -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg))
+ StayAlignedPart.LEFT_LOWER_LEG -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg))
+ StayAlignedPart.RIGHT_LOWER_LEG -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg))
+ StayAlignedPart.LEFT_FOOT -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftFoot))
+ StayAlignedPart.RIGHT_FOOT -> listOfNotNull(trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightFoot))
+}
+
+/** Parts without a tracker that Stay Aligned needs. */
+fun missingRequiredParts(trackerStates: List): List = REQUIRED_PARTS.filter { trackersOf(trackerStates, it).isEmpty() }
+
+private val REQUIRED_PARTS = listOf(
+ StayAlignedPart.UPPER_BODY,
+ StayAlignedPart.LEFT_UPPER_LEG,
+ StayAlignedPart.RIGHT_UPPER_LEG,
+ StayAlignedPart.LEFT_LOWER_LEG,
+ StayAlignedPart.RIGHT_LOWER_LEG,
+)
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt
index 8de26f661..293fd5f6d 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/tracker-yaw-correction.kt
@@ -1,6 +1,6 @@
package dev.slimevr.tracker.stayaligned
-import dev.slimevr.config.StayAlignedConfig
+import dev.slimevr.config.UserConfigData
import dev.slimevr.math.angle.Angle
import dev.slimevr.math.angle.AngleErrors
import dev.slimevr.tracker.Motion
@@ -37,9 +37,9 @@ object TrackerYawCorrection {
trackerState: TrackerState,
trackerStates: List,
applyYawCorrection: Angle,
- config: StayAlignedConfig,
+ userConfig: UserConfigData,
): Angle? = when (trackerState.motion) {
- Motion.ROTATING -> adjustMovingTracker(trackerState, trackerStates, applyYawCorrection, config)
+ Motion.ROTATING -> adjustMovingTracker(trackerState, trackerStates, applyYawCorrection, userConfig)
Motion.RESTING -> adjustLockedTracker(trackerState, applyYawCorrection)
@@ -97,10 +97,10 @@ object TrackerYawCorrection {
trackerState: TrackerState,
trackerStates: List,
applyYawCorrection: Angle,
- config: StayAlignedConfig,
+ userConfig: UserConfigData,
): Angle? {
val centreYaw = YawUtils.centreYawOfTrackers(trackerStates) ?: return null
- val relaxedPose = RelaxedPose.forPose(PlayerPose.of(trackerStates), config) ?: return null
+ val relaxedPose = RelaxedPose.forPose(PlayerPose.of(trackerStates), userConfig) ?: return null
return adjustByError(trackerState, applyYawCorrection) { yawCorrection ->
YawErrors().also {
diff --git a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt
index 25dad0e56..8192eff6d 100644
--- a/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt
+++ b/server/core/src/main/java/dev/slimevr/tracker/stayaligned/yaw-utils.kt
@@ -3,7 +3,6 @@ package dev.slimevr.tracker.stayaligned
import dev.slimevr.math.angle.Angle
import dev.slimevr.math.angle.AngleAverage
import dev.slimevr.tracker.TrackerState
-import dev.slimevr.tracker.getAllActiveFor
import dev.slimevr.tracker.getFirstActiveFor
import dev.slimevr.util.Side
import io.github.axisangles.ktmath.EulerOrder
@@ -73,12 +72,12 @@ object YawUtils {
trackerStates: List,
): Angle? {
val head = trackerStates.getFirstActiveFor(StayAlignedBodyParts.head) // Optional
- val upperBody = trackerStates.getAllActiveFor(StayAlignedBodyParts.upperBodyGroup)
- if (upperBody.isEmpty()) return null
- val leftUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftUpperLeg) ?: return null
- val rightUpperLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightUpperLeg) ?: return null
- val leftLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.leftLowerLeg) ?: return null
- val rightLowerLeg = trackerStates.getFirstActiveFor(StayAlignedBodyParts.rightLowerLeg) ?: return null
+ val required = requiredTrackers(trackerStates) ?: return null
+ val upperBody = required.upperBody
+ val leftUpperLeg = required.leftUpperLeg
+ val rightUpperLeg = required.rightUpperLeg
+ val leftLowerLeg = required.leftLowerLeg
+ val rightLowerLeg = required.rightLowerLeg
// Need a minimum set of trackers, and the trackers need to be oriented in a
// way where we can actually calculate its yaw.
diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt
index 13e732402..ad394f256 100644
--- a/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt
+++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/behaviours.kt
@@ -4,6 +4,7 @@ import dev.slimevr.VRServer
import dev.slimevr.config.Settings
import dev.slimevr.networkprofile.NetworkProfileManager
import dev.slimevr.resets.ResetBodyParts
+import dev.slimevr.resets.ResetsManager
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.routing.Routes
import dev.slimevr.routing.solarXRDriverConnectedFlow
@@ -302,25 +303,33 @@ private fun isImuAssigned(tracker: ChecklistTracker): Boolean = (tracker.origin
class FullResetCheckBehaviour(
private val trackerStates: StateFlow>,
+ private val resetsManager: ResetsManager,
) : TrackingChecklistBehaviourType {
override fun observe(receiver: TrackingChecklist) {
- trackerStates
- .map { trackers ->
- val assigned = trackers.filter { isImuAssigned(it) }
- val pending = assigned.filter { it.needsFullReset }
- TrackingChecklistStep(
- valid = pending.isEmpty(),
- enabled = assigned.isNotEmpty(),
- ignorable = false,
- visibility = TrackingChecklistStepVisibility.ALWAYS,
- extraData = if (pending.isNotEmpty()) {
- TrackingChecklistTrackerReset(trackersId = pending.map { it.id.toUShort() })
- } else {
- null
- },
- )
+ val mountingPending = receiver.context.state
+ .map { state ->
+ listOf(TrackingChecklistStepId.MOUNTING_CALIBRATION, TrackingChecklistStepId.FEET_MOUNTING_CALIBRATION)
+ .any { id -> state.steps[id]?.let { it.enabled && !it.valid } == true }
}
.distinctUntilChanged()
+ val mountingResetAllowed = resetsManager.context.state.map { it.canDoMountingReset }.distinctUntilChanged()
+
+ combine(trackerStates, mountingResetAllowed, mountingPending) { trackers, allowed, pendingMounting ->
+ val assigned = trackers.filter { isImuAssigned(it) }
+ val pending = assigned.filter { it.needsFullReset }
+ TrackingChecklistStep(
+ valid = pending.isEmpty() && (allowed || !pendingMounting),
+ enabled = assigned.isNotEmpty(),
+ ignorable = false,
+ visibility = TrackingChecklistStepVisibility.ALWAYS,
+ extraData = if (pending.isNotEmpty()) {
+ TrackingChecklistTrackerReset(trackersId = pending.map { it.id.toUShort() })
+ } else {
+ null
+ },
+ )
+ }
+ .distinctUntilChanged()
.onEach { step -> receiver.context.dispatch(TrackingChecklistActions.UpdateStep(TrackingChecklistStepId.FULL_RESET, step)) }
.launchIn(receiver.context.scope)
}
diff --git a/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt b/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt
index 7709b4752..5a42d243d 100644
--- a/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt
+++ b/server/core/src/main/java/dev/slimevr/trackingchecklist/module.kt
@@ -31,7 +31,7 @@ class TrackingChecklist(
val stepBehaviours: List = buildList {
add(ReliableReferenceCheckBehaviour(trackerStates))
add(TrackerRestCheckBehaviour(trackerStates))
- add(FullResetCheckBehaviour(trackerStates))
+ add(FullResetCheckBehaviour(trackerStates, appContext.resetsManager))
add(MountingMethodCheckBehaviour(appContext.config.settings))
add(MountingCalibrationCheckBehaviour(trackerStates, appContext.config.settings))
add(TrackerErrorCheckBehaviour(trackerStates))
diff --git a/server/core/src/test/java/dev/slimevr/TestServer.kt b/server/core/src/test/java/dev/slimevr/TestServer.kt
index f41a3f010..9e91ba5a0 100644
--- a/server/core/src/test/java/dev/slimevr/TestServer.kt
+++ b/server/core/src/test/java/dev/slimevr/TestServer.kt
@@ -287,8 +287,7 @@ private fun buildTestUdpServer(): dev.slimevr.udp.UdpServer {
/** A socket that never receives anything and drops what it sends */
class FakeUdpSocket : UdpSocket {
- override suspend fun listen(onDatagram: (from: UdpPeer, payload: Source) -> Unit) =
- awaitCancellation()
+ override suspend fun listen(onDatagram: (from: UdpPeer, payload: Source) -> Unit) = awaitCancellation()
override suspend fun send(to: UdpPeer, payload: ByteArray) {}
override suspend fun close() {}
}
diff --git a/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt b/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt
index bd112bcc9..37187afa0 100644
--- a/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt
+++ b/server/core/src/test/java/dev/slimevr/stayaligned/ComputeYawCorrectionTest.kt
@@ -1,7 +1,7 @@
package dev.slimevr.stayaligned
-import dev.slimevr.config.StayAlignedConfig
-import dev.slimevr.config.StayAlignedRelaxedPoseConfig
+import dev.slimevr.config.StayAlignedPoseConfig
+import dev.slimevr.config.UserConfigData
import dev.slimevr.math.angle.Angle
import dev.slimevr.tracker.Motion
import dev.slimevr.tracker.Tracker
@@ -11,6 +11,7 @@ import io.github.axisangles.ktmath.EulerOrder
import kotlinx.coroutines.test.runTest
import solarxr_protocol.datatypes.BodyPart
import solarxr_protocol.datatypes.TrackerStatus
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
@@ -22,12 +23,14 @@ import kotlin.test.assertNull
*/
class ComputeYawCorrectionTest {
- val enabledStayAlignedConfig = StayAlignedConfig(
- enabled = true,
- standingRelaxedPose = StayAlignedRelaxedPoseConfig(true),
- sittingRelaxedPose = StayAlignedRelaxedPoseConfig(true),
- flatRelaxedPose = StayAlignedRelaxedPoseConfig(true),
- setupComplete = true,
+ val recordedPose = StayAlignedPoseConfig(recorded = true, enabled = true)
+
+ val userConfigWithPoses = UserConfigData(
+ stayAlignedPoses = mapOf(
+ StayAlignedRelaxedPose.STANDING to recordedPose,
+ StayAlignedRelaxedPose.SITTING to recordedPose,
+ StayAlignedRelaxedPose.FLAT to recordedPose,
+ ),
)
val pointFiveYaw = EulerAngles(
@@ -63,7 +66,7 @@ class ComputeYawCorrectionTest {
lockedTrackerState,
listOf(lockedTrackerState),
Angle(0.002f),
- enabledStayAlignedConfig,
+ userConfigWithPoses,
)
assertNotNull(result)
@@ -76,7 +79,7 @@ class ComputeYawCorrectionTest {
lockedTrackerState,
listOf(lockedTrackerState),
Angle(0f),
- enabledStayAlignedConfig,
+ userConfigWithPoses,
)
assertNotNull(result)
@@ -89,7 +92,7 @@ class ComputeYawCorrectionTest {
primarilyAtRestTrackerState,
listOf(primarilyAtRestTrackerState),
Angle(0.002f),
- enabledStayAlignedConfig,
+ userConfigWithPoses,
)
assertNull(result)
@@ -107,7 +110,7 @@ class ComputeYawCorrectionTest {
movingTrackerState.copy(bodyPart = BodyPart.RIGHT_LOWER_LEG, rotation = fiveYaw),
),
Angle(0.002f),
- enabledStayAlignedConfig,
+ userConfigWithPoses,
)
assertNotNull(result)
diff --git a/server/core/src/test/java/dev/slimevr/stayaligned/PoseRecordingTest.kt b/server/core/src/test/java/dev/slimevr/stayaligned/PoseRecordingTest.kt
new file mode 100644
index 000000000..f19142f9c
--- /dev/null
+++ b/server/core/src/test/java/dev/slimevr/stayaligned/PoseRecordingTest.kt
@@ -0,0 +1,129 @@
+package dev.slimevr.stayaligned
+
+import dev.slimevr.config.StayAlignedPoseConfig
+import dev.slimevr.config.UserConfigData
+import dev.slimevr.math.angle.Angle
+import dev.slimevr.solarxr.rpc.buildStayAlignedStatusResponse
+import dev.slimevr.tracker.Motion
+import dev.slimevr.tracker.Tracker
+import dev.slimevr.tracker.TrackerState
+import dev.slimevr.tracker.stayaligned.checkPoseRecording
+import dev.slimevr.tracker.stayaligned.missingRequiredParts
+import dev.slimevr.tracker.stayaligned.poses.PlayerPose
+import dev.slimevr.tracker.stayaligned.poses.RelaxedPose
+import dev.slimevr.tracker.stayaligned.poses.stayAlignedPoseConfig
+import dev.slimevr.tracker.stayaligned.recordedPoseConfig
+import io.github.axisangles.ktmath.EulerAngles
+import io.github.axisangles.ktmath.EulerOrder
+import io.github.axisangles.ktmath.Quaternion
+import solarxr_protocol.datatypes.BodyPart
+import solarxr_protocol.datatypes.TrackerStatus
+import solarxr_protocol.rpc.StayAlignedDetectedPoseState
+import solarxr_protocol.rpc.StayAlignedPart
+import solarxr_protocol.rpc.StayAlignedPoseRecordingFailure
+import solarxr_protocol.rpc.StayAlignedPoseState
+import solarxr_protocol.rpc.StayAlignedRelaxedPose
+import solarxr_protocol.rpc.StayAlignedTrackerCorrection
+import kotlin.math.abs
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ * Tests what Stay Aligned decides about the trackers: whether a pose can be recorded, which angles
+ * it gets, how the poses start, and what the status reports.
+ */
+class PoseRecordingTest {
+
+ private fun tracker(part: BodyPart): TrackerState = Tracker.DEFAULT_STATE.copy(
+ bodyPart = part,
+ motion = Motion.RESTING,
+ status = TrackerStatus.OK,
+ rotation = Quaternion.IDENTITY,
+ stayAlignedData = Tracker.DEFAULT_STATE.stayAlignedData.copy(lockedRotation = Quaternion.IDENTITY),
+ )
+
+ private fun yaw(radians: Float) = EulerAngles(EulerOrder.YZX, 0f, radians, 0f).toQuaternion()
+
+ private val standingTrackers = listOf(
+ BodyPart.HIP,
+ BodyPart.LEFT_UPPER_LEG,
+ BodyPart.RIGHT_UPPER_LEG,
+ BodyPart.LEFT_LOWER_LEG,
+ BodyPart.RIGHT_LOWER_LEG,
+ ).map { tracker(it) }
+
+ private fun withTracker(part: BodyPart, change: (TrackerState) -> TrackerState) = standingTrackers.map { if (it.bodyPart == part) change(it) else it }
+
+ private val unknownPosition = withTracker(BodyPart.LEFT_UPPER_LEG) { it.copy(rotation = Quaternion.rotationAroundZAxis(Math.PI.toFloat() / 2)) }
+ private val standingRecorded = UserConfigData(stayAlignedPoses = mapOf(StayAlignedRelaxedPose.STANDING to StayAlignedPoseConfig(recorded = true, enabled = true)))
+
+ @Test
+ fun `standing still is ready to record standing`() {
+ assertEquals(StayAlignedPoseRecordingFailure.NONE, checkPoseRecording(standingTrackers, StayAlignedRelaxedPose.STANDING).failure)
+ }
+
+ @Test
+ fun `a tracker that moves is reported before the wrong pose`() {
+ val trackers = withTracker(BodyPart.HIP) { it.copy(motion = Motion.ROTATING) }
+
+ assertEquals(StayAlignedPoseRecordingFailure.NOT_STILL, checkPoseRecording(trackers, StayAlignedRelaxedPose.SITTING).failure)
+ }
+
+ @Test
+ fun `another pose than the requested one is the wrong pose`() {
+ assertEquals(StayAlignedPoseRecordingFailure.WRONG_POSE, checkPoseRecording(standingTrackers, StayAlignedRelaxedPose.SITTING).failure)
+ }
+
+ @Test
+ fun `a position that matches no pose is unknown, not wrong`() {
+ assertEquals(StayAlignedPoseRecordingFailure.POSITION_UNKNOWN, checkPoseRecording(unknownPosition, StayAlignedRelaxedPose.STANDING).failure)
+ }
+
+ @Test
+ fun `a missing required tracker is listed and stops the recording, missing feet are fine`() {
+ val trackers = standingTrackers.filter { it.bodyPart != BodyPart.LEFT_LOWER_LEG }
+
+ assertEquals(listOf(StayAlignedPart.LEFT_LOWER_LEG), missingRequiredParts(trackers))
+ assertEquals(StayAlignedPoseRecordingFailure.MISSING_TRACKERS, checkPoseRecording(trackers, StayAlignedRelaxedPose.STANDING).failure)
+ }
+
+ @Test
+ fun `a recorded pose is measured from the locked rotations`() {
+ val trackers = standingTrackers.map {
+ when (it.bodyPart) {
+ BodyPart.LEFT_UPPER_LEG -> it.copy(rotation = yaw(0f), stayAlignedData = it.stayAlignedData.copy(lockedRotation = yaw(0.2f)))
+ BodyPart.RIGHT_UPPER_LEG -> it.copy(rotation = yaw(0f), stayAlignedData = it.stayAlignedData.copy(lockedRotation = yaw(-0.2f)))
+ else -> it
+ }
+ }
+
+ assertTrue(abs(recordedPoseConfig(trackers).upperLegAngleInDeg - Math.toDegrees(0.2).toFloat()) < 0.1f)
+ }
+
+ @Test
+ fun `kneeling starts usable and goes back to that on reset`() {
+ val recorded = UserConfigData(stayAlignedPoses = mapOf(StayAlignedRelaxedPose.KNEELING to StayAlignedPoseConfig(recorded = true, enabled = true, upperLegAngleInDeg = 12f)))
+ val reset = recorded.copy(stayAlignedPoses = recorded.stayAlignedPoses - StayAlignedRelaxedPose.KNEELING)
+
+ assertEquals(StayAlignedPoseConfig(enabled = true), stayAlignedPoseConfig(UserConfigData(), StayAlignedRelaxedPose.KNEELING))
+ assertEquals(StayAlignedPoseConfig(enabled = true), stayAlignedPoseConfig(reset, StayAlignedRelaxedPose.KNEELING))
+ }
+
+ @Test
+ fun `a pose that is turned off has no relaxed angles`() {
+ val config = UserConfigData(stayAlignedPoses = mapOf(StayAlignedRelaxedPose.STANDING to StayAlignedPoseConfig(recorded = true, enabled = false)))
+
+ assertNull(RelaxedPose.forPose(PlayerPose.STANDING, config))
+ }
+
+ @Test
+ fun `status reports the tracker turned the most, rounded`() {
+ val trackers = withTracker(BodyPart.LEFT_LOWER_LEG) { it.copy(stayAlignedData = it.stayAlignedData.copy(yawCorrection = Angle.ofDeg(-4.24f))) }
+
+ assertEquals(StayAlignedTrackerCorrection(BodyPart.LEFT_LOWER_LEG, 4.2f), buildStayAlignedStatusResponse(true, trackers, standingRecorded).largestCorrection)
+ assertNull(buildStayAlignedStatusResponse(false, trackers, standingRecorded).largestCorrection)
+ assertNull(buildStayAlignedStatusResponse(true, standingTrackers, standingRecorded).largestCorrection)
+ }
+}
diff --git a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt
index 6c1b511f5..abc14d8db 100644
--- a/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt
+++ b/server/core/src/test/java/dev/slimevr/trackingchecklist/TrackingChecklistTest.kt
@@ -12,6 +12,7 @@ import dev.slimevr.config.SettingsActions
import dev.slimevr.networkprofile.NetworkInfo
import dev.slimevr.networkprofile.NetworkProfileActions
import dev.slimevr.networkprofile.NetworkProfileManager
+import dev.slimevr.resets.ResetsActions
import dev.slimevr.resets.ResetsManager
import dev.slimevr.routing.BoneRoutingManager
import dev.slimevr.tracker.Tracker
@@ -29,6 +30,7 @@ import solarxr_protocol.datatypes.DeviceOrigin
import solarxr_protocol.datatypes.MountingMethod
import solarxr_protocol.datatypes.TrackerStatus
import solarxr_protocol.datatypes.hardware_info.ImuType
+import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.RoutingOutput
import solarxr_protocol.rpc.TrackingChecklistStep
import solarxr_protocol.rpc.TrackingChecklistStepId
@@ -65,7 +67,7 @@ class TrackingChecklistTest {
ReliableReferenceCheckBehaviour(trackerStates),
TrackerRestCheckBehaviour(trackerStates),
TrackerErrorCheckBehaviour(trackerStates),
- FullResetCheckBehaviour(trackerStates),
+ FullResetCheckBehaviour(trackerStates, resetsManager),
MountingCalibrationCheckBehaviour(trackerStates, settings),
FeetMountingCalibrationCheckBehaviour(trackerStates, settings),
NetworkProfileCheckBehaviour(networkProfileManager),
@@ -104,7 +106,12 @@ class TrackingChecklistTest {
return tracker
}
- fun fullReset() = trackers.forEach { it.context.dispatch(TrackerActions.FullReset(null)) }
+ fun fullReset() {
+ trackers.forEach { it.context.dispatch(TrackerActions.FullReset(null)) }
+ resetsManager.context.dispatch(ResetsActions.EndReset(ResetType.FULL))
+ }
+
+ fun mountingReset() = resetsManager.context.dispatch(ResetsActions.ClearResets(listOf(ResetType.MOUNTING)))
fun setMountingMethod(method: MountingMethod) = settings.context.dispatch(
SettingsActions.Update { copy(resetsConfig = resetsConfig.copy(mountingMethod = method)) },
@@ -181,6 +188,25 @@ class TrackingChecklistTest {
assertEquals(listOf(added.context.state.value.id.toUShort()), pending)
}
+ @Test
+ fun `FULL_RESET is due again when the mounting window closes with a mounting calibration still to do`() = runTest {
+ val h = Harness(this)
+ h.addTracker(bodyPart = BodyPart.LOWER_CHEST)
+ runCurrent()
+ h.fullReset()
+ runCurrent()
+ assertEquals(true, h.step(TrackingChecklistStepId.FULL_RESET).valid)
+ assertEquals(false, h.step(TrackingChecklistStepId.MOUNTING_CALIBRATION).valid)
+
+ h.mountingReset()
+ runCurrent()
+ assertEquals(false, h.step(TrackingChecklistStepId.FULL_RESET).valid)
+
+ h.fullReset()
+ runCurrent()
+ assertEquals(true, h.step(TrackingChecklistStepId.FULL_RESET).valid)
+ }
+
@Test
fun `MOUNTING_CALIBRATION is enabled with an IMU tracker and valid after a mounting reset`() = runTest {
val h = Harness(this)
diff --git a/solarxr-protocol b/solarxr-protocol
index f19f1afab..1f15af406 160000
--- a/solarxr-protocol
+++ b/solarxr-protocol
@@ -1 +1 @@
-Subproject commit f19f1afabc8281db5ba09a4c84aa07e6b6614bba
+Subproject commit 1f15af40681f95e79498f180f1c64cd12e74babb