Compare commits

..
124 changed files with 1550 additions and 2866 deletions

No files matched your search

+4 -4
View File
@@ -1,9 +1,9 @@
if ! has nix_direnv_version || ! nix_direnv_version 3.1.1; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.1.1/direnvrc" "sha256-p+fzQdrms/hDa7g+soShAybJNo4bN4SIAeSfqNKgD5I="
if ! has nix_direnv_version || ! nix_direnv_version 2.2.1; then
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.2.1/direnvrc" "sha256-zelF0vLbEl5uaqrfIzbgNzJWGmLzCmYAkInj/LNxvKs="
fi
watch_file package.json
if ! use flake .
nix_direnv_watch_file package.json
if ! use flake . --impure
then
echo "devenv could not be built. The devenv environment was not loaded. Make the necessary changes to devenv.nix and hit enter to try again." >&2
fi
+5 -2
View File
@@ -1,3 +1,6 @@
# Global code owner
* @Eirenliel
# Make everyone be able to approve SolarXR submodule changes
/solarxr-protocol @ButterscotchV @Erimelowo @loucass003
@@ -13,11 +16,11 @@
/gui/src/components/settings/ @Erimelowo @loucass003
# Electron part of the GUI
# Rust part of the GUI
/gui/electron/ @loucass003
# Some server code~
/server/ @ButterscotchV @loucass003 @Erimelowo
/server/ @ButterscotchV @Eirenliel @Erimelowo
/server/src/main/java/dev/slimevr/autobone/ @ButterscotchV
/server/src/main/java/dev/slimevr/poserecorder/ @ButterscotchV
+37
View File
@@ -0,0 +1,37 @@
"Area: Continuous Integration":
- changed-files:
- any-glob-to-any-file: ".github/**"
"Area: Application Protocol":
- changed-files:
- any-glob-to-any-file: ["solarxr-protocol"]
"Area: AutoBone":
- changed-files:
- any-glob-to-any-file: "server/core/src/main/java/dev/slimevr/autobone/**"
"Area: Documentation":
- changed-files:
- any-glob-to-any-file: "**/*.md"
"Area: GUI":
- all:
- changed-files:
- all-globs-to-any-file: ["gui/**/*", "!gui/public/i18n/**/*"]
"Area: Hardware Protocol":
- changed-files:
- any-glob-to-any-file: "server/core/src/main/java/dev/slimevr/tracking/trackers/udp/**"
"Area: Server":
- changed-files:
- any-glob-to-any-file: ["server/**", "*gradle*", "gradle/**"]
"Area: Skeletal Model":
- changed-files:
- any-glob-to-any-file: "server/core/src/main/java/dev/slimevr/tracking/processor/**"
"Area: SteamVR Driver":
- changed-files:
- any-glob-to-any-file: "server/desktop/src/main/java/dev/slimevr/desktop/platform/**"
"Area: Translation":
- changed-files:
- any-glob-to-any-file: "gui/public/i18n/**"
"Area: VMC":
- changed-files:
- any-glob-to-any-file: ["server/core/src/main/java/dev/slimevr/osc/Unity*", "server/core/src/main/java/dev/slimevr/osc/VMC*", "server/core/src/main/java/dev/slimevr/osc/VRM*"]
"Area: VRCOSC":
- changed-files:
- any-glob-to-any-file: ["server/core/src/main/java/dev/slimevr/osc/VRC*"]
+3 -3
View File
@@ -93,7 +93,7 @@ jobs:
with:
submodules: recursive
- name: Set up JDK 17
uses: actions/setup-java@v6
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
@@ -114,7 +114,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 17
uses: actions/setup-java@v6
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
@@ -261,7 +261,7 @@ jobs:
- name: Get tags
run: git fetch --tags origin --recurse-submodules=no --force
- name: Set up JDK 17
uses: actions/setup-java@v6
uses: actions/setup-java@v5
with:
java-version: '17'
distribution: 'adopt'
-36
View File
@@ -1,36 +0,0 @@
name: Test Crowdin Sync (Dry Run)
on:
workflow_dispatch:
inputs:
dry_run:
description: 'Perform a dry run (logs changes without modifying repository)'
type: boolean
default: true
localization_branch:
description: 'Branch to target for translations'
type: string
default: 'l10n_main'
jobs:
test-crowdin:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
submodules: recursive
- name: Test Crowdin Synchronization
uses: crowdin/github-action@v2
with:
upload_sources: true
upload_translations: false
download_translations: true
localization_branch_name: ${{ inputs.localization_branch }}
dry_run: ${{ inputs.dry_run }}
create_pull_request: false
env:
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
CROWDIN_API_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
+22
View File
@@ -0,0 +1,22 @@
# This workflow will triage pull requests and apply a label based on the
# paths that are modified in the pull request.
#
# To use this workflow, you will need to set up a .github/labeler.yml
# file with configuration. For more information, see:
# https://github.com/actions/labeler
name: Labeler
on: [pull_request_target]
jobs:
label:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/labeler@v6
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
+2 -3
View File
@@ -3,7 +3,6 @@ on:
push:
branches:
- pontoon
- l10n_main
jobs:
pull_request:
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
@@ -18,5 +17,5 @@ jobs:
env:
GH_TOKEN: ${{ secrets.PONTOON_BOT_KEY }}
run: |
gh_pr_up() { gh pr create "$@" --draft --base main || gh pr edit "$@"; }
gh_pr_up --title "New translations" --body "Please don't squash me 🥺"
gh_pr_up() { gh pr create "$@" --label "Area: Translation" --base main || gh pr edit "$@"; }
gh_pr_up --title "New Pontoon translations" --body "Please don't squash me 🥺"
+4 -34
View File
@@ -1,44 +1,14 @@
# This workflow will rebase `l10n_main` and `pontoon` with `main` changes, it's for making the
# translation bots not try making commits to main
# This workflow will rebase `pontoon` with `main` changes, it's for making the
# Pontoon bot not try making commits to main
name: Rebase translation branches to main
name: Rebase pontoon branch to main
on:
push:
branches:
- main
jobs:
rebase-l10n:
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v6
with:
ref: l10n_main
submodules: recursive
# Get all the git history for rebasing
fetch-depth: 0
- name: Rebase
run: |
git config --local user.name "slimevr-bot"
git config --local user.email '[email protected]'
git fetch origin main
git rebase origin/main
git submodule update
- name: Push rebase
uses: github-actions-x/[email protected]
with:
github-token: ${{ secrets.PONTOON_BOT_KEY }}
push-branch: "l10n_main"
commit-message: "update"
force-push: "true"
name: "slimevr-bot"
email: "[email protected]"
rebase-pontoon:
rebase:
if: ${{ github.repository == 'SlimeVR/SlimeVR-Server' }}
runs-on: ubuntu-latest
permissions:
+1 -7
View File
@@ -25,9 +25,7 @@
.settings
# Node Stuff
node_modules/
dist/
stats.html
/node_modules
.husky
# kotlin stuff
@@ -35,10 +33,6 @@ stats.html
# ignore gradle build folder
build/
server/desktop/config/
# created by clangd for index cache
.cache/
# direnv has been claimed for Nix usage
.direnv/
-2
View File
@@ -1,7 +1,5 @@
# Contributing to SlimeVR
Please follow general contribution guidelines: [CONTRIBUTING.md](https://github.com/SlimeVR/.github/blob/main/profile/CONTRIBUTING.md).
This document describes essential knowledge required to contribute to the SlimeVR Server.
### Prerequisites
-12
View File
@@ -1,12 +0,0 @@
$ErrorActionPreference = "Stop"
if ((Get-Command "clang-format" -ErrorAction SilentlyContinue) -eq $null) {
$errorObj = New-Object System.IO.FileNotFoundException("clang-format is not installed, please install clang-format via your package manager (e.g. winget/chocolatey/scoop) and re-run the script")
throw $errorObj
}
$SourceFiles = Get-ChildItem -Path '.\src\' -Recurse -Include "*.cpp","*.hpp"
foreach ($file in $SourceFiles) {
Write-Output "Formatting $(Resolve-Path -Relative $file.FullName)"
clang-format -i "$($file.FullName)"
}
-12
View File
@@ -1,12 +0,0 @@
#!/bin/bash
if ! command -v clang-format >/dev/null 2>&1; then
echo "clang-format is not installed, please install clang-format via your package manager (e.g. pacman/apt/dnf/winget) and re-run the script" >&2
exit 1
fi
find src/ \( \
-iname '*.cpp' \
-or -iname '*.hpp' \
\) \
-exec echo Formatting {} \; \
-exec clang-format -i {} \;
+1 -43
View File
@@ -15,13 +15,6 @@
#include "openvr.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <cstdlib>
#endif
namespace fs = std::filesystem;
using namespace std::chrono_literals;
using namespace solarxr_protocol;
@@ -103,35 +96,6 @@ static void signal_handler(int signal) {
int main() {
auto &logger = Logger::get();
// Steam and SteamVR respectively set these environment variables on applications that
// they spawn, which the SteamVR client library (vrclient) will then use as the
// application key when initiating the connection with vrserver. This may not
// be ideal if we are launched by another Steam or OpenVR application, as we will inherit
// their app key through the environment, which means SteamVR will load the wrong bindings.
// A real-world example of this is if someone uses an application such as OpenVR-Autostarter
// to start the SlimeVR Server. OpenVR-Autostarter installs an application manifest with the
// app key "dreiekk.openvr-autostarter", so when it starts SlimeVR Server, which then starts us,
// the STEAMVR_APPKEY="dreiekk.openvr-autostarter" environment variable will be set.
//
// We want SteamVR to use the appkey of the Steam version of our application if possible.
// Unfortunately, we cannot install an application vrmanifest to force the app key,
// as SteamVR requires a binary path in the manifest to consider it valid. We do not want to install
// a manifest with a binary path because we want the SlimeVR Server to start us when the
// driver initiates a connection, rather than getting auto-started by SteamVR.
//
// This is not documented anywhere publicly, see CVRClient::SendConnectMessage in vrclient instead.
constexpr const char *STEAM_APPID = "3245490";
constexpr const char *STEAMVR_APPKEY = "steam.overlay.3245490";
#ifdef _WIN32
SetEnvironmentVariableA("SteamAppId", STEAM_APPID);
SetEnvironmentVariableA("STEAMVR_APPKEY", STEAMVR_APPKEY);
#else
setenv("SteamAppId", STEAM_APPID, 1);
setenv("STEAMVR_APPKEY", STEAMVR_APPKEY, 1);
#endif
try {
SolarXRConnection conn;
std::unique_ptr<vr::IVRSystem, decltype(&shutdown_vr)> sys{ nullptr,
@@ -164,20 +128,14 @@ int main() {
vr::IVRApplications *app = vr::VRApplications();
vr::IVRInput *input = vr::VRInput();
fs::path actionManifestPath;
std::tie(std::ignore, actionManifestPath) = VRUtils::initialiseManifest();
auto [appManifestPath, actionManifestPath] = VRUtils::initialiseManifest();
// We don't want our app key to randomly change if SteamVR decides to honour
// application manifests with no binary path. Instead let it generate an
// app key based on the executable name (system.generated.[lowercase executable name])
#if false
if (auto err = app->AddApplicationManifest(appManifestPath.string().data(), true);
err != vr::VRApplicationError_None) {
logger.error("Failed to add application manifest: {}",
app->GetApplicationsErrorNameFromEnum(err));
return 1;
}
#endif
// SetActionManifestPath may return IPCError if vrserver is busy and takes
// too long to reply, so keep invoking until it succeeds
+6 -17
View File
@@ -1,9 +1,7 @@
#include "solarxr.hpp"
#include "logger.hpp"
#include "paths.hpp"
#include <stdexcept>
#include <string>
#if defined(__linux__)
#include <sys/socket.h>
@@ -16,24 +14,15 @@
namespace fs = std::filesystem;
static std::string getenvSafe(const char *env) {
char *v = getenv(env);
if (v == nullptr)
return {};
return v;
}
fs::path SolarXRConnection::getSocketPath() {
using namespace std::string_view_literals;
#if defined(__linux__)
#define MAKE_SOCKET_PATH(PATH) \
std::make_pair(PATH##sv, getenvSafe(PATH))
std::make_pair(PATH##sv, static_cast<const char *>(getenv(PATH)))
constexpr std::string_view socketName = "SlimeVRRpc";
std::array<std::pair<std::string_view, fs::path>, 5> socketPaths{
std::array<std::pair<std::string_view, const char *>, 4> socketPaths{
MAKE_SOCKET_PATH("SLIMEVR_SOCKET_DIR"),
{ "Steam socket path", Paths::getDataPath() },
MAKE_SOCKET_PATH("XDG_RUNTIME_DIR"),
MAKE_SOCKET_PATH("TMPDIR"),
{ "/tmp", "/tmp" }
@@ -42,17 +31,17 @@ fs::path SolarXRConnection::getSocketPath() {
#undef MAKE_SOCKET_PATH
for (auto [name, path] : socketPaths) {
if (path.empty()) {
if (path == nullptr) {
Logger::get().info(
"Skipping socket directory '{}' because it doesn't exist", name);
"Skipping socket directory {} because it doesn't exist", name);
continue;
}
fs::path socketPath = path / socketName;
fs::path socketPath = fs::path(path) / socketName;
if (fs::exists(socketPath))
return socketPath;
Logger::get().info(
"Skipping socket directory '{}' because socket does not exist", name);
"Skipping socket directory {} because socket does not exist", name);
}
#elif defined(_WIN32)
throw std::logic_error(
+3
View File
@@ -0,0 +1,3 @@
plugins {
id("org.ajoberstar.grgit")
}
-19
View File
@@ -1,19 +0,0 @@
# Crowdin Configuration File
# https://developer.crowdin.com/configuration-file/
project_id_env: CROWDIN_PROJECT_ID
api_token_env: CROWDIN_PERSONAL_TOKEN
files:
- source: /gui/app/public/i18n/en/translation.ftl
translation: /gui/app/public/i18n/%locale%/%original_file_name%
languages_mapping:
locale:
zh-CN: zh-Hans
zh-TW: zh-Hant
nb: nb-NO
nb-NO: nb-NO
sv: sv-SE
sv-SE: sv-SE
en-OWO: en-x-owo
owo: en-x-owo
Generated
+9 -9
View File
@@ -5,11 +5,11 @@
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1778716662,
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
"lastModified": 1762980239,
"narHash": "sha256-8oNVE8TrD19ulHinjaqONf9QWCKK+w4url56cdStMpM=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
"rev": "52a2caecc898d0b46b2b905f058ccc5081f842da",
"type": "github"
},
"original": {
@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1781577229,
"narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=",
"lastModified": 1756787288,
"narHash": "sha256-rw/PHa1cqiePdBxhF66V7R+WAP8WekQ0mCDG4CFqT8Y=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "567a49d1913ce81ac6e9582e3553dd90a955875f",
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
"type": "github"
},
"original": {
@@ -36,11 +36,11 @@
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1777168982,
"narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",
"lastModified": 1761765539,
"narHash": "sha256-b0yj6kfvO8ApcSE+QmA6mUfu8IYG6/uU28OFn4PaC8M=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14",
"rev": "719359f4562934ae99f5443f20aa06c2ffff91fc",
"type": "github"
},
"original": {
+28 -142
View File
@@ -6,159 +6,45 @@
flake-parts.url = "github:hercules-ci/flake-parts";
};
outputs =
inputs@{
self,
nixpkgs,
flake-parts,
...
}:
outputs = inputs@{ self, nixpkgs, flake-parts, ... }:
flake-parts.lib.mkFlake { inherit inputs; } {
systems = [
"aarch64-linux"
"x86_64-linux"
];
systems = [ "x86_64-linux" ];
perSystem =
{ lib, pkgs, ... }:
perSystem = { pkgs, ... }:
let
runtimeLibs = [
pkgs.alsa-lib
pkgs.libpulseaudio
pkgs.at-spi2-atk
pkgs.at-spi2-core
pkgs.cairo
pkgs.cups
pkgs.dbus
pkgs.expat
pkgs.gdk-pixbuf
pkgs.glib
pkgs.gtk3
pkgs.libdrm
pkgs.libgbm
pkgs.libglvnd
pkgs.libnotify
pkgs.libxkbcommon
pkgs.mesa
pkgs.nspr
pkgs.nss
pkgs.pango
pkgs.systemd
pkgs.vulkan-loader
pkgs.wayland
pkgs.libX11
pkgs.libXcomposite
pkgs.libXdamage
pkgs.libXext
pkgs.libXfixes
pkgs.libXrandr
pkgs.libxcb
pkgs.libxshmfence
pkgs.libusb1
pkgs.udev
pkgs.libxcrypt-legacy
];
runtimeLibs = pkgs: (with pkgs; [
jdk17
toolDirectoryName =
if pkgs.stdenv.hostPlatform.isDarwin then
"darwin"
else if pkgs.stdenv.hostPlatform.isLinux then
{
"armv7l-linux" = "linux-arm32";
"aarch64-linux" = "linux-arm64";
"i686-linux" = "linux-ia32";
"x86_64-linux" = "linux-x64";
}
."${pkgs.stdenv.hostPlatform.system}"
else
throw "Unsupported platform";
alsa-lib libpulseaudio at-spi2-atk at-spi2-core cairo cups dbus expat
gdk-pixbuf glib gtk3 libdrm libgbm libglvnd libnotify
libxkbcommon mesa nspr nss pango systemd vulkan-loader
wayland xorg.libX11 xorg.libXcomposite xorg.libXdamage
xorg.libXext xorg.libXfixes xorg.libXrandr xorg.libxcb
xorg.libxshmfence libusb1 udev libxcrypt-legacy
rpm fpm
# we use fuse2
# https://github.com/electron-userland/electron-builder/blob/a6117b3011a105204af8cc2eca02a56976d1ef29/packages/app-builder-lib/src/toolsets/linux.ts#L122
runtime = pkgs.stdenvNoCC.mkDerivation {
name = "electron-builder-appimage-runtime";
src = pkgs.fetchurl {
url = "https://github.com/electron-userland/electron-builder-binaries/releases/download/appimage-12.0.1/appimage-12.0.1.7z";
hash = "sha256-0S/3648dHsRlLKUjen+9yjOswMdYBFY2/spi3G7LjsQ=";
};
# https://github.com/NixOS/nixpkgs/blob/7890ba0a99c064446fe2178ef2f8e3abdf6ec42a/pkgs/by-name/lo/losslesscut-bin/build-from-windows.nix#L20
nativeBuildInputs = [ pkgs.p7zip ];
unpackPhase = ''
runHook preUnpack
7z x "$src"
runHook postUnpack
'';
installPhase = ''
mkdir $out
cp -r -t $out/ \
lib/ \
runtime-*
'';
};
wineWow64Packages.stable
zlib squashfsTools fakeroot libarchive icu
nodejs_22 pnpm pkg-config python3 gcc gnumake binutils git
pkgs.nodePackages.node-gyp-build
]);
appImageTools = pkgs.stdenvNoCC.mkDerivation {
name = "electron-builder-appimage-tools";
dontUnpack = true;
slimeShell = pkgs.buildFHSEnv {
name = "slimevr-env";
targetPkgs = runtimeLibs;
profile = ''
export JAVA_HOME=${pkgs.jdk17}
export PATH="${pkgs.jdk17}/bin:$PATH"
installPhase = ''
mkdir -p "$out/${toolDirectoryName}"
ln -s -t $out/${toolDirectoryName} \
"${pkgs.desktop-file-utils}/bin/desktop-file-validate" \
"${pkgs.squashfsTools}/bin/mksquashfs"
ln -s ${runtime}/runtime-* $out/
ln -s ${runtime}/lib $out/lib
# Tell electron-builder to use system tools instead of downloading them
export USE_SYSTEM_FPM=true
export USE_SYSTEM_MKSQUASHFS=true
'';
runScript = "bash";
};
in
{
devShells.default = pkgs.mkShell {
packages = [
# for running the jar
pkgs.jdk17
# for build
pkgs.electron
pkgs.rpm
pkgs.fpm
pkgs.p7zip
pkgs.wineWow64Packages.stable
pkgs.zlib
pkgs.squashfsTools
pkgs.desktop-file-utils
pkgs.fakeroot
pkgs.libarchive
pkgs.icu
pkgs.nodejs_22
pkgs.pnpm
pkgs.pkg-config
pkgs.python3
pkgs.gcc
pkgs.gnumake
pkgs.binutils
pkgs.git
pkgs.node-gyp-build
];
buildInputs = runtimeLibs;
JAVA_HOME = "${pkgs.jdk17}/lib/openjdk";
USE_SYSTEM_FPM = "true";
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
APPIMAGE_TOOLS_PATH = "${appImageTools}";
#ELECTRON_SKIP_BINARY_DOWNLOAD = true;
#ELECTRON_DIST = "${pkgs.electron.dist}";
#ELECTRON_VERSION = "${pkgs.electron.version}";
# for electron-vite, so `pnpm gui` works
ELECTRON_EXEC_PATH = "${pkgs.electron}/bin/electron";
shellHook = ''
export LD_LIBRARY_PATH="${
lib.makeLibraryPath [
pkgs.systemd
pkgs.hidapi
]
}:$LD_LIBRARY_PATH"
'';
};
devShells.default = slimeShell.env;
};
};
}
+3 -4
View File
@@ -17,7 +17,6 @@ kotlinVersion=2.3.10
spotlessVersion=8.2.1
shadowJarVersion=9.3.1
buildconfigVersion=6.0.7
# Fix gradle leaving multiple java processes running that accumulate and use multiple GBs of RAM
# This mostly seems to affect it when running from console, and then sending a SIGINT (Ctrl + C)
org.gradle.daemon.idletimeout=10000
# We should probably stop using grgit, see:
# https://andrewoberstar.com/posts/2024-04-02-dont-commit-to-grgit/
grgitVersion=5.3.3
+1 -1
View File
@@ -1,5 +1,5 @@
export default {
'**/*.{ts,tsx}': () => 'tsc -p tsconfig.json --noEmit',
'{electron,src}/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
'src/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
'**/*.{js,jsx,ts,tsx,css,scss,md,json}': 'prettier --write',
};
+22 -16
View File
@@ -1,15 +1,21 @@
import { defineConfig } from 'electron-vite';
import { resolve } from 'path';
import rendererConfig from './vite.config'; // Import your existing React config
import { defineConfig } from 'electron-vite'
import { resolve } from 'path'
import rendererConfig from './vite.config' // Import your existing React config
export default defineConfig({
main: {
build: {
rollupOptions: {
input: resolve(__dirname, 'electron/main/index.ts'),
external: ['pino', 'pino-pretty', 'pino-roll', 'commander', 'open'],
},
},
external: [
'pino',
'pino-pretty',
'pino-roll',
'commander',
'open'
]
}
}
},
preload: {
build: {
@@ -17,12 +23,12 @@ export default defineConfig({
input: resolve(__dirname, 'electron/preload/index.ts'),
output: {
format: 'cjs', // Force CJS for the preload
entryFileNames: 'index.js', // Change back to .js
},
},
},
entryFileNames: 'index.js' // Change back to .js
}
}
}
},
renderer: {
renderer: {
...rendererConfig,
root: '.',
build: {
@@ -34,8 +40,8 @@ export default defineConfig({
transformMixedEsModules: true,
},
rollupOptions: {
input: resolve(__dirname, 'index.html'),
},
},
},
});
input: resolve(__dirname, 'index.html')
}
}
}
})
+3 -3
View File
@@ -1,4 +1,4 @@
import { Option, program } from 'commander';
import { Option, program } from "commander";
program
.option('-p, --path <path>', 'set launch path')
@@ -12,10 +12,10 @@ program
// Allow passing arguments to Electron.
.allowExcessArguments();
if (process.platform === 'linux') {
if (process.platform === "linux") {
const noUdevOption = new Option('--no-udev', 'disable udev warning');
noUdevOption.negate = false;
program.addOption(noUdevOption);
program.addOption(noUdevOption)
}
program.parse(process.argv);
+26 -28
View File
@@ -127,14 +127,14 @@ handleIpc(IPC_CHANNELS.LOG, (e, type, ...args) => {
});
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => {
const allowedUrls = [
const allowed_urls = [
/^steam:\/\//,
/^ms-settings:network$/,
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
/^https:\/\/discord\.gg\/slimevr$/,
];
if (allowedUrls.find((a) => url.match(a))) open(url);
if (allowed_urls.find((a) => url.match(a))) open(url);
else logger.error({ url }, 'attempted to open non-whitelisted URL');
});
@@ -156,8 +156,9 @@ handleIpc(IPC_CHANNELS.STORAGE, async (e, { type, method, key, value }) => {
handleIpc(IPC_CHANNELS.DISCORD_PRESENCE, async (e, options) => {
if (options.enable) {
if (!discordPresence.state.ready) await discordPresence.connect();
discordPresence.updateActivity(options.activity, options.iconText);
if (!discordPresence.state.ready)
await discordPresence.connect();
discordPresence.updateActivity(options.activity);
} else if (discordPresence.state.ready) {
discordPresence.destroy();
}
@@ -192,10 +193,6 @@ handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
}
});
handleIpc(IPC_CHANNELS.IS_STEAM, () => {
return options.steam;
});
const defaultWindowState: {
width: number;
height: number;
@@ -211,11 +208,11 @@ const 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;
});
.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;
@@ -248,9 +245,7 @@ function validateWindowState(state: typeof defaultWindowState) {
const saveWindowState = async () => {
await mkdir(dirname(getWindowStateFile()), { recursive: true });
await writeFile(getWindowStateFile(), JSON.stringify(windowState), {
encoding: 'utf-8',
});
await writeFile(getWindowStateFile(), JSON.stringify(windowState), { encoding: 'utf-8' });
};
function createWindow() {
@@ -298,8 +293,10 @@ function createWindow() {
mainWindow.minimize();
break;
case 'toggle-maximize':
if (mainWindow.isMaximized()) mainWindow.unmaximize();
else mainWindow.maximize();
if (mainWindow.isMaximized())
mainWindow.unmaximize();
else
mainWindow.maximize();
break;
}
});
@@ -371,9 +368,9 @@ function createWindow() {
}
const checkEnvironmentVariables = () => {
const disallowedVars = ['_JAVA_OPTIONS', 'JAVA_TOOL_OPTIONS'];
const to_check = ['_JAVA_OPTIONS', 'JAVA_TOOL_OPTIONS'];
const set = disallowedVars.filter((env) => !!process.env[env]);
const set = to_check.filter((env) => !!process.env[env]);
if (set.length > 0) {
dialog.showErrorBox(
'SlimeVR',
@@ -404,9 +401,9 @@ const spawnServer = async () => {
if (!javaBin) {
dialog.showErrorBox(
'SlimeVR',
'Unable to find a compatible Java version, please download Java 17 or higher'
`Couldn't find a compatible Java version, please download Java 17 or higher`
);
app.quit();
app.quit()
return;
}
@@ -428,9 +425,7 @@ const spawnServer = async () => {
? {
...process.env,
APPDATA: app.getPath('appData'),
LOCALAPPDATA: process.env['USERPROFILE']
? path.join(process.env['USERPROFILE'], 'AppData', 'Local')
: undefined,
LOCALAPPDATA: process.env['USERPROFILE'] ? path.join(process.env['USERPROFILE'], 'AppData', 'Local') : undefined,
}
: undefined,
});
@@ -452,11 +447,11 @@ const spawnServer = async () => {
serverProcess.on('error', (err) => {
logger.info({ err }, 'Error launching the java server');
if (!isQuitting) app.quit();
});
})
serverProcess.on('exit', () => {
logger.info('Server process exiting');
});
})
const exited = new Promise<void>((resolve) => serverProcess.once('exit', resolve));
@@ -470,7 +465,8 @@ const spawnServer = async () => {
const createFolders = async () => {
await mkdir(getServerDataFolder(), { recursive: true });
await mkdir(getGuiDataFolder(), { recursive: true });
};
}
let isQuitting = false;
@@ -481,6 +477,7 @@ app.whenReady().then(async () => {
return net.fetch(pathToFileURL(filePath).toString(), { headers: request.headers });
});
try {
await createFolders();
} catch (err) {
@@ -493,6 +490,7 @@ app.whenReady().then(async () => {
return;
}
stores = await initStores();
checkEnvironmentVariables();
const server = await spawnServer();
+1 -2
View File
@@ -28,13 +28,12 @@ export const richPresence = () => {
logger.error(e, 'Unable to connect to Discord RPC');
}
},
updateActivity: (content: string, iconText: string | undefined) => {
updateActivity: (content: string) => {
if (!state.ready) return;
client.user
?.setActivity({
state: content,
largeImageKey: 'icon',
largeImageText: iconText,
startTimestamp: state.start,
})
.catch((e) => {
+8 -15
View File
@@ -1,7 +1,8 @@
import { access, mkdir, readFile, writeFile } from 'fs/promises';
import { dirname, join } from 'path';
import { logger } from './logger';
import { getGuiDataFolder } from './paths';
import { access, mkdir, readFile, writeFile } from "fs/promises";
import { dirname, join } from "path";
import { logger } from "./logger";
import { getGuiDataFolder } from "./paths";
export class CustomStore {
private data: Record<string, unknown> = {};
@@ -14,10 +15,7 @@ export class CustomStore {
this.debounceMs = debounceMs;
}
static async create(
filePath: string,
debounceMs: number = 2000
): Promise<CustomStore> {
static async create(filePath: string, debounceMs: number = 2000): Promise<CustomStore> {
const store = new CustomStore(filePath, debounceMs);
await store.load();
return store;
@@ -30,9 +28,7 @@ export class CustomStore {
this.data = JSON.parse(raw);
} catch {
this.data = {};
logger.warn(
`No existing store found at ${this.filePath}, starting with empty store.`
);
logger.warn(`No existing store found at ${this.filePath}, starting with empty store.`);
}
}
@@ -77,10 +73,7 @@ export class CustomStore {
export async function initStores() {
return {
settings: await CustomStore.create(
join(getGuiDataFolder(), 'gui-settings.dat'),
1000
),
settings: await CustomStore.create(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
}
+19 -18
View File
@@ -1,8 +1,8 @@
import os from 'os';
import { OSStats } from '../preload/interface';
import os from 'os'
import { OSStats } from "../preload/interface";
import { ipcMain, IpcMainInvokeEvent } from 'electron';
import { IpcInvokeMap } from '../shared';
import net from 'net';
import net from 'net'
export const getPlatform = (): OSStats['type'] => {
switch (os.platform()) {
@@ -19,21 +19,21 @@ export const getPlatform = (): OSStats['type'] => {
export const isPortAvailable = (port: number) => {
return new Promise((resolve) => {
const s = net.createServer();
s.once('error', (err) => {
s.close();
if ('code' in err && err['code'] == 'EADDRINUSE') {
resolve(false);
} else {
resolve(false);
}
const s = net.createServer();
s.once('error', (err) => {
s.close();
if ("code" in err && err["code"] == "EADDRINUSE") {
resolve(false);
} else {
resolve(false);
}
});
s.once('listening', () => {
resolve(true);
s.close();
});
s.listen(port);
});
s.once('listening', () => {
resolve(true);
s.close();
});
s.listen(port);
});
};
export function handleIpc<K extends keyof IpcInvokeMap>(
@@ -44,6 +44,7 @@ export function handleIpc<K extends keyof IpcInvokeMap>(
) => ReturnType<IpcInvokeMap[K]>
) {
ipcMain.handle(channel, (event, ...args) => {
return handler(event, ...(args as any));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return handler(event, ...args as any);
});
}
+3 -13
View File
@@ -14,8 +14,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
close: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'close'),
hide: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'hide'),
minimize: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'minimize'),
toggleMaximize: () =>
ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'toggle-maximize'),
toggleMaximize: () => ipcRenderer.invoke(IPC_CHANNELS.WINDOW_ACTIONS, 'toggle-maximize'),
getStorage: async (type) => {
return {
get: (key) =>
@@ -33,19 +32,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
setTranslations: () => {},
openDialog: (options) => ipcRenderer.invoke(IPC_CHANNELS.OPEN_DIALOG, options),
saveDialog: (options) => ipcRenderer.invoke(IPC_CHANNELS.SAVE_DIALOG, options),
openConfigFolder: async () =>
ipcRenderer.invoke(
IPC_CHANNELS.OPEN_FILE,
await ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'config')
),
openLogsFolder: async () =>
ipcRenderer.invoke(
IPC_CHANNELS.OPEN_FILE,
await ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'logs')
),
openConfigFolder: async () => ipcRenderer.invoke(IPC_CHANNELS.OPEN_FILE, await ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'config')),
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),
getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe'),
isSteam: () => ipcRenderer.invoke(IPC_CHANNELS.IS_STEAM),
} satisfies IElectronAPI);
+1 -4
View File
@@ -34,9 +34,7 @@ export type GHReturn = {
| null;
};
export type DiscordPresence =
| { enable: false }
| { enable: true; activity: string; iconText: string | undefined };
export type DiscordPresence = { enable: false } | { enable: true, activity: string }
export interface IElectronAPI {
onServerStatus: (cb: (data: ServerStatusEvent) => void) => () => void;
@@ -59,7 +57,6 @@ export interface IElectronAPI {
ghGet: <T extends GHGet>(options: T) => Promise<GHReturn[T['type']]>;
setPresence: (options: DiscordPresence) => void;
getInstallDir: () => Promise<string>;
isSteam: () => Promise<boolean>;
}
declare global {
@@ -41,7 +41,6 @@ SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="0002", MODE="0660
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0660", TAG+="uaccess"
## SlimeVR
# SlimeNRF Receiver & Tracker
SUBSYSTEM=="usb|tty", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690|7692", MODE="0660", TAG+="uaccess"
# same thing but hidraw
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690|7692", MODE="0660", TAG+="uaccess"
# smol slime dongle
SUBSYSTEM=="usb", ATTR{idVendor}=="1209", ATTR{idProduct}=="7690", MODE="0660", TAG+="uaccess"
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690", MODE="0660", TAG+="uaccess"
+1 -3
View File
@@ -19,8 +19,7 @@ export const IPC_CHANNELS = {
OPEN_FILE: 'open-file',
GET_FOLDER: 'get-folder',
GH_FETCH: 'gh-fetch',
DISCORD_PRESENCE: 'discord-presence',
IS_STEAM: 'is-steam',
DISCORD_PRESENCE: 'discord-presence'
} as const;
export interface IpcInvokeMap {
@@ -49,5 +48,4 @@ export interface IpcInvokeMap {
options: T
) => Promise<GHReturn[T['type']]>;
[IPC_CHANNELS.DISCORD_PRESENCE]: (options: DiscordPresence) => void;
[IPC_CHANNELS.IS_STEAM]: () => boolean;
}
+1 -1
View File
@@ -39,7 +39,7 @@ export const gui = [
...globals.jest,
},
},
files: ['{electron,src}/**/*.{js,jsx,ts,tsx,json}'],
files: ['src/**/*.{js,jsx,ts,tsx,json}'],
plugins: {
'@typescript-eslint': tseslint.plugin,
'@stylistic': stylistic,
+4 -4
View File
@@ -23,9 +23,9 @@
"package:build": "pnpm build && pnpm package",
"preview": "electron-vite preview --config electron.vite.config.ts",
"skipbundler": "vite build",
"lint": "tsc --noEmit && eslint --max-warnings=0 \"{electron,src}/**/*.{js,jsx,ts,tsx,json}\" && prettier --check \"{electron,src}/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
"lint:fix": "tsc --noEmit && eslint --fix --max-warnings=0 \"{electron,src}/**/*.{js,jsx,ts,tsx,json}\" && pnpm run format",
"format": "prettier --write \"{electron,src}/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
"lint": "tsc --noEmit && eslint --max-warnings=0 \"src/**/*.{js,jsx,ts,tsx,json}\" && prettier --check \"src/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
"lint:fix": "tsc --noEmit && eslint --fix --max-warnings=0 \"src/**/*.{js,jsx,ts,tsx,json}\" && pnpm run format",
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
"javaversion-build": "cd electron/resources/java-version/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
"gen:javaversion": "cd electron/resources/java-version/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
"gen:firmware-tool": "openapi-codegen gen firmwareTool"
@@ -68,7 +68,7 @@
"dmg-license": "^1.0.11",
"dotenv": "^16.4.5",
"electron": "^40.3.0",
"electron-builder": "^26.15.0",
"electron-builder": "^26.9.0",
"electron-vite": "^5.0.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "^9.39.4",
+2 -22
View File
@@ -635,9 +635,6 @@ settings-general-fk_settings-enforce_joint_constraints-correct_constraints-descr
settings-general-fk_settings-ik = Position data
settings-general-fk_settings-ik-use_position = Use Position data
settings-general-fk_settings-ik-use_position-description = Enables the use of position data from trackers that provide it. When enabling this make sure to full reset and recalibrate in game.
settings-general-fk_settings-velocity_settings = Velocity Settings
settings-general-fk_settings-velocity_settings-description = Send derived velocity data to SteamVR. Required for Natural Locomotion support. May cause jitter in FBT.
settings-general-fk_settings-velocity_settings-send_derived_velocity = Send derived velocity to driver
settings-general-fk_settings-arm_fk = Arm tracking
settings-general-fk_settings-arm_fk-description = Force arms to be tracked from the headset (HMD) even if positional hand data is available.
settings-general-fk_settings-arm_fk-force_arms = Force arms from HMD
@@ -674,7 +671,7 @@ settings-general-fk_settings-self_localization-description = Mocap Mode allows t
## Gesture control settings (tracker tapping)
settings-general-gesture_control = Gesture control
settings-general-gesture_control-subtitle = Tap based resets
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
settings-general-gesture_control-description = Allows for resets to be triggered by tapping a tracker. The tracker highest up on your torso is used for Yaw Reset, the tracker highest up on your left leg is used for Full Reset, and the tracker highest up on your right leg is used for Mounting Calibration. Taps must occur within the time limit of 0.3 seconds times the number of taps to be recognized.
# This is a unit: 3 taps, 2 taps, 1 tap
# $amount (Number) - Amount of taps (touches to the tracker's case)
settings-general-gesture_control-taps = { $amount ->
@@ -690,15 +687,12 @@ settings-general-gesture_control-trackers = { $amount ->
settings-general-gesture_control-yawResetEnabled = Enable tap to yaw reset
settings-general-gesture_control-yawResetDelay = Yaw reset delay
settings-general-gesture_control-yawResetTaps = Taps for yaw reset
settings-general-gesture_control-yawResetTracker = Yaw reset tracker
settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
settings-general-gesture_control-fullResetDelay = Full reset delay
settings-general-gesture_control-fullResetTaps = Taps for full reset
settings-general-gesture_control-fullResetTracker = Full reset tracker
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
settings-general-gesture_control-mountingResetTracker = Mounting reset tracker
# The number of trackers that can have higher acceleration before a tap is rejected
settings-general-gesture_control-numberTrackersOverThreshold = Trackers over threshold
settings-general-gesture_control-numberTrackersOverThreshold-description = Increase this value if tap detection is not working. Do not increase it above what is needed to make tap detection work as it would cause more false positives.
@@ -788,12 +782,6 @@ settings-serial-factory_reset-warning-cancel = Cancel
settings-serial-serial_select = Select a serial port
settings-serial-auto_dropdown_item = Auto
settings-serial-get_wifi_scan = Get WiFi Scan
settings-serial-enter_pairing = Enter Pairing
settings-serial-exit_pairing = Exit Pairing
settings-serial-calibrate = Calibrate
settings-serial-six_side_calibrate = 6-Side Calibrate
settings-serial-dfu = Enter DFU
settings-serial-meow = Meow!
settings-serial-file_type = Plain text
settings-serial-save_logs = Save To File
settings-serial-send_command = Send
@@ -1661,20 +1649,12 @@ tracking_checklist-MOUNTING_CALIBRATION = Perform a mounting calibration
tracking_checklist-FEET_MOUNTING_CALIBRATION = Perform a feet mounting calibration
tracking_checklist-FULL_RESET = Perform a full reset
tracking_checklist-FULL_RESET-desc = Some trackers need a reset to be performed.
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR disconnected
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-driver_blocked-desc = The driver has been blocked by SteamVR due to a previous SteamVR crash.
tracking_checklist-STEAMVR_DISCONNECTED-driver_disabled-desc = The driver is disabled in SteamVR settings.
tracking_checklist-STEAMVR_DISCONNECTED-driver_not_installed-desc = The driver is not installed.
tracking_checklist-STEAMVR_DISCONNECTED-open = Launch SteamVR
tracking_checklist-STEAMVR_DISCONNECTED-enable = Enable driver
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-STANDABLE_INSTALLED = Standable is installed
tracking_checklist-STANDABLE_INSTALLED-desc =
Standable frequently causes tracking issues when used alongside SlimeVR. Standable should be fully uninstalled in Steam to ensure no issues arise.
You must close SteamVR before uninstalling Standable in Steam.
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 seconds.
tracking_checklist-TRACKER_ERROR = Trackers with Errors
+32 -89
View File
@@ -355,7 +355,6 @@ tracker-table-column-name = Nombre
tracker-table-column-type = Tipo
tracker-table-column-battery = Batería
tracker-table-column-ping = Latencia
tracker-table-column-packet_loss = Pérdida de paquetes
tracker-table-column-tps = TPS
tracker-table-column-temperature = Temp. °C
tracker-table-column-linear-acceleration = Accel. X/Y/Z
@@ -397,36 +396,33 @@ tracker-infos-magnetometer-status-v1 =
[ENABLED] Habilitado
*[NOT_SUPPORTED] No soportado
}
tracker-infos-packet_loss = Pérdida de paquetes
tracker-infos-packets_lost = Paquetes perdidos
tracker-infos-packets_received = Paquetes recibidos
## Tracker settings
tracker-settings-back = Volver a la lista de trackers
tracker-settings-title = Ajustes de los trackers
tracker-settings-back = Volver a la lista de sensores
tracker-settings-title = Ajustes de los sensores
tracker-settings-assignment_section = Asignación
tracker-settings-assignment_section-description = Parte del cuerpo asignado al sensor.
tracker-settings-assignment_section-edit = Editar asignación
tracker-settings-mounting_section = Posición de montura
tracker-settings-mounting_section-description = ¿Dónde está montado el tracker?
tracker-settings-mounting_section-description = ¿Dónde está montado el sensor?
tracker-settings-mounting_section-edit = Editar montura
tracker-settings-drift_compensation_section = Permitir compensación de desviación
tracker-settings-drift_compensation_section-description = ¿Este tracker debería compensar la desviación?
tracker-settings-drift_compensation_section-description = ¿Este sensor deberia compensar la desviación?
tracker-settings-drift_compensation_section-edit = Permitir compensación de desviación
tracker-settings-use_mag = Permitir el uso del magnetómetro en este tracker
# Multiline!
tracker-settings-use_mag-description =
¿Debería este tracker usar el magnetómetro para reducir la desviacion cuando se permite el uso del magnetómetro? <b>¡Por favor, no apagues tu tracker mientras alternas esto!</b>
Primero debes permitir el uso del magnetómetro, <magSetting>haga clic aquí para ir al ajuste</magSetting>.
tracker-settings-use_mag-label = Permitir el uso del magnetómetro
# The .<name> means it's an attribute and it's related to the top key.
# In this case that is the settings for the assignment section.
tracker-settings-name_section = Nombre del tracker
tracker-settings-name_section = Nombre del sensor
tracker-settings-name_section-description = Dale un apodo bonito :)
tracker-settings-name_section-placeholder = Pata izquierda de Manteca
tracker-settings-name_section-label = Nombre del tracker
tracker-settings-name_section-label = Nombre del sensor
tracker-settings-forget = Olvidar tracker
tracker-settings-forget-description = Remueve el tracker del servidor de SlimeVR y lo previene de conectarse hasta que el servidor se reinicie. La configuración del tracker no se perderá.
tracker-settings-forget-label = Olvidar tracker
@@ -448,11 +444,11 @@ tracker-part_card-unassigned = Sin asignar
## Body assignment menu
body_assignment_menu = ¿Dónde quieres que esté este tracker?
body_assignment_menu-description = Selecciona la posición donde quieres asignar este tracker. También puedes escoger administrar todos los trackers al mismo tiempo en vez de uno por uno.
body_assignment_menu = ¿Dónde quieres que esté este sensor?
body_assignment_menu-description = Selecciona la posición donde quieres asignar este sensor. También puedes escoger administrar todos los sensores al mismo tiempo en vez de uno por uno.
body_assignment_menu-show_advanced_locations = Mostrar posiciones de asignación avanzadas
body_assignment_menu-manage_trackers = Administrar todos los trackers
body_assignment_menu-unassign_tracker = Desasignar tracker
body_assignment_menu-manage_trackers = Administrar todos los sensores
body_assignment_menu-unassign_tracker = Desasignar sensor
## Tracker assignment menu
@@ -461,8 +457,8 @@ body_assignment_menu-unassign_tracker = Desasignar tracker
#
# We are using it here because english doesn't require changing the text in each case but
# maybe your language does.
-tracker_selection-part = ¿Qué tracker asignar a tu
tracker_selection_menu-NONE = ¿Qué tracker quieres que esté sin asignar?
-tracker_selection-part = ¿Qué sensor asignar a tu
tracker_selection_menu-NONE = ¿Qué sensor quieres que esté sin asignar?
tracker_selection_menu-HEAD = { -tracker_selection-part } cabeza?
tracker_selection_menu-NECK = { -tracker_selection-part } cuello?
tracker_selection_menu-RIGHT_SHOULDER = { -tracker_selection-part } hombro derecho?
@@ -485,8 +481,8 @@ tracker_selection_menu-LEFT_UPPER_LEG = { -tracker_selection-part } muslo izquie
tracker_selection_menu-LEFT_LOWER_LEG = { -tracker_selection-part } tobillo izquiero?
tracker_selection_menu-LEFT_FOOT = { -tracker_selection-part } pie izquierdo?
tracker_selection_menu-LEFT_CONTROLLER = { -tracker_selection-part } mando izquierdo?
tracker_selection_menu-unassigned = Trackers sin asignar
tracker_selection_menu-assigned = Trackers asignados
tracker_selection_menu-unassigned = Sensores sin asignar
tracker_selection_menu-assigned = Sensores asignados
tracker_selection_menu-dont_assign = No asignar
# This line cares about multilines.
# <b>text</b> means that the text should be bold.
@@ -498,7 +494,7 @@ tracker_selection_menu-neck_warning-cancel = Cancelar
## Mounting menu
mounting_selection_menu = ¿Dónde quieres colocar el tracker?
mounting_selection_menu = ¿Dónde quieres colocar el sensor?
mounting_selection_menu-close = Cerrar
## Sidebar settings
@@ -506,13 +502,13 @@ mounting_selection_menu-close = Cerrar
settings-sidebar-title = Ajustes
settings-sidebar-general = General
settings-sidebar-steamvr = SteamVR
settings-sidebar-tracker_mechanics = Mecánicas del tracker
settings-sidebar-tracker_mechanics = Mecánicas del sensor
settings-sidebar-stay_aligned = Mantente Alineado
settings-sidebar-fk_settings = Ajustes de FK
settings-sidebar-gesture_control = Control de gestos
settings-sidebar-interface = Interfaz
settings-sidebar-osc_router = Router OSC
settings-sidebar-osc_trackers = Trackers OSC de VRChat
settings-sidebar-osc_trackers = Sensores OSC de VRChat
settings-sidebar-osc_vmc = VMC
settings-sidebar-utils = Utilidades
settings-sidebar-serial = Consola serial
@@ -582,12 +578,12 @@ settings-general-tracker_mechanics-drift_compensation-prediction = Compensación
# This cares about multilines
settings-general-tracker_mechanics-drift_compensation-prediction-description =
Predice la desviación horizontal y compensa cuando esta mas allá del rango previamente medido.
Activa esto si el tracker esta girando continuamente en el eje horizontal.
Activa esto si el sensor esta girando continuamente en el eje horizontal.
settings-general-tracker_mechanics-drift_compensation-prediction-label = Compensación mediante la predicción del desvío
settings-general-tracker_mechanics-drift_compensation_warning =
<b>Advertencia:</b> Solo usa la compensación de desviación si necesitas reiniciar
muy seguido (cada ~5-10 minutos).
Algunos IMUs propensos a reinicios frecuentes incluyen:
Joy-Cons, owoTrack y MPU (sin un firmware reciente).
settings-general-tracker_mechanics-drift_compensation_warning-cancel = Cancelar
@@ -604,9 +600,6 @@ settings-general-tracker_mechanics-use_mag_on_all_trackers-description =
Usa el magnetómetro en todos los trackers que tienen un firmware compatible, lo que reduce la desviación en entornos magnéticos estables.
Se puede desactivar por sensor en la configuración del sensor. <b>¡Por favor, no apagues ninguno de los trackers mientras activas esta opción!</b>
settings-general-tracker_mechanics-use_mag_on_all_trackers-label = Usar magnetómetro en trackers
settings-general-tracker_mechanics-trackers_over_usb = Trackers por USB
settings-general-tracker_mechanics-trackers_over_usb-description = Permite recibir datos de trackers HID por USB. ¡Asegúrate de que los trackers conectados tengan <b>conexión por HID</b> activados!
settings-general-tracker_mechanics-trackers_over_usb-enabled-label = Permite a los trackers HID conectarse directamente por USB
settings-stay_aligned = Mantente Alineado
settings-stay_aligned-description = Mantente Alineado reduce el desvío ajustando gradualmente tus trackers para calzar tus poses relajadas.
settings-stay_aligned-setup-label = Configurar Mantente Alineado
@@ -779,9 +772,9 @@ settings-general-interface-discord_presence-message =
settings-interface-behavior-error_tracking = Recopilación de errores a través de Sentry.io
settings-interface-behavior-error_tracking-description_v2 =
<h1>Consientes a la recopilación de datos de errores anonimizados?</h1>
<b>No recopilamos información personal</b> como tu dirección IP o credenciales del Wi-Fi. ¡SlimeVR respeta tu privacidad!
Para proveer la mejor experiencia de usuario, recopilamos reportes de errores anonimizados, métricas de rendimiento, e información del sistema operativo. Esto nos ayuda a detectar errores y problemas con SlimeVR. Estas métricas son recopiladas a través de Sentry.io.
settings-interface-behavior-error_tracking-label = Enviar errores a los desarrolladores
settings-interface-behavior-bvh_directory = Carpeta para guardar grabaciones de BVH
@@ -849,7 +842,7 @@ settings-osc-vrchat-description-v1 =
Cambia los ajustes específicos de los trackers OSC utilizados para enviar
datos de seguimiento a aplicaciones sin SteamVR (ej. VRChat en Quest).
Asegúrate de activar OSC en VRChat a través del menú Acción en OSC > Activado.
Para permitir la recepción de datos del HMD y de los mandos desde VRChat, ve a los ajustes de tu menú principal
Para permitir la recepción de datos del HMD y de los mandos desde VRChat, ve a los ajustes de tu menú principal
en Tracking & IK > Permitir el envío de datos OSC de seguimiento de RV de cabeza y muñeca.
settings-osc-vrchat-enable = Habilitar
settings-osc-vrchat-enable-description = Habilita el envio y recibo de datos.
@@ -974,51 +967,15 @@ onboarding-setup_warning =
onboarding-setup_warning-skip = Saltar configuración
onboarding-setup_warning-cancel = Continuar configuración
## Quiz
onboarding-quiz_continue = Continuar
onboarding-quiz_back = Atrás
onboarding-quiz-more_sets_modal-title = ¿Has conectado todos tus trackers?
onboarding-quiz-more_sets_modal-desc = Si tienes sets de diferentes modelos, ¡los podemos conectar ahora!
onboarding-quiz-more_sets_modal-confirm = He conectado todos mis trackers
onboarding-quiz-more_sets_modal-cancel = Quiero conectar mas trackers
onboarding-quiz-slimeset-title = ¿Que tipo de trackers estás conectando?
onboarding-quiz-slimeset-description = Si tienes múltiples sets, se te preguntará de nuevo más adelante en el proceso
onboarding-quiz-slimeset-official-sets = Trackers SlimeVR Oficiales
onboarding-quiz-slimeset-thirdparty-sets = Trackers DIY o de terceros
onboarding-quiz-slimeset-answer-regular = SlimeVR V1.0 y V1.2
onboarding-quiz-slimeset-answer-butterfly = Mariposa
onboarding-quiz-usage-title = ¿Para que usas tus trackers?
onboarding-quiz-usage-description = Si planeas usar SlimeVR para múltiples propósitos, puedes cambiar los ajustes afectados más adelante.
onboarding-quiz-usage-answer-VRC = Juegos VR (por ejemplo, VRChat)
onboarding-quiz-usage-answer-mocap_vtubing = Mocap y VTubing
onboarding-quiz-runtime-title = ¿Ejecutas los juegos por SteamVR o directamente del casco (independiente)?
onboarding-quiz-runtime-answer-steamvr = SteamVR
onboarding-quiz-runtime-answer-standalone = Independiente
onboarding-quiz-mocap_preferences-title = Preferencias de Mocap
onboarding-quiz-mocap_preferences-desc = Especifica cómo planeas usar SlimeVR para mocap o VTubing
onboarding-quiz-mocap_preferences-playspace-title = ¿Cuál es tu espacio de juego?
onboarding-quiz-mocap_preferences-playspace-desc = Si estás de pie, SlimeVR intentará trackear el movimiento al caminar en vez de anclarte en un lugar.
onboarding-quiz-mocap_preferences-playspace-sitting = Sentado
onboarding-quiz-mocap_preferences-playspace-standing = De pie
onboarding-quiz-mocap_preferences-vrm_model-title = ¿Tienes un modelo VRM? (Opcional)
onboarding-quiz-mocap_preferences-vrm_model-desc = Cargar un modelo VRM mejorará la calidad de trackeo y la compatibilidad con aplicaciones que usan VMC.
onboarding-quiz-mocap_preferences-head_tracker-title = ¿Tienes un tracker o un casco VR en tu cabeza?
onboarding-quiz-mocap_preferences-head_tracker-yes = Sí
onboarding-quiz-mocap_preferences-head_tracker-no = No
onboarding-quiz-mocap_preferences-head_tracker_location-title = ¿Donde se encuentra el tracker de cabeza?
onboarding-quiz-mocap_preferences-head_tracker_location-forehead = Frente
onboarding-quiz-mocap_preferences-head_tracker_location-face = Cara
## Wi-Fi setup
onboarding-wifi_creds-back-v2 = Volver a la introducción
onboarding-wifi_creds-back = Volver a la introducción
onboarding-wifi_creds-v2 = Trackers utilizando Wi-Fi
# This cares about multilines
onboarding-wifi_creds-description-v2 =
La mayoría de trackers (como los trackers oficiales de SlimeVR) utilizan Wi-Fi para conectar al servidor.
Por favor utiliza las credenciales de la red Wi-Fi donde tu dispositivo esta actualmente conectado.
¡Asegúrate de utilizar una conexión Wi-Fi 2.4Ghz para tus trackers!
onboarding-wifi_creds-skip = Saltar ajustes de Wi-Fi
onboarding-wifi_creds-submit = ¡Enviar!
@@ -1043,27 +1000,22 @@ onboarding-reset_tutorial-skip = Saltar paso
# Cares about multiline
onboarding-reset_tutorial-0 =
Toca { $taps } veces el tracker resaltado para activar el reinicio horizontal.
Esto va a hacer que tus sensores miren para la misma dirección que tu HMD.
# Cares about multiline
onboarding-reset_tutorial-1 =
Toca { $taps } veces el tracker resaltado para activar el reinicio completo.
Se requiere que estés de pie (pose en i). Esto tiene una demora de 3 segundos (configurable) antes de que realmente suceda.
Esto reinicia completamente la posición y rotación de todos tus trackers. Debería de arreglar la mayoría de los problemas.
# Cares about multiline
onboarding-reset_tutorial-2 =
Toca { $taps } veces el tracker resaltado para activar el reinicio de montura.
El reinicio de montura ayuda en como tus sensores están puestos en tu cuerpo, ya que si los movistes o cambiaste para donde están orientados bastante, esto debería de ayudar.
Requiere que estas en una pose como que estás esquiando, como se muestra en el tutorial de montura automática y tenes un retraso de 3 segundos (configurable) antes de que actualmente suceda.
## Install info
install-info_udev-rules_modal_button = Cerrar
install-info_udev-rules_modal-dont-show-again_checkbox = No mostrar de nuevo
## Setup start
onboarding-home = Bienvenido a SlimeVR
@@ -1407,7 +1359,6 @@ onboarding-user_height-description = Necesitamos tu altura para calcular tus pro
onboarding-user_height-need_head_tracker = Un casco y controles con rastreo posicional son requeridos para realizar la calibración.
onboarding-user_height-calculate = Calcular mi altura automáticamente
onboarding-user_height-next_step = Continuar y guardar
onboarding-user_height-prev_step = Atrás
onboarding-user_height-manual-proportions = Proporciones Manuales
onboarding-user_height-calibration-title = Progreso de Calibración
onboarding-user_height-calibration-RECORDING_FLOOR = Toca el suelo con la punta de tu control
@@ -1461,7 +1412,6 @@ onboarding-stay_aligned-previous_step = Atrás
onboarding-stay_aligned-next_step = Siguiente
onboarding-stay_aligned-restart = Reiniciar
onboarding-stay_aligned-done = Hecho
onboarding-stay_aligned-manual_mounting-done = Hecho
## Home
@@ -1512,9 +1462,6 @@ firmware_tool-select_source-firmware = Fuente del Firmware
firmware_tool-select_source-version = Versión del Firmware
firmware_tool-select_source-official = Oficial
firmware_tool-select_source-dev = Desarrollo
firmware_tool-select_source-not_selected = Ninguna fuente seleccionada
firmware_tool-select_source-no_boards = No hay placas disponibles para esta fuente
firmware_tool-select_source-no_versions = No hay versiones disponibles para esta fuente
firmware_tool-board_defaults = Configura tu placa
firmware_tool-board_defaults-description = Establece los pines o ajustes relativos a tu hardware
firmware_tool-board_defaults-add = Añadir
@@ -1541,7 +1488,7 @@ firmware_tool-flashbtn_step-board_SLIMEVR-r12-v2 = Enciende el tracker mientras
firmware_tool-flashbtn_step-board_SLIMEVR-r14-v2 = Enciende el tracker mientras pulsas el botón FLASH en la parte superior de la placa. El LED del tracker deberia hacer un parpadeo breve.
firmware_tool-flashbtn_step-board_OTHER =
Antes de flashear, probablemente tendrá que poner el sensor en modo bootloader.
La mayoría de las veces, esto significa presionar el botón de boot en la placa antes de que comience el proceso de flasheo. Si el proceso de flasheo se agota al comienzo, probablemente significa que el sensor no estaba en modo bootloader.
La mayoría de las veces, esto significa presionar el botón de boot en la placa antes de que comience el proceso de flasheo. Si el proceso de flasheo se agota al comienzo, probablemente significa que el sensor no estaba en modo bootloader.
Por favor, consulte las instrucciones de flasheo de su placa para saber cómo activar el modo bootloader.
firmware_tool-flash_method_ota-title = Flashear por Wi-Fi
firmware_tool-flash_method_ota-devices = Dispositivos OTA detectados:
@@ -1558,7 +1505,6 @@ firmware_tool-flashing_step-description = Sus trackers se están flasheando, por
firmware_tool-flashing_step-warning-v2 = No desconectes o apagues el tracker durante el proceso de subida a menos que se te indique, puede causar que tu placa quede inutilizable.
firmware_tool-flashing_step-flash_more = Flashear más sensores
firmware_tool-flashing_step-exit = Salir
firmware_tool-flashing_step-onboarding_continue = Continuar
## firmware tool build status
@@ -1614,7 +1560,7 @@ tray_or_exit_modal-title = ¿Que debería hacer el botón de cerrar?
# Multiline text
tray_or_exit_modal-description =
Esto te deja escoger si quieres cerrar el servidor o minimizarlo a la bandeja cuando se presiona el botón de cerrar.
¡Puedes cambiar esto luego en los ajustes de la interfaz!
tray_or_exit_modal-radio-exit = Salir al cerrar
tray_or_exit_modal-radio-tray = Minimizar a la bandeja del sistema
@@ -1675,7 +1621,7 @@ vrc_config-avatar_measurement_type-ARM_SPAN = Longitud del brazo
error_collection_modal-title = ¿Podemos recopilar errores?
error_collection_modal-description_v2 =
{ settings-interface-behavior-error_tracking-description_v2 }
Tu puedes cambiar esta configuración más tarde en la sección de comportamiento de la pagina de configuración.
error_collection_modal-confirm = Acepto
error_collection_modal-cancel = No quiero
@@ -1700,9 +1646,6 @@ tracking_checklist-FULL_RESET-desc = Algunos trackers necesitan realizar un rein
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR no se está ejecutando
tracking_checklist-STEAMVR_DISCONNECTED-desc = SteamVR no se esta ejecutando. ¿Lo estas usando para VR?
tracking_checklist-STEAMVR_DISCONNECTED-open = Abrir SteamVR
tracking_checklist-STEAMVR_HANDS_ENABLED = Trackers de mano activados
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = Has activado los trackers de mano virtuales de SteamVR. Esto causará que los botones no funcionarán en SteamVR ni en juegos.
tracking_checklist-STEAMVR_HANDS_ENABLED-go = Desactívalos
tracking_checklist-TRACKERS_REST_CALIBRATION = Calibra tus trackers
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = No realizaste una calibración para los trackers. Por favor deja reposar tus trackers (resaltados en amarillo) en una superficie estable por unos segundos.
tracking_checklist-TRACKER_ERROR = Trackers con Errores
+1 -1
View File
@@ -34,7 +34,7 @@ export function NavButton({
className={classnames(
'flex flex-col justify-center xs:gap-4 mobile:gap-2',
'mobile:w-[65px] mobile:h-[65px]',
'xs:py-3 mobile:py-4 rounded-md mobile:rounded-b-none group',
'xs:py-3 mobile:py-4 rounded-md mobile:rounded-b-none group select-text',
{
'bg-accent-background-50 fill-accent-background-20': doesMatch,
'hover:bg-background-70': !doesMatch,
+1 -3
View File
@@ -5,7 +5,6 @@ import {
NewSerialDeviceResponseT,
RpcMessage,
SerialDeviceT,
SerialDeviceType,
} from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
@@ -57,8 +56,7 @@ export function SerialDetectionModal() {
'/settings/serial',
'/onboarding/connect-trackers',
'/settings/firmware-tool',
].includes(pathname) &&
device?.type !== SerialDeviceType.HID_RECEIVER
].includes(pathname)
) {
setOpen(device);
}
+1 -1
View File
@@ -19,7 +19,7 @@ import { ArrowDownIcon, ArrowUpIcon } from './icon/ArrowIcons';
import { a11yClick } from '@/utils/a11y';
import { createPortal } from 'react-dom';
export type DropdownItem = {
type DropdownItem = {
value: string;
label: ReactNode;
};
+1 -2
View File
@@ -93,10 +93,9 @@ export const FileInputContentFile = ({
</div>
<span className="flex-grow" />
<a
href=""
href="#"
className="h-12 w-12 hover:bg-accent-background-20 cursor-pointer"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
onClearPicker();
}}
@@ -14,13 +14,13 @@ export function InnerSystemFileInput({
value,
onChange,
directory,
refCallback: refCallback,
ref,
}: {
label: string;
value: string | null;
onChange: (...event: any[]) => void;
directory: boolean;
refCallback: RefCallBack;
ref: RefCallBack;
}) {
const electron = useElectron();
@@ -38,7 +38,7 @@ export function InnerSystemFileInput({
};
return (
<div ref={refCallback} onClick={handleClick}>
<div ref={ref} onClick={handleClick}>
{value !== null
? FileInputContentFile({
directory,
@@ -77,7 +77,7 @@ export function SystemFileInput<T extends FieldValues = FieldValues>({
label={label}
value={value}
onChange={onChange}
refCallback={ref}
ref={ref}
directory={directory}
/>
)}
+11 -2
View File
@@ -1,6 +1,15 @@
export function VMCIcon() {
export function VMCIcon({ width }: { width?: number }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-38 0 409 155">
<svg
id="svg5"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x={0}
y={0}
width={width ?? 'fit-content'}
viewBox="-38 0 409 155"
xmlSpace="preserve"
>
<style>
{
'.st1,.st3{stroke:#000;stroke-width:13}.st3{display:inline;fill:none;stroke-width:12.9402;stroke-miterlimit:11.3386}'
+7 -2
View File
@@ -1,6 +1,11 @@
export function VRCIcon() {
export function VRCIcon({ width }: { width?: number }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 100 824 824">
<svg
viewBox="100 100 824 824"
width={width ?? 'fit-content'}
className="fill-background-10"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M246.1 418.9h531.8c8.4 0 16 3.4 21.5 8.9s8.9 13.1 8.9 21.5v125.4c0 8.4-3.4 16-8.9 21.5-4.8 4.8-11.1 8-18.1 8.7v46.3c0 10.9-8.8 19-19.5 15.1-3.8-1.4-7.9-4.6-11.9-9.9L709.6 605H246.1c-8.4 0-16-3.4-21.5-8.9s-8.9-13.1-8.9-21.5V449.3c0-8.4 3.4-16 8.9-21.5s13.1-8.9 21.5-8.9zm523.8 174.8h8c5.2 0 10-2.1 13.5-5.6 3.5-3.5 5.6-8.2 5.6-13.5V449.3c0-5.2-2.1-10-5.6-13.5-3.5-3.5-8.2-5.6-13.5-5.6H246.1c-5.2 0-10 2.1-13.5 5.6-3.5 3.5-5.6 8.2-5.6 13.5v125.4c0 5.2 2.1 10 5.6 13.5 3.5 3.5 8.2 5.6 13.5 5.6h469.4c15.8 19.8 31.1 40 46.9 59.8 2.5 3.3 7.7 3.9 7.6-2.5v-57.4h-.1zm-132.3-67.1h23.9l-12-42.2-11.9 42.2zm110.8-74.2H460.6c-10.8 0-19.6 8.8-19.6 19.6v79.7c0 10.8 8.8 19.6 19.6 19.6h287.8c10.8 0 19.6-8.8 19.6-19.6V472c0-10.7-8.8-19.6-19.6-19.6zm-270.3 91.4c2.5 2.6 6.2 3.9 10.9 3.9 3.1 0 5.6-.5 7.4-1.5 1.8-1 3.2-2.2 4.1-3.7.9-1.5 1.5-3.1 1.9-4.7.3-1.7.5-3.3.6-4.7.2-2.1 1.1-3.6 2.8-4.4 1.7-.8 3.7-1.2 6.1-1.2 3.1 0 5.4.6 6.9 1.8 1.5 1.2 2.2 3.5 2.2 7 0 4.1-.8 7.9-2.4 11.3-1.6 3.4-3.9 6.3-6.8 8.6s-6.4 4.1-10.5 5.4c-4 1.3-8.4 1.9-13.2 1.9-4.3 0-8.4-.6-12.2-1.7-3.9-1.1-7.2-3-10.1-5.4-2.9-2.5-5.2-5.7-6.8-9.7-1.7-4-2.5-8.9-2.5-14.7v-38.4c0-5.8.8-10.7 2.5-14.7s4-7.2 6.9-9.7c2.9-2.5 6.3-4.3 10.1-5.4 3.9-1.1 7.9-1.7 12.2-1.7 4.8 0 9.2.6 13.2 1.9 4 1.2 7.5 3 10.4 5.2 2.9 2.2 5.1 5 6.7 8.3 1.6 3.3 2.4 6.9 2.4 10.8 0 3.6-.7 5.9-2.2 7.1-1.5 1.1-3.7 1.7-6.7 1.7-2.6 0-4.7-.4-6.3-1.2-1.7-.8-2.5-2.3-2.6-4.4-.1-1.1-.3-2.4-.6-3.9s-.9-3-1.9-4.5c-1-1.5-2.4-2.7-4.2-3.7-1.8-1-4.4-1.5-7.7-1.5-4.7 0-8.3 1.3-10.7 3.9-2.5 2.6-3.7 6.6-3.7 12v38.4c0 5.1 1.3 9.1 3.8 11.6zm122.7 13.1c0 1.8-.9 3.2-2.8 4.2s-3.9 1.4-6.1 1.4c-2.3 0-4.4-.5-6.2-1.4-1.8-1-2.8-2.4-2.8-4.2v-39.5h-31v39.5c0 1.8-.9 3.2-2.8 4.2s-3.9 1.4-6.1 1.4c-2.3 0-4.4-.5-6.2-1.4-1.8-1-2.8-2.4-2.8-4.2v-89.4c0-1.9.9-3.3 2.8-4.2 1.8-.9 3.9-1.3 6.2-1.3 2.2 0 4.2.4 6.1 1.3 1.9.9 2.8 2.3 2.8 4.2v35.9h31v-35.9c0-1.9.9-3.3 2.8-4.2 1.8-.9 3.9-1.3 6.2-1.3 2.2 0 4.2.4 6.1 1.3 1.9.9 2.8 2.3 2.8 4.2v89.4zm86 1.2c-.7.9-1.7 1.7-2.8 2.3-1.1.7-2.3 1.2-3.6 1.6-1.3.4-2.6.6-3.8.6-1.6 0-2.9-.3-3.9-.8-1.1-.6-1.8-1.5-2.1-2.8l-5.2-18.3h-31.5l-5.2 18.3c-.4 1.3-1.1 2.2-2.1 2.8-1.1.5-2.4.8-3.9.8-1.2 0-2.5-.2-3.8-.6-1.3-.4-2.5-.9-3.6-1.5s-2-1.4-2.8-2.3c-.7-.9-1.1-1.9-1.1-3 0-.2.1-.6.3-1.4l26.6-86.5c.6-2.1 2.1-3.6 4.3-4.6 2.2-1 4.6-1.4 7.2-1.4 2.7 0 5.1.5 7.3 1.4 2.2 1 3.6 2.5 4.3 4.6l26.6 86.5c.2.7.3 1.2.3 1.4-.4 1-.7 2-1.5 2.9zm65-82.5c-1 1.7-2.4 2.5-4.2 2.5h-20.1v78.8c0 1.8-.9 3.2-2.8 4.2s-3.9 1.4-6.1 1.4c-2.3 0-4.4-.5-6.2-1.4-1.8-1-2.8-2.4-2.8-4.2v-78.8h-20.2c-1.8 0-3.2-.8-4.2-2.4-1-1.6-1.4-3.5-1.4-5.7 0-1.9.5-3.7 1.4-5.4.9-1.7 2.3-2.5 4.3-2.5h58.2c1.9 0 3.3.8 4.3 2.5.9 1.7 1.4 3.5 1.4 5.4-.2 2.1-.7 3.9-1.6 5.6zm-495.2-4.8 26.6 86.5c.7 2.1 2.2 3.6 4.3 4.6 2.2 1 4.6 1.4 7.2 1.4 2.7 0 5.1-.5 7.3-1.4 2.2-1 3.6-2.5 4.3-4.6l26.4-86.5c.2-.7.3-1.2.3-1.4 0-1.1-.4-2.1-1.1-3-.7-.9-1.7-1.7-2.8-2.3-1.1-.7-2.3-1.2-3.6-1.6-1.3-.4-2.6-.5-3.8-.5-1.6 0-2.9.3-3.9.8-1.1.5-1.8 1.5-2.1 2.8l-20.9 74.6-21-74.6c-.4-1.3-1.1-2.2-2.1-2.8-1.1-.6-2.4-.8-3.9-.8-1.2 0-2.5.2-3.8.5-1.3.4-2.5.9-3.6 1.5s-2 1.4-2.8 2.3c-.7.9-1.1 1.9-1.1 3-.2.3-.1.7.1 1.5zm86.9-3.3c0-1.5.5-2.8 1.6-3.9s2.5-1.7 4.2-1.7h27.2c4.5 0 8.7.5 12.7 1.4 3.9 1 7.4 2.5 10.4 4.7s5.3 5.1 7 8.8c1.7 3.7 2.5 8.3 2.5 13.8 0 7.9-1.7 14.1-5.2 18.5-3.4 4.4-7.7 7.5-12.9 9l18 33.4c.3.4.5.8.5 1.2.1.4.1.8.1 1 0 1.1-.3 2.2-1 3.4-.7 1.1-1.6 2.2-2.6 3-1.1.9-2.2 1.6-3.6 2.1-1.3.6-2.6.8-3.9.8-1.3 0-2.5-.4-3.5-1.1-1.1-.7-1.9-1.8-2.7-3.2l-19.5-38h-11.6v35.9c0 1.8-.9 3.2-2.8 4.2-1.8 1-3.9 1.4-6.2 1.4-2.2 0-4.2-.5-6.1-1.4-1.9-1-2.8-2.4-2.8-4.2v-89.1h.2zm17.9 10.2V507h15.1c4.5 0 8.1-1.1 10.7-3.2 2.7-2.2 4-5.9 4-11.3s-1.3-9.2-4-11.4c-2.7-2.2-6.2-3.3-10.7-3.3h-15.1v-.1z" />
</svg>
);
@@ -13,7 +13,6 @@ import {
NewSerialDeviceResponseT,
RpcMessage,
SerialDeviceT,
SerialDeviceType,
SerialDevicesRequestT,
SerialDevicesResponseT,
TrackerStatus,
@@ -78,14 +77,13 @@ function SerialDevicesList({
RpcMessage.SerialDevicesResponse,
(res: SerialDevicesResponseT) => {
setDevices(
res.devices.reduce((curr, device) => {
if (device?.type != SerialDeviceType.ESP_TRACKER) return curr;
return {
res.devices.reduce(
(curr, device) => ({
...curr,
[device?.port?.toString() ?? 'unknown']: device,
};
}, {})
}),
{}
)
);
setLoading(false);
}
@@ -94,7 +92,7 @@ function SerialDevicesList({
useRPCPacket(
RpcMessage.NewSerialDeviceResponse,
({ device }: NewSerialDeviceResponseT) => {
if (device?.port && device?.type === SerialDeviceType.ESP_TRACKER)
if (device?.port)
setDevices((old) => ({
...old,
[device?.port?.toString() ?? 'unknown']: device,
@@ -28,7 +28,7 @@ function IncrementButton({
<div
onClick={onClick}
className={classNames(
'no-user-drag p-3 rounded-lg xs:w-10 xs:h-10 flex flex-col justify-center items-center cursor-pointer',
'p-3 rounded-lg xs:w-10 xs:h-10 flex flex-col justify-center items-center cursor-pointer',
'hover:bg-opacity-50 active:bg-accent-background-30',
{ 'bg-background-60': bgDark, 'bg-background-40': !bgDark }
)}
@@ -34,7 +34,7 @@ function IncrementButton({
return (
<div
className={classNames(
'no-user-drag flex rounded-md items-center justify-center flex-row xs:flex-col w-full gap-1 p-3 xs:p-2 xs:w-[75px] xs:h-[75px]',
'flex rounded-md items-center justify-center flex-row xs:flex-col w-full gap-1 p-3 xs:p-2 xs:w-[75px] xs:h-[75px]',
{
'cursor-not-allowed bg-background-80 opacity-50': disabled,
'bg-background-50 hover:bg-background-40 cursor-pointer': !disabled,
@@ -74,7 +74,7 @@ function UnitSelector({
'bg-accent-background-30': active,
'hover:bg-background-40 bg-background-40': !active,
},
'no-user-drag flex items-center justify-center rounded-md outline-background-10 cursor-pointer'
'flex items-center justify-center rounded-md outline-background-10 cursor-pointer'
)}
onClick={onClick}
>
@@ -29,8 +29,8 @@ function PosePage({
return (
<div className="flex flex-col py-2">
<div className="flex flex-col gap-2">
{descriptionKeys.map((descriptionKey, i) => (
<Typography key={i}>{l10n.getString(descriptionKey)}</Typography>
{descriptionKeys.map((descriptionKey) => (
<Typography>{l10n.getString(descriptionKey)}</Typography>
))}
</div>
<div className="flex pt-1 items-center fill-background-50 justify-center px-12">
@@ -100,11 +100,7 @@ export function TrackersAssignPage() {
tapDetectionSettings.mountingResetDelay,
tapDetectionSettings.mountingResetEnabled,
tapDetectionSettings.mountingResetTaps,
true,
null,
tapDetectionSettings.yawResetTracker,
tapDetectionSettings.fullResetTracker,
tapDetectionSettings.mountingResetTracker
true
);
sendRPCPacket(
@@ -3,11 +3,10 @@ import { ConfigContextC, loadConfig, useConfigProvider } from '@/hooks/config';
import { getSentryOrCompute } from '@/utils/sentry';
const config = await loadConfig();
const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false;
if (config?.errorTracking !== undefined) {
// load sentry ASAP to catch early errors
getSentryOrCompute(config.errorTracking ?? false, config.uuid, isSteam);
getSentryOrCompute(config.errorTracking ?? false, config.uuid);
}
export function ConfigContextProvider({ children }: { children: ReactNode }) {
@@ -1,6 +1,7 @@
import classNames from 'classnames';
import { ReactNode, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { useBreakpoint } from '@/hooks/breakpoint';
export function SettingsPageLayout({
children,
@@ -11,6 +12,7 @@ export function SettingsPageLayout({
} & React.HTMLAttributes<HTMLDivElement>) {
const pageRef = useRef<HTMLDivElement | null>(null);
const { state } = useLocation();
const { isMobile } = useBreakpoint('mobile');
useEffect(() => {
const typedState: { scrollTo: string } = state;
@@ -21,10 +23,19 @@ export function SettingsPageLayout({
`#${typedState.scrollTo}`
) as HTMLElement | null;
if (elem) {
elem.scrollIntoView({
block: 'start',
behavior: 'smooth',
});
// stupid way of doing this, just get the closest overflow-y-auto
// usually its just the parentElem
const closestScroll = elem.closest(
'.overflow-y-auto'
) as HTMLElement | null;
if (closestScroll) {
// The 45 is just enough padding for making the scroll look perfect
const topPadding = isMobile ? 80 : 45;
closestScroll.scroll({
top: elem.offsetTop - topPadding,
behavior: 'smooth',
});
}
}
}, [state]);
@@ -47,7 +58,7 @@ export function SettingsPagePaneLayout({
return (
<div
className={classNames(
'bg-background-70 rounded-lg px-4 py-8 flex xs:gap-4 w-full relative scroll-mt-12 mobile:scroll-mt-20',
'bg-background-70 rounded-lg px-4 py-8 flex xs:gap-4 w-full relative',
className
)}
{...props}
@@ -10,11 +10,8 @@ import { Button } from '@/components/commons/Button';
import { SettingsResetModal } from '@/components/settings/SettingsResetModal';
import { error } from '@/utils/logging';
import {
defaultDevSettings,
defaultConfig as defaultGUIConfig,
useConfig,
} from '@/hooks/config';
import { defaultConfig as defaultGUIConfig, useConfig } from '@/hooks/config';
import { defaultValues as defaultDevConfig } from '@/components/widgets/DeveloperModeWidget';
import { RpcMessage, SettingsResetRequestT } from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { useElectron } from '@/hooks/electron';
@@ -24,7 +21,7 @@ function guiDefaults() {
const { lang, ...guiDefaults } = defaultGUIConfig;
guiDefaults.devSettings = defaultDevSettings;
guiDefaults.devSettings = defaultDevConfig;
return guiDefaults;
}
@@ -15,8 +15,6 @@ import {
SteamVRTrackersSettingT,
TapDetectionSettingsT,
HIDSettingsT,
VelocitySettingsT,
BodyPart,
} from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
@@ -48,8 +46,6 @@ import {
import { atom, useAtomValue, useSetAtom } from 'jotai';
import { isEqual } from '@react-hookz/deep-equal';
import { selectAtom } from 'jotai/utils';
import { Dropdown } from '@/components/commons/Dropdown';
import { ASSIGNMENT_MODES } from '@/components/onboarding/BodyAssignment';
export type SettingsForm = {
trackers: {
@@ -103,9 +99,6 @@ export type SettingsForm = {
fullResetTaps: number;
mountingResetTaps: number;
numberTrackersOverThreshold: number;
yawResetTracker: string;
mountingResetTracker: string;
fullResetTracker: string;
};
legTweaks: {
correctionStrength: number;
@@ -115,9 +108,6 @@ export type SettingsForm = {
hidSettings: {
trackersOverHID: boolean;
};
velocitySettings: {
sendDerivedVelocity: boolean;
};
};
const defaultValues: SettingsForm = {
@@ -169,15 +159,11 @@ const defaultValues: SettingsForm = {
fullResetTaps: 3,
mountingResetTaps: 3,
numberTrackersOverThreshold: 1,
yawResetTracker: String(BodyPart.CHEST),
mountingResetTracker: String(BodyPart.RIGHT_UPPER_LEG),
fullResetTracker: String(BodyPart.LEFT_UPPER_LEG),
},
legTweaks: { correctionStrength: 0.3 },
resetsSettings: defaultResetSettings,
stayAligned: defaultStayAlignedSettings,
hidSettings: { trackersOverHID: false },
velocitySettings: { sendDerivedVelocity: false },
};
const settingsAtom = atom(new SettingsResponseT());
@@ -194,13 +180,6 @@ export function GeneralSettings() {
const { config } = useConfig();
const { currentLocales } = useLocaleConfig();
const bodyParts: { value: string; label: string }[] = Object.values(BodyPart)
.filter((v): v is BodyPart => typeof v === 'number')
.filter((v) => ASSIGNMENT_MODES['full-body'].includes(v as BodyPart))
.map((value) => ({
value: String(value),
label: l10n.getString(`body_part-${BodyPart[value]}`),
}));
const blockHandsWarning = useRef(false);
// If not null, warning will be shown, and showHandsWarning will
// hold which hands should be toggled ([leftHand, rightHand])
@@ -326,13 +305,6 @@ export function GeneralSettings() {
tapDetection.yawResetDelay = values.tapDetection.yawResetDelay;
tapDetection.yawResetEnabled = values.tapDetection.yawResetEnabled;
tapDetection.yawResetTaps = values.tapDetection.yawResetTaps;
tapDetection.yawResetTracker = Number(values.tapDetection.yawResetTracker);
tapDetection.mountingResetTracker = Number(
values.tapDetection.mountingResetTracker
);
tapDetection.fullResetTracker = Number(
values.tapDetection.fullResetTracker
);
tapDetection.mountingResetEnabled =
values.tapDetection.mountingResetEnabled;
tapDetection.mountingResetDelay = values.tapDetection.mountingResetDelay;
@@ -353,11 +325,6 @@ export function GeneralSettings() {
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
settingsReq.hidSettings = hidSettings;
const velocitySettings = new VelocitySettingsT();
velocitySettings.sendDerivedVelocity =
values.velocitySettings.sendDerivedVelocity;
settingsReq.velocitySettings = velocitySettings;
if (values.resetsSettings) {
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
}
@@ -449,18 +416,6 @@ export function GeneralSettings() {
mountingResetTaps:
settings.tapDetectionSettings.mountingResetTaps ||
defaultValues.tapDetection.mountingResetTaps,
yawResetTracker: String(
settings.tapDetectionSettings.yawResetTracker ||
defaultValues.tapDetection.yawResetTracker
),
fullResetTracker: String(
settings.tapDetectionSettings.fullResetTracker ||
defaultValues.tapDetection.fullResetTracker
),
mountingResetTracker: String(
settings.tapDetectionSettings.mountingResetTracker ||
defaultValues.tapDetection.mountingResetTracker
),
numberTrackersOverThreshold:
settings.tapDetectionSettings.numberTrackersOverThreshold ||
defaultValues.tapDetection.numberTrackersOverThreshold,
@@ -491,12 +446,6 @@ export function GeneralSettings() {
};
}
if (settings.velocitySettings) {
formData.velocitySettings = {
sendDerivedVelocity: settings.velocitySettings.sendDerivedVelocity,
};
}
reset({ ...getValues(), ...formData });
}, [settings]);
@@ -1067,32 +1016,6 @@ export function GeneralSettings() {
/>
</div>
<div className="flex flex-col pt-2 pb-1">
<Typography variant="section-title">
{l10n.getString(
'settings-general-fk_settings-velocity_settings'
)}
</Typography>
<div className="pt-2">
<Typography>
{l10n.getString(
'settings-general-fk_settings-velocity_settings-description'
)}
</Typography>
</div>
</div>
<div className="grid sm:grid-cols-1 pb-3">
<CheckBox
variant="toggle"
outlined
control={control}
name="velocitySettings.sendDerivedVelocity"
label={l10n.getString(
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
)}
/>
</div>
{config?.debug && (
<>
<div className="flex flex-col pt-2 pb-3">
@@ -1285,80 +1208,34 @@ export function GeneralSettings() {
{l10n.getString('settings-general-gesture_control-description')}
</Typography>
</div>
<div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.yawResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-yawResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.fullResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-fullResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.mountingResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-mountingResetEnabled'
)}
/>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<div>
<Typography bold>
{l10n.getString(
'settings-general-gesture_control-yawResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="tapDetection.yawResetTracker"
items={bodyParts}
/>
</div>
<div>
<Typography bold>
{l10n.getString(
'settings-general-gesture_control-fullResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="tapDetection.fullResetTracker"
items={bodyParts}
/>
</div>
<div>
<Typography bold>
{l10n.getString(
'settings-general-gesture_control-mountingResetTracker'
)}
</Typography>
<Dropdown
display="block"
control={control}
placeholder={''}
name="tapDetection.mountingResetTracker"
items={bodyParts}
/>
</div>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.yawResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-yawResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.fullResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-fullResetEnabled'
)}
/>
<CheckBox
variant="toggle"
outlined
control={control}
name="tapDetection.mountingResetEnabled"
label={l10n.getString(
'settings-general-gesture_control-mountingResetEnabled'
)}
/>
</div>
<div className="grid sm:grid-cols-3 gap-5 pb-2">
<NumberSelector
@@ -1,13 +1,13 @@
import { Localized, useLocalization } from '@fluent/react';
import { useEffect } from 'react';
import { FieldPath, useForm } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { CheckBox } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { defaultConfig, DeveloperModeConfig, useConfig } from '@/hooks/config';
import { defaultConfig, useConfig } from '@/hooks/config';
import { ThemeSelector } from '@/components/commons/ThemeSelector';
import { SquaresIcon } from '@/components/commons/icon/SquaresIcon';
import { NumberSelector } from '@/components/commons/NumberSelector';
@@ -18,6 +18,7 @@ import { Range } from '@/components/commons/Range';
import { Dropdown } from '@/components/commons/Dropdown';
import { ArrowRightLeftIcon } from '@/components/commons/icon/ArrowIcons';
import { SystemFileInput } from '@/components/commons/SystemFileInput';
import { DeveloperModeWidget } from '@/components/widgets/DeveloperModeWidget';
import { useElectron } from '@/hooks/electron';
interface InterfaceSettingsForm {
@@ -27,6 +28,7 @@ interface InterfaceSettingsForm {
fonts: string;
};
behavior: {
devmode: boolean;
useTray: boolean;
discordPresence: boolean;
errorTracking: boolean;
@@ -38,9 +40,6 @@ interface InterfaceSettingsForm {
feedbackSoundVolume: number;
connectedTrackersWarning: boolean;
};
developer: DeveloperModeConfig & {
enabled: boolean;
};
}
export function InterfaceSettings() {
@@ -66,35 +65,13 @@ export function InterfaceSettings() {
defaultConfig.connectedTrackersWarning,
},
behavior: {
devmode: config?.debug ?? defaultConfig.debug,
useTray: config?.useTray ?? defaultConfig.useTray ?? false,
discordPresence:
config?.discordPresence ?? defaultConfig.discordPresence,
errorTracking: config?.errorTracking ?? false,
bvhDirectory: config?.bvhDirectory ?? defaultConfig.bvhDirectory,
},
developer: {
enabled: config?.debug ?? defaultConfig.debug,
highContrast:
config?.devSettings?.highContrast ??
defaultConfig.devSettings.highContrast,
preciseRotation:
config?.devSettings?.preciseRotation ??
defaultConfig.devSettings.preciseRotation,
fastDataFeed:
config?.devSettings?.fastDataFeed ??
defaultConfig.devSettings.fastDataFeed,
filterSlimesAndHMD:
config?.devSettings?.filterSlimesAndHMD ??
defaultConfig.devSettings.filterSlimesAndHMD,
sortByName:
config?.devSettings?.sortByName ??
defaultConfig.devSettings.sortByName,
rawSlimeRotation:
config?.devSettings?.rawSlimeRotation ??
defaultConfig.devSettings.rawSlimeRotation,
moreInfo:
config?.devSettings?.moreInfo ?? defaultConfig.devSettings.moreInfo,
},
},
});
@@ -135,11 +112,9 @@ export function InterfaceSettings() {
useTray: values.behavior.useTray,
discordPresence: values.behavior.discordPresence,
debug: values.behavior.devmode,
errorTracking: values.behavior.errorTracking,
bvhDirectory: values.behavior.bvhDirectory,
debug: values.developer.enabled,
devSettings: values.developer,
});
};
@@ -153,16 +128,6 @@ export function InterfaceSettings() {
return () => subscription.unsubscribe();
}, []);
const devToggles = {
highContrast: 'high_contrast',
preciseRotation: 'precise_rotation',
fastDataFeed: 'fast_data_feed',
filterSlimesAndHMD: 'filter_slimes_and_hmd',
sortByName: 'sort_by_name',
rawSlimeRotation: 'raw_slime_rotation',
moreInfo: 'more_info',
};
return (
<SettingsPageLayout>
<form
@@ -334,31 +299,18 @@ export function InterfaceSettings() {
</Typography>
</div>
<div className="grid grid-cols-1 gap-2 pb-4 w-full">
<CheckBox
variant="toggle"
control={control}
outlined
name="developer.enabled"
label={l10n.getString(
'settings-general-interface-dev_mode-label'
)}
/>
{!!config?.debug && (
<div className="grid grid-cols-2 w-full rounded-md gap-2">
{Object.entries(devToggles).map(([name, label], i) => (
<CheckBox
key={i}
control={control}
variant="toggle"
outlined
name={
`developer.${name}` as FieldPath<InterfaceSettingsForm>
}
label={l10n.getString(`widget-developer_mode-${label}`)}
/>
))}
</div>
)}
<div className="">
<CheckBox
variant="toggle"
control={control}
outlined
name="behavior.devmode"
label={l10n.getString(
'settings-general-interface-dev_mode-label'
)}
/>
</div>
{config?.debug && <DeveloperModeWidget />}
</div>
<Typography variant="section-title">
@@ -94,10 +94,7 @@ export function MagnetometerToggleSetting({
return settingType === 'general' ? (
<>
<div
className="flex flex-col pt-5 pb-3 scroll-mt-12 mobile:scroll-mt-20"
id={id}
>
<div className="flex flex-col pt-5 pb-3" id={id}>
<Typography variant="section-title">
{l10n.getString(
'settings-general-tracker_mechanics-use_mag_on_all_trackers'
@@ -102,9 +102,9 @@ export function OSCRouterSettings() {
formData.router.oscSettings.address =
settings.oscRouter.oscSettings.address.toString();
}
reset(formData);
}
reset(formData);
});
return (
+74 -173
View File
@@ -14,7 +14,6 @@ import {
SerialUpdateResponseT,
SerialTrackerGetWifiScanRequestT,
SerialTrackerCustomCommandRequestT,
SerialDeviceType,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { Button } from '@/components/commons/Button';
@@ -42,10 +41,7 @@ export function Serial() {
const consoleRef = useRef<HTMLDivElement>(null);
const [consoleContent, setConsole] = useState('');
const [openedSerialDevice, setOpenedSerialDevice] = useState<Omit<
SerialDeviceT,
'pack'
> | null>(null);
const [isSerialOpen, setSerialOpen] = useState(false);
const [serialDevices, setSerialDevices] = useState<
Omit<SerialDeviceT, 'pack'>[]
>([]);
@@ -91,19 +87,11 @@ export function Serial() {
};
useEffect(() => {
sendRPCPacket(RpcMessage.SerialDevicesRequest, new SerialDevicesRequestT());
const typedState: { serialPort: string } = state as any;
if (typedState?.serialPort) {
reset({ port: typedState.serialPort });
}
sendRPCPacket(RpcMessage.SerialDevicesRequest, new SerialDevicesRequestT());
const interval = setInterval(() => {
sendRPCPacket(
RpcMessage.SerialDevicesRequest,
new SerialDevicesRequestT()
);
}, 3000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
@@ -115,8 +103,11 @@ export function Serial() {
useRPCPacket(
RpcMessage.SerialUpdateResponse,
(data: SerialUpdateResponseT) => {
if (data.device) setOpenedSerialDevice(data.device);
else if (data.closed) setOpenedSerialDevice(null);
if (data.closed) {
setSerialOpen(false);
} else {
setSerialOpen(true);
}
if (data.log) {
setConsole((console) => console + data.log);
@@ -131,7 +122,6 @@ export function Serial() {
{
name: l10n.getString('settings-serial-auto_dropdown_item'),
port: 'Auto',
type: SerialDeviceType.ESP_TRACKER,
},
...(res.devices || []),
]);
@@ -171,7 +161,7 @@ export function Serial() {
useEffect(() => {
const id = setInterval(() => {
if (openedSerialDevice === null) {
if (!isSerialOpen) {
openSerial(port ?? defaultValues.port);
} else {
clearInterval(id);
@@ -181,7 +171,7 @@ export function Serial() {
return () => {
clearInterval(id);
};
}, [openedSerialDevice]);
}, [isSerialOpen]);
const reboot = () => {
sendRPCPacket(
@@ -189,8 +179,6 @@ export function Serial() {
new SerialTrackerRebootRequestT()
);
};
// ESP
const factoryReset = () => {
sendRPCPacket(
RpcMessage.SerialTrackerFactoryResetRequest,
@@ -221,48 +209,6 @@ export function Serial() {
setValue('customCommand', '');
};
// HID
const enterPairing = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('pair')
);
};
const dfu = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('dfu')
);
};
const meow = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('meow')
);
};
// HID receiver
const exitPairing = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('exit')
);
};
// HID tracker
const calibrate = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('calibrate')
);
};
const sixSideCalibrate = () => {
sendRPCPacket(
RpcMessage.SerialTrackerCustomCommandRequest,
new SerialTrackerCustomCommandRequestT('6-side')
);
};
const consoleContentRef = useRef(consoleContent);
useLayoutEffect(() => {
consoleContentRef.current = consoleContent;
@@ -372,7 +318,7 @@ export function Serial() {
>
<div className="flex select-text">
<pre>
{openedSerialDevice !== null
{isSerialOpen
? consoleContent
: l10n.getString('settings-serial-connection_lost')}
</pre>
@@ -380,115 +326,70 @@ export function Serial() {
</div>
<div className="border-t-2 pt-2 border-background-60 border-solid gap-2 flex flex-row">
<div className="xs:flex flex-grow xs:flex-wrap gap-2 grid grid-cols-2">
{openedSerialDevice !== null && (
<>
<Button variant="quaternary" onClick={reboot}>
{l10n.getString('settings-serial-reboot')}
</Button>
{openedSerialDevice?.type ===
SerialDeviceType.ESP_TRACKER && (
<>
<Button
variant="quaternary"
onClick={() => setTryFactoryReset(true)}
>
{l10n.getString('settings-serial-factory_reset')}
</Button>
<Button variant="quaternary" onClick={getWifiScan}>
{l10n.getString('settings-serial-get_wifi_scan')}
</Button>
</>
)}
{openedSerialDevice?.type !==
SerialDeviceType.ESP_TRACKER && (
<Button variant="quaternary" onClick={enterPairing}>
{l10n.getString('settings-serial-enter_pairing')}
</Button>
)}
{openedSerialDevice?.type ===
SerialDeviceType.HID_RECEIVER && (
<Button variant="quaternary" onClick={exitPairing}>
{l10n.getString('settings-serial-exit_pairing')}
</Button>
)}
{openedSerialDevice?.type ===
SerialDeviceType.HID_TRACKER && (
<>
<Button variant="quaternary" onClick={calibrate}>
{l10n.getString('settings-serial-calibrate')}
</Button>
<Button variant="quaternary" onClick={sixSideCalibrate}>
{l10n.getString('settings-serial-six_side_calibrate')}
</Button>
</>
)}
{openedSerialDevice?.type !==
SerialDeviceType.ESP_TRACKER && (
<>
<Button variant="quaternary" onClick={dfu}>
{l10n.getString('settings-serial-dfu')}
</Button>
<Button variant="quaternary" onClick={meow}>
{l10n.getString('settings-serial-meow')}
</Button>
</>
)}
<Button
variant="quaternary"
onClick={saveLogToFile}
disabled={
openedSerialDevice === null || !consoleContent.trim()
}
>
{l10n.getString('settings-serial-save_logs')}
</Button>
<div className="ml-auto">
<Button
variant="quaternary"
onClick={pauseScroll}
icon={
isPaused ? (
<PlayIcon width={16} />
) : (
<PauseIcon width={16} />
)
}
/>
</div>
<form
className="w-full flex flex-row gap-2 mobile:col-span-2"
onSubmit={(e) => {
if (openedSerialDevice === null) {
return;
}
e.preventDefault();
if (!acceptedCustomCommandWarning) {
setTrySendCustomCommand(true);
} else {
sendCustomSerialCommand();
}
}}
>
<div className="flex-grow">
<Input
control={control}
name="customCommand"
className="flex-grow"
placeholder={l10n.getString(
'settings-serial-send_command-placeholder'
)}
/>
</div>
<Button
variant="quaternary"
disabled={openedSerialDevice === null}
type="submit"
>
{l10n.getString('settings-serial-send_command')}
</Button>
</form>
</>
)}
<Button variant="quaternary" onClick={reboot}>
{l10n.getString('settings-serial-reboot')}
</Button>
<Button
variant="quaternary"
onClick={() => setTryFactoryReset(true)}
>
{l10n.getString('settings-serial-factory_reset')}
</Button>
<Button variant="quaternary" onClick={getWifiScan}>
{l10n.getString('settings-serial-get_wifi_scan')}
</Button>
<Button
variant="quaternary"
onClick={saveLogToFile}
disabled={!isSerialOpen || !consoleContent.trim()}
>
{l10n.getString('settings-serial-save_logs')}
</Button>
<div className="ml-auto">
<Button
variant="quaternary"
onClick={pauseScroll}
icon={
isPaused ? (
<PlayIcon width={16} />
) : (
<PauseIcon width={16} />
)
}
/>
</div>
<form
className="w-full flex flex-row gap-2 mobile:col-span-2"
onSubmit={(e) => {
if (!isSerialOpen) {
return;
}
e.preventDefault();
if (!acceptedCustomCommandWarning) {
setTrySendCustomCommand(true);
} else {
sendCustomSerialCommand();
}
}}
>
<div className="flex-grow">
<Input
control={control}
name="customCommand"
className="flex-grow"
placeholder={l10n.getString(
'settings-serial-send_command-placeholder'
)}
/>
</div>
<Button
variant="quaternary"
disabled={!isSerialOpen}
type="submit"
>
{l10n.getString('settings-serial-send_command')}
</Button>
</form>
<div className="w-full mobile:col-span-2">
<Dropdown
@@ -8,7 +8,6 @@ import {
SettingsResponseT,
OSCSettingsT,
VMCOSCSettingsT,
VRMSettingsT,
} from 'solarxr-protocol';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
@@ -54,6 +53,7 @@ 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;
@@ -66,21 +66,27 @@ export function VMCFileUpload() {
const vrmJson = watch('vrmJson');
const updateVRMJson = async () => {
if (!settings?.vmcOsc) return;
const req = new ChangeSettingsRequestT();
const vrm = new VRMSettingsT();
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) {
vrm.vrmJson = file.json;
vmcOsc.vrmJson = file.json;
setModelName(file.name);
}
} else {
vrm.vrmJson = '';
vmcOsc.vrmJson = '';
setModelName(null);
}
}
req.vrm = vrm;
req.vmcOsc = vmcOsc;
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
};
@@ -93,7 +99,8 @@ export function VMCFileUpload() {
}, []);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
const vrmJson = settings.vrm?.vrmJson?.toString();
setSettings(settings);
const vrmJson = settings.vmcOsc?.vrmJson?.toString();
if (vrmJson) {
let data: any;
try {
@@ -189,9 +196,9 @@ export function VMCSettings() {
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
formData.vmc.mirrorTracking = settings.vmcOsc.mirrorTracking;
reset(formData);
}
reset(formData);
});
return (
@@ -142,9 +142,9 @@ export function VRCOSCSettings() {
formData.vrchat.trackers = settings.vrcOsc.trackers;
formData.vrchat.oscqueryEnabled = settings.vrcOsc.oscqueryEnabled;
reset(formData);
}
reset(formData);
});
return (
@@ -187,12 +187,14 @@ export function VRCOSCSettings() {
{l10n.getString('settings-osc-vrchat-oscqueryEnabled')}
</Typography>
<div className="flex flex-col pb-2">
{l10n
.getString('settings-osc-vrchat-oscqueryEnabled-description')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
<Typography>
{l10n
.getString('settings-osc-vrchat-oscqueryEnabled-description')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</Typography>
</div>
<div className="grid grid-cols-2 gap-3 pb-5">
<CheckBox
@@ -9,7 +9,7 @@ import { useLocalization } from '@fluent/react';
import { Dispatch, ReactNode, SetStateAction } from 'react';
import { StayAlignedRelaxedPose } from 'solarxr-protocol';
function StayAlignedPoseModal({
function StaAlignedPoseModal({
open,
title,
descriptionKeys,
@@ -39,8 +39,8 @@ function StayAlignedPoseModal({
<Typography variant="main-title">{l10n.getString(title)}</Typography>
</div>
<div className="flex flex-col gap-1">
{descriptionKeys.map((descriptionKey, i) => (
<Typography key={i}>{l10n.getString(descriptionKey)}</Typography>
{descriptionKeys.map((descriptionKey) => (
<Typography>{l10n.getString(descriptionKey)}</Typography>
))}
</div>
<div className="flex pt-1 items-center fill-background-50 justify-center px-12">
@@ -78,7 +78,7 @@ export const StandingRelaxedPoseModal = ({
}: {
open: [boolean, Dispatch<SetStateAction<boolean>>];
}) => (
<StayAlignedPoseModal
<StaAlignedPoseModal
open={open}
title={'onboarding-stay_aligned-relaxed_poses-standing-title'}
descriptionKeys={[
@@ -92,7 +92,7 @@ export const StandingRelaxedPoseModal = ({
width={260}
alt="Reset position"
/>
</StayAlignedPoseModal>
</StaAlignedPoseModal>
);
export const SittingRelaxedPoseModal = ({
@@ -100,7 +100,7 @@ export const SittingRelaxedPoseModal = ({
}: {
open: [boolean, Dispatch<SetStateAction<boolean>>];
}) => (
<StayAlignedPoseModal
<StaAlignedPoseModal
open={open}
title={'onboarding-stay_aligned-relaxed_poses-sitting-title'}
descriptionKeys={[
@@ -114,7 +114,7 @@ export const SittingRelaxedPoseModal = ({
width={260}
alt="Reset position"
/>
</StayAlignedPoseModal>
</StaAlignedPoseModal>
);
export const FlatRelaxedPoseModal = ({
@@ -122,7 +122,7 @@ export const FlatRelaxedPoseModal = ({
}: {
open: [boolean, Dispatch<SetStateAction<boolean>>];
}) => (
<StayAlignedPoseModal
<StaAlignedPoseModal
open={open}
title={'onboarding-stay_aligned-relaxed_poses-flat-title'}
descriptionKeys={[
@@ -136,5 +136,5 @@ export const FlatRelaxedPoseModal = ({
width={560}
alt="Reset position"
/>
</StayAlignedPoseModal>
</StaAlignedPoseModal>
);
+2 -2
View File
@@ -376,9 +376,9 @@ export function TrackersTable({
/>
</div>
<div className="flex flex-col gap-y-0">
{filteredSortedTrackers.map((data, index) => (
{filteredSortedTrackers.map((data) => (
<Row
key={index}
key={data.tracker.trackerId?.trackerNum}
clickedTracker={clickedTracker}
data={data}
highlightedTrackers={highlightedTrackers}
@@ -7,14 +7,12 @@ import {
import classNames from 'classnames';
import {
ChangeSettingsRequestT,
EnableSteamVRDriverRequestT,
ResetType,
RpcMessage,
SettingsRequestT,
SettingsResponseT,
SteamVRTrackersSettingT,
TrackingChecklistPublicNetworksT,
TrackingChecklistSteamVRDisconnectedT,
TrackingChecklistStepId,
} from 'solarxr-protocol';
import { ReactNode, useEffect, useMemo, useState } from 'react';
@@ -30,7 +28,7 @@ import {
ArrowDownIcon,
ArrowRightIcon,
} from '@/components/commons/icon/ArrowIcons';
import { Localized, useLocalization } from '@fluent/react';
import { Localized } from '@fluent/react';
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
import { TrackingChecklistModal } from './TrackingChecklistModal';
import { NavLink, useNavigate } from 'react-router-dom';
@@ -110,69 +108,6 @@ function Step({
);
}
function SteamVRDisconnected({
step,
context,
}: {
step: TrackingChecklistStep;
context: TrackingChecklistContext;
}) {
const { sendRPCPacket } = useWebsocketAPI();
const data = step.extraData as TrackingChecklistSteamVRDisconnectedT | null;
const enableDriver = () => {
sendRPCPacket(
RpcMessage.EnableSteamVRDriverRequest,
new EnableSteamVRDriverRequestT()
);
};
const driverNotInstalled = data?.driverInstalled === false;
const driverBlocked = data?.driverBlockedBySafeMode === true;
const driverDisabled = data?.driverEnabled === false;
const showEnableDriverButton = driverBlocked || driverDisabled;
const getDescriptionId = () => {
if (driverBlocked)
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_blocked-desc';
if (driverDisabled)
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_disabled-desc';
if (driverNotInstalled)
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_not_installed-desc';
return 'tracking_checklist-STEAMVR_DISCONNECTED-desc';
};
return (
<div className="space-y-2.5">
<Typography id={getDescriptionId()} />
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
{showEnableDriverButton && (
<Button
id="tracking_checklist-STEAMVR_DISCONNECTED-enable"
variant="primary"
onClick={enableDriver}
/>
)}
{!showEnableDriverButton && !driverNotInstalled && (
<Button
id="tracking_checklist-STEAMVR_DISCONNECTED-open"
variant="primary"
onClick={() => openUrl('steam://run/250820')}
/>
)}
{step.ignorable && (
<Button
id="tracking_checklist-ignore"
variant="secondary"
onClick={() => context.toggleSession(step.id)}
/>
)}
</div>
</div>
);
}
function SteamVRHandsEnabled() {
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
const [steamVrTrackers, setSteamVrTrackers] = useState<Omit<
@@ -222,21 +157,6 @@ function SteamVRHandsEnabled() {
);
}
function StandableInstalled() {
const { l10n } = useLocalization();
return (
<div className="space-y-2.5">
{l10n
.getString('tracking_checklist-STANDABLE_INSTALLED-desc')
.split('\n')
.map((line, i) => (
<Typography key={i}>{line}</Typography>
))}
</div>
);
}
const stepContentLookup: Record<
number,
(
@@ -304,8 +224,28 @@ const stepContentLookup: Record<
</div>
);
},
[TrackingChecklistStepId.STEAMVR_DISCONNECTED]: (step, context) => {
return <SteamVRDisconnected step={step} context={context} />;
[TrackingChecklistStepId.STEAMVR_DISCONNECTED]: (step, { toggleSession }) => {
return (
<>
<div className="space-y-2.5">
<Typography id="tracking_checklist-STEAMVR_DISCONNECTED-desc" />
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
<Button
id="tracking_checklist-STEAMVR_DISCONNECTED-open"
variant="primary"
onClick={() => openUrl('steam://run/250820')}
/>
{step.ignorable && (
<Button
id="tracking_checklist-ignore"
variant="secondary"
onClick={() => toggleSession(step.id)}
/>
)}
</div>
</div>
</>
);
},
[TrackingChecklistStepId.TRACKER_ERROR]: () => {
return <Typography id="tracking_checklist-TRACKER_ERROR-desc" />;
@@ -470,9 +410,6 @@ const stepContentLookup: Record<
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]: () => {
return <SteamVRHandsEnabled />;
},
[TrackingChecklistStepId.STANDABLE_INSTALLED]: () => {
return <StandableInstalled />;
},
};
export function TrackingChecklistMobile() {
@@ -0,0 +1,80 @@
import { useEffect } from 'react';
import { FieldPath, useForm } from 'react-hook-form';
import { useConfig } from '@/hooks/config';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { CheckBox } from '@/components/commons/Checkbox';
import { useLocalization } from '@fluent/react';
export interface DeveloperModeWidgetForm {
highContrast: boolean;
preciseRotation: boolean;
fastDataFeed: boolean;
filterSlimesAndHMD: boolean;
sortByName: boolean;
rawSlimeRotation: boolean;
moreInfo: boolean;
}
export const defaultValues: DeveloperModeWidgetForm = {
highContrast: false,
preciseRotation: false,
fastDataFeed: false,
filterSlimesAndHMD: false,
sortByName: false,
rawSlimeRotation: false,
moreInfo: false,
};
export function DeveloperModeWidget() {
const { l10n } = useLocalization();
const { config, setConfig } = useConfig();
const { reconnect } = useWebsocketAPI();
const { reset, control, handleSubmit, watch } =
useForm<DeveloperModeWidgetForm>({
defaultValues: defaultValues,
});
useEffect(() => {
reset(config?.devSettings || {});
}, []);
useEffect(() => {
const subscription = watch(() => handleSubmit(onSubmit)());
return () => subscription.unsubscribe();
}, []);
const onSubmit = async (formData: DeveloperModeWidgetForm) => {
const needReconnect =
config?.devSettings?.fastDataFeed !== formData.fastDataFeed;
await setConfig({ devSettings: formData });
if (needReconnect) reconnect();
};
const makeToggle = ([name, label]: string[], index: number) => (
<CheckBox
key={index}
control={control}
variant="toggle"
outlined
name={name as FieldPath<DeveloperModeWidgetForm>}
label={l10n.getString(`widget-developer_mode-${label}`)}
/>
);
const toggles = {
highContrast: 'high_contrast',
preciseRotation: 'precise_rotation',
fastDataFeed: 'fast_data_feed',
filterSlimesAndHMD: 'filter_slimes_and_hmd',
sortByName: 'sort_by_name',
rawSlimeRotation: 'raw_slime_rotation',
moreInfo: 'more_info',
};
return (
<form className="grid grid-cols-2 w-full rounded-md gap-2">
{Object.entries(toggles).map(makeToggle)}
</form>
);
}
@@ -130,18 +130,14 @@ async function initializeIMUVisualizer(
accelArrow.setLength(Math.sqrt(accelLength) * 2);
}
const magVec = Vector3FromVec3fT(mag);
const magVec = new Vector3(mag.x, mag.y, mag.z);
const magLen = magVec.length();
const magMag = Math.sqrt(magLen / 100);
if (magLen > 0) {
if (magArrow.parent === null) scene.add(magArrow);
const magDir = magVec.clone().normalize();
magArrow.position.copy(magDir.clone().multiplyScalar(-magMag));
magArrow.setDirection(magDir);
magArrow.setLength(2 * magMag);
} else {
magArrow.removeFromParent();
}
};
@@ -211,7 +207,9 @@ function IMUVisualizerCanvas({
}, [model]);
useEffect(() => {
contextRef.current?.update(quat, vec, mag);
if (contextRef.current) {
contextRef.current.update(quat, vec, mag);
}
}, [quat, vec, mag]);
if (error) {
+2 -4
View File
@@ -16,8 +16,6 @@ import { getSentryOrCompute, updateSentryContext } from '@/utils/sentry';
import { fetchCurrentFirmwareRelease, FirmwareRelease } from './firmware-update';
import { DEFAULT_LOCALE, LangContext } from '@/i18n/config';
const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false;
export interface AppContext {
currentFirmwareRelease: FirmwareRelease | null;
}
@@ -42,7 +40,7 @@ export function useProvideAppContext(): AppContext {
startDataFeed.dataFeeds = [dataFeedConfig, bonesDataFeedConfig];
sendDataFeedPacket(DataFeedMessage.StartDataFeed, startDataFeed);
}
}, [isConnected, config?.debug, config?.devSettings?.fastDataFeed]);
}, [isConnected]);
useDataFeedPacket(DataFeedMessage.DataFeedUpdate, (packet: DataFeedUpdateT) => {
if (packet.index === 0) {
@@ -81,7 +79,7 @@ export function useProvideAppContext(): AppContext {
if (config.errorTracking !== undefined) {
// Alows for sentry to refresh if user change the setting once the gui
// is initialized
getSentryOrCompute(config.errorTracking ?? false, config.uuid, isSteam);
getSentryOrCompute(config.errorTracking ?? false, config.uuid);
}
}, [config]);
+5 -21
View File
@@ -1,4 +1,8 @@
import { createContext, useContext, useState } from 'react';
import {
defaultValues as defaultDevSettings,
DeveloperModeWidgetForm,
} from '@/components/widgets/DeveloperModeWidget';
import { error } from '@/utils/logging';
import { useDebouncedEffect } from './timeout';
import { waitUntil } from '@/utils/a11y';
@@ -21,33 +25,13 @@ export enum AssignMode {
All = 'all',
}
export interface DeveloperModeConfig {
highContrast: boolean;
preciseRotation: boolean;
fastDataFeed: boolean;
filterSlimesAndHMD: boolean;
sortByName: boolean;
rawSlimeRotation: boolean;
moreInfo: boolean;
}
export const defaultDevSettings: DeveloperModeConfig = {
highContrast: false,
preciseRotation: false,
fastDataFeed: false,
filterSlimesAndHMD: false,
sortByName: false,
rawSlimeRotation: false,
moreInfo: false,
};
export interface Config {
uuid: string;
debug: boolean;
lang: string;
doneOnboarding: boolean;
watchNewDevices: boolean;
devSettings: DeveloperModeConfig;
devSettings: DeveloperModeWidgetForm;
feedbackSound: boolean;
feedbackSoundVolume: number;
connectedTrackersWarning: boolean;
+2 -7
View File
@@ -5,7 +5,7 @@ export function useDataFeedConfig() {
const { config } = useConfig();
const fastDataFeed = config?.debug && config?.devSettings?.fastDataFeed;
const feedMaxTps = fastDataFeed ? 90 : 10;
const feedMaxTps = fastDataFeed ? 40 : 10;
const trackerData = new TrackerDataMaskT();
trackerData.position = true;
@@ -39,13 +39,8 @@ export function useDataFeedConfig() {
}
export function useBonesDataFeedConfig() {
const { config } = useConfig();
const fastDataFeed = config?.debug && config?.devSettings?.fastDataFeed;
const feedMaxTps = fastDataFeed ? 90 : 40;
const dataFeedConfig = new DataFeedConfigT();
dataFeedConfig.boneMask = true;
dataFeedConfig.minimumTimeSinceLast = 1000 / feedMaxTps;
dataFeedConfig.minimumTimeSinceLast = 1000 / 40;
return dataFeedConfig;
}
-1
View File
@@ -25,7 +25,6 @@ export function useDiscordPresence() {
activity: l10n.getString('settings-general-interface-discord_presence-message', {
amount: imuTrackersCount,
}),
iconText: (__VERSION_TAG__ || __COMMIT_HASH__) + (__GIT_CLEAN__ ? '' : '-dirty'),
});
}, [config?.discordPresence, imuTrackersCount]);
}
-2
View File
@@ -32,8 +32,6 @@ export const trackingchecklistIdtoLabel: Record<TrackingChecklistStepId, string>
'tracking_checklist-STAY_ALIGNED_CONFIGURED',
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]:
'tracking_checklist-STEAMVR_HANDS_ENABLED',
[TrackingChecklistStepId.STANDABLE_INSTALLED]:
'tracking_checklist-STANDABLE_INSTALLED',
};
export type TrackingChecklistStepStatus =
-7
View File
@@ -426,10 +426,3 @@ div {
[data-electron-drag-region='true'] {
-webkit-app-region: drag;
}
a,
.no-user-drag {
-webkit-user-drag: none;
-webkit-user-select: none;
user-select: none;
}
+4 -10
View File
@@ -9,13 +9,7 @@ import {
} from 'react-router-dom';
import { DeviceDataT } from 'solarxr-protocol';
export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boolean) {
// to be considered prod it needs to be a proper version tag, non-dirty
const isProd = import.meta.env.PROD && __GIT_CLEAN__ && __VERSION_TAG__;
// We disable sentry for non prod environments
if (!isProd) enabled = false;
export function getSentryOrCompute(enabled = false, uuid: string) {
Sentry.setUser({ id: uuid });
// if sentry is already initialized - SKIP
@@ -50,10 +44,10 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
}),
],
beforeSend: (ev) => (newClient?.getOptions().enabled ? ev : null),
environment: isSteam ? 'steam' : 'production',
environment: import.meta.env.MODE,
release: (__VERSION_TAG__ || __COMMIT_HASH__) + (__GIT_CLEAN__ ? '' : '-dirty'),
// Tracing
tracesSampleRate: 0.5, // Capture 50% of the transactions
tracesSampleRate: import.meta.env.PROD ? 0.5 : 1.0, // Capture 50% of the transactions
// Set profilesSampleRate to 1.0 to profile every transaction.
// Since profilesSampleRate is relative to tracesSampleRate,
// the final profiling rate can be computed as tracesSampleRate * profilesSampleRate
@@ -61,7 +55,7 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
// results in 25% of transactions being profiled (0.5*0.5=0.25)
profilesSampleRate: 0.2,
// Session Replay
replaysSessionSampleRate: 0.1, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
replaysSessionSampleRate: import.meta.env.PROD ? 0.1 : 1.0, // This sets the sample rate at 10%. You may want to change it to 100% while in development and then sample at a lower rate in production.
replaysOnErrorSampleRate: 1.0, // If you're not already sampling the entire session, change the sample rate to 100% when sampling sessions where errors occur.
normalizeDepth: 8,
enabled,
+1 -1
View File
@@ -6,7 +6,7 @@ import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import jotaiReactRefresh from 'jotai/babel/plugin-react-refresh';
const commitHash = execSync('git rev-parse --verify --short=8 HEAD').toString().trim();
const commitHash = execSync('git rev-parse --verify --short HEAD').toString().trim();
const versionTag = execSync('git --no-pager tag --sort -taggerdate --points-at HEAD')
.toString()
.split('\n')[0]
+472 -253
View File
File diff suppressed because it is too large. Load diff
+3 -8
View File
@@ -17,6 +17,7 @@ plugins {
id("com.github.gmazzo.buildconfig")
id("com.android.application") version "8.13.2"
id("org.ajoberstar.grgit")
}
kotlin {
@@ -123,14 +124,8 @@ dependencies {
// The android block is where you configure all your Android-specific build options.
extra.apply {
val tagCount = providers.exec {
commandLine("git", "--no-pager", "tag", "-l")
}.standardOutput.asText.get().trim().split('\n').size
val description = providers.exec {
commandLine("git", "describe", "--tags", "--abbrev=8", "--always")
}.standardOutput.asText.get().trim()
set("gitVersionCode", tagCount)
set("gitVersionName", description)
set("gitVersionCode", grgit.tag.list().size)
set("gitVersionName", grgit.describe(mapOf("tags" to true, "always" to true)))
}
android {
// The app's namespace. Used primarily to access app resources.
@@ -14,7 +14,6 @@ import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import dev.slimevr.serial.SerialHandler
import dev.slimevr.serial.SerialListener
import dev.slimevr.tracking.trackers.hid.HIDCommon
import io.eiren.util.logging.LogManager
import java.io.IOException
import java.nio.ByteBuffer
@@ -58,7 +57,7 @@ class AndroidSerialHandler(val activity: AppCompatActivity) :
get() = getPorts()
.asSequence()
.map { SerialPortWrapper(it.ports[0]) }
.filter { isKnownBoard(it) || HIDCommon.matchesAny(it.vendorId, it.productId) }
.filter { isKnownBoard(it) }
.asStream()
val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
@@ -145,11 +144,11 @@ class AndroidSerialHandler(val activity: AppCompatActivity) :
}
@Synchronized
override fun openSerial(portLocation: String?, auto: Boolean, autoIncludeHid: Boolean): Boolean {
override fun openSerial(portLocation: String?, auto: Boolean): Boolean {
LogManager.info("[SerialHandler] Trying to open: $portLocation, auto: $auto")
lastKnownPorts = knownPorts.asSequence().toSet()
val newPort = lastKnownPorts.find {
(!auto && it.portLocation == portLocation) || (auto && isKnownBoard(it)) || (auto && autoIncludeHid && HIDCommon.matchesAny(it.vendorId, it.productId))
(!auto && it.portLocation == portLocation) || (auto && isKnownBoard(it))
}
if (newPort == null) {
@@ -71,7 +71,6 @@ class AndroidHIDManager(
val serial = hidDevice.serialNumber ?: "Unknown USB Device ${hidDevice.deviceId}"
this.devicesBySerial[serial]?.let {
this.devicesByHID[hidDevice] = it
this.lastDataByHID[hidDevice] = 0
synchronized(this.devices) {
for (id in it) {
val device = this.devices[id]
@@ -188,7 +187,7 @@ class AndroidHIDManager(
}
// LogManager.info("[TrackerServer] HID received $packetCount tracker packets")
} else {
lastDataByHID[hidDevice] = lastDataByHID.getOrDefault(hidDevice, 0) + 1 // increment last data received
lastDataByHID[hidDevice] = lastDataByHID[hidDevice]!! + 1 // increment last data received
}
}
if (!devicesPresent) {
-4
View File
@@ -91,10 +91,6 @@ dependencies {
// Jitpack
implementation("com.github.SlimeVR:oscquery-kt:566a0cba58")
// For SteamVR driver detection
implementation("io.ktor:ktor-client-core:2.3.13")
implementation("io.ktor:ktor-client-cio:2.3.13")
testImplementation(kotlin("test"))
// Use JUnit test framework
testImplementation(platform("org.junit:junit-bom:6.0.2"))
@@ -2,5 +2,5 @@ package dev.slimevr
data class FeatureFlags(
var steam: Boolean = false,
var skipCheckUdev: Boolean = true,
var skipCheckUdev: Boolean = false,
)
@@ -5,7 +5,7 @@ data class NetworkInfo(
val description: String?,
val category: NetworkCategory?,
val connectivity: Set<ConnectivityFlags>?,
val connected: Boolean,
val connected: Boolean?,
)
/**
@@ -18,7 +18,7 @@ enum class NetworkCategory(val value: Int) {
;
companion object {
fun fromInt(value: Int) = entries.find { it.value == value }
fun fromInt(value: Int) = values().find { it.value == value }
}
}
@@ -41,7 +41,7 @@ enum class ConnectivityFlags(val value: Int) {
fun fromInt(value: Int): Set<ConnectivityFlags> = if (value == 0) {
setOf(DISCONNECTED)
} else {
entries.filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet()
values().filter { it != DISCONNECTED && (value and it.value) != 0 }.toSet()
}
}
}
@@ -51,7 +51,7 @@ abstract class NetworkProfileChecker {
abstract val publicNetworks: List<NetworkInfo>
}
class StubNetworkProfileChecker : NetworkProfileChecker() {
class NetworkProfileCheckerStub : NetworkProfileChecker() {
override val isSupported: Boolean
get() = false
override val publicNetworks: List<NetworkInfo>
@@ -35,7 +35,6 @@ import dev.slimevr.tracking.trackers.udp.TrackersUDPServer
import dev.slimevr.trackingchecklist.TrackingChecklistManager
import dev.slimevr.util.ann.VRServerThread
import dev.slimevr.websocketapi.WebSocketVRBridge
import io.eiren.util.Process
import io.eiren.util.ann.ThreadSafe
import io.eiren.util.ann.ThreadSecure
import io.eiren.util.collections.FastList
@@ -62,9 +61,7 @@ class VRServer @JvmOverloads constructor(
serialHandlerProvider: (VRServer) -> SerialHandler = { _ -> SerialHandlerStub() },
flashingHandlerProvider: (VRServer) -> SerialFlashingHandler? = { _ -> null },
vrcConfigHandlerProvider: (VRServer) -> VRCConfigHandler = { _ -> VRCConfigHandlerStub() },
networkProfileProvider: (VRServer) -> NetworkProfileChecker = { _ -> StubNetworkProfileChecker() },
val processListProvider: () -> Sequence<Process> = { emptySequence() },
val tryOpenUri: (String) -> Unit = {},
networkProfileProvider: (VRServer) -> NetworkProfileChecker = { _ -> NetworkProfileCheckerStub() },
acquireMulticastLock: () -> Any? = { null },
@JvmField val configManager: ConfigManager,
) : Thread("VRServer") {
@@ -31,7 +31,7 @@ class ServerConfig {
// it.setMag(false)
// } else {
trackers.map { (_, t) ->
async { it.setMag(MagnetometerStatus.DISABLED, t.trackerNum) }
async { it.setMag(false, t.trackerNum) }
}.awaitAll()
// }
return@async
@@ -51,7 +51,7 @@ class ServerConfig {
.map { (_, t) ->
async {
// FIXME: Tracker gets restarted after each setMag, what will happen for devices with 3 trackers?
it.setMag(MagnetometerStatus.ENABLED, t.trackerNum)
it.setMag(true, t.trackerNum)
}
}.awaitAll()
}
@@ -1,6 +1,6 @@
package dev.slimevr.config
import com.jme3.math.FastMath
import dev.slimevr.tracking.trackers.TrackerPosition
// handles the tap detection config
// this involves the number of taps, the delay, and whether or not the feature is enabled
@@ -12,9 +12,6 @@ class TapDetectionConfig {
var yawResetEnabled = true
var fullResetEnabled = true
var mountingResetEnabled = true
var yawResetTracker = TrackerPosition.CHEST
var mountingResetTracker = TrackerPosition.RIGHT_UPPER_LEG
var fullResetTracker = TrackerPosition.LEFT_UPPER_LEG
var setupMode = false
var yawResetTaps = 2
set(yawResetTaps) {
@@ -58,8 +58,6 @@ class VRConfig {
val trackingChecklist: TrackingChecklistConfig = TrackingChecklistConfig()
val velocityConfig: VelocityConfig = VelocityConfig()
val vrcConfig: VRCConfig = VRCConfig()
init {
@@ -121,7 +119,6 @@ class VRConfig {
.readFilteringConfig(filters, tracker.getRotation())
}
}
tracker.allowVelocity = velocityConfig.sendDerivedVelocity
}
fun writeTrackerConfig(tracker: Tracker?) {
@@ -1,19 +0,0 @@
package dev.slimevr.config
import dev.slimevr.VRServer
/**
* Allows to enable/disable sending of optional derived velocity data via Protobuf.
* Enables Natural Locomotion Support
* May create overprediction in certain titles causing excessive jitter when moving upper body.
*/
class VelocityConfig {
// Disables derived velocity for all trackers. Driver zeroes out velocity if nothing is returned in protobuf message.
var sendDerivedVelocity: Boolean = false
fun updateTrackersVelocitySettings() {
for (t in VRServer.instance.allTrackers) {
t.allowVelocity = sendDerivedVelocity
}
}
}
@@ -16,7 +16,6 @@ import dev.slimevr.osc.UnityBone.Companion.getByStringVal
import dev.slimevr.tracking.processor.BoneType
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.DeviceOrigin
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerStatus
@@ -271,7 +270,7 @@ class VMCHandler(
// Create device if it doesn't exist
var rot = rotation
if (trackerDevice == null) {
trackerDevice = server.deviceManager.createDevice(DeviceOrigin.VMC, "VMC receiver", "1.0", "VMC")
trackerDevice = server.deviceManager.createDevice("VMC receiver", "1.0", "VMC")
server.deviceManager.addDevice(trackerDevice!!)
}
@@ -13,7 +13,6 @@ import com.jme3.system.NanoTimer
import dev.slimevr.VRServer
import dev.slimevr.config.VRCOSCConfig
import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.DeviceOrigin
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerStatus
@@ -119,7 +118,7 @@ class VRCOSCHandler(
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)) {
if (a == netAddr.address || a.address.contentEquals(netAddr.address.address) || a.hostName == netAddr.address.hostName) {
return true
}
}
@@ -134,6 +133,7 @@ class VRCOSCHandler(
b != null &&
(
a.address.contentEquals(b.address) ||
(a.hostName == b.hostName) ||
(ipIsLocal(a) && ipIsLocal(b))
)
)
@@ -328,7 +328,7 @@ class VRCOSCHandler(
// Create device if it doesn't exist
if (vrsystemTrackersDevice == null) {
// Instantiate OSC Trackers device
vrsystemTrackersDevice = server.deviceManager.createDevice(DeviceOrigin.VRCHAT, "VRC VRSystem", null, "VRChat")
vrsystemTrackersDevice = server.deviceManager.createDevice("VRC VRSystem", null, "VRChat")
server.deviceManager.addDevice(vrsystemTrackersDevice!!)
}
@@ -404,7 +404,7 @@ class VRCOSCHandler(
// Receiving OSC Trackers data. This is not from VRChat.
if (oscTrackersDevice == null) {
// Instantiate OSC Trackers device
oscTrackersDevice = server.deviceManager.createDevice(DeviceOrigin.OSC, "OSC Tracker", null, "OSC Trackers")
oscTrackersDevice = server.deviceManager.createDevice("OSC Tracker", null, "OSC Trackers")
server.deviceManager.addDevice(oscTrackersDevice!!)
}
@@ -22,18 +22,14 @@ import dev.slimevr.protocol.rpc.setup.RPCUtil.getLocalIp
import dev.slimevr.protocol.rpc.status.RPCStatusHandler
import dev.slimevr.protocol.rpc.trackingchecklist.RPCTrackingChecklistHandler
import dev.slimevr.protocol.rpc.trackingpause.RPCTrackingPause
import dev.slimevr.steamvr.SteamVRUtils
import dev.slimevr.tracking.processor.config.SkeletonConfigOffsets
import dev.slimevr.tracking.processor.stayaligned.poses.RelaxedPose
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerPosition.Companion.getByBodyPart
import dev.slimevr.tracking.trackers.TrackerStatus
import dev.slimevr.tracking.trackers.TrackerUtils.getTrackerForSkeleton
import dev.slimevr.tracking.trackers.udp.MagnetometerStatus
import io.eiren.util.logging.LogManager
import io.github.axisangles.ktmath.Quaternion
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import kotlinx.coroutines.*
import solarxr_protocol.MessageBundle
import solarxr_protocol.datatypes.TransactionId
@@ -155,11 +151,6 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
RpcMessage.ResetStayAlignedRelaxedPoseRequest,
::onResetStayAlignedRelaxedPoseRequest,
)
registerPacketListener(
RpcMessage.EnableSteamVRDriverRequest,
::onEnableSteamVRDriverRequest,
)
}
private fun onServerInfosRequest(
@@ -526,7 +517,7 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
mainScope.launch {
withTimeoutOrNull(MAG_TIMEOUT) {
tracker.device.setMag(if (state) MagnetometerStatus.ENABLED else MagnetometerStatus.DISABLED, tracker.trackerNum)
tracker.device.setMag(state, tracker.trackerNum)
}
val fbb = FlatBufferBuilder(32)
@@ -619,16 +610,6 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
sendSettingsChangedResponse(conn, messageHeader)
}
private fun onEnableSteamVRDriverRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
val request = messageHeader.message(EnableSteamVRDriverRequest()) as? EnableSteamVRDriverRequest ?: return
mainScope.launch {
val client = HttpClient(CIO)
SteamVRUtils.unblockDriver(client, "slimevr")
client.close()
}
}
fun sendSettingsChangedResponse(conn: GenericConnection, messageHeader: RpcMessageHeader?) {
val fbb = FlatBufferBuilder(32)
val settings = createSettingsResponse(fbb, api.server)
@@ -7,24 +7,10 @@ import dev.slimevr.protocol.ProtocolAPIServer
import dev.slimevr.protocol.rpc.RPCHandler
import dev.slimevr.serial.SerialListener
import dev.slimevr.serial.SerialPort
import dev.slimevr.tracking.trackers.hid.HIDCommon
import io.eiren.util.logging.LogManager
import solarxr_protocol.rpc.*
import java.util.*
import java.util.function.Consumer
import kotlin.collections.emptyList
fun createSerialDevice(fbb: FlatBufferBuilder, port: SerialPort): Int {
val portOffset = fbb.createString(port.portLocation)
val nameOffset = fbb.createString(port.descriptivePortName)
val portType = when {
HIDCommon.matchesReceiver(port.vendorId, port.productId) -> SerialDeviceType.HID_RECEIVER
HIDCommon.matchesTracker(port.vendorId, port.productId) -> SerialDeviceType.HID_TRACKER
else -> SerialDeviceType.ESP_TRACKER
}
return SerialDevice.createSerialDevice(fbb, portOffset, nameOffset, portType)
}
class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : SerialListener {
init {
@@ -49,36 +35,38 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
val outbound = rpcHandler.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update)
fbb.finish(outbound)
this.forAllListeners { conn: GenericConnection ->
conn.send(fbb.dataBuffer())
conn.context.useSerial = false
}
this.forAllListeners(
Consumer { conn: GenericConnection ->
conn.send(fbb.dataBuffer())
conn.context.useSerial = false
},
)
}
override fun onSerialLog(str: String, server: Boolean) {
val fbb = FlatBufferBuilder(32)
val logOffset = fbb.createString(str)
val portOffset = api.server.serialHandler.getCurrentPort()?.let { port ->
createSerialDevice(fbb, port)
} ?: 0
SerialUpdateResponse.startSerialUpdateResponse(fbb)
SerialUpdateResponse.addLog(fbb, logOffset)
SerialUpdateResponse.addDevice(fbb, portOffset)
val update = SerialUpdateResponse.endSerialUpdateResponse(fbb)
val outbound = rpcHandler.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update)
fbb.finish(outbound)
this.forAllListeners { conn ->
conn.send(fbb.dataBuffer())
}
this.forAllListeners(
Consumer { conn: GenericConnection ->
conn.send(fbb.dataBuffer())
},
)
}
override fun onNewSerialDevice(port: SerialPort) {
val fbb = FlatBufferBuilder(32)
val deviceOffset = createSerialDevice(fbb, port)
val portOffset = fbb.createString(port.portLocation)
val nameOffset = fbb.createString(port.descriptivePortName)
val deviceOffset = SerialDevice.createSerialDevice(fbb, portOffset, nameOffset)
val newSerialOffset = NewSerialDeviceResponse
.createNewSerialDeviceResponse(fbb, deviceOffset)
val outbound = rpcHandler
@@ -101,17 +89,17 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
override fun onSerialConnected(port: SerialPort) {
val fbb = FlatBufferBuilder(32)
val deviceOffset = createSerialDevice(fbb, port)
SerialUpdateResponse.startSerialUpdateResponse(fbb)
SerialUpdateResponse.addClosed(fbb, false)
SerialUpdateResponse.addDevice(fbb, deviceOffset)
val update = SerialUpdateResponse.endSerialUpdateResponse(fbb)
val outbound = rpcHandler.createRPCMessage(fbb, RpcMessage.SerialUpdateResponse, update)
fbb.finish(outbound)
this.forAllListeners { conn ->
conn.send(fbb.dataBuffer())
}
this.forAllListeners(
Consumer { conn: GenericConnection ->
conn.send(fbb.dataBuffer())
},
)
}
fun onSerialTrackerRebootRequest(
@@ -177,17 +165,20 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
val fbb = FlatBufferBuilder(32)
val devicesOffsets = try {
api.server.serialHandler.knownPorts.map { port ->
createSerialDevice(fbb, port)
}.toList()
val devicesOffsets: MutableList<Int> = ArrayList()
try {
this.api.server.serialHandler.knownPorts.forEach { port: SerialPort ->
val portOffset = fbb.createString(port.portLocation)
val nameOffset = fbb.createString(port.descriptivePortName)
devicesOffsets.add(SerialDevice.createSerialDevice(fbb, portOffset, nameOffset))
}
} catch (e: Throwable) {
LogManager.severe("Using serial ports is not supported on this platform", e)
emptyList()
}
SerialDevicesResponse.startDevicesVector(fbb, devicesOffsets.size)
devicesOffsets.forEach { offset: Int -> SerialDevicesResponse.addDevices(fbb, offset) }
devicesOffsets.forEach(Consumer { offset: Int -> SerialDevicesResponse.addDevices(fbb, offset) })
val devices = fbb.endVector()
val serialDeviceOffsets = SerialDevicesResponse.createSerialDevicesResponse(fbb, devices)
val outbound = rpcHandler
@@ -197,7 +188,7 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
}
fun onSetWifiRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
val req = messageHeader.message(SetWifiRequest()) as? SetWifiRequest? ?: return
val req = messageHeader.message(SetWifiRequest()) as SetWifiRequest? ?: return
if (req.password() == null || req.ssid() == null || !this.api.server.serialHandler.isConnected) {
return
@@ -207,13 +198,13 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
fun onOpenSerialRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
val req =
messageHeader.message(OpenSerialRequest()) as? OpenSerialRequest? ?: return
messageHeader.message(OpenSerialRequest()) as OpenSerialRequest? ?: return
conn.context.useSerial = true
this.api.server.queueTask {
try {
this.api.server.serialHandler.openSerial(req.port(), req.auto(), true)
this.api.server.serialHandler.openSerial(req.port(), req.auto())
} catch (e: Exception) {
LogManager.severe("Unable to open serial port", e)
} catch (e: Throwable) {
@@ -254,10 +245,17 @@ class RPCSerialHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) : Seria
conn.send(fbb.dataBuffer())
}
fun forAllListeners(action: (GenericConnection) -> Unit) {
this.api.apiServers.forEach { server ->
server.apiConnections.filter { it.context.useSerial }.forEach(action)
}
fun forAllListeners(action: Consumer<in GenericConnection?>?) {
this.api
.apiServers
.forEach(
Consumer { server: ProtocolAPIServer ->
server
.apiConnections
.filter { conn: GenericConnection -> conn.context.useSerial }
.forEach(action)
},
)
}
override fun onSerialDeviceDeleted(port: SerialPort) {
@@ -15,7 +15,6 @@ import dev.slimevr.config.StayAlignedConfig
import dev.slimevr.config.TapDetectionConfig
import dev.slimevr.config.VMCConfig
import dev.slimevr.config.VRCOSCConfig
import dev.slimevr.config.VelocityConfig
import dev.slimevr.filtering.TrackerFilters.Companion.getByConfigkey
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.processor.config.SkeletonConfigToggles
@@ -35,8 +34,6 @@ import solarxr_protocol.rpc.SteamVRTrackersSetting
import solarxr_protocol.rpc.TapDetectionSettings
import solarxr_protocol.rpc.VMCOSCSettings
import solarxr_protocol.rpc.VRCOSCSettings
import solarxr_protocol.rpc.VRMSettings
import solarxr_protocol.rpc.VelocitySettings
import solarxr_protocol.rpc.settings.LegTweaksSettings
import solarxr_protocol.rpc.settings.ModelRatios
import solarxr_protocol.rpc.settings.ModelSettings
@@ -114,25 +111,17 @@ fun createVMCOSCSettings(
addressStringOffset,
)
VMCOSCSettings.startVMCOSCSettings(fbb)
VMCOSCSettings.addOscSettings(fbb, generalSettingOffset)
VMCOSCSettings.addAnchorHip(fbb, config.anchorHip)
VMCOSCSettings.addMirrorTracking(fbb, config.mirrorTracking)
return VMCOSCSettings.endVMCOSCSettings(fbb)
}
fun createVRMSettings(
fbb: FlatBufferBuilder,
config: VMCConfig,
): Int {
val vrmJson = config.vrmJson
var vrmJsonOffset = 0
if (vrmJson != null) vrmJsonOffset = fbb.createString(vrmJson)
VRMSettings.startVRMSettings(fbb)
if (vrmJson != null) VRMSettings.addVrmJson(fbb, vrmJsonOffset)
return VRMSettings.endVRMSettings(fbb)
VMCOSCSettings.startVMCOSCSettings(fbb)
VMCOSCSettings.addOscSettings(fbb, generalSettingOffset)
if (vrmJson != null) VMCOSCSettings.addVrmJson(fbb, vrmJsonOffset)
VMCOSCSettings.addAnchorHip(fbb, config.anchorHip)
VMCOSCSettings.addMirrorTracking(fbb, config.mirrorTracking)
return VMCOSCSettings.endVMCOSCSettings(fbb)
}
fun createFilterSettings(
@@ -174,9 +163,9 @@ fun createTapDetectionSettings(
tapDetectionConfig.mountingResetTaps,
tapDetectionConfig.setupMode,
tapDetectionConfig.numberTrackersOverThreshold,
tapDetectionConfig.yawResetTracker.bodyPart,
tapDetectionConfig.fullResetTracker.bodyPart,
tapDetectionConfig.mountingResetTracker.bodyPart,
0,
0,
0,
)
fun createSteamVRSettings(fbb: FlatBufferBuilder, bridge: ISteamVRBridge?): Int {
@@ -438,11 +427,6 @@ fun createSettingsResponse(fbb: FlatBufferBuilder, server: VRServer): Int {
),
createHIDSettings(fbb, server.configManager.vrConfig.hidConfig),
0,
createVelocitySettings(fbb, server.configManager.vrConfig.velocityConfig),
createVRMSettings(
fbb,
server.configManager.vrConfig.vmc,
),
)
}
@@ -478,12 +462,3 @@ fun createHIDSettings(
fbb,
config.trackersOverHID,
)
fun createVelocitySettings(
fbb: FlatBufferBuilder,
config: VelocityConfig,
): Int = VelocitySettings
.createVelocitySettings(
fbb,
config.sendDerivedVelocity,
)
@@ -9,7 +9,6 @@ import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.RPCHandler
import dev.slimevr.tracking.processor.config.SkeletonConfigToggles
import dev.slimevr.tracking.processor.config.SkeletonConfigValues
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerRole
import solarxr_protocol.rpc.ChangeSettingsRequest
import solarxr_protocol.rpc.RpcMessage
@@ -128,6 +127,7 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
val vmcConfig = api.server.configManager
.vrConfig
.vmc
val vmcHandler = api.server.vMCHandler
val osc = req.vmcOsc().oscSettings()
if (osc != null) {
@@ -136,21 +136,12 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
vmcConfig.portOut = osc.portOut()
vmcConfig.address = osc.address()
}
if (req.vmcOsc().vrmJson() != null) {
vmcConfig.vrmJson = req.vmcOsc().vrmJson().ifEmpty { null }
}
vmcConfig.anchorHip = req.vmcOsc().anchorHip()
vmcConfig.mirrorTracking = req.vmcOsc().mirrorTracking()
}
if (req.vrm() != null) {
val vmcConfig = api.server.configManager
.vrConfig
.vmc
if (req.vrm().vrmJson() != null) {
vmcConfig.vrmJson = req.vrm().vrmJson().ifEmpty { null }
}
}
if (req.vmcOsc() != null || req.vrm() != null) {
val vmcHandler = api.server.vMCHandler
vmcHandler.refreshSettings(true)
}
@@ -168,10 +159,6 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
.mountingResetEnabled = tapDetectionSettings.mountingResetEnabled()
tapDetectionConfig.setupMode = tapDetectionSettings.setupMode()
tapDetectionConfig.yawResetTracker = TrackerPosition.getByBodyPart(tapDetectionSettings.yawResetTracker()) ?: TrackerPosition.CHEST
tapDetectionConfig.fullResetTracker = TrackerPosition.getByBodyPart(tapDetectionSettings.fullResetTracker()) ?: TrackerPosition.LEFT_UPPER_LEG
tapDetectionConfig.mountingResetTracker = TrackerPosition.getByBodyPart(tapDetectionSettings.mountingResetTracker()) ?: TrackerPosition.RIGHT_UPPER_LEG
// set number of trackers that can have high accel before taps
// are rejected
if (tapDetectionSettings.hasNumberTrackersOverThreshold()) {
@@ -375,12 +362,6 @@ class RPCSettingsHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
config.trackersOverHID = requestConfig.trackersOverHid()
}
if (req.velocitySettings() != null) {
val velocityConfig = api.server.configManager.vrConfig.velocityConfig
velocityConfig.sendDerivedVelocity = req.velocitySettings().sendDerivedVelocity()
velocityConfig.updateTrackersVelocitySettings()
}
api.server.configManager.saveConfig()
}
@@ -398,7 +379,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, 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)
@@ -71,9 +71,9 @@ public class ProvisioningHandler implements SerialListener {
try {
boolean openResult = false;
if (port != null)
openResult = vrServer.serialHandler.openSerial(port, false, false);
openResult = vrServer.serialHandler.openSerial(port, false);
else
openResult = vrServer.serialHandler.openSerial(null, true, false);
openResult = vrServer.serialHandler.openSerial(null, true);
if (!openResult)
LogManager.info("[SerialHandler] Serial port wasn't open...");
} catch (Exception e) {
@@ -9,7 +9,7 @@ abstract class SerialHandler {
abstract fun addListener(channel: SerialListener)
abstract fun removeListener(channel: SerialListener)
abstract fun openSerial(portLocation: String?, auto: Boolean, autoIncludeHid: Boolean = false): Boolean
abstract fun openSerial(portLocation: String?, auto: Boolean): Boolean
abstract fun rebootRequest()
abstract fun factoryResetRequest()
abstract fun infoRequest()
@@ -22,7 +22,7 @@ abstract class SerialHandler {
companion object {
// Please also update the udev rules when updating these in:
// gui/electron/resources/69-slimevr-devices.rules
// gui/src-tauri/69-slimevr-devices.rules
val supportedSerial: Set<Pair<Int, Int>> = setOf(
// / QinHeng
// CH340
@@ -61,7 +61,7 @@ class SerialHandlerStub : SerialHandler() {
override fun removeListener(channel: SerialListener) {}
override fun openSerial(portLocation: String?, auto: Boolean, autoIncludeHid: Boolean): Boolean = false
override fun openSerial(portLocation: String?, auto: Boolean): Boolean = false
override fun rebootRequest() {}
@@ -5,8 +5,8 @@ import java.util.*
abstract class SerialPort {
abstract val portLocation: String
abstract val descriptivePortName: String
abstract val vendorId: Int
abstract val productId: Int
abstract val vendorId: Int?
abstract val productId: Int?
override fun equals(other: Any?): Boolean {
val other: SerialPort = other as? SerialPort ?: return super.equals(other)
@@ -1,123 +0,0 @@
package dev.slimevr.steamvr
import dev.slimevr.VRServer
import io.eiren.util.logging.LogManager
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.parameter
import io.ktor.client.request.request
import io.ktor.client.request.setBody
import io.ktor.http.HttpMethod
import io.ktor.http.isSuccess
import kotlinx.coroutines.delay
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.time.Duration.Companion.milliseconds
@Serializable
data class DriverManifest(
val directory: String,
@SerialName("hmd_presence")
val hmdPresence: List<String>?,
val name: String,
)
@Serializable
data class Driver(
@SerialName("always_activate")
val alwaysActivate: Boolean,
@SerialName("blocked_by_safe_mode")
val blockedBySafeMode: Boolean,
val enabled: Boolean,
@SerialName("enabled_by_default")
val enabledByDefault: Boolean,
val id: Int,
@SerialName("load_priority")
val loadPriority: Int,
val manifest: DriverManifest,
@SerialName("on_safemode_whitelist")
val onSafeModeWhitelist: Boolean,
@SerialName("show_enable_in_settings")
val showEnableInSettings: Boolean,
)
@Serializable
private data class DriverListResponse(
val drivers: List<Driver>,
@SerialName("jsonid")
val jsonId: String,
)
class SteamVRUtils {
companion object {
const val SERVER_URL = "http://127.0.0.1:27062"
const val REFERER = "$SERVER_URL/dashboard/index.html"
private val jsonIgnoreUnknownKeys = Json { ignoreUnknownKeys = true }
suspend fun getDriversList(client: HttpClient): List<Driver>? {
val resp = try {
client.request("$SERVER_URL/drivers/list.json") {
header("Referer", REFERER)
}
} catch (_: Exception) {
return null
}
if (!resp.status.isSuccess()) {
LogManager.warning("[SteamVRUtils] Failed to connect to SteamVR web server (status ${resp.status})")
return null
}
val body: String = try {
resp.body()
} catch (_: Exception) {
return null
}
val driverList: DriverListResponse = try {
jsonIgnoreUnknownKeys.decodeFromString(body)
} catch (e: Exception) {
LogManager.warning("[SteamVRUtils] Failed to decode SteamVR drivers list", e)
return null
}
if (driverList.jsonId != "vr_driver_list") {
LogManager.severe("[SteamVRUtils] SteamVR driver list response had wrong jsonId (${driverList.jsonId})")
return null
}
return driverList.drivers
}
suspend fun unblockDriver(client: HttpClient, driver: String) {
val unblockReq = client.get("$SERVER_URL/drivers/unblock") {
method = HttpMethod.Post
header("Referer", REFERER)
setBody("""{"driver":"$driver"}""")
}
if (!unblockReq.status.isSuccess()) {
LogManager.severe("[SteamVRUtils] Failed to unblock driver: ${unblockReq.status}")
}
val enableReq = client.get("$SERVER_URL/drivers/setenable") {
method = HttpMethod.Post
header("Referer", REFERER)
setBody("""{"driver":"$driver","enable":true}""")
}
if (!enableReq.status.isSuccess()) {
LogManager.severe("[SteamVRUtils] Failed to enable driver: ${enableReq.status}")
}
delay(500.milliseconds)
VRServer.instance.tryOpenUri("vrmonitor://restartsystem")
}
}
}
@@ -1171,7 +1171,6 @@ class HumanSkeleton(
it.position = trackerBone.getTailPosition()
it.setRotation(trackerBone.getGlobalRotation() * trackerBone.rotationOffset.inv())
it.dataTick()
it.updateDerivedVelocity()
}
}
@@ -6,15 +6,7 @@ import java.util.*
// class that monitors the acceleration of the waist, hip, chest or upper chest trackers to detect taps
// and use this to trigger a variety of resets (if your wondering why no single tap class exists, it's because
// to many false positives)
class TapDetection(
val skeleton: HumanSkeleton,
val trackerToWatch: Tracker,
// The maximum number of trackers that can accelerate faster than ALLOWED_BODY_ACCEL
// before tap detection will deactivate
val maxAllowedMovingTrackers: Int,
val tapToComplete: Int,
val onTapCompleted: () -> Unit,
) {
class TapDetection(val skeleton: HumanSkeleton, val trackerToWatch: Tracker, val numberTrackersOverThreshold: Int, val tapToComplete: Int, val onTapCompleted: () -> Unit) {
private val accelList = LinkedList<FloatArray>()
private val tapTimestamps = LinkedList<Float>()
@@ -100,20 +92,64 @@ class TapDetection(
// force on any of the torso or upper leg trackers (this sadly implies that
// you need two or more trackers for this feature to be reliable)
private fun isUserStatic(trackerToExclude: Tracker): Boolean {
val trackersToCheck = arrayOf(
skeleton.upperChestTracker,
skeleton.chestTracker,
skeleton.hipTracker,
skeleton.waistTracker,
skeleton.leftUpperLegTracker,
skeleton.rightUpperLegTracker,
skeleton.leftFootTracker,
skeleton.rightFootTracker,
)
val numMovingTrackers = trackersToCheck.count {
it != null && it != trackerToExclude && it.getAcceleration().lenSq() > ALLOWED_BODY_ACCEL_SQUARED
var num = 0
if (skeleton.upperChestTracker != null &&
skeleton.upperChestTracker != trackerToExclude
) {
if (skeleton.upperChestTracker!!.getAcceleration().lenSq()
> ALLOWED_BODY_ACCEL_SQUARED
) {
num++
}
}
return numMovingTrackers < maxAllowedMovingTrackers
if (skeleton.chestTracker != null &&
skeleton.chestTracker != trackerToExclude
) {
if (skeleton.chestTracker!!.getAcceleration().lenSq() > ALLOWED_BODY_ACCEL_SQUARED) num++
}
if (skeleton.hipTracker != null && skeleton.hipTracker != trackerToExclude) {
if (skeleton.hipTracker!!.getAcceleration().lenSq() > ALLOWED_BODY_ACCEL_SQUARED) num++
}
if (skeleton.waistTracker != null &&
skeleton.waistTracker != trackerToExclude
) {
if (skeleton.waistTracker!!.getAcceleration().lenSq() > ALLOWED_BODY_ACCEL_SQUARED) num++
}
if (skeleton.leftUpperLegTracker != null &&
skeleton.leftUpperLegTracker != trackerToExclude
) {
if (skeleton.leftUpperLegTracker!!.getAcceleration().lenSq()
> ALLOWED_BODY_ACCEL_SQUARED
) {
num++
}
}
if (skeleton.rightUpperLegTracker != null &&
skeleton.rightUpperLegTracker != trackerToExclude
) {
if (skeleton.rightUpperLegTracker!!.getAcceleration().lenSq()
> ALLOWED_BODY_ACCEL_SQUARED
) {
num++
}
}
if (skeleton.leftFootTracker != null &&
skeleton.leftFootTracker != trackerToExclude
) {
if (skeleton.leftFootTracker!!.getAcceleration().lenSq() > ALLOWED_BODY_ACCEL_SQUARED) {
num++
}
}
if (skeleton.rightFootTracker != null &&
skeleton.rightFootTracker != trackerToExclude
) {
if (skeleton.rightFootTracker!!.getAcceleration().lenSq()
> ALLOWED_BODY_ACCEL_SQUARED
) {
num++
}
}
return num < numberTrackersOverThreshold
}
companion object {
@@ -3,9 +3,6 @@ package dev.slimevr.tracking.processor.skeleton
import dev.slimevr.VRServer
import dev.slimevr.tracking.processor.HumanPoseManager
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
import dev.slimevr.tracking.trackers.TrackerUtils
import io.eiren.util.logging.LogManager
import java.util.concurrent.CopyOnWriteArrayList
class TapDetectionManager(
@@ -91,29 +88,26 @@ class TapDetectionManager(
private val mountingResetTracker: Tracker?
get() {
return arrayOf(
TrackerUtils.getTrackerForSkeleton(server.allTrackers, config.mountingResetTracker),
if (config.yawResetTracker !== TrackerPosition.RIGHT_UPPER_LEG && config.fullResetTracker !== TrackerPosition.RIGHT_UPPER_LEG) skeleton.rightUpperLegTracker else null,
if (config.yawResetTracker !== TrackerPosition.RIGHT_LOWER_LEG && config.fullResetTracker !== TrackerPosition.RIGHT_LOWER_LEG) skeleton.rightLowerLegTracker else null,
skeleton.rightUpperLegTracker,
skeleton.rightLowerLegTracker,
).firstNotNullOfOrNull { it }
}
private val fullResetTracker: Tracker?
get() {
return arrayOf(
TrackerUtils.getTrackerForSkeleton(server.allTrackers, config.fullResetTracker),
if (config.yawResetTracker !== TrackerPosition.LEFT_UPPER_LEG && config.mountingResetTracker !== TrackerPosition.LEFT_UPPER_LEG) skeleton.leftUpperLegTracker else null,
if (config.yawResetTracker !== TrackerPosition.LEFT_LOWER_LEG && config.mountingResetTracker !== TrackerPosition.LEFT_LOWER_LEG) skeleton.leftLowerLegTracker else null,
skeleton.leftUpperLegTracker,
skeleton.leftLowerLegTracker,
).firstNotNullOfOrNull { it }
}
private val yawResetTracker: Tracker?
get() {
return arrayOf(
TrackerUtils.getTrackerForSkeleton(server.allTrackers, config.yawResetTracker),
if (config.fullResetTracker !== TrackerPosition.UPPER_CHEST && config.mountingResetTracker !== TrackerPosition.UPPER_CHEST) skeleton.upperChestTracker else null,
if (config.fullResetTracker !== TrackerPosition.CHEST && config.mountingResetTracker !== TrackerPosition.CHEST) skeleton.chestTracker else null,
if (config.fullResetTracker !== TrackerPosition.HIP && config.mountingResetTracker !== TrackerPosition.HIP) skeleton.hipTracker else null,
if (config.fullResetTracker !== TrackerPosition.WAIST && config.mountingResetTracker !== TrackerPosition.WAIST) skeleton.waistTracker else null,
skeleton.upperChestTracker,
skeleton.chestTracker,
skeleton.hipTracker,
skeleton.waistTracker,
).firstNotNullOfOrNull { it }
}
@@ -2,7 +2,6 @@ package dev.slimevr.tracking.trackers
import dev.slimevr.tracking.trackers.udp.BoardType
import dev.slimevr.tracking.trackers.udp.MCUType
import dev.slimevr.tracking.trackers.udp.MagnetometerStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
@@ -10,18 +9,7 @@ import kotlinx.coroutines.launch
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
enum class DeviceOrigin {
HID,
UDP,
VRCHAT,
OSC,
VMC,
STEAMVR,
SOLARXR,
WEBSOCKET,
}
open class Device(val origin: DeviceOrigin, val magSupport: Boolean = false) {
open class Device(val magSupport: Boolean = false) {
open val id: Int = nextLocalDeviceId.incrementAndGet()
open var name: String? = null
open var firmwareVersion: String? = null
@@ -38,6 +26,9 @@ open class Device(val origin: DeviceOrigin, val magSupport: Boolean = false) {
open val hardwareIdentifier: String = "Unknown"
val isOpenVrDevice: Boolean
get() = manufacturer == "OpenVR"
init {
CoroutineScope(Job()).launch {
// Wait a little for device to get configured
@@ -50,7 +41,7 @@ open class Device(val origin: DeviceOrigin, val magSupport: Boolean = false) {
* if `sensorId` null or in the specified tracker
* @param sensorId If null, every sensor will be modified
*/
open suspend fun setMag(status: MagnetometerStatus, sensorId: Int = 255) {
open suspend fun setMag(state: Boolean, sensorId: Int = 255) {
TODO("Not implemented because no mag support: $magSupport")
}
@@ -5,8 +5,8 @@ import io.eiren.util.collections.FastList
class DeviceManager(private val server: VRServer) {
val devices = FastList<Device>()
fun createDevice(origin: DeviceOrigin, name: String?, version: String?, manufacturer: String?): Device {
val device = Device(origin)
fun createDevice(name: String?, version: String?, manufacturer: String?): Device {
val device = Device()
device.name = name
device.firmwareVersion = version
device.manufacturer = manufacturer
@@ -12,10 +12,6 @@ import io.eiren.util.BufferedTimer
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import kotlin.properties.Delegates
import kotlin.time.Duration.Companion.microseconds
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.DurationUnit
import kotlin.time.TimeSource
const val TIMEOUT_MS = 2_000L
const val DISCONNECT_MS = 3_000L + TIMEOUT_MS
@@ -79,11 +75,6 @@ class Tracker @JvmOverloads constructor(
*/
val allowMounting: Boolean = false,
/**
* If true, the tracker will send Derived Velocity.
*/
var allowVelocity: Boolean = false,
val isHmd: Boolean = false,
/**
@@ -120,19 +111,7 @@ class Tracker @JvmOverloads constructor(
// IMU: +z forward, +x left, +y up
// SlimeVR: +z backward, +x right, +y up
private var _acceleration = Vector3.NULL
private var _velocity = Vector3.NULL
private var _magVector = Vector3.NULL
/**
* Velocity state server-side differentiation based on sent poses
*/
private data class VelocityState(
var prevMark: TimeSource.Monotonic.ValueTimeMark? = null,
var prevPos: Vector3 = Vector3(0f, 0f, 0f),
)
private val velocityState = VelocityState()
var position = Vector3.NULL
val resetsHandler: TrackerResetsHandler = TrackerResetsHandler(this)
val filteringHandler: TrackerFilteringHandler = TrackerFilteringHandler()
@@ -148,12 +127,8 @@ class Tracker @JvmOverloads constructor(
var packetsLost: Int? = null
var packetLoss: Float? = null
var customName: String? = null
/**
* Please don't use this and instead set it via [Device.setMag]
*/
var magStatus: MagnetometerStatus = magStatus
internal set
private set
/**
* Watch the rest calibration status
@@ -370,39 +345,6 @@ class Tracker @JvmOverloads constructor(
}
}
/**
* If derived velocity is enabled, updates the derived velocity of the tracker,
* calculating it based on the position displacement since the last update,
* applying a sanity check on the time delta to filter out noise and ensure data stability.
*/
fun updateDerivedVelocity() {
if (!allowVelocity || !hasPosition) {
velocityState.prevMark = null
_velocity = Vector3.NULL
return
}
val pos = position
val now = TimeSource.Monotonic.markNow()
val prevMark = velocityState.prevMark
if (prevMark != null) {
val dt = now - prevMark
if (dt in 100.microseconds..250.milliseconds) {
val dtSeconds = dt.toDouble(DurationUnit.SECONDS)
_velocity = Vector3(
((pos.x - velocityState.prevPos.x) / dtSeconds).toFloat(),
((pos.y - velocityState.prevPos.y) / dtSeconds).toFloat(),
((pos.z - velocityState.prevPos.z) / dtSeconds).toFloat(),
)
} else {
_velocity = Vector3.NULL
}
}
velocityState.prevMark = now
velocityState.prevPos = pos
}
/**
* Gets the identity-adjusted tracker rotation after the resetsHandler's corrections
* (identity reset, drift and identity mounting).
@@ -479,30 +421,23 @@ class Tracker @JvmOverloads constructor(
this._acceleration = vec
}
/**
* Sets the derived velocity of the tracker.
*/
fun setVelocity(vec: Vector3) {
this._velocity = if (allowVelocity) vec else Vector3.NULL
}
/**
* Gets the derived velocity of the tracker.
*/
fun getVelocity(): Vector3 = _velocity
/**
* True if the tracker has valid velocity data.
*/
val hasVelocity: Boolean
get() = allowVelocity && _velocity != Vector3.NULL
/**
* True if the raw rotation is coming directly from an IMU (no cameras or lighthouses)
* For example, flex sensor trackers are not considered as IMU trackers (see TrackerDataType)
*/
fun isImu(): Boolean = imuType != null && trackerDataType == TrackerDataType.ROTATION
/**
* Please don't use this and instead set it via [Device.setMag]
*/
internal fun setMagPrivate(mag: Boolean) {
magStatus = if (mag) {
MagnetometerStatus.ENABLED
} else {
MagnetometerStatus.DISABLED
}
}
/**
* Gets the magnetic field vector, in mGauss.
*/
@@ -12,7 +12,6 @@ import io.eiren.util.logging.LogManager
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Quaternion.Companion.fromRotationVector
import io.github.axisangles.ktmath.Vector3
import kotlinx.coroutines.runBlocking
import java.nio.ByteBuffer
import java.util.function.Consumer
import kotlin.collections.set
@@ -135,10 +134,6 @@ class HIDCommon {
.info(
"[TrackerServer] Added sensor $trackerId for ${device.name}, type $sensorType",
)
} else {
runBlocking {
device.setMag(magStatus, trackerId)
}
}
}
@@ -1,20 +1,13 @@
package dev.slimevr.tracking.trackers.hid
import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.DeviceOrigin
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.udp.BoardType
import dev.slimevr.tracking.trackers.udp.MCUType
import dev.slimevr.tracking.trackers.udp.MagnetometerStatus
class HIDDevice(val hidId: Int) : Device(DeviceOrigin.HID) {
class HIDDevice(val hidId: Int) : Device() {
override var hardwareIdentifier: String = "Unknown"
override var boardType: BoardType = BoardType.UNKNOWN
override var mcuType: MCUType = MCUType.UNKNOWN
fun getTracker(id: Int): Tracker? = trackers[id]
override suspend fun setMag(status: MagnetometerStatus, sensorId: Int) {
val tracker = trackers[sensorId] ?: error("Tracker $sensorId not found in device $this")
tracker.magStatus = status
}
}
@@ -249,7 +249,7 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
) {
mainScope.launch {
withTimeoutOrNull(MAG_TIMEOUT) {
connection.setMag(MagnetometerStatus.DISABLED, trackerId)
connection.setMag(false, trackerId)
}
}
} else if (magStatus == MagnetometerStatus.DISABLED &&
@@ -258,7 +258,7 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
) {
mainScope.launch {
withTimeoutOrNull(MAG_TIMEOUT) {
connection.setMag(MagnetometerStatus.ENABLED, trackerId)
connection.setMag(true, trackerId)
}
}
}
@@ -357,6 +357,13 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
LogManager.info("[TrackerServer] Tracker timed out: $conn")
}
} else {
for (value in conn.trackers.values) {
if (value.status == TrackerStatus.DISCONNECTED ||
value.status == TrackerStatus.TIMED_OUT
) {
value.status = TrackerStatus.OK
}
}
conn.timedOut = false
}
@@ -397,6 +404,7 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
}
private fun processPacket(received: DatagramPacket, packet: UDPPacket, connection: UDPDevice?) {
val tracker: Tracker?
when (packet) {
is UDPPacket0Heartbeat, is UDPPacket1Heartbeat, is UDPPacket25SetConfigFlag -> {}
@@ -405,10 +413,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
is RotationPacket -> {
var rot = packet.rotation
rot = AXES_OFFSET.times(rot)
val tracker = connection?.getTracker(packet.sensorId) ?: return
if (tracker.status == TrackerStatus.DISCONNECTED || tracker.status == TrackerStatus.TIMED_OUT) {
tracker.status = TrackerStatus.OK
}
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
tracker.setRotation(rot)
if (packet is UDPPacket23RotationAndAcceleration) {
// sensorOffset is applied correctly since protocol 22
@@ -423,10 +429,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
}
is UDPPacket17RotationData -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
if (tracker.status == TrackerStatus.DISCONNECTED || tracker.status == TrackerStatus.TIMED_OUT) {
tracker.status = TrackerStatus.OK
}
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
var rot17 = packet.rotation
rot17 = AXES_OFFSET * rot17
when (packet.dataType) {
@@ -449,10 +453,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
is UDPPacket18MagnetometerAccuracy -> {}
is UDPPacket4Acceleration -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
if (tracker.status == TrackerStatus.DISCONNECTED || tracker.status == TrackerStatus.TIMED_OUT) {
tracker.status = TrackerStatus.OK
}
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
// sensorOffset is applied correctly since protocol 22
// See: https://github.com/SlimeVR/SlimeVR-Tracker-ESP/pull/480
if (connection.protocolVersion >= 22) {
@@ -488,21 +490,18 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
// 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 != null) {
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
}
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 = packet.level * 100
it.batteryLevel = 0f
}
// Server displays 0% if received 255 or -1, otherwise 0 will hide battery icon
}
is UDPPacket13Tap -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
LogManager.info(
"[TrackerServer] Tap packet received from ${tracker.name}: ${packet.tap}",
)
@@ -512,7 +511,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
LogManager.severe(
"[TrackerServer] Error received from ${received.socketAddress}: ${packet.errorNumber}",
)
val tracker = connection?.getTracker(packet.sensorId) ?: return
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
tracker.status = TrackerStatus.ERROR
}
@@ -544,7 +544,7 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
}
is UDPPacket20Temperature -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
tracker = connection?.getTracker(packet.sensorId) ?: return
tracker.temperature = packet.temperature
}
@@ -612,7 +612,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
}
is UDPPacket26FlexData -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
if (tracker.trackerDataType == TrackerDataType.FLEX_RESISTANCE) {
tracker.trackerFlexHandler.setFlexResistance(packet.flexData)
} else if (tracker.trackerDataType == TrackerDataType.FLEX_ANGLE) {
@@ -622,7 +623,8 @@ class TrackersUDPServer(private val port: Int, name: String, private val tracker
}
is UDPPacket27Position -> {
val tracker = connection?.getTracker(packet.sensorId) ?: return
tracker = connection?.getTracker(packet.sensorId)
if (tracker == null) return
tracker.position = packet.position
// dont call dataTick here as this is just position update
}
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff. Show more