Compare commits

...
Author SHA1 Message Date
Butterscotch! 7a09d31b04 Reset theory tests 2026-04-19 23:56:38 -04:00
Butterscotch! 73984799f2 Rename TrackerTestUtils methods & add quat/vec 2026-04-19 23:56:37 -04:00
gale be77ff73d7 Allow passing excess CLI arguments to Electron (#1817) 2026-04-18 19:22:01 +02:00
Sapphire d79d93cd0e Don't trigger submit when receiving settings from server (#1815) 2026-04-17 21:24:09 +02:00
lucas lelievre c022a557ed Electon - Config loading fixing (#1814) 2026-04-17 20:59:47 +02:00
loucass003 1799483f26 Revert "Electon - Config loading fixing"
This reverts commit 52491f2c2b.
2026-04-17 20:20:17 +02:00
loucass003 52491f2c2b Electon - Config loading fixing 2026-04-17 20:19:01 +02:00
Ilia Kiandsctanf 60077307d5 Introduce VID/PID allow lists (#1792)
Co-authored-by: sctanf <[email protected]>
2026-04-16 19:07:46 +02:00
Butterscotch! 65d4520c10 Rework VRChat OSC address/port handling (#1701) 2026-04-16 19:06:10 +02:00
Butterscotch! 0d3254bc27 Fix BVH hierarchy (#1772) 2026-04-16 18:25:56 +02:00
96cddb52bb Steam (#1763)
Co-authored-by: loucass003 <[email protected]>
Co-authored-by: HannahPadd <[email protected]>
2026-04-16 15:00:19 +02:00
lucas lelievre 110e0ce840 Fix lint / compile issues and Form typings (#1813) 2026-04-16 14:44:39 +02:00
lucas lelievre cc364978a0 Fix ip num (#1812) 2026-04-16 12:18:19 +02:00
Sapphire 0ed7bf5838 Add warning when SteamVR hand trackers are erroneously enabled (#1776) 2026-04-16 11:35:40 +02:00
dependabot[bot] fdbc52a1b6 Bump pnpm/action-setup from 4 to 6 (#1809)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 10:50:40 +02:00
dependabot[bot] 112faacafd Bump softprops/action-gh-release from 2 to 3 (#1810)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 10:47:41 +02:00
loucass003 ae33eea790 Make sure everything combiles after solaxr fix 2026-04-16 10:44:59 +02:00
loucass003 b5a4cf7bac Fix solarxr 2026-04-16 08:38:31 +00:00
Aed 54fbaa7b0b spelling police at it again (#1807) 2026-04-16 09:47:00 +02:00
Sapphire 3343894a80 Fix version sorting for DIY firmware tool (#1803) 2026-04-16 09:45:46 +02:00
dependabot[bot] 7e0a06a7b8 Bump gradle/actions from 5 to 6 (#1800)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 09:45:23 +02:00
Collin 706489d42c Fix floor clip bug (#1799) 2026-04-16 09:45:08 +02:00
Sapphire e9a36313cc Remove unnecessary parts of glTF header when sending VRM to server (#1796) 2026-04-16 09:31:40 +02:00
dependabot[bot] e05d19b435 Bump actions/upload-artifact from 6 to 7 (#1790)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 09:30:39 +02:00
Aed 6b6abebca5 spelling police at it again (#1791) 2026-04-16 09:28:55 +02:00
Kitlith 319f69cdcd Fix udev vid/pid capitalization. (#1788) 2026-04-16 09:04:05 +02:00
Sapphire c46c536a1a RegEditLinux: Find VRChat install location for registry parsing (#1785) 2026-04-16 09:00:32 +02:00
sctanf a98772d3aa HID open fix (#1782) 2026-04-16 08:59:30 +02:00
Spazzwan 6c7e6a4f42 Adjust finger bone length subdivision to more naturally simulate fingers (#1781) 2026-04-16 08:58:55 +02:00
Sapphireandloucass003 f4646f1133 Send SteamVRTrackersSetting when changing tracker toggles (#1778)
Co-authored-by: loucass003 <[email protected]>
2026-04-16 08:56:22 +02:00
ShineBrightMeow 306510c1d9 Add ICM-55686 to Const (#1774) 2026-04-16 08:52:52 +02:00
Sapphire 1560c0a1ec Don't always advance to next Stay Aligned setup step on reset (#1775) 2026-04-16 08:52:34 +02:00
Sapphire 04aa882222 Re-request skeleton config on proportions import (#1777) 2026-04-16 08:43:16 +02:00
dependabot[bot] e4b3b93e35 Bump actions/download-artifact from 6 to 8 (#1769)
Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-16 08:42:18 +02:00
peelz 96b544f5e0 fix: use transaction id in reset response (#1767) 2026-04-16 08:41:55 +02:00
sctanf eca4eb770c HIDCommon scheduled TIMED_OUT (#1761) 2026-04-16 08:40:49 +02:00
sctanf 036a893c28 HIDCommon use button as tap (#1760) 2026-04-16 08:40:12 +02:00
sctanf 428d16f19a Allow 0% battery level (#1755) 2026-04-16 08:37:45 +02:00
c8538b5521 Onboarding Quiz (#1751)
Co-authored-by: Sapphire <[email protected]>
Co-authored-by: loucass003 <[email protected]>
Co-authored-by: lucas lelievre <[email protected]>
Co-authored-by: Hannah <[email protected]>
2026-04-16 08:34:40 +02:00
112 changed files with 4723 additions and 3989 deletions

No files matched your search

+19 -19
View File
@@ -37,7 +37,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
@@ -60,7 +60,7 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Java Spotless Check
run: ./gradlew spotlessCheck --build-cache
@@ -81,13 +81,13 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Build ShadowJar
run: ./gradlew :server:desktop:shadowJar --build-cache
- name: Test with Gradle
run: ./gradlew :server:desktop:test
- name: Upload Server Jar
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: server-jar
path: |
@@ -105,7 +105,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
@@ -118,7 +118,7 @@ jobs:
- name: Tar GUI Dist
run: tar -czf slimevr-gui-dist.tar.gz -C gui/out .
- name: Upload GUI Dist
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: gui-dist
path: slimevr-gui-dist.tar.gz
@@ -138,19 +138,19 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Setup PNPM
uses: pnpm/action-setup@v4
uses: pnpm/action-setup@v6
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Download Server Jar
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Electron
@@ -168,8 +168,8 @@ jobs:
[ -z "$VERSION" ] && VERSION="0.0.0"
VERSION="${VERSION#v}"
echo "Building version: $VERSION"
cd gui
pnpm i
cd gui
pnpm exec electron-builder --${{ matrix.platform }} \
${{ matrix.platform == 'macos' && '--universal' || '' }} \
--config.extraMetadata.version="$VERSION" \
@@ -200,7 +200,7 @@ jobs:
echo "Collected files:"
ls -lh "$DEST_DIR"
- name: Upload For Release
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.platform }}-${{ matrix.os }}
path: release-out/*
@@ -222,9 +222,9 @@ jobs:
java-version: '17'
distribution: 'adopt'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v5
uses: gradle/actions/setup-gradle@v6
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Extract GUI for Android
@@ -241,7 +241,7 @@ jobs:
- name: Prepare APK
run: cp server/android/build/outputs/apk/release/*.apk ./SlimeVR-android.apk
- name: Upload APK
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
with:
name: release-android
path: SlimeVR-android.apk
@@ -256,7 +256,7 @@ jobs:
ANDROID_KEY_PASSWD: ${{ secrets.ANDROID_GPLAY_KEY_PASSWD }}
- name: Upload the Google Play artifact
uses: actions/upload-artifact@v6
uses: actions/upload-artifact@v7
if: startsWith(github.ref, 'refs/tags/')
with:
# Artifact name
@@ -271,22 +271,22 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download All Release Artifacts
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
pattern: release-*
path: release-out
merge-multiple: true
- name: Download Server Jar
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: server-jar
path: server
- name: Download GUI Dist
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
name: gui-dist
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
draft: true
generate_release_notes: true
@@ -20,13 +20,13 @@ jobs:
run: |
npx @slimevr/update-manifest-generator@latest
- uses: actions/upload-artifact@v6
- uses: actions/upload-artifact@v7
with:
name: "update-manifest.json"
path: ./update-manifest.json
- name: Upload update-manifest.json to release
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ secrets.UPDATE_MANIFEST_RELEASE_TAG }}
files: ./update-manifest.json
+13 -3
View File
@@ -1,12 +1,22 @@
import { program } from "commander";
import { Option, program } from "commander";
program
.option('-p --path <path>', 'set launch path')
.option('-p, --path <path>', 'set launch path')
.option('-s, --steam', 'steam mode')
.option('-i, --install', 'run the driver installer')
.option(
'--skip-server-if-running',
'gui will not launch the server if it is already running'
)
.allowUnknownOption();
.allowUnknownOption()
// Allow passing arguments to Electron.
.allowExcessArguments();
if (process.platform === "linux") {
const noUdevOption = new Option('--no-udev', 'disable udev warning');
noUdevOption.negate = false;
program.addOption(noUdevOption)
}
program.parse(process.argv);
export const options = program.opts();
+51 -12
View File
@@ -20,22 +20,25 @@ import { getPlatform, handleIpc, isPortAvailable } from './utils';
import {
findServerJar,
findSystemJRE,
getExeFolder,
getGuiDataFolder,
getLogsFolder,
getServerDataFolder,
getWindowStateFile,
} from './paths';
import { stores } from './store';
import { initStores } from './store';
import { closeLogger, logger } from './logger';
import { writeFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { discordPresence } from './presence';
import { options } from './cli';
import { ServerStatusEvent } from 'electron/preload/interface';
import { mkdir } from 'node:fs/promises';
import { mkdir, writeFile } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
type Stores = Awaited<ReturnType<typeof initStores>>;
let stores: Stores;
// Fixes colors looking washed on linux
// Might affect hdr
if (process.platform === 'linux') {
@@ -182,13 +185,11 @@ handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
return getGuiDataFolder();
case 'logs':
return getLogsFolder();
case 'exe':
return getExeFolder();
}
});
const windowStateFile = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
}).catch(() => null);
const defaultWindowState: {
width: number;
height: number;
@@ -200,7 +201,15 @@ const defaultWindowState: {
x: undefined,
y: undefined,
};
const windowState = windowStateFile ? JSON.parse(windowStateFile) : defaultWindowState;
const windowState = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
})
.then(data => JSON.parse(data))
.catch(() => {
logger.error('Failed to load window state, using defaults');
return defaultWindowState;
});
const MIN_WIDTH = 393;
const MIN_HEIGHT = 667;
@@ -233,7 +242,7 @@ function validateWindowState(state: typeof defaultWindowState) {
const saveWindowState = async () => {
await mkdir(dirname(getWindowStateFile()), { recursive: true });
writeFileSync(getWindowStateFile(), JSON.stringify(windowState));
await writeFile(getWindowStateFile(), JSON.stringify(windowState), { encoding: 'utf-8' });
};
function createWindow() {
@@ -394,7 +403,16 @@ const spawnServer = async () => {
logger.info({ javaBin, serverJar }, 'Found Java and server jar');
const platform = getPlatform();
const serverWorkdir = getServerDataFolder()
const serverProcess = spawn(javaBin, ['-Xmx128M', '-jar', serverJar, 'run'], {
const serverArgs = ['-Xmx128M', '-jar', serverJar]
if (options.steam) serverArgs.push(`--steam`)
if (options.install) serverArgs.push(`--install`)
if (options.noUdev) serverArgs.push(`--no-udev`)
serverArgs.push('run')
const serverProcess = spawn(javaBin, serverArgs, {
cwd: serverWorkdir,
shell: false,
env:
@@ -439,6 +457,12 @@ const spawnServer = async () => {
};
};
const createFolders = async () => {
await mkdir(getServerDataFolder(), { recursive: true });
await mkdir(getGuiDataFolder(), { recursive: true });
}
let isQuitting = false;
app.whenReady().then(async () => {
@@ -449,6 +473,21 @@ app.whenReady().then(async () => {
return net.fetch('file://' + filePath);
});
try {
await createFolders();
} catch (err) {
logger.error(err, 'Failed to initialize stores');
dialog.showErrorBox(
'SlimeVR',
'Failed to initialize application storage. Please make sure the application has write permissions to its data folder.'
);
app.quit();
return;
}
stores = await initStores();
checkEnvironmentVariables();
const server = await spawnServer();
@@ -467,8 +506,8 @@ app.whenReady().then(async () => {
logger.info('App quitting, saving...');
server?.close();
await server?.waitForExit();
stores.settings.save();
stores.cache.save();
await stores.settings.save();
await stores.cache.save();
discordPresence.destroy();
await saveWindowState();
await closeLogger();
+14 -2
View File
@@ -48,12 +48,21 @@ export const getLogsFolder = () => {
return join(getGuiDataFolder(), 'logs');
};
export const getExeFolder = () => {
return path.dirname(app.getPath('exe'));
};
export const getWindowStateFile = () =>
join(getServerDataFolder(), '.window-state.json');
const localJavaBin = (sharedDir: string) => {
const jre = join(sharedDir, 'jre/bin', javaBin);
return jre;
const platform = getPlatform();
switch (platform) {
case 'macos':
return join(sharedDir, '../../../../jre/Contents/Home/bin', javaBin);
default:
return join(sharedDir, 'jre/bin', javaBin);
}
};
const javaHomeBin = () => {
@@ -112,6 +121,9 @@ export const findServerJar = () => {
// For flatpack container
path.resolve('/app/share/slimevr/'),
path.resolve('/usr/share/slimevr/'),
// For macos on steam
path.resolve(`${app.getPath('exe')}/../../../../`),
];
return paths
.filter((p) => !!p)
+23 -20
View File
@@ -1,4 +1,4 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { access, mkdir, readFile, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { logger } from "./logger";
import { getGuiDataFolder } from "./paths";
@@ -10,25 +10,28 @@ export class CustomStore {
private filePath: string;
private debounceMs: number;
constructor(filePath: string, debounceMs: number = 2000) {
private constructor(filePath: string, debounceMs: number = 2000) {
this.filePath = filePath;
this.debounceMs = debounceMs;
this.load();
}
private load() {
static async create(filePath: string, debounceMs: number = 2000): Promise<CustomStore> {
const store = new CustomStore(filePath, debounceMs);
await store.load();
return store;
}
private async load(): Promise<void> {
try {
if (existsSync(this.filePath)) {
const raw = readFileSync(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
}
} catch (err) {
logger.error(err, `Failed to load store at ${this.filePath}`);
await access(this.filePath);
const raw = await readFile(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
} catch {
this.data = {};
logger.warn(`No existing store found at ${this.filePath}, starting with empty store.`);
}
}
/** Set a key and trigger the debounced auto-save */
set(key: string, value: unknown) {
this.data[key] = value;
this.triggerAutoSave();
@@ -54,14 +57,12 @@ export class CustomStore {
}, this.debounceMs);
}
save(): boolean {
async save(): Promise<boolean> {
try {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
const dir = dirname(this.filePath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
return true;
} catch (err) {
logger.error(err, 'Save failed', this.filePath);
@@ -70,7 +71,9 @@ export class CustomStore {
}
}
export const stores = {
settings: new CustomStore(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: new CustomStore(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
export async function initStores() {
return {
settings: await CustomStore.create(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
}
+2 -1
View File
@@ -36,5 +36,6 @@ contextBridge.exposeInMainWorld('electronAPI', {
openLogsFolder: async () => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, await ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'logs')),
openFile: (path) => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, path),
ghGet: (req) => ipcRenderer.invoke(IPC_CHANNELS.GH_FETCH, req),
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options)
setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options),
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe')
} satisfies IElectronAPI);
+1
View File
@@ -56,6 +56,7 @@ export interface IElectronAPI {
openFile: (path: string) => void;
ghGet: <T extends GHGet>(options: T) => Promise<GHReturn[T['type']]>;
setPresence: (options: DiscordPresence) => void;
getInstallDir: () => Promise<string>;
}
declare global {
@@ -14,24 +14,24 @@
## QinHeng
# CH340
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7522", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="7523", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7522", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE="0660", TAG+="uaccess"
# CH341
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="5523", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="5523", MODE="0660", TAG+="uaccess"
# CH343
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D3", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d3", MODE="0660", TAG+="uaccess"
# CH9102x
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1A86", ATTRS{idProduct}=="55D4", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="55d4", MODE="0660", TAG+="uaccess"
## Silabs
# CP210x
SUBSYSTEMS=="usb", ATTRS{idVendor}=="10C4", ATTRS{idProduct}=="EA60", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", MODE="0660", TAG+="uaccess"
## Espressif
# ESP32-S3 / ESP32-C3 / ESP32-C5 / ESP32-C6 / ESP32-C61 / ESP32-H2 / ESP32-P4
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="1001", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="1001", MODE="0660", TAG+="uaccess"
# ESP32-S2
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303A", ATTRS{idProduct}=="0002", MODE="0660", TAG+="uaccess"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="0002", MODE="0660", TAG+="uaccess"
## FTDI
# FT232BM/L/Q, FT245BM/L/Q
+1 -1
View File
@@ -41,7 +41,7 @@ export interface IpcInvokeMap {
value?: unknown;
}) => Promise<unknown>;
[IPC_CHANNELS.OPEN_FILE]: (path: string) => void;
[IPC_CHANNELS.GET_FOLDER]: (folder: 'config' | 'logs') => string;
[IPC_CHANNELS.GET_FOLDER]: (folder: 'config' | 'logs' | 'exe') => string;
[IPC_CHANNELS.GH_FETCH]: <T extends GHGet>(
options: T
) => Promise<GHReturn[T['type']]>;
+2
View File
@@ -70,6 +70,8 @@
"electron": "^40.3.0",
"electron-builder": "^26.7.0",
"electron-vite": "^5.0.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "^9.39.4",
"eslint": "^9.39.1",
"eslint-import-resolver-typescript": "^3.10.1",
"eslint-plugin-import": "^2.32.0",
+58 -4
View File
@@ -524,8 +524,10 @@ settings-general-steamvr-trackers-right_hand = Right hand
settings-general-steamvr-trackers-tracker_toggling = Automatic tracker assignment
settings-general-steamvr-trackers-tracker_toggling-description = Automatically handles toggling SteamVR trackers on or off depending on your current tracker assignments.
settings-general-steamvr-trackers-tracker_toggling-label = Automatic tracker assignment
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> hand trackers will override your controllers.
Are you sure?
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> Enabling the SteamVR hand trackers will disable inputs from real controllers.
This should only be enabled if you are using SlimeVR for hand tracking.
Are you sure you want to do this?
settings-general-steamvr-trackers-hands-warning-cancel = Cancel
settings-general-steamvr-trackers-hands-warning-done = Yes
@@ -934,8 +936,50 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Skip setup
onboarding-setup_warning-cancel = Continue setup
## Quiz
onboarding-quiz_continue = Continue
onboarding-quiz_back = Back
onboarding-quiz-more_sets_modal-title = Have you connected all of your trackers?
onboarding-quiz-more_sets_modal-desc = If you have sets of different models, we can connect them right now!
onboarding-quiz-more_sets_modal-confirm = I have connected all my trackers
onboarding-quiz-more_sets_modal-cancel = I want to connect more trackers
onboarding-quiz-slimeset-title = What type of trackers are you connecting?
onboarding-quiz-slimeset-description = If you have multiple sets, you will be asked again later in the process
onboarding-quiz-slimeset-official-sets = Official SlimeVR Trackers
onboarding-quiz-slimeset-thirdparty-sets = Third-party or DIY Trackers
onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 & V1.2
onboarding-quiz-slimeset-answer-butterfly = Butterfly
onboarding-quiz-slimeset-answer-wifi = WiFi-based Slime
onboarding-quiz-slimeset-answer-dongle = Dongle-based Slime
onboarding-quiz-usage-title = What are you using your trackers for?
onboarding-quiz-usage-description = If you plan on using SlimeVR for multiple purposes, you can change the affected settings later.
onboarding-quiz-usage-answer-VRC = VR Gaming (e.g. VRChat)
onboarding-quiz-usage-answer-mocap_vtubing = Mocap and VTubing
onboarding-quiz-runtime-title = Do you run games via SteamVR, or on the headset itself (standalone)?
onboarding-quiz-runtime-answer-steamvr = SteamVR
onboarding-quiz-runtime-answer-standalone = Standalone
onboarding-quiz-mocap_preferences-title = Mocap Preferences
onboarding-quiz-mocap_preferences-desc = Specify how you plan to use SlimeVR for mocap or VTubing
onboarding-quiz-mocap_preferences-playspace-title = What is your playspace?
onboarding-quiz-mocap_preferences-playspace-desc = If standing, SlimeVR will try to track walking movement instead of anchoring you in one spot.
onboarding-quiz-mocap_preferences-playspace-sitting = Sitting
onboarding-quiz-mocap_preferences-playspace-standing = Standing
onboarding-quiz-mocap_preferences-vrm_model-title = Do you have a VRM model? (Optional)
onboarding-quiz-mocap_preferences-vrm_model-desc = Loading a VRM model will improve tracking quality and compatibility with applications that use VMC.
onboarding-quiz-mocap_preferences-head_tracker-title = Are you wearing a tracker or VR headset on your head?
onboarding-quiz-mocap_preferences-head_tracker-yes = Yes
onboarding-quiz-mocap_preferences-head_tracker-no = No
onboarding-quiz-mocap_preferences-head_tracker_location-title = Where is your head tracker located?
onboarding-quiz-mocap_preferences-head_tracker_location-forehead = Forehead
onboarding-quiz-mocap_preferences-head_tracker_location-face = Face
## Wi-Fi setup
onboarding-wifi_creds-back = Go back to introduction
onboarding-wifi_creds-back-v2 = Go back
onboarding-wifi_creds-v2 = Trackers using Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
@@ -980,6 +1024,11 @@ onboarding-reset_tutorial-2 = Tap the highlighted tracker { $taps } times to tri
You need to be in a pose like you are skiing as shown in the Automatic Mounting wizard, and you have a 3 second delay (configurable) before it gets triggered.
## Install info
install-info_udev-rules_modal_title = Hardware udev access rules not found
install-info_udev-rules_warning = Access rules via udev are required for serial console access & dongle connection. Paste the following command into your terminal to add the udev rules.
install-info_udev-rules_modal_button = Close
install-info_udev-rules_modal-dont-show-again_checkbox = Don't show again
## Setup start
onboarding-home = Welcome to SlimeVR
onboarding-home-start = Let's get set up!
@@ -1306,6 +1355,7 @@ onboarding-user_height-description = We need your height to calculate your body
onboarding-user_height-need_head_tracker = A headset and controllers with positional tracking are required to perform the calibration.
onboarding-user_height-calculate = Calculate my height automatically
onboarding-user_height-next_step = Continue and save
onboarding-user_height-prev_step = Back
onboarding-user_height-manual-proportions = Manual Proportions
onboarding-user_height-calibration-title = Calibration Progress
onboarding-user_height-calibration-RECORDING_FLOOR = Touch the floor with the tip of your controller
@@ -1468,6 +1518,7 @@ firmware_tool-flashing_step-description =
firmware_tool-flashing_step-warning-v2 = Do not unplug or turn off the tracker during the upload process unless told to, it may make your board unusable
firmware_tool-flashing_step-flash_more = Flash more trackers
firmware_tool-flashing_step-exit = Exit
firmware_tool-flashing_step-onboarding_continue = Continue
## firmware tool build status
firmware_tool-build-QUEUED = Waiting to build....
@@ -1601,8 +1652,11 @@ tracking_checklist-FULL_RESET-desc = Some trackers need a reset to be performed.
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR not running
tracking_checklist-STEAMVR_DISCONNECTED-desc = SteamVR is not running. Are you using it for VR?
tracking_checklist-STEAMVR_DISCONNECTED-open = Launch SteamVR
tracking_checklist-STEAMVR_HANDS_ENABLED = Hand trackers toggled on
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = You have enabled the SteamVR virtual hand trackers. This will cause button inputs to not work in SteamVR and in games.
tracking_checklist-STEAMVR_HANDS_ENABLED-go = Disable them
tracking_checklist-TRACKERS_REST_CALIBRATION = Calibrate your trackers
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = You didn't perform tracker calibration. Please let your trackers (highlighted in yellow) rest on a stable surface for a few secconds.
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = You didn't perform tracker calibration. Please let your trackers (highlighted in yellow) rest on a stable surface for a few seconds.
tracking_checklist-TRACKER_ERROR = Trackers with Errors
tracking_checklist-TRACKER_ERROR-desc = Some of your trackers have an error. Please restart the trackers highlighted in yellow.
tracking_checklist-VRCHAT_SETTINGS = Configure VRChat settings
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

+19 -1
View File
@@ -11,16 +11,18 @@ import {
WebSocketApiContext,
} from './hooks/websocket-api';
import { OnboardingContextProvider } from './components/onboarding/OnboardingContextProvicer';
import { OnboardingContextProvider } from './components/onboarding/OnboardingContextProvider';
import { OnboardingLayout } from './components/onboarding/OnboardingLayout';
import { AutomaticProportionsPage } from './components/onboarding/pages/body-proportions/AutomaticProportions';
import { ManualProportionsPage } from './components/onboarding/pages/body-proportions/ManualProportions';
import { ConnectTrackersPage } from './components/onboarding/pages/ConnectTracker';
import { HomePage } from './components/onboarding/pages/Home';
import { ErrorCollectingConsentPage } from './components/onboarding/pages/ErrorCollectingConsent';
import { AutomaticMountingPage } from './components/onboarding/pages/mounting/AutomaticMounting';
import { ManualMountingPage } from './components/onboarding/pages/mounting/ManualMounting';
import { TrackersAssignPage } from './components/onboarding/pages/trackers-assign/TrackerAssignment';
import { WifiCredsPage } from './components/onboarding/pages/WifiCreds';
import { DonglePage } from './components/onboarding/pages/Dongle';
import { ConfigContextProvider } from './components/providers/ConfigContext';
import { SerialDetectionModal } from './components/SerialDetectionModal';
import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings';
@@ -50,9 +52,14 @@ import { StayAlignedSetup } from './components/onboarding/pages/stay-aligned/Sta
import { TrackingChecklistProvider } from './components/tracking-checklist/TrackingChecklistProvider';
import { HomeScreenSettings } from './components/settings/pages/HomeScreenSettings';
import { ChecklistPage } from './components/tracking-checklist/TrackingChecklist';
import { QuizSlimeSetQuestion } from './components/onboarding/pages/quiz/SlimeSetQuestion';
import { QuizUsageQuestion } from './components/onboarding/pages/quiz/UsageQuestion';
import { QuizRuntimeQuestion } from './components/onboarding/pages/quiz/RuntimeQuestion';
import { QuizMocapPosQuestion } from './components/onboarding/pages/quiz/MocapPreferencesQuestions';
import { ElectronContextC, provideElectron } from './hooks/electron';
import { AppLocalizationProvider } from './i18n/config';
import { openUrl } from './hooks/crossplatform';
import { UdevRulesModal } from './components/onboarding/UdevRulesModal';
export const GH_REPO = 'SlimeVR/SlimeVR-Server';
export const VersionContext = createContext('');
@@ -70,6 +77,7 @@ function Layout() {
<SerialDetectionModal />
<VersionUpdateModal />
<UnknownDeviceModal />
<UdevRulesModal />
<SentryRoutes>
<Route element={<AppLayout />}>
<Route
@@ -147,7 +155,17 @@ function Layout() {
}
>
<Route path="home" element={<HomePage />} />
<Route
path="error-collecting-consent"
element={<ErrorCollectingConsentPage />}
/>
<Route path="wifi-creds" element={<WifiCredsPage />} />
<Route path="quiz/slime-set" element={<QuizSlimeSetQuestion />} />
<Route path="quiz/usage" element={<QuizUsageQuestion />} />
<Route path="quiz/runtime" element={<QuizRuntimeQuestion />} />
<Route path="quiz/mocap-pos" element={<QuizMocapPosQuestion />} />
<Route path="dongle" element={<DonglePage />} />
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
<Route path="connect-trackers" element={<ConnectTrackersPage />} />
<Route path="trackers-assign" element={<TrackersAssignPage />} />
<Route path="mounting/choose" element={<MountingChoose />} />
+8 -3
View File
@@ -1,9 +1,10 @@
import { useLayoutEffect } from 'react';
import { useConfig } from './hooks/config';
import { Outlet, useNavigate } from 'react-router-dom';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
export function AppLayout() {
const { config } = useConfig();
const { pathname } = useLocation();
const navigate = useNavigate();
useLayoutEffect(() => {
@@ -28,10 +29,14 @@ export function AppLayout() {
}, [config]);
useLayoutEffect(() => {
if (config && !config.doneOnboarding) {
if (
config &&
!config.doneOnboarding &&
!pathname.startsWith('/onboarding/')
) {
navigate('/onboarding/home');
}
}, [config?.doneOnboarding]);
}, [config]);
return (
<>
-60
View File
@@ -1,60 +0,0 @@
import { Localized, useLocalization } from '@fluent/react';
import { BaseModal } from './commons/BaseModal';
import { Button } from './commons/Button';
import { Typography } from './commons/Typography';
export function ErrorConsentModal({
isOpen = true,
cancel,
accept,
}: {
/**
* Is the parent/sibling component opened?
*/
isOpen: boolean;
/**
* Function to trigger when you still want to close the app
*/
accept: () => void;
/**
* Function to trigger when cancelling app close
*/
cancel?: () => void;
}) {
const { l10n } = useLocalization();
return (
<BaseModal isOpen={isOpen} onRequestClose={cancel} closeable={false}>
<div className="flex flex-col gap-3">
<>
<div className="flex flex-col items-center gap-3 fill-accent-background-20">
<div className="flex flex-col items-center gap-2 max-w-[512px]">
<Typography variant="main-title">
{l10n.getString('error_collection_modal-title')}
</Typography>
<Localized
id={'error_collection_modal-description_v2'}
elems={{
b: <b />,
h1: <span className="text-lg font-bold" />,
}}
>
<Typography
variant="standard"
whitespace="whitespace-pre-line"
/>
</Localized>
</div>
</div>
<Button variant="primary" onClick={accept}>
{l10n.getString('error_collection_modal-confirm')}
</Button>
<Button variant="tertiary" onClick={cancel}>
{l10n.getString('error_collection_modal-cancel')}
</Button>
</>
</div>
</BaseModal>
);
}
+2 -1
View File
@@ -14,7 +14,8 @@
't t t' var(--topbar-h)
'n b s' var(--toolbar-h)
'n c s' calc(100% - var(--topbar-h) - var(--toolbar-h))
/ var(--navbar-w) calc(100% - var(--navbar-w) - var(--right-section-w)) var(--right-section-w);
/ var(--navbar-w) calc(100% - var(--navbar-w) - var(--right-section-w))
var(--right-section-w);
}
@screen nsm {
+1 -6
View File
@@ -22,7 +22,6 @@ import { GearIcon } from './commons/icon/GearIcon';
import { TrackersStillOnModal } from './TrackersStillOnModal';
import { useConfig } from '@/hooks/config';
import { TrayOrExitModal } from './TrayOrExitModal';
import { ErrorConsentModal } from './ErrorConsentModal';
import { useAtomValue } from 'jotai';
import { connectedIMUTrackersAtom } from '@/store/app-store';
import { useElectron } from '@/hooks/electron';
@@ -72,6 +71,7 @@ export function TopBar({
await saveConfig();
electron.api.close();
};
const tryCloseApp = async (dontTray = false) => {
if (!electron.isElectron) throw 'no electron';
@@ -286,11 +286,6 @@ export function TopBar({
setConnectedTrackerWarning(false);
}}
/>
<ErrorConsentModal
isOpen={config?.errorTracking === null}
accept={() => setConfig({ errorTracking: true })}
cancel={() => setConfig({ errorTracking: false })}
/>
</>
);
}
@@ -0,0 +1,60 @@
import { useState } from 'react';
import { BaseModal } from './BaseModal';
import { Button, ButtonProps } from './Button';
export type ButtonConfirmModal = Omit<ButtonProps, 'onClick' | 'to'> & {
onConfirm: () => void;
onCancel: (reason: 'cancel' | 'backdrop') => void;
confirmLabel: string;
cancelLabel: string;
};
export function ButtonConfirmModal(props: ButtonConfirmModal) {
const {
onConfirm,
onCancel,
cancelLabel,
confirmLabel,
children,
...buttonProps
} = props;
const [isOpen, setOpen] = useState(false);
return (
<>
<BaseModal
isOpen={isOpen}
onRequestClose={() => {
setOpen(false);
onCancel('backdrop');
}}
appendClasses="w-full max-w-2xl"
>
<div className="flex flex-col justify-between gap-4">
{children}
<div className="flex w-full justify-between gap-2 xs:flex-row flex-col">
<Button
id={cancelLabel}
variant="tertiary"
onClick={() => {
setOpen(false);
onCancel('cancel');
}}
/>
<Button
id={confirmLabel}
variant="primary"
onClick={() => {
setOpen(false);
onConfirm();
}}
/>
</div>
</div>
</BaseModal>
<Button {...buttonProps} onClick={() => setOpen(true)} />
</>
);
}
+4 -4
View File
@@ -1,6 +1,6 @@
import classNames from 'classnames';
import { forwardRef, useMemo } from 'react';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export const CHECKBOX_CLASSES = classNames(
'bg-background-50 border-background-50 cursor-pointer rounded-md w-5 h-5 text-accent-background-30 focus:border-accent-background-40 focus:ring-transparent focus:ring-offset-transparent focus:outline-transparent'
@@ -112,7 +112,7 @@ export const CheckboxInternal = forwardRef<
);
});
export function CheckBox({
export function CheckBox<T extends FieldValues = FieldValues>({
label,
variant = 'checkbox',
color = 'primary',
@@ -123,8 +123,8 @@ export function CheckBox({
disabled,
}: {
label: string;
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
variant?: 'checkbox' | 'toggle';
color?: 'primary' | 'secondary' | 'tertiary';
outlined?: boolean;
+6 -3
View File
@@ -10,6 +10,8 @@ import {
import {
Control,
FieldError,
FieldPath,
FieldValues,
useController,
UseControllerProps,
} from 'react-hook-form';
@@ -415,14 +417,15 @@ export function DropdownInside({
);
}
export function Dropdown({
export function Dropdown<T extends FieldValues = FieldValues>({
control,
name,
rules,
...props
}: DropdownProps & {
control: Control<any>;
rules?: UseControllerProps<any>['rules'];
control: Control<T>;
name: FieldPath<T>;
rules?: UseControllerProps<T, FieldPath<T>>['rules'];
}) {
const {
field: { value, onChange },
+12 -5
View File
@@ -7,7 +7,13 @@ import {
useRef,
useState,
} from 'react';
import { Control, Controller, UseControllerProps } from 'react-hook-form';
import {
Control,
Controller,
FieldPath,
FieldValues,
UseControllerProps,
} from 'react-hook-form';
import { FileIcon } from './icon/FileIcon';
import { UploadFileIcon } from './icon/UploadFileIcon';
import { Typography } from './Typography';
@@ -193,7 +199,7 @@ export const FileInputInside = forwardRef<
);
});
export const FileInput = ({
export const FileInput = <T extends FieldValues = FieldValues>({
control,
name,
label,
@@ -204,8 +210,9 @@ export const FileInput = ({
capture,
importedFileName,
}: {
rules: UseControllerProps<any>['rules'];
control: Control<any>;
rules: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
name: FieldPath<T>;
accept: string;
multiple?: boolean;
capture?: boolean | 'user' | 'environment';
@@ -214,7 +221,7 @@ export const FileInput = ({
**/
label?: string;
importedFileName: string | null;
} & InputProps &
} & Omit<InputProps, 'name'> &
Partial<HTMLInputElement>) => {
return (
<Controller
+7 -4
View File
@@ -4,6 +4,8 @@ import {
Control,
Controller,
FieldError,
FieldPath,
FieldValues,
UseControllerProps,
} from 'react-hook-form';
import { EyeIcon } from './icon/EyeIcon';
@@ -117,7 +119,7 @@ export const InputInside = forwardRef<
);
});
export const Input = ({
export const Input = <T extends FieldValues = FieldValues>({
type = 'text',
control,
name,
@@ -128,10 +130,11 @@ export const Input = ({
variant = 'primary',
rules,
}: {
rules?: UseControllerProps<any>['rules'];
control: Control<any>;
rules?: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
name: FieldPath<T>;
autocomplete?: boolean | string;
} & InputProps &
} & Omit<InputProps, 'name'> &
Partial<React.HTMLProps<HTMLInputElement>>) => {
return (
<Controller
@@ -1,10 +1,10 @@
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import { Button } from './Button';
import { Typography } from './Typography';
import { useCallback, useMemo } from 'react';
import { useLocaleConfig } from '@/i18n/config';
export function NumberSelector({
export function NumberSelector<T extends FieldValues = FieldValues>({
label,
valueLabelFormat,
control,
@@ -18,8 +18,8 @@ export function NumberSelector({
}: {
label?: string;
valueLabelFormat?: (value: number) => string;
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
min: number;
max: number;
step: number | ((value: number, add: boolean) => number);
+4 -4
View File
@@ -1,9 +1,9 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import { Typography } from './Typography';
import { ReactNode } from 'react';
export function Radio({
export function Radio<T extends FieldValues = FieldValues>({
control,
name,
label,
@@ -14,8 +14,8 @@ export function Radio({
disabled,
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
label?: string;
value: string;
description?: string | null;
+4 -4
View File
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export function Range({
export function Range<T extends FieldValues = FieldValues>({
control,
name,
values,
@@ -11,8 +11,8 @@ export function Range({
// input props
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
max: number;
min: number;
step: number;
@@ -1,6 +1,8 @@
import {
Control,
Controller,
FieldPath,
FieldValues,
RefCallBack,
UseControllerProps,
} from 'react-hook-form';
@@ -48,20 +50,20 @@ export function InnerSystemFileInput({
);
}
export function SystemFileInput({
export function SystemFileInput<T extends FieldValues = FieldValues>({
control,
rules,
name,
label,
directory = false,
}: {
rules: UseControllerProps<any>['rules'];
control: Control<any>;
rules: UseControllerProps<T, FieldPath<T>>['rules'];
control: Control<T>;
/**
* Use a translation key!
**/
label: string;
name: string;
name: FieldPath<T>;
directory?: boolean;
disabled?: boolean;
}) {
+4 -4
View File
@@ -1,7 +1,7 @@
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
export function ThemeSelector({
export function ThemeSelector<T extends FieldValues = FieldValues>({
control,
name,
value,
@@ -10,8 +10,8 @@ export function ThemeSelector({
colors,
...props
}: {
control: Control<any>;
name: string;
control: Control<T>;
name: FieldPath<T>;
colors: string | undefined;
value: string;
} & React.HTMLProps<HTMLInputElement>) {
@@ -60,15 +60,15 @@ export function BatteryIcon({
/>
</mask>
<g mask="url(#mask0_4_39)" className={classNames(col, 'opacity-100')}>
<rect width={charging ? 18 : value * 18} height="9" />
<rect width={charging ? 18 : value > 2 ? 0 : value * 18} height="9" />
</g>
{charging && value <= 1 && (
{charging && (value <= 1 || value > 2) && (
<path
d="M 7.7638355,8.4189633 8.0112251,4.9834646 5.7712838,4.9834645 8.5644084,0.07977871 8.3170195,3.5152773 H 10.55696 Z"
fill="#081e30"
/>
)}
{charging && value > 1 && (
{charging && value > 1 && value <= 2 && (
<path
d="M 5.5342464,4.6225095 C 6.1777799,5.0106205 6.6131537,5.2516456 7.5253371,6.545223 8.4340868,4.4016445 8.7809738,3.661475 10.605195,1.5520288"
fill="none"
@@ -1,10 +1,19 @@
export function HeadsetIcon({ width = 24 }: { width?: number }) {
export function HeadsetIcon({
width = 24,
disabled = false,
}: {
width?: number;
disabled?: boolean;
}) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={width} viewBox="0 0 640 512">
<path
transform="scale(0.75, 0.75) translate(120, 96)"
d="M576 64H64C28.7 64 0 92.7 0 128v256c0 35.3 28.7 64 64 64h120.4c24.2 0 46.4-13.7 57.2-35.4l32-64c8.8-17.5 26.7-28.6 46.3-28.6s37.5 11.1 46.3 28.6l32 64c10.8 21.7 33 35.4 57.2 35.4H576c35.3 0 64-28.7 64-64V128c0-35.3-28.7-64-64-64zM96 240a64 64 0 11128 0 64 64 0 11-128 0zm384-64a64 64 0 110 128 64 64 0 110-128z"
/>
{disabled && (
<line x1="20" y1="20" x2="620" y2="492" stroke="red" strokeWidth="30" />
)}
</svg>
);
}
@@ -0,0 +1,12 @@
export function SittingIcon({ size = 24 }: { size?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
>
<path d="M600-160H320q-33 0-56.5-23.5T240-240v-440h80v440h280v80ZM460-720q-33 0-56.5-23.5T380-800q0-33 23.5-56.5T460-880q33 0 56.5 23.5T540-800q0 33-23.5 56.5T460-720ZM640-80v-200H440q-33 0-56.5-23.5T360-360v-220q0-42 29-71t71-29q42 0 71 29t29 71v180h80q33 0 56.5 23.5T720-320v240h-80Z" />
</svg>
);
}
@@ -1,9 +1,9 @@
export function SteamIcon() {
export function SteamIcon({ size = 20 }) {
return (
<svg
width="20"
height="18"
viewBox="0 0 20 18"
width={size}
height={size}
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M17.6562 5.32031C17.6562 6.10938 17.3903 6.7832 16.8583 7.3418C16.3263 7.90039 15.6845 8.17969 14.933 8.17969C14.1815 8.17969 13.5398 7.90039 13.0078 7.3418C12.4758 6.7832 12.2098 6.10938 12.2098 5.32031C12.2098 4.53125 12.4758 3.85742 13.0078 3.29883C13.5398 2.74023 14.1815 2.46094 14.933 2.46094C15.6845 2.46094 16.3263 2.74023 16.8583 3.29883C17.3903 3.85742 17.6562 4.53125 17.6562 5.32031ZM9.0625 14.0156C9.0625 13.2031 8.79092 12.5117 8.24777 11.9414C7.70461 11.3711 7.04613 11.0859 6.27232 11.0859C6.07143 11.0859 5.87054 11.1094 5.66964 11.1562L6.83036 11.6484C7.40327 11.8906 7.81064 12.3066 8.05246 12.8965C8.29427 13.4863 8.29985 14.0781 8.0692 14.6719C7.83854 15.2734 7.44048 15.6992 6.875 15.9492C6.30952 16.1992 5.74405 16.2031 5.17857 15.9609C5.02232 15.8984 4.79167 15.8027 4.48661 15.6738C4.18155 15.5449 3.95461 15.4492 3.8058 15.3867C4.0439 15.8555 4.38244 16.2324 4.82143 16.5176C5.26042 16.8027 5.74405 16.9453 6.27232 16.9453C7.04613 16.9453 7.70461 16.6602 8.24777 16.0898C8.79092 15.5195 9.0625 14.8281 9.0625 14.0156ZM18.3259 5.33203C18.3259 4.34766 17.9929 3.50586 17.327 2.80664C16.6611 2.10742 15.8594 1.75781 14.9219 1.75781C13.9769 1.75781 13.1715 2.10742 12.5056 2.80664C11.8397 3.50586 11.5067 4.34766 11.5067 5.33203C11.5067 6.32422 11.8397 7.16797 12.5056 7.86328C13.1715 8.55859 13.9769 8.90625 14.9219 8.90625C15.8594 8.90625 16.6611 8.55859 17.327 7.86328C17.9929 7.16797 18.3259 6.32422 18.3259 5.33203ZM20 5.33203C20 6.80859 19.5033 8.06641 18.51 9.10547C17.5167 10.1445 16.3207 10.6641 14.9219 10.6641L10.0446 14.4023C9.95536 15.4102 9.54985 16.2617 8.82812 16.957C8.1064 17.6523 7.25446 18 6.27232 18C5.37202 18 4.57589 17.7031 3.88393 17.1094C3.19196 16.5156 2.75298 15.7656 2.56696 14.8594L0 13.7812V8.75391L4.34152 10.5938C4.92932 10.2188 5.57292 10.0312 6.27232 10.0312C6.36905 10.0312 6.49926 10.0391 6.66295 10.0547L9.83259 5.28516C9.84747 3.82422 10.3516 2.57812 11.3449 1.54688C12.3382 0.515625 13.5305 0 14.9219 0C16.3207 0 17.5167 0.521484 18.51 1.56445C19.5033 2.60742 20 3.86328 20 5.33203Z" />
@@ -7,7 +7,7 @@ import {
} from '@/hooks/firmware-tool';
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { Control, Controller } from 'react-hook-form';
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
import {
FirmwareUpdateStatus,
TrackerStatus as TrackerStatusEnum,
@@ -22,9 +22,9 @@ interface DeviceCardProps {
color?: string;
}
interface DeviceCardControlProps {
control?: Control<any>;
name?: string;
interface DeviceCardControlProps<T extends FieldValues = FieldValues> {
control?: Control<T>;
name?: FieldPath<T>;
progress?: number;
disabled?: boolean;
}
@@ -55,7 +55,7 @@ export function DeviceCardContent({ deviceNames, status }: DeviceCardProps) {
);
}
export function DeviceCardControl({
export function DeviceCardControl<T extends FieldValues = FieldValues>({
control,
name,
progress,
@@ -63,7 +63,7 @@ export function DeviceCardControl({
online = null,
color = 'bg-background-60',
...props
}: DeviceCardControlProps & DeviceCardProps) {
}: DeviceCardControlProps<T> & DeviceCardProps) {
const cardborder = useMemo(() => {
if (!props.status) return 'border-transparent';
@@ -36,7 +36,7 @@ export function FlashingStep({
const { l10n } = useLocalization();
const { selectedDevices, selectDevices, files, selectedDefault } =
useFirmwareTool();
const { state: onboardingState } = useOnboarding();
const { state: onboardingState, state } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [status, setStatus] = useState<{
[key: string]: {
@@ -203,15 +203,28 @@ export function FlashingStep({
onClick={() => goTo('FlashingMethod')}
/>
</Localized>
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
{state.alonePage && (
<Localized id="firmware_tool-flashing_step-exit">
<Button
variant="primary"
onClick={() => {
clear();
nav('/');
}}
/>
</Localized>
)}
{!state.alonePage && (
<Localized id="firmware_tool-flashing_step-onboarding_continue">
<Button
variant="primary"
onClick={() => {
clear();
nav('/onboarding/trackers-assign');
}}
/>
</Localized>
)}
</div>
</div>
</div>
@@ -10,6 +10,7 @@ import {
} from '@/firmware-tool-api/firmwareToolComponents';
import { useEffect, useMemo, useState } from 'react';
import { useSafeLocalization } from '@/i18n/config';
import semver from 'semver';
function Selector({
text,
@@ -142,16 +143,33 @@ export function SelectSourceSetep({
!source.availableBoards.includes(partialBoard.board) ||
source.source !== partialBoard.source,
name: source.version,
isBranch: source.branch == source.version,
});
return curr;
},
[] as { name: string; disabled: boolean; isBranch: boolean }[]
[] as { name: string; disabled: boolean }[]
)
.sort((a, b) => {
if (a.isBranch !== b.isBranch) return a.isBranch ? 1 : -1;
return a.name.localeCompare(b.name);
// safeguard against inf loop
if (a == b) return 0;
const versionA = semver.valid(a.name);
const versionB = semver.valid(b.name);
// if both are not valid versions:
// if one is main, push that higher
// otherwise, push up the one which is alphabetically sooner
if (versionA == null && versionB == null) {
if (a.name == 'main') return -1;
return a.name.localeCompare(b.name);
}
// if one isn't valid, push the one that's valid up
if ((versionA == null) != (versionB == null))
return versionA == null ? 1 : -1;
// if A is lower, push B up
return semver.lt(versionA!, versionB!) ? 1 : -1;
}),
};
}, [sources, partialBoard]);
@@ -58,7 +58,7 @@ const DeviceList = ({
control,
devices,
}: {
control: Control<any>;
control: Control<FirmwareUpdateForm>;
devices: DeviceDataT[];
}) => {
const { l10n } = useLocalization();
@@ -0,0 +1,113 @@
import { useState, useEffect } from 'react';
import { Button } from '@/components/commons/Button';
import { BaseModal } from '@/components/commons/BaseModal';
import { CheckboxInternal } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { useElectron } from '@/hooks/electron';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { RpcMessage, InstalledInfoResponseT } from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useLocalization } from '@fluent/react';
export function UdevRulesModal() {
const { config, setConfig } = useConfig();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const electron = useElectron();
const [udevContent, setUdevContent] = useState('');
const [isUdevInstalledResponse, setIsUdevInstalledResponse] = useState(true);
const [showUdevWarning, setShowUdevWarning] = useState(false);
const [dontShowThisSession, setDontShowThisSession] = useState(false);
const [dontShowAgain, setDontShowAgain] = useState(false);
const { l10n } = useLocalization();
const handleUdevContent = async () => {
if (electron.isElectron) {
const dir = await electron.api.getInstallDir();
const rulesPath = `${dir}/69-slimevr-devices.rules`;
setUdevContent(
`cat ${rulesPath} | sudo sh -c 'tee /etc/udev/rules.d/69-slimevr-devices.rules >/dev/null && udevadm control --reload-rules && udevadm trigger'`
);
}
};
useEffect(() => {
handleUdevContent();
}, []);
useEffect(() => {
if (!config) throw 'Invalid state!';
if (electron.isElectron) {
const isLinux = electron.data().os.type === 'linux';
const udevMissing = !isUdevInstalledResponse;
const notHiddenGlobally = !config.dontShowUdevModal;
const notHiddenThisSession = !dontShowThisSession;
const shouldShow =
isLinux && udevMissing && notHiddenGlobally && notHiddenThisSession;
setShowUdevWarning(shouldShow);
}
}, [config, isUdevInstalledResponse, dontShowThisSession]);
useEffect(() => {
sendRPCPacket(
RpcMessage.InstalledInfoRequest,
new InstalledInfoResponseT()
);
}, []);
useRPCPacket(
RpcMessage.InstalledInfoResponse,
({ isUdevInstalled }: InstalledInfoResponseT) => {
setIsUdevInstalledResponse(isUdevInstalled);
}
);
const handleModalClose = () => {
if (!config) throw 'Invalid State!';
setConfig({ dontShowUdevModal: dontShowAgain });
setDontShowThisSession(true);
};
const copyToClipboard = () => {
navigator.clipboard.writeText(udevContent);
};
return (
<BaseModal isOpen={showUdevWarning} appendClasses={'w-full max-w-2xl'}>
<div className="flex w-full h-full flex-col gap-4">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="install-info_udev-rules_modal_title"
/>
<Typography id="install-info_udev-rules_warning" />
</div>
<div className="relative w-full max-w-2xl">
<div className="absolute right-2 top-2">
<Button variant="secondary" onClick={copyToClipboard}>
Copy
</Button>
</div>
<div className="bg-background-80 rounded-lg overflow-auto p-2 w-full h-[300px]">
<pre className="text-wrap">{udevContent}</pre>
</div>
</div>
</div>
<div className="flex justify-between gap-2">
<CheckboxInternal
label={l10n.getString(
'install-info_udev-rules_modal-dont-show-again_checkbox'
)}
name="dismiss-udev-rules-checkbox"
onChange={(e) => setDontShowAgain(e.currentTarget.checked)}
/>
<Button
variant="primary"
onClick={handleModalClose}
id="install-info_udev-rules_modal_button"
/>
</div>
</div>
</BaseModal>
);
}
@@ -12,9 +12,9 @@
grid-template:
's t' var(--connect-tracker-layout-top)
's c' calc(100% - var(--connect-tracker-layout-top))
/ calc(var(--connect-tracker-layout-sidebar)) calc(100% - var(
--connect-tracker-layout-sidebar
));
/ calc(var(--connect-tracker-layout-sidebar)) calc(
100% - var(--connect-tracker-layout-sidebar)
);
@screen mobile {
grid-template:
@@ -26,6 +26,7 @@ import { connectedIMUTrackersAtom } from '@/store/app-store';
import { BaseModal } from '@/components/commons/BaseModal';
import { A } from '@/components/commons/A';
import { useTrackingChecklist } from '@/hooks/tracking-checklist';
import { MoreSetsConfirm } from './quiz/MoreSetsConfirm';
const statusLabelMap = {
[WifiProvisioningStatus.NONE]:
@@ -317,13 +318,15 @@ export function ConnectTrackersPage() {
? l10n.getString('onboarding-connect_tracker-back')
: l10n.getString('onboarding-previous_step')}
</Button>
<Button
variant="primary"
to={state.alonePage ? '/' : '/onboarding/trackers-assign'}
className="ml-auto"
>
{l10n.getString('onboarding-connect_tracker-next')}
</Button>
{state.alonePage && (
<Button
variant="primary"
to={'/'}
className="ml-auto"
id="onboarding-connect_tracker-next"
/>
)}
{!state.alonePage && <MoreSetsConfirm />}
</div>
</div>
<div style={{ gridArea: 't' }} className="flex items-center px-5 pt-5">
@@ -0,0 +1,57 @@
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { Button } from '@/components/commons/Button';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { WarningBox } from '@/components/commons/TipBox';
import { MoreSetsConfirm } from './quiz/MoreSetsConfirm';
export function DongleSectionContent() {
const { state } = useOnboarding();
return (
<div className="flex flex-col gap-2">
<div className="flex gap-2 items-center">
<div className="bg-accent-background-30 rounded-full p-2 fill-background-10">
<USBIcon size={24} />
</div>
<Typography
variant="main-title"
id="onboarding-wifi_creds-dongle-title"
/>
</div>
<div className={classNames('flex flex-col gap-2 flex-grow p-2')}>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-wifi_creds-dongle-description"
/>
<Localized id="onboarding-wifi_creds-dongle-wip">
<WarningBox whitespace>WARNING</WarningBox>
</Localized>
</div>
<div className="flex px-2 p-6">
{state.alonePage && (
<Button
variant="primary"
to={'/'}
id="onboarding-wifi_creds-dongle-continue"
/>
)}
{!state.alonePage && <MoreSetsConfirm />}
</div>
</div>
);
}
export function DonglePage() {
const { applyProgress } = useOnboarding();
applyProgress(0.5);
return (
<div className="flex flex-col w-full h-full xs:justify-center items-center">
<DongleSectionContent />
</div>
);
}
@@ -0,0 +1,49 @@
import { Localized } from '@fluent/react';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { useConfig } from '@/hooks/config';
export function ErrorCollectingConsentPage() {
const { setConfig } = useConfig();
const accept = () => {
setConfig({ errorTracking: true });
};
const cancel = () => {
setConfig({ errorTracking: false });
};
return (
<div className="flex items-center justify-center h-full flex-col gap-3 p-4">
<div className="max-w-2xl flex flex-col gap-4">
<div className="flex flex-col w-full gap-4">
<Typography variant="main-title" id="error_collection_modal-title" />
<Localized
id="error_collection_modal-description_v2"
elems={{
b: <b />,
h1: <span className="text-md font-bold" />,
}}
>
<Typography variant="standard" whitespace="whitespace-pre-line" />
</Localized>
</div>
<div className="flex flex-row gap-2 justify-between">
<Button
variant="tertiary"
to="/onboarding/wifi-creds"
onClick={cancel}
id="error_collection_modal-cancel"
/>
<Button
variant="primary"
to="/onboarding/wifi-creds"
onClick={accept}
id="error_collection_modal-confirm"
/>
</div>
</div>
</div>
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ export function HomePage() {
<Typography variant="mobile-title">
{l10n.getString('onboarding-home')}
</Typography>
<Button variant="primary" to="/onboarding/wifi-creds">
<Button variant="primary" to="/onboarding/quiz/slime-set">
{l10n.getString('onboarding-home-start')}
</Button>
</div>
@@ -1,16 +1,14 @@
import { Localized, useLocalization } from '@fluent/react';
import { Localized } from '@fluent/react';
import { useOnboarding } from '@/hooks/onboarding';
import { useWifiForm } from '@/hooks/wifi-form';
import { Button } from '@/components/commons/Button';
import { Input } from '@/components/commons/Input';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { WifiIcon } from '@/components/commons/icon/WifiIcon';
import { WarningBox } from '@/components/commons/TipBox';
import { DongleSectionContent } from './Dongle';
export function WifiCredsPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
const { control, handleSubmit, submitWifiCreds, formState } = useWifiForm();
@@ -18,34 +16,12 @@ export function WifiCredsPage() {
return (
<div className="flex flex-col w-full h-full xs:justify-center items-center">
<div className="grid xs:grid-cols-2 gap-4 max-w-6xl p-4">
<div className="flex flex-col gap-2">
<div className="flex gap-2 items-center">
<div className="bg-accent-background-30 rounded-full p-2 fill-background-10">
<USBIcon size={24} />
</div>
<Typography
variant="main-title"
id="onboarding-wifi_creds-dongle-title"
/>
</div>
<div className={classNames('flex flex-col gap-2 flex-grow p-2')}>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-wifi_creds-dongle-description"
/>
<Localized id="onboarding-wifi_creds-dongle-wip">
<WarningBox whitespace>WARNING</WarningBox>
</Localized>
</div>
<div className="flex px-2 p-6">
<Button
variant="primary"
to={state.alonePage ? '/' : '/onboarding/trackers-assign'}
id="onboarding-wifi_creds-dongle-continue"
/>
</div>
</div>
<div
className={classNames('grid gap-4 max-w-6xl p-4', {
'xs:grid-cols-2': state.alonePage,
})}
>
{state.alonePage && <DongleSectionContent />}
<form
className="flex flex-col gap-2"
onSubmit={handleSubmit(submitWifiCreds)}
@@ -105,21 +81,22 @@ export function WifiCredsPage() {
/>
</Localized>
<div className="flex flex-row gap-3 justify-between">
<Button
variant="secondary"
className={state.alonePage ? 'opacity-0' : ''}
state={{ alonePage: state.alonePage }}
to={'/onboarding/trackers-assign'}
>
{l10n.getString('onboarding-wifi_creds-skip')}
</Button>
{!state.alonePage ? (
<Button
variant="secondary"
state={{ alonePage: state.alonePage }}
to={'/onboarding/quiz/slime-set'}
id="onboarding-wifi_creds-back-v2"
/>
) : (
<div />
)}
<Button
type="submit"
variant="primary"
disabled={!formState.isValid}
>
{l10n.getString('onboarding-wifi_creds-submit')}
</Button>
id="onboarding-wifi_creds-submit"
/>
</div>
</div>
</div>
@@ -185,6 +185,10 @@ function ImportExportButtons() {
parseConfigImport(config).forEach((req) =>
sendRPCPacket(RpcMessage.ChangeSkeletonConfigRequest, req)
);
sendRPCPacket(
RpcMessage.SkeletonConfigRequest,
new SkeletonConfigRequestT()
);
setImportState(ImportStatus.SUCCESS);
setTimeout(() => {
setImportState(ImportStatus.OK);
@@ -478,7 +478,7 @@ export function ScaledProportionsPage() {
<Button
variant="primary"
id="onboarding-user_height-next_step"
to="/"
to="/onboarding/quiz/usage"
/>
)}
</div>
@@ -23,7 +23,7 @@ export function AutomaticMountingPage() {
const { l10n } = useLocalization();
const { applyProgress, state } = useOnboarding();
applyProgress(0.7);
applyProgress(0.6);
return (
<>
@@ -28,7 +28,7 @@ export function ManualMountingPage() {
const [selectedRole, setSelectRole] = useState<BodyPart>(BodyPart.NONE);
applyProgress(0.7);
applyProgress(0.6);
const assignedTrackers = useAtomValue(assignedTrackersAtom);
@@ -13,7 +13,7 @@ export function MountingChoose() {
const [animated, setAnimated] = useState(false);
const [showWarning, setShowWarning] = useState(false);
applyProgress(0.65);
applyProgress(0.55);
return (
<>
@@ -0,0 +1,155 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useState } from 'react';
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
import { VMCFileUpload } from '@/components/settings/pages/VMCSettings';
import { QuizButton } from './SlimeSetQuestion';
export function QuizMocapPosQuestion() {
const { applyProgress, setMocapPos, mocapPos, playspace, setPlayspace } =
useOnboarding();
const [headTracker, setHeadTracker] = useState(true);
applyProgress(0.9);
const canContinue = (!headTracker || mocapPos) && playspace;
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-mocap_preferences-title"
/>
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-mocap_preferences-desc"
/>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={headTracker}
onClick={() => setHeadTracker(true)}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-mocap_preferences-head_tracker-yes"
/>
<QuizButton
active={!headTracker}
onClick={() => {
setHeadTracker(false);
setMocapPos(undefined);
}}
icon={<HeadsetIcon width={50} disabled />}
name="onboarding-quiz-mocap_preferences-head_tracker-no"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-vrm_model-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-vrm_model-desc" />
</div>
<VMCFileUpload />
</div>
</div>
{headTracker && (
<>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-playspace-title"
/>
<Typography id="onboarding-quiz-mocap_preferences-playspace-desc" />
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={playspace === 'sitting'}
onClick={() => setPlayspace('sitting')}
icon={<SittingIcon size={50} />}
name="onboarding-quiz-mocap_preferences-playspace-sitting"
/>
<QuizButton
active={playspace === 'standing'}
onClick={() => setPlayspace('standing')}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-mocap_preferences-playspace-standing"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="flex flex-col gap-2">
<Typography
variant="section-title"
id="onboarding-quiz-mocap_preferences-head_tracker_location-title"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={mocapPos === 'forehead'}
onClick={() => setMocapPos('forehead')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_forehead.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-forehead"
/>
<QuizButton
active={mocapPos === 'face'}
onClick={() => setMocapPos('face')}
icon={
<img
src="/images/quiz/quiz_mocap-pos_face.webp"
className="w-44"
/>
}
name="onboarding-quiz-mocap_preferences-head_tracker_location-face"
/>
</div>
</div>
</div>
</>
)}
<div className="flex justify-between pb-4">
<Button
variant="secondary"
id="onboarding-quiz_back"
to="/onboarding/quiz/usage"
/>
<Button
variant="primary"
id="onboarding-quiz_continue"
disabled={!canContinue}
to="/"
/>
</div>
</div>
</div>
);
}
@@ -0,0 +1,30 @@
import { ButtonConfirmModal } from '@/components/commons/ButtonConfirmModal';
import { Typography } from '@/components/commons/Typography';
import { useNavigate } from 'react-router-dom';
export function MoreSetsConfirm() {
const navigate = useNavigate();
return (
<ButtonConfirmModal
variant="primary"
className="ml-auto"
id="onboarding-connect_tracker-next"
cancelLabel="onboarding-quiz-more_sets_modal-cancel"
confirmLabel="onboarding-quiz-more_sets_modal-confirm"
onConfirm={() => navigate('/onboarding/trackers-assign')}
onCancel={(reason) => {
if (reason === 'cancel') navigate('/onboarding/quiz/slime-set');
}}
>
<Typography
variant="main-title"
id="onboarding-quiz-more_sets_modal-title"
/>
<Typography
variant="vr-accessible"
id="onboarding-quiz-more_sets_modal-desc"
/>
</ButtonConfirmModal>
);
}
@@ -0,0 +1,55 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { QuizButton } from './SlimeSetQuestion';
import { SteamIcon } from '@/components/commons/icon/SteamIcon';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { useNavigate } from 'react-router-dom';
import { Button } from '@/components/commons/Button';
export function QuizRuntimeQuestion() {
const { applyProgress, setVrcOSC, vrcOsc } = useOnboarding();
const nav = useNavigate();
applyProgress(0.9);
const next = (type: typeof vrcOsc) => {
setVrcOSC(type);
nav('/');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-runtime-title" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={!vrcOsc}
onClick={() => next(false)}
icon={<SteamIcon size={50} />}
name="onboarding-quiz-runtime-answer-steamvr"
/>
<QuizButton
active={vrcOsc}
onClick={() => next(true)}
icon={<HeadsetIcon width={80} />}
name="onboarding-quiz-runtime-answer-standalone"
/>
</div>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/usage'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -0,0 +1,136 @@
import { useOnboarding } from '@/hooks/onboarding';
import { ReactNode } from 'react';
import { Typography } from '@/components/commons/Typography';
import classNames from 'classnames';
import { USBIcon } from '@/components/commons/icon/UsbIcon';
import { useNavigate } from 'react-router-dom';
export function QuizButton({
name,
active,
icon,
onClick,
}: {
active?: boolean;
name: string;
icon: ReactNode;
onClick: () => void;
}) {
return (
<div
onClick={onClick}
className={classNames(
'flex rounded-lg bg-background-60 hover:bg-background-50 cursor-pointer',
'p-4 outline outline-2 flex-col gap-4 items-center justify-between fill-background-20',
{
'outline-accent-background-30': active,
'outline-transparent': !active,
}
)}
>
{icon}
<Typography id={name} variant="section-title" />
</div>
);
}
export function QuizSlimeSetQuestion() {
const { applyProgress, setSlimeSet, slimeSet } = useOnboarding();
const nav = useNavigate();
applyProgress(0.2);
const next = (type: typeof slimeSet) => {
setSlimeSet(type);
switch (type) {
case 'butterfly':
case 'dongle-slime':
nav('/onboarding/dongle');
break;
case 'slime-v1':
case 'wifi-slime':
nav('/onboarding/wifi-creds');
break;
}
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography
variant="main-title"
id="onboarding-quiz-slimeset-title"
/>
<Typography id="onboarding-quiz-slimeset-description" />
</div>
<div className="flex flex-col gap-6">
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-official-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={slimeSet === 'slime-v1'}
onClick={() => next('slime-v1')}
icon={
<img
src="/images/trackers/v1_2_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-regular"
/>
<QuizButton
active={slimeSet === 'butterfly'}
onClick={() => next('butterfly')}
icon={
<img
src="/images/trackers/butterfly_slime.webp"
className="w-60"
/>
}
name="onboarding-quiz-slimeset-answer-butterfly"
/>
</div>
</div>
<div className="flex gap-2 flex-col">
<Typography
variant="section-title"
id="onboarding-quiz-slimeset-thirdparty-sets"
/>
<div className="grid grid-cols-2 gap-4">
<QuizButton
onClick={() => next('wifi-slime')}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
height="50"
viewBox="0 0 24 24"
width="50"
className="fill-background-20"
>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z" />
</svg>
}
name="onboarding-quiz-slimeset-answer-wifi"
/>
<QuizButton
onClick={() => next('dongle-slime')}
icon={
<div className="fill-background-20">
<USBIcon size={50} />
</div>
}
name="onboarding-quiz-slimeset-answer-dongle"
/>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,62 @@
import { useOnboarding } from '@/hooks/onboarding';
import { Typography } from '@/components/commons/Typography';
import { Button } from '@/components/commons/Button';
import { QuizButton } from './SlimeSetQuestion';
import { useNavigate } from 'react-router-dom';
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
import { HumanIcon } from '@/components/commons/icon/HumanIcon';
export function QuizUsageQuestion() {
const { applyProgress, setUsage, usage } = useOnboarding();
const nav = useNavigate();
applyProgress(0.8);
const next = (type: typeof usage) => {
setUsage(type);
if (type === 'vr-gaming') {
if (window.__ANDROID__) {
nav('/');
} else {
nav('/onboarding/quiz/runtime');
}
} else nav('/onboarding/quiz/mocap-pos');
};
return (
<div className="grid w-full h-full justify-center items-center">
<div className="flex flex-col gap-8 max-w-xl p-2">
<div className="flex flex-col gap-2">
<Typography variant="main-title" id="onboarding-quiz-usage-title" />
<Typography
whitespace="whitespace-pre-wrap"
id="onboarding-quiz-usage-description"
/>
</div>
<div className="flex flex-col gap-6">
<div className="grid grid-cols-2 gap-4">
<QuizButton
active={usage === 'vr-gaming'}
icon={<HeadsetIcon width={50} />}
name="onboarding-quiz-usage-answer-VRC"
onClick={() => next('vr-gaming')}
/>
<QuizButton
active={usage === 'mocap'}
icon={<HumanIcon width={50} />}
name="onboarding-quiz-usage-answer-mocap_vtubing"
onClick={() => next('mocap')}
/>
</div>
</div>
<div className="flex">
<Button
to={'/onboarding/quiz/slime-set'}
variant="secondary"
id="onboarding-quiz_back"
/>
</div>
</div>
</div>
);
}
@@ -11,6 +11,7 @@ import { ResetType } from 'solarxr-protocol';
export function PreparationStep({
nextStep,
prevStep,
isActive,
}: VerticalStepComponentProps) {
return (
<div className="flex flex-col flex-grow justify-between py-2 gap-2">
@@ -53,7 +54,14 @@ export function PreparationStep({
<Button variant={'secondary'} onClick={prevStep} />
</Localized>
<ResetButton type={ResetType.Full} onReseted={nextStep} />
<ResetButton
type={ResetType.Full}
onReseted={() => {
if (isActive) {
nextStep();
}
}}
/>
</div>
</div>
);
@@ -10,6 +10,7 @@ import { ManualMountingPageStayAligned } from '@/components/onboarding/pages/mou
export function VerifyMountingStep({
nextStep,
prevStep,
isActive,
}: VerticalStepComponentProps) {
const { isMobile } = useBreakpoint('mobile');
const [isOpen, setOpen] = useState(false);
@@ -79,7 +80,11 @@ export function VerifyMountingStep({
onClick={() => setDisableMounting(true)}
type={ResetType.Mounting}
group="default"
onReseted={goNextStep}
onReseted={() => {
if (isActive) {
nextStep();
}
}}
onFailed={() => setDisableMounting(false)}
/>
</div>
@@ -55,7 +55,7 @@ export function TrackersAssignPage() {
const { isMd } = useBreakpoint('md');
const { l10n } = useLocalization();
const { config, setConfig } = useConfig();
const { applyProgress, state } = useOnboarding();
const { applyProgress, state, slimeSet } = useOnboarding();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const defaultValues = {
mirrorView: config?.mirrorView ?? defaultConfig.mirrorView,
@@ -329,9 +329,24 @@ export function TrackersAssignPage() {
<div className="flex flex-row">
{!state.alonePage && (
<>
<Button variant="secondary" to="/onboarding/wifi-creds">
{l10n.getString('onboarding-previous_step')}
</Button>
{state.alonePage && (
<Button variant="secondary" to="/onboarding/wifi-creds">
{l10n.getString('onboarding-previous_step')}
</Button>
)}
{!state.alonePage && (
<Button
variant="secondary"
to={
slimeSet &&
['butterfly', 'dongle-slime'].includes(slimeSet)
? '/onboarding/dongle'
: '/onboarding/wifi-creds'
}
>
{l10n.getString('onboarding-previous_step')}
</Button>
)}
<Button
variant="primary"
to="/onboarding/mounting/choose"
@@ -7,9 +7,9 @@
grid-template:
't t t' var(--topbar-h)
'n s c' calc(100% - var(--topbar-h))
/ var(--navbar-w) var(--settings-sidebar-w) calc(100% - var(--navbar-w) - var(
--settings-sidebar-w
));
/ var(--navbar-w) var(--settings-sidebar-w) calc(
100% - var(--navbar-w) - var(--settings-sidebar-w)
);
@screen lg {
--settings-sidebar-w: 270px;
@@ -43,6 +43,9 @@ import {
loadResetSettings,
ResetSettingsForm,
} from '@/hooks/reset-settings';
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
export type SettingsForm = {
trackers: {
@@ -163,7 +166,16 @@ const defaultValues: SettingsForm = {
hidSettings: { trackersOverHID: false },
};
const settingsAtom = atom(new SettingsResponseT());
const settingsValueAtom = selectAtom(
settingsAtom,
(settings) => settings,
isEqual
);
export function GeneralSettings() {
const setSettings = useSetAtom(settingsAtom);
const settings = useAtomValue(settingsValueAtom);
const { l10n } = useLocalization();
const { config } = useConfig();
const { currentLocales } = useLocaleConfig();
@@ -183,7 +195,10 @@ export function GeneralSettings() {
const { reset, control, watch, handleSubmit, getValues, setValue } =
useForm<SettingsForm>({
defaultValues,
mode: 'onChange',
reValidateMode: 'onChange',
});
const {
trackers: {
automaticTrackerToggle,
@@ -294,7 +309,9 @@ export function GeneralSettings() {
};
useEffect(() => {
const subscription = watch(() => handleSubmit(onSubmit)());
const subscription = watch((value, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
return () => subscription.unsubscribe();
}, []);
@@ -302,10 +319,7 @@ export function GeneralSettings() {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
// If null, we still haven't shown the hands warning
// if false then initially the hands warning was disabled
const [handsWarning, setHandsWarning] = useState<boolean | null>(null);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
useEffect(() => {
const formData: DefaultValues<SettingsForm> = {};
if (settings.filtering) {
@@ -408,6 +422,13 @@ export function GeneralSettings() {
}
reset({ ...getValues(), ...formData });
}, [settings]);
// If null, we still haven't shown the hands warning
// if false then initially the hands warning was disabled
const [handsWarning, setHandsWarning] = useState<boolean | null>(null);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
useEffect(() => {
@@ -421,18 +442,6 @@ export function GeneralSettings() {
}
}, [steamVrLeftHand, steamVrRightHand, handsWarning]);
// Handle scrolling to selected page
// useEffect(() => {
// const typedState: { scrollTo: string } = state as any;
// if (!pageRef.current || !typedState || !typedState.scrollTo) {
// return;
// }
// const elem = pageRef.current.querySelector(`#${typedState.scrollTo}`);
// if (elem) {
// elem.scrollIntoView({ behavior: 'smooth' });
// }
// }, [state]);
return (
<SettingsPageLayout>
<HandsWarningModal
@@ -1144,32 +1153,31 @@ export function GeneralSettings() {
/>
</div>
</div>
<div className="flex flex-col pt-2 pb-3">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-self_localization-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap3 pb5">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.selfLocalization"
label={l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
/>
</div>
</>
)}
<div className="flex flex-col pt-2 pb-3">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
</Typography>
<Typography>
{l10n.getString(
'settings-general-fk_settings-self_localization-description'
)}
</Typography>
</div>
<div className="grid sm:grid-cols-1 gap3 pb5">
<CheckBox
variant="toggle"
outlined
control={control}
name="toggles.selfLocalization"
label={l10n.getString(
'settings-general-fk_settings-self_localization-title'
)}
/>
</div>
</>
</SettingsPagePaneLayout>
@@ -14,7 +14,7 @@ import {
import { useLocalization } from '@fluent/react';
import classNames from 'classnames';
import { ReactNode, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { FieldPath, useForm } from 'react-hook-form';
import { TrackingChecklistStepId } from 'solarxr-protocol';
import * as Sentry from '@sentry/react';
@@ -82,7 +82,7 @@ export function TrackingChecklistSettings({
<div key={step.id}>
<CheckBox
control={control}
name={`steps.${step.id}`}
name={`steps.${step.id}` as FieldPath<StepsForm>}
disabled={!step.ignorable || !step.enabled}
label={l10n.getString(trackingchecklistIdtoLabel[step.id])}
outlined
+108 -41
View File
@@ -31,7 +31,6 @@ import { boolean, object } from 'yup';
interface VMCSettingsForm {
vmc: {
oscSettings: OSCSettings;
vrmJson?: FileList;
anchorHip: boolean;
mirrorTracking: boolean;
};
@@ -50,10 +49,92 @@ const defaultValues = {
},
};
export function VMCFileUpload() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { l10n } = useLocalization();
const [modelName, setModelName] = useState<string | null>(null);
const [settings, setSettings] = useState<SettingsResponseT>();
const { control, watch } = useForm<{
vrmJson?: FileList;
}>({
defaultValues: { vrmJson: undefined },
reValidateMode: 'onChange',
mode: 'onChange',
});
const vrmJson = watch('vrmJson');
const updateVRMJson = async () => {
if (!settings?.vmcOsc) return;
const req = new ChangeSettingsRequestT();
const vmcOsc = new VMCOSCSettingsT();
vmcOsc.oscSettings = Object.assign(
new OSCSettingsT(),
settings.vmcOsc.oscSettings
);
if (vrmJson !== undefined) {
if (vrmJson.length > 0) {
const file = await parseVRMFile(vrmJson[0]);
if (file) {
vmcOsc.vrmJson = file.json;
setModelName(file.name);
}
} else {
vmcOsc.vrmJson = '';
setModelName(null);
}
}
req.vmcOsc = vmcOsc;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
};
useEffect(() => {
updateVRMJson();
}, [vrmJson]);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
const vrmJson = settings.vmcOsc?.vrmJson?.toString();
if (vrmJson) {
let data: any;
try {
data = JSON.parse(vrmJson);
setModelName(getVRMName(data) || '');
} catch (e) {
error('Failed to fetch VRM name: ' + e);
}
}
});
return (
<FileInput
control={control}
name="vrmJson"
rules={{
required: false,
}}
value="help"
importedFileName={
// if modelname is an empty string, it's an untitled model
modelName === ''
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
: modelName
}
label="settings-osc-vmc-vrm-file_select"
accept="model/gltf-binary, model/gltf+json, model/vrml, .vrm, .glb, .gltf"
/>
);
}
export function VMCSettings() {
const { l10n } = useLocalization();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [modelName, setModelName] = useState<string | null>(null);
const { oscValidator } = useOscSettingsValidator();
const { reset, control, watch, handleSubmit } = useForm<VMCSettingsForm>({
@@ -81,18 +162,6 @@ export function VMCSettings() {
new OSCSettingsT(),
values.vmc.oscSettings
);
if (values.vmc.vrmJson !== undefined) {
if (values.vmc.vrmJson.length > 0) {
const file = await parseVRMFile(values.vmc.vrmJson[0]);
if (file) {
vmcOsc.vrmJson = file.json;
setModelName(file.name);
}
} else {
vmcOsc.vrmJson = '';
setModelName(null);
}
}
vmcOsc.anchorHip = values.vmc.anchorHip;
vmcOsc.mirrorTracking = values.vmc.mirrorTracking;
@@ -124,10 +193,6 @@ export function VMCSettings() {
formData.vmc.oscSettings.address =
settings.vmcOsc.oscSettings.address.toString();
}
const vrmJson = settings.vmcOsc.vrmJson?.toString();
if (vrmJson) {
setModelName(getVRMName(vrmJson) || '');
}
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
formData.vmc.mirrorTracking = settings.vmcOsc.mirrorTracking;
@@ -238,23 +303,7 @@ export function VMCSettings() {
</Typography>
</div>
<div className="grid gap-3 pb-5">
<FileInput
control={control}
name="vmc.vrmJson"
rules={{
required: false,
}}
value="help"
importedFileName={
// if modelname is an empty string, it's an untitled model
modelName === ''
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
: modelName
}
label="settings-osc-vmc-vrm-file_select"
accept="model/gltf-binary, model/gltf+json, model/vrml, .vrm, .glb, .gltf"
/>
{/* For some reason, linux (GNOME) is detecting the VRM file is a VRML */}
<VMCFileUpload />
</div>
<Typography variant="section-title">
{l10n.getString('settings-osc-vmc-anchor_hip')}
@@ -344,16 +393,34 @@ async function parseVRMFile(
.slice(gltfHeaderEnd, gltfHeaderEnd + jsonLength, 'application/json')
.text();
const name = getVRMName(json);
let data: any;
try {
data = JSON.parse(json);
} catch (e) {
error('Failed to parse VRM glTF header: ' + e);
return null;
}
const name = getVRMName(data);
if (name === null) return null;
return { json, name };
// Only keep the fields we care about
/* eslint-disable camelcase */
const vrmJson = {
extensions: {
vrmV0: data.extensions.vrmV0,
VRMC_vrm: data.extensions.VRMC_vrm,
},
extensionsUsed: data.extensionsUsed,
nodes: data.nodes,
};
/* eslint-enable camelcase */
return { json: JSON.stringify(vrmJson), name };
}
function getVRMName(json: string): string | null {
function getVRMName(data: any): string | null {
try {
const data = JSON.parse(json);
if (typeof data?.extensions?.VRMC_vrm?.specVersion === 'string') {
const name = data.extensions.VRMC_vrm.meta.name;
@@ -369,7 +436,7 @@ function getVRMName(json: string): string | null {
return data?.extensions?.VRM?.meta?.title || '';
}
} catch (e) {
error(e);
error('Failed to fetch VRM name: ' + e);
return null;
}
}
@@ -13,7 +13,9 @@ export function TrackerBattery({
textColor = 'primary',
}: {
/**
* a [0, 1] value range is expected
* Normally [0, 1] value range
* Values >1 indicate fully charged
* Values <0 or >2 (Byte was cast to UByte, so -1 -> 255) also indicate 0%
*/
value: number;
voltage?: number | null;
@@ -36,11 +38,13 @@ export function TrackerBattery({
const debug = config?.debug || config?.devSettings.moreInfo;
const showVoltage = moreInfo && voltage && debug;
const pct = value > 2 ? 0 : Math.min(Math.max(value, 0), 1);
return (
<Tooltip
disabled={charging || !runtime || debug}
preferedDirection="left"
content=<Typography>{percentFormatter.format(value)}</Typography>
content=<Typography>{percentFormatter.format(pct)}</Typography>
>
<div className="flex gap-2">
<div className="flex flex-col justify-around">
@@ -61,7 +65,7 @@ export function TrackerBattery({
)}
{!charging && (!runtime || debug) && (
<Typography color={textColor}>
{percentFormatter.format(value)}
{percentFormatter.format(pct)}
</Typography>
)}
{showVoltage && (
+1 -1
View File
@@ -1,5 +1,5 @@
import classNames from 'classnames';
import { IPv4 } from 'ip-num/IPNumber';
import { IPv4 } from 'ip-num';
import { createContext, ReactNode, useContext, useMemo } from 'react';
import { useConfig } from '@/hooks/config';
import { useTracker } from '@/hooks/tracker';
@@ -6,7 +6,12 @@ import {
} from '@/hooks/tracking-checklist';
import classNames from 'classnames';
import {
ChangeSettingsRequestT,
ResetType,
RpcMessage,
SettingsRequestT,
SettingsResponseT,
SteamVRTrackersSettingT,
TrackingChecklistPublicNetworksT,
TrackingChecklistStepId,
} from 'solarxr-protocol';
@@ -29,6 +34,7 @@ import { TrackingChecklistModal } from './TrackingChecklistModal';
import { NavLink, useNavigate } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
import { openUrl } from '@/hooks/crossplatform';
import { useWebsocketAPI } from '@/hooks/websocket-api';
function Step({
step: { status, id, optional, firstRequired },
@@ -102,6 +108,55 @@ function Step({
);
}
function SteamVRHandsEnabled() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [steamVrTrackers, setSteamVrTrackers] = useState<Omit<
SteamVRTrackersSettingT,
'pack'
> | null>(null);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
if (settings.steamVrTrackers) {
setSteamVrTrackers(settings.steamVrTrackers);
}
});
const disableHandTrackers = () => {
const settings = new ChangeSettingsRequestT();
settings.steamVrTrackers = new SteamVRTrackersSettingT(
steamVrTrackers?.waist,
steamVrTrackers?.chest,
steamVrTrackers?.automaticTrackerToggle,
steamVrTrackers?.leftFoot,
steamVrTrackers?.rightFoot,
steamVrTrackers?.leftKnee,
steamVrTrackers?.rightKnee,
steamVrTrackers?.leftElbow,
steamVrTrackers?.rightElbow,
false,
false
);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
};
return (
<div className="space-y-2.5">
<Typography id="tracking_checklist-STEAMVR_HANDS_ENABLED-desc" />
<div className="flex">
<Button
id="tracking_checklist-STEAMVR_HANDS_ENABLED-go"
variant="primary"
onClick={disableHandTrackers}
/>
</div>
</div>
);
}
const stepContentLookup: Record<
number,
(
@@ -352,6 +407,9 @@ const stepContentLookup: Record<
</>
);
},
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]: () => {
return <SteamVRHandsEnabled />;
},
};
export function TrackingChecklistMobile() {
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { FieldPath, useForm } from 'react-hook-form';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
@@ -57,7 +57,7 @@ export function DeveloperModeWidget() {
control={control}
variant="toggle"
outlined
name={name}
name={name as FieldPath<DeveloperModeWidgetForm>}
label={l10n.getString(`widget-developer_mode-${label}`)}
/>
);
+3 -4
View File
@@ -48,6 +48,7 @@ export interface Config {
homeLayout: 'default' | 'table';
skeletonPreview: boolean;
lastUsedProportions: 'manual' | 'autobone' | 'scaled' | null;
dontShowUdevModal: boolean;
}
export interface ConfigContext {
@@ -79,6 +80,7 @@ export const defaultConfig: Config = {
homeLayout: 'default',
skeletonPreview: true,
lastUsedProportions: null,
dontShowUdevModal: false,
};
const localStore: CrossStorage = {
@@ -103,10 +105,7 @@ function fallbackToDefaults(loadedConfig: any): Config {
// allows to load everything before the first render
export const loadConfig = async () => {
try {
const json = await store.get<string>('config.json');
if (!json) throw new Error('Config has ceased existing for some reason');
const json = (await store.get<string>('config.json')) ?? '{}';
const loadedConfig = fallbackToDefaults(JSON.parse(json));
if (!loadedConfig.uuid) {
+2 -1
View File
@@ -152,7 +152,8 @@ export function checkForUpdate(
if (
canUpdate &&
device.hardwareStatus?.batteryPctEstimate != null &&
device.hardwareStatus.batteryPctEstimate < 50
(device.hardwareStatus.batteryPctEstimate < 50 ||
device.hardwareStatus.batteryPctEstimate > 200)
) {
return 'low-battery';
}
+108 -10
View File
@@ -1,6 +1,28 @@
import { createContext, Reducer, useContext, useLayoutEffect, useReducer } from 'react';
import {
createContext,
Reducer,
useContext,
useEffect,
useLayoutEffect,
useReducer,
useState,
} from 'react';
import { useLocation } from 'react-router-dom';
import { useConfig } from './config';
import { useWebsocketAPI } from './websocket-api';
import {
ChangeSettingsRequestT,
ModelSettingsT,
ModelTogglesT,
OSCSettingsT,
ResetsSettingsT,
RpcMessage,
SettingsRequestT,
SettingsResponseT,
SkeletonBone,
VRCOSCSettingsT,
} from 'solarxr-protocol';
import { useManualProportions } from './manual-proportions';
type OnboardingAction =
| { type: 'progress'; value: number }
@@ -13,13 +35,6 @@ interface OnboardingState {
alonePage: boolean;
}
export interface OnboardingContext {
state: OnboardingState;
applyProgress: (value: number) => void;
setWifiCredentials: (ssid: string, password?: string) => void;
skipSetup: () => void;
}
export function reducer(state: OnboardingState, action: OnboardingAction) {
switch (action.type) {
case 'wifi-creds':
@@ -42,8 +57,17 @@ export function reducer(state: OnboardingState, action: OnboardingAction) {
}
}
export function useProvideOnboarding(): OnboardingContext {
export type OnboardingContext = ReturnType<typeof useProvideOnboarding>;
export function useProvideOnboarding() {
const { setConfig } = useConfig();
const [slimeSet, setSlimeSet] = useState<
'butterfly' | 'slime-v1' | 'dongle-slime' | 'wifi-slime'
>();
const [usage, setUsage] = useState<'vr-gaming' | 'mocap' | 'vtubing'>();
const [vrcOsc, setVrcOSC] = useState<boolean>();
const [mocapPos, setMocapPos] = useState<'forehead' | 'face'>();
const [playspace, setPlayspace] = useState<'sitting' | 'standing'>();
const [state, dispatch] = useReducer<Reducer<OnboardingState, OnboardingAction>>(
reducer,
{
@@ -52,7 +76,11 @@ export function useProvideOnboarding(): OnboardingContext {
}
);
const { state: locatioState } = useLocation();
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const { state: locatioState, pathname } = useLocation();
const [previousPath, setPreviousPath] = useState(pathname);
const [settings, setSettings] = useState<SettingsResponseT>();
useLayoutEffect(() => {
const { alonePage = false }: { alonePage?: boolean } = (locatioState as any) || {};
@@ -61,8 +89,74 @@ export function useProvideOnboarding(): OnboardingContext {
dispatch({ type: 'alone-page', value: alonePage });
}, [locatioState, state]);
useEffect(() => {
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
const { changeBoneValue } = useManualProportions({
type: 'linear',
});
const onboardingEnded = () => {
if (!settings?.modelSettings || !settings?.vrcOsc) return;
const req = new ChangeSettingsRequestT();
const modelSettings = new ModelSettingsT();
const oscSettings = new VRCOSCSettingsT();
const mocap = usage === 'mocap' || usage === 'vtubing';
const toggles = Object.assign(new ModelTogglesT(), settings.modelSettings.toggles);
toggles.selfLocalization = mocap && playspace === 'standing';
modelSettings.toggles = toggles;
req.modelSettings = modelSettings;
const resets = Object.assign(new ResetsSettingsT(), settings.resetsSettings);
resets.resetHmdPitch = mocapPos === 'forehead';
req.resetsSettings = resets;
const osc = Object.assign(new OSCSettingsT(), settings.vrcOsc.oscSettings);
osc.enabled = vrcOsc ?? false;
oscSettings.oscSettings = osc;
req.vrcOsc = oscSettings;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
if (mocap) {
changeBoneValue({ bone: SkeletonBone.HAND_Z, type: 'bone', newValue: 0 });
}
};
const onboardingStarted = () => {
setSlimeSet(undefined);
setUsage(undefined);
setVrcOSC(undefined);
setMocapPos(undefined);
setPlayspace(undefined);
};
useEffect(() => {
setPreviousPath(pathname);
if (!pathname.startsWith('/onboarding') && previousPath.startsWith('/onboarding')) {
onboardingEnded();
}
if (pathname.startsWith('/onboarding') && !previousPath.startsWith('/onboarding')) {
onboardingStarted();
}
}, [pathname]);
return {
state,
slimeSet,
usage,
vrcOsc,
mocapPos,
playspace,
setPlayspace,
applyProgress: (value: number) => {
useLayoutEffect(() => {
dispatch({ type: 'progress', value });
@@ -74,6 +168,10 @@ export function useProvideOnboarding(): OnboardingContext {
skipSetup: () => {
setConfig({ doneOnboarding: true });
},
setSlimeSet,
setUsage,
setVrcOSC,
setMocapPos,
};
}
+2
View File
@@ -30,6 +30,8 @@ export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string>
'tracking_checklist-FEET_MOUNTING_CALIBRATION',
[TrackingChecklistStepId.STAY_ALIGNED_CONFIGURED]:
'tracking_checklist-STAY_ALIGNED_CONFIGURED',
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]:
'tracking_checklist-STEAMVR_HANDS_ENABLED',
};
export type TrackingChecklistStepStatus =
+5 -1
View File
@@ -11,8 +11,12 @@ import { DeviceDataT } from 'solarxr-protocol';
export function getSentryOrCompute(enabled = false, uuid: string) {
Sentry.setUser({ id: uuid });
// if sentry is already initialized - SKIP
if (enabled && Sentry.isInitialized()) return;
if (enabled && Sentry.isInitialized()) {
log('Sentry already enabled, skipping initialization');
return;
}
const client = Sentry.getClient();
if (client) {
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "slimevr",
"version": "0.0.0",
"private": true,
"packageManager": "pnpm@9.12.2",
"packageManager": "pnpm@10.33.0",
"workspaces": [
"solarxr-protocol",
"gui"
+1885 -3216
View File
File diff suppressed because it is too large. Load diff
+10
View File
@@ -2,3 +2,13 @@ packages:
- "solarxr-protocol"
- "gui"
- "!solarxr-protocol/lib/flatbuffers/**"
onlyBuiltDependencies:
- '@parcel/watcher'
- '@sentry/cli'
- '@swc/core'
- electron
- electron-winstaller
- esbuild
- register-scheme
- unrs-resolver
@@ -14,9 +14,6 @@ import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerStatus
import dev.slimevr.tracking.trackers.hid.HIDCommon
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_VID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.PACKET_SIZE
import dev.slimevr.tracking.trackers.hid.HIDDevice
import io.eiren.util.logging.LogManager
@@ -94,7 +91,7 @@ class AndroidHIDManager(
}
fun checkConfigureDevice(usbDevice: UsbDevice, requestPermission: Boolean = false) {
if (usbDevice.vendorId == HID_TRACKER_RECEIVER_VID && (usbDevice.productId == HID_TRACKER_RECEIVER_PID || usbDevice.productId == HID_TRACKER_PID)) {
if (HIDCommon.matchesAny(usbDevice.vendorId, usbDevice.productId)) {
if (usbManager.hasPermission(usbDevice)) {
LogManager.info("[TrackerServer] Already have permission for ${usbDevice.deviceName}")
proceedWithDeviceConfiguration(usbDevice)
@@ -204,7 +201,7 @@ class AndroidHIDManager(
private fun deviceEnumerate(requestPermission: Boolean = false) {
val trackersOverHID: Boolean = VRServer.instance.configManager.vrConfig.hidConfig.trackersOverHID
val hidDeviceList: MutableList<UsbDevice> = usbManager.deviceList.values.filter {
it.vendorId == HID_TRACKER_RECEIVER_VID && (it.productId == HID_TRACKER_RECEIVER_PID || (trackersOverHID && it.productId == HID_TRACKER_PID))
HIDCommon.matchesReceiver(it.vendorId, it.productId) || (trackersOverHID && HIDCommon.matchesTracker(it.vendorId, it.productId))
}.toMutableList()
synchronized(devicesByHID) {
// Work on devicesByHid and add/remove as necessary
@@ -0,0 +1,6 @@
package dev.slimevr
data class FeatureFlags(
var steam: Boolean = false,
var skipCheckUdev: Boolean = false,
)
@@ -17,6 +17,7 @@ import dev.slimevr.osc.VMCHandler
import dev.slimevr.osc.VRCOSCHandler
import dev.slimevr.posestreamer.BVHRecorder
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.TransactionInfo
import dev.slimevr.protocol.rpc.settings.RPCSettingsHandler
import dev.slimevr.reset.ResetHandler
import dev.slimevr.reset.ResetTimerManager
@@ -56,6 +57,7 @@ const val SLIMEVR_IDENTIFIER = "dev.slimevr.SlimeVR"
class VRServer @JvmOverloads constructor(
bridgeProvider: BridgeProvider = { _, _ -> sequence {} },
featureFlagsProvider: (VRServer) -> FeatureFlags = { _ -> FeatureFlags() },
serialHandlerProvider: (VRServer) -> SerialHandler = { _ -> SerialHandlerStub() },
flashingHandlerProvider: (VRServer) -> SerialFlashingHandler? = { _ -> null },
vrcConfigHandlerProvider: (VRServer) -> VRCConfigHandler = { _ -> VRCConfigHandlerStub() },
@@ -83,6 +85,9 @@ class VRServer @JvmOverloads constructor(
@JvmField
val deviceManager: DeviceManager
// UwU
val featureFlags: FeatureFlags = featureFlagsProvider(this)
@JvmField
val bvhRecorder: BVHRecorder
@@ -126,7 +131,6 @@ class VRServer @JvmOverloads constructor(
val serverGuards = ServerGuards()
init {
// UwU
deviceManager = DeviceManager(this)
serialHandler = serialHandlerProvider(this)
serialFlashingHandler = flashingHandlerProvider(this)
@@ -301,9 +305,8 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.updateSkeletonModelFromServer()
vrcOSCHandler.setHeadTracker(TrackerUtils.getTrackerForSkeleton(trackers, TrackerPosition.HEAD))
if (this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically() == true) {
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
@@ -329,9 +332,8 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.setPauseTracking(pauseTracking, sourceName)
// Toggle trackers as they don't toggle when tracking is paused
if (this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically() == true) {
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
@@ -339,55 +341,54 @@ class VRServer @JvmOverloads constructor(
queueTask {
humanPoseManager.togglePauseTracking(sourceName)
// Toggle trackers as they don't toggle when tracking is paused
if (this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically() == true) {
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
this.getVRBridge(ISteamVRBridge::class.java)?.updateShareSettingsAutomatically()
RPCSettingsHandler.sendSteamVRUpdatedSettings(protocolAPI, protocolAPI.rpcHandler)
}
}
fun scheduleResetTrackersFull(resetSourceName: String?, delay: Long, bodyParts: List<Int> = ArrayList()) {
fun scheduleResetTrackersFull(resetSourceName: String?, delay: Long, bodyParts: List<Int> = ArrayList(), tx: TransactionInfo? = null) {
resetTimer(
resetTimerManager,
delay,
onTick = { progress ->
resetHandler.sendStarted(ResetType.Full, bodyParts, progress, delay.toInt())
resetHandler.sendStarted(ResetType.Full, tx, bodyParts, progress, delay.toInt())
},
onComplete = {
queueTask {
humanPoseManager.resetTrackersFull(resetSourceName, bodyParts)
resetHandler.sendFinished(ResetType.Full, bodyParts, delay.toInt())
resetHandler.sendFinished(ResetType.Full, tx, bodyParts, delay.toInt())
}
},
)
}
fun scheduleResetTrackersYaw(resetSourceName: String?, delay: Long, bodyParts: List<Int> = TrackerUtils.allBodyPartsButFingers) {
fun scheduleResetTrackersYaw(resetSourceName: String?, delay: Long, bodyParts: List<Int> = TrackerUtils.allBodyPartsButFingers, tx: TransactionInfo? = null) {
resetTimer(
resetTimerManager,
delay,
onTick = { progress ->
resetHandler.sendStarted(ResetType.Yaw, bodyParts, progress, delay.toInt())
resetHandler.sendStarted(ResetType.Yaw, tx, bodyParts, progress, delay.toInt())
},
onComplete = {
queueTask {
humanPoseManager.resetTrackersYaw(resetSourceName, bodyParts)
resetHandler.sendFinished(ResetType.Yaw, bodyParts, delay.toInt())
resetHandler.sendFinished(ResetType.Yaw, tx, bodyParts, delay.toInt())
}
},
)
}
fun scheduleResetTrackersMounting(resetSourceName: String?, delay: Long, bodyParts: List<Int>? = null) {
fun scheduleResetTrackersMounting(resetSourceName: String?, delay: Long, bodyParts: List<Int>? = null, tx: TransactionInfo? = null) {
resetTimer(
resetTimerManager,
delay,
onTick = { progress ->
resetHandler.sendStarted(ResetType.Mounting, bodyParts, progress, delay.toInt())
resetHandler.sendStarted(ResetType.Mounting, tx, bodyParts, progress, delay.toInt())
},
onComplete = {
queueTask {
humanPoseManager.resetTrackersMounting(resetSourceName, bodyParts)
resetHandler.sendFinished(ResetType.Mounting, bodyParts, delay.toInt())
resetHandler.sendFinished(ResetType.Mounting, tx, bodyParts, delay.toInt())
}
},
)
@@ -12,7 +12,6 @@ import com.jme3.math.FastMath
import com.jme3.system.NanoTimer
import dev.slimevr.VRServer
import dev.slimevr.config.VRCOSCConfig
import dev.slimevr.protocol.rpc.setup.RPCUtil
import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
@@ -26,6 +25,8 @@ import io.github.axisangles.ktmath.Vector3
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import kotlin.collections.iterator
private const val OFFSET_SLERP_FACTOR = 0.5f // Guessed from eyeing VRChat
@@ -37,8 +38,6 @@ class VRCOSCHandler(
private val config: VRCOSCConfig,
private val computedTrackers: List<Tracker>,
) : OSCHandler {
private val localIp = RPCUtil.getLocalIp()
private val loopbackIp = InetAddress.getLoopbackAddress().hostAddress
private val vrsystemTrackersAddresses = arrayOf(
"/tracking/vrsystem/head/pose",
"/tracking/vrsystem/leftwrist/pose",
@@ -60,9 +59,9 @@ class VRCOSCHandler(
private var oscPortIn = 0
private var oscPortOut = 0
private var oscIp: InetAddress? = null
private var oscQuerySenderState = false
private var oscQueryPortOut = 0
private var oscQueryIp: String? = null
private var oscQueryIp: InetAddress? = null
private var oscQueryIpMatch = false
private var timeAtLastError: Long = 0
private var receivingPositionOffset = Vector3.NULL
private var postReceivingPositionOffset = Vector3.NULL
@@ -94,13 +93,15 @@ class VRCOSCHandler(
updateOscReceiver(config.portIn, vrsystemTrackersAddresses + oscTrackersAddresses)
updateOscSender(config.portOut, config.address)
if (vrcOscQueryHandler == null && config.enabled && config.oscqueryEnabled) {
try {
vrcOscQueryHandler = VRCOSCQueryHandler(this)
} catch (e: Throwable) {
LogManager.severe("Unable to initialize OSCQuery: $e", e)
if (config.enabled && config.oscqueryEnabled) {
if (vrcOscQueryHandler == null) {
try {
vrcOscQueryHandler = VRCOSCQueryHandler(server, this)
} catch (e: Throwable) {
LogManager.severe("Unable to initialize OSCQuery: $e", e)
}
}
} else if (vrcOscQueryHandler != null && (!config.enabled || !config.oscqueryEnabled)) {
} else {
vrcOscQueryHandler?.close()
vrcOscQueryHandler = null
}
@@ -110,122 +111,218 @@ class VRCOSCHandler(
}
}
fun ipIsLocal(a: InetAddress): Boolean {
if (a.isLoopbackAddress) {
return true
}
for (netInt in NetworkInterface.getNetworkInterfaces()) {
if (netInt.isUp && !netInt.isLoopback && !netInt.isVirtual) {
for (netAddr in netInt.interfaceAddresses) {
if (a == netAddr.address || a.address.contentEquals(netAddr.address.address) || a.hostName == netAddr.address.hostName) {
return true
}
}
}
}
return false
}
fun ipEquals(a: InetAddress?, b: InetAddress?): Boolean = a == b ||
(
a != null &&
b != null &&
(
a.address.contentEquals(b.address) ||
(a.hostName == b.hostName) ||
(ipIsLocal(a) && ipIsLocal(b))
)
)
/**
* Adds an OSC Sender from OSCQuery
*/
fun addOSCQuerySender(oscPortOut: Int, oscIP: String) {
val addr = InetAddress.getByName(oscIP)
oscQuerySenderState = true
oscQueryIp = oscIP
oscQueryPortOut = oscPortOut
if (oscPortOut != portOut || (oscIP != address.hostName && !(oscIP == localIp && address.hostName == loopbackIp))) {
try {
oscQuerySender = OSCPortOut(InetSocketAddress(addr, oscPortOut))
oscQuerySender?.connect()
LogManager.info("[VRCOSCHandler] OSCQuery sender sending to port $oscPortOut at address $oscIP")
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error connecting to port $oscPortOut at the address $oscIP: $e")
if (!config.enabled) {
closeOscQuerySender()
return
}
try {
// If we already have the best matching client
if (oscQuerySender != null && oscQueryIpMatch) {
return
}
val addr = InetAddress.getByName(oscIP)
val ipMatch = ipEquals(addr, this.oscIp)
// If we already have an OSC sender
if (oscQuerySender != null) {
val portMatch = oscPortOut == this.oscPortOut
// Original IP will be matching because of the check done earlier
val origPortMatch = oscQueryPortOut == this.oscPortOut
// If the IP doesn't match and (the port doesn't match or the original
// port did match), ignore this client
if (!ipMatch && (!portMatch || origPortMatch)) {
return
}
// If this is the same address as what we're already sending to, keep
// using the same OSC sender
if (ipEquals(addr, oscQueryIp)) {
return
}
// So if the IP matches or the port matches and the original one didn't,
// we will select this new address for OSC
}
closeOscQuerySender()
if (ipMatch) {
LogManager.info("[VRCOSCHandler] OSCQuery sender sending to port $oscPortOut at address $oscIP (matches configured address)")
} else {
LogManager.info("[VRCOSCHandler] OSCQuery sender sending to port $oscPortOut at address $oscIP")
}
oscQuerySender = OSCPortOut(InetSocketAddress(addr, oscPortOut))
oscQueryIp = addr
oscQueryIpMatch = ipMatch
oscQueryPortOut = oscPortOut
// Avoids additional security checks, but not necessary for UDP, therefore
// isConnected doesn't really indicate that we are actively "connected"
oscQuerySender?.connect()
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error connecting OSCQuery sender to port $oscPortOut at the address $oscIP: $e")
closeOscQuerySender()
}
}
/**
* Close/remove the osc query sender
* Close/remove the OSC sender
*/
fun closeOscQuerySender(newState: Boolean) {
oscQuerySender?.let {
try {
it.close()
oscQuerySender = null
oscQuerySenderState = newState
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
fun closeOscSender() {
try {
oscSender?.close()
oscSender = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
}
override fun updateOscReceiver(portIn: Int, args: Array<String>) {
// Stop listening
val wasListening = oscReceiver != null && oscReceiver!!.isListening
if (wasListening) {
oscReceiver!!.stopListening()
/**
* Close/remove the OSCQuery sender
*/
fun closeOscQuerySender() {
try {
oscQuerySender?.close()
oscQuerySender = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSCQuery sender: $e")
}
}
/**
* Close/remove the OSC receiver
*/
fun closeOscReceiver() {
try {
oscReceiver?.close()
oscReceiver = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC receiver: $e")
}
}
override fun updateOscReceiver(portIn: Int, oscAddresses: Array<String>) {
if (!config.enabled) {
closeOscReceiver()
return
}
if (config.enabled) {
// Instantiates the OSC receiver
try {
oscReceiver = OSCPortIn(portIn)
if (oscPortIn != portIn || !wasListening) {
LogManager.info("[VRCOSCHandler] Listening to port $portIn")
}
oscPortIn = portIn
vrcOscQueryHandler?.updateOSCQuery(portIn.toUShort())
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error listening to the port $portIn: $e",
)
// If already configured and listening, nothing new needs to be configured
if (oscPortIn == portIn && oscReceiver?.isListening == true) return
try {
closeOscReceiver()
// Instantiate the new OSC receiver
LogManager.info("[VRCOSCHandler] Listening to port $portIn")
val newOscReceiver = OSCPortIn(portIn)
oscReceiver = newOscReceiver
oscPortIn = portIn
val listener = OSCMessageListener { event: OSCMessageEvent ->
handleReceivedMessage(event)
}
for (address in oscAddresses) {
newOscReceiver.dispatcher.addListener(
OSCPatternAddressMessageSelector(address),
listener,
)
}
// Starts listening for VRC or OSCTrackers messages
oscReceiver?.let {
val listener = OSCMessageListener { event: OSCMessageEvent ->
handleReceivedMessage(event)
}
for (address in args) {
it.dispatcher.addListener(
OSCPatternAddressMessageSelector(address),
listener,
)
}
it.startListening()
}
newOscReceiver.startListening()
// Advertise our new receiving port over OSCQuery
vrcOscQueryHandler?.updateOSCQuery(portIn.toUShort())
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error listening to the port $portIn: $e")
closeOscReceiver()
}
}
override fun updateOscSender(portOut: Int, ip: String) {
// Stop sending
val wasConnected = oscSender != null && oscSender!!.isConnected
if (wasConnected) {
try {
oscSender!!.close()
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
if (!config.enabled) {
closeOscSender()
return
}
if (config.enabled) {
// Instantiate the OSC sender
try {
val addr = InetAddress.getByName(ip)
oscSender = OSCPortOut(InetSocketAddress(addr, portOut))
if ((oscPortOut != portOut && oscIp != addr) || !wasConnected) {
LogManager.info("[VRCOSCHandler] Sending to port $portOut at address $ip")
try {
// If already configured, nothing new needs to be configured
val addr = InetAddress.getByName(ip)
val resetQuery = if (ipEquals(addr, oscIp) && oscPortOut == portOut) {
// Technically we are fine if `isConnected` is false, but we can just
// assume we're always gonna be connected
if (oscSender?.isConnected == true) {
return
}
oscPortOut = portOut
oscIp = addr
oscSender?.connect()
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error connecting to port $portOut at the address $ip: $e",
)
return
false
} else {
// If the new IP doesn't match the current OSCQuery IP, close the
// OSCQuery sender after updating the config variables
!ipEquals(addr, oscQueryIp)
}
if (oscQueryPortOut == portOut && (oscQueryIp == ip || (oscQueryIp == localIp && ip == loopbackIp))) {
if (oscQuerySender != null) {
// Close the oscQuerySender if it has the same port/ip
closeOscQuerySender(true)
}
} else if (oscQuerySender == null && oscQuerySenderState) {
// Instantiate the oscQuerySender if it could not be instantiated.
addOSCQuerySender(oscQueryPortOut, oscQueryIp!!)
closeOscSender()
LogManager.info("[VRCOSCHandler] Sending to port $portOut at address $ip")
val newOscSender = OSCPortOut(InetSocketAddress(addr, portOut))
oscSender = newOscSender
oscIp = addr
oscPortOut = portOut
// Avoids additional security checks, but not necessary for UDP, therefore
// isConnected doesn't really indicate that we are actively "connected"
newOscSender.connect()
if (resetQuery) {
closeOscQuerySender()
}
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error connecting to port $portOut at the address $ip: $e",
)
closeOscSender()
return
}
}
private fun handleReceivedMessage(event: OSCMessageEvent) {
// TODO: Track the IP who sent this, we can list them as a send target and
// resolve the VRChat IP/port without scanning OSCQuery
if (vrsystemTrackersAddresses.contains(event.message.address)) {
// Receiving Head and Wrist pose data thanks to OSCQuery
// Create device if it doesn't exist
@@ -407,6 +504,10 @@ class VRCOSCHandler(
}
override fun update() {
if (!config.enabled) {
return
}
// Gets timer from vrServer
if (fpsTimer == null) {
fpsTimer = VRServer.instance.fpsTimer
@@ -420,7 +521,7 @@ class VRCOSCHandler(
val currentTime = System.currentTimeMillis().toFloat()
// Send OSC data
if (oscSender != null && oscSender!!.isConnected) {
if (oscSender != null || oscQuerySender != null) {
// Create new bundle
val bundle = OSCBundle()
@@ -482,8 +583,12 @@ class VRCOSCHandler(
}
try {
oscSender?.send(bundle)
oscQuerySender?.send(bundle)
// Prioritize OSCQuery since we can't validate oscSender
if (oscQuerySender != null) {
oscQuerySender?.send(bundle)
} else {
oscSender?.send(bundle)
}
} catch (e: IOException) {
// Avoid spamming AsynchronousCloseException too many
// times per second
@@ -525,7 +630,7 @@ class VRCOSCHandler(
* Sends the expected HMD rotation upon reset to align the trackers in VRC
*/
fun yawAlign(headRot: Quaternion) {
if (oscSender != null && oscSender!!.isConnected) {
if (oscSender != null || oscQuerySender != null) {
val (_, _, y, _) = headRot.toEulerAngles(EulerOrder.YXZ)
oscArgs.clear()
oscArgs.add(0f)
@@ -536,8 +641,12 @@ class VRCOSCHandler(
oscArgs,
)
try {
oscSender?.send(oscMessage)
oscQuerySender?.send(oscMessage)
// Prioritize OSCQuery since we can't validate oscSender
if (oscQuerySender != null) {
oscQuerySender?.send(oscMessage)
} else {
oscSender?.send(oscMessage)
}
} catch (e: IOException) {
LogManager
.warning("[VRCOSCHandler] Error sending OSC message to VRChat: $e")
@@ -3,6 +3,7 @@ package dev.slimevr.osc
import OSCQueryNode
import OSCQueryServer
import ServiceInfo
import dev.slimevr.VRServer
import dev.slimevr.protocol.rpc.setup.RPCUtil
import io.eiren.util.logging.LogManager
import randomFreePort
@@ -17,6 +18,7 @@ private const val queryPath = "/tracking/vrsystem"
* https://github.com/SlimeVR/oscquery-kt
*/
class VRCOSCQueryHandler(
private val server: VRServer,
private val vrcOscHandler: VRCOSCHandler,
) {
private val oscQueryServer: OSCQueryServer
@@ -71,14 +73,16 @@ class VRCOSCQueryHandler(
val port = info.port
// create a new OSCHandler for this service
vrcOscHandler.addOSCQuerySender(port, ip)
server.queueTask {
vrcOscHandler.addOSCQuerySender(port, ip)
}
}
/**
* Closes the OSCQueryServer and the associated OSC sender.
*/
fun close() {
vrcOscHandler.closeOscQuerySender(false)
vrcOscHandler.closeOscQuerySender()
thread(start = true) {
oscQueryServer.close()
}
@@ -5,6 +5,7 @@ import dev.slimevr.tracking.processor.Bone
import dev.slimevr.tracking.processor.skeleton.HumanSkeleton
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import org.apache.commons.lang3.StringUtils
import java.io.BufferedWriter
import java.io.File
@@ -44,36 +45,91 @@ class BVHFileStream : PoseDataStream {
private fun internalNavigateSkeleton(
bone: Bone,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) -> Unit,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) -> Unit,
footer: (distance: Int) -> Unit,
lastBone: Bone? = null,
invertParentRot: Quaternion = Quaternion.IDENTITY,
distance: Int = 0,
isParent: Boolean = false,
invertOffset: Boolean = false,
zeroOffset: Boolean = false,
) {
val isRoot = lastBone == null
val isInverse = bone === lastBone?.parent
val parent = bone.parent
// If we're visiting the parents or at root, continue to the next parent
val visitParent = (isParent || lastBone == null) && parent != null
val visitParent = (isInverse || isRoot) && parent != null
val children = bone.children
val childCount = children.size - (if (isParent) 1 else 0)
// We are navigating inversely; this bone's node is at the head rather than
// the tail, so we let our origin child take our children, and we take our
// parent's children in turn
// Root is a special condition where it is both states simultaneously
val invChildren = if (visitParent) {
parent.children
} else {
emptyList()
}
val children = if (!isInverse) {
bone.children
} else {
emptyList()
}
val hasBranch = visitParent || childCount > 0
val hasBranch = visitParent || children.isNotEmpty()
header(bone, lastBone, invertParentRot, distance, hasBranch, isParent)
header(
bone,
lastBone,
invertParentRot,
distance,
hasBranch,
invertOffset,
zeroOffset,
)
if (hasBranch) {
// Cache this inverted rotation to reduce computation for each branch
val thisInvertRot = bone.getGlobalRotation().inv()
val thisInvertRot = bone.rotationOffset * bone.getGlobalRotation().inv()
if (visitParent) {
internalNavigateSkeleton(parent, header, footer, bone, thisInvertRot, distance + 1, true)
internalNavigateSkeleton(
parent,
header,
footer,
bone,
thisInvertRot,
distance + 1,
invertOffset || isInverse,
false,
)
}
for (child in invChildren) {
// Ignore our own bone (from parent's children)
if (child == bone) continue
internalNavigateSkeleton(
child,
header,
footer,
bone,
thisInvertRot,
distance + 1,
true,
!invertOffset,
)
}
for (child in children) {
// If we're a parent, ignore the child
if (isParent && child == lastBone) continue
internalNavigateSkeleton(child, header, footer, bone, thisInvertRot, distance + 1, false)
internalNavigateSkeleton(
child,
header,
footer,
bone,
thisInvertRot,
distance + 1,
false,
invertOffset,
)
}
}
@@ -82,13 +138,17 @@ class BVHFileStream : PoseDataStream {
private fun navigateSkeleton(
root: Bone,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) -> Unit,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) -> Unit,
footer: (distance: Int) -> Unit = {},
// Default true if the root isn't the true root (usually hip)
tailRoot: Boolean = root.parent != null,
) {
internalNavigateSkeleton(root, header, footer)
// Root is treated as a parent if we want to target the tail as the root node
internalNavigateSkeleton(root, header, footer, invertOffset = tailRoot)
}
private fun writeBoneDefHeader(bone: Bone?, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) {
private fun writeBoneDefHeader(bone: Bone?, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) {
val isRoot = lastBone == null
val indentLevel = StringUtils.repeat("\t", distance)
val nextIndentLevel = indentLevel + "\t"
@@ -96,24 +156,23 @@ class BVHFileStream : PoseDataStream {
if (bone == null) {
writer.write("${indentLevel}End Site\n")
} else {
writer
.write("${indentLevel}${if (distance > 0) "JOINT" else "ROOT"} ${bone.boneType}\n")
writer.write("${indentLevel}${if (!isRoot) "JOINT" else "ROOT"} ${bone.boneType}\n")
}
writer.write("$indentLevel{\n")
// "OFFSET": Defines the parent bone's local tail position
// Ignore the root and endpoint offsets
if (bone != null && lastBone != null) {
writer.write(
"${nextIndentLevel}OFFSET 0.0 ${(if (isParent) lastBone.length else -lastBone.length) * bvhSettings.offsetScale} 0.0\n",
)
val offset = if (zeroOffset || isRoot) {
Vector3.NULL
} else {
writer.write("${nextIndentLevel}OFFSET 0.0 0.0 0.0\n")
lastBone.rotationOffset.sandwichUnitY() * ((if (invertOffset) 1 else -1) * lastBone.length * bvhSettings.offsetScale)
}
writer.write("${nextIndentLevel}OFFSET ${offset.x} ${offset.y} ${offset.z}\n")
// Define channels
if (bone != null) {
// Only give position for root
if (lastBone != null) {
if (!isRoot) {
writer.write("${nextIndentLevel}CHANNELS 3 Zrotation Xrotation Yrotation\n")
} else {
writer.write(
@@ -125,7 +184,15 @@ class BVHFileStream : PoseDataStream {
// We use null for convenience and treat it as an end node (no bone)
if (!hasBranch) {
val endDistance = distance + 1
writeBoneDefHeader(null, bone, Quaternion.IDENTITY, endDistance, false, false)
writeBoneDefHeader(
null,
bone,
Quaternion.IDENTITY,
endDistance,
hasBranch = false,
invertOffset = false,
zeroOffset = false,
)
writeBoneDefFooter(endDistance)
}
}
@@ -161,10 +228,22 @@ class BVHFileStream : PoseDataStream {
writer.write("Frame Time: ${streamer.frameInterval}\n")
}
private fun writeBoneRot(bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) {
val rot = invertParentRot * bone.getGlobalRotation()
private fun writeBoneRot(bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) {
val rot = bone.rotationOffset.inv() * invertParentRot * bone.getGlobalRotation()
val angles = rot.toEulerAngles(EulerOrder.ZXY)
// We're the root, so write position
if (lastBone == null) {
val rootPos = if (invertOffset) {
bone.getTailPosition()
} else {
bone.getPosition()
}
// Write root position
val positionScale = bvhSettings.positionScale
writer.write("${rootPos.x * positionScale} ${rootPos.y * positionScale} ${rootPos.z * positionScale}")
}
// Output in order of roll (Z), pitch (X), yaw (Y) (extrinsic)
// Assume spacing is needed at the start (we start with position with no following space)
writer
@@ -174,14 +253,6 @@ class BVHFileStream : PoseDataStream {
@Throws(IOException::class)
override fun writeFrame(skeleton: HumanSkeleton) {
val rootBone = skeleton.getBone(bvhSettings.rootBone)
val rootPos = rootBone.getPosition()
// Write root position
val positionScale = bvhSettings.positionScale
writer
.write("${rootPos.x * positionScale} ${rootPos.y * positionScale} ${rootPos.z * positionScale}")
navigateSkeleton(rootBone, ::writeBoneRot)
writer.newLine()
@@ -10,6 +10,7 @@ import dev.slimevr.protocol.datafeed.createTrackerId
import dev.slimevr.protocol.rpc.autobone.RPCAutoBoneHandler
import dev.slimevr.protocol.rpc.firmware.RPCFirmwareUpdateHandler
import dev.slimevr.protocol.rpc.games.vrchat.RPCVRChatHandler
import dev.slimevr.protocol.rpc.installinfo.RPCInstallInfoHandler
import dev.slimevr.protocol.rpc.reset.RPCResetHandler
import dev.slimevr.protocol.rpc.serial.RPCProvisioningHandler
import dev.slimevr.protocol.rpc.serial.RPCSerialHandler
@@ -52,6 +53,7 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
RPCVRChatHandler(this, api)
RPCTrackingChecklistHandler(this, api)
RPCUserHeightCalibration(this, api)
RPCInstallInfoHandler(this, api)
registerPacketListener(
RpcMessage.AssignTrackerRequest,
@@ -374,15 +376,14 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
}
}
@JvmOverloads
fun createRPCMessage(fbb: FlatBufferBuilder, messageType: Byte, messageOffset: Int, respondTo: RpcMessageHeader? = null): Int {
fun createRPCMessage(fbb: FlatBufferBuilder, messageType: Byte, messageOffset: Int, txId: Long?): Int {
val data = IntArray(1)
RpcMessageHeader.startRpcMessageHeader(fbb)
RpcMessageHeader.addMessage(fbb, messageOffset)
RpcMessageHeader.addMessageType(fbb, messageType)
respondTo?.txId()?.let { txId ->
RpcMessageHeader.addTxId(fbb, TransactionId.createTransactionId(fbb, txId.id()))
txId?.let { txId ->
RpcMessageHeader.addTxId(fbb, TransactionId.createTransactionId(fbb, txId))
}
data[0] = RpcMessageHeader.endRpcMessageHeader(fbb)
@@ -393,6 +394,10 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
return MessageBundle.endMessageBundle(fbb)
}
fun createRPCMessage(fbb: FlatBufferBuilder, messageType: Byte, messageOffset: Int): Int = createRPCMessage(fbb, messageType, messageOffset, txId = null)
fun createRPCMessage(fbb: FlatBufferBuilder, messageType: Byte, messageOffset: Int, respondTo: RpcMessageHeader?): Int = createRPCMessage(fbb, messageType, messageOffset, respondTo?.txId()?.id())
override fun messagesCount(): Int = RpcMessage.names.size
fun onStatusSystemRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
@@ -0,0 +1,8 @@
package dev.slimevr.protocol.rpc
import dev.slimevr.protocol.GenericConnection
data class TransactionInfo(
val id: Long,
val conn: GenericConnection,
)
@@ -0,0 +1,57 @@
package dev.slimevr.protocol.rpc.installinfo
import com.google.flatbuffers.FlatBufferBuilder
import dev.slimevr.protocol.GenericConnection
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.RPCHandler
import io.eiren.util.logging.LogManager
import solarxr_protocol.rpc.InstalledInfoResponse.createInstalledInfoResponse
import solarxr_protocol.rpc.RpcMessage
import solarxr_protocol.rpc.RpcMessageHeader
import java.io.IOException
class RPCInstallInfoHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
init {
rpcHandler.registerPacketListener(RpcMessage.InstalledInfoRequest, ::onInstalledInfoRequest)
}
fun onInstalledInfoRequest(conn: GenericConnection, messageHeader: RpcMessageHeader?) {
if (api.server.featureFlags.skipCheckUdev) {
return
}
val command = if (api.server.featureFlags.steam) {
arrayOf("steam-runtime-launch-client", "--alongside-steam", "--", "udevadm", "cat")
} else {
arrayOf("udevadm", "cat")
}
val udevResponse = executeShellCommand(*command)
if (udevResponse == null) {
LogManager.warning("Server couldn't verify if udev is installed")
return
}
val response = udevResponse.contains("slime")
val fbb = FlatBufferBuilder(1024)
val outbound = this.rpcHandler.createRPCMessage(
fbb,
RpcMessage.InstalledInfoResponse,
createInstalledInfoResponse(fbb, response, false),
)
fbb.finish(outbound)
conn.send(fbb.dataBuffer())
}
}
private fun executeShellCommand(vararg command: String): String? = try {
val process = ProcessBuilder(*command)
.redirectErrorStream(true)
.start()
process.inputStream.bufferedReader().readText().also {
process.waitFor()
}
} catch (e: IOException) {
LogManager.warning("Error executing shell command", e)
null
}
@@ -5,6 +5,7 @@ import dev.slimevr.protocol.GenericConnection
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.ProtocolAPIServer
import dev.slimevr.protocol.rpc.RPCHandler
import dev.slimevr.protocol.rpc.TransactionInfo
import dev.slimevr.reset.ResetListener
import solarxr_protocol.rpc.ClearMountingResetRequest
import solarxr_protocol.rpc.ResetRequest
@@ -13,6 +14,7 @@ import solarxr_protocol.rpc.ResetStatus
import solarxr_protocol.rpc.ResetType
import solarxr_protocol.rpc.RpcMessage
import solarxr_protocol.rpc.RpcMessageHeader
import java.nio.ByteBuffer
import java.util.function.Consumer
class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetListener {
@@ -38,6 +40,10 @@ class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetL
}
}
val tx = messageHeader.txId()?.id()?.let {
TransactionInfo(it, conn)
}
if (req.resetType() == ResetType.Yaw) {
val delay = if (req.hasDelay()) {
req.delay()
@@ -45,9 +51,9 @@ class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetL
resetsConfig.yawResetDelay
}
if (bodyParts.isEmpty()) {
api.server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, (delay * 1000).toLong())
api.server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, (delay * 1000).toLong(), tx = tx)
} else {
api.server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList())
api.server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList(), tx = tx)
}
}
if (req.resetType() == ResetType.Full) {
@@ -57,9 +63,9 @@ class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetL
resetsConfig.fullResetDelay
}
if (bodyParts.isEmpty()) {
api.server.scheduleResetTrackersFull(RESET_SOURCE_NAME, (delay * 1000).toLong())
api.server.scheduleResetTrackersFull(RESET_SOURCE_NAME, (delay * 1000).toLong(), tx = tx)
} else {
api.server.scheduleResetTrackersFull(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList())
api.server.scheduleResetTrackersFull(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList(), tx = tx)
}
}
if (req.resetType() == ResetType.Mounting) {
@@ -69,35 +75,55 @@ class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetL
resetsConfig.mountingResetDelay
}
if (bodyParts.isEmpty()) {
api.server.scheduleResetTrackersMounting(RESET_SOURCE_NAME, (delay * 1000).toLong())
api.server.scheduleResetTrackersMounting(RESET_SOURCE_NAME, (delay * 1000).toLong(), tx = tx)
} else {
api.server.scheduleResetTrackersMounting(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList())
api.server.scheduleResetTrackersMounting(RESET_SOURCE_NAME, (delay * 1000).toLong(), bodyParts.toList(), tx = tx)
}
}
}
fun sendResetStatusResponse(resetType: Int, status: Int, bodyParts: List<Int>? = null, progress: Int = 0, duration: Int = 0) {
val fbb = FlatBufferBuilder(32)
fun sendResetStatusResponse(resetType: Int, status: Int, tx: TransactionInfo? = null, bodyParts: List<Int>? = null, progress: Int = 0, duration: Int = 0) {
fun buildMessage(txId: Long?): ByteBuffer {
val fbb = FlatBufferBuilder(32)
val bodyPartsOffset = if (bodyParts != null) ResetResponse.createBodyPartsVector(fbb, bodyParts.map { it.toByte() }.toByteArray()) else 0
val bodyPartsOffset = bodyParts?.let {
ResetResponse.createBodyPartsVector(
fbb,
bodyParts.map { it.toByte() }.toByteArray(),
)
} ?: 0
ResetResponse.startResetResponse(fbb)
ResetResponse.addResetType(fbb, resetType)
ResetResponse.addStatus(fbb, status)
if (bodyPartsOffset >= 0) {
ResetResponse.addBodyParts(fbb, bodyPartsOffset)
ResetResponse.startResetResponse(fbb)
ResetResponse.addResetType(fbb, resetType)
ResetResponse.addStatus(fbb, status)
if (bodyPartsOffset >= 0) {
ResetResponse.addBodyParts(fbb, bodyPartsOffset)
}
ResetResponse.addProgress(fbb, progress)
ResetResponse.addDuration(fbb, duration)
val update = ResetResponse.endResetResponse(fbb)
val outbound = rpcHandler.createRPCMessage(fbb, RpcMessage.ResetResponse, update, txId)
fbb.finish(outbound)
return fbb.dataBuffer()
}
ResetResponse.addProgress(fbb, progress)
ResetResponse.addDuration(fbb, duration)
val update = ResetResponse.endResetResponse(fbb)
val outbound = rpcHandler.createRPCMessage(fbb, RpcMessage.ResetResponse, update)
fbb.finish(outbound)
this.forAllListeners(
Consumer { conn: GenericConnection ->
conn.send(fbb.dataBuffer())
},
)
tx?.let { tx ->
tx.conn.send(buildMessage(tx.id))
}
buildMessage(null).let {
this.forAllListeners(
Consumer { conn: GenericConnection ->
if (tx == null || tx.conn != conn) {
conn.send(it)
}
},
)
}
}
fun onClearMountingResetRequest(
@@ -113,12 +139,12 @@ class RPCResetHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : ResetL
api.server.clearTrackersMounting(RESET_SOURCE_NAME)
}
override fun onStarted(resetType: Int, bodyParts: List<Int>?, progress: Int, duration: Int) {
sendResetStatusResponse(resetType, ResetStatus.STARTED, bodyParts, progress, duration)
override fun onStarted(resetType: Int, tx: TransactionInfo?, bodyParts: List<Int>?, progress: Int, duration: Int) {
sendResetStatusResponse(resetType, ResetStatus.STARTED, tx, bodyParts, progress, duration)
}
override fun onFinished(resetType: Int, bodyParts: List<Int>?, duration: Int) {
sendResetStatusResponse(resetType, ResetStatus.FINISHED, bodyParts, duration, duration)
override fun onFinished(resetType: Int, tx: TransactionInfo?, bodyParts: List<Int>?, duration: Int) {
sendResetStatusResponse(resetType, ResetStatus.FINISHED, tx, bodyParts, duration, duration)
}
fun forAllListeners(action: Consumer<in GenericConnection?>?) {
@@ -421,6 +421,7 @@ fun createSettingsResponse(fbb: FlatBufferBuilder, server: VRServer): Int {
server.configManager.vrConfig.stayAlignedConfig,
),
createHIDSettings(fbb, server.configManager.vrConfig.hidConfig),
0,
)
}
@@ -47,6 +47,7 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
bridge.changeShareSettings(TrackerRole.LEFT_HAND, req.steamVrTrackers().leftHand())
bridge.changeShareSettings(TrackerRole.RIGHT_HAND, req.steamVrTrackers().rightHand())
bridge.setAutomaticSharedTrackers(req.steamVrTrackers().automaticTrackerToggle())
sendSteamVRUpdatedSettings(api, rpcHandler)
}
}
@@ -376,7 +377,7 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
val settings = SettingsResponse
.createSettingsResponse(
fbb,
createSteamVRSettings(fbb, bridge), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
createSteamVRSettings(fbb, bridge), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
)
val outbound =
rpcHandler.createRPCMessage(fbb, RpcMessage.SettingsResponse, settings)
@@ -1,17 +1,18 @@
package dev.slimevr.reset
import dev.slimevr.protocol.rpc.TransactionInfo
import java.util.concurrent.CopyOnWriteArrayList
import java.util.function.Consumer
class ResetHandler {
private val listeners: MutableList<ResetListener> = CopyOnWriteArrayList()
fun sendStarted(resetType: Int, bodyParts: List<Int>? = null, progress: Int = 0, duration: Int = 0) {
this.listeners.forEach { listener: ResetListener -> listener.onStarted(resetType, bodyParts, progress, duration) }
fun sendStarted(resetType: Int, tx: TransactionInfo? = null, bodyParts: List<Int>? = null, progress: Int = 0, duration: Int = 0) {
this.listeners.forEach { listener: ResetListener -> listener.onStarted(resetType, tx, bodyParts, progress, duration) }
}
fun sendFinished(resetType: Int, bodyParts: List<Int>? = null, duration: Int) {
this.listeners.forEach { listener: ResetListener -> listener.onFinished(resetType, bodyParts, duration) }
fun sendFinished(resetType: Int, tx: TransactionInfo? = null, bodyParts: List<Int>? = null, duration: Int) {
this.listeners.forEach { listener: ResetListener -> listener.onFinished(resetType, tx, bodyParts, duration) }
}
fun addListener(listener: ResetListener) {
@@ -1,7 +1,9 @@
package dev.slimevr.reset
interface ResetListener {
fun onStarted(resetType: Int, bodyParts: List<Int>? = null, progress: Int, duration: Int)
import dev.slimevr.protocol.rpc.TransactionInfo
fun onFinished(resetType: Int, bodyParts: List<Int>? = null, duration: Int)
interface ResetListener {
fun onStarted(resetType: Int, tx: TransactionInfo?, bodyParts: List<Int>? = null, progress: Int, duration: Int)
fun onFinished(resetType: Int, tx: TransactionInfo?, bodyParts: List<Int>? = null, duration: Int)
}
@@ -171,6 +171,13 @@ class SkeletonConfigManager(
humanPoseManager?.updateNodeOffset(nodeOffset, offset)
}
// Divides total finger length over anatomical ratios
private fun phalanxLengthDivider(thirdOfTotal: Float, ratio: Float): Float {
val phalanxTotal = thirdOfTotal * 3f
val unit = phalanxTotal / PHALANX_SUM
return unit * ratio
}
fun computeNodeOffset(nodeOffset: BoneType) {
when (nodeOffset) {
BoneType.HEAD -> setNodeOffset(nodeOffset, 0f, 0f, getOffset(SkeletonConfigOffsets.HEAD))
@@ -303,50 +310,83 @@ class SkeletonConfigManager(
0f,
)
BoneType.LEFT_THUMB_METACARPAL, BoneType.LEFT_THUMB_PROXIMAL, BoneType.LEFT_THUMB_DISTAL,
BoneType.RIGHT_THUMB_METACARPAL, BoneType.RIGHT_THUMB_PROXIMAL, BoneType.RIGHT_THUMB_DISTAL,
-> setNodeOffset(
nodeOffset,
0f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.1f,
)
BoneType.LEFT_THUMB_METACARPAL, BoneType.RIGHT_THUMB_METACARPAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
val segY = phalanxLengthDivider(thirdOfTotal, PROXIMAL_RATIO)
setNodeOffset(nodeOffset, 0f, -segY, -(segY * 0.5f))
}
BoneType.LEFT_INDEX_PROXIMAL, BoneType.LEFT_INDEX_INTERMEDIATE, BoneType.LEFT_INDEX_DISTAL,
BoneType.RIGHT_INDEX_PROXIMAL, BoneType.RIGHT_INDEX_INTERMEDIATE, BoneType.RIGHT_INDEX_DISTAL,
-> setNodeOffset(
nodeOffset,
0f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.25f,
0f,
)
BoneType.LEFT_THUMB_PROXIMAL, BoneType.RIGHT_THUMB_PROXIMAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
val segY = phalanxLengthDivider(thirdOfTotal, INTERMEDIATE_RATIO)
setNodeOffset(nodeOffset, 0f, -segY, -(segY * 0.5f))
}
BoneType.LEFT_MIDDLE_PROXIMAL, BoneType.LEFT_MIDDLE_INTERMEDIATE, BoneType.LEFT_MIDDLE_DISTAL,
BoneType.RIGHT_MIDDLE_PROXIMAL, BoneType.RIGHT_MIDDLE_INTERMEDIATE, BoneType.RIGHT_MIDDLE_DISTAL,
-> setNodeOffset(
nodeOffset,
0f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.3f,
0f,
)
BoneType.LEFT_THUMB_DISTAL, BoneType.RIGHT_THUMB_DISTAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
val segY = phalanxLengthDivider(thirdOfTotal, DISTAL_RATIO)
setNodeOffset(nodeOffset, 0f, -segY, -(segY * 0.5f))
}
BoneType.LEFT_RING_PROXIMAL, BoneType.LEFT_RING_INTERMEDIATE, BoneType.LEFT_RING_DISTAL,
BoneType.RIGHT_RING_PROXIMAL, BoneType.RIGHT_RING_INTERMEDIATE, BoneType.RIGHT_RING_DISTAL,
-> setNodeOffset(
nodeOffset,
0f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.28f,
0f,
)
BoneType.LEFT_INDEX_PROXIMAL, BoneType.RIGHT_INDEX_PROXIMAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.25f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, PROXIMAL_RATIO), 0f)
}
BoneType.LEFT_LITTLE_PROXIMAL, BoneType.LEFT_LITTLE_INTERMEDIATE, BoneType.LEFT_LITTLE_DISTAL,
BoneType.RIGHT_LITTLE_PROXIMAL, BoneType.RIGHT_LITTLE_INTERMEDIATE, BoneType.RIGHT_LITTLE_DISTAL,
-> setNodeOffset(
nodeOffset,
0f,
-getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f,
0f,
)
BoneType.LEFT_INDEX_INTERMEDIATE, BoneType.RIGHT_INDEX_INTERMEDIATE -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.25f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, INTERMEDIATE_RATIO), 0f)
}
BoneType.LEFT_INDEX_DISTAL, BoneType.RIGHT_INDEX_DISTAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.25f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, DISTAL_RATIO), 0f)
}
BoneType.LEFT_MIDDLE_PROXIMAL, BoneType.RIGHT_MIDDLE_PROXIMAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.3f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, PROXIMAL_RATIO), 0f)
}
BoneType.LEFT_MIDDLE_INTERMEDIATE, BoneType.RIGHT_MIDDLE_INTERMEDIATE -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.3f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, INTERMEDIATE_RATIO), 0f)
}
BoneType.LEFT_MIDDLE_DISTAL, BoneType.RIGHT_MIDDLE_DISTAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.3f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, DISTAL_RATIO), 0f)
}
BoneType.LEFT_RING_PROXIMAL, BoneType.RIGHT_RING_PROXIMAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.28f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, PROXIMAL_RATIO), 0f)
}
BoneType.LEFT_RING_INTERMEDIATE, BoneType.RIGHT_RING_INTERMEDIATE -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.28f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, INTERMEDIATE_RATIO), 0f)
}
BoneType.LEFT_RING_DISTAL, BoneType.RIGHT_RING_DISTAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.28f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, DISTAL_RATIO), 0f)
}
BoneType.LEFT_LITTLE_PROXIMAL, BoneType.RIGHT_LITTLE_PROXIMAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, PROXIMAL_RATIO), 0f)
}
BoneType.LEFT_LITTLE_INTERMEDIATE, BoneType.RIGHT_LITTLE_INTERMEDIATE -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, INTERMEDIATE_RATIO), 0f)
}
BoneType.LEFT_LITTLE_DISTAL, BoneType.RIGHT_LITTLE_DISTAL -> {
val thirdOfTotal = getOffset(SkeletonConfigOffsets.HAND_Y) * 0.2f
setNodeOffset(nodeOffset, 0f, -phalanxLengthDivider(thirdOfTotal, DISTAL_RATIO), 0f)
}
else -> {}
}
@@ -541,6 +581,11 @@ class SkeletonConfigManager(
}
companion object {
private const val PHALANX_SUM = 4.6f
private const val DISTAL_RATIO = 1.0f
private const val INTERMEDIATE_RATIO = 1.3f
private const val PROXIMAL_RATIO = 2.3f
val HEIGHT_OFFSETS: Array<SkeletonConfigOffsets> = arrayOf(
SkeletonConfigOffsets.NECK,
SkeletonConfigOffsets.UPPER_CHEST,
@@ -92,8 +92,6 @@ class LegTweaks(private val skeleton: HumanSkeleton) {
var toeSnapEnabled = false
var footPlantEnabled = false
private var active = false
private var rightLegActive = false
private var leftLegActive = false
private var leftFramesLocked = 0
private var rightFramesLocked = 0
private var leftFramesUnlocked = 0
@@ -200,53 +198,6 @@ class LegTweaks(private val skeleton: HumanSkeleton) {
// correct for skating if needed (Skating correction)
if (skatingCorrectionEnabled) correctSkating()
// determine if either leg is in a position to activate or
// deactivate
// (use the buffer to get the positions before corrections)
val leftFootDif = abs(
(bufferHead.leftFootPosition - leftFootPosition).y,
)
val rightFootDif = abs(
(bufferHead.rightFootPosition - rightFootPosition).y,
)
if (!active && leftFootDif < NEARLY_ZERO) {
leftLegActive = false
} else if (active && leftFootDif < NEARLY_ZERO) {
leftLegActive = true
}
if (!active && rightFootDif < NEARLY_ZERO) {
rightLegActive = false
} else if (active && rightFootDif < NEARLY_ZERO) {
rightLegActive = true
}
// restore the y positions of inactive legs
if (!leftLegActive) {
leftFootPosition = Vector3(
leftFootPosition.x,
bufferHead.leftFootPosition.y,
leftFootPosition.z,
)
leftKneePosition = Vector3(
leftKneePosition.x,
bufferHead.leftKneePosition.y,
leftKneePosition.z,
)
}
if (!rightLegActive) {
rightFootPosition = Vector3(
rightFootPosition.x,
bufferHead.rightFootPosition.y,
rightFootPosition.z,
)
rightKneePosition = Vector3(
rightKneePosition.x,
bufferHead.rightKneePosition.y,
rightKneePosition.z,
)
}
// calculate the correction for the knees
if (initialized) solveLowerBody()
@@ -64,6 +64,7 @@ object StayAlignedDefaults {
set(IMUType.LSM6DSR, YAW_CORRECTION_IMU_GOOD)
set(IMUType.ICM45686, YAW_CORRECTION_IMU_GOOD)
set(IMUType.ICM45605, YAW_CORRECTION_IMU_GOOD)
set(IMUType.ICM55686, YAW_CORRECTION_IMU_GOOD)
}
// Assume any new IMUs are at least OK, or else we wouldn't be writing firmware to
@@ -97,9 +97,15 @@ class Tracker @JvmOverloads constructor(
* NOT the same as hasRotation (other data types emulate rotation)
*/
val trackerDataType: TrackerDataType = TrackerDataType.ROTATION,
/**
* Set status when tracker is sleeping
*/
val usesSleep: Boolean = false,
) {
private val timer = BufferedTimer(1f)
private var timeAtLastUpdate: Long = System.currentTimeMillis()
private var timeScheduledSleep: Long = Long.MAX_VALUE
private var _rotation = Quaternion.IDENTITY
// IMU: +z forward, +x left, +y up
@@ -261,6 +267,16 @@ class Tracker @JvmOverloads constructor(
}
}
if (usesSleep && status != TrackerStatus.DISCONNECTED) {
if (System.currentTimeMillis() > timeScheduledSleep) {
status = TrackerStatus.TIMED_OUT
}
// Want to also use timeout but without following disconnect
if (System.currentTimeMillis() - timeAtLastUpdate > TIMEOUT_MS) {
status = TrackerStatus.TIMED_OUT
}
}
filteringHandler.update()
yawResetSmoothing.tick(deltaTime)
stayAligned.update()
@@ -450,4 +466,11 @@ class Tracker @JvmOverloads constructor(
fun resetFilteringQuats(reference: Quaternion) {
filteringHandler.resetMovingAverage(getAdjustedRotation(), reference)
}
/**
* Sets time in future if a tracker is expected to sleep
*/
fun setSleepTime(time: Long) {
this.timeScheduledSleep = time
}
}
@@ -26,13 +26,40 @@ import kotlin.math.sqrt
class HIDCommon {
companion object {
const val HID_TRACKER_RECEIVER_VID = 0x1209
const val HID_TRACKER_RECEIVER_PID = 0x7690
const val HID_RECEIVER_PID = 0x7690
const val HID_TRACKER_PID = 0x7692
const val GESTURES_INC_VID = 0x4E76
const val GESTURES_INC_PID_D2XX = 0xD200
const val GESTURES_INC_PID_D2XX_MASK = 0xFF00
const val PACKET_SIZE = 16
private val AXES_OFFSET = fromRotationVector(-FastMath.HALF_PI, 0f, 0f)
data class HidProductRule(
val vendorId: Int,
val productId: Int,
val productMask: Int = 0xFFFF,
)
val receiverProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_RECEIVER_PID),
HidProductRule(GESTURES_INC_VID, GESTURES_INC_PID_D2XX, GESTURES_INC_PID_D2XX_MASK),
)
val trackerProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_TRACKER_PID),
)
private fun matchesProductRule(vendorId: Int, productId: Int, rule: HidProductRule): Boolean = vendorId == rule.vendorId && (productId and rule.productMask) == rule.productId
fun allProductRules(): List<HidProductRule> = (receiverProductRules + trackerProductRules)
fun matchesReceiver(vendorId: Int, productId: Int): Boolean = receiverProductRules.any { matchesProductRule(vendorId, productId, it) }
fun matchesTracker(vendorId: Int, productId: Int): Boolean = trackerProductRules.any { matchesProductRule(vendorId, productId, it) }
fun matchesAny(vendorId: Int, productId: Int): Boolean = allProductRules().any { matchesProductRule(vendorId, productId, it) }
fun deviceIdLookup(
hidDevices: MutableList<HIDDevice>,
hidSerialNumber: String?,
@@ -95,6 +122,7 @@ class HIDCommon {
allowMounting = true,
usesTimeout = false,
magStatus = magStatus,
usesSleep = true,
)
// usesTimeout false because HID trackers aren't "Disconnected" unless receiver is physically removed probably
// TODO: Could tracker maybe use "Timed out" status without marking as disconnecting?
@@ -138,8 +166,16 @@ class HIDCommon {
return
}
if (tracker.status == TrackerStatus.TIMED_OUT) {
// If tracker was previously sleeping/shutdown, reset the sleep time and status
// If there is some other error, the relevant packet should set it a little later
tracker.setSleepTime(Long.MAX_VALUE)
tracker.status = TrackerStatus.OK
}
// Packet data
var runtime: Long? = null
var timeout: Int? = null
var batt: Int? = null
var batt_v: Int? = null
var temp: Int? = null
@@ -238,11 +274,13 @@ class HIDCommon {
6 -> { // data
button = dataReceived[i + 2].toUByte().toInt()
timeout = dataReceived[i + 3].toUByte().toInt() shl 8 or dataReceived[i + 4].toUByte().toInt()
rssi = dataReceived[i + 15].toUByte().toInt()
}
7 -> { // reduced precision quat and accel with data
button = dataReceived[i + 2].toUByte().toInt()
timeout = dataReceived[i + 3].toUByte().toInt() shl 8 or dataReceived[i + 4].toUByte().toInt()
// quaternion is quantized as exponential map
// X = 10 bits, Y/Z = 11 bits
val buffer = ByteBuffer.wrap(dataReceived, i + 5, 4)
@@ -264,20 +302,28 @@ class HIDCommon {
// Assign data
if (runtime != null && runtime >= 0) {
// -1: Not known (e.g. not yet calculated after wake up, reusing known value is okay), 0: N/A (e.g. charging)
tracker.batteryRemainingRuntime = runtime
}
// -1: Not known (e.g. not yet calculated after wake up, reusing known value is okay), 0: N/A (e.g. charging)
if (timeout != null && timeout != 0) {
// 0 or 65535: disable timeout
if (timeout == 65535) {
tracker.setSleepTime(Long.MAX_VALUE)
} else {
tracker.setSleepTime(System.currentTimeMillis() + timeout)
}
}
if (batt != null) {
tracker.batteryLevel = if (batt == 128) 1f else (batt and 127).toFloat()
// Server displays 0% if received 255 or -1, otherwise 0 will hide battery icon
tracker.batteryLevel = if (batt == 128) -1f else (batt and 127).toFloat()
}
// Server still won't display battery at 0% at all
if (batt_v != null) {
tracker.batteryVoltage = (batt_v.toFloat() + 245f) / 100f
}
if (temp != null) {
// Range 1 - 255 -> -38.5 - +88.5 C
tracker.temperature = if (temp > 0) temp.toFloat() / 2f - 39f else null
}
// Range 1 - 255 -> -38.5 - +88.5 C
if (brd_id != null) {
val boardType = BoardType.getById(brd_id.toUInt())
if (boardType != null) {
@@ -291,13 +337,22 @@ class HIDCommon {
}
}
if (button != null) {
// TODO: May support multiple buttons in the future? For now, mask first 2 bits
// Tracker sends button state once button has been released and double press/hold timeout elapsed
// The received state represents the action to be performed, only if it has changed
if (tracker.button == null) {
tracker.button = 0
}
if (button != tracker.button) {
button = button and tracker.button!!.inv()
// Nothing to do now..
val changed: Int = button and tracker.button!!.inv()
if (changed shr 0 and 3 != 0) {
// 0: reset, 1: single press, 2: double press, 3: N/A (held, not available on shared button)
// TODO: For now, just send a tap for any action
val action: Int = button shr 0 and 3
if (action != 0) {
VRServer.instance.tapSetupHandler.sendTap(tracker)
}
}
tracker.button = button
}
if (fw_date != null) {
val firmwareYear = 2020 + (fw_date shr 9 and 127)
@@ -377,6 +432,8 @@ class HIDCommon {
}
if (packetType == 1 || packetType == 2 || packetType == 4 || packetType == 7) {
tracker.dataTick() // only data tick if there is rotation data
} else {
tracker.heartbeat() // else, something received
}
}
}
@@ -20,6 +20,7 @@ enum class IMUType(val id: UInt) {
ICM45686(16u),
ICM45605(17u),
ADC_RESISTANCE(18u),
ICM55686(19u),
DEV_RESERVED(250u),
;
@@ -485,7 +485,18 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
is UDPPacket12BatteryLevel -> connection?.trackers?.values?.forEach {
it.batteryVoltage = packet.voltage
it.batteryLevel = packet.level * 100
// Firmware does not verify the voltage level at all
// Instead guess if a battery is present or not
// Too low or high voltage should mean there is no battery or there is a measurement error
// Some ESP can run at 2.3V, set a limit at 2V
// Below this the tracker is definitely dead if everything is working properly
if (packet.voltage > 2f && packet.voltage < 6f) {
// Assuming floor when converting to int
it.batteryLevel = if (packet.level < 0.01f) -1f else packet.level * 100
} else {
it.batteryLevel = 0f
}
// Server displays 0% if received 255 or -1, otherwise 0 will hide battery icon
}
is UDPPacket13Tap -> {
@@ -8,6 +8,8 @@ import dev.slimevr.games.vrchat.VRCConfigRecommendedValues
import dev.slimevr.games.vrchat.VRCConfigValidity
import dev.slimevr.games.vrchat.VRCConfigValues
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerRole
import dev.slimevr.tracking.trackers.TrackerStatus
import dev.slimevr.tracking.trackers.TrackerUtils
import dev.slimevr.tracking.trackers.udp.TrackerDataType
@@ -86,6 +88,16 @@ class TrackingChecklistManager(private val vrServer: VRServer) : VRCConfigListen
},
)
steps.add(
TrackingChecklistStepT().apply {
id = TrackingChecklistStepId.STEAMVR_HANDS_ENABLED
enabled = false
optional = false
ignorable = false
visibility = TrackingChecklistStepVisibility.WHEN_INVALID
},
)
steps.add(
TrackingChecklistStepT().apply {
id = TrackingChecklistStepId.TRACKER_ERROR
@@ -280,6 +292,17 @@ class TrackingChecklistManager(private val vrServer: VRServer) : VRCConfigListen
it.extraData = null
}
}
val handsEnabled = steamVRBridge.getShareSetting(TrackerRole.LEFT_HAND) || steamVRBridge.getShareSetting(TrackerRole.RIGHT_HAND)
val hasControllers = vrServer.allTrackers.any {
(it.trackerPosition == TrackerPosition.LEFT_HAND || it.trackerPosition == TrackerPosition.RIGHT_HAND) && it.isComputed && !it.isInternal
}
val hasHandTrackers = vrServer.allTrackers.any {
(it.trackerPosition == TrackerPosition.LEFT_HAND || it.trackerPosition == TrackerPosition.RIGHT_HAND) && !it.isComputed
}
updateValidity(TrackingChecklistStepId.STEAMVR_HANDS_ENABLED, !steamvrConnected || !handsEnabled || (!hasControllers && hasHandTrackers)) {
it.enabled = true
}
}
if (vrServer.networkProfileChecker.isSupported) {
@@ -1,5 +1,6 @@
package io.eiren.util
import dev.slimevr.SLIMEVR_IDENTIFIER
import java.io.File
import java.nio.file.Path
import java.util.*
@@ -38,6 +39,12 @@ enum class OperatingSystem(
var dir = System.getenv("SLIMEVR_SOCKET_DIR")
if (dir != null) return dir
if (currentPlatform == LINUX) {
val isPressureVessel = System.getenv("PRESSURE_VESSEL_RUNTIME")?.isNotEmpty() == true
if (isPressureVessel) {
dir = System.getenv("XDG_CONFIG_HOME")?.let { Path(it, SLIMEVR_IDENTIFIER).toString() }
?: System.getenv("HOME")?.let { Path(it, ".local", "share", SLIMEVR_IDENTIFIER).toString() }
if (dir != null) return dir
}
dir = System.getenv("XDG_RUNTIME_DIR")
if (dir != null) return dir
}
@@ -4,9 +4,10 @@ import com.jme3.math.FastMath
import dev.slimevr.VRServer.Companion.getNextLocalTrackerId
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.udp.IMUType
import dev.slimevr.unit.TrackerTestUtils.assertAnglesApproxEqual
import dev.slimevr.unit.TrackerTestUtils.deg
import dev.slimevr.unit.TrackerTestUtils.yaw
import dev.slimevr.unit.TrackerTestUtils.assertAngleEquals
import dev.slimevr.unit.TrackerTestUtils.degYaw
import dev.slimevr.unit.TrackerTestUtils.radToDeg
import dev.slimevr.unit.TrackerTestUtils.radYaw
import io.github.axisangles.ktmath.EulerAngles
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
@@ -26,7 +27,7 @@ class MountingResetTests {
fun testResetAndMounting(): List<DynamicTest> = TrackerTestUtils.directions.flatMap { e ->
TrackerTestUtils.directions.map { m ->
DynamicTest.dynamicTest(
"Full and Mounting Reset Test of Tracker (Expected: ${deg(e)}, reference: ${deg(m)})",
"Full and Mounting Reset Test of Tracker (Expected: ${degYaw(e)}, reference: ${degYaw(m)})",
) {
checkResetMounting(e, m)
}
@@ -56,12 +57,12 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw = yaw(expected)
val resultYaw = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
val expectedYaw = radYaw(expected)
val resultYaw = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
expectedYaw,
resultYaw,
"Resulting mounting yaw after full reset is not equal to reference yaw (${deg(expectedYaw)} vs ${deg(resultYaw)})",
message = "Resulting mounting yaw after full reset is not equal to reference yaw (${radToDeg(expectedYaw)} vs ${radToDeg(resultYaw)})",
)
// Apply full reset and mounting plus offset
@@ -73,12 +74,12 @@ class MountingResetTests {
// it needs to be applied twice
tracker.resetsHandler.resetMounting(reference * reference)
val expectedYaw2 = yaw(expected)
val resultYaw2 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
val expectedYaw2 = radYaw(expected)
val resultYaw2 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
expectedYaw2,
resultYaw2,
"Resulting mounting yaw after full reset with offset is not equal to reference yaw (${deg(expectedYaw2)} vs ${deg(resultYaw2)})",
message = "Resulting mounting yaw after full reset with offset is not equal to reference yaw (${radToDeg(expectedYaw2)} vs ${radToDeg(resultYaw2)})",
)
// Apply yaw reset and mounting
@@ -88,12 +89,12 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw3 = yaw(expected)
val resultYaw3 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
val expectedYaw3 = radYaw(expected)
val resultYaw3 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
expectedYaw3,
resultYaw3,
"Resulting mounting yaw after yaw reset is not equal to reference yaw (${deg(expectedYaw3)} vs ${deg(resultYaw3)})",
message = "Resulting mounting yaw after yaw reset is not equal to reference yaw (${radToDeg(expectedYaw3)} vs ${radToDeg(resultYaw3)})",
)
// Apply yaw reset and mounting plus offset
@@ -106,12 +107,12 @@ class MountingResetTests {
// it needs to be applied twice
tracker.resetsHandler.resetMounting(reference * reference)
val expectedYaw4 = yaw(expected)
val resultYaw4 = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
val expectedYaw4 = radYaw(expected)
val resultYaw4 = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
expectedYaw3,
resultYaw3,
"Resulting mounting yaw after yaw reset with offset is not equal to reference yaw (${deg(expectedYaw4)} vs ${deg(resultYaw4)})",
message = "Resulting mounting yaw after yaw reset with offset is not equal to reference yaw (${radToDeg(expectedYaw4)} vs ${radToDeg(resultYaw4)})",
)
}
@@ -141,23 +142,23 @@ class MountingResetTests {
tracker.setRotation(trackerRot)
tracker.resetsHandler.resetMounting(Quaternion.IDENTITY)
val expectedYaw = yaw(expected)
val resultYaw = yaw(tracker.resetsHandler.mountRotFix)
assertAnglesApproxEqual(
val expectedYaw = radYaw(expected)
val resultYaw = radYaw(tracker.resetsHandler.mountRotFix)
assertAngleEquals(
expectedYaw,
resultYaw,
"Resulting mounting yaw after full reset is not equal to reference yaw (${deg(expectedYaw)} vs ${deg(resultYaw)})",
message = "Resulting mounting yaw after full reset is not equal to reference yaw (${radToDeg(expectedYaw)} vs ${radToDeg(resultYaw)})",
)
tracker.setRotation(reference * reference)
tracker.resetsHandler.resetYaw(reference)
val expectedYaw2 = yaw(reference)
val resultYaw2 = yaw(tracker.getRotation())
assertAnglesApproxEqual(
val expectedYaw2 = radYaw(reference)
val resultYaw2 = radYaw(tracker.getRotation())
assertAngleEquals(
expectedYaw2,
resultYaw2,
"Resulting rotation after yaw reset is not equal to reference yaw (${deg(expectedYaw2)} vs ${deg(resultYaw2)})",
message = "Resulting rotation after yaw reset is not equal to reference yaw (${radToDeg(expectedYaw2)} vs ${radToDeg(resultYaw2)})",
)
}
}
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more